Compare commits

...

10 Commits

Author SHA1 Message Date
teodors e3f3e62482 update 2026-05-12 17:35:38 +03:00
teodors d9ffcb4b92 leilo5 2026-05-11 20:40:21 +03:00
teodors d2d22799b6 leilo4 2026-05-11 18:41:21 +03:00
teodors 9c8b4148bb leilo3 2026-05-11 18:38:14 +03:00
teodors 0298a73e8d leilo2 2026-05-11 18:28:23 +03:00
teodors a50e525de1 leilo 2026-05-11 17:51:47 +03:00
teodors 922cc1bcfc Le4 2026-04-29 12:21:25 +03:00
teodors cde1785fc5 Le3 2026-04-29 11:55:34 +03:00
teodors f9c509e62a Le2 2026-04-29 11:35:45 +03:00
teodors 9d43c1068c Le1 2026-04-29 11:11:18 +03:00
51 changed files with 13660 additions and 603 deletions
+5
View File
@@ -0,0 +1,5 @@
import DashboardSkeleton from "@/app/ui/skeletons";
export default function Loading() {
return <DashboardSkeleton />;
}
+38
View File
@@ -0,0 +1,38 @@
import type { Metadata } from "next";
import { Suspense } from "react";
import CardWrapper from "@/app/ui/dashboard/cards";
import LatestInvoices from "@/app/ui/dashboard/latest-invoices";
import RevenueChart from "@/app/ui/dashboard/revenue-chart";
import { lusitana } from "@/app/ui/fonts";
import {
CardSkeleton,
LatestInvoicesSkeleton,
RevenueChartSkeleton,
} from "@/app/ui/skeletons";
export const metadata: Metadata = {
title: "Dashboard",
};
export default async function Page() {
return (
<main>
<h1 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}>
Dashboard
</h1>
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
<Suspense fallback={<CardSkeleton />}>
<CardWrapper />
</Suspense>
</div>
<div className="mt-6 grid grid-cols-1 gap-6 md:grid-cols-4 lg:grid-cols-8">
<Suspense fallback={<RevenueChartSkeleton />}>
<RevenueChart />
</Suspense>
<Suspense fallback={<LatestInvoicesSkeleton />}>
<LatestInvoices />
</Suspense>
</div>
</main>
);
}
+6
View File
@@ -1,3 +1,9 @@
export default function Page() { export default function Page() {
return <p>Customers Page</p>; return <p>Customers Page</p>;
} }
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "Customers",
};
@@ -0,0 +1,18 @@
import { FaceFrownIcon } from "@heroicons/react/24/outline";
import Link from "next/link";
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>
);
}
+38
View File
@@ -0,0 +1,38 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { fetchCustomers, fetchInvoiceById } from "@/app/lib/data";
import Breadcrumbs from "@/app/ui/invoices/breadcrumbs";
import Form from "@/app/ui/invoices/edit-form";
export const metadata: Metadata = {
title: "Edit invoices",
};
export default async function Page(props: { params: Promise<{ id: string }> }) {
const params = await props.params;
const id = params.id;
const [invoice, customers] = await Promise.all([
fetchInvoiceById(id),
fetchCustomers(),
]);
if (!invoice) {
notFound();
}
return (
<main>
<Breadcrumbs
breadcrumbs={[
{ label: "Invoices", href: "/dashboard/invoices" },
{
label: "Edit Invoice",
href: `/dashboard/invoices/${id}/edit`,
active: true,
},
]}
/>
<Form invoice={invoice} customers={customers} />
</main>
);
}
+28
View File
@@ -0,0 +1,28 @@
import type { Metadata } from "next";
import { fetchCustomers } from "@/app/lib/data";
import Breadcrumbs from "@/app/ui/invoices/breadcrumbs";
import Form from "@/app/ui/invoices/create-form";
export const metadata: Metadata = {
title: "Create invoices",
};
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
View File
@@ -0,0 +1,31 @@
"use client";
import { useEffect } from "react";
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
// Optionally log the error to an error reporting service
console.error(error);
}, [error]);
return (
<main className="flex h-full flex-col items-center justify-center">
<h2 className="text-center">Something went wrong!</h2>
<button
className="mt-4 rounded-md bg-blue-500 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-400"
onClick={
// Attempt to recover by trying to re-render the invoices route
() => reset()
}
>
Try again
</button>
</main>
);
}
+42 -2
View File
@@ -1,3 +1,43 @@
export default function Page() { import type { Metadata } from "next";
return <p>Invoices Page</p>; import { Suspense } from "react";
import { fetchInvoicesPages } from "@/app/lib/data";
import { lusitana } from "@/app/ui/fonts";
import { CreateInvoice } from "@/app/ui/invoices/buttons";
import Pagination from "@/app/ui/invoices/pagination";
import Table from "@/app/ui/invoices/table";
import Search from "@/app/ui/search";
import { InvoicesTableSkeleton } from "@/app/ui/skeletons";
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 {...Search} />
<CreateInvoice />
</div>
<Suspense key={query + currentPage} fallback={<InvoicesTableSkeleton />}>
<Table query={query} currentPage={currentPage} />
</Suspense>
<div className="mt-5 flex w-full justify-center">
<Pagination totalPages={totalPages} />
</div>
</div>
);
} }
+1 -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 (
-3
View File
@@ -1,3 +0,0 @@
export default function Page() {
return <p>Dashboard Page</p>;
}
+12 -2
View File
@@ -1,5 +1,15 @@
import '@/app/ui/global.css'; import "@/app/ui/global.css";
import { inter } from '@/app/ui/fonts'; import type { Metadata } from "next";
import { inter } from "@/app/ui/fonts";
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({ export default function RootLayout({
children, children,
+139
View File
@@ -0,0 +1,139 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { AuthError } from "next-auth";
import postgres from "postgres";
import { z } from "zod";
import { signIn } from "@/auth";
const sql = postgres(process.env.POSTGRES_URL!, { ssl: "require" });
const FormSchema = z.object({
id: z.string(),
customerId: z.string({
invalid_type_error: "Please select a customer",
}),
amount: z.coerce
.number()
.gt(0, { message: "Please enter an amount greater than $0." }),
status: z.enum(["pending", "paid"], {
invalid_type_error: "Please select an invoice status. ",
}),
date: z.string(),
});
const CreateInvoice = FormSchema.omit({ id: true, date: true });
const UpdateInvoice = FormSchema.omit({ id: true, date: true });
export type State = {
errors?: {
customerId?: string[];
amount?: string[];
status?: string[];
};
message?: string | null;
};
export async function createInvoice(_prevState: State, formData: FormData) {
const validateFields = CreateInvoice.safeParse({
customerId: formData.get("customerId"),
amount: formData.get("amount"),
status: formData.get("status"),
});
if (!validateFields.success) {
return {
errors: validateFields.error.flatten().fieldErrors,
message: "Missing Fields. Failed to Create Invoice. ",
};
}
const { customerId, amount, status } = validateFields.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 (_error) {
return {
message: "Database Error: Failed to Create Invoice.",
};
}
revalidatePath("/dashboard/invoices");
redirect("/dashboard/invoices");
}
export async function updateInvoice(
id: string,
_prevState: State,
formData: FormData,
) {
const validateFields = UpdateInvoice.safeParse({
customerId: formData.get("customerId"),
amount: formData.get("amount"),
status: formData.get("status"),
});
if (!validateFields.success) {
return {
errors: validateFields.error.flatten().fieldErrors,
message: "Missing Fields. Failed to update Invoice",
};
}
const { amount, customerId, status } = validateFields.data;
const amountInCents = amount * 100;
try {
await sql`
UPDATE invoices
SET customer_id = ${customerId}, amount = ${amountInCents}, status = ${status}
WHERE id = ${id}
`;
} catch (_error) {
return {
message: "Database Failed: Error while updating the Invoice",
};
}
revalidatePath("/dashboard/invoices");
redirect("/dashboard/invoices");
}
export async function deleteInvoice(id: string) {
// throw new Error('Failed to Delete Invoice. ')
try {
await sql`
DELETE FROM invoices
WHERE id = ${id}
`;
revalidatePath("/dashboard/invoices");
return { message: "Deleted Invoice. " };
} catch (_error) {
return {
message: "Database Error: Failed while deleting record from Invoice. ",
};
}
}
export async function authenticate(
_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;
}
}
+45 -43
View File
@@ -1,15 +1,16 @@
import { sql } from '@neondatabase/serverless'; 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";
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,37 +19,37 @@ 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 = await 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.rows; 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.");
} }
} }
export async function fetchLatestInvoices() { export async function fetchLatestInvoices() {
try { try {
const data = await sql<LatestInvoiceRaw>` const data = await sql<LatestInvoiceRaw[]>`
SELECT invoices.amount, customers.name, customers.image_url, customers.email, invoices.id SELECT invoices.amount, customers.name, customers.image_url, customers.email, invoices.id
FROM invoices FROM invoices
JOIN customers ON invoices.customer_id = customers.id JOIN customers ON invoices.customer_id = customers.id
ORDER BY invoices.date DESC ORDER BY invoices.date DESC
LIMIT 5`; LIMIT 5`;
const latestInvoices = data.rows.map((invoice) => ({ const latestInvoices = data.map((invoice) => ({
...invoice, ...invoice,
amount: formatCurrency(invoice.amount), amount: formatCurrency(invoice.amount),
})); }));
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].rows[0].count ?? '0'); const numberOfInvoices = Number(data[0][0].count ?? "0");
const numberOfCustomers = Number(data[1].rows[0].count ?? '0'); const numberOfCustomers = Number(data[1][0].count ?? "0");
const totalPaidInvoices = formatCurrency(data[2].rows[0].paid ?? '0'); const totalPaidInvoices = formatCurrency(data[2][0].paid ?? "0");
const totalPendingInvoices = formatCurrency(data[2].rows[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.");
} }
} }
@@ -95,7 +96,7 @@ export async function fetchFilteredInvoices(
const offset = (currentPage - 1) * ITEMS_PER_PAGE; const offset = (currentPage - 1) * ITEMS_PER_PAGE;
try { try {
const invoices = await sql<InvoicesTable>` const invoices = await sql<InvoicesTable[]>`
SELECT SELECT
invoices.id, invoices.id,
invoices.amount, invoices.amount,
@@ -116,10 +117,10 @@ export async function fetchFilteredInvoices(
LIMIT ${ITEMS_PER_PAGE} OFFSET ${offset} LIMIT ${ITEMS_PER_PAGE} OFFSET ${offset}
`; `;
return invoices.rows; 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.");
} }
} }
@@ -136,17 +137,17 @@ export async function fetchInvoicesPages(query: string) {
invoices.status ILIKE ${`%${query}%`} invoices.status ILIKE ${`%${query}%`}
`; `;
const totalPages = Math.ceil(Number(count.rows[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.");
} }
} }
export async function fetchInvoiceById(id: string) { export async function fetchInvoiceById(id: string) {
try { try {
const data = await sql<InvoiceForm>` const data = await sql<InvoiceForm[]>`
SELECT SELECT
invoices.id, invoices.id,
invoices.customer_id, invoices.customer_id,
@@ -156,21 +157,22 @@ export async function fetchInvoiceById(id: string) {
WHERE invoices.id = ${id}; WHERE invoices.id = ${id};
`; `;
const invoice = data.rows.map((invoice) => ({ const invoice = data.map((invoice) => ({
...invoice, ...invoice,
// Convert amount from cents to dollars // Convert amount from cents to dollars
amount: invoice.amount / 100, amount: invoice.amount / 100,
})); }));
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);
} }
} }
export async function fetchCustomers() { export async function fetchCustomers() {
try { try {
const data = await sql<CustomerField>` const data = await sql<CustomerField[]>`
SELECT SELECT
id, id,
name name
@@ -178,17 +180,17 @@ export async function fetchCustomers() {
ORDER BY name ASC ORDER BY name ASC
`; `;
const customers = data.rows; 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.");
} }
} }
export async function fetchFilteredCustomers(query: string) { export async function fetchFilteredCustomers(query: string) {
try { try {
const data = await sql<CustomersTable>` const data = await sql<CustomersTable[]>`
SELECT SELECT
customers.id, customers.id,
customers.name, customers.name,
@@ -206,7 +208,7 @@ export async function fetchFilteredCustomers(query: string) {
ORDER BY customers.name ASC ORDER BY customers.name ASC
`; `;
const customers = data.rows.map((customer) => ({ const customers = data.map((customer) => ({
...customer, ...customer,
total_pending: formatCurrency(customer.total_pending), total_pending: formatCurrency(customer.total_pending),
total_paid: formatCurrency(customer.total_paid), total_paid: formatCurrency(customer.total_paid),
@@ -214,17 +216,17 @@ 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.");
} }
} }
export async function getUser(email: string) { export async function getUser(email: string) {
try { try {
const user = await sql`SELECT * from USERS where email=${email}`; const user = await sql`SELECT * from USERS where email=${email}`;
return user.rows[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,
]; ];
}; };
+25
View File
@@ -0,0 +1,25 @@
import type { Metadata } from "next";
import { Suspense } from "react";
import AcmeLogo from "@/app/ui/acme-logo";
import LoginForm from "@/app/ui/login-form";
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>
<Suspense>
<LoginForm />
</Suspense>
</div>
</main>
);
}
+6 -6
View File
@@ -1,8 +1,8 @@
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">
@@ -16,7 +16,7 @@ export default function Page() {
<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>
+17 -23
View File
@@ -1,26 +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() {
try {
export async function GET() { return Response.json(await listInvoices());
return Response.json({ } catch (error) {
message: return Response.json({ error }, { status: 500 });
'Uncomment this file and remove this line. You can delete this file when you are finished.', }
});
// try {
// return Response.json(await listInvoices());
// } catch (error) {
// 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,
)} )}
> >
+6 -7
View File
@@ -1,9 +1,8 @@
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,
}: { }: {
customers: FormattedCustomersTable[]; customers: FormattedCustomersTable[];
@@ -13,7 +12,7 @@ export default async function CustomersTable({
<h1 className={`${lusitana.className} mb-8 text-xl md:text-2xl`}> <h1 className={`${lusitana.className} mb-8 text-xl md:text-2xl`}>
Customers Customers
</h1> </h1>
<Search placeholder="Search customers..." /> <Search {...Search} />
<div className="mt-6 flow-root"> <div className="mt-6 flow-root">
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<div className="inline-block min-w-full align-middle"> <div className="inline-block min-w-full align-middle">
+15 -9
View File
@@ -1,10 +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 { lusitana } from "@/app/ui/fonts";
const iconMap = { const iconMap = {
collected: BanknotesIcon, collected: BanknotesIcon,
@@ -13,19 +14,24 @@ const iconMap = {
invoices: InboxIcon, invoices: InboxIcon,
}; };
export default async function Cards() { export default async function CardWrapper() {
const {
numberOfInvoices,
numberOfCustomers,
totalPaidInvoices,
totalPendingInvoices,
} = await fetchCardData();
return ( return (
<> <>
{/* NOTE: comment in this code when you get to this point in the course */} <Card title="Collected" value={totalPaidInvoices} type="collected" />
{/* <Card title="Collected" value={totalPaidInvoices} type="collected" />
<Card title="Pending" value={totalPendingInvoices} type="pending" /> <Card title="Pending" value={totalPendingInvoices} type="pending" />
<Card title="Total Invoices" value={numberOfInvoices} type="invoices" /> <Card title="Total Invoices" value={numberOfInvoices} type="invoices" />
<Card <Card
title="Total Customers" title="Total Customers"
value={numberOfCustomers} value={numberOfCustomers}
type="customers" type="customers"
/> */} />
</> </>
); );
} }
@@ -37,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];
+16 -14
View File
@@ -1,13 +1,13 @@
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";
export default async function LatestInvoices({
latestInvoices, export default async function LatestInvoices() {
}: { // Remove props
latestInvoices: LatestInvoice[]; const latestInvoices = await fetchLatestInvoices();
}) {
return ( return (
<div className="flex w-full flex-col md:col-span-4 lg:col-span-4"> <div className="flex w-full flex-col md:col-span-4 lg:col-span-4">
<h2 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}> <h2 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}>
@@ -16,15 +16,16 @@ export default async function LatestInvoices({
<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"> {
<div className="bg-white px-6">
{latestInvoices.map((invoice, i) => { {latestInvoices.map((invoice, i) => {
return ( return (
<div <div
key={invoice.id} key={invoice.id}
className={clsx( className={clsx(
'flex flex-row items-center justify-between py-4', "flex flex-row items-center justify-between py-4",
{ {
'border-t': i !== 0, "border-t": i !== 0,
}, },
)} )}
> >
@@ -53,7 +54,8 @@ export default async function LatestInvoices({
</div> </div>
); );
})} })}
</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,
}, },
)} )}
> >
+21 -17
View File
@@ -1,7 +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";
// This component is representational only. // This component is representational only.
// For data visualization UI, check out: // For data visualization UI, check out:
@@ -9,19 +9,18 @@ import { Revenue } from '@/app/lib/definitions';
// https://www.chartjs.org/ // https://www.chartjs.org/
// https://airbnb.io/visx/ // https://airbnb.io/visx/
export default async function RevenueChart({ export default async function RevenueChart() {
revenue, // Make component async, remove the props
}: { const revenue = await fetchRevenue(); // Fetch data inside the component
revenue: Revenue[];
}) {
const chartHeight = 350; const chartHeight = 350;
// NOTE: comment in this code when you get to this point in the course //NOTE: comment in this code when you get to this point in the course
// const { yAxisLabels, topLabel } = generateYAxis(revenue); const { yAxisLabels, topLabel } = generateYAxis(revenue);
// if (!revenue || revenue.length === 0) { if (!revenue || revenue.length === 0) {
// return <p className="mt-4 text-gray-400">No data available.</p>; return <p className="mt-4 text-gray-400">No data available.</p>;
// } }
return ( return (
<div className="w-full md:col-span-4"> <div className="w-full md:col-span-4">
@@ -30,7 +29,8 @@ export default async function RevenueChart({
</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="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="sm:grid-cols-13 mt-0 grid grid-cols-12 items-end gap-2 rounded-md bg-white p-4 md:gap-4">
<div <div
className="mb-6 hidden flex-col justify-between text-sm text-gray-400 sm:flex" className="mb-6 hidden flex-col justify-between text-sm text-gray-400 sm:flex"
@@ -42,7 +42,10 @@ export default async function RevenueChart({
</div> </div>
{revenue.map((month) => ( {revenue.map((month) => (
<div key={month.month} className="flex flex-col items-center gap-2"> <div
key={month.month}
className="flex flex-col items-center gap-2"
>
<div <div
className="w-full rounded-md bg-blue-300" className="w-full rounded-md bg-blue-300"
style={{ style={{
@@ -59,7 +62,8 @@ export default async function RevenueChart({
<CalendarIcon className="h-5 w-5 text-gray-500" /> <CalendarIcon className="h-5 w-5 text-gray-500" />
<h3 className="ml-2 text-sm text-gray-500 ">Last 12 months</h3> <h3 className="ml-2 text-sm text-gray-500 ">Last 12 months</h3>
</div> </div>
</div> */} </div>
}
</div> </div>
); );
} }
+12 -6
View File
@@ -1,7 +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";
export default function SideNav() { export default function SideNav() {
return ( return (
@@ -17,8 +18,13 @@ 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> <form
<button className="flex h-[48px] grow items-center justify-center gap-2 rounded-md bg-gray-50 p-3 text-sm font-medium hover:bg-sky-100 hover:text-blue-600 md:flex-none md:justify-start md:p-2 md:px-3"> action={async () => {
"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" /> <PowerIcon className="w-6" />
<div className="hidden md:block">Sign Out</div> <div className="hidden md:block">Sign Out</div>
</button> </button>
+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>
); );
} }
+19 -6
View File
@@ -1,18 +1,23 @@
'use client'; "use client";
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 { useFormState } from "react-dom";
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 [state, dispatch] = useFormState(createInvoice, initialState);
return ( return (
<form> <form action={dispatch}>
<div className="rounded-md bg-gray-50 p-4 md:p-6"> <div className="rounded-md bg-gray-50 p-4 md:p-6">
{/* Customer Name */} {/* Customer Name */}
<div className="mb-4"> <div className="mb-4">
@@ -25,6 +30,7 @@ export default function Form({ customers }: { customers: CustomerField[] }) {
name="customerId" name="customerId"
className="peer block w-full rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500" className="peer block w-full rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500"
defaultValue="" defaultValue=""
aria-describedby="customer-error"
> >
<option value="" disabled> <option value="" disabled>
Select a customer Select a customer
@@ -37,6 +43,13 @@ export default function Form({ customers }: { customers: CustomerField[] }) {
</select> </select>
<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">
{state.errors?.customerId?.map((error: string) => (
<p className="mt-2 text-sm text-red-500" key={error}>
{error}
</p>
))}
</div>
</div> </div>
{/* Invoice Amount */} {/* Invoice Amount */}
+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
+38 -33
View File
@@ -1,20 +1,26 @@
'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 { generatePagination } from "@/app/lib/utils";
export default function Pagination({ totalPages }: { totalPages: number }) { export default function Pagination({ totalPages }: { totalPages: number }) {
// NOTE: comment in this code when you get to this point in the course const pathname = usePathname();
const searchParams = useSearchParams();
const currentPage = Number(searchParams.get("page")) || 1;
// const allPages = generatePagination(currentPage, totalPages); const createPageURL = (pageNumber: number | string) => {
const params = new URLSearchParams(searchParams);
params.set("page", pageNumber.toString());
return `${pathname}?${params.toString()}`;
};
const allPages = generatePagination(currentPage, totalPages);
return ( return (
<> <div className="inline-flex">
{/* NOTE: comment in this code when you get to this point in the course */}
{/* <div className="inline-flex">
<PaginationArrow <PaginationArrow
direction="left" direction="left"
href={createPageURL(currentPage - 1)} href={createPageURL(currentPage - 1)}
@@ -23,12 +29,12 @@ export default function Pagination({ totalPages }: { totalPages: number }) {
<div className="flex -space-x-px"> <div className="flex -space-x-px">
{allPages.map((page, index) => { {allPages.map((page, index) => {
let position: 'first' | 'last' | 'single' | 'middle' | undefined; let position: "first" | "last" | "single" | "middle" | undefined;
if (index === 0) position = 'first'; if (index === 0) position = "first";
if (index === allPages.length - 1) position = 'last'; if (index === allPages.length - 1) position = "last";
if (allPages.length === 1) position = 'single'; if (allPages.length === 1) position = "single";
if (page === '...') position = 'middle'; if (page === "...") position = "middle";
return ( return (
<PaginationNumber <PaginationNumber
@@ -47,8 +53,7 @@ export default function Pagination({ totalPages }: { totalPages: number }) {
href={createPageURL(currentPage + 1)} href={createPageURL(currentPage + 1)}
isDisabled={currentPage >= totalPages} isDisabled={currentPage >= totalPages}
/> />
</div> */} </div>
</>
); );
} }
@@ -60,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}>
@@ -89,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,
+24 -8
View File
@@ -1,15 +1,20 @@
import { lusitana } from '@/app/ui/fonts'; "use client";
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 { lusitana } from "@/app/ui/fonts";
import { authenticate } from "../lib/actions";
import { Button } from "./button";
export default function LoginForm() { export default function LoginForm() {
const [errorMessage, dispatch] = useFormState(authenticate, undefined);
return ( return (
<form 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">
<h1 className={`${lusitana.className} mb-3 text-2xl`}> <h1 className={`${lusitana.className} mb-3 text-2xl`}>
Please log in to continue. Please log in to continue.
@@ -56,8 +61,18 @@ export default function LoginForm() {
</div> </div>
</div> </div>
<LoginButton /> <LoginButton />
<div className="flex h-8 items-end space-x-1"> <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 && (
<>
<ExclamationCircleIcon className="h-5 w-5 text-red-500" />
<p className="text-sm text-red-500">{errorMessage}</p>
</>
)}
</div> </div>
</div> </div>
</form> </form>
@@ -65,8 +80,9 @@ export default function LoginForm() {
} }
function LoginButton() { function LoginButton() {
const { pending } = useFormStatus();
return ( return (
<Button className="mt-4 w-full"> <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" />
</Button> </Button>
); );
+26 -3
View File
@@ -1,8 +1,27 @@
'use client'; "use client";
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline'; 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 }) { var placeholder = "";
export default function Search() {
const searchParams = useSearchParams();
const pathname = usePathname();
const { replace } = useRouter();
const handleSearch = useDebouncedCallback((term) => {
console.log(`Searching... ${term}`);
const params = new URLSearchParams(searchParams);
params.set("page", "1");
if (term) {
params.set("query", term);
} else {
params.delete("query");
}
replace(`${pathname}?${params.toString()}`);
}, 300);
return ( return (
<div className="relative flex flex-1 flex-shrink-0"> <div className="relative flex flex-1 flex-shrink-0">
<label htmlFor="search" className="sr-only"> <label htmlFor="search" className="sr-only">
@@ -11,6 +30,10 @@ export default function Search({ placeholder }: { placeholder: string }) {
<input <input
className="peer block w-full rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500" 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} 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" /> <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 (
+21
View 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;
+44
View File
@@ -0,0 +1,44 @@
import bcrypt from "bcrypt";
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import postgres from "postgres";
import { z } from "zod";
import type { User } from "@/app/lib/definitions";
import { authConfig } from "./auth.config";
const sql = postgres(process.env.POSTGRES_URL!, { ssl: "require" });
async function getUser(email: string): Promise<User | undefined> {
try {
const user = await sql<User[]>`SELECT * FROM users WHERE email=${email}`;
return user[0];
} catch (error) {
console.error("Failed to fetch user:", error);
throw new Error("Failed to fetch user.");
}
}
export const { auth, signIn, signOut } = NextAuth({
...authConfig,
providers: [
Credentials({
async authorize(credentials) {
const parsedCredentials = z
.object({ email: z.string().email(), password: z.string().min(6) })
.safeParse(credentials);
if (parsedCredentials.success) {
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;
},
}),
],
});
+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"
}
}
}
}
+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 */
+10527
View File
File diff suppressed because it is too large Load Diff
+7 -4
View File
@@ -3,30 +3,33 @@
"scripts": { "scripts": {
"build": "next build", "build": "next build",
"dev": "next dev --turbopack", "dev": "next dev --turbopack",
"start": "next start" "start": "next start",
"lint": "eslint ."
}, },
"dependencies": { "dependencies": {
"@heroicons/react": "^2.2.0", "@heroicons/react": "^2.2.0",
"@tailwindcss/forms": "^0.5.10", "@tailwindcss/forms": "^0.5.10",
"autoprefixer": "10.4.20", "autoprefixer": "10.4.20",
"babel": "^5.8.38",
"bcrypt": "^5.1.1", "bcrypt": "^5.1.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"next": "latest", "next": "latest",
"next-auth": "5.0.0-beta.25", "next-auth": "5.0.0-beta.31",
"postcss": "8.5.1", "postcss": "8.5.1",
"postgres": "^3.4.6", "postgres": "^3.4.6",
"react": "latest", "react": "latest",
"react-dom": "latest", "react-dom": "latest",
"tailwindcss": "3.4.17", "tailwindcss": "3.4.17",
"typescript": "5.7.3",
"use-debounce": "^10.0.4", "use-debounce": "^10.0.4",
"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",
"typescript": "5.7.3"
}, },
"pnpm": { "pnpm": {
"onlyBuiltDependencies": [ "onlyBuiltDependencies": [
+2009 -44
View File
File diff suppressed because it is too large Load Diff
+9
View File
@@ -0,0 +1,9 @@
import NextAuth from "next-auth";
import { authConfig } from "./auth.config";
export default NextAuth(authConfig).auth;
export const config = {
// https://nextjs.org/docs/app/api-reference/file-conventions/proxy#matcher
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;