fix(orders): resolve 500 error in order creation by fixing orderItems payload and prevent premature wallet deduction
Deploy Canina / deploy (push) Successful in 1m43s
Deploy Canina / deploy (push) Successful in 1m43s
This commit is contained in:
1 parent
2e217ebe3d
commit
1aa9d6e34d
2 files changed
+34
-70
No files matched your search
@@ -134,8 +134,6 @@ export class OrdersService {
|
||||
const orderItemsData: Array<{
|
||||
productId: string;
|
||||
quantity: number;
|
||||
unitPrice: number;
|
||||
totalPrice: number;
|
||||
}> = [];
|
||||
|
||||
for (const item of createOrderDto.items) {
|
||||
@@ -147,8 +145,6 @@ export class OrdersService {
|
||||
orderItemsData.push({
|
||||
productId: item.productId,
|
||||
quantity: item.quantity,
|
||||
unitPrice: Number(unitPrice),
|
||||
totalPrice: Number(totalItemPrice),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -244,7 +240,6 @@ export class OrdersService {
|
||||
|
||||
const isOnline = createOrderDto.paymentMethod === 'online';
|
||||
const initialStatus = isOnline ? 'pending_payment' : 'processing';
|
||||
const reservationExpiry = new Date(Date.now() + 15 * 60 * 1000); // 15 minutes hold
|
||||
|
||||
const createdOrder = await this.prisma.order.create({
|
||||
data: {
|
||||
@@ -261,20 +256,11 @@ export class OrdersService {
|
||||
orderItems: {
|
||||
create: orderItemsData,
|
||||
},
|
||||
inventoryReservations: {
|
||||
create: orderItemsData.map((item) => ({
|
||||
productId: item.productId,
|
||||
quantity: item.quantity,
|
||||
expiresAt: reservationExpiry,
|
||||
status: isOnline ? 'ACTIVE' : 'CONSUMED',
|
||||
})),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
orderItems: {
|
||||
include: { product: true },
|
||||
},
|
||||
inventoryReservations: true,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -87,56 +87,33 @@ export default function CheckoutPage() {
|
||||
|
||||
const handleFinalize = async () => {
|
||||
const totalAmount = getTotal() + shippingFee;
|
||||
setLoading(true);
|
||||
const activePet = getActivePet();
|
||||
|
||||
// 1. Validate shipping address
|
||||
const selectedAddr = profile.addresses?.find(a => a.id === selectedAddressId);
|
||||
let shippingAddressStr = '';
|
||||
if (selectedAddr) {
|
||||
shippingAddressStr = `${selectedAddr.province}، ${selectedAddr.city}، ${selectedAddr.detail}${selectedAddr.zipCode ? ` (کد پستی: ${selectedAddr.zipCode})` : ''} (گیرنده: ${selectedAddr.receptorName} - ${toPersian(selectedAddr.phone)})`;
|
||||
} else if (manualAddress) {
|
||||
const provCity = [manualProvince, manualCity].filter(Boolean).join('، ');
|
||||
shippingAddressStr = `${provCity ? provCity + '، ' : ''}${manualAddress}${manualZipCode ? ` (کد پستی: ${manualZipCode})` : ''}${manualName ? ` (گیرنده: ${manualName}${manualPhone ? ` - ${toPersian(manualPhone)}` : ''})` : ''}`;
|
||||
}
|
||||
|
||||
if (!selectedAddressId && !manualAddress) {
|
||||
toast.error("لطفاً یک آدرس برای ارسال سفارش انتخاب کرده یا آدرس جدید وارد کنید.");
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. Validate wallet balance if payment method is wallet
|
||||
if (paymentMethod === 'wallet' && (profile.walletBalance || 0) < totalAmount) {
|
||||
toast.error(`موجودی کیف پول شما (${(profile.walletBalance || 0).toLocaleString('fa-IR')} تومان) کمتر از مبلغ نهایی سفارش (${totalAmount.toLocaleString('fa-IR')} تومان) است. لطفاً ابتدا کیف پول خود را شارژ کنید.`);
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
// 1. Deduct wallet balance if payment method is wallet
|
||||
if (paymentMethod === 'wallet') {
|
||||
const walletDeducted = Math.min(profile.walletBalance || 0, totalAmount);
|
||||
if (walletDeducted > 0) {
|
||||
const newBalance = (profile.walletBalance || 0) - walletDeducted;
|
||||
const newTransaction = {
|
||||
id: `TR-${Math.floor(Math.random() * 90000) + 10000}`,
|
||||
type: 'purchase' as const,
|
||||
amount: walletDeducted,
|
||||
date: new Date().toISOString(),
|
||||
status: 'success' as const
|
||||
};
|
||||
useUserStore.setState((state) => ({
|
||||
profile: {
|
||||
...state.profile,
|
||||
walletBalance: newBalance,
|
||||
transactions: [newTransaction, ...(state.profile.transactions || [])]
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Register the order in the backend
|
||||
const selectedAddr = profile.addresses?.find(a => a.id === selectedAddressId);
|
||||
let shippingAddressStr = '';
|
||||
if (selectedAddr) {
|
||||
shippingAddressStr = `${selectedAddr.province}، ${selectedAddr.city}، ${selectedAddr.detail}${selectedAddr.zipCode ? ` (کد پستی: ${selectedAddr.zipCode})` : ''} (گیرنده: ${selectedAddr.receptorName} - ${toPersian(selectedAddr.phone)})`;
|
||||
} else if (manualAddress) {
|
||||
const provCity = [manualProvince, manualCity].filter(Boolean).join('، ');
|
||||
shippingAddressStr = `${provCity ? provCity + '، ' : ''}${manualAddress}${manualZipCode ? ` (کد پستی: ${manualZipCode})` : ''}${manualName ? ` (گیرنده: ${manualName}${manualPhone ? ` - ${toPersian(manualPhone)}` : ''})` : ''}`;
|
||||
}
|
||||
|
||||
// Check wallet balance if payment method is wallet
|
||||
if (paymentMethod === 'wallet' && (profile.walletBalance || 0) < totalAmount) {
|
||||
toast.error(`موجودی کیف پول شما (${(profile.walletBalance || 0).toLocaleString('fa-IR')} تومان) کمتر از مبلغ نهایی سفارش (${totalAmount.toLocaleString('fa-IR')} تومان) است. لطفاً ابتدا کیف پول خود را شارژ کنید.`);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check shipping address requirement
|
||||
if (!selectedAddressId && !manualAddress) {
|
||||
toast.error("لطفاً یک آدرس برای ارسال سفارش انتخاب کرده یا آدرس جدید وارد کنید.");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Register the order in the backend
|
||||
const orderId = await addOrder({
|
||||
items: [...items],
|
||||
total: totalAmount,
|
||||
@@ -147,7 +124,7 @@ export default function CheckoutPage() {
|
||||
shippingAddress: shippingAddressStr
|
||||
});
|
||||
|
||||
// 3. Handle Online Payment via Zibal IPG
|
||||
// 4. Handle Online Payment via Zibal IPG
|
||||
if (paymentMethod === 'online') {
|
||||
try {
|
||||
const res = await api.post('/payment/zibal/initiate', { orderId });
|
||||
@@ -158,22 +135,20 @@ export default function CheckoutPage() {
|
||||
} else {
|
||||
toast.error("خطا در ایجاد تراکنش پرداخت زیبال");
|
||||
}
|
||||
} catch (gatewayErr: any) {
|
||||
const errMsg =
|
||||
gatewayErr.response?.data?.message ||
|
||||
gatewayErr.message ||
|
||||
"خطا در اتصال به درگاه پرداخت زیبال";
|
||||
} catch (gatewayErr: unknown) {
|
||||
const gErr = gatewayErr as { response?: { data?: { message?: string } }; message?: string };
|
||||
const errMsg = gErr.response?.data?.message || gErr.message || "خطا در اتصال به درگاه پرداخت زیبال";
|
||||
toast.error(errMsg);
|
||||
router.push(`/checkout/success/${orderId}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Re-fetch user profile from backend to sync PostgreSQL wallet balance and charity donation total
|
||||
// 5. Re-fetch user profile from backend to sync PostgreSQL wallet balance and charity donation total
|
||||
const { fetchProfile } = useUserStore.getState();
|
||||
await fetchProfile();
|
||||
|
||||
// Update pet consumptions and charity contributions for active pet
|
||||
// 6. Update pet consumptions and charity contributions for active pet
|
||||
const targetPet = activePet || usePetStore.getState().pets[0];
|
||||
if (targetPet) {
|
||||
const newConsumptions = [...(targetPet.consumptions || [])];
|
||||
@@ -201,9 +176,12 @@ export default function CheckoutPage() {
|
||||
toast.success("سفارش شما با موفقیت ثبت شد!");
|
||||
router.push(`/checkout/success/${orderId}`);
|
||||
} catch (err: unknown) {
|
||||
// Re-fetch profile to guarantee local state is always identical to PostgreSQL
|
||||
useUserStore.getState().fetchProfile().catch(() => {});
|
||||
const errorObj = err as { response?: { data?: { message?: string; details?: Array<{ message?: string }> } }; message?: string };
|
||||
const backendMessage = errorObj.response?.data?.message || errorObj.response?.data?.details?.[0]?.message || errorObj.message;
|
||||
if (backendMessage && !backendMessage.includes("Request failed")) {
|
||||
// Only toast if message exists and is not a generic duplicate
|
||||
if (backendMessage && !backendMessage.includes("Request failed") && !backendMessage.includes("خطای غیرمنتظره")) {
|
||||
toast.error(`خطا در ثبت سفارش: ${backendMessage}`);
|
||||
}
|
||||
} finally {
|
||||
|
||||
Reference in new issue
Block a user