git init
36
(2).gitignore
Normal file
@@ -0,0 +1,36 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# local env files
|
||||
.env*.local
|
||||
.env
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
6
.eslintrc.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"extends": [
|
||||
"next/core-web-vitals",
|
||||
"next/typescript"
|
||||
]
|
||||
}
|
||||
5
README (2).md
Normal file
@@ -0,0 +1,5 @@
|
||||
## Next.js App Router Course - Starter
|
||||
|
||||
This is the starter template for the Next.js App Router Course. It contains the starting code for the dashboard application.
|
||||
|
||||
For more information, see the [course curriculum](https://nextjs.org/learn) on the Next.js Website.
|
||||
4
app/dashboard/(overview)/loading.tsx
Normal file
@@ -0,0 +1,4 @@
|
||||
import DashboardSkeleton from "@/app/ui/skeletons";
|
||||
export default function Loading() {
|
||||
return <DashboardSkeleton />;
|
||||
};
|
||||
34
app/dashboard/(overview)/page.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import CardWrapper 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 {CardsSkeleton, LatestInvoicesSkeleton, RevenueChartSkeleton} from "@/app/ui/skeletons";
|
||||
import {Metadata} from "next";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Dashboard',
|
||||
}
|
||||
|
||||
export default async function Page() {
|
||||
return (
|
||||
<main>
|
||||
<h1 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}>
|
||||
대시보드
|
||||
</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>
|
||||
);
|
||||
}
|
||||
23
app/dashboard/customers/page.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { Metadata } from 'next';
|
||||
import CustomersTable from "@/app/ui/customers/table";
|
||||
import {fetchFilteredCustomers, fetchInvoicesPages} from "@/app/lib/data";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Customers',
|
||||
}
|
||||
|
||||
export default async function Page(props: {
|
||||
searchParams?: Promise<{
|
||||
query?: string;
|
||||
page?: string;
|
||||
}>;
|
||||
}) {
|
||||
const searchParams = await props.searchParams;
|
||||
const query = searchParams?.query || '';
|
||||
const currentPage = Number(searchParams?.page) || 1;
|
||||
const customers = await fetchFilteredCustomers(query);
|
||||
|
||||
return (
|
||||
<CustomersTable customers={customers}/>
|
||||
)
|
||||
}
|
||||
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>
|
||||
);
|
||||
}
|
||||
39
app/dashboard/invoices/[id]/edit/page.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
import Form from '@/app/ui/invoices/edit-form';
|
||||
import Breadcrumbs from '@/app/ui/invoices/breadcrumbs';
|
||||
import {fetchCustomers, fetchInvoiceById} from '@/app/lib/data';
|
||||
import {notFound} from 'next/navigation';
|
||||
import {Metadata} from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Edit Invoice',
|
||||
}
|
||||
|
||||
export default async function Page(props: {
|
||||
params: Promise<{ id: string }>
|
||||
}) {
|
||||
const params = await props.params;
|
||||
const { id } = params;
|
||||
|
||||
const [invoice, customers] = await Promise.all([
|
||||
fetchInvoiceById(id),
|
||||
fetchCustomers()
|
||||
]);
|
||||
|
||||
if (!invoice) return 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>
|
||||
);
|
||||
}
|
||||
28
app/dashboard/invoices/create/page.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
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 Invoice',
|
||||
}
|
||||
|
||||
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
@@ -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>
|
||||
);
|
||||
}
|
||||
43
app/dashboard/invoices/page.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
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";
|
||||
import {Metadata} from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Invoices',
|
||||
}
|
||||
|
||||
export default async function Page(props: {
|
||||
searchParams?: Promise<{
|
||||
query?: string;
|
||||
page?: string;
|
||||
}>;
|
||||
}) {
|
||||
const searchParams = await props.searchParams;
|
||||
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>
|
||||
);
|
||||
}
|
||||
15
app/dashboard/layout.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import React from "react";
|
||||
import SideNav from "@/app/ui/dashboard/sidenav";
|
||||
|
||||
export const experimental_ppr = true;
|
||||
|
||||
export default function Layout({ children } : { children: React.ReactNode}) {
|
||||
return (
|
||||
<div className="flex h-screen flex-col md:flex-row md:overflow-hidden">
|
||||
<div className="w-full flex-none md:w-64">
|
||||
<SideNav />
|
||||
</div>
|
||||
<div className="flex-grow p-6 md:overflow-y-auto md:p-12">{ children }</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
BIN
app/favicon.ico
Normal file
|
After Width: | Height: | Size: 15 KiB |
25
app/layout.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
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,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body className={`${inter.className} antialiased`}>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
144
app/lib/actions.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
'use server';
|
||||
|
||||
import { z } from 'zod';
|
||||
import {sql} from '@vercel/postgres';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { redirect } from 'next/navigation'
|
||||
import {signIn} from "@/auth";
|
||||
import {AuthError} from "next-auth";
|
||||
|
||||
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(),
|
||||
});
|
||||
|
||||
export type State = {
|
||||
errors?: {
|
||||
customerId?: string[];
|
||||
amount?: string[];
|
||||
status?: string[];
|
||||
};
|
||||
message?: string | null;
|
||||
};
|
||||
|
||||
export async function createInvoice(prevState: State, formData: FormData) {
|
||||
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.',
|
||||
};
|
||||
}
|
||||
|
||||
const { customerId, amount, status } = validatedFields.data;
|
||||
const amountInCents = amount * 100;
|
||||
const date = new Date().toISOString().split('t')[0];
|
||||
|
||||
try {
|
||||
await sql`
|
||||
INSERT INTO invoices (customer_id, amount, status, date)
|
||||
VALUES (${customerId}, ${amountInCents}, ${status}, ${date})
|
||||
`;
|
||||
} catch {
|
||||
return {
|
||||
message: 'Database Error: Failed to create invoice.'
|
||||
}
|
||||
}
|
||||
|
||||
revalidatePath('/dashboard/invoices');
|
||||
redirect('/dashboard/invoices');}
|
||||
|
||||
const CreateInvoice = FormSchema.omit({ id: true, date: true });
|
||||
|
||||
// Use Zod to update the expected types
|
||||
const UpdateInvoice = FormSchema.omit({ id: true, date: true });
|
||||
|
||||
// ...
|
||||
|
||||
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 {
|
||||
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 {
|
||||
return {
|
||||
errors: {},
|
||||
message: 'Database Error: Failed to Delete invoice.'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function authenticate(
|
||||
prevState: string | undefined,
|
||||
formData: FormData,
|
||||
) {
|
||||
try {
|
||||
await signIn('credentials', formData);
|
||||
} catch (error) {
|
||||
if (error instanceof AuthError) {
|
||||
switch (error.type) {
|
||||
case 'CredentialsSignin':
|
||||
return 'Invalid credentials.';
|
||||
default:
|
||||
return 'Something went wrong.';
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
217
app/lib/data.ts
Normal file
@@ -0,0 +1,217 @@
|
||||
import { sql } from '@vercel/postgres';
|
||||
import {
|
||||
CustomerField,
|
||||
CustomersTableType,
|
||||
InvoiceForm,
|
||||
InvoicesTable,
|
||||
LatestInvoiceRaw,
|
||||
Revenue,
|
||||
} from './definitions';
|
||||
import { formatCurrency } from './utils';
|
||||
|
||||
export async function fetchRevenue() {
|
||||
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));
|
||||
|
||||
const data = await sql<Revenue>`SELECT * FROM revenue`;
|
||||
|
||||
console.log('Data fetch completed after 3 seconds.');
|
||||
|
||||
return data.rows;
|
||||
} catch (error) {
|
||||
console.error('Database Error:', error);
|
||||
throw new Error('Failed to fetch revenue data.');
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchLatestInvoices() {
|
||||
try {
|
||||
const data = await sql<LatestInvoiceRaw>`
|
||||
SELECT invoices.amount, customers.name, customers.image_url, customers.email, invoices.id
|
||||
FROM invoices
|
||||
JOIN customers ON invoices.customer_id = customers.id
|
||||
ORDER BY invoices.date DESC
|
||||
LIMIT 5`;
|
||||
|
||||
const latestInvoices = data.rows.map((invoice) => ({
|
||||
...invoice,
|
||||
amount: formatCurrency(invoice.amount),
|
||||
}));
|
||||
return latestInvoices;
|
||||
} catch (error) {
|
||||
console.error('Database Error:', error);
|
||||
throw new Error('Failed to fetch the latest invoices.');
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchCardData() {
|
||||
try {
|
||||
// You can probably combine these into a single SQL query
|
||||
// However, we are intentionally splitting them to demonstrate
|
||||
// how to initialize multiple queries in parallel with JS.
|
||||
const invoiceCountPromise = sql`SELECT COUNT(*) FROM invoices`;
|
||||
const customerCountPromise = sql`SELECT COUNT(*) FROM customers`;
|
||||
const invoiceStatusPromise = sql`SELECT
|
||||
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS "paid",
|
||||
SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) AS "pending"
|
||||
FROM invoices`;
|
||||
|
||||
const data = await Promise.all([
|
||||
invoiceCountPromise,
|
||||
customerCountPromise,
|
||||
invoiceStatusPromise,
|
||||
]);
|
||||
|
||||
const numberOfInvoices = Number(data[0].rows[0].count ?? '0');
|
||||
const numberOfCustomers = Number(data[1].rows[0].count ?? '0');
|
||||
const totalPaidInvoices = formatCurrency(data[2].rows[0].paid ?? '0');
|
||||
const totalPendingInvoices = formatCurrency(data[2].rows[0].pending ?? '0');
|
||||
|
||||
return {
|
||||
numberOfCustomers,
|
||||
numberOfInvoices,
|
||||
totalPaidInvoices,
|
||||
totalPendingInvoices,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Database Error:', error);
|
||||
throw new Error('Failed to fetch card data.');
|
||||
}
|
||||
}
|
||||
|
||||
const ITEMS_PER_PAGE = 6;
|
||||
export async function fetchFilteredInvoices(
|
||||
query: string,
|
||||
currentPage: number,
|
||||
) {
|
||||
const offset = (currentPage - 1) * ITEMS_PER_PAGE;
|
||||
|
||||
try {
|
||||
const invoices = await sql<InvoicesTable>`
|
||||
SELECT
|
||||
invoices.id,
|
||||
invoices.amount,
|
||||
invoices.date,
|
||||
invoices.status,
|
||||
customers.name,
|
||||
customers.email,
|
||||
customers.image_url
|
||||
FROM invoices
|
||||
JOIN customers ON invoices.customer_id = customers.id
|
||||
WHERE
|
||||
customers.name ILIKE ${`%${query}%`} OR
|
||||
customers.email ILIKE ${`%${query}%`} OR
|
||||
invoices.amount::text ILIKE ${`%${query}%`} OR
|
||||
invoices.date::text ILIKE ${`%${query}%`} OR
|
||||
invoices.status ILIKE ${`%${query}%`}
|
||||
ORDER BY invoices.date DESC
|
||||
LIMIT ${ITEMS_PER_PAGE} OFFSET ${offset}
|
||||
`;
|
||||
|
||||
return invoices.rows;
|
||||
} catch (error) {
|
||||
console.error('Database Error:', error);
|
||||
throw new Error('Failed to fetch invoices.');
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchInvoicesPages(query: string) {
|
||||
try {
|
||||
const count = await sql`SELECT COUNT(*)
|
||||
FROM invoices
|
||||
JOIN customers ON invoices.customer_id = customers.id
|
||||
WHERE
|
||||
customers.name ILIKE ${`%${query}%`} OR
|
||||
customers.email ILIKE ${`%${query}%`} OR
|
||||
invoices.amount::text ILIKE ${`%${query}%`} OR
|
||||
invoices.date::text ILIKE ${`%${query}%`} OR
|
||||
invoices.status ILIKE ${`%${query}%`}
|
||||
`;
|
||||
|
||||
const totalPages = Math.ceil(Number(count.rows[0].count) / ITEMS_PER_PAGE);
|
||||
return totalPages;
|
||||
} catch (error) {
|
||||
console.error('Database Error:', error);
|
||||
throw new Error('Failed to fetch total number of invoices.');
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchInvoiceById(id: string) {
|
||||
try {
|
||||
const data = await sql<InvoiceForm>`
|
||||
SELECT
|
||||
invoices.id,
|
||||
invoices.customer_id,
|
||||
invoices.amount,
|
||||
invoices.status
|
||||
FROM invoices
|
||||
WHERE invoices.id = ${id};
|
||||
`;
|
||||
|
||||
const invoice = data.rows.map((invoice) => ({
|
||||
...invoice,
|
||||
// Convert amount from cents to dollars
|
||||
amount: invoice.amount / 100,
|
||||
}));
|
||||
|
||||
return invoice[0];
|
||||
} catch (error) {
|
||||
console.error('Database Error:', error);
|
||||
throw new Error('Failed to fetch invoice.');
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchCustomers() {
|
||||
try {
|
||||
const data = await sql<CustomerField>`
|
||||
SELECT
|
||||
id,
|
||||
name
|
||||
FROM customers
|
||||
ORDER BY name ASC
|
||||
`;
|
||||
|
||||
const customers = data.rows;
|
||||
return customers;
|
||||
} catch (err) {
|
||||
console.error('Database Error:', err);
|
||||
throw new Error('Failed to fetch all customers.');
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchFilteredCustomers(query: string) {
|
||||
try {
|
||||
const data = await sql<CustomersTableType>`
|
||||
SELECT
|
||||
customers.id,
|
||||
customers.name,
|
||||
customers.email,
|
||||
customers.image_url,
|
||||
COUNT(invoices.id) AS total_invoices,
|
||||
SUM(CASE WHEN invoices.status = 'pending' THEN invoices.amount ELSE 0 END) AS total_pending,
|
||||
SUM(CASE WHEN invoices.status = 'paid' THEN invoices.amount ELSE 0 END) AS total_paid
|
||||
FROM customers
|
||||
LEFT JOIN invoices ON customers.id = invoices.customer_id
|
||||
WHERE
|
||||
customers.name ILIKE ${`%${query}%`} OR
|
||||
customers.email ILIKE ${`%${query}%`}
|
||||
GROUP BY customers.id, customers.name, customers.email, customers.image_url
|
||||
ORDER BY customers.name ASC
|
||||
`;
|
||||
|
||||
const customers = data.rows.map((customer) => ({
|
||||
...customer,
|
||||
total_pending: formatCurrency(customer.total_pending),
|
||||
total_paid: formatCurrency(customer.total_paid),
|
||||
}));
|
||||
|
||||
return customers;
|
||||
} catch (err) {
|
||||
console.error('Database Error:', err);
|
||||
throw new Error('Failed to fetch customers table.');
|
||||
}
|
||||
}
|
||||
88
app/lib/definitions.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
// This file contains type definitions for your data.
|
||||
// It describes the shape of the data, and what data type each property should accept.
|
||||
// For simplicity of teaching, we're manually defining these types.
|
||||
// However, these types are generated automatically if you're using an ORM such as Prisma.
|
||||
export type User = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
export type Customer = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
image_url: string;
|
||||
};
|
||||
|
||||
export type Invoice = {
|
||||
id: string;
|
||||
customer_id: string;
|
||||
amount: number;
|
||||
date: string;
|
||||
// In TypeScript, this is called a string union type.
|
||||
// It means that the "status" property can only be one of the two strings: 'pending' or 'paid'.
|
||||
status: 'pending' | 'paid';
|
||||
};
|
||||
|
||||
export type Revenue = {
|
||||
month: string;
|
||||
revenue: number;
|
||||
};
|
||||
|
||||
export type LatestInvoice = {
|
||||
id: string;
|
||||
name: string;
|
||||
image_url: string;
|
||||
email: string;
|
||||
amount: string;
|
||||
};
|
||||
|
||||
// The database returns a number for amount, but we later format it to a string with the formatCurrency function
|
||||
export type LatestInvoiceRaw = Omit<LatestInvoice, 'amount'> & {
|
||||
amount: number;
|
||||
};
|
||||
|
||||
export type InvoicesTable = {
|
||||
id: string;
|
||||
customer_id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
image_url: string;
|
||||
date: string;
|
||||
amount: number;
|
||||
status: 'pending' | 'paid';
|
||||
};
|
||||
|
||||
export type CustomersTableType = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
image_url: string;
|
||||
total_invoices: number;
|
||||
total_pending: number;
|
||||
total_paid: number;
|
||||
};
|
||||
|
||||
export type FormattedCustomersTable = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
image_url: string;
|
||||
total_invoices: number;
|
||||
total_pending: string;
|
||||
total_paid: string;
|
||||
};
|
||||
|
||||
export type CustomerField = {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type InvoiceForm = {
|
||||
id: string;
|
||||
customer_id: string;
|
||||
amount: number;
|
||||
status: 'pending' | 'paid';
|
||||
};
|
||||
147
app/lib/placeholder-data.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
// This file contains placeholder data that you'll be replacing with real data in the Data Fetching chapter:
|
||||
// https://nextjs.org/learn/dashboard-app/fetching-data
|
||||
const users = [
|
||||
{
|
||||
id: '410544b2-4001-4271-9855-fec4b6a6442a',
|
||||
name: 'User',
|
||||
email: 'user@nextmail.com',
|
||||
password: '123456',
|
||||
},
|
||||
];
|
||||
|
||||
const customers = [
|
||||
{
|
||||
id: 'd6e15727-9fe1-4961-8c5b-ea44a9bd81aa',
|
||||
name: 'Evil Rabbit',
|
||||
email: 'evil@rabbit.com',
|
||||
image_url: '/customers/evil-rabbit.png',
|
||||
},
|
||||
{
|
||||
id: '3958dc9e-712f-4377-85e9-fec4b6a6442a',
|
||||
name: 'Delba de Oliveira',
|
||||
email: 'delba@oliveira.com',
|
||||
image_url: '/customers/delba-de-oliveira.png',
|
||||
},
|
||||
{
|
||||
id: '3958dc9e-742f-4377-85e9-fec4b6a6442a',
|
||||
name: 'Lee Robinson',
|
||||
email: 'lee@robinson.com',
|
||||
image_url: '/customers/lee-robinson.png',
|
||||
},
|
||||
{
|
||||
id: '76d65c26-f784-44a2-ac19-586678f7c2f2',
|
||||
name: 'Michael Novotny',
|
||||
email: 'michael@novotny.com',
|
||||
image_url: '/customers/michael-novotny.png',
|
||||
},
|
||||
{
|
||||
id: 'CC27C14A-0ACF-4F4A-A6C9-D45682C144B9',
|
||||
name: 'Amy Burns',
|
||||
email: 'amy@burns.com',
|
||||
image_url: '/customers/amy-burns.png',
|
||||
},
|
||||
{
|
||||
id: '13D07535-C59E-4157-A011-F8D2EF4E0CBB',
|
||||
name: 'Balazs Orban',
|
||||
email: 'balazs@orban.com',
|
||||
image_url: '/customers/balazs-orban.png',
|
||||
},
|
||||
];
|
||||
|
||||
const invoices = [
|
||||
{
|
||||
customer_id: customers[0].id,
|
||||
amount: 15795,
|
||||
status: 'pending',
|
||||
date: '2022-12-06',
|
||||
},
|
||||
{
|
||||
customer_id: customers[1].id,
|
||||
amount: 20348,
|
||||
status: 'pending',
|
||||
date: '2022-11-14',
|
||||
},
|
||||
{
|
||||
customer_id: customers[4].id,
|
||||
amount: 3040,
|
||||
status: 'paid',
|
||||
date: '2022-10-29',
|
||||
},
|
||||
{
|
||||
customer_id: customers[3].id,
|
||||
amount: 44800,
|
||||
status: 'paid',
|
||||
date: '2023-09-10',
|
||||
},
|
||||
{
|
||||
customer_id: customers[5].id,
|
||||
amount: 34577,
|
||||
status: 'pending',
|
||||
date: '2023-08-05',
|
||||
},
|
||||
{
|
||||
customer_id: customers[2].id,
|
||||
amount: 54246,
|
||||
status: 'pending',
|
||||
date: '2023-07-16',
|
||||
},
|
||||
{
|
||||
customer_id: customers[0].id,
|
||||
amount: 666,
|
||||
status: 'pending',
|
||||
date: '2023-06-27',
|
||||
},
|
||||
{
|
||||
customer_id: customers[3].id,
|
||||
amount: 32545,
|
||||
status: 'paid',
|
||||
date: '2023-06-09',
|
||||
},
|
||||
{
|
||||
customer_id: customers[4].id,
|
||||
amount: 1250,
|
||||
status: 'paid',
|
||||
date: '2023-06-17',
|
||||
},
|
||||
{
|
||||
customer_id: customers[5].id,
|
||||
amount: 8546,
|
||||
status: 'paid',
|
||||
date: '2023-06-07',
|
||||
},
|
||||
{
|
||||
customer_id: customers[1].id,
|
||||
amount: 500,
|
||||
status: 'paid',
|
||||
date: '2023-08-19',
|
||||
},
|
||||
{
|
||||
customer_id: customers[5].id,
|
||||
amount: 8945,
|
||||
status: 'paid',
|
||||
date: '2023-06-03',
|
||||
},
|
||||
{
|
||||
customer_id: customers[2].id,
|
||||
amount: 1000,
|
||||
status: 'paid',
|
||||
date: '2022-06-05',
|
||||
},
|
||||
];
|
||||
|
||||
const revenue = [
|
||||
{ month: 'Jan', revenue: 2000 },
|
||||
{ month: 'Feb', revenue: 1800 },
|
||||
{ month: 'Mar', revenue: 2200 },
|
||||
{ month: 'Apr', revenue: 2500 },
|
||||
{ month: 'May', revenue: 2300 },
|
||||
{ month: 'Jun', revenue: 3200 },
|
||||
{ month: 'Jul', revenue: 3500 },
|
||||
{ month: 'Aug', revenue: 3700 },
|
||||
{ month: 'Sep', revenue: 2500 },
|
||||
{ month: 'Oct', revenue: 2800 },
|
||||
{ month: 'Nov', revenue: 3000 },
|
||||
{ month: 'Dec', revenue: 4800 },
|
||||
];
|
||||
|
||||
export { users, customers, invoices, revenue };
|
||||
69
app/lib/utils.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { Revenue } from './definitions';
|
||||
|
||||
export const formatCurrency = (amount: number) => {
|
||||
return (amount / 100).toLocaleString('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
});
|
||||
};
|
||||
|
||||
export const formatDateToLocal = (
|
||||
dateStr: string,
|
||||
locale: string = 'en-US',
|
||||
) => {
|
||||
const date = new Date(dateStr);
|
||||
const options: Intl.DateTimeFormatOptions = {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
};
|
||||
const formatter = new Intl.DateTimeFormat(locale, options);
|
||||
return formatter.format(date);
|
||||
};
|
||||
|
||||
export const generateYAxis = (revenue: Revenue[]) => {
|
||||
// Calculate what labels we need to display on the y-axis
|
||||
// based on highest record and in 1000s
|
||||
const yAxisLabels = [];
|
||||
const highestRecord = Math.max(...revenue.map((month) => month.revenue));
|
||||
const topLabel = Math.ceil(highestRecord / 1000) * 1000;
|
||||
|
||||
for (let i = topLabel; i >= 0; i -= 1000) {
|
||||
yAxisLabels.push(`$${i / 1000}K`);
|
||||
}
|
||||
|
||||
return { yAxisLabels, topLabel };
|
||||
};
|
||||
|
||||
export const generatePagination = (currentPage: number, totalPages: number) => {
|
||||
// If the total number of pages is 7 or less,
|
||||
// display all pages without any ellipsis.
|
||||
if (totalPages <= 7) {
|
||||
return Array.from({ length: totalPages }, (_, i) => i + 1);
|
||||
}
|
||||
|
||||
// If the current page is among the first 3 pages,
|
||||
// show the first 3, an ellipsis, and the last 2 pages.
|
||||
if (currentPage <= 3) {
|
||||
return [1, 2, 3, '...', totalPages - 1, totalPages];
|
||||
}
|
||||
|
||||
// If the current page is among the last 3 pages,
|
||||
// show the first 2, an ellipsis, and the last 3 pages.
|
||||
if (currentPage >= totalPages - 2) {
|
||||
return [1, 2, '...', totalPages - 2, totalPages - 1, totalPages];
|
||||
}
|
||||
|
||||
// If the current page is somewhere in the middle,
|
||||
// show the first page, an ellipsis, the current page and its neighbors,
|
||||
// another ellipsis, and the last page.
|
||||
return [
|
||||
1,
|
||||
'...',
|
||||
currentPage - 1,
|
||||
currentPage,
|
||||
currentPage + 1,
|
||||
'...',
|
||||
totalPages,
|
||||
];
|
||||
};
|
||||
23
app/login/page.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import AcmeLogo from '@/app/ui/acme-logo';
|
||||
import LoginForm from '@/app/ui/login-form';
|
||||
|
||||
import { Metadata } from 'next';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Login',
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
BIN
app/opengraph-image.png
Normal file
|
After Width: | Height: | Size: 238 KiB |
53
app/page.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import AcmeLogo from '@/app/ui/acme-logo';
|
||||
import { ArrowRightIcon } from '@heroicons/react/24/outline';
|
||||
import Link from 'next/link';
|
||||
import styles from './ui/home.module.css';
|
||||
import Image from 'next/image';
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col p-6">
|
||||
<div className={styles.shape}>
|
||||
<AcmeLogo />
|
||||
</div>
|
||||
<div className="mt-4 flex grow flex-col gap-4 md:flex-row">
|
||||
<div className="flex flex-col justify-center gap-6 rounded-lg bg-gray-50 px-6 py-10 md:w-2/5 md:px-20">
|
||||
|
||||
<div
|
||||
className="relative w-0 h-0 border-l-[15px] border-r-[15px] border-b-[26px] border-l-transparent border-r-transparent border-b-black"
|
||||
/>
|
||||
<p className={`text-xl text-gray-800 md:text-3xl md:leading-normal`}>
|
||||
<strong>Welcome to Acme.</strong> This is the example for the{' '}
|
||||
<a href="https://nextjs.org/learn/" className="text-blue-500">
|
||||
Next.js Learn Course
|
||||
</a>
|
||||
, brought to you by Vercel.
|
||||
</p>
|
||||
<Link
|
||||
href="/login"
|
||||
className="flex items-center gap-5 self-start rounded-lg bg-blue-500 px-6 py-3 text-sm font-medium text-white transition-colors hover:bg-blue-400 md:text-base"
|
||||
>
|
||||
<span>Log in</span> <ArrowRightIcon className="w-5 md:w-6"/>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="flex items-center justify-center p-6 md:w-3/5 md:px-28 md:py-12">
|
||||
{/* Add Hero Images Here */}
|
||||
<Image
|
||||
src="/hero-desktop.png"
|
||||
width={1000}
|
||||
height={760}
|
||||
className="hidden md:block"
|
||||
alt="Screenshots of the dashboard project showing desktop version"
|
||||
/>
|
||||
<Image
|
||||
src="/hero-mobile.png"
|
||||
width={560}
|
||||
height={620}
|
||||
className="block md:hidden"
|
||||
alt="Screenshots of the dashboard project showing desktop version"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
22
app/query/route.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { db } from "@vercel/postgres";
|
||||
|
||||
const client = await db.connect();
|
||||
|
||||
async function listInvoices() {
|
||||
const data = await client.sql`
|
||||
SELECT invoices.amount, customers.name
|
||||
FROM invoices
|
||||
JOIN customers ON invoices.customer_id = customers.id
|
||||
WHERE invoices.amount = 666;
|
||||
`;
|
||||
|
||||
return data.rows;
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
return Response.json(await listInvoices());
|
||||
} catch (error) {
|
||||
return Response.json({ error }, { status: 500 });
|
||||
}
|
||||
}
|
||||
120
app/seed/route.ts
Normal file
@@ -0,0 +1,120 @@
|
||||
// 주의사항: vercel/postgres 생성제한 -> neon을 통해 postgresql 생성 필요.
|
||||
import bcrypt from 'bcrypt';
|
||||
import { db } from '@vercel/postgres';
|
||||
import { invoices, customers, revenue, users } from '../lib/placeholder-data';
|
||||
|
||||
const client = await db.connect();
|
||||
|
||||
async function seedUsers() {
|
||||
await client.sql`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`;
|
||||
await client.sql`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
password TEXT NOT NULL
|
||||
);
|
||||
`;
|
||||
|
||||
const insertedUsers = await Promise.all(
|
||||
users.map(async (user) => {
|
||||
const hashedPassword = await bcrypt.hash(user.password, 10);
|
||||
return client.sql`
|
||||
INSERT INTO users (id, name, email, password)
|
||||
VALUES (${user.id}, ${user.name}, ${user.email}, ${hashedPassword})
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
`;
|
||||
}),
|
||||
);
|
||||
|
||||
return insertedUsers;
|
||||
}
|
||||
|
||||
async function seedInvoices() {
|
||||
await client.sql`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`;
|
||||
|
||||
await client.sql`
|
||||
CREATE TABLE IF NOT EXISTS invoices (
|
||||
id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
|
||||
customer_id UUID NOT NULL,
|
||||
amount INT NOT NULL,
|
||||
status VARCHAR(255) NOT NULL,
|
||||
date DATE NOT NULL
|
||||
);
|
||||
`;
|
||||
|
||||
const insertedInvoices = await Promise.all(
|
||||
invoices.map(
|
||||
(invoice) => client.sql`
|
||||
INSERT INTO invoices (customer_id, amount, status, date)
|
||||
VALUES (${invoice.customer_id}, ${invoice.amount}, ${invoice.status}, ${invoice.date})
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
`,
|
||||
),
|
||||
);
|
||||
|
||||
return insertedInvoices;
|
||||
}
|
||||
|
||||
async function seedCustomers() {
|
||||
await client.sql`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`;
|
||||
|
||||
await client.sql`
|
||||
CREATE TABLE IF NOT EXISTS customers (
|
||||
id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255) NOT NULL,
|
||||
image_url VARCHAR(255) NOT NULL
|
||||
);
|
||||
`;
|
||||
|
||||
const insertedCustomers = await Promise.all(
|
||||
customers.map(
|
||||
(customers) => client.sql`
|
||||
INSERT INTO customers (id, name, email, image_url)
|
||||
VALUES (${customers.id}, ${customers.name}, ${customers.email}, ${customers.image_url})
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
`,
|
||||
),
|
||||
);
|
||||
|
||||
return insertedCustomers;
|
||||
}
|
||||
|
||||
async function seedRevenue() {
|
||||
await client.sql`
|
||||
CREATE TABLE IF NOT EXISTS revenue (
|
||||
month VARCHAR(4) NOT NULL UNIQUE,
|
||||
revenue INT NOT NULL
|
||||
);
|
||||
`;
|
||||
|
||||
const insertedRevenue = await Promise.all(
|
||||
revenue.map(
|
||||
(rev) => client.sql`
|
||||
INSERT INTO revenue (month, revenue)
|
||||
VALUES (${rev.month}, ${rev.revenue})
|
||||
ON CONFLICT (month) DO NOTHING;
|
||||
`,
|
||||
),
|
||||
);
|
||||
|
||||
return insertedRevenue;
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
await client.sql`BEGIN`;
|
||||
await seedUsers();
|
||||
await seedCustomers();
|
||||
await seedInvoices();
|
||||
await seedRevenue();
|
||||
await client.sql`COMMIT`;
|
||||
|
||||
return Response.json({ message: 'Database seeded successfully' });
|
||||
} catch (error) {
|
||||
console.error('error', error);
|
||||
await client.sql`ROLLBACK`;
|
||||
return Response.json({ error }, { status: 500 });
|
||||
}
|
||||
}
|
||||
13
app/ui/acme-logo.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { GlobeAltIcon } from '@heroicons/react/24/outline';
|
||||
import {lusitana} from "@/app/ui/fonts";
|
||||
|
||||
export default function AcmeLogo() {
|
||||
return (
|
||||
<div
|
||||
className={`${lusitana.className} flex flex-row items-center leading-none text-white`}
|
||||
>
|
||||
<GlobeAltIcon className="h-12 w-12 rotate-[15deg]" />
|
||||
<p className="text-[44px]">Acme</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
19
app/ui/button.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import clsx from 'clsx';
|
||||
|
||||
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function Button({ children, className, ...rest }: ButtonProps) {
|
||||
return (
|
||||
<button
|
||||
{...rest}
|
||||
className={clsx(
|
||||
'flex h-10 items-center rounded-lg bg-blue-500 px-4 text-sm font-medium text-white transition-colors hover:bg-blue-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-500 active:bg-blue-600 aria-disabled:cursor-not-allowed aria-disabled:opacity-50',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
122
app/ui/customers/table.tsx
Normal file
@@ -0,0 +1,122 @@
|
||||
import Image from 'next/image';
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
import Search from '@/app/ui/search';
|
||||
import {
|
||||
FormattedCustomersTable,
|
||||
} from '@/app/lib/definitions';
|
||||
|
||||
export default async function CustomersTable({
|
||||
customers,
|
||||
}: {
|
||||
customers: FormattedCustomersTable[];
|
||||
}) {
|
||||
return (
|
||||
<div className="w-full">
|
||||
<h1 className={`${lusitana.className} mb-8 text-xl md:text-2xl`}>
|
||||
Customers
|
||||
</h1>
|
||||
<Search placeholder="Search customers..." />
|
||||
<div className="mt-6 flow-root">
|
||||
<div className="overflow-x-auto">
|
||||
<div className="inline-block min-w-full align-middle">
|
||||
<div className="overflow-hidden rounded-md bg-gray-50 p-2 md:pt-0">
|
||||
<div className="md:hidden">
|
||||
{customers?.map((customer) => (
|
||||
<div
|
||||
key={customer.id}
|
||||
className="mb-2 w-full rounded-md bg-white p-4"
|
||||
>
|
||||
<div className="flex items-center justify-between border-b pb-4">
|
||||
<div>
|
||||
<div className="mb-2 flex items-center">
|
||||
<div className="flex items-center gap-3">
|
||||
<Image
|
||||
src={customer.image_url}
|
||||
className="rounded-full"
|
||||
alt={`${customer.name}'s profile picture`}
|
||||
width={28}
|
||||
height={28}
|
||||
/>
|
||||
<p>{customer.name}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-gray-500">
|
||||
{customer.email}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full items-center justify-between border-b py-5">
|
||||
<div className="flex w-1/2 flex-col">
|
||||
<p className="text-xs">Pending</p>
|
||||
<p className="font-medium">{customer.total_pending}</p>
|
||||
</div>
|
||||
<div className="flex w-1/2 flex-col">
|
||||
<p className="text-xs">Paid</p>
|
||||
<p className="font-medium">{customer.total_paid}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="pt-4 text-sm">
|
||||
<p>{customer.total_invoices} invoices</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<table className="hidden min-w-full rounded-md text-gray-900 md:table">
|
||||
<thead className="rounded-md bg-gray-50 text-left text-sm font-normal">
|
||||
<tr>
|
||||
<th scope="col" className="px-4 py-5 font-medium sm:pl-6">
|
||||
Name
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-5 font-medium">
|
||||
Email
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-5 font-medium">
|
||||
Total Invoices
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-5 font-medium">
|
||||
Total Pending
|
||||
</th>
|
||||
<th scope="col" className="px-4 py-5 font-medium">
|
||||
Total Paid
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody className="divide-y divide-gray-200 text-gray-900">
|
||||
{customers.map((customer) => (
|
||||
<tr key={customer.id} className="group">
|
||||
<td className="whitespace-nowrap bg-white py-5 pl-4 pr-3 text-sm text-black group-first-of-type:rounded-md group-last-of-type:rounded-md sm:pl-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<Image
|
||||
src={customer.image_url}
|
||||
className="rounded-full"
|
||||
alt={`${customer.name}'s profile picture`}
|
||||
width={28}
|
||||
height={28}
|
||||
/>
|
||||
<p>{customer.name}</p>
|
||||
</div>
|
||||
</td>
|
||||
<td className="whitespace-nowrap bg-white px-4 py-5 text-sm">
|
||||
{customer.email}
|
||||
</td>
|
||||
<td className="whitespace-nowrap bg-white px-4 py-5 text-sm">
|
||||
{customer.total_invoices}
|
||||
</td>
|
||||
<td className="whitespace-nowrap bg-white px-4 py-5 text-sm">
|
||||
{customer.total_pending}
|
||||
</td>
|
||||
<td className="whitespace-nowrap bg-white px-4 py-5 text-sm group-first-of-type:rounded-md group-last-of-type:rounded-md">
|
||||
{customer.total_paid}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
66
app/ui/dashboard/cards.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
import {
|
||||
BanknotesIcon,
|
||||
ClockIcon,
|
||||
UserGroupIcon,
|
||||
InboxIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
import { fetchCardData } from "@/app/lib/data";
|
||||
|
||||
const iconMap = {
|
||||
collected: BanknotesIcon,
|
||||
customers: UserGroupIcon,
|
||||
pending: ClockIcon,
|
||||
invoices: InboxIcon,
|
||||
};
|
||||
|
||||
export default async function CardWrapper() {
|
||||
const {
|
||||
numberOfInvoices,
|
||||
numberOfCustomers,
|
||||
totalPaidInvoices,
|
||||
totalPendingInvoices,
|
||||
} = await fetchCardData();
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* NOTE: Uncomment this code in Chapter 9 */}
|
||||
|
||||
<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"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function Card({
|
||||
title,
|
||||
value,
|
||||
type,
|
||||
}: {
|
||||
title: string;
|
||||
value: number | string;
|
||||
type: 'invoices' | 'customers' | 'pending' | 'collected';
|
||||
}) {
|
||||
const Icon = iconMap[type];
|
||||
|
||||
return (
|
||||
<div className="rounded-xl bg-gray-50 p-2 shadow-sm">
|
||||
<div className="flex p-4">
|
||||
{Icon ? <Icon className="h-5 w-5 text-gray-700" /> : null}
|
||||
<h3 className="ml-2 text-sm font-medium">{title}</h3>
|
||||
</div>
|
||||
<p
|
||||
className={`${lusitana.className}
|
||||
truncate rounded-xl bg-white px-4 py-8 text-center text-2xl`}
|
||||
>
|
||||
{value}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
63
app/ui/dashboard/latest-invoices.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import { ArrowPathIcon } from '@heroicons/react/24/outline';
|
||||
import clsx from 'clsx';
|
||||
import Image from 'next/image';
|
||||
|
||||
import {lusitana} from "@/app/ui/fonts";
|
||||
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`}>최근 송장</h2>
|
||||
<div className="flex grow flex-col justify-between rounded-xl bg-gray-50 p-4">
|
||||
{/* NOTE: Uncomment this code in Chapter 7 */}
|
||||
|
||||
<div className="bg-white px-6">
|
||||
{latestInvoices.map((invoice, i) => {
|
||||
return (
|
||||
<div
|
||||
key={invoice.id}
|
||||
className={clsx(
|
||||
'flex flex-row items-center justify-between py-4',
|
||||
{
|
||||
'border-t': i !== 0,
|
||||
},
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center">
|
||||
<Image
|
||||
src={invoice.image_url}
|
||||
className="mr-4 rounded-full"
|
||||
width={32}
|
||||
height={32}
|
||||
alt="invoices"
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-semibold md:text-base">
|
||||
{invoice.name}
|
||||
</p>
|
||||
<p className="hidden text-sm text-gray-500 sm:block">
|
||||
{invoice.email}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<p
|
||||
className={`${lusitana.className} truncate text-sm font-medium md:text-base`}
|
||||
>
|
||||
{invoice.amount}
|
||||
</p>
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
48
app/ui/dashboard/nav-links.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
UserGroupIcon,
|
||||
HomeIcon,
|
||||
DocumentDuplicateIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import Link from "next/link";
|
||||
import {usePathname} from 'next/navigation';
|
||||
import clsx from "clsx";
|
||||
|
||||
// Map of links to display in the side navigation.
|
||||
// Depending on the size of the application, this would be stored in a database.
|
||||
const links = [
|
||||
{ name: 'Home', href: '/dashboard', icon: HomeIcon },
|
||||
{
|
||||
name: 'Invoices',
|
||||
href: '/dashboard/invoices',
|
||||
icon: DocumentDuplicateIcon,
|
||||
},
|
||||
{ name: 'Customers', href: '/dashboard/customers', icon: UserGroupIcon },
|
||||
];
|
||||
|
||||
export default function NavLinks() {
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<>
|
||||
{links.map((link) => {
|
||||
const LinkIcon = link.icon;
|
||||
return (
|
||||
<Link
|
||||
key={link.name}
|
||||
href={link.href}
|
||||
className={clsx(
|
||||
'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',
|
||||
{
|
||||
'bg-sky-100 text-blue-600': pathname === link.href,
|
||||
},
|
||||
)} >
|
||||
<LinkIcon className="w-6" />
|
||||
<p className="hidden md:block">{link.name}</p>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
61
app/ui/dashboard/revenue-chart.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import { generateYAxis } from '@/app/lib/utils';
|
||||
import { CalendarIcon } from '@heroicons/react/24/outline';
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
import {fetchRevenue} from "@/app/lib/data";
|
||||
|
||||
// This component is representational only.
|
||||
// For data visualization UI, check out:
|
||||
// https://www.tremor.so/
|
||||
// https://www.chartjs.org/
|
||||
// https://airbnb.io/visx/
|
||||
|
||||
export default async function RevenueChart() {
|
||||
const revenue = await fetchRevenue();
|
||||
|
||||
const chartHeight = 350;
|
||||
const { yAxisLabels, topLabel } = generateYAxis(revenue);
|
||||
|
||||
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">
|
||||
<h2 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}>
|
||||
최근 매출액
|
||||
</h2>
|
||||
{/* NOTE: Uncomment this code in Chapter 7 */}
|
||||
|
||||
<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"
|
||||
style={{ height: `${chartHeight}px` }}
|
||||
>
|
||||
{yAxisLabels.map((label) => (
|
||||
<p key={label}>{label}</p>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{revenue.map((month) => (
|
||||
<div key={month.month} className="flex flex-col items-center gap-2">
|
||||
<div
|
||||
className="w-full rounded-md bg-blue-300"
|
||||
style={{
|
||||
height: `${(chartHeight / topLabel) * month.revenue}px`,
|
||||
}}
|
||||
></div>
|
||||
<p className="-rotate-90 text-sm text-gray-400 sm:rotate-0">
|
||||
{month.month}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center pb-2 pt-6">
|
||||
<CalendarIcon className="h-5 w-5 text-gray-500" />
|
||||
<h3 className="ml-2 text-sm text-gray-500 ">최근 12개월 동향</h3>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
36
app/ui/dashboard/sidenav.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import Link from 'next/link';
|
||||
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";
|
||||
|
||||
export default function SideNav() {
|
||||
return (
|
||||
<div className="flex h-full flex-col px-3 py-4 md:px-2">
|
||||
<Link
|
||||
className="mb-2 flex h-20 items-end justify-start rounded-md bg-blue-600 p-4 md:h-40"
|
||||
href="/"
|
||||
>
|
||||
<div className="w-32 text-white md:w-40">
|
||||
<AcmeLogo/>
|
||||
</div>
|
||||
</Link>
|
||||
<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();
|
||||
}}
|
||||
>
|
||||
<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">접속해제</div>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
10
app/ui/fonts.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import {Inter, Lusitana} from 'next/font/google';
|
||||
|
||||
export const inter = Inter({
|
||||
subsets: ['latin'],
|
||||
});
|
||||
|
||||
export const lusitana = Lusitana({
|
||||
weight: ['400', '700'],
|
||||
subsets: ['latin'],
|
||||
});
|
||||
18
app/ui/global.css
Normal file
@@ -0,0 +1,18 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
input[type='number'] {
|
||||
-moz-appearance: textfield;
|
||||
appearance: textfield;
|
||||
}
|
||||
|
||||
input[type='number']::-webkit-inner-spin-button {
|
||||
-webkit-appearance: none;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
input[type='number']::-webkit-outer-spin-button {
|
||||
-webkit-appearance: none;
|
||||
margin: 0;
|
||||
}
|
||||
7
app/ui/home.module.css
Normal file
@@ -0,0 +1,7 @@
|
||||
.shape {
|
||||
height: 0;
|
||||
width: 0;
|
||||
border-bottom: 30px solid black;
|
||||
border-left: 20px solid transparent;
|
||||
border-right: 20px solid transparent;
|
||||
}
|
||||
36
app/ui/invoices/breadcrumbs.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import { clsx } from 'clsx';
|
||||
import Link from 'next/link';
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
|
||||
interface Breadcrumb {
|
||||
label: string;
|
||||
href: string;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
export default function Breadcrumbs({
|
||||
breadcrumbs,
|
||||
}: {
|
||||
breadcrumbs: Breadcrumb[];
|
||||
}) {
|
||||
return (
|
||||
<nav aria-label="Breadcrumb" className="mb-6 block">
|
||||
<ol className={clsx(lusitana.className, 'flex text-xl md:text-2xl')}>
|
||||
{breadcrumbs.map((breadcrumb, index) => (
|
||||
<li
|
||||
key={breadcrumb.href}
|
||||
aria-current={breadcrumb.active}
|
||||
className={clsx(
|
||||
breadcrumb.active ? 'text-gray-900' : 'text-gray-500',
|
||||
)}
|
||||
>
|
||||
<Link href={breadcrumb.href}>{breadcrumb.label}</Link>
|
||||
{index < breadcrumbs.length - 1 ? (
|
||||
<span className="mx-3 inline-block">/</span>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
47
app/ui/invoices/buttons.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
'use client';
|
||||
|
||||
import { PencilIcon, PlusIcon, TrashIcon } from '@heroicons/react/24/outline';
|
||||
import Link from 'next/link';
|
||||
import {deleteInvoice} from "@/app/lib/actions";
|
||||
import {useActionState} from "react";
|
||||
|
||||
export function CreateInvoice() {
|
||||
return (
|
||||
<Link
|
||||
href="/dashboard/invoices/create"
|
||||
className="flex h-10 items-center rounded-lg bg-blue-600 px-4 text-sm font-medium text-white transition-colors hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600"
|
||||
>
|
||||
<span className="hidden md:block">Create Invoice</span>{' '}
|
||||
<PlusIcon className="h-5 md:ml-4" />
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
export function UpdateInvoice({ id }: { id: string }) {
|
||||
return (
|
||||
<Link
|
||||
href={`/dashboard/invoices/${id}/edit`}
|
||||
className="rounded-md border p-2 hover:bg-gray-100"
|
||||
>
|
||||
<PencilIcon className="w-5" />
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
export function DeleteInvoice({ id }: { id: string }) {
|
||||
const deleteInvoiceWithId = deleteInvoice.bind(null, id);
|
||||
const [state, formAction] = useActionState(deleteInvoiceWithId, null);
|
||||
console.log(state);
|
||||
|
||||
return (
|
||||
<form action={formAction}>
|
||||
<button
|
||||
type="submit"
|
||||
className="rounded-md border p-2 hover:bg-gray-100"
|
||||
>
|
||||
<span className="sr-only">삭제</span>
|
||||
<TrashIcon className="w-5"/>
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
149
app/ui/invoices/create-form.tsx
Normal file
@@ -0,0 +1,149 @@
|
||||
'use client';
|
||||
|
||||
import {CustomerField} from '@/app/lib/definitions';
|
||||
import Link from 'next/link';
|
||||
import {
|
||||
CheckIcon,
|
||||
ClockIcon,
|
||||
CurrencyDollarIcon,
|
||||
UserCircleIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import {Button} from '@/app/ui/button';
|
||||
import {createInvoice, State} from "@/app/lib/actions";
|
||||
import {useActionState} from "react";
|
||||
|
||||
export default function Form({customers}: { customers: CustomerField[] }) {
|
||||
const initialState: State = { message: null, errors: {} }
|
||||
const [state, formAction] = useActionState(createInvoice, initialState);
|
||||
|
||||
return (
|
||||
<form action={formAction}>
|
||||
<div className="rounded-md bg-gray-50 p-4 md:p-6">
|
||||
{/* Customer Name */}
|
||||
<div className="mb-4">
|
||||
<label htmlFor="customer" className="mb-2 block text-sm font-medium">
|
||||
Choose customer
|
||||
</label>
|
||||
<div className="relative">
|
||||
<select
|
||||
id="customer"
|
||||
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
|
||||
</option>
|
||||
{customers.map((customer) => (
|
||||
<option key={customer.id} value={customer.id}>
|
||||
{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"/>
|
||||
</div>
|
||||
</div>
|
||||
<div id="customer-error" aria-live="polite" aria-atomic="true">
|
||||
{state.errors?.customerId &&
|
||||
state.errors.customerId.map((error: string) => (
|
||||
<p className="mt-2 text-sm text-red-500" key={error}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Invoice Amount */}
|
||||
<div className="mb-4">
|
||||
<label htmlFor="amount" className="mb-2 block text-sm font-medium">
|
||||
Choose an amount
|
||||
</label>
|
||||
<div className="relative mt-2 rounded-md">
|
||||
<div className="relative">
|
||||
<input
|
||||
id="amount"
|
||||
name="amount"
|
||||
type="number"
|
||||
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"
|
||||
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>
|
||||
</div>
|
||||
</div>
|
||||
<div id="amount-error" aria-live="polite" aria-atomic="true">
|
||||
{state.errors?.amount &&
|
||||
state.errors.amount.map((error: string) => (
|
||||
<p className="mt-2 text-sm text-red-500" key={error}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
{/* Invoice Status */}
|
||||
<fieldset>
|
||||
<legend className="mb-2 block text-sm font-medium">
|
||||
Set the invoice status
|
||||
</legend>
|
||||
<div className="rounded-md border border-gray-200 bg-white px-[14px] py-3">
|
||||
<div className="flex gap-4">
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
id="pending"
|
||||
name="status"
|
||||
type="radio"
|
||||
value="pending"
|
||||
className="h-4 w-4 cursor-pointer border-gray-300 bg-gray-100 text-gray-600 focus:ring-2"
|
||||
aria-describedby="status-error"
|
||||
/>
|
||||
<label
|
||||
htmlFor="pending"
|
||||
className="ml-2 flex cursor-pointer items-center gap-1.5 rounded-full bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-600"
|
||||
>
|
||||
Pending <ClockIcon className="h-4 w-4"/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
id="paid"
|
||||
name="status"
|
||||
type="radio"
|
||||
value="paid"
|
||||
className="h-4 w-4 cursor-pointer border-gray-300 bg-gray-100 text-gray-600 focus:ring-2"
|
||||
/>
|
||||
<label
|
||||
htmlFor="paid"
|
||||
className="ml-2 flex cursor-pointer items-center gap-1.5 rounded-full bg-green-500 px-3 py-1.5 text-xs font-medium text-white"
|
||||
>
|
||||
Paid <CheckIcon className="h-4 w-4"/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="status-error" aria-live="polite" aria-atomic="true">
|
||||
{state.errors?.status &&
|
||||
state.errors.status.map((error: string) => (
|
||||
<p className="mt-2 text-sm text-red-500" key={error}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
{state.message && <p className="mt-2 text-sm text-red-500">{state.message}</p>}
|
||||
</fieldset>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
159
app/ui/invoices/edit-form.tsx
Normal file
@@ -0,0 +1,159 @@
|
||||
'use client';
|
||||
|
||||
import { CustomerField, InvoiceForm } from '@/app/lib/definitions';
|
||||
import {
|
||||
CheckIcon,
|
||||
ClockIcon,
|
||||
CurrencyDollarIcon,
|
||||
UserCircleIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import Link from 'next/link';
|
||||
import { Button } from '@/app/ui/button';
|
||||
import {State, updateInvoice} from '@/app/lib/actions';
|
||||
import {useActionState} from "react";
|
||||
|
||||
export default function EditInvoiceForm({
|
||||
invoice,
|
||||
customers,
|
||||
}: {
|
||||
invoice: InvoiceForm;
|
||||
customers: CustomerField[];
|
||||
}) {
|
||||
const initialState: State = { message: null, errors: {} };
|
||||
const updateInvoiceWithId = updateInvoice.bind(null, invoice.id);
|
||||
const [state, formAction] = useActionState(updateInvoiceWithId, initialState);
|
||||
|
||||
return (
|
||||
<form action={formAction}>
|
||||
<div className="rounded-md bg-gray-50 p-4 md:p-6">
|
||||
{/* Customer Name */}
|
||||
<div className="mb-4">
|
||||
<label htmlFor="customer" className="mb-2 block text-sm font-medium">
|
||||
Choose customer
|
||||
</label>
|
||||
<div className="relative">
|
||||
<select
|
||||
id="customer"
|
||||
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={invoice.customer_id}
|
||||
aria-describedby="customer-error"
|
||||
>
|
||||
<option value="" disabled>
|
||||
Select a customer
|
||||
</option>
|
||||
{customers.map((customer) => (
|
||||
<option key={customer.id} value={customer.id}>
|
||||
{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"/>
|
||||
</div>
|
||||
</div>
|
||||
<div id="customer-error" aria-live="polite" aria-atomic="true">
|
||||
{state.errors?.customerId &&
|
||||
state.errors.customerId.map((error: string) => (
|
||||
<p className="mt-2 text-sm text-red-500" key={error}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Invoice Amount */}
|
||||
<div className="mb-4">
|
||||
<label htmlFor="amount" className="mb-2 block text-sm font-medium">
|
||||
Choose an amount
|
||||
</label>
|
||||
<div className="relative mt-2 rounded-md">
|
||||
<div className="relative">
|
||||
<input
|
||||
id="amount"
|
||||
name="amount"
|
||||
type="number"
|
||||
step="0.01"
|
||||
defaultValue={invoice.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"
|
||||
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>
|
||||
</div>
|
||||
</div>
|
||||
<div id="amount-error" aria-live="polite" aria-atomic="true">
|
||||
{state.errors?.amount &&
|
||||
state.errors.amount.map((error: string) => (
|
||||
<p className="mt-2 text-sm text-red-500" key={error}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Invoice Status */}
|
||||
<fieldset>
|
||||
<legend className="mb-2 block text-sm font-medium">
|
||||
Set the invoice status
|
||||
</legend>
|
||||
<div className="rounded-md border border-gray-200 bg-white px-[14px] py-3">
|
||||
<div className="flex gap-4">
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
id="pending"
|
||||
name="status"
|
||||
type="radio"
|
||||
value="pending"
|
||||
defaultChecked={invoice.status === 'pending'}
|
||||
className="h-4 w-4 cursor-pointer border-gray-300 bg-gray-100 text-gray-600 focus:ring-2"
|
||||
aria-describedby="status-error"
|
||||
/>
|
||||
<label
|
||||
htmlFor="pending"
|
||||
className="ml-2 flex cursor-pointer items-center gap-1.5 rounded-full bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-600"
|
||||
>
|
||||
Pending <ClockIcon className="h-4 w-4"/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
id="paid"
|
||||
name="status"
|
||||
type="radio"
|
||||
value="paid"
|
||||
defaultChecked={invoice.status === 'paid'}
|
||||
className="h-4 w-4 cursor-pointer border-gray-300 bg-gray-100 text-gray-600 focus:ring-2"
|
||||
/>
|
||||
<label
|
||||
htmlFor="paid"
|
||||
className="ml-2 flex cursor-pointer items-center gap-1.5 rounded-full bg-green-500 px-3 py-1.5 text-xs font-medium text-white"
|
||||
>
|
||||
Paid <CheckIcon className="h-4 w-4"/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="status-error" aria-live="polite" aria-atomic="true">
|
||||
{state.errors?.status &&
|
||||
state.errors.status.map((error: string) => (
|
||||
<p className="mt-2 text-sm text-red-500" key={error}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
{state.message && <p className="mt-2 text-sm text-red-500">{state.message}</p>}
|
||||
</fieldset>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
129
app/ui/invoices/pagination.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
'use client';
|
||||
|
||||
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 }) {
|
||||
// NOTE: Uncomment this code in Chapter 11
|
||||
|
||||
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()}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* NOTE: Uncomment this code in Chapter 11 */}
|
||||
|
||||
<div className="inline-flex">
|
||||
<PaginationArrow
|
||||
direction="left"
|
||||
href={createPageURL(currentPage - 1)}
|
||||
isDisabled={currentPage <= 1}
|
||||
/>
|
||||
|
||||
<div className="flex -space-x-px">
|
||||
{allPages.map((page: number | string, index) => {
|
||||
let position: 'first' | 'last' | 'single' | 'middle' | undefined;
|
||||
|
||||
if (index === 0) position = 'first';
|
||||
if (index === allPages.length - 1) position = 'last';
|
||||
if (allPages.length === 1) position = 'single';
|
||||
if (page === '...') position = 'middle';
|
||||
|
||||
return (
|
||||
<PaginationNumber
|
||||
key={page}
|
||||
href={createPageURL(page)}
|
||||
page={page}
|
||||
position={position}
|
||||
isActive={currentPage === page}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<PaginationArrow
|
||||
direction="right"
|
||||
href={createPageURL(currentPage + 1)}
|
||||
isDisabled={currentPage >= totalPages}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function PaginationNumber({
|
||||
page,
|
||||
href,
|
||||
isActive,
|
||||
position,
|
||||
}: {
|
||||
page: number | string;
|
||||
href: string;
|
||||
position?: 'first' | 'last' | 'middle' | 'single';
|
||||
isActive: boolean;
|
||||
}) {
|
||||
const className = clsx(
|
||||
'flex h-10 w-10 items-center justify-center text-sm border',
|
||||
{
|
||||
'rounded-l-md': position === 'first' || position === 'single',
|
||||
'rounded-r-md': position === 'last' || position === 'single',
|
||||
'z-10 bg-blue-600 border-blue-600 text-white': isActive,
|
||||
'hover:bg-gray-100': !isActive && position !== 'middle',
|
||||
'text-gray-300': position === 'middle',
|
||||
},
|
||||
);
|
||||
|
||||
return isActive || position === 'middle' ? (
|
||||
<div className={className}>{page}</div>
|
||||
) : (
|
||||
<Link href={href} className={className}>
|
||||
{page}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function PaginationArrow({
|
||||
href,
|
||||
direction,
|
||||
isDisabled,
|
||||
}: {
|
||||
href: string;
|
||||
direction: 'left' | 'right';
|
||||
isDisabled?: boolean;
|
||||
}) {
|
||||
const className = clsx(
|
||||
'flex h-10 w-10 items-center justify-center rounded-md border',
|
||||
{
|
||||
'pointer-events-none text-gray-300': isDisabled,
|
||||
'hover:bg-gray-100': !isDisabled,
|
||||
'mr-2 md:mr-4': direction === 'left',
|
||||
'ml-2 md:ml-4': direction === 'right',
|
||||
},
|
||||
);
|
||||
|
||||
const icon =
|
||||
direction === 'left' ? (
|
||||
<ArrowLeftIcon className="w-4"/>
|
||||
) : (
|
||||
<ArrowRightIcon className="w-4"/>
|
||||
);
|
||||
|
||||
return isDisabled ? (
|
||||
<div className={className}>{icon}</div>
|
||||
) : (
|
||||
<Link className={className} href={href}>
|
||||
{icon}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
29
app/ui/invoices/status.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import { CheckIcon, ClockIcon } from '@heroicons/react/24/outline';
|
||||
import clsx from 'clsx';
|
||||
|
||||
export default function InvoiceStatus({ status }: { status: string }) {
|
||||
return (
|
||||
<span
|
||||
className={clsx(
|
||||
'inline-flex items-center rounded-full px-2 py-1 text-xs',
|
||||
{
|
||||
'bg-gray-100 text-gray-500': status === 'pending',
|
||||
'bg-green-500 text-white': status === 'paid',
|
||||
},
|
||||
)}
|
||||
>
|
||||
{status === 'pending' ? (
|
||||
<>
|
||||
Pending
|
||||
<ClockIcon className="ml-1 w-4 text-gray-500" />
|
||||
</>
|
||||
) : null}
|
||||
{status === 'paid' ? (
|
||||
<>
|
||||
Paid
|
||||
<CheckIcon className="ml-1 w-4 text-white" />
|
||||
</>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
124
app/ui/invoices/table.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
import Image from 'next/image';
|
||||
import { UpdateInvoice, DeleteInvoice } from '@/app/ui/invoices/buttons';
|
||||
import InvoiceStatus from '@/app/ui/invoices/status';
|
||||
import { formatDateToLocal, formatCurrency } from '@/app/lib/utils';
|
||||
import { fetchFilteredInvoices } from '@/app/lib/data';
|
||||
|
||||
export default async function InvoicesTable({
|
||||
query,
|
||||
currentPage,
|
||||
}: {
|
||||
query: string;
|
||||
currentPage: number;
|
||||
}) {
|
||||
const invoices = await fetchFilteredInvoices(query, currentPage);
|
||||
|
||||
return (
|
||||
<div className="mt-6 flow-root">
|
||||
<div className="inline-block min-w-full align-middle">
|
||||
<div className="rounded-lg bg-gray-50 p-2 md:pt-0">
|
||||
<div className="md:hidden">
|
||||
{invoices?.map((invoice) => (
|
||||
<div
|
||||
key={invoice.id}
|
||||
className="mb-2 w-full rounded-md bg-white p-4"
|
||||
>
|
||||
<div className="flex items-center justify-between border-b pb-4">
|
||||
<div>
|
||||
<div className="mb-2 flex items-center">
|
||||
<Image
|
||||
src={invoice.image_url}
|
||||
className="mr-2 rounded-full"
|
||||
width={28}
|
||||
height={28}
|
||||
alt={`${invoice.name}'s profile picture`}
|
||||
/>
|
||||
<p>{invoice.name}</p>
|
||||
</div>
|
||||
<p className="text-sm text-gray-500">{invoice.email}</p>
|
||||
</div>
|
||||
<InvoiceStatus status={invoice.status} />
|
||||
</div>
|
||||
<div className="flex w-full items-center justify-between pt-4">
|
||||
<div>
|
||||
<p className="text-xl font-medium">
|
||||
{formatCurrency(invoice.amount)}
|
||||
</p>
|
||||
<p>{formatDateToLocal(invoice.date)}</p>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<UpdateInvoice id={invoice.id} />
|
||||
<DeleteInvoice id={invoice.id} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<table className="hidden min-w-full text-gray-900 md:table">
|
||||
<thead className="rounded-lg text-left text-sm font-normal">
|
||||
<tr>
|
||||
<th scope="col" className="px-4 py-5 font-medium sm:pl-6">
|
||||
Customer
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-5 font-medium">
|
||||
Email
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-5 font-medium">
|
||||
Amount
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-5 font-medium">
|
||||
Date
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-5 font-medium">
|
||||
Status
|
||||
</th>
|
||||
<th scope="col" className="relative py-3 pl-6 pr-3">
|
||||
<span className="sr-only">Edit</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white">
|
||||
{invoices?.map((invoice) => (
|
||||
<tr
|
||||
key={invoice.id}
|
||||
className="w-full border-b py-3 text-sm last-of-type:border-none [&:first-child>td:first-child]:rounded-tl-lg [&:first-child>td:last-child]:rounded-tr-lg [&:last-child>td:first-child]:rounded-bl-lg [&:last-child>td:last-child]:rounded-br-lg"
|
||||
>
|
||||
<td className="whitespace-nowrap py-3 pl-6 pr-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Image
|
||||
src={invoice.image_url}
|
||||
className="rounded-full"
|
||||
width={28}
|
||||
height={28}
|
||||
alt={`${invoice.name}'s profile picture`}
|
||||
/>
|
||||
<p>{invoice.name}</p>
|
||||
</div>
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-3">
|
||||
{invoice.email}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-3">
|
||||
{formatCurrency(invoice.amount)}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-3">
|
||||
{formatDateToLocal(invoice.date)}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-3">
|
||||
<InvoiceStatus status={invoice.status} />
|
||||
</td>
|
||||
<td className="whitespace-nowrap py-3 pl-6 pr-3">
|
||||
<div className="flex justify-end gap-3">
|
||||
<UpdateInvoice id={invoice.id} />
|
||||
<DeleteInvoice id={invoice.id} />
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
87
app/ui/login-form.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
'use client';
|
||||
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
import {
|
||||
AtSymbolIcon,
|
||||
KeyIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import {ArrowRightIcon, ExclamationCircleIcon} from '@heroicons/react/20/solid';
|
||||
import { Button } from './button';
|
||||
import {useActionState} from "react";
|
||||
import {authenticate} from "@/app/lib/actions";
|
||||
|
||||
export default function LoginForm() {
|
||||
const [errorMessage, formAction, isPending] = useActionState(
|
||||
authenticate,
|
||||
undefined,
|
||||
);
|
||||
|
||||
return (
|
||||
<form action={formAction} 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`}>계속하려면 로그인하세요.</h1>
|
||||
<div className="w-full">
|
||||
<div>
|
||||
<label
|
||||
className="mb-3 mt-5 block text-xs font-medium text-gray-900"
|
||||
htmlFor="email"
|
||||
>
|
||||
Email
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
|
||||
id="email"
|
||||
type="email"
|
||||
name="email"
|
||||
placeholder="Enter your email address"
|
||||
defaultValue="user@nextmail.com"
|
||||
required
|
||||
/>
|
||||
<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"/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<label
|
||||
className="mb-3 mt-5 block text-xs font-medium text-gray-900"
|
||||
htmlFor="password"
|
||||
>
|
||||
Password
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
|
||||
id="password"
|
||||
type="password"
|
||||
name="password"
|
||||
placeholder="Enter password"
|
||||
required
|
||||
minLength={6}
|
||||
defaultValue="123456"
|
||||
/>
|
||||
<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"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button className="mt-4 w-full" aria-disabled={isPending}>
|
||||
로그인 <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"
|
||||
>
|
||||
{errorMessage && (
|
||||
<>
|
||||
|
||||
<ExclamationCircleIcon className="h-5 w-5 text-red-500"/>
|
||||
<p className="test-sm test-red-500">{errorMessage}</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
43
app/ui/search.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
'use client';
|
||||
|
||||
import {MagnifyingGlassIcon} from '@heroicons/react/24/outline';
|
||||
import {usePathname, useRouter, useSearchParams} from "next/navigation";
|
||||
import {useDebouncedCallback} from "use-debounce";
|
||||
|
||||
export default function Search({placeholder}: { placeholder: string }) {
|
||||
|
||||
const pathname = usePathname();
|
||||
const { replace } = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const handleSearch = useDebouncedCallback((term) => {
|
||||
console.log(`searching for ${term}`)
|
||||
|
||||
const params = new URLSearchParams(searchParams);
|
||||
params.set('page', '1');
|
||||
|
||||
if (term) {
|
||||
params.set('query', term);
|
||||
} else {
|
||||
params.delete('query');
|
||||
}
|
||||
|
||||
replace(`${pathname}?${params.toString()}`); // params.toString() translates this input into a URL-friendly format
|
||||
}, 500);
|
||||
|
||||
return (
|
||||
<div className="relative flex flex-1 flex-shrink-0">
|
||||
<label htmlFor="search" className="sr-only">
|
||||
Search
|
||||
</label>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
218
app/ui/skeletons.tsx
Normal file
@@ -0,0 +1,218 @@
|
||||
// Loading animation
|
||||
const shimmer =
|
||||
'before:absolute before:inset-0 before:-translate-x-full before:animate-[shimmer_2s_infinite] before:bg-gradient-to-r before:from-transparent before:via-white/60 before:to-transparent';
|
||||
|
||||
export function CardSkeleton() {
|
||||
return (
|
||||
<div
|
||||
className={`${shimmer} relative overflow-hidden rounded-xl bg-gray-100 p-2 shadow-sm`}
|
||||
>
|
||||
<div className="flex p-4">
|
||||
<div className="h-5 w-5 rounded-md bg-gray-200" />
|
||||
<div className="ml-2 h-6 w-16 rounded-md bg-gray-200 text-sm font-medium" />
|
||||
</div>
|
||||
<div className="flex items-center justify-center truncate rounded-xl bg-white px-4 py-8">
|
||||
<div className="h-7 w-20 rounded-md bg-gray-200" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CardsSkeleton() {
|
||||
return (
|
||||
<>
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function RevenueChartSkeleton() {
|
||||
return (
|
||||
<div className={`${shimmer} relative w-full overflow-hidden md:col-span-4`}>
|
||||
<div className="mb-4 h-8 w-36 rounded-md bg-gray-100" />
|
||||
<div className="rounded-xl bg-gray-100 p-4">
|
||||
<div className="sm:grid-cols-13 mt-0 grid h-[410px] grid-cols-12 items-end gap-2 rounded-md bg-white p-4 md:gap-4" />
|
||||
<div className="flex items-center pb-2 pt-6">
|
||||
<div className="h-5 w-5 rounded-full bg-gray-200" />
|
||||
<div className="ml-2 h-4 w-20 rounded-md bg-gray-200" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function InvoiceSkeleton() {
|
||||
return (
|
||||
<div className="flex flex-row items-center justify-between border-b border-gray-100 py-4">
|
||||
<div className="flex items-center">
|
||||
<div className="mr-2 h-8 w-8 rounded-full bg-gray-200" />
|
||||
<div className="min-w-0">
|
||||
<div className="h-5 w-40 rounded-md bg-gray-200" />
|
||||
<div className="mt-2 h-4 w-12 rounded-md bg-gray-200" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 h-4 w-12 rounded-md bg-gray-200" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LatestInvoicesSkeleton() {
|
||||
return (
|
||||
<div
|
||||
className={`${shimmer} relative flex w-full flex-col overflow-hidden md:col-span-4`}
|
||||
>
|
||||
<div className="mb-4 h-8 w-36 rounded-md bg-gray-100" />
|
||||
<div className="flex grow flex-col justify-between rounded-xl bg-gray-100 p-4">
|
||||
<div className="bg-white px-6">
|
||||
<InvoiceSkeleton />
|
||||
<InvoiceSkeleton />
|
||||
<InvoiceSkeleton />
|
||||
<InvoiceSkeleton />
|
||||
<InvoiceSkeleton />
|
||||
</div>
|
||||
<div className="flex items-center pb-2 pt-6">
|
||||
<div className="h-5 w-5 rounded-full bg-gray-200" />
|
||||
<div className="ml-2 h-4 w-20 rounded-md bg-gray-200" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DashboardSkeleton() {
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={`${shimmer} relative mb-4 h-8 w-36 overflow-hidden rounded-md bg-gray-100`}
|
||||
/>
|
||||
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
</div>
|
||||
<div className="mt-6 grid grid-cols-1 gap-6 md:grid-cols-4 lg:grid-cols-8">
|
||||
<RevenueChartSkeleton />
|
||||
<LatestInvoicesSkeleton />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function TableRowSkeleton() {
|
||||
return (
|
||||
<tr className="w-full border-b border-gray-100 last-of-type:border-none [&:first-child>td:first-child]:rounded-tl-lg [&:first-child>td:last-child]:rounded-tr-lg [&:last-child>td:first-child]:rounded-bl-lg [&:last-child>td:last-child]:rounded-br-lg">
|
||||
{/* Customer Name and Image */}
|
||||
<td className="relative overflow-hidden whitespace-nowrap py-3 pl-6 pr-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-8 w-8 rounded-full bg-gray-100"></div>
|
||||
<div className="h-6 w-24 rounded bg-gray-100"></div>
|
||||
</div>
|
||||
</td>
|
||||
{/* Email */}
|
||||
<td className="whitespace-nowrap px-3 py-3">
|
||||
<div className="h-6 w-32 rounded bg-gray-100"></div>
|
||||
</td>
|
||||
{/* Amount */}
|
||||
<td className="whitespace-nowrap px-3 py-3">
|
||||
<div className="h-6 w-16 rounded bg-gray-100"></div>
|
||||
</td>
|
||||
{/* Date */}
|
||||
<td className="whitespace-nowrap px-3 py-3">
|
||||
<div className="h-6 w-16 rounded bg-gray-100"></div>
|
||||
</td>
|
||||
{/* Status */}
|
||||
<td className="whitespace-nowrap px-3 py-3">
|
||||
<div className="h-6 w-16 rounded bg-gray-100"></div>
|
||||
</td>
|
||||
{/* Actions */}
|
||||
<td className="whitespace-nowrap py-3 pl-6 pr-3">
|
||||
<div className="flex justify-end gap-3">
|
||||
<div className="h-[38px] w-[38px] rounded bg-gray-100"></div>
|
||||
<div className="h-[38px] w-[38px] rounded bg-gray-100"></div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
export function InvoicesMobileSkeleton() {
|
||||
return (
|
||||
<div className="mb-2 w-full rounded-md bg-white p-4">
|
||||
<div className="flex items-center justify-between border-b border-gray-100 pb-8">
|
||||
<div className="flex items-center">
|
||||
<div className="mr-2 h-8 w-8 rounded-full bg-gray-100"></div>
|
||||
<div className="h-6 w-16 rounded bg-gray-100"></div>
|
||||
</div>
|
||||
<div className="h-6 w-16 rounded bg-gray-100"></div>
|
||||
</div>
|
||||
<div className="flex w-full items-center justify-between pt-4">
|
||||
<div>
|
||||
<div className="h-6 w-16 rounded bg-gray-100"></div>
|
||||
<div className="mt-2 h-6 w-24 rounded bg-gray-100"></div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<div className="h-10 w-10 rounded bg-gray-100"></div>
|
||||
<div className="h-10 w-10 rounded bg-gray-100"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function InvoicesTableSkeleton() {
|
||||
return (
|
||||
<div className="mt-6 flow-root">
|
||||
<div className="inline-block min-w-full align-middle">
|
||||
<div className="rounded-lg bg-gray-50 p-2 md:pt-0">
|
||||
<div className="md:hidden">
|
||||
<InvoicesMobileSkeleton />
|
||||
<InvoicesMobileSkeleton />
|
||||
<InvoicesMobileSkeleton />
|
||||
<InvoicesMobileSkeleton />
|
||||
<InvoicesMobileSkeleton />
|
||||
<InvoicesMobileSkeleton />
|
||||
</div>
|
||||
<table className="hidden min-w-full text-gray-900 md:table">
|
||||
<thead className="rounded-lg text-left text-sm font-normal">
|
||||
<tr>
|
||||
<th scope="col" className="px-4 py-5 font-medium sm:pl-6">
|
||||
Customer
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-5 font-medium">
|
||||
Email
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-5 font-medium">
|
||||
Amount
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-5 font-medium">
|
||||
Date
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-5 font-medium">
|
||||
Status
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="relative pb-4 pl-3 pr-6 pt-2 sm:pr-6"
|
||||
>
|
||||
<span className="sr-only">Edit</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white">
|
||||
<TableRowSkeleton />
|
||||
<TableRowSkeleton />
|
||||
<TableRowSkeleton />
|
||||
<TableRowSkeleton />
|
||||
<TableRowSkeleton />
|
||||
<TableRowSkeleton />
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
21
auth.config.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { NextAuthConfig } from 'next-auth';
|
||||
|
||||
export const authConfig = {
|
||||
pages: {
|
||||
signIn: '/login',
|
||||
},
|
||||
callbacks: {
|
||||
authorized({ auth, request: { nextUrl } }) {
|
||||
const isLoggedIn = !!auth?.user;
|
||||
const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');
|
||||
if (isOnDashboard) {
|
||||
if (isLoggedIn) return true;
|
||||
return false; // Redirect unauthenticated users to login page
|
||||
} else if (isLoggedIn) {
|
||||
return Response.redirect(new URL('/dashboard', nextUrl));
|
||||
}
|
||||
return true;
|
||||
},
|
||||
},
|
||||
providers: [], // Add providers with an empty array for now
|
||||
} satisfies NextAuthConfig;
|
||||
46
auth.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import NextAuth from 'next-auth';
|
||||
import { authConfig } from './auth.config';
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import {z} from 'zod';
|
||||
import { sql } from '@vercel/postgres';
|
||||
import type { User } from '@/app/lib/definitions';
|
||||
import bcrypt from 'bcrypt';
|
||||
|
||||
async function getUser(email: string): Promise<User | undefined> {
|
||||
try {
|
||||
const user = await sql.sql<User>`
|
||||
SELECT * FROM users WHERE email = ${email}
|
||||
`;
|
||||
return user.rows[0];
|
||||
} catch (error) {
|
||||
console.error('Failed to get user: ', error);
|
||||
throw new Error('Failed to get 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) {
|
||||
const { email, password } = parsedCredentials.data;
|
||||
const user = await getUser(email);
|
||||
if (!user) return null;
|
||||
const passwordsMatch = await bcrypt.compare(password, user.password);
|
||||
|
||||
if (passwordsMatch) {
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Invalid credentials');
|
||||
return null;
|
||||
},
|
||||
})],
|
||||
});
|
||||
9
middleware.ts
Normal 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$).*)'],
|
||||
};
|
||||
5
next-env.d.ts
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
9
next.config.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { NextConfig } from 'next';
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
experimental: {
|
||||
ppr: 'incremental',
|
||||
}
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
35
package.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "next build",
|
||||
"dev": "next dev --turbopack",
|
||||
"start": "next start",
|
||||
"lint": "next lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@heroicons/react": "^2.2.0",
|
||||
"@supabase/supabase-js": "^2.47.3",
|
||||
"@tailwindcss/forms": "^0.5.9",
|
||||
"@vercel/postgres": "^0.10.0",
|
||||
"autoprefixer": "10.4.20",
|
||||
"bcrypt": "^5.1.1",
|
||||
"clsx": "^2.1.1",
|
||||
"next": "15.1.1-canary.0",
|
||||
"next-auth": "5.0.0-beta.25",
|
||||
"postcss": "8.4.49",
|
||||
"react": "19.0.0",
|
||||
"react-dom": "19.0.0",
|
||||
"tailwindcss": "3.4.16",
|
||||
"typescript": "5.7.2",
|
||||
"use-debounce": "^10.0.4",
|
||||
"zod": "^3.24.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/node": "22.10.1",
|
||||
"@types/react": "19.0.0",
|
||||
"@types/react-dom": "19.0.0",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "15.1.0"
|
||||
}
|
||||
}
|
||||
4236
pnpm-lock.yaml
generated
Normal file
6
postcss.config.js
Normal file
@@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
BIN
public/customers/amy-burns.png
Normal file
|
After Width: | Height: | Size: 7.8 KiB |
BIN
public/customers/balazs-orban.png
Normal file
|
After Width: | Height: | Size: 7.8 KiB |
BIN
public/customers/delba-de-oliveira.png
Normal file
|
After Width: | Height: | Size: 5.7 KiB |
BIN
public/customers/evil-rabbit.png
Normal file
|
After Width: | Height: | Size: 1019 B |
BIN
public/customers/lee-robinson.png
Normal file
|
After Width: | Height: | Size: 5.5 KiB |
BIN
public/customers/michael-novotny.png
Normal file
|
After Width: | Height: | Size: 9.7 KiB |
BIN
public/hero-desktop.png
Normal file
|
After Width: | Height: | Size: 487 KiB |
BIN
public/hero-mobile.png
Normal file
|
After Width: | Height: | Size: 114 KiB |
32
tailwind.config.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { Config } from 'tailwindcss';
|
||||
|
||||
const config: Config = {
|
||||
content: [
|
||||
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
|
||||
'./components/**/*.{js,ts,jsx,tsx,mdx}',
|
||||
'./app/**/*.{js,ts,jsx,tsx,mdx}',
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
gridTemplateColumns: {
|
||||
'13': 'repeat(13, minmax(0, 1fr))',
|
||||
},
|
||||
colors: {
|
||||
blue: {
|
||||
400: '#2589FE',
|
||||
500: '#0070F3',
|
||||
600: '#2F6FEB',
|
||||
},
|
||||
},
|
||||
},
|
||||
keyframes: {
|
||||
shimmer: {
|
||||
'100%': {
|
||||
transform: 'translateX(100%)',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [require('@tailwindcss/forms')],
|
||||
};
|
||||
export default config;
|
||||
35
tsconfig.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "preserve",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
"app/lib/placeholder-data.ts",
|
||||
"scripts/seed.js"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||