79 lines
2.6 KiB
TypeScript
79 lines
2.6 KiB
TypeScript
import logger from "$lib/server/logger";
|
|
import type { NewTask } from "$lib/server/services/TasksService";
|
|
import TasksService from "$lib/server/services/TasksService";
|
|
import { error, fail, redirect } from "@sveltejs/kit";
|
|
import type { Actions, PageServerLoad } from "./$types";
|
|
|
|
const tasks = new TasksService("internal");
|
|
|
|
export const load: PageServerLoad = async ({ params }) => {
|
|
const taskResult = await tasks.getByTaskId([params.task_id]);
|
|
|
|
if (taskResult.status === "failure" || !taskResult.data || taskResult.data.length === 0) {
|
|
error(404, `No record for '${params.task_id}'.`);
|
|
}
|
|
if (taskResult.data.length > 1) {
|
|
logger.error(`Mulitple database entries match '${params.task_id}' when there should only be one.`);
|
|
error(500, "Internal error. Check the logs.");
|
|
}
|
|
|
|
const task = taskResult.data[0];
|
|
|
|
const [parent, children] = await Promise.all([
|
|
task.parent
|
|
? tasks.getByDbId([task.parent])
|
|
: Promise.resolve({ status: "ok", data: [] }),
|
|
tasks.getByParent(task.id),
|
|
]);
|
|
|
|
return {
|
|
params,
|
|
task,
|
|
parent,
|
|
children,
|
|
};
|
|
};
|
|
|
|
export const actions: Actions = {
|
|
default: async ({ request, url }) => {
|
|
const formData = await request.formData();
|
|
const data = Object.fromEntries(formData);
|
|
|
|
if (!data.description || typeof data.description !== "string" || !data.description.trim()) {
|
|
return fail(400, { data, error: "Description is required.", field: "description" });
|
|
}
|
|
|
|
const createDateFn = (dateStr: unknown) => {
|
|
// The client now sends a full ISO string or an empty string
|
|
if (dateStr && typeof dateStr === "string") {
|
|
return new Date(dateStr);
|
|
}
|
|
return null;
|
|
};
|
|
|
|
const taskData: NewTask = {
|
|
id: data.id ? Number(data.id) : undefined,
|
|
description: typeof data.description === "string" ? data.description : null,
|
|
body: typeof data.body === "string" ? data.body : null,
|
|
status: typeof data.status === "string" ? data.status : null,
|
|
priority: typeof data.priority === "string" ? data.priority : null,
|
|
subtype: typeof data.subtype === "string" ? data.subtype : null,
|
|
openDate: createDateFn(data.openDate),
|
|
closeDate: createDateFn(data.closeDate),
|
|
};
|
|
|
|
const upsertResult = await tasks.upsert(taskData);
|
|
|
|
if (upsertResult.status === "failure") {
|
|
return fail(500, { data, error: upsertResult.error, code: upsertResult.code });
|
|
}
|
|
|
|
if (!upsertResult.data) {
|
|
return fail(500, { data, error: "An unexpected error occurred: missing result data." });
|
|
}
|
|
|
|
// On a successful save, redirect back to the main task page
|
|
throw redirect(303, url.pathname);
|
|
},
|
|
};
|