File size: 5,416 Bytes
6a30288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
"use server";

import { getCart } from "@/server-actions/get-cart-details";
import { db } from "@/db/db";
import { addresses, carts, orders, products, stores } from "@/db/schema";
import { getCurrentUser } from "@/lib/auth";
import { routes } from "@/lib/routes";
import { CheckoutItem } from "@/lib/types";
import { and, eq, inArray, sql } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { cookies } from "next/headers";
import { randomBytes } from "crypto";
import { z } from "zod";

const checkoutSchema = z.object({
  storeSlug: z.string().trim().min(1),
  name: z.string().trim().min(2),
  email: z.string().trim().email(),
  line1: z.string().trim().min(3),
  line2: z.string().trim().optional(),
  city: z.string().trim().min(2),
  state: z.string().trim().min(2),
  postalCode: z.string().trim().min(3),
  country: z.string().trim().min(2),
  cardName: z.string().trim().min(2),
  cardNumber: z.string().trim().min(12),
  expiry: z.string().trim().regex(/^\d{2}\/\d{2}$/),
  cvc: z.string().trim().regex(/^\d{3,4}$/),
});

export async function submitOrder(values: z.infer<typeof checkoutSchema>) {
  try {
    const input = checkoutSchema.parse(values);
    const cartId = Number(cookies().get("cartId")?.value);

    if (isNaN(cartId)) {
      throw new Error("Cart not found");
    }

    const { cartItems, cartItemDetails } = await getCart(cartId);
    const [store] = await db
      .select({
        id: stores.id,
        name: stores.name,
        slug: stores.slug,
      })
      .from(stores)
      .where(eq(stores.slug, input.storeSlug));

    if (!store) {
      throw new Error("Store not found");
    }

    const storeItems = cartItemDetails.filter((item) => item.storeId === store.id);

    if (!storeItems.length) {
      throw new Error("This store has no items in the cart");
    }

    const checkoutItems = storeItems.map((product) => {
      const qty = cartItems.find((item) => item.id === product.id)?.qty ?? 0;

      if (qty < 1) {
        throw new Error("Cart quantity is invalid");
      }

      return {
        id: product.id,
        price: Number(product.price),
        qty,
      };
    }) as CheckoutItem[];

    const outOfStockItem = storeItems.find((product) => {
      const qty = cartItems.find((item) => item.id === product.id)?.qty ?? 0;
      return Number(product.inventory) < qty;
    });

    if (outOfStockItem) {
      return {
        error: true,
        message: "Inventory changed",
        action: `${outOfStockItem.name} no longer has enough stock to fulfill this order.`,
      };
    }

    const [addressInsert] = await db.insert(addresses).values({
      line1: input.line1,
      line2: input.line2 || "",
      city: input.city,
      state: input.state,
      postal_code: input.postalCode,
      country: input.country,
    });

    const [storeOrderCount] = await db
      .select({
        count: sql<number>`count(*)`,
      })
      .from(orders)
      .where(eq(orders.storeId, store.id));

    const reference = `LOCAL-${randomBytes(4).toString("hex").toUpperCase()}`;
    const subtotal = checkoutItems.reduce(
      (sum, item) => sum + item.qty * Number(item.price),
      0
    );
    const shipping = subtotal > 50 ? 0 : 7.5;
    const total = subtotal + shipping;
    const currentUser = await getCurrentUser();

    await db.insert(orders).values({
      prettyOrderId: Number(storeOrderCount?.count ?? 0) + 1,
      storeId: store.id,
      userId: currentUser?.id ?? null,
      items: JSON.stringify(checkoutItems),
      total: total.toFixed(2),
      stripePaymentIntentId: reference,
      stripePaymentIntentStatus: "paid",
      name: input.name,
      email: input.email,
      createdAt: Math.floor(Date.now() / 1000),
      addressId: Number(addressInsert.insertId),
    });

    const orderedProductIds = checkoutItems.map((item) => item.id);
    const inventoryRows = await db
      .select({
        id: products.id,
        inventory: products.inventory,
      })
      .from(products)
      .where(inArray(products.id, orderedProductIds));

    for (const item of checkoutItems) {
      const currentInventory = inventoryRows.find((row) => row.id === item.id);
      const nextInventory = Math.max(
        0,
        Number(currentInventory?.inventory ?? 0) - item.qty
      );

      await db
        .update(products)
        .set({
          inventory: String(nextInventory),
        })
        .where(and(eq(products.id, item.id), eq(products.storeId, store.id)));
    }

    const remainingCartItems = cartItems.filter(
      (item) => !orderedProductIds.includes(item.id)
    );

    await db
      .update(carts)
      .set({
        items: JSON.stringify(remainingCartItems),
        isClosed: remainingCartItems.length === 0,
        paymentIntentId: null,
        clientSecret: null,
      })
      .where(eq(carts.id, cartId));

    revalidatePath(routes.cart);
    revalidatePath(`${routes.checkout}/${store.slug}`);
    revalidatePath(routes.account);

    return {
      error: false,
      message: "Order placed",
      action: "Your local demo checkout completed successfully.",
      redirectTo: `${routes.checkout}/${store.slug}/${routes.orderConfirmation}?order=${reference}`,
    };
  } catch (error) {
    console.log(error);

    return {
      error: true,
      message: "Checkout failed",
      action: "Please review your details and try again.",
    };
  }
}