forked from Yara724/api
Merge pull request 'fix(SMS): change the brand name of the sms' (#413) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#413
This commit is contained in:
@@ -80,7 +80,14 @@ AI_DAMAGE_PRICE_MIN_SEVERITY=severe
|
|||||||
# kavenegar | parsian | moalem (legacy SMS takes precedence when nonempty)
|
# kavenegar | parsian | moalem (legacy SMS takes precedence when nonempty)
|
||||||
SMS_PROVIDER =
|
SMS_PROVIDER =
|
||||||
SMS_API_KEY =
|
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 =
|
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 =
|
EXP_OTP_TIME =
|
||||||
# Development-only fixed OTP. Production rejects true at startup.
|
# Development-only fixed OTP. Production rejects true at startup.
|
||||||
FAKE_OTP = false
|
FAKE_OTP = false
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
- [Fanavaran integration](docs/fanavaran/README.md)
|
- [Fanavaran integration](docs/fanavaran/README.md)
|
||||||
- [Inquiry providers — ESG for all tenants and Fanavaran car-body policies](docs/inquiry-provider-routing.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)
|
- [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).
|
Insurer setup and staff/branch management: [guide](docs/insurer-staff-management.md).
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ The deployment selects `moalem` as its SMS provider. This is independent of the
|
|||||||
|
|
||||||
```dotenv
|
```dotenv
|
||||||
SMS_PROVIDER=moalem
|
SMS_PROVIDER=moalem
|
||||||
|
SMS_BRAND_NAME="سامانه خسارت اپکس"
|
||||||
MIC_SMS_TOKEN_URL=https://auth.mic.co.ir/connect/token
|
MIC_SMS_TOKEN_URL=https://auth.mic.co.ir/connect/token
|
||||||
MIC_SMS_SEND_URL=https://api.mic.co.ir/sms/send
|
MIC_SMS_SEND_URL=https://api.mic.co.ir/sms/send
|
||||||
MIC_SMS_CLIENT_ID=<provided privately by MIC>
|
MIC_SMS_CLIENT_ID=<provided privately by MIC>
|
||||||
@@ -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`.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- Allow outbound HTTPS to `auth.mic.co.ir` and `api.mic.co.ir`. Redirects are disabled. The existing HTTP proxy configuration is reused.
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -29,6 +29,10 @@ export class EnvironmentVariables {
|
|||||||
@IsBooleanString({ message: "FAKE_OTP must be boolean" })
|
@IsBooleanString({ message: "FAKE_OTP must be boolean" })
|
||||||
FAKE_OTP?: string;
|
FAKE_OTP?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
SMS_BRAND_NAME?: string;
|
||||||
|
|
||||||
// --------------------------------------------------------- //
|
// --------------------------------------------------------- //
|
||||||
|
|
||||||
@IsNumber(
|
@IsNumber(
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ describe("SmsSendLogService", () => {
|
|||||||
isOtp: true,
|
isOtp: true,
|
||||||
template: "auth-otp",
|
template: "auth-otp",
|
||||||
tokens: { token: "54321" },
|
tokens: { token: "54321" },
|
||||||
messageText: "کاربر محترم رمز یکبار مصرف شما:\nCode: 54321",
|
messageText: "کاربر محترم رمز یکبار مصرف شما:\nCode: 54321\nیارا۷۲۴",
|
||||||
});
|
});
|
||||||
expect(doc.providerResponse).toEqual({ return: { status: 200 } });
|
expect(doc.providerResponse).toEqual({ return: { status: 200 } });
|
||||||
});
|
});
|
||||||
@@ -67,7 +67,7 @@ describe("SmsSendLogService", () => {
|
|||||||
kind: SmsSendLogKind.SKIPPED,
|
kind: SmsSendLogKind.SKIPPED,
|
||||||
isOtp: true,
|
isOtp: true,
|
||||||
tokens: { token: "12345" },
|
tokens: { token: "12345" },
|
||||||
messageText: "کاربر محترم رمز یکبار مصرف شما:\nCode: 12345",
|
messageText: "کاربر محترم رمز یکبار مصرف شما:\nCode: 12345\nیارا۷۲۴",
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -204,10 +204,12 @@ export class SmsSendLogService {
|
|||||||
otp: string;
|
otp: string;
|
||||||
reason?: string;
|
reason?: string;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
const authMessage =
|
const messageText = this.resolveMessageTextForLookup({
|
||||||
process.env.AUTH_SMS_MESSAGE?.trim() ??
|
receptor: params.receptor,
|
||||||
"کاربر محترم رمز یکبار مصرف شما:\nCode: {token}";
|
template: process.env.AUTH_SMS_TEMPLATE?.trim() || "",
|
||||||
const messageText = authMessage.split("{token}").join(params.otp);
|
token: params.otp,
|
||||||
|
isOtp: true,
|
||||||
|
});
|
||||||
|
|
||||||
await this.record({
|
await this.record({
|
||||||
receptor: params.receptor,
|
receptor: params.receptor,
|
||||||
|
|||||||
@@ -13,6 +13,11 @@ import {
|
|||||||
} from "./sms-provider.exception";
|
} from "./sms-provider.exception";
|
||||||
import { KAVENEGAR_SMS_SENDER } from "./kavenegar-sender";
|
import { KAVENEGAR_SMS_SENDER } from "./kavenegar-sender";
|
||||||
import { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types";
|
import { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types";
|
||||||
|
import { hasCustomSmsBrand } from "./sms-branding";
|
||||||
|
import {
|
||||||
|
buildParsianTemplateMessage,
|
||||||
|
canRenderSmsTemplate,
|
||||||
|
} from "./parsian-template-messages";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class KavenegarSmsGateway {
|
export class KavenegarSmsGateway {
|
||||||
@@ -50,7 +55,16 @@ export class KavenegarSmsGateway {
|
|||||||
async verifyLookUp(data: VerifyLookUpMessage) {
|
async verifyLookUp(data: VerifyLookUpMessage) {
|
||||||
try {
|
try {
|
||||||
const { isOtp: _isOtp, ...providerPayload } = data;
|
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)) {
|
if (!isKavenegarSuccess(body)) {
|
||||||
const normalized = normalizeKavenegarBody(body);
|
const normalized = normalizeKavenegarBody(body);
|
||||||
|
|||||||
@@ -257,7 +257,7 @@ describe("Moalem gateway integration", () => {
|
|||||||
template: "auth-otp",
|
template: "auth-otp",
|
||||||
token: "12345",
|
token: "12345",
|
||||||
});
|
});
|
||||||
expect(sendSms).toHaveBeenLastCalledWith("09120000000", "رمز: 12345");
|
expect(sendSms).toHaveBeenLastCalledWith("09120000000", "رمز: 12345\nیارا۷۲۴");
|
||||||
await gateway.verifyLookUp({
|
await gateway.verifyLookUp({
|
||||||
receptor: "09120000000",
|
receptor: "09120000000",
|
||||||
template: "yara-claim-link",
|
template: "yara-claim-link",
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { VerifyLookUpMessage } from "./sms-gateway.types";
|
import { VerifyLookUpMessage } from "./sms-gateway.types";
|
||||||
|
import { renderSmsText } from "./sms-branding";
|
||||||
const TOKEN_KEYS = ["token", "token2", "token3", "token10"] as const;
|
|
||||||
|
|
||||||
/** Kavenegar template name → plain-text body for Parsian (placeholders: {token}, {token2}, …). */
|
/** Kavenegar template name → plain-text body for Parsian (placeholders: {token}, {token2}, …). */
|
||||||
const PARSIAN_TEMPLATE_BODIES: Record<string, string> = {
|
const PARSIAN_TEMPLATE_BODIES: Record<string, string> = {
|
||||||
"yara724-invite-link":
|
"yara724-invite-link":
|
||||||
"کاربر محترم، لینک ورود به پرونده یارا724:\nشناسه: {token}\n{token2}",
|
"کاربر محترم، لینک ورود به پرونده {brandName}:\nشناسه: {token}\n{token2}",
|
||||||
"yara-field-expert-link":
|
"yara-field-expert-link":
|
||||||
"کارشناس میدانی بیمه {token} ({token2}) پرونده شما را بررسی میکند.\nلینک: {token3}",
|
"کارشناس میدانی بیمه {token} ({token2}) پرونده شما را بررسی میکند.\nلینک: {token3}",
|
||||||
"yara-blame-agreement":
|
"yara-blame-agreement":
|
||||||
@@ -22,46 +21,34 @@ const PARSIAN_TEMPLATE_BODIES: Record<string, string> = {
|
|||||||
"کاربرگرامی پرونده شما به شماره {token} در سامانه فناوران با شناسه {token2} و شماره پرونده {token3} ثبت شده است. جهت پیگیری های آتی از این اطلاعات استفاده کنید.",
|
"کاربرگرامی پرونده شما به شماره {token} در سامانه فناوران با شناسه {token2} و شماره پرونده {token3} ثبت شده است. جهت پیگیری های آتی از این اطلاعات استفاده کنید.",
|
||||||
};
|
};
|
||||||
|
|
||||||
function applyTokens(
|
export function canRenderSmsTemplate(data: VerifyLookUpMessage): boolean {
|
||||||
pattern: string,
|
return (
|
||||||
data: Pick<
|
data.isOtp === true ||
|
||||||
VerifyLookUpMessage,
|
Boolean(
|
||||||
"token" | "token2" | "token3" | "token10"
|
process.env.AUTH_SMS_TEMPLATE?.trim() &&
|
||||||
>,
|
data.template === process.env.AUTH_SMS_TEMPLATE.trim(),
|
||||||
): string {
|
) ||
|
||||||
let out = pattern;
|
Object.prototype.hasOwnProperty.call(PARSIAN_TEMPLATE_BODIES, data.template)
|
||||||
for (const key of TOKEN_KEYS) {
|
);
|
||||||
const value = data[key];
|
|
||||||
if (value != null && value !== "") {
|
|
||||||
out = out.split(`{${key}}`).join(value);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
export function buildParsianTemplateMessage(data: VerifyLookUpMessage): string {
|
||||||
return out.replace(/\{token\d*\}/g, "").trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildParsianTemplateMessage(
|
|
||||||
data: VerifyLookUpMessage,
|
|
||||||
): string {
|
|
||||||
const authTemplate = process.env.AUTH_SMS_TEMPLATE?.trim();
|
const authTemplate = process.env.AUTH_SMS_TEMPLATE?.trim();
|
||||||
if (authTemplate && data.template === authTemplate) {
|
if (data.isOtp || (authTemplate && data.template === authTemplate)) {
|
||||||
const authMessage =
|
const authMessage =
|
||||||
process.env.AUTH_SMS_MESSAGE?.trim() ??
|
process.env.AUTH_SMS_MESSAGE?.trim() ||
|
||||||
"کاربر محترم رمز یکبار مصرف شما:\nCode: {token}";
|
"کاربر محترم رمز یکبار مصرف شما:\nCode: {token}";
|
||||||
return applyTokens(authMessage, data);
|
return renderSmsText(authMessage, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
const body = PARSIAN_TEMPLATE_BODIES[data.template];
|
const body = PARSIAN_TEMPLATE_BODIES[data.template];
|
||||||
if (body) {
|
if (body) {
|
||||||
return applyTokens(body, data);
|
return renderSmsText(body, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
const parts = [
|
// Provider identifiers are technical metadata, not useful message text.
|
||||||
`پیام سیستم (${data.template})`,
|
return renderSmsText(
|
||||||
data.token ? `کد: ${data.token}` : "",
|
"پیام سامانه\n{token}\n{token2}\n{token3}\n{token10}",
|
||||||
data.token2 ?? "",
|
data,
|
||||||
data.token3 ?? "",
|
);
|
||||||
data.token10 ?? "",
|
|
||||||
].filter(Boolean);
|
|
||||||
return parts.join("\n");
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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")),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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<VerifyLookUpMessage, "token" | "token2" | "token3" | "token10">
|
||||||
|
>;
|
||||||
|
|
||||||
|
/** 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();
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import { MoalemSmsGateway } from "./moalem-sms.gateway";
|
|||||||
import { ParsianSmsGateway } from "./parsian-sms.gateway";
|
import { ParsianSmsGateway } from "./parsian-sms.gateway";
|
||||||
import { getSmsProvider } from "./sms-provider.config";
|
import { getSmsProvider } from "./sms-provider.config";
|
||||||
import { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types";
|
import { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types";
|
||||||
|
import { renderSmsText } from "./sms-branding";
|
||||||
|
|
||||||
export type { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types";
|
export type { SendMessage, VerifyLookUpMessage } from "./sms-gateway.types";
|
||||||
|
|
||||||
@@ -24,6 +25,7 @@ export class SmsGatewayService implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async sendMessage(data: SendMessage) {
|
async sendMessage(data: SendMessage) {
|
||||||
|
data = { ...data, message: renderSmsText(data.message) };
|
||||||
const startedAt = Date.now();
|
const startedAt = Date.now();
|
||||||
try {
|
try {
|
||||||
const result = await this.activeGateway().sendMessage(data);
|
const result = await this.activeGateway().sendMessage(data);
|
||||||
|
|||||||
Reference in New Issue
Block a user