diff --git a/.env.example b/.env.example index 94ecd08..ffddbbc 100644 --- a/.env.example +++ b/.env.example @@ -80,7 +80,14 @@ AI_DAMAGE_PRICE_MIN_SEVERITY=severe # kavenegar | parsian | moalem (legacy SMS takes precedence when nonempty) SMS_PROVIDER = SMS_API_KEY = +# Display name used in SMS text for this deployment (blank/unset = یارا۷۲۴). +# Example for Moalem: SMS_BRAND_NAME="سامانه خسارت اپکس" +# Custom Kavenegar branding uses sms/send; the account must allow plain-text SMS. +SMS_BRAND_NAME="یارا۷۲۴" AUTH_SMS_TEMPLATE = +# Optional OTP pattern; {token} is the code and {brandName} is SMS_BRAND_NAME. +# The deployment name is appended automatically when absent from a pattern. +AUTH_SMS_MESSAGE="کاربر محترم رمز یکبار مصرف شما در {brandName}: {token}" EXP_OTP_TIME = # Development-only fixed OTP. Production rejects true at startup. FAKE_OTP = false diff --git a/README.md b/README.md index 4e0e8f0..9077486 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ - [Fanavaran integration](docs/fanavaran/README.md) - [Inquiry providers — ESG for all tenants and Fanavaran car-body policies](docs/inquiry-provider-routing.md) - [AI damage detection and advisory prices — setup and testing](docs/ai-damage-companion.md) +- [Deployment-specific SMS display names](docs/sms-deployment-branding.md) Insurer setup and staff/branch management: [guide](docs/insurer-staff-management.md). diff --git a/docs/MIC/moalem-sms.md b/docs/MIC/moalem-sms.md index 2f6cd62..a09efe0 100644 --- a/docs/MIC/moalem-sms.md +++ b/docs/MIC/moalem-sms.md @@ -6,6 +6,7 @@ The deployment selects `moalem` as its SMS provider. This is independent of the ```dotenv SMS_PROVIDER=moalem +SMS_BRAND_NAME="سامانه خسارت اپکس" MIC_SMS_TOKEN_URL=https://auth.mic.co.ir/connect/token MIC_SMS_SEND_URL=https://api.mic.co.ir/sms/send MIC_SMS_CLIENT_ID= @@ -18,6 +19,7 @@ FAKE_OTP=false - If the legacy `SMS` setting is nonempty, it overrides `SMS_PROVIDER`. Set it to `moalem` as well, or remove it. `moallem` is accepted as an alias; logs use `moalem`. - Keep the existing `AUTH_SMS_TEMPLATE` and `AUTH_SMS_MESSAGE` settings for OTP text. Existing URL and `USER_BASE_PATH` settings continue controlling message links. +- `SMS_BRAND_NAME` controls the name in every SMS; unset or blank defaults to `یارا۷۲۴`. Custom OTP/database patterns can use `{brandName}`. See [SMS deployment branding](../sms-deployment-branding.md). - Supply credentials privately through the server environment or secret store. The repository example contains no credentials. Restart API instances after changing configuration. - Active Moalem deployments fail startup when required MIC credentials, HTTPS URLs or numeric settings are invalid. MIC settings do not block other SMS providers. - Allow outbound HTTPS to `auth.mic.co.ir` and `api.mic.co.ir`. Redirects are disabled. The existing HTTP proxy configuration is reused. diff --git a/docs/sms-deployment-branding.md b/docs/sms-deployment-branding.md new file mode 100644 index 0000000..73085c1 --- /dev/null +++ b/docs/sms-deployment-branding.md @@ -0,0 +1,47 @@ +# Deployment-specific SMS names + +Set the public display name in the API deployment environment and restart the API: + +```env +SMS_BRAND_NAME="سامانه خسارت اپکس" +``` + +The default for an absent, empty or whitespace-only value is `یارا۷۲۴`. +This name is independent of the Fanavaran tenant and SMS provider settings. +No database migration or frontend deployment is required. + +Every locally rendered SMS carries this name: OTPs, invitations, field-expert +links, signature notices, document requests, case-review updates, Fanavaran +registration confirmations and plain messages loaded from `sms-texts`. +Messages without an embedded name receive the name on a final line. Existing +Persian/English Yara724 name spellings in message patterns are replaced when +rendered; stored patterns are not changed. URLs and inserted token values are +preserved. + +Custom OTP and database message patterns can place the name explicitly: + +```env +AUTH_SMS_MESSAGE="رمز ورود شما در {brandName}: {token}" +``` + +`{brandName}` is resolved from `SMS_BRAND_NAME`. The existing `{token}`, +`{token2}`, `{token3}` and `{token10}` placeholders retain their purposes. +Locally rendered deliveries and skipped test OTPs record the same rendered text +in the SMS audit. Kavenegar hosted lookups record a locally reconstructed text; +their actual body is controlled by the provider's approved template. Previously +stored SMS logs are historical records and are not modified. + +## Provider behavior + +- **Parsian and Moalem:** all templates are rendered locally; no provider-side + template changes are needed. +- **Kavenegar:** with the default name, existing hosted lookup templates continue + to work. With a custom name, application templates and OTPs are rendered locally + and sent through `sms/send.json` using the existing sender. The Kavenegar + account/sender must support plain-text delivery, including the intended + recipients. Hosted templates cannot have their fixed text changed by this + environment variable. Unknown external template identifiers continue to use + hosted lookup; all current application notifications have local templates. + +Changing the display name does not change provider credentials, sender numbers, +template identifiers, user-panel links or the SMS destination numbers. diff --git a/src/core/config/config.schema.ts b/src/core/config/config.schema.ts index db6ee57..3427827 100644 --- a/src/core/config/config.schema.ts +++ b/src/core/config/config.schema.ts @@ -29,6 +29,10 @@ export class EnvironmentVariables { @IsBooleanString({ message: "FAKE_OTP must be boolean" }) FAKE_OTP?: string; + @IsOptional() + @IsString() + SMS_BRAND_NAME?: string; + // --------------------------------------------------------- // @IsNumber( diff --git a/src/sms-orchestration/entities/db-service/sms-send-log.service.spec.ts b/src/sms-orchestration/entities/db-service/sms-send-log.service.spec.ts index 234b1c0..216ef93 100644 --- a/src/sms-orchestration/entities/db-service/sms-send-log.service.spec.ts +++ b/src/sms-orchestration/entities/db-service/sms-send-log.service.spec.ts @@ -47,7 +47,7 @@ describe("SmsSendLogService", () => { isOtp: true, template: "auth-otp", tokens: { token: "54321" }, - messageText: "کاربر محترم رمز یکبار مصرف شما:\nCode: 54321", + messageText: "کاربر محترم رمز یکبار مصرف شما:\nCode: 54321\nیارا۷۲۴", }); expect(doc.providerResponse).toEqual({ return: { status: 200 } }); }); @@ -67,7 +67,7 @@ describe("SmsSendLogService", () => { kind: SmsSendLogKind.SKIPPED, isOtp: true, tokens: { token: "12345" }, - messageText: "کاربر محترم رمز یکبار مصرف شما:\nCode: 12345", + messageText: "کاربر محترم رمز یکبار مصرف شما:\nCode: 12345\nیارا۷۲۴", }), ); }); diff --git a/src/sms-orchestration/entities/db-service/sms-send-log.service.ts b/src/sms-orchestration/entities/db-service/sms-send-log.service.ts index 40d10d5..9ac6a74 100644 --- a/src/sms-orchestration/entities/db-service/sms-send-log.service.ts +++ b/src/sms-orchestration/entities/db-service/sms-send-log.service.ts @@ -204,10 +204,12 @@ export class SmsSendLogService { otp: string; reason?: string; }): Promise { - const authMessage = - process.env.AUTH_SMS_MESSAGE?.trim() ?? - "کاربر محترم رمز یکبار مصرف شما:\nCode: {token}"; - const messageText = authMessage.split("{token}").join(params.otp); + const messageText = this.resolveMessageTextForLookup({ + receptor: params.receptor, + template: process.env.AUTH_SMS_TEMPLATE?.trim() || "", + token: params.otp, + isOtp: true, + }); await this.record({ receptor: params.receptor, diff --git a/src/sms-orchestration/provider/kavenegar-sms.gateway.ts b/src/sms-orchestration/provider/kavenegar-sms.gateway.ts index c4c2569..b48fe24 100644 --- a/src/sms-orchestration/provider/kavenegar-sms.gateway.ts +++ b/src/sms-orchestration/provider/kavenegar-sms.gateway.ts @@ -13,6 +13,11 @@ import { } from "./sms-provider.exception"; import { KAVENEGAR_SMS_SENDER } from "./kavenegar-sender"; import { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types"; +import { hasCustomSmsBrand } from "./sms-branding"; +import { + buildParsianTemplateMessage, + canRenderSmsTemplate, +} from "./parsian-template-messages"; @Injectable() export class KavenegarSmsGateway { @@ -50,7 +55,16 @@ export class KavenegarSmsGateway { async verifyLookUp(data: VerifyLookUpMessage) { try { const { isOtp: _isOtp, ...providerPayload } = data; - const body = await this.sender.verifyLookup(providerPayload); + // Hosted templates cannot interpolate deployment branding without a + // separate provider-side approval. Use local text for custom deployments. + const body = + hasCustomSmsBrand() && canRenderSmsTemplate(data) + ? await this.sender.send({ + sender: KAVENEGAR_SMS_SENDER, + receptor: data.receptor, + message: buildParsianTemplateMessage(data), + }) + : await this.sender.verifyLookup(providerPayload); if (!isKavenegarSuccess(body)) { const normalized = normalizeKavenegarBody(body); diff --git a/src/sms-orchestration/provider/mic-sms.service.spec.ts b/src/sms-orchestration/provider/mic-sms.service.spec.ts index 47191b9..014b797 100644 --- a/src/sms-orchestration/provider/mic-sms.service.spec.ts +++ b/src/sms-orchestration/provider/mic-sms.service.spec.ts @@ -257,7 +257,7 @@ describe("Moalem gateway integration", () => { template: "auth-otp", token: "12345", }); - expect(sendSms).toHaveBeenLastCalledWith("09120000000", "رمز: 12345"); + expect(sendSms).toHaveBeenLastCalledWith("09120000000", "رمز: 12345\nیارا۷۲۴"); await gateway.verifyLookUp({ receptor: "09120000000", template: "yara-claim-link", diff --git a/src/sms-orchestration/provider/parsian-template-messages.ts b/src/sms-orchestration/provider/parsian-template-messages.ts index 7b2a990..a47f031 100644 --- a/src/sms-orchestration/provider/parsian-template-messages.ts +++ b/src/sms-orchestration/provider/parsian-template-messages.ts @@ -1,11 +1,10 @@ import { VerifyLookUpMessage } from "./sms-gateway.types"; - -const TOKEN_KEYS = ["token", "token2", "token3", "token10"] as const; +import { renderSmsText } from "./sms-branding"; /** Kavenegar template name → plain-text body for Parsian (placeholders: {token}, {token2}, …). */ const PARSIAN_TEMPLATE_BODIES: Record = { "yara724-invite-link": - "کاربر محترم، لینک ورود به پرونده یارا724:\nشناسه: {token}\n{token2}", + "کاربر محترم، لینک ورود به پرونده {brandName}:\nشناسه: {token}\n{token2}", "yara-field-expert-link": "کارشناس میدانی بیمه {token} ({token2}) پرونده شما را بررسی می‌کند.\nلینک: {token3}", "yara-blame-agreement": @@ -22,46 +21,34 @@ const PARSIAN_TEMPLATE_BODIES: Record = { "کاربرگرامی پرونده شما به شماره {token} در سامانه فناوران با شناسه {token2} و شماره پرونده {token3} ثبت شده است. جهت پیگیری های آتی از این اطلاعات استفاده کنید.", }; -function applyTokens( - pattern: string, - data: Pick< - VerifyLookUpMessage, - "token" | "token2" | "token3" | "token10" - >, -): string { - let out = pattern; - for (const key of TOKEN_KEYS) { - const value = data[key]; - if (value != null && value !== "") { - out = out.split(`{${key}}`).join(value); - } - - } - return out.replace(/\{token\d*\}/g, "").trim(); +export function canRenderSmsTemplate(data: VerifyLookUpMessage): boolean { + return ( + data.isOtp === true || + Boolean( + process.env.AUTH_SMS_TEMPLATE?.trim() && + data.template === process.env.AUTH_SMS_TEMPLATE.trim(), + ) || + Object.prototype.hasOwnProperty.call(PARSIAN_TEMPLATE_BODIES, data.template) + ); } -export function buildParsianTemplateMessage( - data: VerifyLookUpMessage, -): string { +export function buildParsianTemplateMessage(data: VerifyLookUpMessage): string { const authTemplate = process.env.AUTH_SMS_TEMPLATE?.trim(); - if (authTemplate && data.template === authTemplate) { + if (data.isOtp || (authTemplate && data.template === authTemplate)) { const authMessage = - process.env.AUTH_SMS_MESSAGE?.trim() ?? + process.env.AUTH_SMS_MESSAGE?.trim() || "کاربر محترم رمز یکبار مصرف شما:\nCode: {token}"; - return applyTokens(authMessage, data); + return renderSmsText(authMessage, data); } const body = PARSIAN_TEMPLATE_BODIES[data.template]; if (body) { - return applyTokens(body, data); + return renderSmsText(body, data); } - const parts = [ - `پیام سیستم (${data.template})`, - data.token ? `کد: ${data.token}` : "", - data.token2 ?? "", - data.token3 ?? "", - data.token10 ?? "", - ].filter(Boolean); - return parts.join("\n"); + // Provider identifiers are technical metadata, not useful message text. + return renderSmsText( + "پیام سامانه\n{token}\n{token2}\n{token3}\n{token10}", + data, + ); } diff --git a/src/sms-orchestration/provider/sms-branding.spec.ts b/src/sms-orchestration/provider/sms-branding.spec.ts new file mode 100644 index 0000000..e1c5ed3 --- /dev/null +++ b/src/sms-orchestration/provider/sms-branding.spec.ts @@ -0,0 +1,191 @@ +import { of } from "rxjs"; +import { SmsSendLogService } from "../entities/db-service/sms-send-log.service"; +import { KavenegarSmsGateway } from "./kavenegar-sms.gateway"; +import { MoalemSmsGateway } from "./moalem-sms.gateway"; +import { ParsianSmsGateway } from "./parsian-sms.gateway"; +import { buildParsianTemplateMessage } from "./parsian-template-messages"; +import { getSmsBrandName, renderSmsText } from "./sms-branding"; +import { SmsGatewayService } from "./sms-gateway.service"; +import { SmsProviderException } from "./sms-provider.exception"; + +const brand = "سامانه خسارت اپکس"; +const templates = [ + "auth-otp", + "yara724-invite-link", + "yara-field-expert-link", + "yara-blame-agreement", + "yara-claim-link", + "yara-expert-lock", + "yara-resend-documents", + "yara-signature", + "yara-fanavaran-claim", +]; +const message = (template = "yara724-invite-link") => ({ + template, + receptor: "09120000000", + token: "12345", + token2: "https://user.yara724.com/user/v1/user?token=case", + token3: "کارشناس", + token10: "https://user.yara724.com/user/v1/caseClaim?token=case", +}); + +describe("deployment-specific SMS branding", () => { + const originalEnv = { ...process.env }; + beforeEach(() => { + delete process.env.SMS; + process.env.SMS_BRAND_NAME = brand; + process.env.AUTH_SMS_TEMPLATE = "auth-otp"; + process.env.AUTH_SMS_MESSAGE = "رمز ورود: {token}"; + }); + afterEach(() => { + process.env = { ...originalEnv }; + }); + + it.each([undefined, "", " "])( + "defaults to یارا۷۲۴ when name is %s", + (value) => { + if (value === undefined) delete process.env.SMS_BRAND_NAME; + else process.env.SMS_BRAND_NAME = value; + expect(getSmsBrandName()).toBe("یارا۷۲۴"); + expect(buildParsianTemplateMessage(message())).toContain("یارا۷۲۴"); + }, + ); + + it.each(templates)( + "brands %s without showing its provider identifier", + (template) => { + const text = buildParsianTemplateMessage(message(template)); + expect(text).toContain(brand); + expect(text.match(new RegExp(brand, "g"))).toHaveLength(1); + expect(text).toContain("12345"); + expect(text).not.toContain(template); + expect(text).not.toMatch(/یارا[۷7][۲2][۴4]/); + expect(text).not.toMatch(/\{(?:brandName|token\d*)\}/); + }, + ); + + it.each(["یارا724", "یارا۷۲۴", "یارا ۷۲۴", "Yara724"])( + "updates legacy database/custom OTP pattern name %s", + (legacyName) => { + process.env.AUTH_SMS_MESSAGE = `${legacyName}: رمز {token}`; + expect(buildParsianTemplateMessage(message("auth-otp"))).toBe( + `${brand}: رمز 12345`, + ); + expect(renderSmsText(`پیام پرونده از ${legacyName}`)).toBe( + `پیام پرونده از ${brand}`, + ); + }, + ); + + it("renders the brand placeholder once and leaves token data and URLs intact", () => { + process.env.AUTH_SMS_MESSAGE = "رمز {token} در {brandName}"; + expect(buildParsianTemplateMessage(message("auth-otp"))).toBe( + `رمز 12345 در ${brand}`, + ); + const link = + "https://user.yara724.com/یارا۷۲۴?data={token}&brand={brandName}"; + const text = buildParsianTemplateMessage({ ...message(), token2: link }); + expect(text).toContain(link); + expect(renderSmsText(`پرونده\nhttps://user.yara724.com/یارا۷۲۴`)).toBe( + `پرونده\nhttps://user.yara724.com/یارا۷۲۴\n${brand}`, + ); + }); + + it("uses a branded OTP fallback even without a configured template/pattern", () => { + delete process.env.AUTH_SMS_TEMPLATE; + process.env.AUTH_SMS_MESSAGE = " "; + expect(buildParsianTemplateMessage({ ...message(""), isOtp: true })).toBe( + `کاربر محترم رمز یکبار مصرف شما:\nCode: 12345\n${brand}`, + ); + }); + + it("brands the fallback without exposing unknown provider template IDs", () => { + const text = buildParsianTemplateMessage(message("legacy-template-id")); + expect(text).toContain(brand); + expect(text).not.toContain("legacy-template-id"); + }); + + it.each(["parsian", "moalem"])( + "delivers branded %s templates and plain database messages with matching audit text", + async (provider) => { + process.env.SMS_PROVIDER = provider; + process.env.PARSIAN_SMS_URL = "https://sms.example.test/send?recipient"; + const captured: string[] = []; + const get = jest.fn((url: string) => { + captured.push(new URL(url).searchParams.get("Message")!); + return of({ status: 200, data: { ok: true } }); + }); + const sendSms = jest.fn(async (_recipient: string, text: string) => { + captured.push(text); + return { success: true, data: { isSuccessful: true }, error: null }; + }); + const create = jest.fn().mockResolvedValue({}); + const audit = new SmsSendLogService({ create } as never); + const gateway = new SmsGatewayService( + {} as never, + new ParsianSmsGateway({ get } as never), + audit, + new MoalemSmsGateway({ sendSms } as never), + ); + for (const template of templates) + await gateway.verifyLookUp(message(template)); + await gateway.sendMessage({ + receptor: "09120000000", + message: "پرونده یارا724 آماده است.", + }); + expect(captured).toHaveLength(templates.length + 1); + for (let i = 0; i < captured.length; i++) { + expect(captured[i]).toContain(brand); + expect(create.mock.calls[i][0].messageText).toBe(captured[i]); + } + expect(captured[captured.length - 1]).toBe(`پرونده ${brand} آماده است.`); + }, + ); + + it("keeps default Kavenegar hosted-template requests unchanged", async () => { + delete process.env.SMS_BRAND_NAME; + const verifyLookup = jest + .fn() + .mockResolvedValue({ return: { status: 200 } }); + const send = jest.fn(); + const gateway = new KavenegarSmsGateway({ verifyLookup, send } as never); + await gateway.verifyLookUp({ ...message("auth-otp"), isOtp: true }); + expect(verifyLookup).toHaveBeenCalledWith(message("auth-otp")); + expect(send).not.toHaveBeenCalled(); + }); + + it.each(templates)( + "uses branded plain Kavenegar text for %s on custom deployments", + async (template) => { + const verifyLookup = jest.fn(); + const send = jest.fn().mockResolvedValue({ return: { status: 200 } }); + const gateway = new KavenegarSmsGateway({ verifyLookup, send } as never); + await gateway.verifyLookUp(message(template)); + expect(verifyLookup).not.toHaveBeenCalled(); + expect(send).toHaveBeenCalledWith({ + receptor: "09120000000", + sender: "10008663", + message: buildParsianTemplateMessage(message(template)), + }); + }, + ); + + it("continues reporting failed branded Kavenegar delivery as a failure", async () => { + const send = jest + .fn() + .mockResolvedValue({ return: { status: 403, message: "denied" } }); + const gateway = new KavenegarSmsGateway({ send } as never); + await expect(gateway.verifyLookUp(message())).rejects.toBeInstanceOf( + SmsProviderException, + ); + }); + + it("records fake/skipped OTP with the same branding as delivered OTPs", async () => { + const create = jest.fn().mockResolvedValue({}); + const audit = new SmsSendLogService({ create } as never); + await audit.recordSkippedOtp({ receptor: "09120000000", otp: "12345" }); + expect(create.mock.calls[0][0].messageText).toBe( + buildParsianTemplateMessage(message("auth-otp")), + ); + }); +}); diff --git a/src/sms-orchestration/provider/sms-branding.ts b/src/sms-orchestration/provider/sms-branding.ts new file mode 100644 index 0000000..4fe0e9d --- /dev/null +++ b/src/sms-orchestration/provider/sms-branding.ts @@ -0,0 +1,48 @@ +import type { VerifyLookUpMessage } from "./sms-gateway.types"; + +export const DEFAULT_SMS_BRAND_NAME = "یارا۷۲۴"; + +export function getSmsBrandName(): string { + return process.env.SMS_BRAND_NAME?.trim() || DEFAULT_SMS_BRAND_NAME; +} + +export function hasCustomSmsBrand(): boolean { + return getSmsBrandName() !== DEFAULT_SMS_BRAND_NAME; +} + +type MessageTokens = Partial< + Pick +>; + +/** Render patterns only: never replace branding or placeholders inside token values. */ +export function renderSmsText( + pattern: string, + tokens: MessageTokens = {}, +): string { + const brandName = getSmsBrandName(); + // Handle old database/config patterns without rewriting links embedded in them. + let brandedPattern = pattern + .split(/(https?:\/\/[^\s]+)/gi) + .map((part) => + /^https?:\/\//i.test(part) + ? part + : part.replace( + /(^|[\s(«،؛:])(?:یارا[ \u200c]*[۷7][۲2][۴4]|yara[ \u200c]*724)(?=$|[\s)»،؛:.!?])/giu, + "$1{brandName}", + ), + ) + .join(""); + if ( + !brandedPattern.includes("{brandName}") && + !brandedPattern.includes(brandName) + ) { + brandedPattern += "\n{brandName}"; + } + return brandedPattern + .replace( + /\{(brandName|token|token2|token3|token10)\}/g, + (_match, key: "brandName" | keyof MessageTokens) => + key === "brandName" ? brandName : (tokens[key] ?? ""), + ) + .trim(); +} diff --git a/src/sms-orchestration/provider/sms-gateway.service.ts b/src/sms-orchestration/provider/sms-gateway.service.ts index 7534c2e..4cdc954 100644 --- a/src/sms-orchestration/provider/sms-gateway.service.ts +++ b/src/sms-orchestration/provider/sms-gateway.service.ts @@ -5,6 +5,7 @@ import { MoalemSmsGateway } from "./moalem-sms.gateway"; import { ParsianSmsGateway } from "./parsian-sms.gateway"; import { getSmsProvider } from "./sms-provider.config"; import { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types"; +import { renderSmsText } from "./sms-branding"; export type { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types"; @@ -24,6 +25,7 @@ export class SmsGatewayService implements OnModuleInit { } async sendMessage(data: SendMessage) { + data = { ...data, message: renderSmsText(data.message) }; const startedAt = Date.now(); try { const result = await this.activeGateway().sendMessage(data);