feat(admin,sms): implement full pattern management CRUD and live binding directly from admin panel
This commit is contained in:
1 parent
09fd339e89
commit
0934b4f3af
4 files changed
+868
-35
No files matched your search
@@ -20,6 +20,15 @@ export interface SmsConfig {
|
||||
petCareBodyId: number;
|
||||
}
|
||||
|
||||
export interface MeliPayamakPattern {
|
||||
id: number;
|
||||
title: string;
|
||||
body: string;
|
||||
status: number; // 0 = Pending, 1 = Approved, 2 = Needs Edit
|
||||
statusText?: string;
|
||||
assignedTo?: string[];
|
||||
}
|
||||
|
||||
interface MeliPayamakResponse {
|
||||
Value?: number;
|
||||
RetStatus?: number;
|
||||
@@ -68,6 +77,293 @@ export class SmsService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper HTTP POST request to Payamak-Panel ASMX endpoints
|
||||
*/
|
||||
private async postAsmx(endpoint: string, params: Record<string, string | number>): Promise<string> {
|
||||
const postData = Object.entries(params)
|
||||
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
|
||||
.join('&');
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = https.request(
|
||||
`https://api.payamak-panel.com/post/SharedService.asmx/${endpoint}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'Content-Length': Buffer.byteLength(postData),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => (data += chunk));
|
||||
res.on('end', () => resolve(data));
|
||||
},
|
||||
);
|
||||
|
||||
req.on('error', (err) => reject(err));
|
||||
req.write(postData);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse XML response for GetSharedServiceBody into structured pattern array
|
||||
*/
|
||||
private parsePatternsXml(xml: string): MeliPayamakPattern[] {
|
||||
const patterns: MeliPayamakPattern[] = [];
|
||||
const itemRegex = /<SharedServiceBody>([\s\S]*?)<\/SharedServiceBody>/gi;
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
while ((match = itemRegex.exec(xml)) !== null) {
|
||||
const block = match[1];
|
||||
const idMatch = block.match(/<Id>(\d+)<\/Id>/i);
|
||||
const titleMatch = block.match(/<Title>([\s\S]*?)<\/Title>/i);
|
||||
const bodyMatch = block.match(/<Body>([\s\S]*?)<\/Body>/i);
|
||||
const statusMatch = block.match(/<Status>(-?\d+)<\/Status>/i);
|
||||
|
||||
if (idMatch) {
|
||||
const id = parseInt(idMatch[1], 10);
|
||||
const title = (titleMatch ? titleMatch[1] : '').replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
|
||||
const body = (bodyMatch ? bodyMatch[1] : '').replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
|
||||
const status = statusMatch ? parseInt(statusMatch[1], 10) : 0;
|
||||
|
||||
let statusText = 'در انتظار تایید';
|
||||
if (status === 1) statusText = 'تایید شده';
|
||||
else if (status === 2 || status === -1) statusText = 'نیاز به ویرایش';
|
||||
|
||||
patterns.push({ id, title, body, status, statusText });
|
||||
}
|
||||
}
|
||||
|
||||
return patterns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all registered patterns from MeliPayamak (with local cache sync)
|
||||
*/
|
||||
async getPatterns(): Promise<MeliPayamakPattern[]> {
|
||||
const config = await this.getSmsConfig();
|
||||
|
||||
let remotePatterns: MeliPayamakPattern[] = [];
|
||||
if (config.username && config.password) {
|
||||
try {
|
||||
const rawXml = await this.postAsmx('GetSharedServiceBody', {
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
});
|
||||
remotePatterns = this.parsePatternsXml(rawXml);
|
||||
} catch (err: any) {
|
||||
this.logger.warn(`[SMS Patterns] Remote fetch failed: ${err.message}. Using stored patterns.`);
|
||||
}
|
||||
}
|
||||
|
||||
// Load local stored patterns from settings table
|
||||
const storedSetting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms_patterns' },
|
||||
});
|
||||
const localPatterns: MeliPayamakPattern[] = (storedSetting?.value as any) || [];
|
||||
|
||||
// Merge remote and local (remote takes precedence on ID match)
|
||||
const map = new Map<number, MeliPayamakPattern>();
|
||||
|
||||
// Add configured system patterns by default if map is empty
|
||||
const defaultConfigs: Array<{ id: number; title: string; body: string; assigned: string }> = [
|
||||
{ id: config.otpBodyId, title: 'کد تایید ورود و ثبتنام (OTP)', body: 'کد ورود به کانینا: {0}', assigned: 'otp' },
|
||||
{ id: config.orderBodyId, title: 'تایید و ثبت فاکتور سفارش', body: 'سفارش شما به شماره {0} با مبلغ {1} ثبت گردید.', assigned: 'order' },
|
||||
{ id: config.shippingBodyId, title: 'ارسال کد رهگیری پستی', body: 'مرسوله سفارش {0} با کد رهگیری پستی {1} ارسال شد.', assigned: 'shipping' },
|
||||
{ id: config.b2bBodyId, title: 'اطلاعرسانی درخواست B2B', body: 'همکار گرامی {0} درخواست شما دریافت شد.', assigned: 'b2b' },
|
||||
];
|
||||
|
||||
for (const d of defaultConfigs) {
|
||||
if (d.id > 0) {
|
||||
map.set(d.id, {
|
||||
id: d.id,
|
||||
title: d.title,
|
||||
body: d.body,
|
||||
status: 1,
|
||||
statusText: 'تایید شده',
|
||||
assignedTo: [d.assigned],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const lp of localPatterns) {
|
||||
if (lp.id) map.set(lp.id, { ...lp });
|
||||
}
|
||||
|
||||
for (const rp of remotePatterns) {
|
||||
const existing = map.get(rp.id);
|
||||
map.set(rp.id, {
|
||||
...rp,
|
||||
assignedTo: existing?.assignedTo || [],
|
||||
});
|
||||
}
|
||||
|
||||
// Mark current bindings
|
||||
const result = Array.from(map.values()).map((p) => {
|
||||
const assigned: string[] = [];
|
||||
if (p.id === config.otpBodyId) assigned.push('کد تایید OTP');
|
||||
if (p.id === config.orderBodyId) assigned.push('تایید سفارش');
|
||||
if (p.id === config.shippingBodyId) assigned.push('کد رهگیری پست');
|
||||
if (p.id === config.b2bBodyId) assigned.push('همکاران B2B');
|
||||
if (p.id === config.petCareBodyId) assigned.push('یادآور سلامت پت');
|
||||
return { ...p, assignedTo: assigned };
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new pattern to MeliPayamak
|
||||
*/
|
||||
async addPattern(title: string, body: string, blackListId: number = 0): Promise<{ success: boolean; bodyId?: number; message: string }> {
|
||||
const config = await this.getSmsConfig();
|
||||
|
||||
if (!config.username || !config.password) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const rawXml = await this.postAsmx('SharedServiceBodyAdd', {
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
title,
|
||||
body,
|
||||
blackListId,
|
||||
});
|
||||
|
||||
const match = rawXml.match(/<int.*?>(-?\d+)<\/int>/i) || rawXml.match(/>(-?\d+)</);
|
||||
const code = match ? parseInt(match[1], 10) : 0;
|
||||
|
||||
if (code > 0) {
|
||||
// Store locally
|
||||
await this.saveLocalPattern({
|
||||
id: code,
|
||||
title,
|
||||
body,
|
||||
status: 0,
|
||||
statusText: 'در انتظار تایید',
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
bodyId: code,
|
||||
message: `الگو با موفقیت ثبت شد و شناسه اختصاصی ${code} دریافت گردید. (وضعیت: در انتظار تایید ناظر)`,
|
||||
};
|
||||
} else if (code === 0) {
|
||||
return { success: false, message: 'نام کاربری یا کلمه عبور ملی پیامک اشتباه است.' };
|
||||
} else if (code === -2) {
|
||||
return { success: false, message: 'شناسه لیست سیاه ویژه اشتباه است.' };
|
||||
} else {
|
||||
return { success: false, message: `خطا در ثبت پترن با کد پاسخ: ${code}` };
|
||||
}
|
||||
} catch (err: any) {
|
||||
const generatedId = Math.floor(500000 + Math.random() * 90000);
|
||||
await this.saveLocalPattern({
|
||||
id: generatedId,
|
||||
title,
|
||||
body,
|
||||
status: 0,
|
||||
statusText: 'ثبت محلی (در انتظار اتصال سرور)',
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
bodyId: generatedId,
|
||||
message: `الگو به صورت محلی با شناسه موقت ${generatedId} ذخیره شد (${err.message}).`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit an existing pattern in MeliPayamak
|
||||
*/
|
||||
async editPattern(bodyId: number, body: string): Promise<{ success: boolean; message: string }> {
|
||||
const config = await this.getSmsConfig();
|
||||
|
||||
if (!config.username || !config.password) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'مشخصات نام کاربری و رمز عبور سامانه پیامک تنظیم نشده است.',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const rawXml = await this.postAsmx('SharedServiceBodyEdit', {
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
bodyId,
|
||||
body,
|
||||
});
|
||||
|
||||
const match = rawXml.match(/<int.*?>(-?\d+)<\/int>/i) || rawXml.match(/>(-?\d+)</);
|
||||
const code = match ? parseInt(match[1], 10) : 0;
|
||||
|
||||
if (code === 1) {
|
||||
await this.updateLocalPattern(bodyId, body);
|
||||
return {
|
||||
success: true,
|
||||
message: 'ویرایش الگو با موفقیت انجام شد و منتظر تایید مجدد ناظر میباشد.',
|
||||
};
|
||||
} else if (code === -1) {
|
||||
await this.updateLocalPattern(bodyId, body);
|
||||
return {
|
||||
success: true,
|
||||
message: 'متن الگو در سیستم بروز شد (توجه: فقط الگوهای در وضعیت نیاز به ویرایش در وبسرویس اصلاح میشوند).',
|
||||
};
|
||||
} else {
|
||||
return { success: false, message: `خطا در ویرایش الگو با کد پاسخ: ${code}` };
|
||||
}
|
||||
} catch (err: any) {
|
||||
await this.updateLocalPattern(bodyId, body);
|
||||
return {
|
||||
success: true,
|
||||
message: `متن الگو در دیتابیس داخلی بروز شد (${err.message}).`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private async saveLocalPattern(pattern: MeliPayamakPattern) {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms_patterns' },
|
||||
});
|
||||
const list: MeliPayamakPattern[] = (setting?.value as any) || [];
|
||||
const updated = [pattern, ...list.filter((p) => p.id !== pattern.id)];
|
||||
|
||||
await this.prisma.setting.upsert({
|
||||
where: { key: 'sms_patterns_config' },
|
||||
update: { category: 'sms_patterns', value: updated as any },
|
||||
create: { key: 'sms_patterns_config', category: 'sms_patterns', value: updated as any },
|
||||
});
|
||||
} catch (err: any) {
|
||||
this.logger.error(`Failed to save local pattern: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async updateLocalPattern(bodyId: number, newBody: string) {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'sms_patterns' },
|
||||
});
|
||||
const list: MeliPayamakPattern[] = (setting?.value as any) || [];
|
||||
const updated = list.map((p) => (p.id === bodyId ? { ...p, body: newBody, status: 0, statusText: 'در انتظار تایید' } : p));
|
||||
|
||||
await this.prisma.setting.upsert({
|
||||
where: { key: 'sms_patterns_config' },
|
||||
update: { category: 'sms_patterns', value: updated as any },
|
||||
create: { key: 'sms_patterns_config', category: 'sms_patterns', value: updated as any },
|
||||
});
|
||||
} catch (err: any) {
|
||||
this.logger.error(`Failed to update local pattern: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send Pattern SMS using MeliPayamak Shared Service Line (Bypasses Blacklist)
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user