55 lines
1.8 KiB
TypeScript
55 lines
1.8 KiB
TypeScript
import { and, asc, eq, isNull } from 'drizzle-orm';
|
|
import { message, superValidate } from 'sveltekit-superforms/server';
|
|
import { zod4 } from 'sveltekit-superforms/adapters';
|
|
import { db } from '$lib/server/db';
|
|
import { contacts, clients } from '$lib/server/db/schema';
|
|
import { loadOrganizationContext } from '$lib/server/organizations';
|
|
import { archiveSchema } from '$lib/schemas/shared.schema';
|
|
import type { Actions, PageServerLoad } from './$types';
|
|
|
|
async function loadOptions(organizationId: string) {
|
|
const clientRows = await db
|
|
.select({ id: clients.id, name: clients.name })
|
|
.from(clients)
|
|
.where(and(eq(clients.organizationId, organizationId), isNull(clients.archivedAt)))
|
|
.orderBy(asc(clients.name));
|
|
|
|
return {
|
|
clients: clientRows.map((client) => ({ label: client.name, value: client.id }))
|
|
};
|
|
}
|
|
|
|
export const load: PageServerLoad = async ({ locals }) => {
|
|
const { activeOrganizationId } = await loadOrganizationContext(locals);
|
|
const records = await db
|
|
.select()
|
|
.from(contacts)
|
|
.where(and(eq(contacts.organizationId, activeOrganizationId), isNull(contacts.archivedAt)))
|
|
.orderBy(asc(contacts.name));
|
|
|
|
return {
|
|
records,
|
|
options: await loadOptions(activeOrganizationId),
|
|
archiveForm: await superValidate(zod4(archiveSchema), {
|
|
id: 'contacts-archive',
|
|
errors: false
|
|
})
|
|
};
|
|
};
|
|
|
|
export const actions: Actions = {
|
|
archive: async (event) => {
|
|
const { activeOrganizationId } = await loadOrganizationContext(event.locals);
|
|
const form = await superValidate(event, zod4(archiveSchema), { id: 'contacts-archive' });
|
|
|
|
if (!form.valid) return message(form, 'Contact id is required.', { status: 400 });
|
|
|
|
await db
|
|
.update(contacts)
|
|
.set({ archivedAt: new Date(), updatedAt: new Date() })
|
|
.where(and(eq(contacts.id, form.data.id), eq(contacts.organizationId, activeOrganizationId)));
|
|
|
|
return message(form, 'Contact archived.');
|
|
}
|
|
};
|