fix: resolve wallet topup callback and verify flow, fix admin orders BigInt serialization 500 error, and fix reactive B2B settings toggle
Deploy Canina / deploy (push) Successful in 1m41s
Deploy Canina / deploy (push) Successful in 1m41s
This commit is contained in:
1 parent
42707c04cf
commit
b527befe4a
10 files changed
+176
-29
No files matched your search
@@ -9,6 +9,11 @@ import { PrismaExceptionFilter } from './common/filters/prisma-exception.filter'
|
||||
import { DecimalInterceptor } from './common/interceptors/decimal.interceptor';
|
||||
import helmet from 'helmet';
|
||||
|
||||
// Ensure BigInt can be serialized to JSON across all NestJS / Express responses
|
||||
(BigInt.prototype as any).toJSON = function () {
|
||||
return Number(this);
|
||||
};
|
||||
|
||||
async function bootstrap() {
|
||||
process.env.JWT_ACCESS_SECRET =
|
||||
process.env.JWT_ACCESS_SECRET ||
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
HttpStatus,
|
||||
Headers,
|
||||
Ip,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import type { Request, Response } from 'express';
|
||||
import { PaymentService } from './payment.service';
|
||||
@@ -138,6 +139,25 @@ export class PaymentController {
|
||||
}
|
||||
}
|
||||
|
||||
@Get('zibal/verify')
|
||||
@ApiOperation({ summary: 'استعلام و تایید تراکنش زیبال توسط کلاینت' })
|
||||
async verifyPaymentDirect(
|
||||
@Query('trackId') trackId: string,
|
||||
@Query('success') success?: string,
|
||||
@Query('status') status?: string,
|
||||
@Query('orderId') orderId?: string,
|
||||
@Ip() ip?: string,
|
||||
@Headers('user-agent') userAgent?: string,
|
||||
) {
|
||||
if (!trackId) {
|
||||
throw new BadRequestException('trackId is required');
|
||||
}
|
||||
return this.paymentService.verifyAndProcess(trackId, success, status, orderId, {
|
||||
ipAddress: ip,
|
||||
userAgent,
|
||||
});
|
||||
}
|
||||
|
||||
@Post('zibal/callback')
|
||||
@ApiOperation({ summary: 'دریافت وبهوک / کالبک لِیزی زیبال' })
|
||||
async handleZibalLazyCallback(
|
||||
|
||||
@@ -56,9 +56,9 @@ export class PaymentService {
|
||||
);
|
||||
}
|
||||
|
||||
const frontendUrl = await this.zibalService.getFrontendUrl();
|
||||
const backendUrl = await this.zibalService.getBackendUrl();
|
||||
const callbackUrl =
|
||||
customCallbackUrl || `${frontendUrl}/payment/verify?orderId=${order.id}`;
|
||||
customCallbackUrl || `${backendUrl}/payment/zibal/callback?orderId=${order.id}`;
|
||||
|
||||
const requestPayload = {
|
||||
amountRials,
|
||||
@@ -151,9 +151,9 @@ export class PaymentService {
|
||||
}
|
||||
|
||||
const amountRials = Math.round(amountTomans * 10);
|
||||
const frontendUrl = await this.zibalService.getFrontendUrl();
|
||||
const backendUrl = await this.zibalService.getBackendUrl();
|
||||
const callbackUrl =
|
||||
customCallbackUrl || `${frontendUrl}/payment/verify?type=wallet`;
|
||||
customCallbackUrl || `${backendUrl}/payment/zibal/callback?type=WALLET_TOPUP`;
|
||||
|
||||
const requestPayload = {
|
||||
amountRials,
|
||||
|
||||
@@ -122,6 +122,31 @@ export class ZibalService implements IPaymentGateway {
|
||||
return envUrl ? envUrl.replace(/\/+$/, '') : 'https://canina.ir';
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves base backend API URL for Zibal callbacks
|
||||
*/
|
||||
async getBackendUrl(): Promise<string> {
|
||||
try {
|
||||
const setting = await this.prisma.uiText.findUnique({
|
||||
where: { key: 'BACKEND_URL' },
|
||||
});
|
||||
if (setting && setting.value && setting.value.trim() !== '') {
|
||||
return setting.value.trim().replace(/\/+$/, '');
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.warn(`Could not read BACKEND_URL from db: ${e}`);
|
||||
}
|
||||
|
||||
const envUrl = process.env.BACKEND_URL || process.env.API_URL;
|
||||
if (envUrl) return envUrl.replace(/\/+$/, '');
|
||||
|
||||
const frontendUrl = await this.getFrontendUrl();
|
||||
if (frontendUrl.includes('stage')) {
|
||||
return 'https://stageapi.canina.ir/api';
|
||||
}
|
||||
return 'https://api.canina.ir/api';
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. Request Payment (درخواست پرداخت با قابلیت Retry)
|
||||
* Amount must be in Rials.
|
||||
|
||||
@@ -22,14 +22,40 @@ export class SettingsService {
|
||||
this.prisma.setting.findMany(),
|
||||
]);
|
||||
|
||||
const merged = [...uiTexts];
|
||||
const mergedMap = new Map<string, string>();
|
||||
|
||||
// 1. Add all from uiTexts
|
||||
uiTexts.forEach((u) => {
|
||||
mergedMap.set(u.key, u.value);
|
||||
});
|
||||
|
||||
// 2. Add from settings and unpack object keys
|
||||
settings.forEach((s) => {
|
||||
const valStr =
|
||||
typeof s.value === 'string' ? s.value : JSON.stringify(s.value);
|
||||
merged.push({ key: s.key, value: valStr });
|
||||
mergedMap.set(s.key, valStr);
|
||||
|
||||
if (
|
||||
typeof s.value === 'object' &&
|
||||
s.value !== null &&
|
||||
!Array.isArray(s.value)
|
||||
) {
|
||||
Object.entries(s.value as Record<string, any>).forEach(([k, v]) => {
|
||||
mergedMap.set(k, String(v));
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return merged;
|
||||
// If b2bRegistrationOpen is set, sync b2b_enabled
|
||||
if (mergedMap.has('b2bRegistrationOpen')) {
|
||||
const val = mergedMap.get('b2bRegistrationOpen')!;
|
||||
mergedMap.set('b2b_enabled', val);
|
||||
}
|
||||
|
||||
return Array.from(mergedMap.entries()).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
|
||||
async updateUiText(key: string, value: string) {
|
||||
@@ -80,11 +106,35 @@ export class SettingsService {
|
||||
|
||||
async updateCategorySetting(category: string, value: Prisma.InputJsonValue) {
|
||||
const key = `${category}_config`;
|
||||
return this.prisma.setting.upsert({
|
||||
const res = await this.prisma.setting.upsert({
|
||||
where: { key },
|
||||
update: { category, value },
|
||||
create: { key, category, value },
|
||||
});
|
||||
|
||||
// If system config is updated, also sync individual keys into uiText for fast & reliable lookup
|
||||
if (category === 'system' && typeof value === 'object' && value !== null) {
|
||||
const obj = value as Record<string, any>;
|
||||
const promises: Promise<any>[] = [];
|
||||
if ('b2bRegistrationOpen' in obj) {
|
||||
const valStr = String(obj.b2bRegistrationOpen);
|
||||
promises.push(
|
||||
this.prisma.uiText.upsert({
|
||||
where: { key: 'b2bRegistrationOpen' },
|
||||
update: { value: valStr },
|
||||
create: { key: 'b2bRegistrationOpen', value: valStr },
|
||||
}),
|
||||
this.prisma.uiText.upsert({
|
||||
where: { key: 'b2b_enabled' },
|
||||
update: { value: valStr },
|
||||
create: { key: 'b2b_enabled', value: valStr },
|
||||
}),
|
||||
);
|
||||
}
|
||||
await Promise.all(promises);
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
async getSmsSettings() {
|
||||
|
||||
@@ -38,6 +38,7 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
|
||||
|
||||
const fetchSettings = useSettingsStore((state) => state.fetchSettings);
|
||||
const getText = useSettingsStore((state) => state.getText);
|
||||
const isB2BEnabled = useSettingsStore((state) => state.getBoolean('b2bRegistrationOpen', true) && state.getBoolean('b2b_enabled', true));
|
||||
|
||||
useEffect(() => {
|
||||
fetchSettings();
|
||||
@@ -105,7 +106,7 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
|
||||
</main>
|
||||
<Footer onNavigate={handleNavigate} onShopNavigate={navigateToShop} onB2BOpen={() => setB2BPortalOpen(true)} />
|
||||
|
||||
{isB2BPortalOpen && useSettingsStore.getState().getBoolean('b2bRegistrationOpen', true) && useSettingsStore.getState().getBoolean('b2b_enabled', true) && (
|
||||
{isB2BPortalOpen && isB2BEnabled && (
|
||||
<B2BPortal onClose={() => setB2BPortalOpen(false)} />
|
||||
)}
|
||||
<CartDrawer
|
||||
|
||||
@@ -34,6 +34,7 @@ function VerifyContent() {
|
||||
const paymentType = searchParams.get("type") || "ORDER";
|
||||
|
||||
const isSuccess = successParam === "1";
|
||||
const isWallet = paymentType.toLowerCase().includes("wallet");
|
||||
const [orderDetails, setOrderDetails] = useState<any>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [retrying, setRetrying] = useState(false);
|
||||
@@ -42,12 +43,26 @@ function VerifyContent() {
|
||||
const { fetchProfile } = useUserStore();
|
||||
|
||||
useEffect(() => {
|
||||
// If trackId is present and success=1, ping server to guarantee idempotent verification & refresh profile
|
||||
if (trackId && isSuccess) {
|
||||
api.get(`/payment/zibal/verify?trackId=${trackId}&success=${successParam}&status=${searchParams.get("status") || "2"}`)
|
||||
.then((res) => {
|
||||
if (res.data?.amount && !amountParam) {
|
||||
// Updated verified amount
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
fetchProfile().catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
if (isSuccess) {
|
||||
clearCart();
|
||||
fetchProfile().catch(() => {});
|
||||
}
|
||||
|
||||
if (orderId) {
|
||||
if (orderId && !isWallet) {
|
||||
setLoading(true);
|
||||
api
|
||||
.get(`/orders/${orderId}`)
|
||||
@@ -57,7 +72,7 @@ function VerifyContent() {
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false));
|
||||
}
|
||||
}, [isSuccess, orderId, clearCart, fetchProfile]);
|
||||
}, [isSuccess, trackId, successParam, orderId, isWallet, clearCart, fetchProfile, amountParam, searchParams]);
|
||||
|
||||
const handleCopy = (text: string, title: string) => {
|
||||
navigator.clipboard.writeText(text);
|
||||
@@ -65,6 +80,11 @@ function VerifyContent() {
|
||||
};
|
||||
|
||||
const handleRetryPayment = async () => {
|
||||
if (isWallet) {
|
||||
router.push("/dashboard");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!orderId) {
|
||||
router.push("/checkout");
|
||||
return;
|
||||
@@ -131,12 +151,20 @@ function VerifyContent() {
|
||||
{/* Title & Status */}
|
||||
<div>
|
||||
<h1 className="text-2xl sm:text-3xl font-black text-medical-gray-900 italic">
|
||||
{isSuccess ? "پرداخت با موفقیت انجام شد" : "پرداخت ناموفق بود"}
|
||||
{isSuccess
|
||||
? isWallet
|
||||
? "شارژ کیف پول با موفقیت انجام شد"
|
||||
: "پرداخت با موفقیت انجام شد"
|
||||
: isWallet
|
||||
? "پرداخت شارژ کیف پول ناموفق بود"
|
||||
: "پرداخت ناموفق بود"}
|
||||
</h1>
|
||||
<p className="text-xs sm:text-sm text-medical-gray-500 font-bold mt-1">
|
||||
{messageParam ||
|
||||
(isSuccess
|
||||
? "سفارش شما در سامانه ثبت و در حال آمادهسازی و ارسال است."
|
||||
? isWallet
|
||||
? "موجودی کیف پول شما با موفقیت افزایش یافت و هماکنون در حساب کاربری شما قابل استفاده است."
|
||||
: "سفارش شما در سامانه ثبت و در حال آمادهسازی و ارسال است."
|
||||
: "تراکنش بانکی تکمیل نشد یا توسط کاربر لغو گردید.")}
|
||||
</p>
|
||||
</div>
|
||||
@@ -171,7 +199,7 @@ function VerifyContent() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleCopy(refNumber, "شماره مرجع بانکی")}
|
||||
className="p-1 rounded hover:bg-white text-medical-gray-400 hover:text-canina-blue"
|
||||
className="p-1 rounded hover:bg-white text-medical-gray-400 hover:text-canina-blue cursor-pointer"
|
||||
title="کپی"
|
||||
>
|
||||
<Copy className="w-3.5 h-3.5" />
|
||||
@@ -188,7 +216,7 @@ function VerifyContent() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleCopy(trackId, "شناسه پیگیری زیبال")}
|
||||
className="p-1 rounded hover:bg-white text-medical-gray-400 hover:text-canina-blue"
|
||||
className="p-1 rounded hover:bg-white text-medical-gray-400 hover:text-canina-blue cursor-pointer"
|
||||
title="کپی"
|
||||
>
|
||||
<Copy className="w-3.5 h-3.5" />
|
||||
@@ -223,18 +251,31 @@ function VerifyContent() {
|
||||
<div className="mt-8 space-y-3">
|
||||
{isSuccess ? (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
{orderId && (
|
||||
{isWallet ? (
|
||||
<button
|
||||
onClick={() => router.push(`/checkout/success/${orderId}`)}
|
||||
className="w-full bg-canina-blue text-white py-4 rounded-2xl font-black text-sm hover:bg-blue-700 transition-all flex items-center justify-center gap-2 shadow-lg shadow-canina-blue/20"
|
||||
type="button"
|
||||
onClick={() => router.push("/dashboard")}
|
||||
className="w-full bg-canina-blue text-white py-4 rounded-2xl font-black text-sm hover:bg-blue-700 transition-all flex items-center justify-center gap-2 shadow-lg shadow-canina-blue/20 cursor-pointer"
|
||||
>
|
||||
<ShoppingBag className="w-4 h-4" />
|
||||
<span>مشاهده جزئیات سفارش</span>
|
||||
<Receipt className="w-4 h-4" />
|
||||
<span>مشاهده کیف پول در داشبورد</span>
|
||||
</button>
|
||||
) : (
|
||||
orderId && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => router.push(`/checkout/success/${orderId}`)}
|
||||
className="w-full bg-canina-blue text-white py-4 rounded-2xl font-black text-sm hover:bg-blue-700 transition-all flex items-center justify-center gap-2 shadow-lg shadow-canina-blue/20 cursor-pointer"
|
||||
>
|
||||
<ShoppingBag className="w-4 h-4" />
|
||||
<span>مشاهده جزئیات سفارش</span>
|
||||
</button>
|
||||
)
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => router.push("/shop")}
|
||||
className="w-full bg-medical-gray-100 text-medical-gray-900 py-4 rounded-2xl font-black text-sm hover:bg-medical-gray-200 transition-all flex items-center justify-center gap-2"
|
||||
className="w-full bg-medical-gray-100 text-medical-gray-900 py-4 rounded-2xl font-black text-sm hover:bg-medical-gray-200 transition-all flex items-center justify-center gap-2 cursor-pointer"
|
||||
>
|
||||
<span>بازگشت به فروشگاه</span>
|
||||
<ArrowRight className="w-4 h-4 rotate-180" />
|
||||
@@ -243,19 +284,21 @@ function VerifyContent() {
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleRetryPayment}
|
||||
disabled={retrying}
|
||||
className="w-full bg-canina-blue text-white py-4 rounded-2xl font-black text-sm hover:bg-blue-700 transition-all flex items-center justify-center gap-2 shadow-lg shadow-canina-blue/20 disabled:opacity-50"
|
||||
className="w-full bg-canina-blue text-white py-4 rounded-2xl font-black text-sm hover:bg-blue-700 transition-all flex items-center justify-center gap-2 shadow-lg shadow-canina-blue/20 disabled:opacity-50 cursor-pointer"
|
||||
>
|
||||
<RotateCcw className={cn("w-4 h-4", retrying && "animate-spin")} />
|
||||
<span>{retrying ? "در حال انتقال به درگاه..." : "تلاش مجدد برای پرداخت"}</span>
|
||||
<span>{retrying ? "در حال انتقال به درگاه..." : isWallet ? "تلاش مجدد برای شارژ" : "تلاش مجدد برای پرداخت"}</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => router.push("/checkout")}
|
||||
className="w-full bg-medical-gray-100 text-medical-gray-900 py-4 rounded-2xl font-black text-sm hover:bg-medical-gray-200 transition-all flex items-center justify-center gap-2"
|
||||
type="button"
|
||||
onClick={() => router.push(isWallet ? "/dashboard" : "/checkout")}
|
||||
className="w-full bg-medical-gray-100 text-medical-gray-900 py-4 rounded-2xl font-black text-sm hover:bg-medical-gray-200 transition-all flex items-center justify-center gap-2 cursor-pointer"
|
||||
>
|
||||
<span>بازگشت به سبد خرید</span>
|
||||
<span>{isWallet ? "بازگشت به داشبورد" : "بازگشت به سبد خرید"}</span>
|
||||
<ArrowRight className="w-4 h-4 rotate-180" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -63,6 +63,7 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
|
||||
const [showNewPassword, setShowNewPassword] = useState(false);
|
||||
const otpInputRef = useRef<HTMLInputElement>(null);
|
||||
const phoneNumberRef = useRef(phoneNumber);
|
||||
const isB2BEnabled = useSettingsStore((s) => s.getBoolean('b2bRegistrationOpen', true) && s.getBoolean('b2b_enabled', true));
|
||||
|
||||
useEffect(() => {
|
||||
phoneNumberRef.current = phoneNumber;
|
||||
@@ -483,7 +484,7 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{useSettingsStore.getState().getBoolean('b2bRegistrationOpen', true) && useSettingsStore.getState().getBoolean('b2b_enabled', true) && (
|
||||
{isB2BEnabled && (
|
||||
<div className="pt-3 border-t border-medical-gray-100">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -15,6 +15,7 @@ export default function Footer({
|
||||
onB2BOpen?: () => void;
|
||||
}) {
|
||||
const getText = useSettingsStore(state => state.getText);
|
||||
const isB2BEnabled = useSettingsStore((s) => s.getBoolean('b2bRegistrationOpen', true) && s.getBoolean('b2b_enabled', true));
|
||||
const [showScroll, setShowScroll] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -117,7 +118,7 @@ export default function Footer({
|
||||
<span>مشاهده و دانلود کاتالوگ آنلاین محصولات</span>
|
||||
</Link>
|
||||
</li>
|
||||
{useSettingsStore.getState().getBoolean('b2bRegistrationOpen', true) && useSettingsStore.getState().getBoolean('b2b_enabled', true) && (
|
||||
{isB2BEnabled && (
|
||||
<li onClick={onB2BOpen} className="hover:text-canina-blue hover:translate-x-[-4px] transition-all cursor-pointer flex items-center gap-2 group text-blue-200">
|
||||
<div className="w-1.5 h-1.5 rounded-full bg-canina-blue group-hover:w-4 transition-all" />
|
||||
{getText('footer_link_b2b', "همکاری با کلینیکها و پتشاپها (B2B)")}
|
||||
|
||||
@@ -44,6 +44,7 @@ export default function Header({
|
||||
const userProfileRef = useRef<HTMLDivElement>(null);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
|
||||
const isB2BEnabled = useSettingsStore((s) => s.getBoolean('b2bRegistrationOpen', true) && s.getBoolean('b2b_enabled', true));
|
||||
|
||||
const [menuItems, setMenuItems] = useState<{
|
||||
id: string;
|
||||
@@ -468,7 +469,7 @@ export default function Header({
|
||||
<ShieldCheck className="w-4 h-4 text-emerald-600" />
|
||||
نمادهای اعتماد و مجوزهای رسمی
|
||||
</Link>
|
||||
{useSettingsStore.getState().getBoolean('b2bRegistrationOpen', true) && useSettingsStore.getState().getBoolean('b2b_enabled', true) && (
|
||||
{isB2BEnabled && (
|
||||
<button
|
||||
onClick={onB2BOpen}
|
||||
className="w-full text-right flex items-center gap-2 px-3 py-2 hover:bg-canina-blue/5 hover:text-canina-blue rounded-lg font-bold cursor-pointer"
|
||||
|
||||
Reference in new issue
Block a user