Substitute org name and balance tokens in outbound SMS so templates no longer leave {از طرف} literal.

EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-14 17:12:31 +03:30
co-authored by Cursor
parent f36fddc23b
commit 717a41e94b
12 changed files with 666 additions and 200 deletions
+68 -1
View File
@@ -21,15 +21,82 @@ function tehranJalaliLong(d: Date) {
return `${toFaDigits(j.jd)} ${jalaliMonthName(j.jm)} ${toFaDigits(j.jy)}`; return `${toFaDigits(j.jd)} ${jalaliMonthName(j.jm)} ${toFaDigits(j.jy)}`;
} }
/** قالب بس/بد مثل UI ته‌حساب — برای توکن‌های مانده در پیامک */
export function formatSmsBedBes(v: unknown, maximumFractionDigits = 3): string {
if (v == null) return '';
const s = String(v).trim();
if (!s || s === 'null' || s === 'undefined' || s === 'NaN') return '';
const n = Number(s.replace(/,/g, ''));
if (!Number.isFinite(n)) return toFaDigits(s);
const abs = toFaDigits(
new Intl.NumberFormat('en-US', { maximumFractionDigits }).format(Math.abs(n)),
);
if (n === 0) return abs;
return `${abs} ${n < 0 ? 'بد' : 'بس'}`;
}
const METAL_FIELD_LABELS: Record<string, string> = {
MandeyeVazni: 'طلا',
MandeyeVazniNoghre: 'نقره',
MandeyeKolBeTALA: 'کل به طلا',
MandeMenhayeSeke: 'منهای سکه',
};
function isMetalMandehKey(key: string) {
if (METAL_FIELD_LABELS[key]) return true;
if (key.startsWith('Seke_')) return true;
return /Vazni|طلا|نقره|فلز|Gold|Silver/i.test(key);
}
function metalFieldLabel(key: string) {
if (METAL_FIELD_LABELS[key]) return METAL_FIELD_LABELS[key]!;
if (key.startsWith('Seke_')) return `سکه ${key.slice(5)}`;
return key;
}
/** از فیلدهای مانده ته‌حساب، متن مانده ریالی و فلزی می‌سازد */
export function smsBalanceTexts(input: {
mandehFields?: Array<{ key: string; value: string | null }> | null;
rialBalance?: number | null;
goldBalance?: number | null;
}): { rialBalance: string; metalBalance: string } {
const fields = input.mandehFields ?? [];
const mali = fields.find((f) => f.key === 'MandeyeMali' || f.key === 'MandeyeKolBePool');
const rial =
formatSmsBedBes(mali?.value ?? input.rialBalance) ||
formatSmsBedBes(input.rialBalance);
const metalParts = fields
.filter((f) => isMetalMandehKey(f.key) && f.value != null && String(f.value).trim() !== '')
.map((f) => `${metalFieldLabel(f.key)} ${formatSmsBedBes(f.value)}`.trim())
.filter(Boolean);
const metal =
metalParts.join('، ') ||
(input.goldBalance != null && formatSmsBedBes(input.goldBalance)
? `طلا ${formatSmsBedBes(input.goldBalance)}`
: '');
return { rialBalance: rial, metalBalance: metal };
}
export function renderSmsText( export function renderSmsText(
text: string, text: string,
vars: { name?: string; phone?: string; title?: string; company?: string }, vars: {
name?: string;
phone?: string;
title?: string;
company?: string;
from?: string;
rialBalance?: string;
metalBalance?: string;
},
) { ) {
return applyMessageTemplate(text, { return applyMessageTemplate(text, {
name: vars.name, name: vars.name,
phone: vars.phone, phone: vars.phone,
title: vars.title, title: vars.title,
company: vars.company, company: vars.company,
from: vars.from,
rialBalance: vars.rialBalance,
metalBalance: vars.metalBalance,
date: tehranJalaliLong(new Date()), date: tehranJalaliLong(new Date()),
}).trim(); }).trim();
} }
+67 -13
View File
@@ -56,7 +56,8 @@ import { GamificationService } from '../gamification/gamification.service';
import { parseBirthDate } from '../common/excel'; import { parseBirthDate } from '../common/excel';
import { SmsGatewayService } from '../sms-billing/sms-gateway.service'; import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
import { selectMonthBirthdays } from './birthday-month'; import { selectMonthBirthdays } from './birthday-month';
import { renderSmsText } from '../common/sms-text'; import { renderSmsText, smsBalanceTexts } from '../common/sms-text';
import { extractMandehRaw } from '../integrations/tahesab/tahesab-methods';
import { normalizeTags } from '../common/tags'; import { normalizeTags } from '../common/tags';
import { buildSearchWhere, ci, splitCsv } from '../common/search'; import { buildSearchWhere, ci, splitCsv } from '../common/search';
import { import {
@@ -763,6 +764,7 @@ export class PeopleService implements OnModuleInit {
lastName: true, lastName: true,
mobile: true, mobile: true,
phone: true, phone: true,
position: true,
ownerId: true, ownerId: true,
birthDate: true, birthDate: true,
company: { select: { name: true } }, company: { select: { name: true } },
@@ -836,12 +838,15 @@ export class PeopleService implements OnModuleInit {
); );
} }
} }
const message = renderSmsText(body, { const message = renderSmsText(
name: fullName, body,
phone: mobile, await this.personSmsVars(actor.organizationId, person.id, {
title: fullName, name: fullName,
company: person.company?.name ?? '', phone: mobile,
}); title: person.position?.trim() || '',
company: person.company?.name ?? '',
}),
);
if (!message) throw new BadRequestException('متن پیامک خالی است.'); if (!message) throw new BadRequestException('متن پیامک خالی است.');
const result = await this.sms.send({ const result = await this.sms.send({
organizationId: actor.organizationId, organizationId: actor.organizationId,
@@ -902,12 +907,15 @@ export class PeopleService implements OnModuleInit {
const person = await this.get(actor, personId); const person = await this.get(actor, personId);
const mobile = person.mobile || person.phone; const mobile = person.mobile || person.phone;
if (!mobile) throw new BadRequestException('برای این مشتری شماره موبایل ثبت نشده است.'); if (!mobile) throw new BadRequestException('برای این مشتری شماره موبایل ثبت نشده است.');
const message = renderSmsText(body, { const message = renderSmsText(
name: person.fullName, body,
phone: mobile, await this.personSmsVars(actor.organizationId, person.id, {
title: person.fullName, name: person.fullName,
company: person.company?.name ?? '', phone: mobile,
}); title: person.position?.trim() || '',
company: person.company?.name ?? '',
}),
);
if (!message) throw new BadRequestException('متن پیامک خالی است.'); if (!message) throw new BadRequestException('متن پیامک خالی است.');
const result = await this.sms.send({ const result = await this.sms.send({
organizationId: actor.organizationId, organizationId: actor.organizationId,
@@ -937,6 +945,52 @@ export class PeopleService implements OnModuleInit {
return { ok: true }; return { ok: true };
} }
/** نام سازمان + مانده‌های کش‌شدهٔ ته‌حساب برای توکن‌های پیامک */
private async personSmsVars(
organizationId: string,
personId: string,
base: {
name: string;
phone: string;
title: string;
company: string;
},
) {
const [org, link] = await Promise.all([
this.prisma.organization.findUnique({
where: { id: organizationId },
select: { name: true },
}),
this.prisma.personAccountingLink.findFirst({
where: { personId, connection: { organizationId } },
orderBy: [
{ connection: { isDefault: 'desc' } },
{ linkedAt: 'desc' },
],
include: { balanceCache: true },
}),
]);
let rialBalance = '';
let metalBalance = '';
const cache = link?.balanceCache;
if (cache) {
const rawView = extractMandehRaw(cache.rawResponse);
const bal = smsBalanceTexts({
mandehFields: rawView.fields,
rialBalance: cache.rialBalance,
goldBalance: cache.goldBalance,
});
rialBalance = bal.rialBalance;
metalBalance = bal.metalBalance;
}
return {
...base,
from: org?.name?.trim() || '',
rialBalance,
metalBalance,
};
}
listSmsHistory(actor: Actor, personId: string, limit?: number) { listSmsHistory(actor: Actor, personId: string, limit?: number) {
return this.get(actor, personId).then(() => return this.get(actor, personId).then(() =>
this.outboundSms.historyForPerson(actor.organizationId, personId, limit), this.outboundSms.historyForPerson(actor.organizationId, personId, limit),
+6 -1
View File
@@ -1572,11 +1572,16 @@ export class LeadsService {
const mobile = lead.mobile || lead.phone; const mobile = lead.mobile || lead.phone;
if (!mobile) throw new BadRequestException('برای این لید شماره موبایل ثبت نشده است.'); if (!mobile) throw new BadRequestException('برای این لید شماره موبایل ثبت نشده است.');
const name = (lead.contactName || lead.title).trim(); const name = (lead.contactName || lead.title).trim();
const org = await this.prisma.organization.findUnique({
where: { id: actor.organizationId },
select: { name: true },
});
const message = renderSmsText(body, { const message = renderSmsText(body, {
name, name,
phone: mobile, phone: mobile,
title: lead.title, title: lead.title,
company: lead.contactName ? lead.title : '', company: lead.trade?.trim() || '',
from: org?.name?.trim() || '',
}); });
if (!message) throw new BadRequestException('متن پیامک خالی است.'); if (!message) throw new BadRequestException('متن پیامک خالی است.');
const result = await this.sms.send({ const result = await this.sms.send({
@@ -56,7 +56,19 @@ function testTemplate() {
}) === 'سلام علی 0912', }) === 'سلام علی 0912',
'name phone vars', 'name phone vars',
); );
assert(clipSms('الف'.repeat(200)).length === 200, 'sms is not clipped'); assert(
applyMessageTemplate('تبریک {از طرف}', { from: 'هنراندیشه' }) ===
'تبریک هنراندیشه',
'from org var',
);
assert(
applyMessageTemplate('مانده {مانده ریالی} / {مانده فلزی}', {
rialBalance: '۱۰۰۰ بس',
metalBalance: 'طلا ۲',
}) === 'مانده ۱۰۰۰ بس / طلا ۲',
'balance vars',
);
assert(clipSms('ا'.repeat(200)).length === 200, 'sms is not clipped');
} }
testDelay(); testDelay();
@@ -77,6 +77,17 @@ export function buildSendAts(
return times; return times;
} }
/** یکسان‌سازی کلید توکن‌های قالب (فاصله/ZWNJ/ی عربی). */
export function normalizeTemplateKey(key: string): string {
return String(key ?? '')
.normalize('NFKC')
.replace(/[\u200c\u200d\u200e\u200f\ufeff]/g, '')
.replace(/ي/g, 'ی')
.replace(/ك/g, 'ک')
.replace(/\s+/g, ' ')
.trim();
}
export function applyMessageTemplate( export function applyMessageTemplate(
text: string, text: string,
vars: { vars: {
@@ -85,22 +96,44 @@ export function applyMessageTemplate(
phone?: string; phone?: string;
date?: string; date?: string;
company?: string; company?: string;
/** نام سازمان فرستنده */
from?: string;
/** مانده مالی قالب‌بندی‌شده */
rialBalance?: string;
/** مانده‌های وزنی/فلزی قالب‌بندی‌شده */
metalBalance?: string;
}, },
): string { ): string {
const map: Record<string, string> = { const from = vars.from ?? '';
title: vars.title ?? '', const rial = vars.rialBalance ?? '';
عنوان: vars.title ?? '', const metal = vars.metalBalance ?? '';
نام: vars.name ?? '', const entries: Array<[string, string]> = [
name: vars.name ?? '', ['title', vars.title ?? ''],
شماره: vars.phone ?? '', ['عنوان', vars.title ?? ''],
phone: vars.phone ?? '', ['نام', vars.name ?? ''],
تاریخ: vars.date ?? '', ['name', vars.name ?? ''],
date: vars.date ?? '', ['شماره', vars.phone ?? ''],
شرکت: vars.company ?? '', ['phone', vars.phone ?? ''],
company: vars.company ?? '', ['تاریخ', vars.date ?? ''],
}; ['date', vars.date ?? ''],
['شرکت', vars.company ?? ''],
['company', vars.company ?? ''],
['از طرف', from],
['ازطرف', from],
['from', from],
['مانده ریالی', rial],
['ماندهریالی', rial],
['rialBalance', rial],
['مانده فلزی', metal],
['ماندهفلزی', metal],
['metalBalance', metal],
];
const map: Record<string, string> = {};
for (const [key, value] of entries) {
map[normalizeTemplateKey(key)] = value;
}
return text.replace(/\{([^}]+)\}/g, (full, key: string) => { return text.replace(/\{([^}]+)\}/g, (full, key: string) => {
const next = map[key.trim()]; const next = map[normalizeTemplateKey(key)];
return next === undefined ? full : next; return next === undefined ? full : next;
}); });
} }
@@ -356,6 +356,10 @@ export class MessageAutomationsService {
}) })
: null; : null;
const lead = await this.lookupLead(job); const lead = await this.lookupLead(job);
const org = await this.prisma.organization.findUnique({
where: { id: job.organizationId },
select: { name: true },
});
const personName = person const personName = person
? [person.firstName, person.lastName].filter(Boolean).join(' ').trim() ? [person.firstName, person.lastName].filter(Boolean).join(' ').trim()
: ''; : '';
@@ -366,6 +370,7 @@ export class MessageAutomationsService {
phone, phone,
date: formatJalaliDayFa(new Date()), date: formatJalaliDayFa(new Date()),
company: person?.company?.name ?? '', company: person?.company?.name ?? '',
from: org?.name?.trim() || '',
}; };
const title = applyMessageTemplate(job.rule.title, vars).slice(0, 200); const title = applyMessageTemplate(job.rule.title, vars).slice(0, 200);
const body = applyMessageTemplate(job.rule.body, vars); const body = applyMessageTemplate(job.rule.body, vars);
@@ -511,7 +511,7 @@ export class SmsCampaignsService {
const leadIds = batch const leadIds = batch
.map((r) => r.leadId) .map((r) => r.leadId)
.filter((id): id is string => Boolean(id)); .filter((id): id is string => Boolean(id));
const [people, leads] = await Promise.all([ const [people, leads, org] = await Promise.all([
personIds.length personIds.length
? this.prisma.person.findMany({ ? this.prisma.person.findMany({
where: { id: { in: personIds } }, where: { id: { in: personIds } },
@@ -535,9 +535,14 @@ export class SmsCampaignsService {
}, },
}) })
: Promise.resolve([]), : Promise.resolve([]),
this.prisma.organization.findUnique({
where: { id: campaign.organizationId },
select: { name: true },
}),
]); ]);
const personMap = new Map(people.map((p) => [p.id, p])); const personMap = new Map(people.map((p) => [p.id, p]));
const leadMap = new Map(leads.map((l) => [l.id, l])); const leadMap = new Map(leads.map((l) => [l.id, l]));
const fromOrg = org?.name?.trim() || '';
let sent = 0; let sent = 0;
let failed = 0; let failed = 0;
@@ -572,6 +577,7 @@ export class SmsCampaignsService {
phone: recipient.mobile, phone: recipient.mobile,
title, title,
company, company,
from: fromOrg,
}); });
const personalized = await this.tracking.personalizeSmsBody({ const personalized = await this.tracking.personalizeSmsBody({
+4
View File
@@ -38,6 +38,10 @@ describe('اتوماسیون پیام', () => {
'سلام علی از منتکت - {unknown}', 'سلام علی از منتکت - {unknown}',
); );
assert.equal(applyMessageTemplate('{ name }', { name: 'x' }), 'x'); assert.equal(applyMessageTemplate('{ name }', { name: 'x' }), 'x');
assert.equal(
applyMessageTemplate('از طرف {از طرف}', { from: 'هنراندیشه' }),
'از طرف هنراندیشه',
);
}); });
it('متن پیامک بریده نمی‌شود', () => { it('متن پیامک بریده نمی‌شود', () => {
+443 -166
View File
@@ -1,19 +1,23 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from 'vue'; import { computed, nextTick, ref, watch } from 'vue';
import axios from 'axios'; import axios from 'axios';
import type { import type {
OutboundSmsHistoryResponse, OutboundSmsHistoryResponse,
OutboundSmsLogDto, OutboundSmsLogDto,
PersonAssetsDto,
SmsTemplateDto, SmsTemplateDto,
} from '@mento/shared'; } from '@mento/shared';
import { import {
MESSAGE_AUTOMATION_FIELDS, MESSAGE_AUTOMATION_FIELDS,
SMS_TEMPLATE_BODY_MAX,
SMS_TEMPLATE_MAX, SMS_TEMPLATE_MAX,
SMS_TEMPLATE_NAME_MAX, SMS_TEMPLATE_NAME_MAX,
countSmsParts, countSmsParts,
} from '@mento/shared'; } from '@mento/shared';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { formatJalaliDay, formatJalaliNumeric, toFaDigits } from '@/lib/jalali'; import { formatJalaliDay, formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
import { formatTahesabBedBes } from '@/lib/tahesab';
import { useAuthStore } from '@/stores/auth';
import { UiButton, UiModal } from '@/components/ui'; import { UiButton, UiModal } from '@/components/ui';
const props = withDefaults( const props = withDefaults(
@@ -34,7 +38,7 @@ const props = withDefaults(
recordTitle: '', recordTitle: '',
company: '', company: '',
title: 'ارسال پیامک', title: 'ارسال پیامک',
defaultText: 'سلام {نام} عزیز', defaultText: '',
nest: false, nest: false,
}, },
); );
@@ -44,27 +48,70 @@ const emit = defineEmits<{
sent: []; sent: [];
}>(); }>();
type Panel = 'none' | 'fields' | 'templates';
const auth = useAuthStore();
const text = ref(''); const text = ref('');
const busy = ref(false); const busy = ref(false);
const error = ref(''); const error = ref('');
const done = ref(''); const done = ref('');
const fieldsOpen = ref(false); const notice = ref('');
const templatesOpen = ref(false); const panel = ref<Panel>('none');
const savingTemplate = ref(false); const savingTemplate = ref(false);
const templateName = ref(''); const templateName = ref('');
const templateBody = ref('');
const bodyEl = ref<HTMLTextAreaElement | null>(null); const bodyEl = ref<HTMLTextAreaElement | null>(null);
const templateBodyEl = ref<HTMLTextAreaElement | null>(null);
const history = ref<OutboundSmsLogDto[]>([]); const history = ref<OutboundSmsLogDto[]>([]);
const historyLoading = ref(false); const historyLoading = ref(false);
const templates = ref<SmsTemplateDto[]>([]); const templates = ref<SmsTemplateDto[]>([]);
const templatesLoading = ref(false); const templatesLoading = ref(false);
const fromOrg = ref('');
const rialBalanceText = ref('');
const metalBalanceText = ref('');
const METAL_FIELD_LABELS: Record<string, string> = {
MandeyeVazni: 'طلا',
MandeyeVazniNoghre: 'نقره',
MandeyeKolBeTALA: 'کل به طلا',
MandeMenhayeSeke: 'منهای سکه',
};
function isMetalMandehKey(key: string) {
if (METAL_FIELD_LABELS[key]) return true;
if (key.startsWith('Seke_')) return true;
return /Vazni|طلا|نقره|فلز|Gold|Silver/i.test(key);
}
function metalFieldLabel(key: string) {
if (METAL_FIELD_LABELS[key]) return METAL_FIELD_LABELS[key]!;
if (key.startsWith('Seke_')) return `سکه ${key.slice(5)}`;
return key;
}
function applyAssetsToVars(assets: PersonAssetsDto) {
const fields = assets.mandehFields ?? [];
const mali = fields.find((f) => f.key === 'MandeyeMali' || f.key === 'MandeyeKolBePool');
const rialRaw = mali?.value ?? assets.rialBalance;
rialBalanceText.value =
rialRaw == null || String(rialRaw).trim() === ''
? ''
: formatTahesabBedBes(rialRaw);
const metalParts = fields
.filter((f) => isMetalMandehKey(f.key) && f.value != null && String(f.value).trim() !== '')
.map((f) => `${metalFieldLabel(f.key)} ${formatTahesabBedBes(f.value)}`.trim());
metalBalanceText.value =
metalParts.join('، ') ||
(assets.goldBalance != null ? `طلا ${formatTahesabBedBes(assets.goldBalance)}` : '');
}
const preview = computed(() => fill(text.value)); const preview = computed(() => fill(text.value));
const count = computed(() => text.value.length); const count = computed(() => text.value.length);
const parts = computed(() => countSmsParts(text.value)); const parts = computed(() => countSmsParts(text.value));
const canSaveTemplate = computed( const canSaveTemplate = computed(
() => () =>
text.value.trim().length >= 2 &&
templateName.value.trim().length >= 1 && templateName.value.trim().length >= 1 &&
templateBody.value.trim().length >= 2 &&
templates.value.length < SMS_TEMPLATE_MAX && templates.value.length < SMS_TEMPLATE_MAX &&
!savingTemplate.value, !savingTemplate.value,
); );
@@ -76,15 +123,43 @@ watch(
text.value = props.defaultText; text.value = props.defaultText;
error.value = ''; error.value = '';
done.value = ''; done.value = '';
fieldsOpen.value = false; notice.value = '';
templatesOpen.value = false; panel.value = 'none';
templateName.value = ''; templateName.value = '';
templateBody.value = '';
busy.value = false; busy.value = false;
fromOrg.value = auth.user?.organizationName?.trim() || '';
rialBalanceText.value = '';
metalBalanceText.value = '';
void loadHistory(); void loadHistory();
void loadTemplates(); void loadTemplates();
void loadContextVars();
}, },
); );
async function loadContextVars() {
if (!fromOrg.value) {
try {
const { data } = await api.get<{ name?: string }>('/organizations/current');
if (data?.name?.trim()) fromOrg.value = data.name.trim();
} catch {
/* نام سازمان از auth کافی است */
}
}
const personMatch = props.endpoint.match(/\/people\/([^/]+)\/(?:sms|birthday-sms)/);
if (!personMatch?.[1]) return;
try {
const { data } = await api.get<PersonAssetsDto>(
`/integrations/tahesab/people/${personMatch[1]}/assets`,
{ params: { refresh: '0' } },
);
applyAssetsToVars(data);
} catch {
rialBalanceText.value = '';
metalBalanceText.value = '';
}
}
async function loadHistory() { async function loadHistory() {
history.value = []; history.value = [];
if (!props.historyEndpoint) return; if (!props.historyEndpoint) return;
@@ -106,74 +181,135 @@ async function loadTemplates() {
try { try {
const { data } = await api.get<SmsTemplateDto[]>('/sms-templates'); const { data } = await api.get<SmsTemplateDto[]>('/sms-templates');
templates.value = Array.isArray(data) ? data : []; templates.value = Array.isArray(data) ? data : [];
} catch { } catch (e) {
templates.value = []; templates.value = [];
error.value = apiMessage(e, 'بارگذاری پیامک‌های آماده ناموفق بود.');
} finally { } finally {
templatesLoading.value = false; templatesLoading.value = false;
} }
} }
const EMPTY_FIELD_HINT: Record<string, string> = {
عنوان: '〔عنوان ثبت نشده〕',
title: '〔عنوان ثبت نشده〕',
شرکت: '〔شرکت مشتری ثبت نشده〕',
company: '〔شرکت مشتری ثبت نشده〕',
نام: '〔نام ثبت نشده〕',
name: '〔نام ثبت نشده〕',
شماره: '〔شماره ثبت نشده〕',
phone: '〔شماره ثبت نشده〕',
'از طرف': '〔سازمان ثبت نشده〕',
from: '〔سازمان ثبت نشده〕',
'مانده ریالی': '〔مانده ریالی نیست〕',
rialBalance: '〔مانده ریالی نیست〕',
'مانده فلزی': '〔مانده فلزی نیست〕',
metalBalance: '〔مانده فلزی نیست〕',
};
function normalizeTemplateKey(key: string) {
return String(key ?? '')
.normalize('NFKC')
.replace(/[\u200c\u200d\u200e\u200f\ufeff]/g, '')
.replace(/ي/g, 'ی')
.replace(/ك/g, 'ک')
.replace(/\s+/g, ' ')
.trim();
}
/** پیش‌نمایش؛ اگر مقدار خالی باشد نشانه می‌گذارد تا با فیلد خالی قاطی نشود. */
function fill(source: string) { function fill(source: string) {
const map: Record<string, string> = { const from = fromOrg.value.trim();
نام: props.name, const rial = rialBalanceText.value.trim();
name: props.name, const metal = metalBalanceText.value.trim();
شماره: props.phone, const entries: Array<[string, string]> = [
phone: props.phone, ['نام', props.name.trim()],
تاریخ: formatJalaliDay(new Date()), ['name', props.name.trim()],
date: formatJalaliDay(new Date()), ['شماره', props.phone.trim()],
عنوان: props.recordTitle || props.name, ['phone', props.phone.trim()],
title: props.recordTitle || props.name, ['تاریخ', formatJalaliDay(new Date())],
شرکت: props.company, ['date', formatJalaliDay(new Date())],
company: props.company, ['عنوان', props.recordTitle.trim()],
}; ['title', props.recordTitle.trim()],
return source.replace(/\{([^}]+)\}/g, (full, key: string) => { ['شرکت', props.company.trim()],
const next = map[key.trim()]; ['company', props.company.trim()],
return next === undefined ? full : next; ['از طرف', from],
['ازطرف', from],
['from', from],
['مانده ریالی', rial],
['ماندهریالی', rial],
['rialBalance', rial],
['مانده فلزی', metal],
['ماندهفلزی', metal],
['metalBalance', metal],
];
const map: Record<string, string> = {};
const hints: Record<string, string> = {};
for (const [key, value] of entries) {
const norm = normalizeTemplateKey(key);
map[norm] = value;
if (EMPTY_FIELD_HINT[key]) hints[norm] = EMPTY_FIELD_HINT[key]!;
}
return source.replace(/\{([^}]+)\}/g, (full, rawKey: string) => {
const key = normalizeTemplateKey(rawKey);
if (!(key in map)) return full;
const next = map[key] ?? '';
if (next) return next;
return hints[key] ?? full;
}); });
} }
function insertField(token: string) { function insertInto(
const el = bodyEl.value; target: 'compose' | 'draft',
const current = text.value; token: string,
) {
const el = target === 'compose' ? bodyEl.value : templateBodyEl.value;
const current = target === 'compose' ? text.value : templateBody.value;
const setValue = (next: string) => {
if (target === 'compose') text.value = next;
else templateBody.value = next;
};
if (!el) { if (!el) {
text.value = `${current}${token}`; setValue(`${current}${token}`);
} else { return;
const start = el.selectionStart ?? current.length;
const end = el.selectionEnd ?? start;
text.value = `${current.slice(0, start)}${token}${current.slice(end)}`;
const caret = start + token.length;
requestAnimationFrame(() => {
el.focus();
el.setSelectionRange(caret, caret);
});
} }
const start = el.selectionStart ?? current.length;
const end = el.selectionEnd ?? start;
setValue(`${current.slice(0, start)}${token}${current.slice(end)}`);
const caret = start + token.length;
void nextTick(() => {
el.focus();
el.setSelectionRange(caret, caret);
});
} }
function toggleFields() { function openPanel(next: Panel) {
fieldsOpen.value = !fieldsOpen.value; panel.value = panel.value === next ? 'none' : next;
} notice.value = '';
if (panel.value === 'templates') {
function toggleTemplates() { error.value = '';
templatesOpen.value = !templatesOpen.value; void loadTemplates();
if (templatesOpen.value) void loadTemplates(); }
} }
function applyTemplate(item: SmsTemplateDto) { function applyTemplate(item: SmsTemplateDto) {
text.value = item.body; text.value = item.body;
templatesOpen.value = false;
error.value = ''; error.value = '';
notice.value = `قالب «${item.name}» در متن پیام قرار گرفت.`;
} }
async function saveTemplate() { async function saveTemplate() {
const name = templateName.value.trim().slice(0, SMS_TEMPLATE_NAME_MAX); const name = templateName.value.trim().slice(0, SMS_TEMPLATE_NAME_MAX);
const body = text.value.trim(); const body = templateBody.value.trim().slice(0, SMS_TEMPLATE_BODY_MAX);
if (!canSaveTemplate.value || !name || body.length < 2) return; if (!canSaveTemplate.value || !name || body.length < 2) return;
savingTemplate.value = true; savingTemplate.value = true;
error.value = ''; error.value = '';
notice.value = '';
try { try {
const { data } = await api.post<SmsTemplateDto[]>('/sms-templates', { name, body }); const { data } = await api.post<SmsTemplateDto[]>('/sms-templates', { name, body });
templates.value = Array.isArray(data) ? data : []; templates.value = Array.isArray(data) ? data : [];
templateName.value = ''; templateName.value = '';
templateBody.value = '';
notice.value = `پیامک آماده «${name}» ذخیره شد.`;
} catch (e) { } catch (e) {
error.value = apiMessage(e, 'ذخیره پیامک آماده ناموفق بود.'); error.value = apiMessage(e, 'ذخیره پیامک آماده ناموفق بود.');
} finally { } finally {
@@ -184,9 +320,11 @@ async function saveTemplate() {
async function removeTemplate(item: SmsTemplateDto) { async function removeTemplate(item: SmsTemplateDto) {
if (!confirm(`پیامک آماده «${item.name}» حذف شود؟`)) return; if (!confirm(`پیامک آماده «${item.name}» حذف شود؟`)) return;
error.value = ''; error.value = '';
notice.value = '';
try { try {
const { data } = await api.delete<SmsTemplateDto[]>(`/sms-templates/${item.id}`); const { data } = await api.delete<SmsTemplateDto[]>(`/sms-templates/${item.id}`);
templates.value = Array.isArray(data) ? data : []; templates.value = Array.isArray(data) ? data : [];
notice.value = `«${item.name}» حذف شد.`;
} catch (e) { } catch (e) {
error.value = apiMessage(e, 'حذف پیامک آماده ناموفق بود.'); error.value = apiMessage(e, 'حذف پیامک آماده ناموفق بود.');
} }
@@ -204,6 +342,7 @@ async function send(force = false) {
if (!props.endpoint || busy.value || done.value) return; if (!props.endpoint || busy.value || done.value) return;
busy.value = true; busy.value = true;
error.value = ''; error.value = '';
notice.value = '';
try { try {
await api.post(props.endpoint, { text: text.value, ...(force ? { force: true } : {}) }); await api.post(props.endpoint, { text: text.value, ...(force ? { force: true } : {}) });
done.value = 'پیامک ارسال شد.'; done.value = 'پیامک ارسال شد.';
@@ -241,82 +380,140 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
<div class="tools"> <div class="tools">
<div class="tool-row"> <div class="tool-row">
<button type="button" class="pill" :class="{ on: fieldsOpen }" @click="toggleFields"> <button
type="button"
class="pill"
:class="{ on: panel === 'fields' }"
@click="openPanel('fields')"
>
فیلدهای پویا فیلدهای پویا
</button> </button>
<button <button
type="button" type="button"
class="pill" class="pill"
:class="{ on: templatesOpen }" :class="{ on: panel === 'templates' }"
@click="toggleTemplates" @click="openPanel('templates')"
> >
پیامک‌های آماده ساخت پیامک آماده
</button> </button>
</div> </div>
<div v-if="fieldsOpen" class="fields">
<button <div v-if="panel === 'fields'" class="panel">
v-for="item in MESSAGE_AUTOMATION_FIELDS" <p class="panel-hint">روی فیلد بزنید تا داخل متن پیام درج شود.</p>
:key="item.token" <div class="field-grid">
type="button"
@click="insertField(item.token)"
>
<code>{{ item.token }}</code>
<span>{{ item.label }}</span>
</button>
</div>
<div v-if="templatesOpen" class="templates">
<p v-if="templatesLoading" class="muted">در حال بارگذاری…</p>
<p v-else-if="!templates.length" class="muted empty">
هنوز پیامک آماده‌ای نیست. متن را بنویسید و ذخیره کنید.
</p>
<ul v-else class="template-list">
<li v-for="item in templates" :key="item.id">
<button type="button" class="pick" @click="applyTemplate(item)">
<strong>{{ item.name }}</strong>
<span>{{ item.body }}</span>
</button>
<button
type="button"
class="del"
:aria-label="`حذف ${item.name}`"
@click="removeTemplate(item)"
>
حذف
</button>
</li>
</ul>
<div class="tpl-fields" role="group" aria-label="فیلدهای پویا برای متن آماده">
<span class="tpl-fields-label">درج فیلد در متن:</span>
<button <button
v-for="item in MESSAGE_AUTOMATION_FIELDS" v-for="item in MESSAGE_AUTOMATION_FIELDS"
:key="`tpl-${item.token}`" :key="item.token"
type="button" type="button"
:title="item.label" @click="insertInto('compose', item.token)"
@click="insertField(item.token)"
> >
<code>{{ item.token }}</code> <code>{{ item.token }}</code>
<span>{{ item.label }}</span>
</button> </button>
</div> </div>
<form class="save-row" @submit.prevent="saveTemplate"> </div>
<div v-if="panel === 'templates'" class="panel">
<div class="draft">
<strong>ساخت پیامک آماده جدید</strong>
<p class="panel-hint">این متن جدا از پیام ارسالی است؛ بعد از ذخیره، عنوانش بالا برای استفاده سریع می‌آید.</p>
<input <input
v-model="templateName" v-model="templateName"
type="text" type="text"
:maxlength="SMS_TEMPLATE_NAME_MAX" :maxlength="SMS_TEMPLATE_NAME_MAX"
placeholder="نام پیامک آماده" placeholder="نام قالب (مثلاً پیگیری جلسه)"
autocomplete="off" autocomplete="off"
/> />
<button type="submit" :disabled="!canSaveTemplate"> <textarea
{{ savingTemplate ? '…' : 'ذخیره متن فعلی' }} ref="templateBodyEl"
v-model="templateBody"
rows="3"
:maxlength="SMS_TEMPLATE_BODY_MAX"
placeholder="متن قالب، مثلاً: سلام {نام} عزیز…"
/>
<div class="tpl-fields" role="group" aria-label="فیلدهای پویا برای قالب">
<span class="tpl-fields-label">درج فیلد در قالب:</span>
<button
v-for="item in MESSAGE_AUTOMATION_FIELDS"
:key="`tpl-${item.token}`"
type="button"
:title="item.label"
@click="insertInto('draft', item.token)"
>
<code>{{ item.token }}</code>
</button>
</div>
<button
type="button"
class="save-btn"
:disabled="!canSaveTemplate"
@click="saveTemplate"
>
{{ savingTemplate ? 'در حال ذخیره…' : 'ذخیره قالب' }}
</button> </button>
</form> <p v-if="templates.length >= SMS_TEMPLATE_MAX" class="muted">
<p v-if="templates.length >= SMS_TEMPLATE_MAX" class="muted"> سقف {{ toFaDigits(SMS_TEMPLATE_MAX) }} قالب پر شده است.
سقف {{ toFaDigits(SMS_TEMPLATE_MAX) }} قالب پر شده است. </p>
</p> </div>
<div v-if="templates.length" class="manage-list">
<p class="panel-hint">حذف قالب‌های ذخیره‌شده:</p>
<ul class="template-list">
<li v-for="item in templates" :key="`del-${item.id}`">
<span class="pick-name">{{ item.name }}</span>
<button
type="button"
class="del"
:aria-label="`حذف ${item.name}`"
@click="removeTemplate(item)"
>
حذف
</button>
</li>
</ul>
</div>
</div> </div>
</div> </div>
<textarea ref="bodyEl" v-model="text" rows="4" maxlength="500" placeholder="سلام {نام} عزیز" /> <div class="compose-layout">
<p class="count">{{ toFaDigits(count) }} نویسه · {{ toFaDigits(parts) }} پیامک</p> <div class="compose-main">
<label class="compose-label" for="sms-compose-body">متن پیام ارسالی</label>
<textarea
id="sms-compose-body"
ref="bodyEl"
v-model="text"
rows="5"
maxlength="500"
placeholder="متن پیام را بنویسید یا از ستون قالب‌ها انتخاب کنید"
/>
<p class="count">{{ toFaDigits(count) }} نویسه · {{ toFaDigits(parts) }} پیامک</p>
</div>
<aside class="quick-col" aria-label="انتخاب سریع پیامک آماده">
<strong class="quick-col-title">قالب‌ها</strong>
<div v-if="templatesLoading" class="muted tiny">در حال بارگذاری…</div>
<div
v-else-if="templates.length"
class="quick-templates"
role="list"
>
<button
v-for="item in templates"
:key="item.id"
type="button"
class="tpl-chip"
role="listitem"
:title="item.body"
@click="applyTemplate(item)"
>
{{ item.name }}
</button>
</div>
<p v-else class="muted tiny quick-empty">
هنوز قالبی نیست. از «ساخت پیامک آماده» بسازید.
</p>
</aside>
</div>
<div class="preview"> <div class="preview">
<span>پیش‌نمایش</span> <span>پیش‌نمایش</span>
@@ -344,6 +541,7 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
</div> </div>
<p v-if="error" class="err">{{ error }}</p> <p v-if="error" class="err">{{ error }}</p>
<p v-else-if="notice" class="ok">{{ notice }}</p>
<p v-if="done" class="ok">{{ done }}</p> <p v-if="done" class="ok">{{ done }}</p>
<template #footer> <template #footer>
@@ -383,8 +581,7 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
} }
.tools { .tools {
position: relative; margin-bottom: 0.55rem;
margin-bottom: 0.45rem;
} }
.tool-row { .tool-row {
@@ -393,17 +590,13 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
gap: 0.35rem; gap: 0.35rem;
} }
.pill, .pill {
.fields button {
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff); border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
background: var(--accent-subtle); background: var(--accent-subtle);
color: var(--accent-deep); color: var(--accent-deep);
border-radius: 999px; border-radius: 999px;
font: inherit; font: inherit;
cursor: pointer; cursor: pointer;
}
.pill {
padding: 0.28rem 0.7rem; padding: 0.28rem 0.7rem;
font-size: 0.8rem; font-size: 0.8rem;
} }
@@ -414,34 +607,43 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
border-color: var(--accent-deep); border-color: var(--accent-deep);
} }
.fields, .panel {
.templates { margin-top: 0.45rem;
position: absolute;
z-index: 2;
top: calc(100% + 0.3rem);
inset-inline: 0;
display: grid; display: grid;
gap: 0.25rem; gap: 0.45rem;
max-width: 100%; padding: 0.55rem;
padding: 0.4rem;
background: #fff; background: #fff;
border: 1px solid #e7eef2; border: 1px solid #e7eef2;
border-radius: 12px; border-radius: 12px;
box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
} }
.fields button { .panel-hint {
margin: 0;
color: #64748b;
font-size: 0.75rem;
}
.field-grid {
display: grid;
gap: 0.25rem;
}
.field-grid button {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 0.6rem; gap: 0.6rem;
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
border-radius: 8px; border-radius: 8px;
padding: 0.35rem 0.5rem; padding: 0.35rem 0.5rem;
background: #fff; background: #fff;
text-align: start; text-align: start;
font: inherit;
cursor: pointer;
color: var(--accent-deep);
} }
.fields code { .field-grid code {
color: var(--accent-deep); color: var(--accent-deep);
} }
@@ -451,7 +653,7 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
padding: 0; padding: 0;
display: grid; display: grid;
gap: 0.3rem; gap: 0.3rem;
max-height: 11rem; max-height: 9.5rem;
overflow: auto; overflow: auto;
} }
@@ -461,32 +663,98 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
gap: 0.3rem; gap: 0.3rem;
} }
.template-list .pick { .compose-layout {
flex: 1; display: grid;
grid-template-columns: minmax(0, 1fr) 10.5rem;
gap: 0.75rem;
align-items: stretch;
margin-bottom: 0.15rem;
}
.compose-main {
min-width: 0; min-width: 0;
display: grid; display: grid;
gap: 0.15rem; align-content: start;
border: 0; }
border-radius: 8px;
padding: 0.4rem 0.5rem; .quick-col {
background: #f8fafc; display: flex;
text-align: start; flex-direction: column;
font: inherit; gap: 0.35rem;
cursor: pointer; min-height: 0;
max-height: 11.5rem;
padding: 0.5rem;
border: 1px solid #e7eef2;
border-radius: 12px;
background: #fafbfc;
}
.quick-col-title {
font-size: 0.78rem;
color: #0f172a; color: #0f172a;
} }
.template-list .pick:hover { .quick-templates {
background: #f0fdfa; display: flex;
flex-direction: column;
gap: 0.3rem;
min-height: 0;
overflow: auto;
flex: 1;
padding-inline-end: 0.1rem;
} }
.template-list .pick strong { .tpl-chip {
flex: none;
width: 100%;
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
background: #fff;
color: var(--accent-deep);
border-radius: 8px;
font: inherit;
font-size: 0.76rem;
font-weight: 600;
padding: 0.4rem 0.5rem;
cursor: pointer;
text-align: start;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tpl-chip:hover {
background: var(--accent-subtle);
}
.quick-empty {
margin: 0;
}
.tiny {
font-size: 0.72rem;
}
@media (max-width: 640px) {
.compose-layout {
grid-template-columns: 1fr;
}
.quick-col {
max-height: 8.5rem;
}
}
.manage-list {
padding-top: 0.45rem;
border-top: 1px solid #eef2f7;
}
.template-list .pick-name {
flex: 1;
min-width: 0;
padding: 0.4rem 0.5rem;
font-size: 0.82rem; font-size: 0.82rem;
} color: #0f172a;
.template-list .pick span {
color: #64748b;
font-size: 0.74rem;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
@@ -504,14 +772,40 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
padding: 0.35rem 0.45rem; padding: 0.35rem 0.45rem;
} }
.draft {
display: grid;
gap: 0.35rem;
padding-top: 0.45rem;
border-top: 1px solid #eef2f7;
}
.draft strong {
font-size: 0.86rem;
color: #0f172a;
}
.draft input,
.draft textarea,
#sms-compose-body {
width: 100%;
box-sizing: border-box;
border: 1px solid #e2e8f0;
border-radius: 10px;
padding: 0.55rem 0.7rem;
font: inherit;
color: #0f172a;
}
.draft textarea,
#sms-compose-body {
resize: vertical;
}
.tpl-fields { .tpl-fields {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
align-items: center; align-items: center;
gap: 0.3rem; gap: 0.3rem;
margin-top: 0.15rem;
padding-top: 0.35rem;
border-top: 1px solid #eef2f7;
} }
.tpl-fields-label { .tpl-fields-label {
@@ -535,47 +829,29 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
color: inherit; color: inherit;
} }
.save-row { .save-btn {
display: flex; justify-self: start;
gap: 0.3rem;
margin-top: 0.2rem;
}
.save-row input {
flex: 1;
min-width: 0;
border: 1px solid #e2e8f0;
border-radius: 8px;
padding: 0.4rem 0.55rem;
font: inherit;
}
.save-row button {
flex: none;
border: 0; border: 0;
border-radius: 8px; border-radius: 8px;
background: #0f766e; background: #0f766e;
color: #fff; color: #fff;
font: inherit; font: inherit;
font-size: 0.78rem; font-size: 0.8rem;
padding: 0.4rem 0.65rem; padding: 0.45rem 0.75rem;
cursor: pointer; cursor: pointer;
} }
.save-row button:disabled { .save-btn:disabled {
opacity: 0.45; opacity: 0.45;
cursor: not-allowed; cursor: not-allowed;
} }
textarea { .compose-label {
width: 100%; display: block;
box-sizing: border-box; margin: 0.15rem 0 0.35rem;
border: 1px solid #e2e8f0; color: #475569;
border-radius: 12px; font-size: 0.8rem;
padding: 0.7rem 0.8rem; font-weight: 600;
font: inherit;
resize: vertical;
color: #0f172a;
} }
.count { .count {
@@ -600,6 +876,7 @@ textarea {
margin: 0.3rem 0 0; margin: 0.3rem 0 0;
color: #134e4a; color: #134e4a;
overflow-wrap: anywhere; overflow-wrap: anywhere;
white-space: pre-wrap;
} }
.history { .history {
+1 -1
View File
@@ -1179,7 +1179,7 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
:name="lead.contactName || lead.title" :name="lead.contactName || lead.title"
:phone="lead.mobile || lead.phone || ''" :phone="lead.mobile || lead.phone || ''"
:record-title="lead.title" :record-title="lead.title"
:company="lead.contactName ? lead.title : ''" :company="lead.trade ?? ''"
@close="smsOpen = false" @close="smsOpen = false"
/> />
</template> </template>
+1 -1
View File
@@ -1205,7 +1205,7 @@ watch(() => route.query.tab, readTab, { immediate: true });
:history-endpoint="`/people/${id}/sms-history`" :history-endpoint="`/people/${id}/sms-history`"
:name="fullName" :name="fullName"
:phone="phoneNumber" :phone="phoneNumber"
:record-title="fullName" :record-title="person.position?.trim() || ''"
:company="person.company?.name ?? ''" :company="person.company?.name ?? ''"
@close="smsOpen = false" @close="smsOpen = false"
/> />
+5 -2
View File
@@ -4884,8 +4884,11 @@ export const MESSAGE_AUTOMATION_FIELDS = [
{ token: "{نام}", label: "نام مشتری" }, { token: "{نام}", label: "نام مشتری" },
{ token: "{شماره}", label: "شماره موبایل" }, { token: "{شماره}", label: "شماره موبایل" },
{ token: "{تاریخ}", label: "تاریخ ارسال" }, { token: "{تاریخ}", label: "تاریخ ارسال" },
{ token: "{عنوان}", label: "عنوان رکورد" }, { token: "{عنوان}", label: "عنوان / سمت" },
{ token: "{شرکت}", label: "نام شرکت" }, { token: "{شرکت}", label: "شرکت مشتری" },
{ token: "{از طرف}", label: "نام سازمان فرستنده" },
{ token: "{مانده ریالی}", label: "مانده مالی (ریالی)" },
{ token: "{مانده فلزی}", label: "مانده وزنی فلزات" },
] as const; ] as const;
/** First-part Persian SMS limit (legacy UI estimate). Prefer countSmsParts(). */ /** First-part Persian SMS limit (legacy UI estimate). Prefer countSmsParts(). */