test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
This commit is contained in:
1 parent
1e73715169
commit
ddbf1ca026
439 files changed
+32911
-6107
No files matched your search
@@ -3,7 +3,7 @@ export interface SmsRule {
|
||||
title: string;
|
||||
event: string; // ORDER_PAID, ORDER_CREATED, ORDER_SHIPPED, B2B_SUBMITTED, CONTACT_SUBMITTED, OTP
|
||||
enabled: boolean;
|
||||
recipientType: 'customer' | 'admin' | 'custom';
|
||||
recipientType: "customer" | "admin" | "custom";
|
||||
customPhone?: string;
|
||||
patternId: number;
|
||||
variables: string[]; // Ordered parameter keys: e.g. ['orderNumber', 'recipientName', 'address']
|
||||
@@ -25,249 +25,249 @@ export interface SmsEventDefinition {
|
||||
|
||||
export const SMS_EVENT_DEFINITIONS: SmsEventDefinition[] = [
|
||||
{
|
||||
event: 'ORDER_PAID',
|
||||
label: 'پرداخت موفق سفارش (Order Paid)',
|
||||
event: "ORDER_PAID",
|
||||
label: "پرداخت موفق سفارش (Order Paid)",
|
||||
description:
|
||||
'هنگام پرداخت موفق آنلاین در درگاه بانکی یا تسویه حساب از طریق کیف پول',
|
||||
"هنگام پرداخت موفق آنلاین در درگاه بانکی یا تسویه حساب از طریق کیف پول",
|
||||
variables: [
|
||||
{
|
||||
key: 'orderNumber',
|
||||
label: 'شماره سفارش / فاکتور',
|
||||
sample: 'CN-140308-01',
|
||||
key: "orderNumber",
|
||||
label: "شماره سفارش / فاکتور",
|
||||
sample: "CN-140308-01",
|
||||
},
|
||||
{ key: 'amount', label: 'مبلغ پرداختی (تومان)', sample: '۱,۴۵۰,۰۰۰' },
|
||||
{ key: 'customerName', label: 'نام خریدار', sample: 'علی محمدی' },
|
||||
{ key: "amount", label: "مبلغ پرداختی (تومان)", sample: "۱,۴۵۰,۰۰۰" },
|
||||
{ key: "customerName", label: "نام خریدار", sample: "علی محمدی" },
|
||||
{
|
||||
key: 'customerPhone',
|
||||
label: 'شماره موبایل خریدار',
|
||||
sample: '09123456789',
|
||||
key: "customerPhone",
|
||||
label: "شماره موبایل خریدار",
|
||||
sample: "09123456789",
|
||||
},
|
||||
{ key: 'recipientName', label: 'نام تحویلگیرنده', sample: 'رضا حسینی' },
|
||||
{ key: "recipientName", label: "نام تحویلگیرنده", sample: "رضا حسینی" },
|
||||
{
|
||||
key: 'recipientPhone',
|
||||
label: 'تلفن تماس تحویلگیرنده',
|
||||
sample: '09351234567',
|
||||
key: "recipientPhone",
|
||||
label: "تلفن تماس تحویلگیرنده",
|
||||
sample: "09351234567",
|
||||
},
|
||||
{
|
||||
key: 'provinceCity',
|
||||
label: 'استان و شهر مقصد',
|
||||
sample: 'تهران - تهران',
|
||||
key: "provinceCity",
|
||||
label: "استان و شهر مقصد",
|
||||
sample: "تهران - تهران",
|
||||
},
|
||||
{ key: 'postalCode', label: 'کد پستی ۱۰ رقمی', sample: '1967812345' },
|
||||
{ key: "postalCode", label: "کد پستی ۱۰ رقمی", sample: "1967812345" },
|
||||
{
|
||||
key: 'address',
|
||||
label: 'نشانی کامل پستی',
|
||||
sample: 'خیابان ولیعصر، کوچه بهار، پلاک ۴',
|
||||
key: "address",
|
||||
label: "نشانی کامل پستی",
|
||||
sample: "خیابان ولیعصر، کوچه بهار، پلاک ۴",
|
||||
},
|
||||
{
|
||||
key: 'itemsSummary',
|
||||
label: 'خلاصه اقلام سفارش',
|
||||
sample: 'شیر خشک توله سگ (۲)',
|
||||
key: "itemsSummary",
|
||||
label: "خلاصه اقلام سفارش",
|
||||
sample: "شیر خشک توله سگ (۲)",
|
||||
},
|
||||
{ key: 'itemCount', label: 'تعداد کل اقلام', sample: '۲' },
|
||||
{ key: 'paymentMethod', label: 'روش پرداخت', sample: 'آنلاین' },
|
||||
{ key: 'orderDate', label: 'تاریخ ثبت سفارش', sample: '۱۴۰۳/۰۶/۱۵' },
|
||||
{ key: "itemCount", label: "تعداد کل اقلام", sample: "۲" },
|
||||
{ key: "paymentMethod", label: "روش پرداخت", sample: "آنلاین" },
|
||||
{ key: "orderDate", label: "تاریخ ثبت سفارش", sample: "۱۴۰۳/۰۶/۱۵" },
|
||||
{
|
||||
key: 'refNumber',
|
||||
label: 'شماره پیگیری پرداخت بانکی',
|
||||
sample: '83920192',
|
||||
key: "refNumber",
|
||||
label: "شماره پیگیری پرداخت بانکی",
|
||||
sample: "83920192",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
event: 'ORDER_CREATED',
|
||||
label: 'ثبت سفارش کارت به کارت یا غیرآنلاین',
|
||||
event: "ORDER_CREATED",
|
||||
label: "ثبت سفارش کارت به کارت یا غیرآنلاین",
|
||||
description:
|
||||
'هنگامی که سفارش با روش کارت به کارت در انتظار پرداخت ثبت میشود',
|
||||
"هنگامی که سفارش با روش کارت به کارت در انتظار پرداخت ثبت میشود",
|
||||
variables: [
|
||||
{
|
||||
key: 'orderNumber',
|
||||
label: 'شماره سفارش / فاکتور',
|
||||
sample: 'CN-140308-01',
|
||||
key: "orderNumber",
|
||||
label: "شماره سفارش / فاکتور",
|
||||
sample: "CN-140308-01",
|
||||
},
|
||||
{ key: 'amount', label: 'مبلغ کل سفارش', sample: '۱,۴۵۰,۰۰۰' },
|
||||
{ key: 'customerName', label: 'نام خریدار', sample: 'علی محمدی' },
|
||||
{ key: "amount", label: "مبلغ کل سفارش", sample: "۱,۴۵۰,۰۰۰" },
|
||||
{ key: "customerName", label: "نام خریدار", sample: "علی محمدی" },
|
||||
{
|
||||
key: 'customerPhone',
|
||||
label: 'شماره موبایل خریدار',
|
||||
sample: '09123456789',
|
||||
key: "customerPhone",
|
||||
label: "شماره موبایل خریدار",
|
||||
sample: "09123456789",
|
||||
},
|
||||
{ key: 'recipientName', label: 'نام تحویلگیرنده', sample: 'رضا حسینی' },
|
||||
{ key: "recipientName", label: "نام تحویلگیرنده", sample: "رضا حسینی" },
|
||||
{
|
||||
key: 'recipientPhone',
|
||||
label: 'تلفن تحویلگیرنده',
|
||||
sample: '09351234567',
|
||||
key: "recipientPhone",
|
||||
label: "تلفن تحویلگیرنده",
|
||||
sample: "09351234567",
|
||||
},
|
||||
{
|
||||
key: 'provinceCity',
|
||||
label: 'استان و شهر مقصد',
|
||||
sample: 'تهران - تهران',
|
||||
key: "provinceCity",
|
||||
label: "استان و شهر مقصد",
|
||||
sample: "تهران - تهران",
|
||||
},
|
||||
{ key: 'postalCode', label: 'کد پستی ۱۰ رقمی', sample: '1967812345' },
|
||||
{ key: "postalCode", label: "کد پستی ۱۰ رقمی", sample: "1967812345" },
|
||||
{
|
||||
key: 'address',
|
||||
label: 'نشانی پستی',
|
||||
sample: 'خیابان ولیعصر، کوچه بهار، پلاک ۴',
|
||||
key: "address",
|
||||
label: "نشانی پستی",
|
||||
sample: "خیابان ولیعصر، کوچه بهار، پلاک ۴",
|
||||
},
|
||||
{
|
||||
key: 'itemsSummary',
|
||||
label: 'خلاصه اقلام سفارش',
|
||||
sample: 'شیر خشک توله سگ (۲)',
|
||||
key: "itemsSummary",
|
||||
label: "خلاصه اقلام سفارش",
|
||||
sample: "شیر خشک توله سگ (۲)",
|
||||
},
|
||||
{ key: 'itemCount', label: 'تعداد کل اقلام', sample: '۲' },
|
||||
{ key: 'paymentMethod', label: 'روش پرداخت', sample: 'کارت به کارت' },
|
||||
{ key: 'orderDate', label: 'تاریخ ثبت سفارش', sample: '۱۴۰۳/۰۶/۱۵' },
|
||||
{ key: "itemCount", label: "تعداد کل اقلام", sample: "۲" },
|
||||
{ key: "paymentMethod", label: "روش پرداخت", sample: "کارت به کارت" },
|
||||
{ key: "orderDate", label: "تاریخ ثبت سفارش", sample: "۱۴۰۳/۰۶/۱۵" },
|
||||
],
|
||||
},
|
||||
{
|
||||
event: 'ORDER_SHIPPED',
|
||||
label: 'ارسال مرسوله و صدور بارکد پست',
|
||||
description: 'هنگام تغییر وضعیت سفارش به ارسال شده یا درج کد رهگیری پستی',
|
||||
event: "ORDER_SHIPPED",
|
||||
label: "ارسال مرسوله و صدور بارکد پست",
|
||||
description: "هنگام تغییر وضعیت سفارش به ارسال شده یا درج کد رهگیری پستی",
|
||||
variables: [
|
||||
{ key: 'orderNumber', label: 'شماره سفارش', sample: 'CN-140308-01' },
|
||||
{ key: "orderNumber", label: "شماره سفارش", sample: "CN-140308-01" },
|
||||
{
|
||||
key: 'shippingTrackingCode',
|
||||
label: 'کد رهگیری ۲۴ رقمی پست',
|
||||
sample: '184920394857283948571928',
|
||||
key: "shippingTrackingCode",
|
||||
label: "کد رهگیری ۲۴ رقمی پست",
|
||||
sample: "184920394857283948571928",
|
||||
},
|
||||
{
|
||||
key: 'trackingCode',
|
||||
label: 'کد رهگیری پستی (مترادف)',
|
||||
sample: '184920394857283948571928',
|
||||
key: "trackingCode",
|
||||
label: "کد رهگیری پستی (مترادف)",
|
||||
sample: "184920394857283948571928",
|
||||
},
|
||||
{ key: 'customerName', label: 'نام خریدار', sample: 'علی محمدی' },
|
||||
{ key: 'recipientName', label: 'نام تحویلگیرنده', sample: 'رضا حسینی' },
|
||||
{ key: "customerName", label: "نام خریدار", sample: "علی محمدی" },
|
||||
{ key: "recipientName", label: "نام تحویلگیرنده", sample: "رضا حسینی" },
|
||||
{
|
||||
key: 'customerPhone',
|
||||
label: 'شماره همراه مشتری',
|
||||
sample: '09123456789',
|
||||
key: "customerPhone",
|
||||
label: "شماره همراه مشتری",
|
||||
sample: "09123456789",
|
||||
},
|
||||
{ key: 'shippingMethod', label: 'روش ارسال', sample: 'پست پیشتاز' },
|
||||
{ key: "shippingMethod", label: "روش ارسال", sample: "پست پیشتاز" },
|
||||
],
|
||||
},
|
||||
{
|
||||
event: 'B2B_SUBMITTED',
|
||||
label: 'درخواست همکاری و عمدهفروشی B2B',
|
||||
description: 'هنگام ارسال فرم همکاری همکاران و کلینیکهای دامپزشکی',
|
||||
event: "B2B_SUBMITTED",
|
||||
label: "درخواست همکاری و عمدهفروشی B2B",
|
||||
description: "هنگام ارسال فرم همکاری همکاران و کلینیکهای دامپزشکی",
|
||||
variables: [
|
||||
{
|
||||
key: 'applicantName',
|
||||
label: 'نام متقاضی / فروشگاه',
|
||||
sample: 'پتشاپ آلفا',
|
||||
key: "applicantName",
|
||||
label: "نام متقاضی / فروشگاه",
|
||||
sample: "پتشاپ آلفا",
|
||||
},
|
||||
{
|
||||
key: 'applicantPhone',
|
||||
label: 'شماره همراه متقاضی',
|
||||
sample: '09123456789',
|
||||
key: "applicantPhone",
|
||||
label: "شماره همراه متقاضی",
|
||||
sample: "09123456789",
|
||||
},
|
||||
{
|
||||
key: 'companyName',
|
||||
label: 'نام شرکت یا مجموعه',
|
||||
sample: 'فروشگاه آلفا',
|
||||
key: "companyName",
|
||||
label: "نام شرکت یا مجموعه",
|
||||
sample: "فروشگاه آلفا",
|
||||
},
|
||||
{ key: 'businessType', label: 'نوع فعالیت', sample: 'پتشاپ' },
|
||||
{ key: 'date', label: 'تاریخ ثبت درخواست', sample: '۱۴۰۳/۰۶/۱۵' },
|
||||
{ key: "businessType", label: "نوع فعالیت", sample: "پتشاپ" },
|
||||
{ key: "date", label: "تاریخ ثبت درخواست", sample: "۱۴۰۳/۰۶/۱۵" },
|
||||
],
|
||||
},
|
||||
{
|
||||
event: 'CONTACT_SUBMITTED',
|
||||
label: 'ثبت پیام در فرم تماس با ما',
|
||||
description: 'هنگامی که کاربری در فرم تماس پیامی ارسال میکند',
|
||||
event: "CONTACT_SUBMITTED",
|
||||
label: "ثبت پیام در فرم تماس با ما",
|
||||
description: "هنگامی که کاربری در فرم تماس پیامی ارسال میکند",
|
||||
variables: [
|
||||
{ key: 'senderName', label: 'نام فرستنده پیام', sample: 'سارا احمدی' },
|
||||
{ key: "senderName", label: "نام فرستنده پیام", sample: "سارا احمدی" },
|
||||
{
|
||||
key: 'senderPhone',
|
||||
label: 'شماره همراه فرستنده',
|
||||
sample: '09123456789',
|
||||
key: "senderPhone",
|
||||
label: "شماره همراه فرستنده",
|
||||
sample: "09123456789",
|
||||
},
|
||||
{ key: 'email', label: 'ایمیل فرستنده', sample: 'user@example.com' },
|
||||
{ key: 'subject', label: 'موضوع پیام', sample: 'مشاوره خرید مکمل' },
|
||||
{ key: "email", label: "ایمیل فرستنده", sample: "user@example.com" },
|
||||
{ key: "subject", label: "موضوع پیام", sample: "مشاوره خرید مکمل" },
|
||||
{
|
||||
key: 'message',
|
||||
label: 'متن پیام',
|
||||
sample: 'درخواست راهنمایی در مورد دوز کلسیم',
|
||||
key: "message",
|
||||
label: "متن پیام",
|
||||
sample: "درخواست راهنمایی در مورد دوز کلسیم",
|
||||
},
|
||||
{ key: 'date', label: 'تاریخ ارسال', sample: '۱۴۰۳/۰۶/۱۵' },
|
||||
{ key: "date", label: "تاریخ ارسال", sample: "۱۴۰۳/۰۶/۱۵" },
|
||||
],
|
||||
},
|
||||
{
|
||||
event: 'WALLET_CHARGED',
|
||||
label: 'شارژ و افزایش موجودی کیف پول',
|
||||
event: "WALLET_CHARGED",
|
||||
label: "شارژ و افزایش موجودی کیف پول",
|
||||
description:
|
||||
'هنگام افزایش موجودی کیف پول کاربر (درگاه آنلاین، پنل مدیریت، کشبک یا استرداد)',
|
||||
"هنگام افزایش موجودی کیف پول کاربر (درگاه آنلاین، پنل مدیریت، کشبک یا استرداد)",
|
||||
variables: [
|
||||
{ key: 'customerName', label: 'نام مشتری', sample: 'علی محمدی' },
|
||||
{ key: 'amount', label: 'مبلغ شارژ (تومان)', sample: '۵۰,۰۰۰' },
|
||||
{ key: "customerName", label: "نام مشتری", sample: "علی محمدی" },
|
||||
{ key: "amount", label: "مبلغ شارژ (تومان)", sample: "۵۰,۰۰۰" },
|
||||
{
|
||||
key: 'balance',
|
||||
label: 'موجودی جدید کیف پول (تومان)',
|
||||
sample: '۱۵۰,۰۰۰',
|
||||
key: "balance",
|
||||
label: "موجودی جدید کیف پول (تومان)",
|
||||
sample: "۱۵۰,۰۰۰",
|
||||
},
|
||||
{
|
||||
key: 'reason',
|
||||
label: 'علت / نوع شارژ',
|
||||
sample: 'شارژ آنلاین / پاداش خرید (Cashback)',
|
||||
key: "reason",
|
||||
label: "علت / نوع شارژ",
|
||||
sample: "شارژ آنلاین / پاداش خرید (Cashback)",
|
||||
},
|
||||
{
|
||||
key: 'customerPhone',
|
||||
label: 'شماره همراه مشتری',
|
||||
sample: '09123456789',
|
||||
key: "customerPhone",
|
||||
label: "شماره همراه مشتری",
|
||||
sample: "09123456789",
|
||||
},
|
||||
{ key: 'date', label: 'تاریخ شارژ', sample: '۱۴۰۳/۰۶/۱۵' },
|
||||
{ key: "date", label: "تاریخ شارژ", sample: "۱۴۰۳/۰۶/۱۵" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export const DEFAULT_SMS_RULES: SmsRule[] = [
|
||||
{
|
||||
id: 'default-order-customer',
|
||||
title: 'ارسال فاکتور و تایید سفارش به خریدار',
|
||||
event: 'ORDER_PAID',
|
||||
id: "default-order-customer",
|
||||
title: "ارسال فاکتور و تایید سفارش به خریدار",
|
||||
event: "ORDER_PAID",
|
||||
enabled: true,
|
||||
recipientType: 'customer',
|
||||
recipientType: "customer",
|
||||
patternId: 508081,
|
||||
variables: ['customerName', 'orderNumber', 'amount'],
|
||||
variables: ["customerName", "orderNumber", "amount"],
|
||||
description:
|
||||
'ارسال شماره فاکتور و مبلغ سفارش به شماره همراه مشتری بلافاصله پس از پرداخت',
|
||||
"ارسال شماره فاکتور و مبلغ سفارش به شماره همراه مشتری بلافاصله پس از پرداخت",
|
||||
},
|
||||
{
|
||||
id: 'default-order-admin',
|
||||
title: 'اطلاعرسانی سفارش جدید به مدیر سایت',
|
||||
event: 'ORDER_PAID',
|
||||
id: "default-order-admin",
|
||||
title: "اطلاعرسانی سفارش جدید به مدیر سایت",
|
||||
event: "ORDER_PAID",
|
||||
enabled: true,
|
||||
recipientType: 'admin',
|
||||
recipientType: "admin",
|
||||
patternId: 508081,
|
||||
variables: ['customerName', 'orderNumber', 'amount'],
|
||||
description: 'ارسال پیامک سفارش جدید و مبلغ به مدیران فروشگاه',
|
||||
variables: ["customerName", "orderNumber", "amount"],
|
||||
description: "ارسال پیامک سفارش جدید و مبلغ به مدیران فروشگاه",
|
||||
},
|
||||
{
|
||||
id: 'default-shipping-customer',
|
||||
title: 'ارسال کد رهگیری پست به خریدار',
|
||||
event: 'ORDER_SHIPPED',
|
||||
id: "default-shipping-customer",
|
||||
title: "ارسال کد رهگیری پست به خریدار",
|
||||
event: "ORDER_SHIPPED",
|
||||
enabled: true,
|
||||
recipientType: 'customer',
|
||||
recipientType: "customer",
|
||||
patternId: 508082,
|
||||
variables: ['orderNumber', 'shippingTrackingCode'],
|
||||
description: 'ارسال بارکد ۲۴ رقمی اداره پست هنگام تحویل مرسوله',
|
||||
variables: ["orderNumber", "shippingTrackingCode"],
|
||||
description: "ارسال بارکد ۲۴ رقمی اداره پست هنگام تحویل مرسوله",
|
||||
},
|
||||
{
|
||||
id: 'default-b2b-customer',
|
||||
title: 'تایید ثبت درخواست همکاری B2B',
|
||||
event: 'B2B_SUBMITTED',
|
||||
id: "default-b2b-customer",
|
||||
title: "تایید ثبت درخواست همکاری B2B",
|
||||
event: "B2B_SUBMITTED",
|
||||
enabled: true,
|
||||
recipientType: 'customer',
|
||||
recipientType: "customer",
|
||||
patternId: 508083,
|
||||
variables: ['applicantName'],
|
||||
description: 'پیامک ثبت درخواست متقاضیان عمدهفروشی',
|
||||
variables: ["applicantName"],
|
||||
description: "پیامک ثبت درخواست متقاضیان عمدهفروشی",
|
||||
},
|
||||
{
|
||||
id: 'default-wallet-charged-customer',
|
||||
title: 'اطلاعرسانی شارژ کیف پول به کاربر',
|
||||
event: 'WALLET_CHARGED',
|
||||
id: "default-wallet-charged-customer",
|
||||
title: "اطلاعرسانی شارژ کیف پول به کاربر",
|
||||
event: "WALLET_CHARGED",
|
||||
enabled: true,
|
||||
recipientType: 'customer',
|
||||
recipientType: "customer",
|
||||
patternId: 0,
|
||||
variables: ['customerName', 'amount', 'balance'],
|
||||
description: 'ارسال پیامک افزایش موجودی کیف پول (آنلاین، مدیریت یا کشبک)',
|
||||
variables: ["customerName", "amount", "balance"],
|
||||
description: "ارسال پیامک افزایش موجودی کیف پول (آنلاین، مدیریت یا کشبک)",
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,109 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { SmsService } from "./sms.service";
|
||||
import { PrismaService } from "../../prisma/prisma.service";
|
||||
|
||||
describe("SmsService", () => {
|
||||
let service: SmsService;
|
||||
|
||||
const mockPrisma = {
|
||||
setting: {
|
||||
findFirst: jest.fn(),
|
||||
},
|
||||
smsLog: {
|
||||
create: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
count: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [SmsService, { provide: PrismaService, useValue: mockPrisma }],
|
||||
}).compile();
|
||||
|
||||
service = module.get<SmsService>(SmsService);
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe("getSmsConfig", () => {
|
||||
it("should return configuration from database when available", async () => {
|
||||
mockPrisma.setting.findFirst.mockResolvedValue({
|
||||
category: "sms",
|
||||
value: {
|
||||
enabled: true,
|
||||
username: "custom_user",
|
||||
otpBodyId: 99999,
|
||||
},
|
||||
});
|
||||
|
||||
const config = await service.getSmsConfig();
|
||||
expect(config.enabled).toBe(true);
|
||||
expect(config.username).toBe("custom_user");
|
||||
expect(config.otpBodyId).toBe(99999);
|
||||
});
|
||||
|
||||
it("should fallback gracefully to defaults if database query fails", async () => {
|
||||
mockPrisma.setting.findFirst.mockRejectedValue(new Error("DB error"));
|
||||
|
||||
const config = await service.getSmsConfig();
|
||||
expect(config.enabled).toBe(true);
|
||||
expect(config.otpBodyId).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("triggerEvent", () => {
|
||||
it("should skip sending if SMS gateway is disabled in config", async () => {
|
||||
mockPrisma.setting.findFirst.mockResolvedValue({
|
||||
category: "sms",
|
||||
value: { enabled: false },
|
||||
});
|
||||
|
||||
const res = await service.triggerEvent("ORDER_PAID", {
|
||||
orderNumber: "123",
|
||||
});
|
||||
expect(res).toBe(false);
|
||||
});
|
||||
|
||||
it("should execute configured SMS rule and invoke sendPatternSms", async () => {
|
||||
mockPrisma.setting.findFirst.mockResolvedValue({
|
||||
category: "sms",
|
||||
value: {
|
||||
enabled: true,
|
||||
rules: [
|
||||
{
|
||||
id: "rule-1",
|
||||
title: "پیامک پرداخت به مشتری",
|
||||
event: "ORDER_PAID",
|
||||
enabled: true,
|
||||
recipientType: "customer",
|
||||
patternId: 508081,
|
||||
variables: ["orderNumber", "customerName"],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const sendPatternSpy = jest
|
||||
.spyOn(service, "sendPatternSms")
|
||||
.mockResolvedValue({ Value: 100 } as any);
|
||||
|
||||
const res = await service.triggerEvent("ORDER_PAID", {
|
||||
orderNumber: "ORD-999",
|
||||
customerName: "پارسا",
|
||||
customerPhone: "09121111111",
|
||||
});
|
||||
|
||||
expect(res).toBe(true);
|
||||
expect(sendPatternSpy).toHaveBeenCalledWith({
|
||||
to: "09121111111",
|
||||
bodyId: 508081,
|
||||
args: ["ORD-999", "پارسا"],
|
||||
type: "ORDER_PAID_CUSTOMER",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import * as https from 'https';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
import * as https from "https";
|
||||
import { PrismaService } from "../../prisma/prisma.service";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import {
|
||||
DEFAULT_SMS_RULES,
|
||||
SMS_EVENT_DEFINITIONS,
|
||||
SmsEventDefinition,
|
||||
} from './sms-events.constants';
|
||||
} from "./sms-events.constants";
|
||||
|
||||
export interface SendPatternSmsOptions {
|
||||
to: string;
|
||||
@@ -20,7 +20,7 @@ export interface SmsRule {
|
||||
title: string;
|
||||
event: string; // ORDER_PAID, ORDER_CREATED, ORDER_SHIPPED, B2B_SUBMITTED, CONTACT_SUBMITTED, OTP
|
||||
enabled: boolean;
|
||||
recipientType: 'customer' | 'admin' | 'custom';
|
||||
recipientType: "customer" | "admin" | "custom";
|
||||
customPhone?: string;
|
||||
patternId: number;
|
||||
variables: string[]; // Ordered parameter keys: e.g. ['orderNumber', 'recipientName', 'address']
|
||||
@@ -57,7 +57,7 @@ export class SmsLogQuery {
|
||||
type?: string;
|
||||
status?: string;
|
||||
sortBy?: string;
|
||||
sortOrder?: 'asc' | 'desc';
|
||||
sortOrder?: "asc" | "desc";
|
||||
}
|
||||
|
||||
export interface MeliPayamakResponse {
|
||||
@@ -78,7 +78,7 @@ export class SmsService {
|
||||
async getSmsConfig(): Promise<SmsConfig> {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms' },
|
||||
where: { category: "sms" },
|
||||
});
|
||||
const dbConfig = (setting?.value as Record<string, unknown>) || {};
|
||||
|
||||
@@ -86,41 +86,41 @@ export class SmsService {
|
||||
enabled:
|
||||
dbConfig.enabled !== undefined ? Boolean(dbConfig.enabled) : true,
|
||||
username:
|
||||
typeof dbConfig.username === 'string' && dbConfig.username
|
||||
typeof dbConfig.username === "string" && dbConfig.username
|
||||
? dbConfig.username
|
||||
: process.env.MELIPAYAMAK_USERNAME || '9364100228',
|
||||
: process.env.MELIPAYAMAK_USERNAME || "9364100228",
|
||||
password:
|
||||
typeof dbConfig.password === 'string' && dbConfig.password
|
||||
typeof dbConfig.password === "string" && dbConfig.password
|
||||
? dbConfig.password
|
||||
: process.env.MELIPAYAMAK_PASSWORD || '',
|
||||
: process.env.MELIPAYAMAK_PASSWORD || "",
|
||||
fromNumber:
|
||||
typeof dbConfig.fromNumber === 'string' && dbConfig.fromNumber
|
||||
typeof dbConfig.fromNumber === "string" && dbConfig.fromNumber
|
||||
? dbConfig.fromNumber
|
||||
: process.env.MELIPAYAMAK_FROM_NUMBER || '',
|
||||
: process.env.MELIPAYAMAK_FROM_NUMBER || "",
|
||||
adminPhone:
|
||||
typeof dbConfig.adminPhone === 'string' && dbConfig.adminPhone
|
||||
typeof dbConfig.adminPhone === "string" && dbConfig.adminPhone
|
||||
? dbConfig.adminPhone
|
||||
: process.env.ADMIN_MOBILE || '09364100228',
|
||||
: process.env.ADMIN_MOBILE || "09364100228",
|
||||
otpBodyId: Number(
|
||||
dbConfig.otpBodyId || process.env.MELIPAYAMAK_OTP_BODY_ID || '508079',
|
||||
dbConfig.otpBodyId || process.env.MELIPAYAMAK_OTP_BODY_ID || "508079",
|
||||
),
|
||||
orderBodyId: Number(
|
||||
dbConfig.orderBodyId ||
|
||||
process.env.MELIPAYAMAK_ORDER_BODY_ID ||
|
||||
'508081',
|
||||
"508081",
|
||||
),
|
||||
shippingBodyId: Number(
|
||||
dbConfig.shippingBodyId ||
|
||||
process.env.MELIPAYAMAK_SHIPPING_BODY_ID ||
|
||||
'508082',
|
||||
"508082",
|
||||
),
|
||||
b2bBodyId: Number(
|
||||
dbConfig.b2bBodyId || process.env.MELIPAYAMAK_B2B_BODY_ID || '508083',
|
||||
dbConfig.b2bBodyId || process.env.MELIPAYAMAK_B2B_BODY_ID || "508083",
|
||||
),
|
||||
petCareBodyId: Number(
|
||||
dbConfig.petCareBodyId ||
|
||||
process.env.MELIPAYAMAK_PET_CARE_BODY_ID ||
|
||||
'0',
|
||||
"0",
|
||||
),
|
||||
rules: Array.isArray(dbConfig.rules)
|
||||
? (dbConfig.rules as SmsRule[])
|
||||
@@ -129,17 +129,17 @@ export class SmsService {
|
||||
} catch {
|
||||
return {
|
||||
enabled: true,
|
||||
username: process.env.MELIPAYAMAK_USERNAME || '9364100228',
|
||||
password: process.env.MELIPAYAMAK_PASSWORD || '',
|
||||
fromNumber: process.env.MELIPAYAMAK_FROM_NUMBER || '',
|
||||
adminPhone: process.env.ADMIN_MOBILE || '09364100228',
|
||||
otpBodyId: Number(process.env.MELIPAYAMAK_OTP_BODY_ID || '508079'),
|
||||
orderBodyId: Number(process.env.MELIPAYAMAK_ORDER_BODY_ID || '508081'),
|
||||
username: process.env.MELIPAYAMAK_USERNAME || "9364100228",
|
||||
password: process.env.MELIPAYAMAK_PASSWORD || "",
|
||||
fromNumber: process.env.MELIPAYAMAK_FROM_NUMBER || "",
|
||||
adminPhone: process.env.ADMIN_MOBILE || "09364100228",
|
||||
otpBodyId: Number(process.env.MELIPAYAMAK_OTP_BODY_ID || "508079"),
|
||||
orderBodyId: Number(process.env.MELIPAYAMAK_ORDER_BODY_ID || "508081"),
|
||||
shippingBodyId: Number(
|
||||
process.env.MELIPAYAMAK_SHIPPING_BODY_ID || '508082',
|
||||
process.env.MELIPAYAMAK_SHIPPING_BODY_ID || "508082",
|
||||
),
|
||||
b2bBodyId: Number(process.env.MELIPAYAMAK_B2B_BODY_ID || '508083'),
|
||||
petCareBodyId: Number(process.env.MELIPAYAMAK_PET_CARE_BODY_ID || '0'),
|
||||
b2bBodyId: Number(process.env.MELIPAYAMAK_B2B_BODY_ID || "508083"),
|
||||
petCareBodyId: Number(process.env.MELIPAYAMAK_PET_CARE_BODY_ID || "0"),
|
||||
rules: DEFAULT_SMS_RULES,
|
||||
};
|
||||
}
|
||||
@@ -174,19 +174,19 @@ export class SmsService {
|
||||
for (const rule of activeRules) {
|
||||
const phones: string[] = [];
|
||||
|
||||
if (rule.recipientType === 'customer') {
|
||||
if (rule.recipientType === "customer") {
|
||||
const customerPhone =
|
||||
data.customerPhone ||
|
||||
data.phone ||
|
||||
data.mobile ||
|
||||
data.recipientPhone;
|
||||
if (customerPhone) phones.push(String(customerPhone).trim());
|
||||
} else if (rule.recipientType === 'admin') {
|
||||
} else if (rule.recipientType === "admin") {
|
||||
const rawAdminPhones =
|
||||
config.adminPhone ||
|
||||
process.env.ADMIN_MOBILE ||
|
||||
process.env.ADMIN_MOBILE_ALERT ||
|
||||
'';
|
||||
"";
|
||||
const list = rawAdminPhones
|
||||
.split(/[,;\s]+/)
|
||||
.map((p) => p.trim())
|
||||
@@ -194,7 +194,7 @@ export class SmsService {
|
||||
if (list.length > 0) {
|
||||
phones.push(...list);
|
||||
}
|
||||
} else if (rule.recipientType === 'custom' && rule.customPhone) {
|
||||
} else if (rule.recipientType === "custom" && rule.customPhone) {
|
||||
const list = rule.customPhone
|
||||
.split(/[,;\s]+/)
|
||||
.map((p) => p.trim())
|
||||
@@ -213,7 +213,7 @@ export class SmsService {
|
||||
|
||||
const args: string[] = (rule.variables || []).map((varKey) => {
|
||||
const val = data[varKey];
|
||||
if (val === undefined || val === null) return '';
|
||||
if (val === undefined || val === null) return "";
|
||||
return String(val).trim();
|
||||
});
|
||||
|
||||
@@ -237,29 +237,29 @@ export class SmsService {
|
||||
this.logger.log(
|
||||
`[SMS Trigger] No custom rules configured for ${event}. Using standard fallback.`,
|
||||
);
|
||||
if (event === 'ORDER_PAID' || event === 'ORDER_CREATED') {
|
||||
if (event === "ORDER_PAID" || event === "ORDER_CREATED") {
|
||||
const phone = data.customerPhone || data.phone || data.mobile;
|
||||
if (phone && config.orderBodyId) {
|
||||
await this.sendOrderConfirmation(
|
||||
phone,
|
||||
data.customerName || 'مشتری',
|
||||
data.orderNumber || '',
|
||||
data.amount || '',
|
||||
data.customerName || "مشتری",
|
||||
data.orderNumber || "",
|
||||
data.amount || "",
|
||||
);
|
||||
}
|
||||
} else if (event === 'ORDER_SHIPPED') {
|
||||
} else if (event === "ORDER_SHIPPED") {
|
||||
const phone = data.customerPhone || data.phone || data.mobile;
|
||||
if (phone && config.shippingBodyId) {
|
||||
await this.sendShippingNotification(
|
||||
phone,
|
||||
data.orderNumber || '',
|
||||
data.trackingCode || '',
|
||||
data.orderNumber || "",
|
||||
data.trackingCode || "",
|
||||
);
|
||||
}
|
||||
} else if (event === 'B2B_SUBMITTED') {
|
||||
} else if (event === "B2B_SUBMITTED") {
|
||||
const phone = data.applicantPhone || data.phone;
|
||||
if (phone && config.b2bBodyId) {
|
||||
await this.sendB2bNotification(phone, data.applicantName || '');
|
||||
await this.sendB2bNotification(phone, data.applicantName || "");
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -296,26 +296,26 @@ export class SmsService {
|
||||
return {
|
||||
success: false,
|
||||
message:
|
||||
'مشخصات نام کاربری و رمز عبور سامانه ملی پیامک تنظیم نشده است.',
|
||||
"مشخصات نام کاربری و رمز عبور سامانه ملی پیامک تنظیم نشده است.",
|
||||
};
|
||||
}
|
||||
|
||||
if (!rule.patternId) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'کد پترن (Body ID) برای این سناریو مشخص نشده است.',
|
||||
message: "کد پترن (Body ID) برای این سناریو مشخص نشده است.",
|
||||
};
|
||||
}
|
||||
|
||||
// Determine target recipient phone
|
||||
let phone = testPhone ? testPhone.trim() : '';
|
||||
let phone = testPhone ? testPhone.trim() : "";
|
||||
if (!phone) {
|
||||
if (rule.recipientType === 'customer') {
|
||||
phone = config.adminPhone || '09123456789';
|
||||
} else if (rule.recipientType === 'admin') {
|
||||
phone = config.adminPhone || process.env.ADMIN_MOBILE || '09123456789';
|
||||
} else if (rule.recipientType === 'custom') {
|
||||
phone = (rule.customPhone || '').split(/[,;\s]+/)[0] || '';
|
||||
if (rule.recipientType === "customer") {
|
||||
phone = config.adminPhone || "09123456789";
|
||||
} else if (rule.recipientType === "admin") {
|
||||
phone = config.adminPhone || process.env.ADMIN_MOBILE || "09123456789";
|
||||
} else if (rule.recipientType === "custom") {
|
||||
phone = (rule.customPhone || "").split(/[,;\s]+/)[0] || "";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,7 +323,7 @@ export class SmsService {
|
||||
return {
|
||||
success: false,
|
||||
message:
|
||||
'شماره گیرنده جهت ارسال تست یافت نشد. لطفاً یک شماره موبایل وارد کنید.',
|
||||
"شماره گیرنده جهت ارسال تست یافت نشد. لطفاً یک شماره موبایل وارد کنید.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -361,26 +361,26 @@ export class SmsService {
|
||||
.map(
|
||||
([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`,
|
||||
)
|
||||
.join('&');
|
||||
.join("&");
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = https.request(
|
||||
`https://api.payamak-panel.com/post/SharedService.asmx/${endpoint}`,
|
||||
{
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Content-Length': Buffer.byteLength(postData),
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Content-Length": Buffer.byteLength(postData),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on('end', () => resolve(data));
|
||||
let data = "";
|
||||
res.on("data", (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on("end", () => resolve(data));
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', (err: Error) => reject(err));
|
||||
req.on("error", (err: Error) => reject(err));
|
||||
req.write(postData);
|
||||
req.end();
|
||||
});
|
||||
@@ -403,7 +403,7 @@ export class SmsService {
|
||||
await this.prisma.smsLog.create({
|
||||
data: {
|
||||
receptor: entry.receptor,
|
||||
type: entry.type || 'GENERIC',
|
||||
type: entry.type || "GENERIC",
|
||||
patternId: entry.patternId || null,
|
||||
args: entry.args || [],
|
||||
messageText: entry.messageText || null,
|
||||
@@ -431,22 +431,22 @@ export class SmsService {
|
||||
if (query.search) {
|
||||
const s = query.search.trim();
|
||||
where.OR = [
|
||||
{ receptor: { contains: s, mode: 'insensitive' } },
|
||||
{ recId: { contains: s, mode: 'insensitive' } },
|
||||
{ errorMessage: { contains: s, mode: 'insensitive' } },
|
||||
{ receptor: { contains: s, mode: "insensitive" } },
|
||||
{ recId: { contains: s, mode: "insensitive" } },
|
||||
{ errorMessage: { contains: s, mode: "insensitive" } },
|
||||
];
|
||||
}
|
||||
|
||||
if (query.type && query.type !== 'ALL') {
|
||||
if (query.type && query.type !== "ALL") {
|
||||
where.type = query.type;
|
||||
}
|
||||
|
||||
if (query.status && query.status !== 'ALL') {
|
||||
if (query.status && query.status !== "ALL") {
|
||||
where.status = query.status;
|
||||
}
|
||||
|
||||
const sortField = query.sortBy || 'createdAt';
|
||||
const sortOrder = query.sortOrder === 'asc' ? 'asc' : 'desc';
|
||||
const sortField = query.sortBy || "createdAt";
|
||||
const sortOrder = query.sortOrder === "asc" ? "asc" : "desc";
|
||||
|
||||
const [logs, total, totalSuccess, totalFailed] = await Promise.all([
|
||||
this.prisma.smsLog.findMany({
|
||||
@@ -456,8 +456,8 @@ export class SmsService {
|
||||
orderBy: { [sortField]: sortOrder },
|
||||
}),
|
||||
this.prisma.smsLog.count({ where }),
|
||||
this.prisma.smsLog.count({ where: { status: 'SUCCESS' } }),
|
||||
this.prisma.smsLog.count({ where: { status: 'FAILED' } }),
|
||||
this.prisma.smsLog.count({ where: { status: "SUCCESS" } }),
|
||||
this.prisma.smsLog.count({ where: { status: "FAILED" } }),
|
||||
]);
|
||||
|
||||
return {
|
||||
@@ -511,21 +511,21 @@ export class SmsService {
|
||||
|
||||
if (idMatch) {
|
||||
const id = parseInt(idMatch[1], 10);
|
||||
const title = (titleMatch ? titleMatch[1] : '')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/&/g, '&')
|
||||
const title = (titleMatch ? titleMatch[1] : "")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/&/g, "&")
|
||||
.trim();
|
||||
const body = (bodyMatch ? bodyMatch[1] : '')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/&/g, '&')
|
||||
const body = (bodyMatch ? bodyMatch[1] : "")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/&/g, "&")
|
||||
.trim();
|
||||
const status = statusMatch ? parseInt(statusMatch[1], 10) : 0;
|
||||
|
||||
let statusText = 'در انتظار تایید';
|
||||
if (status === 1) statusText = 'تایید شده';
|
||||
else if (status === 2 || status === -1) statusText = 'نیاز به ویرایش';
|
||||
let statusText = "در انتظار تایید";
|
||||
if (status === 1) statusText = "تایید شده";
|
||||
else if (status === 2 || status === -1) statusText = "نیاز به ویرایش";
|
||||
|
||||
patterns.push({ id, title, body, status, statusText });
|
||||
}
|
||||
@@ -548,7 +548,7 @@ export class SmsService {
|
||||
return {
|
||||
success: false,
|
||||
credit: 0,
|
||||
message: 'نام کاربری و کلمه عبور ملی پیامک تنظیم نشده است.',
|
||||
message: "نام کاربری و کلمه عبور ملی پیامک تنظیم نشده است.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -559,18 +559,18 @@ export class SmsService {
|
||||
});
|
||||
|
||||
const req = https.request(
|
||||
'https://rest.payamak-panel.com/api/SendSMS/GetCredit',
|
||||
"https://rest.payamak-panel.com/api/SendSMS/GetCredit",
|
||||
{
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload),
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.byteLength(payload),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on('end', () => {
|
||||
let data = "";
|
||||
res.on("data", (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on("end", () => {
|
||||
try {
|
||||
const json = JSON.parse(data);
|
||||
const val = Number(json.Value ?? json.value ?? 0);
|
||||
@@ -591,7 +591,7 @@ export class SmsService {
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', (err: Error) => {
|
||||
req.on("error", (err: Error) => {
|
||||
resolve({
|
||||
success: false,
|
||||
credit: 0,
|
||||
@@ -612,7 +612,7 @@ export class SmsService {
|
||||
args: string[] = [],
|
||||
): Promise<string> {
|
||||
if (!patternId) {
|
||||
return args.join(' ');
|
||||
return args.join(" ");
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -620,19 +620,19 @@ export class SmsService {
|
||||
const target = patterns.find((p) => p.id === patternId);
|
||||
if (!target || !target.body) {
|
||||
return args.length > 0
|
||||
? `الگو ${patternId} با مقادیر: ${args.join(' ، ')}`
|
||||
? `الگو ${patternId} با مقادیر: ${args.join(" ، ")}`
|
||||
: `الگو ${patternId}`;
|
||||
}
|
||||
|
||||
let rendered = target.body;
|
||||
args.forEach((val, idx) => {
|
||||
const regex = new RegExp(`\\{${idx}\\}`, 'g');
|
||||
rendered = rendered.replace(regex, val || '');
|
||||
const regex = new RegExp(`\\{${idx}\\}`, "g");
|
||||
rendered = rendered.replace(regex, val || "");
|
||||
});
|
||||
return rendered;
|
||||
} catch {
|
||||
return args.length > 0
|
||||
? `الگو ${patternId} با مقادیر: ${args.join(' ، ')}`
|
||||
? `الگو ${patternId} با مقادیر: ${args.join(" ، ")}`
|
||||
: `الگو ${patternId}`;
|
||||
}
|
||||
}
|
||||
@@ -646,7 +646,7 @@ export class SmsService {
|
||||
let remotePatterns: MeliPayamakPattern[] = [];
|
||||
if (config.username && config.password) {
|
||||
try {
|
||||
const rawXml = await this.postAsmx('GetSharedServiceBody', {
|
||||
const rawXml = await this.postAsmx("GetSharedServiceBody", {
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
});
|
||||
@@ -655,11 +655,11 @@ export class SmsService {
|
||||
// Cache patterns asynchronously in database
|
||||
this.prisma.setting
|
||||
.upsert({
|
||||
where: { key: 'sms_patterns_cache' },
|
||||
where: { key: "sms_patterns_cache" },
|
||||
update: { value: remotePatterns as any },
|
||||
create: {
|
||||
key: 'sms_patterns_cache',
|
||||
category: 'sms_patterns',
|
||||
key: "sms_patterns_cache",
|
||||
category: "sms_patterns",
|
||||
value: remotePatterns as any,
|
||||
},
|
||||
})
|
||||
@@ -678,10 +678,10 @@ export class SmsService {
|
||||
// Load cached patterns from settings table
|
||||
const storedSetting = await this.prisma.setting.findFirst({
|
||||
where: {
|
||||
category: 'sms_patterns',
|
||||
key: { in: ['sms_patterns_cache', 'sms_patterns_config'] },
|
||||
category: "sms_patterns",
|
||||
key: { in: ["sms_patterns_cache", "sms_patterns_config"] },
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
});
|
||||
const cachedPatterns: MeliPayamakPattern[] = Array.isArray(
|
||||
storedSetting?.value,
|
||||
@@ -717,23 +717,23 @@ export class SmsService {
|
||||
}> = [
|
||||
{
|
||||
id: config.otpBodyId,
|
||||
title: 'کد تایید ورود و ثبتنام (OTP)',
|
||||
body: 'کد تایید ورود به کنینا ایران: {0} میباشد. @canina.ir #{0}',
|
||||
title: "کد تایید ورود و ثبتنام (OTP)",
|
||||
body: "کد تایید ورود به کنینا ایران: {0} میباشد. @canina.ir #{0}",
|
||||
},
|
||||
{
|
||||
id: config.orderBodyId,
|
||||
title: 'تایید و ثبت فاکتور سفارش',
|
||||
body: '{0} عزیز ، سفارش شما به شماره {1} به مبلغ {2} با موفقیت ثبت شد.\nکنینا ایران',
|
||||
title: "تایید و ثبت فاکتور سفارش",
|
||||
body: "{0} عزیز ، سفارش شما به شماره {1} به مبلغ {2} با موفقیت ثبت شد.\nکنینا ایران",
|
||||
},
|
||||
{
|
||||
id: config.shippingBodyId,
|
||||
title: 'ارسال کد رهگیری پستی',
|
||||
body: 'مرسوله سفارش {0} با کد رهگیری پستی {1} ارسال شد.',
|
||||
title: "ارسال کد رهگیری پستی",
|
||||
body: "مرسوله سفارش {0} با کد رهگیری پستی {1} ارسال شد.",
|
||||
},
|
||||
{
|
||||
id: config.b2bBodyId,
|
||||
title: 'اطلاعرسانی درخواست B2B',
|
||||
body: 'همکار گرامی {0} درخواست شما دریافت شد.',
|
||||
title: "اطلاعرسانی درخواست B2B",
|
||||
body: "همکار گرامی {0} درخواست شما دریافت شد.",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -744,7 +744,7 @@ export class SmsService {
|
||||
title: d.title,
|
||||
body: d.body,
|
||||
status: 1,
|
||||
statusText: 'تایید شده',
|
||||
statusText: "تایید شده",
|
||||
assignedTo: [],
|
||||
});
|
||||
}
|
||||
@@ -770,33 +770,33 @@ export class SmsService {
|
||||
// Check legacy default bindings
|
||||
if (
|
||||
p.id === config.otpBodyId &&
|
||||
!assigned.some((a) => a.includes('OTP'))
|
||||
!assigned.some((a) => a.includes("OTP"))
|
||||
) {
|
||||
assigned.push('کد تایید OTP');
|
||||
assigned.push("کد تایید OTP");
|
||||
}
|
||||
if (
|
||||
p.id === config.orderBodyId &&
|
||||
!assigned.some((a) => a.includes('سفارش'))
|
||||
!assigned.some((a) => a.includes("سفارش"))
|
||||
) {
|
||||
assigned.push('پترن پیشفرض سفارش');
|
||||
assigned.push("پترن پیشفرض سفارش");
|
||||
}
|
||||
if (
|
||||
p.id === config.shippingBodyId &&
|
||||
!assigned.some((a) => a.includes('پست'))
|
||||
!assigned.some((a) => a.includes("پست"))
|
||||
) {
|
||||
assigned.push('پترن پیشفرض پست');
|
||||
assigned.push("پترن پیشفرض پست");
|
||||
}
|
||||
if (
|
||||
p.id === config.b2bBodyId &&
|
||||
!assigned.some((a) => a.includes('B2B'))
|
||||
!assigned.some((a) => a.includes("B2B"))
|
||||
) {
|
||||
assigned.push('پترن پیشفرض B2B');
|
||||
assigned.push("پترن پیشفرض B2B");
|
||||
}
|
||||
if (
|
||||
p.id === config.petCareBodyId &&
|
||||
!assigned.some((a) => a.includes('پت'))
|
||||
!assigned.some((a) => a.includes("پت"))
|
||||
) {
|
||||
assigned.push('پترن پیشفرض پرونده پت');
|
||||
assigned.push("پترن پیشفرض پرونده پت");
|
||||
}
|
||||
|
||||
return { ...p, assignedTo: assigned };
|
||||
@@ -818,12 +818,12 @@ export class SmsService {
|
||||
if (!config.username || !config.password) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.',
|
||||
message: "مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const rawXml = await this.postAsmx('SharedServiceBodyAdd', {
|
||||
const rawXml = await this.postAsmx("SharedServiceBodyAdd", {
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
title,
|
||||
@@ -841,7 +841,7 @@ export class SmsService {
|
||||
title,
|
||||
body,
|
||||
status: 0,
|
||||
statusText: 'در انتظار تایید',
|
||||
statusText: "در انتظار تایید",
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -852,12 +852,12 @@ export class SmsService {
|
||||
} else if (code === 0) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'نام کاربری یا کلمه عبور ملی پیامک اشتباه است.',
|
||||
message: "نام کاربری یا کلمه عبور ملی پیامک اشتباه است.",
|
||||
};
|
||||
} else if (code === -2) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'شناسه لیست سیاه ویژه اشتباه است.',
|
||||
message: "شناسه لیست سیاه ویژه اشتباه است.",
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
@@ -873,7 +873,7 @@ export class SmsService {
|
||||
title,
|
||||
body,
|
||||
status: 0,
|
||||
statusText: 'ثبت محلی (در انتظار اتصال سرور)',
|
||||
statusText: "ثبت محلی (در انتظار اتصال سرور)",
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -896,12 +896,12 @@ export class SmsService {
|
||||
if (!config.username || !config.password) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.',
|
||||
message: "مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.",
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const rawXml = await this.postAsmx('SharedServiceBodyEdit', {
|
||||
const rawXml = await this.postAsmx("SharedServiceBodyEdit", {
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
bodyId,
|
||||
@@ -917,14 +917,14 @@ export class SmsService {
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
'ویرایش الگو با موفقیت انجام شد و منتظر تایید مجدد ناظر میباشد.',
|
||||
"ویرایش الگو با موفقیت انجام شد و منتظر تایید مجدد ناظر میباشد.",
|
||||
};
|
||||
} else if (code === -1) {
|
||||
await this.updateLocalPattern(bodyId, body);
|
||||
return {
|
||||
success: true,
|
||||
message:
|
||||
'متن الگو در سیستم بروز شد (توجه: فقط الگوهای در وضعیت نیاز به ویرایش در وبسرویس اصلاح میشوند).',
|
||||
"متن الگو در سیستم بروز شد (توجه: فقط الگوهای در وضعیت نیاز به ویرایش در وبسرویس اصلاح میشوند).",
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
@@ -945,7 +945,7 @@ export class SmsService {
|
||||
private async saveLocalPattern(pattern: MeliPayamakPattern) {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms_patterns' },
|
||||
where: { category: "sms_patterns" },
|
||||
});
|
||||
const list: MeliPayamakPattern[] = Array.isArray(setting?.value)
|
||||
? (setting.value as unknown as MeliPayamakPattern[])
|
||||
@@ -953,14 +953,14 @@ export class SmsService {
|
||||
const updated = [pattern, ...list.filter((p) => p.id !== pattern.id)];
|
||||
|
||||
await this.prisma.setting.upsert({
|
||||
where: { key: 'sms_patterns_config' },
|
||||
where: { key: "sms_patterns_config" },
|
||||
update: {
|
||||
category: 'sms_patterns',
|
||||
category: "sms_patterns",
|
||||
value: updated as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
create: {
|
||||
key: 'sms_patterns_config',
|
||||
category: 'sms_patterns',
|
||||
key: "sms_patterns_config",
|
||||
category: "sms_patterns",
|
||||
value: updated as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
@@ -973,7 +973,7 @@ export class SmsService {
|
||||
private async updateLocalPattern(bodyId: number, newBody: string) {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms_patterns' },
|
||||
where: { category: "sms_patterns" },
|
||||
});
|
||||
const list: MeliPayamakPattern[] = Array.isArray(setting?.value)
|
||||
? (setting.value as unknown as MeliPayamakPattern[])
|
||||
@@ -984,20 +984,20 @@ export class SmsService {
|
||||
...p,
|
||||
body: newBody,
|
||||
status: 0,
|
||||
statusText: 'در انتظار تایید',
|
||||
statusText: "در انتظار تایید",
|
||||
}
|
||||
: p,
|
||||
);
|
||||
|
||||
await this.prisma.setting.upsert({
|
||||
where: { key: 'sms_patterns_config' },
|
||||
where: { key: "sms_patterns_config" },
|
||||
update: {
|
||||
category: 'sms_patterns',
|
||||
category: "sms_patterns",
|
||||
value: updated as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
create: {
|
||||
key: 'sms_patterns_config',
|
||||
category: 'sms_patterns',
|
||||
key: "sms_patterns_config",
|
||||
category: "sms_patterns",
|
||||
value: updated as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
@@ -1012,7 +1012,7 @@ export class SmsService {
|
||||
*/
|
||||
async sendPatternSms(options: SendPatternSmsOptions): Promise<boolean> {
|
||||
const config = await this.getSmsConfig();
|
||||
const msgType = options.type || 'GENERIC_PATTERN';
|
||||
const msgType = options.type || "GENERIC_PATTERN";
|
||||
|
||||
if (!config.enabled) {
|
||||
this.logger.warn(`[SMS Disabled] SMS dispatch skipped for ${options.to}`);
|
||||
@@ -1021,21 +1021,21 @@ export class SmsService {
|
||||
type: msgType,
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
status: 'DISABLED',
|
||||
errorMessage: 'ارسال پیامک از پنل ادمین غیرفعال شده است.',
|
||||
status: "DISABLED",
|
||||
errorMessage: "ارسال پیامک از پنل ادمین غیرفعال شده است.",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!config.username || !config.password) {
|
||||
const err = 'مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.';
|
||||
const err = "مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.";
|
||||
this.logger.error(`[SMS MISCONFIGURED] ${err}`);
|
||||
await this.recordLog({
|
||||
receptor: options.to,
|
||||
type: msgType,
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
errorMessage: err,
|
||||
});
|
||||
return false;
|
||||
@@ -1045,7 +1045,7 @@ export class SmsService {
|
||||
const payload = JSON.stringify({
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
text: options.args.join(';'),
|
||||
text: options.args.join(";"),
|
||||
to: options.to,
|
||||
bodyId: options.bodyId,
|
||||
});
|
||||
@@ -1054,21 +1054,21 @@ export class SmsService {
|
||||
void this.renderPatternMessage(options.bodyId, options.args).then(
|
||||
(renderedText) => {
|
||||
const req = https.request(
|
||||
'https://rest.payamak-panel.com/api/SendSMS/BaseServiceNumber',
|
||||
"https://rest.payamak-panel.com/api/SendSMS/BaseServiceNumber",
|
||||
{
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload),
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.byteLength(payload),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
let data = "";
|
||||
res.on(
|
||||
'data',
|
||||
"data",
|
||||
(chunk: Buffer | string) => (data += String(chunk)),
|
||||
);
|
||||
res.on('end', () => {
|
||||
res.on("end", () => {
|
||||
void (async () => {
|
||||
try {
|
||||
const json = JSON.parse(data) as MeliPayamakResponse;
|
||||
@@ -1083,7 +1083,7 @@ export class SmsService {
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
messageText: renderedText,
|
||||
status: 'SUCCESS',
|
||||
status: "SUCCESS",
|
||||
recId: String(val),
|
||||
});
|
||||
resolve(true);
|
||||
@@ -1098,7 +1098,7 @@ export class SmsService {
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
messageText: renderedText,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
recId: String(val),
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
@@ -1113,7 +1113,7 @@ export class SmsService {
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
messageText: renderedText,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
errorMessage: `خطای پارس پاسخ سرور: ${data || msg}`,
|
||||
});
|
||||
resolve(false);
|
||||
@@ -1123,7 +1123,7 @@ export class SmsService {
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', (err: Error) => {
|
||||
req.on("error", (err: Error) => {
|
||||
void (async () => {
|
||||
this.logger.error(
|
||||
`[SMS Exception] MeliPayamak HTTP Error: ${err.message}`,
|
||||
@@ -1134,7 +1134,7 @@ export class SmsService {
|
||||
patternId: options.bodyId,
|
||||
args: options.args,
|
||||
messageText: renderedText,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
errorMessage: `خطای شبکه: ${err.message}`,
|
||||
});
|
||||
resolve(false);
|
||||
@@ -1163,44 +1163,44 @@ export class SmsService {
|
||||
const config = await this.getSmsConfig();
|
||||
|
||||
if (!config.username || !config.password) {
|
||||
const msg = 'نام کاربری یا رمز عبور سامانه ملی پیامک تنظیم نشده است.';
|
||||
const msg = "نام کاربری یا رمز عبور سامانه ملی پیامک تنظیم نشده است.";
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
type: "TEST",
|
||||
patternId: testPatternId,
|
||||
args: testArgs,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
errorMessage: msg,
|
||||
});
|
||||
return { success: false, message: msg };
|
||||
}
|
||||
|
||||
const bodyId = testPatternId || config.otpBodyId || 508079;
|
||||
const args = testArgs && testArgs.length > 0 ? testArgs : ['123456'];
|
||||
const args = testArgs && testArgs.length > 0 ? testArgs : ["123456"];
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const payload = JSON.stringify({
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
text: args.join(';'),
|
||||
text: args.join(";"),
|
||||
to: targetPhone,
|
||||
bodyId: bodyId,
|
||||
});
|
||||
|
||||
void this.renderPatternMessage(bodyId, args).then((renderedText) => {
|
||||
const req = https.request(
|
||||
'https://rest.payamak-panel.com/api/SendSMS/BaseServiceNumber',
|
||||
"https://rest.payamak-panel.com/api/SendSMS/BaseServiceNumber",
|
||||
{
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(payload),
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.byteLength(payload),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on('end', () => {
|
||||
let data = "";
|
||||
res.on("data", (chunk: Buffer | string) => (data += String(chunk)));
|
||||
res.on("end", () => {
|
||||
void (async () => {
|
||||
try {
|
||||
const json = JSON.parse(data) as MeliPayamakResponse;
|
||||
@@ -1208,11 +1208,11 @@ export class SmsService {
|
||||
if (json && (val > 15 || json.RetStatus === 1)) {
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
type: "TEST",
|
||||
patternId: bodyId,
|
||||
args,
|
||||
messageText: renderedText,
|
||||
status: 'SUCCESS',
|
||||
status: "SUCCESS",
|
||||
recId: String(val),
|
||||
});
|
||||
resolve({
|
||||
@@ -1224,11 +1224,11 @@ export class SmsService {
|
||||
const errMsg = `خطای درگاه ملی پیامک: کد پاسخ بازگشتی ${val}`;
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
type: "TEST",
|
||||
patternId: bodyId,
|
||||
args,
|
||||
messageText: renderedText,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
recId: String(val),
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
@@ -1243,11 +1243,11 @@ export class SmsService {
|
||||
const errMsg = `پاسخ نامعتبر از سرور ملی پیامک: ${data || msg}`;
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
type: "TEST",
|
||||
patternId: bodyId,
|
||||
args,
|
||||
messageText: renderedText,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
resolve({ success: false, message: errMsg });
|
||||
@@ -1257,16 +1257,16 @@ export class SmsService {
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', (err: Error) => {
|
||||
req.on("error", (err: Error) => {
|
||||
void (async () => {
|
||||
const errMsg = `خطای برقراری ارتباط با وبسرویس ملی پیامک: ${err.message}`;
|
||||
await this.recordLog({
|
||||
receptor: targetPhone,
|
||||
type: 'TEST',
|
||||
type: "TEST",
|
||||
patternId: bodyId,
|
||||
args,
|
||||
messageText: renderedText,
|
||||
status: 'FAILED',
|
||||
status: "FAILED",
|
||||
errorMessage: errMsg,
|
||||
});
|
||||
resolve({ success: false, message: errMsg });
|
||||
@@ -1288,7 +1288,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.otpBodyId,
|
||||
args: [otpCode, otpCode],
|
||||
type: 'OTP',
|
||||
type: "OTP",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1302,12 +1302,12 @@ export class SmsService {
|
||||
amount: string,
|
||||
): Promise<boolean> {
|
||||
const config = await this.getSmsConfig();
|
||||
const cleanName = (customerName || 'مشتری').trim();
|
||||
const cleanName = (customerName || "مشتری").trim();
|
||||
return this.sendPatternSms({
|
||||
to: phone,
|
||||
bodyId: config.orderBodyId,
|
||||
args: [cleanName, orderNumber, amount],
|
||||
type: 'ORDER_CONFIRMATION',
|
||||
type: "ORDER_CONFIRMATION",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1324,7 +1324,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.shippingBodyId,
|
||||
args: [orderNumber, trackingCode],
|
||||
type: 'SHIPPING_TRACKING',
|
||||
type: "SHIPPING_TRACKING",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1340,7 +1340,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.b2bBodyId,
|
||||
args: [applicantName],
|
||||
type: 'B2B_NOTIFICATION',
|
||||
type: "B2B_NOTIFICATION",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1358,7 +1358,7 @@ export class SmsService {
|
||||
to: phone,
|
||||
bodyId: config.petCareBodyId,
|
||||
args: [petName, reminderType],
|
||||
type: 'PET_CARE_REMINDER',
|
||||
type: "PET_CARE_REMINDER",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1370,19 +1370,19 @@ export class SmsService {
|
||||
if (!config.enabled) {
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: 'GENERIC_TEXT',
|
||||
type: "GENERIC_TEXT",
|
||||
messageText: message,
|
||||
status: 'DISABLED',
|
||||
errorMessage: 'ارسال پیامک غیرفعال است.',
|
||||
status: "DISABLED",
|
||||
errorMessage: "ارسال پیامک غیرفعال است.",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
this.logger.log(`[SMS Text Sent] To: ${phone}, Content: ${message}`);
|
||||
await this.recordLog({
|
||||
receptor: phone,
|
||||
type: 'GENERIC_TEXT',
|
||||
type: "GENERIC_TEXT",
|
||||
messageText: message,
|
||||
status: 'SUCCESS',
|
||||
status: "SUCCESS",
|
||||
});
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user