summaryrefslogtreecommitdiff
path: root/app/src/lib/server/assignments.ts
blob: 787865c1f0297e194475dc7946da5b63f8e1a3c4 (plain)
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import { PutObjectCommand, type S3Client } from "@aws-sdk/client-s3"; /*=;* /
import type { ClientBase } from "pg";
import type { CemetaryPlot, Assignment, AssignmentState } from "../common/assignments";

/**
 * Retrieves all assignments for the given user.
 *
 * @param dbConn Connection to database.
 * @param userId ID used to identify user.
 */
export async function getAssignments(dbConn: ClientBase, userId: number): Promise<Assignment[]> {
	const result = await dbConn.query(
		"SELECT * FROM assignments WHERE gardener_id = $1 ORDER BY date",
		[userId],
	);
	return result.rows.map(
		(r) =>
			({
				id: r.id,
				gardenerId: r.gardener_id,
				cemetaryPlotId: r.cemetary_plot_id,
				date: r.date,
				state: r.state,
			}) satisfies Assignment,
	);
}

type GetAssignmentResult =
	| { assignment: Assignment; cemetaryPlot: CemetaryPlot }
	| { assignment: null; cemetaryPlot: null };

/**
 * Retrieves a specfic assignment, along with relevant cemetary plot.
 */
export async function getAssignmentAndCemetaryById(
	dbConn: ClientBase,
	assignmentId: number,
): Promise<GetAssignmentResult> {
	const queryText = `SELECT
		a.id,
		a.gardener_id,
		a.cemetary_plot_id,
		a.date,
		a.state,
		c.id,
		c.address,
		c.owner_id,
		c.assignment_interval
	FROM
		assignments AS a
	INNER JOIN
		cemetary_plots AS C ON c.id = a.cemetary_plot_id
	WHERE c.id = $1`;
	const result = await dbConn.query({ rowMode: "array", text: queryText }, [assignmentId]);
	if (result.rowCount == 0) {
		return { assignment: null, cemetaryPlot: null };
	}

	const assignment: Assignment = {
		id: result.rows[0][0],
		gardenerId: result.rows[0][1],
		cemetaryPlotId: result.rows[0][2],
		date: result.rows[0][3],
		state: result.rows[0][4],
	};
	const cemetaryPlot: CemetaryPlot = {
		id: result.rows[0][5],
		address: result.rows[0][6],
		ownerId: result.rows[0][7],
		//assignmentInterval: result.rows[0][8],
	};
	return { assignment, cemetaryPlot };
}

export interface FinishAssignmentArgs {
	images: { bytes: Uint8Array; name: string }[];
	note?: string;
	assignmentId: number;
}

// TODO: Error recovery.
export async function finishAssignment(
	dbConn: ClientBase,
	s3Client: S3Client,
	{ images, note, assignmentId }: FinishAssignmentArgs,
): Promise<void> {
	// Upload to S3, returning path
	// FIXME: Should be factored out?
	const uploadPromises = images.map(async (image) => {
		const key = generateImageKey();

		const cmd = new PutObjectCommand({
			Bucket: "images",
			Key: key,
			Body: image.bytes,
			IfNoneMatch: "*", // Error, in case of key collision.
		});

		await s3Client.send(cmd);
		return { ...image, key };
	});
	const uploadedImages = await Promise.all(uploadPromises);

	// TODO: Add beanstalkd job

	await dbConn.query("BEGIN");

	try {
		// Create 'images' row for each image.
		// FIXME: Apparently node-pg doesn't have an equivalent to Python's `insert_many`??
		for (const image of uploadedImages) {
			dbConn.query({
				name: "insert-assignment-image",
				text: "INSERT INTO images(s3_path, original_filename, assignment_id) VALUES ($1, $2, $3)",
				values: [image.key, image.name, assignmentId],
			});
		}

		// Update the assingment's state.
		dbConn.query(
			`UPDATE
				assignments
			SET
				state = 'AWAITING_WATERMARKING' :: assignment_state,
				note = $1
			WHERE
				id = $2`,
			[note, assignmentId],
		);

		dbConn.query("COMMIT");
	} catch (err) {
		// We should probably try to delete S3 objects.

		// We should probably try to delete the job.

		await dbConn.query("ROLLBACK");
		throw err;
	}
}

function generateImageKey(): string {
	return crypto.randomUUID();
}