Updated with a few functions
This commit is contained in:
parent
f293c5a14c
commit
92e5df8f94
20 changed files with 422 additions and 46 deletions
5
app/dashboard/(overview)/loading.tsx
Normal file
5
app/dashboard/(overview)/loading.tsx
Normal file
|
@ -0,0 +1,5 @@
|
|||
import DashboardSkeleton from "@/app/ui/skeletons";
|
||||
|
||||
export default function Loading() {
|
||||
return <DashboardSkeleton />;
|
||||
}
|
34
app/dashboard/(overview)/page.tsx
Normal file
34
app/dashboard/(overview)/page.tsx
Normal file
|
@ -0,0 +1,34 @@
|
|||
import CardWrapper from "@/app/ui/dashboard/cards";
|
||||
import { 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 { Suspense } from "react";
|
||||
import {
|
||||
RevenueChartSkeleton,
|
||||
LatestInvoicesSkeleton,
|
||||
CardsSkeleton,
|
||||
} from "@/app/ui/skeletons";
|
||||
|
||||
export default async function Page() {
|
||||
return (
|
||||
<main>
|
||||
<h1 className={`${lusitana.className} mb-4 text-xl mb:text-2xl`}>
|
||||
Dashboard
|
||||
</h1>
|
||||
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Suspense fallback={<CardsSkeleton />}>
|
||||
<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 />}>
|
||||
<LatestInvoices />
|
||||
</Suspense>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
18
app/dashboard/invoices/[id]/edit/not-found.tsx
Normal file
18
app/dashboard/invoices/[id]/edit/not-found.tsx
Normal 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>
|
||||
);
|
||||
}
|
32
app/dashboard/invoices/[id]/edit/page.tsx
Normal file
32
app/dashboard/invoices/[id]/edit/page.tsx
Normal file
|
@ -0,0 +1,32 @@
|
|||
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';
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
23
app/dashboard/invoices/create/page.tsx
Normal file
23
app/dashboard/invoices/create/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
31
app/dashboard/invoices/error.tsx
Normal file
31
app/dashboard/invoices/error.tsx
Normal 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>
|
||||
);
|
||||
}
|
|
@ -1,3 +1,40 @@
|
|||
export default function Page() {
|
||||
return <p>Invoices Page</p>
|
||||
import Pagination from '@/app/ui/invoices/pagination';
|
||||
import Search from '@/app/ui/search';
|
||||
import Table from '@/app/ui/invoices/table';
|
||||
import { CreateInvoice } from '@/app/ui/invoices/buttons';
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
import { InvoicesTableSkeleton } from '@/app/ui/skeletons';
|
||||
import { Suspense } from 'react';
|
||||
import { fetchInvoicesPages } from '@/app/lib/data';
|
||||
|
||||
export default async function Page({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams?: {
|
||||
query?: string;
|
||||
page?: string;
|
||||
};
|
||||
}) {
|
||||
const query = searchParams?.query || '';
|
||||
const currentPage = Number(searchParams?.page) || 1;
|
||||
|
||||
const totalPages = await fetchInvoicesPages(query);
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<h1 className={`${lusitana.className} text-2xl`}>Invoices</h1>
|
||||
</div>
|
||||
<div className="mt-4 flex items-center justify-between gap-2 md:mt-8">
|
||||
<Search placeholder="Search invoices..." />
|
||||
<CreateInvoice />
|
||||
</div>
|
||||
<Suspense key={query + currentPage} fallback={<InvoicesTableSkeleton />}>
|
||||
<Table query={query} currentPage={currentPage} />
|
||||
</Suspense>
|
||||
<div className="mt-5 flex w-full justify-center">
|
||||
<Pagination totalPages={totalPages} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
|
@ -1,3 +0,0 @@
|
|||
export default function Page() {
|
||||
return <p>Dashboard Page</p>
|
||||
}
|
116
app/lib/actions.ts
Normal file
116
app/lib/actions.ts
Normal file
|
@ -0,0 +1,116 @@
|
|||
'use server';
|
||||
|
||||
import { z } from 'zod';
|
||||
import { sql } from '@vercel/postgres';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
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 amount 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({ id: true, date: 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(
|
||||
id: string,
|
||||
prevState: State,
|
||||
formData: FormData,
|
||||
) {
|
||||
const validatedFields = UpdateInvoice.safeParse({
|
||||
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 { 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(id: string) {
|
||||
try {
|
||||
await sql`DELETE FROM invoices WHERE id = ${id}`;
|
||||
revalidatePath('/dashboard/invoices');
|
||||
return {message: 'Deleted Invoice.'};
|
||||
} catch (error) {
|
||||
return {message: 'Database Error: Failed to Delete Invoice.'};
|
||||
}
|
||||
}
|
|
@ -9,21 +9,22 @@ import {
|
|||
Revenue,
|
||||
} from './definitions';
|
||||
import { formatCurrency } from './utils';
|
||||
import { unstable_noStore as noStore } from 'next/cache';
|
||||
|
||||
export async function fetchRevenue() {
|
||||
// Add noStore() here to prevent the response from being cached.
|
||||
// This is equivalent to in fetch(..., {cache: 'no-store'}).
|
||||
noStore();
|
||||
|
||||
try {
|
||||
// Artificially delay a response for demo purposes.
|
||||
// Don't do this in production :)
|
||||
|
||||
// console.log('Fetching revenue data...');
|
||||
// await new Promise((resolve) => setTimeout(resolve, 3000));
|
||||
console.log('Fetching revenue data...');
|
||||
await new Promise((resolve) => setTimeout(resolve, 3000));
|
||||
|
||||
const data = await sql<Revenue>`SELECT * FROM revenue`;
|
||||
|
||||
// console.log('Data fetch completed after 3 seconds.');
|
||||
console.log('Data fetch completed after 3 seconds.');
|
||||
|
||||
return data.rows;
|
||||
} catch (error) {
|
||||
|
@ -33,6 +34,7 @@ export async function fetchRevenue() {
|
|||
}
|
||||
|
||||
export async function fetchLatestInvoices() {
|
||||
noStore();
|
||||
try {
|
||||
const data = await sql<LatestInvoiceRaw>`
|
||||
SELECT invoices.amount, customers.name, customers.image_url, customers.email, invoices.id
|
||||
|
@ -53,6 +55,7 @@ export async function fetchLatestInvoices() {
|
|||
}
|
||||
|
||||
export async function fetchCardData() {
|
||||
noStore();
|
||||
try {
|
||||
// You can probably combine these into a single SQL query
|
||||
// However, we are intentionally splitting them to demonstrate
|
||||
|
@ -92,6 +95,7 @@ export async function fetchFilteredInvoices(
|
|||
query: string,
|
||||
currentPage: number,
|
||||
) {
|
||||
noStore();
|
||||
const offset = (currentPage - 1) * ITEMS_PER_PAGE;
|
||||
|
||||
try {
|
||||
|
@ -124,6 +128,7 @@ export async function fetchFilteredInvoices(
|
|||
}
|
||||
|
||||
export async function fetchInvoicesPages(query: string) {
|
||||
noStore();
|
||||
try {
|
||||
const count = await sql`SELECT COUNT(*)
|
||||
FROM invoices
|
||||
|
@ -145,6 +150,7 @@ export async function fetchInvoicesPages(query: string) {
|
|||
}
|
||||
|
||||
export async function fetchInvoiceById(id: string) {
|
||||
noStore();
|
||||
try {
|
||||
const data = await sql<InvoiceForm>`
|
||||
SELECT
|
||||
|
@ -162,6 +168,7 @@ export async function fetchInvoiceById(id: string) {
|
|||
amount: invoice.amount / 100,
|
||||
}));
|
||||
|
||||
console.log(invoice);
|
||||
return invoice[0];
|
||||
} catch (error) {
|
||||
console.error('Database Error:', error);
|
||||
|
@ -188,6 +195,7 @@ export async function fetchCustomers() {
|
|||
}
|
||||
|
||||
export async function fetchFilteredCustomers(query: string) {
|
||||
noStore();
|
||||
try {
|
||||
const data = await sql<CustomersTableType>`
|
||||
SELECT
|
||||
|
|
|
@ -5,6 +5,7 @@ import {
|
|||
InboxIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
import { fetchCardData } from '@/app/lib/data';
|
||||
|
||||
const iconMap = {
|
||||
collected: BanknotesIcon,
|
||||
|
@ -14,18 +15,25 @@ const iconMap = {
|
|||
};
|
||||
|
||||
export default async function CardWrapper() {
|
||||
const {
|
||||
numberOfInvoices,
|
||||
numberOfCustomers,
|
||||
totalPaidInvoices,
|
||||
totalPendingInvoices,
|
||||
} = await fetchCardData();
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* NOTE: comment in this code when you get to this point in the course */}
|
||||
|
||||
{/* <Card title="Collected" value={totalPaidInvoices} type="collected" />
|
||||
<Card title="Collected" value={totalPaidInvoices} type="collected" />
|
||||
<Card title="Pending" value={totalPendingInvoices} type="pending" />
|
||||
<Card title="Total Invoices" value={numberOfInvoices} type="invoices" />
|
||||
<Card
|
||||
title="Total Customers"
|
||||
value={numberOfCustomers}
|
||||
type="customers"
|
||||
/> */}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -2,12 +2,9 @@ import { ArrowPathIcon } from '@heroicons/react/24/outline';
|
|||
import clsx from 'clsx';
|
||||
import Image from 'next/image';
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
import { LatestInvoice } from '@/app/lib/definitions';
|
||||
export default async function LatestInvoices({
|
||||
latestInvoices,
|
||||
}: {
|
||||
latestInvoices: LatestInvoice[];
|
||||
}) {
|
||||
import { fetchLatestInvoices } from '@/app/lib/data';
|
||||
export default async function LatestInvoices() {
|
||||
const latestInvoices = await fetchLatestInvoices();
|
||||
return (
|
||||
<div className="flex w-full flex-col md:col-span-4">
|
||||
<h2 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}>
|
||||
|
@ -16,7 +13,7 @@ export default async function LatestInvoices({
|
|||
<div className="flex grow flex-col justify-between rounded-xl bg-gray-50 p-4">
|
||||
{/* NOTE: comment in this code when you get to this point in the course */}
|
||||
|
||||
{/* <div className="bg-white px-6">
|
||||
<div className="bg-white px-6">
|
||||
{latestInvoices.map((invoice, i) => {
|
||||
return (
|
||||
<div
|
||||
|
@ -53,7 +50,7 @@ export default async function LatestInvoices({
|
|||
</div>
|
||||
);
|
||||
})}
|
||||
</div> */}
|
||||
</div>
|
||||
<div className="flex items-center pb-2 pt-6">
|
||||
<ArrowPathIcon className="h-5 w-5 text-gray-500" />
|
||||
<h3 className="ml-2 text-sm text-gray-500 ">Updated just now</h3>
|
||||
|
|
|
@ -2,6 +2,7 @@ import { generateYAxis } from '@/app/lib/utils';
|
|||
import { CalendarIcon } from '@heroicons/react/24/outline';
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
import { Revenue } from '@/app/lib/definitions';
|
||||
import { fetchRevenue } from '@/app/lib/data';
|
||||
|
||||
// This component is representational only.
|
||||
// For data visualization UI, check out:
|
||||
|
@ -9,19 +10,17 @@ import { Revenue } from '@/app/lib/definitions';
|
|||
// https://www.chartjs.org/
|
||||
// https://airbnb.io/visx/
|
||||
|
||||
export default async function RevenueChart({
|
||||
revenue,
|
||||
}: {
|
||||
revenue: Revenue[];
|
||||
}) {
|
||||
export default async function RevenueChart() {
|
||||
const revenue = await fetchRevenue();
|
||||
|
||||
const chartHeight = 350;
|
||||
// NOTE: comment in this code when you get to this point in the course
|
||||
|
||||
// const { yAxisLabels, topLabel } = generateYAxis(revenue);
|
||||
const { yAxisLabels, topLabel } = generateYAxis(revenue);
|
||||
|
||||
// if (!revenue || revenue.length === 0) {
|
||||
// return <p className="mt-4 text-gray-400">No data available.</p>;
|
||||
// }
|
||||
if (!revenue || revenue.length === 0) {
|
||||
return <p className="mt-4 text-gray-400">No data available.</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full md:col-span-4">
|
||||
|
@ -30,7 +29,7 @@ export default async function RevenueChart({
|
|||
</h2>
|
||||
{/* NOTE: comment in this code when you get to this point in the course */}
|
||||
|
||||
{/* <div className="rounded-xl bg-gray-50 p-4">
|
||||
<div className="rounded-xl bg-gray-50 p-4">
|
||||
<div className="sm:grid-cols-13 mt-0 grid grid-cols-12 items-end gap-2 rounded-md bg-white p-4 md:gap-4">
|
||||
<div
|
||||
className="mb-6 hidden flex-col justify-between text-sm text-gray-400 sm:flex"
|
||||
|
@ -59,7 +58,7 @@ export default async function RevenueChart({
|
|||
<CalendarIcon className="h-5 w-5 text-gray-500" />
|
||||
<h3 className="ml-2 text-sm text-gray-500 ">Last 12 months</h3>
|
||||
</div>
|
||||
</div> */}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
import { PencilIcon, PlusIcon, TrashIcon } from '@heroicons/react/24/outline';
|
||||
import Link from 'next/link';
|
||||
import { deleteInvoice } from '@/app/lib/actions';
|
||||
|
||||
export function CreateInvoice() {
|
||||
return (
|
||||
|
@ -16,7 +17,7 @@ export function CreateInvoice() {
|
|||
export function UpdateInvoice({ id }: { id: string }) {
|
||||
return (
|
||||
<Link
|
||||
href="/dashboard/invoices"
|
||||
href={`/dashboard/invoices/${id}/edit`}
|
||||
className="rounded-md border p-2 hover:bg-gray-100"
|
||||
>
|
||||
<PencilIcon className="w-5" />
|
||||
|
@ -25,12 +26,13 @@ export function UpdateInvoice({ id }: { id: string }) {
|
|||
}
|
||||
|
||||
export function DeleteInvoice({ id }: { id: string }) {
|
||||
const deleteInvoiceWithId = deleteInvoice.bind(null, id);
|
||||
return (
|
||||
<>
|
||||
<form action={deleteInvoiceWithId}>
|
||||
<button className="rounded-md border p-2 hover:bg-gray-100">
|
||||
<span className="sr-only">Delete</span>
|
||||
<TrashIcon className="w-5" />
|
||||
</button>
|
||||
</>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -1,3 +1,5 @@
|
|||
'use client';
|
||||
|
||||
import { CustomerField } from '@/app/lib/definitions';
|
||||
import Link from 'next/link';
|
||||
import {
|
||||
|
@ -7,10 +9,14 @@ import {
|
|||
UserCircleIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { Button } from '@/app/ui/button';
|
||||
import { createInvoice } from '@/app/lib/actions';
|
||||
import { useFormState } from 'react-dom';
|
||||
|
||||
export default function Form({ customers }: { customers: CustomerField[] }) {
|
||||
const initialState = { message: null, errors: {} };
|
||||
const [state, dispatch] = useFormState(createInvoice, initialState);
|
||||
return (
|
||||
<form>
|
||||
<form action={dispatch}>
|
||||
<div className="rounded-md bg-gray-50 p-4 md:p-6">
|
||||
{/* Customer Name */}
|
||||
<div className="mb-4">
|
||||
|
@ -23,6 +29,7 @@ export default function Form({ customers }: { customers: CustomerField[] }) {
|
|||
name="customerId"
|
||||
className="peer block w-full cursor-pointer rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500"
|
||||
defaultValue=""
|
||||
aria-describedby='customer-error'
|
||||
>
|
||||
<option value="" disabled>
|
||||
Select a customer
|
||||
|
@ -35,6 +42,14 @@ export default function Form({ customers }: { customers: CustomerField[] }) {
|
|||
</select>
|
||||
<UserCircleIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500" />
|
||||
</div>
|
||||
<div id="customer-error" aria-live="polite" aria-atomic="true">
|
||||
{state.errors?.customerId &&
|
||||
state.errors.customerId.map((error) => (
|
||||
<p className="mt-2 text-sm text-red-500" key={error}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Invoice Amount */}
|
||||
|
@ -51,6 +66,7 @@ export default function Form({ customers }: { customers: CustomerField[] }) {
|
|||
step="0.01"
|
||||
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"
|
||||
required
|
||||
/>
|
||||
<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>
|
||||
|
|
|
@ -9,6 +9,8 @@ import {
|
|||
} from '@heroicons/react/24/outline';
|
||||
import Link from 'next/link';
|
||||
import { Button } from '@/app/ui/button';
|
||||
import { updateInvoice } from '@/app/lib/actions';
|
||||
import { useFormState } from 'react-dom';
|
||||
|
||||
export default function EditInvoiceForm({
|
||||
invoice,
|
||||
|
@ -16,9 +18,12 @@ export default function EditInvoiceForm({
|
|||
}: {
|
||||
invoice: InvoiceForm;
|
||||
customers: CustomerField[];
|
||||
}) {
|
||||
}) {
|
||||
const initialState = {message: null, errors: {}}
|
||||
const updateInvoiceWithId = updateInvoice.bind(null, invoice.id);
|
||||
const [state, dispatch] = useFormState(updateInvoiceWithId, initialState);
|
||||
return (
|
||||
<form>
|
||||
<form action={dispatch}>
|
||||
<div className="rounded-md bg-gray-50 p-4 md:p-6">
|
||||
{/* Customer Name */}
|
||||
<div className="mb-4">
|
||||
|
|
|
@ -4,8 +4,19 @@ import { ArrowLeftIcon, ArrowRightIcon } from '@heroicons/react/24/outline';
|
|||
import clsx from 'clsx';
|
||||
import Link from 'next/link';
|
||||
import { generatePagination } from '@/app/lib/utils';
|
||||
import { usePathname, useSearchParams } from 'next/navigation';
|
||||
|
||||
export default function Pagination({ totalPages }: { totalPages: number }) {
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const currentPage = Number(searchParams.get('page')) || 1;
|
||||
|
||||
const createPageURL = (page: number) => {
|
||||
const params = new URLSearchParams(searchParams);
|
||||
params.set('page', page.toString());
|
||||
return `${pathname}?${params.toString()}`;
|
||||
};
|
||||
|
||||
// NOTE: comment in this code when you get to this point in the course
|
||||
|
||||
// const allPages = generatePagination(currentPage, totalPages);
|
||||
|
|
|
@ -1,8 +1,26 @@
|
|||
'use client';
|
||||
|
||||
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
|
||||
import { useSearchParams, usePathname, useRouter } from 'next/navigation';
|
||||
import { useDebouncedCallback } from 'use-debounce';
|
||||
|
||||
export default function Search({ placeholder }: { placeholder: string }) {
|
||||
const searchParams = useSearchParams();
|
||||
const pathname = usePathname();
|
||||
const {replace} = useRouter();
|
||||
|
||||
const handleSearch = useDebouncedCallback((term) => {
|
||||
console.log(`Searching... ${term}`);
|
||||
|
||||
const params = new URLSearchParams(searchParams);
|
||||
params.set('page', '1');
|
||||
if (term) {
|
||||
params.set('query', term);
|
||||
} else {
|
||||
params.delete('query');
|
||||
}
|
||||
replace(`${pathname}?${params.toString()}`);
|
||||
}, 300);
|
||||
return (
|
||||
<div className="relative flex flex-1 flex-shrink-0">
|
||||
<label htmlFor="search" className="sr-only">
|
||||
|
@ -11,6 +29,10 @@ export default function Search({ placeholder }: { placeholder: string }) {
|
|||
<input
|
||||
className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => {
|
||||
handleSearch(e.target.value);
|
||||
}}
|
||||
defaultValue={searchParams.get('query')?.toString()}
|
||||
/>
|
||||
<MagnifyingGlassIcon className="absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
|
||||
</div>
|
||||
|
|
28
package-lock.json
generated
28
package-lock.json
generated
|
@ -8,7 +8,7 @@
|
|||
"@heroicons/react": "^2.0.18",
|
||||
"@tailwindcss/forms": "^0.5.7",
|
||||
"@types/node": "20.5.7",
|
||||
"@vercel/postgres": "^0.5.0",
|
||||
"@vercel/postgres": "^0.5.1",
|
||||
"autoprefixer": "10.4.15",
|
||||
"bcrypt": "^5.1.1",
|
||||
"clsx": "^2.0.0",
|
||||
|
@ -18,6 +18,7 @@
|
|||
"react-dom": "18.2.0",
|
||||
"tailwindcss": "3.3.3",
|
||||
"typescript": "5.2.2",
|
||||
"use-debounce": "^10.0.0",
|
||||
"zod": "^3.22.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
@ -1534,12 +1535,12 @@
|
|||
"dev": true
|
||||
},
|
||||
"node_modules/@vercel/postgres": {
|
||||
"version": "0.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@vercel/postgres/-/postgres-0.5.0.tgz",
|
||||
"integrity": "sha512-MFWp9SZmADqBe2x2mzEvwmGLiwOd8PVkUxYeBZx/RqdHl0bd8/1BH0zBR+zSimGyi9P/MVtZoJLdf5dkWw9m5Q==",
|
||||
"version": "0.5.1",
|
||||
"resolved": "https://registry.npmjs.org/@vercel/postgres/-/postgres-0.5.1.tgz",
|
||||
"integrity": "sha512-JKl8QOBIDnifhkxAhIKtY0A5Tb8oWBf2nzZhm0OH7Ffjsl0hGVnDL2w1/FCfpX8xna3JAWM034NGuhZfTFdmiw==",
|
||||
"dependencies": {
|
||||
"@neondatabase/serverless": "0.6.0",
|
||||
"bufferutil": "4.0.7",
|
||||
"bufferutil": "4.0.8",
|
||||
"utf-8-validate": "6.0.3",
|
||||
"ws": "8.14.2"
|
||||
},
|
||||
|
@ -2037,9 +2038,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/bufferutil": {
|
||||
"version": "4.0.7",
|
||||
"resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.7.tgz",
|
||||
"integrity": "sha512-kukuqc39WOHtdxtw4UScxF/WVnMFVSQVKhtx3AjZJzhd0RGZZldcrfSEbVsWWe6KNH253574cq5F+wpv0G9pJw==",
|
||||
"version": "4.0.8",
|
||||
"resolved": "https://registry.npmjs.org/bufferutil/-/bufferutil-4.0.8.tgz",
|
||||
"integrity": "sha512-4T53u4PdgsXqKaIctwF8ifXlRTTmEPJ8iEPWFdGZvcf7sbwYo6FKFEX9eNNAnzFZ7EzJAQ3CJeOtCRA4rDp7Pw==",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"node-gyp-build": "^4.3.0"
|
||||
|
@ -7100,6 +7101,17 @@
|
|||
"punycode": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/use-debounce": {
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/use-debounce/-/use-debounce-10.0.0.tgz",
|
||||
"integrity": "sha512-XRjvlvCB46bah9IBXVnq/ACP2lxqXyZj0D9hj4K5OzNroMDpTEBg8Anuh1/UfRTRs7pLhQ+RiNxxwZu9+MVl1A==",
|
||||
"engines": {
|
||||
"node": ">= 16.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/utf-8-validate": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-6.0.3.tgz",
|
||||
|
|
|
@ -5,13 +5,15 @@
|
|||
"dev": "next dev",
|
||||
"prettier": "prettier --write --ignore-unknown .",
|
||||
"prettier:check": "prettier --check --ignore-unknown .",
|
||||
"start": "next start"
|
||||
"start": "next start",
|
||||
"seed": "node -r dotenv/config ./scripts/seed.js",
|
||||
"lint": "next lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@heroicons/react": "^2.0.18",
|
||||
"@tailwindcss/forms": "^0.5.7",
|
||||
"@types/node": "20.5.7",
|
||||
"@vercel/postgres": "^0.5.0",
|
||||
"@vercel/postgres": "^0.5.1",
|
||||
"autoprefixer": "10.4.15",
|
||||
"bcrypt": "^5.1.1",
|
||||
"clsx": "^2.0.0",
|
||||
|
@ -21,6 +23,7 @@
|
|||
"react-dom": "18.2.0",
|
||||
"tailwindcss": "3.3.3",
|
||||
"typescript": "5.2.2",
|
||||
"use-debounce": "^10.0.0",
|
||||
"zod": "^3.22.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
Loading…
Reference in a new issue