Skip to content

Commit 40f4a09

Browse files
Add create invoice page, form and validation before insert to database
1 parent 9a881ea commit 40f4a09

File tree

3 files changed

+62
-1
lines changed

3 files changed

+62
-1
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import Form from '@/app/ui/invoices/create-form';
2+
import Breadcrumbs from '@/app/ui/invoices/breadcrumbs';
3+
import { fetchCustomers } from '@/app/lib/data';
4+
5+
export default async function Page() {
6+
const customers = await fetchCustomers();
7+
debugger;
8+
9+
return (
10+
<main>
11+
<Breadcrumbs
12+
breadcrumbs={[
13+
{ label: 'Invoices', href: '/dashboard/invoices' },
14+
{
15+
label: 'Create Invoice',
16+
href: '/dashboard/invoices/create',
17+
active: true,
18+
},
19+
]}
20+
/>
21+
<Form customers={customers} />
22+
</main>
23+
);
24+
}

app/lib/actions.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'use server';
2+
3+
import { z } from 'zod';
4+
import { sql } from '@vercel/postgres';
5+
import { revalidatePath } from 'next/cache';
6+
import { redirect } from 'next/navigation';
7+
8+
const formSchema = z.object({
9+
id: z.string(),
10+
customerId: z.string(),
11+
amount: z.coerce.number(),
12+
status: z.enum(['paid', 'pending']),
13+
date: z.string(),
14+
});
15+
16+
const CreateInvoice = formSchema.omit({ id: true, date: true });
17+
18+
export async function createInvoice(formData: FormData) {
19+
const { customerId, amount, status } = CreateInvoice.parse({
20+
customerId: formData.get('customerId'),
21+
amount: formData.get('amount'),
22+
status: formData.get('status'),
23+
});
24+
const amountInCents = amount * 100;
25+
const date = new Date().toISOString().split('T')[0];
26+
27+
await sql`
28+
INSERT INTO invoices (customer_id, amount, status, date)
29+
VALUES (${customerId}, ${amountInCents}, ${status}, ${date})
30+
`;
31+
32+
revalidatePath('/dashboard/invoices');
33+
redirect('/dashboard/invoices');
34+
}

app/ui/invoices/create-form.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
'use client';
2+
13
import { CustomerField } from '@/app/lib/definitions';
24
import Link from 'next/link';
35
import {
@@ -7,10 +9,11 @@ import {
79
UserCircleIcon,
810
} from '@heroicons/react/24/outline';
911
import { Button } from '@/app/ui/button';
12+
import { createInvoice } from '@/app/lib/actions';
1013

1114
export default function Form({ customers }: { customers: CustomerField[] }) {
1215
return (
13-
<form>
16+
<form action={createInvoice}>
1417
<div className="rounded-md bg-gray-50 p-4 md:p-6">
1518
{/* Customer Name */}
1619
<div className="mb-4">

0 commit comments

Comments
 (0)