This commit is contained in:
2026-05-12 17:35:38 +03:00
parent d9ffcb4b92
commit e3f3e62482
51 changed files with 882 additions and 3413 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
import DashboardSkeleton from '@/app/ui/skeletons'; import DashboardSkeleton from "@/app/ui/skeletons";
export default function Loading() { export default function Loading() {
return <DashboardSkeleton />; return <DashboardSkeleton />;
+12 -10
View File
@@ -1,16 +1,19 @@
import CardWrapper, { Card } from '@/app/ui/dashboard/cards'; import type { Metadata } from "next";
import RevenueChart from '@/app/ui/dashboard/revenue-chart'; import { Suspense } from "react";
import LatestInvoices from '@/app/ui/dashboard/latest-invoices'; import CardWrapper from "@/app/ui/dashboard/cards";
import { lusitana } from '@/app/ui/fonts'; import LatestInvoices from "@/app/ui/dashboard/latest-invoices";
import { Suspense } from 'react'; import RevenueChart from "@/app/ui/dashboard/revenue-chart";
import { CardSkeleton, LatestInvoicesSkeleton, RevenueChartSkeleton } from '@/app/ui/skeletons'; import { lusitana } from "@/app/ui/fonts";
import { Metadata } from 'next'; import {
CardSkeleton,
LatestInvoicesSkeleton,
RevenueChartSkeleton,
} from "@/app/ui/skeletons";
export const metadata: Metadata = { export const metadata: Metadata = {
title: 'Dashboard', title: "Dashboard",
}; };
export default async function Page() { export default async function Page() {
return ( return (
<main> <main>
<h1 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}> <h1 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}>
@@ -22,7 +25,6 @@ export default async function Page() {
</Suspense> </Suspense>
</div> </div>
<div className="mt-6 grid grid-cols-1 gap-6 md:grid-cols-4 lg:grid-cols-8"> <div className="mt-6 grid grid-cols-1 gap-6 md:grid-cols-4 lg:grid-cols-8">
<Suspense fallback={<RevenueChartSkeleton />}> <Suspense fallback={<RevenueChartSkeleton />}>
<RevenueChart /> <RevenueChart />
</Suspense> </Suspense>
+3 -3
View File
@@ -1,9 +1,9 @@
export default function Page() { export default function Page() {
return <p>Customers Page</p>; return <p>Customers Page</p>;
} }
import { Metadata } from 'next';
import type { Metadata } from "next";
export const metadata: Metadata = { export const metadata: Metadata = {
title: 'Customers', title: "Customers",
}; };
@@ -1,5 +1,5 @@
import Link from 'next/link'; import { FaceFrownIcon } from "@heroicons/react/24/outline";
import { FaceFrownIcon } from '@heroicons/react/24/outline'; import Link from "next/link";
export default function NotFound() { export default function NotFound() {
return ( return (
+10 -10
View File
@@ -1,11 +1,11 @@
import Form from '@/app/ui/invoices/edit-form'; import type { Metadata } from "next";
import Breadcrumbs from '@/app/ui/invoices/breadcrumbs'; import { notFound } from "next/navigation";
import { fetchInvoiceById, fetchCustomers } from '@/app/lib/data'; import { fetchCustomers, fetchInvoiceById } from "@/app/lib/data";
import { notFound } from 'next/navigation'; import Breadcrumbs from "@/app/ui/invoices/breadcrumbs";
import { Metadata } from 'next'; import Form from "@/app/ui/invoices/edit-form";
export const metadata: Metadata = { export const metadata: Metadata = {
title: 'Edit invoices', title: "Edit invoices",
}; };
export default async function Page(props: { params: Promise<{ id: string }> }) { export default async function Page(props: { params: Promise<{ id: string }> }) {
@@ -16,17 +16,17 @@ export default async function Page(props: { params: Promise<{ id: string }> }) {
fetchCustomers(), fetchCustomers(),
]); ]);
if (!invoice) { if (!invoice) {
notFound(); notFound();
} }
return ( return (
<main> <main>
<Breadcrumbs <Breadcrumbs
breadcrumbs={[ breadcrumbs={[
{ label: 'Invoices', href: '/dashboard/invoices' }, { label: "Invoices", href: "/dashboard/invoices" },
{ {
label: 'Edit Invoice', label: "Edit Invoice",
href: `/dashboard/invoices/${id}/edit`, href: `/dashboard/invoices/${id}/edit`,
active: true, active: true,
}, },
+8 -8
View File
@@ -1,10 +1,10 @@
import Form from '@/app/ui/invoices/create-form'; import type { Metadata } from "next";
import Breadcrumbs from '@/app/ui/invoices/breadcrumbs'; import { fetchCustomers } from "@/app/lib/data";
import { fetchCustomers } from '@/app/lib/data'; import Breadcrumbs from "@/app/ui/invoices/breadcrumbs";
import { Metadata } from 'next'; import Form from "@/app/ui/invoices/create-form";
export const metadata: Metadata = { export const metadata: Metadata = {
title: 'Create invoices', title: "Create invoices",
}; };
export default async function Page() { export default async function Page() {
@@ -14,10 +14,10 @@ export default async function Page() {
<main> <main>
<Breadcrumbs <Breadcrumbs
breadcrumbs={[ breadcrumbs={[
{ label: 'Invoices', href: '/dashboard/invoices' }, { label: "Invoices", href: "/dashboard/invoices" },
{ {
label: 'Create Invoice', label: "Create Invoice",
href: '/dashboard/invoices/create', href: "/dashboard/invoices/create",
active: true, active: true,
}, },
]} ]}
+2 -2
View File
@@ -1,6 +1,6 @@
'use client'; "use client";
import { useEffect } from 'react'; import { useEffect } from "react";
export default function Error({ export default function Error({
error, error,
+11 -11
View File
@@ -1,15 +1,15 @@
import Pagination from '@/app/ui/invoices/pagination'; import type { Metadata } from "next";
import Search from '@/app/ui/search'; import { Suspense } from "react";
import Table from '@/app/ui/invoices/table'; import { fetchInvoicesPages } from "@/app/lib/data";
import { CreateInvoice } from '@/app/ui/invoices/buttons'; import { lusitana } from "@/app/ui/fonts";
import { lusitana } from '@/app/ui/fonts'; import { CreateInvoice } from "@/app/ui/invoices/buttons";
import { Suspense } from 'react'; import Pagination from "@/app/ui/invoices/pagination";
import { InvoicesTableSkeleton } from '@/app/ui/skeletons'; import Table from "@/app/ui/invoices/table";
import { fetchInvoicesPages } from '@/app/lib/data'; import Search from "@/app/ui/search";
import { Metadata } from 'next'; import { InvoicesTableSkeleton } from "@/app/ui/skeletons";
export const metadata: Metadata = { export const metadata: Metadata = {
title: 'Invoices', title: "Invoices",
}; };
export default async function Page(props: { export default async function Page(props: {
@@ -19,7 +19,7 @@ export default async function Page(props: {
}>; }>;
}) { }) {
const searchParams = await props.searchParams; const searchParams = await props.searchParams;
const query = searchParams?.query || ''; const query = searchParams?.query || "";
const currentPage = Number(searchParams?.page) || 1; const currentPage = Number(searchParams?.page) || 1;
const totalPages = await fetchInvoicesPages(query); const totalPages = await fetchInvoicesPages(query);
+1 -1
View File
@@ -1,4 +1,4 @@
import SideNav from '@/app/ui/dashboard/sidenav'; import SideNav from "@/app/ui/dashboard/sidenav";
export default function Layout({ children }: { children: React.ReactNode }) { export default function Layout({ children }: { children: React.ReactNode }) {
return ( return (
+7 -7
View File
@@ -1,14 +1,14 @@
import '@/app/ui/global.css'; import "@/app/ui/global.css";
import { inter } from '@/app/ui/fonts'; import type { Metadata } from "next";
import { Metadata } from 'next'; import { inter } from "@/app/ui/fonts";
export const metadata: Metadata = { export const metadata: Metadata = {
title: { title: {
template: '%s | Acme Dashboard', template: "%s | Acme Dashboard",
default: 'Acme Dashboard', default: "Acme Dashboard",
}, },
description: 'The official Next.js Learn Dashboard built with App Router.', description: "The official Next.js Learn Dashboard built with App Router.",
metadataBase: new URL('https://next-learn-dashboard.vercel.sh'), metadataBase: new URL("https://next-learn-dashboard.vercel.sh"),
}; };
export default function RootLayout({ export default function RootLayout({
+40 -40
View File
@@ -1,24 +1,24 @@
'use server'; "use server";
import { z } from 'zod'; import { revalidatePath } from "next/cache";
import { revalidatePath } from 'next/cache'; import { redirect } from "next/navigation";
import { redirect } from 'next/navigation'; import { AuthError } from "next-auth";
import postgres from 'postgres'; import postgres from "postgres";
import { signIn } from '@/auth'; import { z } from "zod";
import { AuthError } from 'next-auth'; import { signIn } from "@/auth";
const sql = postgres(process.env.POSTGRES_URL!, { ssl: 'require' }); const sql = postgres(process.env.POSTGRES_URL!, { ssl: "require" });
const FormSchema = z.object({ const FormSchema = z.object({
id: z.string(), id: z.string(),
customerId: z.string({ customerId: z.string({
invalid_type_error: 'Please select a customer', invalid_type_error: "Please select a customer",
}), }),
amount: z.coerce amount: z.coerce
.number() .number()
.gt(0, { message: 'Please enter an amount greater than $0.' }), .gt(0, { message: "Please enter an amount greater than $0." }),
status: z.enum(['pending', 'paid'], { status: z.enum(["pending", "paid"], {
invalid_type_error: 'Please select an invoice status. ', invalid_type_error: "Please select an invoice status. ",
}), }),
date: z.string(), date: z.string(),
}); });
@@ -35,53 +35,53 @@ export type State = {
message?: string | null; message?: string | null;
}; };
export async function createInvoice(prevState: State, formData: FormData) { export async function createInvoice(_prevState: State, formData: FormData) {
const validateFields = CreateInvoice.safeParse({ const validateFields = CreateInvoice.safeParse({
customerId: formData.get('customerId'), customerId: formData.get("customerId"),
amount: formData.get('amount'), amount: formData.get("amount"),
status: formData.get('status'), status: formData.get("status"),
}); });
if (!validateFields.success) { if (!validateFields.success) {
return { return {
errors: validateFields.error.flatten().fieldErrors, errors: validateFields.error.flatten().fieldErrors,
message: 'Missing Fields. Failed to Create Invoice. ', message: "Missing Fields. Failed to Create Invoice. ",
}; };
} }
const { customerId, amount, status } = validateFields.data; const { customerId, amount, status } = validateFields.data;
const amountInCents = amount * 100; const amountInCents = amount * 100;
const date = new Date().toISOString().split('T')[0]; const date = new Date().toISOString().split("T")[0];
try { try {
await sql` await sql`
INSERT INTO invoices (customer_id, amount, status, date) INSERT INTO invoices (customer_id, amount, status, date)
VALUES (${customerId}, ${amountInCents}, ${status}, ${date}) VALUES (${customerId}, ${amountInCents}, ${status}, ${date})
`; `;
} catch (error) { } catch (_error) {
return { return {
message: 'Database Error: Failed to Create Invoice.', message: "Database Error: Failed to Create Invoice.",
}; };
} }
revalidatePath('/dashboard/invoices'); revalidatePath("/dashboard/invoices");
redirect('/dashboard/invoices'); redirect("/dashboard/invoices");
} }
export async function updateInvoice( export async function updateInvoice(
id: string, id: string,
prevState: State, _prevState: State,
formData: FormData, formData: FormData,
) { ) {
const validateFields = UpdateInvoice.safeParse({ const validateFields = UpdateInvoice.safeParse({
customerId: formData.get('customerId'), customerId: formData.get("customerId"),
amount: formData.get('amount'), amount: formData.get("amount"),
status: formData.get('status'), status: formData.get("status"),
}); });
if (!validateFields.success) { if (!validateFields.success) {
return { return {
errors: validateFields.error.flatten().fieldErrors, errors: validateFields.error.flatten().fieldErrors,
message: 'Missing Fields. Failed to update Invoice', message: "Missing Fields. Failed to update Invoice",
}; };
} }
@@ -93,14 +93,14 @@ export async function updateInvoice(
SET customer_id = ${customerId}, amount = ${amountInCents}, status = ${status} SET customer_id = ${customerId}, amount = ${amountInCents}, status = ${status}
WHERE id = ${id} WHERE id = ${id}
`; `;
} catch (error) { } catch (_error) {
return { return {
message: 'Database Failed: Error while updating the Invoice', message: "Database Failed: Error while updating the Invoice",
}; };
} }
revalidatePath('/dashboard/invoices'); revalidatePath("/dashboard/invoices");
redirect('/dashboard/invoices'); redirect("/dashboard/invoices");
} }
export async function deleteInvoice(id: string) { export async function deleteInvoice(id: string) {
@@ -110,28 +110,28 @@ export async function deleteInvoice(id: string) {
DELETE FROM invoices DELETE FROM invoices
WHERE id = ${id} WHERE id = ${id}
`; `;
revalidatePath('/dashboard/invoices'); revalidatePath("/dashboard/invoices");
return { message: 'Deleted Invoice. ' }; return { message: "Deleted Invoice. " };
} catch (error) { } catch (_error) {
return { return {
message: 'Database Error: Failed while deleting record from Invoice. ', message: "Database Error: Failed while deleting record from Invoice. ",
}; };
} }
} }
export async function authenticate( export async function authenticate(
prevState: string | undefined, _prevState: string | undefined,
formData: FormData, formData: FormData,
) { ) {
try { try {
await signIn('credentials', formData); await signIn("credentials", formData);
} catch (error) { } catch (error) {
if (error instanceof AuthError) { if (error instanceof AuthError) {
switch (error.type) { switch (error.type) {
case 'CredentialsSignin': case "CredentialsSignin":
return 'Invalid credentials'; return "Invalid credentials";
default: default:
return 'Something went wrong.'; return "Something went wrong.";
} }
} }
throw error; throw error;
+32 -31
View File
@@ -1,15 +1,16 @@
import postgres from 'postgres'; import postgres from "postgres";
import { import type {
CustomerField, CustomerField,
CustomersTable, CustomersTable,
InvoiceForm, InvoiceForm,
InvoicesTable, InvoicesTable,
LatestInvoiceRaw, LatestInvoiceRaw,
User,
Revenue, Revenue,
} from './definitions'; User,
import { formatCurrency } from './utils'; } from "./definitions";
const sql = postgres(process.env.POSTGRES_URL!, { ssl: 'require' }); import { formatCurrency } from "./utils";
const sql = postgres(process.env.POSTGRES_URL!, { ssl: "require" });
export async function fetchRevenue() { export async function fetchRevenue() {
// Add noStore() here prevent the response from being cached. // Add noStore() here prevent the response from being cached.
// This is equivalent to in fetch(..., {cache: 'no-store'}). // This is equivalent to in fetch(..., {cache: 'no-store'}).
@@ -18,17 +19,17 @@ export async function fetchRevenue() {
// Artificially delay a reponse for demo purposes. // Artificially delay a reponse for demo purposes.
// Don't do this in real life :) // Don't do this in real life :)
console.log('Fetching revenue data...'); console.log("Fetching revenue data...");
await new Promise((resolve) => setTimeout(resolve, 3000)); await new Promise((resolve) => setTimeout(resolve, 3000));
const data = sql<Revenue[]>`SELECT * FROM revenue`; const data = sql<Revenue[]>`SELECT * FROM revenue`;
console.log('Data fetch complete after 3 seconds.'); console.log("Data fetch complete after 3 seconds.");
return data; return data;
} catch (error) { } catch (error) {
console.error('Database Error:', error); console.error("Database Error:", error);
throw new Error('Failed to fetch revenue data.'); throw new Error("Failed to fetch revenue data.");
} }
} }
@@ -47,8 +48,8 @@ export async function fetchLatestInvoices() {
})); }));
return latestInvoices; return latestInvoices;
} catch (error) { } catch (error) {
console.error('Database Error:', error); console.error("Database Error:", error);
throw new Error('Failed to fetch the latest invoices.'); throw new Error("Failed to fetch the latest invoices.");
} }
} }
@@ -70,10 +71,10 @@ export async function fetchCardData() {
invoiceStatusPromise, invoiceStatusPromise,
]); ]);
const numberOfInvoices = Number(data[0][0].count ?? '0'); const numberOfInvoices = Number(data[0][0].count ?? "0");
const numberOfCustomers = Number(data[1][0].count ?? '0'); const numberOfCustomers = Number(data[1][0].count ?? "0");
const totalPaidInvoices = formatCurrency(data[2][0].paid ?? '0'); const totalPaidInvoices = formatCurrency(data[2][0].paid ?? "0");
const totalPendingInvoices = formatCurrency(data[2][0].pending ?? '0'); const totalPendingInvoices = formatCurrency(data[2][0].pending ?? "0");
return { return {
numberOfCustomers, numberOfCustomers,
@@ -82,8 +83,8 @@ export async function fetchCardData() {
totalPendingInvoices, totalPendingInvoices,
}; };
} catch (error) { } catch (error) {
console.error('Database Error:', error); console.error("Database Error:", error);
throw new Error('Failed to card data.'); throw new Error("Failed to card data.");
} }
} }
@@ -118,8 +119,8 @@ export async function fetchFilteredInvoices(
return invoices; return invoices;
} catch (error) { } catch (error) {
console.error('Database Error:', error); console.error("Database Error:", error);
throw new Error('Failed to fetch invoices.'); throw new Error("Failed to fetch invoices.");
} }
} }
@@ -139,8 +140,8 @@ export async function fetchInvoicesPages(query: string) {
const totalPages = Math.ceil(Number(count[0].count) / ITEMS_PER_PAGE); const totalPages = Math.ceil(Number(count[0].count) / ITEMS_PER_PAGE);
return totalPages; return totalPages;
} catch (error) { } catch (error) {
console.error('Database Error:', error); console.error("Database Error:", error);
throw new Error('Failed to fetch total number of invoices.'); throw new Error("Failed to fetch total number of invoices.");
} }
} }
@@ -165,7 +166,7 @@ export async function fetchInvoiceById(id: string) {
console.log(invoice); // Invoice is an empty array [] console.log(invoice); // Invoice is an empty array []
return invoice[0]; return invoice[0];
} catch (error) { } catch (error) {
console.error('Database Error:', error); console.error("Database Error:", error);
} }
} }
@@ -182,8 +183,8 @@ export async function fetchCustomers() {
const customers = data; const customers = data;
return customers; return customers;
} catch (err) { } catch (err) {
console.error('Database Error:', err); console.error("Database Error:", err);
throw new Error('Failed to fetch all customers.'); throw new Error("Failed to fetch all customers.");
} }
} }
@@ -215,8 +216,8 @@ export async function fetchFilteredCustomers(query: string) {
return customers; return customers;
} catch (err) { } catch (err) {
console.error('Database Error:', err); console.error("Database Error:", err);
throw new Error('Failed to fetch customer table.'); throw new Error("Failed to fetch customer table.");
} }
} }
@@ -225,7 +226,7 @@ export async function getUser(email: string) {
const user = await sql`SELECT * from USERS where email=${email}`; const user = await sql`SELECT * from USERS where email=${email}`;
return user[0] as User; return user[0] as User;
} catch (error) { } catch (error) {
console.error('Failed to fetch user:', error); console.error("Failed to fetch user:", error);
throw new Error('Failed to fetch user.'); throw new Error("Failed to fetch user.");
} }
} }
+4 -4
View File
@@ -23,7 +23,7 @@ export type Invoice = {
date: string; date: string;
// In TypeScript, this is called a string union type. // 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'. // It means that the "status" property can only be one of the two strings: 'pending' or 'paid'.
status: 'pending' | 'paid'; status: "pending" | "paid";
}; };
export type Revenue = { export type Revenue = {
@@ -40,7 +40,7 @@ export type LatestInvoice = {
}; };
// The database returns a number for amount, but we later format it to a string with the formatCurrency function // 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'> & { export type LatestInvoiceRaw = Omit<LatestInvoice, "amount"> & {
amount: number; amount: number;
}; };
@@ -52,7 +52,7 @@ export type InvoicesTable = {
image_url: string; image_url: string;
date: string; date: string;
amount: number; amount: number;
status: 'pending' | 'paid'; status: "pending" | "paid";
}; };
export type CustomersTable = { export type CustomersTable = {
@@ -84,5 +84,5 @@ export type InvoiceForm = {
id: string; id: string;
customer_id: string; customer_id: string;
amount: number; amount: number;
status: 'pending' | 'paid'; status: "pending" | "paid";
}; };
+86 -86
View File
@@ -2,73 +2,73 @@
// https://nextjs.org/learn/dashboard-app/fetching-data // https://nextjs.org/learn/dashboard-app/fetching-data
const users = [ const users = [
{ {
id: '410544b2-4001-4271-9855-fec4b6a6442a', id: "410544b2-4001-4271-9855-fec4b6a6442a",
name: 'User', name: "User",
email: 'user@nextmail.com', email: "user@nextmail.com",
password: '123456', password: "123456",
}, },
]; ];
const customers = [ const customers = [
{ {
id: '3958dc9e-712f-4377-85e9-fec4b6a6442a', id: "3958dc9e-712f-4377-85e9-fec4b6a6442a",
name: 'Delba de Oliveira', name: "Delba de Oliveira",
email: 'delba@oliveira.com', email: "delba@oliveira.com",
image_url: '/customers/delba-de-oliveira.png', image_url: "/customers/delba-de-oliveira.png",
}, },
{ {
id: '3958dc9e-742f-4377-85e9-fec4b6a6442a', id: "3958dc9e-742f-4377-85e9-fec4b6a6442a",
name: 'Lee Robinson', name: "Lee Robinson",
email: 'lee@robinson.com', email: "lee@robinson.com",
image_url: '/customers/lee-robinson.png', image_url: "/customers/lee-robinson.png",
}, },
{ {
id: '3958dc9e-737f-4377-85e9-fec4b6a6442a', id: "3958dc9e-737f-4377-85e9-fec4b6a6442a",
name: 'Hector Simpson', name: "Hector Simpson",
email: 'hector@simpson.com', email: "hector@simpson.com",
image_url: '/customers/hector-simpson.png', image_url: "/customers/hector-simpson.png",
}, },
{ {
id: '50ca3e18-62cd-11ee-8c99-0242ac120002', id: "50ca3e18-62cd-11ee-8c99-0242ac120002",
name: 'Steven Tey', name: "Steven Tey",
email: 'steven@tey.com', email: "steven@tey.com",
image_url: '/customers/steven-tey.png', image_url: "/customers/steven-tey.png",
}, },
{ {
id: '3958dc9e-787f-4377-85e9-fec4b6a6442a', id: "3958dc9e-787f-4377-85e9-fec4b6a6442a",
name: 'Steph Dietz', name: "Steph Dietz",
email: 'steph@dietz.com', email: "steph@dietz.com",
image_url: '/customers/steph-dietz.png', image_url: "/customers/steph-dietz.png",
}, },
{ {
id: '76d65c26-f784-44a2-ac19-586678f7c2f2', id: "76d65c26-f784-44a2-ac19-586678f7c2f2",
name: 'Michael Novotny', name: "Michael Novotny",
email: 'michael@novotny.com', email: "michael@novotny.com",
image_url: '/customers/michael-novotny.png', image_url: "/customers/michael-novotny.png",
}, },
{ {
id: 'd6e15727-9fe1-4961-8c5b-ea44a9bd81aa', id: "d6e15727-9fe1-4961-8c5b-ea44a9bd81aa",
name: 'Evil Rabbit', name: "Evil Rabbit",
email: 'evil@rabbit.com', email: "evil@rabbit.com",
image_url: '/customers/evil-rabbit.png', image_url: "/customers/evil-rabbit.png",
}, },
{ {
id: '126eed9c-c90c-4ef6-a4a8-fcf7408d3c66', id: "126eed9c-c90c-4ef6-a4a8-fcf7408d3c66",
name: 'Emil Kowalski', name: "Emil Kowalski",
email: 'emil@kowalski.com', email: "emil@kowalski.com",
image_url: '/customers/emil-kowalski.png', image_url: "/customers/emil-kowalski.png",
}, },
{ {
id: 'CC27C14A-0ACF-4F4A-A6C9-D45682C144B9', id: "CC27C14A-0ACF-4F4A-A6C9-D45682C144B9",
name: 'Amy Burns', name: "Amy Burns",
email: 'amy@burns.com', email: "amy@burns.com",
image_url: '/customers/amy-burns.png', image_url: "/customers/amy-burns.png",
}, },
{ {
id: '13D07535-C59E-4157-A011-F8D2EF4E0CBB', id: "13D07535-C59E-4157-A011-F8D2EF4E0CBB",
name: 'Balazs Orban', name: "Balazs Orban",
email: 'balazs@orban.com', email: "balazs@orban.com",
image_url: '/customers/balazs-orban.png', image_url: "/customers/balazs-orban.png",
}, },
]; ];
@@ -76,108 +76,108 @@ const invoices = [
{ {
customer_id: customers[0].id, customer_id: customers[0].id,
amount: 15795, amount: 15795,
status: 'pending', status: "pending",
date: '2022-12-06', date: "2022-12-06",
}, },
{ {
customer_id: customers[1].id, customer_id: customers[1].id,
amount: 20348, amount: 20348,
status: 'pending', status: "pending",
date: '2022-11-14', date: "2022-11-14",
}, },
{ {
customer_id: customers[4].id, customer_id: customers[4].id,
amount: 3040, amount: 3040,
status: 'paid', status: "paid",
date: '2022-10-29', date: "2022-10-29",
}, },
{ {
customer_id: customers[3].id, customer_id: customers[3].id,
amount: 44800, amount: 44800,
status: 'paid', status: "paid",
date: '2023-09-10', date: "2023-09-10",
}, },
{ {
customer_id: customers[5].id, customer_id: customers[5].id,
amount: 34577, amount: 34577,
status: 'pending', status: "pending",
date: '2023-08-05', date: "2023-08-05",
}, },
{ {
customer_id: customers[7].id, customer_id: customers[7].id,
amount: 54246, amount: 54246,
status: 'pending', status: "pending",
date: '2023-07-16', date: "2023-07-16",
}, },
{ {
customer_id: customers[6].id, customer_id: customers[6].id,
amount: 666, amount: 666,
status: 'pending', status: "pending",
date: '2023-06-27', date: "2023-06-27",
}, },
{ {
customer_id: customers[3].id, customer_id: customers[3].id,
amount: 32545, amount: 32545,
status: 'paid', status: "paid",
date: '2023-06-09', date: "2023-06-09",
}, },
{ {
customer_id: customers[4].id, customer_id: customers[4].id,
amount: 1250, amount: 1250,
status: 'paid', status: "paid",
date: '2023-06-17', date: "2023-06-17",
}, },
{ {
customer_id: customers[5].id, customer_id: customers[5].id,
amount: 8546, amount: 8546,
status: 'paid', status: "paid",
date: '2023-06-07', date: "2023-06-07",
}, },
{ {
customer_id: customers[1].id, customer_id: customers[1].id,
amount: 500, amount: 500,
status: 'paid', status: "paid",
date: '2023-08-19', date: "2023-08-19",
}, },
{ {
customer_id: customers[5].id, customer_id: customers[5].id,
amount: 8945, amount: 8945,
status: 'paid', status: "paid",
date: '2023-06-03', date: "2023-06-03",
}, },
{ {
customer_id: customers[2].id, customer_id: customers[2].id,
amount: 8945, amount: 8945,
status: 'paid', status: "paid",
date: '2023-06-18', date: "2023-06-18",
}, },
{ {
customer_id: customers[0].id, customer_id: customers[0].id,
amount: 8945, amount: 8945,
status: 'paid', status: "paid",
date: '2023-10-04', date: "2023-10-04",
}, },
{ {
customer_id: customers[2].id, customer_id: customers[2].id,
amount: 1000, amount: 1000,
status: 'paid', status: "paid",
date: '2022-06-05', date: "2022-06-05",
}, },
]; ];
const revenue = [ const revenue = [
{ month: 'Jan', revenue: 2000 }, { month: "Jan", revenue: 2000 },
{ month: 'Feb', revenue: 1800 }, { month: "Feb", revenue: 1800 },
{ month: 'Mar', revenue: 2200 }, { month: "Mar", revenue: 2200 },
{ month: 'Apr', revenue: 2500 }, { month: "Apr", revenue: 2500 },
{ month: 'May', revenue: 2300 }, { month: "May", revenue: 2300 },
{ month: 'Jun', revenue: 3200 }, { month: "Jun", revenue: 3200 },
{ month: 'Jul', revenue: 3500 }, { month: "Jul", revenue: 3500 },
{ month: 'Aug', revenue: 3700 }, { month: "Aug", revenue: 3700 },
{ month: 'Sep', revenue: 2500 }, { month: "Sep", revenue: 2500 },
{ month: 'Oct', revenue: 2800 }, { month: "Oct", revenue: 2800 },
{ month: 'Nov', revenue: 3000 }, { month: "Nov", revenue: 3000 },
{ month: 'Dec', revenue: 4800 }, { month: "Dec", revenue: 4800 },
]; ];
module.exports = { module.exports = {
+67 -67
View File
@@ -2,49 +2,49 @@
// https://nextjs.org/learn/dashboard-app/fetching-data // https://nextjs.org/learn/dashboard-app/fetching-data
const users = [ const users = [
{ {
id: '410544b2-4001-4271-9855-fec4b6a6442a', id: "410544b2-4001-4271-9855-fec4b6a6442a",
name: 'User', name: "User",
email: 'user@nextmail.com', email: "user@nextmail.com",
password: '123456', password: "123456",
}, },
]; ];
const customers = [ const customers = [
{ {
id: 'd6e15727-9fe1-4961-8c5b-ea44a9bd81aa', id: "d6e15727-9fe1-4961-8c5b-ea44a9bd81aa",
name: 'Evil Rabbit', name: "Evil Rabbit",
email: 'evil@rabbit.com', email: "evil@rabbit.com",
image_url: '/customers/evil-rabbit.png', image_url: "/customers/evil-rabbit.png",
}, },
{ {
id: '3958dc9e-712f-4377-85e9-fec4b6a6442a', id: "3958dc9e-712f-4377-85e9-fec4b6a6442a",
name: 'Delba de Oliveira', name: "Delba de Oliveira",
email: 'delba@oliveira.com', email: "delba@oliveira.com",
image_url: '/customers/delba-de-oliveira.png', image_url: "/customers/delba-de-oliveira.png",
}, },
{ {
id: '3958dc9e-742f-4377-85e9-fec4b6a6442a', id: "3958dc9e-742f-4377-85e9-fec4b6a6442a",
name: 'Lee Robinson', name: "Lee Robinson",
email: 'lee@robinson.com', email: "lee@robinson.com",
image_url: '/customers/lee-robinson.png', image_url: "/customers/lee-robinson.png",
}, },
{ {
id: '76d65c26-f784-44a2-ac19-586678f7c2f2', id: "76d65c26-f784-44a2-ac19-586678f7c2f2",
name: 'Michael Novotny', name: "Michael Novotny",
email: 'michael@novotny.com', email: "michael@novotny.com",
image_url: '/customers/michael-novotny.png', image_url: "/customers/michael-novotny.png",
}, },
{ {
id: 'CC27C14A-0ACF-4F4A-A6C9-D45682C144B9', id: "CC27C14A-0ACF-4F4A-A6C9-D45682C144B9",
name: 'Amy Burns', name: "Amy Burns",
email: 'amy@burns.com', email: "amy@burns.com",
image_url: '/customers/amy-burns.png', image_url: "/customers/amy-burns.png",
}, },
{ {
id: '13D07535-C59E-4157-A011-F8D2EF4E0CBB', id: "13D07535-C59E-4157-A011-F8D2EF4E0CBB",
name: 'Balazs Orban', name: "Balazs Orban",
email: 'balazs@orban.com', email: "balazs@orban.com",
image_url: '/customers/balazs-orban.png', image_url: "/customers/balazs-orban.png",
}, },
]; ];
@@ -52,96 +52,96 @@ const invoices = [
{ {
customer_id: customers[0].id, customer_id: customers[0].id,
amount: 15795, amount: 15795,
status: 'pending', status: "pending",
date: '2022-12-06', date: "2022-12-06",
}, },
{ {
customer_id: customers[1].id, customer_id: customers[1].id,
amount: 20348, amount: 20348,
status: 'pending', status: "pending",
date: '2022-11-14', date: "2022-11-14",
}, },
{ {
customer_id: customers[4].id, customer_id: customers[4].id,
amount: 3040, amount: 3040,
status: 'paid', status: "paid",
date: '2022-10-29', date: "2022-10-29",
}, },
{ {
customer_id: customers[3].id, customer_id: customers[3].id,
amount: 44800, amount: 44800,
status: 'paid', status: "paid",
date: '2023-09-10', date: "2023-09-10",
}, },
{ {
customer_id: customers[5].id, customer_id: customers[5].id,
amount: 34577, amount: 34577,
status: 'pending', status: "pending",
date: '2023-08-05', date: "2023-08-05",
}, },
{ {
customer_id: customers[2].id, customer_id: customers[2].id,
amount: 54246, amount: 54246,
status: 'pending', status: "pending",
date: '2023-07-16', date: "2023-07-16",
}, },
{ {
customer_id: customers[0].id, customer_id: customers[0].id,
amount: 666, amount: 666,
status: 'pending', status: "pending",
date: '2023-06-27', date: "2023-06-27",
}, },
{ {
customer_id: customers[3].id, customer_id: customers[3].id,
amount: 32545, amount: 32545,
status: 'paid', status: "paid",
date: '2023-06-09', date: "2023-06-09",
}, },
{ {
customer_id: customers[4].id, customer_id: customers[4].id,
amount: 1250, amount: 1250,
status: 'paid', status: "paid",
date: '2023-06-17', date: "2023-06-17",
}, },
{ {
customer_id: customers[5].id, customer_id: customers[5].id,
amount: 8546, amount: 8546,
status: 'paid', status: "paid",
date: '2023-06-07', date: "2023-06-07",
}, },
{ {
customer_id: customers[1].id, customer_id: customers[1].id,
amount: 500, amount: 500,
status: 'paid', status: "paid",
date: '2023-08-19', date: "2023-08-19",
}, },
{ {
customer_id: customers[5].id, customer_id: customers[5].id,
amount: 8945, amount: 8945,
status: 'paid', status: "paid",
date: '2023-06-03', date: "2023-06-03",
}, },
{ {
customer_id: customers[2].id, customer_id: customers[2].id,
amount: 1000, amount: 1000,
status: 'paid', status: "paid",
date: '2022-06-05', date: "2022-06-05",
}, },
]; ];
const revenue = [ const revenue = [
{ month: 'Jan', revenue: 2000 }, { month: "Jan", revenue: 2000 },
{ month: 'Feb', revenue: 1800 }, { month: "Feb", revenue: 1800 },
{ month: 'Mar', revenue: 2200 }, { month: "Mar", revenue: 2200 },
{ month: 'Apr', revenue: 2500 }, { month: "Apr", revenue: 2500 },
{ month: 'May', revenue: 2300 }, { month: "May", revenue: 2300 },
{ month: 'Jun', revenue: 3200 }, { month: "Jun", revenue: 3200 },
{ month: 'Jul', revenue: 3500 }, { month: "Jul", revenue: 3500 },
{ month: 'Aug', revenue: 3700 }, { month: "Aug", revenue: 3700 },
{ month: 'Sep', revenue: 2500 }, { month: "Sep", revenue: 2500 },
{ month: 'Oct', revenue: 2800 }, { month: "Oct", revenue: 2800 },
{ month: 'Nov', revenue: 3000 }, { month: "Nov", revenue: 3000 },
{ month: 'Dec', revenue: 4800 }, { month: "Dec", revenue: 4800 },
]; ];
export { users, customers, invoices, revenue }; export { customers, invoices, revenue, users };
+12 -12
View File
@@ -1,21 +1,21 @@
import { Revenue } from './definitions'; import type { Revenue } from "./definitions";
export const formatCurrency = (amount: number) => { export const formatCurrency = (amount: number) => {
return (amount / 100).toLocaleString('en-US', { return (amount / 100).toLocaleString("en-US", {
style: 'currency', style: "currency",
currency: 'USD', currency: "USD",
}); });
}; };
export const formatDateToLocal = ( export const formatDateToLocal = (
dateStr: string, dateStr: string,
locale: string = 'en-US', locale: string = "en-US",
) => { ) => {
const date = new Date(dateStr); const date = new Date(dateStr);
const options: Intl.DateTimeFormatOptions = { const options: Intl.DateTimeFormatOptions = {
day: 'numeric', day: "numeric",
month: 'short', month: "short",
year: 'numeric', year: "numeric",
}; };
const formatter = new Intl.DateTimeFormat(locale, options); const formatter = new Intl.DateTimeFormat(locale, options);
return formatter.format(date); return formatter.format(date);
@@ -45,13 +45,13 @@ export const generatePagination = (currentPage: number, totalPages: number) => {
// If the current page is among the first 3 pages, // If the current page is among the first 3 pages,
// show the first 3, an ellipsis, and the last 2 pages. // show the first 3, an ellipsis, and the last 2 pages.
if (currentPage <= 3) { if (currentPage <= 3) {
return [1, 2, 3, '...', totalPages - 1, totalPages]; return [1, 2, 3, "...", totalPages - 1, totalPages];
} }
// If the current page is among the last 3 pages, // If the current page is among the last 3 pages,
// show the first 2, an ellipsis, and the last 3 pages. // show the first 2, an ellipsis, and the last 3 pages.
if (currentPage >= totalPages - 2) { if (currentPage >= totalPages - 2) {
return [1, 2, '...', totalPages - 2, totalPages - 1, totalPages]; return [1, 2, "...", totalPages - 2, totalPages - 1, totalPages];
} }
// If the current page is somewhere in the middle, // If the current page is somewhere in the middle,
@@ -59,11 +59,11 @@ export const generatePagination = (currentPage: number, totalPages: number) => {
// another ellipsis, and the last page. // another ellipsis, and the last page.
return [ return [
1, 1,
'...', "...",
currentPage - 1, currentPage - 1,
currentPage, currentPage,
currentPage + 1, currentPage + 1,
'...', "...",
totalPages, totalPages,
]; ];
}; };
+5 -5
View File
@@ -1,10 +1,10 @@
import AcmeLogo from '@/app/ui/acme-logo'; import type { Metadata } from "next";
import LoginForm from '@/app/ui/login-form'; import { Suspense } from "react";
import { Suspense } from 'react'; import AcmeLogo from "@/app/ui/acme-logo";
import { Metadata } from 'next'; import LoginForm from "@/app/ui/login-form";
export const metadata: Metadata = { export const metadata: Metadata = {
title: 'Login', title: "Login",
}; };
export default function LoginPage() { export default function LoginPage() {
+25 -25
View File
@@ -1,22 +1,22 @@
import AcmeLogo from '@/app/ui/acme-logo'; import Image from "next/image";
import styles from '@/app/ui/home.module.css'; import Link from "next/link";
import Link from 'next/link'; import AcmeLogo from "@/app/ui/acme-logo";
import { lusitana } from '@/app/ui/fonts'; import { lusitana } from "@/app/ui/fonts";
import Image from 'next/image'; import styles from "@/app/ui/home.module.css";
export default function Page() { export default function Page() {
return ( return (
<main className="flex min-h-screen flex-col p-6"> <main className="flex min-h-screen flex-col p-6">
<div className="flex h-20 shrink-0 items-end rounded-lg bg-blue-500 p-4 md:h-52"> <div className="flex h-20 shrink-0 items-end rounded-lg bg-blue-500 p-4 md:h-52">
<AcmeLogo /> <AcmeLogo />
{/* <AcmeLogo /> */} {/* <AcmeLogo /> */}
</div> </div>
<div className="mt-4 flex grow flex-col gap-4 md:flex-row"> <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="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={styles.shape} /> <div className={styles.shape} />
<p <p
className={`${lusitana.className} text-xl text-gray-800 md:text-3xl md:leading-normal`} className={`${lusitana.className} text-xl text-gray-800 md:text-3xl md:leading-normal`}
> >
<strong>Welcome to Acme.</strong> This is the example for the{' '} <strong>Welcome to Acme.</strong> This is the example for the{" "}
<a href="https://nextjs.org/learn/" className="text-blue-500"> <a href="https://nextjs.org/learn/" className="text-blue-500">
Next.js Learn Course Next.js Learn Course
</a> </a>
@@ -30,20 +30,20 @@ export default function Page() {
</Link> </Link>
</div> </div>
<div className="flex items-center justify-center p-6 md:w-3/5 md:px-28 md:py-12"> <div className="flex items-center justify-center p-6 md:w-3/5 md:px-28 md:py-12">
<Image <Image
src="/hero-desktop.png" src="/hero-desktop.png"
width={1000} width={1000}
height={760} height={760}
className="hidden md:block" className="hidden md:block"
alt="Screenshots of the dashboard project showing desktop version" alt="Screenshots of the dashboard project showing desktop version"
/> />
<Image <Image
src="/hero-mobile.png" src="/hero-mobile.png"
width={560} width={560}
height={620} height={620}
className="block md:hidden" className="block md:hidden"
alt="Screenshots of the dashboard project showing mobile version" alt="Screenshots of the dashboard project showing mobile version"
/> />
</div> </div>
</div> </div>
</main> </main>
+7 -7
View File
@@ -1,20 +1,20 @@
import postgres from 'postgres'; import postgres from "postgres";
const sql = postgres(process.env.POSTGRES_URL!, { ssl: 'require' }); const sql = postgres(process.env.POSTGRES_URL!, { ssl: "require" });
async function listInvoices() { async function listInvoices() {
const data = await sql` const data = await sql`
SELECT invoices.amount, customers.name SELECT invoices.amount, customers.name
FROM invoices FROM invoices
JOIN customers ON invoices.customer_id = customers.id JOIN customers ON invoices.customer_id = customers.id
WHERE invoices.amount = 666; WHERE invoices.amount = 666;
`; `;
return data; return data;
} }
export async function GET() { export async function GET() {
try { try {
return Response.json(await listInvoices()); return Response.json(await listInvoices());
} catch (error) { } catch (error) {
return Response.json({ error }, { status: 500 }); return Response.json({ error }, { status: 500 });
} }
} }
+6 -6
View File
@@ -1,8 +1,8 @@
import bcrypt from 'bcrypt'; import bcrypt from "bcrypt";
import postgres from 'postgres'; import postgres from "postgres";
import { invoices, customers, revenue, users } from '../lib/placeholder-data'; import { customers, invoices, revenue, users } from "../lib/placeholder-data";
const sql = postgres(process.env.POSTGRES_URL!, { ssl: 'require' }); const sql = postgres(process.env.POSTGRES_URL!, { ssl: "require" });
async function seedUsers() { async function seedUsers() {
await sql`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`; await sql`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`;
@@ -103,14 +103,14 @@ async function seedRevenue() {
export async function GET() { export async function GET() {
try { try {
const result = await sql.begin((sql) => [ const _result = await sql.begin((_sql) => [
seedUsers(), seedUsers(),
seedCustomers(), seedCustomers(),
seedInvoices(), seedInvoices(),
seedRevenue(), seedRevenue(),
]); ]);
return Response.json({ message: 'Database seeded successfully' }); return Response.json({ message: "Database seeded successfully" });
} catch (error) { } catch (error) {
return Response.json({ error }, { status: 500 }); return Response.json({ error }, { status: 500 });
} }
+2 -2
View File
@@ -1,5 +1,5 @@
import { GlobeAltIcon } from '@heroicons/react/24/outline'; import { GlobeAltIcon } from "@heroicons/react/24/outline";
import { lusitana } from '@/app/ui/fonts'; import { lusitana } from "@/app/ui/fonts";
export default function AcmeLogo() { export default function AcmeLogo() {
return ( return (
+2 -2
View File
@@ -1,4 +1,4 @@
import clsx from 'clsx'; import clsx from "clsx";
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
children: React.ReactNode; children: React.ReactNode;
@@ -9,7 +9,7 @@ export function Button({ children, className, ...rest }: ButtonProps) {
<button <button
{...rest} {...rest}
className={clsx( 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', "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, className,
)} )}
> >
+4 -4
View File
@@ -1,7 +1,7 @@
import Image from 'next/image'; import Image from "next/image";
import { lusitana } from '@/app/ui/fonts'; import type { FormattedCustomersTable } from "@/app/lib/definitions";
import Search from '../search'; import { lusitana } from "@/app/ui/fonts";
import { CustomersTable, FormattedCustomersTable } from '@/app/lib/definitions'; import Search from "../search";
export default async function customersTable({ export default async function customersTable({
customers, customers,
}: { }: {
+5 -5
View File
@@ -1,11 +1,11 @@
import { import {
BanknotesIcon, BanknotesIcon,
ClockIcon, ClockIcon,
UserGroupIcon,
InboxIcon, InboxIcon,
} from '@heroicons/react/24/outline'; UserGroupIcon,
import { lusitana } from '@/app/ui/fonts'; } from "@heroicons/react/24/outline";
import { fetchCardData } from '@/app/lib/data'; import { fetchCardData } from "@/app/lib/data";
import { lusitana } from "@/app/ui/fonts";
const iconMap = { const iconMap = {
collected: BanknotesIcon, collected: BanknotesIcon,
@@ -43,7 +43,7 @@ export function Card({
}: { }: {
title: string; title: string;
value: number | string; value: number | string;
type: 'invoices' | 'customers' | 'pending' | 'collected'; type: "invoices" | "customers" | "pending" | "collected";
}) { }) {
const Icon = iconMap[type]; const Icon = iconMap[type];
+46 -44
View File
@@ -1,11 +1,11 @@
import { ArrowPathIcon } from '@heroicons/react/24/outline'; import { ArrowPathIcon } from "@heroicons/react/24/outline";
import clsx from 'clsx'; import clsx from "clsx";
import Image from 'next/image'; import Image from "next/image";
import { lusitana } from '@/app/ui/fonts'; import { fetchLatestInvoices } from "@/app/lib/data";
import { LatestInvoice } from '@/app/lib/definitions'; import { lusitana } from "@/app/ui/fonts";
import { fetchLatestInvoices } from '@/app/lib/data';
export default async function LatestInvoices() { // Remove props export default async function LatestInvoices() {
// Remove props
const latestInvoices = await fetchLatestInvoices(); const latestInvoices = await fetchLatestInvoices();
return ( return (
@@ -16,44 +16,46 @@ export default async function LatestInvoices() { // Remove props
<div className="flex grow flex-col justify-between rounded-xl bg-gray-50 p-4"> <div className="flex grow flex-col justify-between rounded-xl bg-gray-50 p-4">
{/* NOTE: comment in this code when you get to this point in the course */} {/* NOTE: comment in this code when you get to this point in the course */}
{ <div className="bg-white px-6"> {
{latestInvoices.map((invoice, i) => { <div className="bg-white px-6">
return ( {latestInvoices.map((invoice, i) => {
<div return (
key={invoice.id} <div
className={clsx( key={invoice.id}
'flex flex-row items-center justify-between py-4', className={clsx(
{ "flex flex-row items-center justify-between py-4",
'border-t': i !== 0, {
}, "border-t": i !== 0,
)} },
> )}
<div className="flex items-center">
<Image
src={invoice.image_url}
alt={`${invoice.name}'s profile picture`}
className="mr-4 rounded-full"
width={32}
height={32}
/>
<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} <div className="flex items-center">
</p> <Image
</div> src={invoice.image_url}
); alt={`${invoice.name}'s profile picture`}
})} className="mr-4 rounded-full"
</div> } width={32}
height={32}
/>
<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"> <div className="flex items-center pb-2 pt-6">
<ArrowPathIcon className="h-5 w-5 text-gray-500" /> <ArrowPathIcon className="h-5 w-5 text-gray-500" />
<h3 className="ml-2 text-sm text-gray-500 ">Updated just now</h3> <h3 className="ml-2 text-sm text-gray-500 ">Updated just now</h3>
+14 -14
View File
@@ -1,29 +1,29 @@
'use client'; "use client";
import { import {
UserGroupIcon,
HomeIcon,
DocumentDuplicateIcon, DocumentDuplicateIcon,
} from '@heroicons/react/24/outline'; HomeIcon,
import Link from 'next/link'; UserGroupIcon,
import { usePathname } from 'next/navigation'; } from "@heroicons/react/24/outline";
import clsx from 'clsx'; import clsx from "clsx";
import Link from "next/link";
import { usePathname } from "next/navigation";
// Map of links to display in the side navigation. // Map of links to display in the side navigation.
// Depending on the size of the application, this would be stored in a database. // Depending on the size of the application, this would be stored in a database.
const links = [ const links = [
{ name: 'Home', href: '/dashboard', icon: HomeIcon }, { name: "Home", href: "/dashboard", icon: HomeIcon },
{ {
name: 'Invoices', name: "Invoices",
href: '/dashboard/invoices', href: "/dashboard/invoices",
icon: DocumentDuplicateIcon, icon: DocumentDuplicateIcon,
}, },
{ name: 'Customers', href: '/dashboard/customers', icon: UserGroupIcon }, { name: "Customers", href: "/dashboard/customers", icon: UserGroupIcon },
]; ];
export default function NavLinks() { export default function NavLinks() {
const pathname = usePathname(); const pathname = usePathname();
return ( return (
<> <>
{links.map((link) => { {links.map((link) => {
const LinkIcon = link.icon; const LinkIcon = link.icon;
@@ -32,9 +32,9 @@ return (
key={link.name} key={link.name}
href={link.href} href={link.href}
className={clsx( 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', "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, "bg-sky-100 text-blue-600": pathname === link.href,
}, },
)} )}
> >
+38 -33
View File
@@ -1,8 +1,7 @@
import { generateYAxis } from '@/app/lib/utils'; import { CalendarIcon } from "@heroicons/react/24/outline";
import { CalendarIcon } from '@heroicons/react/24/outline'; import { fetchRevenue } from "@/app/lib/data";
import { lusitana } from '@/app/ui/fonts'; import { generateYAxis } from "@/app/lib/utils";
import { Revenue } from '@/app/lib/definitions'; import { lusitana } from "@/app/ui/fonts";
import { fetchRevenue } from '@/app/lib/data';
// This component is representational only. // This component is representational only.
// For data visualization UI, check out: // For data visualization UI, check out:
@@ -10,7 +9,8 @@ import { fetchRevenue } from '@/app/lib/data';
// https://www.chartjs.org/ // https://www.chartjs.org/
// https://airbnb.io/visx/ // https://airbnb.io/visx/
export default async function RevenueChart() { // Make component async, remove the props export default async function RevenueChart() {
// Make component async, remove the props
const revenue = await fetchRevenue(); // Fetch data inside the component const revenue = await fetchRevenue(); // Fetch data inside the component
const chartHeight = 350; const chartHeight = 350;
@@ -29,36 +29,41 @@ export default async function RevenueChart() { // Make component async, remove t
</h2> </h2>
{/* NOTE: comment in this code when you get to this point in the course */} {/* NOTE: comment in this code when you get to this point in the course */}
{ <div className="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="rounded-xl bg-gray-50 p-4">
<div <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">
className="mb-6 hidden flex-col justify-between text-sm text-gray-400 sm:flex" <div
style={{ height: `${chartHeight}px` }} 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> {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>
<div className="flex items-center pb-2 pt-6">
{revenue.map((month) => ( <CalendarIcon className="h-5 w-5 text-gray-500" />
<div key={month.month} className="flex flex-col items-center gap-2"> <h3 className="ml-2 text-sm text-gray-500 ">Last 12 months</h3>
<div </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>
<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 ">Last 12 months</h3>
</div>
</div> }
</div> </div>
); );
} }
+11 -10
View File
@@ -1,9 +1,8 @@
import Link from 'next/link'; import { PowerIcon } from "@heroicons/react/24/outline";
import NavLinks from '@/app/ui/dashboard/nav-links'; import Link from "next/link";
import AcmeLogo from '@/app/ui/acme-logo'; import AcmeLogo from "@/app/ui/acme-logo";
import { PowerIcon } from '@heroicons/react/24/outline'; import NavLinks from "@/app/ui/dashboard/nav-links";
import { signOut } from '@/auth'; import { signOut } from "@/auth";
import { redirect } from 'next/navigation';
export default function SideNav() { export default function SideNav() {
return ( return (
@@ -19,10 +18,12 @@ export default function SideNav() {
<div className="flex grow flex-row justify-between space-x-2 md:flex-col md:space-x-0 md:space-y-2"> <div className="flex grow flex-row justify-between space-x-2 md:flex-col md:space-x-0 md:space-y-2">
<NavLinks /> <NavLinks />
<div className="hidden h-auto w-full grow rounded-md bg-gray-50 md:block"></div> <div className="hidden h-auto w-full grow rounded-md bg-gray-50 md:block"></div>
<form action={async () => { <form
'use server'; action={async () => {
await signOut(); "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"> <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" /> <PowerIcon className="w-6" />
<div className="hidden md:block">Sign Out</div> <div className="hidden md:block">Sign Out</div>
+4 -4
View File
@@ -1,8 +1,8 @@
import { Inter, Lusitana } from 'next/font/google'; import { Inter, Lusitana } from "next/font/google";
export const inter = Inter({ subsets: ['latin'] }); export const inter = Inter({ subsets: ["latin"] });
export const lusitana = Lusitana({ export const lusitana = Lusitana({
weight: ['400', '700'], weight: ["400", "700"],
subsets: ['latin'], subsets: ["latin"],
}); });
+3 -3
View File
@@ -2,17 +2,17 @@
@tailwind components; @tailwind components;
@tailwind utilities; @tailwind utilities;
input[type='number'] { input[type="number"] {
-moz-appearance: textfield; -moz-appearance: textfield;
appearance: textfield; appearance: textfield;
} }
input[type='number']::-webkit-inner-spin-button { input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none; -webkit-appearance: none;
margin: 0; margin: 0;
} }
input[type='number']::-webkit-outer-spin-button { input[type="number"]::-webkit-outer-spin-button {
-webkit-appearance: none; -webkit-appearance: none;
margin: 0; margin: 0;
} }
+5 -5
View File
@@ -1,6 +1,6 @@
import { clsx } from 'clsx'; import { clsx } from "clsx";
import Link from 'next/link'; import Link from "next/link";
import { lusitana } from '@/app/ui/fonts'; import { lusitana } from "@/app/ui/fonts";
interface Breadcrumb { interface Breadcrumb {
label: string; label: string;
@@ -15,13 +15,13 @@ export default function Breadcrumbs({
}) { }) {
return ( return (
<nav aria-label="Breadcrumb" className="mb-6 block"> <nav aria-label="Breadcrumb" className="mb-6 block">
<ol className={clsx(lusitana.className, 'flex text-xl md:text-2xl')}> <ol className={clsx(lusitana.className, "flex text-xl md:text-2xl")}>
{breadcrumbs.map((breadcrumb, index) => ( {breadcrumbs.map((breadcrumb, index) => (
<li <li
key={breadcrumb.href} key={breadcrumb.href}
aria-current={breadcrumb.active} aria-current={breadcrumb.active}
className={clsx( className={clsx(
breadcrumb.active ? 'text-gray-900' : 'text-gray-500', breadcrumb.active ? "text-gray-900" : "text-gray-500",
)} )}
> >
<Link href={breadcrumb.href}>{breadcrumb.label}</Link> <Link href={breadcrumb.href}>{breadcrumb.label}</Link>
+8 -7
View File
@@ -1,13 +1,13 @@
import { PencilIcon, PlusIcon, TrashIcon } from '@heroicons/react/24/outline'; import { PencilIcon, PlusIcon, TrashIcon } from "@heroicons/react/24/outline";
import Link from 'next/link'; import Link from "next/link";
import { deleteInvoice } from "@/app/lib/actions";
export function CreateInvoice() { export function CreateInvoice() {
return ( return (
<Link <Link
href="/dashboard/invoices/create" 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" 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>{' '} <span className="hidden md:block">Create Invoice</span>{" "}
<PlusIcon className="h-5 md:ml-4" /> <PlusIcon className="h-5 md:ml-4" />
</Link> </Link>
); );
@@ -16,7 +16,7 @@ export function CreateInvoice() {
export function UpdateInvoice({ id }: { id: string }) { export function UpdateInvoice({ id }: { id: string }) {
return ( return (
<Link <Link
href="/dashboard/invoices" href={`/dashboard/invoices/${id}/edit`}
className="rounded-md border p-2 hover:bg-gray-100" className="rounded-md border p-2 hover:bg-gray-100"
> >
<PencilIcon className="w-5" /> <PencilIcon className="w-5" />
@@ -25,12 +25,13 @@ export function UpdateInvoice({ id }: { id: string }) {
} }
export function DeleteInvoice({ id }: { id: string }) { export function DeleteInvoice({ id }: { id: string }) {
const deleteInvoiceWithId = deleteInvoice.bind(null, id);
return ( return (
<> <form action={deleteInvoiceWithId}>
<button className="rounded-md border p-2 hover:bg-gray-100"> <button className="rounded-md border p-2 hover:bg-gray-100">
<span className="sr-only">Delete</span> <span className="sr-only">Delete</span>
<TrashIcon className="w-5" /> <TrashIcon className="w-5" />
</button> </button>
</> </form>
); );
} }
+13 -16
View File
@@ -1,25 +1,23 @@
'use client'; "use client";
import { useFormState } from 'react-dom';
import { CustomerField } from '@/app/lib/definitions';
import Link from 'next/link';
import { import {
CheckIcon, CheckIcon,
ClockIcon, ClockIcon,
CurrencyDollarIcon, CurrencyDollarIcon,
UserCircleIcon, UserCircleIcon,
} from '@heroicons/react/24/outline'; } from "@heroicons/react/24/outline";
import { Button } from '../button'; import Link from "next/link";
import { createInvoice, State } from '@/app/lib/actions'; import { useFormState } from "react-dom";
import { useActionState } from 'react'; import { createInvoice } from "@/app/lib/actions";
import type { CustomerField } from "@/app/lib/definitions";
import { Button } from "../button";
export default function Form({ customers }: { customers: CustomerField[] }) { export default function Form({ customers }: { customers: CustomerField[] }) {
const initialState = { message: '', error: {} }; const initialState = { message: "", error: {} };
const [state, dispatch] = useFormState(createInvoice, initialState); const [state, dispatch] = useFormState(createInvoice, initialState);
return ( return (
<form action={dispatch}> <form action={dispatch}>
<div className="rounded-md bg-gray-50 p-4 md:p-6"> <div className="rounded-md bg-gray-50 p-4 md:p-6">
{/* Customer Name */} {/* Customer Name */}
<div className="mb-4"> <div className="mb-4">
@@ -46,11 +44,10 @@ const [state, dispatch] = useFormState(createInvoice, initialState);
<UserCircleIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500" /> <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"> <div id="customer-error" aria-live="polite" aria-atomic="true">
{state.errors?.customerId && {state.errors?.customerId?.map((error: string) => (
state.errors.customerId.map((error: string) => ( <p className="mt-2 text-sm text-red-500" key={error}>
<p className="mt-2 text-sm text-red-500" key={error}>
{error} {error}
</p> </p>
))} ))}
</div> </div>
</div> </div>
+7 -7
View File
@@ -1,14 +1,14 @@
'use client'; "use client";
import { CustomerField, InvoiceForm } from '@/app/lib/definitions';
import { import {
CheckIcon, CheckIcon,
ClockIcon, ClockIcon,
CurrencyDollarIcon, CurrencyDollarIcon,
UserCircleIcon, UserCircleIcon,
} from '@heroicons/react/24/outline'; } from "@heroicons/react/24/outline";
import Link from 'next/link'; import Link from "next/link";
import { Button } from '@/app/ui/button'; import type { CustomerField, InvoiceForm } from "@/app/lib/definitions";
import { Button } from "@/app/ui/button";
export default function EditInvoiceForm({ export default function EditInvoiceForm({
invoice, invoice,
@@ -80,7 +80,7 @@ export default function EditInvoiceForm({
name="status" name="status"
type="radio" type="radio"
value="pending" value="pending"
defaultChecked={invoice.status === 'pending'} defaultChecked={invoice.status === "pending"}
className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600" className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600"
/> />
<label <label
@@ -96,7 +96,7 @@ export default function EditInvoiceForm({
name="status" name="status"
type="radio" type="radio"
value="paid" value="paid"
defaultChecked={invoice.status === 'paid'} defaultChecked={invoice.status === "paid"}
className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600" className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600"
/> />
<label <label
+53 -56
View File
@@ -1,62 +1,59 @@
'use client'; "use client";
import { ArrowLeftIcon, ArrowRightIcon } from '@heroicons/react/24/outline'; import { ArrowLeftIcon, ArrowRightIcon } from "@heroicons/react/24/outline";
import clsx from 'clsx'; import clsx from "clsx";
import Link from 'next/link'; import Link from "next/link";
import { generatePagination } from '@/app/lib/utils'; import { usePathname, useSearchParams } from "next/navigation";
import { usePathname, useSearchParams } from 'next/navigation'; import { generatePagination } from "@/app/lib/utils";
export default function Pagination({ totalPages }: { totalPages: number }) { export default function Pagination({ totalPages }: { totalPages: number }) {
const pathname = usePathname(); const pathname = usePathname();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const currentPage = Number(searchParams.get('page')) || 1; const currentPage = Number(searchParams.get("page")) || 1;
const createPageURL = (pageNumber: number | string) => { const createPageURL = (pageNumber: number | string) => {
const params = new URLSearchParams(searchParams); const params = new URLSearchParams(searchParams);
params.set('page', pageNumber.toString()); params.set("page", pageNumber.toString());
return `${pathname}?${params.toString()}`; return `${pathname}?${params.toString()}`;
}; };
const allPages = generatePagination(currentPage, totalPages); const allPages = generatePagination(currentPage, totalPages);
return ( return (
<> <div className="inline-flex">
<PaginationArrow
direction="left"
href={createPageURL(currentPage - 1)}
isDisabled={currentPage <= 1}
/>
<div className="inline-flex"> <div className="flex -space-x-px">
<PaginationArrow {allPages.map((page, index) => {
direction="left" let position: "first" | "last" | "single" | "middle" | undefined;
href={createPageURL(currentPage - 1)}
isDisabled={currentPage <= 1}
/>
<div className="flex -space-x-px"> if (index === 0) position = "first";
{allPages.map((page, index) => { if (index === allPages.length - 1) position = "last";
let position: 'first' | 'last' | 'single' | 'middle' | undefined; if (allPages.length === 1) position = "single";
if (page === "...") position = "middle";
if (index === 0) position = 'first'; return (
if (index === allPages.length - 1) position = 'last'; <PaginationNumber
if (allPages.length === 1) position = 'single'; key={page}
if (page === '...') position = 'middle'; href={createPageURL(page)}
page={page}
return ( position={position}
<PaginationNumber isActive={currentPage === page}
key={page} />
href={createPageURL(page)} );
page={page} })}
position={position}
isActive={currentPage === page}
/>
);
})}
</div>
<PaginationArrow
direction="right"
href={createPageURL(currentPage + 1)}
isDisabled={currentPage >= totalPages}
/>
</div> </div>
</>
<PaginationArrow
direction="right"
href={createPageURL(currentPage + 1)}
isDisabled={currentPage >= totalPages}
/>
</div>
); );
} }
@@ -68,21 +65,21 @@ function PaginationNumber({
}: { }: {
page: number | string; page: number | string;
href: string; href: string;
position?: 'first' | 'last' | 'middle' | 'single'; position?: "first" | "last" | "middle" | "single";
isActive: boolean; isActive: boolean;
}) { }) {
const className = clsx( const className = clsx(
'flex h-10 w-10 items-center justify-center text-sm border', "flex h-10 w-10 items-center justify-center text-sm border",
{ {
'rounded-l-md': position === 'first' || position === 'single', "rounded-l-md": position === "first" || position === "single",
'rounded-r-md': position === 'last' || position === 'single', "rounded-r-md": position === "last" || position === "single",
'z-10 bg-blue-600 border-blue-600 text-white': isActive, "z-10 bg-blue-600 border-blue-600 text-white": isActive,
'hover:bg-gray-100': !isActive && position !== 'middle', "hover:bg-gray-100": !isActive && position !== "middle",
'text-gray-300': position === 'middle', "text-gray-300": position === "middle",
}, },
); );
return isActive || position === 'middle' ? ( return isActive || position === "middle" ? (
<div className={className}>{page}</div> <div className={className}>{page}</div>
) : ( ) : (
<Link href={href} className={className}> <Link href={href} className={className}>
@@ -97,21 +94,21 @@ function PaginationArrow({
isDisabled, isDisabled,
}: { }: {
href: string; href: string;
direction: 'left' | 'right'; direction: "left" | "right";
isDisabled?: boolean; isDisabled?: boolean;
}) { }) {
const className = clsx( const className = clsx(
'flex h-10 w-10 items-center justify-center rounded-md border', "flex h-10 w-10 items-center justify-center rounded-md border",
{ {
'pointer-events-none text-gray-300': isDisabled, "pointer-events-none text-gray-300": isDisabled,
'hover:bg-gray-100': !isDisabled, "hover:bg-gray-100": !isDisabled,
'mr-2 md:mr-4': direction === 'left', "mr-2 md:mr-4": direction === "left",
'ml-2 md:ml-4': direction === 'right', "ml-2 md:ml-4": direction === "right",
}, },
); );
const icon = const icon =
direction === 'left' ? ( direction === "left" ? (
<ArrowLeftIcon className="w-4" /> <ArrowLeftIcon className="w-4" />
) : ( ) : (
<ArrowRightIcon className="w-4" /> <ArrowRightIcon className="w-4" />
+7 -7
View File
@@ -1,24 +1,24 @@
import { CheckIcon, ClockIcon } from '@heroicons/react/24/outline'; import { CheckIcon, ClockIcon } from "@heroicons/react/24/outline";
import clsx from 'clsx'; import clsx from "clsx";
export default function InvoiceStatus({ status }: { status: string }) { export default function InvoiceStatus({ status }: { status: string }) {
return ( return (
<span <span
className={clsx( className={clsx(
'inline-flex items-center rounded-full px-2 py-1 text-xs', "inline-flex items-center rounded-full px-2 py-1 text-xs",
{ {
'bg-gray-100 text-gray-500': status === 'pending', "bg-gray-100 text-gray-500": status === "pending",
'bg-green-500 text-white': status === 'paid', "bg-green-500 text-white": status === "paid",
}, },
)} )}
> >
{status === 'pending' ? ( {status === "pending" ? (
<> <>
Pending Pending
<ClockIcon className="ml-1 w-4 text-gray-500" /> <ClockIcon className="ml-1 w-4 text-gray-500" />
</> </>
) : null} ) : null}
{status === 'paid' ? ( {status === "paid" ? (
<> <>
Paid Paid
<CheckIcon className="ml-1 w-4 text-white" /> <CheckIcon className="ml-1 w-4 text-white" />
+5 -5
View File
@@ -1,8 +1,8 @@
import Image from 'next/image'; import Image from "next/image";
import { UpdateInvoice, DeleteInvoice } from '@/app/ui/invoices/buttons'; import { fetchFilteredInvoices } from "@/app/lib/data";
import InvoiceStatus from '@/app/ui/invoices/status'; import { formatCurrency, formatDateToLocal } from "@/app/lib/utils";
import { formatDateToLocal, formatCurrency } from '@/app/lib/utils'; import { DeleteInvoice, UpdateInvoice } from "@/app/ui/invoices/buttons";
import { fetchFilteredInvoices } from '@/app/lib/data'; import InvoiceStatus from "@/app/ui/invoices/status";
export default async function InvoicesTable({ export default async function InvoicesTable({
query, query,
+17 -15
View File
@@ -1,19 +1,18 @@
'use client'; "use client";
import { lusitana } from '@/app/ui/fonts'; import { ArrowRightIcon } from "@heroicons/react/20/solid";
import { import {
AtSymbolIcon, AtSymbolIcon,
KeyIcon,
ExclamationCircleIcon, ExclamationCircleIcon,
} from '@heroicons/react/24/outline'; KeyIcon,
import { ArrowRightIcon } from '@heroicons/react/20/solid'; } from "@heroicons/react/24/outline";
import { Button } from './button'; import { useFormState, useFormStatus } from "react-dom";
import { useFormState, useFormStatus } from 'react-dom'; import { lusitana } from "@/app/ui/fonts";
import { authenticate } from '../lib/actions'; import { authenticate } from "../lib/actions";
import { Button } from "./button";
export default function LoginForm() { export default function LoginForm() {
const [errorMessage, dispatch] = useFormState(authenticate, undefined);
const [errorMessage, dispatch] = useFormState(authenticate, undefined)
return ( return (
<form action={dispatch} className="space-y-3"> <form action={dispatch} className="space-y-3">
<div className="flex-1 rounded-lg bg-gray-50 px-6 pb-4 pt-8"> <div className="flex-1 rounded-lg bg-gray-50 px-6 pb-4 pt-8">
@@ -62,15 +61,18 @@ export default function LoginForm() {
</div> </div>
</div> </div>
<LoginButton /> <LoginButton />
<div className="flex h-8 items-end space-x-1" aria-live='polite' aria-atomic='true'> <div
className="flex h-8 items-end space-x-1"
aria-live="polite"
aria-atomic="true"
>
{/* Add form errors here */} {/* Add form errors here */}
{errorMessage && ( {errorMessage && (
<> <>
<ExclamationCircleIcon className='h-5 w-5 text-red-500' /> <ExclamationCircleIcon className="h-5 w-5 text-red-500" />
<p className='text-sm text-red-500'>{errorMessage}</p> <p className="text-sm text-red-500">{errorMessage}</p>
</> </>
)} )}
</div> </div>
</div> </div>
</form> </form>
@@ -78,7 +80,7 @@ export default function LoginForm() {
} }
function LoginButton() { function LoginButton() {
const {pending} = useFormStatus() const { pending } = useFormStatus();
return ( return (
<Button className="mt-4 w-full" aria-disabled={pending}> <Button className="mt-4 w-full" aria-disabled={pending}>
Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" /> Log in <ArrowRightIcon className="ml-auto h-5 w-5 text-gray-50" />
+10 -11
View File
@@ -1,10 +1,10 @@
'use client'; "use client";
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline'; import { MagnifyingGlassIcon } from "@heroicons/react/24/outline";
import { useSearchParams, usePathname, useRouter } from 'next/navigation'; import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useDebouncedCallback } from 'use-debounce'; import { useDebouncedCallback } from "use-debounce";
var placeholder = ''; var placeholder = "";
export default function Search() { export default function Search() {
const searchParams = useSearchParams(); const searchParams = useSearchParams();
@@ -12,14 +12,13 @@ export default function Search() {
const { replace } = useRouter(); const { replace } = useRouter();
const handleSearch = useDebouncedCallback((term) => { const handleSearch = useDebouncedCallback((term) => {
console.log(`Searching... ${term}`); console.log(`Searching... ${term}`);
const params = new URLSearchParams(searchParams); const params = new URLSearchParams(searchParams);
params.set('page', '1'); params.set("page", "1");
if (term) { if (term) {
params.set('query', term); params.set("query", term);
} else { } else {
params.delete('query'); params.delete("query");
} }
replace(`${pathname}?${params.toString()}`); replace(`${pathname}?${params.toString()}`);
}, 300); }, 300);
@@ -34,8 +33,8 @@ export default function Search() {
onChange={(e) => { onChange={(e) => {
handleSearch(e.target.value); handleSearch(e.target.value);
}} }}
defaultValue={searchParams.get('query')?.toString()} 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" /> <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> </div>
); );
+1 -1
View File
@@ -1,6 +1,6 @@
// Loading animation // Loading animation
const shimmer = 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'; "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() { export function CardSkeleton() {
return ( return (
+4 -4
View File
@@ -1,18 +1,18 @@
import type { NextAuthConfig } from 'next-auth'; import type { NextAuthConfig } from "next-auth";
export const authConfig = { export const authConfig = {
pages: { pages: {
signIn: '/login', signIn: "/login",
}, },
callbacks: { callbacks: {
authorized({ auth, request: { nextUrl } }) { authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user; const isLoggedIn = !!auth?.user;
const isOnDashboard = nextUrl.pathname.startsWith('/dashboard'); const isOnDashboard = nextUrl.pathname.startsWith("/dashboard");
if (isOnDashboard) { if (isOnDashboard) {
if (isLoggedIn) return true; if (isLoggedIn) return true;
return false; // Redirect unauthenticated users to login page return false; // Redirect unauthenticated users to login page
} else if (isLoggedIn) { } else if (isLoggedIn) {
return Response.redirect(new URL('/dashboard', nextUrl)); return Response.redirect(new URL("/dashboard", nextUrl));
} }
return true; return true;
}, },
+11 -11
View File
@@ -1,20 +1,20 @@
import NextAuth from 'next-auth'; import bcrypt from "bcrypt";
import Credentials from 'next-auth/providers/credentials'; import NextAuth from "next-auth";
import { authConfig } from './auth.config'; import Credentials from "next-auth/providers/credentials";
import { z } from 'zod'; import postgres from "postgres";
import type { User } from '@/app/lib/definitions'; import { z } from "zod";
import bcrypt from 'bcrypt'; import type { User } from "@/app/lib/definitions";
import postgres from 'postgres'; import { authConfig } from "./auth.config";
const sql = postgres(process.env.POSTGRES_URL!, { ssl: 'require' }); const sql = postgres(process.env.POSTGRES_URL!, { ssl: "require" });
async function getUser(email: string): Promise<User | undefined> { async function getUser(email: string): Promise<User | undefined> {
try { try {
const user = await sql<User[]>`SELECT * FROM users WHERE email=${email}`; const user = await sql<User[]>`SELECT * FROM users WHERE email=${email}`;
return user[0]; return user[0];
} catch (error) { } catch (error) {
console.error('Failed to fetch user:', error); console.error("Failed to fetch user:", error);
throw new Error('Failed to fetch user.'); throw new Error("Failed to fetch user.");
} }
} }
@@ -36,7 +36,7 @@ export const { auth, signIn, signOut } = NextAuth({
if (passwordsMatch) return user; if (passwordsMatch) return user;
} }
console.log('Invalid credentials'); console.log("Invalid credentials");
return null; return null;
}, },
}), }),
+42
View File
@@ -0,0 +1,42 @@
{
"$schema": "https://biomejs.dev/schemas/2.4.15/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true
},
"files": {
"ignoreUnknown": false
},
"formatter": {
"enabled": true,
"indentStyle": "space"
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"style": {
"noNonNullAssertion": "off"
}
}
},
"css": {
"parser": {
"tailwindDirectives": true
}
},
"javascript": {
"formatter": {
"quoteStyle": "double"
}
},
"assist": {
"enabled": true,
"actions": {
"source": {
"organizeImports": "on"
}
}
}
}
-24
View File
@@ -1,24 +0,0 @@
import { defineConfig, globalIgnores } from 'eslint/config';
import nextVitals from 'eslint-config-next/core-web-vitals';
const eslintConfig = defineConfig([
...nextVitals,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
'.next/**',
'out/**',
'build/**',
'next-env.d.ts',
]),
{
settings: {
// Fix for ESLint 10+: eslint-plugin-react uses context.getFilename() (legacy API)
// which was removed in ESLint 10 flat config. Declaring the version explicitly
// prevents the plugin from trying to auto-detect it and failing.
react: { version: '19' },
},
},
]);
export default eslintConfig;
+1 -1
View File
@@ -1,4 +1,4 @@
import type { NextConfig } from 'next'; import type { NextConfig } from "next";
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
/* config options here */ /* config options here */
+1 -2
View File
@@ -24,12 +24,11 @@
"zod": "^3.25.17" "zod": "^3.25.17"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "^2.4.15",
"@types/bcrypt": "^5.0.2", "@types/bcrypt": "^5.0.2",
"@types/node": "22.10.7", "@types/node": "22.10.7",
"@types/react": "19.0.7", "@types/react": "19.0.7",
"@types/react-dom": "19.0.3", "@types/react-dom": "19.0.3",
"eslint": "^10.3.0",
"eslint-config-next": "^16.2.6",
"typescript": "5.7.3" "typescript": "5.7.3"
}, },
"pnpm": { "pnpm": {
+86 -2633
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -1,9 +1,9 @@
import NextAuth from 'next-auth'; import NextAuth from "next-auth";
import { authConfig } from './auth.config'; import { authConfig } from "./auth.config";
export default NextAuth(authConfig).auth; export default NextAuth(authConfig).auth;
export const config = { export const config = {
// https://nextjs.org/docs/app/api-reference/file-conventions/proxy#matcher // https://nextjs.org/docs/app/api-reference/file-conventions/proxy#matcher
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'], matcher: ["/((?!api|_next/static|_next/image|.*\\.png$).*)"],
}; };
+11 -11
View File
@@ -1,32 +1,32 @@
import type { Config } from 'tailwindcss'; import type { Config } from "tailwindcss";
const config: Config = { const config: Config = {
content: [ content: [
'./pages/**/*.{js,ts,jsx,tsx,mdx}', "./pages/**/*.{js,ts,jsx,tsx,mdx}",
'./components/**/*.{js,ts,jsx,tsx,mdx}', "./components/**/*.{js,ts,jsx,tsx,mdx}",
'./app/**/*.{js,ts,jsx,tsx,mdx}', "./app/**/*.{js,ts,jsx,tsx,mdx}",
], ],
theme: { theme: {
extend: { extend: {
gridTemplateColumns: { gridTemplateColumns: {
'13': 'repeat(13, minmax(0, 1fr))', "13": "repeat(13, minmax(0, 1fr))",
}, },
colors: { colors: {
blue: { blue: {
400: '#2589FE', 400: "#2589FE",
500: '#0070F3', 500: "#0070F3",
600: '#2F6FEB', 600: "#2F6FEB",
}, },
}, },
}, },
keyframes: { keyframes: {
shimmer: { shimmer: {
'100%': { "100%": {
transform: 'translateX(100%)', transform: "translateX(100%)",
}, },
}, },
}, },
}, },
plugins: [require('@tailwindcss/forms')], plugins: [require("@tailwindcss/forms")],
}; };
export default config; export default config;
+3 -11
View File
@@ -1,11 +1,7 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2017", "target": "ES2017",
"lib": [ "lib": ["dom", "dom.iterable", "esnext"],
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
"strict": true, "strict": true,
@@ -23,9 +19,7 @@
} }
], ],
"paths": { "paths": {
"@/*": [ "@/*": ["./*"]
"./*"
]
} }
}, },
"include": [ "include": [
@@ -37,7 +31,5 @@
"scripts/seed.js", "scripts/seed.js",
".next/dev/types/**/*.ts" ".next/dev/types/**/*.ts"
], ],
"exclude": [ "exclude": ["node_modules"]
"node_modules"
]
} }