Add org-scoped reusable SMS templates in the compose modal.
Users can save, pick, and delete prepared messages shared across the organization. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Organization" ADD COLUMN "smsTemplates" JSONB NOT NULL DEFAULT '[]';
|
||||
@@ -164,6 +164,8 @@ model Organization {
|
||||
enabledModules String[] @default([])
|
||||
/// برچسب/رنگ اولویت فعالیت و روتین (کلیدهای enum ثابت؛ فقط ظاهر)
|
||||
activityPriorities Json @default("{}")
|
||||
/// قالبهای آمادهٔ پیامک دستی ([{ id, name, body }, …])
|
||||
smsTemplates Json @default("[]")
|
||||
/// تاریخ قطع بایگانی اطلاعات قبل (شروع روز انتخابشده)؛ null = بدون فیلتر
|
||||
priorArchiveEnabledAt DateTime?
|
||||
isActive Boolean @default(true)
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { OutboundSmsLogService } from './outbound-sms-log.service';
|
||||
import { SmsTemplatesController } from './sms-templates.controller';
|
||||
import { SmsTemplatesService } from './sms-templates.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [OutboundSmsLogService],
|
||||
exports: [OutboundSmsLogService],
|
||||
controllers: [SmsTemplatesController],
|
||||
providers: [OutboundSmsLogService, SmsTemplatesService],
|
||||
exports: [OutboundSmsLogService, SmsTemplatesService],
|
||||
})
|
||||
export class OutboundSmsModule {}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import type { Actor } from '../common/record-scope';
|
||||
import {
|
||||
CreateSmsTemplateDto,
|
||||
UpdateSmsTemplateDto,
|
||||
} from './sms-templates.dto';
|
||||
import { SmsTemplatesService } from './sms-templates.service';
|
||||
|
||||
@Controller('sms-templates')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
export class SmsTemplatesController {
|
||||
constructor(private readonly templates: SmsTemplatesService) {}
|
||||
|
||||
@Get()
|
||||
list(@CurrentUser() user: Actor) {
|
||||
return this.templates.list(user.organizationId);
|
||||
}
|
||||
|
||||
@Post()
|
||||
create(@CurrentUser() user: Actor, @Body() dto: CreateSmsTemplateDto) {
|
||||
return this.templates.create(user.organizationId, dto);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(
|
||||
@CurrentUser() user: Actor,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateSmsTemplateDto,
|
||||
) {
|
||||
return this.templates.update(user.organizationId, id, dto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
remove(@CurrentUser() user: Actor, @Param('id') id: string) {
|
||||
return this.templates.remove(user.organizationId, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
|
||||
import { SMS_TEMPLATE_BODY_MAX, SMS_TEMPLATE_NAME_MAX } from '@mento/shared';
|
||||
|
||||
export class CreateSmsTemplateDto {
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
@MaxLength(SMS_TEMPLATE_NAME_MAX)
|
||||
name!: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
@MaxLength(SMS_TEMPLATE_BODY_MAX)
|
||||
body!: string;
|
||||
}
|
||||
|
||||
export class UpdateSmsTemplateDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
@MaxLength(SMS_TEMPLATE_NAME_MAX)
|
||||
name?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
@MaxLength(SMS_TEMPLATE_BODY_MAX)
|
||||
body?: string;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import type { Prisma } from '@prisma/client';
|
||||
import {
|
||||
parseSmsTemplates,
|
||||
SMS_TEMPLATE_MAX,
|
||||
type SmsTemplateDto,
|
||||
} from '@mento/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type {
|
||||
CreateSmsTemplateDto,
|
||||
UpdateSmsTemplateDto,
|
||||
} from './sms-templates.dto';
|
||||
|
||||
@Injectable()
|
||||
export class SmsTemplatesService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async list(organizationId: string): Promise<SmsTemplateDto[]> {
|
||||
const row = await this.prisma.organization.findUnique({
|
||||
where: { id: organizationId },
|
||||
select: { smsTemplates: true },
|
||||
});
|
||||
return parseSmsTemplates(row?.smsTemplates);
|
||||
}
|
||||
|
||||
async create(
|
||||
organizationId: string,
|
||||
dto: CreateSmsTemplateDto,
|
||||
): Promise<SmsTemplateDto[]> {
|
||||
const current = await this.list(organizationId);
|
||||
if (current.length >= SMS_TEMPLATE_MAX) {
|
||||
throw new BadRequestException(
|
||||
`حداکثر ${SMS_TEMPLATE_MAX} پیامک آماده میتوانید داشته باشید.`,
|
||||
);
|
||||
}
|
||||
const next: SmsTemplateDto[] = [
|
||||
...current,
|
||||
{
|
||||
id: randomUUID(),
|
||||
name: dto.name.trim(),
|
||||
body: dto.body.trim(),
|
||||
},
|
||||
];
|
||||
return this.persist(organizationId, next);
|
||||
}
|
||||
|
||||
async update(
|
||||
organizationId: string,
|
||||
id: string,
|
||||
dto: UpdateSmsTemplateDto,
|
||||
): Promise<SmsTemplateDto[]> {
|
||||
const current = await this.list(organizationId);
|
||||
const idx = current.findIndex((item) => item.id === id);
|
||||
if (idx < 0) throw new NotFoundException('پیامک آماده پیدا نشد.');
|
||||
const prev = current[idx]!;
|
||||
const next = [...current];
|
||||
next[idx] = {
|
||||
id: prev.id,
|
||||
name: dto.name !== undefined ? dto.name.trim() : prev.name,
|
||||
body: dto.body !== undefined ? dto.body.trim() : prev.body,
|
||||
};
|
||||
return this.persist(organizationId, next);
|
||||
}
|
||||
|
||||
async remove(organizationId: string, id: string): Promise<SmsTemplateDto[]> {
|
||||
const current = await this.list(organizationId);
|
||||
if (!current.some((item) => item.id === id)) {
|
||||
throw new NotFoundException('پیامک آماده پیدا نشد.');
|
||||
}
|
||||
return this.persist(
|
||||
organizationId,
|
||||
current.filter((item) => item.id !== id),
|
||||
);
|
||||
}
|
||||
|
||||
private async persist(
|
||||
organizationId: string,
|
||||
items: SmsTemplateDto[],
|
||||
): Promise<SmsTemplateDto[]> {
|
||||
const stored = parseSmsTemplates(items);
|
||||
await this.prisma.organization.update({
|
||||
where: { id: organizationId },
|
||||
data: { smsTemplates: stored as unknown as Prisma.InputJsonValue },
|
||||
});
|
||||
return stored;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,17 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import axios from 'axios';
|
||||
import type { OutboundSmsHistoryResponse, OutboundSmsLogDto } from '@mento/shared';
|
||||
import { MESSAGE_AUTOMATION_FIELDS, countSmsParts } from '@mento/shared';
|
||||
import type {
|
||||
OutboundSmsHistoryResponse,
|
||||
OutboundSmsLogDto,
|
||||
SmsTemplateDto,
|
||||
} from '@mento/shared';
|
||||
import {
|
||||
MESSAGE_AUTOMATION_FIELDS,
|
||||
SMS_TEMPLATE_MAX,
|
||||
SMS_TEMPLATE_NAME_MAX,
|
||||
countSmsParts,
|
||||
} from '@mento/shared';
|
||||
import { api } from '@/lib/api';
|
||||
import { formatJalaliDay, formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
|
||||
import { UiButton, UiModal } from '@/components/ui';
|
||||
@@ -40,13 +49,25 @@ const busy = ref(false);
|
||||
const error = ref('');
|
||||
const done = ref('');
|
||||
const fieldsOpen = ref(false);
|
||||
const templatesOpen = ref(false);
|
||||
const savingTemplate = ref(false);
|
||||
const templateName = ref('');
|
||||
const bodyEl = ref<HTMLTextAreaElement | null>(null);
|
||||
const history = ref<OutboundSmsLogDto[]>([]);
|
||||
const historyLoading = ref(false);
|
||||
const templates = ref<SmsTemplateDto[]>([]);
|
||||
const templatesLoading = ref(false);
|
||||
|
||||
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 &&
|
||||
templates.value.length < SMS_TEMPLATE_MAX &&
|
||||
!savingTemplate.value,
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
@@ -56,8 +77,11 @@ watch(
|
||||
error.value = '';
|
||||
done.value = '';
|
||||
fieldsOpen.value = false;
|
||||
templatesOpen.value = false;
|
||||
templateName.value = '';
|
||||
busy.value = false;
|
||||
void loadHistory();
|
||||
void loadTemplates();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -77,6 +101,18 @@ async function loadHistory() {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTemplates() {
|
||||
templatesLoading.value = true;
|
||||
try {
|
||||
const { data } = await api.get<SmsTemplateDto[]>('/sms-templates');
|
||||
templates.value = Array.isArray(data) ? data : [];
|
||||
} catch {
|
||||
templates.value = [];
|
||||
} finally {
|
||||
templatesLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function fill(source: string) {
|
||||
const map: Record<string, string> = {
|
||||
نام: props.name,
|
||||
@@ -114,6 +150,53 @@ function insertField(token: string) {
|
||||
fieldsOpen.value = false;
|
||||
}
|
||||
|
||||
function toggleFields() {
|
||||
fieldsOpen.value = !fieldsOpen.value;
|
||||
if (fieldsOpen.value) templatesOpen.value = false;
|
||||
}
|
||||
|
||||
function toggleTemplates() {
|
||||
templatesOpen.value = !templatesOpen.value;
|
||||
if (templatesOpen.value) {
|
||||
fieldsOpen.value = false;
|
||||
void loadTemplates();
|
||||
}
|
||||
}
|
||||
|
||||
function applyTemplate(item: SmsTemplateDto) {
|
||||
text.value = item.body;
|
||||
templatesOpen.value = false;
|
||||
error.value = '';
|
||||
}
|
||||
|
||||
async function saveTemplate() {
|
||||
const name = templateName.value.trim().slice(0, SMS_TEMPLATE_NAME_MAX);
|
||||
const body = text.value.trim();
|
||||
if (!canSaveTemplate.value || !name || body.length < 2) return;
|
||||
savingTemplate.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const { data } = await api.post<SmsTemplateDto[]>('/sms-templates', { name, body });
|
||||
templates.value = Array.isArray(data) ? data : [];
|
||||
templateName.value = '';
|
||||
} catch (e) {
|
||||
error.value = apiMessage(e, 'ذخیره پیامک آماده ناموفق بود.');
|
||||
} finally {
|
||||
savingTemplate.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeTemplate(item: SmsTemplateDto) {
|
||||
if (!confirm(`پیامک آماده «${item.name}» حذف شود؟`)) return;
|
||||
error.value = '';
|
||||
try {
|
||||
const { data } = await api.delete<SmsTemplateDto[]>(`/sms-templates/${item.id}`);
|
||||
templates.value = Array.isArray(data) ? data : [];
|
||||
} catch (e) {
|
||||
error.value = apiMessage(e, 'حذف پیامک آماده ناموفق بود.');
|
||||
}
|
||||
}
|
||||
|
||||
function apiMessage(e: unknown, fallback: string) {
|
||||
if (!axios.isAxiosError(e)) return fallback;
|
||||
const msg = (e.response?.data as { message?: string | string[] })?.message;
|
||||
@@ -162,7 +245,19 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
|
||||
</p>
|
||||
|
||||
<div class="tools">
|
||||
<button type="button" class="pill" @click="fieldsOpen = !fieldsOpen">فیلدهای پویا</button>
|
||||
<div class="tool-row">
|
||||
<button type="button" class="pill" :class="{ on: fieldsOpen }" @click="toggleFields">
|
||||
فیلدهای پویا
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="pill"
|
||||
:class="{ on: templatesOpen }"
|
||||
@click="toggleTemplates"
|
||||
>
|
||||
پیامکهای آماده
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="fieldsOpen" class="fields">
|
||||
<button
|
||||
v-for="item in MESSAGE_AUTOMATION_FIELDS"
|
||||
@@ -174,6 +269,43 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
|
||||
<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>
|
||||
<form class="save-row" @submit.prevent="saveTemplate">
|
||||
<input
|
||||
v-model="templateName"
|
||||
type="text"
|
||||
:maxlength="SMS_TEMPLATE_NAME_MAX"
|
||||
placeholder="نام پیامک آماده"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<button type="submit" :disabled="!canSaveTemplate">
|
||||
{{ savingTemplate ? '…' : 'ذخیره متن فعلی' }}
|
||||
</button>
|
||||
</form>
|
||||
<p v-if="templates.length >= SMS_TEMPLATE_MAX" class="muted">
|
||||
سقف {{ toFaDigits(SMS_TEMPLATE_MAX) }} قالب پر شده است.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<textarea ref="bodyEl" v-model="text" rows="4" maxlength="500" placeholder="سلام {نام} عزیز" />
|
||||
@@ -248,6 +380,12 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
|
||||
margin-bottom: 0.45rem;
|
||||
}
|
||||
|
||||
.tool-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.pill,
|
||||
.fields button {
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
|
||||
@@ -263,7 +401,14 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.fields {
|
||||
.pill.on {
|
||||
background: var(--accent-deep);
|
||||
color: #fff;
|
||||
border-color: var(--accent-deep);
|
||||
}
|
||||
|
||||
.fields,
|
||||
.templates {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
top: calc(100% + 0.3rem);
|
||||
@@ -293,6 +438,97 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
|
||||
color: var(--accent-deep);
|
||||
}
|
||||
|
||||
.template-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 0.3rem;
|
||||
max-height: 11rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.template-list li {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.template-list .pick {
|
||||
flex: 1;
|
||||
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;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.template-list .pick:hover {
|
||||
background: #f0fdfa;
|
||||
}
|
||||
|
||||
.template-list .pick strong {
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.template-list .pick span {
|
||||
color: #64748b;
|
||||
font-size: 0.74rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.template-list .del {
|
||||
flex: none;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: #b91c1c;
|
||||
font: inherit;
|
||||
font-size: 0.75rem;
|
||||
cursor: pointer;
|
||||
padding: 0.35rem 0.45rem;
|
||||
}
|
||||
|
||||
.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;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
background: #0f766e;
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-size: 0.78rem;
|
||||
padding: 0.4rem 0.65rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.save-row button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
textarea {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
|
||||
@@ -5407,6 +5407,39 @@ export interface OutboundSmsHistoryResponse {
|
||||
items: OutboundSmsLogDto[];
|
||||
}
|
||||
|
||||
/* ——— قالبهای آمادهٔ پیامک دستی (سازمانی) ——— */
|
||||
|
||||
export type SmsTemplateDto = {
|
||||
id: string;
|
||||
name: string;
|
||||
body: string;
|
||||
};
|
||||
|
||||
export const SMS_TEMPLATE_MAX = 40;
|
||||
export const SMS_TEMPLATE_NAME_MAX = 80;
|
||||
export const SMS_TEMPLATE_BODY_MAX = 500;
|
||||
|
||||
/** نرمالسازی لیست ذخیرهشده؛ آیتمهای ناقص حذف میشوند */
|
||||
export function parseSmsTemplates(raw: unknown): SmsTemplateDto[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
const out: SmsTemplateDto[] = [];
|
||||
for (const row of raw) {
|
||||
if (!row || typeof row !== "object") continue;
|
||||
const rec = row as Record<string, unknown>;
|
||||
const id = typeof rec.id === "string" ? rec.id.trim() : "";
|
||||
const name = typeof rec.name === "string" ? rec.name.trim() : "";
|
||||
const body = typeof rec.body === "string" ? rec.body.trim() : "";
|
||||
if (!id || !name || body.length < 2) continue;
|
||||
out.push({
|
||||
id,
|
||||
name: name.slice(0, SMS_TEMPLATE_NAME_MAX),
|
||||
body: body.slice(0, SMS_TEMPLATE_BODY_MAX),
|
||||
});
|
||||
if (out.length >= SMS_TEMPLATE_MAX) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ——— پیامک گروهی ——— */
|
||||
|
||||
export type SmsCampaignStatus =
|
||||
|
||||
Reference in New Issue
Block a user