From a7721e0260650bbdc90e37cfb0be73424782bdee Mon Sep 17 00:00:00 2001 From: mrevanzak Date: Thu, 30 Nov 2023 01:24:58 +0700 Subject: [PATCH] feat(api/orders): add getOrders and confirmPayment improvement --- packages/api/src/router/orders.ts | 63 ++++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 5 deletions(-) diff --git a/packages/api/src/router/orders.ts b/packages/api/src/router/orders.ts index 7cc3977..0c05ff8 100644 --- a/packages/api/src/router/orders.ts +++ b/packages/api/src/router/orders.ts @@ -1,12 +1,16 @@ +import { TRPCError } from "@trpc/server"; import { v4 } from "uuid"; -import { eq } from "@vivat/db"; +import { eq, sql } from "@vivat/db"; +import { addresses } from "@vivat/db/schema/addresses"; import { insertOrderParams, orderIdSchema, orders, } from "@vivat/db/schema/orders"; import { createPaymentParams, payments } from "@vivat/db/schema/payments"; +import { products } from "@vivat/db/schema/products"; +import { users } from "@vivat/db/schema/users"; import { createTRPCRouter, protectedProcedure } from "../trpc"; @@ -22,6 +26,15 @@ export const orderRouter = createTRPCRouter({ }); return { orderId }; }), + getOrders: protectedProcedure.query(async ({ ctx }) => { + return await ctx.db + .select({ id: orders.id, status: orders.status, products, users }) + .from(orders) + .innerJoin(addresses, eq(orders.addressId, addresses.id)) + .innerJoin(users, eq(addresses.userId, users.id)) + .innerJoin(products, eq(orders.productId, products.id)) + .where(eq(users.id, ctx.auth.userId)); + }), showOrder: protectedProcedure .input(orderIdSchema) .query(async ({ input, ctx }) => { @@ -38,19 +51,59 @@ export const orderRouter = createTRPCRouter({ confirmPayment: protectedProcedure .input(createPaymentParams) .mutation(async ({ input, ctx }) => { - return await ctx.db.transaction(async (db) => { - const paymentId = v4(); - await db.insert(payments).values({ + const paymentId = v4(); + + const order = await ctx.db.query.orders.findFirst({ + columns: { + id: true, + }, + with: { + product: { + columns: { + id: true, + stock: true, + }, + }, + }, + where: (order, { eq }) => eq(order.id, input.orderId), + }); + if (!order) { + throw new TRPCError({ + code: "NOT_FOUND", + message: "Order not found", + }); + } + if (order.product.stock < 1) { + await ctx.db + .update(orders) + .set({ + status: "cancelled", + }) + .where(eq(orders.id, input.orderId)); + throw new TRPCError({ + code: "CONFLICT", + message: "Product out of stock", + }); + } + + return await ctx.db.transaction(async (tx) => { + await tx.insert(payments).values({ ...input, id: paymentId, }); - await db + await tx .update(orders) .set({ status: "payment", paymentId, }) .where(eq(orders.id, input.orderId)); + await tx + .update(products) + .set({ + stock: sql`${products.stock} - 1`, + }) + .where(eq(products.id, order.product.id)); }); }), });