aboutsummaryrefslogtreecommitdiff
path: root/src/lib/server/services/references.ts
blob: accf1ba63f9607d143711938dd3f1c9140c05747 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

import { db as defaultDb } from '$lib/server/db';
import { references } from '$lib/server/db/schema';
import { eq, ne, and, desc, asc } from 'drizzle-orm';
import type { AppDatabase } from '$lib/server/db/types';
import type { Reference } from './types';

/** Primary refs first, then best score, then insertion order. */
export const referenceOrder = [
	desc(references.isPrimary),
	desc(references.qualityScore),
	asc(references.id),
];

export async function loadForGrocery(
	groceryId: number,
	db = defaultDb,
): Promise<Reference[]> {
	return db
		.select()
		.from(references)
		.where(eq(references.groceryId, groceryId))
		.orderBy(...referenceOrder);
}

/**
 * Marks `id` as the primary ref of its grocery, clearing any sibling primary
 * so at most one ref per grocery is promoted.
 */
export async function promote(id: number, db = defaultDb): Promise<void> {
	const [target] = await db
		.select()
		.from(references)
		.where(eq(references.id, id));
	if (!target) throw new Error('Reference not found');

	await db
		.update(references)
		.set({ isPrimary: true })
		.where(eq(references.id, id));
	await db
		.update(references)
		.set({ isPrimary: false })
		.where(
			and(eq(references.groceryId, target.groceryId), ne(references.id, id)),
		);
}

export async function add(
	groceryId: number,
	reference: string,
	price: number | null,
	unit: string | null,
	qualityScore: number | null,
	db = defaultDb,
): Promise<Reference> {
	const [inserted] = await db
		.insert(references)
		.values({ groceryId, reference, price, unit, qualityScore })
		.returning();
	return inserted;
}

export async function deleteReference(
	id: number,
	db = defaultDb,
): Promise<void> {
	await db.delete(references).where(eq(references.id, id));
}