fix(order): robust shipping address extraction for sms and enable address editing in checkout
This commit is contained in:
1 parent
174a2f8cab
commit
9e3ea3a1b1
3 files changed
+192
-28
No files matched your search
@@ -310,7 +310,56 @@ export class OrdersService {
|
||||
}
|
||||
|
||||
private buildOrderEventData(order: any, user: any): Record<string, any> {
|
||||
const shipping = (order.shippingAddress as Record<string, any>) || {};
|
||||
const rawShipping = order.shippingAddress;
|
||||
let shipping: Record<string, any> = {};
|
||||
|
||||
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:
|
||||
|
||||
@@ -495,7 +495,47 @@ export class PaymentService {
|
||||
transaction.user?.mobile ||
|
||||
(transaction.rawRequest as { mobile?: string })?.mobile;
|
||||
|
||||
const shipping = (order?.shippingAddress as unknown as Record<string, any>) || {};
|
||||
const rawShipping = order?.shippingAddress;
|
||||
let shipping: Record<string, any> = {};
|
||||
|
||||
if (typeof rawShipping === 'object' && rawShipping !== null) {
|
||||
shipping = rawShipping as Record<string, any>;
|
||||
} 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: 'آنلاین',
|
||||
|
||||
@@ -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<string>('card');
|
||||
const [showTopUpModal, setShowTopUpModal] = useState(false);
|
||||
const [showAddressModal, setShowAddressModal] = useState(false);
|
||||
const [editingAddress, setEditingAddress] = useState<any>(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 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowAddressModal(true)}
|
||||
onClick={() => {
|
||||
setEditingAddress(null);
|
||||
setShowAddressModal(true);
|
||||
}}
|
||||
className="flex items-center gap-1 text-canina-blue font-bold text-xs hover:underline bg-canina-blue/5 border border-canina-blue/20 px-2.5 py-1 rounded-lg transition-all cursor-pointer"
|
||||
>
|
||||
<PlusCircle className="w-3.5 h-3.5" />
|
||||
@@ -375,7 +380,7 @@ export default function CheckoutPage() {
|
||||
key={addr.id}
|
||||
onClick={() => setSelectedAddressId(addr.id)}
|
||||
className={cn(
|
||||
"p-3 rounded-xl border transition-all flex items-start gap-2.5 cursor-pointer",
|
||||
"p-3 rounded-xl border transition-all flex items-start gap-2.5 cursor-pointer group relative",
|
||||
selectedAddressId === addr.id ? "border-canina-blue bg-canina-blue/5 shadow-xs" : "border-medical-gray-200 hover:border-medical-gray-300"
|
||||
)}
|
||||
>
|
||||
@@ -386,12 +391,26 @@ export default function CheckoutPage() {
|
||||
onChange={() => setSelectedAddressId(addr.id)}
|
||||
className="mt-1 shrink-0 cursor-pointer"
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-0.5">
|
||||
<span className="font-black text-xs text-medical-gray-900">{addr.title}</span>
|
||||
{addr.isDefault && (
|
||||
<span className="bg-canina-blue/10 text-canina-blue text-[9px] font-bold px-1.5 py-0.2 rounded-md">پیشفرض</span>
|
||||
)}
|
||||
<div className="flex-1 min-w-0 pr-1">
|
||||
<div className="flex items-center justify-between mb-0.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-black text-xs text-medical-gray-900">{addr.title}</span>
|
||||
{addr.isDefault && (
|
||||
<span className="bg-canina-blue/10 text-canina-blue text-[9px] font-bold px-1.5 py-0.2 rounded-md">پیشفرض</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setEditingAddress(addr);
|
||||
setShowAddressModal(true);
|
||||
}}
|
||||
className="p-1 rounded-md text-medical-gray-400 hover:text-canina-blue hover:bg-canina-blue/10 transition-colors"
|
||||
title="ویرایش این آدرس"
|
||||
>
|
||||
<Edit2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-[11px] text-medical-gray-600 line-clamp-2 leading-relaxed">{addr.province}، {addr.city}، {addr.detail}</p>
|
||||
<p className="text-[10px] text-medical-gray-400 font-bold mt-1">گیرنده: {addr.receptorName} ({toPersian(addr.phone)})</p>
|
||||
@@ -852,17 +871,27 @@ export default function CheckoutPage() {
|
||||
|
||||
<AddressModal
|
||||
isOpen={showAddressModal}
|
||||
onClose={() => 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);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
Reference in new issue
Block a user