leilo5
This commit is contained in:
@@ -1,23 +1,15 @@
|
||||
import { Card } from '@/app/ui/dashboard/cards';
|
||||
import CardWrapper, { Card } from '@/app/ui/dashboard/cards';
|
||||
import RevenueChart from '@/app/ui/dashboard/revenue-chart';
|
||||
import LatestInvoices from '@/app/ui/dashboard/latest-invoices';
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
import { fetchCardData } from '@/app/lib/data';
|
||||
import { Suspense } from 'react';
|
||||
import CardWrapper from '@/app/ui/dashboard/cards';
|
||||
import {
|
||||
RevenueChartSkeleton,
|
||||
LatestInvoicesSkeleton,
|
||||
CardsSkeleton,
|
||||
} from '@/app/ui/skeletons';
|
||||
import { CardSkeleton, LatestInvoicesSkeleton, RevenueChartSkeleton } from '@/app/ui/skeletons';
|
||||
import { Metadata } from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Dashboard',
|
||||
};
|
||||
export default async function Page() {
|
||||
const {
|
||||
numberOfInvoices,
|
||||
numberOfCustomers,
|
||||
totalPaidInvoices,
|
||||
totalPendingInvoices,
|
||||
} = await fetchCardData();
|
||||
|
||||
return (
|
||||
<main>
|
||||
@@ -25,15 +17,17 @@ export default async function Page() {
|
||||
Dashboard
|
||||
</h1>
|
||||
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Suspense fallback={<CardsSkeleton />}>
|
||||
<Suspense fallback={<CardSkeleton />}>
|
||||
<CardWrapper />
|
||||
</Suspense>
|
||||
</div>
|
||||
<div className="mt-6 grid grid-cols-1 gap-6 md:grid-cols-4 lg:grid-cols-8">
|
||||
|
||||
<Suspense fallback={<RevenueChartSkeleton />}>
|
||||
<RevenueChart />
|
||||
</Suspense>
|
||||
<Suspense fallback={<LatestInvoicesSkeleton />}>
|
||||
|
||||
<Suspense fallback={<LatestInvoicesSkeleton />}>
|
||||
<LatestInvoices />
|
||||
</Suspense>
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
export default function Page() {
|
||||
return <p>Customers Page</p>;
|
||||
|
||||
}
|
||||
import { Metadata } from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Customers',
|
||||
};
|
||||
@@ -2,6 +2,11 @@ import Form from '@/app/ui/invoices/edit-form';
|
||||
import Breadcrumbs from '@/app/ui/invoices/breadcrumbs';
|
||||
import { fetchInvoiceById, fetchCustomers } from '@/app/lib/data';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { Metadata } from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Edit invoices',
|
||||
};
|
||||
|
||||
export default async function Page(props: { params: Promise<{ id: string }> }) {
|
||||
const params = await props.params;
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import Form from '@/app/ui/invoices/create-form';
|
||||
import Breadcrumbs from '@/app/ui/invoices/breadcrumbs';
|
||||
import { fetchCustomers } from '@/app/lib/data';
|
||||
import { Metadata } from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Create invoices',
|
||||
};
|
||||
|
||||
export default async function Page() {
|
||||
const customers = await fetchCustomers();
|
||||
|
||||
@@ -6,6 +6,11 @@ import { lusitana } from '@/app/ui/fonts';
|
||||
import { Suspense } from 'react';
|
||||
import { InvoicesTableSkeleton } from '@/app/ui/skeletons';
|
||||
import { fetchInvoicesPages } from '@/app/lib/data';
|
||||
import { Metadata } from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Invoices',
|
||||
};
|
||||
|
||||
export default async function Page(props: {
|
||||
searchParams?: Promise<{
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import '@/app/ui/global.css';
|
||||
import { inter } from '@/app/ui/fonts';
|
||||
import { Metadata } from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: {
|
||||
template: '%s | Acme Dashboard',
|
||||
default: 'Acme Dashboard',
|
||||
},
|
||||
description: 'The official Next.js Learn Dashboard built with App Router.',
|
||||
metadataBase: new URL('https://next-learn-dashboard.vercel.sh'),
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
|
||||
+38
-34
@@ -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,75 +36,67 @@ 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
|
||||
const date = new Date().toISOString().split('T')[0];
|
||||
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');
|
||||
@@ -111,8 +104,19 @@ export async function updateInvoice(
|
||||
}
|
||||
|
||||
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.';
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import AcmeLogo from '@/app/ui/acme-logo';
|
||||
import LoginForm from '@/app/ui/login-form';
|
||||
import { Suspense } from 'react';
|
||||
import { Metadata } from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Login',
|
||||
};
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
|
||||
@@ -3,6 +3,7 @@ import NavLinks from '@/app/ui/dashboard/nav-links';
|
||||
import AcmeLogo from '@/app/ui/acme-logo';
|
||||
import { PowerIcon } from '@heroicons/react/24/outline';
|
||||
import { signOut } from '@/auth';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default function SideNav() {
|
||||
return (
|
||||
@@ -18,13 +19,11 @@ export default function SideNav() {
|
||||
<div className="flex grow flex-row justify-between space-x-2 md:flex-col md:space-x-0 md:space-y-2">
|
||||
<NavLinks />
|
||||
<div className="hidden h-auto w-full grow rounded-md bg-gray-50 md:block"></div>
|
||||
<form
|
||||
action={async () => {
|
||||
'use server';
|
||||
await signOut({ redirectTo: '/' });
|
||||
}}
|
||||
>
|
||||
<button className="flex h-[48px] grow items-center justify-center gap-2 rounded-md bg-gray-50 p-3 text-sm font-medium hover:bg-sky-100 hover:text-blue-600 md:flex-none md:justify-start md:p-2 md:px-3">
|
||||
<form action={async () => {
|
||||
'use server';
|
||||
await signOut();
|
||||
}}>
|
||||
<button className="flex h-[48px] w-full grow items-center justify-center gap-2 rounded-md bg-gray-50 p-3 text-sm font-medium hover:bg-sky-100 hover:text-blue-600 md:flex-none md:justify-start md:p-2 md:px-3">
|
||||
<PowerIcon className="w-6" />
|
||||
<div className="hidden md:block">Sign Out</div>
|
||||
</button>
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { PencilIcon, PlusIcon, TrashIcon } from '@heroicons/react/24/outline';
|
||||
import Link from 'next/link';
|
||||
import { deleteInvoice } from '@/app/lib/actions';
|
||||
|
||||
|
||||
export function CreateInvoice() {
|
||||
return (
|
||||
@@ -18,7 +16,7 @@ export function CreateInvoice() {
|
||||
export function UpdateInvoice({ id }: { id: string }) {
|
||||
return (
|
||||
<Link
|
||||
href={`/dashboard/invoices/${id}/edit`}
|
||||
href="/dashboard/invoices"
|
||||
className="rounded-md border p-2 hover:bg-gray-100"
|
||||
>
|
||||
<PencilIcon className="w-5" />
|
||||
@@ -27,14 +25,12 @@ export function UpdateInvoice({ id }: { id: string }) {
|
||||
}
|
||||
|
||||
export function DeleteInvoice({ id }: { id: string }) {
|
||||
const deleteInvoiceWithId = deleteInvoice.bind(null, id);
|
||||
return (
|
||||
<form action={deleteInvoiceWithId}>
|
||||
<button type="submit" className="rounded-md border p-2 hover:bg-gray-100">
|
||||
<>
|
||||
<button className="rounded-md border p-2 hover:bg-gray-100">
|
||||
<span className="sr-only">Delete</span>
|
||||
<TrashIcon className="w-4" />
|
||||
<TrashIcon className="w-5" />
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useFormState } from 'react-dom';
|
||||
import { CustomerField } from '@/app/lib/definitions';
|
||||
import Link from 'next/link';
|
||||
import {
|
||||
@@ -14,11 +15,11 @@ import { useActionState } from 'react';
|
||||
|
||||
|
||||
export default function Form({ customers }: { customers: CustomerField[] }) {
|
||||
const initialState: State = { message: null, errors: {} };
|
||||
const [state, formAction] = useActionState(createInvoice, initialState);
|
||||
const initialState = { message: '', error: {} };
|
||||
const [state, dispatch] = useFormState(createInvoice, initialState);
|
||||
|
||||
return (
|
||||
<form action={createInvoice}>
|
||||
<form action={dispatch}>
|
||||
<div className="rounded-md bg-gray-50 p-4 md:p-6">
|
||||
{/* Customer Name */}
|
||||
<div className="mb-4">
|
||||
|
||||
+20
-22
@@ -7,21 +7,15 @@ import {
|
||||
ExclamationCircleIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { ArrowRightIcon } from '@heroicons/react/20/solid';
|
||||
import { Button } from '@/app/ui/button';
|
||||
import { useActionState } from 'react';
|
||||
import { authenticate } from '@/app/lib/actions';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { Button } from './button';
|
||||
import { useFormState, useFormStatus } from 'react-dom';
|
||||
import { authenticate } from '../lib/actions';
|
||||
|
||||
export default function LoginForm() {
|
||||
const searchParams = useSearchParams();
|
||||
const callbackUrl = searchParams.get('callbackUrl') || '/dashboard';
|
||||
const [errorMessage, formAction, isPending] = useActionState(
|
||||
authenticate,
|
||||
undefined,
|
||||
);
|
||||
|
||||
const [errorMessage, dispatch] = useFormState(authenticate, undefined)
|
||||
return (
|
||||
<form action={formAction} className="space-y-3">
|
||||
<form action={dispatch} className="space-y-3">
|
||||
<div className="flex-1 rounded-lg bg-gray-50 px-6 pb-4 pt-8">
|
||||
<h1 className={`${lusitana.className} mb-3 text-2xl`}>
|
||||
Please log in to continue.
|
||||
@@ -67,23 +61,27 @@ export default function LoginForm() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<input type="hidden" name="redirectTo" value={callbackUrl} />
|
||||
<Button className="mt-4 w-full" aria-disabled={isPending}>
|
||||
Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" />
|
||||
</Button>
|
||||
<div
|
||||
className="flex h-8 items-end space-x-1"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
>
|
||||
<LoginButton />
|
||||
<div className="flex h-8 items-end space-x-1" aria-live='polite' aria-atomic='true'>
|
||||
{/* Add form errors here */}
|
||||
{errorMessage && (
|
||||
<>
|
||||
<ExclamationCircleIcon className="h-5 w-5 text-red-500" />
|
||||
<p className="text-sm text-red-500">{errorMessage}</p>
|
||||
<ExclamationCircleIcon className='h-5 w-5 text-red-500' />
|
||||
<p className='text-sm text-red-500'>{errorMessage}</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginButton() {
|
||||
const {pending} = useFormStatus()
|
||||
return (
|
||||
<Button className="mt-4 w-full" aria-disabled={pending}>
|
||||
Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
Generated
+1515
-1279
File diff suppressed because it is too large
Load Diff
+2
-2
@@ -20,7 +20,6 @@
|
||||
"react": "latest",
|
||||
"react-dom": "latest",
|
||||
"tailwindcss": "3.4.17",
|
||||
"typescript": "5.7.3",
|
||||
"use-debounce": "^10.0.4",
|
||||
"zod": "^3.25.17"
|
||||
},
|
||||
@@ -30,7 +29,8 @@
|
||||
"@types/react": "19.0.7",
|
||||
"@types/react-dom": "19.0.3",
|
||||
"eslint": "^10.3.0",
|
||||
"eslint-config-next": "^16.2.6"
|
||||
"eslint-config-next": "^16.2.6",
|
||||
"typescript": "5.7.3"
|
||||
},
|
||||
"pnpm": {
|
||||
"onlyBuiltDependencies": [
|
||||
|
||||
Generated
+3
-3
@@ -47,9 +47,6 @@ importers:
|
||||
tailwindcss:
|
||||
specifier: 3.4.17
|
||||
version: 3.4.17
|
||||
typescript:
|
||||
specifier: 5.7.3
|
||||
version: 5.7.3
|
||||
use-debounce:
|
||||
specifier: ^10.0.4
|
||||
version: 10.0.6(react@19.2.0)
|
||||
@@ -75,6 +72,9 @@ importers:
|
||||
eslint-config-next:
|
||||
specifier: ^16.2.6
|
||||
version: 16.2.6(@typescript-eslint/parser@8.59.2(eslint@10.3.0(jiti@1.21.7))(typescript@5.7.3))(eslint@10.3.0(jiti@1.21.7))(typescript@5.7.3)
|
||||
typescript:
|
||||
specifier: 5.7.3
|
||||
version: 5.7.3
|
||||
|
||||
packages:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user