freshyo/apps/backend/src/trpc/apis/user-apis/apis/order.ts
2026-11-14 21:26:25 +05:30

740 lines
24 KiB
TypeScript

import { router, protectedProcedure } from "@/src/trpc/trpc-index";
import { z } from "zod";
import {
cancelUserOrderTransaction,
checkUserSuspended,
composeUnitNotation,
db,
deleteUserCartItemsForOrder,
getOrderProductById,
getUserAddressByIdAndUser,
getUserCouponUsageForOrder,
getUserCouponUsageForOrderGroup,
getUserOrderBasic,
getUserOrderByIdWithRelations,
getUserOrderCount,
getUserOrdersWithRelations,
getUserSlotCapacityStatus,
getUserDeliverySlotById,
getEffectiveRegionSettings,
getEffectiveBoundId,
getRegionSettingsForBound,
orders,
orderItems,
orderStatus,
placeUserOrderTransaction,
recordUserCouponUsage,
updateUserOrderNotes,
validateAndGetUserCoupons,
} from "@/src/dbService";
import { scaffoldAssetUrl } from "@/src/lib/s3-client";
import { ApiError } from "@/src/lib/api-error";
import { resolveRegionAndBound } from "@/src/lib/region-geo";
import type { DeliveryStatus, OrderStatus } from "@packages/shared";
import { computeCartPricing, type CartLine } from "@packages/shared";
import { CONST_KEYS } from "@/src/lib/const-store";
import { publishFormattedOrder, publishCancellation } from "@/src/lib/post-order-handler";
import { trackIfFirstOrder, clearFirstOrderIfMatches } from "@/src/lib/order-tracker";
import type {
UserOrdersResponse,
UserOrderDetail,
UserCancelOrderResponse,
UserUpdateNotesResponse,
} from "@/src/dbService";
const placeOrderUtil = async (params: {
userId: number;
regionId: number;
boundId?: number | null;
selectedItems: Array<{
skuId: number;
quantity: number;
slotId: number | null;
}>;
addressId: number;
couponIds?: number[];
userNotes?: string;
isFlash?: boolean;
}) => {
const {
userId,
selectedItems,
addressId,
couponIds,
userNotes,
} = params;
const isFlashDelivery = params.isFlash;
const orderGroupId = `${Date.now()}-${userId}`;
const address = await getUserAddressByIdAndUser(addressId, userId);
if (!address) {
throw new ApiError("Invalid address", 400);
}
// The delivery address's coordinates are authoritative: they decide the
// region (and bound) the order is placed into, so a stale or spoofed client
// regionId cannot mis-scope pricing, products or slots. When the address has
// no coordinates we fall back to its stored region, then the client's.
let regionId = params.regionId;
let resolvedBoundId: number | null = null;
if (address.latitude != null && address.longitude != null) {
const resolved = await resolveRegionAndBound(address.latitude, address.longitude);
if (resolved) {
regionId = resolved.region.id;
resolvedBoundId = resolved.bound.id;
}
} else if (address.regionId != null) {
regionId = address.regionId;
}
// Flash delivery is enabled per BOUND (region_bound_consts). The delivery
// address's bound is authoritative, so the flag is read from the same bound
// chain the pricing below uses — a client-supplied region/bound can never turn
// flash on for an address whose bound has it switched off.
if (isFlashDelivery) {
const constBoundId =
resolvedBoundId ?? address.boundId ?? params.boundId ?? (await getEffectiveBoundId(regionId));
const flashSettings =
(constBoundId != null ? await getRegionSettingsForBound(regionId, constBoundId) : null) ??
(await getEffectiveRegionSettings(regionId));
const raw = flashSettings?.settings?.[CONST_KEYS.isFlashDeliveryEnabled];
const isFlashEnabled = raw === 'true' || raw === '1';
if (!isFlashEnabled) {
throw new ApiError(
"Flash delivery is currently unavailable. Please opt for scheduled delivery.",
403
);
}
}
// Bound-level constants (delivery charge/thresholds/min order) come from the bound the
// delivery address resolves to, so pricing cannot be changed by a client-supplied id.
// Only when the address carries no bound do we fall back to the bound the client is
// browsing in, then to the region's effective bound. This mirrors the customer app, which
// already prices the selected address's bound (prominent-api-hooks useGetEssentialConsts).
// Region-level constants are shared across the region's bounds.
const boundId =
resolvedBoundId ?? address.boundId ?? params.boundId ?? (await getEffectiveBoundId(regionId));
const effective =
(boundId != null ? await getRegionSettingsForBound(regionId, boundId) : null) ??
(await getEffectiveRegionSettings(regionId));
const boundSettings = effective?.settings ?? {};
const numSetting = (key: string): number => {
const raw = boundSettings[key];
const parsed = raw == null ? NaN : Number(raw);
return Number.isFinite(parsed) ? parsed : 0;
};
const freeDeliveryThreshold = isFlashDelivery
? numSetting(CONST_KEYS.flashFreeDeliveryThreshold)
: numSetting(CONST_KEYS.freeDeliveryThreshold);
const deliveryCharge = isFlashDelivery
? numSetting(CONST_KEYS.flashDeliveryCharge)
: numSetting(CONST_KEYS.deliveryCharge);
const ordersBySlot = new Map<
number | null,
Array<{
skuId: number;
quantity: number;
slotId: number | null;
product: Awaited<ReturnType<typeof getOrderProductById>>;
}>
>();
for (const item of selectedItems) {
const product = await getOrderProductById(item.skuId, regionId);
if (!product) {
throw new ApiError(`Product ${item.skuId} not found`, 400);
}
// SEC-04: the SKU must belong to the region being ordered into. A product with no region is
// GLOBAL: the catalogue reads (stores/products) serve it in every region by the same rule, so it
// is accepted anywhere — only another region's product is rejected.
const productRegionId = product.product?.regionId ?? null
if (productRegionId !== null && productRegionId !== regionId) {
throw new ApiError(
`Product ${item.skuId} is not available in this region`,
409
);
}
// SEC-05: never sell a deleted, out-of-stock or suspended product.
if (
product.isDeleted ||
product.isOutOfStock ||
product.isSuspended ||
product.marketStats?.isSuspendedInRegion
) {
throw new ApiError(`Product ${item.skuId} is unavailable`, 400);
}
if (!ordersBySlot.has(item.slotId)) {
ordersBySlot.set(item.slotId, []);
}
ordersBySlot.get(item.slotId)!.push({ ...item, product });
}
if (params.isFlash) {
for (const item of selectedItems) {
const product = await getOrderProductById(item.skuId, regionId);
if (!product?.isFlashAvailable) {
throw new ApiError(`Product ${item.skuId} is not available for flash delivery`, 400);
}
}
}
// SEC-05 / SL-04: validate every scheduled slot (existence, region, active
// state, freeze/delivery time) and that it actually carries the ordered SKUs.
if (!params.isFlash) {
for (const [slotId, items] of ordersBySlot) {
if (slotId == null) {
throw new ApiError("A delivery slot is required for scheduled orders", 400);
}
const slot = await getUserDeliverySlotById(slotId);
if (!slot) {
throw new ApiError("Selected delivery slot not found", 400);
}
if (slot.regionId !== regionId) {
throw new ApiError("Selected delivery slot belongs to a different region", 409);
}
if (!slot.isActive) {
throw new ApiError("Selected delivery slot is not available", 400);
}
const now = Date.now();
if (slot.freezeTime.getTime() <= now) {
throw new ApiError("Selected delivery slot is closed for orders", 400);
}
if (slot.deliveryTime.getTime() <= now) {
throw new ApiError("Selected delivery slot has already passed", 400);
}
const slotSkuIds = new Set(slot.skuIds ?? []);
for (const item of items) {
if (!slotSkuIds.has(item.skuId)) {
throw new ApiError(
`Product ${item.skuId} is not available in the selected delivery slot`,
400
);
}
}
}
}
let totalAmount = 0;
const subOrderSubtotals: number[] = [];
const subOrderInputs: { key: number | null; items: CartLine[] }[] = [];
for (const [slotId, items] of ordersBySlot) {
const lines: CartLine[] = [];
let orderTotal = 0;
for (const item of items) {
if (!item.product) continue;
const basePrice = params.isFlash
? (item.product.flashPrice ?? item.product.price)
: item.product.price;
const unitPrice = parseFloat((basePrice ?? 0).toString());
lines.push({ skuId: item.skuId, quantity: item.quantity, unitPrice });
orderTotal += unitPrice * item.quantity;
}
subOrderInputs.push({ key: slotId, items: lines });
subOrderSubtotals.push(orderTotal);
totalAmount += orderTotal;
}
const validatedCoupons = await validateAndGetUserCoupons({
couponIds: couponIds ?? [],
userId,
regionId: regionId,
items: subOrderInputs.flatMap((so) => so.items),
});
// The discount is computed on GOODS subtotals only (delivery — flash or
// scheduled — never enters the base). Multiple coupons stack sequentially in
// the order the customer applied them, each capped by its own maxValue and
// rounded to the nearest rupee.
const pricing = computeCartPricing({
subOrders: subOrderInputs,
coupons: validatedCoupons.map((c) => ({
id: c.id,
discountPercent: c.discountPercent,
flatDiscount: c.flatDiscount,
maxValue: c.maxValue,
applicableSkuIds: c.applicableSkuIds,
})),
delivery: { threshold: freeDeliveryThreshold, charge: deliveryCharge },
});
const totalWithDelivery = pricing.grandTotal;
type OrderData = {
order: Omit<typeof orders.$inferInsert, "id">;
orderItems: Omit<typeof orderItems.$inferInsert, "id">[];
orderStatus: Omit<typeof orderStatus.$inferInsert, "id">;
};
const ordersData: OrderData[] = [];
let subOrderIndex = 0;
for (const [slotId, items] of ordersBySlot) {
const pricedSubOrder = pricing.subOrders[subOrderIndex];
const subOrderTotal = pricedSubOrder.goodsSubtotal;
const orderGroupProportion = totalAmount > 0 ? subOrderTotal / totalAmount : 0;
const orderDiscount = pricedSubOrder.discount;
const orderDelivery = pricedSubOrder.delivery;
const finalOrderAmount = pricedSubOrder.total;
const order: Omit<typeof orders.$inferInsert, "id"> = {
userId,
regionId: regionId,
addressId,
slotId: params.isFlash ? null : slotId,
totalAmount: finalOrderAmount.toString(),
deliveryCharge: orderDelivery.toString(),
discountAmount: orderDiscount.toString(),
readableId: -1,
userNotes: userNotes || null,
orderGroupId,
orderGroupProportion: orderGroupProportion.toString(),
isFlashDelivery: params.isFlash,
};
const validItems = items.filter(
(item): item is typeof item & { product: NonNullable<typeof item.product> } =>
item.product !== null && item.product !== undefined
)
const orderItemsData: Omit<typeof orderItems.$inferInsert, "id">[] = validItems.map(
(item) => {
const basePrice = params.isFlash
? (item.product.flashPrice ?? item.product.price)
: item.product.price
const priceString = (basePrice ?? 0).toString()
return {
orderId: 0,
skuId: item.skuId,
quantity: item.quantity.toString(),
price: priceString,
discountedPrice: priceString,
}
}
);
const orderStatusData: Omit<typeof orderStatus.$inferInsert, "id"> = {
userId,
orderId: 0,
};
ordersData.push({ order, orderItems: orderItemsData, orderStatus: orderStatusData });
subOrderIndex++;
}
const createdOrders = await placeUserOrderTransaction({
userId,
ordersData,
totalWithDelivery,
});
if (createdOrders.length > 0) {
await trackIfFirstOrder(userId, createdOrders[0].id);
}
await deleteUserCartItemsForOrder(
userId,
selectedItems.map((item) => item.skuId)
);
if (validatedCoupons.length > 0 && createdOrders.length > 0) {
// One coupon_usage row per coupon, all attached to the primary sub-order
// (highest goods subtotal). Each sub-order's discount is stored on the order
// itself (discountAmount), so the split is not re-derived at display time.
const primaryOrder = createdOrders[pricing.primaryIndex] ?? createdOrders[0];
for (const coupon of validatedCoupons) {
await recordUserCouponUsage(userId, coupon.id, primaryOrder.id);
}
}
console.log('publishing the order')
await publishFormattedOrder(createdOrders, ordersBySlot);
return { success: true, data: createdOrders };
};
export const orderRouter = router({
placeOrder: protectedProcedure
.input(
z.object({
selectedItems: z.array(
z.object({
skuId: z.number().int().positive(),
quantity: z.number().int().positive(),
slotId: z.union([z.number().int(), z.null()]),
})
),
addressId: z.number().int().positive(),
regionId: z.number().int().positive(),
boundId: z.number().int().positive().optional(),
couponIds: z.array(z.number().int().positive()).optional(),
userNotes: z.string().optional(),
isFlashDelivery: z.boolean().optional().default(false),
})
)
.mutation(async ({ input, ctx }) => {
const userId = ctx.user.userId;
const isSuspended = await checkUserSuspended(userId);
if (isSuspended) {
throw new ApiError("Unable to place order", 403);
}
const {
selectedItems,
addressId,
regionId,
boundId,
couponIds,
userNotes,
isFlashDelivery,
} = input;
// Flash delivery availability is checked inside placeOrderUtil, where the
// delivery address's bound is known (the flag is per bound).
if (!isFlashDelivery) {
const slotIds = [...new Set(selectedItems.filter(i => i.slotId !== null).map(i => i.slotId as number))];
for (const slotId of slotIds) {
const isCapacityFull = await getUserSlotCapacityStatus(slotId);
if (isCapacityFull) {
throw new ApiError("Selected delivery slot is at full capacity. Please choose another slot.", 403);
}
}
}
let processedItems = selectedItems;
if (isFlashDelivery) {
processedItems = selectedItems.map(item => ({
...item,
slotId: null as any,
}));
}
return await placeOrderUtil({
userId,
regionId,
boundId,
selectedItems: processedItems,
addressId,
couponIds,
userNotes,
isFlash: isFlashDelivery,
});
}),
getOrders: protectedProcedure
.input(
z
.object({
page: z.number().min(1).default(1),
pageSize: z.number().min(1).max(50).default(10),
})
.optional()
)
.query(async ({ input, ctx }): Promise<UserOrdersResponse> => {
const { page = 1, pageSize = 10 } = input || {};
const userId = ctx.user.userId;
const offset = (page - 1) * pageSize;
const [totalCount, userOrders] = await Promise.all([
getUserOrderCount(userId),
getUserOrdersWithRelations(userId, offset, pageSize),
]);
const mappedOrders = await Promise.all(
userOrders.map(async (order) => {
const status = order.orderStatus[0];
let deliveryStatus: DeliveryStatus;
let orderStatus: OrderStatus;
const allItemsPackaged = order.orderItems.every(
(item) => item.is_packaged
);
if (status?.isCancelled) {
deliveryStatus = "cancelled";
orderStatus = "cancelled";
} else if (status?.isDelivered) {
deliveryStatus = "success";
orderStatus = "success";
} else if (allItemsPackaged) {
deliveryStatus = "packaged";
orderStatus = "success";
} else {
deliveryStatus = "pending";
orderStatus = "success";
}
const items = await Promise.all(
order.orderItems.map(async (item) => {
const signedImages = item.sku?.images
? scaffoldAssetUrl(
item.sku.images as string[]
)
: [];
return {
productName: item.sku?.product?.name || 'Unknown',
skuName: item.sku?.name || null,
quantity: parseFloat(item.quantity),
unitNotation: composeUnitNotation(item.sku?.features || []),
price: parseFloat(item.price.toString()),
discountedPrice: parseFloat(
item.discountedPrice?.toString() || item.price.toString()
),
amount:
parseFloat(item.price.toString()) * parseFloat(item.quantity),
image: signedImages[0] || null,
};
})
);
return {
id: order.id,
orderId: `ORD${order.id}`,
orderDate: order.createdAt.toISOString(),
deliveryStatus,
deliveryDate: order.slot?.deliveryTime.toISOString(),
orderStatus,
cancelReason: status?.cancelReason || null,
totalAmount: Number(order.totalAmount),
deliveryCharge: Number(order.deliveryCharge),
userNotes: order.userNotes || null,
items,
isFlashDelivery: order.isFlashDelivery,
regionId: order.region?.id ?? null,
regionName: order.region?.name ?? null,
createdAt: order.createdAt.toISOString(),
};
})
);
return {
success: true,
data: mappedOrders,
pagination: {
page,
pageSize,
totalCount,
totalPages: Math.ceil(totalCount / pageSize),
},
};
}),
getOrderById: protectedProcedure
.input(z.object({ orderId: z.string() }))
.query(async ({ input, ctx }): Promise<UserOrderDetail> => {
const { orderId } = input;
const userId = ctx.user.userId;
const order = await getUserOrderByIdWithRelations(parseInt(orderId), userId);
if (!order) {
throw new Error("Order not found");
}
const couponUsageData = order.orderGroupId
? await getUserCouponUsageForOrderGroup(order.orderGroupId)
: await getUserCouponUsageForOrder(order.id);
let couponData = null;
if (couponUsageData.length > 0) {
// The per-order discount is stored on the order itself (`discount_amount`),
// so the displayed amount always equals what was charged.
couponData = {
couponCode: couponUsageData.map((u) => u.coupon.couponCode).join(", "),
couponDescription: `${couponUsageData.length} coupons applied`,
discountAmount: parseFloat(order.discountAmount?.toString() || "0"),
};
}
const status = order.orderStatus[0];
let deliveryStatus: DeliveryStatus;
let orderStatusResult: OrderStatus;
const allItemsPackaged = order.orderItems.every(
(item) => item.is_packaged
);
if (status?.isCancelled) {
deliveryStatus = "cancelled";
orderStatusResult = "cancelled";
} else if (status?.isDelivered) {
deliveryStatus = "success";
orderStatusResult = "success";
} else if (allItemsPackaged) {
deliveryStatus = "packaged";
orderStatusResult = "success";
} else {
deliveryStatus = "pending";
orderStatusResult = "success";
}
const items = await Promise.all(
order.orderItems.map(async (item) => {
const signedImages = item.sku?.images
? scaffoldAssetUrl(
item.sku.images as string[]
)
: [];
return {
productName: item.sku?.product?.name || 'Unknown',
skuName: item.sku?.name || null,
quantity: parseFloat(item.quantity),
unitNotation: composeUnitNotation(item.sku?.features || []),
price: parseFloat(item.price.toString()),
discountedPrice: parseFloat(
item.discountedPrice?.toString() || item.price.toString()
),
amount:
parseFloat(item.price.toString()) * parseFloat(item.quantity),
image: signedImages[0] || null,
};
})
);
return {
id: order.id,
orderId: `ORD${order.id}`,
orderDate: order.createdAt.toISOString(),
deliveryStatus,
deliveryDate: order.slot?.deliveryTime.toISOString(),
orderStatus: orderStatusResult,
cancellationStatus: orderStatusResult,
cancelReason: status?.cancelReason || null,
userNotes: order.userNotes || null,
items,
couponCode: couponData?.couponCode || null,
couponDescription: couponData?.couponDescription || null,
discountAmount: couponData?.discountAmount || null,
orderAmount: parseFloat(order.totalAmount.toString()),
isFlashDelivery: order.isFlashDelivery,
regionId: order.region?.id ?? null,
regionName: order.region?.name ?? null,
createdAt: order.createdAt.toISOString(),
totalAmount: parseFloat(order.totalAmount.toString()),
deliveryCharge: parseFloat(order.deliveryCharge.toString()),
};
}),
cancelOrder: protectedProcedure
.input(
z.object({
id: z.number(),
reason: z.string().min(1, "Cancellation reason is required"),
})
)
.mutation(async ({ input, ctx }): Promise<UserCancelOrderResponse> => {
try {
const userId = ctx.user.userId;
const { id, reason } = input;
const order = await getUserOrderBasic(id);
if (!order) {
console.error("Order not found:", id);
throw new ApiError("Order not found", 404);
}
if (order.userId !== userId) {
console.error("Order does not belong to user:", {
orderId: id,
orderUserId: order.userId,
requestUserId: userId,
});
throw new ApiError("Order not found", 404);
}
const status = order.orderStatus[0];
if (!status) {
console.error("Order status not found for order:", id);
throw new ApiError("Order status not found", 400);
}
if (status.isCancelled) {
console.error("Order is already cancelled:", id);
throw new ApiError("Order is already cancelled", 400);
}
if (status.isDelivered) {
console.error("Cannot cancel delivered order:", id);
throw new ApiError("Cannot cancel delivered order", 400);
}
await cancelUserOrderTransaction(id, status.id, reason);
await clearFirstOrderIfMatches(userId, id);
await publishCancellation(id, 'user', reason);
return { success: true, message: "Order cancelled successfully" };
} catch (e) {
console.log(e);
throw new ApiError("failed to cancel order");
}
}),
updateUserNotes: protectedProcedure
.input(
z.object({
id: z.number(),
userNotes: z.string(),
})
)
.mutation(async ({ input, ctx }): Promise<UserUpdateNotesResponse> => {
const userId = ctx.user.userId;
const { id, userNotes } = input;
const order = await getUserOrderBasic(id);
if (!order) {
console.error("Order not found:", id);
throw new ApiError("Order not found", 404);
}
if (order.userId !== userId) {
console.error("Order does not belong to user:", {
orderId: id,
orderUserId: order.userId,
requestUserId: userId,
});
throw new ApiError("Order not found", 404);
}
const status = order.orderStatus[0];
if (!status) {
console.error("Order status not found for order:", id);
throw new ApiError("Order status not found", 400);
}
if (status.isDelivered) {
console.error("Cannot update notes for delivered order:", id);
throw new ApiError("Cannot update notes for delivered order", 400);
}
if (status.isCancelled) {
console.error("Cannot update notes for cancelled order:", id);
throw new ApiError("Cannot update notes for cancelled order", 400);
}
await updateUserOrderNotes(id, userNotes);
return { success: true, message: "Notes updated successfully" };
}),
});