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);
console.log({constants})
for (const constant of constants) {
const redisKey = `${CONST_REDIS_PREFIX}${constant.key}`;
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>> => {
const result: Record<string, any> = {};

View file

@ -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<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}`;
// 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;
@ -409,8 +416,6 @@ export const orderRouter = router({
}));
}
console.log({isFlashDelivery, processedItems})
return await placeOrderUtil({
userId,
selectedItems: processedItems,
@ -418,7 +423,6 @@ export const orderRouter = router({
paymentMethod,
couponId,
userNotes,
deliveryPrice,
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 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() {
<MyText style={tw`text-emerald-600 font-medium`}>-{discountAmount}</MyText>
</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`}>
<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>

View file

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