This commit is contained in:
2026-05-11 20:40:21 +03:00
parent d2d22799b6
commit d9ffcb4b92
15 changed files with 1652 additions and 1388 deletions
+44 -40
View File
@@ -12,18 +12,19 @@ const sql = postgres(process.env.POSTGRES_URL!, { ssl: 'require' });
const FormSchema = z.object({
id: z.string(),
customerId: z.string({
invalid_type_error: 'Please select a customer.',
invalid_type_error: 'Please select a customer',
}),
amount: z.coerce
.number()
.gt(0, { message: 'Please enter an amount greater than $0.' }),
status: z.enum(['pending', 'paid'], {
invalid_type_error: 'Please select an invoice status.',
invalid_type_error: 'Please select an invoice status. ',
}),
date: z.string(),
});
const CreateInvoice = FormSchema.omit({ id: true, date: true });
const UpdateInvoice = FormSchema.omit({ id: true, date: true });
export type State = {
errors?: {
@@ -35,84 +36,87 @@ export type State = {
};
export async function createInvoice(prevState: State, formData: FormData) {
// Validate form using Zod
const validatedFields = CreateInvoice.safeParse({
const validateFields = CreateInvoice.safeParse({
customerId: formData.get('customerId'),
amount: formData.get('amount'),
status: formData.get('status'),
});
// If form validation fails, return errors early. Otherwise, continue.
if (!validatedFields.success) {
if (!validateFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: 'Missing Fields. Failed to Create Invoice.',
errors: validateFields.error.flatten().fieldErrors,
message: 'Missing Fields. Failed to Create Invoice. ',
};
}
// Prepare data for insertion into the database
const { customerId, amount, status } = validatedFields.data;
const { customerId, amount, status } = validateFields.data;
const amountInCents = amount * 100;
const date = new Date().toISOString().split('T')[0];
// Insert data into the database
try {
await sql`
INSERT INTO invoices (customer_id, amount, status, date)
VALUES (${customerId}, ${amountInCents}, ${status}, ${date})
`;
INSERT INTO invoices (customer_id, amount, status, date)
VALUES (${customerId}, ${amountInCents}, ${status}, ${date})
`;
} catch (error) {
// If a database error occurs, return a more specific error.
return {
message: 'Database Error: Failed to Create Invoice.',
};
}
// Revalidate the cache for the invoices page and redirect the user.
revalidatePath('/dashboard/invoices');
redirect('/dashboard/invoices');
}
const UpdateInvoice = FormSchema.omit({ id: true, date: true });
export async function updateInvoice(
id: string,
prevState: State,
formData: FormData,
) {
const validatedFields = UpdateInvoice.safeParse({
const validateFields = UpdateInvoice.safeParse({
customerId: formData.get('customerId'),
amount: formData.get('amount'),
status: formData.get('status'),
});
if (!validatedFields.success) {
if (!validateFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: 'Missing Fields. Failed to Update Invoice.',
errors: validateFields.error.flatten().fieldErrors,
message: 'Missing Fields. Failed to update Invoice',
};
}
const { customerId, amount, status } = validatedFields.data;
const { amount, customerId, status } = validateFields.data;
const amountInCents = amount * 100;
try {
await sql`
UPDATE invoices
SET customer_id = ${customerId}, amount = ${amountInCents}, status = ${status}
WHERE id = ${id}
`;
UPDATE invoices
SET customer_id = ${customerId}, amount = ${amountInCents}, status = ${status}
WHERE id = ${id}
`;
} catch (error) {
return { message: 'Database Error: Failed to Update Invoice.' };
return {
message: 'Database Failed: Error while updating the Invoice',
};
}
revalidatePath('/dashboard/invoices');
redirect('/dashboard/invoices');
}
export async function deleteInvoice(id: string) {
await sql`DELETE FROM invoices WHERE id = ${id}`;
revalidatePath('/dashboard/invoices');
// throw new Error('Failed to Delete Invoice. ')
try {
await sql`
DELETE FROM invoices
WHERE id = ${id}
`;
revalidatePath('/dashboard/invoices');
return { message: 'Deleted Invoice. ' };
} catch (error) {
return {
message: 'Database Error: Failed while deleting record from Invoice. ',
};
}
}
export async function authenticate(
@@ -125,7 +129,7 @@ export async function authenticate(
if (error instanceof AuthError) {
switch (error.type) {
case 'CredentialsSignin':
return 'Invalid credentials.';
return 'Invalid credentials';
default:
return 'Something went wrong.';
}