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)}`;
}
/** قالب بس/بد مثل 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(
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, {
name: vars.name,
phone: vars.phone,
title: vars.title,
company: vars.company,
from: vars.from,
rialBalance: vars.rialBalance,
metalBalance: vars.metalBalance,
date: tehranJalaliLong(new Date()),
}).trim();
}
+67 -13
View File
@@ -56,7 +56,8 @@ import { GamificationService } from '../gamification/gamification.service';
import { parseBirthDate } from '../common/excel';
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
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 { buildSearchWhere, ci, splitCsv } from '../common/search';
import {
@@ -763,6 +764,7 @@ export class PeopleService implements OnModuleInit {
lastName: true,
mobile: true,
phone: true,
position: true,
ownerId: true,
birthDate: true,
company: { select: { name: true } },
@@ -836,12 +838,15 @@ export class PeopleService implements OnModuleInit {
);
}
}
const message = renderSmsText(body, {
name: fullName,
phone: mobile,
title: fullName,
company: person.company?.name ?? '',
});
const message = renderSmsText(
body,
await this.personSmsVars(actor.organizationId, person.id, {
name: fullName,
phone: mobile,
title: person.position?.trim() || '',
company: person.company?.name ?? '',
}),
);
if (!message) throw new BadRequestException('متن پیامک خالی است.');
const result = await this.sms.send({
organizationId: actor.organizationId,
@@ -902,12 +907,15 @@ export class PeopleService implements OnModuleInit {
const person = await this.get(actor, personId);
const mobile = person.mobile || person.phone;
if (!mobile) throw new BadRequestException('برای این مشتری شماره موبایل ثبت نشده است.');
const message = renderSmsText(body, {
name: person.fullName,
phone: mobile,
title: person.fullName,
company: person.company?.name ?? '',
});
const message = renderSmsText(
body,
await this.personSmsVars(actor.organizationId, person.id, {
name: person.fullName,
phone: mobile,
title: person.position?.trim() || '',
company: person.company?.name ?? '',
}),
);
if (!message) throw new BadRequestException('متن پیامک خالی است.');
const result = await this.sms.send({
organizationId: actor.organizationId,
@@ -937,6 +945,52 @@ export class PeopleService implements OnModuleInit {
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) {
return this.get(actor, personId).then(() =>
this.outboundSms.historyForPerson(actor.organizationId, personId, limit),
+6 -1
View File
@@ -1572,11 +1572,16 @@ export class LeadsService {
const mobile = lead.mobile || lead.phone;
if (!mobile) throw new BadRequestException('برای این لید شماره موبایل ثبت نشده است.');
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, {
name,
phone: mobile,
title: lead.title,
company: lead.contactName ? lead.title : '',
company: lead.trade?.trim() || '',
from: org?.name?.trim() || '',
});
if (!message) throw new BadRequestException('متن پیامک خالی است.');
const result = await this.sms.send({
@@ -56,7 +56,19 @@ function testTemplate() {
}) === 'سلام علی 0912',
'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();
@@ -77,6 +77,17 @@ export function buildSendAts(
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(
text: string,
vars: {
@@ -85,22 +96,44 @@ export function applyMessageTemplate(
phone?: string;
date?: string;
company?: string;
/** نام سازمان فرستنده */
from?: string;
/** مانده مالی قالب‌بندی‌شده */
rialBalance?: string;
/** مانده‌های وزنی/فلزی قالب‌بندی‌شده */
metalBalance?: string;
},
): string {
const map: Record<string, string> = {
title: vars.title ?? '',
عنوان: vars.title ?? '',
نام: vars.name ?? '',
name: vars.name ?? '',
شماره: vars.phone ?? '',
phone: vars.phone ?? '',
تاریخ: vars.date ?? '',
date: vars.date ?? '',
شرکت: vars.company ?? '',
company: vars.company ?? '',
};
const from = vars.from ?? '';
const rial = vars.rialBalance ?? '';
const metal = vars.metalBalance ?? '';
const entries: Array<[string, string]> = [
['title', vars.title ?? ''],
['عنوان', vars.title ?? ''],
['نام', vars.name ?? ''],
['name', vars.name ?? ''],
['شماره', vars.phone ?? ''],
['phone', vars.phone ?? ''],
['تاریخ', 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) => {
const next = map[key.trim()];
const next = map[normalizeTemplateKey(key)];
return next === undefined ? full : next;
});
}
@@ -356,6 +356,10 @@ export class MessageAutomationsService {
})
: null;
const lead = await this.lookupLead(job);
const org = await this.prisma.organization.findUnique({
where: { id: job.organizationId },
select: { name: true },
});
const personName = person
? [person.firstName, person.lastName].filter(Boolean).join(' ').trim()
: '';
@@ -366,6 +370,7 @@ export class MessageAutomationsService {
phone,
date: formatJalaliDayFa(new Date()),
company: person?.company?.name ?? '',
from: org?.name?.trim() || '',
};
const title = applyMessageTemplate(job.rule.title, vars).slice(0, 200);
const body = applyMessageTemplate(job.rule.body, vars);
@@ -511,7 +511,7 @@ export class SmsCampaignsService {
const leadIds = batch
.map((r) => r.leadId)
.filter((id): id is string => Boolean(id));
const [people, leads] = await Promise.all([
const [people, leads, org] = await Promise.all([
personIds.length
? this.prisma.person.findMany({
where: { id: { in: personIds } },
@@ -535,9 +535,14 @@ export class SmsCampaignsService {
},
})
: Promise.resolve([]),
this.prisma.organization.findUnique({
where: { id: campaign.organizationId },
select: { name: true },
}),
]);
const personMap = new Map(people.map((p) => [p.id, p]));
const leadMap = new Map(leads.map((l) => [l.id, l]));
const fromOrg = org?.name?.trim() || '';
let sent = 0;
let failed = 0;
@@ -572,6 +577,7 @@ export class SmsCampaignsService {
phone: recipient.mobile,
title,
company,
from: fromOrg,
});
const personalized = await this.tracking.personalizeSmsBody({
+4
View File
@@ -38,6 +38,10 @@ describe('اتوماسیون پیام', () => {
'سلام علی از منتکت - {unknown}',
);
assert.equal(applyMessageTemplate('{ name }', { name: 'x' }), 'x');
assert.equal(
applyMessageTemplate('از طرف {از طرف}', { from: 'هنراندیشه' }),
'از طرف هنراندیشه',
);
});
it('متن پیامک بریده نمی‌شود', () => {
+443 -166
View File
@@ -1,19 +1,23 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { computed, nextTick, ref, watch } from 'vue';
import axios from 'axios';
import type {
OutboundSmsHistoryResponse,
OutboundSmsLogDto,
PersonAssetsDto,
SmsTemplateDto,
} from '@mento/shared';
import {
MESSAGE_AUTOMATION_FIELDS,
SMS_TEMPLATE_BODY_MAX,
SMS_TEMPLATE_MAX,
SMS_TEMPLATE_NAME_MAX,
countSmsParts,
} from '@mento/shared';
import { api } from '@/lib/api';
import { formatJalaliDay, formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
import { formatTahesabBedBes } from '@/lib/tahesab';
import { useAuthStore } from '@/stores/auth';
import { UiButton, UiModal } from '@/components/ui';
const props = withDefaults(
@@ -34,7 +38,7 @@ const props = withDefaults(
recordTitle: '',
company: '',
title: 'ارسال پیامک',
defaultText: 'سلام {نام} عزیز',
defaultText: '',
nest: false,
},
);
@@ -44,27 +48,70 @@ const emit = defineEmits<{
sent: [];
}>();
type Panel = 'none' | 'fields' | 'templates';
const auth = useAuthStore();
const text = ref('');
const busy = ref(false);
const error = ref('');
const done = ref('');
const fieldsOpen = ref(false);
const templatesOpen = ref(false);
const notice = ref('');
const panel = ref<Panel>('none');
const savingTemplate = ref(false);
const templateName = ref('');
const templateBody = ref('');
const bodyEl = ref<HTMLTextAreaElement | null>(null);
const templateBodyEl = ref<HTMLTextAreaElement | null>(null);
const history = ref<OutboundSmsLogDto[]>([]);
const historyLoading = ref(false);
const templates = ref<SmsTemplateDto[]>([]);
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 count = computed(() => text.value.length);
const parts = computed(() => countSmsParts(text.value));
const canSaveTemplate = computed(
() =>
text.value.trim().length >= 2 &&
templateName.value.trim().length >= 1 &&
templateBody.value.trim().length >= 2 &&
templates.value.length < SMS_TEMPLATE_MAX &&
!savingTemplate.value,
);
@@ -76,15 +123,43 @@ watch(
text.value = props.defaultText;
error.value = '';
done.value = '';
fieldsOpen.value = false;
templatesOpen.value = false;
notice.value = '';
panel.value = 'none';
templateName.value = '';
templateBody.value = '';
busy.value = false;
fromOrg.value = auth.user?.organizationName?.trim() || '';
rialBalanceText.value = '';
metalBalanceText.value = '';
void loadHistory();
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() {
history.value = [];
if (!props.historyEndpoint) return;
@@ -106,74 +181,135 @@ async function loadTemplates() {
try {
const { data } = await api.get<SmsTemplateDto[]>('/sms-templates');
templates.value = Array.isArray(data) ? data : [];
} catch {
} catch (e) {
templates.value = [];
error.value = apiMessage(e, 'بارگذاری پیامک‌های آماده ناموفق بود.');
} finally {
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) {
const map: Record<string, string> = {
نام: props.name,
name: props.name,
شماره: props.phone,
phone: props.phone,
تاریخ: formatJalaliDay(new Date()),
date: formatJalaliDay(new Date()),
عنوان: props.recordTitle || props.name,
title: props.recordTitle || props.name,
شرکت: props.company,
company: props.company,
};
return source.replace(/\{([^}]+)\}/g, (full, key: string) => {
const next = map[key.trim()];
return next === undefined ? full : next;
const from = fromOrg.value.trim();
const rial = rialBalanceText.value.trim();
const metal = metalBalanceText.value.trim();
const entries: Array<[string, string]> = [
['نام', props.name.trim()],
['name', props.name.trim()],
['شماره', props.phone.trim()],
['phone', props.phone.trim()],
['تاریخ', formatJalaliDay(new Date())],
['date', formatJalaliDay(new Date())],
['عنوان', props.recordTitle.trim()],
['title', props.recordTitle.trim()],
['شرکت', props.company.trim()],
['company', props.company.trim()],
['از طرف', 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) {
const el = bodyEl.value;
const current = text.value;
function insertInto(
target: 'compose' | 'draft',
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) {
text.value = `${current}${token}`;
} else {
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);
});
setValue(`${current}${token}`);
return;
}
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() {
fieldsOpen.value = !fieldsOpen.value;
}
function toggleTemplates() {
templatesOpen.value = !templatesOpen.value;
if (templatesOpen.value) void loadTemplates();
function openPanel(next: Panel) {
panel.value = panel.value === next ? 'none' : next;
notice.value = '';
if (panel.value === 'templates') {
error.value = '';
void loadTemplates();
}
}
function applyTemplate(item: SmsTemplateDto) {
text.value = item.body;
templatesOpen.value = false;
error.value = '';
notice.value = `قالب «${item.name}» در متن پیام قرار گرفت.`;
}
async function saveTemplate() {
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;
savingTemplate.value = true;
error.value = '';
notice.value = '';
try {
const { data } = await api.post<SmsTemplateDto[]>('/sms-templates', { name, body });
templates.value = Array.isArray(data) ? data : [];
templateName.value = '';
templateBody.value = '';
notice.value = `پیامک آماده «${name}» ذخیره شد.`;
} catch (e) {
error.value = apiMessage(e, 'ذخیره پیامک آماده ناموفق بود.');
} finally {
@@ -184,9 +320,11 @@ async function saveTemplate() {
async function removeTemplate(item: SmsTemplateDto) {
if (!confirm(`پیامک آماده «${item.name}» حذف شود؟`)) return;
error.value = '';
notice.value = '';
try {
const { data } = await api.delete<SmsTemplateDto[]>(`/sms-templates/${item.id}`);
templates.value = Array.isArray(data) ? data : [];
notice.value = `«${item.name}» حذف شد.`;
} catch (e) {
error.value = apiMessage(e, 'حذف پیامک آماده ناموفق بود.');
}
@@ -204,6 +342,7 @@ async function send(force = false) {
if (!props.endpoint || busy.value || done.value) return;
busy.value = true;
error.value = '';
notice.value = '';
try {
await api.post(props.endpoint, { text: text.value, ...(force ? { force: true } : {}) });
done.value = 'پیامک ارسال شد.';
@@ -241,82 +380,140 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
<div class="tools">
<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
type="button"
class="pill"
:class="{ on: templatesOpen }"
@click="toggleTemplates"
:class="{ on: panel === 'templates' }"
@click="openPanel('templates')"
>
پیامک‌های آماده
ساخت پیامک آماده
</button>
</div>
<div v-if="fieldsOpen" class="fields">
<button
v-for="item in MESSAGE_AUTOMATION_FIELDS"
:key="item.token"
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>
<div v-if="panel === 'fields'" class="panel">
<p class="panel-hint">روی فیلد بزنید تا داخل متن پیام درج شود.</p>
<div class="field-grid">
<button
v-for="item in MESSAGE_AUTOMATION_FIELDS"
:key="`tpl-${item.token}`"
:key="item.token"
type="button"
:title="item.label"
@click="insertField(item.token)"
@click="insertInto('compose', item.token)"
>
<code>{{ item.token }}</code>
<span>{{ item.label }}</span>
</button>
</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
v-model="templateName"
type="text"
:maxlength="SMS_TEMPLATE_NAME_MAX"
placeholder="نام پیامک آماده"
placeholder="نام قالب (مثلاً پیگیری جلسه)"
autocomplete="off"
/>
<button type="submit" :disabled="!canSaveTemplate">
{{ savingTemplate ? '…' : 'ذخیره متن فعلی' }}
<textarea
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>
</form>
<p v-if="templates.length >= SMS_TEMPLATE_MAX" class="muted">
سقف {{ toFaDigits(SMS_TEMPLATE_MAX) }} قالب پر شده است.
</p>
<p v-if="templates.length >= SMS_TEMPLATE_MAX" class="muted">
سقف {{ toFaDigits(SMS_TEMPLATE_MAX) }} قالب پر شده است.
</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>
<textarea ref="bodyEl" v-model="text" rows="4" maxlength="500" placeholder="سلام {نام} عزیز" />
<p class="count">{{ toFaDigits(count) }} نویسه · {{ toFaDigits(parts) }} پیامک</p>
<div class="compose-layout">
<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">
<span>پیش‌نمایش</span>
@@ -344,6 +541,7 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
</div>
<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>
<template #footer>
@@ -383,8 +581,7 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
}
.tools {
position: relative;
margin-bottom: 0.45rem;
margin-bottom: 0.55rem;
}
.tool-row {
@@ -393,17 +590,13 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
gap: 0.35rem;
}
.pill,
.fields button {
.pill {
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
background: var(--accent-subtle);
color: var(--accent-deep);
border-radius: 999px;
font: inherit;
cursor: pointer;
}
.pill {
padding: 0.28rem 0.7rem;
font-size: 0.8rem;
}
@@ -414,34 +607,43 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
border-color: var(--accent-deep);
}
.fields,
.templates {
position: absolute;
z-index: 2;
top: calc(100% + 0.3rem);
inset-inline: 0;
.panel {
margin-top: 0.45rem;
display: grid;
gap: 0.25rem;
max-width: 100%;
padding: 0.4rem;
gap: 0.45rem;
padding: 0.55rem;
background: #fff;
border: 1px solid #e7eef2;
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;
align-items: center;
justify-content: space-between;
gap: 0.6rem;
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
border-radius: 8px;
padding: 0.35rem 0.5rem;
background: #fff;
text-align: start;
font: inherit;
cursor: pointer;
color: var(--accent-deep);
}
.fields code {
.field-grid code {
color: var(--accent-deep);
}
@@ -451,7 +653,7 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
padding: 0;
display: grid;
gap: 0.3rem;
max-height: 11rem;
max-height: 9.5rem;
overflow: auto;
}
@@ -461,32 +663,98 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
gap: 0.3rem;
}
.template-list .pick {
flex: 1;
.compose-layout {
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;
display: grid;
gap: 0.15rem;
border: 0;
border-radius: 8px;
padding: 0.4rem 0.5rem;
background: #f8fafc;
text-align: start;
font: inherit;
cursor: pointer;
align-content: start;
}
.quick-col {
display: flex;
flex-direction: column;
gap: 0.35rem;
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;
}
.template-list .pick:hover {
background: #f0fdfa;
.quick-templates {
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;
}
.template-list .pick span {
color: #64748b;
font-size: 0.74rem;
color: #0f172a;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -504,14 +772,40 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
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 {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.3rem;
margin-top: 0.15rem;
padding-top: 0.35rem;
border-top: 1px solid #eef2f7;
}
.tpl-fields-label {
@@ -535,47 +829,29 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
color: inherit;
}
.save-row {
display: flex;
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;
.save-btn {
justify-self: start;
border: 0;
border-radius: 8px;
background: #0f766e;
color: #fff;
font: inherit;
font-size: 0.78rem;
padding: 0.4rem 0.65rem;
font-size: 0.8rem;
padding: 0.45rem 0.75rem;
cursor: pointer;
}
.save-row button:disabled {
.save-btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
textarea {
width: 100%;
box-sizing: border-box;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 0.7rem 0.8rem;
font: inherit;
resize: vertical;
color: #0f172a;
.compose-label {
display: block;
margin: 0.15rem 0 0.35rem;
color: #475569;
font-size: 0.8rem;
font-weight: 600;
}
.count {
@@ -600,6 +876,7 @@ textarea {
margin: 0.3rem 0 0;
color: #134e4a;
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.history {
+1 -1
View File
@@ -1179,7 +1179,7 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
:name="lead.contactName || lead.title"
:phone="lead.mobile || lead.phone || ''"
:record-title="lead.title"
:company="lead.contactName ? lead.title : ''"
:company="lead.trade ?? ''"
@close="smsOpen = false"
/>
</template>
+1 -1
View File
@@ -1205,7 +1205,7 @@ watch(() => route.query.tab, readTab, { immediate: true });
:history-endpoint="`/people/${id}/sms-history`"
:name="fullName"
:phone="phoneNumber"
:record-title="fullName"
:record-title="person.position?.trim() || ''"
:company="person.company?.name ?? ''"
@close="smsOpen = false"
/>