Adding crud operations for invoices, client and server side validation, and NextAuth for login.

This commit is contained in:
Bradley Shellnut 2023-10-30 22:24:00 -07:00
parent d12596f9b6
commit 73d3c564de
19 changed files with 2495 additions and 351 deletions

View file

@ -0,0 +1,18 @@
import Link from "next/link";
import { FaceFrownIcon } from "@heroicons/react/24/outline";
export default function NotFound() {
return (
<main className="flex h-full flex-col items-center justify-center gap-2">
<FaceFrownIcon className="w-10 text-gray-400" />
<h2 className="text-xl font-semibold">404 Not Found</h2>
<p>Could not find the requested invoice.</p>
<Link
href="/dashboard/invoices"
className="mt-4 rounded-md bg-blue-500 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-400"
>
Go Back
</Link>
</main>
);
}

View file

@ -0,0 +1,32 @@
import { notFound } from "next/navigation";
import Form from "@/app/ui/invoices/edit-form";
import Breadcrumbs from "@/app/ui/invoices/breadcrumbs";
import { fetchCustomers, fetchInvoiceById } from "@/app/lib/data";
export default async function Page({ params }: { params: { id: string } }) {
const id = params.id;
const [invoice, customers] = await Promise.all([
fetchInvoiceById(id),
fetchCustomers(),
]);
if (!invoice) {
notFound();
}
return (
<main>
<Breadcrumbs
breadcrumbs={[
{ label: "Invoices", href: "/dashboard/invoices" },
{
label: "Edit Invoice",
href: `/dashboard/invoices/${id}/edit`,
active: true,
},
]}
/>
<Form invoice={invoice} customers={customers} />
</main>
);
}

View file

@ -0,0 +1,23 @@
import Form from "@/app/ui/invoices/create-form";
import Breadcrumbs from "@/app/ui/invoices/breadcrumbs";
import { fetchCustomers } from "@/app/lib/data";
export default async function Page() {
const customers = await fetchCustomers();
return (
<main>
<Breadcrumbs
breadcrumbs={[
{ label: "Invoices", href: "/dashboard/invoices" },
{
label: "Create Invoice",
href: "/dashboard/invoices/create",
active: true,
},
]}
/>
<Form customers={customers} />
</main>
);
}

View file

@ -0,0 +1,31 @@
'use client';
import { useEffect } from 'react';
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
// Optionally log the error to an error reporting service
console.error(error);
}, [error]);
return (
<main className="flex h-full flex-col items-center justify-center">
<h2 className="text-center">Something went wrong!</h2>
<button
className="mt-4 rounded-md bg-blue-500 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-400"
onClick={
// Attempt to recover by trying to re-render the invoices route
() => reset()
}
>
Try again
</button>
</main>
);
}

View file

@ -5,6 +5,7 @@ import Table from "@/app/ui/invoices/table";
import { CreateInvoice } from "@/app/ui/invoices/buttons"; import { CreateInvoice } from "@/app/ui/invoices/buttons";
import { lusitana } from "@/app/ui/fonts"; import { lusitana } from "@/app/ui/fonts";
import { InvoicesTableSkeleton } from "@/app/ui/skeletons"; import { InvoicesTableSkeleton } from "@/app/ui/skeletons";
import { fetchInvoicesPages } from "@/app/lib/data";
export default async function Page({ export default async function Page({
searchParams, searchParams,
@ -16,6 +17,7 @@ export default async function Page({
}) { }) {
const query = searchParams?.query || ""; const query = searchParams?.query || "";
const currentPage = Number(searchParams?.page) || 1; const currentPage = Number(searchParams?.page) || 1;
const totalPages = await fetchInvoicesPages(query);
return ( return (
<div className="w-full"> <div className="w-full">
@ -30,7 +32,7 @@ export default async function Page({
<Table query={query} currentPage={currentPage} /> <Table query={query} currentPage={currentPage} />
</Suspense> </Suspense>
<div className="mt-5 flex w-full justify-center"> <div className="mt-5 flex w-full justify-center">
{/* <Pagination totalPages={totalPages} /> */} <Pagination totalPages={totalPages} />
</div> </div>
</div> </div>
); );

135
app/lib/actions.ts Normal file
View file

@ -0,0 +1,135 @@
'use server';
import { redirect } from 'next/navigation';
import { revalidatePath } from 'next/cache';
import { sql } from '@vercel/postgres';
import { signIn } from '@/auth';
import { z } from 'zod';
const FormSchema = z.object({
id: z.string(),
customerId: z.string({
invalid_type_error: "Please select a customer.",
}),
amount: z.coerce
.number()
.gt(0, { message: "Please enter an amoint greater than $0." }),
status: z.enum(["pending", "paid"], {
invalid_type_error: "Please select an invoice status.",
}),
date: z.string(),
});
const CreateInvoice = FormSchema.omit({ id: true, date: true });
const UpdateInvoice = FormSchema.omit({ date: true });
const DeleteInvoice = FormSchema.pick({ id: true });
export type State = {
errors?: {
customerId?: string[];
amount?: string[];
status?: string[];
};
message?: string | null;
}
export async function createInvoice(prevState: State, formData: FormData) {
// Validate form using Zod
const validatedFields = 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) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: "Missing Fields. Failed to Create Invoice.",
};
}
// Prepare data for insertion into the database
const { customerId, amount, status } = validatedFields.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})
`;
} 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");
}
export async function updateInvoice(prevState: State, formData: FormData) {
const validatedFields = UpdateInvoice.safeParse({
id: formData.get("id"),
customerId: formData.get("customerId"),
amount: formData.get("amount"),
status: formData.get("status"),
});
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: "Missing Fields. Failed to Update Invoice.",
};
}
const { id, customerId, amount, status } = validatedFields.data;
const amountInCents = amount * 100;
try {
await sql`
UPDATE invoices
SET customer_id = ${customerId}, amount = ${amountInCents}, status = ${status}
WHERE id = ${id}
`;
} catch (error) {
return { message: "Database Error: Failed to Update Invoice." };
}
revalidatePath("/dashboard/invoices");
redirect("/dashboard/invoices");
}
export async function deleteInvoice(formData: FormData) {
const { id } = DeleteInvoice.parse({
id: formData.get("id"),
});
try {
await sql`DELETE FROM invoices WHERE id = ${id}`;
} catch (error) {
return {
message: 'Database Error: Failed to Delete Invoice.'
}
}
revalidatePath('/dashboard/invoices');
}
export async function authenticate(
prevState: string | undefined,
formData: FormData
) {
try {
await signIn("credentials", Object.fromEntries(formData));
} catch (error) {
if ((error as Error).message.includes("CredentialsSignin")) {
return "CredentialSignin";
}
throw error;
}
}

17
app/login/page.tsx Normal file
View file

@ -0,0 +1,17 @@
import AcmeLogo from "@/app/ui/acme-logo";
import LoginForm from "@/app/ui/login-form";
export default function LoginPage() {
return (
<main className="flex items-center justify-center md:h-screen">
<div className="relative mx-auto flex w-full max-w-[400px] flex-col space-y-2.5 p-4 md:-mt-32">
<div className="flex h-20 w-full items-end rounded-lg bg-blue-500 p-3 md:h-36">
<div className="w-32 text-white md:w-36">
<AcmeLogo />
</div>
</div>
<LoginForm />
</div>
</main>
);
}

View file

@ -1,29 +1,35 @@
import Link from 'next/link'; import Link from "next/link";
import NavLinks from '@/app/ui/dashboard/nav-links'; import NavLinks from "@/app/ui/dashboard/nav-links";
import AcmeLogo from '@/app/ui/acme-logo'; import AcmeLogo from "@/app/ui/acme-logo";
import { PowerIcon } from '@heroicons/react/24/outline'; import { PowerIcon } from "@heroicons/react/24/outline";
import { signOut } from "@/auth";
export default function SideNav() { export default function SideNav() {
return ( return (
<div className="flex h-full flex-col px-3 py-4 md:px-2"> <div className="flex h-full flex-col px-3 py-4 md:px-2">
<Link <Link
className="mb-2 flex h-20 items-end justify-start rounded-md bg-blue-600 p-4 md:h-40" className="mb-2 flex h-20 items-end justify-start rounded-md bg-blue-600 p-4 md:h-40"
href="/" href="/"
> >
<div className="w-32 text-white md:w-40"> <div className="w-32 text-white md:w-40">
<AcmeLogo /> <AcmeLogo />
</div> </div>
</Link> </Link>
<div className="flex grow flex-row justify-between space-x-2 md:flex-col md:space-x-0 md:space-y-2"> <div className="flex grow flex-row justify-between space-x-2 md:flex-col md:space-x-0 md:space-y-2">
<NavLinks /> <NavLinks />
<div className="hidden h-auto w-full grow rounded-md bg-gray-50 md:block"></div> <div className="hidden h-auto w-full grow rounded-md bg-gray-50 md:block"></div>
<form> <form
<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"> action={async () => {
<PowerIcon className="w-6" /> "use server";
<div className="hidden md:block">Sign Out</div> await signOut();
</button> }}
</form> >
</div> <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">
</div> <PowerIcon className="w-6" />
); <div className="hidden md:block">Sign Out</div>
</button>
</form>
</div>
</div>
);
} }

View file

@ -1,5 +1,6 @@
import { PencilIcon, PlusIcon, TrashIcon } from '@heroicons/react/24/outline'; import { PencilIcon, PlusIcon, TrashIcon } from '@heroicons/react/24/outline';
import Link from 'next/link'; import Link from 'next/link';
import { deleteInvoice } from '@/app/lib/actions';
export function CreateInvoice() { export function CreateInvoice() {
return ( return (
@ -16,7 +17,7 @@ export function CreateInvoice() {
export function UpdateInvoice({ id }: { id: string }) { export function UpdateInvoice({ id }: { id: string }) {
return ( return (
<Link <Link
href="/dashboard/invoices" href={`/dashboard/invoices/${id}/edit`}
className="rounded-md border p-2 hover:bg-gray-100" className="rounded-md border p-2 hover:bg-gray-100"
> >
<PencilIcon className="w-5" /> <PencilIcon className="w-5" />
@ -26,11 +27,12 @@ export function UpdateInvoice({ id }: { id: string }) {
export function DeleteInvoice({ id }: { id: string }) { export function DeleteInvoice({ id }: { id: string }) {
return ( return (
<> <form action={deleteInvoice}>
<input type="hidden" name="id" value={id} />
<button 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> <span className="sr-only">Delete</span>
<TrashIcon className="w-5" /> <TrashIcon className="w-5" />
</button> </button>
</> </form>
); );
} }

View file

@ -1,6 +1,6 @@
'use client'; 'use client';
import { CustomerField } from '@/app/lib/definitions'; import { useFormState } from 'react-dom';
import Link from 'next/link'; import Link from 'next/link';
import { import {
CheckIcon, CheckIcon,
@ -9,107 +9,161 @@ import {
UserCircleIcon, UserCircleIcon,
} from '@heroicons/react/24/outline'; } from '@heroicons/react/24/outline';
import { Button } from '../button'; import { Button } from '../button';
import { CustomerField } from '@/app/lib/definitions';
import { createInvoice } from '@/app/lib/actions';
export default function Form({ customers }: { customers: CustomerField[] }) { export default function Form({ customers }: { customers: CustomerField[] }) {
const initialState = {
message: null,
errors: {}
};
const [state, dispatch] = useFormState(createInvoice, initialState);
console.log('state', state);
return ( return (
<form> <form action={dispatch}>
<div className="rounded-md bg-gray-50 p-4 md:p-6"> <div className="rounded-md bg-gray-50 p-4 md:p-6">
{/* Customer Name */} {/* Customer Name */}
<div className="mb-4"> <div className="mb-4">
<label htmlFor="customer" className="mb-2 block text-sm font-medium"> <label htmlFor="customer" className="mb-2 block text-sm font-medium">
Choose customer Choose customer
</label> </label>
<div className="relative"> <div className="relative">
<select <select
id="customer" id="customer"
name="customerId" name="customerId"
className="peer block w-full rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500" className="peer block w-full rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500"
defaultValue="" defaultValue=""
> aria-describedby="customer-error"
<option value="" disabled> >
Select a customer <option value="" disabled>
</option> Select a customer
{customers.map((customer) => ( </option>
<option key={customer.id} value={customer.id}> {customers.map((customer) => (
{customer.name} <option key={customer.id} value={customer.id}>
</option> {customer.name}
))} </option>
</select> ))}
<UserCircleIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500" /> </select>
</div> <UserCircleIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500" />
</div> </div>
{state.errors?.customerId ? (
<div
id="customer-error"
aria-live="polite"
className="mt-2 text-sm text-red-500"
>
{state.errors.customerId.map((error: string) => (
<p key={error}>{error}</p>
))}
</div>
) : null}
</div>
{/* Invoice Amount */} {/* Invoice Amount */}
<div className="mb-4"> <div className="mb-4">
<label htmlFor="amount" className="mb-2 block text-sm font-medium"> <label htmlFor="amount" className="mb-2 block text-sm font-medium">
Choose an amount Choose an amount
</label> </label>
<div className="relative mt-2 rounded-md"> <div className="relative mt-2 rounded-md">
<div className="relative"> <div className="relative">
<input <input
id="amount" id="amount"
name="amount" name="amount"
type="number" type="number"
step="0.01" step="0.01"
placeholder="Enter USD amount" placeholder="Enter USD amount"
className="peer block w-full rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500" className="peer block w-full rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500"
/> aria-describedby="amount-error"
<CurrencyDollarIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" /> />
</div> <CurrencyDollarIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
</div> </div>
s </div>
</div> {state.errors?.amount ? (
<div
id="amount-error"
aria-live="polite"
className="mt-2 text-sm text-red-500"
>
{state.errors.amount.map((error: string) => (
<p key={error}>{error}</p>
))}
</div>
) : null}
</div>
{/* Invoice Status */} {/* Invoice Status */}
<div> <div>
<label htmlFor="status" className="mb-2 block text-sm font-medium"> <label htmlFor="status" className="mb-2 block text-sm font-medium">
Set the invoice status Set the invoice status
</label> </label>
<div className="rounded-md border border-gray-200 bg-white px-[14px] py-3"> <div className="rounded-md border border-gray-200 bg-white px-[14px] py-3">
<div className="flex gap-4"> <div className="flex gap-4">
<div className="flex items-center"> <div className="flex items-center">
<input <input
id="pending" id="pending"
name="status" name="status"
type="radio" type="radio"
value="pending" value="pending"
className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600" className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600"
/> aria-describedby="status-error"
<label />
htmlFor="pending" <label
className="ml-2 flex items-center gap-1.5 rounded-full bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-600 dark:text-gray-300" htmlFor="pending"
> className="ml-2 flex items-center gap-1.5 rounded-full bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-600 dark:text-gray-300"
Pending <ClockIcon className="h-4 w-4" /> >
</label> Pending <ClockIcon className="h-4 w-4" />
</div> </label>
<div className="flex items-center"> </div>
<input <div className="flex items-center">
id="paid" <input
name="status" id="paid"
type="radio" name="status"
value="paid" type="radio"
className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600" value="paid"
/> className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600"
<label aria-describedby="status-error"
htmlFor="paid" />
className="ml-2 flex items-center gap-1.5 rounded-full bg-green-500 px-3 py-1.5 text-xs font-medium text-white dark:text-gray-300" <label
> htmlFor="paid"
Paid <CheckIcon className="h-4 w-4" /> className="ml-2 flex items-center gap-1.5 rounded-full bg-green-500 px-3 py-1.5 text-xs font-medium text-white dark:text-gray-300"
</label> >
</div> Paid <CheckIcon className="h-4 w-4" />
</div> </label>
</div> </div>
</div> </div>
</div> </div>
<div className="mt-6 flex justify-end gap-4"> {state.errors?.status ? (
<Link <div
href="/dashboard/invoices" id="status-error"
className="flex h-10 items-center rounded-lg bg-gray-100 px-4 text-sm font-medium text-gray-600 transition-colors hover:bg-gray-200" aria-live="polite"
> className="mt-2 text-sm text-red-500"
Cancel >
</Link> {state.errors.status.map((error: string) => (
<Button type="submit">Create Invoice</Button> <p key={error}>{error}</p>
</div> ))}
</form> </div>
); ) : null}
{state.message ? (
<div
id="edit-error"
aria-live="polite"
className="mt-2 text-sm text-red-500"
>
<p>{state.message}</p>
</div>
) : null}
</div>
</div>
<div className="mt-6 flex justify-end gap-4">
<Link
href="/dashboard/invoices"
className="flex h-10 items-center rounded-lg bg-gray-100 px-4 text-sm font-medium text-gray-600 transition-colors hover:bg-gray-200"
>
Cancel
</Link>
<Button type="submit">Create Invoice</Button>
</div>
</form>
);
} }

View file

@ -1,5 +1,6 @@
'use client'; 'use client';
import { useFormState } from 'react-dom';
import { CustomerField, InvoiceForm } from '@/app/lib/definitions'; import { CustomerField, InvoiceForm } from '@/app/lib/definitions';
import { import {
CheckIcon, CheckIcon,
@ -9,6 +10,7 @@ import {
} from '@heroicons/react/24/outline'; } from '@heroicons/react/24/outline';
import Link from 'next/link'; import Link from 'next/link';
import { Button } from '@/app/ui/button'; import { Button } from '@/app/ui/button';
import { updateInvoice } from '@/app/lib/actions';
export default function EditInvoiceForm({ export default function EditInvoiceForm({
invoice, invoice,
@ -17,108 +19,153 @@ export default function EditInvoiceForm({
invoice: InvoiceForm; invoice: InvoiceForm;
customers: CustomerField[]; customers: CustomerField[];
}) { }) {
const initialState = { message: null, errors: {} };
const [state, dispatch] = useFormState(updateInvoice, initialState);
return ( return (
<form> <form action={dispatch}>
<div className="rounded-md bg-gray-50 p-4 md:p-6"> <input type="hidden" name="id" value={invoice.id} />
{/* Invoice ID */} <div className="rounded-md bg-gray-50 p-4 md:p-6">
<input type="hidden" name="id" value={invoice.id} /> {/* Invoice ID */}
{/* Customer Name */} <input type="hidden" name="id" value={invoice.id} />
<div className="mb-4"> {/* Customer Name */}
<label htmlFor="customer" className="mb-2 block text-sm font-medium"> <div className="mb-4">
Choose customer <label htmlFor="customer" className="mb-2 block text-sm font-medium">
</label> Choose customer
<div className="relative"> </label>
<select <div className="relative">
id="customer" <select
name="customerId" id="customer"
className="peer block w-full rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500" name="customerId"
defaultValue={invoice.customer_id} className="peer block w-full rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500"
> defaultValue={invoice.customer_id}
<option value="" disabled> aria-describedby="customer-error"
Select a customer >
</option> <option value="" disabled>
{customers.map((customer) => ( Select a customer
<option key={customer.id} value={customer.id}> </option>
{customer.name} {customers.map((customer) => (
</option> <option key={customer.id} value={customer.id}>
))} {customer.name}
</select> </option>
<UserCircleIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500" /> ))}
</div> </select>
</div> <UserCircleIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500" />
</div>
{state.errors?.customerId ? (
<div
id="customer-error"
aria-live="polite"
className="mt-2 text-sm text-red-500"
>
{state.errors.customerId.map((error: string) => (
<p key={error}>{error}</p>
))}
</div>
) : null}
</div>
{/* Invoice Amount */} {/* Invoice Amount */}
<div className="mb-4"> <div className="mb-4">
<label htmlFor="amount" className="mb-2 block text-sm font-medium"> <label htmlFor="amount" className="mb-2 block text-sm font-medium">
Choose an amount Choose an amount
</label> </label>
<div className="relative mt-2 rounded-md"> <div className="relative mt-2 rounded-md">
<div className="relative"> <div className="relative">
<input <input
id="amount" id="amount"
name="amount" name="amount"
type="number" type="number"
defaultValue={invoice.amount} defaultValue={invoice.amount}
placeholder="Enter USD amount" placeholder="Enter USD amount"
className="peer block w-full rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500" className="peer block w-full rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500"
/> aria-describedby="amount-error"
<CurrencyDollarIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" /> />
</div> <CurrencyDollarIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
</div> </div>
</div> </div>
{state.errors?.amount ? (
<div
id="amount-error"
aria-live="polite"
className="mt-2 text-sm text-red-500"
>
{state.errors.amount.map((error: string) => (
<p key={error}>{error}</p>
))}
</div>
) : null}
</div>
{/* Invoice Status */} {/* Invoice Status */}
<div> <fieldset>
<label htmlFor="status" className="mb-2 block text-sm font-medium"> <label htmlFor="status" className="mb-2 block text-sm font-medium">
Set the invoice status Set the invoice status
</label> </label>
<div className="rounded-md border border-gray-200 bg-white px-[14px] py-3"> <div className="rounded-md border border-gray-200 bg-white px-[14px] py-3">
<div className="flex gap-4"> <div className="flex gap-4">
<div className="flex items-center"> <div className="flex items-center">
<input <input
id="pending" id="pending"
name="status" name="status"
type="radio" type="radio"
value="pending" value="pending"
defaultChecked={invoice.status === 'pending'} defaultChecked={invoice.status === "pending"}
className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600" className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600"
/> />
<label <label
htmlFor="pending" htmlFor="pending"
className="ml-2 flex items-center gap-1.5 rounded-full bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-600 dark:text-gray-300" className="ml-2 flex items-center gap-1.5 rounded-full bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-600 dark:text-gray-300"
> >
Pending <ClockIcon className="h-4 w-4" /> Pending <ClockIcon className="h-4 w-4" />
</label> </label>
</div> </div>
<div className="flex items-center"> <div className="flex items-center">
<input <input
id="paid" id="paid"
name="status" name="status"
type="radio" type="radio"
value="paid" value="paid"
defaultChecked={invoice.status === 'paid'} defaultChecked={invoice.status === "paid"}
className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600" className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600"
/> />
<label <label
htmlFor="paid" htmlFor="paid"
className="ml-2 flex items-center gap-1.5 rounded-full bg-green-500 px-3 py-1.5 text-xs font-medium text-white dark:text-gray-300" className="ml-2 flex items-center gap-1.5 rounded-full bg-green-500 px-3 py-1.5 text-xs font-medium text-white dark:text-gray-300"
> >
Paid <CheckIcon className="h-4 w-4" /> Paid <CheckIcon className="h-4 w-4" />
</label> </label>
</div> </div>
</div> </div>
</div> </div>
</div> {state.errors?.status ? (
</div> <div
<div className="mt-6 flex justify-end gap-4"> aria-describedby="status-error"
<Link aria-live="polite"
href="/dashboard/invoices" className="mt-2 text-sm text-red-500"
className="flex h-10 items-center rounded-lg bg-gray-100 px-4 text-sm font-medium text-gray-600 transition-colors hover:bg-gray-200" >
> {state.errors.status.map((error: string) => (
Cancel <p key={error}>{error}</p>
</Link> ))}
<Button type="submit">Edit Invoice</Button> </div>
</div> ) : null}
</form> </fieldset>
);
{state.message ? (
<div aria-live="polite" className="my-2 text-sm text-red-500">
<p>{state.message}</p>
</div>
) : null}
</div>
<div className="mt-6 flex justify-end gap-4">
<Link
href="/dashboard/invoices"
className="flex h-10 items-center rounded-lg bg-gray-100 px-4 text-sm font-medium text-gray-600 transition-colors hover:bg-gray-200"
>
Cancel
</Link>
<Button type="submit">Edit Invoice</Button>
</div>
</form>
);
} }

View file

@ -1,20 +1,30 @@
'use client'; 'use client';
import { usePathname, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeftIcon, ArrowRightIcon } from '@heroicons/react/24/outline'; import { ArrowLeftIcon, ArrowRightIcon } from '@heroicons/react/24/outline';
import clsx from 'clsx'; import clsx from 'clsx';
import Link from 'next/link';
import { generatePagination } from '@/app/lib/utils'; import { generatePagination } from '@/app/lib/utils';
export default function Pagination({ totalPages }: { totalPages: number }) { export default function Pagination({ totalPages }: { totalPages: number }) {
// NOTE: comment in this code when you get to this point in the course // NOTE: comment in this code when you get to this point in the course
const pathname = usePathname();
const searchParams = useSearchParams();
const currentPage = Number(searchParams.get('page')) || 1;
// const allPages = generatePagination(currentPage, totalPages); const createPageURL = (pageNumber: number | string) => {
const params = new URLSearchParams(searchParams);
params.set("page", pageNumber.toString());
return `${pathname}?${params.toString()}`;
}
const allPages = generatePagination(currentPage, totalPages);
return ( return (
<> <>
{/* NOTE: comment in this code when you get to this point in the course */} {/* NOTE: comment in this code when you get to this point in the course */}
{/* <div className="inline-flex"> <div className="inline-flex">
<PaginationArrow <PaginationArrow
direction="left" direction="left"
href={createPageURL(currentPage - 1)} href={createPageURL(currentPage - 1)}
@ -47,7 +57,7 @@ export default function Pagination({ totalPages }: { totalPages: number }) {
href={createPageURL(currentPage + 1)} href={createPageURL(currentPage + 1)}
isDisabled={currentPage >= totalPages} isDisabled={currentPage >= totalPages}
/> />
</div> */} </div>
</> </>
); );
} }

View file

@ -1,73 +1,89 @@
import { lusitana } from '@/app/ui/fonts'; "use client";
import { authenticate } from "@/app/lib/actions";
import { lusitana } from "@/app/ui/fonts";
import { import {
AtSymbolIcon, AtSymbolIcon,
KeyIcon, KeyIcon,
ExclamationCircleIcon, ExclamationCircleIcon,
} from '@heroicons/react/24/outline'; } from "@heroicons/react/24/outline";
import { ArrowRightIcon } from '@heroicons/react/20/solid'; import { ArrowRightIcon } from "@heroicons/react/20/solid";
import { Button } from './button'; import { Button } from "./button";
import { useFormState, useFormStatus } from "react-dom";
export default function LoginForm() { export default function LoginForm() {
return ( const [code, action] = useFormState(authenticate, undefined);
<form className="space-y-3"> const { pending } = useFormStatus();
<div className="flex-1 rounded-lg bg-gray-50 px-6 pb-4 pt-8">
<h1 className={`${lusitana.className} mb-3 text-2xl`}> return (
Please log in to continue. <form action={action} className="space-y-3">
</h1> <div className="flex-1 rounded-lg bg-gray-50 px-6 pb-4 pt-8">
<div className="w-full"> <h1 className={`${lusitana.className} mb-3 text-2xl`}>
<div> Please log in to continue.
<label </h1>
className="mb-3 mt-5 block text-xs font-medium text-gray-900" <div className="w-full">
htmlFor="email" <div>
> <label
Email className="mb-3 mt-5 block text-xs font-medium text-gray-900"
</label> htmlFor="email"
<div className="relative"> >
<input Email
className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500" </label>
id="email" <div className="relative">
type="email" <input
name="email" className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
placeholder="Enter your email address" id="email"
required type="email"
/> name="email"
<AtSymbolIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" /> placeholder="Enter your email address"
</div> required
</div> />
<div className="mt-4"> <AtSymbolIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
<label </div>
className="mb-3 mt-5 block text-xs font-medium text-gray-900" </div>
htmlFor="password" <div className="mt-4">
> <label
Password className="mb-3 mt-5 block text-xs font-medium text-gray-900"
</label> htmlFor="password"
<div className="relative"> >
<input Password
className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500" </label>
id="password" <div className="relative">
type="password" <input
name="password" className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
placeholder="Enter password" id="password"
required type="password"
minLength={6} name="password"
/> placeholder="Enter password"
<KeyIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" /> required
</div> minLength={6}
</div> />
</div> <KeyIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
<LoginButton /> </div>
<div className="flex h-8 items-end space-x-1"> </div>
{/* Add form errors here */} </div>
</div> <LoginButton />
</div> <div className="flex h-8 items-end space-x-1">
</form> {code === "CredentialsSignin" && (
); <>
<ExclamationCircleIcon className="h-5 w-5 text-red-500" />
<p aria-live="polite" className="text-sm text-red-500">
Invalid credentials
</p>
</>
)}
</div>
</div>
</form>
);
} }
function LoginButton() { function LoginButton() {
return ( const { pending } = useFormStatus();
<Button className="mt-4 w-full">
Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" /> return (
</Button> <Button className="mt-4 w-full" aria-disabled={pending}>
); Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" />
</Button>
);
} }

View file

@ -10,8 +10,8 @@ export default function Search({ placeholder }: { placeholder: string }) {
const { replace } = useRouter(); const { replace } = useRouter();
const handleSearch = useDebouncedCallback((term: string) => { const handleSearch = useDebouncedCallback((term: string) => {
console.log(`Searching... ${term}`);
const params = new URLSearchParams(searchParams); const params = new URLSearchParams(searchParams);
params.set('page', '1');
if (term) { if (term) {
params.set('query', term); params.set('query', term);
} else { } else {

24
auth.config.ts Normal file
View file

@ -0,0 +1,24 @@
import type { NextAuthConfig } from "next-auth";
export const authConfig = {
pages: {
signIn: "/login",
},
providers: [
// added later in auth.ts since it requires bcrypt which is only compatible with Node.js
// while this file is also used in non-Node.js environments
],
callbacks: {
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
const isOnDashboard = nextUrl.pathname.startsWith("/dashboard");
if (isOnDashboard) {
if (isLoggedIn) return true;
return false; // Redirect unathenticated users to login page
} else if (isLoggedIn) {
return Response.redirect(new URL("/dashboard", nextUrl));
}
return true;
},
},
} satisfies NextAuthConfig;

45
auth.ts Normal file
View file

@ -0,0 +1,45 @@
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import bcrypt from "bcrypt";
import { sql } from "@vercel/postgres";
import { z } from "zod";
import type { User } from "@/app/lib/definitions";
import { authConfig } from "./auth.config";
async function getUser(email: string): Promise<User | undefined> {
try {
const user = await sql<User>`SELECT * from USERS where email=${email}`;
return user.rows[0];
} catch (error) {
console.error("Failed to fetch user:", error);
throw new Error("Failed to fetch user.");
}
}
export const { auth, signIn, signOut } = NextAuth({
...authConfig,
providers: [
Credentials({
async authorize(credentials) {
const parsedCredentials = z
.object({ email: z.string().email(), password: z.string().min(6) })
.safeParse(credentials);
if (parsedCredentials.success) {
console.log('Valid credentials');
const { email, password } = parsedCredentials.data;
const user = await getUser(email);
if (!user) return null;
const passwordsMatch = await bcrypt.compare(password, user.password);
console.log('Passwords match', passwordsMatch);
if (passwordsMatch) return user;
}
console.log("Invalid credentials");
return null;
},
}),
],
});

9
middleware.ts Normal file
View file

@ -0,0 +1,9 @@
import NextAuth from "next-auth";
import { authConfig } from "./auth.config";
export default NextAuth(authConfig).auth;
export const config = {
// https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
matcher: ["/((?!api|_next/static|_next/image|.png).*)"],
};

View file

@ -3,8 +3,9 @@
"scripts": { "scripts": {
"build": "next build", "build": "next build",
"dev": "next dev", "dev": "next dev",
"seed": "node -r dotenv/config ./scripts/seed.js",
"start": "next start", "start": "next start",
"seed": "node -r dotenv/config ./scripts/seed.js" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"@heroicons/react": "^2.0.18", "@heroicons/react": "^2.0.18",
@ -15,6 +16,7 @@
"bcrypt": "^5.1.1", "bcrypt": "^5.1.1",
"clsx": "^2.0.0", "clsx": "^2.0.0",
"next": "^14.0.0", "next": "^14.0.0",
"next-auth": "5.0.0-beta.3",
"postcss": "8.4.31", "postcss": "8.4.31",
"react": "18.2.0", "react": "18.2.0",
"react-dom": "18.2.0", "react-dom": "18.2.0",
@ -28,6 +30,8 @@
"@types/react": "18.2.21", "@types/react": "18.2.21",
"@types/react-dom": "18.2.14", "@types/react-dom": "18.2.14",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"eslint": "8.52.0",
"eslint-config-next": "14.0.1",
"prettier": "^3.0.3" "prettier": "^3.0.3"
}, },
"engines": { "engines": {

File diff suppressed because it is too large Load diff