Guest User

Untitled

a guest
Feb 16th, 2025
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. "use server";
  2.  
  3. import { AuthError } from "next-auth";
  4. import { signIn } from "@/auth";
  5. import { revalidatePath } from "next/cache";
  6. import { redirect } from "next/navigation";
  7. import postgres from "postgres";
  8. import { z } from "zod";
  9.  
  10. export type State = {
  11.   errors?: {
  12.     customerId?: string[];
  13.     amount?: string[];
  14.     status?: string[];
  15.   };
  16.   message?: string | null;
  17. };
  18.  
  19. const sql = postgres(process.env.POSTGRES_URL!, { ssl: "require" });
  20. const FormSchema = z.object({
  21.   id: z.string(),
  22.   customerId: z.string({ invalid_type_error: "Please select a customer" }),
  23.   amount: z.coerce
  24.     .number()
  25.     .gt(0, { message: "Please enter an amount greater than $0" }),
  26.   status: z.enum(["pending", "paid"], {
  27.     invalid_type_error: "Please select an invoice status",
  28.   }),
  29.   date: z.string(),
  30. });
  31.  
  32. const CreateInvoice = FormSchema.omit({ id: true, date: true });
  33. const UpdateInvoice = FormSchema.omit({ id: true, date: true });
  34.  
  35. export async function createInvoice(prevState: State, formData: FormData) {
  36.   const validatedFields = CreateInvoice.safeParse({
  37.     customerId: formData.get("customerId"),
  38.     amount: formData.get("amount"),
  39.     status: formData.get("status"),
  40.   });
  41.   if (!validatedFields.success) {
  42.     return {
  43.       errors: validatedFields.error.flatten().fieldErrors,
  44.       message: "Missing Fields. Failed to Create Invoice",
  45.     };
  46.   }
  47.   const { customerId, amount, status } = validatedFields.data;
  48.   const amountInCents = amount * 100;
  49.   const date = new Date().toISOString().split("T")[0];
  50.  
  51.   try {
  52.     await sql`
  53.     INSERT INTO invoices (customer_id, amount, status, date)
  54.     VALUES (${customerId}, ${amountInCents}, ${status}, ${date})
  55.   `;
  56.   } catch (error) {
  57.     return {
  58.       message: "Database Error: Failed to Create Invoice.",
  59.     };
  60.   }
  61.  
  62.   revalidatePath("/dashboard/invoices");
  63.   redirect("/dashboard/invoices");
  64. }
  65. export async function updateInvoice(id: string, formData: FormData) {
  66.   const { customerId, amount, status } = UpdateInvoice.parse({
  67.     customerId: formData.get("customerId"),
  68.     amount: formData.get("amount"),
  69.     status: formData.get("status"),
  70.   });
  71.   const amountInCents = amount * 100;
  72.  
  73.   try {
  74.     await sql`
  75.   UPDATE invoices
  76.   SET customer_id = ${customerId}, amount=${amountInCents}, status = ${status}
  77.   WHERE id = ${id}
  78.   `;
  79.   } catch (error) {
  80.     console.log(error);
  81.   }
  82.  
  83.   revalidatePath("/dashboard/invoices");
  84.   redirect("/dashboard/invoices");
  85. }
  86. export async function deleteInvoice(id: string) {
  87.   await sql`
  88.   DELETE FROM INVOICES WHERE id = ${id}
  89.   `;
  90.   revalidatePath("/dashboard/invoices");
  91. }
  92.  
  93. export async function authenticate(
  94.   prevState: string | undefined,
  95.   formData: FormData,
  96. ) {
  97.   try {
  98.     await signIn("credentials", formData);
  99.   } catch (error) {
  100.     if (error instanceof AuthError) {
  101.       switch (error.type) {
  102.         case "CredentialsSignin":
  103.           return "Invalid credentials";
  104.         default:
  105.           return "Something went wrong";
  106.       }
  107.     }
  108.     throw Error;
  109.   }
  110. }
  111.  
Advertisement
Add Comment
Please, Sign In to add comment