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

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

View file

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

View file

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

View file

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

View file

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

View file

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

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

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

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

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

View file

@ -1,7 +1,8 @@
import Link from 'next/link';
import NavLinks from '@/app/ui/dashboard/nav-links';
import AcmeLogo from '@/app/ui/acme-logo';
import { PowerIcon } from '@heroicons/react/24/outline';
import Link from "next/link";
import NavLinks from "@/app/ui/dashboard/nav-links";
import AcmeLogo from "@/app/ui/acme-logo";
import { PowerIcon } from "@heroicons/react/24/outline";
import { signOut } from "@/auth";
export default function SideNav() {
return (
@ -17,7 +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">
<NavLinks />
<div className="hidden h-auto w-full grow rounded-md bg-gray-50 md:block"></div>
<form>
<form
action={async () => {
"use server";
await signOut();
}}
>
<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">
<PowerIcon className="w-6" />
<div className="hidden md:block">Sign Out</div>

View file

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

View file

@ -1,6 +1,6 @@
'use client';
import { CustomerField } from '@/app/lib/definitions';
import { useFormState } from 'react-dom';
import Link from 'next/link';
import {
CheckIcon,
@ -9,10 +9,19 @@ import {
UserCircleIcon,
} from '@heroicons/react/24/outline';
import { Button } from '../button';
import { CustomerField } from '@/app/lib/definitions';
import { createInvoice } from '@/app/lib/actions';
export default function Form({ customers }: { customers: CustomerField[] }) {
const initialState = {
message: null,
errors: {}
};
const [state, dispatch] = useFormState(createInvoice, initialState);
console.log('state', state);
return (
<form>
<form action={dispatch}>
<div className="rounded-md bg-gray-50 p-4 md:p-6">
{/* Customer Name */}
<div className="mb-4">
@ -25,6 +34,7 @@ export default function Form({ customers }: { customers: CustomerField[] }) {
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"
defaultValue=""
aria-describedby="customer-error"
>
<option value="" disabled>
Select a customer
@ -37,6 +47,17 @@ export default function Form({ customers }: { customers: CustomerField[] }) {
</select>
<UserCircleIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500" />
</div>
{state.errors?.customerId ? (
<div
id="customer-error"
aria-live="polite"
className="mt-2 text-sm text-red-500"
>
{state.errors.customerId.map((error: string) => (
<p key={error}>{error}</p>
))}
</div>
) : null}
</div>
{/* Invoice Amount */}
@ -53,11 +74,22 @@ export default function Form({ customers }: { customers: CustomerField[] }) {
step="0.01"
placeholder="Enter USD amount"
className="peer block w-full rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500"
aria-describedby="amount-error"
/>
<CurrencyDollarIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
</div>
</div>
s
{state.errors?.amount ? (
<div
id="amount-error"
aria-live="polite"
className="mt-2 text-sm text-red-500"
>
{state.errors.amount.map((error: string) => (
<p key={error}>{error}</p>
))}
</div>
) : null}
</div>
{/* Invoice Status */}
@ -74,6 +106,7 @@ export default function Form({ customers }: { customers: CustomerField[] }) {
type="radio"
value="pending"
className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600"
aria-describedby="status-error"
/>
<label
htmlFor="pending"
@ -89,6 +122,7 @@ export default function Form({ customers }: { customers: CustomerField[] }) {
type="radio"
value="paid"
className="h-4 w-4 border-gray-300 bg-gray-100 text-gray-600 focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:ring-offset-gray-800 dark:focus:ring-gray-600"
aria-describedby="status-error"
/>
<label
htmlFor="paid"
@ -99,6 +133,26 @@ export default function Form({ customers }: { customers: CustomerField[] }) {
</div>
</div>
</div>
{state.errors?.status ? (
<div
id="status-error"
aria-live="polite"
className="mt-2 text-sm text-red-500"
>
{state.errors.status.map((error: string) => (
<p key={error}>{error}</p>
))}
</div>
) : null}
{state.message ? (
<div
id="edit-error"
aria-live="polite"
className="mt-2 text-sm text-red-500"
>
<p>{state.message}</p>
</div>
) : null}
</div>
</div>
<div className="mt-6 flex justify-end gap-4">

View file

@ -1,5 +1,6 @@
'use client';
import { useFormState } from 'react-dom';
import { CustomerField, InvoiceForm } from '@/app/lib/definitions';
import {
CheckIcon,
@ -9,6 +10,7 @@ import {
} from '@heroicons/react/24/outline';
import Link from 'next/link';
import { Button } from '@/app/ui/button';
import { updateInvoice } from '@/app/lib/actions';
export default function EditInvoiceForm({
invoice,
@ -17,8 +19,12 @@ export default function EditInvoiceForm({
invoice: InvoiceForm;
customers: CustomerField[];
}) {
const initialState = { message: null, errors: {} };
const [state, dispatch] = useFormState(updateInvoice, initialState);
return (
<form>
<form action={dispatch}>
<input type="hidden" name="id" value={invoice.id} />
<div className="rounded-md bg-gray-50 p-4 md:p-6">
{/* Invoice ID */}
<input type="hidden" name="id" value={invoice.id} />
@ -33,6 +39,7 @@ export default function EditInvoiceForm({
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"
defaultValue={invoice.customer_id}
aria-describedby="customer-error"
>
<option value="" disabled>
Select a customer
@ -45,6 +52,17 @@ export default function EditInvoiceForm({
</select>
<UserCircleIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500" />
</div>
{state.errors?.customerId ? (
<div
id="customer-error"
aria-live="polite"
className="mt-2 text-sm text-red-500"
>
{state.errors.customerId.map((error: string) => (
<p key={error}>{error}</p>
))}
</div>
) : null}
</div>
{/* Invoice Amount */}
@ -61,14 +79,26 @@ export default function EditInvoiceForm({
defaultValue={invoice.amount}
placeholder="Enter USD amount"
className="peer block w-full rounded-md border border-gray-200 py-2 pl-10 text-sm outline-2 placeholder:text-gray-500"
aria-describedby="amount-error"
/>
<CurrencyDollarIcon className="pointer-events-none absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
</div>
</div>
{state.errors?.amount ? (
<div
id="amount-error"
aria-live="polite"
className="mt-2 text-sm text-red-500"
>
{state.errors.amount.map((error: string) => (
<p key={error}>{error}</p>
))}
</div>
) : null}
</div>
{/* Invoice Status */}
<div>
<fieldset>
<label htmlFor="status" className="mb-2 block text-sm font-medium">
Set the invoice status
</label>
@ -80,7 +110,7 @@ export default function EditInvoiceForm({
name="status"
type="radio"
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"
/>
<label
@ -96,7 +126,7 @@ export default function EditInvoiceForm({
name="status"
type="radio"
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"
/>
<label
@ -108,7 +138,24 @@ export default function EditInvoiceForm({
</div>
</div>
</div>
{state.errors?.status ? (
<div
aria-describedby="status-error"
aria-live="polite"
className="mt-2 text-sm text-red-500"
>
{state.errors.status.map((error: string) => (
<p key={error}>{error}</p>
))}
</div>
) : null}
</fieldset>
{state.message ? (
<div aria-live="polite" className="my-2 text-sm text-red-500">
<p>{state.message}</p>
</div>
) : null}
</div>
<div className="mt-6 flex justify-end gap-4">
<Link

View file

@ -1,20 +1,30 @@
'use client';
import { usePathname, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeftIcon, ArrowRightIcon } from '@heroicons/react/24/outline';
import clsx from 'clsx';
import Link from 'next/link';
import { generatePagination } from '@/app/lib/utils';
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 (
<>
{/* NOTE: comment in this code when you get to this point in the course */}
{/* <div className="inline-flex">
<div className="inline-flex">
<PaginationArrow
direction="left"
href={createPageURL(currentPage - 1)}
@ -47,7 +57,7 @@ export default function Pagination({ totalPages }: { totalPages: number }) {
href={createPageURL(currentPage + 1)}
isDisabled={currentPage >= totalPages}
/>
</div> */}
</div>
</>
);
}

View file

@ -1,15 +1,22 @@
import { lusitana } from '@/app/ui/fonts';
"use client";
import { authenticate } from "@/app/lib/actions";
import { lusitana } from "@/app/ui/fonts";
import {
AtSymbolIcon,
KeyIcon,
ExclamationCircleIcon,
} from '@heroicons/react/24/outline';
import { ArrowRightIcon } from '@heroicons/react/20/solid';
import { Button } from './button';
} from "@heroicons/react/24/outline";
import { ArrowRightIcon } from "@heroicons/react/20/solid";
import { Button } from "./button";
import { useFormState, useFormStatus } from "react-dom";
export default function LoginForm() {
const [code, action] = useFormState(authenticate, undefined);
const { pending } = useFormStatus();
return (
<form className="space-y-3">
<form action={action} className="space-y-3">
<div className="flex-1 rounded-lg bg-gray-50 px-6 pb-4 pt-8">
<h1 className={`${lusitana.className} mb-3 text-2xl`}>
Please log in to continue.
@ -57,7 +64,14 @@ export default function LoginForm() {
</div>
<LoginButton />
<div className="flex h-8 items-end space-x-1">
{/* Add form errors here */}
{code === "CredentialsSignin" && (
<>
<ExclamationCircleIcon className="h-5 w-5 text-red-500" />
<p aria-live="polite" className="text-sm text-red-500">
Invalid credentials
</p>
</>
)}
</div>
</div>
</form>
@ -65,8 +79,10 @@ export default function LoginForm() {
}
function LoginButton() {
const { pending } = useFormStatus();
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" />
</Button>
);

View file

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

24
auth.config.ts Normal file
View file

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

45
auth.ts Normal file
View file

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

9
middleware.ts Normal file
View file

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

View file

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

File diff suppressed because it is too large Load diff