diff --git a/apps/backend/src/lib/const-store.ts b/apps/backend/src/lib/const-store.ts index bd9b658..1c2c089 100644 --- a/apps/backend/src/lib/const-store.ts +++ b/apps/backend/src/lib/const-store.ts @@ -10,8 +10,6 @@ export const computeConstants = async (): Promise => { console.log('Computing constants from database...'); const constants = await db.select().from(keyValStore); - - console.log({constants}) for (const constant of constants) { const redisKey = `${CONST_REDIS_PREFIX}${constant.key}`; @@ -43,6 +41,27 @@ export const getConstant = async (key: string): Promise => { } }; +export const getConstants = async (keys: string[]): Promise> => { + const redisKeys = keys.map(key => `${CONST_REDIS_PREFIX}${key}`); + const values = await redisClient.MGET(redisKeys); + + const result: Record = {}; + keys.forEach((key, index) => { + const value = values[index]; + if (!value) { + result[key] = null; + } else { + try { + result[key] = JSON.parse(value) as T; + } catch { + result[key] = value as unknown as T; + } + } + }); + + return result; +}; + export const getAllConstValues = async (): Promise> => { const result: Record = {}; diff --git a/apps/backend/src/trpc/user-apis/order.ts b/apps/backend/src/trpc/user-apis/order.ts index 2d2429a..5ecfd3a 100644 --- a/apps/backend/src/trpc/user-apis/order.ts +++ b/apps/backend/src/trpc/user-apis/order.ts @@ -24,9 +24,8 @@ import { sendOrderCancelledNotification, } from "../../lib/notif-job"; import { RazorpayPaymentService } from "../../lib/payments-utils"; -import { deliveryCharge, minOrderValue } from "../../lib/env-exporter"; import { getNextDeliveryDate } from "../common-apis/common"; -import { CONST_KEYS, getConstant } from "../../lib/const-store"; +import { CONST_KEYS, getConstant, getConstants } from "../../lib/const-store"; const validateAndGetCoupon = async ( @@ -116,7 +115,6 @@ const placeOrderUtil = async (params: { paymentMethod: "online" | "cod"; couponId?: number; userNotes?: string; - deliveryPrice?: number; isFlash?: boolean; }) => { const { @@ -126,9 +124,23 @@ const placeOrderUtil = async (params: { paymentMethod, couponId, userNotes, - deliveryPrice, } = params; + const constants = await getConstants([ + CONST_KEYS.minRegularOrderValue, + CONST_KEYS.deliveryCharge, + CONST_KEYS.flashFreeDeliveryThreshold, + CONST_KEYS.flashDeliveryCharge, + ]); + + const minOrderValue = constants[CONST_KEYS.minRegularOrderValue] ?? 0; + const deliveryCharge = constants[CONST_KEYS.deliveryCharge] ?? 0; + const flashFreeDeliveryThreshold = constants[CONST_KEYS.flashFreeDeliveryThreshold] ?? 0; + const flashDeliveryCharge = constants[CONST_KEYS.flashDeliveryCharge] ?? 0; + + const freeThreshold = params.isFlash ? flashFreeDeliveryThreshold : minOrderValue; + const charge = params.isFlash ? flashDeliveryCharge : deliveryCharge; + const orderGroupId = `${Date.now()}-${userId}`; // Validate address belongs to user const address = await db.query.addresses.findFirst({ @@ -194,15 +206,12 @@ const placeOrderUtil = async (params: { const appliedCoupon = await validateAndGetCoupon(couponId, userId, totalAmount); - // Calculate and verify delivery charge + // Calculate delivery charge const expectedDeliveryCharge = totalAmount < minOrderValue ? deliveryCharge : 0; - if ( - deliveryPrice !== undefined && - deliveryPrice !== expectedDeliveryCharge - ) { - throw new ApiError("Invalid delivery charge amount", 400); - } + + // Calculate total amount including delivery charge for first order + const totalWithDelivery = totalAmount + expectedDeliveryCharge; // Create orders in transaction const createdOrders = await db.transaction(async (tx) => { @@ -259,25 +268,25 @@ const placeOrderUtil = async (params: { // const orderGroupProportion = orderTotal / totalAmount; - // Create order record - const [order] = await tx - .insert(orders) - .values({ - userId, - addressId, - slotId: params.isFlash ? null : slotId, // No slot assignment for flash delivery - isCod: paymentMethod === "cod", - isOnlinePayment: paymentMethod === "online", - paymentInfoId: sharedPaymentInfoId, - totalAmount: finalOrderTotal.toString(), - deliveryCharge: isFirstOrder ? expectedDeliveryCharge.toString() : '0', - readableId: currentReadableId++, - userNotes: userNotes || null, - orderGroupId, - orderGroupProportion: orderGroupProportion.toString(), - isFlashDelivery: params.isFlash, - }) - .returning(); + // Create order record + const [order] = await tx + .insert(orders) + .values({ + userId, + addressId, + slotId: params.isFlash ? null : slotId, // No slot assignment for flash delivery + isCod: paymentMethod === "cod", + isOnlinePayment: paymentMethod === "online", + paymentInfoId: sharedPaymentInfoId, + totalAmount: isFirstOrder ? totalWithDelivery.toString() : finalOrderTotal.toString(), + deliveryCharge: isFirstOrder ? expectedDeliveryCharge.toString() : '0', + readableId: currentReadableId++, + userNotes: userNotes || null, + orderGroupId, + orderGroupProportion: orderGroupProportion.toString(), + isFlashDelivery: params.isFlash, + }) + .returning(); // Create order items const orderItemsData = items.map((item) => ({ @@ -317,7 +326,7 @@ const placeOrderUtil = async (params: { if (paymentMethod === "online" && sharedPaymentInfoId) { const razorpayOrder = await RazorpayPaymentService.createOrder( sharedPaymentInfoId, - (totalAmount+expectedDeliveryCharge).toString() + totalWithDelivery.toString() ); await RazorpayPaymentService.insertPaymentRecord( sharedPaymentInfoId, @@ -374,7 +383,6 @@ export const orderRouter = router({ paymentMethod: z.enum(["online", "cod"]), couponId: z.number().int().positive().optional(), userNotes: z.string().optional(), - deliveryPrice: z.number().min(0).optional(), isFlashDelivery: z.boolean().optional().default(false), }) ) @@ -386,7 +394,6 @@ export const orderRouter = router({ paymentMethod, couponId, userNotes, - deliveryPrice, isFlashDelivery, } = input; @@ -408,8 +415,6 @@ export const orderRouter = router({ slotId: null as any, // Type override for flash delivery })); } - - console.log({isFlashDelivery, processedItems}) return await placeOrderUtil({ userId, @@ -418,7 +423,6 @@ export const orderRouter = router({ paymentMethod, couponId, userNotes, - deliveryPrice, isFlash: isFlashDelivery, }); }), diff --git a/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/[id].tsx b/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/[id].tsx index 6c4b66a..d1009b8 100644 --- a/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/[id].tsx +++ b/apps/user-ui/app/(drawer)/(tabs)/me/my-orders/[id].tsx @@ -117,8 +117,10 @@ export default function OrderDetails() { } }; + const orderAny = order as any; const subtotal = order.items.reduce((sum, item) => sum + item.amount, 0); const discountAmount = order.discountAmount || 0; + const deliveryCharge = orderAny.deliveryCharge || 0; const totalAmount = order.orderAmount; const statusConfig = getStatusConfig(order.deliveryStatus || "pending"); @@ -341,6 +343,12 @@ export default function OrderDetails() { -₹{discountAmount} )} + + Delivery + + {deliveryCharge > 0 ? `₹${deliveryCharge}` : 'Free'} + + Total Amount ₹{totalAmount} diff --git a/apps/user-ui/components/UpdateChecker.tsx b/apps/user-ui/components/UpdateChecker.tsx index cee29dd..02827d8 100644 --- a/apps/user-ui/components/UpdateChecker.tsx +++ b/apps/user-ui/components/UpdateChecker.tsx @@ -17,7 +17,7 @@ const UpdateChecker: React.FC = ({ children }) => { "Restart app to apply the update?", [ { text: "Later", style: "cancel" }, - { text: "Restart", onPress: () => Updates.reloadAsync() } + { text: "Update & Restart", onPress: () => Updates.reloadAsync() } ] ); }