diff --git a/backend/src/orders/orders.service.ts b/backend/src/orders/orders.service.ts index 8ed4f30b..0cd3cfab 100644 --- a/backend/src/orders/orders.service.ts +++ b/backend/src/orders/orders.service.ts @@ -310,7 +310,56 @@ export class OrdersService { } private buildOrderEventData(order: any, user: any): Record { - const shipping = (order.shippingAddress as Record) || {}; + const rawShipping = order.shippingAddress; + let shipping: Record = {}; + + if (typeof rawShipping === 'object' && rawShipping !== null) { + shipping = rawShipping; + } else if (typeof rawShipping === 'string') { + const trimmed = rawShipping.trim(); + if (trimmed.startsWith('{') && trimmed.endsWith('}')) { + try { + shipping = JSON.parse(trimmed); + } catch { + shipping = {}; + } + } + + // If not parsed as JSON or fields are missing, extract from formatted address string: + // Pattern: "استان، شهر، آدرس پستی (کد پستی: ۱۲۳۴۵۶۷۸۹۰) (گیرنده: نام گیرنده - ۰۹۱۲۰۰۰۰۰۰۰)" + if (!shipping.province || !shipping.address) { + let text = trimmed; + + // 1. Extract recipient & phone: (گیرنده: نام گیرنده - ۰۹۱۲۰۰۰۰۰۰۰) + const recipientMatch = text.match(/\(گیرنده:\s*([^-)]+)(?:-\s*([^)]+))?\)/); + if (recipientMatch) { + if (!shipping.fullName) shipping.fullName = recipientMatch[1]?.trim(); + if (!shipping.phone && recipientMatch[2]) shipping.phone = recipientMatch[2]?.trim(); + text = text.replace(recipientMatch[0], '').trim(); + } + + // 2. Extract postal code: (کد پستی: ۱۲۳۴۵۶۷۸۹۰) + const postalMatch = text.match(/\(کد پستی:\s*([^)]+)\)/); + if (postalMatch) { + if (!shipping.postalCode) shipping.postalCode = postalMatch[1]?.trim(); + text = text.replace(postalMatch[0], '').trim(); + } + + // 3. Extract province and city: "استان، شهر، بقیه آدرس" or "استان - شهر - بقیه آدرس" + const parts = text.split(/[،,]/).map((p) => p.trim()).filter(Boolean); + if (parts.length >= 3) { + if (!shipping.province) shipping.province = parts[0]; + if (!shipping.city) shipping.city = parts[1]; + if (!shipping.address) shipping.address = parts.slice(2).join('، '); + } else if (parts.length === 2) { + if (!shipping.province) shipping.province = parts[0]; + if (!shipping.address) shipping.address = parts[1]; + } else if (parts.length === 1 && !shipping.address) { + shipping.address = parts[0]; + } + } + } + const items = order.orderItems || []; const itemsSummary = items .map( @@ -329,17 +378,40 @@ export class OrdersService { : shipping.fullName || 'مشتری' ).trim(); + const recipientFullName = ( + shipping.fullName || + shipping.receptorName || + customerFullName + ).trim(); + + const recipientMobile = ( + shipping.phone || + user?.mobile || + '' + ).trim(); + + const provinceCity = ( + shipping.province && shipping.city + ? `${shipping.province} - ${shipping.city}` + : shipping.province || shipping.city || '' + ).trim(); + + const addressDetail = ( + shipping.address || + shipping.detail || + (typeof rawShipping === 'string' ? rawShipping : '') + ).trim(); + return { orderNumber: order.trackingNumber || order.id.slice(0, 8), amount: Number(order.totalAmount || 0).toLocaleString('fa-IR'), customerName: customerFullName, customerPhone: user?.mobile || shipping.phone || '', - recipientName: shipping.fullName || customerFullName, - recipientPhone: shipping.phone || user?.mobile || '', - provinceCity: - `${shipping.province || ''} - ${shipping.city || ''}`.trim(), - postalCode: shipping.postalCode || '', - address: shipping.address || '', + recipientName: recipientFullName, + recipientPhone: recipientMobile, + provinceCity: provinceCity || 'ثبت نشده', + postalCode: shipping.postalCode || shipping.zipCode || '', + address: addressDetail || '', itemsSummary, itemCount: String(itemCount), paymentMethod: diff --git a/backend/src/payment/payment.service.ts b/backend/src/payment/payment.service.ts index d5800494..5c3643dc 100644 --- a/backend/src/payment/payment.service.ts +++ b/backend/src/payment/payment.service.ts @@ -495,7 +495,47 @@ export class PaymentService { transaction.user?.mobile || (transaction.rawRequest as { mobile?: string })?.mobile; - const shipping = (order?.shippingAddress as unknown as Record) || {}; + const rawShipping = order?.shippingAddress; + let shipping: Record = {}; + + if (typeof rawShipping === 'object' && rawShipping !== null) { + shipping = rawShipping as Record; + } else if (typeof rawShipping === 'string') { + const trimmed = rawShipping.trim(); + if (trimmed.startsWith('{') && trimmed.endsWith('}')) { + try { + shipping = JSON.parse(trimmed); + } catch { + shipping = {}; + } + } + if (!shipping.province || !shipping.address) { + let text = trimmed; + const recipientMatch = text.match(/\(گیرنده:\s*([^-)]+)(?:-\s*([^)]+))?\)/); + if (recipientMatch) { + if (!shipping.fullName) shipping.fullName = recipientMatch[1]?.trim(); + if (!shipping.phone && recipientMatch[2]) shipping.phone = recipientMatch[2]?.trim(); + text = text.replace(recipientMatch[0], '').trim(); + } + const postalMatch = text.match(/\(کد پستی:\s*([^)]+)\)/); + if (postalMatch) { + if (!shipping.postalCode) shipping.postalCode = postalMatch[1]?.trim(); + text = text.replace(postalMatch[0], '').trim(); + } + const parts = text.split(/[،,]/).map((p) => p.trim()).filter(Boolean); + if (parts.length >= 3) { + if (!shipping.province) shipping.province = parts[0]; + if (!shipping.city) shipping.city = parts[1]; + if (!shipping.address) shipping.address = parts.slice(2).join('، '); + } else if (parts.length === 2) { + if (!shipping.province) shipping.province = parts[0]; + if (!shipping.address) shipping.address = parts[1]; + } else if (parts.length === 1 && !shipping.address) { + shipping.address = parts[0]; + } + } + } + const items = order?.orderItems || []; const itemsSummary = items .map( @@ -516,6 +556,30 @@ export class PaymentService { : shipping.fullName || 'مشتری' ).trim(); + const recipientFullName = ( + shipping.fullName || + shipping.receptorName || + customerName + ).trim(); + + const recipientMobile = ( + shipping.phone || + customerMobile || + '' + ).trim(); + + const provinceCity = ( + shipping.province && shipping.city + ? `${shipping.province} - ${shipping.city}` + : shipping.province || shipping.city || '' + ).trim(); + + const addressDetail = ( + shipping.address || + shipping.detail || + (typeof rawShipping === 'string' ? rawShipping : '') + ).trim(); + const orderData = { orderNumber: order?.trackingNumber || @@ -525,12 +589,11 @@ export class PaymentService { amount: Number(transaction.amount).toLocaleString('fa-IR'), customerName, customerPhone: customerMobile || '', - recipientName: shipping.fullName || customerName, - recipientPhone: shipping.phone || customerMobile || '', - provinceCity: - `${shipping.province || ''} - ${shipping.city || ''}`.trim(), - postalCode: shipping.postalCode || '', - address: shipping.address || '', + recipientName: recipientFullName, + recipientPhone: recipientMobile, + provinceCity: provinceCity || 'ثبت نشده', + postalCode: shipping.postalCode || shipping.zipCode || '', + address: addressDetail || '', itemsSummary, itemCount: String(itemCount), paymentMethod: 'آنلاین', diff --git a/frontend/application/components/CheckoutPage.tsx b/frontend/application/components/CheckoutPage.tsx index 9f1b935f..1475c99a 100644 --- a/frontend/application/components/CheckoutPage.tsx +++ b/frontend/application/components/CheckoutPage.tsx @@ -14,7 +14,8 @@ import { PlusCircle, Copy, Phone, - AlertCircle + AlertCircle, + Edit2 } from "lucide-react"; import { toPersian, cn } from "../lib/utils"; import { PRODUCTS } from "../lib/data/products"; @@ -45,6 +46,7 @@ export default function CheckoutPage() { const [paymentMethod, setPaymentMethod] = useState('card'); const [showTopUpModal, setShowTopUpModal] = useState(false); const [showAddressModal, setShowAddressModal] = useState(false); + const [editingAddress, setEditingAddress] = useState(null); const isRefillEnabled = useSettingsStore((state) => state.getText('REFILL_SUBSCRIPTION_ENABLED', 'false') === 'true'); const refillPercent = Number(useSettingsStore((state) => state.getText('REFILL_REWARD_PERCENT', '5'))) || 5; @@ -358,7 +360,10 @@ export default function CheckoutPage() { {isLoggedIn && (

{addr.province}، {addr.city}، {addr.detail}

گیرنده: {addr.receptorName} ({toPersian(addr.phone)})

@@ -852,17 +871,27 @@ export default function CheckoutPage() { setShowAddressModal(false)} - onSave={async (newAddr) => { + onClose={() => { + setShowAddressModal(false); + setEditingAddress(null); + }} + editingAddress={editingAddress} + onSave={async (savedAddr) => { try { - await useUserStore.getState().addAddress(newAddr); + if (editingAddress) { + await useUserStore.getState().updateAddress(savedAddr.id, savedAddr); + } else { + await useUserStore.getState().addAddress(savedAddr); + } const updatedProfile = useUserStore.getState().profile; if (updatedProfile.addresses && updatedProfile.addresses.length > 0) { - setSelectedAddressId(updatedProfile.addresses[0].id); + const matched = updatedProfile.addresses.find((a) => a.id === savedAddr.id); + setSelectedAddressId(matched ? matched.id : updatedProfile.addresses[0].id); } setShowAddressModal(false); + setEditingAddress(null); } catch (e) { - console.error("Failed to add address", e); + console.error("Failed to save address", e); } }} />