aboutsummaryrefslogtreecommitdiff
path: root/src/lib/server/services/references.ts
blob: 60dcc01ce650b71a1ff0cce8c0f9523b5fa0b735 (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

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 class ReferencesService {
	constructor(private readonly db: AppDatabase) {}

	async loadForGrocery(groceryId: number): Promise<Reference[]> {
		return this.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.
	 */
	async promote(id: number): Promise<void> {
		const [target] = await this.db
			.select()
			.from(references)
			.where(eq(references.id, id));
		if (!target) throw new Error('Reference not found');

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

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

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