This commit is contained in:
shafi54 2026-01-30 12:42:58 +05:30
parent a8e52583d4
commit 6a7f0a2243
4 changed files with 70 additions and 39 deletions

View file

@ -11,8 +11,6 @@ export const computeConstants = async (): Promise<void> => {
const constants = await db.select().from(keyValStore); const constants = await db.select().from(keyValStore);
console.log({constants})
for (const constant of constants) { for (const constant of constants) {
const redisKey = `${CONST_REDIS_PREFIX}${constant.key}`; const redisKey = `${CONST_REDIS_PREFIX}${constant.key}`;
const value = JSON.stringify(constant.value); const value = JSON.stringify(constant.value);
@ -43,6 +41,27 @@ export const getConstant = async <T = any>(key: string): Promise<T | null> => {
} }
}; };
export const getConstants = async <T = any>(keys: string[]): Promise<Record<string, T | null>> => {
const redisKeys = keys.map(key => `${CONST_REDIS_PREFIX}${key}`);
const values = await redisClient.MGET(redisKeys);
const result: Record<string, T | null> = {};
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<Record<ConstKey, any>> => { export const getAllConstValues = async (): Promise<Record<ConstKey, any>> => {
const result: Record<string, any> = {}; const result: Record<string, any> = {};

View file

@ -24,9 +24,8 @@ import {
sendOrderCancelledNotification, sendOrderCancelledNotification,
} from "../../lib/notif-job"; } from "../../lib/notif-job";
import { RazorpayPaymentService } from "../../lib/payments-utils"; import { RazorpayPaymentService } from "../../lib/payments-utils";
import { deliveryCharge, minOrderValue } from "../../lib/env-exporter";
import { getNextDeliveryDate } from "../common-apis/common"; 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 ( const validateAndGetCoupon = async (
@ -116,7 +115,6 @@ const placeOrderUtil = async (params: {
paymentMethod: "online" | "cod"; paymentMethod: "online" | "cod";
couponId?: number; couponId?: number;
userNotes?: string; userNotes?: string;
deliveryPrice?: number;
isFlash?: boolean; isFlash?: boolean;
}) => { }) => {
const { const {
@ -126,9 +124,23 @@ const placeOrderUtil = async (params: {
paymentMethod, paymentMethod,
couponId, couponId,
userNotes, userNotes,
deliveryPrice,
} = params; } = params;
const constants = await getConstants<number>([
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}`; const orderGroupId = `${Date.now()}-${userId}`;
// Validate address belongs to user // Validate address belongs to user
const address = await db.query.addresses.findFirst({ const address = await db.query.addresses.findFirst({
@ -194,15 +206,12 @@ const placeOrderUtil = async (params: {
const appliedCoupon = await validateAndGetCoupon(couponId, userId, totalAmount); const appliedCoupon = await validateAndGetCoupon(couponId, userId, totalAmount);
// Calculate and verify delivery charge // Calculate delivery charge
const expectedDeliveryCharge = const expectedDeliveryCharge =
totalAmount < minOrderValue ? deliveryCharge : 0; totalAmount < minOrderValue ? deliveryCharge : 0;
if (
deliveryPrice !== undefined && // Calculate total amount including delivery charge for first order
deliveryPrice !== expectedDeliveryCharge const totalWithDelivery = totalAmount + expectedDeliveryCharge;
) {
throw new ApiError("Invalid delivery charge amount", 400);
}
// Create orders in transaction // Create orders in transaction
const createdOrders = await db.transaction(async (tx) => { const createdOrders = await db.transaction(async (tx) => {
@ -269,7 +278,7 @@ const placeOrderUtil = async (params: {
isCod: paymentMethod === "cod", isCod: paymentMethod === "cod",
isOnlinePayment: paymentMethod === "online", isOnlinePayment: paymentMethod === "online",
paymentInfoId: sharedPaymentInfoId, paymentInfoId: sharedPaymentInfoId,
totalAmount: finalOrderTotal.toString(), totalAmount: isFirstOrder ? totalWithDelivery.toString() : finalOrderTotal.toString(),
deliveryCharge: isFirstOrder ? expectedDeliveryCharge.toString() : '0', deliveryCharge: isFirstOrder ? expectedDeliveryCharge.toString() : '0',
readableId: currentReadableId++, readableId: currentReadableId++,
userNotes: userNotes || null, userNotes: userNotes || null,
@ -317,7 +326,7 @@ const placeOrderUtil = async (params: {
if (paymentMethod === "online" && sharedPaymentInfoId) { if (paymentMethod === "online" && sharedPaymentInfoId) {
const razorpayOrder = await RazorpayPaymentService.createOrder( const razorpayOrder = await RazorpayPaymentService.createOrder(
sharedPaymentInfoId, sharedPaymentInfoId,
(totalAmount+expectedDeliveryCharge).toString() totalWithDelivery.toString()
); );
await RazorpayPaymentService.insertPaymentRecord( await RazorpayPaymentService.insertPaymentRecord(
sharedPaymentInfoId, sharedPaymentInfoId,
@ -374,7 +383,6 @@ export const orderRouter = router({
paymentMethod: z.enum(["online", "cod"]), paymentMethod: z.enum(["online", "cod"]),
couponId: z.number().int().positive().optional(), couponId: z.number().int().positive().optional(),
userNotes: z.string().optional(), userNotes: z.string().optional(),
deliveryPrice: z.number().min(0).optional(),
isFlashDelivery: z.boolean().optional().default(false), isFlashDelivery: z.boolean().optional().default(false),
}) })
) )
@ -386,7 +394,6 @@ export const orderRouter = router({
paymentMethod, paymentMethod,
couponId, couponId,
userNotes, userNotes,
deliveryPrice,
isFlashDelivery, isFlashDelivery,
} = input; } = input;
@ -409,8 +416,6 @@ export const orderRouter = router({
})); }));
} }
console.log({isFlashDelivery, processedItems})
return await placeOrderUtil({ return await placeOrderUtil({
userId, userId,
selectedItems: processedItems, selectedItems: processedItems,
@ -418,7 +423,6 @@ export const orderRouter = router({
paymentMethod, paymentMethod,
couponId, couponId,
userNotes, userNotes,
deliveryPrice,
isFlash: isFlashDelivery, isFlash: isFlashDelivery,
}); });
}), }),

View file

@ -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 subtotal = order.items.reduce((sum, item) => sum + item.amount, 0);
const discountAmount = order.discountAmount || 0; const discountAmount = order.discountAmount || 0;
const deliveryCharge = orderAny.deliveryCharge || 0;
const totalAmount = order.orderAmount; const totalAmount = order.orderAmount;
const statusConfig = getStatusConfig(order.deliveryStatus || "pending"); const statusConfig = getStatusConfig(order.deliveryStatus || "pending");
@ -341,6 +343,12 @@ export default function OrderDetails() {
<MyText style={tw`text-emerald-600 font-medium`}>-{discountAmount}</MyText> <MyText style={tw`text-emerald-600 font-medium`}>-{discountAmount}</MyText>
</View> </View>
)} )}
<View style={tw`flex-row justify-between mb-3`}>
<MyText style={tw`text-slate-500 text-sm`}>Delivery</MyText>
<MyText style={tw`text-slate-900 font-medium`}>
{deliveryCharge > 0 ? `${deliveryCharge}` : 'Free'}
</MyText>
</View>
<View style={tw`pt-4 border-t border-slate-50 flex-row justify-between items-center`}> <View style={tw`pt-4 border-t border-slate-50 flex-row justify-between items-center`}>
<MyText style={tw`text-slate-900 font-bold text-base`}>Total Amount</MyText> <MyText style={tw`text-slate-900 font-bold text-base`}>Total Amount</MyText>
<MyText style={tw`text-slate-900 font-bold text-xl`}>{totalAmount}</MyText> <MyText style={tw`text-slate-900 font-bold text-xl`}>{totalAmount}</MyText>

View file

@ -17,7 +17,7 @@ const UpdateChecker: React.FC<UpdateCheckerProps> = ({ children }) => {
"Restart app to apply the update?", "Restart app to apply the update?",
[ [
{ text: "Later", style: "cancel" }, { text: "Later", style: "cancel" },
{ text: "Restart", onPress: () => Updates.reloadAsync() } { text: "Update & Restart", onPress: () => Updates.reloadAsync() }
] ]
); );
} }