Skip to content

Commit

Permalink
feat(api/orders): add getOrders and confirmPayment improvement
Browse files Browse the repository at this point in the history
  • Loading branch information
mrevanzak committed Nov 29, 2023
1 parent e95c766 commit a7721e0
Showing 1 changed file with 58 additions and 5 deletions.
63 changes: 58 additions & 5 deletions packages/api/src/router/orders.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -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 }) => {
Expand All @@ -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));
});
}),
});

0 comments on commit a7721e0

Please sign in to comment.