feat: add phone frequency controls and modularize codebase
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
CREATE TABLE "PhoneFrequencyHit" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenantId" TEXT NOT NULL,
|
||||
"applicationId" TEXT NOT NULL,
|
||||
"ruleId" TEXT,
|
||||
"ruleCode" TEXT NOT NULL,
|
||||
"ruleName" TEXT NOT NULL,
|
||||
"phoneNumber" TEXT NOT NULL,
|
||||
"thresholdValue" INTEGER NOT NULL,
|
||||
"actualValue" INTEGER NOT NULL,
|
||||
"windowStartedAt" TIMESTAMP(3) NOT NULL,
|
||||
"windowEndsAt" TIMESTAMP(3) NOT NULL,
|
||||
"generation" INTEGER NOT NULL DEFAULT 0,
|
||||
"action" TEXT NOT NULL DEFAULT 'block',
|
||||
"sourceType" TEXT,
|
||||
"releasedAt" TIMESTAMP(3),
|
||||
"releasedById" TEXT,
|
||||
"releaseReason" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "PhoneFrequencyHit_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE TABLE "PhoneFrequencyState" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenantId" TEXT NOT NULL,
|
||||
"applicationId" TEXT NOT NULL,
|
||||
"ruleId" TEXT,
|
||||
"ruleCode" TEXT NOT NULL,
|
||||
"phoneNumber" TEXT NOT NULL,
|
||||
"windowStartedAt" TIMESTAMP(3) NOT NULL,
|
||||
"windowEndsAt" TIMESTAMP(3) NOT NULL,
|
||||
"count" INTEGER NOT NULL DEFAULT 0,
|
||||
"generation" INTEGER NOT NULL DEFAULT 0,
|
||||
"activeHitId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "PhoneFrequencyState_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX "PhoneFrequencyHit_applicationId_ruleCode_phoneNumber_windowStartedAt_generation_key"
|
||||
ON "PhoneFrequencyHit"("applicationId", "ruleCode", "phoneNumber", "windowStartedAt", "generation");
|
||||
|
||||
CREATE INDEX "PhoneFrequencyHit_tenantId_applicationId_createdAt_idx"
|
||||
ON "PhoneFrequencyHit"("tenantId", "applicationId", "createdAt");
|
||||
|
||||
CREATE INDEX "PhoneFrequencyHit_applicationId_phoneNumber_createdAt_idx"
|
||||
ON "PhoneFrequencyHit"("applicationId", "phoneNumber", "createdAt");
|
||||
|
||||
CREATE INDEX "PhoneFrequencyHit_windowEndsAt_releasedAt_idx"
|
||||
ON "PhoneFrequencyHit"("windowEndsAt", "releasedAt");
|
||||
|
||||
CREATE INDEX "PhoneFrequencyHit_ruleId_idx" ON "PhoneFrequencyHit"("ruleId");
|
||||
CREATE INDEX "PhoneFrequencyHit_releasedById_idx" ON "PhoneFrequencyHit"("releasedById");
|
||||
|
||||
CREATE UNIQUE INDEX "PhoneFrequencyState_activeHitId_key" ON "PhoneFrequencyState"("activeHitId");
|
||||
|
||||
CREATE UNIQUE INDEX "PhoneFrequencyState_applicationId_ruleCode_phoneNumber_key"
|
||||
ON "PhoneFrequencyState"("applicationId", "ruleCode", "phoneNumber");
|
||||
|
||||
CREATE INDEX "PhoneFrequencyState_tenantId_applicationId_windowEndsAt_idx"
|
||||
ON "PhoneFrequencyState"("tenantId", "applicationId", "windowEndsAt");
|
||||
|
||||
CREATE INDEX "PhoneFrequencyState_ruleId_idx" ON "PhoneFrequencyState"("ruleId");
|
||||
|
||||
ALTER TABLE "PhoneFrequencyHit"
|
||||
ADD CONSTRAINT "PhoneFrequencyHit_tenantId_fkey"
|
||||
FOREIGN KEY ("tenantId") REFERENCES "Tenant"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "PhoneFrequencyHit"
|
||||
ADD CONSTRAINT "PhoneFrequencyHit_applicationId_fkey"
|
||||
FOREIGN KEY ("applicationId") REFERENCES "SmsApplication"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "PhoneFrequencyHit"
|
||||
ADD CONSTRAINT "PhoneFrequencyHit_ruleId_fkey"
|
||||
FOREIGN KEY ("ruleId") REFERENCES "RiskRule"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "PhoneFrequencyHit"
|
||||
ADD CONSTRAINT "PhoneFrequencyHit_releasedById_fkey"
|
||||
FOREIGN KEY ("releasedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "PhoneFrequencyState"
|
||||
ADD CONSTRAINT "PhoneFrequencyState_tenantId_fkey"
|
||||
FOREIGN KEY ("tenantId") REFERENCES "Tenant"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "PhoneFrequencyState"
|
||||
ADD CONSTRAINT "PhoneFrequencyState_applicationId_fkey"
|
||||
FOREIGN KEY ("applicationId") REFERENCES "SmsApplication"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "PhoneFrequencyState"
|
||||
ADD CONSTRAINT "PhoneFrequencyState_ruleId_fkey"
|
||||
FOREIGN KEY ("ruleId") REFERENCES "RiskRule"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "PhoneFrequencyState"
|
||||
ADD CONSTRAINT "PhoneFrequencyState_activeHitId_fkey"
|
||||
FOREIGN KEY ("activeHitId") REFERENCES "PhoneFrequencyHit"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
INSERT INTO "RiskRule" (
|
||||
"id", "tenantId", "applicationId", "code", "name", "description", "metric",
|
||||
"thresholdValue", "action", "status", "priority", "config", "createdAt", "updatedAt"
|
||||
)
|
||||
SELECT
|
||||
'default-phone-frequency-24h', NULL, NULL, 'PHONE_FREQUENCY_24H',
|
||||
'单号码24小时发送频次', '同一企业应用下,单个号码在北京时间自然日内最多允许10条业务短信。',
|
||||
'phoneFrequencyCount', 10, 'block', 'active', 40,
|
||||
'{"periodSeconds":86400,"timeZone":"Asia/Shanghai","alignment":"fixed"}'::jsonb,
|
||||
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM "RiskRule"
|
||||
WHERE "applicationId" IS NULL
|
||||
AND "code" = 'PHONE_FREQUENCY_24H'
|
||||
AND "status" <> 'deleted'
|
||||
);
|
||||
|
||||
INSERT INTO "RiskRule" (
|
||||
"id", "tenantId", "applicationId", "code", "name", "description", "metric",
|
||||
"thresholdValue", "action", "status", "priority", "config", "createdAt", "updatedAt"
|
||||
)
|
||||
SELECT
|
||||
'default-phone-frequency-5m', NULL, NULL, 'PHONE_FREQUENCY_5M',
|
||||
'单号码5分钟发送频次', '同一企业应用下,单个号码在固定5分钟周期内最多允许5条业务短信。',
|
||||
'phoneFrequencyCount', 5, 'block', 'active', 50,
|
||||
'{"periodSeconds":300,"timeZone":"Asia/Shanghai","alignment":"fixed"}'::jsonb,
|
||||
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM "RiskRule"
|
||||
WHERE "applicationId" IS NULL
|
||||
AND "code" = 'PHONE_FREQUENCY_5M'
|
||||
AND "status" <> 'deleted'
|
||||
);
|
||||
@@ -0,0 +1,34 @@
|
||||
CREATE TABLE "PhoneFrequencyWhitelist" (
|
||||
"id" TEXT NOT NULL,
|
||||
"phoneNumber" TEXT NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'active',
|
||||
"reason" TEXT NOT NULL,
|
||||
"remark" TEXT,
|
||||
"createdById" TEXT NOT NULL,
|
||||
"updatedById" TEXT NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "PhoneFrequencyWhitelist_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX "PhoneFrequencyWhitelist_phoneNumber_key"
|
||||
ON "PhoneFrequencyWhitelist"("phoneNumber");
|
||||
|
||||
CREATE INDEX "PhoneFrequencyWhitelist_status_updatedAt_idx"
|
||||
ON "PhoneFrequencyWhitelist"("status", "updatedAt");
|
||||
|
||||
CREATE INDEX "PhoneFrequencyWhitelist_createdById_idx"
|
||||
ON "PhoneFrequencyWhitelist"("createdById");
|
||||
|
||||
CREATE INDEX "PhoneFrequencyWhitelist_updatedById_idx"
|
||||
ON "PhoneFrequencyWhitelist"("updatedById");
|
||||
|
||||
ALTER TABLE "PhoneFrequencyWhitelist"
|
||||
ADD CONSTRAINT "PhoneFrequencyWhitelist_createdById_fkey"
|
||||
FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE "PhoneFrequencyWhitelist"
|
||||
ADD CONSTRAINT "PhoneFrequencyWhitelist_updatedById_fkey"
|
||||
FOREIGN KEY ("updatedById") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
+98
-10
@@ -32,6 +32,8 @@ model Tenant {
|
||||
riskRules RiskRule[]
|
||||
smsSendTasks SmsSendTask[]
|
||||
riskHitRecords RiskHitRecord[]
|
||||
phoneFrequencyStates PhoneFrequencyState[]
|
||||
phoneFrequencyHits PhoneFrequencyHit[]
|
||||
smsBatchTasks SmsBatchTask[]
|
||||
smsMessageRecords SmsMessageRecord[]
|
||||
smsApiRequests SmsApiRequest[]
|
||||
@@ -88,13 +90,16 @@ model User {
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
tenant Tenant? @relation(fields: [tenantId], references: [id])
|
||||
roles UserRole[]
|
||||
operationLogs OperationLog[]
|
||||
auditRecords AuditRecord[]
|
||||
createdSmsSendTasks SmsSendTask[] @relation("SmsSendTaskCreator")
|
||||
reviewedSmsSendTasks SmsSendTask[] @relation("SmsSendTaskReviewer")
|
||||
createdSmsBatchTasks SmsBatchTask[] @relation("SmsBatchTaskCreator")
|
||||
tenant Tenant? @relation(fields: [tenantId], references: [id])
|
||||
roles UserRole[]
|
||||
operationLogs OperationLog[]
|
||||
auditRecords AuditRecord[]
|
||||
createdSmsSendTasks SmsSendTask[] @relation("SmsSendTaskCreator")
|
||||
reviewedSmsSendTasks SmsSendTask[] @relation("SmsSendTaskReviewer")
|
||||
createdSmsBatchTasks SmsBatchTask[] @relation("SmsBatchTaskCreator")
|
||||
releasedPhoneFrequencyHits PhoneFrequencyHit[] @relation("PhoneFrequencyHitReleaser")
|
||||
createdPhoneFrequencyWhitelistEntries PhoneFrequencyWhitelist[] @relation("PhoneFrequencyWhitelistCreator")
|
||||
updatedPhoneFrequencyWhitelistEntries PhoneFrequencyWhitelist[] @relation("PhoneFrequencyWhitelistUpdater")
|
||||
}
|
||||
|
||||
model Role {
|
||||
@@ -440,6 +445,8 @@ model SmsApplication {
|
||||
dailyUsages SmsApplicationDailyUsage[]
|
||||
inboundLongMessages CmppInboundLongMessage[]
|
||||
riskRules RiskRule[]
|
||||
phoneFrequencyStates PhoneFrequencyState[]
|
||||
phoneFrequencyHits PhoneFrequencyHit[]
|
||||
|
||||
@@index([tenantId, status])
|
||||
@@index([status, createdAt])
|
||||
@@ -1268,9 +1275,11 @@ model RiskRule {
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
tenant Tenant? @relation(fields: [tenantId], references: [id])
|
||||
application SmsApplication? @relation(fields: [applicationId], references: [id], onDelete: Cascade)
|
||||
hits RiskHitRecord[]
|
||||
tenant Tenant? @relation(fields: [tenantId], references: [id])
|
||||
application SmsApplication? @relation(fields: [applicationId], references: [id], onDelete: Cascade)
|
||||
hits RiskHitRecord[]
|
||||
phoneFrequencyStates PhoneFrequencyState[]
|
||||
phoneFrequencyHits PhoneFrequencyHit[]
|
||||
|
||||
@@unique([applicationId, code])
|
||||
@@index([tenantId, applicationId, status, priority])
|
||||
@@ -1339,6 +1348,85 @@ model RiskHitRecord {
|
||||
@@index([ruleCode])
|
||||
}
|
||||
|
||||
model PhoneFrequencyState {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
applicationId String
|
||||
ruleId String?
|
||||
ruleCode String
|
||||
phoneNumber String
|
||||
windowStartedAt DateTime
|
||||
windowEndsAt DateTime
|
||||
count Int @default(0)
|
||||
generation Int @default(0)
|
||||
activeHitId String? @unique
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id])
|
||||
application SmsApplication @relation(fields: [applicationId], references: [id], onDelete: Cascade)
|
||||
rule RiskRule? @relation(fields: [ruleId], references: [id], onDelete: SetNull)
|
||||
activeHit PhoneFrequencyHit? @relation("ActivePhoneFrequencyHit", fields: [activeHitId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@unique([applicationId, ruleCode, phoneNumber])
|
||||
@@index([tenantId, applicationId, windowEndsAt])
|
||||
@@index([ruleId])
|
||||
}
|
||||
|
||||
model PhoneFrequencyHit {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
applicationId String
|
||||
ruleId String?
|
||||
ruleCode String
|
||||
ruleName String
|
||||
phoneNumber String
|
||||
thresholdValue Int
|
||||
actualValue Int
|
||||
windowStartedAt DateTime
|
||||
windowEndsAt DateTime
|
||||
generation Int @default(0)
|
||||
action String @default("block")
|
||||
sourceType String?
|
||||
releasedAt DateTime?
|
||||
releasedById String?
|
||||
releaseReason String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id])
|
||||
application SmsApplication @relation(fields: [applicationId], references: [id])
|
||||
rule RiskRule? @relation(fields: [ruleId], references: [id], onDelete: SetNull)
|
||||
releasedBy User? @relation("PhoneFrequencyHitReleaser", fields: [releasedById], references: [id])
|
||||
activeForState PhoneFrequencyState? @relation("ActivePhoneFrequencyHit")
|
||||
|
||||
@@unique([applicationId, ruleCode, phoneNumber, windowStartedAt, generation])
|
||||
@@index([tenantId, applicationId, createdAt])
|
||||
@@index([applicationId, phoneNumber, createdAt])
|
||||
@@index([windowEndsAt, releasedAt])
|
||||
@@index([ruleId])
|
||||
@@index([releasedById])
|
||||
}
|
||||
|
||||
model PhoneFrequencyWhitelist {
|
||||
id String @id @default(cuid())
|
||||
phoneNumber String @unique
|
||||
status String @default("active")
|
||||
reason String
|
||||
remark String?
|
||||
createdById String
|
||||
updatedById String
|
||||
deletedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
createdBy User @relation("PhoneFrequencyWhitelistCreator", fields: [createdById], references: [id])
|
||||
updatedBy User @relation("PhoneFrequencyWhitelistUpdater", fields: [updatedById], references: [id])
|
||||
|
||||
@@index([status, updatedAt])
|
||||
@@index([createdById])
|
||||
@@index([updatedById])
|
||||
}
|
||||
|
||||
model SmsBatchTask {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { BadRequestException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Queue } from 'bullmq';
|
||||
import IORedis from 'ioredis';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { assertMoneyUnits, moneyToNumber } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { CreateChannelDto, UpdateChannelDto, CreateChannelGroupDto, CreateChannelGroupItemDto, UpdateChannelGroupDto, CreateRouteRuleDto, CreateReportFieldDto, ReplaceReportFieldsDto, CreateReportMaterialDto, CreateReportTaskDto, ChangeReportTaskStatusesDto, CreateReportExportDto, CreateReceiptImportDto, UpsertConnectionStateDto, ChangeChannelStatusDto, CopyChannelDto, TestChannelDto } from './channels.contracts';
|
||||
import { GATEWAY_CONNECTION_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_GATEWAY_CONTROL_URL, DEFAULT_CHANNEL_CONNECTION_ID, DEFAULT_CONNECTING_TIMEOUT_MS, DEFAULT_CONNECTING_TIMEOUT_SCAN_MS, DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS, DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS, DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS, DEFAULT_HEARTBEAT_INTERVAL_SECONDS, DEFAULT_HEARTBEAT_MISS_THRESHOLD, HEARTBEAT_AUDIT_INTERVAL_MS, CONNECTING_TIMEOUT_ERROR, DEFAULT_CMPP_VERSION, normalizeTestPhones, normalizeTestContent, calculateBillingUnits, buildChannelTestSubmitCommand, getConfigValue, getStringConfigValue, normalizeConnectionAction, normalizeCmppVersion, normalizeGatewayConnectionStatus, defaultChannelConnectionId, getDesiredConnections, ChannelConnectionSettings, getRuntimeConfigInteger, channelConnectionSettingsChanged, channelGroupAuditSnapshot, normalizeChannelRuntimeConfig, normalizeCmppServiceId, normalizeChannelRateLimit, normalizeExtensionDigits, getPositiveRuntimeInteger, bullmqConnection, getPositiveIntegerEnv, parseReceiptContent, splitReceiptLine, stripReceiptCell, findReceiptStatusIndex, normalizeReceiptStatus, deriveReceiptStatus, ChannelReportDeliveryRow, summarizeChannelReportDelivery, sumReportDelivery, percentage, latestDate, currentShanghaiDayRange, normalizeRetryTimeLimitMinutes, normalizeSpreadsheetSize, normalizeBusinessCarrier, normalizeChannelCarrier, isChannelCarrierCompatible, normalizeRegion, isRegionCompatible, validateGroupItems, normalizeReportType, summarizeReportStatuses, normalizeLinkEvent } from './channels.helpers';
|
||||
import { ChannelConnectionService } from './channel-connection.service';
|
||||
|
||||
/** R5 channel domain service composed behind ChannelsService. */
|
||||
export class ChannelConfigurationService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly connection: ChannelConnectionService) {}
|
||||
|
||||
listChannels() {
|
||||
return this.prisma.smsChannel.findMany({
|
||||
include: { connectionStates: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
async listChannelsPage(query: { keyword?: string; carrier?: string; status?: string; page?: number; pageSize?: number }) {
|
||||
const page = Math.max(1, Math.floor(Number(query.page) || 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 10)));
|
||||
const where: Prisma.SmsChannelWhereInput = {
|
||||
status: query.status && query.status !== 'all' ? query.status : { not: 'deleted' },
|
||||
carrier: query.carrier && query.carrier !== 'all' ? query.carrier : undefined,
|
||||
name: query.keyword?.trim() ? { contains: query.keyword.trim() } : undefined,
|
||||
};
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.smsChannel.findMany({
|
||||
where,
|
||||
include: { connectionStates: true },
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.smsChannel.count({ where }),
|
||||
]);
|
||||
return { items, total, page, pageSize };
|
||||
}
|
||||
|
||||
async createChannel(data: CreateChannelDto) {
|
||||
assertMoneyUnits(data.unitPrice ?? 0, '通道单价');
|
||||
const missingFields = ['code', 'name', 'gatewayHost', 'account', 'passwordCipher', 'srcId'].filter((field) => {
|
||||
const value = data[field as keyof CreateChannelDto];
|
||||
return value === undefined || value === null || value === '';
|
||||
});
|
||||
if (missingFields.length > 0) {
|
||||
throw new BadRequestException(`Missing required channel fields: ${missingFields.join(', ')}`);
|
||||
}
|
||||
const gatewayPort = Number(data.gatewayPort ?? 7890);
|
||||
if (!Number.isInteger(gatewayPort) || gatewayPort <= 0 || gatewayPort > 65535) {
|
||||
throw new BadRequestException('gatewayPort must be an integer between 1 and 65535');
|
||||
}
|
||||
const cmppVersion = normalizeCmppVersion(data.cmppVersion);
|
||||
const config = normalizeChannelRuntimeConfig(
|
||||
undefined,
|
||||
data.config,
|
||||
data.desiredConnections,
|
||||
data.windowSize,
|
||||
data.heartbeatIntervalSeconds,
|
||||
data.heartbeatMissThreshold,
|
||||
);
|
||||
const rateLimitPerSecond = normalizeChannelRateLimit(data.rateLimitPerSecond);
|
||||
const channel = await this.prisma.smsChannel.create({
|
||||
data: {
|
||||
code: data.code,
|
||||
name: data.name,
|
||||
carrier: data.carrier,
|
||||
sendRegion: data.sendRegion ?? '全国',
|
||||
protocol: 'CMPP',
|
||||
gatewayHost: data.gatewayHost,
|
||||
gatewayPort,
|
||||
enterpriseCode: data.enterpriseCode,
|
||||
account: data.account,
|
||||
passwordCipher: data.passwordCipher,
|
||||
srcId: data.srcId,
|
||||
cmppVersion,
|
||||
rateLimitPerSecond,
|
||||
unitPrice: data.unitPrice ?? 0,
|
||||
status: data.status ?? 'active',
|
||||
config: config as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
if (channel.status === 'active') {
|
||||
await this.connection.requestChannelConnection(channel, 'channel_created');
|
||||
}
|
||||
return channel;
|
||||
}
|
||||
|
||||
async updateChannel(channelId: string, data: UpdateChannelDto) {
|
||||
const channel = await this.prisma.smsChannel.findUnique({ where: { id: channelId } });
|
||||
if (!channel) {
|
||||
throw new NotFoundException('Channel not found');
|
||||
}
|
||||
if (data.unitPrice !== undefined) {
|
||||
assertMoneyUnits(data.unitPrice, '通道单价');
|
||||
}
|
||||
const gatewayPort = data.gatewayPort === undefined ? undefined : Number(data.gatewayPort);
|
||||
if (gatewayPort !== undefined && (!Number.isInteger(gatewayPort) || gatewayPort <= 0 || gatewayPort > 65535)) {
|
||||
throw new BadRequestException('gatewayPort must be an integer between 1 and 65535');
|
||||
}
|
||||
const cmppVersion = data.cmppVersion === undefined ? undefined : normalizeCmppVersion(data.cmppVersion);
|
||||
const config = data.config !== undefined
|
||||
|| data.desiredConnections !== undefined
|
||||
|| data.windowSize !== undefined
|
||||
|| data.heartbeatIntervalSeconds !== undefined
|
||||
|| data.heartbeatMissThreshold !== undefined
|
||||
? normalizeChannelRuntimeConfig(
|
||||
channel.config,
|
||||
data.config,
|
||||
data.desiredConnections,
|
||||
data.windowSize,
|
||||
data.heartbeatIntervalSeconds,
|
||||
data.heartbeatMissThreshold,
|
||||
)
|
||||
: undefined;
|
||||
const rateLimitPerSecond = data.rateLimitPerSecond === undefined
|
||||
? undefined
|
||||
: normalizeChannelRateLimit(data.rateLimitPerSecond);
|
||||
const connectionConfigChanged = channelConnectionSettingsChanged(channel, {
|
||||
gatewayHost: data.gatewayHost ?? channel.gatewayHost,
|
||||
gatewayPort: gatewayPort ?? channel.gatewayPort,
|
||||
account: data.account ?? channel.account,
|
||||
passwordCipher: data.passwordCipher ?? channel.passwordCipher,
|
||||
cmppVersion: cmppVersion ?? channel.cmppVersion,
|
||||
config: config ?? channel.config,
|
||||
});
|
||||
const updated = await this.prisma.smsChannel.update({
|
||||
where: { id: channelId },
|
||||
data: {
|
||||
code: data.code,
|
||||
name: data.name,
|
||||
carrier: data.carrier,
|
||||
sendRegion: data.sendRegion,
|
||||
protocol: 'CMPP',
|
||||
gatewayHost: data.gatewayHost,
|
||||
gatewayPort,
|
||||
enterpriseCode: data.enterpriseCode,
|
||||
account: data.account,
|
||||
passwordCipher: data.passwordCipher,
|
||||
srcId: data.srcId,
|
||||
cmppVersion,
|
||||
rateLimitPerSecond,
|
||||
unitPrice: data.unitPrice,
|
||||
status: data.status,
|
||||
config: config as Prisma.InputJsonValue | undefined,
|
||||
},
|
||||
});
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
action: 'sms_channel.update',
|
||||
resource: 'sms_channel',
|
||||
resourceId: channelId,
|
||||
detail: {
|
||||
before: {
|
||||
code: channel.code,
|
||||
name: channel.name,
|
||||
carrier: channel.carrier,
|
||||
sendRegion: channel.sendRegion,
|
||||
gatewayHost: channel.gatewayHost,
|
||||
gatewayPort: channel.gatewayPort,
|
||||
enterpriseCode: channel.enterpriseCode,
|
||||
account: channel.account,
|
||||
srcId: channel.srcId,
|
||||
unitPrice: moneyToNumber(channel.unitPrice),
|
||||
},
|
||||
after: data,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
const updatedStatus = data.status ?? channel.status;
|
||||
if (updatedStatus === 'active' && (connectionConfigChanged || channel.status !== 'active')) {
|
||||
await this.connection.requestChannelConnection(updated, 'channel_updated');
|
||||
} else if (updatedStatus !== 'active' && channel.status === 'active') {
|
||||
await this.connection.requestChannelDisconnection(updated, 'channel_disabled');
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
async changeChannelStatus(channelId: string, data: ChangeChannelStatusDto) {
|
||||
const channel = await this.prisma.smsChannel.findUnique({ where: { id: channelId } });
|
||||
if (!channel) {
|
||||
throw new NotFoundException('Channel not found');
|
||||
}
|
||||
const updated = await this.prisma.smsChannel.update({ where: { id: channelId }, data: { status: data.status } });
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
userId: data.operatorId,
|
||||
action: `sms_channel.${data.status}`,
|
||||
resource: 'sms_channel',
|
||||
resourceId: channelId,
|
||||
detail: {
|
||||
statusBefore: channel.status,
|
||||
statusAfter: data.status,
|
||||
reason: data.reason,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
if (data.status === 'active') {
|
||||
await this.connection.requestChannelConnection(updated, 'channel_enabled', data.operatorId);
|
||||
} else if (channel.status === 'active' || data.status === 'deleted') {
|
||||
await this.connection.requestChannelDisconnection(
|
||||
updated,
|
||||
data.status === 'deleted' ? 'channel_deleted' : 'channel_disabled',
|
||||
data.operatorId,
|
||||
);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
import { BadRequestException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Queue } from 'bullmq';
|
||||
import IORedis from 'ioredis';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { assertMoneyUnits, moneyToNumber } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { CreateChannelDto, UpdateChannelDto, CreateChannelGroupDto, CreateChannelGroupItemDto, UpdateChannelGroupDto, CreateRouteRuleDto, CreateReportFieldDto, ReplaceReportFieldsDto, CreateReportMaterialDto, CreateReportTaskDto, ChangeReportTaskStatusesDto, CreateReportExportDto, CreateReceiptImportDto, UpsertConnectionStateDto, ChangeChannelStatusDto, CopyChannelDto, TestChannelDto } from './channels.contracts';
|
||||
import { GATEWAY_CONNECTION_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_GATEWAY_CONTROL_URL, DEFAULT_CHANNEL_CONNECTION_ID, DEFAULT_CONNECTING_TIMEOUT_MS, DEFAULT_CONNECTING_TIMEOUT_SCAN_MS, DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS, DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS, DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS, DEFAULT_HEARTBEAT_INTERVAL_SECONDS, DEFAULT_HEARTBEAT_MISS_THRESHOLD, HEARTBEAT_AUDIT_INTERVAL_MS, CONNECTING_TIMEOUT_ERROR, DEFAULT_CMPP_VERSION, normalizeTestPhones, normalizeTestContent, calculateBillingUnits, buildChannelTestSubmitCommand, getConfigValue, getStringConfigValue, normalizeConnectionAction, normalizeCmppVersion, normalizeGatewayConnectionStatus, defaultChannelConnectionId, getDesiredConnections, ChannelConnectionSettings, getRuntimeConfigInteger, channelConnectionSettingsChanged, channelGroupAuditSnapshot, normalizeChannelRuntimeConfig, normalizeCmppServiceId, normalizeChannelRateLimit, normalizeExtensionDigits, getPositiveRuntimeInteger, bullmqConnection, getPositiveIntegerEnv, parseReceiptContent, splitReceiptLine, stripReceiptCell, findReceiptStatusIndex, normalizeReceiptStatus, deriveReceiptStatus, ChannelReportDeliveryRow, summarizeChannelReportDelivery, sumReportDelivery, percentage, latestDate, currentShanghaiDayRange, normalizeRetryTimeLimitMinutes, normalizeSpreadsheetSize, normalizeBusinessCarrier, normalizeChannelCarrier, isChannelCarrierCompatible, normalizeRegion, isRegionCompatible, validateGroupItems, normalizeReportType, summarizeReportStatuses, normalizeLinkEvent } from './channels.helpers';
|
||||
|
||||
|
||||
/** R5 channel domain service composed behind ChannelsService. */
|
||||
export class ChannelConnectionService {
|
||||
private readonly logger = new Logger(ChannelConnectionService.name);
|
||||
private gatewayConnectionQueue?: Queue;
|
||||
private gatewaySubmitQueue?: Queue;
|
||||
private redis?: IORedis;
|
||||
private connectionTimeoutTimer?: ReturnType<typeof setInterval>;
|
||||
private gatewayStartupReconnectTimer?: ReturnType<typeof setTimeout>;
|
||||
private gatewayReconcileTimer?: ReturnType<typeof setInterval>;
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
onModuleInit() {
|
||||
if (process.env.GATEWAY_CONNECTING_TIMEOUT_SCANNER_DISABLED !== 'true') {
|
||||
this.connectionTimeoutTimer = setInterval(() => {
|
||||
void this.markTimedOutConnectingChannels().catch((error) => {
|
||||
this.logger.error(`Failed to mark timed-out CMPP connections: ${error instanceof Error ? error.message : String(error)}`);
|
||||
});
|
||||
}, getPositiveIntegerEnv('GATEWAY_CONNECTING_TIMEOUT_SCAN_MS', DEFAULT_CONNECTING_TIMEOUT_SCAN_MS));
|
||||
this.connectionTimeoutTimer.unref?.();
|
||||
}
|
||||
this.gatewayStartupReconnectTimer = setTimeout(() => {
|
||||
void this.reconnectActiveChannelsAfterGatewayRestart();
|
||||
}, getPositiveIntegerEnv('GATEWAY_STARTUP_RECONNECT_DELAY_MS', DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS));
|
||||
this.gatewayStartupReconnectTimer.unref?.();
|
||||
if (process.env.GATEWAY_CONNECTION_RECONCILER_DISABLED !== 'true') {
|
||||
this.gatewayReconcileTimer = setInterval(() => {
|
||||
void this.reconcileGatewayConnections().catch((error) => {
|
||||
this.logger.error(`Failed to reconcile supplier connections: ${error instanceof Error ? error.message : String(error)}`);
|
||||
});
|
||||
}, getPositiveIntegerEnv('GATEWAY_CONNECTION_RECONCILE_INTERVAL_MS', DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS));
|
||||
this.gatewayReconcileTimer.unref?.();
|
||||
}
|
||||
}
|
||||
|
||||
async onModuleDestroy() {
|
||||
if (this.connectionTimeoutTimer) {
|
||||
clearInterval(this.connectionTimeoutTimer);
|
||||
}
|
||||
if (this.gatewayStartupReconnectTimer) {
|
||||
clearTimeout(this.gatewayStartupReconnectTimer);
|
||||
}
|
||||
if (this.gatewayReconcileTimer) {
|
||||
clearInterval(this.gatewayReconcileTimer);
|
||||
}
|
||||
await this.gatewayConnectionQueue?.close();
|
||||
await this.gatewaySubmitQueue?.close();
|
||||
this.redis?.disconnect();
|
||||
}
|
||||
|
||||
listChannelMetrics(channelId: string) {
|
||||
return this.prisma.channelHealthMetric.findMany({
|
||||
where: { channelId },
|
||||
orderBy: { windowStart: 'desc' },
|
||||
take: 100,
|
||||
});
|
||||
}
|
||||
|
||||
listChannelConnections(channelId: string) {
|
||||
return this.prisma.cmppConnectionState.findMany({
|
||||
where: { channelId },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
async listChannelConnectionLogs(channelId: string) {
|
||||
const channel = await this.prisma.smsChannel.findUnique({ where: { id: channelId }, select: { id: true } });
|
||||
if (!channel) {
|
||||
throw new NotFoundException('Channel not found');
|
||||
}
|
||||
const [connectionStates, logs] = await Promise.all([
|
||||
this.prisma.cmppConnectionState.findMany({
|
||||
where: { channelId },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
take: 50,
|
||||
}),
|
||||
this.prisma.operationLog.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ resource: 'sms_channel', resourceId: channelId },
|
||||
{ resource: 'cmpp_connection', resourceId: { startsWith: `${channelId}:` } },
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 100,
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
channelId,
|
||||
connectionStates,
|
||||
logs: logs.map((log) => ({
|
||||
id: log.id,
|
||||
time: log.createdAt,
|
||||
event: normalizeLinkEvent(log.action),
|
||||
action: log.action,
|
||||
resourceId: log.resourceId,
|
||||
detail: log.detail,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
listTenantConnections(tenantId: string) {
|
||||
return this.prisma.cmppConnectionState.findMany({
|
||||
where: { tenantId },
|
||||
include: { channel: true },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
async upsertConnectionState(data: UpsertConnectionStateDto) {
|
||||
const rawStatus = data.status;
|
||||
const status = normalizeGatewayConnectionStatus(rawStatus);
|
||||
if (data.applicationId) {
|
||||
const application = await this.prisma.smsApplication.findUnique({ where: { id: data.applicationId }, select: { tenantId: true } });
|
||||
if (!application) {
|
||||
throw new BadRequestException('applicationId does not reference an existing application');
|
||||
}
|
||||
if (data.tenantId && data.tenantId !== application.tenantId) {
|
||||
throw new BadRequestException('applicationId does not belong to tenantId');
|
||||
}
|
||||
data.tenantId = application.tenantId;
|
||||
}
|
||||
const payload = {
|
||||
tenantId: data.tenantId,
|
||||
applicationId: data.applicationId,
|
||||
status,
|
||||
desiredConnections: data.desiredConnections ?? 1,
|
||||
currentConnections: data.currentConnections ?? (status === 'connected' ? 1 : 0),
|
||||
lastConnectedAt: data.lastConnectedAt ? new Date(data.lastConnectedAt) : undefined,
|
||||
lastDisconnectedAt: data.lastDisconnectedAt ? new Date(data.lastDisconnectedAt) : undefined,
|
||||
lastHeartbeatAt: data.lastHeartbeatAt ? new Date(data.lastHeartbeatAt) : undefined,
|
||||
reconnectCount: data.reconnectCount ?? 0,
|
||||
lastReconnectAttemptAt: data.lastReconnectAttemptAt ? new Date(data.lastReconnectAttemptAt) : undefined,
|
||||
nextReconnectAt: data.nextReconnectAt ? new Date(data.nextReconnectAt) : status === 'connected' ? null : undefined,
|
||||
lastErrorCategory: status === 'connected' ? null : data.lastErrorCategory,
|
||||
lastError: status === 'connected' ? null : data.lastError,
|
||||
};
|
||||
const existing = await this.prisma.cmppConnectionState.findFirst({
|
||||
where: {
|
||||
applicationId: data.applicationId ?? null,
|
||||
channelId: data.channelId,
|
||||
connectionId: data.connectionId,
|
||||
},
|
||||
});
|
||||
let state;
|
||||
if (existing) {
|
||||
state = await this.prisma.cmppConnectionState.update({ where: { id: existing.id }, data: payload });
|
||||
} else {
|
||||
try {
|
||||
state = await this.prisma.cmppConnectionState.create({
|
||||
data: {
|
||||
channelId: data.channelId,
|
||||
connectionId: data.connectionId,
|
||||
...payload,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if ((error as { code?: string }).code !== 'P2002') {
|
||||
throw error;
|
||||
}
|
||||
const concurrent = await this.prisma.cmppConnectionState.findFirst({
|
||||
where: {
|
||||
applicationId: data.applicationId ?? null,
|
||||
channelId: data.channelId,
|
||||
connectionId: data.connectionId,
|
||||
},
|
||||
});
|
||||
if (!concurrent) {
|
||||
throw error;
|
||||
}
|
||||
state = await this.prisma.cmppConnectionState.update({ where: { id: concurrent.id }, data: payload });
|
||||
}
|
||||
}
|
||||
const action = normalizeConnectionAction(
|
||||
['heartbeat', 'active_test'].includes(rawStatus.toLowerCase()) ? rawStatus : status,
|
||||
);
|
||||
const heartbeatObservedAt = data.lastHeartbeatAt ? new Date(data.lastHeartbeatAt) : new Date();
|
||||
const shouldWriteAudit = action !== 'heartbeat'
|
||||
|| !existing?.lastHeartbeatAt
|
||||
|| heartbeatObservedAt.getTime() - existing.lastHeartbeatAt.getTime() >= HEARTBEAT_AUDIT_INTERVAL_MS;
|
||||
if (shouldWriteAudit) {
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
action: `cmpp_connection.${action}`,
|
||||
resource: 'cmpp_connection',
|
||||
resourceId: `${data.channelId}:${data.connectionId}`,
|
||||
detail: {
|
||||
status,
|
||||
applicationId: state.applicationId,
|
||||
desiredConnections: state.desiredConnections,
|
||||
currentConnections: state.currentConnections,
|
||||
lastError: state.lastError,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
async markTimedOutConnectingChannels(now = new Date()) {
|
||||
const timeoutMs = getPositiveIntegerEnv('GATEWAY_CONNECTING_TIMEOUT_MS', DEFAULT_CONNECTING_TIMEOUT_MS);
|
||||
const cutoff = new Date(now.getTime() - timeoutMs);
|
||||
const lastError = `${CONNECTING_TIMEOUT_ERROR} after ${Math.round(timeoutMs / 1000)} seconds`;
|
||||
const states = await this.prisma.cmppConnectionState.findMany({
|
||||
where: {
|
||||
status: 'connecting',
|
||||
updatedAt: { lte: cutoff },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
tenantId: true,
|
||||
applicationId: true,
|
||||
channelId: true,
|
||||
connectionId: true,
|
||||
desiredConnections: true,
|
||||
currentConnections: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
take: 100,
|
||||
});
|
||||
let failed = 0;
|
||||
for (const state of states) {
|
||||
const result = await this.prisma.cmppConnectionState.updateMany({
|
||||
where: {
|
||||
id: state.id,
|
||||
status: 'connecting',
|
||||
updatedAt: { lte: cutoff },
|
||||
},
|
||||
data: {
|
||||
status: 'failed',
|
||||
currentConnections: 0,
|
||||
lastDisconnectedAt: now,
|
||||
nextReconnectAt: now,
|
||||
lastErrorCategory: 'timeout',
|
||||
lastError,
|
||||
},
|
||||
});
|
||||
if (result.count === 0) {
|
||||
continue;
|
||||
}
|
||||
failed += result.count;
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
tenantId: state.tenantId,
|
||||
action: 'cmpp_connection.failed',
|
||||
resource: 'cmpp_connection',
|
||||
resourceId: `${state.channelId}:${state.connectionId}`,
|
||||
detail: {
|
||||
reason: 'connect_timeout',
|
||||
applicationId: state.applicationId,
|
||||
status: 'failed',
|
||||
previousStatus: 'connecting',
|
||||
desiredConnections: state.desiredConnections,
|
||||
currentConnectionsBefore: state.currentConnections,
|
||||
currentConnections: 0,
|
||||
timeoutMs,
|
||||
lastError,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
}
|
||||
return { checked: states.length, failed };
|
||||
}
|
||||
|
||||
async requestChannelConnection(
|
||||
channel: {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
gatewayHost: string;
|
||||
gatewayPort: number;
|
||||
account: string;
|
||||
passwordCipher: string;
|
||||
srcId: string;
|
||||
cmppVersion: string;
|
||||
rateLimitPerSecond: number;
|
||||
config?: Prisma.JsonValue | null;
|
||||
},
|
||||
reason: 'channel_created' | 'channel_enabled' | 'channel_updated' | 'gateway_restarted' | 'automatic_reconnect',
|
||||
operatorId?: string,
|
||||
) {
|
||||
const desiredConnections = getDesiredConnections(channel.config);
|
||||
const connectionId = defaultChannelConnectionId(channel.id);
|
||||
const existing = await this.prisma.cmppConnectionState.findFirst({
|
||||
where: {
|
||||
applicationId: null,
|
||||
channelId: channel.id,
|
||||
connectionId,
|
||||
},
|
||||
});
|
||||
const data = {
|
||||
applicationId: null,
|
||||
status: 'connecting',
|
||||
desiredConnections,
|
||||
currentConnections: 0,
|
||||
lastError: null,
|
||||
lastReconnectAttemptAt: new Date(),
|
||||
nextReconnectAt: new Date(Date.now() + getPositiveIntegerEnv('GATEWAY_CONNECTING_TIMEOUT_MS', DEFAULT_CONNECTING_TIMEOUT_MS)),
|
||||
};
|
||||
let state;
|
||||
if (existing) {
|
||||
state = await this.prisma.cmppConnectionState.update({ where: { id: existing.id }, data });
|
||||
} else {
|
||||
try {
|
||||
state = await this.prisma.cmppConnectionState.create({
|
||||
data: {
|
||||
channelId: channel.id,
|
||||
connectionId,
|
||||
...data,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if ((error as { code?: string }).code !== 'P2002') {
|
||||
throw error;
|
||||
}
|
||||
const concurrent = await this.prisma.cmppConnectionState.findFirst({
|
||||
where: { applicationId: null, channelId: channel.id, connectionId },
|
||||
});
|
||||
if (!concurrent) {
|
||||
throw error;
|
||||
}
|
||||
state = await this.prisma.cmppConnectionState.update({ where: { id: concurrent.id }, data });
|
||||
}
|
||||
}
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
userId: operatorId,
|
||||
action: 'cmpp_connection.connect_requested',
|
||||
resource: 'cmpp_connection',
|
||||
resourceId: `${channel.id}:${connectionId}`,
|
||||
detail: {
|
||||
reason,
|
||||
status: state.status,
|
||||
desiredConnections: state.desiredConnections,
|
||||
currentConnections: state.currentConnections,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
const command = {
|
||||
schemaVersion: 'v1',
|
||||
messageType: 'ConnectChannel',
|
||||
traceId: randomUUID(),
|
||||
channelId: channel.id,
|
||||
connectionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
reason,
|
||||
desiredConnections,
|
||||
channel: {
|
||||
code: channel.code,
|
||||
name: channel.name,
|
||||
gatewayHost: channel.gatewayHost,
|
||||
gatewayPort: channel.gatewayPort,
|
||||
account: channel.account,
|
||||
passwordCipher: channel.passwordCipher,
|
||||
srcId: channel.srcId,
|
||||
cmppVersion: channel.cmppVersion,
|
||||
rateLimitPerSecond: channel.rateLimitPerSecond,
|
||||
windowSize: getPositiveRuntimeInteger(getConfigValue(channel.config, 'windowSize'), 16, 'windowSize'),
|
||||
heartbeatIntervalSeconds: getPositiveRuntimeInteger(
|
||||
getConfigValue(channel.config, 'heartbeatIntervalSeconds'),
|
||||
DEFAULT_HEARTBEAT_INTERVAL_SECONDS,
|
||||
'heartbeatIntervalSeconds',
|
||||
),
|
||||
heartbeatMissThreshold: getPositiveRuntimeInteger(
|
||||
getConfigValue(channel.config, 'heartbeatMissThreshold'),
|
||||
DEFAULT_HEARTBEAT_MISS_THRESHOLD,
|
||||
'heartbeatMissThreshold',
|
||||
),
|
||||
},
|
||||
};
|
||||
const queuedJob = await this.getGatewayConnectionQueue().add('connect-channel', command, {
|
||||
jobId: `gateway-connect-${channel.id}-${command.traceId}`,
|
||||
removeOnComplete: 1000,
|
||||
removeOnFail: 1000,
|
||||
}).catch((error) => {
|
||||
this.logger.warn(`Gateway connect marker enqueue failed; continuing with direct control request: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return undefined;
|
||||
});
|
||||
try {
|
||||
await this.notifyGatewayConnect(command);
|
||||
} finally {
|
||||
if (queuedJob) {
|
||||
await queuedJob.remove().catch((error) => {
|
||||
this.logger.warn(`Failed to remove delivered Gateway connect marker ${queuedJob.id}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
async reconnectActiveChannelsAfterGatewayRestart() {
|
||||
const channels = await this.prisma.smsChannel.findMany({ where: { status: 'active' } });
|
||||
const results = await Promise.allSettled(
|
||||
channels.map((channel) => this.requestChannelConnection(channel, 'gateway_restarted')),
|
||||
);
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
const channel = channels[index];
|
||||
this.logger.error(
|
||||
`Failed to restore active CMPP channel ${channel?.code ?? channel?.id ?? index}: ${result.reason instanceof Error ? result.reason.message : String(result.reason)}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async reconcileGatewayConnections(now = new Date()) {
|
||||
const channels = await this.prisma.smsChannel.findMany({
|
||||
where: { status: { in: ['active', 'disabled', 'deleted'] } },
|
||||
include: {
|
||||
connectionStates: {
|
||||
where: { applicationId: null },
|
||||
},
|
||||
},
|
||||
take: 200,
|
||||
});
|
||||
let reconnectRequested = 0;
|
||||
let disconnectRequested = 0;
|
||||
for (const channel of channels) {
|
||||
const state = channel.connectionStates.find((item) => item.connectionId === defaultChannelConnectionId(channel.id));
|
||||
if (channel.status !== 'active') {
|
||||
if (state && (state.currentConnections > 0 || ['connected', 'connecting', 'reconnecting'].includes(state.status))) {
|
||||
await this.withGatewayReconcileLock(channel.id, async () => {
|
||||
await this.requestChannelDisconnection(channel, 'inactive_channel_reconcile');
|
||||
disconnectRequested++;
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const desiredConnections = getDesiredConnections(channel.config);
|
||||
const heartbeatIntervalSeconds = getPositiveRuntimeInteger(
|
||||
getConfigValue(channel.config, 'heartbeatIntervalSeconds'),
|
||||
DEFAULT_HEARTBEAT_INTERVAL_SECONDS,
|
||||
'heartbeatIntervalSeconds',
|
||||
);
|
||||
const heartbeatMissThreshold = getPositiveRuntimeInteger(
|
||||
getConfigValue(channel.config, 'heartbeatMissThreshold'),
|
||||
DEFAULT_HEARTBEAT_MISS_THRESHOLD,
|
||||
'heartbeatMissThreshold',
|
||||
);
|
||||
const heartbeatCutoff = new Date(now.getTime() - heartbeatIntervalSeconds * (heartbeatMissThreshold + 1) * 1000);
|
||||
const connectedAndFresh = state?.status === 'connected'
|
||||
&& state.currentConnections >= desiredConnections
|
||||
&& Boolean(state.lastHeartbeatAt && state.lastHeartbeatAt > heartbeatCutoff);
|
||||
const retryDue = !state?.nextReconnectAt || state.nextReconnectAt <= now;
|
||||
if (!connectedAndFresh && retryDue) {
|
||||
await this.withGatewayReconcileLock(channel.id, async () => {
|
||||
await this.requestChannelConnection(channel, 'automatic_reconnect');
|
||||
reconnectRequested++;
|
||||
});
|
||||
}
|
||||
}
|
||||
return { scanned: channels.length, reconnectRequested, disconnectRequested };
|
||||
}
|
||||
|
||||
async withGatewayReconcileLock(channelId: string, action: () => Promise<void>) {
|
||||
const redis = this.getRedis();
|
||||
const key = `cmpp:gateway:reconcile:${channelId}`;
|
||||
const token = randomUUID();
|
||||
const acquired = await redis.set(key, token, 'PX', DEFAULT_CONNECTING_TIMEOUT_MS, 'NX');
|
||||
if (acquired !== 'OK') {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await action();
|
||||
} finally {
|
||||
await redis.eval(
|
||||
'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',
|
||||
1,
|
||||
key,
|
||||
token,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async requestChannelDisconnection(
|
||||
channel: { id: string },
|
||||
reason: 'channel_disabled' | 'channel_deleted' | 'inactive_channel_reconcile',
|
||||
operatorId?: string,
|
||||
) {
|
||||
const connectionId = defaultChannelConnectionId(channel.id);
|
||||
const now = new Date();
|
||||
await this.prisma.cmppConnectionState.updateMany({
|
||||
where: {
|
||||
applicationId: null,
|
||||
channelId: channel.id,
|
||||
connectionId,
|
||||
},
|
||||
data: {
|
||||
status: 'disconnected',
|
||||
currentConnections: 0,
|
||||
lastDisconnectedAt: now,
|
||||
nextReconnectAt: null,
|
||||
lastErrorCategory: null,
|
||||
lastError: null,
|
||||
},
|
||||
});
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
userId: operatorId,
|
||||
action: 'cmpp_connection.disconnect_requested',
|
||||
resource: 'cmpp_connection',
|
||||
resourceId: `${channel.id}:${connectionId}`,
|
||||
detail: { reason } as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
const command = {
|
||||
schemaVersion: 'v1',
|
||||
messageType: 'DisconnectChannel',
|
||||
traceId: randomUUID(),
|
||||
channelId: channel.id,
|
||||
connectionId,
|
||||
createdAt: now.toISOString(),
|
||||
reason,
|
||||
};
|
||||
const queuedJob = await this.getGatewayConnectionQueue().add('disconnect-channel', command, {
|
||||
jobId: `gateway-disconnect-${channel.id}-${command.traceId}`,
|
||||
removeOnComplete: 1000,
|
||||
removeOnFail: 1000,
|
||||
}).catch((error) => {
|
||||
this.logger.warn(`Gateway disconnect marker enqueue failed; continuing with direct control request: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return undefined;
|
||||
});
|
||||
try {
|
||||
await this.notifyGatewayDisconnect(command);
|
||||
} finally {
|
||||
if (queuedJob) {
|
||||
await queuedJob.remove().catch((error) => {
|
||||
this.logger.warn(`Failed to remove delivered Gateway disconnect marker ${queuedJob.id}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getGatewayConnectionQueue() {
|
||||
this.gatewayConnectionQueue ??= new Queue(GATEWAY_CONNECTION_QUEUE, { connection: bullmqConnection() });
|
||||
return this.gatewayConnectionQueue;
|
||||
}
|
||||
|
||||
getGatewaySubmitQueue() {
|
||||
this.gatewaySubmitQueue ??= new Queue(GATEWAY_SUBMIT_QUEUE, { connection: bullmqConnection() });
|
||||
return this.gatewaySubmitQueue;
|
||||
}
|
||||
|
||||
getRedis() {
|
||||
if (!this.redis) {
|
||||
this.redis = new IORedis(process.env.REDIS_URL ?? 'redis://127.0.0.1:6379', {
|
||||
maxRetriesPerRequest: null,
|
||||
});
|
||||
}
|
||||
return this.redis;
|
||||
}
|
||||
|
||||
async publishGatewaySubmitCommand(command: unknown) {
|
||||
return this.getRedis().xadd(
|
||||
process.env.GATEWAY_SUBMIT_STREAM ?? GATEWAY_SUBMIT_STREAM,
|
||||
'*',
|
||||
'messageType',
|
||||
'SubmitCommand',
|
||||
'data',
|
||||
JSON.stringify(command),
|
||||
);
|
||||
}
|
||||
|
||||
async notifyGatewayConnect(command: Record<string, unknown>) {
|
||||
const baseUrl = (process.env.GATEWAY_CONTROL_URL ?? DEFAULT_GATEWAY_CONTROL_URL).replace(/\/+$/, '');
|
||||
let response: { ok: boolean; status: number; text: () => Promise<string> };
|
||||
try {
|
||||
response = await fetch(`${baseUrl}/connections/connect`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(command),
|
||||
signal: AbortSignal.timeout(getPositiveIntegerEnv('GATEWAY_CONTROL_TIMEOUT_MS', DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS)),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new BadRequestException(`Gateway connect request failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
if (!response.ok) {
|
||||
const responseText = await response.text();
|
||||
throw new BadRequestException(`Gateway connect request failed: ${response.status} ${responseText}`);
|
||||
}
|
||||
}
|
||||
|
||||
async notifyGatewayDisconnect(command: Record<string, unknown>) {
|
||||
const baseUrl = (process.env.GATEWAY_CONTROL_URL ?? DEFAULT_GATEWAY_CONTROL_URL).replace(/\/+$/, '');
|
||||
let response: { ok: boolean; status: number; text: () => Promise<string> };
|
||||
try {
|
||||
response = await fetch(`${baseUrl}/connections/disconnect`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(command),
|
||||
signal: AbortSignal.timeout(getPositiveIntegerEnv('GATEWAY_CONTROL_TIMEOUT_MS', DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS)),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new BadRequestException(`Gateway disconnect request failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
if (!response.ok) {
|
||||
const responseText = await response.text();
|
||||
throw new BadRequestException(`Gateway disconnect request failed: ${response.status} ${responseText}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { BadRequestException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Queue } from 'bullmq';
|
||||
import IORedis from 'ioredis';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { assertMoneyUnits, moneyToNumber } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { CreateChannelDto, UpdateChannelDto, CreateChannelGroupDto, CreateChannelGroupItemDto, UpdateChannelGroupDto, CreateRouteRuleDto, CreateReportFieldDto, ReplaceReportFieldsDto, CreateReportMaterialDto, CreateReportTaskDto, ChangeReportTaskStatusesDto, CreateReportExportDto, CreateReceiptImportDto, UpsertConnectionStateDto, ChangeChannelStatusDto, CopyChannelDto, TestChannelDto } from './channels.contracts';
|
||||
import { GATEWAY_CONNECTION_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_GATEWAY_CONTROL_URL, DEFAULT_CHANNEL_CONNECTION_ID, DEFAULT_CONNECTING_TIMEOUT_MS, DEFAULT_CONNECTING_TIMEOUT_SCAN_MS, DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS, DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS, DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS, DEFAULT_HEARTBEAT_INTERVAL_SECONDS, DEFAULT_HEARTBEAT_MISS_THRESHOLD, HEARTBEAT_AUDIT_INTERVAL_MS, CONNECTING_TIMEOUT_ERROR, DEFAULT_CMPP_VERSION, normalizeTestPhones, normalizeTestContent, calculateBillingUnits, buildChannelTestSubmitCommand, getConfigValue, getStringConfigValue, normalizeConnectionAction, normalizeCmppVersion, normalizeGatewayConnectionStatus, defaultChannelConnectionId, getDesiredConnections, ChannelConnectionSettings, getRuntimeConfigInteger, channelConnectionSettingsChanged, channelGroupAuditSnapshot, normalizeChannelRuntimeConfig, normalizeCmppServiceId, normalizeChannelRateLimit, normalizeExtensionDigits, getPositiveRuntimeInteger, bullmqConnection, getPositiveIntegerEnv, parseReceiptContent, splitReceiptLine, stripReceiptCell, findReceiptStatusIndex, normalizeReceiptStatus, deriveReceiptStatus, ChannelReportDeliveryRow, summarizeChannelReportDelivery, sumReportDelivery, percentage, latestDate, currentShanghaiDayRange, normalizeRetryTimeLimitMinutes, normalizeSpreadsheetSize, normalizeBusinessCarrier, normalizeChannelCarrier, isChannelCarrierCompatible, normalizeRegion, isRegionCompatible, validateGroupItems, normalizeReportType, summarizeReportStatuses, normalizeLinkEvent } from './channels.helpers';
|
||||
|
||||
|
||||
/** R5 channel domain service composed behind ChannelsService. */
|
||||
export class ChannelCopyService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async copyChannel(channelId: string, data: CopyChannelDto = {}) {
|
||||
const source = await this.prisma.smsChannel.findUnique({
|
||||
where: { id: channelId },
|
||||
include: { reportFields: true },
|
||||
});
|
||||
if (!source) {
|
||||
throw new NotFoundException('Channel not found');
|
||||
}
|
||||
|
||||
const suffix = Date.now().toString(36).toUpperCase();
|
||||
const nextName = data.name ?? `${source.name}副本`;
|
||||
const nextCode = data.code ?? `${source.code}-COPY-${suffix}`;
|
||||
|
||||
const copied = await this.prisma.$transaction(async (tx) => {
|
||||
const nextChannel = await tx.smsChannel.create({
|
||||
data: {
|
||||
code: nextCode,
|
||||
name: nextName,
|
||||
carrier: source.carrier,
|
||||
protocol: source.protocol,
|
||||
gatewayHost: source.gatewayHost,
|
||||
gatewayPort: source.gatewayPort,
|
||||
enterpriseCode: source.enterpriseCode,
|
||||
account: source.account,
|
||||
passwordCipher: source.passwordCipher,
|
||||
srcId: source.srcId,
|
||||
sendRegion: source.sendRegion,
|
||||
cmppVersion: source.cmppVersion,
|
||||
rateLimitPerSecond: source.rateLimitPerSecond,
|
||||
unitPrice: source.unitPrice,
|
||||
status: 'disabled',
|
||||
config: source.config as Prisma.InputJsonValue | undefined,
|
||||
reportFields: {
|
||||
create: source.reportFields.map((field) => ({
|
||||
drainageFieldId: field.drainageFieldId,
|
||||
reportType: field.reportType,
|
||||
code: field.code,
|
||||
name: field.name,
|
||||
fieldType: field.fieldType,
|
||||
required: field.required,
|
||||
description: field.description,
|
||||
sortOrder: field.sortOrder,
|
||||
status: field.status,
|
||||
})),
|
||||
},
|
||||
},
|
||||
include: { reportFields: true },
|
||||
});
|
||||
|
||||
const reportMaterials = await tx.signatureReportMaterial.findMany({ where: { channelId } });
|
||||
if (reportMaterials.length > 0) {
|
||||
await tx.signatureReportMaterial.createMany({
|
||||
data: reportMaterials.map((material) => ({
|
||||
signatureId: material.signatureId,
|
||||
channelId: nextChannel.id,
|
||||
fieldCode: material.fieldCode,
|
||||
fieldValue: material.fieldValue,
|
||||
fileObjectId: material.fileObjectId,
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
|
||||
await tx.operationLog.create({
|
||||
data: {
|
||||
userId: data.operatorId,
|
||||
action: 'sms_channel.copy',
|
||||
resource: 'sms_channel',
|
||||
resourceId: nextChannel.id,
|
||||
detail: {
|
||||
sourceChannelId: source.id,
|
||||
sourceCode: source.code,
|
||||
sourceStatus: source.status,
|
||||
copiedStatus: 'disabled',
|
||||
copiedReportFields: source.reportFields.length,
|
||||
copiedReportMaterials: reportMaterials.length,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
|
||||
return nextChannel;
|
||||
});
|
||||
|
||||
return copied;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { BadRequestException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Queue } from 'bullmq';
|
||||
import IORedis from 'ioredis';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { assertMoneyUnits, moneyToNumber } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { CreateChannelDto, UpdateChannelDto, CreateChannelGroupDto, CreateChannelGroupItemDto, UpdateChannelGroupDto, CreateRouteRuleDto, CreateReportFieldDto, ReplaceReportFieldsDto, CreateReportMaterialDto, CreateReportTaskDto, ChangeReportTaskStatusesDto, CreateReportExportDto, CreateReceiptImportDto, UpsertConnectionStateDto, ChangeChannelStatusDto, CopyChannelDto, TestChannelDto } from './channels.contracts';
|
||||
import { GATEWAY_CONNECTION_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_GATEWAY_CONTROL_URL, DEFAULT_CHANNEL_CONNECTION_ID, DEFAULT_CONNECTING_TIMEOUT_MS, DEFAULT_CONNECTING_TIMEOUT_SCAN_MS, DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS, DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS, DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS, DEFAULT_HEARTBEAT_INTERVAL_SECONDS, DEFAULT_HEARTBEAT_MISS_THRESHOLD, HEARTBEAT_AUDIT_INTERVAL_MS, CONNECTING_TIMEOUT_ERROR, DEFAULT_CMPP_VERSION, normalizeTestPhones, normalizeTestContent, calculateBillingUnits, buildChannelTestSubmitCommand, getConfigValue, getStringConfigValue, normalizeConnectionAction, normalizeCmppVersion, normalizeGatewayConnectionStatus, defaultChannelConnectionId, getDesiredConnections, ChannelConnectionSettings, getRuntimeConfigInteger, channelConnectionSettingsChanged, channelGroupAuditSnapshot, normalizeChannelRuntimeConfig, normalizeCmppServiceId, normalizeChannelRateLimit, normalizeExtensionDigits, getPositiveRuntimeInteger, bullmqConnection, getPositiveIntegerEnv, parseReceiptContent, splitReceiptLine, stripReceiptCell, findReceiptStatusIndex, normalizeReceiptStatus, deriveReceiptStatus, ChannelReportDeliveryRow, summarizeChannelReportDelivery, sumReportDelivery, percentage, latestDate, currentShanghaiDayRange, normalizeRetryTimeLimitMinutes, normalizeSpreadsheetSize, normalizeBusinessCarrier, normalizeChannelCarrier, isChannelCarrierCompatible, normalizeRegion, isRegionCompatible, validateGroupItems, normalizeReportType, summarizeReportStatuses, normalizeLinkEvent } from './channels.helpers';
|
||||
import { ChannelConfigurationService } from './channel-configuration.service';
|
||||
|
||||
/** R5 channel domain service composed behind ChannelsService. */
|
||||
export class ChannelDeletionService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly configuration: ChannelConfigurationService) {}
|
||||
|
||||
async deleteChannel(channelId: string, data: ChangeChannelStatusDto = { status: 'deleted' }) {
|
||||
return this.configuration.changeChannelStatus(channelId, { ...data, status: 'deleted' });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { BadRequestException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Queue } from 'bullmq';
|
||||
import IORedis from 'ioredis';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { assertMoneyUnits, moneyToNumber } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { CreateChannelDto, UpdateChannelDto, CreateChannelGroupDto, CreateChannelGroupItemDto, UpdateChannelGroupDto, CreateRouteRuleDto, CreateReportFieldDto, ReplaceReportFieldsDto, CreateReportMaterialDto, CreateReportTaskDto, ChangeReportTaskStatusesDto, CreateReportExportDto, CreateReceiptImportDto, UpsertConnectionStateDto, ChangeChannelStatusDto, CopyChannelDto, TestChannelDto } from './channels.contracts';
|
||||
import { GATEWAY_CONNECTION_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_GATEWAY_CONTROL_URL, DEFAULT_CHANNEL_CONNECTION_ID, DEFAULT_CONNECTING_TIMEOUT_MS, DEFAULT_CONNECTING_TIMEOUT_SCAN_MS, DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS, DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS, DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS, DEFAULT_HEARTBEAT_INTERVAL_SECONDS, DEFAULT_HEARTBEAT_MISS_THRESHOLD, HEARTBEAT_AUDIT_INTERVAL_MS, CONNECTING_TIMEOUT_ERROR, DEFAULT_CMPP_VERSION, normalizeTestPhones, normalizeTestContent, calculateBillingUnits, buildChannelTestSubmitCommand, getConfigValue, getStringConfigValue, normalizeConnectionAction, normalizeCmppVersion, normalizeGatewayConnectionStatus, defaultChannelConnectionId, getDesiredConnections, ChannelConnectionSettings, getRuntimeConfigInteger, channelConnectionSettingsChanged, channelGroupAuditSnapshot, normalizeChannelRuntimeConfig, normalizeCmppServiceId, normalizeChannelRateLimit, normalizeExtensionDigits, getPositiveRuntimeInteger, bullmqConnection, getPositiveIntegerEnv, parseReceiptContent, splitReceiptLine, stripReceiptCell, findReceiptStatusIndex, normalizeReceiptStatus, deriveReceiptStatus, ChannelReportDeliveryRow, summarizeChannelReportDelivery, sumReportDelivery, percentage, latestDate, currentShanghaiDayRange, normalizeRetryTimeLimitMinutes, normalizeSpreadsheetSize, normalizeBusinessCarrier, normalizeChannelCarrier, isChannelCarrierCompatible, normalizeRegion, isRegionCompatible, validateGroupItems, normalizeReportType, summarizeReportStatuses, normalizeLinkEvent } from './channels.helpers';
|
||||
|
||||
|
||||
/** R5 channel domain service composed behind ChannelsService. */
|
||||
export class ChannelGroupRoutingService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
listGroups() {
|
||||
return this.prisma.smsChannelGroup.findMany({
|
||||
include: { items: { include: { channel: { include: { connectionStates: true } } }, orderBy: [{ province: 'asc' }, { priority: 'asc' }] } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
createGroup(data: CreateChannelGroupDto) {
|
||||
const retryTimeLimitMinutes = normalizeRetryTimeLimitMinutes(data.retryTimeLimitMinutes, data.retryTimeLimitHours, 720);
|
||||
const carrier = normalizeBusinessCarrier(data.carrier);
|
||||
return this.prisma.smsChannelGroup.create({
|
||||
data: {
|
||||
code: data.code,
|
||||
name: data.name,
|
||||
carrier,
|
||||
description: data.description,
|
||||
status: data.status ?? 'active',
|
||||
retryEnabled: data.retryEnabled ?? true,
|
||||
retryTimeLimitHours: Math.ceil(retryTimeLimitMinutes / 60),
|
||||
retryTimeLimitMinutes,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async addGroupItem(data: CreateChannelGroupItemDto) {
|
||||
const group = await this.prisma.smsChannelGroup.findUnique({ where: { id: data.groupId } });
|
||||
if (!group) {
|
||||
throw new NotFoundException('Channel group not found');
|
||||
}
|
||||
const groupCarrier = normalizeBusinessCarrier(group.carrier);
|
||||
const itemCarrier = data.carrier ? normalizeBusinessCarrier(data.carrier) : groupCarrier;
|
||||
if (itemCarrier !== groupCarrier) {
|
||||
throw new BadRequestException('Channel group items must use the same carrier as the channel group');
|
||||
}
|
||||
const channel = await this.prisma.smsChannel.findUnique({ where: { id: data.channelId } });
|
||||
if (!channel) {
|
||||
throw new NotFoundException('Channel not found');
|
||||
}
|
||||
if (!isChannelCarrierCompatible(channel.carrier, groupCarrier)) {
|
||||
throw new BadRequestException('Channel carrier is not compatible with the channel group carrier');
|
||||
}
|
||||
if (data.province && !isRegionCompatible(channel.sendRegion, data.province)) {
|
||||
throw new BadRequestException('Province route must use a channel with the same sendRegion');
|
||||
}
|
||||
const existing = await this.prisma.smsChannelGroupItem.findFirst({
|
||||
where: { groupId: data.groupId, channelId: data.channelId },
|
||||
});
|
||||
if (existing) {
|
||||
throw new BadRequestException('通道组内不能重复配置同一通道');
|
||||
}
|
||||
if (data.province) {
|
||||
const existingProvince = await this.prisma.smsChannelGroupItem.findFirst({
|
||||
where: { groupId: data.groupId, province: data.province },
|
||||
});
|
||||
if (existingProvince) {
|
||||
throw new BadRequestException('同一通道组内同一省份只能配置一个通道');
|
||||
}
|
||||
} else {
|
||||
const existingPriority = await this.prisma.smsChannelGroupItem.findFirst({
|
||||
where: { groupId: data.groupId, province: null, priority: data.priority ?? 100 },
|
||||
});
|
||||
if (existingPriority) {
|
||||
throw new BadRequestException('同一通道组内全国通道优先级不能重复');
|
||||
}
|
||||
}
|
||||
return this.prisma.smsChannelGroupItem.create({
|
||||
data: {
|
||||
groupId: data.groupId,
|
||||
channelId: data.channelId,
|
||||
carrier: itemCarrier,
|
||||
province: data.province,
|
||||
priority: data.priority ?? 100,
|
||||
weight: data.weight ?? 1,
|
||||
isBackup: data.isBackup ?? false,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async updateGroup(groupId: string, data: UpdateChannelGroupDto) {
|
||||
const current = await this.prisma.smsChannelGroup.findUnique({
|
||||
where: { id: groupId },
|
||||
include: { items: { include: { channel: true }, orderBy: [{ province: 'asc' }, { priority: 'asc' }] } },
|
||||
});
|
||||
if (!current) {
|
||||
throw new NotFoundException('Channel group not found');
|
||||
}
|
||||
const retryTimeLimitMinutes = normalizeRetryTimeLimitMinutes(
|
||||
data.retryTimeLimitMinutes,
|
||||
data.retryTimeLimitHours,
|
||||
current.retryTimeLimitMinutes ?? current.retryTimeLimitHours * 60,
|
||||
);
|
||||
const carrier = data.carrier ? normalizeBusinessCarrier(data.carrier) : normalizeBusinessCarrier(current.carrier);
|
||||
const items = data.items ?? [];
|
||||
const channelIds = [...new Set(items.map((item) => item.channelId))];
|
||||
const channels = await this.prisma.smsChannel.findMany({ where: { id: { in: channelIds } } });
|
||||
const channelById = new Map(channels.map((channel) => [channel.id, channel]));
|
||||
validateGroupItems(carrier, items, channelById);
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
await tx.smsChannelGroupItem.deleteMany({ where: { groupId } });
|
||||
await tx.smsChannelGroup.update({
|
||||
where: { id: groupId },
|
||||
data: {
|
||||
code: data.code ?? current.code,
|
||||
name: data.name ?? current.name,
|
||||
carrier,
|
||||
description: data.description,
|
||||
status: data.status ?? current.status,
|
||||
retryEnabled: data.retryEnabled ?? current.retryEnabled,
|
||||
retryTimeLimitHours: Math.ceil(retryTimeLimitMinutes / 60),
|
||||
retryTimeLimitMinutes,
|
||||
},
|
||||
});
|
||||
if (items.length > 0) {
|
||||
await tx.smsChannelGroupItem.createMany({
|
||||
data: items.map((item) => ({
|
||||
groupId,
|
||||
channelId: item.channelId,
|
||||
carrier,
|
||||
province: item.province,
|
||||
priority: item.priority ?? 100,
|
||||
weight: item.weight ?? 1,
|
||||
isBackup: item.isBackup ?? false,
|
||||
})),
|
||||
});
|
||||
}
|
||||
const updated = await tx.smsChannelGroup.findUnique({
|
||||
where: { id: groupId },
|
||||
include: { items: { include: { channel: true }, orderBy: [{ province: 'asc' }, { priority: 'asc' }] } },
|
||||
});
|
||||
await tx.operationLog.create({
|
||||
data: {
|
||||
action: 'sms_channel_group.update',
|
||||
resource: 'sms_channel_group',
|
||||
resourceId: groupId,
|
||||
detail: {
|
||||
before: channelGroupAuditSnapshot(current),
|
||||
after: updated ? channelGroupAuditSnapshot(updated) : null,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
async deleteGroup(groupId: string) {
|
||||
const group = await this.prisma.smsChannelGroup.findUnique({ where: { id: groupId } });
|
||||
if (!group) {
|
||||
throw new NotFoundException('Channel group not found');
|
||||
}
|
||||
const boundRoute = await this.prisma.channelRouteRule.findFirst({
|
||||
where: {
|
||||
groupId,
|
||||
status: 'active',
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (boundRoute) {
|
||||
throw new BadRequestException('Channel group is used by application route rules and cannot be deleted');
|
||||
}
|
||||
await this.prisma.smsChannelGroupItem.deleteMany({ where: { groupId } });
|
||||
return this.prisma.smsChannelGroup.delete({ where: { id: groupId } });
|
||||
}
|
||||
|
||||
listRouteRules() {
|
||||
return this.prisma.channelRouteRule.findMany({
|
||||
include: { group: true, channel: true },
|
||||
orderBy: [{ priority: 'asc' }, { createdAt: 'desc' }],
|
||||
});
|
||||
}
|
||||
|
||||
async createRouteRule(data: CreateRouteRuleDto) {
|
||||
if (!data.applicationId) {
|
||||
throw new BadRequestException('applicationId is required for channel group routing');
|
||||
}
|
||||
if (!data.carrier) {
|
||||
throw new BadRequestException('carrier is required for application channel group routing');
|
||||
}
|
||||
const carrier = normalizeBusinessCarrier(data.carrier);
|
||||
if (data.channelId) {
|
||||
throw new BadRequestException('Route rules can only bind channel groups, not single channels');
|
||||
}
|
||||
if (data.province) {
|
||||
throw new BadRequestException('Province routing must be configured inside the channel group');
|
||||
}
|
||||
const group = await this.prisma.smsChannelGroup.findUnique({ where: { id: data.groupId } });
|
||||
if (!group) {
|
||||
throw new NotFoundException('Channel group not found');
|
||||
}
|
||||
if (normalizeBusinessCarrier(group.carrier) !== carrier) {
|
||||
throw new BadRequestException('Route rule carrier must match the channel group carrier');
|
||||
}
|
||||
return this.prisma.channelRouteRule.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
applicationId: data.applicationId,
|
||||
groupId: data.groupId,
|
||||
channelId: undefined,
|
||||
carrier,
|
||||
province: undefined,
|
||||
priority: data.priority ?? 100,
|
||||
status: data.status ?? 'active',
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
import { BadRequestException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Queue } from 'bullmq';
|
||||
import IORedis from 'ioredis';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { assertMoneyUnits, moneyToNumber } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { CreateChannelDto, UpdateChannelDto, CreateChannelGroupDto, CreateChannelGroupItemDto, UpdateChannelGroupDto, CreateRouteRuleDto, CreateReportFieldDto, ReplaceReportFieldsDto, CreateReportMaterialDto, CreateReportTaskDto, ChangeReportTaskStatusesDto, CreateReportExportDto, CreateReceiptImportDto, UpsertConnectionStateDto, ChangeChannelStatusDto, CopyChannelDto, TestChannelDto } from './channels.contracts';
|
||||
import { GATEWAY_CONNECTION_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_GATEWAY_CONTROL_URL, DEFAULT_CHANNEL_CONNECTION_ID, DEFAULT_CONNECTING_TIMEOUT_MS, DEFAULT_CONNECTING_TIMEOUT_SCAN_MS, DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS, DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS, DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS, DEFAULT_HEARTBEAT_INTERVAL_SECONDS, DEFAULT_HEARTBEAT_MISS_THRESHOLD, HEARTBEAT_AUDIT_INTERVAL_MS, CONNECTING_TIMEOUT_ERROR, DEFAULT_CMPP_VERSION, normalizeTestPhones, normalizeTestContent, calculateBillingUnits, buildChannelTestSubmitCommand, getConfigValue, getStringConfigValue, normalizeConnectionAction, normalizeCmppVersion, normalizeGatewayConnectionStatus, defaultChannelConnectionId, getDesiredConnections, ChannelConnectionSettings, getRuntimeConfigInteger, channelConnectionSettingsChanged, channelGroupAuditSnapshot, normalizeChannelRuntimeConfig, normalizeCmppServiceId, normalizeChannelRateLimit, normalizeExtensionDigits, getPositiveRuntimeInteger, bullmqConnection, getPositiveIntegerEnv, parseReceiptContent, splitReceiptLine, stripReceiptCell, findReceiptStatusIndex, normalizeReceiptStatus, deriveReceiptStatus, ChannelReportDeliveryRow, summarizeChannelReportDelivery, sumReportDelivery, percentage, latestDate, currentShanghaiDayRange, normalizeRetryTimeLimitMinutes, normalizeSpreadsheetSize, normalizeBusinessCarrier, normalizeChannelCarrier, isChannelCarrierCompatible, normalizeRegion, isRegionCompatible, validateGroupItems, normalizeReportType, summarizeReportStatuses, normalizeLinkEvent } from './channels.helpers';
|
||||
|
||||
|
||||
/** R5 channel domain service composed behind ChannelsService. */
|
||||
export class ChannelReportingService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
listReportFields(channelId?: string) {
|
||||
return this.prisma.channelReportField.findMany({
|
||||
where: channelId ? { channelId } : undefined,
|
||||
include: { drainageField: true },
|
||||
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
|
||||
});
|
||||
}
|
||||
|
||||
async createReportField(data: CreateReportFieldDto) {
|
||||
if (!data.drainageFieldId) throw new BadRequestException('drainageFieldId is required');
|
||||
const field = await this.prisma.drainageField.findUnique({ where: { id: data.drainageFieldId } });
|
||||
if (!field || field.status !== 'active') {
|
||||
throw new BadRequestException('报备字段库字段不存在或已停用');
|
||||
}
|
||||
const reportType = normalizeReportType(data.reportType);
|
||||
return this.prisma.channelReportField.create({
|
||||
data: {
|
||||
channelId: data.channelId,
|
||||
drainageFieldId: field.id,
|
||||
reportType,
|
||||
code: field.code,
|
||||
name: field.name,
|
||||
exportName: data.exportName?.trim() || field.name,
|
||||
fieldType: field.fieldType,
|
||||
required: data.required ?? field.required,
|
||||
description: data.description ?? field.description,
|
||||
sortOrder: data.sortOrder ?? 100,
|
||||
columnWidth: normalizeSpreadsheetSize(data.columnWidth, 18, 6, 80),
|
||||
imageWidth: normalizeSpreadsheetSize(data.imageWidth, 120, 24, 600),
|
||||
imageHeight: normalizeSpreadsheetSize(data.imageHeight, 80, 24, 600),
|
||||
defaultValue: data.defaultValue,
|
||||
transform: data.transform,
|
||||
status: data.status ?? 'active',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async replaceReportFields(channelId: string, reportType: 'signature' | 'drainage', data: ReplaceReportFieldsDto) {
|
||||
const channel = await this.prisma.smsChannel.findUnique({ where: { id: channelId } });
|
||||
if (!channel) throw new NotFoundException('Channel not found');
|
||||
const ids = data.fields.map((field) => field.drainageFieldId);
|
||||
if (new Set(ids).size !== ids.length) throw new BadRequestException('同一通道报备类型不能重复配置字段');
|
||||
const libraryFields = await this.prisma.drainageField.findMany({ where: { id: { in: ids }, status: 'active' } });
|
||||
if (libraryFields.length !== ids.length) throw new BadRequestException('报备字段库字段不存在或已停用');
|
||||
const fieldById = new Map(libraryFields.map((field) => [field.id, field]));
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const oppositeType = reportType === 'signature' ? 'drainage' : 'signature';
|
||||
const [legacyBoth, oppositeFields] = await Promise.all([
|
||||
tx.channelReportField.findMany({ where: { channelId, reportType: 'both' } }),
|
||||
tx.channelReportField.findMany({ where: { channelId, reportType: oppositeType } }),
|
||||
]);
|
||||
const oppositeCodes = new Set(oppositeFields.map((field) => field.code));
|
||||
await tx.channelReportField.deleteMany({ where: { channelId, reportType: { in: [reportType, 'both'] } } });
|
||||
for (const legacy of legacyBoth) {
|
||||
if (oppositeCodes.has(legacy.code)) continue;
|
||||
const { id: _id, createdAt: _createdAt, updatedAt: _updatedAt, ...legacyData } = legacy;
|
||||
await tx.channelReportField.create({ data: { ...legacyData, reportType: oppositeType } });
|
||||
}
|
||||
for (const [index, configured] of data.fields.entries()) {
|
||||
const field = fieldById.get(configured.drainageFieldId)!;
|
||||
await tx.channelReportField.create({
|
||||
data: {
|
||||
channelId,
|
||||
drainageFieldId: field.id,
|
||||
reportType,
|
||||
code: field.code,
|
||||
name: field.name,
|
||||
exportName: configured.exportName?.trim() || field.name,
|
||||
fieldType: field.fieldType,
|
||||
required: configured.required ?? field.required,
|
||||
description: configured.description ?? field.description,
|
||||
sortOrder: configured.sortOrder ?? (index + 1) * 10,
|
||||
columnWidth: normalizeSpreadsheetSize(configured.columnWidth, 18, 6, 80),
|
||||
imageWidth: normalizeSpreadsheetSize(configured.imageWidth, 120, 24, 600),
|
||||
imageHeight: normalizeSpreadsheetSize(configured.imageHeight, 80, 24, 600),
|
||||
defaultValue: configured.defaultValue,
|
||||
transform: configured.transform,
|
||||
status: configured.status ?? 'active',
|
||||
},
|
||||
});
|
||||
}
|
||||
return tx.channelReportField.findMany({ where: { channelId, reportType }, include: { drainageField: true }, orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }] });
|
||||
});
|
||||
}
|
||||
|
||||
listReportMaterials(signatureId?: string, channelId?: string) {
|
||||
return this.prisma.signatureReportMaterial.findMany({
|
||||
where: {
|
||||
signatureId,
|
||||
channelId,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
upsertReportMaterial(data: CreateReportMaterialDto) {
|
||||
return this.prisma.signatureReportMaterial.upsert({
|
||||
where: {
|
||||
signatureId_channelId_fieldCode: {
|
||||
signatureId: data.signatureId,
|
||||
channelId: data.channelId,
|
||||
fieldCode: data.fieldCode,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
fieldValue: data.fieldValue,
|
||||
fileObjectId: data.fileObjectId,
|
||||
},
|
||||
create: {
|
||||
signatureId: data.signatureId,
|
||||
channelId: data.channelId,
|
||||
fieldCode: data.fieldCode,
|
||||
fieldValue: data.fieldValue,
|
||||
fileObjectId: data.fileObjectId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async listReportTasks(tenantId?: string, status?: string, channelId?: string, reportType?: string) {
|
||||
const tasks = await this.prisma.channelSignatureReportTask.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
status,
|
||||
channelId,
|
||||
reportType,
|
||||
signature: { auditStatus: { not: 'deleted' } },
|
||||
},
|
||||
include: {
|
||||
signature: { include: { tenant: true, application: true } },
|
||||
channel: true,
|
||||
drainageInfo: true,
|
||||
exportItems: {
|
||||
include: { exportFile: true, batchItem: { include: { batch: true } } },
|
||||
orderBy: { id: 'desc' },
|
||||
take: 1,
|
||||
},
|
||||
records: { orderBy: { createdAt: 'desc' }, take: 20 },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
if (tasks.length === 0) {
|
||||
return tasks;
|
||||
}
|
||||
|
||||
const channelIds = [...new Set(tasks.map((task) => task.channelId))];
|
||||
const signatureIds = [...new Set(tasks.map((task) => task.signatureId))];
|
||||
const day = currentShanghaiDayRange();
|
||||
const rows = await this.prisma.$queryRaw<ChannelReportDeliveryRow[]>(Prisma.sql`
|
||||
WITH base AS (
|
||||
SELECT
|
||||
submit."channelId" AS channel_id,
|
||||
message."signatureId" AS signature_id,
|
||||
message."drainageInfoId" AS drainage_info_id,
|
||||
submit."submitStatus" AS submit_status,
|
||||
COALESCE(submit."submittedAt", submit."createdAt") AS attempted_at,
|
||||
CASE
|
||||
WHEN segment_summary.segment_count > 0
|
||||
AND segment_summary.delivered_count = segment_summary.segment_count
|
||||
THEN segment_summary.completed_at
|
||||
WHEN segment_summary.segment_count = 0 THEN delivered_receipt.delivered_at
|
||||
END AS successful_at,
|
||||
CASE
|
||||
WHEN submit."submitStatus" <> 'accepted' THEN 'submit_failed'
|
||||
WHEN segment_summary.segment_count > 0 AND segment_summary.failure_count > 0 THEN 'failure'
|
||||
WHEN segment_summary.segment_count > 0
|
||||
AND segment_summary.delivered_count = segment_summary.segment_count THEN 'success'
|
||||
WHEN segment_summary.segment_count = 0 AND failed_receipt.failed_at IS NOT NULL THEN 'failure'
|
||||
WHEN segment_summary.segment_count = 0 AND delivered_receipt.delivered_at IS NOT NULL THEN 'success'
|
||||
ELSE 'unknown'
|
||||
END AS delivery_status
|
||||
FROM "SmsSubmitRecord" submit
|
||||
JOIN "SmsMessageRecord" message ON message.id = submit."messageRecordId"
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT
|
||||
COUNT(*)::integer AS segment_count,
|
||||
COUNT(*) FILTER (WHERE segment."receiptStatus" = 'delivered')::integer AS delivered_count,
|
||||
COUNT(*) FILTER (WHERE segment."receiptStatus" = 'undelivered')::integer AS failure_count,
|
||||
MAX(segment."deliveredAt") FILTER (WHERE segment."receiptStatus" = 'delivered') AS completed_at
|
||||
FROM "SmsMessageSegmentAudit" segment
|
||||
WHERE segment."submitRecordId" = submit.id
|
||||
) segment_summary ON TRUE
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT MIN(receipt."deliveredAt") AS delivered_at
|
||||
FROM "SmsReceiptRecord" receipt
|
||||
WHERE receipt."gatewayMessageId" = submit."gatewayMessageId"
|
||||
AND receipt."channelId" = submit."channelId"
|
||||
AND receipt."receiptStatus" = 'delivered'
|
||||
) delivered_receipt ON TRUE
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT MIN(receipt."deliveredAt") AS failed_at
|
||||
FROM "SmsReceiptRecord" receipt
|
||||
WHERE receipt."gatewayMessageId" = submit."gatewayMessageId"
|
||||
AND receipt."channelId" = submit."channelId"
|
||||
AND receipt."receiptStatus" = 'undelivered'
|
||||
) failed_receipt ON TRUE
|
||||
WHERE submit."submitStatus" IN ('accepted', 'rejected', 'timeout')
|
||||
AND submit."channelId" IN (${Prisma.join(channelIds)})
|
||||
AND message."signatureId" IN (${Prisma.join(signatureIds)})
|
||||
)
|
||||
SELECT
|
||||
channel_id AS "channelId",
|
||||
signature_id AS "signatureId",
|
||||
drainage_info_id AS "drainageInfoId",
|
||||
COUNT(*) FILTER (
|
||||
WHERE attempted_at >= ${day.startAt} AND attempted_at < ${day.endAt}
|
||||
)::integer AS total,
|
||||
COUNT(*) FILTER (
|
||||
WHERE attempted_at >= ${day.startAt} AND attempted_at < ${day.endAt}
|
||||
AND submit_status = 'accepted'
|
||||
)::integer AS "acceptedCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE attempted_at >= ${day.startAt} AND attempted_at < ${day.endAt}
|
||||
AND delivery_status = 'submit_failed'
|
||||
)::integer AS "submitFailureCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE attempted_at >= ${day.startAt} AND attempted_at < ${day.endAt}
|
||||
AND delivery_status = 'success'
|
||||
)::integer AS "successCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE attempted_at >= ${day.startAt} AND attempted_at < ${day.endAt}
|
||||
AND delivery_status = 'unknown'
|
||||
)::integer AS "unknownCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE attempted_at >= ${day.startAt} AND attempted_at < ${day.endAt}
|
||||
AND delivery_status = 'failure'
|
||||
)::integer AS "failureCount",
|
||||
MAX(successful_at) FILTER (WHERE delivery_status = 'success') AS "lastSuccessfulSentAt"
|
||||
FROM base
|
||||
GROUP BY channel_id, signature_id, drainage_info_id
|
||||
`);
|
||||
|
||||
return tasks.map((task) => {
|
||||
const taskRows = rows.filter((row) => (
|
||||
row.channelId === task.channelId
|
||||
&& row.signatureId === task.signatureId
|
||||
&& ((task.reportType ?? 'signature') === 'signature' || row.drainageInfoId === task.drainageItemId)
|
||||
));
|
||||
const deliveryStats = summarizeChannelReportDelivery(taskRows);
|
||||
return {
|
||||
...task,
|
||||
deliveryStats,
|
||||
lastSuccessfulSentAt: latestDate(taskRows.map((row) => row.lastSuccessfulSentAt)),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async listReportTasksPage(query: {
|
||||
tenantId?: string;
|
||||
status?: string;
|
||||
channelId?: string;
|
||||
reportType?: string;
|
||||
keyword?: string;
|
||||
createdAtFrom?: string;
|
||||
createdAtTo?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}) {
|
||||
const page = Math.max(1, Math.floor(Number(query.page) || 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 10)));
|
||||
const keyword = query.keyword?.trim();
|
||||
const where: Prisma.ChannelSignatureReportTaskWhereInput = {
|
||||
tenantId: query.tenantId,
|
||||
status: query.status,
|
||||
channelId: query.channelId,
|
||||
reportType: query.reportType,
|
||||
signature: { auditStatus: { not: 'deleted' } },
|
||||
createdAt: query.createdAtFrom || query.createdAtTo ? {
|
||||
gte: query.createdAtFrom ? new Date(`${query.createdAtFrom}T00:00:00+08:00`) : undefined,
|
||||
lte: query.createdAtTo ? new Date(`${query.createdAtTo}T23:59:59.999+08:00`) : undefined,
|
||||
} : undefined,
|
||||
OR: keyword ? [
|
||||
{ id: { contains: keyword } },
|
||||
{ channel: { name: { contains: keyword } } },
|
||||
{ signature: { name: { contains: keyword } } },
|
||||
{ signature: { tenant: { name: { contains: keyword } } } },
|
||||
{ signature: { application: { name: { contains: keyword } } } },
|
||||
{ drainageInfo: { siteName: { contains: keyword } } },
|
||||
{ drainageInfo: { url: { contains: keyword } } },
|
||||
] : undefined,
|
||||
};
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.channelSignatureReportTask.findMany({
|
||||
where,
|
||||
include: {
|
||||
signature: { include: { tenant: true, application: true } },
|
||||
channel: true,
|
||||
drainageInfo: true,
|
||||
exportItems: {
|
||||
include: { exportFile: true, batchItem: { include: { batch: true } } },
|
||||
orderBy: { id: 'desc' },
|
||||
take: 1,
|
||||
},
|
||||
records: { orderBy: { createdAt: 'desc' }, take: 20 },
|
||||
},
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.channelSignatureReportTask.count({ where }),
|
||||
]);
|
||||
return { items, total, page, pageSize };
|
||||
}
|
||||
|
||||
async createReportTask(data: CreateReportTaskDto) {
|
||||
const reportType = data.reportType ?? 'signature';
|
||||
if (reportType === 'drainage' && !data.drainageItemId) throw new BadRequestException('drainageItemId is required');
|
||||
if (reportType === 'drainage') {
|
||||
const drainageInfo = await this.prisma.smsDrainageInfo.findUnique({ where: { id: data.drainageItemId! } });
|
||||
if (!drainageInfo || drainageInfo.signatureId !== data.signatureId) throw new NotFoundException('Drainage info not found');
|
||||
if (drainageInfo.auditStatus !== 'approved') throw new BadRequestException('引流信息审核通过后才能进入通道报备');
|
||||
throw new BadRequestException('引流信息通道报备任务由运营审核通过后按应用路由自动生成');
|
||||
}
|
||||
const task = await this.prisma.channelSignatureReportTask.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
signatureId: data.signatureId,
|
||||
channelId: data.channelId,
|
||||
reportType,
|
||||
drainageItemId: undefined,
|
||||
createdById: data.createdById,
|
||||
status: 'pending',
|
||||
},
|
||||
});
|
||||
await this.recordReportTask(task.id, task.channelId, 'create', undefined, 'pending');
|
||||
return task;
|
||||
}
|
||||
|
||||
async changeReportTaskStatuses(data: ChangeReportTaskStatusesDto) {
|
||||
if (!data.items.length) throw new BadRequestException('items is required');
|
||||
const allowed = new Set(['pending', 'waiting_material', 'reporting', 'approved', 'failed', 'rejected', 'abandoned']);
|
||||
for (const item of data.items) {
|
||||
if (!allowed.has(item.status)) throw new BadRequestException('unsupported report task status');
|
||||
}
|
||||
const sourceEntry = data.sourceEntry ?? 'report_task';
|
||||
if (!['enterprise_signature', 'report_task', 'channel_report'].includes(sourceEntry)) {
|
||||
throw new BadRequestException('unsupported report task source entry');
|
||||
}
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const signatureIds = [...new Set(data.items.filter((item) => (item.reportType ?? 'signature') === 'signature').map((item) => item.signatureId))];
|
||||
const drainageResults: Array<{ signatureId: string; reportType: 'drainage'; drainageItemId: string; channelId: string; status: string }> = [];
|
||||
for (const item of data.items) {
|
||||
const reportType = item.reportType ?? 'signature';
|
||||
if (reportType === 'drainage' && !item.drainageItemId) throw new BadRequestException('drainageItemId is required');
|
||||
const signature = await tx.smsSignature.findUnique({ where: { id: item.signatureId } });
|
||||
const channel = await tx.smsChannel.findUnique({ where: { id: item.channelId } });
|
||||
if (!signature || !channel) throw new NotFoundException('Signature or channel not found');
|
||||
if (reportType === 'drainage') {
|
||||
const drainageInfo = await tx.smsDrainageInfo.findUnique({ where: { id: item.drainageItemId! } });
|
||||
if (!drainageInfo || drainageInfo.signatureId !== item.signatureId) throw new NotFoundException('Drainage info not found');
|
||||
if (drainageInfo.auditStatus !== 'approved') throw new BadRequestException('引流信息审核通过后才能修改通道报备状态');
|
||||
}
|
||||
const existing = await tx.channelSignatureReportTask.findFirst({ where: { signatureId: item.signatureId, channelId: item.channelId, reportType, drainageItemId: reportType === 'drainage' ? item.drainageItemId : null } });
|
||||
if (reportType === 'drainage' && !existing) throw new BadRequestException('引流信息通道报备任务不存在,请先完成运营审核');
|
||||
const task = existing
|
||||
? await tx.channelSignatureReportTask.update({ where: { id: existing.id }, data: { status: item.status, reason: data.reason } })
|
||||
: await tx.channelSignatureReportTask.create({ data: { tenantId: signature.tenantId, signatureId: item.signatureId, channelId: item.channelId, reportType, drainageItemId: reportType === 'drainage' ? item.drainageItemId : undefined, status: item.status, reason: data.reason, createdById: data.operatorId } });
|
||||
await tx.channelSignatureReportRecord.create({ data: { taskId: task.id, channelId: item.channelId, action: 'manual_status_change', statusBefore: existing?.status, statusAfter: item.status, reason: data.reason, operatorId: data.operatorId, sourceEntry } });
|
||||
if (reportType === 'drainage') drainageResults.push({ signatureId: item.signatureId, reportType, drainageItemId: item.drainageItemId!, channelId: item.channelId, status: item.status });
|
||||
}
|
||||
const summaries = [];
|
||||
for (const signatureId of signatureIds) summaries.push(await this.recomputeSignatureReportSummary(tx, signatureId));
|
||||
return [...summaries, ...drainageResults];
|
||||
});
|
||||
}
|
||||
|
||||
async recomputeSignatureReportSummary(tx: Prisma.TransactionClient, signatureId: string) {
|
||||
const signature = await tx.smsSignature.findUnique({ where: { id: signatureId } });
|
||||
if (!signature) throw new NotFoundException('Signature not found');
|
||||
const routes = signature.applicationId ? await tx.channelRouteRule.findMany({
|
||||
where: { applicationId: signature.applicationId, status: 'active' },
|
||||
include: { group: { include: { items: { include: { channel: true } } } } },
|
||||
}) : [];
|
||||
const configuredChannels = routes.flatMap((route) => route.group.items.map((item) => item.channel)).filter((channel) => channel.status !== 'deleted');
|
||||
const tasks = await tx.channelSignatureReportTask.findMany({ where: { signatureId, reportType: 'signature' }, include: { channel: true } });
|
||||
const channels = configuredChannels.length ? configuredChannels : tasks.map((task) => task.channel);
|
||||
const uniqueChannels = [...new Map(channels.map((channel) => [channel.id, channel])).values()];
|
||||
const taskByChannel = new Map(tasks.map((task) => [task.channelId, task]));
|
||||
const carrierReportSummary = Object.fromEntries(['mobile', 'unicom', 'telecom'].map((carrier) => {
|
||||
const targets = uniqueChannels.filter((channel) => channel.carrier === carrier || channel.carrier === 'all');
|
||||
const statuses = targets.map((channel) => taskByChannel.get(channel.id)?.status ?? 'pending');
|
||||
return [carrier, summarizeReportStatuses(statuses)];
|
||||
}));
|
||||
const allStatuses = uniqueChannels.map((channel) => taskByChannel.get(channel.id)?.status ?? 'pending');
|
||||
const reportStatus = summarizeReportStatuses(allStatuses).status;
|
||||
await tx.smsSignature.update({ where: { id: signatureId }, data: { reportStatus } });
|
||||
return { signatureId, reportStatus, carrierReportSummary };
|
||||
}
|
||||
|
||||
async createReportExport(taskId: string, data: CreateReportExportDto) {
|
||||
const task = await this.getReportTaskOrThrow(taskId);
|
||||
const exported = await this.prisma.reportExportFile.create({
|
||||
data: {
|
||||
taskId,
|
||||
fileObjectId: data.fileObjectId,
|
||||
fileName: data.fileName,
|
||||
rowCount: data.rowCount ?? 0,
|
||||
},
|
||||
});
|
||||
await this.updateReportTaskStatus(taskId, task.channelId, task.status, 'exporting', 'export');
|
||||
return exported;
|
||||
}
|
||||
|
||||
async importReportReceipt(taskId: string, data: CreateReceiptImportDto) {
|
||||
const task = await this.getReportTaskOrThrow(taskId);
|
||||
const parsed = data.fileContent ? parseReceiptContent(data.fileContent, data.delimiter) : undefined;
|
||||
const rowCount = data.rowCount ?? parsed?.rowCount ?? 0;
|
||||
const successCount = data.successCount ?? parsed?.successCount ?? 0;
|
||||
const failedCount = data.failedCount ?? parsed?.failedCount ?? 0;
|
||||
const statusAfter = data.statusAfter ?? deriveReceiptStatus(rowCount, successCount, failedCount);
|
||||
const imported = await this.prisma.reportReceiptImport.create({
|
||||
data: {
|
||||
taskId,
|
||||
fileObjectId: data.fileObjectId,
|
||||
fileName: data.fileName,
|
||||
rowCount,
|
||||
successCount,
|
||||
failedCount,
|
||||
status: 'imported',
|
||||
result: (data.result ?? parsed?.result) as Prisma.InputJsonValue | undefined,
|
||||
},
|
||||
});
|
||||
await this.updateReportTaskStatus(taskId, task.channelId, task.status, statusAfter, 'receipt_import', data.reason);
|
||||
if ((task.reportType ?? 'signature') === 'signature') {
|
||||
await this.recomputeSignatureReportSummary(this.prisma as unknown as Prisma.TransactionClient, task.signatureId);
|
||||
}
|
||||
return imported;
|
||||
}
|
||||
|
||||
listReportRecords(taskId?: string, channelId?: string) {
|
||||
return this.prisma.channelSignatureReportRecord.findMany({
|
||||
where: { taskId, channelId },
|
||||
include: { channel: true, task: { include: { signature: true, drainageInfo: true } } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
async listReportRecordsPage(query: {
|
||||
taskId?: string;
|
||||
channelId?: string;
|
||||
keyword?: string;
|
||||
reportType?: string;
|
||||
createdAtFrom?: string;
|
||||
createdAtTo?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}) {
|
||||
const page = Math.max(1, Math.floor(Number(query.page) || 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 10)));
|
||||
const keyword = query.keyword?.trim();
|
||||
const where: Prisma.ChannelSignatureReportRecordWhereInput = {
|
||||
taskId: query.taskId,
|
||||
channelId: query.channelId,
|
||||
task: query.reportType ? { reportType: query.reportType } : undefined,
|
||||
createdAt: query.createdAtFrom || query.createdAtTo ? {
|
||||
gte: query.createdAtFrom ? new Date(`${query.createdAtFrom}T00:00:00+08:00`) : undefined,
|
||||
lte: query.createdAtTo ? new Date(`${query.createdAtTo}T23:59:59.999+08:00`) : undefined,
|
||||
} : undefined,
|
||||
OR: keyword ? [
|
||||
{ taskId: { contains: keyword } },
|
||||
{ action: { contains: keyword } },
|
||||
{ reason: { contains: keyword } },
|
||||
{ channel: { name: { contains: keyword } } },
|
||||
{ task: { signature: { name: { contains: keyword } } } },
|
||||
{ task: { drainageInfo: { siteName: { contains: keyword } } } },
|
||||
{ task: { drainageInfo: { url: { contains: keyword } } } },
|
||||
] : undefined,
|
||||
};
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.channelSignatureReportRecord.findMany({
|
||||
where,
|
||||
include: { channel: true, task: { include: { signature: true, drainageInfo: true } } },
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.channelSignatureReportRecord.count({ where }),
|
||||
]);
|
||||
return { items, total, page, pageSize };
|
||||
}
|
||||
|
||||
async getReportTaskOrThrow(taskId: string) {
|
||||
const task = await this.prisma.channelSignatureReportTask.findUnique({ where: { id: taskId }, include: { drainageInfo: true } });
|
||||
if (!task) {
|
||||
throw new NotFoundException('Report task not found');
|
||||
}
|
||||
if (task.reportType === 'drainage' && task.drainageInfo?.auditStatus !== 'approved') {
|
||||
throw new BadRequestException('引流信息审核通过后才能处理通道报备任务');
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
async updateReportTaskStatus(
|
||||
taskId: string,
|
||||
channelId: string,
|
||||
statusBefore: string,
|
||||
statusAfter: string,
|
||||
action: string,
|
||||
reason?: string,
|
||||
) {
|
||||
await this.prisma.channelSignatureReportTask.update({
|
||||
where: { id: taskId },
|
||||
data: { status: statusAfter, reason },
|
||||
});
|
||||
await this.recordReportTask(taskId, channelId, action, statusBefore, statusAfter, reason);
|
||||
}
|
||||
|
||||
recordReportTask(
|
||||
taskId: string,
|
||||
channelId: string,
|
||||
action: string,
|
||||
statusBefore: string | undefined,
|
||||
statusAfter: string,
|
||||
reason?: string,
|
||||
) {
|
||||
return this.prisma.channelSignatureReportRecord.create({
|
||||
data: {
|
||||
taskId,
|
||||
channelId,
|
||||
action,
|
||||
statusBefore,
|
||||
statusAfter,
|
||||
reason,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { BadRequestException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Queue } from 'bullmq';
|
||||
import IORedis from 'ioredis';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { assertMoneyUnits, moneyToNumber } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { CreateChannelDto, UpdateChannelDto, CreateChannelGroupDto, CreateChannelGroupItemDto, UpdateChannelGroupDto, CreateRouteRuleDto, CreateReportFieldDto, ReplaceReportFieldsDto, CreateReportMaterialDto, CreateReportTaskDto, ChangeReportTaskStatusesDto, CreateReportExportDto, CreateReceiptImportDto, UpsertConnectionStateDto, ChangeChannelStatusDto, CopyChannelDto, TestChannelDto } from './channels.contracts';
|
||||
import { GATEWAY_CONNECTION_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_GATEWAY_CONTROL_URL, DEFAULT_CHANNEL_CONNECTION_ID, DEFAULT_CONNECTING_TIMEOUT_MS, DEFAULT_CONNECTING_TIMEOUT_SCAN_MS, DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS, DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS, DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS, DEFAULT_HEARTBEAT_INTERVAL_SECONDS, DEFAULT_HEARTBEAT_MISS_THRESHOLD, HEARTBEAT_AUDIT_INTERVAL_MS, CONNECTING_TIMEOUT_ERROR, DEFAULT_CMPP_VERSION, normalizeTestPhones, normalizeTestContent, calculateBillingUnits, buildChannelTestSubmitCommand, getConfigValue, getStringConfigValue, normalizeConnectionAction, normalizeCmppVersion, normalizeGatewayConnectionStatus, defaultChannelConnectionId, getDesiredConnections, ChannelConnectionSettings, getRuntimeConfigInteger, channelConnectionSettingsChanged, channelGroupAuditSnapshot, normalizeChannelRuntimeConfig, normalizeCmppServiceId, normalizeChannelRateLimit, normalizeExtensionDigits, getPositiveRuntimeInteger, bullmqConnection, getPositiveIntegerEnv, parseReceiptContent, splitReceiptLine, stripReceiptCell, findReceiptStatusIndex, normalizeReceiptStatus, deriveReceiptStatus, ChannelReportDeliveryRow, summarizeChannelReportDelivery, sumReportDelivery, percentage, latestDate, currentShanghaiDayRange, normalizeRetryTimeLimitMinutes, normalizeSpreadsheetSize, normalizeBusinessCarrier, normalizeChannelCarrier, isChannelCarrierCompatible, normalizeRegion, isRegionCompatible, validateGroupItems, normalizeReportType, summarizeReportStatuses, normalizeLinkEvent } from './channels.helpers';
|
||||
import { ChannelConnectionService } from './channel-connection.service';
|
||||
|
||||
/** R5 channel domain service composed behind ChannelsService. */
|
||||
export class ChannelTestService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly connection: ChannelConnectionService) {}
|
||||
|
||||
async testChannel(channelId: string, data: TestChannelDto = {}) {
|
||||
const phoneNumbers = normalizeTestPhones(data);
|
||||
const content = normalizeTestContent(data.content);
|
||||
const channel = await this.prisma.smsChannel.findUnique({
|
||||
where: { id: channelId },
|
||||
include: { connectionStates: true },
|
||||
});
|
||||
if (!channel) {
|
||||
throw new NotFoundException('Channel not found');
|
||||
}
|
||||
if (channel.status !== 'active') {
|
||||
throw new BadRequestException('通道未启用,不能发送测试短信');
|
||||
}
|
||||
const connectedState = channel.connectionStates.find((state) =>
|
||||
normalizeGatewayConnectionStatus(state.status) === 'connected' && (state.currentConnections ?? 0) > 0,
|
||||
);
|
||||
if (!connectedState) {
|
||||
throw new BadRequestException('通道当前没有可用 CMPP 连接,请先连接成功后再测试发送');
|
||||
}
|
||||
|
||||
const createdAt = new Date();
|
||||
const testNo = `CHTEST-${Date.now()}-${randomUUID().slice(0, 8)}`;
|
||||
const results = [];
|
||||
for (const [index, phoneNumber] of phoneNumbers.entries()) {
|
||||
const messageId = `MSG-TEST-${Date.now()}-${randomUUID().slice(0, 8)}`;
|
||||
const submitId = `SUB-TEST-${Date.now()}-${randomUUID().slice(0, 8)}`;
|
||||
const session = await this.prisma.cmppSubmitSession.upsert({
|
||||
where: { sessionNo: `OPEN-${channel.id}` },
|
||||
update: { submitTotal: { increment: 1 } },
|
||||
create: { channelId: channel.id, sessionNo: `OPEN-${channel.id}`, submitTotal: 1 },
|
||||
});
|
||||
const messageRecord = await this.prisma.smsMessageRecord.create({
|
||||
data: {
|
||||
messageId,
|
||||
phoneNumber,
|
||||
content,
|
||||
billingUnits: calculateBillingUnits(content),
|
||||
unitPrice: 0,
|
||||
amountCents: 0,
|
||||
queuePriority: 'normal',
|
||||
channelId: channel.id,
|
||||
submitId,
|
||||
status: 'submit_queued',
|
||||
submitStatus: 'queued',
|
||||
},
|
||||
});
|
||||
await this.prisma.smsSubmitRecord.create({
|
||||
data: {
|
||||
messageRecordId: messageRecord.id,
|
||||
channelId: channel.id,
|
||||
sessionId: session.id,
|
||||
submitId,
|
||||
submitStatus: 'queued',
|
||||
costUnitPrice: channel.unitPrice,
|
||||
costAmountCents: moneyToNumber(channel.unitPrice) * messageRecord.billingUnits,
|
||||
},
|
||||
});
|
||||
const command = buildChannelTestSubmitCommand({
|
||||
channel,
|
||||
content,
|
||||
phoneNumber,
|
||||
messageId,
|
||||
submitId,
|
||||
testNo,
|
||||
attempt: index,
|
||||
accessNo: data.accessNo,
|
||||
});
|
||||
await this.connection.getGatewaySubmitQueue().add('submit-command', command);
|
||||
const streamMessageId = await this.connection.publishGatewaySubmitCommand(command);
|
||||
results.push({
|
||||
phoneNumber,
|
||||
messageRecordId: messageRecord.id,
|
||||
submitId,
|
||||
streamMessageId,
|
||||
});
|
||||
}
|
||||
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
userId: data.operatorId,
|
||||
action: 'sms_channel.test_submit',
|
||||
resource: 'sms_channel',
|
||||
resourceId: channel.id,
|
||||
detail: {
|
||||
testNo,
|
||||
phoneTotal: phoneNumbers.length,
|
||||
messageRecordIds: results.map((item) => item.messageRecordId),
|
||||
connectionId: connectedState.connectionId,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
channelId,
|
||||
status: 'submit_queued',
|
||||
testNo,
|
||||
submitted: results.length,
|
||||
messages: results,
|
||||
queuedAt: createdAt,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
/** Stable request contracts shared by the channel controller and R5 domains. */
|
||||
|
||||
export interface CreateChannelDto {
|
||||
code: string;
|
||||
name: string;
|
||||
carrier?: string;
|
||||
sendRegion?: string;
|
||||
protocol?: string;
|
||||
gatewayHost: string;
|
||||
gatewayPort?: number;
|
||||
enterpriseCode?: string;
|
||||
account: string;
|
||||
passwordCipher: string;
|
||||
srcId: string;
|
||||
cmppVersion?: string;
|
||||
rateLimitPerSecond?: number;
|
||||
unitPrice?: number;
|
||||
status?: string;
|
||||
desiredConnections?: number;
|
||||
windowSize?: number;
|
||||
heartbeatIntervalSeconds?: number;
|
||||
heartbeatMissThreshold?: number;
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export type UpdateChannelDto = Partial<CreateChannelDto>;
|
||||
|
||||
export interface CreateChannelGroupDto {
|
||||
code: string;
|
||||
name: string;
|
||||
carrier: string;
|
||||
description?: string;
|
||||
status?: string;
|
||||
retryEnabled?: boolean;
|
||||
retryTimeLimitHours?: number;
|
||||
retryTimeLimitMinutes?: number;
|
||||
}
|
||||
|
||||
export interface CreateChannelGroupItemDto {
|
||||
groupId: string;
|
||||
channelId: string;
|
||||
carrier?: string;
|
||||
province?: string;
|
||||
priority?: number;
|
||||
weight?: number;
|
||||
isBackup?: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateChannelGroupDto {
|
||||
code?: string;
|
||||
name?: string;
|
||||
carrier?: string;
|
||||
description?: string;
|
||||
status?: string;
|
||||
retryEnabled?: boolean;
|
||||
retryTimeLimitHours?: number;
|
||||
retryTimeLimitMinutes?: number;
|
||||
items?: Array<Omit<CreateChannelGroupItemDto, 'groupId'>>;
|
||||
}
|
||||
|
||||
export interface CreateRouteRuleDto {
|
||||
tenantId?: string;
|
||||
applicationId?: string;
|
||||
groupId: string;
|
||||
channelId?: string;
|
||||
carrier?: string;
|
||||
province?: string;
|
||||
priority?: number;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
export interface CreateReportFieldDto {
|
||||
channelId: string;
|
||||
drainageFieldId: string;
|
||||
reportType: 'signature' | 'drainage' | 'both';
|
||||
code?: string;
|
||||
name?: string;
|
||||
fieldType?: string;
|
||||
required?: boolean;
|
||||
description?: string;
|
||||
sortOrder?: number;
|
||||
exportName?: string;
|
||||
columnWidth?: number;
|
||||
imageWidth?: number;
|
||||
imageHeight?: number;
|
||||
defaultValue?: string;
|
||||
transform?: string;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
export interface ReplaceReportFieldsDto {
|
||||
fields: Array<Omit<CreateReportFieldDto, 'channelId' | 'reportType'>>;
|
||||
}
|
||||
|
||||
export interface CreateReportMaterialDto {
|
||||
signatureId: string;
|
||||
channelId: string;
|
||||
fieldCode: string;
|
||||
fieldValue?: string;
|
||||
fileObjectId?: string;
|
||||
}
|
||||
|
||||
export interface CreateReportTaskDto {
|
||||
tenantId: string;
|
||||
signatureId: string;
|
||||
channelId: string;
|
||||
reportType?: 'signature' | 'drainage';
|
||||
drainageItemId?: string;
|
||||
createdById?: string;
|
||||
}
|
||||
|
||||
export interface ChangeReportTaskStatusesDto {
|
||||
items: Array<{ signatureId: string; channelId: string; status: string; reportType?: 'signature' | 'drainage'; drainageItemId?: string }>;
|
||||
reason?: string;
|
||||
operatorId?: string;
|
||||
sourceEntry?: 'enterprise_signature' | 'report_task' | 'channel_report';
|
||||
}
|
||||
|
||||
export interface CreateReportExportDto {
|
||||
fileObjectId?: string;
|
||||
fileName: string;
|
||||
rowCount?: number;
|
||||
}
|
||||
|
||||
export interface CreateReceiptImportDto {
|
||||
fileObjectId?: string;
|
||||
fileName: string;
|
||||
fileContent?: string;
|
||||
delimiter?: ',' | '\t';
|
||||
rowCount?: number;
|
||||
successCount?: number;
|
||||
failedCount?: number;
|
||||
statusAfter?: string;
|
||||
reason?: string;
|
||||
result?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface UpsertConnectionStateDto {
|
||||
tenantId?: string;
|
||||
applicationId?: string;
|
||||
channelId: string;
|
||||
connectionId: string;
|
||||
status: string;
|
||||
desiredConnections?: number;
|
||||
currentConnections?: number;
|
||||
lastConnectedAt?: string;
|
||||
lastDisconnectedAt?: string;
|
||||
lastHeartbeatAt?: string;
|
||||
reconnectCount?: number;
|
||||
lastReconnectAttemptAt?: string;
|
||||
nextReconnectAt?: string;
|
||||
lastErrorCategory?: string;
|
||||
lastError?: string;
|
||||
}
|
||||
|
||||
export interface ChangeChannelStatusDto {
|
||||
status: string;
|
||||
operatorId?: string;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface CopyChannelDto {
|
||||
name?: string;
|
||||
code?: string;
|
||||
operatorId?: string;
|
||||
}
|
||||
|
||||
export interface TestChannelDto {
|
||||
phoneNumber?: string;
|
||||
phones?: string[] | string;
|
||||
content?: string;
|
||||
accessNo?: string;
|
||||
operatorId?: string;
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { RequireRecentAuthentication } from '../auth/require-recent-authenticati
|
||||
import { CurrentSessionUserId } from '../auth/current-session-user.decorator';
|
||||
import { DeleteTargetDto, DeletionGovernanceService } from '../deletion-governance/deletion-governance.service';
|
||||
import {
|
||||
ChannelsService,
|
||||
ChangeChannelStatusDto,
|
||||
CopyChannelDto,
|
||||
CreateChannelDto,
|
||||
@@ -22,7 +21,8 @@ import {
|
||||
UpsertConnectionStateDto,
|
||||
UpdateChannelDto,
|
||||
UpdateChannelGroupDto,
|
||||
} from './channels.service';
|
||||
} from './channels.contracts';
|
||||
import { ChannelsService } from './channels.service';
|
||||
|
||||
@ApiTags('channels')
|
||||
@Controller('admin')
|
||||
|
||||
@@ -0,0 +1,685 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'crypto';
|
||||
import type { CreateChannelDto, UpdateChannelDto, CreateChannelGroupDto, CreateChannelGroupItemDto, UpdateChannelGroupDto, CreateRouteRuleDto, CreateReportFieldDto, ReplaceReportFieldsDto, CreateReportMaterialDto, CreateReportTaskDto, ChangeReportTaskStatusesDto, CreateReportExportDto, CreateReceiptImportDto, UpsertConnectionStateDto, ChangeChannelStatusDto, CopyChannelDto, TestChannelDto } from './channels.contracts';
|
||||
|
||||
/** Constants and pure validation/normalization helpers shared by R5 domains. */
|
||||
export const GATEWAY_CONNECTION_QUEUE = 'gateway.connection.commands';
|
||||
|
||||
export const GATEWAY_SUBMIT_QUEUE = 'gateway.submit.queue';
|
||||
|
||||
export const GATEWAY_SUBMIT_STREAM = 'gateway.submit.commands';
|
||||
|
||||
export const DEFAULT_GATEWAY_CONTROL_URL = 'http://127.0.0.1:8090';
|
||||
|
||||
export const DEFAULT_CHANNEL_CONNECTION_ID = 'primary';
|
||||
|
||||
export const DEFAULT_CONNECTING_TIMEOUT_MS = 30_000;
|
||||
|
||||
export const DEFAULT_CONNECTING_TIMEOUT_SCAN_MS = 5_000;
|
||||
|
||||
export const DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS = 1_000;
|
||||
|
||||
export const DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS = 30_000;
|
||||
|
||||
export const DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS = 10_000;
|
||||
|
||||
export const DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30;
|
||||
|
||||
export const DEFAULT_HEARTBEAT_MISS_THRESHOLD = 3;
|
||||
|
||||
export const HEARTBEAT_AUDIT_INTERVAL_MS = 5 * 60_000;
|
||||
|
||||
export const CONNECTING_TIMEOUT_ERROR = 'Gateway connection request timed out';
|
||||
|
||||
export const DEFAULT_CMPP_VERSION = '2.0';
|
||||
|
||||
export function normalizeTestPhones(data: TestChannelDto) {
|
||||
const rawPhones = Array.isArray(data.phones)
|
||||
? data.phones
|
||||
: String(data.phoneNumber ?? data.phones ?? '').split(/[,\n,\s]+/u);
|
||||
const phones = rawPhones.map((phone) => String(phone).trim()).filter(Boolean);
|
||||
const uniquePhones = Array.from(new Set(phones));
|
||||
if (uniquePhones.length === 0) {
|
||||
throw new BadRequestException('请填写测试手机号');
|
||||
}
|
||||
if (uniquePhones.length > 10) {
|
||||
throw new BadRequestException('测试手机号最多允许 10 个');
|
||||
}
|
||||
for (const phone of uniquePhones) {
|
||||
if (!/^1[3-9]\d{9}$/.test(phone)) {
|
||||
throw new BadRequestException(`手机号格式不正确:${phone}`);
|
||||
}
|
||||
}
|
||||
return uniquePhones;
|
||||
}
|
||||
|
||||
export function normalizeTestContent(content?: string) {
|
||||
const normalized = (content ?? '').trim();
|
||||
if (!normalized) {
|
||||
throw new BadRequestException('请填写测试短信内容');
|
||||
}
|
||||
if (normalized.length > 1000) {
|
||||
throw new BadRequestException('测试短信内容不能超过 1000 字符');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function calculateBillingUnits(content: string) {
|
||||
return Math.max(1, Math.ceil([...content].length / 67));
|
||||
}
|
||||
|
||||
export function buildChannelTestSubmitCommand({
|
||||
channel,
|
||||
content,
|
||||
phoneNumber,
|
||||
messageId,
|
||||
submitId,
|
||||
testNo,
|
||||
attempt,
|
||||
accessNo,
|
||||
}: {
|
||||
channel: {
|
||||
id: string;
|
||||
code: string;
|
||||
gatewayHost: string;
|
||||
gatewayPort: number;
|
||||
account: string;
|
||||
passwordCipher: string;
|
||||
srcId: string;
|
||||
cmppVersion: string;
|
||||
rateLimitPerSecond: number;
|
||||
config?: Prisma.JsonValue | null;
|
||||
};
|
||||
content: string;
|
||||
phoneNumber: string;
|
||||
messageId: string;
|
||||
submitId: string;
|
||||
testNo: string;
|
||||
attempt: number;
|
||||
accessNo?: string;
|
||||
}) {
|
||||
const srcId = accessNo?.trim() ? `${channel.srcId}${accessNo.trim()}` : channel.srcId;
|
||||
return {
|
||||
schemaVersion: 'v1',
|
||||
messageType: 'SubmitCommand',
|
||||
traceId: randomUUID(),
|
||||
messageId,
|
||||
channelId: channel.id,
|
||||
createdAt: new Date().toISOString(),
|
||||
tenantId: 'platform-channel-test',
|
||||
applicationId: 'admin-channel-test',
|
||||
taskId: testNo,
|
||||
submitId,
|
||||
queuePriority: 'normal',
|
||||
phoneNumber,
|
||||
content,
|
||||
signature: 'CHANNEL_TEST',
|
||||
templateId: 'admin-channel-test',
|
||||
billingUnits: calculateBillingUnits(content),
|
||||
route: {
|
||||
channelCode: channel.code,
|
||||
cmppAccountCode: channel.account,
|
||||
priority: attempt,
|
||||
rateLimitPerSecond: channel.rateLimitPerSecond,
|
||||
},
|
||||
cmpp: {
|
||||
serviceId: getStringConfigValue(channel.config, 'serviceId', 'SMS'),
|
||||
srcId,
|
||||
extensionDigits: normalizeExtensionDigits(getConfigValue(channel.config, 'extensionDigits')),
|
||||
registeredDelivery: 1,
|
||||
msgFmt: 8,
|
||||
},
|
||||
upstream: {
|
||||
gatewayHost: channel.gatewayHost,
|
||||
gatewayPort: channel.gatewayPort,
|
||||
account: channel.account,
|
||||
passwordCipher: channel.passwordCipher,
|
||||
cmppVersion: channel.cmppVersion,
|
||||
desiredConnections: getPositiveRuntimeInteger(getConfigValue(channel.config, 'desiredConnections'), 1, 'desiredConnections'),
|
||||
windowSize: getPositiveRuntimeInteger(getConfigValue(channel.config, 'windowSize'), 16, 'windowSize'),
|
||||
heartbeatIntervalSeconds: getPositiveRuntimeInteger(
|
||||
getConfigValue(channel.config, 'heartbeatIntervalSeconds'),
|
||||
DEFAULT_HEARTBEAT_INTERVAL_SECONDS,
|
||||
'heartbeatIntervalSeconds',
|
||||
),
|
||||
heartbeatMissThreshold: getPositiveRuntimeInteger(
|
||||
getConfigValue(channel.config, 'heartbeatMissThreshold'),
|
||||
DEFAULT_HEARTBEAT_MISS_THRESHOLD,
|
||||
'heartbeatMissThreshold',
|
||||
),
|
||||
},
|
||||
retry: { attempt: 0, maxAttempts: 1 },
|
||||
};
|
||||
}
|
||||
|
||||
export function getConfigValue(config: Prisma.JsonValue | null | undefined, key: string) {
|
||||
if (config && typeof config === 'object' && !Array.isArray(config) && key in config) {
|
||||
return config[key as keyof typeof config];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function getStringConfigValue(config: Prisma.JsonValue | null | undefined, key: string, fallback: string) {
|
||||
const value = getConfigValue(config, key);
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return fallback;
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
export function normalizeConnectionAction(status: string) {
|
||||
const normalized = status.toLowerCase();
|
||||
if (normalized === 'connected') {
|
||||
return 'connected';
|
||||
}
|
||||
if (['heartbeat', 'active_test'].includes(normalized)) {
|
||||
return 'heartbeat';
|
||||
}
|
||||
if (['reconnecting', 'reconnect'].includes(normalized)) {
|
||||
return 'reconnecting';
|
||||
}
|
||||
if (['offline', 'closed', 'disconnected'].includes(normalized)) {
|
||||
return 'disconnected';
|
||||
}
|
||||
if (['auth_failed', 'heartbeat_timeout', 'failed', 'error'].includes(normalized)) {
|
||||
return 'failed';
|
||||
}
|
||||
return 'updated';
|
||||
}
|
||||
|
||||
export function normalizeCmppVersion(version?: string) {
|
||||
const normalized = (version ?? DEFAULT_CMPP_VERSION).trim();
|
||||
if (normalized === '2.0' || normalized === '3.0') {
|
||||
return normalized;
|
||||
}
|
||||
throw new BadRequestException('cmppVersion must be 2.0 or 3.0');
|
||||
}
|
||||
|
||||
export function normalizeGatewayConnectionStatus(status: string) {
|
||||
const normalized = status.toLowerCase();
|
||||
if (['online', 'open', 'connected', 'heartbeat', 'active_test'].includes(normalized)) {
|
||||
return 'connected';
|
||||
}
|
||||
if (['connecting', 'connect_requested'].includes(normalized)) {
|
||||
return 'connecting';
|
||||
}
|
||||
if (['reconnecting', 'reconnect'].includes(normalized)) {
|
||||
return 'reconnecting';
|
||||
}
|
||||
if (['offline', 'closed', 'disconnected'].includes(normalized)) {
|
||||
return 'disconnected';
|
||||
}
|
||||
if (['auth_failed', 'heartbeat_timeout', 'failed', 'error'].includes(normalized)) {
|
||||
return 'failed';
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function defaultChannelConnectionId(channelId: string) {
|
||||
return `${channelId}:${DEFAULT_CHANNEL_CONNECTION_ID}`;
|
||||
}
|
||||
|
||||
export function getDesiredConnections(config?: Prisma.JsonValue | null) {
|
||||
if (config && typeof config === 'object' && !Array.isArray(config) && 'desiredConnections' in config) {
|
||||
const value = Number(config.desiredConnections);
|
||||
if (Number.isInteger(value) && value > 0) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
export type ChannelConnectionSettings = {
|
||||
gatewayHost: string;
|
||||
gatewayPort: number;
|
||||
account: string;
|
||||
passwordCipher: string;
|
||||
cmppVersion: string;
|
||||
config?: Prisma.JsonValue | Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
export function getRuntimeConfigInteger(
|
||||
config: Prisma.JsonValue | Record<string, unknown> | null | undefined,
|
||||
key: string,
|
||||
fallback: number,
|
||||
) {
|
||||
if (!config || typeof config !== 'object' || Array.isArray(config)) return fallback;
|
||||
const value = Number((config as Record<string, unknown>)[key]);
|
||||
return Number.isInteger(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
|
||||
export function channelConnectionSettingsChanged(
|
||||
before: ChannelConnectionSettings,
|
||||
after: ChannelConnectionSettings,
|
||||
) {
|
||||
return before.gatewayHost !== after.gatewayHost
|
||||
|| before.gatewayPort !== after.gatewayPort
|
||||
|| before.account !== after.account
|
||||
|| before.passwordCipher !== after.passwordCipher
|
||||
|| before.cmppVersion !== after.cmppVersion
|
||||
|| getRuntimeConfigInteger(before.config, 'desiredConnections', 1)
|
||||
!== getRuntimeConfigInteger(after.config, 'desiredConnections', 1)
|
||||
|| getRuntimeConfigInteger(before.config, 'windowSize', 16)
|
||||
!== getRuntimeConfigInteger(after.config, 'windowSize', 16)
|
||||
|| getRuntimeConfigInteger(before.config, 'heartbeatIntervalSeconds', DEFAULT_HEARTBEAT_INTERVAL_SECONDS)
|
||||
!== getRuntimeConfigInteger(after.config, 'heartbeatIntervalSeconds', DEFAULT_HEARTBEAT_INTERVAL_SECONDS)
|
||||
|| getRuntimeConfigInteger(before.config, 'heartbeatMissThreshold', DEFAULT_HEARTBEAT_MISS_THRESHOLD)
|
||||
!== getRuntimeConfigInteger(after.config, 'heartbeatMissThreshold', DEFAULT_HEARTBEAT_MISS_THRESHOLD);
|
||||
}
|
||||
|
||||
export function channelGroupAuditSnapshot(group: {
|
||||
code: string;
|
||||
name: string;
|
||||
carrier: string;
|
||||
description?: string | null;
|
||||
status: string;
|
||||
retryEnabled: boolean;
|
||||
retryTimeLimitMinutes: number;
|
||||
items?: Array<{
|
||||
channelId: string;
|
||||
carrier?: string | null;
|
||||
province?: string | null;
|
||||
priority: number;
|
||||
weight: number;
|
||||
isBackup: boolean;
|
||||
channel?: { code?: string; name?: string } | null;
|
||||
}>;
|
||||
}) {
|
||||
return {
|
||||
code: group.code,
|
||||
name: group.name,
|
||||
carrier: group.carrier,
|
||||
description: group.description ?? null,
|
||||
status: group.status,
|
||||
retryEnabled: group.retryEnabled,
|
||||
retryTimeLimitMinutes: group.retryTimeLimitMinutes,
|
||||
items: (group.items ?? []).map((item) => ({
|
||||
channelId: item.channelId,
|
||||
channelCode: item.channel?.code ?? null,
|
||||
channelName: item.channel?.name ?? null,
|
||||
carrier: item.carrier ?? null,
|
||||
province: item.province ?? null,
|
||||
priority: item.priority,
|
||||
weight: item.weight,
|
||||
isBackup: item.isBackup,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeChannelRuntimeConfig(
|
||||
existingConfig?: Prisma.JsonValue | Record<string, unknown> | null,
|
||||
incomingConfig?: Record<string, unknown> | null,
|
||||
desiredConnections?: number,
|
||||
windowSize?: number,
|
||||
heartbeatIntervalSeconds?: number,
|
||||
heartbeatMissThreshold?: number,
|
||||
) {
|
||||
const existing = existingConfig && typeof existingConfig === 'object' && !Array.isArray(existingConfig)
|
||||
? existingConfig as Record<string, unknown>
|
||||
: {};
|
||||
const incoming = incomingConfig && typeof incomingConfig === 'object' && !Array.isArray(incomingConfig)
|
||||
? incomingConfig
|
||||
: {};
|
||||
const base = { ...existing, ...incoming };
|
||||
base.desiredConnections = getPositiveRuntimeInteger(desiredConnections ?? base.desiredConnections, 1, 'desiredConnections');
|
||||
base.windowSize = getPositiveRuntimeInteger(windowSize ?? base.windowSize, 16, 'windowSize');
|
||||
base.heartbeatIntervalSeconds = getPositiveRuntimeInteger(
|
||||
heartbeatIntervalSeconds ?? base.heartbeatIntervalSeconds,
|
||||
DEFAULT_HEARTBEAT_INTERVAL_SECONDS,
|
||||
'heartbeatIntervalSeconds',
|
||||
);
|
||||
base.heartbeatMissThreshold = getPositiveRuntimeInteger(
|
||||
heartbeatMissThreshold ?? base.heartbeatMissThreshold,
|
||||
DEFAULT_HEARTBEAT_MISS_THRESHOLD,
|
||||
'heartbeatMissThreshold',
|
||||
);
|
||||
base.extensionDigits = normalizeExtensionDigits(base.extensionDigits);
|
||||
base.serviceId = normalizeCmppServiceId(base.serviceId);
|
||||
return base;
|
||||
}
|
||||
|
||||
export function normalizeCmppServiceId(value: unknown) {
|
||||
const normalized = String(value ?? 'SMS').trim() || 'SMS';
|
||||
if (!/^[\x20-\x7E]{1,10}$/.test(normalized)) {
|
||||
throw new BadRequestException('serviceId must contain 1 to 10 ASCII characters');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function normalizeChannelRateLimit(value: unknown) {
|
||||
const normalized = getPositiveRuntimeInteger(value, 100, 'rateLimitPerSecond');
|
||||
if (normalized > 2000) {
|
||||
throw new BadRequestException('rateLimitPerSecond must be between 1 and 2000');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function normalizeExtensionDigits(value: unknown) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return 0;
|
||||
}
|
||||
const normalized = Number(value);
|
||||
if (!Number.isInteger(normalized) || normalized < 0 || normalized > 20) {
|
||||
throw new BadRequestException('extensionDigits must be an integer between 0 and 20');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function getPositiveRuntimeInteger(value: unknown, fallback: number, fieldName: string) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return fallback;
|
||||
}
|
||||
const normalized = Number(value);
|
||||
if (!Number.isInteger(normalized) || normalized <= 0) {
|
||||
throw new BadRequestException(`${fieldName} must be a positive integer`);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function bullmqConnection() {
|
||||
const redisUrl = new URL(process.env.REDIS_URL ?? 'redis://127.0.0.1:6379');
|
||||
return {
|
||||
host: redisUrl.hostname,
|
||||
port: Number(redisUrl.port || 6379),
|
||||
username: redisUrl.username || undefined,
|
||||
password: redisUrl.password || undefined,
|
||||
maxRetriesPerRequest: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function getPositiveIntegerEnv(name: string, fallback: number) {
|
||||
const value = Number(process.env[name]);
|
||||
if (Number.isInteger(value) && value > 0) {
|
||||
return value;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function parseReceiptContent(content: string, delimiter?: ',' | '\t') {
|
||||
const lines = content.replace(/^\uFEFF/, '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
||||
if (lines.length === 0) {
|
||||
throw new BadRequestException('Receipt file is empty');
|
||||
}
|
||||
const separator = delimiter ?? (lines[0].includes('\t') ? '\t' : ',');
|
||||
const firstCells = splitReceiptLine(lines[0], separator);
|
||||
const hasHeader = firstCells.some((cell) => ['phone', 'mobile', 'status', 'result', '手机号', '号码', '状态', '结果'].includes(cell.toLowerCase()));
|
||||
const header = hasHeader ? firstCells : [];
|
||||
const rows = hasHeader ? lines.slice(1) : lines;
|
||||
const statusIndex = findReceiptStatusIndex(header);
|
||||
let successCount = 0;
|
||||
let failedCount = 0;
|
||||
const resultRows = rows.map((line, index) => {
|
||||
const cells = splitReceiptLine(line, separator);
|
||||
const rawStatus = cells[statusIndex] ?? cells[cells.length - 1] ?? '';
|
||||
const normalizedStatus = normalizeReceiptStatus(rawStatus);
|
||||
if (normalizedStatus === 'success') {
|
||||
successCount += 1;
|
||||
} else {
|
||||
failedCount += 1;
|
||||
}
|
||||
return {
|
||||
rowNumber: (hasHeader ? index + 2 : index + 1),
|
||||
phone: cells[0] ?? '',
|
||||
status: normalizedStatus,
|
||||
rawStatus,
|
||||
raw: cells,
|
||||
};
|
||||
});
|
||||
return {
|
||||
rowCount: resultRows.length,
|
||||
successCount,
|
||||
failedCount,
|
||||
result: {
|
||||
delimiter: separator === '\t' ? 'tab' : 'comma',
|
||||
hasHeader,
|
||||
rows: resultRows,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function splitReceiptLine(line: string, delimiter: ',' | '\t') {
|
||||
if (delimiter === '\t') {
|
||||
return line.split('\t').map((cell) => stripReceiptCell(cell));
|
||||
}
|
||||
const cells: string[] = [];
|
||||
let current = '';
|
||||
let quoted = false;
|
||||
for (let index = 0; index < line.length; index += 1) {
|
||||
const char = line[index];
|
||||
const next = line[index + 1];
|
||||
if (char === '"' && quoted && next === '"') {
|
||||
current += '"';
|
||||
index += 1;
|
||||
} else if (char === '"') {
|
||||
quoted = !quoted;
|
||||
} else if (char === ',' && !quoted) {
|
||||
cells.push(stripReceiptCell(current));
|
||||
current = '';
|
||||
} else {
|
||||
current += char;
|
||||
}
|
||||
}
|
||||
cells.push(stripReceiptCell(current));
|
||||
return cells;
|
||||
}
|
||||
|
||||
export function stripReceiptCell(value: string) {
|
||||
return value.trim().replace(/^"|"$/g, '').trim();
|
||||
}
|
||||
|
||||
export function findReceiptStatusIndex(header: string[]) {
|
||||
if (header.length === 0) {
|
||||
return 1;
|
||||
}
|
||||
const index = header.findIndex((cell) => ['status', 'result', '状态', '结果'].includes(cell.toLowerCase()));
|
||||
return index >= 0 ? index : Math.max(0, header.length - 1);
|
||||
}
|
||||
|
||||
export function normalizeReceiptStatus(value: string) {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (['success', 'succeeded', 'approved', 'completed', 'ok', 'pass', 'passed', '通过', '成功', '已完成', '报备成功'].includes(normalized)) {
|
||||
return 'success';
|
||||
}
|
||||
if (['failed', 'fail', 'rejected', 'reject', 'error', 'no', 'denied', '驳回', '失败', '不通过', '拒绝', '报备失败'].includes(normalized)) {
|
||||
return 'failed';
|
||||
}
|
||||
return 'failed';
|
||||
}
|
||||
|
||||
export function deriveReceiptStatus(rowCount: number, successCount: number, failedCount: number) {
|
||||
if (rowCount <= 0 || successCount <= 0) {
|
||||
return 'failed';
|
||||
}
|
||||
if (failedCount > 0) {
|
||||
return 'partial';
|
||||
}
|
||||
return 'completed';
|
||||
}
|
||||
|
||||
export type ChannelReportDeliveryRow = {
|
||||
channelId: string;
|
||||
signatureId: string;
|
||||
drainageInfoId: string | null;
|
||||
total: number;
|
||||
acceptedCount: number;
|
||||
submitFailureCount: number;
|
||||
successCount: number;
|
||||
unknownCount: number;
|
||||
failureCount: number;
|
||||
lastSuccessfulSentAt: Date | null;
|
||||
};
|
||||
|
||||
export function summarizeChannelReportDelivery(rows: ChannelReportDeliveryRow[]) {
|
||||
const total = sumReportDelivery(rows, 'total');
|
||||
const acceptedCount = sumReportDelivery(rows, 'acceptedCount');
|
||||
const submitFailureCount = sumReportDelivery(rows, 'submitFailureCount');
|
||||
const successCount = sumReportDelivery(rows, 'successCount');
|
||||
const unknownCount = sumReportDelivery(rows, 'unknownCount');
|
||||
const failureCount = sumReportDelivery(rows, 'failureCount');
|
||||
return {
|
||||
total,
|
||||
acceptedCount,
|
||||
submitFailureCount,
|
||||
submitFailureRate: percentage(submitFailureCount, total),
|
||||
successCount,
|
||||
successRate: percentage(successCount, acceptedCount),
|
||||
unknownCount,
|
||||
unknownRate: percentage(unknownCount, acceptedCount),
|
||||
failureCount,
|
||||
failureRate: percentage(failureCount, acceptedCount),
|
||||
};
|
||||
}
|
||||
|
||||
export function sumReportDelivery(rows: ChannelReportDeliveryRow[], key: keyof Pick<
|
||||
ChannelReportDeliveryRow,
|
||||
'total' | 'acceptedCount' | 'submitFailureCount' | 'successCount' | 'unknownCount' | 'failureCount'
|
||||
>) {
|
||||
return rows.reduce((total, row) => total + Number(row[key] ?? 0), 0);
|
||||
}
|
||||
|
||||
export function percentage(count: number, total: number) {
|
||||
return total > 0 ? Number(((count * 100) / total).toFixed(1)) : 0;
|
||||
}
|
||||
|
||||
export function latestDate(values: Array<Date | null>) {
|
||||
const timestamps = values.filter((value): value is Date => Boolean(value)).map((value) => value.getTime());
|
||||
return timestamps.length > 0 ? new Date(Math.max(...timestamps)) : null;
|
||||
}
|
||||
|
||||
export function currentShanghaiDayRange(now = new Date()) {
|
||||
const shifted = new Date(now.getTime() + 8 * 60 * 60 * 1_000);
|
||||
const localDate = shifted.toISOString().slice(0, 10);
|
||||
const startAt = new Date(`${localDate}T00:00:00+08:00`);
|
||||
return { startAt, endAt: new Date(startAt.getTime() + 24 * 60 * 60 * 1_000) };
|
||||
}
|
||||
|
||||
export function normalizeRetryTimeLimitMinutes(minutes: number | undefined, hours: number | undefined, fallbackMinutes: number) {
|
||||
const value = minutes ?? (hours === undefined ? fallbackMinutes : hours * 60);
|
||||
if (!Number.isInteger(value) || value <= 0 || value > 72 * 60) {
|
||||
throw new BadRequestException('retryTimeLimitMinutes must be an integer between 1 and 4320');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function normalizeSpreadsheetSize(value: number | undefined, fallback: number, minimum: number, maximum: number) {
|
||||
if (value === undefined || !Number.isFinite(value)) return fallback;
|
||||
return Math.min(maximum, Math.max(minimum, Math.round(value)));
|
||||
}
|
||||
|
||||
export function normalizeBusinessCarrier(carrier?: string | null) {
|
||||
const normalized = normalizeChannelCarrier(carrier);
|
||||
if (!['mobile', 'unicom', 'telecom'].includes(normalized)) {
|
||||
throw new BadRequestException('carrier must be mobile, unicom, or telecom');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function normalizeChannelCarrier(carrier?: string | null) {
|
||||
const value = String(carrier ?? '').trim().toLowerCase();
|
||||
if (['mobile', 'cmcc', '移动', '中国移动'].includes(value)) return 'mobile';
|
||||
if (['unicom', 'cucc', '联通', '中国联通'].includes(value)) return 'unicom';
|
||||
if (['telecom', 'ctcc', '电信', '中国电信'].includes(value)) return 'telecom';
|
||||
if (['all', 'tri', '三网', '全网'].includes(value)) return 'all';
|
||||
return value;
|
||||
}
|
||||
|
||||
export function isChannelCarrierCompatible(channelCarrier: string | null | undefined, groupCarrier: string) {
|
||||
const normalized = normalizeChannelCarrier(channelCarrier);
|
||||
return normalized === 'all' || normalized === groupCarrier;
|
||||
}
|
||||
|
||||
export function normalizeRegion(region?: string | null) {
|
||||
return String(region ?? '').replace(/省|市|自治区|壮族|回族|维吾尔/g, '').trim();
|
||||
}
|
||||
|
||||
export function isRegionCompatible(channelRegion: string | null | undefined, itemProvince: string) {
|
||||
return normalizeRegion(channelRegion) === normalizeRegion(itemProvince);
|
||||
}
|
||||
|
||||
export function validateGroupItems(
|
||||
groupCarrier: string,
|
||||
items: Array<Omit<CreateChannelGroupItemDto, 'groupId'>>,
|
||||
channels: Map<string, { id: string; carrier?: string | null; sendRegion?: string | null }>,
|
||||
) {
|
||||
const channelIds = new Set<string>();
|
||||
const provinces = new Set<string>();
|
||||
const nationalPriorities = new Set<number>();
|
||||
for (const item of items) {
|
||||
const itemCarrier = item.carrier ? normalizeBusinessCarrier(item.carrier) : groupCarrier;
|
||||
if (itemCarrier !== groupCarrier) {
|
||||
throw new BadRequestException('Channel group items must use the same carrier as the channel group');
|
||||
}
|
||||
const channel = channels.get(item.channelId);
|
||||
if (!channel) {
|
||||
throw new NotFoundException('Channel not found');
|
||||
}
|
||||
if (channelIds.has(item.channelId)) {
|
||||
throw new BadRequestException('通道组内不能重复配置同一通道');
|
||||
}
|
||||
channelIds.add(item.channelId);
|
||||
if (!isChannelCarrierCompatible(channel.carrier, groupCarrier)) {
|
||||
throw new BadRequestException('Channel carrier is not compatible with the channel group carrier');
|
||||
}
|
||||
if (item.province) {
|
||||
const province = normalizeRegion(item.province);
|
||||
if (provinces.has(province)) {
|
||||
throw new BadRequestException('同一通道组内同一省份只能配置一个通道');
|
||||
}
|
||||
provinces.add(province);
|
||||
if (!isRegionCompatible(channel.sendRegion, item.province)) {
|
||||
throw new BadRequestException('Province route must use a channel with the same sendRegion');
|
||||
}
|
||||
} else {
|
||||
const priority = item.priority ?? 100;
|
||||
if (nationalPriorities.has(priority)) {
|
||||
throw new BadRequestException('同一通道组内全国通道优先级不能重复');
|
||||
}
|
||||
nationalPriorities.add(priority);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeReportType(value?: string) {
|
||||
if (value === 'signature' || value === 'drainage' || value === 'both') return value;
|
||||
throw new BadRequestException('reportType must be signature, drainage or both');
|
||||
}
|
||||
|
||||
export function summarizeReportStatuses(statuses: string[]) {
|
||||
if (!statuses.length) return { status: 'not_applicable', approved: 0, total: 0 };
|
||||
const approved = statuses.filter((status) => status === 'approved').length;
|
||||
let status = 'pending';
|
||||
if (approved === statuses.length) status = 'approved';
|
||||
else if (statuses.some((item) => ['failed', 'rejected'].includes(item))) status = 'failed';
|
||||
else if (statuses.some((item) => ['reporting', 'exporting', 'partial', 'partial_success'].includes(item)) || approved > 0) status = 'reporting';
|
||||
else if (statuses.some((item) => item === 'waiting_material')) status = 'waiting_material';
|
||||
return { status, approved, total: statuses.length };
|
||||
}
|
||||
|
||||
export function normalizeLinkEvent(action: string) {
|
||||
if (action.includes('connect_requested')) {
|
||||
return '连接请求';
|
||||
}
|
||||
if (action.includes('connected')) {
|
||||
return '连接成功';
|
||||
}
|
||||
if (action.includes('heartbeat')) {
|
||||
return '心跳';
|
||||
}
|
||||
if (action.includes('reconnecting')) {
|
||||
return '重连';
|
||||
}
|
||||
if (action.includes('disconnected')) {
|
||||
return '断开';
|
||||
}
|
||||
if (action.includes('failed')) {
|
||||
return '连接失败';
|
||||
}
|
||||
if (action.includes('copy')) {
|
||||
return '复制';
|
||||
}
|
||||
if (action.includes('deleted')) {
|
||||
return '删除';
|
||||
}
|
||||
return '更新';
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,87 @@
|
||||
// Stable controller/query contracts extracted in R2.
|
||||
|
||||
export interface MessageQuery {
|
||||
tenantId?: string;
|
||||
applicationId?: string;
|
||||
channelId?: string;
|
||||
channelKeyword?: string;
|
||||
taskId?: string;
|
||||
messageId?: string;
|
||||
phoneNumber?: string;
|
||||
contentKeyword?: string;
|
||||
carrier?: string;
|
||||
status?: string;
|
||||
queuedAtFrom?: string;
|
||||
queuedAtTo?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface TraceQuery extends MessageQuery {
|
||||
messageId?: string;
|
||||
}
|
||||
|
||||
export interface OperationLogQuery {
|
||||
tenantId?: string;
|
||||
userId?: string;
|
||||
keyword?: string;
|
||||
level?: string;
|
||||
module?: string;
|
||||
range?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface GatewaySubmitDeadLetterQuery {
|
||||
tenantId?: string;
|
||||
applicationId?: string;
|
||||
channelId?: string;
|
||||
status?: string;
|
||||
keyword?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface DownstreamDeliveryQuery {
|
||||
tenantId?: string;
|
||||
applicationId?: string;
|
||||
deliveryType?: string;
|
||||
status?: string;
|
||||
keyword?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
createdAtFrom?: string;
|
||||
createdAtTo?: string;
|
||||
}
|
||||
|
||||
export interface DownstreamDeliveryDashboardQuery {
|
||||
tenantId?: string;
|
||||
applicationId?: string;
|
||||
deliveryType?: string;
|
||||
createdAtFrom?: string;
|
||||
createdAtTo?: string;
|
||||
}
|
||||
|
||||
export interface DownstreamRecoveryStatusQuery {
|
||||
tenantId?: string;
|
||||
applicationId?: string;
|
||||
state?: string;
|
||||
failureCategory?: string;
|
||||
keyword?: string;
|
||||
updatedAtFrom?: string;
|
||||
updatedAtTo?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface MessageSegmentAuditQuery {
|
||||
messageId?: string;
|
||||
messageRecordId?: string;
|
||||
}
|
||||
|
||||
export interface SignatureQualityQuery {
|
||||
date?: string;
|
||||
keyword?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import type { MessageQuery, TraceQuery, OperationLogQuery, GatewaySubmitDeadLetterQuery, DownstreamDeliveryQuery, DownstreamDeliveryDashboardQuery, DownstreamRecoveryStatusQuery, MessageSegmentAuditQuery, SignatureQualityQuery } from './operations.contracts';
|
||||
|
||||
// Pure query builders and response mappers shared by the R2 query domains.
|
||||
export function messageWhere(query: MessageQuery): Prisma.SmsMessageRecordWhereInput {
|
||||
const statusWhere = query.status === 'submit_failed'
|
||||
? { OR: [{ status: 'submit_failed' }, { submitStatus: { in: ['rejected', 'timeout'] } }] }
|
||||
: query.status === 'failed'
|
||||
? { status: 'failed', submitStatus: 'accepted' }
|
||||
: query.status
|
||||
? { status: query.status }
|
||||
: {};
|
||||
return {
|
||||
tenantId: query.tenantId,
|
||||
applicationId: query.applicationId,
|
||||
channelId: query.channelId,
|
||||
batchTaskId: query.taskId,
|
||||
messageId: query.messageId,
|
||||
phoneNumber: query.phoneNumber,
|
||||
...carrierWhere(query.carrier),
|
||||
...statusWhere,
|
||||
...(query.contentKeyword ? { content: { contains: query.contentKeyword, mode: 'insensitive' } } : {}),
|
||||
...(query.channelKeyword ? { channel: { name: { contains: query.channelKeyword, mode: 'insensitive' } } } : {}),
|
||||
...(query.queuedAtFrom || query.queuedAtTo ? {
|
||||
queuedAt: {
|
||||
...(query.queuedAtFrom ? { gte: startOfShanghaiDay(query.queuedAtFrom) } : {}),
|
||||
...(query.queuedAtTo ? { lte: endOfShanghaiDay(query.queuedAtTo) } : {}),
|
||||
},
|
||||
} : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export const recognizedCarrierValues = [
|
||||
'mobile', 'cmcc', '移动', '中国移动',
|
||||
'unicom', 'cucc', '联通', '中国联通',
|
||||
'telecom', 'ctcc', '电信', '中国电信',
|
||||
];
|
||||
export function carrierWhere(carrier?: string): Prisma.SmsMessageRecordWhereInput {
|
||||
if (!carrier) return {};
|
||||
// Keep historical aliases queryable while treating null and future/nonstandard values as unrecognized.
|
||||
if (carrier === 'unknown') {
|
||||
return {
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
{ carrier: null },
|
||||
{ carrier: { notIn: recognizedCarrierValues } },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
const valuesByCarrier: Record<string, string[]> = {
|
||||
mobile: ['mobile', 'cmcc', '移动', '中国移动'],
|
||||
unicom: ['unicom', 'cucc', '联通', '中国联通'],
|
||||
telecom: ['telecom', 'ctcc', '电信', '中国电信'],
|
||||
};
|
||||
return valuesByCarrier[carrier] ? { carrier: { in: valuesByCarrier[carrier] } } : {};
|
||||
}
|
||||
export function startOfShanghaiDay(value: string) {
|
||||
return new Date(`${value}T00:00:00+08:00`);
|
||||
}
|
||||
export function endOfShanghaiDay(value: string) {
|
||||
return new Date(`${value}T23:59:59.999+08:00`);
|
||||
}
|
||||
export function qualityBusinessDay(value?: string) {
|
||||
const key = value || shanghaiDateKey();
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(key)) {
|
||||
throw new BadRequestException('统计日期格式必须为 YYYY-MM-DD');
|
||||
}
|
||||
const startAt = startOfShanghaiDay(key);
|
||||
if (Number.isNaN(startAt.getTime()) || shanghaiDateKey(startAt) !== key) {
|
||||
throw new BadRequestException('统计日期无效');
|
||||
}
|
||||
return {
|
||||
key,
|
||||
startAt,
|
||||
endAt: new Date(startAt.getTime() + 24 * 60 * 60 * 1000),
|
||||
};
|
||||
}
|
||||
export function shanghaiDateKey(value = new Date()) {
|
||||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
}).formatToParts(value);
|
||||
const byType = new Map(parts.map((part) => [part.type, part.value]));
|
||||
return `${byType.get('year')}-${byType.get('month')}-${byType.get('day')}`;
|
||||
}
|
||||
export function normalizeGroupBy(groupBy?: string) {
|
||||
if (groupBy === 'tenant' || groupBy === 'tenantId') {
|
||||
return 'tenantId';
|
||||
}
|
||||
if (groupBy === 'application' || groupBy === 'applicationId') {
|
||||
return 'applicationId';
|
||||
}
|
||||
return 'channelId';
|
||||
}
|
||||
export function returnedTransactionWhere(since: Date, tenantId?: string): Prisma.AccountTransactionWhereInput {
|
||||
return {
|
||||
tenantId,
|
||||
createdAt: { gte: since },
|
||||
OR: [
|
||||
{ transactionType: 'refunded' },
|
||||
{ transactionType: 'released', relatedType: 'sms_message_record' },
|
||||
],
|
||||
};
|
||||
}
|
||||
export function createdAtRange(range?: string): Prisma.DateTimeFilter | undefined {
|
||||
if (!range || range === 'all') {
|
||||
return undefined;
|
||||
}
|
||||
const date = new Date();
|
||||
date.setHours(0, 0, 0, 0);
|
||||
if (range === '7d') {
|
||||
date.setDate(date.getDate() - 6);
|
||||
} else if (range === '30d') {
|
||||
date.setDate(date.getDate() - 29);
|
||||
}
|
||||
return { gte: date };
|
||||
}
|
||||
export function downstreamAlertPendingMinutes() {
|
||||
const value = Number(process.env.CMPP_DOWNSTREAM_ALERT_PENDING_MINUTES ?? 10);
|
||||
return Number.isFinite(value) && value > 0 ? value : 10;
|
||||
}
|
||||
export function downstreamAlertRecentFailedHours() {
|
||||
const value = Number(process.env.CMPP_DOWNSTREAM_ALERT_RECENT_FAILED_HOURS ?? 1);
|
||||
return Number.isFinite(value) && value > 0 ? value : 1;
|
||||
}
|
||||
export function downstreamAlertWindows(now = new Date()) {
|
||||
return {
|
||||
now,
|
||||
stalledPendingAt: new Date(now.getTime() - downstreamAlertPendingMinutes() * 60_000),
|
||||
recentFailedAt: new Date(now.getTime() - downstreamAlertRecentFailedHours() * 60 * 60_000),
|
||||
};
|
||||
}
|
||||
export function downstreamAlertWhere(
|
||||
scopedWhere: Prisma.CmppDownstreamDeliveryWhereInput,
|
||||
window: ReturnType<typeof downstreamAlertWindows>,
|
||||
): Prisma.CmppDownstreamDeliveryWhereInput {
|
||||
return {
|
||||
AND: [
|
||||
scopedWhere,
|
||||
{
|
||||
OR: [
|
||||
stalledPendingWhere(window.stalledPendingAt),
|
||||
{ status: 'awaiting_ack', ackDeadlineAt: { lte: window.now } },
|
||||
{ status: { in: ['failed', 'unconfirmed', 'rejected'] }, updatedAt: { gte: window.recentFailedAt } },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
export function stalledPendingWhere(cutoff: Date): Prisma.CmppDownstreamDeliveryWhereInput {
|
||||
return {
|
||||
status: 'pending',
|
||||
OR: [
|
||||
{ lastRetriedAt: null, createdAt: { lte: cutoff } },
|
||||
{ lastRetriedAt: { lte: cutoff } },
|
||||
],
|
||||
};
|
||||
}
|
||||
export function downstreamDeliveryScopedWhere(query: DownstreamDeliveryDashboardQuery): Prisma.CmppDownstreamDeliveryWhereInput {
|
||||
const createdAtFrom = parseDateBoundary(query.createdAtFrom, false);
|
||||
const createdAtTo = parseDateBoundary(query.createdAtTo, true);
|
||||
return {
|
||||
tenantId: query.tenantId,
|
||||
applicationId: query.applicationId,
|
||||
deliveryType: query.deliveryType && query.deliveryType !== 'all' ? query.deliveryType : undefined,
|
||||
createdAt: createdAtFrom || createdAtTo ? { gte: createdAtFrom, lte: createdAtTo } : undefined,
|
||||
};
|
||||
}
|
||||
export function parseDateBoundary(value?: string, endOfDay = false) {
|
||||
if (!value) return undefined;
|
||||
const parsed = new Date(`${value}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}+08:00`);
|
||||
return Number.isNaN(parsed.getTime()) ? undefined : parsed;
|
||||
}
|
||||
export function downstreamRecoveryStatusWhere(query: DownstreamRecoveryStatusQuery) {
|
||||
const updatedAtFrom = parseDateBoundary(query.updatedAtFrom, false);
|
||||
const updatedAtTo = parseDateBoundary(query.updatedAtTo, true);
|
||||
return {
|
||||
tenantId: query.tenantId,
|
||||
applicationId: query.applicationId,
|
||||
state: query.state && query.state !== 'all' ? query.state : undefined,
|
||||
failureCategory: query.failureCategory && query.failureCategory !== 'all' ? query.failureCategory : undefined,
|
||||
updatedAt: updatedAtFrom || updatedAtTo ? { gte: updatedAtFrom, lte: updatedAtTo } : undefined,
|
||||
OR: query.keyword ? [
|
||||
{ account: { contains: query.keyword } },
|
||||
{ gatewayInstanceId: { contains: query.keyword } },
|
||||
{ lastError: { contains: query.keyword } },
|
||||
{ lastSkipReason: { contains: query.keyword } },
|
||||
{ tenant: { name: { contains: query.keyword } } },
|
||||
{ application: { name: { contains: query.keyword } } },
|
||||
] : undefined,
|
||||
};
|
||||
}
|
||||
export function escapeCsvCell(value: string) {
|
||||
let normalized = value.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
||||
if (/^[=+\-@]/.test(normalized)) {
|
||||
normalized = `'${normalized}`;
|
||||
}
|
||||
if (normalized.includes(',') || normalized.includes('"') || normalized.includes('\n')) {
|
||||
return `"${normalized.replace(/"/g, '""')}"`;
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
export function formatCsvDate(value?: Date | string | null) {
|
||||
if (!value) {
|
||||
return '';
|
||||
}
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
}
|
||||
export function formatExportTimestamp(date: Date) {
|
||||
const parts = [
|
||||
date.getFullYear(),
|
||||
String(date.getMonth() + 1).padStart(2, '0'),
|
||||
String(date.getDate()).padStart(2, '0'),
|
||||
String(date.getHours()).padStart(2, '0'),
|
||||
String(date.getMinutes()).padStart(2, '0'),
|
||||
String(date.getSeconds()).padStart(2, '0'),
|
||||
];
|
||||
return `${parts[0]}${parts[1]}${parts[2]}-${parts[3]}${parts[4]}${parts[5]}`;
|
||||
}
|
||||
export function clientApplicationView(application?: Record<string, any> | null) {
|
||||
if (!application) return null;
|
||||
return { id: application.id, name: application.name };
|
||||
}
|
||||
export function clientReceiptView(receipt: Record<string, any>) {
|
||||
return {
|
||||
id: receipt.id,
|
||||
messageId: receipt.messageId,
|
||||
receiptStatus: receipt.receiptStatus,
|
||||
rawStatus: receipt.rawStatus,
|
||||
errorCode: receipt.errorCode ?? null,
|
||||
errorMessage: receipt.errorMessage ?? null,
|
||||
deliveredAt: receipt.deliveredAt,
|
||||
createdAt: receipt.createdAt,
|
||||
};
|
||||
}
|
||||
export function clientMessageView(message: Record<string, any>) {
|
||||
return {
|
||||
id: message.id,
|
||||
batchTaskId: message.batchTaskId ?? null,
|
||||
applicationId: message.applicationId ?? null,
|
||||
messageId: message.messageId,
|
||||
phoneNumber: message.phoneNumber,
|
||||
carrier: message.carrier ?? null,
|
||||
province: message.province ?? null,
|
||||
content: message.content,
|
||||
billingUnits: message.billingUnits,
|
||||
amountCents: moneyToNumber(message.amountCents),
|
||||
status: message.status,
|
||||
submitStatus: message.submitStatus ?? null,
|
||||
receiptStatus: message.receiptStatus ?? null,
|
||||
errorCode: message.errorCode ?? null,
|
||||
errorMessage: message.errorMessage ?? null,
|
||||
queuedAt: message.queuedAt,
|
||||
submittedAt: message.submittedAt ?? null,
|
||||
deliveredAt: message.deliveredAt ?? null,
|
||||
application: clientApplicationView(message.application),
|
||||
receiptRecords: Array.isArray(message.receiptRecords) ? message.receiptRecords.map(clientReceiptView) : [],
|
||||
};
|
||||
}
|
||||
export function clientBatchTaskView(task: Record<string, any>) {
|
||||
return {
|
||||
id: task.id,
|
||||
taskNo: task.taskNo,
|
||||
applicationId: task.applicationId ?? null,
|
||||
templateId: task.templateId ?? null,
|
||||
content: task.content,
|
||||
category: task.category ?? null,
|
||||
phoneTotal: task.phoneTotal,
|
||||
status: task.status,
|
||||
auditStatus: task.auditStatus ?? null,
|
||||
reviewReason: task.reviewReason ?? null,
|
||||
rejectReason: task.rejectReason ?? null,
|
||||
progressTotal: task.progressTotal,
|
||||
progressSent: task.progressSent ?? 0,
|
||||
progressDelivered: task.progressDelivered ?? 0,
|
||||
progressFailed: task.progressFailed ?? 0,
|
||||
submittedTotal: task.submittedTotal ?? 0,
|
||||
successTotal: task.successTotal ?? 0,
|
||||
failedTotal: task.failedTotal ?? 0,
|
||||
unknownTotal: task.unknownTotal ?? 0,
|
||||
timeoutTotal: task.timeoutTotal ?? 0,
|
||||
scheduledAt: task.scheduledAt ?? null,
|
||||
canceledAt: task.canceledAt ?? null,
|
||||
createdAt: task.createdAt,
|
||||
application: clientApplicationView(task.application),
|
||||
messages: Array.isArray(task.messages) ? task.messages.map(clientMessageView) : [],
|
||||
};
|
||||
}
|
||||
export function clientUplinkView(message: Record<string, any>) {
|
||||
return {
|
||||
id: message.id,
|
||||
applicationId: message.applicationId ?? null,
|
||||
messageRecordId: message.messageRecordId ?? null,
|
||||
messageId: message.messageId ?? null,
|
||||
phoneNumber: message.phoneNumber,
|
||||
destId: message.destId,
|
||||
content: message.content,
|
||||
matchStatus: message.matchStatus,
|
||||
matchReason: message.matchReason ?? null,
|
||||
receivedAt: message.receivedAt,
|
||||
createdAt: message.createdAt,
|
||||
application: clientApplicationView(message.application),
|
||||
messageRecord: message.messageRecord ? clientMessageView(message.messageRecord) : null,
|
||||
};
|
||||
}
|
||||
export function clientAccountView(account: Record<string, any>) {
|
||||
return {
|
||||
id: account.id,
|
||||
tenantId: account.tenantId,
|
||||
balanceCents: moneyToNumber(account.balanceCents),
|
||||
creditCents: moneyToNumber(account.creditCents),
|
||||
status: account.status,
|
||||
updatedAt: account.updatedAt,
|
||||
tenant: account.tenant ? { id: account.tenant.id, name: account.tenant.name, status: account.tenant.status } : null,
|
||||
};
|
||||
}
|
||||
export function clientRechargeView(order: Record<string, any>) {
|
||||
return {
|
||||
id: order.id,
|
||||
orderNo: order.orderNo,
|
||||
amountCents: moneyToNumber(order.amountCents),
|
||||
status: order.status,
|
||||
payMethod: order.payMethod,
|
||||
remark: order.remark ?? null,
|
||||
createdAt: order.createdAt,
|
||||
completedAt: order.completedAt ?? null,
|
||||
};
|
||||
}
|
||||
export function summarizeMessageGroups(groups: Array<{ status: string; _count: { _all: number }; _sum: { amountCents: number | bigint | null; billingUnits: number | null } }>) {
|
||||
return groups.reduce(
|
||||
(summary, group) => {
|
||||
const count = group._count._all;
|
||||
summary.total += count;
|
||||
summary.amountCents += moneyToNumber(group._sum.amountCents);
|
||||
summary.billingUnits += group._sum.billingUnits ?? 0;
|
||||
if (group.status === 'delivered') {
|
||||
summary.delivered += count;
|
||||
} else if (['undelivered', 'submit_failed', 'timeout', 'failed', 'rejected'].includes(group.status)) {
|
||||
summary.failed += count;
|
||||
} else if (group.status === 'unknown') {
|
||||
summary.unknown += count;
|
||||
}
|
||||
return summary;
|
||||
},
|
||||
{ total: 0, delivered: 0, failed: 0, unknown: 0, amountCents: 0, billingUnits: 0 },
|
||||
);
|
||||
}
|
||||
export function groupDownstreamByType(
|
||||
groups: Array<{ deliveryType: string; status: string; _count: { _all: number } }>,
|
||||
) {
|
||||
return groups.reduce<Record<string, { total: number; pending: number; awaitingAck: number; delivered: number; failed: number; unconfirmed: number; rejected: number }>>((accumulator, item) => {
|
||||
const current = accumulator[item.deliveryType] ?? { total: 0, pending: 0, awaitingAck: 0, delivered: 0, failed: 0, unconfirmed: 0, rejected: 0 };
|
||||
current.total += item._count._all;
|
||||
if (item.status === 'pending') {
|
||||
current.pending += item._count._all;
|
||||
} else if (item.status === 'awaiting_ack') {
|
||||
current.awaitingAck += item._count._all;
|
||||
} else if (item.status === 'delivered') {
|
||||
current.delivered += item._count._all;
|
||||
} else if (item.status === 'failed') {
|
||||
current.failed += item._count._all;
|
||||
} else if (item.status === 'unconfirmed') {
|
||||
current.unconfirmed += item._count._all;
|
||||
} else if (item.status === 'rejected') {
|
||||
current.rejected += item._count._all;
|
||||
}
|
||||
accumulator[item.deliveryType] = current;
|
||||
return accumulator;
|
||||
}, {});
|
||||
}
|
||||
export function groupDownstreamByApplication(
|
||||
groups: Array<{ applicationId: string; status: string; _count: { _all: number } }>,
|
||||
applicationMap: Map<string, string>,
|
||||
applicationAlertMap: Map<string, number>,
|
||||
) {
|
||||
const summaryMap = new Map<string, { applicationId: string; name: string; pending: number; awaitingAck: number; failed: number; unconfirmed: number; rejected: number; delivered: number; alertCount: number }>();
|
||||
groups.forEach((item) => {
|
||||
const current = summaryMap.get(item.applicationId) ?? {
|
||||
applicationId: item.applicationId,
|
||||
name: applicationMap.get(item.applicationId) ?? item.applicationId,
|
||||
pending: 0,
|
||||
awaitingAck: 0,
|
||||
failed: 0,
|
||||
unconfirmed: 0,
|
||||
rejected: 0,
|
||||
delivered: 0,
|
||||
alertCount: 0,
|
||||
};
|
||||
if (item.status === 'pending') {
|
||||
current.pending += item._count._all;
|
||||
} else if (item.status === 'awaiting_ack') {
|
||||
current.awaitingAck += item._count._all;
|
||||
} else if (item.status === 'failed') {
|
||||
current.failed += item._count._all;
|
||||
} else if (item.status === 'unconfirmed') {
|
||||
current.unconfirmed += item._count._all;
|
||||
} else if (item.status === 'rejected') {
|
||||
current.rejected += item._count._all;
|
||||
} else if (item.status === 'delivered') {
|
||||
current.delivered += item._count._all;
|
||||
}
|
||||
current.alertCount = applicationAlertMap.get(item.applicationId) ?? 0;
|
||||
summaryMap.set(item.applicationId, current);
|
||||
});
|
||||
return [...summaryMap.values()];
|
||||
}
|
||||
export function positiveInteger(value: number | undefined, fallback: number) {
|
||||
const normalized = Number(value);
|
||||
return Number.isInteger(normalized) && normalized > 0 ? normalized : fallback;
|
||||
}
|
||||
export function operationLogLevelWhere(level: string): Prisma.OperationLogWhereInput {
|
||||
const error: Prisma.OperationLogWhereInput = {
|
||||
OR: [
|
||||
{ action: { contains: 'failed' } },
|
||||
{ action: { contains: 'reject' } },
|
||||
{ detail: { path: ['result'], string_contains: 'fail' } },
|
||||
{ detail: { path: ['status'], string_contains: 'fail' } },
|
||||
],
|
||||
};
|
||||
const warning: Prisma.OperationLogWhereInput = {
|
||||
OR: [
|
||||
{ action: { contains: 'warning' } },
|
||||
{ action: { contains: 'risk' } },
|
||||
],
|
||||
};
|
||||
const success: Prisma.OperationLogWhereInput = {
|
||||
OR: [
|
||||
{ action: { contains: 'approve' } },
|
||||
{ action: { contains: 'recharge' } },
|
||||
{ action: { contains: 'connected' } },
|
||||
],
|
||||
};
|
||||
if (level === 'error') {
|
||||
return error;
|
||||
}
|
||||
if (level === 'warning') {
|
||||
return { AND: [{ NOT: error }, warning] };
|
||||
}
|
||||
if (level === 'success') {
|
||||
return { AND: [{ NOT: error }, { NOT: warning }, success] };
|
||||
}
|
||||
if (level === 'info') {
|
||||
return { NOT: { OR: [error, warning, success] } };
|
||||
}
|
||||
return {};
|
||||
}
|
||||
export function normalizeOperationLog(log: Prisma.OperationLogGetPayload<{ include: { tenant: true; user: true } }>) {
|
||||
const detail = (log.detail ?? {}) as Record<string, unknown>;
|
||||
const result = String(detail.result ?? detail.status ?? '');
|
||||
const level = result.includes('fail') || log.action.includes('failed') || log.action.includes('reject')
|
||||
? 'error'
|
||||
: log.action.includes('warning') || log.action.includes('risk')
|
||||
? 'warning'
|
||||
: log.action.includes('approve') || log.action.includes('recharge') || log.action.includes('connected')
|
||||
? 'success'
|
||||
: 'info';
|
||||
return {
|
||||
id: log.id,
|
||||
time: log.createdAt,
|
||||
level,
|
||||
tenant: log.tenant?.name ?? (log.tenantId ? log.tenantId : '平台'),
|
||||
module: log.resource,
|
||||
operator: log.user?.displayName ?? log.user?.username ?? log.userId ?? 'system',
|
||||
action: log.action,
|
||||
resourceId: log.resourceId ?? '',
|
||||
detail,
|
||||
ip: log.ipAddress ?? '',
|
||||
userAgent: log.userAgent ?? '',
|
||||
};
|
||||
}
|
||||
export function sanitizeGatewaySubmitException(
|
||||
item: Prisma.GatewaySubmitDeadLetterGetPayload<{ include: { tenant: true; application: true; channel: true } }>,
|
||||
messageState?: { status: string; submitStatus: string | null; receiptStatus: string | null; phoneNumber: string; content: string },
|
||||
) {
|
||||
const { rawPayload, commandPayload, tenant, application, channel, ...record } = item;
|
||||
return {
|
||||
...record,
|
||||
tenant: tenant ? { id: tenant.id, name: tenant.name, code: tenant.code, status: tenant.status } : null,
|
||||
application: application ? { id: application.id, tenantId: application.tenantId, name: application.name, status: application.status } : null,
|
||||
channel: channel ? {
|
||||
id: channel.id,
|
||||
code: channel.code,
|
||||
name: channel.name,
|
||||
status: channel.status,
|
||||
carrier: channel.carrier,
|
||||
sendRegion: channel.sendRegion,
|
||||
rateLimitPerSecond: channel.rateLimitPerSecond,
|
||||
} : null,
|
||||
rawPayloadAvailable: Boolean(rawPayload),
|
||||
commandPayload: redactGatewayCommandValue(commandPayload),
|
||||
messageState: messageState ?? null,
|
||||
};
|
||||
}
|
||||
export function redactGatewayCommandValue(value: Prisma.JsonValue | null): Prisma.JsonValue | null {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => redactGatewayCommandValue(item));
|
||||
}
|
||||
if (value && typeof value === 'object') {
|
||||
const redacted: Record<string, Prisma.JsonValue | null> = {};
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
const normalizedKey = key.toLowerCase();
|
||||
redacted[key] = [
|
||||
'password', 'passwordcipher', 'secret', 'secrethash', 'authsource',
|
||||
'token', 'apikey', 'accesskey', 'secretkey',
|
||||
].includes(normalizedKey)
|
||||
? '[REDACTED]'
|
||||
: redactGatewayCommandValue(child as Prisma.JsonValue);
|
||||
}
|
||||
return redacted;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -6,6 +6,9 @@ function createPrismaMock() {
|
||||
user: {
|
||||
findFirst: jest.fn().mockResolvedValue({ tenantId: 'tenant-1' }),
|
||||
},
|
||||
tenant: {
|
||||
findUnique: jest.fn().mockResolvedValue({ id: 'tenant-1', name: '企业A' }),
|
||||
},
|
||||
smsBatchTask: {
|
||||
findMany: jest.fn().mockResolvedValue([{ id: 'task-1', taskNo: 'BATCH-1' }]),
|
||||
count: jest.fn().mockResolvedValue(3),
|
||||
@@ -50,6 +53,7 @@ function createPrismaMock() {
|
||||
},
|
||||
enterpriseCertification: {
|
||||
count: jest.fn().mockResolvedValue(1),
|
||||
findFirst: jest.fn().mockResolvedValue({ id: 'certification-1' }),
|
||||
},
|
||||
smsApplication: {
|
||||
findMany: jest.fn().mockResolvedValue([
|
||||
@@ -388,6 +392,22 @@ describe('OperationsService', () => {
|
||||
|
||||
expect(dashboard.gatewayConnections).toEqual([]);
|
||||
expect(dashboard.recentTasks).toEqual([expect.objectContaining({ id: 'task-1', taskNo: 'BATCH-1' })]);
|
||||
expect(dashboard.clientOverview).toEqual({
|
||||
enterpriseName: '企业A',
|
||||
certificationStatus: 'certified',
|
||||
signatureCount: 1,
|
||||
pendingBatchTaskCount: 3,
|
||||
});
|
||||
expect(prisma.smsBatchTask.count).toHaveBeenCalledWith({
|
||||
where: { tenantId: 'tenant-1', sourceType: 'client', status: 'pending_review' },
|
||||
});
|
||||
expect(prisma.enterpriseCertification.findFirst).toHaveBeenCalledWith({
|
||||
where: { tenantId: 'tenant-1', status: 'approved' },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(prisma.smsSignature.count).toHaveBeenCalledWith({
|
||||
where: { tenantId: 'tenant-1', auditStatus: { notIn: ['deleted', 'disabled'] } },
|
||||
});
|
||||
expect(JSON.stringify(dashboard)).not.toMatch(/passwordCipher|supplier|cipher|unitPrice/);
|
||||
});
|
||||
|
||||
@@ -480,6 +500,10 @@ describe('OperationsService', () => {
|
||||
updatedAt: { gte: expect.any(Date) },
|
||||
},
|
||||
});
|
||||
const hourlyTrendQuery = prisma.$queryRaw.mock.calls[1]?.[0] as { sql?: string };
|
||||
expect(hourlyTrendQuery.sql).toContain(
|
||||
`HOUR FROM (message."queuedAt" AT TIME ZONE 'UTC') AT TIME ZONE 'Asia/Shanghai'`,
|
||||
);
|
||||
expect(prisma.accountTransaction.aggregate).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: 'tenant-1',
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,377 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { moneyToNumber } from '../../common/money';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import type { MessageQuery, TraceQuery, OperationLogQuery, GatewaySubmitDeadLetterQuery, DownstreamDeliveryQuery, DownstreamDeliveryDashboardQuery, DownstreamRecoveryStatusQuery, MessageSegmentAuditQuery, SignatureQualityQuery } from '../operations.contracts';
|
||||
import { messageWhere, recognizedCarrierValues, carrierWhere, startOfShanghaiDay, endOfShanghaiDay, qualityBusinessDay, shanghaiDateKey, normalizeGroupBy, returnedTransactionWhere, createdAtRange, downstreamAlertPendingMinutes, downstreamAlertRecentFailedHours, downstreamAlertWindows, downstreamAlertWhere, stalledPendingWhere, downstreamDeliveryScopedWhere, parseDateBoundary, downstreamRecoveryStatusWhere, escapeCsvCell, formatCsvDate, formatExportTimestamp, clientApplicationView, clientReceiptView, clientMessageView, clientBatchTaskView, clientUplinkView, clientAccountView, clientRechargeView, summarizeMessageGroups, groupDownstreamByType, groupDownstreamByApplication, positiveInteger, operationLogLevelWhere, normalizeOperationLog, sanitizeGatewaySubmitException, redactGatewayCommandValue } from '../operations.helpers';
|
||||
|
||||
// R2 dashboard query domain. Method bodies are preserved byte-for-byte from the facade baseline.
|
||||
export class OperationsDashboardQueries {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async dashboard(query: { tenantId?: string }) {
|
||||
const businessDay = qualityBusinessDay();
|
||||
const sinceToday = businessDay.startAt;
|
||||
const downstreamAlertWindow = downstreamAlertWindows();
|
||||
const messageWhereClause = messageWhere({ tenantId: query.tenantId });
|
||||
const todayMessageWhereClause = {
|
||||
...messageWhereClause,
|
||||
queuedAt: { gte: sinceToday, lt: businessDay.endAt },
|
||||
};
|
||||
const [
|
||||
taskCount,
|
||||
messageGroups,
|
||||
todayMessageGroups,
|
||||
uplinkCount,
|
||||
billingAggregate,
|
||||
transactionAggregate,
|
||||
connectionGroups,
|
||||
pendingAudits,
|
||||
tenantAccounts,
|
||||
recentTasks,
|
||||
recentRecharges,
|
||||
enterpriseSpendRows,
|
||||
downstreamPendingCount,
|
||||
downstreamFailedCount,
|
||||
downstreamDeliveredCount,
|
||||
downstreamStalledPendingCount,
|
||||
downstreamStalledAckCount,
|
||||
downstreamRecentFailedCount,
|
||||
hourlySendRows,
|
||||
auditSpeedRows,
|
||||
] = await Promise.all([
|
||||
this.prisma.smsBatchTask.count({ where: { tenantId: query.tenantId } }),
|
||||
this.prisma.smsMessageRecord.groupBy({
|
||||
by: ['status'],
|
||||
where: messageWhereClause,
|
||||
_count: { _all: true },
|
||||
_sum: { amountCents: true, billingUnits: true },
|
||||
}),
|
||||
this.prisma.smsMessageRecord.groupBy({
|
||||
by: ['status'],
|
||||
where: todayMessageWhereClause,
|
||||
_count: { _all: true },
|
||||
_sum: { amountCents: true, billingUnits: true },
|
||||
}),
|
||||
this.prisma.smsUplinkMessage.count({ where: { tenantId: query.tenantId } }),
|
||||
this.prisma.smsBillingRecord.aggregate({
|
||||
where: { tenantId: query.tenantId },
|
||||
_sum: { amountCents: true, billingUnits: true },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
this.prisma.accountTransaction.aggregate({
|
||||
where: returnedTransactionWhere(sinceToday, query.tenantId),
|
||||
_sum: { amountCents: true },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
this.prisma.cmppConnectionState.groupBy({
|
||||
by: ['status'],
|
||||
where: { tenantId: query.tenantId },
|
||||
_count: { _all: true },
|
||||
_sum: { currentConnections: true, desiredConnections: true },
|
||||
}),
|
||||
this.countPendingAudits(query.tenantId),
|
||||
this.prisma.tenantAccount.findMany({
|
||||
where: query.tenantId ? { tenantId: query.tenantId } : undefined,
|
||||
include: { tenant: true },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
take: 20,
|
||||
}),
|
||||
this.prisma.smsBatchTask.findMany({
|
||||
where: query.tenantId ? { tenantId: query.tenantId } : undefined,
|
||||
include: { application: true, messages: { take: 1, include: { channel: true } } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 10,
|
||||
}),
|
||||
this.prisma.rechargeOrder.findMany({
|
||||
where: {
|
||||
tenantId: query.tenantId,
|
||||
payMethod: 'manual_topup',
|
||||
},
|
||||
include: { tenant: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 10,
|
||||
}),
|
||||
this.prisma.$queryRaw<Array<{
|
||||
tenantId: string;
|
||||
tenantName: string;
|
||||
todaySpendCents: bigint;
|
||||
balanceCents: bigint;
|
||||
creditCents: bigint;
|
||||
}>>(Prisma.sql`
|
||||
SELECT
|
||||
tenant.id AS "tenantId",
|
||||
tenant.name AS "tenantName",
|
||||
COALESCE(SUM(billing."amountCents") FILTER (WHERE billing."billingStatus" = 'charged'), 0)::bigint AS "todaySpendCents",
|
||||
account."balanceCents" AS "balanceCents",
|
||||
account."creditCents" AS "creditCents"
|
||||
FROM "TenantAccount" account
|
||||
JOIN "Tenant" tenant ON tenant.id = account."tenantId"
|
||||
LEFT JOIN "SmsBillingRecord" billing
|
||||
ON billing."tenantId" = tenant.id
|
||||
AND billing."createdAt" >= ${businessDay.startAt}
|
||||
AND billing."createdAt" < ${businessDay.endAt}
|
||||
WHERE tenant.status <> 'deleted'
|
||||
AND (${query.tenantId ?? null}::text IS NULL OR tenant.id = ${query.tenantId ?? null})
|
||||
GROUP BY tenant.id, tenant.name, account."balanceCents", account."creditCents"
|
||||
ORDER BY "todaySpendCents" DESC, tenant.name ASC
|
||||
`),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: { tenantId: query.tenantId, status: 'pending' },
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: { tenantId: query.tenantId, status: 'failed' },
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: { tenantId: query.tenantId, status: 'delivered' },
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: {
|
||||
tenantId: query.tenantId,
|
||||
...stalledPendingWhere(downstreamAlertWindow.stalledPendingAt),
|
||||
},
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: {
|
||||
tenantId: query.tenantId,
|
||||
status: 'awaiting_ack',
|
||||
ackDeadlineAt: { lte: downstreamAlertWindow.now },
|
||||
},
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: {
|
||||
tenantId: query.tenantId,
|
||||
status: { in: ['failed', 'unconfirmed', 'rejected'] },
|
||||
updatedAt: { gte: downstreamAlertWindow.recentFailedAt },
|
||||
},
|
||||
}),
|
||||
this.prisma.$queryRaw<Array<{
|
||||
hour: number;
|
||||
submittedCount: bigint;
|
||||
successCount: bigint;
|
||||
}>>(Prisma.sql`
|
||||
SELECT
|
||||
EXTRACT(
|
||||
HOUR FROM (message."queuedAt" AT TIME ZONE 'UTC') AT TIME ZONE 'Asia/Shanghai'
|
||||
)::integer AS hour,
|
||||
COUNT(*)::bigint AS "submittedCount",
|
||||
COUNT(*) FILTER (WHERE message.status = 'delivered')::bigint AS "successCount"
|
||||
FROM "SmsMessageRecord" message
|
||||
WHERE message."queuedAt" >= ${businessDay.startAt}
|
||||
AND message."queuedAt" < ${businessDay.endAt}
|
||||
AND (${query.tenantId ?? null}::text IS NULL OR message."tenantId" = ${query.tenantId ?? null})
|
||||
GROUP BY 1
|
||||
ORDER BY 1
|
||||
`),
|
||||
// Signature/template tables have no review timestamps, so their latest pending audit is paired with the review audit.
|
||||
this.prisma.$queryRaw<Array<{
|
||||
category: string;
|
||||
count: bigint;
|
||||
averageProcessingMs: bigint | null;
|
||||
}>>(Prisma.sql`
|
||||
WITH review_samples AS (
|
||||
SELECT
|
||||
'enterpriseCertifications'::text AS category,
|
||||
certification."submittedAt" AS "submittedAt",
|
||||
certification."reviewedAt" AS "reviewedAt"
|
||||
FROM "EnterpriseCertification" certification
|
||||
WHERE certification."reviewedAt" >= ${businessDay.startAt}
|
||||
AND certification."reviewedAt" < ${businessDay.endAt}
|
||||
AND (${query.tenantId ?? null}::text IS NULL OR certification."tenantId" = ${query.tenantId ?? null})
|
||||
|
||||
UNION ALL
|
||||
|
||||
SELECT
|
||||
'smsAudits'::text,
|
||||
task."createdAt",
|
||||
task."reviewedAt"
|
||||
FROM "SmsSendTask" task
|
||||
WHERE task."reviewedAt" >= ${businessDay.startAt}
|
||||
AND task."reviewedAt" < ${businessDay.endAt}
|
||||
AND (${query.tenantId ?? null}::text IS NULL OR task."tenantId" = ${query.tenantId ?? null})
|
||||
|
||||
UNION ALL
|
||||
|
||||
SELECT
|
||||
'drainageInfos'::text,
|
||||
drainage."submittedAt",
|
||||
drainage."reviewedAt"
|
||||
FROM "SmsDrainageInfo" drainage
|
||||
WHERE drainage."reviewedAt" >= ${businessDay.startAt}
|
||||
AND drainage."reviewedAt" < ${businessDay.endAt}
|
||||
AND (${query.tenantId ?? null}::text IS NULL OR drainage."tenantId" = ${query.tenantId ?? null})
|
||||
|
||||
UNION ALL
|
||||
|
||||
SELECT
|
||||
CASE review."targetType"
|
||||
WHEN 'sms_signature' THEN 'signatures'
|
||||
WHEN 'sms_template' THEN 'templates'
|
||||
END,
|
||||
submission."createdAt",
|
||||
review."createdAt"
|
||||
FROM "AuditRecord" review
|
||||
JOIN LATERAL (
|
||||
SELECT pending."createdAt"
|
||||
FROM "AuditRecord" pending
|
||||
WHERE pending."targetType" = review."targetType"
|
||||
AND pending."targetId" = review."targetId"
|
||||
AND pending."statusAfter" = 'pending'
|
||||
AND pending."createdAt" <= review."createdAt"
|
||||
ORDER BY pending."createdAt" DESC
|
||||
LIMIT 1
|
||||
) submission ON true
|
||||
WHERE review."targetType" IN ('sms_signature', 'sms_template')
|
||||
AND review."statusBefore" = 'pending'
|
||||
AND review."statusAfter" IN ('approved', 'rejected')
|
||||
AND review."createdAt" >= ${businessDay.startAt}
|
||||
AND review."createdAt" < ${businessDay.endAt}
|
||||
AND (${query.tenantId ?? null}::text IS NULL OR review."tenantId" = ${query.tenantId ?? null})
|
||||
)
|
||||
SELECT
|
||||
category,
|
||||
COUNT(*)::bigint AS count,
|
||||
ROUND(AVG(EXTRACT(EPOCH FROM ("reviewedAt" - "submittedAt")) * 1000))::bigint AS "averageProcessingMs"
|
||||
FROM review_samples
|
||||
WHERE "reviewedAt" >= "submittedAt"
|
||||
GROUP BY category
|
||||
`),
|
||||
]);
|
||||
const todayTotals = summarizeMessageGroups(todayMessageGroups);
|
||||
const hourlyRowsByHour = new Map(hourlySendRows.map((row) => [Number(row.hour), row]));
|
||||
// Always return all 24 Shanghai-time buckets so the line chart does not imply missing hours are missing data.
|
||||
const hourlySendTrend = Array.from({ length: 24 }, (_, hour) => {
|
||||
const row = hourlyRowsByHour.get(hour);
|
||||
return {
|
||||
hour,
|
||||
label: `${String(hour).padStart(2, '0')}:00`,
|
||||
submittedCount: Number(row?.submittedCount ?? 0),
|
||||
successCount: Number(row?.successCount ?? 0),
|
||||
};
|
||||
});
|
||||
const auditSpeedByCategory = new Map(auditSpeedRows.map((row) => [row.category, row]));
|
||||
const auditProcessingSpeed = [
|
||||
['enterpriseCertifications', '企业认证'],
|
||||
['smsAudits', '短信审核'],
|
||||
['templates', '模板'],
|
||||
['signatures', '签名'],
|
||||
['drainageInfos', '引流信息'],
|
||||
].map(([category, label]) => {
|
||||
const row = auditSpeedByCategory.get(category);
|
||||
return {
|
||||
category,
|
||||
label,
|
||||
count: Number(row?.count ?? 0),
|
||||
averageProcessingMs: row?.averageProcessingMs == null ? null : Number(row.averageProcessingMs),
|
||||
};
|
||||
});
|
||||
const downstreamAlertCount = downstreamStalledPendingCount + downstreamStalledAckCount + downstreamRecentFailedCount;
|
||||
return {
|
||||
taskCount,
|
||||
messageStatus: messageGroups,
|
||||
today: {
|
||||
sent: todayTotals.total,
|
||||
delivered: todayTotals.delivered,
|
||||
failed: todayTotals.failed,
|
||||
unknown: todayTotals.unknown,
|
||||
successRate: todayTotals.total > 0 ? Number(((todayTotals.delivered / todayTotals.total) * 100).toFixed(1)) : 0,
|
||||
spendCents: todayTotals.amountCents,
|
||||
returnedCents: moneyToNumber(transactionAggregate._sum.amountCents),
|
||||
billingUnits: todayTotals.billingUnits,
|
||||
},
|
||||
uplinkCount,
|
||||
billing: billingAggregate,
|
||||
transactions: transactionAggregate,
|
||||
gatewayConnections: connectionGroups,
|
||||
pendingAuditCount: pendingAudits.total,
|
||||
pendingAudits,
|
||||
hourlySendTrend,
|
||||
auditProcessingSpeed,
|
||||
downstreamDeliverySummary: {
|
||||
pending: downstreamPendingCount,
|
||||
failed: downstreamFailedCount,
|
||||
delivered: downstreamDeliveredCount,
|
||||
stalledPending: downstreamStalledPendingCount,
|
||||
stalledAck: downstreamStalledAckCount,
|
||||
recentFailed: downstreamRecentFailedCount,
|
||||
alertCount: downstreamAlertCount,
|
||||
},
|
||||
accounts: tenantAccounts,
|
||||
enterpriseSpendRanks: enterpriseSpendRows.map((row) => ({
|
||||
tenantId: row.tenantId,
|
||||
tenantName: row.tenantName,
|
||||
todaySpendCents: moneyToNumber(row.todaySpendCents),
|
||||
balanceCents: moneyToNumber(row.balanceCents),
|
||||
creditCents: moneyToNumber(row.creditCents),
|
||||
})),
|
||||
recentTasks,
|
||||
recentRecharges,
|
||||
};
|
||||
}
|
||||
async clientDashboard(query: { tenantId?: string }) {
|
||||
const tenantId = query.tenantId;
|
||||
const [dashboard, tenant, approvedCertification, signatureCount, pendingBatchTaskCount] = await Promise.all([
|
||||
this.dashboard(query),
|
||||
tenantId
|
||||
? this.prisma.tenant.findUnique({ where: { id: tenantId }, select: { id: true, name: true } })
|
||||
: Promise.resolve(null),
|
||||
tenantId
|
||||
? this.prisma.enterpriseCertification.findFirst({
|
||||
where: { tenantId, status: 'approved' },
|
||||
select: { id: true },
|
||||
})
|
||||
: Promise.resolve(null),
|
||||
tenantId
|
||||
? this.prisma.smsSignature.count({
|
||||
where: { tenantId, auditStatus: { notIn: ['deleted', 'disabled'] } },
|
||||
})
|
||||
: Promise.resolve(0),
|
||||
tenantId
|
||||
? this.prisma.smsBatchTask.count({
|
||||
where: { tenantId, sourceType: 'client', status: 'pending_review' },
|
||||
})
|
||||
: Promise.resolve(0),
|
||||
]);
|
||||
return {
|
||||
taskCount: dashboard.taskCount,
|
||||
messageStatus: dashboard.messageStatus,
|
||||
today: dashboard.today,
|
||||
uplinkCount: dashboard.uplinkCount,
|
||||
billing: dashboard.billing,
|
||||
transactions: dashboard.transactions,
|
||||
gatewayConnections: [],
|
||||
pendingAuditCount: dashboard.pendingAuditCount,
|
||||
pendingAudits: dashboard.pendingAudits,
|
||||
hourlySendTrend: dashboard.hourlySendTrend,
|
||||
auditProcessingSpeed: dashboard.auditProcessingSpeed,
|
||||
downstreamDeliverySummary: dashboard.downstreamDeliverySummary,
|
||||
accounts: dashboard.accounts.map(clientAccountView),
|
||||
enterpriseSpendRanks: dashboard.enterpriseSpendRanks,
|
||||
recentTasks: dashboard.recentTasks.map(clientBatchTaskView),
|
||||
recentRecharges: dashboard.recentRecharges.map(clientRechargeView),
|
||||
clientOverview: {
|
||||
enterpriseName: tenant?.name ?? null,
|
||||
certificationStatus: approvedCertification ? 'certified' : 'uncertified',
|
||||
signatureCount,
|
||||
pendingBatchTaskCount,
|
||||
},
|
||||
};
|
||||
}
|
||||
private countPendingAudits(tenantId?: string) {
|
||||
return Promise.all([
|
||||
this.prisma.smsTemplate.count({ where: { tenantId, auditStatus: 'pending' } }),
|
||||
this.prisma.smsSignature.count({ where: { tenantId, auditStatus: 'pending' } }),
|
||||
this.prisma.smsDrainageInfo.count({ where: { tenantId, auditStatus: 'pending' } }),
|
||||
this.prisma.enterpriseCertification.count({ where: { tenantId, status: 'pending' } }),
|
||||
this.prisma.smsSendTask.count({ where: { tenantId, status: 'pending_review' } }),
|
||||
]).then(([templates, signatures, drainageInfos, enterpriseCertifications, smsAudits]) => ({
|
||||
templates,
|
||||
signatures,
|
||||
drainageInfos,
|
||||
enterpriseCertifications,
|
||||
smsAudits,
|
||||
total: templates + signatures + drainageInfos + enterpriseCertifications + smsAudits,
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { moneyToNumber } from '../../common/money';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import type { MessageQuery, TraceQuery, OperationLogQuery, GatewaySubmitDeadLetterQuery, DownstreamDeliveryQuery, DownstreamDeliveryDashboardQuery, DownstreamRecoveryStatusQuery, MessageSegmentAuditQuery, SignatureQualityQuery } from '../operations.contracts';
|
||||
import { recognizedCarrierValues, carrierWhere, startOfShanghaiDay, endOfShanghaiDay, qualityBusinessDay, shanghaiDateKey, normalizeGroupBy, returnedTransactionWhere, createdAtRange, downstreamAlertPendingMinutes, downstreamAlertRecentFailedHours, downstreamAlertWindows, downstreamAlertWhere, stalledPendingWhere, downstreamDeliveryScopedWhere, parseDateBoundary, downstreamRecoveryStatusWhere, escapeCsvCell, formatCsvDate, formatExportTimestamp, clientApplicationView, clientReceiptView, clientMessageView, clientBatchTaskView, clientUplinkView, clientAccountView, clientRechargeView, summarizeMessageGroups, groupDownstreamByType, groupDownstreamByApplication, positiveInteger, operationLogLevelWhere, normalizeOperationLog, sanitizeGatewaySubmitException, redactGatewayCommandValue } from '../operations.helpers';
|
||||
|
||||
// R2 downstream query domain. Method bodies are preserved byte-for-byte from the facade baseline.
|
||||
export class OperationsDownstreamQueries {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async listGatewaySubmitDeadLetters(query: GatewaySubmitDeadLetterQuery) {
|
||||
const page = Math.max(1, Number(query.page ?? 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Number(query.pageSize ?? 10)));
|
||||
const baseWhere: Prisma.GatewaySubmitDeadLetterWhereInput = {
|
||||
tenantId: query.tenantId,
|
||||
applicationId: query.applicationId,
|
||||
channelId: query.channelId,
|
||||
OR: query.keyword ? [
|
||||
{ streamMessageId: { contains: query.keyword } },
|
||||
{ traceId: { contains: query.keyword } },
|
||||
{ messageId: { contains: query.keyword } },
|
||||
{ submitId: { contains: query.keyword } },
|
||||
{ failureCode: { contains: query.keyword } },
|
||||
{ failureMessage: { contains: query.keyword } },
|
||||
] : undefined,
|
||||
};
|
||||
const where: Prisma.GatewaySubmitDeadLetterWhereInput = {
|
||||
...baseWhere,
|
||||
status: query.status && query.status !== 'all' ? query.status : undefined,
|
||||
};
|
||||
const [items, total, statusGroups, oldestPending] = await Promise.all([
|
||||
this.prisma.gatewaySubmitDeadLetter.findMany({
|
||||
where,
|
||||
include: { tenant: true, application: true, channel: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.gatewaySubmitDeadLetter.count({ where }),
|
||||
this.prisma.gatewaySubmitDeadLetter.groupBy({
|
||||
by: ['status'],
|
||||
where: baseWhere,
|
||||
_count: { _all: true },
|
||||
}),
|
||||
this.prisma.gatewaySubmitDeadLetter.findFirst({
|
||||
where: { ...baseWhere, status: 'pending' },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
select: { createdAt: true },
|
||||
}),
|
||||
]);
|
||||
const statusCounts = new Map(statusGroups.map((item) => [item.status, item._count._all]));
|
||||
const messageIds = items.map((item) => item.messageId).filter((value): value is string => Boolean(value));
|
||||
const messageStates = messageIds.length > 0
|
||||
? await this.prisma.smsMessageRecord.findMany({
|
||||
where: { messageId: { in: messageIds } },
|
||||
select: { messageId: true, status: true, submitStatus: true, receiptStatus: true, phoneNumber: true, content: true },
|
||||
})
|
||||
: [];
|
||||
const messageStateById = new Map(messageStates.map((item) => [item.messageId, item]));
|
||||
return {
|
||||
items: items.map((item) => sanitizeGatewaySubmitException(item, item.messageId ? messageStateById.get(item.messageId) : undefined)),
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
summary: {
|
||||
pending: statusCounts.get('pending') ?? 0,
|
||||
requeueing: statusCounts.get('requeueing') ?? 0,
|
||||
requeued: statusCounts.get('requeued') ?? 0,
|
||||
resolved: statusCounts.get('resolved') ?? 0,
|
||||
oldestPendingAt: oldestPending?.createdAt ?? null,
|
||||
},
|
||||
};
|
||||
}
|
||||
async listDownstreamDeliveries(query: DownstreamDeliveryQuery) {
|
||||
const page = Math.max(1, Number(query.page ?? 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Number(query.pageSize ?? 10)));
|
||||
const where: Prisma.CmppDownstreamDeliveryWhereInput = {
|
||||
...downstreamDeliveryScopedWhere(query),
|
||||
status: query.status && query.status !== 'all' ? query.status : undefined,
|
||||
OR: query.keyword ? [
|
||||
{ messageId: { contains: query.keyword } },
|
||||
{ payload: { path: ['account'], string_contains: query.keyword } },
|
||||
{ payload: { path: ['phoneNumber'], string_contains: query.keyword } },
|
||||
{ lastError: { contains: query.keyword } },
|
||||
] : undefined,
|
||||
};
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.cmppDownstreamDelivery.findMany({
|
||||
where,
|
||||
include: {
|
||||
tenant: true,
|
||||
application: true,
|
||||
messageRecord: true,
|
||||
attempts: { orderBy: [{ attemptNo: 'desc' }, { createdAt: 'desc' }] },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({ where }),
|
||||
]);
|
||||
return { items, total, page, pageSize };
|
||||
}
|
||||
async downstreamDeliveryDashboard(query: DownstreamDeliveryDashboardQuery) {
|
||||
const scopedWhere = downstreamDeliveryScopedWhere(query);
|
||||
const downstreamAlertWindow = downstreamAlertWindows();
|
||||
const [total, pending, awaitingAck, delivered, failed, unconfirmed, rejected, stalledPending, stalledAck, recentFailed, typeGroups, applicationGroups, applicationAlertGroups, retryZero, retryLow, retryHigh] = await Promise.all([
|
||||
this.prisma.cmppDownstreamDelivery.count({ where: scopedWhere }),
|
||||
this.prisma.cmppDownstreamDelivery.count({ where: { ...scopedWhere, status: 'pending' } }),
|
||||
this.prisma.cmppDownstreamDelivery.count({ where: { ...scopedWhere, status: 'awaiting_ack' } }),
|
||||
this.prisma.cmppDownstreamDelivery.count({ where: { ...scopedWhere, status: 'delivered' } }),
|
||||
this.prisma.cmppDownstreamDelivery.count({ where: { ...scopedWhere, status: 'failed' } }),
|
||||
this.prisma.cmppDownstreamDelivery.count({ where: { ...scopedWhere, status: 'unconfirmed' } }),
|
||||
this.prisma.cmppDownstreamDelivery.count({ where: { ...scopedWhere, status: 'rejected' } }),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: {
|
||||
...scopedWhere,
|
||||
...stalledPendingWhere(downstreamAlertWindow.stalledPendingAt),
|
||||
},
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: { ...scopedWhere, status: 'awaiting_ack', ackDeadlineAt: { lte: downstreamAlertWindow.now } },
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: {
|
||||
...scopedWhere,
|
||||
status: { in: ['failed', 'unconfirmed', 'rejected'] },
|
||||
updatedAt: { gte: downstreamAlertWindow.recentFailedAt },
|
||||
},
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.groupBy({
|
||||
by: ['deliveryType', 'status'],
|
||||
where: scopedWhere,
|
||||
_count: { _all: true },
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.groupBy({
|
||||
by: ['applicationId', 'status'],
|
||||
where: scopedWhere,
|
||||
_count: { _all: true },
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.groupBy({
|
||||
by: ['applicationId'],
|
||||
where: downstreamAlertWhere(scopedWhere, downstreamAlertWindow),
|
||||
_count: { _all: true },
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: {
|
||||
...scopedWhere,
|
||||
status: { in: ['pending', 'failed', 'unconfirmed', 'rejected'] },
|
||||
retryCount: 0,
|
||||
},
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: {
|
||||
...scopedWhere,
|
||||
status: { in: ['pending', 'failed', 'unconfirmed', 'rejected'] },
|
||||
retryCount: { gte: 1, lte: 3 },
|
||||
},
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: {
|
||||
...scopedWhere,
|
||||
status: { in: ['pending', 'failed', 'unconfirmed', 'rejected'] },
|
||||
retryCount: { gte: 4 },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
const applicationIds = [...new Set(applicationGroups.map((item) => item.applicationId).filter((value): value is string => Boolean(value)))];
|
||||
const applications: Array<{ id: string; name: string }> = applicationIds.length > 0
|
||||
? await this.prisma.smsApplication.findMany({
|
||||
where: { id: { in: applicationIds } },
|
||||
select: { id: true, name: true },
|
||||
})
|
||||
: [];
|
||||
const applicationMap = new Map<string, string>(applications.map((item) => [item.id, item.name]));
|
||||
const applicationAlertMap = new Map<string, number>(
|
||||
applicationAlertGroups.map((item) => [item.applicationId, item._count._all]),
|
||||
);
|
||||
const groupedByType = groupDownstreamByType(typeGroups);
|
||||
const groupedByApplication = groupDownstreamByApplication(applicationGroups, applicationMap, applicationAlertMap);
|
||||
|
||||
return {
|
||||
summary: {
|
||||
total,
|
||||
pending,
|
||||
awaitingAck,
|
||||
delivered,
|
||||
failed,
|
||||
unconfirmed,
|
||||
rejected,
|
||||
stalledPending,
|
||||
stalledAck,
|
||||
recentFailed,
|
||||
alertCount: stalledPending + stalledAck + recentFailed,
|
||||
},
|
||||
typeBreakdown: ['receipt', 'uplink'].map((deliveryType) => ({
|
||||
deliveryType,
|
||||
total: groupedByType[deliveryType]?.total ?? 0,
|
||||
pending: groupedByType[deliveryType]?.pending ?? 0,
|
||||
awaitingAck: groupedByType[deliveryType]?.awaitingAck ?? 0,
|
||||
delivered: groupedByType[deliveryType]?.delivered ?? 0,
|
||||
failed: groupedByType[deliveryType]?.failed ?? 0,
|
||||
unconfirmed: groupedByType[deliveryType]?.unconfirmed ?? 0,
|
||||
rejected: groupedByType[deliveryType]?.rejected ?? 0,
|
||||
})),
|
||||
retryBuckets: [
|
||||
{ label: '0次', count: retryZero },
|
||||
{ label: '1-3次', count: retryLow },
|
||||
{ label: '4次及以上', count: retryHigh },
|
||||
],
|
||||
topApplications: groupedByApplication
|
||||
.sort((left, right) => (
|
||||
right.alertCount - left.alertCount
|
||||
|| right.failed - left.failed
|
||||
|| right.pending - left.pending
|
||||
|| left.name.localeCompare(right.name, 'zh-CN')
|
||||
))
|
||||
.slice(0, 5),
|
||||
};
|
||||
}
|
||||
async listDownstreamRecoveryStatuses(query: DownstreamRecoveryStatusQuery) {
|
||||
const recoveryStatuses = this.gatewayDownstreamRecoveryStatusDelegate();
|
||||
const page = Math.max(1, Number(query.page ?? 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Number(query.pageSize ?? 10)));
|
||||
const where = downstreamRecoveryStatusWhere(query);
|
||||
const now = new Date();
|
||||
const [items, total, runningCount, successCount, failedCount, waitingConnectionCount, backoffCount, categoryGroups] = await Promise.all([
|
||||
recoveryStatuses.findMany({
|
||||
where,
|
||||
include: { tenant: true, application: true },
|
||||
orderBy: [{ updatedAt: 'desc' }, { account: 'asc' }],
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
recoveryStatuses.count({ where }),
|
||||
recoveryStatuses.count({ where: { ...where, state: 'running' } }),
|
||||
recoveryStatuses.count({ where: { ...where, state: 'success' } }),
|
||||
recoveryStatuses.count({ where: { ...where, state: 'failed' } }),
|
||||
recoveryStatuses.count({ where: { ...where, state: 'waiting_connection' } }),
|
||||
recoveryStatuses.count({
|
||||
where: {
|
||||
...where,
|
||||
nextRetryAt: { gt: now },
|
||||
},
|
||||
}),
|
||||
recoveryStatuses.groupBy({
|
||||
by: ['failureCategory'],
|
||||
where,
|
||||
_count: { _all: true },
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
items,
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
summary: {
|
||||
total,
|
||||
running: runningCount,
|
||||
success: successCount,
|
||||
failed: failedCount,
|
||||
waitingConnection: waitingConnectionCount,
|
||||
backoff: backoffCount,
|
||||
failureCategories: categoryGroups
|
||||
.filter((item) => item.failureCategory)
|
||||
.map((item) => ({
|
||||
category: String(item.failureCategory),
|
||||
count: item._count?._all ?? 0,
|
||||
}))
|
||||
.sort((left, right) => right.count - left.count || left.category.localeCompare(right.category)),
|
||||
},
|
||||
};
|
||||
}
|
||||
async listMessageSegmentAudits(query: MessageSegmentAuditQuery) {
|
||||
const segmentAudits = (this.prisma as PrismaService & {
|
||||
smsMessageSegmentAudit: {
|
||||
findMany: (args: Record<string, unknown>) => Promise<any[]>;
|
||||
};
|
||||
}).smsMessageSegmentAudit;
|
||||
if (!query.messageId && !query.messageRecordId) {
|
||||
return [];
|
||||
}
|
||||
return segmentAudits.findMany({
|
||||
where: {
|
||||
messageRecordId: query.messageRecordId,
|
||||
messageRecord: query.messageId ? { messageId: query.messageId } : undefined,
|
||||
},
|
||||
include: { channel: true, submitRecord: true },
|
||||
orderBy: [{ createdAt: 'asc' }, { segmentIndex: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
}
|
||||
async getDownstreamRecoveryStatus(id: string) {
|
||||
const recoveryStatuses = this.gatewayDownstreamRecoveryStatusDelegate();
|
||||
const item = await recoveryStatuses.findUnique({
|
||||
where: { id },
|
||||
include: { tenant: true, application: true },
|
||||
});
|
||||
if (!item) {
|
||||
throw new NotFoundException('Recovery status not found');
|
||||
}
|
||||
return item;
|
||||
}
|
||||
async exportDownstreamRecoveryStatuses(query: DownstreamRecoveryStatusQuery) {
|
||||
const recoveryStatuses = this.gatewayDownstreamRecoveryStatusDelegate();
|
||||
const where = downstreamRecoveryStatusWhere(query);
|
||||
const items = await recoveryStatuses.findMany({
|
||||
where,
|
||||
include: { tenant: true, application: true },
|
||||
orderBy: [{ updatedAt: 'desc' }, { account: 'asc' }],
|
||||
take: 5000,
|
||||
});
|
||||
const rows = [
|
||||
[
|
||||
'账号',
|
||||
'企业',
|
||||
'应用',
|
||||
'Gateway实例',
|
||||
'恢复状态',
|
||||
'锁持有实例',
|
||||
'锁过期时间',
|
||||
'失败分类',
|
||||
'尝试次数',
|
||||
'最后尝试时间',
|
||||
'恢复成功时间',
|
||||
'恢复失败时间',
|
||||
'下次恢复时间',
|
||||
'最后错误',
|
||||
'最后跳过原因',
|
||||
'创建时间',
|
||||
'更新时间',
|
||||
],
|
||||
...items.map((item) => [
|
||||
item.account ?? '',
|
||||
item.tenant?.name ?? '',
|
||||
item.application?.name ?? '',
|
||||
item.gatewayInstanceId ?? '',
|
||||
item.state ?? '',
|
||||
(item as { lockOwner?: string | null }).lockOwner ?? '',
|
||||
formatCsvDate((item as { lockExpiresAt?: Date | string | null }).lockExpiresAt),
|
||||
(item as { failureCategory?: string | null }).failureCategory ?? '',
|
||||
String(item.attemptCount ?? 0),
|
||||
formatCsvDate(item.lastAttemptAt),
|
||||
formatCsvDate(item.lastSuccessAt),
|
||||
formatCsvDate(item.lastFailureAt),
|
||||
formatCsvDate(item.nextRetryAt),
|
||||
item.lastError ?? '',
|
||||
item.lastSkipReason ?? '',
|
||||
formatCsvDate(item.createdAt),
|
||||
formatCsvDate(item.updatedAt),
|
||||
]),
|
||||
];
|
||||
|
||||
return {
|
||||
fileName: `gateway-downstream-recovery-statuses-${formatExportTimestamp(new Date())}.csv`,
|
||||
content: rows.map((row) => row.map(escapeCsvCell).join(',')).join('\n'),
|
||||
total: items.length,
|
||||
};
|
||||
}
|
||||
private gatewayDownstreamRecoveryStatusDelegate() {
|
||||
return (this.prisma as PrismaService & {
|
||||
gatewayDownstreamRecoveryStatus: {
|
||||
findMany: (args: Record<string, unknown>) => Promise<any[]>;
|
||||
count: (args: Record<string, unknown>) => Promise<number>;
|
||||
findUnique: (args: Record<string, unknown>) => Promise<any | null>;
|
||||
groupBy: (args: Record<string, unknown>) => Promise<any[]>;
|
||||
};
|
||||
}).gatewayDownstreamRecoveryStatus;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { moneyToNumber } from '../../common/money';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import type { MessageQuery, TraceQuery, OperationLogQuery, GatewaySubmitDeadLetterQuery, DownstreamDeliveryQuery, DownstreamDeliveryDashboardQuery, DownstreamRecoveryStatusQuery, MessageSegmentAuditQuery, SignatureQualityQuery } from '../operations.contracts';
|
||||
import { recognizedCarrierValues, carrierWhere, startOfShanghaiDay, endOfShanghaiDay, qualityBusinessDay, shanghaiDateKey, normalizeGroupBy, returnedTransactionWhere, createdAtRange, downstreamAlertPendingMinutes, downstreamAlertRecentFailedHours, downstreamAlertWindows, downstreamAlertWhere, stalledPendingWhere, downstreamDeliveryScopedWhere, parseDateBoundary, downstreamRecoveryStatusWhere, escapeCsvCell, formatCsvDate, formatExportTimestamp, clientApplicationView, clientReceiptView, clientMessageView, clientBatchTaskView, clientUplinkView, clientAccountView, clientRechargeView, summarizeMessageGroups, groupDownstreamByType, groupDownstreamByApplication, positiveInteger, operationLogLevelWhere, normalizeOperationLog, sanitizeGatewaySubmitException, redactGatewayCommandValue } from '../operations.helpers';
|
||||
|
||||
// R2 logs query domain. Method bodies are preserved byte-for-byte from the facade baseline.
|
||||
export class OperationsLogQueries {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async auditLogs(query: { tenantId?: string; userId?: string; page?: number; pageSize?: number }) {
|
||||
const page = positiveInteger(query.page, 1);
|
||||
const pageSize = Math.min(100, positiveInteger(query.pageSize, 20));
|
||||
const where: Prisma.OperationLogWhereInput = { tenantId: query.tenantId, userId: query.userId };
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.operationLog.findMany({
|
||||
where,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.operationLog.count({ where }),
|
||||
]);
|
||||
return { items, total, page, pageSize };
|
||||
}
|
||||
async systemLogs(query: OperationLogQuery) {
|
||||
const page = positiveInteger(query.page, 1);
|
||||
const pageSize = Math.min(100, positiveInteger(query.pageSize, 10));
|
||||
const where: Prisma.OperationLogWhereInput = {
|
||||
tenantId: query.tenantId,
|
||||
userId: query.userId,
|
||||
createdAt: createdAtRange(query.range),
|
||||
resource: query.module && query.module !== 'all' ? query.module : undefined,
|
||||
AND: query.level && query.level !== 'all' ? operationLogLevelWhere(query.level) : undefined,
|
||||
OR: query.keyword ? [
|
||||
{ action: { contains: query.keyword } },
|
||||
{ resource: { contains: query.keyword } },
|
||||
{ resourceId: { contains: query.keyword } },
|
||||
{ tenant: { name: { contains: query.keyword } } },
|
||||
{ user: { displayName: { contains: query.keyword } } },
|
||||
{ user: { username: { contains: query.keyword } } },
|
||||
] : undefined,
|
||||
};
|
||||
const [items, total, modules] = await Promise.all([
|
||||
this.prisma.operationLog.findMany({
|
||||
where,
|
||||
include: { tenant: true, user: true },
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.operationLog.count({ where }),
|
||||
this.prisma.operationLog.groupBy({
|
||||
by: ['resource'],
|
||||
where: { tenantId: query.tenantId },
|
||||
_count: { _all: true },
|
||||
orderBy: { resource: 'asc' },
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
items: items.map((item) => normalizeOperationLog(item)),
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
modules: modules.map((item) => item.resource),
|
||||
};
|
||||
}
|
||||
async exportSystemLogs(query: OperationLogQuery, clientUserId?: string) {
|
||||
const clientTenantId = clientUserId ? await this.resolveClientTenantId(clientUserId) : undefined;
|
||||
const effectiveQuery = { ...query, tenantId: clientTenantId ?? query.tenantId };
|
||||
const where: Prisma.OperationLogWhereInput = {
|
||||
tenantId: effectiveQuery.tenantId,
|
||||
userId: effectiveQuery.userId,
|
||||
createdAt: createdAtRange(effectiveQuery.range),
|
||||
resource: effectiveQuery.module && effectiveQuery.module !== 'all' ? effectiveQuery.module : undefined,
|
||||
AND: effectiveQuery.level && effectiveQuery.level !== 'all' ? operationLogLevelWhere(effectiveQuery.level) : undefined,
|
||||
OR: effectiveQuery.keyword ? [
|
||||
{ action: { contains: effectiveQuery.keyword } },
|
||||
{ resource: { contains: effectiveQuery.keyword } },
|
||||
{ resourceId: { contains: effectiveQuery.keyword } },
|
||||
{ tenant: { name: { contains: effectiveQuery.keyword } } },
|
||||
{ user: { displayName: { contains: effectiveQuery.keyword } } },
|
||||
{ user: { username: { contains: effectiveQuery.keyword } } },
|
||||
] : undefined,
|
||||
};
|
||||
const rows = await this.prisma.operationLog.findMany({
|
||||
where,
|
||||
include: { tenant: true, user: true },
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
take: 10_001,
|
||||
});
|
||||
const truncated = rows.length > 10_000;
|
||||
const exportedRows = rows.slice(0, 10_000).map(normalizeOperationLog);
|
||||
const clientExport = Boolean(clientUserId);
|
||||
const headers = clientExport
|
||||
? ['时间', '级别', '模块', '操作人', '动作', '资源ID']
|
||||
: ['时间', '级别', '企业', '模块', '操作人', '动作', '资源ID', '详情', 'IP'];
|
||||
const values = exportedRows.map((item) => clientExport
|
||||
? [item.time, item.level, item.module, item.operator, item.action, item.resourceId]
|
||||
: [item.time, item.level, item.tenant, item.module, item.operator, item.action, item.resourceId, JSON.stringify(item.detail), item.ip]);
|
||||
return {
|
||||
operationId: randomUUID(),
|
||||
status: 'completed' as const,
|
||||
fileName: `system-logs-${new Date().toISOString().replace(/[:.]/g, '-')}.csv`,
|
||||
recordCount: exportedRows.length,
|
||||
truncated,
|
||||
content: [headers, ...values].map((row) => row.map((cell) => escapeCsvCell(String(cell ?? ''))).join(',')).join('\n'),
|
||||
filters: { keyword: effectiveQuery.keyword, level: effectiveQuery.level, module: effectiveQuery.module, range: effectiveQuery.range },
|
||||
};
|
||||
}
|
||||
private async resolveClientTenantId(userId: string) {
|
||||
const user = await this.prisma.user.findFirst({
|
||||
where: { id: userId, status: 'active', deletedAt: null, tenantId: { not: null } },
|
||||
select: { tenantId: true },
|
||||
});
|
||||
if (!user?.tenantId) throw new NotFoundException('Client tenant not found');
|
||||
return user.tenantId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { moneyToNumber } from '../../common/money';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import type { MessageQuery, TraceQuery, OperationLogQuery, GatewaySubmitDeadLetterQuery, DownstreamDeliveryQuery, DownstreamDeliveryDashboardQuery, DownstreamRecoveryStatusQuery, MessageSegmentAuditQuery, SignatureQualityQuery } from '../operations.contracts';
|
||||
import { messageWhere, recognizedCarrierValues, carrierWhere, startOfShanghaiDay, endOfShanghaiDay, qualityBusinessDay, shanghaiDateKey, normalizeGroupBy, returnedTransactionWhere, createdAtRange, downstreamAlertPendingMinutes, downstreamAlertRecentFailedHours, downstreamAlertWindows, downstreamAlertWhere, stalledPendingWhere, downstreamDeliveryScopedWhere, parseDateBoundary, downstreamRecoveryStatusWhere, escapeCsvCell, formatCsvDate, formatExportTimestamp, clientApplicationView, clientReceiptView, clientMessageView, clientBatchTaskView, clientUplinkView, clientAccountView, clientRechargeView, summarizeMessageGroups, groupDownstreamByType, groupDownstreamByApplication, positiveInteger, operationLogLevelWhere, normalizeOperationLog, sanitizeGatewaySubmitException, redactGatewayCommandValue } from '../operations.helpers';
|
||||
|
||||
// R2 messages query domain. Method bodies are preserved byte-for-byte from the facade baseline.
|
||||
export class OperationsMessageQueries {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
listBatchTasks(query: { tenantId?: string; status?: string }) {
|
||||
return this.prisma.smsBatchTask.findMany({
|
||||
where: { tenantId: query.tenantId, status: query.status, sourceType: 'client' },
|
||||
include: { apiRequests: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
}
|
||||
async listClientBatchTasks(query: { tenantId?: string; status?: string }) {
|
||||
const items = await this.listBatchTasks(query);
|
||||
return items.map(clientBatchTaskView);
|
||||
}
|
||||
listMessages(query: MessageQuery) {
|
||||
return this.prisma.smsMessageRecord.findMany({
|
||||
where: messageWhere(query),
|
||||
include: {
|
||||
tenant: true,
|
||||
application: true,
|
||||
channel: true,
|
||||
submitRecords: { include: { channel: true, channelGroup: true } },
|
||||
receiptRecords: { include: { channel: true } },
|
||||
downstreamDeliveries: {
|
||||
where: { deliveryType: 'receipt' },
|
||||
select: { id: true, deliveryType: true, status: true, deliveredAt: true, lastError: true },
|
||||
},
|
||||
},
|
||||
orderBy: { queuedAt: 'desc' },
|
||||
});
|
||||
}
|
||||
async listMessagesPage(query: MessageQuery) {
|
||||
const page = Math.max(1, Math.floor(Number(query.page) || 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 25)));
|
||||
const where = messageWhere(query);
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.smsMessageRecord.findMany({
|
||||
where,
|
||||
include: {
|
||||
tenant: { select: { id: true, name: true } },
|
||||
application: { select: { id: true, name: true } },
|
||||
channel: { select: { id: true, name: true, srcId: true } },
|
||||
submitRecords: {
|
||||
select: {
|
||||
id: true,
|
||||
submitId: true,
|
||||
channelId: true,
|
||||
channelGroupId: true,
|
||||
channelGroupName: true,
|
||||
gatewayMessageId: true,
|
||||
submitStatus: true,
|
||||
submittedAt: true,
|
||||
createdAt: true,
|
||||
channel: { select: { id: true, name: true } },
|
||||
channelGroup: { select: { id: true, name: true } },
|
||||
},
|
||||
},
|
||||
receiptRecords: {
|
||||
select: {
|
||||
id: true,
|
||||
messageId: true,
|
||||
gatewayMessageId: true,
|
||||
receiptStatus: true,
|
||||
rawStatus: true,
|
||||
errorCode: true,
|
||||
errorMessage: true,
|
||||
deliveredAt: true,
|
||||
createdAt: true,
|
||||
channelId: true,
|
||||
channel: { select: { id: true, name: true } },
|
||||
},
|
||||
},
|
||||
downstreamDeliveries: {
|
||||
where: { deliveryType: 'receipt' },
|
||||
select: { id: true, deliveryType: true, status: true, deliveredAt: true, lastError: true },
|
||||
},
|
||||
},
|
||||
orderBy: [{ queuedAt: 'desc' }, { id: 'desc' }],
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.smsMessageRecord.count({ where }),
|
||||
]);
|
||||
return { items, total, page, pageSize };
|
||||
}
|
||||
async exportMessages(query: MessageQuery) {
|
||||
const items = await this.prisma.smsMessageRecord.findMany({
|
||||
where: messageWhere(query),
|
||||
select: {
|
||||
messageId: true,
|
||||
queuedAt: true,
|
||||
phoneNumber: true,
|
||||
province: true,
|
||||
carrier: true,
|
||||
billingUnits: true,
|
||||
amountCents: true,
|
||||
status: true,
|
||||
submitStatus: true,
|
||||
deliveredAt: true,
|
||||
content: true,
|
||||
tenant: { select: { name: true } },
|
||||
application: { select: { name: true } },
|
||||
channel: { select: { name: true } },
|
||||
},
|
||||
orderBy: [{ queuedAt: 'desc' }, { id: 'desc' }],
|
||||
});
|
||||
const rows = [
|
||||
['消息编号', '企业', '应用', '提交时间', '手机号', '地区', '运营商', '计费条数', '金额', '通道', '状态', '回执时间', '短信内容'],
|
||||
...items.map((item) => [
|
||||
item.messageId,
|
||||
item.tenant?.name ?? '',
|
||||
item.application?.name ?? '',
|
||||
item.queuedAt.toISOString(),
|
||||
item.phoneNumber,
|
||||
item.province ?? '',
|
||||
item.carrier ?? '',
|
||||
String(item.billingUnits),
|
||||
String(moneyToNumber(item.amountCents)),
|
||||
item.channel?.name ?? '',
|
||||
item.status === 'submit_failed' || ['rejected', 'timeout'].includes(item.submitStatus ?? '') ? 'submit_failed' : item.status,
|
||||
item.deliveredAt?.toISOString() ?? '',
|
||||
item.content,
|
||||
]),
|
||||
];
|
||||
return {
|
||||
fileName: `sms-records-${formatExportTimestamp(new Date())}.csv`,
|
||||
content: rows.map((row) => row.map((cell) => escapeCsvCell(String(cell))).join(',')).join('\n'),
|
||||
};
|
||||
}
|
||||
async listClientMessages(query: MessageQuery) {
|
||||
const items = await this.listMessages(query);
|
||||
return items.map(clientMessageView);
|
||||
}
|
||||
async listClientMessagesPage(query: MessageQuery) {
|
||||
const result = await this.listMessagesPage(query);
|
||||
return { ...result, items: result.items.map(clientMessageView) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,580 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { moneyToNumber } from '../../common/money';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import type { MessageQuery, TraceQuery, OperationLogQuery, GatewaySubmitDeadLetterQuery, DownstreamDeliveryQuery, DownstreamDeliveryDashboardQuery, DownstreamRecoveryStatusQuery, MessageSegmentAuditQuery, SignatureQualityQuery } from '../operations.contracts';
|
||||
import { messageWhere, recognizedCarrierValues, carrierWhere, startOfShanghaiDay, endOfShanghaiDay, qualityBusinessDay, shanghaiDateKey, normalizeGroupBy, returnedTransactionWhere, createdAtRange, downstreamAlertPendingMinutes, downstreamAlertRecentFailedHours, downstreamAlertWindows, downstreamAlertWhere, stalledPendingWhere, downstreamDeliveryScopedWhere, parseDateBoundary, downstreamRecoveryStatusWhere, escapeCsvCell, formatCsvDate, formatExportTimestamp, clientApplicationView, clientReceiptView, clientMessageView, clientBatchTaskView, clientUplinkView, clientAccountView, clientRechargeView, summarizeMessageGroups, groupDownstreamByType, groupDownstreamByApplication, positiveInteger, operationLogLevelWhere, normalizeOperationLog, sanitizeGatewaySubmitException, redactGatewayCommandValue } from '../operations.helpers';
|
||||
|
||||
// R2 quality query domain. Method bodies are preserved byte-for-byte from the facade baseline.
|
||||
export class OperationsQualityQueries {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async statistics(query: { tenantId?: string; groupBy?: string }) {
|
||||
const groupBy = normalizeGroupBy(query.groupBy);
|
||||
if (groupBy === 'tenantId') {
|
||||
return this.prisma.smsMessageRecord.groupBy({
|
||||
by: ['tenantId'],
|
||||
where: messageWhere({ tenantId: query.tenantId }),
|
||||
_count: { _all: true },
|
||||
_sum: { amountCents: true, billingUnits: true },
|
||||
});
|
||||
}
|
||||
if (groupBy === 'applicationId') {
|
||||
return this.prisma.smsMessageRecord.groupBy({
|
||||
by: ['applicationId'],
|
||||
where: messageWhere({ tenantId: query.tenantId }),
|
||||
_count: { _all: true },
|
||||
_sum: { amountCents: true, billingUnits: true },
|
||||
});
|
||||
}
|
||||
return this.prisma.smsMessageRecord.groupBy({
|
||||
by: ['channelId'],
|
||||
where: messageWhere({ tenantId: query.tenantId }),
|
||||
_count: { _all: true },
|
||||
_sum: { amountCents: true, billingUnits: true },
|
||||
});
|
||||
}
|
||||
async sendQuality(date?: string) {
|
||||
const day = qualityBusinessDay(date);
|
||||
const [channels, signatures, summaryRows, applications] = await Promise.all([
|
||||
this.prisma.$queryRaw<Array<{
|
||||
channelId: string;
|
||||
channelName: string;
|
||||
total: number;
|
||||
acceptedCount: number;
|
||||
submitFailureCount: number;
|
||||
submitFailureRate: number;
|
||||
successCount: number;
|
||||
unknownCount: number;
|
||||
failureCount: number;
|
||||
successRate: number;
|
||||
unknownRate: number;
|
||||
failureRate: number;
|
||||
averageArrivalMs: number | null;
|
||||
}>>(Prisma.sql`
|
||||
WITH base AS (
|
||||
SELECT
|
||||
submit."channelId" AS channel_id,
|
||||
channel.name AS channel_name,
|
||||
submit."submitStatus" AS submit_status,
|
||||
receipt."deliveredAt" AS delivered_at,
|
||||
failed_receipt."failedAt" AS failed_at,
|
||||
COALESCE(segment_summary.segment_count, 0) AS segment_count,
|
||||
COALESCE(segment_summary.delivered_count, 0) AS segment_delivered_count,
|
||||
COALESCE(segment_summary.failure_count, 0) AS segment_failure_count,
|
||||
CASE
|
||||
WHEN segment_summary.segment_count > 0
|
||||
AND segment_summary.delivered_count = segment_summary.segment_count
|
||||
AND segment_summary.completed_at >= COALESCE(submit."submittedAt", submit."createdAt")
|
||||
THEN EXTRACT(EPOCH FROM (segment_summary.completed_at - COALESCE(submit."submittedAt", submit."createdAt"))) * 1000
|
||||
WHEN segment_summary.segment_count = 0
|
||||
AND receipt."deliveredAt" >= COALESCE(submit."submittedAt", submit."createdAt")
|
||||
THEN EXTRACT(EPOCH FROM (receipt."deliveredAt" - COALESCE(submit."submittedAt", submit."createdAt"))) * 1000
|
||||
END AS arrival_ms
|
||||
FROM "SmsSubmitRecord" submit
|
||||
JOIN "SmsChannel" channel ON channel.id = submit."channelId"
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT
|
||||
COUNT(*)::integer AS segment_count,
|
||||
COUNT(*) FILTER (WHERE segment."receiptStatus" = 'delivered')::integer AS delivered_count,
|
||||
COUNT(*) FILTER (WHERE segment."receiptStatus" = 'undelivered')::integer AS failure_count,
|
||||
MAX(segment."deliveredAt") FILTER (WHERE segment."receiptStatus" = 'delivered') AS completed_at
|
||||
FROM "SmsMessageSegmentAudit" segment
|
||||
WHERE segment."submitRecordId" = submit.id
|
||||
) segment_summary ON TRUE
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT MIN(receipt."deliveredAt") AS "deliveredAt"
|
||||
FROM "SmsReceiptRecord" receipt
|
||||
WHERE receipt."gatewayMessageId" = submit."gatewayMessageId"
|
||||
AND receipt."channelId" = submit."channelId"
|
||||
AND receipt."receiptStatus" = 'delivered'
|
||||
) receipt ON TRUE
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT MIN(receipt."deliveredAt") AS "failedAt"
|
||||
FROM "SmsReceiptRecord" receipt
|
||||
WHERE receipt."gatewayMessageId" = submit."gatewayMessageId"
|
||||
AND receipt."channelId" = submit."channelId"
|
||||
AND receipt."receiptStatus" = 'undelivered'
|
||||
) failed_receipt ON TRUE
|
||||
WHERE submit."submitStatus" IN ('accepted', 'rejected', 'timeout')
|
||||
AND COALESCE(submit."submittedAt", submit."createdAt") >= ${day.startAt}
|
||||
AND COALESCE(submit."submittedAt", submit."createdAt") < ${day.endAt}
|
||||
), classified AS (
|
||||
SELECT
|
||||
*,
|
||||
CASE
|
||||
WHEN submit_status <> 'accepted' THEN 'submit_failed'
|
||||
WHEN segment_count > 0 AND segment_failure_count > 0 THEN 'failure'
|
||||
WHEN segment_count > 0 AND segment_delivered_count = segment_count THEN 'success'
|
||||
WHEN segment_count = 0 AND failed_at IS NOT NULL THEN 'failure'
|
||||
WHEN segment_count = 0 AND delivered_at IS NOT NULL THEN 'success'
|
||||
ELSE 'unknown'
|
||||
END AS delivery_status
|
||||
FROM base
|
||||
)
|
||||
SELECT
|
||||
channel_id AS "channelId",
|
||||
MAX(channel_name) AS "channelName",
|
||||
COUNT(*)::integer AS total,
|
||||
COUNT(*) FILTER (WHERE submit_status = 'accepted')::integer AS "acceptedCount",
|
||||
COUNT(*) FILTER (WHERE delivery_status = 'submit_failed')::integer AS "submitFailureCount",
|
||||
CASE WHEN COUNT(*) = 0 THEN 0 ELSE ROUND(COUNT(*) FILTER (WHERE delivery_status = 'submit_failed') * 100.0 / COUNT(*), 1)::double precision END AS "submitFailureRate",
|
||||
COUNT(*) FILTER (WHERE delivery_status = 'success')::integer AS "successCount",
|
||||
COUNT(*) FILTER (WHERE delivery_status = 'unknown')::integer AS "unknownCount",
|
||||
COUNT(*) FILTER (WHERE delivery_status = 'failure')::integer AS "failureCount",
|
||||
CASE WHEN COUNT(*) FILTER (WHERE submit_status = 'accepted') = 0 THEN 0 ELSE ROUND(COUNT(*) FILTER (WHERE delivery_status = 'success') * 100.0 / COUNT(*) FILTER (WHERE submit_status = 'accepted'), 1)::double precision END AS "successRate",
|
||||
CASE WHEN COUNT(*) FILTER (WHERE submit_status = 'accepted') = 0 THEN 0 ELSE ROUND(COUNT(*) FILTER (WHERE delivery_status = 'unknown') * 100.0 / COUNT(*) FILTER (WHERE submit_status = 'accepted'), 1)::double precision END AS "unknownRate",
|
||||
CASE WHEN COUNT(*) FILTER (WHERE submit_status = 'accepted') = 0 THEN 0 ELSE ROUND(COUNT(*) FILTER (WHERE delivery_status = 'failure') * 100.0 / COUNT(*) FILTER (WHERE submit_status = 'accepted'), 1)::double precision END AS "failureRate",
|
||||
ROUND(AVG(arrival_ms) FILTER (WHERE delivery_status = 'success' AND arrival_ms IS NOT NULL))::integer AS "averageArrivalMs"
|
||||
FROM classified
|
||||
GROUP BY channel_id
|
||||
ORDER BY COUNT(*) DESC, channel_id
|
||||
`),
|
||||
this.prisma.$queryRaw<Array<{
|
||||
id: string;
|
||||
signatureId: string;
|
||||
signatureName: string;
|
||||
tenantId: string;
|
||||
tenantName: string;
|
||||
hasDrainage: boolean;
|
||||
total: number;
|
||||
acceptedCount: number;
|
||||
submitFailureCount: number;
|
||||
successCount: number;
|
||||
unknownCount: number;
|
||||
failureCount: number;
|
||||
successRate: number;
|
||||
averageArrivalMs: number | null;
|
||||
}>>(Prisma.sql`
|
||||
WITH base AS (
|
||||
SELECT
|
||||
message."signatureId" AS signature_id,
|
||||
(message."drainageInfoId" IS NOT NULL) AS has_drainage,
|
||||
message.status,
|
||||
message."submitStatus" AS submit_status,
|
||||
message."receiptStatus" AS receipt_status,
|
||||
CASE
|
||||
WHEN (message.status = 'delivered' OR message."receiptStatus" = 'delivered')
|
||||
AND message."submittedAt" IS NOT NULL
|
||||
AND message."deliveredAt" >= message."submittedAt"
|
||||
THEN EXTRACT(EPOCH FROM (message."deliveredAt" - message."submittedAt")) * 1000
|
||||
END AS arrival_ms
|
||||
FROM "SmsMessageRecord" message
|
||||
WHERE message."signatureId" IS NOT NULL
|
||||
AND message."queuedAt" >= ${day.startAt}
|
||||
AND message."queuedAt" < ${day.endAt}
|
||||
)
|
||||
SELECT
|
||||
signature.id || ':' || CASE WHEN base.has_drainage THEN 'drainage' ELSE 'plain' END AS id,
|
||||
signature.id AS "signatureId",
|
||||
signature.name AS "signatureName",
|
||||
tenant.id AS "tenantId",
|
||||
tenant.name AS "tenantName",
|
||||
base.has_drainage AS "hasDrainage",
|
||||
COUNT(*)::integer AS total,
|
||||
COUNT(*) FILTER (
|
||||
WHERE COALESCE(base.status, '') <> 'submit_failed'
|
||||
AND COALESCE(base.submit_status, '') NOT IN ('rejected', 'timeout')
|
||||
)::integer AS "acceptedCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE base.status = 'submit_failed'
|
||||
OR base.submit_status IN ('rejected', 'timeout')
|
||||
)::integer AS "submitFailureCount",
|
||||
COUNT(*) FILTER (WHERE base.status = 'delivered' OR base.receipt_status = 'delivered')::integer AS "successCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE COALESCE(base.status, '') <> 'submit_failed'
|
||||
AND COALESCE(base.submit_status, '') NOT IN ('rejected', 'timeout')
|
||||
AND NOT (COALESCE(base.status = 'delivered', false) OR COALESCE(base.receipt_status = 'delivered', false))
|
||||
AND NOT (COALESCE(base.status IN ('failed', 'timeout'), false) OR COALESCE(base.receipt_status = 'undelivered', false))
|
||||
)::integer AS "unknownCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE COALESCE(base.status, '') <> 'submit_failed'
|
||||
AND COALESCE(base.submit_status, '') NOT IN ('rejected', 'timeout')
|
||||
AND NOT (COALESCE(base.status = 'delivered', false) OR COALESCE(base.receipt_status = 'delivered', false))
|
||||
AND (COALESCE(base.status IN ('failed', 'timeout'), false) OR COALESCE(base.receipt_status = 'undelivered', false))
|
||||
)::integer AS "failureCount",
|
||||
CASE
|
||||
WHEN COUNT(*) FILTER (
|
||||
WHERE COALESCE(base.status, '') <> 'submit_failed'
|
||||
AND COALESCE(base.submit_status, '') NOT IN ('rejected', 'timeout')
|
||||
) = 0 THEN 0
|
||||
ELSE ROUND(
|
||||
COUNT(*) FILTER (WHERE base.status = 'delivered' OR base.receipt_status = 'delivered')
|
||||
* 100.0
|
||||
/ COUNT(*) FILTER (
|
||||
WHERE COALESCE(base.status, '') <> 'submit_failed'
|
||||
AND COALESCE(base.submit_status, '') NOT IN ('rejected', 'timeout')
|
||||
),
|
||||
1
|
||||
)::double precision
|
||||
END AS "successRate",
|
||||
ROUND(AVG(base.arrival_ms) FILTER (WHERE base.arrival_ms IS NOT NULL))::integer AS "averageArrivalMs"
|
||||
FROM base
|
||||
JOIN "SmsSignature" signature ON signature.id = base.signature_id
|
||||
JOIN "Tenant" tenant ON tenant.id = signature."tenantId"
|
||||
GROUP BY signature.id, signature.name, tenant.id, tenant.name, base.has_drainage
|
||||
ORDER BY "successCount" DESC, total DESC, signature.name
|
||||
`),
|
||||
this.prisma.$queryRaw<Array<{
|
||||
total: number;
|
||||
successCount: number;
|
||||
unknownCount: number;
|
||||
failureCount: number;
|
||||
successRate: number;
|
||||
}>>(Prisma.sql`
|
||||
WITH base AS (
|
||||
SELECT message.status, message."receiptStatus" AS receipt_status
|
||||
FROM "SmsMessageRecord" message
|
||||
WHERE message."queuedAt" >= ${day.startAt}
|
||||
AND message."queuedAt" < ${day.endAt}
|
||||
AND COALESCE(message.status, '') <> 'rejected'
|
||||
)
|
||||
SELECT
|
||||
COUNT(*)::integer AS total,
|
||||
COUNT(*) FILTER (WHERE base.status = 'delivered' OR base.receipt_status = 'delivered')::integer AS "successCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE NOT (COALESCE(base.status = 'delivered', false) OR COALESCE(base.receipt_status = 'delivered', false))
|
||||
AND NOT (COALESCE(base.status IN ('submit_failed', 'failed', 'timeout'), false) OR COALESCE(base.receipt_status = 'undelivered', false))
|
||||
)::integer AS "unknownCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE NOT (COALESCE(base.status = 'delivered', false) OR COALESCE(base.receipt_status = 'delivered', false))
|
||||
AND (COALESCE(base.status IN ('submit_failed', 'failed', 'timeout'), false) OR COALESCE(base.receipt_status = 'undelivered', false))
|
||||
)::integer AS "failureCount",
|
||||
CASE
|
||||
WHEN COUNT(*) = 0 THEN 0
|
||||
ELSE ROUND(
|
||||
COUNT(*) FILTER (WHERE base.status = 'delivered' OR base.receipt_status = 'delivered')
|
||||
* 100.0 / COUNT(*),
|
||||
1
|
||||
)::double precision
|
||||
END AS "successRate"
|
||||
FROM base
|
||||
`),
|
||||
this.prisma.$queryRaw<Array<{
|
||||
applicationId: string;
|
||||
applicationName: string;
|
||||
tenantId: string;
|
||||
tenantName: string;
|
||||
total: number;
|
||||
successCount: number;
|
||||
unknownCount: number;
|
||||
failureCount: number;
|
||||
successRate: number;
|
||||
}>>(Prisma.sql`
|
||||
WITH base AS (
|
||||
SELECT
|
||||
message."applicationId" AS application_id,
|
||||
message.status,
|
||||
message."receiptStatus" AS receipt_status
|
||||
FROM "SmsMessageRecord" message
|
||||
WHERE message."applicationId" IS NOT NULL
|
||||
AND message."queuedAt" >= ${day.startAt}
|
||||
AND message."queuedAt" < ${day.endAt}
|
||||
AND COALESCE(message.status, '') <> 'rejected'
|
||||
)
|
||||
SELECT
|
||||
application.id AS "applicationId",
|
||||
application.name AS "applicationName",
|
||||
tenant.id AS "tenantId",
|
||||
tenant.name AS "tenantName",
|
||||
COUNT(*)::integer AS total,
|
||||
COUNT(*) FILTER (WHERE base.status = 'delivered' OR base.receipt_status = 'delivered')::integer AS "successCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE NOT (COALESCE(base.status = 'delivered', false) OR COALESCE(base.receipt_status = 'delivered', false))
|
||||
AND NOT (COALESCE(base.status IN ('submit_failed', 'failed', 'timeout'), false) OR COALESCE(base.receipt_status = 'undelivered', false))
|
||||
)::integer AS "unknownCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE NOT (COALESCE(base.status = 'delivered', false) OR COALESCE(base.receipt_status = 'delivered', false))
|
||||
AND (COALESCE(base.status IN ('submit_failed', 'failed', 'timeout'), false) OR COALESCE(base.receipt_status = 'undelivered', false))
|
||||
)::integer AS "failureCount",
|
||||
CASE
|
||||
WHEN COUNT(*) = 0 THEN 0
|
||||
ELSE ROUND(
|
||||
COUNT(*) FILTER (WHERE base.status = 'delivered' OR base.receipt_status = 'delivered')
|
||||
* 100.0 / COUNT(*),
|
||||
1
|
||||
)::double precision
|
||||
END AS "successRate"
|
||||
FROM base
|
||||
JOIN "SmsApplication" application ON application.id = base.application_id
|
||||
JOIN "Tenant" tenant ON tenant.id = application."tenantId"
|
||||
GROUP BY application.id, application.name, tenant.id, tenant.name
|
||||
ORDER BY total DESC, application.name
|
||||
`),
|
||||
]);
|
||||
const summary = summaryRows[0] ?? {
|
||||
total: 0,
|
||||
successCount: 0,
|
||||
unknownCount: 0,
|
||||
failureCount: 0,
|
||||
successRate: 0,
|
||||
};
|
||||
return { date: day.key, summary, channels, signatures, applications };
|
||||
}
|
||||
async signatureQuality(query: SignatureQualityQuery) {
|
||||
const day = qualityBusinessDay(query.date);
|
||||
const page = positiveInteger(query.page, 1);
|
||||
const pageSize = Math.min(50, positiveInteger(query.pageSize, 10));
|
||||
const keyword = query.keyword?.trim() || null;
|
||||
const keywordPattern = keyword ? `%${keyword}%` : null;
|
||||
const summaries = await this.prisma.$queryRaw<Array<{
|
||||
signatureId: string;
|
||||
signatureName: string;
|
||||
tenantId: string;
|
||||
tenantName: string;
|
||||
applicationNames: string | null;
|
||||
total: number;
|
||||
acceptedCount: number;
|
||||
submitFailureCount: number;
|
||||
successCount: number;
|
||||
unknownCount: number;
|
||||
failureCount: number;
|
||||
successRate: number;
|
||||
averageArrivalMs: number | null;
|
||||
rowCount: number;
|
||||
}>>(Prisma.sql`
|
||||
WITH base AS (
|
||||
SELECT
|
||||
message."signatureId" AS signature_id,
|
||||
message."applicationId" AS application_id,
|
||||
message.status,
|
||||
message."submitStatus" AS submit_status,
|
||||
message."receiptStatus" AS receipt_status,
|
||||
CASE
|
||||
WHEN (message.status = 'delivered' OR message."receiptStatus" = 'delivered')
|
||||
AND message."submittedAt" IS NOT NULL
|
||||
AND message."deliveredAt" >= message."submittedAt"
|
||||
THEN EXTRACT(EPOCH FROM (message."deliveredAt" - message."submittedAt")) * 1000
|
||||
END AS arrival_ms
|
||||
FROM "SmsMessageRecord" message
|
||||
WHERE message."signatureId" IS NOT NULL
|
||||
AND message."queuedAt" >= ${day.startAt}
|
||||
AND message."queuedAt" < ${day.endAt}
|
||||
)
|
||||
SELECT
|
||||
signature.id AS "signatureId",
|
||||
signature.name AS "signatureName",
|
||||
tenant.id AS "tenantId",
|
||||
tenant.name AS "tenantName",
|
||||
STRING_AGG(DISTINCT application.name, '、') FILTER (WHERE application.name IS NOT NULL) AS "applicationNames",
|
||||
COUNT(*)::integer AS total,
|
||||
COUNT(*) FILTER (
|
||||
WHERE COALESCE(base.status, '') <> 'submit_failed'
|
||||
AND COALESCE(base.submit_status, '') NOT IN ('rejected', 'timeout')
|
||||
)::integer AS "acceptedCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE base.status = 'submit_failed'
|
||||
OR base.submit_status IN ('rejected', 'timeout')
|
||||
)::integer AS "submitFailureCount",
|
||||
COUNT(*) FILTER (WHERE base.status = 'delivered' OR base.receipt_status = 'delivered')::integer AS "successCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE COALESCE(base.status, '') <> 'submit_failed'
|
||||
AND COALESCE(base.submit_status, '') NOT IN ('rejected', 'timeout')
|
||||
AND NOT (COALESCE(base.status = 'delivered', false) OR COALESCE(base.receipt_status = 'delivered', false))
|
||||
AND NOT (COALESCE(base.status IN ('failed', 'timeout'), false) OR COALESCE(base.receipt_status = 'undelivered', false))
|
||||
)::integer AS "unknownCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE COALESCE(base.status, '') <> 'submit_failed'
|
||||
AND COALESCE(base.submit_status, '') NOT IN ('rejected', 'timeout')
|
||||
AND NOT (COALESCE(base.status = 'delivered', false) OR COALESCE(base.receipt_status = 'delivered', false))
|
||||
AND (COALESCE(base.status IN ('failed', 'timeout'), false) OR COALESCE(base.receipt_status = 'undelivered', false))
|
||||
)::integer AS "failureCount",
|
||||
CASE
|
||||
WHEN COUNT(*) FILTER (
|
||||
WHERE COALESCE(base.status, '') <> 'submit_failed'
|
||||
AND COALESCE(base.submit_status, '') NOT IN ('rejected', 'timeout')
|
||||
) = 0 THEN 0
|
||||
ELSE ROUND(
|
||||
COUNT(*) FILTER (WHERE base.status = 'delivered' OR base.receipt_status = 'delivered')
|
||||
* 100.0
|
||||
/ COUNT(*) FILTER (
|
||||
WHERE COALESCE(base.status, '') <> 'submit_failed'
|
||||
AND COALESCE(base.submit_status, '') NOT IN ('rejected', 'timeout')
|
||||
),
|
||||
1
|
||||
)::double precision
|
||||
END AS "successRate",
|
||||
ROUND(AVG(base.arrival_ms) FILTER (WHERE base.arrival_ms IS NOT NULL))::integer AS "averageArrivalMs",
|
||||
COUNT(*) OVER()::integer AS "rowCount"
|
||||
FROM base
|
||||
JOIN "SmsSignature" signature ON signature.id = base.signature_id
|
||||
JOIN "Tenant" tenant ON tenant.id = signature."tenantId"
|
||||
LEFT JOIN "SmsApplication" application ON application.id = base.application_id
|
||||
WHERE (
|
||||
${keyword}::text IS NULL
|
||||
OR signature.name ILIKE ${keywordPattern}
|
||||
OR tenant.name ILIKE ${keywordPattern}
|
||||
OR application.name ILIKE ${keywordPattern}
|
||||
)
|
||||
GROUP BY signature.id, signature.name, tenant.id, tenant.name
|
||||
ORDER BY total DESC, signature.name
|
||||
LIMIT ${pageSize}
|
||||
OFFSET ${(page - 1) * pageSize}
|
||||
`);
|
||||
const signatureIds = summaries.map((item) => item.signatureId);
|
||||
const breakdowns = signatureIds.length === 0
|
||||
? []
|
||||
: await this.prisma.$queryRaw<Array<{
|
||||
signatureId: string;
|
||||
channelId: string;
|
||||
channelName: string;
|
||||
carrier: string;
|
||||
total: number;
|
||||
acceptedCount: number;
|
||||
submitFailureCount: number;
|
||||
successCount: number;
|
||||
unknownCount: number;
|
||||
failureCount: number;
|
||||
successRate: number;
|
||||
averageArrivalMs: number | null;
|
||||
}>>(Prisma.sql`
|
||||
WITH base AS (
|
||||
SELECT
|
||||
message."signatureId" AS signature_id,
|
||||
submit."channelId" AS channel_id,
|
||||
channel.name AS channel_name,
|
||||
COALESCE(NULLIF(message.carrier, ''), 'unknown') AS carrier,
|
||||
submit."submitStatus" AS submit_status,
|
||||
receipt."deliveredAt" AS delivered_at,
|
||||
failed_receipt."failedAt" AS failed_at,
|
||||
COALESCE(segment_summary.segment_count, 0) AS segment_count,
|
||||
COALESCE(segment_summary.delivered_count, 0) AS segment_delivered_count,
|
||||
COALESCE(segment_summary.failure_count, 0) AS segment_failure_count,
|
||||
CASE
|
||||
WHEN segment_summary.segment_count > 0
|
||||
AND segment_summary.delivered_count = segment_summary.segment_count
|
||||
AND segment_summary.completed_at >= COALESCE(submit."submittedAt", submit."createdAt")
|
||||
THEN EXTRACT(EPOCH FROM (segment_summary.completed_at - COALESCE(submit."submittedAt", submit."createdAt"))) * 1000
|
||||
WHEN segment_summary.segment_count = 0
|
||||
AND receipt."deliveredAt" >= COALESCE(submit."submittedAt", submit."createdAt")
|
||||
THEN EXTRACT(EPOCH FROM (receipt."deliveredAt" - COALESCE(submit."submittedAt", submit."createdAt"))) * 1000
|
||||
END AS arrival_ms
|
||||
FROM "SmsSubmitRecord" submit
|
||||
JOIN "SmsMessageRecord" message ON message.id = submit."messageRecordId"
|
||||
JOIN "SmsChannel" channel ON channel.id = submit."channelId"
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT
|
||||
COUNT(*)::integer AS segment_count,
|
||||
COUNT(*) FILTER (WHERE segment."receiptStatus" = 'delivered')::integer AS delivered_count,
|
||||
COUNT(*) FILTER (WHERE segment."receiptStatus" = 'undelivered')::integer AS failure_count,
|
||||
MAX(segment."deliveredAt") FILTER (WHERE segment."receiptStatus" = 'delivered') AS completed_at
|
||||
FROM "SmsMessageSegmentAudit" segment
|
||||
WHERE segment."submitRecordId" = submit.id
|
||||
) segment_summary ON TRUE
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT MIN(receipt."deliveredAt") AS "deliveredAt"
|
||||
FROM "SmsReceiptRecord" receipt
|
||||
WHERE receipt."gatewayMessageId" = submit."gatewayMessageId"
|
||||
AND receipt."channelId" = submit."channelId"
|
||||
AND receipt."receiptStatus" = 'delivered'
|
||||
) receipt ON TRUE
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT MIN(receipt."deliveredAt") AS "failedAt"
|
||||
FROM "SmsReceiptRecord" receipt
|
||||
WHERE receipt."gatewayMessageId" = submit."gatewayMessageId"
|
||||
AND receipt."channelId" = submit."channelId"
|
||||
AND receipt."receiptStatus" = 'undelivered'
|
||||
) failed_receipt ON TRUE
|
||||
WHERE message."signatureId" IN (${Prisma.join(signatureIds)})
|
||||
AND submit."submitStatus" IN ('accepted', 'rejected', 'timeout')
|
||||
AND COALESCE(submit."submittedAt", submit."createdAt") >= ${day.startAt}
|
||||
AND COALESCE(submit."submittedAt", submit."createdAt") < ${day.endAt}
|
||||
), classified AS (
|
||||
SELECT
|
||||
*,
|
||||
CASE
|
||||
WHEN submit_status <> 'accepted' THEN 'submit_failed'
|
||||
WHEN segment_count > 0 AND segment_failure_count > 0 THEN 'failure'
|
||||
WHEN segment_count > 0 AND segment_delivered_count = segment_count THEN 'success'
|
||||
WHEN segment_count = 0 AND failed_at IS NOT NULL THEN 'failure'
|
||||
WHEN segment_count = 0 AND delivered_at IS NOT NULL THEN 'success'
|
||||
ELSE 'unknown'
|
||||
END AS delivery_status
|
||||
FROM base
|
||||
)
|
||||
SELECT
|
||||
signature_id AS "signatureId",
|
||||
channel_id AS "channelId",
|
||||
MAX(channel_name) AS "channelName",
|
||||
carrier,
|
||||
COUNT(*)::integer AS total,
|
||||
COUNT(*) FILTER (WHERE submit_status = 'accepted')::integer AS "acceptedCount",
|
||||
COUNT(*) FILTER (WHERE delivery_status = 'submit_failed')::integer AS "submitFailureCount",
|
||||
COUNT(*) FILTER (WHERE delivery_status = 'success')::integer AS "successCount",
|
||||
COUNT(*) FILTER (WHERE delivery_status = 'unknown')::integer AS "unknownCount",
|
||||
COUNT(*) FILTER (WHERE delivery_status = 'failure')::integer AS "failureCount",
|
||||
CASE
|
||||
WHEN COUNT(*) FILTER (WHERE submit_status = 'accepted') = 0 THEN 0
|
||||
ELSE ROUND(
|
||||
COUNT(*) FILTER (WHERE delivery_status = 'success')
|
||||
* 100.0 / COUNT(*) FILTER (WHERE submit_status = 'accepted'),
|
||||
1
|
||||
)::double precision
|
||||
END AS "successRate",
|
||||
ROUND(AVG(arrival_ms) FILTER (WHERE delivery_status = 'success' AND arrival_ms IS NOT NULL))::integer AS "averageArrivalMs"
|
||||
FROM classified
|
||||
GROUP BY signature_id, channel_id, carrier
|
||||
ORDER BY signature_id, COUNT(*) DESC, channel_id, carrier
|
||||
`);
|
||||
const carrierOverview = signatureIds.length === 0
|
||||
? []
|
||||
: await this.prisma.$queryRaw<Array<{
|
||||
signatureId: string;
|
||||
carrier: string;
|
||||
businessMessageCount: number;
|
||||
finalSuccessCount: number;
|
||||
finalSuccessRate: number;
|
||||
averageArrivalMs: number | null;
|
||||
}>>(Prisma.sql`
|
||||
SELECT
|
||||
message."signatureId" AS "signatureId",
|
||||
COALESCE(NULLIF(message.carrier, ''), 'unknown') AS carrier,
|
||||
COUNT(*)::integer AS "businessMessageCount",
|
||||
COUNT(*) FILTER (
|
||||
WHERE message.status = 'delivered'
|
||||
OR message."receiptStatus" = 'delivered'
|
||||
)::integer AS "finalSuccessCount",
|
||||
CASE
|
||||
WHEN COUNT(*) = 0 THEN 0
|
||||
ELSE ROUND(
|
||||
COUNT(*) FILTER (
|
||||
WHERE message.status = 'delivered'
|
||||
OR message."receiptStatus" = 'delivered'
|
||||
) * 100.0 / COUNT(*),
|
||||
1
|
||||
)::double precision
|
||||
END AS "finalSuccessRate",
|
||||
ROUND(AVG(
|
||||
CASE
|
||||
WHEN (message.status = 'delivered' OR message."receiptStatus" = 'delivered')
|
||||
AND message."submittedAt" IS NOT NULL
|
||||
AND message."deliveredAt" >= message."submittedAt"
|
||||
THEN EXTRACT(EPOCH FROM (message."deliveredAt" - message."submittedAt")) * 1000
|
||||
END
|
||||
))::integer AS "averageArrivalMs"
|
||||
FROM "SmsMessageRecord" message
|
||||
WHERE message."signatureId" IN (${Prisma.join(signatureIds)})
|
||||
AND message."queuedAt" >= ${day.startAt}
|
||||
AND message."queuedAt" < ${day.endAt}
|
||||
GROUP BY message."signatureId", COALESCE(NULLIF(message.carrier, ''), 'unknown')
|
||||
ORDER BY message."signatureId", COUNT(*) DESC, carrier
|
||||
`);
|
||||
const items = summaries.map(({ rowCount: _rowCount, ...summary }) => {
|
||||
const signatureBreakdowns = breakdowns.filter((item) => item.signatureId === summary.signatureId);
|
||||
return {
|
||||
...summary,
|
||||
channelSubmitTotal: signatureBreakdowns.reduce((sum, item) => sum + item.total, 0),
|
||||
carrierOverview: carrierOverview.filter((item) => item.signatureId === summary.signatureId),
|
||||
breakdowns: signatureBreakdowns,
|
||||
};
|
||||
});
|
||||
return {
|
||||
date: day.key,
|
||||
items,
|
||||
total: summaries[0]?.rowCount ?? 0,
|
||||
page,
|
||||
pageSize,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { moneyToNumber } from '../../common/money';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import type { MessageQuery, TraceQuery, OperationLogQuery, GatewaySubmitDeadLetterQuery, DownstreamDeliveryQuery, DownstreamDeliveryDashboardQuery, DownstreamRecoveryStatusQuery, MessageSegmentAuditQuery, SignatureQualityQuery } from '../operations.contracts';
|
||||
import { messageWhere, recognizedCarrierValues, carrierWhere, startOfShanghaiDay, endOfShanghaiDay, qualityBusinessDay, shanghaiDateKey, normalizeGroupBy, returnedTransactionWhere, createdAtRange, downstreamAlertPendingMinutes, downstreamAlertRecentFailedHours, downstreamAlertWindows, downstreamAlertWhere, stalledPendingWhere, downstreamDeliveryScopedWhere, parseDateBoundary, downstreamRecoveryStatusWhere, escapeCsvCell, formatCsvDate, formatExportTimestamp, clientApplicationView, clientReceiptView, clientMessageView, clientBatchTaskView, clientUplinkView, clientAccountView, clientRechargeView, summarizeMessageGroups, groupDownstreamByType, groupDownstreamByApplication, positiveInteger, operationLogLevelWhere, normalizeOperationLog, sanitizeGatewaySubmitException, redactGatewayCommandValue } from '../operations.helpers';
|
||||
|
||||
// R2 trace query domain. Method bodies are preserved byte-for-byte from the facade baseline.
|
||||
export class OperationsTraceQueries {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
auditSummary(query: { tenantId?: string }) {
|
||||
return this.prisma.operationLog.groupBy({
|
||||
by: ['action', 'resource'],
|
||||
where: { tenantId: query.tenantId },
|
||||
_count: { _all: true },
|
||||
orderBy: { _count: { action: 'desc' } },
|
||||
take: 100,
|
||||
});
|
||||
}
|
||||
async trace(query: TraceQuery) {
|
||||
const messages = await this.prisma.smsMessageRecord.findMany({
|
||||
where: {
|
||||
...messageWhere(query),
|
||||
messageId: query.messageId,
|
||||
},
|
||||
include: {
|
||||
batchTask: { include: { apiRequests: true } },
|
||||
submitRecords: { include: { session: true } },
|
||||
receiptRecords: true,
|
||||
},
|
||||
orderBy: { queuedAt: 'desc' },
|
||||
take: 100,
|
||||
});
|
||||
const messageIds = messages.map((message) => message.messageId);
|
||||
const [billingRecords, uplinks] = await Promise.all([
|
||||
this.prisma.smsBillingRecord.findMany({
|
||||
where: {
|
||||
tenantId: query.tenantId,
|
||||
taskId: query.taskId,
|
||||
messageId: messageIds.length > 0 ? { in: messageIds } : undefined,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
}),
|
||||
this.prisma.smsUplinkMessage.findMany({
|
||||
where: {
|
||||
tenantId: query.tenantId,
|
||||
messageId: messageIds.length > 0 ? { in: messageIds } : undefined,
|
||||
},
|
||||
orderBy: { receivedAt: 'desc' },
|
||||
}),
|
||||
]);
|
||||
return { messages, billingRecords, uplinks };
|
||||
}
|
||||
async reconciliation(query: { tenantId?: string; taskId?: string }) {
|
||||
const [messages, billing, transactions] = await Promise.all([
|
||||
this.prisma.smsMessageRecord.aggregate({
|
||||
where: messageWhere({ tenantId: query.tenantId, taskId: query.taskId }),
|
||||
_count: { _all: true },
|
||||
_sum: { amountCents: true, billingUnits: true },
|
||||
}),
|
||||
this.prisma.smsBillingRecord.aggregate({
|
||||
where: { tenantId: query.tenantId, taskId: query.taskId },
|
||||
_count: { _all: true },
|
||||
_sum: { amountCents: true, billingUnits: true },
|
||||
}),
|
||||
this.prisma.accountTransaction.aggregate({
|
||||
where: {
|
||||
tenantId: query.tenantId,
|
||||
relatedType: query.taskId ? { in: ['sms_batch_task', 'sms_message_record'] } : undefined,
|
||||
relatedId: query.taskId,
|
||||
},
|
||||
_count: { _all: true },
|
||||
_sum: { amountCents: true },
|
||||
}),
|
||||
]);
|
||||
const messageAmount = moneyToNumber(messages._sum.amountCents);
|
||||
const billingAmount = moneyToNumber(billing._sum.amountCents);
|
||||
const transactionAmount = moneyToNumber(transactions._sum.amountCents);
|
||||
return {
|
||||
messages,
|
||||
billing,
|
||||
transactions,
|
||||
diff: {
|
||||
messageVsBillingAmountCents: messageAmount - billingAmount,
|
||||
billingVsTransactionAmountCents: billingAmount + transactionAmount,
|
||||
messageVsBillingUnits: (messages._sum.billingUnits ?? 0) - (billing._sum.billingUnits ?? 0),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { BadRequestException, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { moneyToNumber } from '../../common/money';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import type { MessageQuery, TraceQuery, OperationLogQuery, GatewaySubmitDeadLetterQuery, DownstreamDeliveryQuery, DownstreamDeliveryDashboardQuery, DownstreamRecoveryStatusQuery, MessageSegmentAuditQuery, SignatureQualityQuery } from '../operations.contracts';
|
||||
import { messageWhere, recognizedCarrierValues, carrierWhere, startOfShanghaiDay, endOfShanghaiDay, qualityBusinessDay, shanghaiDateKey, normalizeGroupBy, returnedTransactionWhere, createdAtRange, downstreamAlertPendingMinutes, downstreamAlertRecentFailedHours, downstreamAlertWindows, downstreamAlertWhere, stalledPendingWhere, downstreamDeliveryScopedWhere, parseDateBoundary, downstreamRecoveryStatusWhere, escapeCsvCell, formatCsvDate, formatExportTimestamp, clientApplicationView, clientReceiptView, clientMessageView, clientBatchTaskView, clientUplinkView, clientAccountView, clientRechargeView, summarizeMessageGroups, groupDownstreamByType, groupDownstreamByApplication, positiveInteger, operationLogLevelWhere, normalizeOperationLog, sanitizeGatewaySubmitException, redactGatewayCommandValue } from '../operations.helpers';
|
||||
|
||||
// R2 uplink query domain. Method bodies are preserved byte-for-byte from the facade baseline.
|
||||
export class OperationsUplinkQueries {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
listUplinkMessages(query: { tenantId?: string; channelId?: string; applicationId?: string; phoneNumber?: string; keyword?: string; startTime?: string; endTime?: string; page?: number; pageSize?: number }) {
|
||||
return this.prisma.smsUplinkMessage.findMany({
|
||||
where: {
|
||||
tenantId: query.tenantId,
|
||||
channelId: query.channelId,
|
||||
applicationId: query.applicationId,
|
||||
phoneNumber: query.phoneNumber ? { contains: query.phoneNumber } : undefined,
|
||||
content: query.keyword ? { contains: query.keyword } : undefined,
|
||||
receivedAt: query.startTime || query.endTime ? { gte: query.startTime ? new Date(query.startTime) : undefined, lte: query.endTime ? new Date(query.endTime) : undefined } : undefined,
|
||||
},
|
||||
include: {
|
||||
tenant: true,
|
||||
application: true,
|
||||
channel: true,
|
||||
messageRecord: { include: { application: true } },
|
||||
matchCandidates: {
|
||||
include: {
|
||||
tenant: true,
|
||||
application: true,
|
||||
messageRecord: { include: { application: true, tenant: true, channel: true } },
|
||||
},
|
||||
orderBy: [{ status: 'asc' }, { confidence: 'desc' }, { createdAt: 'asc' }],
|
||||
},
|
||||
},
|
||||
orderBy: { receivedAt: 'desc' },
|
||||
skip: query.page && query.pageSize ? (query.page - 1) * query.pageSize : undefined,
|
||||
take: query.pageSize ?? 500,
|
||||
});
|
||||
}
|
||||
async listClientUplinkMessages(query: { tenantId?: string; applicationId?: string; phoneNumber?: string; keyword?: string; startTime?: string; endTime?: string; page?: number; pageSize?: number }) {
|
||||
const items = await this.listUplinkMessages(query);
|
||||
return items.map(clientUplinkView);
|
||||
}
|
||||
async listUplinkMessagesPage(query: { tenantId?: string; channelId?: string; applicationId?: string; phoneNumber?: string; keyword?: string; startTime?: string; endTime?: string; page?: number; pageSize?: number }, clientView = false) {
|
||||
const page = Math.max(1, Math.floor(Number(query.page) || 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 10)));
|
||||
const where: Prisma.SmsUplinkMessageWhereInput = {
|
||||
tenantId: query.tenantId,
|
||||
channelId: query.channelId,
|
||||
applicationId: query.applicationId,
|
||||
phoneNumber: query.phoneNumber ? { contains: query.phoneNumber } : undefined,
|
||||
content: query.keyword ? { contains: query.keyword } : undefined,
|
||||
receivedAt: query.startTime || query.endTime ? {
|
||||
gte: query.startTime ? new Date(query.startTime) : undefined,
|
||||
lte: query.endTime ? new Date(query.endTime) : undefined,
|
||||
} : undefined,
|
||||
};
|
||||
const [rawItems, total] = await Promise.all([
|
||||
this.listUplinkMessages({ ...query, page, pageSize }),
|
||||
this.prisma.smsUplinkMessage.count({ where }),
|
||||
]);
|
||||
return {
|
||||
items: clientView ? rawItems.map(clientUplinkView) : rawItems,
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
};
|
||||
}
|
||||
async monitor(query: { tenantId?: string; channelId?: string }) {
|
||||
const where = messageWhere(query);
|
||||
const [byStatus, recentMessages, recentReceipts, recentUplinks] = await Promise.all([
|
||||
this.prisma.smsMessageRecord.groupBy({ by: ['status'], where, _count: { _all: true } }),
|
||||
this.prisma.smsMessageRecord.findMany({
|
||||
where,
|
||||
include: { submitRecords: true, receiptRecords: true },
|
||||
orderBy: { queuedAt: 'desc' },
|
||||
take: 20,
|
||||
}),
|
||||
this.prisma.smsReceiptRecord.findMany({
|
||||
where: { tenantId: query.tenantId, channelId: query.channelId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 20,
|
||||
}),
|
||||
this.listUplinkMessages({ tenantId: query.tenantId, channelId: query.channelId }),
|
||||
]);
|
||||
return {
|
||||
byStatus,
|
||||
recentMessages,
|
||||
recentReceipts,
|
||||
recentUplinks: recentUplinks.slice(0, 20),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import ExcelJS from 'exceljs';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { extname } from 'node:path';
|
||||
import { FilesService } from '../files/files.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsConfigService } from '../sms-config/sms-config.service';
|
||||
import type { AnalyzeImportOptions, CreateImportProfileDto, CreateReportBatchDto, EmbeddedImage, ImportCommitDto, ImportMapping, PagedQuery, ReportBatchInspection, ReportBatchTarget, ReviewImportItemsDto } from './report-materials.contracts';
|
||||
import { profileData, validateProfile, loadWorkbook, assertSafeWorkbook, safeSpreadsheetText, readEmbeddedImages, suggestMappings, remapProfileColumns, signatureCoreMapping, drainageCoreMapping, normalizeHeader, normalizeFieldCode, clamp, normalizePage, normalizePageSize, dateRange, cellText, transformValue, mappedCoreValue, dynamicValues, jsonRecord, hasValue, isFileRef, resolveExportValue, applyExportTransform, styleHeader, normalizeImageExtension, imageContentType, safeFileName, normalizeBatchIdempotencyKey, jsonStringArray, jsonSafe } from './report-materials.helpers';
|
||||
import { ReportBatchOperationService } from './batch-operation.service';
|
||||
import { ReportChannelExportService } from './channel-export.service';
|
||||
|
||||
/** R4 report-materials domain service composed behind ReportMaterialsService. */
|
||||
export class ReportBatchGenerationService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly files: FilesService, private readonly smsConfig: SmsConfigService, private readonly operations: ReportBatchOperationService, private readonly channelExport: ReportChannelExportService) {}
|
||||
|
||||
async listBatches(query: PagedQuery = {}) {
|
||||
const page = normalizePage(query.page);
|
||||
const pageSize = normalizePageSize(query.pageSize);
|
||||
const where: Prisma.ReportMaterialBatchWhereInput = {
|
||||
createdAt: dateRange(query.startAt, query.endAt),
|
||||
batchNo: query.keyword?.trim() ? { contains: query.keyword.trim() } : undefined,
|
||||
};
|
||||
const [batches, total] = await Promise.all([
|
||||
this.prisma.reportMaterialBatch.findMany({
|
||||
where,
|
||||
include: {
|
||||
exportFiles: {
|
||||
include: {
|
||||
items: { include: { task: { select: { id: true, status: true } } } },
|
||||
},
|
||||
},
|
||||
items: true,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.reportMaterialBatch.count({ where }),
|
||||
]);
|
||||
return {
|
||||
items: batches.map((batch) => {
|
||||
const reportItems = batch.exportFiles.flatMap((file) => file.items);
|
||||
const reportTotal = reportItems.length;
|
||||
const successCount = reportItems.filter((item) => item.task.status === 'approved').length;
|
||||
return {
|
||||
...batch,
|
||||
reportTotal,
|
||||
successCount,
|
||||
successRate: reportTotal ? successCount / reportTotal : 0,
|
||||
};
|
||||
}),
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
};
|
||||
}
|
||||
|
||||
async createBatch(data: CreateReportBatchDto) {
|
||||
if (!data.items?.length) throw new BadRequestException('请选择需要报备的签名或引流信息');
|
||||
const idempotencyKey = normalizeBatchIdempotencyKey(data.idempotencyKey);
|
||||
const uniqueItems = [...new Map(data.items.map((item) => [`${item.reportType}:${item.drainageItemId ?? item.signatureId}`, item])).values()];
|
||||
const fingerprint = createHash('sha256').update(JSON.stringify(uniqueItems.map((item) => ({ reportType: item.reportType, signatureId: item.signatureId, drainageItemId: item.drainageItemId ?? null, materialVersion: item.materialVersion ?? null })).sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right))))).digest('hex');
|
||||
const claimed = await this.operations.claimBatchOperation(idempotencyKey, fingerprint, data.createdById);
|
||||
if (claimed.replayed) return claimed.result;
|
||||
|
||||
let preflight: Awaited<ReturnType<ReportBatchGenerationService['preflightBatch']>>;
|
||||
try {
|
||||
preflight = await this.preflightBatch({ items: uniqueItems });
|
||||
} catch (error) {
|
||||
await this.operations.failBatchOperation(claimed.operationId, error instanceof Error ? error.message : '报备资格预检失败');
|
||||
throw error;
|
||||
}
|
||||
if (preflight.eligibleTargetCount === 0) {
|
||||
await this.operations.failBatchOperation(claimed.operationId, '没有可生成的报备目标');
|
||||
throw new BadRequestException({ code: 'REPORT_BATCH_NOT_ELIGIBLE', message: '所选资料没有可生成的通道,请按资格检查补充后重试', preflight });
|
||||
}
|
||||
const eligibleInspections = preflight.items.filter((item) => item.targets.some((target) => target.eligible));
|
||||
const batch = await this.prisma.reportMaterialBatch.create({
|
||||
data: { batchNo: `RB${new Date().toISOString().replace(/\D/g, '').slice(0, 14)}${randomUUID().slice(0, 4).toUpperCase()}`, createdById: data.createdById, selectedCount: eligibleInspections.length },
|
||||
});
|
||||
try {
|
||||
const prepared = [];
|
||||
for (const inspection of eligibleInspections) {
|
||||
const selected = uniqueItems.find((item) => item.reportType === inspection.reportType && (item.drainageItemId ?? item.signatureId) === (inspection.drainageItemId ?? inspection.signatureId))!;
|
||||
prepared.push(await this.prepareBatchItem(batch.id, selected, inspection));
|
||||
}
|
||||
const channelMap = new Map<string, Array<(typeof prepared)[number]>>();
|
||||
for (const item of prepared) {
|
||||
for (const channel of item.channels) {
|
||||
const current = channelMap.get(channel.id) ?? [];
|
||||
current.push({ ...item, channels: [channel] });
|
||||
channelMap.set(channel.id, current);
|
||||
}
|
||||
}
|
||||
const exportedFiles = [];
|
||||
const incomplete = new Set<string>(prepared.filter((item) => item.channels.length === 0).map((item) => item.batchItem.id));
|
||||
let failedTargetCount = 0;
|
||||
for (const [channelId, items] of channelMap) {
|
||||
const result = await this.channelExport.exportChannelBatch(batch.id, channelId, items);
|
||||
exportedFiles.push(result.file);
|
||||
failedTargetCount += result.incompleteBatchItemIds.length;
|
||||
for (const itemId of result.incompleteBatchItemIds) incomplete.add(itemId);
|
||||
}
|
||||
for (const item of prepared) {
|
||||
if (incomplete.has(item.batchItem.id) || item.channels.length === 0) continue;
|
||||
if (item.reportType === 'signature') await this.prisma.smsSignature.update({ where: { id: item.signature.id }, data: { pendingReport: false } });
|
||||
else await this.prisma.smsDrainageInfo.update({ where: { id: item.drainageInfo!.id }, data: { pendingReport: false } });
|
||||
}
|
||||
const completed = await this.prisma.reportMaterialBatch.update({ where: { id: batch.id }, data: { status: incomplete.size ? 'partial_failed' : 'completed', channelCount: channelMap.size, fileCount: exportedFiles.length, completedAt: new Date() }, include: { exportFiles: true, items: true } });
|
||||
const result = {
|
||||
...completed,
|
||||
operationId: claimed.operationId,
|
||||
replayed: false,
|
||||
result: {
|
||||
successCount: preflight.eligibleTargetCount - failedTargetCount,
|
||||
skippedCount: preflight.skippedTargetCount,
|
||||
failedCount: failedTargetCount,
|
||||
items: preflight.items,
|
||||
},
|
||||
};
|
||||
await this.operations.completeBatchOperation(claimed.operationId, batch.id, result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
await this.prisma.reportMaterialBatch.update({ where: { id: batch.id }, data: { status: 'failed', errorMessage: error instanceof Error ? error.message : '生成报备批次失败', completedAt: new Date() } });
|
||||
await this.operations.failBatchOperation(claimed.operationId, error instanceof Error ? error.message : '生成报备批次失败', batch.id);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async preflightBatch(data: Pick<CreateReportBatchDto, 'items'>) {
|
||||
if (!data.items?.length) throw new BadRequestException('请选择需要报备的签名或引流信息');
|
||||
for (const item of data.items) {
|
||||
if (!['signature', 'drainage'].includes(item.reportType) || !item.signatureId) throw new BadRequestException({ code: 'REPORT_BATCH_ITEM_INVALID', message: '每条报备资料必须包含有效的资料类型和签名ID' });
|
||||
if (item.reportType === 'drainage' && !item.drainageItemId) throw new BadRequestException({ code: 'REPORT_BATCH_ITEM_INVALID', message: '引流资料必须包含引流资料ID' });
|
||||
}
|
||||
const uniqueItems = [...new Map(data.items.map((item) => [`${item.reportType}:${item.drainageItemId ?? item.signatureId}`, item])).values()];
|
||||
const items = await Promise.all(uniqueItems.map((item) => this.inspectBatchItem(item)));
|
||||
return {
|
||||
checkedAt: new Date().toISOString(),
|
||||
eligible: items.some((item) => item.eligible),
|
||||
eligibleItemCount: items.filter((item) => item.eligible).length,
|
||||
blockedItemCount: items.filter((item) => !item.eligible).length,
|
||||
eligibleTargetCount: items.reduce((sum, item) => sum + item.targets.filter((target) => target.eligible).length, 0),
|
||||
skippedTargetCount: items.reduce((sum, item) => sum + item.targets.filter((target) => !target.eligible).length, 0),
|
||||
items,
|
||||
};
|
||||
}
|
||||
|
||||
async prepareBatchItem(batchId: string, selected: CreateReportBatchDto['items'][number], inspection: ReportBatchInspection) {
|
||||
const signature = await this.prisma.smsSignature.findUnique({ where: { id: selected.signatureId }, include: { tenant: true, application: true } });
|
||||
if (!signature || signature.auditStatus !== 'approved') throw new BadRequestException('签名不存在或未审核通过');
|
||||
const drainageInfo = selected.reportType === 'drainage' && selected.drainageItemId
|
||||
? await this.prisma.smsDrainageInfo.findUnique({ where: { id: selected.drainageItemId } }) : null;
|
||||
if (selected.reportType === 'drainage' && (!drainageInfo || drainageInfo.signatureId !== signature.id || drainageInfo.auditStatus !== 'approved')) throw new BadRequestException('引流信息不存在或未审核通过');
|
||||
const routes = signature.applicationId ? await this.prisma.channelRouteRule.findMany({
|
||||
where: { applicationId: signature.applicationId, status: 'active' },
|
||||
include: { group: { include: { items: { include: { channel: true }, orderBy: { priority: 'asc' } } } } },
|
||||
orderBy: { priority: 'asc' },
|
||||
}) : [];
|
||||
const eligibleChannelIds = new Set(inspection.targets.filter((target) => target.eligible).map((target) => target.id));
|
||||
const channels = [...new Map(routes.flatMap((route) => route.group.items.map((entry) => entry.channel)).filter((channel) => channel.status === 'active' && eligibleChannelIds.has(channel.id)).map((channel) => [channel.id, channel])).values()];
|
||||
const snapshot = selected.reportType === 'signature'
|
||||
? { reportType: 'signature', applicationId: signature.applicationId, businessKeys: inspection.targets.filter((target) => target.eligible).map((target) => target.businessKey), signature: { id: signature.id, name: signature.name, purpose: signature.purpose, tenantName: signature.tenant.name, applicationName: signature.application?.name }, values: jsonRecord(jsonRecord(signature.drainageInfo).signatureReportValues) }
|
||||
: { reportType: 'drainage', applicationId: signature.applicationId, businessKeys: inspection.targets.filter((target) => target.eligible).map((target) => target.businessKey), signature: { id: signature.id, name: signature.name, tenantName: signature.tenant.name, applicationName: signature.application?.name }, drainage: { id: drainageInfo!.id, siteName: drainageInfo!.siteName, url: drainageInfo!.url, remark: drainageInfo!.remark }, values: jsonRecord(drainageInfo!.reportValues) };
|
||||
const materialVersion = selected.reportType === 'signature' ? signature.materialVersion : drainageInfo!.materialVersion;
|
||||
const batchItem = await this.prisma.reportMaterialBatchItem.create({ data: { batchId, signatureId: signature.id, drainageItemId: drainageInfo?.id, reportType: selected.reportType, materialVersion, snapshot: snapshot as Prisma.InputJsonValue } });
|
||||
return { batchItem, signature, drainageInfo, reportType: selected.reportType, snapshot, channels };
|
||||
}
|
||||
|
||||
async inspectBatchItem(selected: CreateReportBatchDto['items'][number]): Promise<ReportBatchInspection> {
|
||||
const signature = await this.prisma.smsSignature.findUnique({ where: { id: selected.signatureId }, include: { tenant: true, application: true } });
|
||||
if (!signature) throw new NotFoundException('签名不存在');
|
||||
const drainageInfo = selected.reportType === 'drainage' && selected.drainageItemId
|
||||
? await this.prisma.smsDrainageInfo.findUnique({ where: { id: selected.drainageItemId } }) : null;
|
||||
const materialVersion = selected.reportType === 'signature' ? signature.materialVersion : drainageInfo?.materialVersion ?? 0;
|
||||
const blockedReasons: string[] = [];
|
||||
if (signature.auditStatus !== 'approved') blockedReasons.push('签名尚未审核通过');
|
||||
if (!signature.pendingReport) blockedReasons.push('该签名版本已不在待报备池');
|
||||
if (!signature.applicationId || !signature.application) blockedReasons.push('未绑定短信应用');
|
||||
else if (signature.application.status !== 'active') blockedReasons.push('短信应用未启用');
|
||||
if (selected.materialVersion !== undefined && selected.materialVersion !== materialVersion) blockedReasons.push(`资料版本已变化(当前 V${materialVersion})`);
|
||||
if (selected.reportType === 'drainage') {
|
||||
if (!drainageInfo || drainageInfo.signatureId !== signature.id) blockedReasons.push('引流资料不存在或不属于当前签名');
|
||||
else {
|
||||
if (drainageInfo.auditStatus !== 'approved') blockedReasons.push('引流资料尚未审核通过');
|
||||
if (!drainageInfo.pendingReport) blockedReasons.push('该引流资料版本已不在待报备池');
|
||||
}
|
||||
}
|
||||
const snapshot = selected.reportType === 'signature'
|
||||
? { signature: { name: signature.name, purpose: signature.purpose, tenantName: signature.tenant.name, applicationName: signature.application?.name }, values: jsonRecord(jsonRecord(signature.drainageInfo).signatureReportValues) }
|
||||
: { signature: { name: signature.name, tenantName: signature.tenant.name, applicationName: signature.application?.name }, drainage: { siteName: drainageInfo?.siteName, url: drainageInfo?.url, remark: drainageInfo?.remark }, values: jsonRecord(drainageInfo?.reportValues) };
|
||||
const routes = signature.applicationId ? await this.prisma.channelRouteRule.findMany({
|
||||
where: { applicationId: signature.applicationId, status: 'active' },
|
||||
include: { group: { include: { items: { include: { channel: true }, orderBy: { priority: 'asc' } } } } },
|
||||
orderBy: { priority: 'asc' },
|
||||
}) : [];
|
||||
const channelCarriers = new Map<string, { channel: { id: string; name: string; status: string; carrier?: string | null }; carriers: Set<string> }>();
|
||||
for (const route of routes) {
|
||||
if (route.group.status !== 'active') continue;
|
||||
for (const entry of route.group.items) {
|
||||
if (entry.channel.status !== 'active') continue;
|
||||
const current = channelCarriers.get(entry.channel.id) ?? { channel: entry.channel, carriers: new Set<string>() };
|
||||
current.carriers.add(route.carrier || entry.carrier || entry.channel.carrier || 'all');
|
||||
channelCarriers.set(entry.channel.id, current);
|
||||
}
|
||||
}
|
||||
if (blockedReasons.length === 0 && channelCarriers.size === 0) blockedReasons.push('当前应用没有启用且可路由的通道');
|
||||
const previous = await this.prisma.reportMaterialBatchItem.findMany({
|
||||
where: { signatureId: signature.id, drainageItemId: selected.reportType === 'drainage' ? drainageInfo?.id : null, reportType: selected.reportType, materialVersion, batch: { status: { in: ['completed', 'partial_failed'] } } },
|
||||
select: { batchId: true, snapshot: true, exportItems: { select: { exportFile: { select: { channelId: true } } } } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
const priorKeys = new Map<string, string>();
|
||||
for (const item of previous) {
|
||||
const exportedChannelIds = new Set(item.exportItems.map((entry) => entry.exportFile.channelId).filter((value): value is string => Boolean(value)));
|
||||
for (const key of jsonStringArray(jsonRecord(item.snapshot).businessKeys)) {
|
||||
if ([...exportedChannelIds].some((channelId) => key.includes(`:channel:${channelId}:`)) && !priorKeys.has(key)) priorKeys.set(key, item.batchId);
|
||||
}
|
||||
}
|
||||
const targets: ReportBatchTarget[] = [];
|
||||
for (const { channel, carriers } of channelCarriers.values()) {
|
||||
const carrier = [...carriers].sort().join(',');
|
||||
const businessKey = `${selected.reportType}:${selected.drainageItemId ?? signature.id}:v${materialVersion}:app:${signature.applicationId}:channel:${channel.id}:carrier:${carrier}`;
|
||||
const targetReasons = [...blockedReasons];
|
||||
const fields = await this.prisma.channelReportField.findMany({ where: { channelId: channel.id, status: 'active', reportType: { in: [selected.reportType, 'both'] } }, orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }] });
|
||||
if (fields.length === 0) targetReasons.push('通道未配置当前资料类型的报备字段');
|
||||
else {
|
||||
const missing = fields.filter((field) => field.required && !hasValue(resolveExportValue(snapshot, field.code, field.name) ?? field.defaultValue));
|
||||
if (missing.length) targetReasons.push(`缺少必填字段:${missing.map((field) => field.exportName || field.name).join('、')}`);
|
||||
}
|
||||
const duplicateBatchId = priorKeys.get(businessKey);
|
||||
if (duplicateBatchId) targetReasons.push(`同一资料版本已在批次 ${duplicateBatchId} 生成`);
|
||||
targets.push({ id: channel.id, name: channel.name, carrier, businessKey, eligible: targetReasons.length === 0, blockedReasons: targetReasons, duplicateBatchId });
|
||||
}
|
||||
return {
|
||||
id: `${selected.reportType}:${selected.drainageItemId ?? signature.id}`,
|
||||
reportType: selected.reportType,
|
||||
signatureId: signature.id,
|
||||
drainageItemId: drainageInfo?.id,
|
||||
materialVersion,
|
||||
name: selected.reportType === 'signature' ? signature.name : drainageInfo?.siteName ?? '引流资料',
|
||||
tenantName: signature.tenant.name,
|
||||
applicationId: signature.applicationId ?? undefined,
|
||||
applicationName: signature.application?.name ?? '未指定应用',
|
||||
eligible: targets.some((target) => target.eligible),
|
||||
blockedReasons: targets.length ? [...new Set(targets.flatMap((target) => target.blockedReasons))] : blockedReasons,
|
||||
targets,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import ExcelJS from 'exceljs';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { extname } from 'node:path';
|
||||
import { FilesService } from '../files/files.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsConfigService } from '../sms-config/sms-config.service';
|
||||
import type { AnalyzeImportOptions, CreateImportProfileDto, CreateReportBatchDto, EmbeddedImage, ImportCommitDto, ImportMapping, PagedQuery, ReportBatchInspection, ReportBatchTarget, ReviewImportItemsDto } from './report-materials.contracts';
|
||||
import { profileData, validateProfile, loadWorkbook, assertSafeWorkbook, safeSpreadsheetText, readEmbeddedImages, suggestMappings, remapProfileColumns, signatureCoreMapping, drainageCoreMapping, normalizeHeader, normalizeFieldCode, clamp, normalizePage, normalizePageSize, dateRange, cellText, transformValue, mappedCoreValue, dynamicValues, jsonRecord, hasValue, isFileRef, resolveExportValue, applyExportTransform, styleHeader, normalizeImageExtension, imageContentType, safeFileName, normalizeBatchIdempotencyKey, jsonStringArray, jsonSafe } from './report-materials.helpers';
|
||||
|
||||
|
||||
/** R4 report-materials domain service composed behind ReportMaterialsService. */
|
||||
export class ReportBatchOperationService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly files: FilesService, private readonly smsConfig: SmsConfigService) {}
|
||||
|
||||
async claimBatchOperation(idempotencyKey: string, fingerprint: string, userId?: string) {
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${idempotencyKey}))`;
|
||||
const existing = await tx.operationLog.findFirst({ where: { action: 'report_material.batch_generation', resource: 'report_material_batch', resourceId: idempotencyKey }, orderBy: { createdAt: 'desc' } });
|
||||
if (existing) {
|
||||
const detail = jsonRecord(existing.detail);
|
||||
if (detail.fingerprint !== fingerprint) throw new ConflictException({ code: 'IDEMPOTENCY_KEY_REUSED', message: '该幂等键已用于不同的报备范围' });
|
||||
if (detail.status === 'completed' && detail.result) return { operationId: existing.id, replayed: true as const, result: { ...jsonRecord(detail.result), replayed: true, operationId: existing.id } };
|
||||
throw new ConflictException({ code: 'REPORT_BATCH_IN_PROGRESS', message: detail.status === 'failed' ? '上次生成失败,请使用新的操作单重试' : '该报备操作正在处理中,请勿重复提交' });
|
||||
}
|
||||
const operation = await tx.operationLog.create({ data: { userId, action: 'report_material.batch_generation', resource: 'report_material_batch', resourceId: idempotencyKey, detail: { status: 'processing', fingerprint } } });
|
||||
return { operationId: operation.id, replayed: false as const, result: null };
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
|
||||
}
|
||||
|
||||
async completeBatchOperation(operationId: string, batchId: string, result: Record<string, unknown>) {
|
||||
await this.prisma.operationLog.update({ where: { id: operationId }, data: { detail: { status: 'completed', batchId, fingerprint: jsonRecord((await this.prisma.operationLog.findUnique({ where: { id: operationId } }))?.detail).fingerprint, result: jsonSafe(result) } as Prisma.InputJsonValue } });
|
||||
}
|
||||
|
||||
async failBatchOperation(operationId: string, message: string, batchId?: string) {
|
||||
const operation = await this.prisma.operationLog.findUnique({ where: { id: operationId } });
|
||||
await this.prisma.operationLog.update({ where: { id: operationId }, data: { detail: { ...jsonRecord(operation?.detail), status: 'failed', batchId, message } as Prisma.InputJsonValue } });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import ExcelJS from 'exceljs';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { extname } from 'node:path';
|
||||
import { FilesService } from '../files/files.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsConfigService } from '../sms-config/sms-config.service';
|
||||
import type { AnalyzeImportOptions, CreateImportProfileDto, CreateReportBatchDto, EmbeddedImage, ImportCommitDto, ImportMapping, PagedQuery, ReportBatchInspection, ReportBatchTarget, ReviewImportItemsDto } from './report-materials.contracts';
|
||||
import { profileData, validateProfile, loadWorkbook, assertSafeWorkbook, safeSpreadsheetText, readEmbeddedImages, suggestMappings, remapProfileColumns, signatureCoreMapping, drainageCoreMapping, normalizeHeader, normalizeFieldCode, clamp, normalizePage, normalizePageSize, dateRange, cellText, transformValue, mappedCoreValue, dynamicValues, jsonRecord, hasValue, isFileRef, resolveExportValue, applyExportTransform, styleHeader, normalizeImageExtension, imageContentType, safeFileName, normalizeBatchIdempotencyKey, jsonStringArray, jsonSafe } from './report-materials.helpers';
|
||||
import type { ReportBatchGenerationService } from './batch-generation.service';
|
||||
|
||||
/** R4 report-materials domain service composed behind ReportMaterialsService. */
|
||||
export class ReportChannelExportService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly files: FilesService, private readonly smsConfig: SmsConfigService) {}
|
||||
|
||||
async exportChannelBatch(batchId: string, channelId: string, items: Array<Awaited<ReturnType<ReportBatchGenerationService['prepareBatchItem']>>>) {
|
||||
const channel = await this.prisma.smsChannel.findUnique({ where: { id: channelId } });
|
||||
if (!channel) throw new NotFoundException('通道不存在');
|
||||
const reportTypes = [...new Set(items.map((item) => item.reportType))];
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const fileRows: Array<{ item: (typeof items)[number]; taskId: string; rowNumber: number }> = [];
|
||||
const incompleteBatchItemIds: string[] = [];
|
||||
let totalRows = 0;
|
||||
for (const reportType of reportTypes) {
|
||||
const fields = await this.prisma.channelReportField.findMany({ where: { channelId, status: 'active', reportType: { in: [reportType, 'both'] } }, orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }] });
|
||||
const sheet = workbook.addWorksheet(reportType === 'signature' ? '签名报备' : '引流信息报备', { views: [{ state: 'frozen', ySplit: 1 }] });
|
||||
sheet.properties.defaultRowHeight = 22;
|
||||
sheet.columns = fields.map((field) => ({ header: field.exportName || field.name, key: field.code, width: field.columnWidth }));
|
||||
styleHeader(sheet.getRow(1));
|
||||
for (const item of items.filter((current) => current.reportType === reportType)) {
|
||||
const values = fields.map((field) => resolveExportValue(item.snapshot, field.code, field.name) ?? field.defaultValue ?? '');
|
||||
const missing = fields.filter((field, index) => field.required && !hasValue(values[index]));
|
||||
const missingReason = fields.length === 0 ? '通道未配置当前资料类型的报备字段' : missing.length ? `缺少字段:${missing.map((field) => field.exportName || field.name).join('、')}` : null;
|
||||
const existingTask = await this.prisma.channelSignatureReportTask.findFirst({ where: { signatureId: item.signature.id, channelId, reportType, drainageItemId: reportType === 'drainage' ? item.drainageInfo!.id : null } });
|
||||
const task = existingTask
|
||||
? await this.prisma.channelSignatureReportTask.update({ where: { id: existingTask.id }, data: { status: missingReason ? 'waiting_material' : 'exporting', reason: missingReason } })
|
||||
: await this.prisma.channelSignatureReportTask.create({ data: { tenantId: item.signature.tenantId, signatureId: item.signature.id, channelId, reportType, drainageItemId: item.drainageInfo?.id, status: missingReason ? 'waiting_material' : 'exporting', reason: missingReason } });
|
||||
if (missingReason) {
|
||||
incompleteBatchItemIds.push(item.batchItem.id);
|
||||
await this.recordTask(task.id, channelId, existingTask?.status, 'waiting_material', task.reason ?? undefined);
|
||||
continue;
|
||||
}
|
||||
const row = sheet.addRow(values.map((value, index) => isFileRef(value) ? value.fileName : applyExportTransform(value, fields[index]?.transform)));
|
||||
totalRows += 1;
|
||||
let targetHeight = 22;
|
||||
for (const [index, value] of values.entries()) {
|
||||
if (!isFileRef(value)) continue;
|
||||
const downloaded = await this.files.getDownload(value.fileObjectId);
|
||||
if (!downloaded.fileObject.contentType.startsWith('image/')) continue;
|
||||
const extension = normalizeImageExtension(extname(downloaded.fileObject.fileName).slice(1) || downloaded.fileObject.contentType.split('/')[1]);
|
||||
if (!['png', 'jpeg', 'gif'].includes(extension)) continue;
|
||||
const imageId = workbook.addImage({ base64: `data:${downloaded.fileObject.contentType};base64,${downloaded.content.toString('base64')}`, extension: extension as 'png' | 'jpeg' | 'gif' });
|
||||
const widthCells = Math.max(0.8, fields[index].imageWidth / Math.max(60, fields[index].columnWidth * 7));
|
||||
const heightRows = Math.max(0.8, fields[index].imageHeight / 20);
|
||||
sheet.addImage(imageId, { tl: { col: index + 0.08, row: row.number - 1 + 0.08 }, br: { col: index + Math.min(0.95, widthCells), row: row.number - 1 + Math.min(0.95, heightRows) }, editAs: 'oneCell' } as never);
|
||||
targetHeight = Math.max(targetHeight, fields[index].imageHeight * 0.75 + 8);
|
||||
}
|
||||
row.height = targetHeight;
|
||||
fileRows.push({ item, taskId: task.id, rowNumber: row.number });
|
||||
await this.recordTask(task.id, channelId, existingTask?.status, 'exporting');
|
||||
}
|
||||
}
|
||||
if (workbook.worksheets.every((sheet) => sheet.rowCount <= 1)) {
|
||||
for (const sheet of [...workbook.worksheets]) workbook.removeWorksheet(sheet.id);
|
||||
const empty = workbook.addWorksheet('无可导出数据');
|
||||
empty.getCell('A1').value = '所选资料缺少当前通道必填字段,请补充后重新生成。';
|
||||
empty.getColumn(1).width = 64;
|
||||
}
|
||||
const buffer = Buffer.from(await workbook.xlsx.writeBuffer());
|
||||
const fileName = `${safeFileName(channel.name)}-${batchId.slice(-8)}.xlsx`;
|
||||
const uploaded = await this.files.upload({ purpose: 'report_export', prefix: `report-exports/${batchId}` }, { originalname: fileName, mimetype: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', size: buffer.length, buffer });
|
||||
const file = await this.prisma.reportExportFile.create({ data: { batchId, channelId, fileObjectId: uploaded.id, fileName, rowCount: totalRows } });
|
||||
if (fileRows.length) await this.prisma.reportExportFileItem.createMany({ data: fileRows.map((entry) => ({ exportFileId: file.id, batchItemId: entry.item.batchItem.id, taskId: entry.taskId, rowNumber: entry.rowNumber })) });
|
||||
return { file: { ...file, fileObject: uploaded }, incompleteBatchItemIds };
|
||||
}
|
||||
|
||||
recordTask(taskId: string, channelId: string, statusBefore: string | undefined, statusAfter: string, reason?: string) {
|
||||
return this.prisma.channelSignatureReportRecord.create({ data: { taskId, channelId, action: 'batch_export', statusBefore, statusAfter, reason, sourceEntry: 'report_task' } });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import ExcelJS from 'exceljs';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { extname } from 'node:path';
|
||||
import { FilesService } from '../files/files.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsConfigService } from '../sms-config/sms-config.service';
|
||||
import type { AnalyzeImportOptions, CreateImportProfileDto, CreateReportBatchDto, EmbeddedImage, ImportCommitDto, ImportMapping, PagedQuery, ReportBatchInspection, ReportBatchTarget, ReviewImportItemsDto } from './report-materials.contracts';
|
||||
import { profileData, validateProfile, loadWorkbook, assertSafeWorkbook, safeSpreadsheetText, readEmbeddedImages, suggestMappings, remapProfileColumns, signatureCoreMapping, drainageCoreMapping, normalizeHeader, normalizeFieldCode, clamp, normalizePage, normalizePageSize, dateRange, cellText, transformValue, mappedCoreValue, dynamicValues, jsonRecord, hasValue, isFileRef, resolveExportValue, applyExportTransform, styleHeader, normalizeImageExtension, imageContentType, safeFileName, normalizeBatchIdempotencyKey, jsonStringArray, jsonSafe } from './report-materials.helpers';
|
||||
|
||||
|
||||
/** R4 report-materials domain service composed behind ReportMaterialsService. */
|
||||
export class ReportImportParserService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly files: FilesService, private readonly smsConfig: SmsConfigService) {}
|
||||
|
||||
listImportProfiles(reportType?: 'signature' | 'drainage') {
|
||||
return this.prisma.reportMaterialImportProfile.findMany({
|
||||
where: { reportType, status: 'active' },
|
||||
include: { columns: { orderBy: [{ sortOrder: 'asc' }, { sourceColumnIndex: 'asc' }] } },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
async saveImportProfile(data: CreateImportProfileDto) {
|
||||
validateProfile(data);
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const profile = data.id
|
||||
? await tx.reportMaterialImportProfile.update({ where: { id: data.id }, data: profileData(data) })
|
||||
: await tx.reportMaterialImportProfile.create({ data: profileData(data) });
|
||||
await tx.reportMaterialImportProfileColumn.deleteMany({ where: { profileId: profile.id } });
|
||||
await tx.reportMaterialImportProfileColumn.createMany({
|
||||
data: data.columns.map((column, index) => ({
|
||||
profileId: profile.id,
|
||||
sourceHeader: column.sourceHeader,
|
||||
sourceHeaderPath: column.sourceHeaderPath,
|
||||
sourceColumnIndex: column.sourceColumnIndex,
|
||||
targetFieldCode: column.targetFieldCode,
|
||||
targetKind: column.targetKind,
|
||||
fieldType: column.fieldType,
|
||||
required: column.required ?? false,
|
||||
transform: column.transform,
|
||||
sortOrder: column.sortOrder ?? (index + 1) * 10,
|
||||
})),
|
||||
});
|
||||
return tx.reportMaterialImportProfile.findUnique({ where: { id: profile.id }, include: { columns: { orderBy: { sortOrder: 'asc' } } } });
|
||||
});
|
||||
}
|
||||
|
||||
async analyzeImport(file: { originalname: string; mimetype: string; size: number; buffer: Buffer }, options: AnalyzeImportOptions) {
|
||||
if (!options.tenantId) throw new BadRequestException('tenantId is required');
|
||||
if (!['signature', 'drainage'].includes(options.reportType)) throw new BadRequestException('reportType must be signature or drainage');
|
||||
if (extname(file.originalname).toLowerCase() !== '.xlsx' || file.buffer[0] !== 0x50 || file.buffer[1] !== 0x4b) throw new BadRequestException('仅支持有效的 XLSX 文件');
|
||||
const workbook = await loadWorkbook(file.buffer);
|
||||
assertSafeWorkbook(workbook);
|
||||
const profile = options.profileId ? await this.prisma.reportMaterialImportProfile.findUnique({ where: { id: options.profileId }, include: { columns: { orderBy: { sortOrder: 'asc' } } } }) : null;
|
||||
const selectedSheetName = options.sheetName || profile?.sheetName || undefined;
|
||||
const worksheet = selectedSheetName ? workbook.getWorksheet(selectedSheetName) : workbook.worksheets[0];
|
||||
if (!worksheet) throw new BadRequestException('工作簿没有可读取的工作表');
|
||||
const headerRowCount = clamp(options.headerRowCount, 1, 5);
|
||||
const dataStartRow = Math.max(options.dataStartRow, headerRowCount + 1);
|
||||
const images = readEmbeddedImages(workbook, worksheet);
|
||||
const columnCount = Math.min(worksheet.columnCount, 200);
|
||||
const columns = Array.from({ length: columnCount }, (_, offset) => {
|
||||
const sourceColumnIndex = offset + 1;
|
||||
const parts = Array.from({ length: headerRowCount }, (_, headerOffset) => cellText(worksheet.getCell(headerOffset + 1, sourceColumnIndex))).filter(Boolean);
|
||||
const sourceHeaderPath = [...new Set(parts)].join('/');
|
||||
return {
|
||||
sourceColumnIndex,
|
||||
columnLetter: worksheet.getColumn(sourceColumnIndex).letter,
|
||||
sourceHeader: parts.at(-1) || `第${sourceColumnIndex}列`,
|
||||
sourceHeaderPath,
|
||||
imageCount: images.filter((image) => image.column === sourceColumnIndex).length,
|
||||
};
|
||||
}).filter((column) => column.sourceHeaderPath || column.imageCount > 0);
|
||||
const previewRows = [];
|
||||
for (let rowNumber = dataStartRow; rowNumber <= Math.min(worksheet.rowCount, dataStartRow + 9); rowNumber += 1) {
|
||||
const values = Object.fromEntries(columns.map((column) => [String(column.sourceColumnIndex), cellText(worksheet.getCell(rowNumber, column.sourceColumnIndex))]));
|
||||
const imageColumns = images.filter((image) => image.row === rowNumber).map((image) => image.column);
|
||||
if (Object.values(values).some(Boolean) || imageColumns.length) previewRows.push({ rowNumber, values, imageColumns });
|
||||
}
|
||||
const sourceFile = await this.files.upload({ tenantId: options.tenantId, purpose: 'report_material_import', prefix: 'report-material-imports' }, file);
|
||||
const profileMappings = profile?.columns.map((column) => ({
|
||||
sourceHeader: column.sourceHeader,
|
||||
sourceHeaderPath: column.sourceHeaderPath ?? undefined,
|
||||
sourceColumnIndex: column.sourceColumnIndex,
|
||||
targetFieldCode: column.targetFieldCode,
|
||||
targetKind: column.targetKind as ImportMapping['targetKind'],
|
||||
fieldType: column.fieldType as ImportMapping['fieldType'],
|
||||
required: column.required,
|
||||
transform: column.transform ?? undefined,
|
||||
sortOrder: column.sortOrder,
|
||||
}));
|
||||
const suggestedMappings = profileMappings?.length ? remapProfileColumns(profileMappings, columns) : suggestMappings(columns, options.reportType);
|
||||
const batch = await this.prisma.reportMaterialImportBatch.create({
|
||||
data: {
|
||||
tenantId: options.tenantId,
|
||||
applicationId: options.applicationId,
|
||||
profileId: options.profileId,
|
||||
fileObjectId: sourceFile.id,
|
||||
fileName: sourceFile.fileName,
|
||||
reportType: options.reportType,
|
||||
sheetName: worksheet.name,
|
||||
headerRowCount,
|
||||
dataStartRow,
|
||||
mapping: suggestedMappings as Prisma.InputJsonValue,
|
||||
preview: { sheets: workbook.worksheets.map((sheet) => sheet.name), columns, rows: previewRows, imageCount: images.length } as Prisma.InputJsonValue,
|
||||
rowCount: Math.max(0, worksheet.rowCount - dataStartRow + 1),
|
||||
},
|
||||
});
|
||||
await this.prisma.operationLog.create({ data: {
|
||||
tenantId: options.tenantId, userId: options.operatorId, action: 'report_material.import_analyzed', resource: 'report_material_import', resourceId: batch.id,
|
||||
detail: { fileName: sourceFile.fileName, filters: { applicationId: options.applicationId, reportType: options.reportType, sheetName: worksheet.name }, successCount: previewRows.length, failedCount: 0 } as Prisma.InputJsonValue,
|
||||
} });
|
||||
return { ...batch, sourceFile, sheets: workbook.worksheets.map((sheet) => sheet.name), columns, rows: previewRows, imageCount: images.length, suggestedMappings };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import ExcelJS from 'exceljs';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { extname } from 'node:path';
|
||||
import { FilesService } from '../files/files.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsConfigService } from '../sms-config/sms-config.service';
|
||||
import type { AnalyzeImportOptions, CreateImportProfileDto, CreateReportBatchDto, EmbeddedImage, ImportCommitDto, ImportMapping, PagedQuery, ReportBatchInspection, ReportBatchTarget, ReviewImportItemsDto } from './report-materials.contracts';
|
||||
import { profileData, validateProfile, loadWorkbook, assertSafeWorkbook, safeSpreadsheetText, readEmbeddedImages, suggestMappings, remapProfileColumns, signatureCoreMapping, drainageCoreMapping, normalizeHeader, normalizeFieldCode, clamp, normalizePage, normalizePageSize, dateRange, cellText, transformValue, mappedCoreValue, dynamicValues, jsonRecord, hasValue, isFileRef, resolveExportValue, applyExportTransform, styleHeader, normalizeImageExtension, imageContentType, safeFileName, normalizeBatchIdempotencyKey, jsonStringArray, jsonSafe } from './report-materials.helpers';
|
||||
import { ReportImportParserService } from './import-parser.service';
|
||||
|
||||
/** R4 report-materials domain service composed behind ReportMaterialsService. */
|
||||
export class ReportImportReviewService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly files: FilesService, private readonly smsConfig: SmsConfigService, private readonly importParser: ReportImportParserService) {}
|
||||
|
||||
async commitImport(batchId: string, data: ImportCommitDto) {
|
||||
const batch = await this.prisma.reportMaterialImportBatch.findUnique({ where: { id: batchId } });
|
||||
if (!batch) throw new NotFoundException('导入批次不存在');
|
||||
if (batch.status !== 'analyzed') throw new ConflictException('该导入批次已提交审核,不能重复导入');
|
||||
if (!data.mappings?.length) throw new BadRequestException('请至少配置一个导入字段映射');
|
||||
if (data.profile) await this.importParser.saveImportProfile({ ...data.profile, reportType: batch.reportType as 'signature' | 'drainage', columns: data.mappings });
|
||||
const { content } = await this.files.getDownload(batch.fileObjectId);
|
||||
const workbook = await loadWorkbook(content);
|
||||
assertSafeWorkbook(workbook);
|
||||
const worksheet = workbook.getWorksheet(batch.sheetName);
|
||||
if (!worksheet) throw new BadRequestException('导入工作表不存在');
|
||||
const images = readEmbeddedImages(workbook, worksheet);
|
||||
const imageByCell = new Map(images.map((image) => [`${image.row}:${image.column}`, image]));
|
||||
let successCount = 0;
|
||||
const failures: Array<{ rowNumber: number; reason: string }> = [];
|
||||
const stagedItems: Prisma.ReportMaterialImportItemCreateManyInput[] = [];
|
||||
for (let rowNumber = batch.dataStartRow; rowNumber <= worksheet.rowCount; rowNumber += 1) {
|
||||
const values: Record<string, unknown> = {};
|
||||
try {
|
||||
for (const mapping of data.mappings) {
|
||||
const image = imageByCell.get(`${rowNumber}:${mapping.sourceColumnIndex}`);
|
||||
if (image && mapping.fieldType !== 'string') {
|
||||
const uploaded = await this.files.upload({ tenantId: batch.tenantId, purpose: 'report_material', prefix: `report-materials/import-${batch.id}` }, {
|
||||
originalname: `${mapping.targetFieldCode}-row-${rowNumber}.${normalizeImageExtension(image.extension)}`,
|
||||
mimetype: imageContentType(image.extension),
|
||||
size: image.buffer.length,
|
||||
buffer: image.buffer,
|
||||
});
|
||||
values[mapping.targetFieldCode] = { fileObjectId: uploaded.id, fileName: uploaded.fileName, contentType: uploaded.contentType };
|
||||
} else {
|
||||
values[mapping.targetFieldCode] = transformValue(cellText(worksheet.getCell(rowNumber, mapping.sourceColumnIndex)), mapping.transform);
|
||||
}
|
||||
}
|
||||
if (!Object.values(values).some(hasValue)) continue;
|
||||
for (const mapping of data.mappings.filter((item) => item.required)) {
|
||||
if (!hasValue(values[mapping.targetFieldCode])) throw new Error(`缺少必填字段:${mapping.sourceHeader}`);
|
||||
}
|
||||
const staged = batch.reportType === 'signature'
|
||||
? await this.stageSignatureRow(batch.tenantId, batch.applicationId ?? undefined, data.mappings, values)
|
||||
: await this.stageDrainageRow(batch.tenantId, batch.applicationId ?? undefined, data.mappings, values);
|
||||
stagedItems.push({
|
||||
batchId,
|
||||
rowNumber,
|
||||
reportType: batch.reportType,
|
||||
operation: staged.operation,
|
||||
targetId: staged.targetId,
|
||||
status: 'pending_review',
|
||||
payload: staged.payload as Prisma.InputJsonValue,
|
||||
originalSnapshot: staged.originalSnapshot as Prisma.InputJsonValue | undefined,
|
||||
});
|
||||
successCount += 1;
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : '导入失败';
|
||||
failures.push({ rowNumber, reason });
|
||||
stagedItems.push({
|
||||
batchId,
|
||||
rowNumber,
|
||||
reportType: batch.reportType,
|
||||
operation: 'invalid',
|
||||
status: 'invalid',
|
||||
payload: values as Prisma.InputJsonValue,
|
||||
errorMessage: reason,
|
||||
});
|
||||
}
|
||||
}
|
||||
const updated = await this.prisma.$transaction(async (tx) => {
|
||||
if (stagedItems.length) await tx.reportMaterialImportItem.createMany({ data: stagedItems });
|
||||
return tx.reportMaterialImportBatch.update({
|
||||
where: { id: batchId },
|
||||
data: {
|
||||
status: successCount ? 'pending_review' : 'failed',
|
||||
mapping: data.mappings as Prisma.InputJsonValue,
|
||||
result: { failures } as Prisma.InputJsonValue,
|
||||
successCount,
|
||||
failedCount: failures.length,
|
||||
},
|
||||
include: { items: { orderBy: { rowNumber: 'asc' } } },
|
||||
});
|
||||
});
|
||||
await this.prisma.operationLog.create({ data: {
|
||||
tenantId: batch.tenantId, userId: data.operatorId, action: 'report_material.import_committed', resource: 'report_material_import', resourceId: batch.id,
|
||||
detail: { fileName: batch.fileName, filters: { applicationId: batch.applicationId, reportType: batch.reportType, sheetName: batch.sheetName }, successCount, failedCount: failures.length } as Prisma.InputJsonValue,
|
||||
} });
|
||||
return updated;
|
||||
}
|
||||
|
||||
async listImportReviewBatches(query: PagedQuery & { reportType?: 'signature' | 'drainage'; status?: string } = {}) {
|
||||
const page = normalizePage(query.page);
|
||||
const pageSize = normalizePageSize(query.pageSize);
|
||||
const where: Prisma.ReportMaterialImportBatchWhereInput = {
|
||||
reportType: query.reportType,
|
||||
status: query.status && query.status !== 'all' ? query.status : undefined,
|
||||
createdAt: dateRange(query.startAt, query.endAt),
|
||||
OR: query.keyword?.trim() ? [
|
||||
{ fileName: { contains: query.keyword.trim() } },
|
||||
{ id: { contains: query.keyword.trim() } },
|
||||
] : undefined,
|
||||
};
|
||||
const [batches, total] = await Promise.all([
|
||||
this.prisma.reportMaterialImportBatch.findMany({
|
||||
where,
|
||||
include: { items: { orderBy: { rowNumber: 'asc' } } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.reportMaterialImportBatch.count({ where }),
|
||||
]);
|
||||
const tenantIds = [...new Set(batches.map((batch) => batch.tenantId))];
|
||||
const applicationIds = [...new Set(batches.map((batch) => batch.applicationId).filter((id): id is string => Boolean(id)))];
|
||||
const reviewerIds = [...new Set(batches.flatMap((batch) => [
|
||||
batch.reviewedById,
|
||||
...batch.items.map((item) => item.reviewedById),
|
||||
]).filter((id): id is string => Boolean(id)))];
|
||||
const [tenants, applications, reviewers] = await Promise.all([
|
||||
tenantIds.length ? this.prisma.tenant.findMany({ where: { id: { in: tenantIds } }, select: { id: true, name: true } }) : [],
|
||||
applicationIds.length ? this.prisma.smsApplication.findMany({ where: { id: { in: applicationIds } }, select: { id: true, name: true } }) : [],
|
||||
reviewerIds.length ? this.prisma.user.findMany({ where: { id: { in: reviewerIds } }, select: { id: true, username: true, displayName: true } }) : [],
|
||||
]);
|
||||
const tenantById = new Map(tenants.map((item) => [item.id, item]));
|
||||
const applicationById = new Map(applications.map((item) => [item.id, item]));
|
||||
const reviewerById = new Map(reviewers.map((item) => [item.id, item]));
|
||||
return {
|
||||
items: batches.map((batch) => ({
|
||||
...batch,
|
||||
tenant: tenantById.get(batch.tenantId) ?? null,
|
||||
application: batch.applicationId ? applicationById.get(batch.applicationId) ?? null : null,
|
||||
reviewer: batch.reviewedById ? reviewerById.get(batch.reviewedById) ?? null : null,
|
||||
items: batch.items.map((item) => ({
|
||||
...item,
|
||||
reviewer: item.reviewedById ? reviewerById.get(item.reviewedById) ?? null : null,
|
||||
})),
|
||||
})),
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
};
|
||||
}
|
||||
|
||||
async reviewImportItems(batchId: string, data: ReviewImportItemsDto) {
|
||||
if (!data.reviewerId) throw new BadRequestException('Reviewer session is required');
|
||||
if (!['approve', 'reject'].includes(data.decision)) throw new BadRequestException('Unsupported import review decision');
|
||||
const batch = await this.prisma.reportMaterialImportBatch.findUnique({
|
||||
where: { id: batchId },
|
||||
include: { items: { where: { id: data.itemIds?.length ? { in: data.itemIds } : undefined, status: 'pending_review' }, orderBy: { rowNumber: 'asc' } } },
|
||||
});
|
||||
if (!batch) throw new NotFoundException('导入审核批次不存在');
|
||||
if (!batch.items.length) throw new BadRequestException('没有可审核的导入明细');
|
||||
let approvedCount = 0;
|
||||
let rejectedCount = 0;
|
||||
const failures: Array<{ itemId: string; rowNumber: number; reason: string }> = [];
|
||||
for (const item of batch.items) {
|
||||
if (data.decision === 'reject') {
|
||||
await this.prisma.reportMaterialImportItem.update({
|
||||
where: { id: item.id },
|
||||
data: { status: 'rejected', reviewReason: data.reason?.trim(), reviewedById: data.reviewerId, reviewedAt: new Date() },
|
||||
});
|
||||
rejectedCount += 1;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const targetId = await this.applyImportItem(batch, item, data.reviewerId);
|
||||
await this.prisma.reportMaterialImportItem.update({
|
||||
where: { id: item.id },
|
||||
data: { targetId, status: 'approved', reviewReason: data.reason?.trim(), reviewedById: data.reviewerId, reviewedAt: new Date(), errorMessage: null },
|
||||
});
|
||||
approvedCount += 1;
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : '导入审核应用失败';
|
||||
failures.push({ itemId: item.id, rowNumber: item.rowNumber, reason });
|
||||
await this.prisma.reportMaterialImportItem.update({
|
||||
where: { id: item.id },
|
||||
data: { status: 'invalid', errorMessage: reason, reviewedById: data.reviewerId, reviewedAt: new Date() },
|
||||
});
|
||||
}
|
||||
}
|
||||
const counts = await this.prisma.reportMaterialImportItem.groupBy({
|
||||
by: ['status'],
|
||||
where: { batchId },
|
||||
_count: { _all: true },
|
||||
});
|
||||
const countByStatus = new Map(counts.map((item) => [item.status, item._count._all]));
|
||||
const pendingCount = countByStatus.get('pending_review') ?? 0;
|
||||
const totalApproved = countByStatus.get('approved') ?? 0;
|
||||
const totalRejected = countByStatus.get('rejected') ?? 0;
|
||||
const totalInvalid = countByStatus.get('invalid') ?? 0;
|
||||
const status = pendingCount
|
||||
? 'partially_reviewed'
|
||||
: totalApproved && (totalRejected || totalInvalid)
|
||||
? 'partially_approved'
|
||||
: totalApproved
|
||||
? 'approved'
|
||||
: totalRejected
|
||||
? 'rejected'
|
||||
: 'failed';
|
||||
await this.prisma.reportMaterialImportBatch.update({
|
||||
where: { id: batchId },
|
||||
data: {
|
||||
status,
|
||||
reviewedById: pendingCount ? undefined : data.reviewerId,
|
||||
reviewedAt: pendingCount ? undefined : new Date(),
|
||||
completedAt: pendingCount ? undefined : new Date(),
|
||||
},
|
||||
});
|
||||
return { batchId, status, approvedCount, rejectedCount, failedCount: failures.length, failures };
|
||||
}
|
||||
|
||||
async stageSignatureRow(tenantId: string, applicationId: string | undefined, mappings: ImportMapping[], values: Record<string, unknown>) {
|
||||
const name = mappedCoreValue(mappings, values, 'signatureName');
|
||||
if (!name) throw new Error('缺少短信签名');
|
||||
const purpose = mappedCoreValue(mappings, values, 'purpose');
|
||||
const signatureReportValues = dynamicValues(mappings, values);
|
||||
const existing = await this.prisma.smsSignature.findFirst({ where: { tenantId, applicationId: applicationId ?? null, name, auditStatus: { not: 'deleted' } } });
|
||||
return {
|
||||
operation: existing ? 'update' : 'create',
|
||||
targetId: existing?.id,
|
||||
payload: {
|
||||
tenantId,
|
||||
applicationId,
|
||||
name,
|
||||
purpose,
|
||||
drainageInfo: { ...jsonRecord(existing?.drainageInfo), signatureReportValues },
|
||||
},
|
||||
originalSnapshot: existing ? {
|
||||
id: existing.id,
|
||||
applicationId: existing.applicationId,
|
||||
name: existing.name,
|
||||
purpose: existing.purpose,
|
||||
drainageInfo: existing.drainageInfo,
|
||||
auditStatus: existing.auditStatus,
|
||||
updatedAt: existing.updatedAt,
|
||||
} : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async stageDrainageRow(tenantId: string, applicationId: string | undefined, mappings: ImportMapping[], values: Record<string, unknown>) {
|
||||
const signatureName = mappedCoreValue(mappings, values, 'signatureName');
|
||||
const siteName = mappedCoreValue(mappings, values, 'siteName');
|
||||
const url = mappedCoreValue(mappings, values, 'url');
|
||||
if (!signatureName || !siteName || !url) throw new Error('引流信息必须包含短信签名、站点名称和URL');
|
||||
const signature = await this.prisma.smsSignature.findFirst({ where: { tenantId, applicationId: applicationId ?? null, name: signatureName, auditStatus: 'approved' } });
|
||||
if (!signature) throw new Error(`未找到已审核签名:${signatureName}`);
|
||||
const remark = mappedCoreValue(mappings, values, 'remark');
|
||||
const reportValues = dynamicValues(mappings, values);
|
||||
const existing = await this.prisma.smsDrainageInfo.findFirst({ where: { signatureId: signature.id, url, auditStatus: { not: 'deleted' } } });
|
||||
return {
|
||||
operation: existing ? 'update' : 'create',
|
||||
targetId: existing?.id,
|
||||
payload: { tenantId, applicationId, signatureId: signature.id, signatureName, siteName, url, remark, reportValues },
|
||||
originalSnapshot: existing ? {
|
||||
id: existing.id,
|
||||
siteName: existing.siteName,
|
||||
url: existing.url,
|
||||
remark: existing.remark,
|
||||
reportValues: existing.reportValues,
|
||||
auditStatus: existing.auditStatus,
|
||||
updatedAt: existing.updatedAt,
|
||||
} : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async applyImportItem(
|
||||
batch: { tenantId: string; applicationId: string | null; reportType: string },
|
||||
item: { reportType: string; targetId: string | null; payload: Prisma.JsonValue },
|
||||
reviewerId: string,
|
||||
) {
|
||||
const payload = jsonRecord(item.payload);
|
||||
if (item.reportType === 'signature') {
|
||||
const name = String(payload.name ?? '');
|
||||
const applicationId = typeof payload.applicationId === 'string' ? payload.applicationId : undefined;
|
||||
const body = {
|
||||
applicationId,
|
||||
name,
|
||||
purpose: typeof payload.purpose === 'string' ? payload.purpose : undefined,
|
||||
drainageInfo: jsonRecord(payload.drainageInfo),
|
||||
};
|
||||
let targetId = item.targetId;
|
||||
if (targetId) {
|
||||
const current = await this.prisma.smsSignature.findUnique({ where: { id: targetId } });
|
||||
if (!current || current.auditStatus === 'deleted') throw new Error('原签名已删除,不能应用导入修改');
|
||||
await this.smsConfig.updateSignature(targetId, body, batch.tenantId);
|
||||
} else {
|
||||
const duplicate = await this.prisma.smsSignature.findFirst({
|
||||
where: { tenantId: batch.tenantId, applicationId: applicationId ?? null, name, auditStatus: { not: 'deleted' } },
|
||||
});
|
||||
if (duplicate) {
|
||||
targetId = duplicate.id;
|
||||
await this.smsConfig.updateSignature(targetId, body, batch.tenantId);
|
||||
} else {
|
||||
const created = await this.smsConfig.createSignature({ tenantId: batch.tenantId, ...body });
|
||||
targetId = created.id;
|
||||
}
|
||||
}
|
||||
await this.smsConfig.approveSignature(targetId, { reviewerId, reason: `批量导入审核通过:${name}` });
|
||||
return targetId;
|
||||
}
|
||||
const signatureId = String(payload.signatureId ?? '');
|
||||
const siteName = String(payload.siteName ?? '');
|
||||
const url = String(payload.url ?? '');
|
||||
const body = {
|
||||
siteName,
|
||||
url,
|
||||
remark: typeof payload.remark === 'string' ? payload.remark : undefined,
|
||||
reportValues: jsonRecord(payload.reportValues),
|
||||
};
|
||||
let targetId = item.targetId;
|
||||
if (targetId) {
|
||||
const current = await this.prisma.smsDrainageInfo.findUnique({ where: { id: targetId } });
|
||||
if (!current || current.auditStatus === 'deleted') throw new Error('原引流信息已删除,不能应用导入修改');
|
||||
await this.smsConfig.updateDrainageInfo(targetId, body, { initialAuditStatus: 'pending' }, batch.tenantId);
|
||||
} else {
|
||||
const duplicate = await this.prisma.smsDrainageInfo.findFirst({
|
||||
where: { signatureId, url, auditStatus: { not: 'deleted' } },
|
||||
});
|
||||
if (duplicate) {
|
||||
targetId = duplicate.id;
|
||||
await this.smsConfig.updateDrainageInfo(targetId, body, { initialAuditStatus: 'pending' }, batch.tenantId);
|
||||
} else {
|
||||
const created = await this.smsConfig.createDrainageInfo(signatureId, body, { initialAuditStatus: 'pending' }, batch.tenantId);
|
||||
targetId = created.id;
|
||||
}
|
||||
}
|
||||
await this.smsConfig.approveDrainageInfo(targetId, { reviewerId, reason: `批量导入审核通过:${siteName || url}` });
|
||||
return targetId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import ExcelJS from 'exceljs';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { extname } from 'node:path';
|
||||
import { FilesService } from '../files/files.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsConfigService } from '../sms-config/sms-config.service';
|
||||
import type { AnalyzeImportOptions, CreateImportProfileDto, CreateReportBatchDto, EmbeddedImage, ImportCommitDto, ImportMapping, PagedQuery, ReportBatchInspection, ReportBatchTarget, ReviewImportItemsDto } from './report-materials.contracts';
|
||||
import { profileData, validateProfile, loadWorkbook, assertSafeWorkbook, safeSpreadsheetText, readEmbeddedImages, suggestMappings, remapProfileColumns, signatureCoreMapping, drainageCoreMapping, normalizeHeader, normalizeFieldCode, clamp, normalizePage, normalizePageSize, dateRange, cellText, transformValue, mappedCoreValue, dynamicValues, jsonRecord, hasValue, isFileRef, resolveExportValue, applyExportTransform, styleHeader, normalizeImageExtension, imageContentType, safeFileName, normalizeBatchIdempotencyKey, jsonStringArray, jsonSafe } from './report-materials.helpers';
|
||||
import { ReportPendingQueryService } from './pending-query.service';
|
||||
|
||||
/** R4 report-materials domain service composed behind ReportMaterialsService. */
|
||||
export class ReportOfficialExportService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly files: FilesService, private readonly smsConfig: SmsConfigService, private readonly pending: ReportPendingQueryService) {}
|
||||
|
||||
async buildOfficialTemplate(reportType: 'signature' | 'drainage', operatorId?: string) {
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
workbook.creator = 'CMPP短信平台';
|
||||
const sheet = workbook.addWorksheet(reportType === 'signature' ? '签名资料' : '引流信息', { views: [{ state: 'frozen', ySplit: 1 }] });
|
||||
const headers = reportType === 'signature'
|
||||
? ['短信签名', '用途说明', '营业执照图片', '授权书图片', '备注']
|
||||
: ['短信签名', '站点名称', 'URL', '备注', '网站截图'];
|
||||
sheet.addRow(headers);
|
||||
sheet.addRow(reportType === 'signature'
|
||||
? ['示例签名', '验证码通知', '请在本单元格插入图片', '请在本单元格插入图片', '示例行,导入前请删除']
|
||||
: ['示例签名', '官方站点', 'https://example.com', '示例行,导入前请删除', '请在本单元格插入图片']);
|
||||
styleHeader(sheet.getRow(1));
|
||||
sheet.columns.forEach((column) => { column.width = 24; });
|
||||
sheet.getRow(2).height = 48;
|
||||
const content = Buffer.from(await workbook.xlsx.writeBuffer());
|
||||
const fileName = `${reportType === 'signature' ? '签名' : '引流信息'}报备资料官方模板.xlsx`;
|
||||
await this.prisma.operationLog.create({ data: {
|
||||
userId: operatorId, action: 'report_material.template_downloaded', resource: 'report_material',
|
||||
detail: { fileName, filters: { reportType }, successCount: 1, failedCount: 0 } as Prisma.InputJsonValue,
|
||||
} });
|
||||
return { fileName, content };
|
||||
}
|
||||
|
||||
async exportPending(query: { reportType?: 'signature' | 'drainage'; tenantId?: string; applicationId?: string }, operatorId?: string) {
|
||||
const items = await this.pending.findPendingItems(query);
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const sheet = workbook.addWorksheet('待报备资料', { views: [{ state: 'frozen', ySplit: 1 }] });
|
||||
sheet.addRow(['资料类型', '企业', '企业应用', '签名/站点', '详情', '变更时间']);
|
||||
styleHeader(sheet.getRow(1));
|
||||
for (const item of items) sheet.addRow([
|
||||
item.reportType === 'signature' ? '签名' : '引流信息', safeSpreadsheetText(item.tenant?.name),
|
||||
safeSpreadsheetText(item.application?.name), safeSpreadsheetText(item.name), safeSpreadsheetText(item.detail), item.changedAt,
|
||||
]);
|
||||
sheet.columns.forEach((column, index) => { column.width = index === 4 ? 42 : 22; });
|
||||
const fileName = `待报备资料-${new Date().toISOString().slice(0, 10)}.xlsx`;
|
||||
await this.prisma.operationLog.create({ data: {
|
||||
tenantId: query.tenantId, userId: operatorId, action: 'report_material.pending_export', resource: 'report_material',
|
||||
detail: { fileName, filters: query, successCount: items.length, failedCount: 0 } as Prisma.InputJsonValue,
|
||||
} });
|
||||
return { fileName, content: Buffer.from(await workbook.xlsx.writeBuffer()) };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import ExcelJS from 'exceljs';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { extname } from 'node:path';
|
||||
import { FilesService } from '../files/files.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SmsConfigService } from '../sms-config/sms-config.service';
|
||||
import type { AnalyzeImportOptions, CreateImportProfileDto, CreateReportBatchDto, EmbeddedImage, ImportCommitDto, ImportMapping, PagedQuery, ReportBatchInspection, ReportBatchTarget, ReviewImportItemsDto } from './report-materials.contracts';
|
||||
import { profileData, validateProfile, loadWorkbook, assertSafeWorkbook, safeSpreadsheetText, readEmbeddedImages, suggestMappings, remapProfileColumns, signatureCoreMapping, drainageCoreMapping, normalizeHeader, normalizeFieldCode, clamp, normalizePage, normalizePageSize, dateRange, cellText, transformValue, mappedCoreValue, dynamicValues, jsonRecord, hasValue, isFileRef, resolveExportValue, applyExportTransform, styleHeader, normalizeImageExtension, imageContentType, safeFileName, normalizeBatchIdempotencyKey, jsonStringArray, jsonSafe } from './report-materials.helpers';
|
||||
|
||||
|
||||
/** R4 report-materials domain service composed behind ReportMaterialsService. */
|
||||
export class ReportPendingQueryService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly files: FilesService, private readonly smsConfig: SmsConfigService) {}
|
||||
|
||||
async listPending(query: { reportType?: 'signature' | 'drainage'; tenantId?: string; applicationId?: string } & PagedQuery) {
|
||||
const items = await this.findPendingItems(query);
|
||||
const page = normalizePage(query.page);
|
||||
const pageSize = normalizePageSize(query.pageSize);
|
||||
return {
|
||||
items: items.slice((page - 1) * pageSize, page * pageSize),
|
||||
total: items.length,
|
||||
page,
|
||||
pageSize,
|
||||
};
|
||||
}
|
||||
|
||||
async findPendingItems(query: { reportType?: 'signature' | 'drainage'; tenantId?: string; applicationId?: string } & PagedQuery) {
|
||||
const changedAt = dateRange(query.startAt, query.endAt);
|
||||
const keyword = query.keyword?.trim();
|
||||
const [signatures, drainageInfos] = await Promise.all([
|
||||
query.reportType === 'drainage' ? Promise.resolve([]) : this.prisma.smsSignature.findMany({
|
||||
where: {
|
||||
pendingReport: true,
|
||||
auditStatus: 'approved',
|
||||
tenantId: query.tenantId,
|
||||
applicationId: query.applicationId,
|
||||
reportChangedAt: changedAt,
|
||||
OR: keyword ? [
|
||||
{ name: { contains: keyword } },
|
||||
{ tenant: { name: { contains: keyword } } },
|
||||
{ application: { name: { contains: keyword } } },
|
||||
] : undefined,
|
||||
},
|
||||
include: { tenant: true, application: true },
|
||||
orderBy: { reportChangedAt: 'desc' },
|
||||
}),
|
||||
query.reportType === 'signature' ? Promise.resolve([]) : this.prisma.smsDrainageInfo.findMany({
|
||||
where: {
|
||||
pendingReport: true,
|
||||
auditStatus: 'approved',
|
||||
tenantId: query.tenantId,
|
||||
applicationId: query.applicationId,
|
||||
reportChangedAt: changedAt,
|
||||
OR: keyword ? [
|
||||
{ siteName: { contains: keyword } },
|
||||
{ url: { contains: keyword } },
|
||||
{ signature: { name: { contains: keyword } } },
|
||||
{ tenant: { name: { contains: keyword } } },
|
||||
{ application: { name: { contains: keyword } } },
|
||||
] : undefined,
|
||||
},
|
||||
include: { tenant: true, application: true, signature: true },
|
||||
orderBy: { reportChangedAt: 'desc' },
|
||||
}),
|
||||
]);
|
||||
return [
|
||||
...signatures.map((item) => ({ id: `signature:${item.id}`, reportType: 'signature', signatureId: item.id, drainageItemId: null, materialVersion: item.materialVersion, changedAt: item.reportChangedAt, name: item.name, detail: item.purpose, tenant: item.tenant, application: item.application })),
|
||||
...drainageInfos.map((item) => ({ id: `drainage:${item.id}`, reportType: 'drainage', signatureId: item.signatureId, drainageItemId: item.id, materialVersion: item.materialVersion, changedAt: item.reportChangedAt, name: item.siteName, detail: item.url, signatureName: item.signature.name, tenant: item.tenant, application: item.application })),
|
||||
].sort((left, right) => new Date(right.changedAt).getTime() - new Date(left.changedAt).getTime());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/** Stable request, query and internal data contracts for report-material domains. */
|
||||
|
||||
export type ImportMapping = {
|
||||
sourceHeader: string;
|
||||
sourceHeaderPath?: string;
|
||||
sourceColumnIndex: number;
|
||||
targetFieldCode: string;
|
||||
targetKind: 'signatureName' | 'purpose' | 'siteName' | 'url' | 'remark' | 'dynamic';
|
||||
fieldType: 'string' | 'image' | 'file';
|
||||
required?: boolean;
|
||||
transform?: string;
|
||||
sortOrder?: number;
|
||||
};
|
||||
|
||||
export interface CreateImportProfileDto {
|
||||
id?: string;
|
||||
name: string;
|
||||
reportType: 'signature' | 'drainage';
|
||||
tenantId?: string;
|
||||
applicationId?: string;
|
||||
sheetName?: string;
|
||||
headerRowCount?: number;
|
||||
dataStartRow?: number;
|
||||
status?: string;
|
||||
columns: ImportMapping[];
|
||||
}
|
||||
|
||||
export interface ImportCommitDto {
|
||||
mappings: ImportMapping[];
|
||||
profile?: CreateImportProfileDto;
|
||||
operatorId?: string;
|
||||
}
|
||||
|
||||
export interface ReviewImportItemsDto {
|
||||
decision: 'approve' | 'reject';
|
||||
itemIds?: string[];
|
||||
reason?: string;
|
||||
reviewerId?: string;
|
||||
}
|
||||
|
||||
export type PagedQuery = {
|
||||
keyword?: string;
|
||||
startAt?: string;
|
||||
endAt?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
};
|
||||
|
||||
export interface CreateReportBatchDto {
|
||||
createdById?: string;
|
||||
idempotencyKey?: string;
|
||||
items: Array<{ reportType: 'signature' | 'drainage'; signatureId: string; drainageItemId?: string; materialVersion?: number }>;
|
||||
}
|
||||
|
||||
export type ReportBatchTarget = { id: string; name: string; carrier: string; businessKey: string; eligible: boolean; blockedReasons: string[]; duplicateBatchId?: string };
|
||||
|
||||
export type ReportBatchInspection = {
|
||||
id: string;
|
||||
reportType: 'signature' | 'drainage';
|
||||
signatureId: string;
|
||||
drainageItemId?: string;
|
||||
materialVersion: number;
|
||||
name: string;
|
||||
tenantName: string;
|
||||
applicationId?: string;
|
||||
applicationName: string;
|
||||
eligible: boolean;
|
||||
blockedReasons: string[];
|
||||
targets: ReportBatchTarget[];
|
||||
};
|
||||
|
||||
export type AnalyzeImportOptions = {
|
||||
tenantId: string;
|
||||
applicationId?: string;
|
||||
reportType: 'signature' | 'drainage';
|
||||
sheetName?: string;
|
||||
headerRowCount: number;
|
||||
dataStartRow: number;
|
||||
profileId?: string;
|
||||
operatorId?: string;
|
||||
};
|
||||
|
||||
export type EmbeddedImage = { row: number; column: number; extension: string; buffer: Buffer };
|
||||
@@ -3,7 +3,8 @@ import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { RequireRecentAuthentication } from '../auth/require-recent-authentication.decorator';
|
||||
import { CurrentSessionUserId } from '../auth/current-session-user.decorator';
|
||||
import { CreateImportProfileDto, CreateReportBatchDto, ImportCommitDto, ReportMaterialsService, ReviewImportItemsDto } from './report-materials.service';
|
||||
import { ReportMaterialsService } from './report-materials.service';
|
||||
import { CreateImportProfileDto, CreateReportBatchDto, ImportCommitDto, ReviewImportItemsDto } from './report-materials.contracts';
|
||||
|
||||
type UploadedWorkbook = { originalname: string; mimetype: string; size: number; buffer: Buffer };
|
||||
type DownloadResponse = { setHeader(name: string, value: string): void; send(content: Buffer): void };
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import ExcelJS from 'exceljs';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { CreateImportProfileDto, EmbeddedImage, ImportMapping } from './report-materials.contracts';
|
||||
|
||||
/** Pure workbook, mapping, pagination and export helpers shared by R4 domains. */
|
||||
export function profileData(data: CreateImportProfileDto) {
|
||||
return { name: data.name.trim(), reportType: data.reportType, tenantId: data.tenantId, applicationId: data.applicationId, sheetName: data.sheetName, headerRowCount: clamp(data.headerRowCount ?? 1, 1, 5), dataStartRow: Math.max(data.dataStartRow ?? 2, 2), status: data.status ?? 'active' };
|
||||
}
|
||||
|
||||
export function validateProfile(data: CreateImportProfileDto) {
|
||||
if (!data.name?.trim()) throw new BadRequestException('映射模板名称不能为空');
|
||||
if (!data.columns?.length) throw new BadRequestException('映射模板至少包含一个字段');
|
||||
const indexes = data.columns.map((column) => column.sourceColumnIndex);
|
||||
if (new Set(indexes).size !== indexes.length) throw new BadRequestException('同一源列不能重复映射');
|
||||
}
|
||||
|
||||
export async function loadWorkbook(buffer: Buffer) {
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
await workbook.xlsx.load(buffer as never);
|
||||
return workbook;
|
||||
}
|
||||
|
||||
export function assertSafeWorkbook(workbook: ExcelJS.Workbook) {
|
||||
for (const worksheet of workbook.worksheets) {
|
||||
worksheet.eachRow((row) => row.eachCell((cell) => {
|
||||
const value = cell.value;
|
||||
if (value && typeof value === 'object' && ('formula' in value || 'sharedFormula' in value)) {
|
||||
throw new BadRequestException(`工作表 ${worksheet.name} 包含公式或可执行单元格`);
|
||||
}
|
||||
const text = typeof value === 'string' ? value.trimStart() : '';
|
||||
if (/^[=+@]/.test(text) || /^-[^\d.]/.test(text)) {
|
||||
throw new BadRequestException(`工作表 ${worksheet.name} 包含公式或可执行单元格`);
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
export function safeSpreadsheetText(value: unknown) {
|
||||
const text = value == null ? '' : String(value);
|
||||
return /^[=+@]/.test(text) || /^-[^\d.]/.test(text) ? `'${text}` : text;
|
||||
}
|
||||
|
||||
export function readEmbeddedImages(workbook: ExcelJS.Workbook, worksheet: ExcelJS.Worksheet): EmbeddedImage[] {
|
||||
const getImages = (worksheet as unknown as { getImages?: () => Array<{ imageId: number; range: { tl: { nativeRow?: number; nativeCol?: number; row?: number; col?: number } } }> }).getImages;
|
||||
if (!getImages) return [];
|
||||
return getImages.call(worksheet).flatMap((drawing) => {
|
||||
const image = (workbook as unknown as { getImage?: (id: number) => { buffer?: Buffer; base64?: string; extension?: string } }).getImage?.(drawing.imageId);
|
||||
if (!image) return [];
|
||||
const row = (drawing.range.tl.nativeRow ?? drawing.range.tl.row ?? 0) + 1;
|
||||
const column = (drawing.range.tl.nativeCol ?? drawing.range.tl.col ?? 0) + 1;
|
||||
const buffer = image.buffer ?? (image.base64 ? Buffer.from(image.base64.replace(/^data:[^;]+;base64,/, ''), 'base64') : undefined);
|
||||
return buffer ? [{ row, column, extension: image.extension ?? 'png', buffer }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
export function suggestMappings(columns: Array<{ sourceColumnIndex: number; sourceHeader: string; sourceHeaderPath: string; imageCount: number }>, reportType: 'signature' | 'drainage'): ImportMapping[] {
|
||||
return columns.flatMap((column, index) => {
|
||||
const normalized = normalizeHeader(`${column.sourceHeaderPath}/${column.sourceHeader}`);
|
||||
const core = reportType === 'signature' ? signatureCoreMapping(normalized) : drainageCoreMapping(normalized);
|
||||
if (!core && !column.imageCount) return [];
|
||||
return [{ sourceHeader: column.sourceHeader, sourceHeaderPath: column.sourceHeaderPath, sourceColumnIndex: column.sourceColumnIndex, targetFieldCode: core?.code ?? normalizeFieldCode(column.sourceHeader), targetKind: core?.kind ?? 'dynamic', fieldType: column.imageCount ? 'image' : 'string', required: Boolean(core?.required), sortOrder: (index + 1) * 10 }];
|
||||
});
|
||||
}
|
||||
|
||||
export function remapProfileColumns(profileColumns: ImportMapping[], sourceColumns: Array<{ sourceColumnIndex: number; sourceHeader: string; sourceHeaderPath: string; imageCount: number }>): ImportMapping[] {
|
||||
const used = new Set<number>();
|
||||
return profileColumns.flatMap((profileColumn) => {
|
||||
const headerPath = normalizeHeader(profileColumn.sourceHeaderPath || profileColumn.sourceHeader);
|
||||
const header = normalizeHeader(profileColumn.sourceHeader);
|
||||
const source = sourceColumns.find((column) => !used.has(column.sourceColumnIndex) && normalizeHeader(column.sourceHeaderPath) === headerPath)
|
||||
?? sourceColumns.find((column) => !used.has(column.sourceColumnIndex) && normalizeHeader(column.sourceHeader) === header);
|
||||
if (!source) return [];
|
||||
used.add(source.sourceColumnIndex);
|
||||
return [{ ...profileColumn, sourceColumnIndex: source.sourceColumnIndex, sourceHeader: source.sourceHeader, sourceHeaderPath: source.sourceHeaderPath, fieldType: source.imageCount > 0 && profileColumn.fieldType === 'string' ? 'image' : profileColumn.fieldType }];
|
||||
});
|
||||
}
|
||||
|
||||
export function signatureCoreMapping(header: string): { code: string; kind: ImportMapping['targetKind']; required?: boolean } | undefined {
|
||||
if (/短信签名|签名名称|签名/.test(header)) return { code: 'signature_name', kind: 'signatureName', required: true };
|
||||
if (/用途|签名依据/.test(header)) return { code: 'purpose', kind: 'purpose' };
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function drainageCoreMapping(header: string): { code: string; kind: ImportMapping['targetKind']; required?: boolean } | undefined {
|
||||
if (/短信签名|签名名称/.test(header)) return { code: 'signature_name', kind: 'signatureName', required: true };
|
||||
if (/站点|网站名称/.test(header)) return { code: 'site_name', kind: 'siteName', required: true };
|
||||
if (/引流地址|网址|url|链接/.test(header)) return { code: 'url', kind: 'url', required: true };
|
||||
if (/备注|说明/.test(header)) return { code: 'remark', kind: 'remark' };
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function normalizeHeader(value: string) { return value.toLowerCase().replace(/[\s**::()()_-]/g, ''); }
|
||||
|
||||
export function normalizeFieldCode(value: string) { return `import_${value.trim().toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '_').slice(0, 40) || randomUUID().slice(0, 8)}`; }
|
||||
|
||||
export function clamp(value: number, minimum: number, maximum: number) { return Math.min(maximum, Math.max(minimum, Number.isFinite(value) ? Math.round(value) : minimum)); }
|
||||
|
||||
export function normalizePage(value?: number) { return Math.max(1, Math.floor(Number(value) || 1)); }
|
||||
|
||||
export function normalizePageSize(value?: number) { return Math.min(100, Math.max(1, Math.floor(Number(value) || 20))); }
|
||||
|
||||
export function dateRange(startAt?: string, endAt?: string) {
|
||||
const start = startAt ? new Date(`${startAt}T00:00:00+08:00`) : undefined;
|
||||
const end = endAt ? new Date(`${endAt}T23:59:59.999+08:00`) : undefined;
|
||||
if (start && Number.isNaN(start.getTime())) throw new BadRequestException('开始日期无效');
|
||||
if (end && Number.isNaN(end.getTime())) throw new BadRequestException('结束日期无效');
|
||||
return start || end ? { gte: start, lte: end } : undefined;
|
||||
}
|
||||
|
||||
export function cellText(cell: ExcelJS.Cell) {
|
||||
const value = cell.value;
|
||||
if (value === null || value === undefined) return '';
|
||||
if (typeof value === 'number') return Number.isInteger(value) ? String(value) : String(value);
|
||||
if (typeof value === 'string' || typeof value === 'boolean') return String(value).trim();
|
||||
if ('result' in value && value.result !== undefined) return String(value.result ?? '').trim();
|
||||
if ('richText' in value) return value.richText.map((item) => item.text).join('').trim();
|
||||
if ('text' in value) return String(value.text).trim();
|
||||
return cell.text.trim();
|
||||
}
|
||||
|
||||
export function transformValue(value: string, transform?: string) {
|
||||
if (!transform || transform === 'trim') return value.trim();
|
||||
if (transform === 'digits') return value.replace(/\D/g, '');
|
||||
if (transform === 'uppercase') return value.trim().toUpperCase();
|
||||
if (transform === 'lowercase') return value.trim().toLowerCase();
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
export function mappedCoreValue(mappings: ImportMapping[], values: Record<string, unknown>, kind: ImportMapping['targetKind']) {
|
||||
const mapping = mappings.find((item) => item.targetKind === kind);
|
||||
return mapping ? String(values[mapping.targetFieldCode] ?? '').trim() : '';
|
||||
}
|
||||
|
||||
export function dynamicValues(mappings: ImportMapping[], values: Record<string, unknown>) {
|
||||
return Object.fromEntries(mappings.filter((item) => item.targetKind === 'dynamic').map((item) => [item.targetFieldCode, values[item.targetFieldCode]]));
|
||||
}
|
||||
|
||||
export function jsonRecord(value: unknown): Record<string, unknown> { return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}; }
|
||||
|
||||
export function hasValue(value: unknown) { return isFileRef(value) ? Boolean(value.fileObjectId) : value !== null && value !== undefined && String(value).trim().length > 0; }
|
||||
|
||||
export function isFileRef(value: unknown): value is { fileObjectId: string; fileName: string; contentType?: string } { return Boolean(value) && typeof value === 'object' && !Array.isArray(value) && typeof (value as Record<string, unknown>).fileObjectId === 'string'; }
|
||||
|
||||
export function resolveExportValue(snapshot: Record<string, unknown>, code: string, name?: string) {
|
||||
const values = jsonRecord(snapshot.values);
|
||||
if (hasValue(values[code])) return values[code];
|
||||
const signature = jsonRecord(snapshot.signature);
|
||||
const drainage = jsonRecord(snapshot.drainage);
|
||||
const aliases: Record<string, unknown> = {
|
||||
signature_name: signature.name, sign_name: signature.name, signatureName: signature.name,
|
||||
purpose: signature.purpose, enterprise_name: signature.tenantName, company_name: signature.tenantName,
|
||||
application_name: signature.applicationName, site_name: drainage.siteName, url: drainage.url, remark: drainage.remark,
|
||||
};
|
||||
if (hasValue(aliases[code])) return aliases[code];
|
||||
const semantic = normalizeHeader(`${code}/${name ?? ''}`);
|
||||
if (/短信签名|签名名称|signaturename|sms(?:signature|sign)|^sign$/.test(semantic)) return signature.name;
|
||||
if (/签名用途|签名依据|purpose/.test(semantic)) return signature.purpose;
|
||||
if (/企业名称|公司名称|enterprisename|companyname/.test(semantic)) return signature.tenantName;
|
||||
if (/应用名称|applicationname|appname/.test(semantic)) return signature.applicationName;
|
||||
if (/站点名称|网站名称|sitename/.test(semantic)) return drainage.siteName;
|
||||
if (/引流地址|网址|链接|url/.test(semantic)) return drainage.url;
|
||||
if (/备注|说明|remark/.test(semantic)) return drainage.remark;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function applyExportTransform(value: unknown, transform?: string | null) {
|
||||
const text = value === null || value === undefined ? '' : String(value);
|
||||
return transformValue(text, transform ?? undefined);
|
||||
}
|
||||
|
||||
export function styleHeader(row: ExcelJS.Row) {
|
||||
row.height = 28;
|
||||
row.eachCell((cell) => {
|
||||
cell.font = { bold: true, color: { argb: 'FFFFFFFF' } };
|
||||
cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF2563EB' } };
|
||||
cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true };
|
||||
cell.border = { bottom: { style: 'thin', color: { argb: 'FFD1D5DB' } } };
|
||||
});
|
||||
}
|
||||
|
||||
export function normalizeImageExtension(value: string) { const normalized = value.toLowerCase().replace(/^\./, ''); return normalized === 'jpg' ? 'jpeg' : normalized; }
|
||||
|
||||
export function imageContentType(extension: string) { const normalized = normalizeImageExtension(extension); return normalized === 'jpeg' ? 'image/jpeg' : normalized === 'gif' ? 'image/gif' : 'image/png'; }
|
||||
|
||||
export function safeFileName(value: string) { return value.replace(/[\\/:*?"<>|]/g, '_').slice(0, 80) || '通道报备'; }
|
||||
|
||||
export function normalizeBatchIdempotencyKey(value?: string) {
|
||||
const key = value?.trim();
|
||||
if (!key || key.length > 128 || !/^[A-Za-z0-9._:-]{8,128}$/.test(key)) throw new BadRequestException({ code: 'IDEMPOTENCY_KEY_INVALID', message: 'idempotencyKey 必填且长度为8至128位' });
|
||||
return key;
|
||||
}
|
||||
|
||||
export function jsonStringArray(value: unknown) {
|
||||
return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
|
||||
}
|
||||
|
||||
export function jsonSafe(value: unknown): Prisma.InputJsonValue {
|
||||
return JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Get, Param, Post, Put, Query } from '@nestjs/common';
|
||||
import { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { CurrentSessionUserId } from '../auth/current-session-user.decorator';
|
||||
import { SendChainService } from '../send-chain/send-chain.service';
|
||||
@@ -8,11 +8,20 @@ import {
|
||||
ReviewSmsTaskDto,
|
||||
RiskReviewService,
|
||||
} from './risk-review.service';
|
||||
import {
|
||||
CreatePhoneFrequencyWhitelistDto,
|
||||
PhoneFrequencyService,
|
||||
UpdatePhoneFrequencyWhitelistDto,
|
||||
} from './phone-frequency.service';
|
||||
|
||||
@ApiTags('risk-review')
|
||||
@Controller('admin/risk-review')
|
||||
export class AdminRiskReviewController {
|
||||
constructor(private readonly riskReview: RiskReviewService, private readonly sendChain: SendChainService) {}
|
||||
constructor(
|
||||
private readonly riskReview: RiskReviewService,
|
||||
private readonly sendChain: SendChainService,
|
||||
private readonly phoneFrequency: PhoneFrequencyService,
|
||||
) {}
|
||||
|
||||
@Get('rules')
|
||||
listRules(@Query('applicationId') applicationId?: string) {
|
||||
@@ -34,6 +43,85 @@ export class AdminRiskReviewController {
|
||||
return this.riskReview.listHits(tenantId, taskId);
|
||||
}
|
||||
|
||||
@Get('phone-frequency-hits')
|
||||
listPhoneFrequencyHits(
|
||||
@Query('tenantId') tenantId?: string,
|
||||
@Query('applicationId') applicationId?: string,
|
||||
@Query('phoneNumber') phoneNumber?: string,
|
||||
@Query('status') status?: 'active' | 'expired' | 'released',
|
||||
@Query('createdAtFrom') createdAtFrom?: string,
|
||||
@Query('createdAtTo') createdAtTo?: string,
|
||||
@Query('page') page?: string,
|
||||
@Query('pageSize') pageSize?: string,
|
||||
) {
|
||||
return this.phoneFrequency.listHits({
|
||||
tenantId,
|
||||
applicationId,
|
||||
phoneNumber,
|
||||
status,
|
||||
createdAtFrom,
|
||||
createdAtTo,
|
||||
page: Number(page ?? 1),
|
||||
pageSize: Number(pageSize ?? 20),
|
||||
});
|
||||
}
|
||||
|
||||
@Post('phone-frequency-hits/:id/release')
|
||||
releasePhoneFrequencyHit(
|
||||
@Param('id') hitId: string,
|
||||
@Body() body: { reason?: string },
|
||||
@CurrentSessionUserId() reviewerId?: string,
|
||||
) {
|
||||
return this.phoneFrequency.releaseHit(hitId, reviewerId, body.reason);
|
||||
}
|
||||
|
||||
@Get('phone-frequency-whitelist')
|
||||
listPhoneFrequencyWhitelist(
|
||||
@Query('phoneNumber') phoneNumber?: string,
|
||||
@Query('keyword') keyword?: string,
|
||||
@Query('status') status?: 'active' | 'inactive' | 'deleted',
|
||||
@Query('updatedAtFrom') updatedAtFrom?: string,
|
||||
@Query('updatedAtTo') updatedAtTo?: string,
|
||||
@Query('page') page?: string,
|
||||
@Query('pageSize') pageSize?: string,
|
||||
) {
|
||||
return this.phoneFrequency.listWhitelist({
|
||||
phoneNumber,
|
||||
keyword,
|
||||
status,
|
||||
updatedAtFrom,
|
||||
updatedAtTo,
|
||||
page: Number(page ?? 1),
|
||||
pageSize: Number(pageSize ?? 20),
|
||||
});
|
||||
}
|
||||
|
||||
@Post('phone-frequency-whitelist')
|
||||
createPhoneFrequencyWhitelist(
|
||||
@Body() body: CreatePhoneFrequencyWhitelistDto,
|
||||
@CurrentSessionUserId() operatorId?: string,
|
||||
) {
|
||||
return this.phoneFrequency.createWhitelist(body, operatorId);
|
||||
}
|
||||
|
||||
@Put('phone-frequency-whitelist/:id')
|
||||
updatePhoneFrequencyWhitelist(
|
||||
@Param('id') id: string,
|
||||
@Body() body: UpdatePhoneFrequencyWhitelistDto,
|
||||
@CurrentSessionUserId() operatorId?: string,
|
||||
) {
|
||||
return this.phoneFrequency.updateWhitelist(id, body, operatorId);
|
||||
}
|
||||
|
||||
@Delete('phone-frequency-whitelist/:id')
|
||||
deletePhoneFrequencyWhitelist(
|
||||
@Param('id') id: string,
|
||||
@Body() body: { reason?: string },
|
||||
@CurrentSessionUserId() operatorId?: string,
|
||||
) {
|
||||
return this.phoneFrequency.deleteWhitelist(id, operatorId, body.reason);
|
||||
}
|
||||
|
||||
@Get('tasks')
|
||||
listTasks(@Query('tenantId') tenantId?: string, @Query('status') status?: string) {
|
||||
return this.riskReview.listTasks(tenantId, status);
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { PhoneFrequencyService, fixedShanghaiWindow } from './phone-frequency.service';
|
||||
|
||||
describe('PhoneFrequencyService', () => {
|
||||
it('aligns five-minute cycles and natural days in Asia/Shanghai', () => {
|
||||
const requestedAt = new Date('2026-07-30T16:07:42.000Z');
|
||||
|
||||
expect(fixedShanghaiWindow(requestedAt, 300)).toEqual({
|
||||
startAt: new Date('2026-07-30T16:05:00.000Z'),
|
||||
endAt: new Date('2026-07-30T16:10:00.000Z'),
|
||||
});
|
||||
expect(fixedShanghaiWindow(requestedAt, 86400)).toEqual({
|
||||
startAt: new Date('2026-07-30T16:00:00.000Z'),
|
||||
endAt: new Date('2026-07-31T16:00:00.000Z'),
|
||||
});
|
||||
});
|
||||
|
||||
it('creates a persistent hit and rejects the threshold-exceeding phone only', async () => {
|
||||
const tx = {
|
||||
$queryRaw: jest.fn()
|
||||
.mockResolvedValueOnce([{
|
||||
id: 'state-24h',
|
||||
phoneNumber: '13800000001',
|
||||
count: 2,
|
||||
generation: 0,
|
||||
activeHitId: null,
|
||||
windowStartedAt: new Date('2026-07-29T16:00:00.000Z'),
|
||||
windowEndsAt: new Date('2026-07-30T16:00:00.000Z'),
|
||||
}])
|
||||
.mockResolvedValueOnce([{
|
||||
id: 'state-5m',
|
||||
phoneNumber: '13800000001',
|
||||
count: 6,
|
||||
generation: 0,
|
||||
activeHitId: null,
|
||||
windowStartedAt: new Date('2026-07-30T01:00:00.000Z'),
|
||||
windowEndsAt: new Date('2026-07-30T01:05:00.000Z'),
|
||||
}]),
|
||||
$executeRaw: jest.fn().mockResolvedValue(1),
|
||||
phoneFrequencyHit: {
|
||||
createMany: jest.fn().mockResolvedValue({ count: 1 }),
|
||||
},
|
||||
phoneFrequencyWhitelist: {
|
||||
findMany: jest.fn().mockResolvedValue([]),
|
||||
},
|
||||
};
|
||||
const prisma = {
|
||||
riskRule: {
|
||||
findMany: jest.fn().mockResolvedValue([
|
||||
{
|
||||
id: 'rule-24h',
|
||||
applicationId: null,
|
||||
code: 'PHONE_FREQUENCY_24H',
|
||||
name: '单号码24小时发送频次',
|
||||
thresholdValue: 10,
|
||||
action: 'block',
|
||||
priority: 40,
|
||||
config: { periodSeconds: 86400 },
|
||||
},
|
||||
{
|
||||
id: 'rule-5m',
|
||||
applicationId: null,
|
||||
code: 'PHONE_FREQUENCY_5M',
|
||||
name: '单号码5分钟发送频次',
|
||||
thresholdValue: 5,
|
||||
action: 'block',
|
||||
priority: 50,
|
||||
config: { periodSeconds: 300 },
|
||||
},
|
||||
]),
|
||||
},
|
||||
$transaction: jest.fn(async (callback: (client: typeof tx) => unknown) => callback(tx)),
|
||||
};
|
||||
const riskReview = { ensureDefaultRules: jest.fn().mockResolvedValue(undefined) };
|
||||
const service = new PhoneFrequencyService(prisma as never, riskReview as never);
|
||||
|
||||
const rejected = await service.reserve(
|
||||
'tenant-1',
|
||||
'application-1',
|
||||
['13800000001'],
|
||||
'client',
|
||||
new Date('2026-07-30T01:03:00.000Z'),
|
||||
);
|
||||
|
||||
expect(rejected.get('13800000001')).toEqual(expect.objectContaining({
|
||||
code: 'PHONE_FREQUENCY_LIMIT',
|
||||
reason: expect.stringContaining('当前第6条'),
|
||||
}));
|
||||
expect(tx.phoneFrequencyHit.createMany).toHaveBeenCalledWith({
|
||||
data: [expect.objectContaining({
|
||||
applicationId: 'application-1',
|
||||
phoneNumber: '13800000001',
|
||||
ruleCode: 'PHONE_FREQUENCY_5M',
|
||||
thresholdValue: 5,
|
||||
actualValue: 6,
|
||||
})],
|
||||
});
|
||||
expect(tx.$executeRaw).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('bypasses both frequency rules for active platform-level whitelist phones', async () => {
|
||||
const tx = {
|
||||
phoneFrequencyWhitelist: {
|
||||
findMany: jest.fn().mockResolvedValue([{ phoneNumber: '13800000001' }]),
|
||||
},
|
||||
$queryRaw: jest.fn(),
|
||||
};
|
||||
const prisma = {
|
||||
riskRule: {
|
||||
findMany: jest.fn().mockResolvedValue([{
|
||||
id: 'rule-5m',
|
||||
applicationId: null,
|
||||
code: 'PHONE_FREQUENCY_5M',
|
||||
name: '单号码5分钟发送频次',
|
||||
thresholdValue: 5,
|
||||
action: 'block',
|
||||
priority: 50,
|
||||
config: { periodSeconds: 300 },
|
||||
}]),
|
||||
},
|
||||
$transaction: jest.fn(async (callback: (client: typeof tx) => unknown) => callback(tx)),
|
||||
};
|
||||
const riskReview = { ensureDefaultRules: jest.fn().mockResolvedValue(undefined) };
|
||||
const service = new PhoneFrequencyService(prisma as never, riskReview as never);
|
||||
|
||||
const rejected = await service.reserve(
|
||||
'tenant-1',
|
||||
'application-1',
|
||||
['13800000001'],
|
||||
'client',
|
||||
new Date('2026-07-30T01:03:00.000Z'),
|
||||
);
|
||||
|
||||
expect(rejected.size).toBe(0);
|
||||
expect(tx.phoneFrequencyWhitelist.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
phoneNumber: { in: ['13800000001'] },
|
||||
status: 'active',
|
||||
deletedAt: null,
|
||||
},
|
||||
select: { phoneNumber: true },
|
||||
});
|
||||
expect(tx.$queryRaw).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,690 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { RiskReviewService } from './risk-review.service';
|
||||
|
||||
const PHONE_FREQUENCY_RULE_CODES = ['PHONE_FREQUENCY_24H', 'PHONE_FREQUENCY_5M'] as const;
|
||||
const FREQUENCY_WRITE_CHUNK_SIZE = 1000;
|
||||
|
||||
type FrequencyRule = {
|
||||
id: string;
|
||||
applicationId: string | null;
|
||||
code: string;
|
||||
name: string;
|
||||
thresholdValue: number;
|
||||
action: string;
|
||||
priority: number;
|
||||
config: unknown;
|
||||
};
|
||||
|
||||
type FrequencyStateRow = {
|
||||
id: string;
|
||||
phoneNumber: string;
|
||||
count: number;
|
||||
generation: number;
|
||||
activeHitId: string | null;
|
||||
windowStartedAt: Date;
|
||||
windowEndsAt: Date;
|
||||
};
|
||||
|
||||
export interface PhoneFrequencyHitQuery {
|
||||
tenantId?: string;
|
||||
applicationId?: string;
|
||||
phoneNumber?: string;
|
||||
status?: 'active' | 'expired' | 'released';
|
||||
createdAtFrom?: string;
|
||||
createdAtTo?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface PhoneFrequencyWhitelistQuery {
|
||||
phoneNumber?: string;
|
||||
keyword?: string;
|
||||
status?: 'active' | 'inactive' | 'deleted';
|
||||
updatedAtFrom?: string;
|
||||
updatedAtTo?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface CreatePhoneFrequencyWhitelistDto {
|
||||
phoneNumber: string;
|
||||
reason: string;
|
||||
remark?: string;
|
||||
status?: 'active' | 'inactive';
|
||||
}
|
||||
|
||||
export type UpdatePhoneFrequencyWhitelistDto = Partial<CreatePhoneFrequencyWhitelistDto>;
|
||||
|
||||
export interface PhoneFrequencyRejection {
|
||||
code: 'PHONE_FREQUENCY_LIMIT';
|
||||
reason: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PhoneFrequencyService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly riskReview: RiskReviewService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 为一次初始业务短信提交占用频次。调用方只传尚未被格式或黑名单拒绝的号码;
|
||||
* 长短信分片、通道重试和补发不会进入这里,因此同一业务号码只计一次。
|
||||
*/
|
||||
async reserve(
|
||||
tenantId: string,
|
||||
applicationId: string | undefined,
|
||||
phones: string[],
|
||||
sourceType?: string,
|
||||
requestedAt = new Date(),
|
||||
) {
|
||||
if (!applicationId) return new Map<string, PhoneFrequencyRejection>();
|
||||
const normalizedPhones = [...new Set(phones.map((phone) => phone.trim()).filter(Boolean))].sort();
|
||||
if (normalizedPhones.length === 0) return new Map<string, PhoneFrequencyRejection>();
|
||||
|
||||
await this.riskReview.ensureDefaultRules();
|
||||
const rules = await this.effectiveRules(applicationId);
|
||||
if (rules.length === 0) return new Map<string, PhoneFrequencyRejection>();
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const rejected = new Map<string, PhoneFrequencyRejection>();
|
||||
// 平台级白名单只截断号码频控链路;调用 reserve 之前已执行的格式、黑名单等校验不受影响。
|
||||
const whitelistedPhones = await this.findActiveWhitelistedPhones(tx, normalizedPhones);
|
||||
const controlledPhones = normalizedPhones.filter((phone) => !whitelistedPhones.has(phone));
|
||||
if (controlledPhones.length === 0) return rejected;
|
||||
for (const rule of rules) {
|
||||
const window = fixedShanghaiWindow(requestedAt, readPeriodSeconds(rule));
|
||||
// 分块限制 SQL 参数数量,但两条规则的全部分块仍在同一事务中提交或回滚。
|
||||
for (const phoneChunk of chunks(controlledPhones, FREQUENCY_WRITE_CHUNK_SIZE)) {
|
||||
const states = await this.upsertStates(tx, {
|
||||
tenantId,
|
||||
applicationId,
|
||||
phones: phoneChunk,
|
||||
rule,
|
||||
window,
|
||||
});
|
||||
const newTriggers = states.filter((state) => state.activeHitId === null && state.count > rule.thresholdValue);
|
||||
const hitByStateId = new Map<string, string>();
|
||||
if (newTriggers.length > 0) {
|
||||
const hitRows = newTriggers.map((state) => {
|
||||
const hitId = randomUUID();
|
||||
hitByStateId.set(state.id, hitId);
|
||||
return {
|
||||
id: hitId,
|
||||
tenantId,
|
||||
applicationId,
|
||||
ruleId: rule.id,
|
||||
ruleCode: rule.code,
|
||||
ruleName: rule.name,
|
||||
phoneNumber: state.phoneNumber,
|
||||
thresholdValue: Math.floor(rule.thresholdValue),
|
||||
actualValue: state.count,
|
||||
windowStartedAt: state.windowStartedAt,
|
||||
windowEndsAt: state.windowEndsAt,
|
||||
generation: state.generation,
|
||||
action: 'block',
|
||||
sourceType,
|
||||
};
|
||||
});
|
||||
await tx.phoneFrequencyHit.createMany({ data: hitRows });
|
||||
await this.attachActiveHits(tx, hitByStateId);
|
||||
}
|
||||
|
||||
for (const state of states) {
|
||||
if (state.activeHitId === null && state.count <= rule.thresholdValue) continue;
|
||||
const reason = `${rule.name}命中:本周期最多${Math.floor(rule.thresholdValue)}条,当前第${state.count}条,周期${formatWindow(state.windowStartedAt, state.windowEndsAt)}`;
|
||||
const existing = rejected.get(state.phoneNumber);
|
||||
rejected.set(state.phoneNumber, {
|
||||
code: 'PHONE_FREQUENCY_LIMIT',
|
||||
reason: existing ? `${existing.reason};${reason}` : reason,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return rejected;
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted });
|
||||
}
|
||||
|
||||
async listHits(query: PhoneFrequencyHitQuery) {
|
||||
const page = Math.max(1, Math.floor(Number(query.page) || 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 20)));
|
||||
const now = new Date();
|
||||
if (query.status && !['active', 'expired', 'released'].includes(query.status)) {
|
||||
throw new BadRequestException('号码频次触发记录状态无效');
|
||||
}
|
||||
const createdAtFrom = parseOptionalDate(query.createdAtFrom, '开始时间');
|
||||
const createdAtTo = parseOptionalDate(query.createdAtTo, '结束时间');
|
||||
if (createdAtFrom && createdAtTo && createdAtFrom > createdAtTo) {
|
||||
throw new BadRequestException('开始时间不能晚于结束时间');
|
||||
}
|
||||
const where: Prisma.PhoneFrequencyHitWhereInput = {
|
||||
tenantId: query.tenantId,
|
||||
applicationId: query.applicationId,
|
||||
phoneNumber: query.phoneNumber?.trim() ? { contains: query.phoneNumber.trim() } : undefined,
|
||||
createdAt: createdAtFrom || createdAtTo ? {
|
||||
gte: createdAtFrom,
|
||||
lte: createdAtTo,
|
||||
} : undefined,
|
||||
...(query.status === 'active' ? { releasedAt: null, windowEndsAt: { gt: now } } : {}),
|
||||
...(query.status === 'expired' ? { releasedAt: null, windowEndsAt: { lte: now } } : {}),
|
||||
...(query.status === 'released' ? { releasedAt: { not: null } } : {}),
|
||||
};
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.phoneFrequencyHit.findMany({
|
||||
where,
|
||||
include: {
|
||||
tenant: { select: { id: true, name: true } },
|
||||
application: { select: { id: true, name: true } },
|
||||
releasedBy: { select: { id: true, username: true, displayName: true } },
|
||||
},
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.phoneFrequencyHit.count({ where }),
|
||||
]);
|
||||
return { items, total, page, pageSize };
|
||||
}
|
||||
|
||||
async releaseHit(hitId: string, reviewerId: string | undefined, reason?: string) {
|
||||
const normalizedReason = reason?.trim();
|
||||
if (!reviewerId) throw new BadRequestException('解除操作需要有效的运营登录会话');
|
||||
if (!normalizedReason) throw new BadRequestException('解除并清零时必须填写原因');
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
// 与并发 reserve 串行:解除先锁住当前活跃状态,再同时清零计数和断开命中关联。
|
||||
const [lockedState] = await tx.$queryRaw<Array<{ id: string }>>(Prisma.sql`
|
||||
SELECT state.id
|
||||
FROM "PhoneFrequencyState" state
|
||||
WHERE state."activeHitId" = ${hitId}
|
||||
FOR UPDATE
|
||||
`);
|
||||
const hit = await tx.phoneFrequencyHit.findUnique({ where: { id: hitId } });
|
||||
if (!hit) throw new NotFoundException('号码频次触发记录不存在');
|
||||
if (hit.releasedAt) {
|
||||
return tx.phoneFrequencyHit.findUnique({
|
||||
where: { id: hitId },
|
||||
include: { tenant: true, application: true, releasedBy: true },
|
||||
});
|
||||
}
|
||||
const releasedAt = new Date();
|
||||
if (lockedState) {
|
||||
await tx.phoneFrequencyState.update({
|
||||
where: { id: lockedState.id },
|
||||
data: {
|
||||
count: 0,
|
||||
generation: { increment: 1 },
|
||||
activeHitId: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
const released = await tx.phoneFrequencyHit.update({
|
||||
where: { id: hitId },
|
||||
data: {
|
||||
releasedAt,
|
||||
releasedById: reviewerId,
|
||||
releaseReason: normalizedReason,
|
||||
},
|
||||
include: {
|
||||
tenant: { select: { id: true, name: true } },
|
||||
application: { select: { id: true, name: true } },
|
||||
releasedBy: { select: { id: true, username: true, displayName: true } },
|
||||
},
|
||||
});
|
||||
await tx.operationLog.create({
|
||||
data: {
|
||||
tenantId: hit.tenantId,
|
||||
userId: reviewerId,
|
||||
action: 'phone_frequency.release',
|
||||
resource: 'phone_frequency_hit',
|
||||
resourceId: hitId,
|
||||
detail: {
|
||||
applicationId: hit.applicationId,
|
||||
phoneNumber: hit.phoneNumber,
|
||||
ruleCode: hit.ruleCode,
|
||||
countReset: Boolean(lockedState),
|
||||
reason: normalizedReason,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
return released;
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted });
|
||||
}
|
||||
|
||||
async listWhitelist(query: PhoneFrequencyWhitelistQuery) {
|
||||
const page = Math.max(1, Math.floor(Number(query.page) || 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 20)));
|
||||
if (query.status && !['active', 'inactive', 'deleted'].includes(query.status)) {
|
||||
throw new BadRequestException('号码频控白名单状态无效');
|
||||
}
|
||||
const updatedAtFrom = parseOptionalDate(query.updatedAtFrom, '开始时间');
|
||||
const updatedAtTo = parseOptionalDate(query.updatedAtTo, '结束时间');
|
||||
if (updatedAtFrom && updatedAtTo && updatedAtFrom > updatedAtTo) {
|
||||
throw new BadRequestException('开始时间不能晚于结束时间');
|
||||
}
|
||||
const keyword = query.keyword?.trim();
|
||||
const phoneNumber = query.phoneNumber?.trim();
|
||||
const where: Prisma.PhoneFrequencyWhitelistWhereInput = {
|
||||
status: query.status ?? { not: 'deleted' },
|
||||
phoneNumber: phoneNumber ? { contains: phoneNumber } : undefined,
|
||||
updatedAt: updatedAtFrom || updatedAtTo ? { gte: updatedAtFrom, lte: updatedAtTo } : undefined,
|
||||
OR: keyword ? [
|
||||
{ phoneNumber: { contains: keyword } },
|
||||
{ reason: { contains: keyword, mode: 'insensitive' } },
|
||||
{ remark: { contains: keyword, mode: 'insensitive' } },
|
||||
] : undefined,
|
||||
};
|
||||
const include = {
|
||||
createdBy: { select: { id: true, username: true, displayName: true } },
|
||||
updatedBy: { select: { id: true, username: true, displayName: true } },
|
||||
} as const;
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.phoneFrequencyWhitelist.findMany({
|
||||
where,
|
||||
include,
|
||||
orderBy: [{ updatedAt: 'desc' }, { id: 'desc' }],
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.phoneFrequencyWhitelist.count({ where }),
|
||||
]);
|
||||
return { items, total, page, pageSize };
|
||||
}
|
||||
|
||||
async createWhitelist(data: CreatePhoneFrequencyWhitelistDto, operatorId: string | undefined) {
|
||||
const normalized = normalizeWhitelistInput(data, false);
|
||||
if (!operatorId) throw new BadRequestException('白名单操作需要有效的运营登录会话');
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const existing = await tx.phoneFrequencyWhitelist.findUnique({
|
||||
where: { phoneNumber: normalized.phoneNumber },
|
||||
});
|
||||
if (existing && existing.status !== 'deleted') {
|
||||
throw new BadRequestException('该号码已存在于号码频控白名单');
|
||||
}
|
||||
const entry = existing
|
||||
? await tx.phoneFrequencyWhitelist.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
...normalized,
|
||||
deletedAt: null,
|
||||
updatedById: operatorId,
|
||||
},
|
||||
})
|
||||
: await tx.phoneFrequencyWhitelist.create({
|
||||
data: {
|
||||
...normalized,
|
||||
createdById: operatorId,
|
||||
updatedById: operatorId,
|
||||
},
|
||||
});
|
||||
const reset = normalized.status === 'active'
|
||||
? await this.resetFrequencyStates(tx, [normalized.phoneNumber], operatorId, '号码加入平台级频控白名单')
|
||||
: { stateCount: 0, hitCount: 0 };
|
||||
await tx.operationLog.create({
|
||||
data: {
|
||||
userId: operatorId,
|
||||
action: existing ? 'phone_frequency_whitelist.restore' : 'phone_frequency_whitelist.create',
|
||||
resource: 'phone_frequency_whitelist',
|
||||
resourceId: entry.id,
|
||||
detail: {
|
||||
after: normalized,
|
||||
reset,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
return tx.phoneFrequencyWhitelist.findUnique({
|
||||
where: { id: entry.id },
|
||||
include: whitelistUserInclude,
|
||||
});
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted });
|
||||
}
|
||||
|
||||
async updateWhitelist(
|
||||
id: string,
|
||||
data: UpdatePhoneFrequencyWhitelistDto,
|
||||
operatorId: string | undefined,
|
||||
) {
|
||||
if (!operatorId) throw new BadRequestException('白名单操作需要有效的运营登录会话');
|
||||
if (!data || Object.keys(data).length === 0) throw new BadRequestException('没有需要修改的白名单字段');
|
||||
const normalized = normalizeWhitelistInput(data, true);
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
await tx.$queryRaw(Prisma.sql`
|
||||
SELECT id FROM "PhoneFrequencyWhitelist" WHERE id = ${id} FOR UPDATE
|
||||
`);
|
||||
const existing = await tx.phoneFrequencyWhitelist.findUnique({ where: { id } });
|
||||
if (!existing || existing.status === 'deleted') {
|
||||
throw new NotFoundException('号码频控白名单记录不存在');
|
||||
}
|
||||
const nextPhone = normalized.phoneNumber ?? existing.phoneNumber;
|
||||
const nextStatus = normalized.status ?? existing.status;
|
||||
if (nextPhone !== existing.phoneNumber) {
|
||||
const duplicate = await tx.phoneFrequencyWhitelist.findUnique({ where: { phoneNumber: nextPhone } });
|
||||
if (duplicate && duplicate.id !== id) {
|
||||
throw new BadRequestException(
|
||||
duplicate.status === 'deleted'
|
||||
? '该号码存在已删除的白名单历史记录,请直接重新新增该号码以恢复记录'
|
||||
: '该号码已存在于号码频控白名单',
|
||||
);
|
||||
}
|
||||
}
|
||||
const shouldReset = nextPhone !== existing.phoneNumber || nextStatus !== existing.status;
|
||||
const reset = shouldReset
|
||||
? await this.resetFrequencyStates(
|
||||
tx,
|
||||
[existing.phoneNumber, nextPhone],
|
||||
operatorId,
|
||||
'平台级频控白名单号码或状态发生变更',
|
||||
)
|
||||
: { stateCount: 0, hitCount: 0 };
|
||||
const entry = await tx.phoneFrequencyWhitelist.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...normalized,
|
||||
updatedById: operatorId,
|
||||
},
|
||||
include: whitelistUserInclude,
|
||||
});
|
||||
await tx.operationLog.create({
|
||||
data: {
|
||||
userId: operatorId,
|
||||
action: 'phone_frequency_whitelist.update',
|
||||
resource: 'phone_frequency_whitelist',
|
||||
resourceId: id,
|
||||
detail: {
|
||||
before: whitelistAuditValue(existing),
|
||||
after: whitelistAuditValue(entry),
|
||||
reset,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
return entry;
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted });
|
||||
}
|
||||
|
||||
async deleteWhitelist(id: string, operatorId: string | undefined, reason?: string) {
|
||||
if (!operatorId) throw new BadRequestException('白名单操作需要有效的运营登录会话');
|
||||
const normalizedReason = reason?.trim();
|
||||
if (!normalizedReason) throw new BadRequestException('删除白名单时必须填写原因');
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
await tx.$queryRaw(Prisma.sql`
|
||||
SELECT id FROM "PhoneFrequencyWhitelist" WHERE id = ${id} FOR UPDATE
|
||||
`);
|
||||
const existing = await tx.phoneFrequencyWhitelist.findUnique({ where: { id } });
|
||||
if (!existing || existing.status === 'deleted') {
|
||||
throw new NotFoundException('号码频控白名单记录不存在');
|
||||
}
|
||||
const reset = await this.resetFrequencyStates(
|
||||
tx,
|
||||
[existing.phoneNumber],
|
||||
operatorId,
|
||||
`删除平台级频控白名单:${normalizedReason}`,
|
||||
);
|
||||
const entry = await tx.phoneFrequencyWhitelist.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: 'deleted',
|
||||
deletedAt: new Date(),
|
||||
updatedById: operatorId,
|
||||
},
|
||||
include: whitelistUserInclude,
|
||||
});
|
||||
await tx.operationLog.create({
|
||||
data: {
|
||||
userId: operatorId,
|
||||
action: 'phone_frequency_whitelist.delete',
|
||||
resource: 'phone_frequency_whitelist',
|
||||
resourceId: id,
|
||||
detail: {
|
||||
phoneNumber: existing.phoneNumber,
|
||||
reason: normalizedReason,
|
||||
reset,
|
||||
} as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
return entry;
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted });
|
||||
}
|
||||
|
||||
private async findActiveWhitelistedPhones(tx: Prisma.TransactionClient, phones: string[]) {
|
||||
const result = new Set<string>();
|
||||
for (const phoneChunk of chunks(phones, FREQUENCY_WRITE_CHUNK_SIZE)) {
|
||||
const rows = await tx.phoneFrequencyWhitelist.findMany({
|
||||
where: { phoneNumber: { in: phoneChunk }, status: 'active', deletedAt: null },
|
||||
select: { phoneNumber: true },
|
||||
});
|
||||
for (const row of rows) result.add(row.phoneNumber);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private async resetFrequencyStates(
|
||||
tx: Prisma.TransactionClient,
|
||||
phones: string[],
|
||||
operatorId: string,
|
||||
releaseReason: string,
|
||||
) {
|
||||
// 白名单状态变化按号码跨应用清零;历史命中保留,只解除当前仍与状态关联的活跃命中。
|
||||
const normalizedPhones = [...new Set(phones)].sort();
|
||||
const states = await tx.phoneFrequencyState.findMany({
|
||||
where: { phoneNumber: { in: normalizedPhones } },
|
||||
select: { id: true, activeHitId: true },
|
||||
});
|
||||
const activeHitIds = states.flatMap((state) => state.activeHitId ? [state.activeHitId] : []);
|
||||
const releasedAt = new Date();
|
||||
const released = activeHitIds.length > 0
|
||||
? await tx.phoneFrequencyHit.updateMany({
|
||||
where: { id: { in: activeHitIds }, releasedAt: null },
|
||||
data: { releasedAt, releasedById: operatorId, releaseReason },
|
||||
})
|
||||
: { count: 0 };
|
||||
const reset = states.length > 0
|
||||
? await tx.phoneFrequencyState.updateMany({
|
||||
where: { id: { in: states.map((state) => state.id) } },
|
||||
data: { count: 0, generation: { increment: 1 }, activeHitId: null },
|
||||
})
|
||||
: { count: 0 };
|
||||
return { stateCount: reset.count, hitCount: released.count };
|
||||
}
|
||||
|
||||
private async effectiveRules(applicationId: string): Promise<FrequencyRule[]> {
|
||||
const rules = await this.prisma.riskRule.findMany({
|
||||
where: {
|
||||
status: 'active',
|
||||
code: { in: [...PHONE_FREQUENCY_RULE_CODES] },
|
||||
OR: [{ applicationId: null }, { applicationId }],
|
||||
},
|
||||
orderBy: [{ priority: 'asc' }, { createdAt: 'asc' }],
|
||||
});
|
||||
const byCode = new Map<string, FrequencyRule>();
|
||||
for (const rule of rules) {
|
||||
if (rule.applicationId || !byCode.has(rule.code)) byCode.set(rule.code, rule);
|
||||
}
|
||||
return [...byCode.values()].sort((left, right) => left.priority - right.priority);
|
||||
}
|
||||
|
||||
private upsertStates(
|
||||
tx: Prisma.TransactionClient,
|
||||
input: {
|
||||
tenantId: string;
|
||||
applicationId: string;
|
||||
phones: string[];
|
||||
rule: FrequencyRule;
|
||||
window: { startAt: Date; endAt: Date };
|
||||
},
|
||||
) {
|
||||
const values = input.phones.map((phone) => Prisma.sql`(${randomUUID()}, ${phone})`);
|
||||
// ON CONFLICT 对同一应用、规则、号码取得行锁,保证并发越过阈值时只有一个首次命中者。
|
||||
return tx.$queryRaw<FrequencyStateRow[]>(Prisma.sql`
|
||||
WITH input("id", "phoneNumber") AS (
|
||||
VALUES ${Prisma.join(values)}
|
||||
)
|
||||
INSERT INTO "PhoneFrequencyState" (
|
||||
"id", "tenantId", "applicationId", "ruleId", "ruleCode", "phoneNumber",
|
||||
"windowStartedAt", "windowEndsAt", "count", "generation", "createdAt", "updatedAt"
|
||||
)
|
||||
SELECT
|
||||
input.id, ${input.tenantId}, ${input.applicationId}, ${input.rule.id}, ${input.rule.code},
|
||||
input."phoneNumber", ${input.window.startAt}, ${input.window.endAt}, 1, 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
FROM input
|
||||
ON CONFLICT ("applicationId", "ruleCode", "phoneNumber")
|
||||
DO UPDATE SET
|
||||
"ruleId" = EXCLUDED."ruleId",
|
||||
"windowStartedAt" = EXCLUDED."windowStartedAt",
|
||||
"windowEndsAt" = EXCLUDED."windowEndsAt",
|
||||
"count" = CASE
|
||||
WHEN "PhoneFrequencyState"."windowStartedAt" <> EXCLUDED."windowStartedAt" THEN 1
|
||||
WHEN "PhoneFrequencyState"."activeHitId" IS NOT NULL THEN "PhoneFrequencyState"."count"
|
||||
ELSE "PhoneFrequencyState"."count" + 1
|
||||
END,
|
||||
"generation" = CASE
|
||||
WHEN "PhoneFrequencyState"."windowStartedAt" <> EXCLUDED."windowStartedAt" THEN 0
|
||||
ELSE "PhoneFrequencyState"."generation"
|
||||
END,
|
||||
"activeHitId" = CASE
|
||||
WHEN "PhoneFrequencyState"."windowStartedAt" <> EXCLUDED."windowStartedAt" THEN NULL
|
||||
ELSE "PhoneFrequencyState"."activeHitId"
|
||||
END,
|
||||
"updatedAt" = CURRENT_TIMESTAMP
|
||||
RETURNING
|
||||
"id", "phoneNumber", "count", "generation", "activeHitId", "windowStartedAt", "windowEndsAt"
|
||||
`);
|
||||
}
|
||||
|
||||
private async attachActiveHits(tx: Prisma.TransactionClient, hitByStateId: Map<string, string>) {
|
||||
if (hitByStateId.size === 0) return;
|
||||
const values = [...hitByStateId].map(([stateId, hitId]) => Prisma.sql`(${stateId}, ${hitId})`);
|
||||
await tx.$executeRaw(Prisma.sql`
|
||||
UPDATE "PhoneFrequencyState" state
|
||||
SET "activeHitId" = updates."hitId", "updatedAt" = CURRENT_TIMESTAMP
|
||||
FROM (VALUES ${Prisma.join(values)}) AS updates("stateId", "hitId")
|
||||
WHERE state.id = updates."stateId"
|
||||
AND state."activeHitId" IS NULL
|
||||
`);
|
||||
}
|
||||
}
|
||||
|
||||
const whitelistUserInclude = {
|
||||
createdBy: { select: { id: true, username: true, displayName: true } },
|
||||
updatedBy: { select: { id: true, username: true, displayName: true } },
|
||||
} as const;
|
||||
|
||||
function normalizeWhitelistInput(
|
||||
input: CreatePhoneFrequencyWhitelistDto | UpdatePhoneFrequencyWhitelistDto,
|
||||
partial: boolean,
|
||||
) {
|
||||
const result: {
|
||||
phoneNumber?: string;
|
||||
reason?: string;
|
||||
remark?: string | null;
|
||||
status?: 'active' | 'inactive';
|
||||
} = {};
|
||||
if (!partial || input.phoneNumber !== undefined) {
|
||||
const phoneNumber = normalizeMainlandPhone(input.phoneNumber);
|
||||
if (!phoneNumber) throw new BadRequestException('请输入有效的中国大陆11位手机号码');
|
||||
result.phoneNumber = phoneNumber;
|
||||
}
|
||||
if (!partial || input.reason !== undefined) {
|
||||
const reason = input.reason?.trim();
|
||||
if (!reason) throw new BadRequestException('白名单用途说明不能为空');
|
||||
if (reason.length > 200) throw new BadRequestException('白名单用途说明不能超过200个字符');
|
||||
result.reason = reason;
|
||||
}
|
||||
if (input.remark !== undefined) {
|
||||
const remark = input.remark?.trim() ?? '';
|
||||
if (remark.length > 500) throw new BadRequestException('白名单备注不能超过500个字符');
|
||||
result.remark = remark || null;
|
||||
}
|
||||
const status = input.status ?? (partial ? undefined : 'active');
|
||||
if (status !== undefined && !['active', 'inactive'].includes(status)) {
|
||||
throw new BadRequestException('白名单状态无效');
|
||||
}
|
||||
if (status) result.status = status;
|
||||
return result as {
|
||||
phoneNumber: string;
|
||||
reason: string;
|
||||
remark?: string | null;
|
||||
status: 'active' | 'inactive';
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeMainlandPhone(value: string | undefined) {
|
||||
const compact = value?.trim().replace(/[\s-]/g, '') ?? '';
|
||||
const withoutCountryCode = compact.startsWith('+86')
|
||||
? compact.slice(3)
|
||||
: compact.startsWith('86') && compact.length === 13
|
||||
? compact.slice(2)
|
||||
: compact;
|
||||
return /^1\d{10}$/.test(withoutCountryCode) ? withoutCountryCode : undefined;
|
||||
}
|
||||
|
||||
function whitelistAuditValue(entry: {
|
||||
phoneNumber: string;
|
||||
status: string;
|
||||
reason: string;
|
||||
remark: string | null;
|
||||
deletedAt: Date | null;
|
||||
}) {
|
||||
return {
|
||||
phoneNumber: entry.phoneNumber,
|
||||
status: entry.status,
|
||||
reason: entry.reason,
|
||||
remark: entry.remark,
|
||||
deletedAt: entry.deletedAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function readPeriodSeconds(rule: FrequencyRule) {
|
||||
const config = rule.config && typeof rule.config === 'object' && !Array.isArray(rule.config)
|
||||
? rule.config as Record<string, unknown>
|
||||
: {};
|
||||
const fallback = rule.code === 'PHONE_FREQUENCY_24H' ? 24 * 60 * 60 : 5 * 60;
|
||||
const value = Number(config.periodSeconds ?? fallback);
|
||||
return Number.isInteger(value) && value >= 60 && value <= 24 * 60 * 60 && 24 * 60 * 60 % value === 0
|
||||
? value
|
||||
: fallback;
|
||||
}
|
||||
|
||||
export function fixedShanghaiWindow(value: Date, periodSeconds: number) {
|
||||
const shanghaiOffsetMs = 8 * 60 * 60 * 1000;
|
||||
const shifted = value.getTime() + shanghaiOffsetMs;
|
||||
const dayMs = 24 * 60 * 60 * 1000;
|
||||
const localDayStart = Math.floor(shifted / dayMs) * dayMs;
|
||||
const periodMs = periodSeconds * 1000;
|
||||
const localWindowStart = localDayStart + Math.floor((shifted - localDayStart) / periodMs) * periodMs;
|
||||
return {
|
||||
startAt: new Date(localWindowStart - shanghaiOffsetMs),
|
||||
endAt: new Date(localWindowStart - shanghaiOffsetMs + periodMs),
|
||||
};
|
||||
}
|
||||
|
||||
function formatWindow(startAt: Date, endAt: Date) {
|
||||
const formatter = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
});
|
||||
return `${formatter.format(startAt)}至${formatter.format(endAt)}`;
|
||||
}
|
||||
|
||||
function chunks<T>(items: T[], size: number) {
|
||||
const result: T[][] = [];
|
||||
for (let index = 0; index < items.length; index += size) {
|
||||
result.push(items.slice(index, index + size));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseOptionalDate(value: string | undefined, label: string) {
|
||||
if (!value) return undefined;
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) {
|
||||
throw new BadRequestException(`${label}格式无效`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
@@ -3,12 +3,13 @@ import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { AdminRiskReviewController } from './admin-risk-review.controller';
|
||||
import { ClientRiskReviewController } from './client-risk-review.controller';
|
||||
import { RiskReviewService } from './risk-review.service';
|
||||
import { PhoneFrequencyService } from './phone-frequency.service';
|
||||
import { SendChainModule } from '../send-chain/send-chain.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, forwardRef(() => SendChainModule)],
|
||||
controllers: [AdminRiskReviewController, ClientRiskReviewController],
|
||||
providers: [RiskReviewService],
|
||||
exports: [RiskReviewService],
|
||||
providers: [RiskReviewService, PhoneFrequencyService],
|
||||
exports: [RiskReviewService, PhoneFrequencyService],
|
||||
})
|
||||
export class RiskReviewModule {}
|
||||
|
||||
@@ -61,6 +61,18 @@ function createPrismaMock(overrides: Record<string, unknown> = {}) {
|
||||
}
|
||||
|
||||
describe('RiskReviewService', () => {
|
||||
it('keeps phone-frequency periods fixed and rejects manual-review actions', () => {
|
||||
const service = new RiskReviewService(createPrismaMock() as never);
|
||||
|
||||
expect(() => service['normalizeRuleConfig']('PHONE_FREQUENCY_5M', { periodSeconds: 600 }))
|
||||
.toThrow('号码频次周期首版固定为24小时自然日或5分钟,不允许修改');
|
||||
expect(() => service['validateRuleInput']({
|
||||
code: 'PHONE_FREQUENCY_24H',
|
||||
thresholdValue: 10,
|
||||
action: 'manual_review',
|
||||
})).toThrow('号码频次阈值必须是大于0的整数,首版处理动作固定为直接拒绝');
|
||||
});
|
||||
|
||||
it('includes the sending enterprise and application in SMS review rows', async () => {
|
||||
const prisma = createPrismaMock();
|
||||
prisma.smsSendTask.findMany.mockResolvedValue([]);
|
||||
|
||||
@@ -87,6 +87,26 @@ const DEFAULT_RULES: CreateRiskRuleDto[] = [
|
||||
action: 'manual_review',
|
||||
priority: 30,
|
||||
},
|
||||
{
|
||||
code: 'PHONE_FREQUENCY_24H',
|
||||
name: '单号码24小时发送频次',
|
||||
description: '同一企业应用下,单个号码在北京时间自然日内最多允许10条业务短信。',
|
||||
metric: 'phoneFrequencyCount',
|
||||
thresholdValue: 10,
|
||||
action: 'block',
|
||||
priority: 40,
|
||||
config: { periodSeconds: 24 * 60 * 60, timeZone: 'Asia/Shanghai', alignment: 'fixed' },
|
||||
},
|
||||
{
|
||||
code: 'PHONE_FREQUENCY_5M',
|
||||
name: '单号码5分钟发送频次',
|
||||
description: '同一企业应用下,单个号码在固定5分钟周期内最多允许5条业务短信。',
|
||||
metric: 'phoneFrequencyCount',
|
||||
thresholdValue: 5,
|
||||
action: 'block',
|
||||
priority: 50,
|
||||
config: { periodSeconds: 5 * 60, timeZone: 'Asia/Shanghai', alignment: 'fixed' },
|
||||
},
|
||||
];
|
||||
|
||||
const RULE_DEFINITIONS = new Map(DEFAULT_RULES.map((rule) => [rule.code, rule]));
|
||||
@@ -129,7 +149,7 @@ export class RiskReviewService {
|
||||
description: definition.description,
|
||||
metric: definition.metric!,
|
||||
thresholdValue: data.thresholdValue,
|
||||
action: data.action ?? 'manual_review',
|
||||
action: isPhoneFrequencyRule(data.code) ? 'block' : data.action ?? 'manual_review',
|
||||
status: data.status ?? 'active',
|
||||
priority: data.priority ?? definition.priority ?? 100,
|
||||
config: this.normalizeRuleConfig(data.code, data.config ?? definition.config) as Prisma.InputJsonValue | undefined,
|
||||
@@ -468,7 +488,7 @@ export class RiskReviewService {
|
||||
return rejected;
|
||||
}
|
||||
|
||||
private async ensureDefaultRules() {
|
||||
async ensureDefaultRules() {
|
||||
for (const rule of DEFAULT_RULES) {
|
||||
const exists = await this.prisma.riskRule.findFirst({
|
||||
where: { applicationId: null, code: rule.code, status: { not: 'deleted' } },
|
||||
@@ -556,6 +576,12 @@ export class RiskReviewService {
|
||||
if (!Number.isFinite(data.thresholdValue) || data.thresholdValue < 0) {
|
||||
throw new BadRequestException('风控阈值必须是大于等于0的有效数字');
|
||||
}
|
||||
if (
|
||||
isPhoneFrequencyRule(data.code)
|
||||
&& (!Number.isInteger(data.thresholdValue) || data.thresholdValue < 1 || data.action === 'manual_review')
|
||||
) {
|
||||
throw new BadRequestException('号码频次阈值必须是大于0的整数,首版处理动作固定为直接拒绝');
|
||||
}
|
||||
if (data.action && !['block', 'manual_review'].includes(data.action)) {
|
||||
throw new BadRequestException('风控处理动作无效');
|
||||
}
|
||||
@@ -581,6 +607,18 @@ export class RiskReviewService {
|
||||
}
|
||||
|
||||
private normalizeRuleConfig(code: string, config?: Record<string, unknown> | null) {
|
||||
if (code === 'PHONE_FREQUENCY_24H' || code === 'PHONE_FREQUENCY_5M') {
|
||||
const defaultPeriodSeconds = code === 'PHONE_FREQUENCY_24H' ? 24 * 60 * 60 : 5 * 60;
|
||||
const periodSeconds = Number(config?.periodSeconds ?? defaultPeriodSeconds);
|
||||
if (periodSeconds !== defaultPeriodSeconds) {
|
||||
throw new BadRequestException('号码频次周期首版固定为24小时自然日或5分钟,不允许修改');
|
||||
}
|
||||
return {
|
||||
periodSeconds: defaultPeriodSeconds,
|
||||
timeZone: 'Asia/Shanghai',
|
||||
alignment: 'fixed',
|
||||
};
|
||||
}
|
||||
if (code !== 'NON_WORKING_MARKETING_BULK') {
|
||||
return config ?? undefined;
|
||||
}
|
||||
@@ -599,6 +637,10 @@ export class RiskReviewService {
|
||||
}
|
||||
}
|
||||
|
||||
function isPhoneFrequencyRule(code: string) {
|
||||
return code === 'PHONE_FREQUENCY_24H' || code === 'PHONE_FREQUENCY_5M';
|
||||
}
|
||||
|
||||
function ratio(count: number, total: number) {
|
||||
if (total <= 0) {
|
||||
return 0;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { SendChainService, TimeoutUnknownDto } from './send-chain.service';
|
||||
import { TimeoutUnknownDto } from './send-chain.contracts';
|
||||
import { SendChainService } from './send-chain.service';
|
||||
|
||||
@ApiTags('send-chain')
|
||||
@Controller('admin/send')
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { BadRequestException, Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { TenantId } from '../common/tenant-id.decorator';
|
||||
import { ConfirmImportDto, CreateBatchTaskDto, ImportPreviewDto, SendChainService } from './send-chain.service';
|
||||
import { ConfirmImportDto, CreateBatchTaskDto, ImportPreviewDto } from './send-chain.contracts';
|
||||
import { SendChainService } from './send-chain.service';
|
||||
|
||||
@ApiTags('client-send-chain')
|
||||
@Controller('client/send')
|
||||
|
||||
@@ -13,9 +13,10 @@ import {
|
||||
GatewaySubmitResultDto,
|
||||
GatewaySubmitSegmentResultDto,
|
||||
GatewayUplinkEventDto,
|
||||
SendChainService,
|
||||
} from './send-chain.service';
|
||||
import { GatewayDownstreamConnectionEventDto, SmsConfigService } from '../sms-config/sms-config.service';
|
||||
} from './send-chain.contracts';
|
||||
import { SendChainService } from './send-chain.service';
|
||||
import { GatewayDownstreamConnectionEventDto } from '../sms-config/sms-config.contracts';
|
||||
import { SmsConfigService } from '../sms-config/sms-config.service';
|
||||
import { ProtocolLogsService, type ProtocolLogInput } from '../protocol-logs/protocol-logs.service';
|
||||
|
||||
@ApiTags('gateway-events')
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { BadRequestException, HttpException, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import type { OpenApiService } from '../open-api/open-api.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { GatewaySubmitResultDto, GatewaySubmitSegmentResultDto, GatewayReceiptEventDto, GatewayUplinkEventDto, GatewayPendingDeliveryQueryDto, GatewayDownstreamSentDto, GatewayDownstreamAcknowledgedDto, GatewayDownstreamFailureType, GatewayControlDeliveryResult, GatewaySubmitDeadLetterDto, RequeueGatewaySubmitExceptionDto, GatewayDownstreamRecoveryStatusDto, TimeoutUnknownDto } from './send-chain.contracts';
|
||||
import { positiveInteger, normalizeReceiptStatus, normalizeCarrier, DEFAULT_DOWNSTREAM_RETRY_DELAY_MS, DEFAULT_DOWNSTREAM_RETRY_MAX_DELAY_MS, DEFAULT_DOWNSTREAM_MAX_RETRIES, DEFAULT_DOWNSTREAM_PENDING_TIMEOUT_HOURS, DEFAULT_RECEIPT_TIMEOUT_HOURS, DEFAULT_GATEWAY_SUBMIT_REQUEUE_STALE_MS, DEFAULT_DOWNSTREAM_MANUAL_REQUEUE_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_ATTEMPTS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_AGE_HOURS, gatewaySubmitRequeueKey, isObjectRecord, asDateOrNull, downstreamRetryDelayMs, downstreamAckTimeoutMs, downstreamRetryBaseDelayMs, downstreamRetryMaxDelayMs, downstreamMaxRetries, downstreamPendingTimeoutHours, downstreamControlFailureMessage, normalizeSubmitStatus, downstreamDeliveryAttemptKey, hasRecoveryAuditStateChanged, normalizeRecoveryFailureCategory, aggregateReceiptSegmentState, isSameUpstreamEndpointIdentity, receiptEventKey } from './send-chain.helpers';
|
||||
import type { SendSubmissionService } from './send-submission.service';
|
||||
import type { SendCompletionCallbacks, SendCompletionFacade } from './send-completion.service';
|
||||
|
||||
|
||||
/**
|
||||
* R10 accounting implementation.
|
||||
* Cross-domain calls return through the stable SendChainService seam to preserve locking and test observability.
|
||||
*/
|
||||
export class SendAccountingService {
|
||||
private readonly logger = new Logger('SendChainService');
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly openApi: OpenApiService | undefined,
|
||||
private readonly facade: SendCompletionFacade,
|
||||
private readonly callbacks: SendCompletionCallbacks,
|
||||
) {}
|
||||
|
||||
async chargeAcceptedMessage(message: {
|
||||
tenantId: string;
|
||||
applicationId?: string | null;
|
||||
batchTaskId: string;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
content: string;
|
||||
billingUnits: number;
|
||||
unitPrice: number | bigint;
|
||||
amountCents: number | bigint;
|
||||
}) {
|
||||
const amountCents = moneyToNumber(message.amountCents);
|
||||
const unitPrice = moneyToNumber(message.unitPrice);
|
||||
const billingUnits = message.billingUnits ?? 0;
|
||||
const exists = await this.prisma.smsBillingRecord.findFirst({ where: { messageId: message.messageId } });
|
||||
if (exists?.billingStatus === 'charged') {
|
||||
return;
|
||||
}
|
||||
if (amountCents > 0) {
|
||||
await this.billing.release({
|
||||
tenantId: message.tenantId,
|
||||
amountCents,
|
||||
idempotencyKey: `sms-charge-release:${message.messageId}`,
|
||||
relatedType: 'sms_batch_task',
|
||||
relatedId: message.batchTaskId,
|
||||
remark: `短信 ${message.messageId} 提交成功释放冻结并转扣费`,
|
||||
});
|
||||
}
|
||||
const transaction = await this.billing.charge({
|
||||
tenantId: message.tenantId,
|
||||
amountCents,
|
||||
idempotencyKey: `sms-charge:${message.messageId}`,
|
||||
relatedType: 'sms_message_record',
|
||||
relatedId: message.messageId,
|
||||
remark: '提交成功扣费',
|
||||
});
|
||||
const data = {
|
||||
tenantId: message.tenantId,
|
||||
applicationId: message.applicationId ?? undefined,
|
||||
taskId: message.batchTaskId,
|
||||
messageId: message.messageId,
|
||||
phoneNumber: message.phoneNumber,
|
||||
contentLength: [...message.content].length,
|
||||
billingUnits,
|
||||
unitPrice,
|
||||
amountCents,
|
||||
billingStatus: 'charged',
|
||||
transactionId: transaction.id,
|
||||
};
|
||||
if (exists) {
|
||||
await this.prisma.smsBillingRecord.update({ where: { id: exists.id }, data });
|
||||
return;
|
||||
}
|
||||
await this.prisma.smsBillingRecord.create({ data });
|
||||
}
|
||||
|
||||
async releaseMessageReservation(
|
||||
message: { tenantId: string; batchTaskId: string; messageId: string; amountCents: number | bigint; billingUnits: number },
|
||||
remark: string,
|
||||
) {
|
||||
const amountCents = moneyToNumber(message.amountCents);
|
||||
if (amountCents <= 0) {
|
||||
return;
|
||||
}
|
||||
const charged = await this.prisma.smsBillingRecord.findFirst({ where: { messageId: message.messageId, billingStatus: 'charged' } });
|
||||
if (charged) {
|
||||
return;
|
||||
}
|
||||
const released = await this.prisma.accountTransaction.findFirst({
|
||||
where: { relatedType: 'sms_message_record', relatedId: message.messageId, transactionType: 'released' },
|
||||
});
|
||||
if (released) {
|
||||
return;
|
||||
}
|
||||
await this.billing.release({
|
||||
tenantId: message.tenantId,
|
||||
amountCents,
|
||||
idempotencyKey: `sms-reservation-release:${message.messageId}`,
|
||||
relatedType: 'sms_message_record',
|
||||
relatedId: message.messageId,
|
||||
remark: `${remark}: ${message.messageId}`,
|
||||
});
|
||||
}
|
||||
|
||||
async refundMessage(
|
||||
message: { tenantId: string; messageId: string; amountCents: number | bigint; billingUnits: number },
|
||||
remark: string,
|
||||
) {
|
||||
const amountCents = moneyToNumber(message.amountCents);
|
||||
if (amountCents <= 0) {
|
||||
return;
|
||||
}
|
||||
const refunded = await this.prisma.smsBillingRecord.findFirst({ where: { messageId: message.messageId, billingStatus: 'refunded' } });
|
||||
if (refunded) {
|
||||
return;
|
||||
}
|
||||
const charged = await this.prisma.smsBillingRecord.findFirst({ where: { messageId: message.messageId, billingStatus: 'charged' } });
|
||||
if (!charged) {
|
||||
return;
|
||||
}
|
||||
const transaction = await this.billing.refund({
|
||||
tenantId: message.tenantId,
|
||||
amountCents,
|
||||
idempotencyKey: `sms-refund:${message.messageId}`,
|
||||
relatedType: 'sms_message_record',
|
||||
relatedId: message.messageId,
|
||||
remark,
|
||||
});
|
||||
await this.prisma.smsBillingRecord.updateMany({
|
||||
where: { messageId: message.messageId },
|
||||
data: { billingStatus: 'refunded', transactionId: transaction.id },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
import { BadRequestException, HttpException, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { Queue, Worker } from 'bullmq';
|
||||
import IORedis from 'ioredis';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { isIpAllowed } from '../common/ip-allowlist';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import { PhoneRoutingLookupService } from '../dictionaries/phone-routing-lookup.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { RiskReviewService } from '../risk-review/risk-review.service';
|
||||
import { PhoneFrequencyService } from '../risk-review/phone-frequency.service';
|
||||
import type { CreateBatchTaskDto, CreateHttpBatchTaskDto, GatewayInboundAuthDto, GatewayInboundSubmitDto, GatewayInboundSingleSubmitResult, ImportPreviewDto, ConfirmImportDto, SendJob, QueuePriority, RoutedChannel } from './send-chain.contracts';
|
||||
import { SEND_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_SCHEDULED_DISPATCH_STALE_MS, DEFAULT_INBOUND_LONG_MESSAGE_PROCESSING_STALE_SECONDS, GATEWAY_SUBMIT_REQUEUE_IDEMPOTENCY_TTL_SECONDS, BULLMQ_PRIORITY, drainageRejectionReason, statusFromRisk, parseSchedule, parseImportRows, splitImportLine, cellByHeader, normalizeCarrier, normalizeQueuePriority, getPositiveConfigInteger, getNonNegativeConfigInteger, isCarrierCompatible, matchTemplateContent, isNationalChannel, validateInboundApplicationSrcId, composeUpstreamSrcId, positiveInteger, parseOptionalSequenceId, shanghaiDateKey, bullmqConnection, matchesApplicationSecret, octetString, selectChannelCandidate } from './send-chain.helpers';
|
||||
import type { SendSubmissionCallbacks, SendSubmissionService } from './send-submission.service';
|
||||
|
||||
/**
|
||||
* R9 batchEntry implementation. Cross-method calls return through the stable SendChainService seam.
|
||||
*/
|
||||
export class SendBatchEntryService {
|
||||
private readonly logger = new Logger('SendChainService');
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly riskReview: RiskReviewService,
|
||||
private readonly phoneFrequency: PhoneFrequencyService,
|
||||
private readonly phoneRouting: PhoneRoutingLookupService,
|
||||
private readonly facade: SendSubmissionService,
|
||||
private readonly callbacks: SendSubmissionCallbacks,
|
||||
) {}
|
||||
|
||||
private releaseMessageReservation(
|
||||
message: { tenantId: string; batchTaskId: string; messageId: string; amountCents: number | bigint; billingUnits: number },
|
||||
remark: string,
|
||||
) {
|
||||
return this.callbacks.releaseMessageReservation(message, remark);
|
||||
}
|
||||
|
||||
private recordCmppFailureReceipt(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
applicationId?: string | null;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
cmppSubmitSequenceId?: string | null;
|
||||
cmppSubmitGroupMessageId?: string | null;
|
||||
},
|
||||
errorCode: string,
|
||||
reason: string,
|
||||
) {
|
||||
return this.callbacks.recordCmppFailureReceipt(message, errorCode, reason);
|
||||
}
|
||||
|
||||
|
||||
async createBatchTask(data: CreateBatchTaskDto) {
|
||||
const phones = [...new Set(data.phones ?? [])];
|
||||
const schedule = parseSchedule(data);
|
||||
await this.facade.validateSendResources(data.tenantId, data.applicationId, data.templateId);
|
||||
const phoneRejections = await this.facade.classifyRejectedPhones(data.tenantId, data.applicationId, phones);
|
||||
let sendablePhones = phones.filter((phone) => !phoneRejections.has(phone));
|
||||
const [messageClassification, unitPrice, queuePriority, accessNumber] = await Promise.all([
|
||||
this.facade.resolveTemplateMessageClassification(data.tenantId, data.applicationId, data.templateId, data.content),
|
||||
this.facade.resolveUnitPrice(data.tenantId, data.applicationId),
|
||||
this.facade.resolveQueuePriority(data.tenantId, data.applicationId),
|
||||
this.facade.resolveApplicationAccessNumber(data.tenantId, data.applicationId),
|
||||
]);
|
||||
const risk = messageClassification.rejectionReason
|
||||
? { status: 'rejected', reason: messageClassification.rejectionReason, task: null }
|
||||
: await this.riskReview.evaluateTask({
|
||||
tenantId: data.tenantId,
|
||||
applicationId: data.applicationId,
|
||||
templateId: data.templateId,
|
||||
content: data.content,
|
||||
category: data.category,
|
||||
phones,
|
||||
variables: messageClassification.variables ?? data.variables,
|
||||
createdById: data.createdById,
|
||||
sourceType: data.sourceType ?? 'client',
|
||||
});
|
||||
let frequencyRejectedAll = false;
|
||||
let frequencyBatchReason: string | undefined;
|
||||
if (risk.status !== 'rejected' && sendablePhones.length > 0) {
|
||||
const frequencyRejections = await this.phoneFrequency.reserve(
|
||||
data.tenantId,
|
||||
data.applicationId,
|
||||
sendablePhones,
|
||||
data.sourceType ?? 'client',
|
||||
);
|
||||
for (const [phone, rejection] of frequencyRejections) {
|
||||
phoneRejections.set(phone, rejection);
|
||||
}
|
||||
sendablePhones = sendablePhones.filter((phone) => !frequencyRejections.has(phone));
|
||||
frequencyRejectedAll = frequencyRejections.size > 0 && sendablePhones.length === 0;
|
||||
frequencyBatchReason = frequencyRejectedAll
|
||||
? [...frequencyRejections.values()][0]?.reason
|
||||
: undefined;
|
||||
}
|
||||
if (frequencyRejectedAll && risk.status === 'pending_review' && risk.task?.id) {
|
||||
await this.prisma.smsSendTask.update({
|
||||
where: { id: risk.task.id },
|
||||
data: {
|
||||
status: 'rejected',
|
||||
riskDecision: 'block',
|
||||
reviewReason: null,
|
||||
rejectReason: frequencyBatchReason,
|
||||
},
|
||||
});
|
||||
}
|
||||
const billing = this.billing.estimateSmsCost({
|
||||
tenantId: data.tenantId,
|
||||
applicationId: data.applicationId,
|
||||
taskId: risk.task?.id,
|
||||
content: data.content,
|
||||
phoneCount: sendablePhones.length,
|
||||
unitPrice,
|
||||
});
|
||||
const batchStatus = frequencyRejectedAll
|
||||
? 'rejected'
|
||||
: risk.status === 'approved' && sendablePhones.length === 0
|
||||
? 'failed'
|
||||
: statusFromRisk(risk.status, Boolean(schedule.scheduledAt));
|
||||
const shouldReserveBalance = batchStatus === 'ready';
|
||||
if (risk.status === 'approved') {
|
||||
const accountCheck = await this.billing.checkAccount({
|
||||
tenantId: data.tenantId,
|
||||
amountCents: billing.amountCents,
|
||||
});
|
||||
if (!accountCheck.canSend) {
|
||||
throw new BadRequestException('企业账户余额不足');
|
||||
}
|
||||
}
|
||||
if (data.applicationId && risk.status !== 'rejected' && sendablePhones.length > 0) {
|
||||
await this.facade.reserveDailySendQuota(data.applicationId, sendablePhones.length);
|
||||
}
|
||||
const task = await this.prisma.smsBatchTask.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
applicationId: data.applicationId,
|
||||
templateId: data.templateId,
|
||||
taskNo: `BT-${Date.now()}-${randomUUID().slice(0, 8)}`,
|
||||
sourceType: data.sourceType ?? 'client',
|
||||
content: data.content,
|
||||
category: data.category,
|
||||
phoneTotal: phones.length,
|
||||
status: batchStatus,
|
||||
riskTaskId: risk.task?.id,
|
||||
auditStatus: frequencyRejectedAll || risk.status === 'rejected' ? 'rejected' : risk.status === 'pending_review' ? 'pending' : 'approved',
|
||||
reviewReason: !frequencyRejectedAll && risk.status === 'pending_review' ? risk.reason : null,
|
||||
rejectReason: frequencyRejectedAll ? frequencyBatchReason : risk.status === 'rejected' ? risk.reason : null,
|
||||
progressTotal: phones.length,
|
||||
scheduledAt: schedule.scheduledAt,
|
||||
createdById: data.createdById,
|
||||
},
|
||||
});
|
||||
if (shouldReserveBalance && billing.amountCents > 0) {
|
||||
await this.billing.freeze({
|
||||
tenantId: data.tenantId,
|
||||
amountCents: billing.amountCents,
|
||||
relatedType: 'sms_batch_task',
|
||||
relatedId: task.id,
|
||||
remark: '发送任务创建冻结',
|
||||
});
|
||||
}
|
||||
await this.prisma.smsApiRequest.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
batchTaskId: task.id,
|
||||
requestId: `REQ-${Date.now()}-${randomUUID().slice(0, 8)}`,
|
||||
sourceIp: data.sourceIp,
|
||||
userAgent: data.userAgent,
|
||||
payloadSummary: {
|
||||
phoneTotal: phones.length,
|
||||
contentLength: [...data.content].length,
|
||||
category: data.category,
|
||||
sendMode: schedule.scheduledAt ? 'scheduled' : 'immediate',
|
||||
scheduledAt: schedule.scheduledAt?.toISOString(),
|
||||
},
|
||||
status: ['rejected', 'failed'].includes(batchStatus) ? 'rejected' : 'accepted',
|
||||
},
|
||||
});
|
||||
if (phones.length > 0) {
|
||||
await this.prisma.smsMessageRecord.createMany({
|
||||
data: phones.map((phone) => {
|
||||
const rejection = phoneRejections.get(phone);
|
||||
const status = rejection
|
||||
? 'submit_failed'
|
||||
: batchStatus === 'ready'
|
||||
? 'queued'
|
||||
: batchStatus === 'scheduled'
|
||||
? 'scheduled'
|
||||
: batchStatus;
|
||||
return {
|
||||
tenantId: data.tenantId,
|
||||
batchTaskId: task.id,
|
||||
applicationId: data.applicationId,
|
||||
templateId: data.templateId,
|
||||
signatureId: messageClassification.signatureId,
|
||||
drainageInfoId: messageClassification.drainageInfoId,
|
||||
reviewTaskId: !rejection && risk.status === 'pending_review' ? risk.task?.id : undefined,
|
||||
messageId: `MSG-${randomUUID()}`,
|
||||
clientMessageId: data.clientMessageId,
|
||||
phoneNumber: phone,
|
||||
content: data.content,
|
||||
billingUnits: billing.billingUnitsPerMessage,
|
||||
unitPrice: rejection ? 0 : billing.unitPrice,
|
||||
amountCents: rejection ? 0 : billing.billingUnitsPerMessage * billing.unitPrice,
|
||||
queuePriority,
|
||||
clientSrcId: accessNumber.clientSrcId,
|
||||
applicationExtension: accessNumber.applicationExtension,
|
||||
status,
|
||||
submitStatus: rejection ? 'rejected' : undefined,
|
||||
errorCode: rejection?.code,
|
||||
errorMessage: rejection?.reason ?? (risk.status === 'rejected' ? risk.reason ?? undefined : undefined),
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (batchStatus === 'ready' && sendablePhones.length > 0) {
|
||||
await this.facade.enqueueBatchTask(task.id);
|
||||
} else if (batchStatus === 'failed') {
|
||||
await this.facade.refreshTaskProgress(task.id);
|
||||
}
|
||||
return this.facade.getBatchTask(task.id, undefined, data.sourceType ?? 'client');
|
||||
}
|
||||
|
||||
async createHttpBatchTask(data: CreateHttpBatchTaskDto) {
|
||||
if (!data.applicationId) {
|
||||
throw new BadRequestException('公开 HTTP 发送必须关联企业应用');
|
||||
}
|
||||
const template = await this.facade.resolveInboundTemplateCandidate(data.applicationId, data.content);
|
||||
if (!template || template.auditStatus !== 'approved' || template.signature?.auditStatus !== 'approved') {
|
||||
throw new BadRequestException('短信内容未匹配当前应用已审核通过的签名和模板');
|
||||
}
|
||||
const variables = matchTemplateContent(template.content, data.content);
|
||||
if (variables === null) {
|
||||
throw new BadRequestException('短信内容与已审核模板不匹配');
|
||||
}
|
||||
return this.facade.createBatchTask({
|
||||
...data,
|
||||
templateId: template.id,
|
||||
variables,
|
||||
sourceType: 'api',
|
||||
});
|
||||
}
|
||||
|
||||
async getBatchTask(taskId: string, tenantId?: string, sourceType = 'client') {
|
||||
const task = await this.prisma.smsBatchTask.findFirst({
|
||||
where: { id: taskId, tenantId, sourceType },
|
||||
include: { apiRequests: true, messages: { take: 20, orderBy: { queuedAt: 'asc' } } },
|
||||
});
|
||||
if (!task) {
|
||||
throw new NotFoundException('SMS batch task not found');
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
async previewImport(data: ImportPreviewDto) {
|
||||
const sizeBytes = Buffer.byteLength(data.content, 'utf8');
|
||||
if (sizeBytes > 20 * 1024 * 1024) {
|
||||
throw new BadRequestException('导入文件不能超过 20MB');
|
||||
}
|
||||
const rows = parseImportRows(data.content, data.delimiter);
|
||||
const phones: string[] = [];
|
||||
const errors: Array<{ rowNumber: number; phoneNumber?: string; reason: string }> = [];
|
||||
const requiredVariables = data.requiredVariables ?? [];
|
||||
const enterpriseBlacklist = data.applicationId ? await this.prisma.enterpriseBlacklist.findMany({
|
||||
where: { tenantId: data.tenantId, applicationId: data.applicationId, status: 'active' },
|
||||
select: { phoneNumber: true },
|
||||
}) : [];
|
||||
const globalBlacklist = await this.prisma.globalBlacklist.findMany({
|
||||
where: { status: 'active' },
|
||||
select: { phoneNumber: true },
|
||||
});
|
||||
const blacklist = new Set([...enterpriseBlacklist, ...globalBlacklist].map((item) => item.phoneNumber));
|
||||
const seen = new Set<string>();
|
||||
for (const row of rows) {
|
||||
if (!row.phoneNumber) {
|
||||
errors.push({ rowNumber: row.rowNumber, reason: '缺少手机号' });
|
||||
continue;
|
||||
}
|
||||
if (!/^1[3-9]\d{9}$/.test(row.phoneNumber)) {
|
||||
errors.push({ rowNumber: row.rowNumber, phoneNumber: row.phoneNumber, reason: '手机号格式非法' });
|
||||
continue;
|
||||
}
|
||||
if (seen.has(row.phoneNumber)) {
|
||||
errors.push({ rowNumber: row.rowNumber, phoneNumber: row.phoneNumber, reason: '重复号码' });
|
||||
continue;
|
||||
}
|
||||
if (blacklist.has(row.phoneNumber)) {
|
||||
errors.push({ rowNumber: row.rowNumber, phoneNumber: row.phoneNumber, reason: '命中黑名单' });
|
||||
continue;
|
||||
}
|
||||
const missingVariables = requiredVariables.filter((name) => !row.variables[name]);
|
||||
if (missingVariables.length > 0) {
|
||||
errors.push({ rowNumber: row.rowNumber, phoneNumber: row.phoneNumber, reason: `变量列缺失:${missingVariables.join(',')}` });
|
||||
continue;
|
||||
}
|
||||
seen.add(row.phoneNumber);
|
||||
phones.push(row.phoneNumber);
|
||||
}
|
||||
return {
|
||||
fileName: data.fileName,
|
||||
encoding: data.encoding ?? 'utf8',
|
||||
totalRows: rows.length,
|
||||
validCount: phones.length,
|
||||
errorCount: errors.length,
|
||||
phones,
|
||||
errors,
|
||||
};
|
||||
}
|
||||
|
||||
async confirmImport(data: ConfirmImportDto) {
|
||||
const preview = await this.facade.previewImport({
|
||||
tenantId: data.tenantId,
|
||||
applicationId: data.applicationId,
|
||||
content: data.importContent,
|
||||
requiredVariables: data.requiredVariables,
|
||||
});
|
||||
if (preview.validCount === 0) {
|
||||
throw new BadRequestException('导入文件没有可发送号码');
|
||||
}
|
||||
return this.facade.createBatchTask({ ...data, phones: preview.phones });
|
||||
}
|
||||
|
||||
async resolveUnitPrice(tenantId: string, applicationId?: string) {
|
||||
if (!applicationId) {
|
||||
return 0;
|
||||
}
|
||||
const application = await this.prisma.smsApplication.findUnique({
|
||||
where: { id: applicationId },
|
||||
select: { tenantId: true, customerUnitPrice: true },
|
||||
});
|
||||
if (!application || application.tenantId !== tenantId) {
|
||||
return 0;
|
||||
}
|
||||
return moneyToNumber(application.customerUnitPrice);
|
||||
}
|
||||
|
||||
async resolveQueuePriority(tenantId: string, applicationId?: string): Promise<QueuePriority> {
|
||||
if (!applicationId) {
|
||||
return 'normal';
|
||||
}
|
||||
const application = await this.prisma.smsApplication.findUnique({
|
||||
where: { id: applicationId },
|
||||
select: { tenantId: true, queuePriority: true },
|
||||
});
|
||||
if (!application || application.tenantId !== tenantId) {
|
||||
return 'normal';
|
||||
}
|
||||
return normalizeQueuePriority(application.queuePriority);
|
||||
}
|
||||
|
||||
async resolveApplicationAccessNumber(tenantId: string, applicationId?: string) {
|
||||
if (!applicationId) {
|
||||
return { clientSrcId: null, applicationExtension: null };
|
||||
}
|
||||
const application = await this.prisma.smsApplication.findUnique({
|
||||
where: { id: applicationId },
|
||||
select: { tenantId: true, cmppClientSrcId: true, cmppApplicationExtension: true },
|
||||
});
|
||||
if (!application || application.tenantId !== tenantId) {
|
||||
return { clientSrcId: null, applicationExtension: null };
|
||||
}
|
||||
return {
|
||||
clientSrcId: application.cmppClientSrcId,
|
||||
applicationExtension: application.cmppApplicationExtension,
|
||||
};
|
||||
}
|
||||
|
||||
async resolveTemplateMessageClassification(
|
||||
tenantId: string,
|
||||
applicationId: string | undefined,
|
||||
templateId: string | undefined,
|
||||
content: string,
|
||||
) {
|
||||
if (templateId) {
|
||||
const template = await this.prisma.smsTemplate.findUnique({
|
||||
where: { id: templateId },
|
||||
include: { signature: true },
|
||||
});
|
||||
if (!template || template.tenantId !== tenantId || template.applicationId !== applicationId
|
||||
|| template.auditStatus !== 'approved' || template.signature?.auditStatus !== 'approved') {
|
||||
throw new BadRequestException('短信模板不存在、未通过审核或不属于当前应用');
|
||||
}
|
||||
const variables = matchTemplateContent(template.content, content);
|
||||
if (variables === null) {
|
||||
throw new BadRequestException('短信内容与选定的审核模板不匹配');
|
||||
}
|
||||
const drainage = await this.facade.resolveDrainageInfoMatch(template.signatureId, content);
|
||||
return {
|
||||
signatureId: template.signatureId,
|
||||
drainageInfoId: drainage?.id,
|
||||
variables,
|
||||
rejectionReason: drainageRejectionReason(drainage),
|
||||
};
|
||||
}
|
||||
|
||||
if (!applicationId) {
|
||||
throw new BadRequestException('自由内容短信必须关联企业应用');
|
||||
}
|
||||
const [application, signature] = await Promise.all([
|
||||
this.prisma.smsApplication.findUnique({
|
||||
where: { id: applicationId },
|
||||
select: { tenantId: true, templateMismatchMode: true },
|
||||
}),
|
||||
this.facade.resolveInboundSignatureCandidate(applicationId, content),
|
||||
]);
|
||||
if (!application || application.tenantId !== tenantId) {
|
||||
throw new BadRequestException('短信应用不存在或不属于当前企业');
|
||||
}
|
||||
if (!signature) {
|
||||
throw new BadRequestException('短信内容未以当前应用已审核通过的签名开头');
|
||||
}
|
||||
if (application.templateMismatchMode !== 'direct_send') {
|
||||
throw new BadRequestException('当前应用未允许无模板自由内容直接发送');
|
||||
}
|
||||
const drainage = await this.facade.resolveDrainageInfoMatch(signature.id, content);
|
||||
return {
|
||||
signatureId: signature.id,
|
||||
drainageInfoId: drainage?.id,
|
||||
variables: undefined,
|
||||
rejectionReason: drainageRejectionReason(drainage),
|
||||
};
|
||||
}
|
||||
|
||||
async classifyRejectedPhones(tenantId: string, applicationId: string | undefined, phones: string[]) {
|
||||
const rejected = new Map<string, { code: string; reason: string }>();
|
||||
for (const phone of phones) {
|
||||
if (!/^1\d{10}$/.test(phone)) {
|
||||
rejected.set(phone, { code: 'INVALID_PHONE', reason: '手机号码必须是1开头的11位数字' });
|
||||
}
|
||||
}
|
||||
const validPhones = phones.filter((phone) => !rejected.has(phone));
|
||||
if (validPhones.length === 0) {
|
||||
return rejected;
|
||||
}
|
||||
const [globalHits, enterpriseHits] = await Promise.all([
|
||||
this.prisma.globalBlacklist.findMany({
|
||||
where: { phoneNumber: { in: validPhones }, status: 'active' },
|
||||
select: { phoneNumber: true, reason: true },
|
||||
}),
|
||||
applicationId
|
||||
? this.prisma.enterpriseBlacklist.findMany({
|
||||
where: { tenantId, applicationId, phoneNumber: { in: validPhones }, status: 'active' },
|
||||
select: { phoneNumber: true, reason: true },
|
||||
})
|
||||
: Promise.resolve([]),
|
||||
]);
|
||||
for (const hit of globalHits) {
|
||||
rejected.set(hit.phoneNumber, {
|
||||
code: 'GLOBAL_BLACKLIST',
|
||||
reason: hit.reason?.trim() || '号码命中平台黑名单',
|
||||
});
|
||||
}
|
||||
for (const hit of enterpriseHits) {
|
||||
rejected.set(hit.phoneNumber, {
|
||||
code: 'ENTERPRISE_BLACKLIST',
|
||||
reason: hit.reason?.trim() || '号码命中企业应用黑名单',
|
||||
});
|
||||
}
|
||||
return rejected;
|
||||
}
|
||||
|
||||
async validateSendResources(tenantId: string, applicationId?: string, templateId?: string) {
|
||||
const tenant = await this.prisma.tenant.findUnique({ where: { id: tenantId } });
|
||||
if (!tenant || tenant.status !== 'active') {
|
||||
throw new BadRequestException('企业客户不存在或已停用');
|
||||
}
|
||||
if (tenant.certificationStatus !== 'approved') {
|
||||
throw new BadRequestException('企业认证未通过,不能发送短信');
|
||||
}
|
||||
if (!applicationId) {
|
||||
return;
|
||||
}
|
||||
const application = await this.prisma.smsApplication.findUnique({ where: { id: applicationId } });
|
||||
if (!application || application.tenantId !== tenantId || application.status !== 'active') {
|
||||
throw new BadRequestException('短信应用不存在或已停用');
|
||||
}
|
||||
if (!application.interfaceEnabled) {
|
||||
throw new BadRequestException('短信应用接口未开通,不能发送短信');
|
||||
}
|
||||
if (!templateId) {
|
||||
return;
|
||||
}
|
||||
const template = await this.prisma.smsTemplate.findUnique({
|
||||
where: { id: templateId },
|
||||
include: { signature: true },
|
||||
});
|
||||
if (!template || template.tenantId !== tenantId || template.applicationId !== applicationId || template.auditStatus !== 'approved') {
|
||||
throw new BadRequestException('短信模板不存在、未通过审核或不属于当前应用');
|
||||
}
|
||||
if (!template.signature || template.signature.auditStatus !== 'approved') {
|
||||
throw new BadRequestException('短信签名未审核通过');
|
||||
}
|
||||
}
|
||||
|
||||
async reserveDailySendQuota(applicationId: string, requestedCount: number) {
|
||||
const result = await this.facade.tryReserveDailySendQuota(applicationId, requestedCount);
|
||||
if (!result.reserved) {
|
||||
throw new HttpException({
|
||||
code: 'DAILY_SEND_LIMIT_EXCEEDED',
|
||||
message: `应用当日发送上限${result.dailyLimit}条,本次${requestedCount}条超出剩余配额`,
|
||||
dailyLimit: result.dailyLimit,
|
||||
requestedCount,
|
||||
}, HttpStatus.TOO_MANY_REQUESTS);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async tryReserveDailySendQuota(applicationId: string, requestedCount: number) {
|
||||
if (!Number.isInteger(requestedCount) || requestedCount <= 0) {
|
||||
throw new BadRequestException('发送号码数量必须为正整数');
|
||||
}
|
||||
const usageDate = shanghaiDateKey();
|
||||
const reservationId = randomUUID();
|
||||
const rows = await this.prisma.$queryRaw<Array<{ dailyLimit: number; usedCount: number | null }>>(Prisma.sql`
|
||||
WITH application_limit AS (
|
||||
SELECT id, COALESCE("dailyLimit", 100000)::integer AS "dailyLimit"
|
||||
FROM "SmsApplication"
|
||||
WHERE id = ${applicationId}
|
||||
), reservation AS (
|
||||
INSERT INTO "SmsApplicationDailyUsage" (
|
||||
id, "applicationId", "usageDate", "usedCount", "createdAt", "updatedAt"
|
||||
)
|
||||
SELECT ${reservationId}, id, ${usageDate}::date, ${requestedCount}, NOW(), NOW()
|
||||
FROM application_limit
|
||||
WHERE ${requestedCount} <= "dailyLimit"
|
||||
ON CONFLICT ("applicationId", "usageDate") DO UPDATE
|
||||
SET "usedCount" = "SmsApplicationDailyUsage"."usedCount" + EXCLUDED."usedCount",
|
||||
"updatedAt" = NOW()
|
||||
WHERE "SmsApplicationDailyUsage"."usedCount" + EXCLUDED."usedCount"
|
||||
<= (SELECT "dailyLimit" FROM application_limit)
|
||||
RETURNING "usedCount"
|
||||
)
|
||||
SELECT application_limit."dailyLimit", reservation."usedCount"
|
||||
FROM application_limit
|
||||
LEFT JOIN reservation ON TRUE
|
||||
`);
|
||||
if (rows.length === 0) {
|
||||
throw new NotFoundException('短信应用不存在');
|
||||
}
|
||||
return {
|
||||
dailyLimit: Number(rows[0].dailyLimit),
|
||||
usedCount: rows[0].usedCount == null ? null : Number(rows[0].usedCount),
|
||||
reserved: rows[0].usedCount != null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
// R8 contract-only declarations. Runtime behavior remains in SendChainService.
|
||||
|
||||
export interface CreateBatchTaskDto {
|
||||
tenantId: string;
|
||||
applicationId?: string;
|
||||
templateId?: string;
|
||||
content: string;
|
||||
category?: string;
|
||||
phones: string[];
|
||||
sendMode?: 'immediate' | 'scheduled';
|
||||
scheduledAt?: string;
|
||||
variables?: Record<string, unknown>;
|
||||
createdById?: string;
|
||||
sourceIp?: string;
|
||||
userAgent?: string;
|
||||
sourceType?: 'client' | 'api' | 'cmpp';
|
||||
clientMessageId?: string;
|
||||
}
|
||||
|
||||
export type CreateHttpBatchTaskDto = Omit<CreateBatchTaskDto, 'templateId' | 'variables' | 'sourceType'>;
|
||||
|
||||
export interface GatewayInboundAuthDto {
|
||||
account: string;
|
||||
password?: string;
|
||||
authSource?: string;
|
||||
timestamp?: number;
|
||||
remoteIp?: string;
|
||||
}
|
||||
|
||||
export interface GatewayInboundSubmitDto {
|
||||
account: string;
|
||||
phoneNumber?: string;
|
||||
phoneNumbers?: string[];
|
||||
content: string;
|
||||
srcId?: string;
|
||||
destId?: string;
|
||||
sequenceId?: number;
|
||||
remoteIp?: string;
|
||||
longMessage?: {
|
||||
reference: number;
|
||||
total: number;
|
||||
index: number;
|
||||
format: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface GatewayInboundSingleSubmitResult {
|
||||
accepted: boolean;
|
||||
tenantId: string;
|
||||
applicationId: string;
|
||||
taskId: string;
|
||||
messageId: string;
|
||||
messageRecordId: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface GatewaySubmitResultDto {
|
||||
traceId?: string;
|
||||
messageId: string;
|
||||
channelId: string;
|
||||
submitId?: string;
|
||||
sequenceId?: number;
|
||||
gatewayMessageId: string;
|
||||
submitStatus: 'accepted' | 'rejected' | 'timeout';
|
||||
errorCode?: string;
|
||||
errorMessage?: string;
|
||||
submittedAt?: string;
|
||||
segments?: Array<{
|
||||
segmentTotal?: number;
|
||||
segmentIndex?: number;
|
||||
sequenceId?: number;
|
||||
gatewayMessageId?: string;
|
||||
submitStatus?: 'accepted' | 'rejected' | 'timeout' | string;
|
||||
errorCode?: string;
|
||||
errorMessage?: string;
|
||||
submittedAt?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface GatewaySubmitSegmentResultDto {
|
||||
traceId?: string;
|
||||
messageId: string;
|
||||
channelId: string;
|
||||
submitId?: string;
|
||||
segmentTotal: number;
|
||||
segmentIndex: number;
|
||||
sequenceId?: number;
|
||||
gatewayMessageId?: string;
|
||||
submitStatus: 'accepted' | 'rejected' | 'timeout' | string;
|
||||
errorCode?: string;
|
||||
errorMessage?: string;
|
||||
submittedAt?: string;
|
||||
}
|
||||
|
||||
export interface GatewayReceiptEventDto {
|
||||
traceId?: string;
|
||||
messageId?: string;
|
||||
channelId: string;
|
||||
sequenceId?: number;
|
||||
gatewayMessageId: string;
|
||||
phoneNumber?: string;
|
||||
receiptStatus: 'delivered' | 'undelivered' | 'unknown';
|
||||
rawStatus: string;
|
||||
errorCode?: string;
|
||||
errorMessage?: string;
|
||||
deliveredAt?: string;
|
||||
connectionId?: string;
|
||||
}
|
||||
|
||||
export interface GatewayUplinkEventDto {
|
||||
traceId?: string;
|
||||
messageId?: string;
|
||||
channelId: string;
|
||||
sequenceId?: number;
|
||||
phoneNumber: string;
|
||||
destId: string;
|
||||
content: string;
|
||||
receivedAt?: string;
|
||||
}
|
||||
|
||||
export type UplinkMatchCandidateInput = {
|
||||
tenantId: string;
|
||||
applicationId: string;
|
||||
messageRecordId?: string;
|
||||
matchSource: 'access_number' | 'phone_window';
|
||||
confidence: number;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
export interface GatewayPendingDeliveryQueryDto {
|
||||
account: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface GatewayDownstreamSentDto {
|
||||
id: string;
|
||||
connectionId?: string;
|
||||
sequenceId?: string;
|
||||
messageId?: string;
|
||||
sentAt?: string;
|
||||
ackDeadlineAt?: string;
|
||||
}
|
||||
|
||||
export interface GatewayDownstreamAcknowledgedDto extends GatewayDownstreamSentDto {
|
||||
result: number;
|
||||
acknowledgedAt?: string;
|
||||
}
|
||||
|
||||
export type GatewayDownstreamFailureType =
|
||||
| 'send_failed'
|
||||
| 'ack_timeout'
|
||||
| 'ack_rejected'
|
||||
| 'ack_invalid'
|
||||
| 'connection_lost'
|
||||
| 'unrecoverable'
|
||||
| 'queue_timeout';
|
||||
|
||||
export type GatewayControlDeliveryResult = {
|
||||
sent?: boolean;
|
||||
delivered?: boolean;
|
||||
retryable?: boolean;
|
||||
reasonCode?: string;
|
||||
errorMessage?: string;
|
||||
connectionId?: string;
|
||||
sequenceId?: string;
|
||||
messageId?: string;
|
||||
sentAt?: string;
|
||||
ackDeadlineAt?: string;
|
||||
};
|
||||
|
||||
export interface GatewaySubmitDeadLetterDto {
|
||||
streamMessageId: string;
|
||||
traceId?: string;
|
||||
messageId?: string;
|
||||
channelId?: string;
|
||||
tenantId?: string;
|
||||
applicationId?: string;
|
||||
submitId?: string;
|
||||
failureCode: string;
|
||||
failureMessage: string;
|
||||
attempts: number;
|
||||
maxAttempts: number;
|
||||
commandPayload?: Record<string, unknown>;
|
||||
rawPayload?: string;
|
||||
deadLetteredAt?: string;
|
||||
}
|
||||
|
||||
export interface RequeueGatewaySubmitExceptionDto {
|
||||
confirmedNotSubmitted?: boolean;
|
||||
reason?: string;
|
||||
operatorId?: string;
|
||||
}
|
||||
|
||||
export interface GatewayDownstreamRecoveryStatusDto {
|
||||
account: string;
|
||||
gatewayInstanceId?: string;
|
||||
state: string;
|
||||
lockOwner?: string;
|
||||
lockExpiresAt?: string;
|
||||
lastAttemptAt?: string;
|
||||
lastSuccessAt?: string;
|
||||
lastFailureAt?: string;
|
||||
nextRetryAt?: string;
|
||||
attemptCount?: number;
|
||||
failureCategory?: string;
|
||||
lastError?: string;
|
||||
lastSkipReason?: string;
|
||||
}
|
||||
|
||||
export interface TimeoutUnknownDto {
|
||||
olderThanHours?: number;
|
||||
}
|
||||
|
||||
export interface ImportPreviewDto {
|
||||
tenantId: string;
|
||||
applicationId?: string;
|
||||
content: string;
|
||||
fileName?: string;
|
||||
encoding?: 'utf8' | 'gbk';
|
||||
delimiter?: ',' | '\t';
|
||||
requiredVariables?: string[];
|
||||
}
|
||||
|
||||
export interface ConfirmImportDto extends CreateBatchTaskDto {
|
||||
importContent: string;
|
||||
requiredVariables?: string[];
|
||||
}
|
||||
|
||||
export interface SendJob {
|
||||
messageRecordId: string;
|
||||
}
|
||||
|
||||
export type QueuePriority = 'normal' | 'priority';
|
||||
|
||||
export type RoutedChannel = {
|
||||
channel: {
|
||||
id: string;
|
||||
code: string;
|
||||
account: string;
|
||||
srcId: string;
|
||||
rateLimitPerSecond: number;
|
||||
unitPrice: number;
|
||||
status: string;
|
||||
carrier?: string | null;
|
||||
sendRegion: string;
|
||||
gatewayHost: string;
|
||||
gatewayPort: number;
|
||||
passwordCipher: string;
|
||||
cmppVersion: string;
|
||||
config?: unknown;
|
||||
};
|
||||
carrier: string;
|
||||
province?: string | null;
|
||||
groupId: string;
|
||||
groupName: string;
|
||||
routeScope: 'province' | 'national';
|
||||
};
|
||||
@@ -0,0 +1,111 @@
|
||||
import {
|
||||
aggregateReceiptSegmentState,
|
||||
isSameUpstreamEndpointIdentity,
|
||||
receiptEventKey,
|
||||
selectChannelCandidate,
|
||||
} from './send-chain.helpers';
|
||||
|
||||
const connected = [{ status: 'connected', currentConnections: 1, desiredConnections: 1 }];
|
||||
|
||||
describe('send-chain pure policies', () => {
|
||||
it('prefers an approved online province channel while preserving priority order', () => {
|
||||
const items = [
|
||||
{ channelId: 'national', carrier: 'mobile', province: null, channel: { carrier: 'mobile', sendRegion: '全国', status: 'active', connectionStates: connected } },
|
||||
{ channelId: 'province', carrier: 'mobile', province: '安徽省', channel: { carrier: 'mobile', sendRegion: '安徽', status: 'active', connectionStates: connected } },
|
||||
];
|
||||
|
||||
expect(selectChannelCandidate(items, {
|
||||
carrier: 'mobile',
|
||||
province: '安徽省',
|
||||
excludedChannelIds: new Set(),
|
||||
approvedChannelIds: new Set(['national', 'province']),
|
||||
})?.channelId).toBe('province');
|
||||
});
|
||||
|
||||
it('falls back to an approved online national channel', () => {
|
||||
const items = [
|
||||
{ channelId: 'offline', carrier: 'mobile', province: '安徽', channel: { carrier: 'mobile', sendRegion: '安徽', status: 'active', connectionStates: [] } },
|
||||
{ channelId: 'national', carrier: 'mobile', province: null, channel: { carrier: 'all', sendRegion: '全国', status: 'active', connectionStates: connected } },
|
||||
];
|
||||
|
||||
expect(selectChannelCandidate(items, {
|
||||
carrier: 'mobile',
|
||||
province: '安徽',
|
||||
excludedChannelIds: new Set(),
|
||||
approvedChannelIds: new Set(['offline', 'national']),
|
||||
})?.channelId).toBe('national');
|
||||
});
|
||||
|
||||
it('does not select excluded or unreported channels', () => {
|
||||
const items = [
|
||||
{ channelId: 'excluded', carrier: 'mobile', province: null, channel: { carrier: 'mobile', sendRegion: '全国', status: 'active', connectionStates: connected } },
|
||||
{ channelId: 'unreported', carrier: 'mobile', province: null, channel: { carrier: 'mobile', sendRegion: '全国', status: 'active', connectionStates: connected } },
|
||||
];
|
||||
|
||||
expect(selectChannelCandidate(items, {
|
||||
carrier: 'mobile',
|
||||
excludedChannelIds: new Set(['excluded']),
|
||||
approvedChannelIds: new Set(['excluded']),
|
||||
})).toBeUndefined();
|
||||
});
|
||||
|
||||
it('keeps a segmented message non-terminal until all receipts arrive', () => {
|
||||
const result = aggregateReceiptSegmentState(
|
||||
[{ segmentTotal: 2, receiptStatus: 'delivered', deliveredAt: new Date('2026-07-31T00:00:00Z') }],
|
||||
2,
|
||||
{ channelId: 'channel-1', gatewayMessageId: 'gw-1', receiptStatus: 'delivered', rawStatus: 'DELIVRD' },
|
||||
new Date('2026-07-31T00:01:00Z'),
|
||||
);
|
||||
expect(result).toMatchObject({ terminal: false, segmentTotal: 2, status: 'submitted' });
|
||||
});
|
||||
|
||||
it('marks all delivered segments successful at the latest receipt time', () => {
|
||||
const latest = new Date('2026-07-31T00:02:00Z');
|
||||
const result = aggregateReceiptSegmentState(
|
||||
[
|
||||
{ segmentTotal: 2, receiptStatus: 'delivered', deliveredAt: new Date('2026-07-31T00:01:00Z') },
|
||||
{ segmentTotal: 2, receiptStatus: 'delivered', deliveredAt: latest },
|
||||
],
|
||||
2,
|
||||
{ channelId: 'channel-1', gatewayMessageId: 'gw-2', receiptStatus: 'delivered', rawStatus: 'DELIVRD' },
|
||||
latest,
|
||||
);
|
||||
expect(result).toMatchObject({ terminal: true, segmentTotal: 2, status: 'delivered', deliveredAt: latest });
|
||||
});
|
||||
|
||||
it('lets a failed segment decide the terminal message result', () => {
|
||||
const result = aggregateReceiptSegmentState(
|
||||
[
|
||||
{ segmentTotal: 2, receiptStatus: 'delivered' },
|
||||
{ segmentTotal: 2, receiptStatus: 'undelivered', rawStatus: 'REJECTD', errorCode: 'ERR' },
|
||||
],
|
||||
2,
|
||||
{ channelId: 'channel-1', gatewayMessageId: 'gw-3', receiptStatus: 'undelivered', rawStatus: 'REJECTD' },
|
||||
new Date('2026-07-31T00:03:00Z'),
|
||||
);
|
||||
expect(result).toMatchObject({ terminal: true, status: 'failed', receiptStatus: 'undelivered', errorCode: 'ERR' });
|
||||
});
|
||||
|
||||
it('normalizes upstream endpoint identity without weakening port or version equality', () => {
|
||||
expect(isSameUpstreamEndpointIdentity(
|
||||
{ account: ' acct ', gatewayHost: 'SMSC.EXAMPLE', gatewayPort: 7890, protocol: 'cmpp', cmppVersion: '2.0' },
|
||||
{ account: 'acct', gatewayHost: 'smsc.example', gatewayPort: 7890, protocol: 'CMPP', cmppVersion: '2.0' },
|
||||
)).toBe(true);
|
||||
expect(isSameUpstreamEndpointIdentity(
|
||||
{ account: 'acct', gatewayHost: 'smsc.example', gatewayPort: 7890, protocol: 'CMPP', cmppVersion: '2.0' },
|
||||
{ account: 'acct', gatewayHost: 'smsc.example', gatewayPort: 7891, protocol: 'CMPP', cmppVersion: '2.0' },
|
||||
)).toBe(false);
|
||||
});
|
||||
|
||||
it('generates a stable receipt event key and changes it with logical channel identity', () => {
|
||||
const event = {
|
||||
channelId: 'physical',
|
||||
gatewayMessageId: 'gw-4',
|
||||
phoneNumber: '13800000000',
|
||||
receiptStatus: 'delivered' as const,
|
||||
rawStatus: 'DELIVRD',
|
||||
};
|
||||
expect(receiptEventKey(event, 'logical')).toBe(receiptEventKey({ ...event }, 'logical'));
|
||||
expect(receiptEventKey(event, 'logical')).not.toBe(receiptEventKey(event, 'other'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,602 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { createHash } from 'node:crypto';
|
||||
import type { CreateBatchTaskDto, GatewayControlDeliveryResult, GatewayDownstreamRecoveryStatusDto, GatewayDownstreamSentDto, GatewayInboundAuthDto, GatewayReceiptEventDto, GatewaySubmitResultDto, QueuePriority } from './send-chain.contracts';
|
||||
|
||||
// R8 pure policies and deterministic key/status helpers. No database, queue or network access.
|
||||
|
||||
export const SEND_QUEUE = 'sms.send.queue';
|
||||
|
||||
export const GATEWAY_SUBMIT_QUEUE = 'gateway.submit.queue';
|
||||
|
||||
export const GATEWAY_SUBMIT_STREAM = 'gateway.submit.commands';
|
||||
|
||||
export const DEFAULT_DOWNSTREAM_RETRY_DELAY_MS = 60_000;
|
||||
|
||||
export const DEFAULT_DOWNSTREAM_RETRY_MAX_DELAY_MS = 30 * 60_000;
|
||||
|
||||
export const DEFAULT_DOWNSTREAM_MAX_RETRIES = 10;
|
||||
|
||||
export const DEFAULT_DOWNSTREAM_PENDING_TIMEOUT_HOURS = 72;
|
||||
|
||||
export const DEFAULT_RECEIPT_TIMEOUT_HOURS = 72;
|
||||
|
||||
export const DEFAULT_RECEIPT_TIMEOUT_SCAN_INTERVAL_MS = 5 * 60_000;
|
||||
|
||||
export const RECEIPT_TIMEOUT_INITIAL_DELAY_MS = 60_000;
|
||||
|
||||
export const DEFAULT_SCHEDULED_DISPATCH_SCAN_INTERVAL_MS = 5_000;
|
||||
|
||||
export const DEFAULT_SCHEDULED_DISPATCH_STALE_MS = 2 * 60_000;
|
||||
|
||||
export const SCHEDULED_DISPATCH_INITIAL_DELAY_MS = 1_000;
|
||||
|
||||
export const DEFAULT_GATEWAY_SUBMIT_REQUEUE_STALE_MS = 2 * 60_000;
|
||||
|
||||
export const DEFAULT_DOWNSTREAM_MANUAL_REQUEUE_STALE_MS = 2 * 60_000;
|
||||
|
||||
export const DEFAULT_INBOUND_LONG_MESSAGE_SCAN_INTERVAL_MS = 60_000;
|
||||
|
||||
export const INBOUND_LONG_MESSAGE_SCAN_INITIAL_DELAY_MS = 10_000;
|
||||
|
||||
export const DEFAULT_INBOUND_LONG_MESSAGE_PROCESSING_STALE_SECONDS = 30;
|
||||
|
||||
export const DEFAULT_UPSTREAM_RECEIPT_INBOX_SCAN_INTERVAL_MS = 5_000;
|
||||
|
||||
export const UPSTREAM_RECEIPT_INBOX_INITIAL_DELAY_MS = 1_000;
|
||||
|
||||
export const DEFAULT_UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS = 2 * 60_000;
|
||||
|
||||
export const DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_ATTEMPTS = 30;
|
||||
|
||||
export const DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_AGE_HOURS = 72;
|
||||
|
||||
export const GATEWAY_SUBMIT_REQUEUE_IDEMPOTENCY_TTL_SECONDS = 30 * 24 * 60 * 60;
|
||||
|
||||
export const BULLMQ_PRIORITY: Record<QueuePriority, number> = {
|
||||
priority: 1,
|
||||
normal: 100,
|
||||
};
|
||||
|
||||
export function gatewaySubmitRequeueKey(deadLetterId: string, attempt: number) {
|
||||
return `gateway:submit:requeue:${deadLetterId}:${attempt}`;
|
||||
}
|
||||
|
||||
export function drainageRejectionReason(drainage?: { id: string; auditStatus: string }) {
|
||||
if (!drainage || drainage.auditStatus === 'approved') return undefined;
|
||||
return `短信内容匹配的引流资料 ${drainage.id} 当前为 ${drainage.auditStatus},必须审核通过后才能发送`;
|
||||
}
|
||||
|
||||
export function statusFromRisk(status: string, scheduled: boolean) {
|
||||
if (status === 'rejected') {
|
||||
return 'rejected';
|
||||
}
|
||||
if (status === 'pending_review') {
|
||||
return 'pending_review';
|
||||
}
|
||||
if (scheduled) {
|
||||
return 'scheduled';
|
||||
}
|
||||
return 'ready';
|
||||
}
|
||||
|
||||
export function parseSchedule(data: CreateBatchTaskDto) {
|
||||
if (data.sendMode !== 'scheduled' && !data.scheduledAt) {
|
||||
return { scheduledAt: null };
|
||||
}
|
||||
if (!data.scheduledAt) {
|
||||
throw new BadRequestException('定时发送必须提供 scheduledAt');
|
||||
}
|
||||
const scheduledAt = new Date(data.scheduledAt);
|
||||
if (Number.isNaN(scheduledAt.getTime())) {
|
||||
throw new BadRequestException('scheduledAt 时间格式无效');
|
||||
}
|
||||
if (scheduledAt.getTime() <= Date.now()) {
|
||||
throw new BadRequestException('scheduledAt 必须晚于当前时间');
|
||||
}
|
||||
return { scheduledAt };
|
||||
}
|
||||
|
||||
export function isObjectRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function asDateOrNull(value?: string | null) {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
const parsed = new Date(value);
|
||||
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
||||
}
|
||||
|
||||
export function downstreamRetryDelayMs(retryCount = 1) {
|
||||
const base = downstreamRetryBaseDelayMs();
|
||||
const max = downstreamRetryMaxDelayMs();
|
||||
const attempt = Math.max(1, Math.floor(retryCount));
|
||||
const delay = base * Math.pow(2, Math.max(0, attempt - 1));
|
||||
return Math.min(delay, max);
|
||||
}
|
||||
|
||||
export function downstreamAckTimeoutMs() {
|
||||
const configured = Number(process.env.CMPP_DOWNSTREAM_ACK_TIMEOUT_SECONDS ?? 30);
|
||||
return Math.max(5, Number.isFinite(configured) ? configured : 30) * 1000;
|
||||
}
|
||||
|
||||
export function downstreamRetryBaseDelayMs() {
|
||||
const value = Number(process.env.CMPP_DOWNSTREAM_RETRY_DELAY_MS ?? DEFAULT_DOWNSTREAM_RETRY_DELAY_MS);
|
||||
return Number.isFinite(value) && value > 0 ? value : DEFAULT_DOWNSTREAM_RETRY_DELAY_MS;
|
||||
}
|
||||
|
||||
export function downstreamRetryMaxDelayMs() {
|
||||
const value = Number(process.env.CMPP_DOWNSTREAM_RETRY_MAX_DELAY_MS ?? DEFAULT_DOWNSTREAM_RETRY_MAX_DELAY_MS);
|
||||
return Number.isFinite(value) && value > 0 ? value : DEFAULT_DOWNSTREAM_RETRY_MAX_DELAY_MS;
|
||||
}
|
||||
|
||||
export function downstreamMaxRetries() {
|
||||
const value = Number(process.env.CMPP_DOWNSTREAM_MAX_RETRIES ?? DEFAULT_DOWNSTREAM_MAX_RETRIES);
|
||||
return Number.isFinite(value) && value > 0 ? Math.floor(value) : DEFAULT_DOWNSTREAM_MAX_RETRIES;
|
||||
}
|
||||
|
||||
export function downstreamPendingTimeoutHours() {
|
||||
const value = Number(process.env.CMPP_DOWNSTREAM_PENDING_TIMEOUT_HOURS ?? DEFAULT_DOWNSTREAM_PENDING_TIMEOUT_HOURS);
|
||||
return Number.isFinite(value) && value > 0 ? value : DEFAULT_DOWNSTREAM_PENDING_TIMEOUT_HOURS;
|
||||
}
|
||||
|
||||
export function downstreamControlFailureMessage(result: GatewayControlDeliveryResult) {
|
||||
const reason = String(result.errorMessage ?? '').trim();
|
||||
const code = String(result.reasonCode ?? '').trim();
|
||||
if (reason && code) return `${reason} (${code})`;
|
||||
if (reason) return reason;
|
||||
if (code) return `Gateway 未完成下游投递 (${code})`;
|
||||
return 'Gateway 未完成下游投递,等待自动重试';
|
||||
}
|
||||
|
||||
export function parseImportRows(content: string, delimiter?: ',' | '\t') {
|
||||
const normalized = content.replace(/^\uFEFF/, '');
|
||||
const lines = normalized.split(/\r?\n/).filter((line) => line.trim().length > 0);
|
||||
if (lines.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const firstDelimiter = delimiter ?? (lines[0].includes(',') ? ',' : '\t');
|
||||
const firstCells = splitImportLine(lines[0], firstDelimiter);
|
||||
const hasHeader = firstCells.some((cell) => ['phone', 'phoneNumber', 'mobile', '手机号'].includes(cell));
|
||||
const headers = hasHeader ? firstCells : ['phoneNumber'];
|
||||
const dataLines = hasHeader ? lines.slice(1) : lines;
|
||||
return dataLines.map((line, index) => {
|
||||
const cells = splitImportLine(line, firstDelimiter);
|
||||
const row: { rowNumber: number; phoneNumber?: string; variables: Record<string, string> } = {
|
||||
rowNumber: (hasHeader ? index + 2 : index + 1),
|
||||
phoneNumber: hasHeader ? cellByHeader(headers, cells, ['phone', 'phoneNumber', 'mobile', '手机号']) : cells[0],
|
||||
variables: {},
|
||||
};
|
||||
headers.forEach((header, cellIndex) => {
|
||||
if (!['phone', 'phoneNumber', 'mobile', '手机号'].includes(header)) {
|
||||
row.variables[header] = cells[cellIndex] ?? '';
|
||||
}
|
||||
});
|
||||
return row;
|
||||
});
|
||||
}
|
||||
|
||||
export function splitImportLine(line: string, delimiter: ',' | '\t') {
|
||||
return line.split(delimiter).map((cell) => cell.trim().replace(/^"|"$/g, ''));
|
||||
}
|
||||
|
||||
export function cellByHeader(headers: string[], cells: string[], candidates: string[]) {
|
||||
const index = headers.findIndex((header) => candidates.includes(header));
|
||||
return index >= 0 ? cells[index] : undefined;
|
||||
}
|
||||
|
||||
export function normalizeCarrier(carrier?: string | null) {
|
||||
const value = String(carrier ?? '').trim().toLowerCase();
|
||||
if (['mobile', 'cmcc', '移动', '中国移动'].includes(value)) return 'mobile';
|
||||
if (['unicom', 'cucc', '联通', '中国联通'].includes(value)) return 'unicom';
|
||||
if (['telecom', 'ctcc', '电信', '中国电信'].includes(value)) return 'telecom';
|
||||
if (['all', 'tri', '三网', '全网'].includes(value)) return 'all';
|
||||
return value || 'mobile';
|
||||
}
|
||||
|
||||
export function normalizeQueuePriority(queuePriority?: string | null): QueuePriority {
|
||||
return queuePriority === 'priority' ? 'priority' : 'normal';
|
||||
}
|
||||
|
||||
export function getPositiveConfigInteger(config: unknown, key: string, fallback: number) {
|
||||
if (config && typeof config === 'object' && !Array.isArray(config) && key in config) {
|
||||
const value = Number((config as Record<string, unknown>)[key]);
|
||||
if (Number.isInteger(value) && value > 0) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function getNonNegativeConfigInteger(config: unknown, key: string, fallback: number) {
|
||||
if (config && typeof config === 'object' && !Array.isArray(config) && key in config) {
|
||||
const value = Number((config as Record<string, unknown>)[key]);
|
||||
if (Number.isInteger(value) && value >= 0) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function isCarrierCompatible(channelCarrier: string | null | undefined, targetCarrier: string) {
|
||||
const normalized = normalizeCarrier(channelCarrier);
|
||||
return normalized === 'all' || normalized === targetCarrier;
|
||||
}
|
||||
|
||||
export function normalizeRegion(region?: string | null) {
|
||||
return String(region ?? '').replace(/省|市|自治区|壮族|回族|维吾尔/g, '').trim();
|
||||
}
|
||||
|
||||
export function matchTemplateContent(templateContent: string, actualContent: string) {
|
||||
if (templateContent === actualContent) {
|
||||
return {} as Record<string, string>;
|
||||
}
|
||||
const tokenPattern = /\$\{([a-zA-Z0-9_]+)\}/g;
|
||||
const names: string[] = [];
|
||||
let cursor = 0;
|
||||
let pattern = '^';
|
||||
for (const match of templateContent.matchAll(tokenPattern)) {
|
||||
const index = match.index ?? 0;
|
||||
pattern += escapeRegularExpression(templateContent.slice(cursor, index));
|
||||
pattern += '([\\s\\S]+?)';
|
||||
names.push(match[1]);
|
||||
cursor = index + match[0].length;
|
||||
}
|
||||
if (names.length === 0) {
|
||||
return null;
|
||||
}
|
||||
pattern += `${escapeRegularExpression(templateContent.slice(cursor))}$`;
|
||||
const matched = new RegExp(pattern, 'u').exec(actualContent);
|
||||
if (!matched) {
|
||||
return null;
|
||||
}
|
||||
const variables: Record<string, string> = {};
|
||||
for (let index = 0; index < names.length; index += 1) {
|
||||
const name = names[index];
|
||||
const value = matched[index + 1];
|
||||
if (variables[name] !== undefined && variables[name] !== value) {
|
||||
return null;
|
||||
}
|
||||
variables[name] = value;
|
||||
}
|
||||
return variables;
|
||||
}
|
||||
|
||||
export function escapeRegularExpression(value: string) {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
export function isNationalChannel(item: { province?: string | null; channel: { sendRegion?: string | null } }) {
|
||||
const itemProvince = normalizeRegion(item.province);
|
||||
const sendRegion = normalizeRegion(item.channel.sendRegion);
|
||||
return !itemProvince || itemProvince === '全国' || !sendRegion || sendRegion === '全国';
|
||||
}
|
||||
|
||||
export function isProvinceChannel(item: { province?: string | null; channel: { sendRegion?: string | null } }, province?: string | null) {
|
||||
if (!province) {
|
||||
return false;
|
||||
}
|
||||
const target = normalizeRegion(province);
|
||||
const itemProvince = normalizeRegion(item.province);
|
||||
const sendRegion = normalizeRegion(item.channel.sendRegion);
|
||||
return itemProvince === target || sendRegion === target;
|
||||
}
|
||||
|
||||
export function validateInboundApplicationSrcId(
|
||||
srcId: string | undefined,
|
||||
application: {
|
||||
cmppApplicationExtension?: string | null;
|
||||
cmppAccessNumberFillEnabled?: boolean | null;
|
||||
cmppAccessNumberFillPrefix?: string | null;
|
||||
cmppClientSrcId?: string | null;
|
||||
},
|
||||
) {
|
||||
const submittedSrcId = srcId?.trim() ?? '';
|
||||
const applicationExtension = application.cmppApplicationExtension?.trim() ?? '';
|
||||
if (!applicationExtension) {
|
||||
return submittedSrcId || null;
|
||||
}
|
||||
|
||||
const fillPrefix = application.cmppAccessNumberFillEnabled
|
||||
? application.cmppAccessNumberFillPrefix?.trim() ?? ''
|
||||
: '';
|
||||
const expectedSrcId = application.cmppClientSrcId?.trim() || `${fillPrefix}${applicationExtension}`;
|
||||
if (!submittedSrcId || submittedSrcId !== expectedSrcId) {
|
||||
throw new BadRequestException(`CMPP Src_Id must equal the access number assigned to this application: ${expectedSrcId}`);
|
||||
}
|
||||
return submittedSrcId;
|
||||
}
|
||||
|
||||
export function composeUpstreamSrcId(baseSrcId: string, applicationExtension?: string | null) {
|
||||
const upstreamSrcId = `${baseSrcId.trim()}${applicationExtension?.trim() ?? ''}`;
|
||||
if (upstreamSrcId.length > 21) {
|
||||
throw new BadRequestException('channel base access number plus application extension must not exceed 21 digits');
|
||||
}
|
||||
return upstreamSrcId;
|
||||
}
|
||||
|
||||
export function positiveInteger(value: string | undefined, fallback: number) {
|
||||
const parsed = Number(value);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
|
||||
}
|
||||
|
||||
export function parseOptionalSequenceId(value: string | null | undefined) {
|
||||
if (!value) return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isInteger(parsed) && parsed >= 0 && parsed <= 0xffffffff ? parsed : undefined;
|
||||
}
|
||||
|
||||
export function normalizeSubmitStatus(value: string): GatewaySubmitResultDto['submitStatus'] {
|
||||
return value === 'accepted' || value === 'rejected' || value === 'timeout' ? value : 'timeout';
|
||||
}
|
||||
|
||||
export function normalizeReceiptStatus(value: string): GatewayReceiptEventDto['receiptStatus'] {
|
||||
return value === 'delivered' || value === 'undelivered' || value === 'unknown' ? value : 'unknown';
|
||||
}
|
||||
|
||||
export function downstreamDeliveryAttemptKey(data: GatewayDownstreamSentDto) {
|
||||
return createHash('sha256').update([
|
||||
data.id,
|
||||
data.connectionId ?? '',
|
||||
data.sequenceId ?? '',
|
||||
data.messageId ?? '',
|
||||
data.sequenceId ? '' : data.sentAt ?? '',
|
||||
].join('\u0000')).digest('hex');
|
||||
}
|
||||
|
||||
export function shanghaiDateKey(now = new Date()) {
|
||||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
}).formatToParts(now);
|
||||
const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
|
||||
return `${values.year}-${values.month}-${values.day}`;
|
||||
}
|
||||
|
||||
export function bullmqConnection() {
|
||||
const redisUrl = new URL(process.env.REDIS_URL ?? 'redis://127.0.0.1:6379');
|
||||
return {
|
||||
host: redisUrl.hostname,
|
||||
port: Number(redisUrl.port || 6379),
|
||||
username: redisUrl.username || undefined,
|
||||
password: redisUrl.password || undefined,
|
||||
maxRetriesPerRequest: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function matchesApplicationSecret(data: GatewayInboundAuthDto, secretHash: string) {
|
||||
if (data.authSource && data.timestamp !== undefined) {
|
||||
const expected = createHash('md5')
|
||||
.update(Buffer.concat([
|
||||
Buffer.from(octetString(data.account, 6), 'binary'),
|
||||
Buffer.alloc(9),
|
||||
Buffer.from(secretHash),
|
||||
Buffer.from(String(data.timestamp).padStart(10, '0')),
|
||||
]))
|
||||
.digest('base64');
|
||||
return expected === data.authSource;
|
||||
}
|
||||
if (!data.password) {
|
||||
return false;
|
||||
}
|
||||
return data.password === secretHash || createHash('sha256').update(data.password).digest('hex') === secretHash;
|
||||
}
|
||||
|
||||
export function octetString(value: string, fixedLength: number) {
|
||||
if (value.length === fixedLength) {
|
||||
return value;
|
||||
}
|
||||
if (value.length > fixedLength) {
|
||||
return value.slice(value.length - fixedLength);
|
||||
}
|
||||
return value + '\0'.repeat(fixedLength - value.length);
|
||||
}
|
||||
|
||||
export function hasRecoveryAuditStateChanged(
|
||||
previous: Record<string, unknown> | null,
|
||||
current: Record<string, unknown>,
|
||||
) {
|
||||
if (!previous) {
|
||||
return true;
|
||||
}
|
||||
return ['state', 'gatewayInstanceId', 'lockOwner', 'failureCategory', 'lastError', 'lastSkipReason']
|
||||
.some((key) => (previous[key] ?? null) !== (current[key] ?? null));
|
||||
}
|
||||
|
||||
export function normalizeRecoveryFailureCategory(data: GatewayDownstreamRecoveryStatusDto) {
|
||||
const explicit = String(data.failureCategory ?? '').trim();
|
||||
if (explicit) {
|
||||
return explicit;
|
||||
}
|
||||
if (data.state === 'success' || data.state === 'running') {
|
||||
return null;
|
||||
}
|
||||
if (data.lastSkipReason === 'backoff') {
|
||||
return 'backoff';
|
||||
}
|
||||
if (data.lastSkipReason === 'locked') {
|
||||
return 'lock_contended';
|
||||
}
|
||||
if (data.lastSkipReason === 'lock_lost') {
|
||||
return 'lock_lost';
|
||||
}
|
||||
if (data.state === 'waiting_connection') {
|
||||
return 'client_disconnected';
|
||||
}
|
||||
if (data.state === 'partial') {
|
||||
return 'partial_delivery_failed';
|
||||
}
|
||||
if (data.state === 'failed' && data.lastError) {
|
||||
return 'flush_failed';
|
||||
}
|
||||
return data.state ? 'unknown' : null;
|
||||
}
|
||||
|
||||
export type ChannelCandidate = {
|
||||
channelId: string;
|
||||
carrier?: string | null;
|
||||
province?: string | null;
|
||||
channel: {
|
||||
carrier?: string | null;
|
||||
sendRegion?: string | null;
|
||||
status: string;
|
||||
connectionStates?: Array<{ status: string; currentConnections: number; desiredConnections: number }>;
|
||||
};
|
||||
};
|
||||
|
||||
export function isChannelSendAvailable(channel: ChannelCandidate['channel']) {
|
||||
if (channel.status !== 'active') {
|
||||
return false;
|
||||
}
|
||||
return (channel.connectionStates ?? []).some((connection) =>
|
||||
connection.desiredConnections > 0 && connection.currentConnections > 0 && connection.status === 'connected',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Preserve database priority order while preferring matching province routes
|
||||
* over national fallbacks. Filtering remains deterministic and side-effect free.
|
||||
*/
|
||||
export function selectChannelCandidate<T extends ChannelCandidate>(
|
||||
items: T[],
|
||||
options: {
|
||||
carrier: string;
|
||||
province?: string | null;
|
||||
forceNational?: boolean;
|
||||
excludedChannelIds: ReadonlySet<string>;
|
||||
approvedChannelIds: ReadonlySet<string>;
|
||||
},
|
||||
) {
|
||||
const eligible = items.filter((item) =>
|
||||
!options.excludedChannelIds.has(item.channelId)
|
||||
&& options.approvedChannelIds.has(item.channelId)
|
||||
&& normalizeCarrier(item.carrier) === options.carrier
|
||||
&& isCarrierCompatible(item.channel.carrier, options.carrier),
|
||||
);
|
||||
const provinceCandidates = options.forceNational
|
||||
? []
|
||||
: eligible.filter((item) => isProvinceChannel(item, options.province));
|
||||
const nationalCandidates = eligible.filter((item) => isNationalChannel(item));
|
||||
return [...provinceCandidates, ...nationalCandidates].find((item) => isChannelSendAvailable(item.channel));
|
||||
}
|
||||
|
||||
export type ReceiptSegmentAudit = {
|
||||
segmentTotal?: number | null;
|
||||
receiptStatus?: string | null;
|
||||
rawStatus?: string | null;
|
||||
errorCode?: string | null;
|
||||
errorMessage?: string | null;
|
||||
deliveredAt?: Date | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Calculate one message's terminal state without reading or writing storage.
|
||||
* A failed segment wins; success requires every expected segment to be delivered.
|
||||
*/
|
||||
export function aggregateReceiptSegmentState(
|
||||
audits: ReceiptSegmentAudit[],
|
||||
billingUnits: number | null | undefined,
|
||||
data: GatewayReceiptEventDto,
|
||||
deliveredAt: Date,
|
||||
) {
|
||||
if (audits.length === 0) {
|
||||
const status = data.receiptStatus === 'delivered'
|
||||
? 'delivered'
|
||||
: data.receiptStatus === 'unknown'
|
||||
? 'unknown'
|
||||
: 'failed';
|
||||
return {
|
||||
terminal: true,
|
||||
segmentTotal: 1,
|
||||
status,
|
||||
receiptStatus: data.receiptStatus,
|
||||
rawStatus: data.rawStatus,
|
||||
errorCode: data.errorCode,
|
||||
errorMessage: data.errorMessage,
|
||||
deliveredAt,
|
||||
};
|
||||
}
|
||||
|
||||
const segmentTotal = Math.max(
|
||||
1,
|
||||
Number(billingUnits ?? 1),
|
||||
...audits.map((audit) => Number(audit.segmentTotal ?? 1)),
|
||||
);
|
||||
const received = audits.filter((audit) => Boolean(audit.receiptStatus));
|
||||
const failed = received.find((audit) => !['delivered', 'unknown'].includes(audit.receiptStatus ?? ''));
|
||||
if (failed) {
|
||||
return {
|
||||
terminal: true,
|
||||
segmentTotal,
|
||||
status: 'failed',
|
||||
receiptStatus: failed.receiptStatus ?? 'undelivered',
|
||||
rawStatus: failed.rawStatus ?? data.rawStatus,
|
||||
errorCode: failed.errorCode ?? data.errorCode,
|
||||
errorMessage: failed.errorMessage ?? data.errorMessage,
|
||||
deliveredAt: failed.deliveredAt ?? deliveredAt,
|
||||
};
|
||||
}
|
||||
const delivered = received.filter((audit) => audit.receiptStatus === 'delivered');
|
||||
if (delivered.length >= segmentTotal) {
|
||||
const latest = delivered.reduce((current, audit) =>
|
||||
(audit.deliveredAt?.getTime() ?? 0) > (current.deliveredAt?.getTime() ?? 0) ? audit : current);
|
||||
return {
|
||||
terminal: true,
|
||||
segmentTotal,
|
||||
status: 'delivered',
|
||||
receiptStatus: 'delivered',
|
||||
rawStatus: latest.rawStatus ?? data.rawStatus,
|
||||
errorCode: latest.errorCode ?? undefined,
|
||||
errorMessage: undefined,
|
||||
deliveredAt: latest.deliveredAt ?? deliveredAt,
|
||||
};
|
||||
}
|
||||
if (received.length >= segmentTotal) {
|
||||
const latest = received[received.length - 1];
|
||||
return {
|
||||
terminal: true,
|
||||
segmentTotal,
|
||||
status: 'unknown',
|
||||
receiptStatus: 'unknown',
|
||||
rawStatus: latest.rawStatus ?? data.rawStatus,
|
||||
errorCode: latest.errorCode ?? data.errorCode,
|
||||
errorMessage: latest.errorMessage ?? data.errorMessage,
|
||||
deliveredAt: latest.deliveredAt ?? deliveredAt,
|
||||
};
|
||||
}
|
||||
return {
|
||||
terminal: false,
|
||||
segmentTotal,
|
||||
status: 'submitted',
|
||||
receiptStatus: data.receiptStatus,
|
||||
rawStatus: data.rawStatus,
|
||||
errorCode: data.errorCode,
|
||||
errorMessage: data.errorMessage,
|
||||
deliveredAt,
|
||||
};
|
||||
}
|
||||
|
||||
export function isSameUpstreamEndpointIdentity(
|
||||
left: { account: string; gatewayHost: string; gatewayPort: number; protocol: string; cmppVersion: string },
|
||||
right: { account: string; gatewayHost: string; gatewayPort: number; protocol: string; cmppVersion: string },
|
||||
) {
|
||||
return left.account.trim() === right.account.trim()
|
||||
&& left.gatewayHost.trim().toLowerCase() === right.gatewayHost.trim().toLowerCase()
|
||||
&& left.gatewayPort === right.gatewayPort
|
||||
&& left.protocol.trim().toUpperCase() === right.protocol.trim().toUpperCase()
|
||||
&& left.cmppVersion.trim() === right.cmppVersion.trim();
|
||||
}
|
||||
|
||||
export function receiptEventKey(data: GatewayReceiptEventDto, channelId = data.channelId) {
|
||||
return createHash('sha256').update([
|
||||
channelId,
|
||||
data.gatewayMessageId,
|
||||
data.phoneNumber?.trim() ?? '',
|
||||
data.receiptStatus,
|
||||
data.rawStatus.trim(),
|
||||
data.errorCode ?? '',
|
||||
].join('\u0000')).digest('hex');
|
||||
}
|
||||
@@ -111,6 +111,7 @@ function createPrismaMock() {
|
||||
},
|
||||
smsSendTask: {
|
||||
findUnique: jest.fn().mockResolvedValue(null),
|
||||
update: jest.fn().mockResolvedValue({ id: 'review-task-1', status: 'rejected' }),
|
||||
},
|
||||
smsBatchTask: {
|
||||
create: jest.fn().mockResolvedValue(task),
|
||||
@@ -374,10 +375,19 @@ function createService(
|
||||
reviewReason: '企业应用已配置模板不匹配进入人工审核',
|
||||
}),
|
||||
} as unknown as RiskReviewService;
|
||||
const service = new SendChainService(prisma as never, billing, riskReview, openApi as never);
|
||||
const phoneFrequency = {
|
||||
reserve: jest.fn().mockResolvedValue(new Map()),
|
||||
};
|
||||
const service = new SendChainService(
|
||||
prisma as never,
|
||||
billing,
|
||||
riskReview,
|
||||
phoneFrequency as never,
|
||||
openApi as never,
|
||||
);
|
||||
service['postGatewayControl'] = jest.fn().mockResolvedValue({ delivered: true });
|
||||
service['publishGatewaySubmitCommand'] = jest.fn().mockResolvedValue(undefined);
|
||||
return { service, prisma, billing, riskReview };
|
||||
return { service, prisma, billing, riskReview, phoneFrequency };
|
||||
}
|
||||
|
||||
describe('SendChainService', () => {
|
||||
@@ -451,6 +461,94 @@ describe('SendChainService', () => {
|
||||
expect(service.enqueueBatchTask).toHaveBeenCalledWith('task-1');
|
||||
});
|
||||
|
||||
it('rejects only phones that hit application frequency rules and excludes them from billing', async () => {
|
||||
const { service, prisma, billing, phoneFrequency } = createService();
|
||||
service.enqueueBatchTask = jest.fn().mockResolvedValue({ taskId: 'task-1', enqueued: 1 });
|
||||
phoneFrequency.reserve.mockResolvedValue(new Map([
|
||||
['13800000002', {
|
||||
code: 'PHONE_FREQUENCY_LIMIT',
|
||||
reason: '单号码5分钟发送频次命中:本周期最多5条,当前第6条',
|
||||
}],
|
||||
]));
|
||||
(billing.estimateSmsCost as jest.Mock).mockReturnValue({
|
||||
billingUnitsPerMessage: 1,
|
||||
totalBillingUnits: 1,
|
||||
unitPrice: 3,
|
||||
amountCents: 3,
|
||||
});
|
||||
|
||||
await service.createBatchTask({
|
||||
tenantId: 'tenant-1',
|
||||
applicationId: 'app-1',
|
||||
templateId: 'tpl-1',
|
||||
content: 'hello',
|
||||
phones: ['13800000001', '13800000002'],
|
||||
});
|
||||
|
||||
expect(phoneFrequency.reserve).toHaveBeenCalledWith(
|
||||
'tenant-1',
|
||||
'app-1',
|
||||
['13800000001', '13800000002'],
|
||||
'client',
|
||||
);
|
||||
expect(billing.estimateSmsCost).toHaveBeenCalledWith(expect.objectContaining({ phoneCount: 1 }));
|
||||
expect(prisma.smsMessageRecord.createMany).toHaveBeenCalledWith({
|
||||
data: expect.arrayContaining([
|
||||
expect.objectContaining({ phoneNumber: '13800000001', status: 'queued', amountCents: 3 }),
|
||||
expect.objectContaining({
|
||||
phoneNumber: '13800000002',
|
||||
status: 'submit_failed',
|
||||
submitStatus: 'rejected',
|
||||
errorCode: 'PHONE_FREQUENCY_LIMIT',
|
||||
amountCents: 0,
|
||||
}),
|
||||
]),
|
||||
});
|
||||
expect(billing.freeze).toHaveBeenCalledWith(expect.objectContaining({ amountCents: 3 }));
|
||||
expect(service.enqueueBatchTask).toHaveBeenCalledWith('task-1');
|
||||
});
|
||||
|
||||
it('marks a batch and its pending review task rejected when every phone hits frequency rules', async () => {
|
||||
const { service, prisma, riskReview, phoneFrequency } = createService();
|
||||
(riskReview.evaluateTask as jest.Mock).mockResolvedValue({
|
||||
status: 'pending_review',
|
||||
reason: '命中人工审核规则',
|
||||
task: { id: 'review-task-1' },
|
||||
});
|
||||
phoneFrequency.reserve.mockResolvedValue(new Map([
|
||||
['13800000001', {
|
||||
code: 'PHONE_FREQUENCY_LIMIT',
|
||||
reason: '单号码5分钟发送频次命中:本周期最多5条,当前第6条',
|
||||
}],
|
||||
]));
|
||||
|
||||
await service.createBatchTask({
|
||||
tenantId: 'tenant-1',
|
||||
applicationId: 'app-1',
|
||||
templateId: 'tpl-1',
|
||||
content: 'hello',
|
||||
phones: ['13800000001'],
|
||||
});
|
||||
|
||||
expect(prisma.smsSendTask.update).toHaveBeenCalledWith({
|
||||
where: { id: 'review-task-1' },
|
||||
data: expect.objectContaining({
|
||||
status: 'rejected',
|
||||
riskDecision: 'block',
|
||||
reviewReason: null,
|
||||
rejectReason: expect.stringContaining('单号码5分钟发送频次命中'),
|
||||
}),
|
||||
});
|
||||
expect(prisma.smsBatchTask.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
status: 'rejected',
|
||||
auditStatus: 'rejected',
|
||||
reviewReason: null,
|
||||
rejectReason: expect.stringContaining('单号码5分钟发送频次命中'),
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it('persists the review task id on every message waiting for manual review', async () => {
|
||||
const { service, prisma, riskReview } = createService();
|
||||
(riskReview.evaluateTask as jest.Mock).mockResolvedValue({
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,323 @@
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import type { OpenApiService } from '../open-api/open-api.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { GatewaySubmitResultDto, GatewaySubmitSegmentResultDto, GatewayReceiptEventDto, GatewayUplinkEventDto, UplinkMatchCandidateInput, GatewayPendingDeliveryQueryDto, GatewayDownstreamSentDto, GatewayDownstreamAcknowledgedDto, GatewayDownstreamFailureType, GatewaySubmitDeadLetterDto, RequeueGatewaySubmitExceptionDto, GatewayDownstreamRecoveryStatusDto, TimeoutUnknownDto } from './send-chain.contracts';
|
||||
import { downstreamPendingTimeoutHours } from './send-chain.helpers';
|
||||
import type { SendSubmissionService } from './send-submission.service';
|
||||
import { SendAccountingService } from './send-accounting.service';
|
||||
import { SendDownstreamDeliveryService } from './send-downstream-delivery.service';
|
||||
import { SendDownstreamStateService } from './send-downstream-state.service';
|
||||
import { SendGatewayResultService } from './send-gateway-result.service';
|
||||
import { SendReceiptService } from './send-receipt.service';
|
||||
import { SendRetryService } from './send-retry.service';
|
||||
import { SendTimeoutService } from './send-timeout.service';
|
||||
|
||||
|
||||
export type SendCompletionCallbacks = Record<string, never>;
|
||||
export type SendCompletionFacade = SendCompletionService & SendSubmissionService;
|
||||
|
||||
/**
|
||||
* R10 internal compatibility facade. SendChainService remains the only public NestJS provider.
|
||||
*/
|
||||
export class SendCompletionService {
|
||||
private readonly gatewayResult: SendGatewayResultService;
|
||||
private readonly receipt: SendReceiptService;
|
||||
private readonly retry: SendRetryService;
|
||||
private readonly accounting: SendAccountingService;
|
||||
private readonly downstreamState: SendDownstreamStateService;
|
||||
private readonly downstreamDelivery: SendDownstreamDeliveryService;
|
||||
private readonly timeout: SendTimeoutService;
|
||||
|
||||
constructor(
|
||||
prisma: PrismaService,
|
||||
billing: BillingService,
|
||||
openApi: OpenApiService | undefined,
|
||||
facade: SendCompletionFacade,
|
||||
callbacks: SendCompletionCallbacks = {},
|
||||
) {
|
||||
this.gatewayResult = new SendGatewayResultService(prisma, billing, openApi, facade, callbacks);
|
||||
this.receipt = new SendReceiptService(prisma, billing, openApi, facade, callbacks);
|
||||
this.retry = new SendRetryService(prisma, billing, openApi, facade, callbacks);
|
||||
this.accounting = new SendAccountingService(prisma, billing, openApi, facade, callbacks);
|
||||
this.downstreamState = new SendDownstreamStateService(prisma, billing, openApi, facade, callbacks);
|
||||
this.downstreamDelivery = new SendDownstreamDeliveryService(prisma, billing, openApi, facade, callbacks);
|
||||
this.timeout = new SendTimeoutService(prisma, billing, openApi, facade, callbacks);
|
||||
}
|
||||
|
||||
async handleSubmitSegmentResult(data: GatewaySubmitSegmentResultDto) {
|
||||
return this.gatewayResult.handleSubmitSegmentResult(data);
|
||||
}
|
||||
|
||||
async resolveSubmitRecordForGatewaySegmentResult(
|
||||
messageRecordId: string,
|
||||
data: GatewaySubmitSegmentResultDto,
|
||||
) {
|
||||
return this.gatewayResult.resolveSubmitRecordForGatewaySegmentResult(messageRecordId, data);
|
||||
}
|
||||
|
||||
async handleSubmitResult(data: GatewaySubmitResultDto) {
|
||||
return this.gatewayResult.handleSubmitResult(data);
|
||||
}
|
||||
|
||||
async resolveSubmitRecordForGatewayResult(messageRecordId: string, data: GatewaySubmitResultDto) {
|
||||
return this.gatewayResult.resolveSubmitRecordForGatewayResult(messageRecordId, data);
|
||||
}
|
||||
|
||||
smsMessageSegmentAuditDelegate() {
|
||||
return this.gatewayResult.smsMessageSegmentAuditDelegate();
|
||||
}
|
||||
|
||||
async recordSubmitSegments(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
channelId?: string | null;
|
||||
submitId?: string | null;
|
||||
billingUnits?: number | null;
|
||||
},
|
||||
data: GatewaySubmitResultDto,
|
||||
submittedAt: Date,
|
||||
) {
|
||||
return this.gatewayResult.recordSubmitSegments(message, data, submittedAt);
|
||||
}
|
||||
|
||||
async findMessageByGatewayEvent(messageId?: string, gatewayMessageId?: string) {
|
||||
return this.gatewayResult.findMessageByGatewayEvent(messageId, gatewayMessageId);
|
||||
}
|
||||
|
||||
async requireMessageByGatewayEvent(messageId?: string, gatewayMessageId?: string) {
|
||||
return this.gatewayResult.requireMessageByGatewayEvent(messageId, gatewayMessageId);
|
||||
}
|
||||
|
||||
async intakeReceipt(data: GatewayReceiptEventDto) {
|
||||
return this.receipt.intakeReceipt(data);
|
||||
}
|
||||
|
||||
async processPendingUpstreamReceiptInbox(limit = 100) {
|
||||
return this.receipt.processPendingUpstreamReceiptInbox(limit);
|
||||
}
|
||||
|
||||
async processUpstreamReceiptInboxRecord(id: string) {
|
||||
return this.receipt.processUpstreamReceiptInboxRecord(id);
|
||||
}
|
||||
|
||||
async runUpstreamReceiptInboxScan() {
|
||||
return this.receipt.runUpstreamReceiptInboxScan();
|
||||
}
|
||||
|
||||
async handleReceipt(
|
||||
data: GatewayReceiptEventDto,
|
||||
incomingIdentity?: { account: string; gatewayHost: string; gatewayPort: number; protocol: string; cmppVersion: string },
|
||||
) {
|
||||
return this.receipt.handleReceipt(data, incomingIdentity);
|
||||
}
|
||||
|
||||
async recordReceiptSegment(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
channelId?: string | null;
|
||||
submitId?: string | null;
|
||||
billingUnits?: number | null;
|
||||
},
|
||||
data: GatewayReceiptEventDto,
|
||||
deliveredAt: Date,
|
||||
submitRecordId?: string,
|
||||
) {
|
||||
return this.receipt.recordReceiptSegment(message, data, deliveredAt, submitRecordId);
|
||||
}
|
||||
|
||||
async aggregateReceiptSegments(
|
||||
message: {
|
||||
id: string;
|
||||
billingUnits?: number | null;
|
||||
},
|
||||
data: GatewayReceiptEventDto,
|
||||
deliveredAt: Date,
|
||||
submitRecordId?: string,
|
||||
submitId?: string,
|
||||
) {
|
||||
return this.receipt.aggregateReceiptSegments(message, data, deliveredAt, submitRecordId, submitId);
|
||||
}
|
||||
|
||||
async resolveReceiptMessage(
|
||||
data: GatewayReceiptEventDto,
|
||||
incomingIdentity?: { account: string; gatewayHost: string; gatewayPort: number; protocol: string; cmppVersion: string },
|
||||
) {
|
||||
return this.receipt.resolveReceiptMessage(data, incomingIdentity);
|
||||
}
|
||||
|
||||
async recordGatewaySubmitDeadLetter(data: GatewaySubmitDeadLetterDto) {
|
||||
return this.retry.recordGatewaySubmitDeadLetter(data);
|
||||
}
|
||||
|
||||
async requeueGatewaySubmitDeadLetter(id: string, data: RequeueGatewaySubmitExceptionDto = {}) {
|
||||
return this.retry.requeueGatewaySubmitDeadLetter(id, data);
|
||||
}
|
||||
|
||||
async recoverStaleGatewaySubmitRequeues(now = new Date()) {
|
||||
return this.retry.recoverStaleGatewaySubmitRequeues(now);
|
||||
}
|
||||
|
||||
async retryMessageIfAllowed(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
batchTaskId: string;
|
||||
applicationId?: string | null;
|
||||
templateId?: string | null;
|
||||
signatureId?: string | null;
|
||||
submitId?: string | null;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
content: string;
|
||||
billingUnits: number;
|
||||
queuedAt?: Date;
|
||||
clientSrcId?: string | null;
|
||||
applicationExtension?: string | null;
|
||||
carrier?: string | null;
|
||||
province?: string | null;
|
||||
},
|
||||
reason: string,
|
||||
sourceSubmitRecordId?: string,
|
||||
) {
|
||||
return this.retry.retryMessageIfAllowed(message, reason, sourceSubmitRecordId);
|
||||
}
|
||||
|
||||
async chargeAcceptedMessage(message: {
|
||||
tenantId: string;
|
||||
applicationId?: string | null;
|
||||
batchTaskId: string;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
content: string;
|
||||
billingUnits: number;
|
||||
unitPrice: number | bigint;
|
||||
amountCents: number | bigint;
|
||||
}) {
|
||||
return this.accounting.chargeAcceptedMessage(message);
|
||||
}
|
||||
|
||||
async releaseMessageReservation(
|
||||
message: { tenantId: string; batchTaskId: string; messageId: string; amountCents: number | bigint; billingUnits: number },
|
||||
remark: string,
|
||||
) {
|
||||
return this.accounting.releaseMessageReservation(message, remark);
|
||||
}
|
||||
|
||||
async refundMessage(
|
||||
message: { tenantId: string; messageId: string; amountCents: number | bigint; billingUnits: number },
|
||||
remark: string,
|
||||
) {
|
||||
return this.accounting.refundMessage(message, remark);
|
||||
}
|
||||
|
||||
async listPendingDownstreamDeliveries(data: GatewayPendingDeliveryQueryDto) {
|
||||
return this.downstreamState.listPendingDownstreamDeliveries(data);
|
||||
}
|
||||
|
||||
async markDownstreamDeliveryDelivered(id: string) {
|
||||
return this.downstreamState.markDownstreamDeliveryDelivered(id);
|
||||
}
|
||||
|
||||
async markDownstreamDeliverySent(data: GatewayDownstreamSentDto) {
|
||||
return this.downstreamState.markDownstreamDeliverySent(data);
|
||||
}
|
||||
|
||||
async acknowledgeDownstreamDelivery(data: GatewayDownstreamAcknowledgedDto) {
|
||||
return this.downstreamState.acknowledgeDownstreamDelivery(data);
|
||||
}
|
||||
|
||||
async markDownstreamDeliveryFailed(
|
||||
id: string,
|
||||
errorMessage?: string,
|
||||
failureType: GatewayDownstreamFailureType = 'send_failed',
|
||||
attempt?: GatewayDownstreamSentDto,
|
||||
) {
|
||||
return this.downstreamState.markDownstreamDeliveryFailed(id, errorMessage, failureType, attempt);
|
||||
}
|
||||
|
||||
async recordGatewayDownstreamRecoveryStatus(data: GatewayDownstreamRecoveryStatusDto) {
|
||||
return this.downstreamState.recordGatewayDownstreamRecoveryStatus(data);
|
||||
}
|
||||
|
||||
async requeueDownstreamDelivery(id: string) {
|
||||
return this.downstreamState.requeueDownstreamDelivery(id);
|
||||
}
|
||||
|
||||
async recoverStaleDownstreamManualRequeues(now = new Date()) {
|
||||
return this.downstreamState.recoverStaleDownstreamManualRequeues(now);
|
||||
}
|
||||
|
||||
async batchRequeueDownstreamDeliveries(ids: string[]) {
|
||||
return this.downstreamState.batchRequeueDownstreamDeliveries(ids);
|
||||
}
|
||||
|
||||
async handleUplink(data: GatewayUplinkEventDto) {
|
||||
return this.downstreamDelivery.handleUplink(data);
|
||||
}
|
||||
|
||||
async claimUplinkMatchCandidate(uplinkMessageId: string, candidateId: string, operatorId?: string) {
|
||||
return this.downstreamDelivery.claimUplinkMatchCandidate(uplinkMessageId, candidateId, operatorId);
|
||||
}
|
||||
|
||||
async queueAndTryDownstreamDelivery(data: {
|
||||
tenantId: string;
|
||||
applicationId?: string | null;
|
||||
messageRecordId?: string | null;
|
||||
messageId?: string | null;
|
||||
deliveryType: 'receipt' | 'uplink';
|
||||
payload: Record<string, unknown>;
|
||||
}) {
|
||||
return this.downstreamDelivery.queueAndTryDownstreamDelivery(data);
|
||||
}
|
||||
|
||||
async resolveUplinkMatch(
|
||||
data: GatewayUplinkEventDto,
|
||||
channel: { id: string; srcId?: string | null },
|
||||
): Promise<{
|
||||
tenantId?: string;
|
||||
applicationId?: string;
|
||||
messageRecordId?: string;
|
||||
matchStatus: string;
|
||||
matchReason: string;
|
||||
candidates: UplinkMatchCandidateInput[];
|
||||
}> {
|
||||
return this.downstreamDelivery.resolveUplinkMatch(data, channel);
|
||||
}
|
||||
|
||||
async recordCmppFailureReceipt(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
applicationId?: string | null;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
cmppSubmitSequenceId?: string | null;
|
||||
cmppSubmitGroupMessageId?: string | null;
|
||||
},
|
||||
errorCode: string,
|
||||
reason: string,
|
||||
) {
|
||||
return this.downstreamDelivery.recordCmppFailureReceipt(message, errorCode, reason);
|
||||
}
|
||||
|
||||
async postGatewayControl(path: string, payload: unknown) {
|
||||
return this.downstreamDelivery.postGatewayControl(path, payload);
|
||||
}
|
||||
|
||||
async markUnknownTimeout(data: TimeoutUnknownDto) {
|
||||
return this.timeout.markUnknownTimeout(data);
|
||||
}
|
||||
|
||||
async markExpiredDownstreamDeliveries(olderThanHours = downstreamPendingTimeoutHours()) {
|
||||
return this.timeout.markExpiredDownstreamDeliveries(olderThanHours);
|
||||
}
|
||||
|
||||
async runReceiptTimeoutScan() {
|
||||
return this.timeout.runReceiptTimeoutScan();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
import { BadRequestException, HttpException, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import type { OpenApiService } from '../open-api/open-api.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { GatewaySubmitResultDto, GatewaySubmitSegmentResultDto, GatewayReceiptEventDto, GatewayUplinkEventDto, UplinkMatchCandidateInput, GatewayPendingDeliveryQueryDto, GatewayDownstreamSentDto, GatewayDownstreamAcknowledgedDto, GatewayDownstreamFailureType, GatewayControlDeliveryResult, GatewaySubmitDeadLetterDto, RequeueGatewaySubmitExceptionDto, GatewayDownstreamRecoveryStatusDto, TimeoutUnknownDto } from './send-chain.contracts';
|
||||
import { positiveInteger, normalizeReceiptStatus, normalizeCarrier, DEFAULT_DOWNSTREAM_RETRY_DELAY_MS, DEFAULT_DOWNSTREAM_RETRY_MAX_DELAY_MS, DEFAULT_DOWNSTREAM_MAX_RETRIES, DEFAULT_DOWNSTREAM_PENDING_TIMEOUT_HOURS, DEFAULT_RECEIPT_TIMEOUT_HOURS, DEFAULT_GATEWAY_SUBMIT_REQUEUE_STALE_MS, DEFAULT_DOWNSTREAM_MANUAL_REQUEUE_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_ATTEMPTS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_AGE_HOURS, gatewaySubmitRequeueKey, isObjectRecord, asDateOrNull, downstreamRetryDelayMs, downstreamAckTimeoutMs, downstreamRetryBaseDelayMs, downstreamRetryMaxDelayMs, downstreamMaxRetries, downstreamPendingTimeoutHours, downstreamControlFailureMessage, normalizeSubmitStatus, downstreamDeliveryAttemptKey, hasRecoveryAuditStateChanged, normalizeRecoveryFailureCategory, aggregateReceiptSegmentState, isSameUpstreamEndpointIdentity, receiptEventKey } from './send-chain.helpers';
|
||||
import type { SendSubmissionService } from './send-submission.service';
|
||||
import type { SendCompletionCallbacks, SendCompletionFacade } from './send-completion.service';
|
||||
|
||||
|
||||
/**
|
||||
* R10 downstreamDelivery implementation.
|
||||
* Cross-domain calls return through the stable SendChainService seam to preserve locking and test observability.
|
||||
*/
|
||||
export class SendDownstreamDeliveryService {
|
||||
private readonly logger = new Logger('SendChainService');
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly openApi: OpenApiService | undefined,
|
||||
private readonly facade: SendCompletionFacade,
|
||||
private readonly callbacks: SendCompletionCallbacks,
|
||||
) {}
|
||||
|
||||
async handleUplink(data: GatewayUplinkEventDto) {
|
||||
const channel = await this.prisma.smsChannel.findUnique({ where: { id: data.channelId } });
|
||||
if (!channel) {
|
||||
throw new NotFoundException('SMS channel not found');
|
||||
}
|
||||
const match = await this.facade.resolveUplinkMatch(data, channel);
|
||||
const record = await this.prisma.smsUplinkMessage.create({
|
||||
data: {
|
||||
tenantId: match.tenantId,
|
||||
applicationId: match.applicationId,
|
||||
messageRecordId: match.messageRecordId,
|
||||
channelId: data.channelId,
|
||||
messageId: data.messageId,
|
||||
sequenceId: data.sequenceId,
|
||||
phoneNumber: data.phoneNumber,
|
||||
destId: data.destId,
|
||||
content: data.content,
|
||||
matchStatus: match.matchStatus,
|
||||
matchReason: match.matchReason,
|
||||
receivedAt: data.receivedAt ? new Date(data.receivedAt) : new Date(),
|
||||
},
|
||||
});
|
||||
if (match.candidates.length > 0) {
|
||||
await this.prisma.smsUplinkMatchCandidate.createMany({
|
||||
data: match.candidates.map((candidate) => ({
|
||||
uplinkMessageId: record.id,
|
||||
tenantId: candidate.tenantId,
|
||||
applicationId: candidate.applicationId,
|
||||
messageRecordId: candidate.messageRecordId,
|
||||
matchSource: candidate.matchSource,
|
||||
confidence: candidate.confidence,
|
||||
reason: candidate.reason,
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
}
|
||||
if (match.tenantId && match.applicationId) {
|
||||
await this.facade.queueAndTryDownstreamDelivery({
|
||||
tenantId: match.tenantId,
|
||||
applicationId: match.applicationId,
|
||||
messageRecordId: match.messageRecordId,
|
||||
messageId: data.messageId,
|
||||
deliveryType: 'uplink',
|
||||
payload: {
|
||||
messageId: data.messageId,
|
||||
applicationId: match.applicationId,
|
||||
phoneNumber: data.phoneNumber,
|
||||
destId: data.destId,
|
||||
content: data.content,
|
||||
receivedAt: record.receivedAt.toISOString(),
|
||||
uplinkMessageId: record.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
return record;
|
||||
}
|
||||
|
||||
async claimUplinkMatchCandidate(uplinkMessageId: string, candidateId: string, operatorId?: string) {
|
||||
const candidate = await this.prisma.smsUplinkMatchCandidate.findFirst({
|
||||
where: { id: candidateId, uplinkMessageId },
|
||||
include: {
|
||||
application: { select: { id: true, name: true, cmppAccount: true } },
|
||||
messageRecord: { select: { id: true, messageId: true, content: true } },
|
||||
uplinkMessage: true,
|
||||
},
|
||||
});
|
||||
if (!candidate) {
|
||||
throw new NotFoundException('Uplink match candidate not found');
|
||||
}
|
||||
if (candidate.status === 'rejected') {
|
||||
throw new BadRequestException('该候选已被排除,不能认领');
|
||||
}
|
||||
if (candidate.uplinkMessage.matchStatus === 'matched' && candidate.status !== 'claimed') {
|
||||
throw new BadRequestException('该上行记录已完成匹配,不能重复认领');
|
||||
}
|
||||
const claimedAt = new Date();
|
||||
const messageId = candidate.uplinkMessage.messageId ?? candidate.messageRecord?.messageId ?? null;
|
||||
const [updatedUplink] = await this.prisma.$transaction([
|
||||
this.prisma.smsUplinkMessage.update({
|
||||
where: { id: uplinkMessageId },
|
||||
data: {
|
||||
tenantId: candidate.tenantId,
|
||||
applicationId: candidate.applicationId,
|
||||
messageRecordId: candidate.messageRecordId,
|
||||
messageId,
|
||||
matchStatus: 'matched',
|
||||
matchReason: `人工认领:${candidate.reason ?? candidate.matchSource}`,
|
||||
},
|
||||
}),
|
||||
this.prisma.smsUplinkMatchCandidate.updateMany({
|
||||
where: {
|
||||
uplinkMessageId,
|
||||
id: { not: candidate.id },
|
||||
status: 'pending',
|
||||
},
|
||||
data: { status: 'rejected' },
|
||||
}),
|
||||
this.prisma.smsUplinkMatchCandidate.update({
|
||||
where: { id: candidate.id },
|
||||
data: {
|
||||
status: 'claimed',
|
||||
claimedAt,
|
||||
claimedById: operatorId,
|
||||
},
|
||||
}),
|
||||
this.prisma.operationLog.create({
|
||||
data: {
|
||||
tenantId: candidate.tenantId,
|
||||
userId: operatorId,
|
||||
action: 'gateway.uplink_manual_claim',
|
||||
resource: 'sms_uplink_message',
|
||||
resourceId: uplinkMessageId,
|
||||
detail: {
|
||||
candidateId: candidate.id,
|
||||
applicationId: candidate.applicationId,
|
||||
applicationName: candidate.application.name,
|
||||
messageRecordId: candidate.messageRecordId,
|
||||
messageId,
|
||||
matchSource: candidate.matchSource,
|
||||
phoneNumber: candidate.uplinkMessage.phoneNumber,
|
||||
destId: candidate.uplinkMessage.destId,
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
await this.facade.queueAndTryDownstreamDelivery({
|
||||
tenantId: candidate.tenantId,
|
||||
applicationId: candidate.applicationId,
|
||||
messageRecordId: candidate.messageRecordId,
|
||||
messageId,
|
||||
deliveryType: 'uplink',
|
||||
payload: {
|
||||
messageId,
|
||||
applicationId: candidate.applicationId,
|
||||
phoneNumber: candidate.uplinkMessage.phoneNumber,
|
||||
destId: candidate.uplinkMessage.destId,
|
||||
content: candidate.uplinkMessage.content,
|
||||
receivedAt: candidate.uplinkMessage.receivedAt.toISOString(),
|
||||
manualClaim: true,
|
||||
uplinkMessageId,
|
||||
},
|
||||
});
|
||||
return this.prisma.smsUplinkMessage.findUnique({
|
||||
where: { id: updatedUplink.id },
|
||||
include: {
|
||||
tenant: true,
|
||||
application: true,
|
||||
channel: true,
|
||||
messageRecord: { include: { application: true } },
|
||||
matchCandidates: {
|
||||
include: {
|
||||
tenant: true,
|
||||
application: true,
|
||||
messageRecord: { include: { application: true, tenant: true, channel: true } },
|
||||
},
|
||||
orderBy: [{ status: 'asc' }, { confidence: 'desc' }, { createdAt: 'asc' }],
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async queueAndTryDownstreamDelivery(data: {
|
||||
tenantId: string;
|
||||
applicationId?: string | null;
|
||||
messageRecordId?: string | null;
|
||||
messageId?: string | null;
|
||||
deliveryType: 'receipt' | 'uplink';
|
||||
payload: Record<string, unknown>;
|
||||
}) {
|
||||
if (!data.applicationId) {
|
||||
return null;
|
||||
}
|
||||
const application = await this.prisma.smsApplication.findUnique({
|
||||
where: { id: data.applicationId },
|
||||
select: {
|
||||
cmppAccount: true,
|
||||
interfaceEnabled: true,
|
||||
status: true,
|
||||
downstreamReceiptRetryEnabled: true,
|
||||
downstreamUplinkRetryEnabled: true,
|
||||
httpConfig: true,
|
||||
},
|
||||
});
|
||||
const deliveryAllowed = application?.status === 'active' || application?.status === 'disabling';
|
||||
if (deliveryAllowed) {
|
||||
try {
|
||||
await this.openApi?.queueWebhookEvent({
|
||||
tenantId: data.tenantId,
|
||||
applicationId: data.applicationId,
|
||||
messageRecordId: data.messageRecordId,
|
||||
messageId: data.messageId,
|
||||
uplinkMessageId: typeof data.payload.uplinkMessageId === 'string' ? data.payload.uplinkMessageId : undefined,
|
||||
eventType: data.deliveryType,
|
||||
payload: data.payload,
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error(`HTTP webhook queue failed for ${data.deliveryType}/${data.messageId ?? '-'}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
if (application?.interfaceEnabled !== true) {
|
||||
return null;
|
||||
}
|
||||
const payload = { account: application?.cmppAccount, applicationId: data.applicationId, ...data.payload };
|
||||
const dedupeKey = data.deliveryType === 'receipt' && data.messageRecordId
|
||||
? `receipt:${data.messageRecordId}`
|
||||
: data.deliveryType === 'uplink' && typeof data.payload.uplinkMessageId === 'string'
|
||||
? `uplink:${data.payload.uplinkMessageId}`
|
||||
: null;
|
||||
let delivery;
|
||||
try {
|
||||
delivery = await this.prisma.cmppDownstreamDelivery.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
applicationId: data.applicationId,
|
||||
messageRecordId: data.messageRecordId,
|
||||
messageId: data.messageId,
|
||||
dedupeKey,
|
||||
deliveryType: data.deliveryType,
|
||||
payload,
|
||||
retryEnabled: deliveryAllowed && (data.deliveryType === 'uplink'
|
||||
? application?.downstreamUplinkRetryEnabled ?? true
|
||||
: application?.downstreamReceiptRetryEnabled ?? true),
|
||||
status: deliveryAllowed ? 'pending' : 'abandoned',
|
||||
lastError: deliveryAllowed ? null : '企业应用已停用,保留回执但不再向客户应用推送',
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (
|
||||
dedupeKey
|
||||
&& error instanceof Prisma.PrismaClientKnownRequestError
|
||||
&& error.code === 'P2002'
|
||||
) {
|
||||
const existing = await this.prisma.cmppDownstreamDelivery.findUnique({
|
||||
where: { dedupeKey },
|
||||
});
|
||||
if (existing) {
|
||||
this.logger.warn(`downstream_delivery_deduplicated ${JSON.stringify({
|
||||
deliveryType: data.deliveryType,
|
||||
messageRecordId: data.messageRecordId,
|
||||
messageId: data.messageId,
|
||||
dedupeKey,
|
||||
deliveryId: existing.id,
|
||||
})}`);
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (!deliveryAllowed) {
|
||||
return delivery;
|
||||
}
|
||||
try {
|
||||
const result = await this.facade.postGatewayControl(
|
||||
data.deliveryType === 'receipt' ? '/downstream/receipt' : '/downstream/uplink',
|
||||
{ deliveryId: delivery.id, ...payload },
|
||||
) as GatewayControlDeliveryResult;
|
||||
if (result.sent || result.delivered) {
|
||||
await this.facade.markDownstreamDeliverySent({ id: delivery.id, ...result });
|
||||
} else if (result.reasonCode === 'SUBMIT_RESPONSE_PENDING') {
|
||||
return delivery;
|
||||
} else {
|
||||
await this.facade.markDownstreamDeliveryFailed(
|
||||
delivery.id,
|
||||
downstreamControlFailureMessage(result),
|
||||
result.retryable === false ? 'unrecoverable' : 'send_failed',
|
||||
{ id: delivery.id, ...result },
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
await this.facade.markDownstreamDeliveryFailed(delivery.id, error instanceof Error ? error.message : 'Gateway control delivery failed');
|
||||
}
|
||||
return delivery;
|
||||
}
|
||||
|
||||
async resolveUplinkMatch(
|
||||
data: GatewayUplinkEventDto,
|
||||
channel: { id: string; srcId?: string | null },
|
||||
): Promise<{
|
||||
tenantId?: string;
|
||||
applicationId?: string;
|
||||
messageRecordId?: string;
|
||||
matchStatus: string;
|
||||
matchReason: string;
|
||||
candidates: UplinkMatchCandidateInput[];
|
||||
}> {
|
||||
if (data.messageId) {
|
||||
const message = await this.prisma.smsMessageRecord.findUnique({ where: { messageId: data.messageId } });
|
||||
if (message?.tenantId) {
|
||||
return {
|
||||
tenantId: message.tenantId,
|
||||
applicationId: message.applicationId ?? undefined,
|
||||
messageRecordId: message.id,
|
||||
matchStatus: message.applicationId ? 'matched' : 'unmatched',
|
||||
matchReason: message.applicationId ? 'messageId 精确匹配' : 'messageId 匹配到下发记录但无应用',
|
||||
candidates: [],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const accessNumber = data.destId || channel.srcId || '';
|
||||
const accessRoutes = accessNumber
|
||||
? await this.prisma.channelRouteRule.findMany({
|
||||
where: {
|
||||
applicationId: { not: null },
|
||||
status: 'active',
|
||||
group: { items: { some: { channelId: channel.id, channel: { srcId: accessNumber } } } },
|
||||
},
|
||||
select: { applicationId: true },
|
||||
take: 10,
|
||||
})
|
||||
: [];
|
||||
const accessApplicationIds = [...new Set(accessRoutes.map((route) => route.applicationId).filter((value): value is string => Boolean(value)))];
|
||||
const accessApplications = accessApplicationIds.length > 0
|
||||
? await this.prisma.smsApplication.findMany({
|
||||
where: { id: { in: accessApplicationIds }, status: 'active' },
|
||||
select: { id: true, tenantId: true, name: true },
|
||||
})
|
||||
: [];
|
||||
if (accessApplications.length === 1) {
|
||||
return {
|
||||
tenantId: accessApplications[0].tenantId,
|
||||
applicationId: accessApplications[0].id,
|
||||
matchStatus: 'matched',
|
||||
matchReason: '接入号唯一匹配应用',
|
||||
candidates: [],
|
||||
};
|
||||
}
|
||||
if (accessApplications.length > 1) {
|
||||
return {
|
||||
matchStatus: 'ambiguous',
|
||||
matchReason: '接入号匹配多个应用',
|
||||
candidates: accessApplications.map((application) => ({
|
||||
tenantId: application.tenantId,
|
||||
applicationId: application.id,
|
||||
matchSource: 'access_number',
|
||||
confidence: 70,
|
||||
reason: `接入号 ${accessNumber} 可匹配应用 ${application.name}`,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
const windowHours = Number(process.env.UPLINK_MATCH_WINDOW_HOURS ?? 72);
|
||||
const since = new Date(Date.now() - Math.max(1, windowHours) * 60 * 60 * 1000);
|
||||
const recentMessages = await this.prisma.smsMessageRecord.findMany({
|
||||
where: {
|
||||
phoneNumber: data.phoneNumber,
|
||||
tenantId: { not: null },
|
||||
applicationId: { not: null },
|
||||
submittedAt: { gte: since },
|
||||
},
|
||||
orderBy: { submittedAt: 'desc' },
|
||||
take: 2,
|
||||
});
|
||||
const matchableRecentMessages = recentMessages.filter((message) => message.tenantId && message.applicationId);
|
||||
if (matchableRecentMessages.length === 1) {
|
||||
return {
|
||||
tenantId: matchableRecentMessages[0].tenantId ?? undefined,
|
||||
applicationId: matchableRecentMessages[0].applicationId ?? undefined,
|
||||
messageRecordId: matchableRecentMessages[0].id,
|
||||
matchStatus: 'matched',
|
||||
matchReason: `手机号 ${windowHours} 小时窗口唯一匹配`,
|
||||
candidates: [],
|
||||
};
|
||||
}
|
||||
if (matchableRecentMessages.length > 1) {
|
||||
return {
|
||||
matchStatus: 'ambiguous',
|
||||
matchReason: `手机号 ${windowHours} 小时窗口匹配多条下发记录`,
|
||||
candidates: matchableRecentMessages
|
||||
.map((message) => ({
|
||||
tenantId: String(message.tenantId),
|
||||
applicationId: String(message.applicationId),
|
||||
messageRecordId: message.id,
|
||||
matchSource: 'phone_window',
|
||||
confidence: 55,
|
||||
reason: `手机号 ${windowHours} 小时窗口候选下发 ${message.messageId}`,
|
||||
})),
|
||||
};
|
||||
}
|
||||
return { matchStatus: 'unmatched', matchReason: '未匹配到应用或下发记录', candidates: [] };
|
||||
}
|
||||
|
||||
async recordCmppFailureReceipt(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
applicationId?: string | null;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
cmppSubmitSequenceId?: string | null;
|
||||
cmppSubmitGroupMessageId?: string | null;
|
||||
},
|
||||
errorCode: string,
|
||||
reason: string,
|
||||
) {
|
||||
if (!message.tenantId || !message.applicationId) return null;
|
||||
const existing = await this.prisma.smsReceiptRecord.findFirst({
|
||||
where: { messageRecordId: message.id, gatewayMessageId: `PLATFORM:${message.messageId}` },
|
||||
});
|
||||
if (existing) return existing;
|
||||
const deliveredAt = new Date();
|
||||
await this.prisma.smsMessageRecord.update({
|
||||
where: { id: message.id },
|
||||
data: { status: 'failed', receiptStatus: 'undelivered', receiptRawStatus: 'REJECTD', errorCode, errorMessage: reason, deliveredAt },
|
||||
});
|
||||
const gatewayMessageId = `PLATFORM:${message.messageId}`;
|
||||
const receipt = await this.prisma.smsReceiptRecord.create({
|
||||
data: {
|
||||
tenantId: message.tenantId,
|
||||
batchTaskId: message.batchTaskId,
|
||||
messageRecordId: message.id,
|
||||
receiptKey: createHash('sha256').update(`platform\u0000${gatewayMessageId}\u0000${message.phoneNumber}\u0000undelivered\u0000REJECTD\u0000${errorCode}`).digest('hex'),
|
||||
messageId: message.messageId,
|
||||
gatewayMessageId,
|
||||
phoneNumber: message.phoneNumber,
|
||||
receiptStatus: 'undelivered',
|
||||
rawStatus: 'REJECTD',
|
||||
errorCode,
|
||||
errorMessage: reason,
|
||||
deliveredAt,
|
||||
},
|
||||
});
|
||||
await this.facade.queueAndTryDownstreamDelivery({
|
||||
tenantId: message.tenantId,
|
||||
applicationId: message.applicationId,
|
||||
messageRecordId: message.id,
|
||||
messageId: message.messageId,
|
||||
deliveryType: 'receipt',
|
||||
payload: {
|
||||
messageId: message.messageId,
|
||||
gatewayMessageId: `PLATFORM:${message.messageId}`,
|
||||
phoneNumber: message.phoneNumber,
|
||||
receiptStatus: 'undelivered',
|
||||
rawStatus: 'REJECTD',
|
||||
errorCode,
|
||||
errorMessage: reason,
|
||||
submitSequenceId: message.cmppSubmitSequenceId ? Number(message.cmppSubmitSequenceId) : undefined,
|
||||
submitGroupMessageId: message.cmppSubmitGroupMessageId ?? undefined,
|
||||
deliveredAt: deliveredAt.toISOString(),
|
||||
},
|
||||
});
|
||||
if (message.batchTaskId) await this.facade.refreshTaskProgress(message.batchTaskId);
|
||||
return receipt;
|
||||
}
|
||||
|
||||
async postGatewayControl(path: string, payload: unknown) {
|
||||
const baseUrl = (process.env.GATEWAY_CONTROL_URL ?? 'http://127.0.0.1:8090').replace(/\/$/, '');
|
||||
const response = await fetch(`${baseUrl}${path}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const body = await response.text().catch(() => '');
|
||||
throw new Error(`Gateway control ${path} returned ${response.status}${body ? `: ${body}` : ''}`);
|
||||
}
|
||||
return response.json().catch(() => ({}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
import { BadRequestException, HttpException, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import type { OpenApiService } from '../open-api/open-api.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { GatewaySubmitResultDto, GatewaySubmitSegmentResultDto, GatewayReceiptEventDto, GatewayUplinkEventDto, GatewayPendingDeliveryQueryDto, GatewayDownstreamSentDto, GatewayDownstreamAcknowledgedDto, GatewayDownstreamFailureType, GatewayControlDeliveryResult, GatewaySubmitDeadLetterDto, RequeueGatewaySubmitExceptionDto, GatewayDownstreamRecoveryStatusDto, TimeoutUnknownDto } from './send-chain.contracts';
|
||||
import { positiveInteger, normalizeReceiptStatus, normalizeCarrier, DEFAULT_DOWNSTREAM_RETRY_DELAY_MS, DEFAULT_DOWNSTREAM_RETRY_MAX_DELAY_MS, DEFAULT_DOWNSTREAM_MAX_RETRIES, DEFAULT_DOWNSTREAM_PENDING_TIMEOUT_HOURS, DEFAULT_RECEIPT_TIMEOUT_HOURS, DEFAULT_GATEWAY_SUBMIT_REQUEUE_STALE_MS, DEFAULT_DOWNSTREAM_MANUAL_REQUEUE_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_ATTEMPTS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_AGE_HOURS, gatewaySubmitRequeueKey, isObjectRecord, asDateOrNull, downstreamRetryDelayMs, downstreamAckTimeoutMs, downstreamRetryBaseDelayMs, downstreamRetryMaxDelayMs, downstreamMaxRetries, downstreamPendingTimeoutHours, downstreamControlFailureMessage, normalizeSubmitStatus, downstreamDeliveryAttemptKey, hasRecoveryAuditStateChanged, normalizeRecoveryFailureCategory, aggregateReceiptSegmentState, isSameUpstreamEndpointIdentity, receiptEventKey } from './send-chain.helpers';
|
||||
import type { SendSubmissionService } from './send-submission.service';
|
||||
import type { SendCompletionCallbacks, SendCompletionFacade } from './send-completion.service';
|
||||
|
||||
|
||||
/**
|
||||
* R10 downstreamState implementation.
|
||||
* Cross-domain calls return through the stable SendChainService seam to preserve locking and test observability.
|
||||
*/
|
||||
export class SendDownstreamStateService {
|
||||
private readonly logger = new Logger('SendChainService');
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly openApi: OpenApiService | undefined,
|
||||
private readonly facade: SendCompletionFacade,
|
||||
private readonly callbacks: SendCompletionCallbacks,
|
||||
) {}
|
||||
|
||||
async listPendingDownstreamDeliveries(data: GatewayPendingDeliveryQueryDto) {
|
||||
const application = await this.facade.findInboundApplication(data.account);
|
||||
if (!application) {
|
||||
throw new BadRequestException('CMPP account is invalid');
|
||||
}
|
||||
const expiredAcknowledgements = await this.prisma.cmppDownstreamDelivery.findMany({
|
||||
where: { applicationId: application.id, status: 'awaiting_ack', ackDeadlineAt: { lte: new Date() } },
|
||||
select: { id: true },
|
||||
take: 500,
|
||||
});
|
||||
for (const expired of expiredAcknowledgements) {
|
||||
await this.facade.markDownstreamDeliveryFailed(expired.id, 'CMPP_DELIVER_RESP timeout recovered after Gateway restart', 'ack_timeout');
|
||||
}
|
||||
return this.prisma.cmppDownstreamDelivery.findMany({
|
||||
where: {
|
||||
applicationId: application.id,
|
||||
status: 'pending',
|
||||
OR: [{ nextRetryAt: null }, { nextRetryAt: { lte: new Date() } }],
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
take: Math.min(Math.max(data.limit ?? 100, 1), 500),
|
||||
});
|
||||
}
|
||||
|
||||
async markDownstreamDeliveryDelivered(id: string) {
|
||||
return this.prisma.cmppDownstreamDelivery.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: 'delivered',
|
||||
deliveredAt: new Date(),
|
||||
lastError: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async markDownstreamDeliverySent(data: GatewayDownstreamSentDto) {
|
||||
const sentAt = asDateOrNull(data.sentAt) ?? new Date();
|
||||
const ackDeadlineAt = asDateOrNull(data.ackDeadlineAt) ?? new Date(sentAt.getTime() + downstreamAckTimeoutMs());
|
||||
const delivery = await this.prisma.cmppDownstreamDelivery.findUnique({ where: { id: data.id } });
|
||||
if (!delivery) {
|
||||
throw new NotFoundException('Downstream delivery not found');
|
||||
}
|
||||
const attemptKey = downstreamDeliveryAttemptKey(data);
|
||||
await this.prisma.cmppDownstreamDeliveryAttempt.upsert({
|
||||
where: { attemptKey },
|
||||
update: {
|
||||
connectionId: data.connectionId,
|
||||
sequenceId: data.sequenceId,
|
||||
messageId: data.messageId,
|
||||
sentAt,
|
||||
ackDeadlineAt,
|
||||
},
|
||||
create: {
|
||||
deliveryId: data.id,
|
||||
attemptKey,
|
||||
attemptNo: delivery.retryCount + 1,
|
||||
connectionId: data.connectionId,
|
||||
sequenceId: data.sequenceId,
|
||||
messageId: data.messageId,
|
||||
status: 'awaiting_ack',
|
||||
sentAt,
|
||||
ackDeadlineAt,
|
||||
},
|
||||
});
|
||||
await this.prisma.cmppDownstreamDelivery.updateMany({
|
||||
where: { id: data.id, status: { not: 'delivered' } },
|
||||
data: {
|
||||
status: 'awaiting_ack',
|
||||
sentAt,
|
||||
ackDeadlineAt,
|
||||
ackSequenceId: data.sequenceId,
|
||||
ackMessageId: data.messageId,
|
||||
connectionId: data.connectionId,
|
||||
nextRetryAt: null,
|
||||
lastError: null,
|
||||
},
|
||||
});
|
||||
return this.prisma.cmppDownstreamDelivery.findUnique({ where: { id: data.id } });
|
||||
}
|
||||
|
||||
async acknowledgeDownstreamDelivery(data: GatewayDownstreamAcknowledgedDto) {
|
||||
const acknowledgedAt = asDateOrNull(data.acknowledgedAt) ?? new Date();
|
||||
const acknowledgedMessageId = String(data.messageId ?? '').trim();
|
||||
const delivery = await this.prisma.cmppDownstreamDelivery.findUnique({ where: { id: data.id } });
|
||||
if (!delivery) {
|
||||
throw new NotFoundException('Downstream delivery not found');
|
||||
}
|
||||
const attemptKey = downstreamDeliveryAttemptKey(data);
|
||||
const acknowledgementAccepted = data.result === 0 && acknowledgedMessageId !== '' && acknowledgedMessageId !== '0';
|
||||
await this.prisma.cmppDownstreamDeliveryAttempt.upsert({
|
||||
where: { attemptKey },
|
||||
update: {
|
||||
status: acknowledgementAccepted ? 'acknowledged' : 'rejected',
|
||||
connectionId: data.connectionId,
|
||||
sequenceId: data.sequenceId,
|
||||
messageId: data.messageId,
|
||||
acknowledgedAt,
|
||||
ackResult: data.result,
|
||||
ackDeadlineAt: null,
|
||||
failureType: acknowledgementAccepted ? null : data.result === 0 ? 'ack_invalid' : 'ack_rejected',
|
||||
errorMessage: acknowledgementAccepted
|
||||
? null
|
||||
: data.result === 0
|
||||
? 'CMPP_DELIVER_RESP Msg_Id=0'
|
||||
: `CMPP_DELIVER_RESP result=${data.result}`,
|
||||
},
|
||||
create: {
|
||||
deliveryId: data.id,
|
||||
attemptKey,
|
||||
attemptNo: delivery.retryCount + 1,
|
||||
connectionId: data.connectionId,
|
||||
sequenceId: data.sequenceId,
|
||||
messageId: data.messageId,
|
||||
status: acknowledgementAccepted ? 'acknowledged' : 'rejected',
|
||||
acknowledgedAt,
|
||||
ackResult: data.result,
|
||||
failureType: acknowledgementAccepted ? null : data.result === 0 ? 'ack_invalid' : 'ack_rejected',
|
||||
errorMessage: acknowledgementAccepted
|
||||
? null
|
||||
: data.result === 0
|
||||
? 'CMPP_DELIVER_RESP Msg_Id=0'
|
||||
: `CMPP_DELIVER_RESP result=${data.result}`,
|
||||
},
|
||||
});
|
||||
if (acknowledgementAccepted) {
|
||||
await this.prisma.cmppDownstreamDelivery.updateMany({
|
||||
where: { id: data.id, status: { not: 'delivered' } },
|
||||
data: {
|
||||
status: 'delivered',
|
||||
acknowledgedAt,
|
||||
deliveredAt: acknowledgedAt,
|
||||
ackDeadlineAt: null,
|
||||
ackResult: data.result,
|
||||
ackSequenceId: data.sequenceId,
|
||||
ackMessageId: data.messageId,
|
||||
connectionId: data.connectionId,
|
||||
nextRetryAt: null,
|
||||
lastError: null,
|
||||
},
|
||||
});
|
||||
return this.prisma.cmppDownstreamDelivery.findUnique({ where: { id: data.id } });
|
||||
}
|
||||
await this.prisma.cmppDownstreamDelivery.updateMany({
|
||||
where: { id: data.id, status: { not: 'delivered' } },
|
||||
data: {
|
||||
acknowledgedAt,
|
||||
ackResult: data.result,
|
||||
ackSequenceId: data.sequenceId,
|
||||
ackMessageId: data.messageId,
|
||||
connectionId: data.connectionId,
|
||||
},
|
||||
});
|
||||
if (data.result === 0) {
|
||||
return this.facade.markDownstreamDeliveryFailed(data.id, 'CMPP_DELIVER_RESP Msg_Id=0,客户端仅确认协议收包,无法关联原短信', 'ack_invalid');
|
||||
}
|
||||
return this.facade.markDownstreamDeliveryFailed(data.id, `downstream CMPP_DELIVER_RESP result=${data.result}`, 'ack_rejected');
|
||||
}
|
||||
|
||||
async markDownstreamDeliveryFailed(
|
||||
id: string,
|
||||
errorMessage?: string,
|
||||
failureType: GatewayDownstreamFailureType = 'send_failed',
|
||||
attempt?: GatewayDownstreamSentDto,
|
||||
) {
|
||||
const delivery = await this.prisma.cmppDownstreamDelivery.findUnique({ where: { id } });
|
||||
if (!delivery) {
|
||||
throw new NotFoundException('Downstream delivery not found');
|
||||
}
|
||||
if (delivery.status === 'delivered') {
|
||||
return delivery;
|
||||
}
|
||||
if (failureType === 'queue_timeout' && delivery.status !== 'pending') {
|
||||
return delivery;
|
||||
}
|
||||
const retryCount = (delivery.retryCount ?? 0) + 1;
|
||||
const acknowledgementFailure = failureType === 'ack_timeout' || failureType === 'ack_rejected' || failureType === 'ack_invalid' || failureType === 'connection_lost';
|
||||
const retryAllowed = !acknowledgementFailure || delivery.retryEnabled !== false;
|
||||
const nonRetryableFailure = failureType === 'unrecoverable' || failureType === 'queue_timeout';
|
||||
const finalFailure = nonRetryableFailure || !retryAllowed || retryCount >= downstreamMaxRetries();
|
||||
const finalStatus = failureType === 'ack_rejected' ? 'rejected' : acknowledgementFailure ? 'unconfirmed' : 'failed';
|
||||
if (attempt && (attempt.connectionId || attempt.sequenceId || attempt.messageId)) {
|
||||
const attemptKey = downstreamDeliveryAttemptKey({ ...attempt, id });
|
||||
await this.prisma.cmppDownstreamDeliveryAttempt.upsert({
|
||||
where: { attemptKey },
|
||||
update: {
|
||||
status: 'failed',
|
||||
connectionId: attempt.connectionId,
|
||||
sequenceId: attempt.sequenceId,
|
||||
messageId: attempt.messageId,
|
||||
failureType,
|
||||
errorMessage: errorMessage ?? 'downstream delivery failed',
|
||||
ackDeadlineAt: null,
|
||||
},
|
||||
create: {
|
||||
deliveryId: id,
|
||||
attemptKey,
|
||||
attemptNo: delivery.retryCount + 1,
|
||||
connectionId: attempt.connectionId,
|
||||
sequenceId: attempt.sequenceId,
|
||||
messageId: attempt.messageId,
|
||||
status: 'failed',
|
||||
sentAt: asDateOrNull(attempt.sentAt),
|
||||
failureType,
|
||||
errorMessage: errorMessage ?? 'downstream delivery failed',
|
||||
},
|
||||
});
|
||||
}
|
||||
const updated = await this.prisma.cmppDownstreamDelivery.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: finalFailure ? finalStatus : 'pending',
|
||||
retryCount,
|
||||
nextRetryAt: finalFailure ? null : new Date(Date.now() + downstreamRetryDelayMs(retryCount)),
|
||||
ackDeadlineAt: null,
|
||||
lastError: errorMessage ?? 'downstream delivery failed',
|
||||
},
|
||||
});
|
||||
if (finalFailure) {
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
tenantId: updated.tenantId,
|
||||
action: 'gateway.downstream_delivery_failed',
|
||||
resource: 'cmpp_downstream_delivery',
|
||||
resourceId: updated.id,
|
||||
detail: {
|
||||
deliveryType: updated.deliveryType,
|
||||
applicationId: updated.applicationId,
|
||||
messageId: updated.messageId,
|
||||
retryCount,
|
||||
failureType,
|
||||
retryEnabled: updated.retryEnabled,
|
||||
errorMessage: updated.lastError,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
async recordGatewayDownstreamRecoveryStatus(data: GatewayDownstreamRecoveryStatusDto) {
|
||||
const account = String(data.account ?? '').trim();
|
||||
if (!account) {
|
||||
throw new BadRequestException('account is required');
|
||||
}
|
||||
const recoveryStatuses = (this.prisma as PrismaService & {
|
||||
gatewayDownstreamRecoveryStatus: {
|
||||
findUnique: (args: Record<string, unknown>) => Promise<any>;
|
||||
upsert: (args: Record<string, unknown>) => Promise<any>;
|
||||
};
|
||||
}).gatewayDownstreamRecoveryStatus;
|
||||
const previous = await recoveryStatuses.findUnique({
|
||||
where: { account },
|
||||
select: {
|
||||
state: true,
|
||||
gatewayInstanceId: true,
|
||||
lockOwner: true,
|
||||
failureCategory: true,
|
||||
lastError: true,
|
||||
lastSkipReason: true,
|
||||
},
|
||||
});
|
||||
const application = await this.prisma.smsApplication.findUnique({
|
||||
where: { cmppAccount: account },
|
||||
select: { id: true, tenantId: true, name: true },
|
||||
});
|
||||
const failureCategory = normalizeRecoveryFailureCategory(data);
|
||||
const updated = await recoveryStatuses.upsert({
|
||||
where: { account },
|
||||
update: {
|
||||
tenantId: application?.tenantId ?? null,
|
||||
applicationId: application?.id ?? null,
|
||||
gatewayInstanceId: data.gatewayInstanceId ?? null,
|
||||
state: data.state,
|
||||
lockOwner: data.lockOwner ?? null,
|
||||
lockExpiresAt: asDateOrNull(data.lockExpiresAt),
|
||||
lastAttemptAt: asDateOrNull(data.lastAttemptAt),
|
||||
lastSuccessAt: asDateOrNull(data.lastSuccessAt),
|
||||
lastFailureAt: asDateOrNull(data.lastFailureAt),
|
||||
nextRetryAt: asDateOrNull(data.nextRetryAt),
|
||||
attemptCount: Number.isFinite(Number(data.attemptCount)) ? Number(data.attemptCount) : 0,
|
||||
failureCategory,
|
||||
lastError: data.lastError ?? null,
|
||||
lastSkipReason: data.lastSkipReason ?? null,
|
||||
},
|
||||
create: {
|
||||
account,
|
||||
tenantId: application?.tenantId,
|
||||
applicationId: application?.id,
|
||||
gatewayInstanceId: data.gatewayInstanceId,
|
||||
state: data.state,
|
||||
lockOwner: data.lockOwner,
|
||||
lockExpiresAt: asDateOrNull(data.lockExpiresAt),
|
||||
lastAttemptAt: asDateOrNull(data.lastAttemptAt),
|
||||
lastSuccessAt: asDateOrNull(data.lastSuccessAt),
|
||||
lastFailureAt: asDateOrNull(data.lastFailureAt),
|
||||
nextRetryAt: asDateOrNull(data.nextRetryAt),
|
||||
attemptCount: Number.isFinite(Number(data.attemptCount)) ? Number(data.attemptCount) : 0,
|
||||
failureCategory,
|
||||
lastError: data.lastError,
|
||||
lastSkipReason: data.lastSkipReason,
|
||||
},
|
||||
include: {
|
||||
tenant: true,
|
||||
application: true,
|
||||
},
|
||||
});
|
||||
const normalizedUpdated = updated as typeof updated & {
|
||||
failureCategory?: string | null;
|
||||
lockOwner?: string | null;
|
||||
lockExpiresAt?: Date | null;
|
||||
};
|
||||
if (hasRecoveryAuditStateChanged(previous, updated)) {
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
tenantId: updated.tenantId ?? undefined,
|
||||
action: 'gateway.downstream_recovery_status_changed',
|
||||
resource: 'gateway_downstream_recovery_status',
|
||||
resourceId: updated.id,
|
||||
detail: {
|
||||
account,
|
||||
previousState: previous?.state ?? null,
|
||||
state: updated.state,
|
||||
gatewayInstanceId: updated.gatewayInstanceId,
|
||||
lockOwner: normalizedUpdated.lockOwner,
|
||||
attemptCount: updated.attemptCount,
|
||||
nextRetryAt: updated.nextRetryAt,
|
||||
failureCategory: normalizedUpdated.failureCategory,
|
||||
applicationId: updated.applicationId,
|
||||
applicationName: application?.name,
|
||||
lastError: updated.lastError,
|
||||
lastSkipReason: updated.lastSkipReason,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
async requeueDownstreamDelivery(id: string) {
|
||||
const delivery = await this.prisma.cmppDownstreamDelivery.findUnique({
|
||||
where: { id },
|
||||
include: { application: { select: { cmppAccount: true } } },
|
||||
});
|
||||
if (!delivery) {
|
||||
throw new NotFoundException('Downstream delivery not found');
|
||||
}
|
||||
if (delivery.status === 'awaiting_ack') {
|
||||
throw new BadRequestException('该记录正在等待客户端确认,不允许并发重投');
|
||||
}
|
||||
const payload = isObjectRecord(delivery.payload) ? { ...delivery.payload } : null;
|
||||
if (!payload) {
|
||||
throw new BadRequestException('下游投递记录缺少可重放 payload');
|
||||
}
|
||||
const path =
|
||||
delivery.deliveryType === 'receipt'
|
||||
? '/downstream/receipt'
|
||||
: delivery.deliveryType === 'uplink'
|
||||
? '/downstream/uplink'
|
||||
: null;
|
||||
if (!path) {
|
||||
throw new BadRequestException(`Unsupported downstream delivery type ${delivery.deliveryType}`);
|
||||
}
|
||||
|
||||
const requestPayload = {
|
||||
deliveryId: delivery.id,
|
||||
account: String(payload.account ?? delivery.application?.cmppAccount ?? ''),
|
||||
...payload,
|
||||
};
|
||||
const retriedAt = new Date();
|
||||
const claimed = await this.prisma.cmppDownstreamDelivery.updateMany({
|
||||
where: {
|
||||
id: delivery.id,
|
||||
status: delivery.status,
|
||||
updatedAt: delivery.updatedAt,
|
||||
},
|
||||
data: {
|
||||
status: 'manual_requeueing',
|
||||
retryCount: 0,
|
||||
manualRetryCount: { increment: 1 },
|
||||
lastRetriedAt: retriedAt,
|
||||
nextRetryAt: null,
|
||||
sentAt: null,
|
||||
acknowledgedAt: null,
|
||||
ackDeadlineAt: null,
|
||||
ackResult: null,
|
||||
ackSequenceId: null,
|
||||
ackMessageId: null,
|
||||
connectionId: null,
|
||||
deliveredAt: null,
|
||||
lastError: null,
|
||||
},
|
||||
});
|
||||
if (claimed.count !== 1) {
|
||||
throw new BadRequestException('该下游投递记录已被其他操作处理,请刷新后重试');
|
||||
}
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
tenantId: delivery.tenantId,
|
||||
action: 'gateway.downstream_delivery_requeue',
|
||||
resource: 'cmpp_downstream_delivery',
|
||||
resourceId: delivery.id,
|
||||
detail: {
|
||||
deliveryType: delivery.deliveryType,
|
||||
applicationId: delivery.applicationId,
|
||||
messageId: delivery.messageId,
|
||||
previousStatus: delivery.status,
|
||||
previousRetryCount: delivery.retryCount,
|
||||
manualRetryCount: (delivery.manualRetryCount ?? 0) + 1,
|
||||
lastRetriedAt: retriedAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
try {
|
||||
const result = await this.facade.postGatewayControl(path, requestPayload) as GatewayControlDeliveryResult;
|
||||
if (result.sent || result.delivered) {
|
||||
return this.facade.markDownstreamDeliverySent({ id: delivery.id, ...result });
|
||||
}
|
||||
return this.facade.markDownstreamDeliveryFailed(
|
||||
delivery.id,
|
||||
downstreamControlFailureMessage(result),
|
||||
result.retryable === false ? 'unrecoverable' : 'send_failed',
|
||||
);
|
||||
} catch (error) {
|
||||
return this.facade.markDownstreamDeliveryFailed(
|
||||
delivery.id,
|
||||
error instanceof Error ? error.message : 'Gateway control delivery failed',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async recoverStaleDownstreamManualRequeues(now = new Date()) {
|
||||
const staleCutoff = new Date(now.getTime() - positiveInteger(
|
||||
process.env.CMPP_DOWNSTREAM_MANUAL_REQUEUE_STALE_MS,
|
||||
DEFAULT_DOWNSTREAM_MANUAL_REQUEUE_STALE_MS,
|
||||
));
|
||||
const stale = await this.prisma.cmppDownstreamDelivery.findMany({
|
||||
where: { status: 'manual_requeueing', updatedAt: { lt: staleCutoff } },
|
||||
select: { id: true, updatedAt: true },
|
||||
orderBy: { updatedAt: 'asc' },
|
||||
take: 500,
|
||||
});
|
||||
let recovered = 0;
|
||||
for (const delivery of stale) {
|
||||
const updated = await this.prisma.cmppDownstreamDelivery.updateMany({
|
||||
where: { id: delivery.id, status: 'manual_requeueing', updatedAt: delivery.updatedAt },
|
||||
data: {
|
||||
status: 'pending',
|
||||
nextRetryAt: null,
|
||||
lastError: '人工重投进程中断,已恢复为待投递',
|
||||
},
|
||||
});
|
||||
recovered += updated.count;
|
||||
}
|
||||
return { recovered };
|
||||
}
|
||||
|
||||
async batchRequeueDownstreamDeliveries(ids: string[]) {
|
||||
const uniqueIds = [...new Set(ids.filter(Boolean))];
|
||||
if (uniqueIds.length === 0) {
|
||||
throw new BadRequestException('请选择至少一条下游投递记录');
|
||||
}
|
||||
const results: Array<{ id: string; status: 'success' | 'failed'; errorMessage?: string }> = [];
|
||||
for (const id of uniqueIds) {
|
||||
try {
|
||||
await this.facade.requeueDownstreamDelivery(id);
|
||||
results.push({ id, status: 'success' });
|
||||
} catch (error) {
|
||||
results.push({
|
||||
id,
|
||||
status: 'failed',
|
||||
errorMessage: error instanceof Error ? error.message : '批量重投失败',
|
||||
});
|
||||
}
|
||||
}
|
||||
return {
|
||||
total: uniqueIds.length,
|
||||
successCount: results.filter((item) => item.status === 'success').length,
|
||||
failedCount: results.filter((item) => item.status === 'failed').length,
|
||||
results,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
import { BadRequestException, HttpException, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import type { OpenApiService } from '../open-api/open-api.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { GatewaySubmitResultDto, GatewaySubmitSegmentResultDto, GatewayReceiptEventDto, GatewayUplinkEventDto, GatewayPendingDeliveryQueryDto, GatewayDownstreamSentDto, GatewayDownstreamAcknowledgedDto, GatewayDownstreamFailureType, GatewayControlDeliveryResult, GatewaySubmitDeadLetterDto, RequeueGatewaySubmitExceptionDto, GatewayDownstreamRecoveryStatusDto, TimeoutUnknownDto } from './send-chain.contracts';
|
||||
import { positiveInteger, normalizeReceiptStatus, normalizeCarrier, DEFAULT_DOWNSTREAM_RETRY_DELAY_MS, DEFAULT_DOWNSTREAM_RETRY_MAX_DELAY_MS, DEFAULT_DOWNSTREAM_MAX_RETRIES, DEFAULT_DOWNSTREAM_PENDING_TIMEOUT_HOURS, DEFAULT_RECEIPT_TIMEOUT_HOURS, DEFAULT_GATEWAY_SUBMIT_REQUEUE_STALE_MS, DEFAULT_DOWNSTREAM_MANUAL_REQUEUE_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_ATTEMPTS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_AGE_HOURS, gatewaySubmitRequeueKey, isObjectRecord, asDateOrNull, downstreamRetryDelayMs, downstreamAckTimeoutMs, downstreamRetryBaseDelayMs, downstreamRetryMaxDelayMs, downstreamMaxRetries, downstreamPendingTimeoutHours, downstreamControlFailureMessage, normalizeSubmitStatus, downstreamDeliveryAttemptKey, hasRecoveryAuditStateChanged, normalizeRecoveryFailureCategory, aggregateReceiptSegmentState, isSameUpstreamEndpointIdentity, receiptEventKey } from './send-chain.helpers';
|
||||
import type { SendSubmissionService } from './send-submission.service';
|
||||
import type { SendCompletionCallbacks, SendCompletionFacade } from './send-completion.service';
|
||||
|
||||
|
||||
/**
|
||||
* R10 gatewayResult implementation.
|
||||
* Cross-domain calls return through the stable SendChainService seam to preserve locking and test observability.
|
||||
*/
|
||||
export class SendGatewayResultService {
|
||||
private readonly logger = new Logger('SendChainService');
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly openApi: OpenApiService | undefined,
|
||||
private readonly facade: SendCompletionFacade,
|
||||
private readonly callbacks: SendCompletionCallbacks,
|
||||
) {}
|
||||
|
||||
async handleSubmitSegmentResult(data: GatewaySubmitSegmentResultDto) {
|
||||
const message = await this.facade.requireMessageByGatewayEvent(data.messageId, data.gatewayMessageId);
|
||||
const submitRecord = await this.facade.resolveSubmitRecordForGatewaySegmentResult(message.id, data);
|
||||
const effectiveSubmitId = submitRecord.submitId;
|
||||
const submittedAt = data.submittedAt ? new Date(data.submittedAt) : new Date();
|
||||
await this.facade.recordSubmitSegments(message, {
|
||||
messageId: data.messageId,
|
||||
channelId: data.channelId,
|
||||
submitId: effectiveSubmitId,
|
||||
sequenceId: data.sequenceId,
|
||||
gatewayMessageId: data.gatewayMessageId ?? '',
|
||||
submitStatus: normalizeSubmitStatus(data.submitStatus),
|
||||
errorCode: data.errorCode,
|
||||
errorMessage: data.errorMessage,
|
||||
submittedAt: submittedAt.toISOString(),
|
||||
segments: [{
|
||||
segmentTotal: data.segmentTotal,
|
||||
segmentIndex: data.segmentIndex,
|
||||
sequenceId: data.sequenceId,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
submitStatus: data.submitStatus,
|
||||
errorCode: data.errorCode,
|
||||
errorMessage: data.errorMessage,
|
||||
submittedAt: submittedAt.toISOString(),
|
||||
}],
|
||||
}, submittedAt);
|
||||
if (data.gatewayMessageId) {
|
||||
await this.prisma.smsSubmitRecord.updateMany({
|
||||
where: {
|
||||
id: submitRecord.id,
|
||||
gatewayMessageId: null,
|
||||
},
|
||||
data: {
|
||||
sequenceId: data.sequenceId,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
submittedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
return { accepted: true };
|
||||
}
|
||||
|
||||
async resolveSubmitRecordForGatewaySegmentResult(
|
||||
messageRecordId: string,
|
||||
data: GatewaySubmitSegmentResultDto,
|
||||
) {
|
||||
if (data.submitId) {
|
||||
const exact = await this.prisma.smsSubmitRecord.findUnique({
|
||||
where: { submitId: data.submitId },
|
||||
});
|
||||
if (
|
||||
!exact ||
|
||||
(exact.messageRecordId && exact.messageRecordId !== messageRecordId) ||
|
||||
(exact.channelId && exact.channelId !== data.channelId)
|
||||
) {
|
||||
this.logger.error(`gateway_submit_segment_result_unmatched ${JSON.stringify({
|
||||
messageId: data.messageId,
|
||||
messageRecordId,
|
||||
submitId: data.submitId,
|
||||
channelId: data.channelId,
|
||||
segmentIndex: data.segmentIndex,
|
||||
})}`);
|
||||
throw new BadRequestException(
|
||||
'Gateway SubmitSegmentResult submitId does not match the SMS message and channel',
|
||||
);
|
||||
}
|
||||
return exact;
|
||||
}
|
||||
|
||||
const candidates = await this.prisma.smsSubmitRecord.findMany({
|
||||
where: {
|
||||
messageRecordId,
|
||||
channelId: data.channelId,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 2,
|
||||
});
|
||||
if (candidates.length !== 1) {
|
||||
this.logger.error(`gateway_submit_segment_result_unmatched ${JSON.stringify({
|
||||
messageId: data.messageId,
|
||||
messageRecordId,
|
||||
channelId: data.channelId,
|
||||
segmentIndex: data.segmentIndex,
|
||||
candidateCount: candidates.length,
|
||||
})}`);
|
||||
throw new BadRequestException(
|
||||
'Gateway SubmitSegmentResult without submitId cannot be matched uniquely',
|
||||
);
|
||||
}
|
||||
this.logger.warn(`gateway_submit_segment_result_legacy_match ${JSON.stringify({
|
||||
messageId: data.messageId,
|
||||
messageRecordId,
|
||||
channelId: data.channelId,
|
||||
segmentIndex: data.segmentIndex,
|
||||
submitId: candidates[0].submitId,
|
||||
})}`);
|
||||
return candidates[0];
|
||||
}
|
||||
|
||||
async handleSubmitResult(data: GatewaySubmitResultDto) {
|
||||
const message = await this.facade.requireMessageByGatewayEvent(data.messageId, data.gatewayMessageId);
|
||||
const submitRecord = await this.facade.resolveSubmitRecordForGatewayResult(message.id, data);
|
||||
const effectiveData = { ...data, submitId: submitRecord.submitId };
|
||||
const batchTask = message.batchTaskId
|
||||
? await this.prisma.smsBatchTask.findUnique({ where: { id: message.batchTaskId }, select: { sourceType: true } })
|
||||
: null;
|
||||
const submittedAt = data.submittedAt ? new Date(data.submittedAt) : new Date();
|
||||
await this.prisma.smsSubmitRecord.updateMany({
|
||||
where: { id: submitRecord.id },
|
||||
data: {
|
||||
sequenceId: data.sequenceId,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
submitStatus: data.submitStatus,
|
||||
errorCode: data.errorCode,
|
||||
errorMessage: data.errorMessage,
|
||||
submittedAt,
|
||||
},
|
||||
});
|
||||
await this.facade.recordSubmitSegments(message, effectiveData, submittedAt);
|
||||
const isStandaloneChannelTest = !message.tenantId && !message.batchTaskId;
|
||||
if (message.submitId && effectiveData.submitId !== message.submitId) {
|
||||
return this.prisma.smsMessageRecord.findUnique({ where: { id: message.id } });
|
||||
}
|
||||
const status = data.submitStatus === 'accepted' ? 'submitted' : data.submitStatus === 'timeout' ? 'timeout' : 'submit_failed';
|
||||
if (data.submitStatus === 'accepted' && !isStandaloneChannelTest && message.tenantId && message.batchTaskId) {
|
||||
const businessMessage = message as typeof message & { tenantId: string; batchTaskId: string };
|
||||
await this.facade.chargeAcceptedMessage(businessMessage);
|
||||
const latest = await this.prisma.smsMessageRecord.findUnique({ where: { id: message.id } });
|
||||
if (latest?.status === 'failed') {
|
||||
await this.facade.refundMessage(businessMessage, '先到失败回执补偿退款');
|
||||
}
|
||||
} else if (data.submitStatus !== 'accepted' && !isStandaloneChannelTest && message.tenantId && message.batchTaskId) {
|
||||
const businessMessage = message as typeof message & { tenantId: string; batchTaskId: string };
|
||||
const retried = await this.facade.retryMessageIfAllowed(
|
||||
businessMessage,
|
||||
data.submitStatus === 'timeout' ? '提交超时补发' : '提交失败补发',
|
||||
submitRecord.id,
|
||||
);
|
||||
if (retried) {
|
||||
await this.facade.refreshTaskProgress(businessMessage.batchTaskId);
|
||||
return retried;
|
||||
}
|
||||
await this.facade.releaseMessageReservation(businessMessage, data.submitStatus === 'timeout' ? '提交超时释放冻结' : '提交失败释放冻结');
|
||||
}
|
||||
const protectedTerminalStatuses = ['delivered', 'failed', 'unknown'];
|
||||
const updated = await this.prisma.smsMessageRecord.updateMany({
|
||||
where: data.submitStatus === 'accepted'
|
||||
? { id: message.id, status: { notIn: protectedTerminalStatuses } }
|
||||
: { id: message.id, status: { not: 'delivered' } },
|
||||
data: {
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
submitStatus: data.submitStatus,
|
||||
status,
|
||||
errorCode: data.errorCode,
|
||||
errorMessage: data.errorMessage,
|
||||
submittedAt,
|
||||
timeoutAt: data.submitStatus === 'timeout' ? submittedAt : undefined,
|
||||
},
|
||||
});
|
||||
if (updated.count === 0 && data.submitStatus === 'accepted') {
|
||||
await this.prisma.smsMessageRecord.updateMany({
|
||||
where: { id: message.id, gatewayMessageId: null },
|
||||
data: {
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
submittedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (data.submitStatus !== 'accepted' && batchTask?.sourceType === 'cmpp' && message.tenantId && message.applicationId) {
|
||||
await this.facade.recordCmppFailureReceipt(
|
||||
message as typeof message & { tenantId: string; applicationId: string; batchTaskId: string },
|
||||
data.errorCode || 'SUBMIT',
|
||||
data.errorMessage || (data.submitStatus === 'timeout' ? '上游提交超时' : '上游拒绝短信'),
|
||||
);
|
||||
}
|
||||
await this.prisma.gatewaySubmitDeadLetter.updateMany({
|
||||
where: {
|
||||
status: { in: ['pending', 'requeueing', 'requeue_recovering', 'requeued'] },
|
||||
OR: [
|
||||
{ submitId: effectiveData.submitId },
|
||||
data.messageId ? { messageId: data.messageId } : undefined,
|
||||
].filter(Boolean) as Array<{ submitId?: string; messageId?: string }>,
|
||||
},
|
||||
data: {
|
||||
status: 'resolved',
|
||||
resolvedAt: submittedAt,
|
||||
resolvedStatus: data.submitStatus,
|
||||
},
|
||||
});
|
||||
if (message.batchTaskId) {
|
||||
await this.facade.refreshTaskProgress(message.batchTaskId);
|
||||
}
|
||||
return this.prisma.smsMessageRecord.findUnique({ where: { id: message.id } });
|
||||
}
|
||||
|
||||
async resolveSubmitRecordForGatewayResult(messageRecordId: string, data: GatewaySubmitResultDto) {
|
||||
if (data.submitId) {
|
||||
const exact = await this.prisma.smsSubmitRecord.findUnique({ where: { submitId: data.submitId } });
|
||||
if (!exact
|
||||
|| (exact.messageRecordId && exact.messageRecordId !== messageRecordId)
|
||||
|| (exact.channelId && exact.channelId !== data.channelId)) {
|
||||
throw new BadRequestException('Gateway SubmitResult submitId does not match the SMS message and channel');
|
||||
}
|
||||
return exact;
|
||||
}
|
||||
const candidates = await this.prisma.smsSubmitRecord.findMany({
|
||||
where: {
|
||||
messageRecordId,
|
||||
channelId: data.channelId,
|
||||
OR: [
|
||||
data.gatewayMessageId ? { gatewayMessageId: data.gatewayMessageId } : undefined,
|
||||
{ gatewayMessageId: null },
|
||||
].filter(Boolean) as Array<{ gatewayMessageId?: string | null }>,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 2,
|
||||
});
|
||||
if (candidates.length !== 1) {
|
||||
this.logger.error(`gateway_submit_result_unmatched ${JSON.stringify({
|
||||
messageId: data.messageId,
|
||||
messageRecordId,
|
||||
channelId: data.channelId,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
candidateCount: candidates.length,
|
||||
})}`);
|
||||
throw new BadRequestException('Gateway SubmitResult without submitId cannot be matched uniquely');
|
||||
}
|
||||
this.logger.warn(`gateway_submit_result_legacy_match ${JSON.stringify({
|
||||
messageId: data.messageId,
|
||||
messageRecordId,
|
||||
channelId: data.channelId,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
submitId: candidates[0].submitId,
|
||||
})}`);
|
||||
return candidates[0];
|
||||
}
|
||||
|
||||
smsMessageSegmentAuditDelegate() {
|
||||
return (this.prisma as PrismaService & {
|
||||
smsMessageSegmentAudit: {
|
||||
upsert: (args: Record<string, unknown>) => Promise<any>;
|
||||
updateMany: (args: Record<string, unknown>) => Promise<{ count: number }>;
|
||||
findFirst: (args: Record<string, unknown>) => Promise<any | null>;
|
||||
findMany: (args: Record<string, unknown>) => Promise<any[]>;
|
||||
};
|
||||
}).smsMessageSegmentAudit;
|
||||
}
|
||||
|
||||
async recordSubmitSegments(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
channelId?: string | null;
|
||||
submitId?: string | null;
|
||||
billingUnits?: number | null;
|
||||
},
|
||||
data: GatewaySubmitResultDto,
|
||||
submittedAt: Date,
|
||||
) {
|
||||
const segmentAudits = this.facade.smsMessageSegmentAuditDelegate();
|
||||
const submitRecord = await this.prisma.smsSubmitRecord.findFirst({
|
||||
where: {
|
||||
messageRecordId: message.id,
|
||||
OR: [
|
||||
data.submitId ? { submitId: data.submitId } : undefined,
|
||||
data.gatewayMessageId ? { gatewayMessageId: data.gatewayMessageId } : undefined,
|
||||
].filter(Boolean) as Array<{ submitId?: string; gatewayMessageId?: string }>,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
const submitId = data.submitId ?? submitRecord?.submitId ?? message.submitId ?? `SUB-AUDIT-${message.id}`;
|
||||
const attempt = submitRecord
|
||||
? Math.max(0, await this.prisma.smsSubmitRecord.count({
|
||||
where: {
|
||||
messageRecordId: message.id,
|
||||
createdAt: { lte: submitRecord.createdAt },
|
||||
},
|
||||
}) - 1)
|
||||
: 0;
|
||||
const fallbackSegments = [{
|
||||
segmentTotal: Math.max(1, Number(message.billingUnits ?? 1)),
|
||||
segmentIndex: 1,
|
||||
sequenceId: data.sequenceId,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
submitStatus: data.submitStatus,
|
||||
errorCode: data.errorCode,
|
||||
errorMessage: data.errorMessage,
|
||||
submittedAt: data.submittedAt,
|
||||
}];
|
||||
const segments = data.segments && data.segments.length > 0 ? data.segments : fallbackSegments;
|
||||
const segmentTotal = Math.max(1, ...segments.map((item) => Number(item.segmentTotal ?? segments.length ?? 1)));
|
||||
await Promise.all(segments.map((segment, index) => {
|
||||
const segmentIndex = Math.max(1, Number(segment.segmentIndex ?? index + 1));
|
||||
const status = segment.submitStatus ?? data.submitStatus;
|
||||
return segmentAudits.upsert({
|
||||
where: {
|
||||
messageRecordId_submitId_segmentIndex: {
|
||||
messageRecordId: message.id,
|
||||
submitId,
|
||||
segmentIndex,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
submitRecordId: submitRecord?.id ?? null,
|
||||
channelId: data.channelId ?? message.channelId ?? null,
|
||||
attempt,
|
||||
segmentTotal,
|
||||
sequenceId: segment.sequenceId ?? data.sequenceId ?? null,
|
||||
gatewayMessageId: segment.gatewayMessageId ?? data.gatewayMessageId ?? null,
|
||||
submitStatus: status,
|
||||
errorCode: segment.errorCode ?? data.errorCode ?? null,
|
||||
errorMessage: segment.errorMessage ?? data.errorMessage ?? null,
|
||||
submittedAt: segment.submittedAt ? new Date(segment.submittedAt) : submittedAt,
|
||||
},
|
||||
create: {
|
||||
tenantId: message.tenantId,
|
||||
batchTaskId: message.batchTaskId,
|
||||
messageRecordId: message.id,
|
||||
submitRecordId: submitRecord?.id ?? null,
|
||||
channelId: data.channelId ?? message.channelId ?? null,
|
||||
submitId,
|
||||
attempt,
|
||||
segmentTotal,
|
||||
segmentIndex,
|
||||
sequenceId: segment.sequenceId ?? data.sequenceId ?? null,
|
||||
gatewayMessageId: segment.gatewayMessageId ?? data.gatewayMessageId ?? null,
|
||||
submitStatus: status,
|
||||
compensationType: submitRecord && submitRecord.submitId !== message.submitId ? 'retry_submit' : null,
|
||||
errorCode: segment.errorCode ?? data.errorCode ?? null,
|
||||
errorMessage: segment.errorMessage ?? data.errorMessage ?? null,
|
||||
submittedAt: segment.submittedAt ? new Date(segment.submittedAt) : submittedAt,
|
||||
},
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
async findMessageByGatewayEvent(messageId?: string, gatewayMessageId?: string) {
|
||||
const conditions = [{ messageId }, gatewayMessageId ? { gatewayMessageId } : undefined].filter(
|
||||
Boolean,
|
||||
) as Array<{
|
||||
messageId?: string;
|
||||
gatewayMessageId?: string;
|
||||
}>;
|
||||
if (conditions.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return this.prisma.smsMessageRecord.findFirst({
|
||||
where: {
|
||||
OR: conditions,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async requireMessageByGatewayEvent(messageId?: string, gatewayMessageId?: string) {
|
||||
const message = await this.facade.findMessageByGatewayEvent(messageId, gatewayMessageId);
|
||||
if (!message) {
|
||||
throw new NotFoundException('SMS message record not found');
|
||||
}
|
||||
return message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
import { BadRequestException, HttpException, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { Queue, Worker } from 'bullmq';
|
||||
import IORedis from 'ioredis';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { isIpAllowed } from '../common/ip-allowlist';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import { PhoneRoutingLookupService } from '../dictionaries/phone-routing-lookup.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { RiskReviewService } from '../risk-review/risk-review.service';
|
||||
import { PhoneFrequencyService } from '../risk-review/phone-frequency.service';
|
||||
import type { CreateBatchTaskDto, CreateHttpBatchTaskDto, GatewayInboundAuthDto, GatewayInboundSubmitDto, GatewayInboundSingleSubmitResult, ImportPreviewDto, ConfirmImportDto, SendJob, QueuePriority, RoutedChannel } from './send-chain.contracts';
|
||||
import { SEND_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_SCHEDULED_DISPATCH_STALE_MS, DEFAULT_INBOUND_LONG_MESSAGE_PROCESSING_STALE_SECONDS, GATEWAY_SUBMIT_REQUEUE_IDEMPOTENCY_TTL_SECONDS, BULLMQ_PRIORITY, drainageRejectionReason, statusFromRisk, parseSchedule, parseImportRows, splitImportLine, cellByHeader, normalizeCarrier, normalizeQueuePriority, getPositiveConfigInteger, getNonNegativeConfigInteger, isCarrierCompatible, matchTemplateContent, isNationalChannel, validateInboundApplicationSrcId, composeUpstreamSrcId, positiveInteger, parseOptionalSequenceId, shanghaiDateKey, bullmqConnection, matchesApplicationSecret, octetString, selectChannelCandidate } from './send-chain.helpers';
|
||||
import type { SendSubmissionCallbacks, SendSubmissionService } from './send-submission.service';
|
||||
|
||||
/**
|
||||
* R9 gatewaySubmit implementation. Cross-method calls return through the stable SendChainService seam.
|
||||
*/
|
||||
export class SendGatewaySubmitService {
|
||||
private readonly logger = new Logger('SendChainService');
|
||||
private redis?: IORedis;
|
||||
private sendQueue?: Queue<SendJob, unknown, 'send-message'>;
|
||||
private gatewayQueue?: Queue;
|
||||
private worker?: Worker<SendJob>;
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly riskReview: RiskReviewService,
|
||||
private readonly phoneFrequency: PhoneFrequencyService,
|
||||
private readonly phoneRouting: PhoneRoutingLookupService,
|
||||
private readonly facade: SendSubmissionService,
|
||||
private readonly callbacks: SendSubmissionCallbacks,
|
||||
) {}
|
||||
|
||||
async onModuleDestroy() {
|
||||
await this.worker?.close();
|
||||
await this.sendQueue?.close();
|
||||
await this.gatewayQueue?.close();
|
||||
this.redis?.disconnect();
|
||||
}
|
||||
|
||||
private releaseMessageReservation(
|
||||
message: { tenantId: string; batchTaskId: string; messageId: string; amountCents: number | bigint; billingUnits: number },
|
||||
remark: string,
|
||||
) {
|
||||
return this.callbacks.releaseMessageReservation(message, remark);
|
||||
}
|
||||
|
||||
private recordCmppFailureReceipt(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
applicationId?: string | null;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
cmppSubmitSequenceId?: string | null;
|
||||
cmppSubmitGroupMessageId?: string | null;
|
||||
},
|
||||
errorCode: string,
|
||||
reason: string,
|
||||
) {
|
||||
return this.callbacks.recordCmppFailureReceipt(message, errorCode, reason);
|
||||
}
|
||||
|
||||
|
||||
async enqueueBatchTask(taskId: string) {
|
||||
const task = await this.prisma.smsBatchTask.findUnique({ where: { id: taskId } });
|
||||
if (!task) {
|
||||
throw new NotFoundException('SMS batch task not found');
|
||||
}
|
||||
if (task.status === 'canceled') {
|
||||
throw new BadRequestException('SMS batch task is canceled');
|
||||
}
|
||||
const messages = await this.prisma.smsMessageRecord.findMany({
|
||||
where: { batchTaskId: taskId, status: 'queued' },
|
||||
select: { id: true, queuePriority: true },
|
||||
take: 100000,
|
||||
});
|
||||
const queue = this.facade.getSendQueue();
|
||||
for (const message of messages) {
|
||||
const queuePriority = normalizeQueuePriority(message.queuePriority);
|
||||
await queue.add('send-message', { messageRecordId: message.id }, {
|
||||
jobId: message.id,
|
||||
attempts: 3,
|
||||
priority: BULLMQ_PRIORITY[queuePriority],
|
||||
});
|
||||
}
|
||||
await this.prisma.smsBatchTask.update({ where: { id: taskId }, data: { status: 'queued' } });
|
||||
return { taskId, enqueued: messages.length };
|
||||
}
|
||||
|
||||
startWorker() {
|
||||
if (this.worker) {
|
||||
return { status: 'already_started' };
|
||||
}
|
||||
const connection = bullmqConnection();
|
||||
this.worker = new Worker<SendJob>(
|
||||
SEND_QUEUE,
|
||||
async (job) => this.facade.processSendJob(job.data),
|
||||
{ connection, concurrency: Number(process.env.API_SEND_WORKER_CONCURRENCY ?? 20) },
|
||||
);
|
||||
return { status: 'started' };
|
||||
}
|
||||
|
||||
async processSendJob(job: SendJob) {
|
||||
const message = await this.prisma.smsMessageRecord.findUnique({
|
||||
where: { id: job.messageRecordId },
|
||||
include: { batchTask: true, template: { include: { signature: true } }, signature: true },
|
||||
});
|
||||
if (!message || message.status !== 'queued') {
|
||||
return { skipped: true };
|
||||
}
|
||||
if (!message.tenantId || !message.batchTaskId) {
|
||||
return { skipped: true, reason: 'standalone channel test message' };
|
||||
}
|
||||
const businessMessage = message as typeof message & { tenantId: string; batchTaskId: string };
|
||||
try {
|
||||
const routed = await this.facade.selectChannelForMessage(businessMessage);
|
||||
return await this.facade.submitMessageToGateway(businessMessage, routed, 0);
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : '无可用通道组或通道';
|
||||
await this.prisma.smsMessageRecord.update({
|
||||
where: { id: message.id },
|
||||
data: { status: 'failed', errorMessage: reason },
|
||||
});
|
||||
await this.releaseMessageReservation(businessMessage, reason);
|
||||
if (message.batchTask?.sourceType === 'cmpp') {
|
||||
await this.recordCmppFailureReceipt(businessMessage, 'ROUTE', reason);
|
||||
} else {
|
||||
await this.facade.refreshTaskProgress(businessMessage.batchTaskId);
|
||||
}
|
||||
return { submitted: false, messageRecordId: message.id, status: 'failed', reason };
|
||||
}
|
||||
}
|
||||
|
||||
async submitMessageToGateway(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
batchTaskId: string;
|
||||
applicationId?: string | null;
|
||||
templateId?: string | null;
|
||||
signatureId?: string | null;
|
||||
submitId?: string | null;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
content: string;
|
||||
billingUnits: number;
|
||||
queuePriority?: string | null;
|
||||
clientSrcId?: string | null;
|
||||
applicationExtension?: string | null;
|
||||
template?: { signature?: { id?: string | null; name?: string | null } | null } | null;
|
||||
signature?: { id?: string | null; name?: string | null } | null;
|
||||
},
|
||||
routed: RoutedChannel,
|
||||
attempt: number,
|
||||
retryOfSubmitRecordId?: string,
|
||||
) {
|
||||
const channel = routed.channel;
|
||||
const upstreamSrcId = composeUpstreamSrcId(channel.srcId, message.applicationExtension);
|
||||
await this.facade.ensureSignatureReportedForChannel(message, channel.id);
|
||||
await this.facade.waitForChannelRateLimit(channel.id, channel.rateLimitPerSecond);
|
||||
const submitId = `SUB-${randomUUID()}`;
|
||||
try {
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
const session = await tx.cmppSubmitSession.upsert({
|
||||
where: { sessionNo: `OPEN-${channel.id}` },
|
||||
update: { submitTotal: { increment: 1 } },
|
||||
create: { channelId: channel.id, sessionNo: `OPEN-${channel.id}`, submitTotal: 1 },
|
||||
});
|
||||
await tx.smsSubmitRecord.create({
|
||||
data: {
|
||||
tenantId: message.tenantId,
|
||||
batchTaskId: message.batchTaskId,
|
||||
messageRecordId: message.id,
|
||||
channelId: channel.id,
|
||||
channelGroupId: routed.groupId,
|
||||
channelGroupName: routed.groupName,
|
||||
sessionId: session.id,
|
||||
retryOfSubmitRecordId,
|
||||
submitId,
|
||||
submitStatus: 'queued',
|
||||
costUnitPrice: channel.unitPrice ?? 0,
|
||||
costAmountCents: moneyToNumber(channel.unitPrice) * Math.max(1, message.billingUnits ?? 1),
|
||||
},
|
||||
});
|
||||
await tx.smsMessageRecord.update({
|
||||
where: { id: message.id },
|
||||
data: {
|
||||
channelId: channel.id,
|
||||
carrier: routed.carrier,
|
||||
province: routed.province,
|
||||
submitId,
|
||||
status: 'submit_queued',
|
||||
submitStatus: 'queued',
|
||||
receiptStatus: null,
|
||||
errorCode: null,
|
||||
errorMessage: attempt > 0 ? `第 ${attempt + 1} 次提交,路由至${routed.routeScope === 'national' ? '全国' : '省网'}通道` : undefined,
|
||||
},
|
||||
});
|
||||
});
|
||||
if (retryOfSubmitRecordId) {
|
||||
this.logger.log(`sms_retry_claim_acquired ${JSON.stringify({
|
||||
messageId: message.messageId,
|
||||
messageRecordId: message.id,
|
||||
retryOfSubmitRecordId,
|
||||
submitId,
|
||||
channelId: channel.id,
|
||||
})}`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (
|
||||
retryOfSubmitRecordId
|
||||
&& error instanceof Prisma.PrismaClientKnownRequestError
|
||||
&& error.code === 'P2002'
|
||||
) {
|
||||
const existingRetry = await this.prisma.smsSubmitRecord.findUnique({
|
||||
where: { retryOfSubmitRecordId },
|
||||
});
|
||||
if (existingRetry) {
|
||||
this.logger.warn(`sms_retry_claim_reused ${JSON.stringify({
|
||||
messageId: message.messageId,
|
||||
messageRecordId: message.id,
|
||||
retryOfSubmitRecordId,
|
||||
submitId: existingRetry.submitId,
|
||||
channelId: existingRetry.channelId,
|
||||
})}`);
|
||||
return {
|
||||
submitted: false,
|
||||
duplicateRetry: true,
|
||||
messageRecordId: message.id,
|
||||
channelId: existingRetry.channelId,
|
||||
attempt,
|
||||
submitId: existingRetry.submitId,
|
||||
};
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const command = {
|
||||
schemaVersion: 'v1',
|
||||
messageType: 'SubmitCommand',
|
||||
traceId: randomUUID(),
|
||||
messageId: message.messageId,
|
||||
channelId: channel.id,
|
||||
createdAt: new Date().toISOString(),
|
||||
tenantId: message.tenantId,
|
||||
applicationId: message.applicationId ?? 'unknown',
|
||||
taskId: message.batchTaskId,
|
||||
submitId,
|
||||
queuePriority: normalizeQueuePriority(message.queuePriority),
|
||||
phoneNumber: message.phoneNumber,
|
||||
content: message.content,
|
||||
signature: message.template?.signature?.name ?? message.signature?.name ?? 'SMS',
|
||||
templateId: message.templateId ?? 'unknown',
|
||||
billingUnits: message.billingUnits,
|
||||
route: {
|
||||
channelCode: channel.code,
|
||||
cmppAccountCode: channel.account,
|
||||
priority: attempt,
|
||||
rateLimitPerSecond: channel.rateLimitPerSecond,
|
||||
carrier: routed.carrier,
|
||||
province: routed.province ?? undefined,
|
||||
scope: routed.routeScope,
|
||||
groupId: routed.groupId,
|
||||
},
|
||||
cmpp: {
|
||||
serviceId: channel.config && typeof channel.config === 'object' && 'serviceId' in channel.config
|
||||
? String(channel.config.serviceId)
|
||||
: 'SMS',
|
||||
srcId: upstreamSrcId,
|
||||
extensionDigits: getNonNegativeConfigInteger(channel.config, 'extensionDigits', 0),
|
||||
registeredDelivery: 1,
|
||||
msgFmt: 8,
|
||||
},
|
||||
upstream: {
|
||||
gatewayHost: channel.gatewayHost,
|
||||
gatewayPort: channel.gatewayPort,
|
||||
account: channel.account,
|
||||
passwordCipher: channel.passwordCipher,
|
||||
cmppVersion: channel.cmppVersion,
|
||||
desiredConnections: getPositiveConfigInteger(channel.config, 'desiredConnections', 1),
|
||||
windowSize: getPositiveConfigInteger(channel.config, 'windowSize', 16),
|
||||
heartbeatIntervalSeconds: getPositiveConfigInteger(channel.config, 'heartbeatIntervalSeconds', 30),
|
||||
heartbeatMissThreshold: getPositiveConfigInteger(channel.config, 'heartbeatMissThreshold', 3),
|
||||
},
|
||||
retry: { attempt, maxAttempts: 1 },
|
||||
};
|
||||
await this.facade.getGatewayQueue().add('submit-command', command);
|
||||
await this.facade.publishGatewaySubmitCommand(command);
|
||||
await this.facade.refreshTaskProgress(message.batchTaskId);
|
||||
return { submitted: true, messageRecordId: message.id, channelId: channel.id, attempt };
|
||||
}
|
||||
|
||||
async selectChannelForMessage(
|
||||
message: { id: string; tenantId: string; applicationId?: string | null; templateId?: string | null; signatureId?: string | null; phoneNumber: string; carrier?: string | null; province?: string | null; template?: { signature?: { id?: string | null } | null } | null; signature?: { id?: string | null } | null },
|
||||
options: { forceNational?: boolean; excludeChannelIds?: string[] } = {},
|
||||
): Promise<RoutedChannel> {
|
||||
if (!message.applicationId) {
|
||||
throw new BadRequestException('短信应用未配置,无法选择通道组');
|
||||
}
|
||||
const hasPersistedRouting = Boolean(message.carrier);
|
||||
const [carrier, province] = hasPersistedRouting
|
||||
? [normalizeCarrier(message.carrier), message.province ?? null]
|
||||
: await Promise.all([
|
||||
this.facade.identifyCarrier(message.phoneNumber),
|
||||
this.facade.identifyProvince(message.phoneNumber),
|
||||
]);
|
||||
if (!hasPersistedRouting) {
|
||||
await this.prisma.smsMessageRecord.update({
|
||||
where: { id: message.id },
|
||||
data: { carrier, province },
|
||||
});
|
||||
}
|
||||
const route = await this.facade.findApplicationRoute(message.tenantId, message.applicationId, carrier);
|
||||
const excluded = new Set(options.excludeChannelIds ?? []);
|
||||
const signatureId = await this.facade.resolveMessageSignatureId(message);
|
||||
if (!signatureId) throw new BadRequestException('短信签名未配置,无法选择已报备通道');
|
||||
const approvedTasks = await this.prisma.channelSignatureReportTask.findMany({
|
||||
where: { signatureId, reportType: 'signature', status: 'approved', channelId: { in: route.group.items.map((item) => item.channelId) } },
|
||||
select: { channelId: true },
|
||||
});
|
||||
const approvedChannelIds = new Set(approvedTasks.map((task) => task.channelId));
|
||||
const selected = selectChannelCandidate(route.group.items, {
|
||||
carrier,
|
||||
province,
|
||||
forceNational: options.forceNational,
|
||||
excludedChannelIds: excluded,
|
||||
approvedChannelIds,
|
||||
});
|
||||
if (!selected) {
|
||||
throw new NotFoundException('无已报备通过且在线的可用通道');
|
||||
}
|
||||
return {
|
||||
channel: { ...selected.channel, unitPrice: moneyToNumber(selected.channel.unitPrice) },
|
||||
carrier,
|
||||
province,
|
||||
groupId: route.groupId,
|
||||
groupName: route.group.name,
|
||||
routeScope: isNationalChannel(selected) ? 'national' : 'province',
|
||||
};
|
||||
}
|
||||
|
||||
async findApplicationRoute(tenantId: string, applicationId: string | undefined, carrier: string) {
|
||||
const route = await this.prisma.channelRouteRule.findFirst({
|
||||
where: {
|
||||
status: 'active',
|
||||
tenantId,
|
||||
applicationId,
|
||||
carrier,
|
||||
channelId: null,
|
||||
province: null,
|
||||
},
|
||||
include: { group: { include: { items: { include: { channel: { include: { connectionStates: true } } }, orderBy: { priority: 'asc' } } } } },
|
||||
orderBy: { priority: 'asc' },
|
||||
});
|
||||
if (!route) {
|
||||
throw new NotFoundException('企业应用未配置对应运营商通道组');
|
||||
}
|
||||
if (route.group.status !== 'active') {
|
||||
throw new BadRequestException('企业应用绑定的通道组已停用');
|
||||
}
|
||||
if (normalizeCarrier(route.group.carrier) !== carrier) {
|
||||
throw new BadRequestException('企业应用绑定的通道组运营商与路由规则不一致');
|
||||
}
|
||||
return route;
|
||||
}
|
||||
|
||||
async identifyCarrier(phoneNumber: string) {
|
||||
return normalizeCarrier(await this.phoneRouting.identifyCarrier(phoneNumber));
|
||||
}
|
||||
|
||||
async identifyProvince(phoneNumber: string) {
|
||||
return this.phoneRouting.identifyProvince(phoneNumber);
|
||||
}
|
||||
|
||||
async ensureSignatureReportedForChannel(
|
||||
message: {
|
||||
id: string;
|
||||
templateId?: string | null;
|
||||
template?: { signature?: { id?: string | null; name?: string | null } | null } | null;
|
||||
signature?: { id?: string | null; name?: string | null } | null;
|
||||
},
|
||||
channelId: string,
|
||||
) {
|
||||
const signatureId = await this.facade.resolveMessageSignatureId(message);
|
||||
if (!signatureId) {
|
||||
throw new BadRequestException('短信签名未配置,不能提交到通道');
|
||||
}
|
||||
const reportTask = await this.prisma.channelSignatureReportTask.findFirst({
|
||||
where: { signatureId, channelId, reportType: 'signature', status: 'approved' },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!reportTask) {
|
||||
throw new BadRequestException('短信签名未在最终通道报备通过');
|
||||
}
|
||||
}
|
||||
|
||||
async resolveMessageSignatureId(message: { templateId?: string | null; signatureId?: string | null; template?: { signature?: { id?: string | null } | null } | null; signature?: { id?: string | null } | null }) {
|
||||
const direct = message.signatureId ?? message.template?.signature?.id ?? message.signature?.id ?? null;
|
||||
if (direct || !message.templateId) return direct;
|
||||
const template = await this.prisma.smsTemplate.findUnique({ where: { id: message.templateId }, include: { signature: true } });
|
||||
return template?.signature?.id ?? null;
|
||||
}
|
||||
|
||||
async waitForChannelRateLimit(channelId: string, tps: number) {
|
||||
const redis = this.facade.getRedis();
|
||||
for (;;) {
|
||||
const bucket = `rate:channel:${channelId}:${Math.floor(Date.now() / 1000)}`;
|
||||
const count = await redis.incr(bucket);
|
||||
if (count === 1) {
|
||||
await redis.expire(bucket, 2);
|
||||
}
|
||||
if (count <= Math.max(1, tps)) {
|
||||
return;
|
||||
}
|
||||
await sleep(100);
|
||||
}
|
||||
}
|
||||
|
||||
async refreshTaskProgress(batchTaskId: string) {
|
||||
const groups = await this.prisma.smsMessageRecord.groupBy({
|
||||
by: ['status'],
|
||||
where: { batchTaskId },
|
||||
_count: { _all: true },
|
||||
});
|
||||
const count = (statuses: string[]) =>
|
||||
groups.filter((group) => statuses.includes(group.status)).reduce((sum, group) => sum + group._count._all, 0);
|
||||
const progressTotal = groups.reduce((sum, group) => sum + group._count._all, 0);
|
||||
const submittedTotal = count(['submit_queued', 'submitted', 'delivered', 'failed', 'unknown', 'timeout']);
|
||||
const successTotal = count(['delivered']);
|
||||
const failedTotal = count(['submit_failed', 'failed']);
|
||||
const unknownTotal = count(['unknown']);
|
||||
const timeoutTotal = count(['timeout']);
|
||||
const doneTotal = successTotal + failedTotal + timeoutTotal;
|
||||
const status = progressTotal > 0 && doneTotal >= progressTotal ? 'finished' : submittedTotal > 0 ? 'sending' : 'queued';
|
||||
await this.prisma.smsBatchTask.update({
|
||||
where: { id: batchTaskId },
|
||||
data: { progressTotal, submittedTotal, successTotal, failedTotal, unknownTotal, timeoutTotal, status },
|
||||
});
|
||||
}
|
||||
|
||||
getSendQueue(): Queue<SendJob, unknown, 'send-message'> {
|
||||
if (!this.sendQueue) {
|
||||
this.sendQueue = new Queue<SendJob, unknown, 'send-message'>(SEND_QUEUE, { connection: bullmqConnection() });
|
||||
}
|
||||
return this.sendQueue;
|
||||
}
|
||||
|
||||
getGatewayQueue(): Queue {
|
||||
if (!this.gatewayQueue) {
|
||||
this.gatewayQueue = new Queue(GATEWAY_SUBMIT_QUEUE, { connection: bullmqConnection() });
|
||||
}
|
||||
return this.gatewayQueue;
|
||||
}
|
||||
|
||||
getRedis() {
|
||||
if (!this.redis) {
|
||||
this.redis = new IORedis(process.env.REDIS_URL ?? 'redis://127.0.0.1:6379', {
|
||||
maxRetriesPerRequest: null,
|
||||
});
|
||||
}
|
||||
return this.redis;
|
||||
}
|
||||
|
||||
async publishGatewaySubmitCommand(command: unknown, idempotencyKey?: string) {
|
||||
const redis = this.facade.getRedis();
|
||||
const stream = process.env.GATEWAY_SUBMIT_STREAM ?? GATEWAY_SUBMIT_STREAM;
|
||||
const payload = JSON.stringify(command);
|
||||
if (!idempotencyKey) {
|
||||
return redis.xadd(stream, '*', 'messageType', 'SubmitCommand', 'data', payload);
|
||||
}
|
||||
const result = await redis.eval(
|
||||
`local existing = redis.call('GET', KEYS[2])
|
||||
if existing then return existing end
|
||||
local streamId = redis.call('XADD', KEYS[1], '*', 'messageType', 'SubmitCommand', 'data', ARGV[1])
|
||||
redis.call('SET', KEYS[2], streamId, 'EX', ARGV[2])
|
||||
return streamId`,
|
||||
2,
|
||||
stream,
|
||||
idempotencyKey,
|
||||
payload,
|
||||
String(GATEWAY_SUBMIT_REQUEUE_IDEMPOTENCY_TTL_SECONDS),
|
||||
);
|
||||
return typeof result === 'string' ? result : String(result ?? '');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,840 @@
|
||||
import { BadRequestException, HttpException, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { Queue, Worker } from 'bullmq';
|
||||
import IORedis from 'ioredis';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { isIpAllowed } from '../common/ip-allowlist';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import { PhoneRoutingLookupService } from '../dictionaries/phone-routing-lookup.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { RiskReviewService } from '../risk-review/risk-review.service';
|
||||
import { PhoneFrequencyService } from '../risk-review/phone-frequency.service';
|
||||
import type { CreateBatchTaskDto, CreateHttpBatchTaskDto, GatewayInboundAuthDto, GatewayInboundSubmitDto, GatewayInboundSingleSubmitResult, ImportPreviewDto, ConfirmImportDto, SendJob, QueuePriority, RoutedChannel } from './send-chain.contracts';
|
||||
import { SEND_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_SCHEDULED_DISPATCH_STALE_MS, DEFAULT_INBOUND_LONG_MESSAGE_PROCESSING_STALE_SECONDS, GATEWAY_SUBMIT_REQUEUE_IDEMPOTENCY_TTL_SECONDS, BULLMQ_PRIORITY, drainageRejectionReason, statusFromRisk, parseSchedule, parseImportRows, splitImportLine, cellByHeader, normalizeCarrier, normalizeQueuePriority, getPositiveConfigInteger, getNonNegativeConfigInteger, isCarrierCompatible, matchTemplateContent, isNationalChannel, validateInboundApplicationSrcId, composeUpstreamSrcId, positiveInteger, parseOptionalSequenceId, shanghaiDateKey, bullmqConnection, matchesApplicationSecret, octetString, selectChannelCandidate } from './send-chain.helpers';
|
||||
import type { SendSubmissionCallbacks, SendSubmissionService } from './send-submission.service';
|
||||
|
||||
/**
|
||||
* R9 inboundEntry implementation. Cross-method calls return through the stable SendChainService seam.
|
||||
*/
|
||||
export class SendInboundEntryService {
|
||||
private readonly logger = new Logger('SendChainService');
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly riskReview: RiskReviewService,
|
||||
private readonly phoneFrequency: PhoneFrequencyService,
|
||||
private readonly phoneRouting: PhoneRoutingLookupService,
|
||||
private readonly facade: SendSubmissionService,
|
||||
private readonly callbacks: SendSubmissionCallbacks,
|
||||
) {}
|
||||
|
||||
private releaseMessageReservation(
|
||||
message: { tenantId: string; batchTaskId: string; messageId: string; amountCents: number | bigint; billingUnits: number },
|
||||
remark: string,
|
||||
) {
|
||||
return this.callbacks.releaseMessageReservation(message, remark);
|
||||
}
|
||||
|
||||
private recordCmppFailureReceipt(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
applicationId?: string | null;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
cmppSubmitSequenceId?: string | null;
|
||||
cmppSubmitGroupMessageId?: string | null;
|
||||
},
|
||||
errorCode: string,
|
||||
reason: string,
|
||||
) {
|
||||
return this.callbacks.recordCmppFailureReceipt(message, errorCode, reason);
|
||||
}
|
||||
|
||||
|
||||
async authenticateInboundApplication(data: GatewayInboundAuthDto) {
|
||||
const application = await this.facade.findInboundApplication(data.account);
|
||||
if (!application || !['active', 'disabling'].includes(application.status) || application.tenant.status !== 'active') {
|
||||
throw new BadRequestException('CMPP account is invalid or disabled');
|
||||
}
|
||||
if (!application.interfaceEnabled) {
|
||||
throw new BadRequestException('CMPP interface is disabled for this application');
|
||||
}
|
||||
if (application.tenant.certificationStatus !== 'approved') {
|
||||
throw new BadRequestException('Enterprise certification is not approved');
|
||||
}
|
||||
if (!matchesApplicationSecret(data, application.secretHash)) {
|
||||
throw new BadRequestException('CMPP account or password is invalid');
|
||||
}
|
||||
if (data.remoteIp && !isIpAllowed(data.remoteIp, application.ipAllowlist.map((item) => item.ipCidr))) {
|
||||
throw new BadRequestException('CMPP source IP is not in application allowlist');
|
||||
}
|
||||
return {
|
||||
applicationId: application.id,
|
||||
tenantId: application.tenantId,
|
||||
account: application.cmppAccount,
|
||||
enterpriseCode: application.cmppEnterpriseCode,
|
||||
passwordCipher: application.secretHash,
|
||||
maxConnections: application.cmppMaxConnections,
|
||||
status: 'authenticated',
|
||||
};
|
||||
}
|
||||
|
||||
async submitInboundMessage(data: GatewayInboundSubmitDto) {
|
||||
const phoneNumbers = data.phoneNumbers?.length
|
||||
? data.phoneNumbers.map((phoneNumber) => phoneNumber.trim())
|
||||
: data.phoneNumber
|
||||
? [data.phoneNumber.trim()]
|
||||
: [];
|
||||
if (phoneNumbers.length === 0) {
|
||||
throw new BadRequestException('CMPP submit phone number is invalid');
|
||||
}
|
||||
|
||||
const application = await this.facade.findInboundApplication(data.account);
|
||||
if (!application) {
|
||||
throw new BadRequestException('CMPP account is invalid');
|
||||
}
|
||||
if (application.status !== 'active' || application.tenant.status !== 'active' || !application.interfaceEnabled) {
|
||||
throw new BadRequestException('CMPP account is disabled for new submissions');
|
||||
}
|
||||
if (data.longMessage) {
|
||||
if (data.remoteIp && !isIpAllowed(data.remoteIp, application.ipAllowlist.map((item) => item.ipCidr))) {
|
||||
throw new BadRequestException('CMPP source IP is not in application allowlist');
|
||||
}
|
||||
validateInboundApplicationSrcId(data.srcId, application);
|
||||
const collection = await this.facade.collectInboundLongMessageFragment(data, application, phoneNumbers);
|
||||
if (collection.response) {
|
||||
return collection.response;
|
||||
}
|
||||
if (!collection.complete) {
|
||||
return {
|
||||
accepted: true,
|
||||
tenantId: application.tenantId,
|
||||
applicationId: application.id,
|
||||
messageId: collection.messageId,
|
||||
status: 'fragment_pending',
|
||||
fragmentPending: true,
|
||||
receivedSegments: collection.receivedSegments,
|
||||
segmentTotal: data.longMessage.total,
|
||||
phoneCount: phoneNumbers.length,
|
||||
messages: phoneNumbers.map((phoneNumber) => ({
|
||||
phoneNumber,
|
||||
messageId: collection.messageId,
|
||||
status: 'fragment_pending',
|
||||
})),
|
||||
};
|
||||
}
|
||||
try {
|
||||
const response = await this.facade.recoverCompletedInboundLongMessageResponse(
|
||||
collection.messageId,
|
||||
phoneNumbers,
|
||||
) ?? await this.facade.submitCompleteInboundMessage({
|
||||
...data,
|
||||
content: collection.content,
|
||||
sequenceId: collection.sequenceId,
|
||||
longMessage: undefined,
|
||||
}, phoneNumbers, application, collection.messageId);
|
||||
await this.prisma.cmppInboundLongMessage.update({
|
||||
where: { id: collection.groupId },
|
||||
data: {
|
||||
status: 'completed',
|
||||
response: JSON.parse(JSON.stringify(response)) as Prisma.InputJsonValue,
|
||||
completedAt: new Date(),
|
||||
},
|
||||
});
|
||||
return response;
|
||||
} catch (error) {
|
||||
await this.prisma.cmppInboundLongMessage.update({
|
||||
where: { id: collection.groupId },
|
||||
data: {
|
||||
status: 'rejected',
|
||||
completedAt: new Date(),
|
||||
},
|
||||
}).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return this.facade.submitCompleteInboundMessage(data, phoneNumbers, application);
|
||||
}
|
||||
|
||||
async recoverCompletedInboundLongMessageResponse(messageId: string, phoneNumbers: string[]) {
|
||||
const existing = await this.prisma.smsMessageRecord.findMany({
|
||||
where: {
|
||||
cmppSubmitGroupMessageId: messageId,
|
||||
phoneNumber: { in: phoneNumbers },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
tenantId: true,
|
||||
applicationId: true,
|
||||
batchTaskId: true,
|
||||
messageId: true,
|
||||
phoneNumber: true,
|
||||
status: true,
|
||||
errorCode: true,
|
||||
},
|
||||
});
|
||||
const byPhone = new Map(existing.map((item) => [item.phoneNumber, item]));
|
||||
const ordered = phoneNumbers.map((phoneNumber) => byPhone.get(phoneNumber));
|
||||
if (ordered.some((item) => !item)) {
|
||||
return null;
|
||||
}
|
||||
const messages = ordered.map((item, index) => ({
|
||||
phoneNumber: phoneNumbers[index],
|
||||
messageId: item!.messageId,
|
||||
messageRecordId: item!.id,
|
||||
taskId: item!.batchTaskId ?? '',
|
||||
status: item!.status,
|
||||
}));
|
||||
const first = ordered[0]!;
|
||||
const dailyLimitRejected = ordered.every((item) => item!.errorCode === 'DAILY_LIMIT');
|
||||
return {
|
||||
accepted: !dailyLimitRejected,
|
||||
tenantId: first.tenantId ?? '',
|
||||
applicationId: first.applicationId ?? '',
|
||||
taskId: first.batchTaskId ?? '',
|
||||
messageId: first.messageId,
|
||||
messageRecordId: first.id,
|
||||
status: dailyLimitRejected ? 'rejected' : 'accepted',
|
||||
result: dailyLimitRejected ? 8 : undefined,
|
||||
phoneCount: messages.length,
|
||||
messages,
|
||||
};
|
||||
}
|
||||
|
||||
async submitCompleteInboundMessage(
|
||||
data: GatewayInboundSubmitDto,
|
||||
phoneNumbers: string[],
|
||||
application: Awaited<ReturnType<SendSubmissionService['findInboundApplication']>>,
|
||||
requestedGroupMessageId?: string,
|
||||
) {
|
||||
if (!application) {
|
||||
throw new BadRequestException('CMPP account is invalid');
|
||||
}
|
||||
const persisted = requestedGroupMessageId
|
||||
? await this.prisma.smsMessageRecord.findMany({
|
||||
where: {
|
||||
cmppSubmitGroupMessageId: requestedGroupMessageId,
|
||||
phoneNumber: { in: phoneNumbers },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
tenantId: true,
|
||||
applicationId: true,
|
||||
batchTaskId: true,
|
||||
messageId: true,
|
||||
phoneNumber: true,
|
||||
status: true,
|
||||
errorCode: true,
|
||||
},
|
||||
})
|
||||
: [];
|
||||
const persistedByPhone = new Map(persisted.map((item) => [item.phoneNumber, item]));
|
||||
const phoneRejections = await this.facade.classifyRejectedPhones(application.tenantId, application.id, phoneNumbers);
|
||||
const missingPhoneCount = phoneNumbers.filter((phoneNumber) => (
|
||||
!persistedByPhone.has(phoneNumber) && !phoneRejections.has(phoneNumber)
|
||||
)).length;
|
||||
const dailyQuota = missingPhoneCount > 0
|
||||
? await this.facade.tryReserveDailySendQuota(application.id, missingPhoneCount)
|
||||
: { reserved: true, dailyLimit: application.dailyLimit ?? 100000 };
|
||||
const dailyLimitRejection = dailyQuota.reserved
|
||||
? undefined
|
||||
: {
|
||||
code: 'DAILY_LIMIT',
|
||||
reason: `应用当日发送上限${dailyQuota.dailyLimit}条,本次${missingPhoneCount}条超出剩余配额`,
|
||||
};
|
||||
|
||||
const submitGroupMessageId = requestedGroupMessageId ?? `MSG-${randomUUID()}`;
|
||||
const submissions = phoneNumbers.map((phoneNumber, index) => ({
|
||||
phoneNumber,
|
||||
persisted: persistedByPhone.get(phoneNumber),
|
||||
receiptRejection: phoneRejections.get(phoneNumber),
|
||||
messageId: persistedByPhone.get(phoneNumber)?.messageId
|
||||
?? (index === 0 ? submitGroupMessageId : `MSG-${randomUUID()}`),
|
||||
}));
|
||||
const results: GatewayInboundSingleSubmitResult[] = [];
|
||||
const concurrency = 10;
|
||||
for (let offset = 0; offset < submissions.length; offset += concurrency) {
|
||||
const batch = submissions.slice(offset, offset + concurrency);
|
||||
results.push(...await Promise.all(batch.map((submission) => submission.persisted
|
||||
? Promise.resolve({
|
||||
accepted: submission.persisted.errorCode !== 'DAILY_LIMIT',
|
||||
tenantId: submission.persisted.tenantId ?? application.tenantId,
|
||||
applicationId: submission.persisted.applicationId ?? application.id,
|
||||
taskId: submission.persisted.batchTaskId ?? '',
|
||||
messageId: submission.persisted.messageId,
|
||||
messageRecordId: submission.persisted.id,
|
||||
status: submission.persisted.status,
|
||||
})
|
||||
: this.facade.submitInboundSingleMessage({
|
||||
...data,
|
||||
phoneNumber: submission.phoneNumber,
|
||||
phoneNumbers: undefined,
|
||||
}, submission.messageId, submitGroupMessageId, submission.receiptRejection ? undefined : dailyLimitRejection, submission.receiptRejection))));
|
||||
}
|
||||
const first = results[0];
|
||||
return {
|
||||
...first,
|
||||
result: dailyLimitRejection ? 8 : undefined,
|
||||
phoneCount: results.length,
|
||||
messages: results.map((result, index) => ({
|
||||
phoneNumber: phoneNumbers[index],
|
||||
messageId: result.messageId,
|
||||
messageRecordId: result.messageRecordId,
|
||||
taskId: result.taskId,
|
||||
status: result.status,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
async collectInboundLongMessageFragment(
|
||||
data: GatewayInboundSubmitDto,
|
||||
application: NonNullable<Awaited<ReturnType<SendSubmissionService['findInboundApplication']>>>,
|
||||
phoneNumbers: string[],
|
||||
) {
|
||||
const fragment = data.longMessage;
|
||||
if (!fragment || !Number.isInteger(fragment.reference) || fragment.reference < 0 || fragment.reference > 65535
|
||||
|| !Number.isInteger(fragment.total) || fragment.total < 2 || fragment.total > 255
|
||||
|| !Number.isInteger(fragment.index) || fragment.index < 1 || fragment.index > fragment.total
|
||||
|| !Number.isInteger(fragment.format) || fragment.format < 0 || fragment.format > 255) {
|
||||
throw new BadRequestException('CMPP long message fragment metadata is invalid');
|
||||
}
|
||||
const groupKey = createHash('sha256').update(JSON.stringify({
|
||||
applicationId: application.id,
|
||||
account: data.account,
|
||||
srcId: data.srcId?.trim() ?? '',
|
||||
phoneNumbers,
|
||||
reference: fragment.reference,
|
||||
total: fragment.total,
|
||||
format: fragment.format,
|
||||
})).digest('hex');
|
||||
const contentHash = createHash('sha256').update(data.content).digest('hex');
|
||||
const now = new Date();
|
||||
const expiresAt = new Date(now.getTime() + positiveInteger(
|
||||
process.env.CMPP_INBOUND_LONG_MESSAGE_TTL_SECONDS,
|
||||
300,
|
||||
) * 1000);
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${groupKey}, 0))`;
|
||||
await tx.cmppInboundLongMessage.updateMany({
|
||||
where: {
|
||||
groupKey,
|
||||
status: { in: ['collecting', 'processing'] },
|
||||
expiresAt: { lte: now },
|
||||
},
|
||||
data: { status: 'expired', completedAt: now },
|
||||
});
|
||||
|
||||
const recent = await tx.cmppInboundLongMessage.findFirst({
|
||||
where: {
|
||||
groupKey,
|
||||
expiresAt: { gt: now },
|
||||
},
|
||||
include: { segments: { orderBy: { segmentIndex: 'asc' } } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
const matchingRecentSegment = recent?.segments.find((item) => item.segmentIndex === fragment.index);
|
||||
if (recent && ['completed', 'rejected'].includes(recent.status)
|
||||
&& matchingRecentSegment?.contentHash === contentHash
|
||||
&& matchingRecentSegment.sequenceId === (data.sequenceId == null ? null : String(data.sequenceId))) {
|
||||
return {
|
||||
complete: recent.status === 'completed',
|
||||
groupId: recent.id,
|
||||
messageId: recent.messageId,
|
||||
receivedSegments: recent.segments.length,
|
||||
response: recent.response as any,
|
||||
content: recent.segments.map((item) => item.content).join(''),
|
||||
sequenceId: parseOptionalSequenceId(recent.segments[0]?.sequenceId),
|
||||
};
|
||||
}
|
||||
|
||||
let group = recent && ['collecting', 'processing'].includes(recent.status) ? recent : null;
|
||||
if (!group) {
|
||||
group = await tx.cmppInboundLongMessage.create({
|
||||
data: {
|
||||
tenantId: application.tenantId,
|
||||
applicationId: application.id,
|
||||
groupKey,
|
||||
account: data.account,
|
||||
srcId: data.srcId?.trim() || null,
|
||||
phoneNumbers,
|
||||
concatReference: fragment.reference,
|
||||
segmentTotal: fragment.total,
|
||||
msgFmt: fragment.format,
|
||||
messageId: `MSG-${randomUUID()}`,
|
||||
expiresAt,
|
||||
},
|
||||
include: { segments: { orderBy: { segmentIndex: 'asc' } } },
|
||||
});
|
||||
}
|
||||
if (group.status === 'processing') {
|
||||
const processingStaleMs = positiveInteger(
|
||||
process.env.CMPP_INBOUND_LONG_MESSAGE_PROCESSING_STALE_SECONDS,
|
||||
DEFAULT_INBOUND_LONG_MESSAGE_PROCESSING_STALE_SECONDS,
|
||||
) * 1000;
|
||||
const complete = group.segments.length === fragment.total
|
||||
&& group.segments.every((item, index) => item.segmentIndex === index + 1);
|
||||
if (complete && now.getTime() - group.updatedAt.getTime() >= processingStaleMs) {
|
||||
await tx.cmppInboundLongMessage.update({
|
||||
where: { id: group.id },
|
||||
data: { status: 'processing', expiresAt },
|
||||
});
|
||||
return {
|
||||
complete: true,
|
||||
groupId: group.id,
|
||||
messageId: group.messageId,
|
||||
receivedSegments: group.segments.length,
|
||||
response: null,
|
||||
content: group.segments.map((item) => item.content).join(''),
|
||||
sequenceId: parseOptionalSequenceId(group.segments[0]?.sequenceId),
|
||||
};
|
||||
}
|
||||
return {
|
||||
complete: false,
|
||||
groupId: group.id,
|
||||
messageId: group.messageId,
|
||||
receivedSegments: group.segments.length,
|
||||
response: group.response as any,
|
||||
content: '',
|
||||
sequenceId: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const existing = group.segments.find((item) => item.segmentIndex === fragment.index);
|
||||
if (existing && (existing.contentHash !== contentHash
|
||||
|| existing.sequenceId !== (data.sequenceId == null ? null : String(data.sequenceId)))) {
|
||||
throw new BadRequestException(`CMPP long message fragment ${fragment.index} conflicts with the stored fragment`);
|
||||
}
|
||||
if (!existing) {
|
||||
await tx.cmppInboundLongMessageSegment.create({
|
||||
data: {
|
||||
groupId: group.id,
|
||||
segmentIndex: fragment.index,
|
||||
sequenceId: data.sequenceId == null ? null : String(data.sequenceId),
|
||||
content: data.content,
|
||||
contentHash,
|
||||
},
|
||||
});
|
||||
}
|
||||
const segments = await tx.cmppInboundLongMessageSegment.findMany({
|
||||
where: { groupId: group.id },
|
||||
orderBy: { segmentIndex: 'asc' },
|
||||
});
|
||||
const complete = segments.length === fragment.total
|
||||
&& segments.every((item, index) => item.segmentIndex === index + 1);
|
||||
if (complete) {
|
||||
await tx.cmppInboundLongMessage.update({
|
||||
where: { id: group.id },
|
||||
data: { status: 'processing', expiresAt },
|
||||
});
|
||||
}
|
||||
return {
|
||||
complete,
|
||||
groupId: group.id,
|
||||
messageId: group.messageId,
|
||||
receivedSegments: segments.length,
|
||||
response: null,
|
||||
content: complete ? segments.map((item) => item.content).join('') : '',
|
||||
sequenceId: parseOptionalSequenceId(segments[0]?.sequenceId),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async expireInboundLongMessages(now = new Date()) {
|
||||
return this.prisma.cmppInboundLongMessage.updateMany({
|
||||
where: {
|
||||
status: { in: ['collecting', 'processing'] },
|
||||
expiresAt: { lte: now },
|
||||
},
|
||||
data: {
|
||||
status: 'expired',
|
||||
completedAt: now,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async submitInboundSingleMessage(
|
||||
data: GatewayInboundSubmitDto & { phoneNumber: string },
|
||||
messageId: string,
|
||||
submitGroupMessageId: string,
|
||||
synchronousRejection?: { code: string; reason: string },
|
||||
receiptRejection?: { code: string; reason: string },
|
||||
) {
|
||||
const application = await this.facade.findInboundApplication(data.account);
|
||||
if (!application) {
|
||||
throw new BadRequestException('CMPP account is invalid');
|
||||
}
|
||||
if (data.remoteIp && !isIpAllowed(data.remoteIp, application.ipAllowlist.map((item) => item.ipCidr))) {
|
||||
throw new BadRequestException('CMPP source IP is not in application allowlist');
|
||||
}
|
||||
const clientSrcId = validateInboundApplicationSrcId(data.srcId, application);
|
||||
const template = await this.facade.resolveInboundTemplateCandidate(application.id, data.content);
|
||||
const templateVariables = template ? matchTemplateContent(template.content, data.content) ?? {} : {};
|
||||
const unitPrice = moneyToNumber(application.customerUnitPrice);
|
||||
const queuePriority = normalizeQueuePriority(application.queuePriority);
|
||||
const billing = this.billing.estimateSmsCost({
|
||||
tenantId: application.tenantId,
|
||||
applicationId: application.id,
|
||||
content: data.content,
|
||||
phoneCount: 1,
|
||||
unitPrice,
|
||||
});
|
||||
const task = await this.prisma.smsBatchTask.create({
|
||||
data: {
|
||||
tenantId: application.tenantId,
|
||||
applicationId: application.id,
|
||||
templateId: template?.id,
|
||||
taskNo: `BT-${Date.now()}-${randomUUID().slice(0, 8)}`,
|
||||
sourceType: 'cmpp',
|
||||
content: data.content,
|
||||
phoneTotal: 1,
|
||||
status: synchronousRejection ? 'rejected' : 'validating',
|
||||
auditStatus: synchronousRejection ? 'rejected' : undefined,
|
||||
rejectReason: synchronousRejection?.reason,
|
||||
progressTotal: 1,
|
||||
},
|
||||
});
|
||||
await this.prisma.smsApiRequest.create({
|
||||
data: {
|
||||
tenantId: application.tenantId,
|
||||
batchTaskId: task.id,
|
||||
requestId: `REQ-${Date.now()}-${randomUUID().slice(0, 8)}`,
|
||||
sourceIp: data.remoteIp,
|
||||
userAgent: 'cmpp-gateway',
|
||||
payloadSummary: { phoneTotal: 1, contentLength: [...data.content].length, account: data.account },
|
||||
status: synchronousRejection ? 'rejected' : 'accepted',
|
||||
},
|
||||
});
|
||||
const message = await this.prisma.smsMessageRecord.create({
|
||||
data: {
|
||||
tenantId: application.tenantId,
|
||||
batchTaskId: task.id,
|
||||
applicationId: application.id,
|
||||
templateId: template?.id,
|
||||
messageId,
|
||||
phoneNumber: data.phoneNumber,
|
||||
content: data.content,
|
||||
billingUnits: billing.billingUnitsPerMessage,
|
||||
unitPrice: receiptRejection ? 0 : billing.unitPrice,
|
||||
amountCents: receiptRejection ? 0 : billing.amountCents,
|
||||
queuePriority,
|
||||
cmppSubmitSequenceId: data.sequenceId == null ? null : String(data.sequenceId),
|
||||
cmppSubmitGroupMessageId: submitGroupMessageId,
|
||||
clientSrcId,
|
||||
applicationExtension: application.cmppApplicationExtension,
|
||||
status: synchronousRejection ? 'rejected' : 'validating',
|
||||
errorCode: synchronousRejection?.code,
|
||||
errorMessage: synchronousRejection?.reason,
|
||||
},
|
||||
});
|
||||
|
||||
if (synchronousRejection) {
|
||||
return {
|
||||
accepted: false,
|
||||
tenantId: application.tenantId,
|
||||
applicationId: application.id,
|
||||
taskId: task.id,
|
||||
messageId: message.messageId,
|
||||
messageRecordId: message.id,
|
||||
status: 'rejected',
|
||||
};
|
||||
}
|
||||
|
||||
const reject = async (code: string, reason: string) => {
|
||||
await this.prisma.smsBatchTask.update({
|
||||
where: { id: task.id },
|
||||
data: { status: 'rejected', auditStatus: 'rejected', rejectReason: reason },
|
||||
});
|
||||
await this.recordCmppFailureReceipt(message, code, reason);
|
||||
};
|
||||
const queueAfterRiskChecks = async (options: { templateId?: string; signatureId?: string }) => {
|
||||
const drainage = await this.facade.resolveDrainageInfoMatch(options.signatureId, data.content);
|
||||
const drainageInfoId = drainage?.id;
|
||||
const drainageReason = drainageRejectionReason(drainage);
|
||||
if (drainageReason) {
|
||||
await this.prisma.smsMessageRecord.update({
|
||||
where: { id: message.id },
|
||||
data: { drainageInfoId, signatureId: options.signatureId },
|
||||
});
|
||||
await reject('DRAINAGE_NOT_APPROVED', drainageReason);
|
||||
return;
|
||||
}
|
||||
const risk = await this.facade.evaluateRiskWithPhoneFrequency({
|
||||
tenantId: application.tenantId,
|
||||
applicationId: application.id,
|
||||
templateId: options.templateId,
|
||||
content: data.content,
|
||||
variables: options.templateId ? templateVariables : undefined,
|
||||
phoneNumber: data.phoneNumber,
|
||||
sourceType: 'cmpp',
|
||||
});
|
||||
if (risk.status === 'rejected') {
|
||||
await reject('RISK', risk.reason || '短信被风控拒绝');
|
||||
return;
|
||||
}
|
||||
if (risk.status === 'pending_review') {
|
||||
await this.prisma.smsMessageRecord.update({
|
||||
where: { id: message.id },
|
||||
data: {
|
||||
status: 'pending_review',
|
||||
reviewTaskId: risk.task?.id,
|
||||
signatureId: options.signatureId,
|
||||
drainageInfoId,
|
||||
},
|
||||
});
|
||||
await this.prisma.smsBatchTask.update({
|
||||
where: { id: task.id },
|
||||
data: { status: 'pending_review', riskTaskId: risk.task?.id, auditStatus: 'pending', reviewReason: risk.reason },
|
||||
});
|
||||
return;
|
||||
}
|
||||
const accountCheck = await this.billing.checkAccount({
|
||||
tenantId: application.tenantId,
|
||||
amountCents: billing.amountCents,
|
||||
});
|
||||
if (!accountCheck.canSend) {
|
||||
await reject('BALANCE', '企业账户余额不足');
|
||||
return;
|
||||
}
|
||||
if (billing.amountCents > 0) {
|
||||
await this.billing.freeze({
|
||||
tenantId: application.tenantId,
|
||||
amountCents: billing.amountCents,
|
||||
relatedType: 'sms_batch_task',
|
||||
relatedId: task.id,
|
||||
remark: 'CMPP 入站短信冻结',
|
||||
});
|
||||
}
|
||||
await this.prisma.smsMessageRecord.update({
|
||||
where: { id: message.id },
|
||||
data: { status: 'queued', signatureId: options.signatureId, drainageInfoId },
|
||||
});
|
||||
await this.prisma.smsBatchTask.update({
|
||||
where: { id: task.id },
|
||||
data: { status: 'ready', riskTaskId: risk.task?.id, auditStatus: 'approved' },
|
||||
});
|
||||
await this.facade.enqueueBatchTask(task.id);
|
||||
};
|
||||
if (receiptRejection) {
|
||||
await reject(receiptRejection.code, receiptRejection.reason);
|
||||
} else if (application.status !== 'active' || application.tenant.status !== 'active') {
|
||||
await reject('ACCOUNT', '企业或短信应用已停用');
|
||||
} else if (!application.interfaceEnabled) {
|
||||
await reject('INTERFACE', '短信应用 CMPP 接口已停用');
|
||||
} else if (application.tenant.certificationStatus !== 'approved') {
|
||||
await reject('CERT', '企业认证未通过');
|
||||
} else if (!template && application.templateMismatchMode === 'manual_review') {
|
||||
const signature = await this.facade.resolveInboundSignatureCandidate(application.id, data.content);
|
||||
if (!signature) {
|
||||
await reject('SIGNATURE', '短信内容未识别到已审核通过的签名');
|
||||
} else {
|
||||
const drainage = await this.facade.resolveDrainageInfoMatch(signature.id, data.content);
|
||||
const drainageReason = drainageRejectionReason(drainage);
|
||||
if (drainageReason) {
|
||||
await this.prisma.smsMessageRecord.update({
|
||||
where: { id: message.id },
|
||||
data: { drainageInfoId: drainage?.id, signatureId: signature.id },
|
||||
});
|
||||
await reject('DRAINAGE_NOT_APPROVED', drainageReason);
|
||||
return {
|
||||
accepted: true,
|
||||
tenantId: application.tenantId,
|
||||
applicationId: application.id,
|
||||
messageId,
|
||||
messageRecordId: message.id,
|
||||
taskId: task.id,
|
||||
status: 'rejected',
|
||||
};
|
||||
}
|
||||
const risk = await this.facade.evaluateRiskWithPhoneFrequency({
|
||||
tenantId: application.tenantId,
|
||||
applicationId: application.id,
|
||||
content: data.content,
|
||||
phoneNumber: data.phoneNumber,
|
||||
sourceType: 'cmpp',
|
||||
});
|
||||
if (risk.status === 'rejected') {
|
||||
await reject('RISK', risk.reason || '短信被风控拒绝');
|
||||
} else {
|
||||
const accountCheck = await this.billing.checkAccount({
|
||||
tenantId: application.tenantId,
|
||||
amountCents: billing.amountCents,
|
||||
});
|
||||
if (!accountCheck.canSend) {
|
||||
await reject('BALANCE', '企业账户余额不足');
|
||||
} else {
|
||||
if (billing.amountCents > 0) {
|
||||
await this.billing.freeze({
|
||||
tenantId: application.tenantId,
|
||||
amountCents: billing.amountCents,
|
||||
relatedType: 'sms_batch_task',
|
||||
relatedId: task.id,
|
||||
remark: 'CMPP 模板不匹配待审核短信冻结',
|
||||
});
|
||||
}
|
||||
const reviewTask = risk.status === 'pending_review' && risk.task
|
||||
? await this.facade.attachMessageToReviewTask(risk.task.id, message.id, signature.id, drainage?.id)
|
||||
: await this.riskReview.aggregateTemplateMismatch({
|
||||
tenantId: application.tenantId,
|
||||
applicationId: application.id,
|
||||
account: data.account,
|
||||
messageRecordId: message.id,
|
||||
signatureId: signature.id,
|
||||
content: data.content,
|
||||
});
|
||||
await this.prisma.smsBatchTask.update({
|
||||
where: { id: task.id },
|
||||
data: {
|
||||
status: 'pending_review',
|
||||
riskTaskId: reviewTask?.id,
|
||||
auditStatus: 'pending',
|
||||
reviewReason: reviewTask?.reviewReason ?? '模板不匹配,等待人工审核',
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (!template && application.templateMismatchMode === 'direct_send') {
|
||||
const signature = await this.facade.resolveInboundSignatureCandidate(application.id, data.content);
|
||||
if (!signature) {
|
||||
await reject('SIGNATURE', '短信内容未识别到已审核通过的签名');
|
||||
} else {
|
||||
await queueAfterRiskChecks({ signatureId: signature.id });
|
||||
}
|
||||
} else if (!template) {
|
||||
await reject('TEMPLATE', '短信内容未匹配到已报备模板');
|
||||
} else if (template.auditStatus !== 'approved') {
|
||||
await reject('TEMPLATE', '短信模板尚未审核通过');
|
||||
} else if (!template.signature || template.signature.auditStatus !== 'approved') {
|
||||
await reject('SIGNATURE', '短信签名尚未审核通过');
|
||||
} else {
|
||||
await queueAfterRiskChecks({ templateId: template.id, signatureId: template.signature.id });
|
||||
}
|
||||
return {
|
||||
accepted: true,
|
||||
tenantId: application.tenantId,
|
||||
applicationId: application.id,
|
||||
taskId: task.id,
|
||||
messageId: message.messageId,
|
||||
messageRecordId: message.id,
|
||||
status: 'accepted',
|
||||
};
|
||||
}
|
||||
|
||||
async evaluateRiskWithPhoneFrequency(input: {
|
||||
tenantId: string;
|
||||
applicationId: string;
|
||||
templateId?: string;
|
||||
content: string;
|
||||
variables?: Record<string, unknown>;
|
||||
phoneNumber: string;
|
||||
sourceType: 'cmpp';
|
||||
}) {
|
||||
const risk = await this.riskReview.evaluateTask({
|
||||
tenantId: input.tenantId,
|
||||
applicationId: input.applicationId,
|
||||
templateId: input.templateId,
|
||||
content: input.content,
|
||||
variables: input.variables,
|
||||
phones: [input.phoneNumber],
|
||||
sourceType: input.sourceType,
|
||||
});
|
||||
if (risk.status === 'rejected') return risk;
|
||||
const frequencyRejections = await this.phoneFrequency.reserve(
|
||||
input.tenantId,
|
||||
input.applicationId,
|
||||
[input.phoneNumber],
|
||||
input.sourceType,
|
||||
);
|
||||
const rejection = frequencyRejections.get(input.phoneNumber);
|
||||
return rejection
|
||||
? { ...risk, status: 'rejected' as const, reason: rejection.reason }
|
||||
: risk;
|
||||
}
|
||||
|
||||
findInboundApplication(account: string) {
|
||||
return this.prisma.smsApplication.findFirst({
|
||||
where: { cmppAccount: account },
|
||||
include: {
|
||||
tenant: true,
|
||||
ipAllowlist: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async resolveInboundTemplateCandidate(applicationId: string, content: string) {
|
||||
const exact = await this.prisma.smsTemplate.findFirst({
|
||||
where: {
|
||||
applicationId,
|
||||
content,
|
||||
auditStatus: 'approved',
|
||||
signature: { auditStatus: 'approved' },
|
||||
},
|
||||
include: { signature: true },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
});
|
||||
if (exact) return exact;
|
||||
const variableTemplates = await this.prisma.smsTemplate.findMany({
|
||||
where: {
|
||||
applicationId,
|
||||
content: { contains: '${' },
|
||||
auditStatus: 'approved',
|
||||
signature: { auditStatus: 'approved' },
|
||||
},
|
||||
include: { signature: true },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
});
|
||||
return variableTemplates.find((template) => matchTemplateContent(template.content, content) !== null) ?? null;
|
||||
}
|
||||
|
||||
resolveInboundSignatureCandidate(applicationId: string, content: string) {
|
||||
const match = content.match(/^【[^】]+】/);
|
||||
if (!match?.[0]) return null;
|
||||
return this.prisma.smsSignature.findFirst({
|
||||
where: {
|
||||
applicationId,
|
||||
name: match[0],
|
||||
auditStatus: 'approved',
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
async resolveDrainageInfoMatch(signatureId: string | null | undefined, content: string) {
|
||||
if (!signatureId) return undefined;
|
||||
const candidates = await this.prisma.smsDrainageInfo.findMany({
|
||||
where: { signatureId, auditStatus: { not: 'deleted' } },
|
||||
select: { id: true, url: true, auditStatus: true, updatedAt: true },
|
||||
orderBy: [{ updatedAt: 'desc' }, { id: 'asc' }],
|
||||
});
|
||||
const matches = candidates
|
||||
.map((item) => ({ ...item, normalizedUrl: item.url.trim() }))
|
||||
.filter((item) => item.normalizedUrl.length > 0 && content.includes(item.normalizedUrl))
|
||||
.sort((left, right) => right.normalizedUrl.length - left.normalizedUrl.length || right.updatedAt.getTime() - left.updatedAt.getTime());
|
||||
if (matches.length === 0) return undefined;
|
||||
const longestLength = matches[0].normalizedUrl.length;
|
||||
const longestMatches = matches.filter((item) => item.normalizedUrl.length === longestLength);
|
||||
if (longestMatches.length !== 1) {
|
||||
throw new BadRequestException({
|
||||
code: 'DRAINAGE_MATCH_AMBIGUOUS',
|
||||
message: '短信内容同时匹配多条等长引流地址,无法确定报备资料',
|
||||
drainageInfoIds: longestMatches.map((item) => item.id),
|
||||
});
|
||||
}
|
||||
const matched = longestMatches[0];
|
||||
return { id: matched.id, auditStatus: matched.auditStatus };
|
||||
}
|
||||
|
||||
async attachMessageToReviewTask(reviewTaskId: string, messageRecordId: string, signatureId: string, drainageInfoId?: string) {
|
||||
await this.prisma.smsMessageRecord.update({
|
||||
where: { id: messageRecordId },
|
||||
data: { reviewTaskId, signatureId, drainageInfoId, status: 'pending_review' },
|
||||
});
|
||||
return this.prisma.smsSendTask.findUnique({ where: { id: reviewTaskId } });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,593 @@
|
||||
import { BadRequestException, HttpException, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import type { OpenApiService } from '../open-api/open-api.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { GatewaySubmitResultDto, GatewaySubmitSegmentResultDto, GatewayReceiptEventDto, GatewayUplinkEventDto, GatewayPendingDeliveryQueryDto, GatewayDownstreamSentDto, GatewayDownstreamAcknowledgedDto, GatewayDownstreamFailureType, GatewayControlDeliveryResult, GatewaySubmitDeadLetterDto, RequeueGatewaySubmitExceptionDto, GatewayDownstreamRecoveryStatusDto, TimeoutUnknownDto } from './send-chain.contracts';
|
||||
import { positiveInteger, normalizeReceiptStatus, normalizeCarrier, DEFAULT_DOWNSTREAM_RETRY_DELAY_MS, DEFAULT_DOWNSTREAM_RETRY_MAX_DELAY_MS, DEFAULT_DOWNSTREAM_MAX_RETRIES, DEFAULT_DOWNSTREAM_PENDING_TIMEOUT_HOURS, DEFAULT_RECEIPT_TIMEOUT_HOURS, DEFAULT_GATEWAY_SUBMIT_REQUEUE_STALE_MS, DEFAULT_DOWNSTREAM_MANUAL_REQUEUE_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_ATTEMPTS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_AGE_HOURS, gatewaySubmitRequeueKey, isObjectRecord, asDateOrNull, downstreamRetryDelayMs, downstreamAckTimeoutMs, downstreamRetryBaseDelayMs, downstreamRetryMaxDelayMs, downstreamMaxRetries, downstreamPendingTimeoutHours, downstreamControlFailureMessage, normalizeSubmitStatus, downstreamDeliveryAttemptKey, hasRecoveryAuditStateChanged, normalizeRecoveryFailureCategory, aggregateReceiptSegmentState, isSameUpstreamEndpointIdentity, receiptEventKey } from './send-chain.helpers';
|
||||
import type { SendSubmissionService } from './send-submission.service';
|
||||
import type { SendCompletionCallbacks, SendCompletionFacade } from './send-completion.service';
|
||||
|
||||
|
||||
/**
|
||||
* R10 receipt implementation.
|
||||
* Cross-domain calls return through the stable SendChainService seam to preserve locking and test observability.
|
||||
*/
|
||||
export class SendReceiptService {
|
||||
private readonly logger = new Logger('SendChainService');
|
||||
private upstreamReceiptInboxScanRunning = false;
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly openApi: OpenApiService | undefined,
|
||||
private readonly facade: SendCompletionFacade,
|
||||
private readonly callbacks: SendCompletionCallbacks,
|
||||
) {}
|
||||
|
||||
async intakeReceipt(data: GatewayReceiptEventDto) {
|
||||
const channel = await this.prisma.smsChannel.findUnique({
|
||||
where: { id: data.channelId },
|
||||
select: {
|
||||
id: true,
|
||||
account: true,
|
||||
gatewayHost: true,
|
||||
gatewayPort: true,
|
||||
protocol: true,
|
||||
cmppVersion: true,
|
||||
},
|
||||
});
|
||||
if (!channel) {
|
||||
throw new NotFoundException('SMS channel not found');
|
||||
}
|
||||
const deliveredAt = data.deliveredAt ? new Date(data.deliveredAt) : new Date();
|
||||
const receiptKey = receiptEventKey(data, data.channelId);
|
||||
const inbox = await this.prisma.upstreamReceiptInbox.upsert({
|
||||
where: { receiptKey },
|
||||
update: {
|
||||
incomingConnectionId: data.connectionId,
|
||||
},
|
||||
create: {
|
||||
receiptKey,
|
||||
incomingChannelId: data.channelId,
|
||||
incomingConnectionId: data.connectionId,
|
||||
upstreamAccount: channel.account,
|
||||
upstreamHost: channel.gatewayHost,
|
||||
upstreamPort: channel.gatewayPort,
|
||||
protocol: channel.protocol,
|
||||
protocolVersion: channel.cmppVersion,
|
||||
provisionalMessageId: data.messageId,
|
||||
sequenceId: data.sequenceId,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
phoneNumber: data.phoneNumber?.trim() || null,
|
||||
receiptStatus: data.receiptStatus,
|
||||
rawStatus: data.rawStatus,
|
||||
errorCode: data.errorCode,
|
||||
errorMessage: data.errorMessage,
|
||||
deliveredAt,
|
||||
status: 'pending',
|
||||
nextRetryAt: new Date(),
|
||||
},
|
||||
});
|
||||
if (['pending', 'retrying'].includes(inbox.status)) {
|
||||
setImmediate(() => void this.facade.processUpstreamReceiptInboxRecord(inbox.id));
|
||||
}
|
||||
return { accepted: true, inboxId: inbox.id, status: inbox.status };
|
||||
}
|
||||
|
||||
async processPendingUpstreamReceiptInbox(limit = 100) {
|
||||
const now = new Date();
|
||||
const staleBefore = new Date(
|
||||
now.getTime()
|
||||
- positiveInteger(
|
||||
process.env.UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS,
|
||||
DEFAULT_UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS,
|
||||
),
|
||||
);
|
||||
const candidates = await this.prisma.upstreamReceiptInbox.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{
|
||||
status: { in: ['pending', 'retrying'] },
|
||||
OR: [{ nextRetryAt: null }, { nextRetryAt: { lte: now } }],
|
||||
},
|
||||
{ status: 'processing', updatedAt: { lte: staleBefore } },
|
||||
],
|
||||
},
|
||||
orderBy: [{ receivedAt: 'asc' }, { id: 'asc' }],
|
||||
take: Math.min(Math.max(limit, 1), 500),
|
||||
select: { id: true },
|
||||
});
|
||||
let processed = 0;
|
||||
for (const candidate of candidates) {
|
||||
if (await this.facade.processUpstreamReceiptInboxRecord(candidate.id)) processed += 1;
|
||||
}
|
||||
return { scanned: candidates.length, processed };
|
||||
}
|
||||
|
||||
async processUpstreamReceiptInboxRecord(id: string) {
|
||||
const staleBefore = new Date(
|
||||
Date.now()
|
||||
- positiveInteger(
|
||||
process.env.UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS,
|
||||
DEFAULT_UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS,
|
||||
),
|
||||
);
|
||||
const claimed = await this.prisma.upstreamReceiptInbox.updateMany({
|
||||
where: {
|
||||
id,
|
||||
OR: [
|
||||
{ status: { in: ['pending', 'retrying'] } },
|
||||
{ status: 'processing', updatedAt: { lte: staleBefore } },
|
||||
],
|
||||
},
|
||||
data: { status: 'processing', attemptCount: { increment: 1 }, nextRetryAt: null },
|
||||
});
|
||||
if (claimed.count !== 1) return false;
|
||||
const inbox = await this.prisma.upstreamReceiptInbox.findUnique({ where: { id } });
|
||||
if (!inbox) return false;
|
||||
try {
|
||||
const message = await this.facade.handleReceipt({
|
||||
messageId: inbox.provisionalMessageId ?? undefined,
|
||||
channelId: inbox.incomingChannelId,
|
||||
connectionId: inbox.incomingConnectionId ?? undefined,
|
||||
sequenceId: inbox.sequenceId ?? undefined,
|
||||
gatewayMessageId: inbox.gatewayMessageId,
|
||||
phoneNumber: inbox.phoneNumber ?? undefined,
|
||||
receiptStatus: normalizeReceiptStatus(inbox.receiptStatus),
|
||||
rawStatus: inbox.rawStatus,
|
||||
errorCode: inbox.errorCode ?? undefined,
|
||||
errorMessage: inbox.errorMessage ?? undefined,
|
||||
deliveredAt: inbox.deliveredAt.toISOString(),
|
||||
}, {
|
||||
account: inbox.upstreamAccount,
|
||||
gatewayHost: inbox.upstreamHost,
|
||||
gatewayPort: inbox.upstreamPort,
|
||||
protocol: inbox.protocol,
|
||||
cmppVersion: inbox.protocolVersion,
|
||||
});
|
||||
const matchedMessageRecordId = message && 'id' in message ? message.id : message?.messageRecordId;
|
||||
const matchedChannelId = message && 'channelId' in message ? message.channelId : undefined;
|
||||
await this.prisma.upstreamReceiptInbox.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: 'matched',
|
||||
matchedMessageRecordId: matchedMessageRecordId ?? null,
|
||||
matchedChannelId: matchedChannelId ?? null,
|
||||
lastError: null,
|
||||
processedAt: new Date(),
|
||||
},
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const maxAttempts = positiveInteger(
|
||||
process.env.UPSTREAM_RECEIPT_INBOX_MAX_ATTEMPTS,
|
||||
DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_ATTEMPTS,
|
||||
);
|
||||
const maxAgeHours = positiveInteger(
|
||||
process.env.UPSTREAM_RECEIPT_INBOX_MAX_AGE_HOURS,
|
||||
DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_AGE_HOURS,
|
||||
);
|
||||
const exhausted = inbox.attemptCount >= maxAttempts
|
||||
|| inbox.receivedAt.getTime() <= Date.now() - maxAgeHours * 60 * 60_000;
|
||||
const retryDelayMs = Math.min(30 * 60_000, 5_000 * 2 ** Math.min(Math.max(inbox.attemptCount - 1, 0), 8));
|
||||
await this.prisma.upstreamReceiptInbox.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: exhausted ? 'unmatched' : 'retrying',
|
||||
nextRetryAt: exhausted ? null : new Date(Date.now() + retryDelayMs),
|
||||
lastError: error instanceof Error ? error.message : String(error),
|
||||
processedAt: exhausted ? new Date() : null,
|
||||
},
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async runUpstreamReceiptInboxScan() {
|
||||
if (this.upstreamReceiptInboxScanRunning) return;
|
||||
this.upstreamReceiptInboxScanRunning = true;
|
||||
try {
|
||||
const result = await this.facade.processPendingUpstreamReceiptInbox();
|
||||
if (result.processed > 0) {
|
||||
this.logger.log(`Matched ${result.processed}/${result.scanned} pending upstream receipts`);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error('Upstream receipt inbox scan failed', error instanceof Error ? error.stack : String(error));
|
||||
} finally {
|
||||
this.upstreamReceiptInboxScanRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
async handleReceipt(
|
||||
data: GatewayReceiptEventDto,
|
||||
incomingIdentity?: { account: string; gatewayHost: string; gatewayPort: number; protocol: string; cmppVersion: string },
|
||||
) {
|
||||
const resolved = await this.facade.resolveReceiptMessage(data, incomingIdentity);
|
||||
const logicalChannelId = resolved.channelId ?? data.channelId;
|
||||
const receiptKey = receiptEventKey(data, logicalChannelId);
|
||||
const existingReceipt = await this.prisma.smsReceiptRecord.findUnique({
|
||||
where: { receiptKey },
|
||||
include: { messageRecord: true },
|
||||
});
|
||||
if (existingReceipt?.messageRecord) {
|
||||
return existingReceipt.messageRecord;
|
||||
}
|
||||
const message = resolved.message;
|
||||
const deliveredAt = data.deliveredAt ? new Date(data.deliveredAt) : new Date();
|
||||
if (resolved.submitRecordId) {
|
||||
await this.prisma.smsSubmitRecord.updateMany({
|
||||
where: {
|
||||
id: resolved.submitRecordId,
|
||||
gatewayMessageId: null,
|
||||
},
|
||||
data: {
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
sequenceId: data.sequenceId,
|
||||
},
|
||||
});
|
||||
}
|
||||
try {
|
||||
await this.prisma.smsReceiptRecord.create({
|
||||
data: {
|
||||
tenantId: message.tenantId,
|
||||
batchTaskId: message.batchTaskId,
|
||||
messageRecordId: message.id,
|
||||
receiptKey,
|
||||
channelId: logicalChannelId,
|
||||
messageId: resolved.messageId,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
phoneNumber: data.phoneNumber?.trim() || message.phoneNumber,
|
||||
sequenceId: data.sequenceId,
|
||||
receiptStatus: data.receiptStatus,
|
||||
rawStatus: data.rawStatus,
|
||||
errorCode: data.errorCode,
|
||||
errorMessage: data.errorMessage,
|
||||
deliveredAt,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
|
||||
const duplicate = await this.prisma.smsReceiptRecord.findUnique({
|
||||
where: { receiptKey },
|
||||
include: { messageRecord: true },
|
||||
});
|
||||
if (duplicate?.messageRecord) return duplicate.messageRecord;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const logicalReceipt = { ...data, channelId: logicalChannelId };
|
||||
await this.facade.recordReceiptSegment(message, logicalReceipt, deliveredAt, resolved.submitRecordId);
|
||||
const aggregate = await this.facade.aggregateReceiptSegments(
|
||||
message,
|
||||
logicalReceipt,
|
||||
deliveredAt,
|
||||
resolved.submitRecordId,
|
||||
resolved.submitId,
|
||||
);
|
||||
if (!aggregate.terminal) {
|
||||
return this.prisma.smsMessageRecord.findUnique({ where: { id: message.id } });
|
||||
}
|
||||
const status = aggregate.status;
|
||||
const isCurrentAttempt =
|
||||
(!message.channelId || message.channelId === logicalChannelId)
|
||||
&& (
|
||||
!message.gatewayMessageId
|
||||
|| message.gatewayMessageId === data.gatewayMessageId
|
||||
|| (aggregate.segmentTotal > 1 && (!message.submitId || message.submitId === resolved.submitId))
|
||||
);
|
||||
if (!isCurrentAttempt || (status === 'failed' && message.status === 'delivered')) {
|
||||
return this.prisma.smsMessageRecord.findUnique({ where: { id: message.id } });
|
||||
}
|
||||
const isStandaloneChannelTest = !message.tenantId && !message.batchTaskId;
|
||||
if (status === 'failed' && !isStandaloneChannelTest && message.tenantId && message.batchTaskId) {
|
||||
const businessMessage = message as typeof message & { tenantId: string; batchTaskId: string };
|
||||
const retried = await this.facade.retryMessageIfAllowed(
|
||||
businessMessage,
|
||||
'回执失败补发',
|
||||
resolved.submitRecordId,
|
||||
);
|
||||
if (retried) {
|
||||
await this.facade.refreshTaskProgress(businessMessage.batchTaskId);
|
||||
return retried;
|
||||
}
|
||||
await this.facade.refundMessage(businessMessage, '最终失败退款');
|
||||
}
|
||||
await this.prisma.smsMessageRecord.update({
|
||||
where: { id: message.id },
|
||||
data: {
|
||||
channelId: logicalChannelId,
|
||||
gatewayMessageId: message.gatewayMessageId ?? data.gatewayMessageId,
|
||||
receiptStatus: aggregate.receiptStatus,
|
||||
receiptRawStatus: aggregate.rawStatus,
|
||||
status,
|
||||
errorCode: aggregate.errorCode,
|
||||
errorMessage: aggregate.errorMessage ?? (status === 'delivered' ? null : aggregate.rawStatus),
|
||||
deliveredAt: aggregate.deliveredAt,
|
||||
},
|
||||
});
|
||||
if (!isStandaloneChannelTest && message.tenantId && message.applicationId) {
|
||||
await this.facade.queueAndTryDownstreamDelivery({
|
||||
tenantId: message.tenantId,
|
||||
applicationId: message.applicationId,
|
||||
messageRecordId: message.id,
|
||||
messageId: message.messageId,
|
||||
deliveryType: 'receipt',
|
||||
payload: {
|
||||
messageId: message.messageId,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
phoneNumber: message.phoneNumber,
|
||||
receiptStatus: aggregate.receiptStatus,
|
||||
rawStatus: aggregate.rawStatus,
|
||||
errorCode: aggregate.errorCode,
|
||||
submitSequenceId: message.cmppSubmitSequenceId ? Number(message.cmppSubmitSequenceId) : undefined,
|
||||
submitGroupMessageId: message.cmppSubmitGroupMessageId ?? undefined,
|
||||
deliveredAt: aggregate.deliveredAt.toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
if (message.batchTaskId) {
|
||||
await this.facade.refreshTaskProgress(message.batchTaskId);
|
||||
}
|
||||
return this.prisma.smsMessageRecord.findUnique({ where: { id: message.id } });
|
||||
}
|
||||
|
||||
async recordReceiptSegment(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
channelId?: string | null;
|
||||
submitId?: string | null;
|
||||
billingUnits?: number | null;
|
||||
},
|
||||
data: GatewayReceiptEventDto,
|
||||
deliveredAt: Date,
|
||||
submitRecordId?: string,
|
||||
) {
|
||||
const segmentAudits = this.facade.smsMessageSegmentAuditDelegate();
|
||||
const updated = await segmentAudits.updateMany({
|
||||
where: {
|
||||
messageRecordId: message.id,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
},
|
||||
data: {
|
||||
receiptStatus: data.receiptStatus,
|
||||
rawStatus: data.rawStatus,
|
||||
errorCode: data.errorCode ?? null,
|
||||
deliveredAt,
|
||||
},
|
||||
});
|
||||
if (updated.count > 0) {
|
||||
return;
|
||||
}
|
||||
const submitRecord = submitRecordId
|
||||
? await this.prisma.smsSubmitRecord.findUnique({ where: { id: submitRecordId } })
|
||||
: await this.prisma.smsSubmitRecord.findFirst({
|
||||
where: { messageRecordId: message.id, gatewayMessageId: data.gatewayMessageId },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
await segmentAudits.upsert({
|
||||
where: {
|
||||
messageRecordId_submitId_segmentIndex: {
|
||||
messageRecordId: message.id,
|
||||
submitId: submitRecord?.submitId ?? message.submitId ?? `RECEIPT-AUDIT-${data.gatewayMessageId}`,
|
||||
segmentIndex: 1,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
submitRecordId: submitRecord?.id ?? submitRecordId ?? null,
|
||||
channelId: data.channelId ?? message.channelId ?? null,
|
||||
sequenceId: data.sequenceId ?? null,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
receiptStatus: data.receiptStatus,
|
||||
rawStatus: data.rawStatus,
|
||||
errorCode: data.errorCode ?? null,
|
||||
deliveredAt,
|
||||
},
|
||||
create: {
|
||||
tenantId: message.tenantId,
|
||||
batchTaskId: message.batchTaskId,
|
||||
messageRecordId: message.id,
|
||||
submitRecordId: submitRecord?.id ?? submitRecordId ?? null,
|
||||
channelId: data.channelId ?? message.channelId ?? null,
|
||||
submitId: submitRecord?.submitId ?? message.submitId ?? `RECEIPT-AUDIT-${data.gatewayMessageId}`,
|
||||
attempt: 0,
|
||||
segmentTotal: Math.max(1, Number(message.billingUnits ?? 1)),
|
||||
segmentIndex: 1,
|
||||
sequenceId: data.sequenceId ?? null,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
submitStatus: submitRecord?.submitStatus ?? 'accepted',
|
||||
receiptStatus: data.receiptStatus,
|
||||
rawStatus: data.rawStatus,
|
||||
compensationType: 'receipt_recovered',
|
||||
errorCode: data.errorCode ?? null,
|
||||
deliveredAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async aggregateReceiptSegments(
|
||||
message: {
|
||||
id: string;
|
||||
billingUnits?: number | null;
|
||||
},
|
||||
data: GatewayReceiptEventDto,
|
||||
deliveredAt: Date,
|
||||
submitRecordId?: string,
|
||||
submitId?: string,
|
||||
) {
|
||||
const audits = await this.facade.smsMessageSegmentAuditDelegate().findMany({
|
||||
where: submitRecordId
|
||||
? { messageRecordId: message.id, submitRecordId }
|
||||
: submitId
|
||||
? { messageRecordId: message.id, submitId }
|
||||
: { messageRecordId: message.id, gatewayMessageId: data.gatewayMessageId },
|
||||
orderBy: { segmentIndex: 'asc' },
|
||||
});
|
||||
return aggregateReceiptSegmentState(audits, message.billingUnits, data, deliveredAt);
|
||||
}
|
||||
|
||||
async resolveReceiptMessage(
|
||||
data: GatewayReceiptEventDto,
|
||||
incomingIdentity?: { account: string; gatewayHost: string; gatewayPort: number; protocol: string; cmppVersion: string },
|
||||
) {
|
||||
const exactMessage = data.messageId
|
||||
? await this.prisma.smsMessageRecord.findUnique({ where: { messageId: data.messageId } })
|
||||
: null;
|
||||
if (exactMessage) {
|
||||
const segmentAudit = data.gatewayMessageId
|
||||
? await this.facade.smsMessageSegmentAuditDelegate().findFirst({
|
||||
where: {
|
||||
messageRecordId: exactMessage.id,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
})
|
||||
: null;
|
||||
if (segmentAudit) {
|
||||
return {
|
||||
message: exactMessage,
|
||||
messageId: exactMessage.messageId,
|
||||
submitRecordId: segmentAudit.submitRecordId ?? undefined,
|
||||
submitId: segmentAudit.submitId,
|
||||
channelId: segmentAudit.channelId ?? data.channelId,
|
||||
};
|
||||
}
|
||||
const submitRecord = await this.prisma.smsSubmitRecord.findFirst({
|
||||
where: {
|
||||
messageRecordId: exactMessage.id,
|
||||
channelId: data.channelId,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
return {
|
||||
message: exactMessage,
|
||||
messageId: exactMessage.messageId,
|
||||
submitRecordId: submitRecord?.id,
|
||||
submitId: submitRecord?.submitId,
|
||||
channelId: submitRecord?.channelId ?? data.channelId,
|
||||
};
|
||||
}
|
||||
|
||||
const phoneNumber = data.phoneNumber?.trim();
|
||||
const exactSubmits = await this.prisma.smsSubmitRecord.findMany({
|
||||
where: {
|
||||
channelId: data.channelId,
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
...(phoneNumber ? { messageRecord: { phoneNumber } } : {}),
|
||||
},
|
||||
include: { messageRecord: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 2,
|
||||
});
|
||||
if (exactSubmits.length === 1 && exactSubmits[0]?.messageRecord) {
|
||||
return {
|
||||
message: exactSubmits[0].messageRecord,
|
||||
messageId: exactSubmits[0].messageRecord.messageId,
|
||||
submitRecordId: exactSubmits[0].id,
|
||||
submitId: exactSubmits[0].submitId,
|
||||
channelId: exactSubmits[0].channelId,
|
||||
};
|
||||
}
|
||||
|
||||
if (!phoneNumber) {
|
||||
throw new NotFoundException('SMS message record not found');
|
||||
}
|
||||
|
||||
const incomingChannel = incomingIdentity
|
||||
?? await this.prisma.smsChannel.findUnique({ where: { id: data.channelId } });
|
||||
if (!incomingChannel) {
|
||||
throw new NotFoundException('SMS message record not found');
|
||||
}
|
||||
const segmentMatches = await this.facade.smsMessageSegmentAuditDelegate().findMany({
|
||||
where: {
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
messageRecord: { phoneNumber },
|
||||
},
|
||||
include: { messageRecord: true, submitRecord: true, channel: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 10,
|
||||
});
|
||||
const exactSegmentMatches = segmentMatches.filter((candidate) => candidate.channelId === data.channelId);
|
||||
if (exactSegmentMatches.length === 1 && exactSegmentMatches[0]?.messageRecord) {
|
||||
return {
|
||||
message: exactSegmentMatches[0].messageRecord,
|
||||
messageId: exactSegmentMatches[0].messageRecord.messageId,
|
||||
submitRecordId: exactSegmentMatches[0].submitRecordId ?? undefined,
|
||||
submitId: exactSegmentMatches[0].submitRecord?.submitId ?? exactSegmentMatches[0].submitId,
|
||||
channelId: exactSegmentMatches[0].channelId,
|
||||
};
|
||||
}
|
||||
const sameSupplierSegments = segmentMatches.filter((candidate) =>
|
||||
candidate.channel && isSameUpstreamEndpointIdentity(incomingChannel, candidate.channel));
|
||||
if (sameSupplierSegments.length === 1 && sameSupplierSegments[0]?.messageRecord) {
|
||||
return {
|
||||
message: sameSupplierSegments[0].messageRecord,
|
||||
messageId: sameSupplierSegments[0].messageRecord.messageId,
|
||||
submitRecordId: sameSupplierSegments[0].submitRecordId ?? undefined,
|
||||
submitId: sameSupplierSegments[0].submitRecord?.submitId ?? sameSupplierSegments[0].submitId,
|
||||
channelId: sameSupplierSegments[0].channelId,
|
||||
};
|
||||
}
|
||||
const crossConnectionSubmits = await this.prisma.smsSubmitRecord.findMany({
|
||||
where: {
|
||||
gatewayMessageId: data.gatewayMessageId,
|
||||
messageRecord: { phoneNumber },
|
||||
},
|
||||
include: { messageRecord: true, channel: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: 10,
|
||||
});
|
||||
const sameSupplierSubmits = crossConnectionSubmits.filter((candidate) =>
|
||||
candidate.channel && isSameUpstreamEndpointIdentity(incomingChannel, candidate.channel));
|
||||
if (sameSupplierSubmits.length === 1 && sameSupplierSubmits[0]?.messageRecord) {
|
||||
return {
|
||||
message: sameSupplierSubmits[0].messageRecord,
|
||||
messageId: sameSupplierSubmits[0].messageRecord.messageId,
|
||||
submitRecordId: sameSupplierSubmits[0].id,
|
||||
submitId: sameSupplierSubmits[0].submitId,
|
||||
channelId: sameSupplierSubmits[0].channelId,
|
||||
};
|
||||
}
|
||||
|
||||
const deliveredAt = data.deliveredAt ? new Date(data.deliveredAt) : new Date();
|
||||
const submittedAfter = new Date(deliveredAt.getTime() - 72 * 60 * 60 * 1000);
|
||||
const candidates = await this.prisma.smsSubmitRecord.findMany({
|
||||
where: {
|
||||
channelId: data.channelId,
|
||||
gatewayMessageId: null,
|
||||
submitStatus: 'timeout',
|
||||
submittedAt: {
|
||||
gte: submittedAfter,
|
||||
lte: deliveredAt,
|
||||
},
|
||||
messageRecord: {
|
||||
phoneNumber,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
messageRecord: true,
|
||||
},
|
||||
orderBy: {
|
||||
submittedAt: 'desc',
|
||||
},
|
||||
take: 10,
|
||||
});
|
||||
|
||||
if (candidates.length !== 1 || !candidates[0]?.messageRecord) {
|
||||
throw new NotFoundException('SMS message record not found');
|
||||
}
|
||||
|
||||
return {
|
||||
message: candidates[0].messageRecord,
|
||||
messageId: candidates[0].messageRecord.messageId,
|
||||
submitRecordId: candidates[0].id,
|
||||
submitId: candidates[0].submitId,
|
||||
channelId: candidates[0].channelId,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
import { BadRequestException, HttpException, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import type { OpenApiService } from '../open-api/open-api.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { GatewaySubmitResultDto, GatewaySubmitSegmentResultDto, GatewayReceiptEventDto, GatewayUplinkEventDto, GatewayPendingDeliveryQueryDto, GatewayDownstreamSentDto, GatewayDownstreamAcknowledgedDto, GatewayDownstreamFailureType, GatewayControlDeliveryResult, GatewaySubmitDeadLetterDto, RequeueGatewaySubmitExceptionDto, GatewayDownstreamRecoveryStatusDto, TimeoutUnknownDto } from './send-chain.contracts';
|
||||
import { positiveInteger, normalizeReceiptStatus, normalizeCarrier, DEFAULT_DOWNSTREAM_RETRY_DELAY_MS, DEFAULT_DOWNSTREAM_RETRY_MAX_DELAY_MS, DEFAULT_DOWNSTREAM_MAX_RETRIES, DEFAULT_DOWNSTREAM_PENDING_TIMEOUT_HOURS, DEFAULT_RECEIPT_TIMEOUT_HOURS, DEFAULT_GATEWAY_SUBMIT_REQUEUE_STALE_MS, DEFAULT_DOWNSTREAM_MANUAL_REQUEUE_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_ATTEMPTS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_AGE_HOURS, gatewaySubmitRequeueKey, isObjectRecord, asDateOrNull, downstreamRetryDelayMs, downstreamAckTimeoutMs, downstreamRetryBaseDelayMs, downstreamRetryMaxDelayMs, downstreamMaxRetries, downstreamPendingTimeoutHours, downstreamControlFailureMessage, normalizeSubmitStatus, downstreamDeliveryAttemptKey, hasRecoveryAuditStateChanged, normalizeRecoveryFailureCategory, aggregateReceiptSegmentState, isSameUpstreamEndpointIdentity, receiptEventKey } from './send-chain.helpers';
|
||||
import type { SendSubmissionService } from './send-submission.service';
|
||||
import type { SendCompletionCallbacks, SendCompletionFacade } from './send-completion.service';
|
||||
|
||||
|
||||
/**
|
||||
* R10 retry implementation.
|
||||
* Cross-domain calls return through the stable SendChainService seam to preserve locking and test observability.
|
||||
*/
|
||||
export class SendRetryService {
|
||||
private readonly logger = new Logger('SendChainService');
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly openApi: OpenApiService | undefined,
|
||||
private readonly facade: SendCompletionFacade,
|
||||
private readonly callbacks: SendCompletionCallbacks,
|
||||
) {}
|
||||
|
||||
async recordGatewaySubmitDeadLetter(data: GatewaySubmitDeadLetterDto) {
|
||||
const createdAt = data.deadLetteredAt ? new Date(data.deadLetteredAt) : new Date();
|
||||
return this.prisma.gatewaySubmitDeadLetter.upsert({
|
||||
where: { streamMessageId: data.streamMessageId },
|
||||
update: {
|
||||
tenantId: data.tenantId,
|
||||
applicationId: data.applicationId,
|
||||
channelId: data.channelId,
|
||||
traceId: data.traceId,
|
||||
messageId: data.messageId,
|
||||
submitId: data.submitId,
|
||||
failureCode: data.failureCode,
|
||||
failureMessage: data.failureMessage,
|
||||
attempts: data.attempts,
|
||||
maxAttempts: data.maxAttempts,
|
||||
commandPayload: data.commandPayload as Prisma.InputJsonValue | undefined,
|
||||
rawPayload: data.rawPayload,
|
||||
},
|
||||
create: {
|
||||
streamMessageId: data.streamMessageId,
|
||||
tenantId: data.tenantId,
|
||||
applicationId: data.applicationId,
|
||||
channelId: data.channelId,
|
||||
traceId: data.traceId,
|
||||
messageId: data.messageId,
|
||||
submitId: data.submitId,
|
||||
failureCode: data.failureCode,
|
||||
failureMessage: data.failureMessage,
|
||||
attempts: data.attempts,
|
||||
maxAttempts: data.maxAttempts,
|
||||
commandPayload: data.commandPayload as Prisma.InputJsonValue | undefined,
|
||||
rawPayload: data.rawPayload,
|
||||
createdAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async requeueGatewaySubmitDeadLetter(id: string, data: RequeueGatewaySubmitExceptionDto = {}) {
|
||||
const deadLetter = await this.prisma.gatewaySubmitDeadLetter.findUnique({ where: { id } });
|
||||
if (!deadLetter) {
|
||||
throw new NotFoundException('Gateway提交异常记录不存在');
|
||||
}
|
||||
if (deadLetter.status !== 'pending') {
|
||||
throw new BadRequestException('该提交异常当前状态不允许重新入队');
|
||||
}
|
||||
if (!data.confirmedNotSubmitted) {
|
||||
throw new BadRequestException('请确认运营商未接收该短信后再重新入队');
|
||||
}
|
||||
const reason = String(data.reason ?? '').trim();
|
||||
if (reason.length < 5 || reason.length > 500) {
|
||||
throw new BadRequestException('请填写5至500字的重新入队原因');
|
||||
}
|
||||
if (!deadLetter.commandPayload || !isObjectRecord(deadLetter.commandPayload)) {
|
||||
throw new BadRequestException('该提交异常缺少可重新入队的SubmitCommand');
|
||||
}
|
||||
if (deadLetter.manualRetryCount >= 3) {
|
||||
throw new BadRequestException('该提交异常已达到人工重新入队次数上限');
|
||||
}
|
||||
const message = deadLetter.messageId
|
||||
? await this.prisma.smsMessageRecord.findUnique({ where: { messageId: deadLetter.messageId } })
|
||||
: null;
|
||||
if (message && (
|
||||
message.submitStatus === 'accepted'
|
||||
|| ['submitted', 'delivered', 'unknown'].includes(message.status)
|
||||
|| ['delivered', 'unknown'].includes(message.receiptStatus ?? '')
|
||||
)) {
|
||||
throw new BadRequestException('该短信已有成功或不确定的上游结果,为避免重复发送,禁止重新入队');
|
||||
}
|
||||
const commandChannelId = String(deadLetter.commandPayload.channelId ?? deadLetter.channelId ?? '').trim();
|
||||
if (!commandChannelId) {
|
||||
throw new BadRequestException('该提交异常缺少通道信息');
|
||||
}
|
||||
const channel = await this.prisma.smsChannel.findUnique({
|
||||
where: { id: commandChannelId },
|
||||
include: { connectionStates: true },
|
||||
});
|
||||
if (!channel || channel.status !== 'active') {
|
||||
throw new BadRequestException('原通道不存在或已停用,不能重新入队');
|
||||
}
|
||||
if (!channel.connectionStates.some((state) => state.status === 'connected' && state.currentConnections > 0)) {
|
||||
throw new BadRequestException('原通道当前没有可用CMPP连接,请先恢复通道');
|
||||
}
|
||||
const claimed = await this.prisma.gatewaySubmitDeadLetter.updateMany({
|
||||
where: { id, status: 'pending' },
|
||||
data: { status: 'requeueing' },
|
||||
});
|
||||
if (claimed.count !== 1) {
|
||||
throw new BadRequestException('该提交异常已被其他操作处理,请刷新后重试');
|
||||
}
|
||||
const requeueKey = gatewaySubmitRequeueKey(deadLetter.id, deadLetter.manualRetryCount + 1);
|
||||
let retryStreamMessageId: string;
|
||||
try {
|
||||
const publishedStreamMessageId = await this.facade.publishGatewaySubmitCommand(deadLetter.commandPayload, requeueKey);
|
||||
if (!publishedStreamMessageId) {
|
||||
throw new Error('Gateway提交异常重新入队未返回Stream消息编号');
|
||||
}
|
||||
retryStreamMessageId = publishedStreamMessageId;
|
||||
} catch (error) {
|
||||
await this.prisma.gatewaySubmitDeadLetter.updateMany({
|
||||
where: { id, status: 'requeueing' },
|
||||
data: { status: 'pending' },
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
const finalized = await this.prisma.gatewaySubmitDeadLetter.updateMany({
|
||||
where: { id, status: 'requeueing' },
|
||||
data: {
|
||||
status: 'requeued',
|
||||
manualRetryCount: { increment: 1 },
|
||||
lastRetryStreamId: retryStreamMessageId,
|
||||
lastRetriedAt: new Date(),
|
||||
},
|
||||
});
|
||||
const updated = await this.prisma.gatewaySubmitDeadLetter.findUnique({ where: { id } });
|
||||
if (!updated) {
|
||||
throw new NotFoundException('Gateway提交异常记录不存在');
|
||||
}
|
||||
if (finalized.count !== 1 && updated.status !== 'resolved') {
|
||||
throw new BadRequestException('该提交异常状态已变化,请刷新后确认处理结果');
|
||||
}
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
tenantId: updated.tenantId ?? undefined,
|
||||
userId: data.operatorId,
|
||||
action: 'gateway.submit_dead_letter_requeue',
|
||||
resource: 'gateway_submit_dead_letter',
|
||||
resourceId: updated.id,
|
||||
detail: {
|
||||
streamMessageId: updated.streamMessageId,
|
||||
retryStreamMessageId,
|
||||
submitId: updated.submitId,
|
||||
messageId: updated.messageId,
|
||||
reason,
|
||||
confirmedNotSubmitted: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
return updated;
|
||||
}
|
||||
|
||||
async recoverStaleGatewaySubmitRequeues(now = new Date()) {
|
||||
const staleCutoff = new Date(now.getTime() - positiveInteger(
|
||||
process.env.GATEWAY_SUBMIT_REQUEUE_STALE_MS,
|
||||
DEFAULT_GATEWAY_SUBMIT_REQUEUE_STALE_MS,
|
||||
));
|
||||
const stale = await this.prisma.gatewaySubmitDeadLetter.findMany({
|
||||
where: { status: 'requeueing', updatedAt: { lt: staleCutoff } },
|
||||
orderBy: { updatedAt: 'asc' },
|
||||
take: 100,
|
||||
});
|
||||
let recovered = 0;
|
||||
let failed = 0;
|
||||
for (const deadLetter of stale) {
|
||||
if (!deadLetter.commandPayload || !isObjectRecord(deadLetter.commandPayload)) {
|
||||
await this.prisma.gatewaySubmitDeadLetter.updateMany({
|
||||
where: { id: deadLetter.id, status: 'requeueing', updatedAt: deadLetter.updatedAt },
|
||||
data: { status: 'pending' },
|
||||
});
|
||||
failed += 1;
|
||||
continue;
|
||||
}
|
||||
const claimed = await this.prisma.gatewaySubmitDeadLetter.updateMany({
|
||||
where: { id: deadLetter.id, status: 'requeueing', updatedAt: deadLetter.updatedAt },
|
||||
data: { status: 'requeue_recovering' },
|
||||
});
|
||||
if (claimed.count !== 1) continue;
|
||||
try {
|
||||
const requeueKey = gatewaySubmitRequeueKey(deadLetter.id, deadLetter.manualRetryCount + 1);
|
||||
const retryStreamMessageId = await this.facade.publishGatewaySubmitCommand(deadLetter.commandPayload, requeueKey);
|
||||
if (!retryStreamMessageId) throw new Error('Gateway提交异常恢复未返回Stream消息编号');
|
||||
const finalized = await this.prisma.gatewaySubmitDeadLetter.updateMany({
|
||||
where: { id: deadLetter.id, status: 'requeue_recovering' },
|
||||
data: {
|
||||
status: 'requeued',
|
||||
manualRetryCount: { increment: 1 },
|
||||
lastRetryStreamId: retryStreamMessageId,
|
||||
lastRetriedAt: new Date(),
|
||||
},
|
||||
});
|
||||
if (finalized.count === 1) {
|
||||
recovered += 1;
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
tenantId: deadLetter.tenantId ?? undefined,
|
||||
action: 'gateway.submit_dead_letter_requeue_recovered',
|
||||
resource: 'gateway_submit_dead_letter',
|
||||
resourceId: deadLetter.id,
|
||||
detail: { retryStreamMessageId, requeueKey },
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
failed += 1;
|
||||
await this.prisma.gatewaySubmitDeadLetter.updateMany({
|
||||
where: { id: deadLetter.id, status: 'requeue_recovering' },
|
||||
data: { status: 'requeueing' },
|
||||
});
|
||||
this.logger.error(`Gateway submit requeue recovery failed for ${deadLetter.id}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
return { recovered, failed };
|
||||
}
|
||||
|
||||
async retryMessageIfAllowed(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
batchTaskId: string;
|
||||
applicationId?: string | null;
|
||||
templateId?: string | null;
|
||||
signatureId?: string | null;
|
||||
submitId?: string | null;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
content: string;
|
||||
billingUnits: number;
|
||||
queuedAt?: Date;
|
||||
clientSrcId?: string | null;
|
||||
applicationExtension?: string | null;
|
||||
carrier?: string | null;
|
||||
province?: string | null;
|
||||
},
|
||||
reason: string,
|
||||
sourceSubmitRecordId?: string,
|
||||
) {
|
||||
const attempts = await this.prisma.smsSubmitRecord.findMany({
|
||||
where: { messageRecordId: message.id },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
take: 200,
|
||||
});
|
||||
const attemptedChannelIds = attempts.map((attempt) => attempt.channelId);
|
||||
let sourceAttempt = sourceSubmitRecordId
|
||||
? attempts.find((attempt) => attempt.id === sourceSubmitRecordId)
|
||||
: attempts.find((attempt) => attempt.submitId === message.submitId) ?? attempts[attempts.length - 1];
|
||||
if (!sourceAttempt && sourceSubmitRecordId) {
|
||||
sourceAttempt = await this.prisma.smsSubmitRecord.findUnique({
|
||||
where: { id: sourceSubmitRecordId },
|
||||
}) ?? undefined;
|
||||
}
|
||||
if (!sourceAttempt || sourceAttempt.messageRecordId !== message.id) {
|
||||
this.logger.error(`sms_retry_route_failed ${JSON.stringify({
|
||||
messageId: message.messageId,
|
||||
messageRecordId: message.id,
|
||||
reason,
|
||||
sourceSubmitRecordId,
|
||||
sourceMessageRecordId: sourceAttempt?.messageRecordId,
|
||||
error: sourceAttempt ? 'retry_source_submit_record_mismatch' : 'retry_source_submit_record_missing',
|
||||
})}`);
|
||||
return null;
|
||||
}
|
||||
const existingRetry = await this.prisma.smsSubmitRecord.findUnique({
|
||||
where: { retryOfSubmitRecordId: sourceAttempt.id },
|
||||
});
|
||||
if (existingRetry) {
|
||||
this.logger.warn(`sms_retry_claim_reused ${JSON.stringify({
|
||||
messageId: message.messageId,
|
||||
messageRecordId: message.id,
|
||||
retryOfSubmitRecordId: sourceAttempt.id,
|
||||
submitId: existingRetry.submitId,
|
||||
channelId: existingRetry.channelId,
|
||||
})}`);
|
||||
return this.prisma.smsMessageRecord.findUnique({ where: { id: message.id } });
|
||||
}
|
||||
const ageMinutes = (Date.now() - new Date(message.queuedAt ?? Date.now()).getTime()) / 60_000;
|
||||
this.logger.log(`sms_retry_route_started ${JSON.stringify({
|
||||
messageId: message.messageId,
|
||||
messageRecordId: message.id,
|
||||
reason,
|
||||
attemptedChannelIds,
|
||||
ageMinutes: Math.round(ageMinutes * 100) / 100,
|
||||
})}`);
|
||||
if (ageMinutes >= 72 * 60) {
|
||||
this.logger.warn(`sms_retry_route_skipped ${JSON.stringify({
|
||||
messageId: message.messageId,
|
||||
messageRecordId: message.id,
|
||||
reason: 'maximum_message_age_exceeded',
|
||||
ageMinutes: Math.round(ageMinutes * 100) / 100,
|
||||
})}`);
|
||||
return null;
|
||||
}
|
||||
const retryCarrier = message.carrier
|
||||
? normalizeCarrier(message.carrier)
|
||||
: await this.facade.identifyCarrier(message.phoneNumber);
|
||||
const route = await this.facade.findApplicationRoute(message.tenantId, message.applicationId ?? undefined, retryCarrier);
|
||||
const retryTimeLimitMinutes = Math.min(route.group.retryTimeLimitMinutes ?? route.group.retryTimeLimitHours * 60, 72 * 60);
|
||||
if (!route.group.retryEnabled || ageMinutes >= retryTimeLimitMinutes) {
|
||||
this.logger.warn(`sms_retry_route_skipped ${JSON.stringify({
|
||||
messageId: message.messageId,
|
||||
messageRecordId: message.id,
|
||||
groupId: route.groupId,
|
||||
reason: !route.group.retryEnabled ? 'group_retry_disabled' : 'group_retry_time_limit_exceeded',
|
||||
ageMinutes: Math.round(ageMinutes * 100) / 100,
|
||||
retryTimeLimitMinutes,
|
||||
})}`);
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const routed = await this.facade.selectChannelForMessage({ ...message, carrier: retryCarrier }, {
|
||||
forceNational: true,
|
||||
excludeChannelIds: attemptedChannelIds,
|
||||
});
|
||||
await this.prisma.smsMessageRecord.update({
|
||||
where: { id: message.id },
|
||||
data: { errorMessage: reason },
|
||||
});
|
||||
const retried = await this.facade.submitMessageToGateway(
|
||||
message,
|
||||
routed,
|
||||
attempts.length,
|
||||
sourceAttempt.id,
|
||||
);
|
||||
this.logger.log(`sms_retry_route_selected ${JSON.stringify({
|
||||
messageId: message.messageId,
|
||||
messageRecordId: message.id,
|
||||
groupId: routed.groupId,
|
||||
channelId: routed.channel.id,
|
||||
attempt: attempts.length,
|
||||
})}`);
|
||||
return retried;
|
||||
} catch (error) {
|
||||
this.logger.error(`sms_retry_route_failed ${JSON.stringify({
|
||||
messageId: message.messageId,
|
||||
messageRecordId: message.id,
|
||||
reason,
|
||||
attemptedChannelIds,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { BadRequestException, HttpException, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { Queue, Worker } from 'bullmq';
|
||||
import IORedis from 'ioredis';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { isIpAllowed } from '../common/ip-allowlist';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import { PhoneRoutingLookupService } from '../dictionaries/phone-routing-lookup.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { RiskReviewService } from '../risk-review/risk-review.service';
|
||||
import { PhoneFrequencyService } from '../risk-review/phone-frequency.service';
|
||||
import type { CreateBatchTaskDto, CreateHttpBatchTaskDto, GatewayInboundAuthDto, GatewayInboundSubmitDto, GatewayInboundSingleSubmitResult, ImportPreviewDto, ConfirmImportDto, SendJob, QueuePriority, RoutedChannel } from './send-chain.contracts';
|
||||
import { SEND_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_SCHEDULED_DISPATCH_STALE_MS, DEFAULT_INBOUND_LONG_MESSAGE_PROCESSING_STALE_SECONDS, GATEWAY_SUBMIT_REQUEUE_IDEMPOTENCY_TTL_SECONDS, BULLMQ_PRIORITY, drainageRejectionReason, statusFromRisk, parseSchedule, parseImportRows, splitImportLine, cellByHeader, normalizeCarrier, normalizeQueuePriority, getPositiveConfigInteger, getNonNegativeConfigInteger, isCarrierCompatible, matchTemplateContent, isNationalChannel, validateInboundApplicationSrcId, composeUpstreamSrcId, positiveInteger, parseOptionalSequenceId, shanghaiDateKey, bullmqConnection, matchesApplicationSecret, octetString, selectChannelCandidate } from './send-chain.helpers';
|
||||
import type { SendSubmissionCallbacks, SendSubmissionService } from './send-submission.service';
|
||||
|
||||
/**
|
||||
* R9 reviewContinuation implementation. Cross-method calls return through the stable SendChainService seam.
|
||||
*/
|
||||
export class SendReviewContinuationService {
|
||||
private readonly logger = new Logger('SendChainService');
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly riskReview: RiskReviewService,
|
||||
private readonly phoneFrequency: PhoneFrequencyService,
|
||||
private readonly phoneRouting: PhoneRoutingLookupService,
|
||||
private readonly facade: SendSubmissionService,
|
||||
private readonly callbacks: SendSubmissionCallbacks,
|
||||
) {}
|
||||
|
||||
private releaseMessageReservation(
|
||||
message: { tenantId: string; batchTaskId: string; messageId: string; amountCents: number | bigint; billingUnits: number },
|
||||
remark: string,
|
||||
) {
|
||||
return this.callbacks.releaseMessageReservation(message, remark);
|
||||
}
|
||||
|
||||
private recordCmppFailureReceipt(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
applicationId?: string | null;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
cmppSubmitSequenceId?: string | null;
|
||||
cmppSubmitGroupMessageId?: string | null;
|
||||
},
|
||||
errorCode: string,
|
||||
reason: string,
|
||||
) {
|
||||
return this.callbacks.recordCmppFailureReceipt(message, errorCode, reason);
|
||||
}
|
||||
|
||||
|
||||
async handleReviewDecision(reviewTaskId: string, decision: 'approved' | 'rejected', reason: string) {
|
||||
const reviewTask = await this.prisma.smsSendTask.findUnique({
|
||||
where: { id: reviewTaskId },
|
||||
});
|
||||
if (!reviewTask) {
|
||||
return { reviewTaskId, decision, affected: 0 };
|
||||
}
|
||||
const messageRecords = await this.prisma.smsMessageRecord.findMany({
|
||||
where: {
|
||||
status: 'pending_review',
|
||||
OR: [
|
||||
{ reviewTaskId },
|
||||
{ batchTask: { riskTaskId: reviewTaskId } },
|
||||
],
|
||||
},
|
||||
include: { batchTask: true },
|
||||
});
|
||||
if (messageRecords.length === 0) {
|
||||
return { reviewTaskId, decision, affected: 0 };
|
||||
}
|
||||
const batchTaskIds = new Set<string>();
|
||||
for (const message of messageRecords) {
|
||||
if (!message.tenantId || !message.applicationId || !message.batchTaskId) continue;
|
||||
if (decision === 'approved') {
|
||||
await this.prisma.smsMessageRecord.update({
|
||||
where: { id: message.id },
|
||||
data: { status: 'queued', errorCode: null, errorMessage: null },
|
||||
});
|
||||
await this.prisma.smsBatchTask.update({
|
||||
where: { id: message.batchTaskId },
|
||||
data: { status: 'ready', auditStatus: 'approved', reviewReason: reason, rejectReason: null },
|
||||
});
|
||||
batchTaskIds.add(message.batchTaskId);
|
||||
} else {
|
||||
await this.releaseMessageReservation(
|
||||
message as typeof message & { tenantId: string; batchTaskId: string },
|
||||
'模板不匹配人工审核驳回释放冻结',
|
||||
);
|
||||
await this.prisma.smsBatchTask.update({
|
||||
where: { id: message.batchTaskId },
|
||||
data: { status: 'rejected', auditStatus: 'rejected', rejectReason: reason },
|
||||
});
|
||||
await this.recordCmppFailureReceipt(message, 'REVIEW_REJECTED', reason);
|
||||
}
|
||||
}
|
||||
for (const batchTaskId of batchTaskIds) {
|
||||
await this.facade.enqueueBatchTask(batchTaskId);
|
||||
}
|
||||
return { reviewTaskId, decision, affected: messageRecords.length };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { BadRequestException, HttpException, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { Queue, Worker } from 'bullmq';
|
||||
import IORedis from 'ioredis';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { setTimeout as sleep } from 'node:timers/promises';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { isIpAllowed } from '../common/ip-allowlist';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import { PhoneRoutingLookupService } from '../dictionaries/phone-routing-lookup.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { RiskReviewService } from '../risk-review/risk-review.service';
|
||||
import { PhoneFrequencyService } from '../risk-review/phone-frequency.service';
|
||||
import type { CreateBatchTaskDto, CreateHttpBatchTaskDto, GatewayInboundAuthDto, GatewayInboundSubmitDto, GatewayInboundSingleSubmitResult, ImportPreviewDto, ConfirmImportDto, SendJob, QueuePriority, RoutedChannel } from './send-chain.contracts';
|
||||
import { SEND_QUEUE, GATEWAY_SUBMIT_QUEUE, GATEWAY_SUBMIT_STREAM, DEFAULT_SCHEDULED_DISPATCH_STALE_MS, DEFAULT_INBOUND_LONG_MESSAGE_PROCESSING_STALE_SECONDS, GATEWAY_SUBMIT_REQUEUE_IDEMPOTENCY_TTL_SECONDS, BULLMQ_PRIORITY, drainageRejectionReason, statusFromRisk, parseSchedule, parseImportRows, splitImportLine, cellByHeader, normalizeCarrier, normalizeQueuePriority, getPositiveConfigInteger, getNonNegativeConfigInteger, isCarrierCompatible, matchTemplateContent, isNationalChannel, validateInboundApplicationSrcId, composeUpstreamSrcId, positiveInteger, parseOptionalSequenceId, shanghaiDateKey, bullmqConnection, matchesApplicationSecret, octetString, selectChannelCandidate } from './send-chain.helpers';
|
||||
import type { SendSubmissionCallbacks, SendSubmissionService } from './send-submission.service';
|
||||
|
||||
/**
|
||||
* R9 scheduledDispatch implementation. Cross-method calls return through the stable SendChainService seam.
|
||||
*/
|
||||
export class SendScheduledDispatchService {
|
||||
private readonly logger = new Logger('SendChainService');
|
||||
private scheduledDispatchScanRunning = false;
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly riskReview: RiskReviewService,
|
||||
private readonly phoneFrequency: PhoneFrequencyService,
|
||||
private readonly phoneRouting: PhoneRoutingLookupService,
|
||||
private readonly facade: SendSubmissionService,
|
||||
private readonly callbacks: SendSubmissionCallbacks,
|
||||
) {}
|
||||
|
||||
private releaseMessageReservation(
|
||||
message: { tenantId: string; batchTaskId: string; messageId: string; amountCents: number | bigint; billingUnits: number },
|
||||
remark: string,
|
||||
) {
|
||||
return this.callbacks.releaseMessageReservation(message, remark);
|
||||
}
|
||||
|
||||
private recordCmppFailureReceipt(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
applicationId?: string | null;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
cmppSubmitSequenceId?: string | null;
|
||||
cmppSubmitGroupMessageId?: string | null;
|
||||
},
|
||||
errorCode: string,
|
||||
reason: string,
|
||||
) {
|
||||
return this.callbacks.recordCmppFailureReceipt(message, errorCode, reason);
|
||||
}
|
||||
|
||||
|
||||
async dispatchDueScheduledTasks(now = new Date()) {
|
||||
const staleCutoff = new Date(now.getTime() - positiveInteger(
|
||||
process.env.SMS_SCHEDULED_DISPATCH_STALE_MS,
|
||||
DEFAULT_SCHEDULED_DISPATCH_STALE_MS,
|
||||
));
|
||||
const tasks = await this.prisma.smsBatchTask.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ status: 'scheduled', scheduledAt: { lte: now } },
|
||||
{ status: { in: ['scheduled_dispatching', 'scheduled_recovering'] }, updatedAt: { lt: staleCutoff } },
|
||||
],
|
||||
},
|
||||
orderBy: { scheduledAt: 'asc' },
|
||||
});
|
||||
const results: Array<{ taskId: string; status: string; enqueued?: number; reason?: string }> = [];
|
||||
for (const task of tasks) {
|
||||
const candidateStatus = task.status || 'scheduled';
|
||||
const claimedStatus = candidateStatus === 'scheduled_dispatching' ? 'scheduled_recovering' : 'scheduled_dispatching';
|
||||
const claimed = await this.prisma.smsBatchTask.updateMany({
|
||||
where: {
|
||||
id: task.id,
|
||||
status: candidateStatus,
|
||||
...(candidateStatus === 'scheduled' ? {} : { updatedAt: { lt: staleCutoff } }),
|
||||
},
|
||||
data: { status: claimedStatus },
|
||||
});
|
||||
if (claimed.count !== 1) continue;
|
||||
let reservationEstablished = false;
|
||||
let dispatchPrepared = false;
|
||||
try {
|
||||
await this.facade.validateSendResources(task.tenantId, task.applicationId ?? undefined, task.templateId ?? undefined);
|
||||
const messages = await this.prisma.smsMessageRecord.findMany({
|
||||
where: { batchTaskId: task.id, status: { in: ['scheduled', 'queued'] } },
|
||||
select: { id: true, amountCents: true, billingUnits: true },
|
||||
take: 100000,
|
||||
});
|
||||
const amountCents = messages.reduce((sum, message) => sum + moneyToNumber(message.amountCents), 0);
|
||||
const existingReservation = await this.prisma.accountTransaction.findFirst({
|
||||
where: { tenantId: task.tenantId, transactionType: 'frozen', relatedType: 'sms_batch_task', relatedId: task.id },
|
||||
select: { id: true },
|
||||
});
|
||||
reservationEstablished = Boolean(existingReservation);
|
||||
if (!reservationEstablished) {
|
||||
const accountCheck = await this.billing.checkAccount({ tenantId: task.tenantId, amountCents });
|
||||
if (!accountCheck.canSend) {
|
||||
throw new BadRequestException('定时任务到点时企业账户余额不足');
|
||||
}
|
||||
if (amountCents > 0) {
|
||||
await this.billing.freeze({
|
||||
tenantId: task.tenantId,
|
||||
amountCents,
|
||||
relatedType: 'sms_batch_task',
|
||||
relatedId: task.id,
|
||||
remark: '定时任务到点冻结',
|
||||
});
|
||||
reservationEstablished = true;
|
||||
}
|
||||
}
|
||||
dispatchPrepared = true;
|
||||
await this.prisma.smsMessageRecord.updateMany({
|
||||
where: { batchTaskId: task.id, status: 'scheduled' },
|
||||
data: { status: 'queued' },
|
||||
});
|
||||
const enqueued = await this.facade.enqueueBatchTask(task.id);
|
||||
results.push({ taskId: task.id, status: 'queued', enqueued: enqueued.enqueued });
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : '定时任务到点执行失败';
|
||||
if (reservationEstablished || dispatchPrepared) {
|
||||
await this.prisma.smsBatchTask.update({
|
||||
where: { id: task.id },
|
||||
data: { status: claimedStatus, rejectReason: `调度将在超时后恢复:${reason}` },
|
||||
});
|
||||
results.push({ taskId: task.id, status: 'retrying', reason });
|
||||
continue;
|
||||
}
|
||||
await this.prisma.smsMessageRecord.updateMany({
|
||||
where: { batchTaskId: task.id, status: 'scheduled' },
|
||||
data: { status: 'rejected', errorMessage: reason },
|
||||
});
|
||||
await this.prisma.smsBatchTask.update({
|
||||
where: { id: task.id },
|
||||
data: { status: 'failed', rejectReason: reason },
|
||||
});
|
||||
results.push({ taskId: task.id, status: 'failed', reason });
|
||||
}
|
||||
}
|
||||
return { dispatched: results.filter((result) => result.status === 'queued').length, results };
|
||||
}
|
||||
|
||||
async runScheduledDispatchScan() {
|
||||
if (this.scheduledDispatchScanRunning) return;
|
||||
this.scheduledDispatchScanRunning = true;
|
||||
try {
|
||||
await this.facade.dispatchDueScheduledTasks();
|
||||
} catch (error) {
|
||||
this.logger.error(`Scheduled SMS dispatch scan failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
} finally {
|
||||
this.scheduledDispatchScanRunning = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { Queue } from 'bullmq';
|
||||
import { PhoneRoutingLookupService } from '../dictionaries/phone-routing-lookup.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { RiskReviewService } from '../risk-review/risk-review.service';
|
||||
import { PhoneFrequencyService } from '../risk-review/phone-frequency.service';
|
||||
import type { CreateBatchTaskDto, CreateHttpBatchTaskDto, GatewayInboundAuthDto, GatewayInboundSubmitDto, ImportPreviewDto, ConfirmImportDto, SendJob, QueuePriority, RoutedChannel } from './send-chain.contracts';
|
||||
import { SendBatchEntryService } from './send-batch-entry.service';
|
||||
import { SendGatewaySubmitService } from './send-gateway-submit.service';
|
||||
import { SendInboundEntryService } from './send-inbound-entry.service';
|
||||
import { SendReviewContinuationService } from './send-review-continuation.service';
|
||||
import { SendScheduledDispatchService } from './send-scheduled-dispatch.service';
|
||||
|
||||
|
||||
export type SendSubmissionCallbacks = {
|
||||
releaseMessageReservation: (
|
||||
message: { tenantId: string; batchTaskId: string; messageId: string; amountCents: number | bigint; billingUnits: number },
|
||||
remark: string,
|
||||
) => Promise<void>;
|
||||
recordCmppFailureReceipt: (
|
||||
message: {
|
||||
id: string;
|
||||
tenantId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
applicationId?: string | null;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
cmppSubmitSequenceId?: string | null;
|
||||
cmppSubmitGroupMessageId?: string | null;
|
||||
},
|
||||
errorCode: string,
|
||||
reason: string,
|
||||
) => Promise<unknown>;
|
||||
};
|
||||
|
||||
/**
|
||||
* R9 internal compatibility facade. SendChainService remains the only public NestJS provider.
|
||||
*/
|
||||
export class SendSubmissionService {
|
||||
private readonly batchEntry: SendBatchEntryService;
|
||||
private readonly inboundEntry: SendInboundEntryService;
|
||||
private readonly reviewContinuation: SendReviewContinuationService;
|
||||
private readonly scheduledDispatch: SendScheduledDispatchService;
|
||||
private readonly gatewaySubmit: SendGatewaySubmitService;
|
||||
|
||||
constructor(
|
||||
prisma: PrismaService,
|
||||
billing: BillingService,
|
||||
riskReview: RiskReviewService,
|
||||
phoneFrequency: PhoneFrequencyService,
|
||||
phoneRouting: PhoneRoutingLookupService,
|
||||
facade: SendSubmissionService,
|
||||
callbacks: SendSubmissionCallbacks,
|
||||
) {
|
||||
this.batchEntry = new SendBatchEntryService(prisma, billing, riskReview, phoneFrequency, phoneRouting, facade, callbacks);
|
||||
this.inboundEntry = new SendInboundEntryService(prisma, billing, riskReview, phoneFrequency, phoneRouting, facade, callbacks);
|
||||
this.reviewContinuation = new SendReviewContinuationService(prisma, billing, riskReview, phoneFrequency, phoneRouting, facade, callbacks);
|
||||
this.scheduledDispatch = new SendScheduledDispatchService(prisma, billing, riskReview, phoneFrequency, phoneRouting, facade, callbacks);
|
||||
this.gatewaySubmit = new SendGatewaySubmitService(prisma, billing, riskReview, phoneFrequency, phoneRouting, facade, callbacks);
|
||||
}
|
||||
|
||||
onModuleDestroy() {
|
||||
return this.gatewaySubmit.onModuleDestroy();
|
||||
}
|
||||
|
||||
async createBatchTask(data: CreateBatchTaskDto) {
|
||||
return this.batchEntry.createBatchTask(data);
|
||||
}
|
||||
|
||||
async createHttpBatchTask(data: CreateHttpBatchTaskDto) {
|
||||
return this.batchEntry.createHttpBatchTask(data);
|
||||
}
|
||||
|
||||
async getBatchTask(taskId: string, tenantId?: string, sourceType = 'client') {
|
||||
return this.batchEntry.getBatchTask(taskId, tenantId, sourceType);
|
||||
}
|
||||
|
||||
async previewImport(data: ImportPreviewDto) {
|
||||
return this.batchEntry.previewImport(data);
|
||||
}
|
||||
|
||||
async confirmImport(data: ConfirmImportDto) {
|
||||
return this.batchEntry.confirmImport(data);
|
||||
}
|
||||
|
||||
async resolveUnitPrice(tenantId: string, applicationId?: string) {
|
||||
return this.batchEntry.resolveUnitPrice(tenantId, applicationId);
|
||||
}
|
||||
|
||||
async resolveQueuePriority(tenantId: string, applicationId?: string): Promise<QueuePriority> {
|
||||
return this.batchEntry.resolveQueuePriority(tenantId, applicationId);
|
||||
}
|
||||
|
||||
async resolveApplicationAccessNumber(tenantId: string, applicationId?: string) {
|
||||
return this.batchEntry.resolveApplicationAccessNumber(tenantId, applicationId);
|
||||
}
|
||||
|
||||
async resolveTemplateMessageClassification(
|
||||
tenantId: string,
|
||||
applicationId: string | undefined,
|
||||
templateId: string | undefined,
|
||||
content: string,
|
||||
) {
|
||||
return this.batchEntry.resolveTemplateMessageClassification(tenantId, applicationId, templateId, content);
|
||||
}
|
||||
|
||||
async classifyRejectedPhones(tenantId: string, applicationId: string | undefined, phones: string[]) {
|
||||
return this.batchEntry.classifyRejectedPhones(tenantId, applicationId, phones);
|
||||
}
|
||||
|
||||
async validateSendResources(tenantId: string, applicationId?: string, templateId?: string) {
|
||||
return this.batchEntry.validateSendResources(tenantId, applicationId, templateId);
|
||||
}
|
||||
|
||||
async reserveDailySendQuota(applicationId: string, requestedCount: number) {
|
||||
return this.batchEntry.reserveDailySendQuota(applicationId, requestedCount);
|
||||
}
|
||||
|
||||
async tryReserveDailySendQuota(applicationId: string, requestedCount: number) {
|
||||
return this.batchEntry.tryReserveDailySendQuota(applicationId, requestedCount);
|
||||
}
|
||||
|
||||
async authenticateInboundApplication(data: GatewayInboundAuthDto) {
|
||||
return this.inboundEntry.authenticateInboundApplication(data);
|
||||
}
|
||||
|
||||
async submitInboundMessage(data: GatewayInboundSubmitDto) {
|
||||
return this.inboundEntry.submitInboundMessage(data);
|
||||
}
|
||||
|
||||
async recoverCompletedInboundLongMessageResponse(messageId: string, phoneNumbers: string[]) {
|
||||
return this.inboundEntry.recoverCompletedInboundLongMessageResponse(messageId, phoneNumbers);
|
||||
}
|
||||
|
||||
async submitCompleteInboundMessage(
|
||||
data: GatewayInboundSubmitDto,
|
||||
phoneNumbers: string[],
|
||||
application: Awaited<ReturnType<SendSubmissionService['findInboundApplication']>>,
|
||||
requestedGroupMessageId?: string,
|
||||
) {
|
||||
return this.inboundEntry.submitCompleteInboundMessage(data, phoneNumbers, application, requestedGroupMessageId);
|
||||
}
|
||||
|
||||
async collectInboundLongMessageFragment(
|
||||
data: GatewayInboundSubmitDto,
|
||||
application: NonNullable<Awaited<ReturnType<SendSubmissionService['findInboundApplication']>>>,
|
||||
phoneNumbers: string[],
|
||||
) {
|
||||
return this.inboundEntry.collectInboundLongMessageFragment(data, application, phoneNumbers);
|
||||
}
|
||||
|
||||
async expireInboundLongMessages(now = new Date()) {
|
||||
return this.inboundEntry.expireInboundLongMessages(now);
|
||||
}
|
||||
|
||||
async submitInboundSingleMessage(
|
||||
data: GatewayInboundSubmitDto & { phoneNumber: string },
|
||||
messageId: string,
|
||||
submitGroupMessageId: string,
|
||||
synchronousRejection?: { code: string; reason: string },
|
||||
receiptRejection?: { code: string; reason: string },
|
||||
) {
|
||||
return this.inboundEntry.submitInboundSingleMessage(data, messageId, submitGroupMessageId, synchronousRejection, receiptRejection);
|
||||
}
|
||||
|
||||
async evaluateRiskWithPhoneFrequency(input: {
|
||||
tenantId: string;
|
||||
applicationId: string;
|
||||
templateId?: string;
|
||||
content: string;
|
||||
variables?: Record<string, unknown>;
|
||||
phoneNumber: string;
|
||||
sourceType: 'cmpp';
|
||||
}) {
|
||||
return this.inboundEntry.evaluateRiskWithPhoneFrequency(input);
|
||||
}
|
||||
|
||||
findInboundApplication(account: string) {
|
||||
return this.inboundEntry.findInboundApplication(account);
|
||||
}
|
||||
|
||||
async resolveInboundTemplateCandidate(applicationId: string, content: string) {
|
||||
return this.inboundEntry.resolveInboundTemplateCandidate(applicationId, content);
|
||||
}
|
||||
|
||||
resolveInboundSignatureCandidate(applicationId: string, content: string) {
|
||||
return this.inboundEntry.resolveInboundSignatureCandidate(applicationId, content);
|
||||
}
|
||||
|
||||
async resolveDrainageInfoMatch(signatureId: string | null | undefined, content: string) {
|
||||
return this.inboundEntry.resolveDrainageInfoMatch(signatureId, content);
|
||||
}
|
||||
|
||||
async attachMessageToReviewTask(reviewTaskId: string, messageRecordId: string, signatureId: string, drainageInfoId?: string) {
|
||||
return this.inboundEntry.attachMessageToReviewTask(reviewTaskId, messageRecordId, signatureId, drainageInfoId);
|
||||
}
|
||||
|
||||
async handleReviewDecision(reviewTaskId: string, decision: 'approved' | 'rejected', reason: string) {
|
||||
return this.reviewContinuation.handleReviewDecision(reviewTaskId, decision, reason);
|
||||
}
|
||||
|
||||
async dispatchDueScheduledTasks(now = new Date()) {
|
||||
return this.scheduledDispatch.dispatchDueScheduledTasks(now);
|
||||
}
|
||||
|
||||
async runScheduledDispatchScan() {
|
||||
return this.scheduledDispatch.runScheduledDispatchScan();
|
||||
}
|
||||
|
||||
async enqueueBatchTask(taskId: string) {
|
||||
return this.gatewaySubmit.enqueueBatchTask(taskId);
|
||||
}
|
||||
|
||||
startWorker() {
|
||||
return this.gatewaySubmit.startWorker();
|
||||
}
|
||||
|
||||
async processSendJob(job: SendJob) {
|
||||
return this.gatewaySubmit.processSendJob(job);
|
||||
}
|
||||
|
||||
async submitMessageToGateway(
|
||||
message: {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
batchTaskId: string;
|
||||
applicationId?: string | null;
|
||||
templateId?: string | null;
|
||||
signatureId?: string | null;
|
||||
submitId?: string | null;
|
||||
messageId: string;
|
||||
phoneNumber: string;
|
||||
content: string;
|
||||
billingUnits: number;
|
||||
queuePriority?: string | null;
|
||||
clientSrcId?: string | null;
|
||||
applicationExtension?: string | null;
|
||||
template?: { signature?: { id?: string | null; name?: string | null } | null } | null;
|
||||
signature?: { id?: string | null; name?: string | null } | null;
|
||||
},
|
||||
routed: RoutedChannel,
|
||||
attempt: number,
|
||||
retryOfSubmitRecordId?: string,
|
||||
) {
|
||||
return this.gatewaySubmit.submitMessageToGateway(message, routed, attempt, retryOfSubmitRecordId);
|
||||
}
|
||||
|
||||
async selectChannelForMessage(
|
||||
message: { id: string; tenantId: string; applicationId?: string | null; templateId?: string | null; signatureId?: string | null; phoneNumber: string; carrier?: string | null; province?: string | null; template?: { signature?: { id?: string | null } | null } | null; signature?: { id?: string | null } | null },
|
||||
options: { forceNational?: boolean; excludeChannelIds?: string[] } = {},
|
||||
): Promise<RoutedChannel> {
|
||||
return this.gatewaySubmit.selectChannelForMessage(message, options);
|
||||
}
|
||||
|
||||
async findApplicationRoute(tenantId: string, applicationId: string | undefined, carrier: string) {
|
||||
return this.gatewaySubmit.findApplicationRoute(tenantId, applicationId, carrier);
|
||||
}
|
||||
|
||||
async identifyCarrier(phoneNumber: string) {
|
||||
return this.gatewaySubmit.identifyCarrier(phoneNumber);
|
||||
}
|
||||
|
||||
async identifyProvince(phoneNumber: string) {
|
||||
return this.gatewaySubmit.identifyProvince(phoneNumber);
|
||||
}
|
||||
|
||||
async ensureSignatureReportedForChannel(
|
||||
message: {
|
||||
id: string;
|
||||
templateId?: string | null;
|
||||
template?: { signature?: { id?: string | null; name?: string | null } | null } | null;
|
||||
signature?: { id?: string | null; name?: string | null } | null;
|
||||
},
|
||||
channelId: string,
|
||||
) {
|
||||
return this.gatewaySubmit.ensureSignatureReportedForChannel(message, channelId);
|
||||
}
|
||||
|
||||
async resolveMessageSignatureId(message: { templateId?: string | null; signatureId?: string | null; template?: { signature?: { id?: string | null } | null } | null; signature?: { id?: string | null } | null }) {
|
||||
return this.gatewaySubmit.resolveMessageSignatureId(message);
|
||||
}
|
||||
|
||||
async waitForChannelRateLimit(channelId: string, tps: number) {
|
||||
return this.gatewaySubmit.waitForChannelRateLimit(channelId, tps);
|
||||
}
|
||||
|
||||
async refreshTaskProgress(batchTaskId: string) {
|
||||
return this.gatewaySubmit.refreshTaskProgress(batchTaskId);
|
||||
}
|
||||
|
||||
getSendQueue(): Queue<SendJob, unknown, 'send-message'> {
|
||||
return this.gatewaySubmit.getSendQueue();
|
||||
}
|
||||
|
||||
getGatewayQueue(): Queue {
|
||||
return this.gatewaySubmit.getGatewayQueue();
|
||||
}
|
||||
|
||||
getRedis() {
|
||||
return this.gatewaySubmit.getRedis();
|
||||
}
|
||||
|
||||
async publishGatewaySubmitCommand(command: unknown, idempotencyKey?: string) {
|
||||
return this.gatewaySubmit.publishGatewaySubmitCommand(command, idempotencyKey);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { BadRequestException, HttpException, HttpStatus, Logger, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { BillingService } from '../billing/billing.service';
|
||||
import { moneyToNumber } from '../common/money';
|
||||
import type { OpenApiService } from '../open-api/open-api.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type { GatewaySubmitResultDto, GatewaySubmitSegmentResultDto, GatewayReceiptEventDto, GatewayUplinkEventDto, GatewayPendingDeliveryQueryDto, GatewayDownstreamSentDto, GatewayDownstreamAcknowledgedDto, GatewayDownstreamFailureType, GatewayControlDeliveryResult, GatewaySubmitDeadLetterDto, RequeueGatewaySubmitExceptionDto, GatewayDownstreamRecoveryStatusDto, TimeoutUnknownDto } from './send-chain.contracts';
|
||||
import { positiveInteger, normalizeReceiptStatus, normalizeCarrier, DEFAULT_DOWNSTREAM_RETRY_DELAY_MS, DEFAULT_DOWNSTREAM_RETRY_MAX_DELAY_MS, DEFAULT_DOWNSTREAM_MAX_RETRIES, DEFAULT_DOWNSTREAM_PENDING_TIMEOUT_HOURS, DEFAULT_RECEIPT_TIMEOUT_HOURS, DEFAULT_GATEWAY_SUBMIT_REQUEUE_STALE_MS, DEFAULT_DOWNSTREAM_MANUAL_REQUEUE_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_ATTEMPTS, DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_AGE_HOURS, gatewaySubmitRequeueKey, isObjectRecord, asDateOrNull, downstreamRetryDelayMs, downstreamAckTimeoutMs, downstreamRetryBaseDelayMs, downstreamRetryMaxDelayMs, downstreamMaxRetries, downstreamPendingTimeoutHours, downstreamControlFailureMessage, normalizeSubmitStatus, downstreamDeliveryAttemptKey, hasRecoveryAuditStateChanged, normalizeRecoveryFailureCategory, aggregateReceiptSegmentState, isSameUpstreamEndpointIdentity, receiptEventKey } from './send-chain.helpers';
|
||||
import type { SendSubmissionService } from './send-submission.service';
|
||||
import type { SendCompletionCallbacks, SendCompletionFacade } from './send-completion.service';
|
||||
|
||||
|
||||
/**
|
||||
* R10 timeout implementation.
|
||||
* Cross-domain calls return through the stable SendChainService seam to preserve locking and test observability.
|
||||
*/
|
||||
export class SendTimeoutService {
|
||||
private readonly logger = new Logger('SendChainService');
|
||||
private receiptTimeoutScanRunning = false;
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly billing: BillingService,
|
||||
private readonly openApi: OpenApiService | undefined,
|
||||
private readonly facade: SendCompletionFacade,
|
||||
private readonly callbacks: SendCompletionCallbacks,
|
||||
) {}
|
||||
|
||||
async markUnknownTimeout(data: TimeoutUnknownDto) {
|
||||
const olderThanHours = data.olderThanHours ?? positiveInteger(process.env.SMS_RECEIPT_TIMEOUT_HOURS, DEFAULT_RECEIPT_TIMEOUT_HOURS);
|
||||
const cutoff = new Date(Date.now() - olderThanHours * 60 * 60 * 1000);
|
||||
const candidates = await this.prisma.smsMessageRecord.findMany({
|
||||
where: {
|
||||
tenantId: { not: null },
|
||||
status: { in: ['submitted', 'unknown'] },
|
||||
submittedAt: { lte: cutoff },
|
||||
},
|
||||
select: { id: true, tenantId: true, batchTaskId: true, messageId: true, amountCents: true, billingUnits: true },
|
||||
take: 10000,
|
||||
});
|
||||
const timedOutTaskIds = new Set<string>();
|
||||
let timeout = 0;
|
||||
for (const candidate of candidates) {
|
||||
if (!candidate.tenantId) continue;
|
||||
const transitioned = await this.prisma.smsMessageRecord.updateMany({
|
||||
where: { id: candidate.id, status: { in: ['submitted', 'unknown'] } },
|
||||
data: { status: 'timeout', timeoutAt: new Date(), errorMessage: `${olderThanHours}小时未收到明确回执,自动转超时` },
|
||||
});
|
||||
if (transitioned.count !== 1) continue;
|
||||
timeout += 1;
|
||||
await this.facade.refundMessage(candidate as typeof candidate & { tenantId: string }, `${olderThanHours}小时未收到明确回执,自动超时退款`);
|
||||
if (candidate.batchTaskId) timedOutTaskIds.add(candidate.batchTaskId);
|
||||
}
|
||||
for (const batchTaskId of timedOutTaskIds) {
|
||||
await this.facade.refreshTaskProgress(batchTaskId);
|
||||
}
|
||||
return { timeout };
|
||||
}
|
||||
|
||||
async markExpiredDownstreamDeliveries(olderThanHours = downstreamPendingTimeoutHours()) {
|
||||
const cutoff = new Date(Date.now() - olderThanHours * 60 * 60_000);
|
||||
const expired = await this.prisma.cmppDownstreamDelivery.findMany({
|
||||
where: {
|
||||
status: 'pending',
|
||||
OR: [
|
||||
{ lastRetriedAt: null, createdAt: { lte: cutoff } },
|
||||
{ lastRetriedAt: { lte: cutoff } },
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
take: 500,
|
||||
});
|
||||
for (const delivery of expired) {
|
||||
await this.facade.markDownstreamDeliveryFailed(
|
||||
delivery.id,
|
||||
`下游投递排队超过 ${olderThanHours} 小时,系统自动终止重试`,
|
||||
'queue_timeout',
|
||||
);
|
||||
}
|
||||
return { failed: expired.length };
|
||||
}
|
||||
|
||||
async runReceiptTimeoutScan() {
|
||||
if (this.receiptTimeoutScanRunning) return;
|
||||
this.receiptTimeoutScanRunning = true;
|
||||
try {
|
||||
const [receiptResult, downstreamResult, requeueRecoveryResult, downstreamManualRecoveryResult] = await Promise.all([
|
||||
this.facade.markUnknownTimeout({}),
|
||||
this.facade.markExpiredDownstreamDeliveries(),
|
||||
this.facade.recoverStaleGatewaySubmitRequeues(),
|
||||
this.facade.recoverStaleDownstreamManualRequeues(),
|
||||
]);
|
||||
if (receiptResult.timeout > 0) this.logger.log(`Marked ${receiptResult.timeout} messages as receipt timeout and refunded charged messages`);
|
||||
if (downstreamResult.failed > 0) this.logger.log(`Terminated ${downstreamResult.failed} expired downstream deliveries`);
|
||||
if (requeueRecoveryResult.recovered > 0) this.logger.log(`Recovered ${requeueRecoveryResult.recovered} stale Gateway submit requeues`);
|
||||
if (downstreamManualRecoveryResult.recovered > 0) this.logger.log(`Recovered ${downstreamManualRecoveryResult.recovered} stale downstream manual requeues`);
|
||||
} catch (error) {
|
||||
this.logger.error('Receipt timeout scan failed', error instanceof Error ? error.stack : String(error));
|
||||
} finally {
|
||||
this.receiptTimeoutScanRunning = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,8 @@ import { RequireRecentAuthentication } from '../auth/require-recent-authenticati
|
||||
import { CurrentSessionUserId } from '../auth/current-session-user.decorator';
|
||||
import { ReviewDecisionDto, ReviewGovernanceService } from './review-governance.service';
|
||||
import { DeleteTargetDto, DeletionGovernanceService } from '../deletion-governance/deletion-governance.service';
|
||||
import { CreateSmsApplicationDto, CreateSmsDrainageInfoDto, CreateSmsSignatureDto, CreateSmsTemplateDto, ReplaceApplicationRouteRulesDto, ReviewDto, SmsConfigService, StatusChangeDto, UpdateSmsApplicationDto, UpdateSmsDrainageInfoDto, UpdateSmsSignatureDto, UpdateSmsTemplateDto } from './sms-config.service';
|
||||
import { SmsConfigService } from './sms-config.service';
|
||||
import { CreateSmsApplicationDto, CreateSmsDrainageInfoDto, CreateSmsSignatureDto, CreateSmsTemplateDto, ReplaceApplicationRouteRulesDto, ReviewDto, StatusChangeDto, UpdateSmsApplicationDto, UpdateSmsDrainageInfoDto, UpdateSmsSignatureDto, UpdateSmsTemplateDto } from './sms-config.contracts';
|
||||
|
||||
@ApiTags('admin-sms-config')
|
||||
@Controller('admin')
|
||||
|
||||
@@ -0,0 +1,513 @@
|
||||
import { BadRequestException, ForbiddenException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomInt, randomUUID } from 'node:crypto';
|
||||
import { isIpAllowed } from '../common/ip-allowlist';
|
||||
import { assertMoneyUnits } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { automaticDeliveryMode } from '../open-api/delivery-mode';
|
||||
import type { ApplicationListQuery, CreateSignatureMaterialDto, CreateSmsApplicationDto, CreateSmsDrainageInfoDto, CreateSmsSignatureDto, CreateSmsSignatureOptions, CreateSmsTemplateDto, CreateSmsTemplateOptions, DrainageInfoListQuery, GatewayDownstreamConnectionEventDto, ReplaceApplicationRouteRulesDto, ReviewDto, SignatureListQuery, StatusChangeDto, TemplateListQuery, UpdateSmsApplicationDto, UpdateSmsDrainageInfoDto, UpdateSmsSignatureDto, UpdateSmsTemplateDto } from './sms-config.contracts';
|
||||
import { APPLICATION_DISABLE_GRACE_MS, DEFAULT_APPLICATION_DISABLE_SCAN_INTERVAL_MS, DEFAULT_DOWNSTREAM_HEARTBEAT_TIMEOUT_MS, UNRESOLVED_DOWNSTREAM_STATUSES, type TemplateVariableInput, estimateBillingUnits, generateApplicationPassword, getPositiveInteger, getPositiveIntegerEnv, hasReportValue, inferTemplateVariables, isRecord, normalizeApplicationCmppStatus, normalizeApplicationInterfaceType, normalizeApplicationPassword, normalizeApplicationQueuePriority, normalizeCmppAccessNumberConfig, normalizeSmsSignature, parseGatewayDate, reportValueParts, startOfToday, validateAndNormalizeTemplateVariables, validateCompleteSmsSignature } from './sms-config.helpers';
|
||||
import { SmsApplicationLifecycleService } from './application-lifecycle.service';
|
||||
|
||||
/** R3 domain service. Kept framework-agnostic and composed behind SmsConfigService. */
|
||||
export class SmsApplicationConfigService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly lifecycle: SmsApplicationLifecycleService) {}
|
||||
async listApplications(queryOrTenantId?: string | ApplicationListQuery) {
|
||||
const query = typeof queryOrTenantId === 'string' ? { tenantId: queryOrTenantId } : queryOrTenantId ?? {};
|
||||
if (query.includeConnections) {
|
||||
await this.lifecycle.markTimedOutDownstreamConnections();
|
||||
}
|
||||
const applications = await this.prisma.smsApplication.findMany({
|
||||
where: {
|
||||
tenantId: query.tenantId,
|
||||
status: query.status && query.status !== 'all' ? query.status : { not: 'deleted' },
|
||||
tenant: query.enterpriseKeyword ? { name: { contains: query.enterpriseKeyword } } : undefined,
|
||||
name: query.applicationKeyword ? { contains: query.applicationKeyword } : undefined,
|
||||
OR: query.keyword ? [
|
||||
{ name: { contains: query.keyword } },
|
||||
{ tenant: { name: { contains: query.keyword } } },
|
||||
] : undefined,
|
||||
},
|
||||
include: {
|
||||
tenant: true,
|
||||
ipAllowlist: true,
|
||||
httpConfig: true,
|
||||
},
|
||||
omit: {
|
||||
secretHash: true,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
...(query.page && query.pageSize ? {
|
||||
skip: (query.page - 1) * query.pageSize,
|
||||
take: query.pageSize,
|
||||
} : {}),
|
||||
});
|
||||
if (!query.includeConnections) {
|
||||
return applications;
|
||||
}
|
||||
const applicationIds = applications.map((application) => application.id);
|
||||
const [connections, messageStats] = await Promise.all([
|
||||
this.prisma.cmppDownstreamConnection.findMany({
|
||||
where: { applicationId: { in: applicationIds }, status: 'connected' },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
}),
|
||||
this.prisma.smsMessageRecord.groupBy({
|
||||
by: ['applicationId', 'status'],
|
||||
where: { applicationId: { in: applicationIds }, queuedAt: { gte: startOfToday() } },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
]);
|
||||
const disablingDetails = new Map((await Promise.all(applications
|
||||
.filter((application) => application.status === 'disabling')
|
||||
.map(async (application) => [application.id, await this.lifecycle.getApplicationDeactivationPreview(application.id)] as const))));
|
||||
return applications.map((application) => {
|
||||
const appConnections = connections.filter((connection) => connection.applicationId === application.id);
|
||||
const appStats = messageStats.filter((item) => item.applicationId === application.id);
|
||||
const todayTotal = appStats.reduce((sum, item) => sum + item._count._all, 0);
|
||||
const delivered = appStats.find((item) => item.status === 'delivered')?._count._all ?? 0;
|
||||
return {
|
||||
...application,
|
||||
cmppConnections: appConnections,
|
||||
cmppStatus: normalizeApplicationCmppStatus(appConnections, application.status),
|
||||
sentToday: todayTotal,
|
||||
deliveryRate: todayTotal > 0 ? Number(((delivered / todayTotal) * 100).toFixed(1)) : 0,
|
||||
deactivation: disablingDetails.get(application.id) ?? null,
|
||||
};
|
||||
}).sort((left, right) => right.sentToday - left.sentToday
|
||||
|| left.name.localeCompare(right.name, 'zh-CN')
|
||||
|| left.id.localeCompare(right.id));
|
||||
}
|
||||
|
||||
async listApplicationsPage(query: ApplicationListQuery) {
|
||||
const page = Math.max(1, Math.floor(Number(query.page) || 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 10)));
|
||||
const where: Prisma.SmsApplicationWhereInput = {
|
||||
tenantId: query.tenantId,
|
||||
status: query.status && query.status !== 'all' ? query.status : { not: 'deleted' },
|
||||
tenant: query.enterpriseKeyword ? { name: { contains: query.enterpriseKeyword } } : undefined,
|
||||
name: query.applicationKeyword ? { contains: query.applicationKeyword } : undefined,
|
||||
OR: query.keyword ? [
|
||||
{ name: { contains: query.keyword } },
|
||||
{ tenant: { name: { contains: query.keyword } } },
|
||||
] : undefined,
|
||||
};
|
||||
const [items, total] = await Promise.all([
|
||||
this.listApplications({ ...query, page, pageSize }),
|
||||
this.prisma.smsApplication.count({ where }),
|
||||
]);
|
||||
return { items, total, page, pageSize };
|
||||
}
|
||||
|
||||
listApplicationOptions(tenantId?: string) {
|
||||
return this.prisma.smsApplication.findMany({
|
||||
where: { tenantId, status: { not: 'deleted' } },
|
||||
select: { id: true, tenantId: true, name: true, status: true },
|
||||
orderBy: [{ name: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
}
|
||||
|
||||
async getApplication(applicationId: string, tenantId?: string) {
|
||||
const application = await this.prisma.smsApplication.findUnique({
|
||||
where: { id: applicationId },
|
||||
include: {
|
||||
tenant: true,
|
||||
ipAllowlist: true,
|
||||
httpConfig: true,
|
||||
},
|
||||
});
|
||||
if (!application || (tenantId && application.tenantId !== tenantId)) {
|
||||
throw new NotFoundException('Application not found');
|
||||
}
|
||||
return application;
|
||||
}
|
||||
|
||||
async getApplicationReportFields(applicationId?: string, reportType?: 'signature' | 'drainage') {
|
||||
if (applicationId) await this.getApplication(applicationId);
|
||||
const [commonFields, routes] = await Promise.all([
|
||||
this.prisma.commonReportField.findMany({
|
||||
where: {
|
||||
status: 'active',
|
||||
reportType,
|
||||
drainageField: { status: 'active' },
|
||||
},
|
||||
include: { drainageField: true },
|
||||
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }],
|
||||
}),
|
||||
applicationId ? this.prisma.channelRouteRule.findMany({
|
||||
where: { applicationId, status: 'active' },
|
||||
include: {
|
||||
group: {
|
||||
include: {
|
||||
items: {
|
||||
include: {
|
||||
channel: {
|
||||
include: {
|
||||
reportFields: { include: { drainageField: true }, orderBy: { sortOrder: 'asc' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { priority: 'asc' },
|
||||
}) : Promise.resolve([]),
|
||||
]);
|
||||
type MergedReportField = {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
fieldType: string;
|
||||
required: boolean;
|
||||
description?: string | null;
|
||||
reportTypes: string[];
|
||||
commonReportTypes: string[];
|
||||
channels: Array<{ id: string; code: string; name: string; groupId: string; groupName: string; required: boolean; reportType: string; source: 'common' | 'channel' | 'both' }>;
|
||||
};
|
||||
const merged = new Map<string, MergedReportField>();
|
||||
const routeChannels = new Map<string, { id: string; code: string; name: string; groupId: string; groupName: string }>();
|
||||
for (const route of routes) {
|
||||
if (!route.group) continue;
|
||||
for (const item of route.group.items) {
|
||||
if (!routeChannels.has(item.channel.id)) {
|
||||
routeChannels.set(item.channel.id, {
|
||||
id: item.channel.id,
|
||||
code: item.channel.code,
|
||||
name: item.channel.name,
|
||||
groupId: route.group.id,
|
||||
groupName: route.group.name,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const configured of commonFields) {
|
||||
merged.set(configured.drainageField.id, {
|
||||
id: configured.drainageField.id,
|
||||
code: configured.drainageField.code,
|
||||
name: configured.drainageField.name,
|
||||
fieldType: configured.drainageField.fieldType,
|
||||
required: configured.required,
|
||||
description: configured.drainageField.description,
|
||||
reportTypes: [configured.reportType],
|
||||
commonReportTypes: [configured.reportType],
|
||||
channels: Array.from(routeChannels.values()).map((channel) => ({
|
||||
...channel,
|
||||
required: configured.required,
|
||||
reportType: configured.reportType,
|
||||
source: 'common' as const,
|
||||
})),
|
||||
});
|
||||
}
|
||||
for (const route of routes) {
|
||||
if (!route.group) continue;
|
||||
for (const item of route.group.items) {
|
||||
for (const configured of item.channel.reportFields) {
|
||||
if (configured.status !== 'active' || !configured.drainageField || configured.drainageField.status !== 'active') continue;
|
||||
if (reportType && configured.reportType !== 'both' && configured.reportType !== reportType) continue;
|
||||
const key = configured.drainageField.id;
|
||||
const current: MergedReportField = merged.get(key) ?? {
|
||||
id: configured.drainageField.id,
|
||||
code: configured.drainageField.code,
|
||||
name: configured.drainageField.name,
|
||||
fieldType: configured.drainageField.fieldType,
|
||||
required: false,
|
||||
description: configured.drainageField.description,
|
||||
reportTypes: [],
|
||||
commonReportTypes: [],
|
||||
channels: [],
|
||||
};
|
||||
current.required = current.required || configured.required;
|
||||
if (!current.reportTypes.includes(configured.reportType)) current.reportTypes.push(configured.reportType);
|
||||
const existingChannel = current.channels.find((channel) => channel.id === item.channel.id);
|
||||
if (existingChannel) {
|
||||
existingChannel.required = existingChannel.required || configured.required;
|
||||
existingChannel.reportType = configured.reportType;
|
||||
existingChannel.source = existingChannel.source === 'common' ? 'both' : existingChannel.source;
|
||||
} else {
|
||||
current.channels.push({
|
||||
id: item.channel.id,
|
||||
code: item.channel.code,
|
||||
name: item.channel.name,
|
||||
groupId: route.group.id,
|
||||
groupName: route.group.name,
|
||||
required: configured.required,
|
||||
reportType: configured.reportType,
|
||||
source: 'channel',
|
||||
});
|
||||
}
|
||||
merged.set(key, current);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Array.from(merged.values());
|
||||
}
|
||||
|
||||
async getClientApplicationReportFields(applicationId?: string, reportType?: 'signature' | 'drainage') {
|
||||
const fields = await this.getApplicationReportFields(applicationId, reportType);
|
||||
return fields.map(({ channels: _channels, commonReportTypes: _commonReportTypes, ...field }) => field);
|
||||
}
|
||||
|
||||
async createApplication(data: CreateSmsApplicationDto) {
|
||||
assertMoneyUnits(data.customerUnitPrice ?? 0, '客户单价');
|
||||
const secret = normalizeApplicationPassword(data.passwordCipher);
|
||||
const queuePriority = normalizeApplicationQueuePriority(data.queuePriority);
|
||||
const interfaceType = normalizeApplicationInterfaceType(data.interfaceType);
|
||||
const cmppAccount = data.cmppAccount ? await this.validateAndReserveCmppAccount(data.cmppAccount) : await this.generateCmppAccount();
|
||||
const cmppEnterpriseCode = cmppAccount;
|
||||
const accessNumber = normalizeCmppAccessNumberConfig(data);
|
||||
await this.validateClientSrcIdAvailable(accessNumber.clientSrcId);
|
||||
return this.prisma.smsApplication.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
name: data.name,
|
||||
scene: data.scene,
|
||||
callbackUrl: data.callbackUrl,
|
||||
cmppAccount,
|
||||
cmppEnterpriseCode,
|
||||
cmppApplicationExtension: accessNumber.applicationExtension,
|
||||
cmppAccessNumberFillEnabled: accessNumber.fillEnabled,
|
||||
cmppAccessNumberFillPrefix: accessNumber.fillPrefix,
|
||||
cmppClientSrcId: accessNumber.clientSrcId,
|
||||
secretHash: secret,
|
||||
interfaceEnabled: data.interfaceEnabled ?? true,
|
||||
interfaceType,
|
||||
cmppMaxConnections: getPositiveInteger(data.cmppMaxConnections, 1, 'cmppMaxConnections'),
|
||||
cmppWindowSize: getPositiveInteger(data.cmppWindowSize, 16, 'cmppWindowSize'),
|
||||
dailyLimit: getPositiveInteger(data.dailyLimit, 100000, 'dailyLimit'),
|
||||
customerUnitPrice: data.customerUnitPrice ?? 0,
|
||||
queuePriority,
|
||||
templateMismatchMode: data.templateMismatchMode ?? 'reject',
|
||||
downstreamReceiptRetryEnabled: data.downstreamReceiptRetryEnabled ?? true,
|
||||
downstreamUplinkRetryEnabled: data.downstreamUplinkRetryEnabled ?? true,
|
||||
ipAllowlist: {
|
||||
create: (data.ipAllowlist ?? []).map((ipCidr) => ({ ipCidr })),
|
||||
},
|
||||
},
|
||||
include: { ipAllowlist: true },
|
||||
});
|
||||
}
|
||||
|
||||
async updateApplication(applicationId: string, data: UpdateSmsApplicationDto) {
|
||||
const application = await this.prisma.smsApplication.findUnique({
|
||||
where: { id: applicationId },
|
||||
include: { httpConfig: true },
|
||||
});
|
||||
if (!application) {
|
||||
throw new NotFoundException('Application not found');
|
||||
}
|
||||
if (data.customerUnitPrice !== undefined) {
|
||||
assertMoneyUnits(data.customerUnitPrice, '客户单价');
|
||||
}
|
||||
const queuePriority = data.queuePriority === undefined
|
||||
? undefined
|
||||
: normalizeApplicationQueuePriority(data.queuePriority);
|
||||
const cmppAccount = data.cmppAccount === undefined
|
||||
? undefined
|
||||
: await this.validateAndReserveCmppAccount(data.cmppAccount, applicationId);
|
||||
const cmppEnterpriseCode = cmppAccount ?? application.cmppAccount;
|
||||
const interfaceType = data.interfaceType === undefined
|
||||
? undefined
|
||||
: normalizeApplicationInterfaceType(data.interfaceType);
|
||||
const secretHash = data.passwordCipher === undefined
|
||||
? undefined
|
||||
: normalizeApplicationPassword(data.passwordCipher);
|
||||
const accessNumberChanged = data.cmppApplicationExtension !== undefined
|
||||
|| data.cmppAccessNumberFillEnabled !== undefined
|
||||
|| data.cmppAccessNumberFillPrefix !== undefined;
|
||||
const accessNumber = accessNumberChanged
|
||||
? normalizeCmppAccessNumberConfig(data, application)
|
||||
: undefined;
|
||||
if (accessNumber?.clientSrcId && accessNumber.clientSrcId !== application.cmppClientSrcId) {
|
||||
await this.validateClientSrcIdAvailable(accessNumber.clientSrcId, applicationId);
|
||||
}
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
if (data.ipAllowlist) {
|
||||
await tx.smsApplicationIpAllowlist.deleteMany({ where: { applicationId } });
|
||||
}
|
||||
const updated = await tx.smsApplication.update({
|
||||
where: { id: applicationId },
|
||||
data: {
|
||||
name: data.name,
|
||||
scene: data.scene,
|
||||
callbackUrl: data.callbackUrl,
|
||||
cmppAccount,
|
||||
cmppEnterpriseCode,
|
||||
cmppApplicationExtension: accessNumber?.applicationExtension,
|
||||
cmppAccessNumberFillEnabled: accessNumber?.fillEnabled,
|
||||
cmppAccessNumberFillPrefix: accessNumber?.fillPrefix,
|
||||
cmppClientSrcId: accessNumber?.clientSrcId,
|
||||
secretHash,
|
||||
interfaceEnabled: data.interfaceEnabled,
|
||||
interfaceType,
|
||||
cmppMaxConnections: data.cmppMaxConnections === undefined ? undefined : getPositiveInteger(data.cmppMaxConnections, 1, 'cmppMaxConnections'),
|
||||
cmppWindowSize: data.cmppWindowSize === undefined ? undefined : getPositiveInteger(data.cmppWindowSize, 16, 'cmppWindowSize'),
|
||||
dailyLimit: data.dailyLimit === undefined ? undefined : getPositiveInteger(data.dailyLimit, 100000, 'dailyLimit'),
|
||||
customerUnitPrice: data.customerUnitPrice,
|
||||
queuePriority,
|
||||
templateMismatchMode: data.templateMismatchMode,
|
||||
downstreamReceiptRetryEnabled: data.downstreamReceiptRetryEnabled,
|
||||
downstreamUplinkRetryEnabled: data.downstreamUplinkRetryEnabled,
|
||||
status: data.status,
|
||||
ipAllowlist: data.ipAllowlist ? {
|
||||
create: data.ipAllowlist.map((ipCidr) => ({ ipCidr })),
|
||||
} : undefined,
|
||||
},
|
||||
include: { tenant: true, ipAllowlist: true },
|
||||
});
|
||||
if (data.interfaceEnabled !== undefined && application.httpConfig) {
|
||||
const deliveryMode = automaticDeliveryMode(data.interfaceEnabled, application.httpConfig.enabled);
|
||||
await tx.smsApplicationHttpConfig.update({
|
||||
where: { applicationId },
|
||||
data: {
|
||||
receiptDeliveryMode: deliveryMode,
|
||||
uplinkDeliveryMode: deliveryMode,
|
||||
},
|
||||
});
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
async replaceApplicationRouteRules(applicationId: string, data: ReplaceApplicationRouteRulesDto) {
|
||||
const application = await this.prisma.smsApplication.findUnique({ where: { id: applicationId } });
|
||||
if (!application) {
|
||||
throw new NotFoundException('Application not found');
|
||||
}
|
||||
const routes = data.routes ?? [];
|
||||
if (routes.length === 0) {
|
||||
throw new BadRequestException('At least one carrier channel group is required');
|
||||
}
|
||||
|
||||
const carriers = new Set<string>();
|
||||
routes.forEach((route) => {
|
||||
if (!['mobile', 'unicom', 'telecom'].includes(route.carrier)) {
|
||||
throw new BadRequestException('carrier must be mobile, unicom or telecom');
|
||||
}
|
||||
if (carriers.has(route.carrier)) {
|
||||
throw new BadRequestException('Duplicate carrier route is not allowed');
|
||||
}
|
||||
carriers.add(route.carrier);
|
||||
});
|
||||
|
||||
const groups = await this.prisma.smsChannelGroup.findMany({
|
||||
where: { id: { in: routes.map((route) => route.groupId) }, status: { not: 'deleted' } },
|
||||
select: { id: true, carrier: true },
|
||||
});
|
||||
const groupMap = new Map(groups.map((group) => [group.id, group]));
|
||||
routes.forEach((route) => {
|
||||
const group = groupMap.get(route.groupId);
|
||||
if (!group) {
|
||||
throw new BadRequestException(`channel group ${route.groupId} does not exist`);
|
||||
}
|
||||
if (group.carrier !== route.carrier) {
|
||||
throw new BadRequestException('channel group carrier must match route carrier');
|
||||
}
|
||||
});
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
await tx.channelRouteRule.deleteMany({
|
||||
where: {
|
||||
applicationId,
|
||||
channelId: null,
|
||||
province: null,
|
||||
},
|
||||
});
|
||||
await tx.channelRouteRule.createMany({
|
||||
data: routes.map((route, index) => ({
|
||||
tenantId: application.tenantId,
|
||||
applicationId,
|
||||
groupId: route.groupId,
|
||||
carrier: route.carrier,
|
||||
priority: route.priority ?? (index + 1) * 10,
|
||||
status: route.status ?? 'active',
|
||||
})),
|
||||
});
|
||||
return tx.channelRouteRule.findMany({
|
||||
where: { applicationId, channelId: null, province: null, status: { not: 'deleted' } },
|
||||
orderBy: [{ priority: 'asc' }, { createdAt: 'asc' }],
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async resetApplicationSecret(applicationId: string, data: StatusChangeDto = {}) {
|
||||
const application = await this.prisma.smsApplication.findUnique({ where: { id: applicationId } });
|
||||
if (!application) {
|
||||
throw new NotFoundException('Application not found');
|
||||
}
|
||||
const secret = generateApplicationPassword();
|
||||
const updated = await this.prisma.smsApplication.update({
|
||||
where: { id: applicationId },
|
||||
data: { secretHash: secret },
|
||||
});
|
||||
await this.lifecycle.writeOperationLog(application.tenantId, data.operatorId, 'sms_application.secret_reset', 'sms_application', applicationId, {
|
||||
reason: data.reason,
|
||||
});
|
||||
return { ...updated, secret };
|
||||
}
|
||||
|
||||
async getApplicationCmppParams(applicationId: string, tenantId?: string) {
|
||||
const application = await this.prisma.smsApplication.findUnique({
|
||||
where: { id: applicationId },
|
||||
include: { tenant: true },
|
||||
});
|
||||
if (!application || (tenantId && application.tenantId !== tenantId)) {
|
||||
throw new NotFoundException('Application not found');
|
||||
}
|
||||
if (tenantId && !application.interfaceEnabled) {
|
||||
throw new ForbiddenException('该企业应用未开通 CMPP 接口');
|
||||
}
|
||||
return {
|
||||
applicationId: application.id,
|
||||
applicationName: application.name,
|
||||
tenantId: application.tenantId,
|
||||
tenantName: application.tenant.name,
|
||||
appCode: application.id,
|
||||
gatewayHost: process.env.CMPP_PUBLIC_HOST?.trim() || '127.0.0.1',
|
||||
gatewayPort: getPositiveIntegerEnv('CMPP_PUBLIC_PORT', 17890),
|
||||
enterpriseCode: application.cmppEnterpriseCode,
|
||||
account: application.cmppAccount,
|
||||
passwordCipher: application.secretHash,
|
||||
srcId: application.cmppClientSrcId ?? '',
|
||||
applicationExtension: application.cmppApplicationExtension,
|
||||
accessNumberFillEnabled: application.cmppAccessNumberFillEnabled,
|
||||
accessNumberFillPrefix: application.cmppAccessNumberFillPrefix,
|
||||
interfaceEnabled: application.interfaceEnabled,
|
||||
interfaceType: application.interfaceType,
|
||||
maxConnections: application.cmppMaxConnections,
|
||||
heartbeatSeconds: 30,
|
||||
windowSize: application.cmppWindowSize,
|
||||
protocolVersion: application.interfaceType === 'cmpp20' ? 'CMPP2.0' : application.interfaceType,
|
||||
};
|
||||
}
|
||||
|
||||
async validateAndReserveCmppAccount(cmppAccount: string, currentApplicationId?: string) {
|
||||
if (!/^\d{6}$/.test(cmppAccount)) {
|
||||
throw new BadRequestException('cmppAccount must be a 6-digit number');
|
||||
}
|
||||
const exists = await this.prisma.smsApplication.findUnique({ where: { cmppAccount } });
|
||||
if (exists && exists.id !== currentApplicationId) {
|
||||
throw new BadRequestException('cmppAccount already exists');
|
||||
}
|
||||
return cmppAccount;
|
||||
}
|
||||
|
||||
async validateClientSrcIdAvailable(clientSrcId: string | null, currentApplicationId?: string) {
|
||||
if (!clientSrcId) return;
|
||||
const exists = await this.prisma.smsApplication.findUnique({ where: { cmppClientSrcId: clientSrcId } });
|
||||
if (exists && exists.id !== currentApplicationId) {
|
||||
throw new BadRequestException('client CMPP Src_Id already exists');
|
||||
}
|
||||
}
|
||||
|
||||
async generateCmppAccount() {
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
const cmppAccount = String(randomInt(100000, 1000000));
|
||||
const exists = await this.prisma.smsApplication.findUnique({ where: { cmppAccount } });
|
||||
if (!exists) {
|
||||
return cmppAccount;
|
||||
}
|
||||
}
|
||||
throw new BadRequestException('Unable to generate unique CMPP account');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
import { BadRequestException, ForbiddenException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomInt, randomUUID } from 'node:crypto';
|
||||
import { isIpAllowed } from '../common/ip-allowlist';
|
||||
import { assertMoneyUnits } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { automaticDeliveryMode } from '../open-api/delivery-mode';
|
||||
import type { ApplicationListQuery, CreateSignatureMaterialDto, CreateSmsApplicationDto, CreateSmsDrainageInfoDto, CreateSmsSignatureDto, CreateSmsSignatureOptions, CreateSmsTemplateDto, CreateSmsTemplateOptions, DrainageInfoListQuery, GatewayDownstreamConnectionEventDto, ReplaceApplicationRouteRulesDto, ReviewDto, SignatureListQuery, StatusChangeDto, TemplateListQuery, UpdateSmsApplicationDto, UpdateSmsDrainageInfoDto, UpdateSmsSignatureDto, UpdateSmsTemplateDto } from './sms-config.contracts';
|
||||
import { APPLICATION_DISABLE_GRACE_MS, DEFAULT_APPLICATION_DISABLE_SCAN_INTERVAL_MS, DEFAULT_DOWNSTREAM_HEARTBEAT_TIMEOUT_MS, UNRESOLVED_DOWNSTREAM_STATUSES, type TemplateVariableInput, estimateBillingUnits, generateApplicationPassword, getPositiveInteger, getPositiveIntegerEnv, hasReportValue, inferTemplateVariables, isRecord, normalizeApplicationCmppStatus, normalizeApplicationInterfaceType, normalizeApplicationPassword, normalizeApplicationQueuePriority, normalizeCmppAccessNumberConfig, normalizeSmsSignature, parseGatewayDate, reportValueParts, startOfToday, validateAndNormalizeTemplateVariables, validateCompleteSmsSignature } from './sms-config.helpers';
|
||||
|
||||
|
||||
/** R3 domain service. Kept framework-agnostic and composed behind SmsConfigService. */
|
||||
export class SmsApplicationLifecycleService {
|
||||
private readonly logger = new Logger(SmsApplicationLifecycleService.name);
|
||||
private applicationDisableTimer?: ReturnType<typeof setInterval>;
|
||||
private applicationDisableScanRunning = false;
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
onModuleInit() {
|
||||
this.applicationDisableTimer = setInterval(
|
||||
() => void this.runApplicationDisableScan(),
|
||||
getPositiveIntegerEnv('APPLICATION_DISABLE_SCAN_INTERVAL_MS', DEFAULT_APPLICATION_DISABLE_SCAN_INTERVAL_MS),
|
||||
);
|
||||
this.applicationDisableTimer.unref?.();
|
||||
void this.runApplicationDisableScan();
|
||||
}
|
||||
|
||||
onModuleDestroy() {
|
||||
if (this.applicationDisableTimer) clearInterval(this.applicationDisableTimer);
|
||||
}
|
||||
|
||||
async changeApplicationStatus(applicationId: string, data: StatusChangeDto) {
|
||||
const application = await this.prisma.smsApplication.findUnique({ where: { id: applicationId } });
|
||||
if (!application) {
|
||||
throw new NotFoundException('Application not found');
|
||||
}
|
||||
const status = data.status ?? 'disabled';
|
||||
if (status === 'active') {
|
||||
const updated = await this.prisma.smsApplication.update({
|
||||
where: { id: applicationId },
|
||||
data: { status: 'active', disablingAt: null, autoDisableAt: null, disableReason: null },
|
||||
});
|
||||
await this.writeApplicationStatusLog(application, data, 'active', {});
|
||||
return updated;
|
||||
}
|
||||
if (!['disabled', 'disabling', 'deleted'].includes(status)) {
|
||||
throw new BadRequestException(`不支持的企业应用状态:${status}`);
|
||||
}
|
||||
|
||||
const preview = await this.getApplicationDeactivationPreview(applicationId);
|
||||
if ((status === 'disabling' || status === 'disabled') && preview.totalOutstanding > 0 && !data.force) {
|
||||
const disablingAt = new Date();
|
||||
const autoDisableAt = new Date(disablingAt.getTime() + APPLICATION_DISABLE_GRACE_MS);
|
||||
const updated = await this.prisma.smsApplication.update({
|
||||
where: { id: applicationId },
|
||||
data: {
|
||||
status: 'disabling',
|
||||
disablingAt,
|
||||
autoDisableAt,
|
||||
disableReason: data.reason?.trim() || '等待未完成回执清算',
|
||||
},
|
||||
});
|
||||
await this.writeApplicationStatusLog(application, data, 'disabling', { preview, disablingAt, autoDisableAt });
|
||||
return { ...updated, deactivation: { ...preview, disablingAt, autoDisableAt } };
|
||||
}
|
||||
|
||||
const finalStatus = status === 'deleted' ? 'deleted' : 'disabled';
|
||||
const abandonReason = status === 'deleted'
|
||||
? '企业应用已删除,放弃剩余下游投递'
|
||||
: data.force
|
||||
? '运营强制停用企业应用,放弃剩余下游投递'
|
||||
: '企业应用无待清算数据,完成停用';
|
||||
const abandoned = await this.abandonApplicationDeliveries(applicationId, abandonReason);
|
||||
const updated = await this.prisma.smsApplication.update({
|
||||
where: { id: applicationId },
|
||||
data: {
|
||||
status: finalStatus,
|
||||
disablingAt: null,
|
||||
autoDisableAt: null,
|
||||
disableReason: data.reason?.trim() || abandonReason,
|
||||
},
|
||||
});
|
||||
const disconnect = await this.disconnectDownstreamAccount(application.cmppAccount, abandonReason);
|
||||
await this.writeApplicationStatusLog(application, data, finalStatus, { preview, abandoned, disconnect });
|
||||
return { ...updated, deactivation: null, abandoned, disconnect };
|
||||
}
|
||||
|
||||
async getApplicationDeactivationPreview(applicationId: string) {
|
||||
const application = await this.prisma.smsApplication.findUnique({
|
||||
where: { id: applicationId },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
disablingAt: true,
|
||||
autoDisableAt: true,
|
||||
disableReason: true,
|
||||
},
|
||||
});
|
||||
if (!application) throw new NotFoundException('Application not found');
|
||||
const [
|
||||
awaitingSupplierReceipt,
|
||||
waitingToSend,
|
||||
awaitingClientAck,
|
||||
retryableFailures,
|
||||
pendingUplinks,
|
||||
activeConnections,
|
||||
] = await Promise.all([
|
||||
this.prisma.smsMessageRecord.count({
|
||||
where: { applicationId, status: { in: ['submitted', 'unknown'] }, receiptStatus: null },
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: { applicationId, deliveryType: 'receipt', status: { in: ['pending', 'manual_requeueing'] } },
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: { applicationId, deliveryType: 'receipt', status: 'awaiting_ack' },
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: { applicationId, deliveryType: 'receipt', status: 'failed', retryEnabled: true },
|
||||
}),
|
||||
this.prisma.cmppDownstreamDelivery.count({
|
||||
where: { applicationId, deliveryType: 'uplink', status: { in: [...UNRESOLVED_DOWNSTREAM_STATUSES] } },
|
||||
}),
|
||||
this.prisma.cmppDownstreamConnection.count({
|
||||
where: { applicationId, status: 'connected' },
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
status: application.status,
|
||||
reason: application.disableReason,
|
||||
disablingAt: application.disablingAt,
|
||||
autoDisableAt: application.autoDisableAt,
|
||||
awaitingSupplierReceipt,
|
||||
waitingToSend,
|
||||
awaitingClientAck,
|
||||
retryableFailures,
|
||||
pendingUplinks,
|
||||
activeConnections,
|
||||
totalOutstanding: awaitingSupplierReceipt + waitingToSend + awaitingClientAck + retryableFailures + pendingUplinks,
|
||||
};
|
||||
}
|
||||
|
||||
async listApplicationConnections(applicationId: string) {
|
||||
const application = await this.prisma.smsApplication.findUnique({
|
||||
where: { id: applicationId },
|
||||
include: { tenant: true },
|
||||
});
|
||||
if (!application) {
|
||||
throw new NotFoundException('Application not found');
|
||||
}
|
||||
await this.markTimedOutDownstreamConnections();
|
||||
const connections = await this.prisma.cmppDownstreamConnection.findMany({
|
||||
where: { applicationId },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
});
|
||||
return {
|
||||
application,
|
||||
connections,
|
||||
summary: {
|
||||
desiredConnections: application.cmppMaxConnections,
|
||||
currentConnections: connections.filter((connection) => connection.status === 'connected').length,
|
||||
status: normalizeApplicationCmppStatus(connections, application.status),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async recordDownstreamConnectionEvent(data: GatewayDownstreamConnectionEventDto) {
|
||||
const application = await this.prisma.smsApplication.findUnique({
|
||||
where: { cmppAccount: data.account },
|
||||
include: { ipAllowlist: true },
|
||||
});
|
||||
if (!application) {
|
||||
throw new BadRequestException('CMPP account does not reference an application');
|
||||
}
|
||||
const observedAt = parseGatewayDate(data.observedAt) ?? new Date();
|
||||
const connectedAt = parseGatewayDate(data.connectedAt) ?? observedAt;
|
||||
const existing = await this.prisma.cmppDownstreamConnection.findUnique({ where: { connectionId: data.connectionId } });
|
||||
if (data.status === 'disconnected') {
|
||||
if (existing) {
|
||||
await this.prisma.cmppDownstreamConnection.delete({ where: { id: existing.id } });
|
||||
}
|
||||
await this.writeOperationLog(application.tenantId, undefined, 'cmpp_downstream_connection.disconnected', 'cmpp_downstream_connection', data.connectionId, {
|
||||
applicationId: application.id,
|
||||
account: data.account,
|
||||
remoteIp: data.remoteIp,
|
||||
protocol: data.protocol,
|
||||
status: 'disconnected',
|
||||
errorMessage: data.errorMessage,
|
||||
});
|
||||
return { connectionId: data.connectionId, status: 'disconnected', deleted: Boolean(existing) };
|
||||
}
|
||||
if (!application.interfaceEnabled || !['active', 'disabling'].includes(application.status)) {
|
||||
throw new ForbiddenException('CMPP interface is disabled for this application');
|
||||
}
|
||||
if (data.remoteIp && !isIpAllowed(data.remoteIp, application.ipAllowlist.map((item) => item.ipCidr))) {
|
||||
throw new ForbiddenException('CMPP source IP is not in application allowlist');
|
||||
}
|
||||
// A Gateway process can disappear before it reports disconnect. Prune its
|
||||
// expired rows here so a restarted process can reclaim connection slots
|
||||
// without waiting for an operator to open the connection-list page.
|
||||
await this.markTimedOutDownstreamConnections(observedAt);
|
||||
const activeConnections = await this.prisma.cmppDownstreamConnection.findMany({
|
||||
where: { applicationId: application.id, status: 'connected' },
|
||||
select: { connectionId: true },
|
||||
orderBy: [{ connectedAt: 'asc' }, { connectionId: 'asc' }],
|
||||
});
|
||||
const allowedConnectionIds = activeConnections.slice(0, application.cmppMaxConnections).map((item) => item.connectionId);
|
||||
if ((!existing && activeConnections.length >= application.cmppMaxConnections)
|
||||
|| (existing && activeConnections.length > application.cmppMaxConnections && !allowedConnectionIds.includes(data.connectionId))) {
|
||||
throw new ForbiddenException(`CMPP connection limit exceeded (${application.cmppMaxConnections})`);
|
||||
}
|
||||
const payload = {
|
||||
tenantId: application.tenantId,
|
||||
applicationId: application.id,
|
||||
account: data.account,
|
||||
enterpriseCode: application.cmppEnterpriseCode,
|
||||
remoteIp: data.remoteIp,
|
||||
protocol: data.protocol,
|
||||
status: 'connected',
|
||||
connectedAt: existing?.connectedAt ?? connectedAt,
|
||||
lastHeartbeatAt: data.status === 'connected' || data.status === 'heartbeat' ? observedAt : existing?.lastHeartbeatAt,
|
||||
lastSubmitAt: data.status === 'submit' ? observedAt : existing?.lastSubmitAt,
|
||||
lastDeliverAt: data.status === 'deliver' ? observedAt : existing?.lastDeliverAt,
|
||||
disconnectedAt: null,
|
||||
lastError: null,
|
||||
};
|
||||
const connection = existing
|
||||
? await this.prisma.cmppDownstreamConnection.update({ where: { id: existing.id }, data: payload })
|
||||
: await this.prisma.cmppDownstreamConnection.create({ data: { connectionId: data.connectionId, ...payload } });
|
||||
if (data.status === 'connected') {
|
||||
await this.writeOperationLog(application.tenantId, undefined, `cmpp_downstream_connection.${data.status}`, 'cmpp_downstream_connection', data.connectionId, {
|
||||
applicationId: application.id,
|
||||
account: data.account,
|
||||
remoteIp: data.remoteIp,
|
||||
protocol: data.protocol,
|
||||
status: connection.status,
|
||||
});
|
||||
}
|
||||
return connection;
|
||||
}
|
||||
|
||||
async markTimedOutDownstreamConnections(now = new Date()) {
|
||||
const timeoutMs = getPositiveIntegerEnv('CMPP_DOWNSTREAM_HEARTBEAT_TIMEOUT_MS', DEFAULT_DOWNSTREAM_HEARTBEAT_TIMEOUT_MS);
|
||||
const cutoff = new Date(now.getTime() - timeoutMs);
|
||||
return this.prisma.cmppDownstreamConnection.deleteMany({
|
||||
where: {
|
||||
status: 'connected',
|
||||
OR: [
|
||||
{ lastHeartbeatAt: { lt: cutoff } },
|
||||
{ lastHeartbeatAt: null, connectedAt: { lt: cutoff } },
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async abandonApplicationDeliveries(applicationId: string, reason: string) {
|
||||
const deliveries = await this.prisma.cmppDownstreamDelivery.findMany({
|
||||
where: { applicationId, status: { in: [...UNRESOLVED_DOWNSTREAM_STATUSES] } },
|
||||
select: { id: true },
|
||||
});
|
||||
const deliveryIds = deliveries.map((delivery) => delivery.id);
|
||||
if (deliveryIds.length === 0) return 0;
|
||||
await this.prisma.cmppDownstreamDeliveryAttempt.updateMany({
|
||||
where: { deliveryId: { in: deliveryIds }, status: { in: ['awaiting_ack', 'sent'] } },
|
||||
data: {
|
||||
status: 'abandoned',
|
||||
ackDeadlineAt: null,
|
||||
failureType: 'application_disabled',
|
||||
errorMessage: reason,
|
||||
},
|
||||
});
|
||||
const updated = await this.prisma.cmppDownstreamDelivery.updateMany({
|
||||
where: { id: { in: deliveryIds }, status: { in: [...UNRESOLVED_DOWNSTREAM_STATUSES] } },
|
||||
data: {
|
||||
status: 'abandoned',
|
||||
retryEnabled: false,
|
||||
nextRetryAt: null,
|
||||
ackDeadlineAt: null,
|
||||
lastError: reason,
|
||||
},
|
||||
});
|
||||
return updated.count;
|
||||
}
|
||||
|
||||
async disconnectDownstreamAccount(account: string, reason: string) {
|
||||
const baseUrl = process.env.GATEWAY_CONTROL_URL?.trim() || 'http://127.0.0.1:8090';
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/downstream/connections/disconnect`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ account, reason }),
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
const responseText = await response.text();
|
||||
if (!response.ok) {
|
||||
throw new Error(`Gateway returned ${response.status}: ${responseText}`);
|
||||
}
|
||||
return responseText ? JSON.parse(responseText) as { account: string; disconnected: number } : { account, disconnected: 0 };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
this.logger.error(`Failed to disconnect downstream CMPP account ${account}: ${message}`);
|
||||
return { account, disconnected: 0, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
writeApplicationStatusLog(
|
||||
application: { id: string; tenantId: string; status: string },
|
||||
data: StatusChangeDto,
|
||||
statusAfter: string,
|
||||
detail: Record<string, unknown>,
|
||||
) {
|
||||
return this.writeOperationLog(
|
||||
application.tenantId,
|
||||
data.operatorId,
|
||||
`sms_application.${statusAfter}`,
|
||||
'sms_application',
|
||||
application.id,
|
||||
{
|
||||
statusBefore: application.status,
|
||||
statusAfter,
|
||||
reason: data.reason,
|
||||
force: Boolean(data.force),
|
||||
...JSON.parse(JSON.stringify(detail)) as Record<string, unknown>,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async runApplicationDisableScan() {
|
||||
if (this.applicationDisableScanRunning) return;
|
||||
this.applicationDisableScanRunning = true;
|
||||
try {
|
||||
const applications = await this.prisma.smsApplication.findMany({
|
||||
where: { status: 'disabling' },
|
||||
select: { id: true, tenantId: true, cmppAccount: true, status: true, autoDisableAt: true },
|
||||
take: 500,
|
||||
});
|
||||
const now = new Date();
|
||||
for (const application of applications) {
|
||||
const preview = await this.getApplicationDeactivationPreview(application.id);
|
||||
if (preview.totalOutstanding === 0) {
|
||||
await this.finalizeDisablingApplication(application, false, '待处理回执已清算完成,系统自动停用', preview);
|
||||
} else if (application.autoDisableAt && application.autoDisableAt <= now) {
|
||||
await this.finalizeDisablingApplication(application, true, '进入停用中状态已满72小时,系统自动放弃剩余回执', preview);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error(`Application disabling scan failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
} finally {
|
||||
this.applicationDisableScanRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
async finalizeDisablingApplication(
|
||||
application: { id: string; tenantId: string; cmppAccount: string; status: string },
|
||||
abandonOutstanding: boolean,
|
||||
reason: string,
|
||||
preview: Awaited<ReturnType<SmsApplicationLifecycleService['getApplicationDeactivationPreview']>>,
|
||||
) {
|
||||
const claimed = await this.prisma.smsApplication.updateMany({
|
||||
where: { id: application.id, status: 'disabling' },
|
||||
data: {
|
||||
status: 'disabled',
|
||||
disablingAt: null,
|
||||
autoDisableAt: null,
|
||||
disableReason: reason,
|
||||
},
|
||||
});
|
||||
if (claimed.count !== 1) return false;
|
||||
const abandoned = abandonOutstanding
|
||||
? await this.abandonApplicationDeliveries(application.id, reason)
|
||||
: 0;
|
||||
const disconnect = await this.disconnectDownstreamAccount(application.cmppAccount, reason);
|
||||
await this.writeApplicationStatusLog(application, { reason, force: abandonOutstanding }, 'disabled', {
|
||||
preview,
|
||||
abandoned,
|
||||
disconnect,
|
||||
automatic: true,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
writeOperationLog(
|
||||
tenantId: string,
|
||||
userId: string | undefined,
|
||||
action: string,
|
||||
resource: string,
|
||||
resourceId: string,
|
||||
detail: Record<string, unknown>,
|
||||
) {
|
||||
return this.prisma.operationLog.create({
|
||||
data: {
|
||||
tenantId,
|
||||
userId,
|
||||
action,
|
||||
resource,
|
||||
resourceId,
|
||||
detail: detail as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { BadRequestException, ForbiddenException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomInt, randomUUID } from 'node:crypto';
|
||||
import { isIpAllowed } from '../common/ip-allowlist';
|
||||
import { assertMoneyUnits } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { automaticDeliveryMode } from '../open-api/delivery-mode';
|
||||
import type { ApplicationListQuery, CreateSignatureMaterialDto, CreateSmsApplicationDto, CreateSmsDrainageInfoDto, CreateSmsSignatureDto, CreateSmsSignatureOptions, CreateSmsTemplateDto, CreateSmsTemplateOptions, DrainageInfoListQuery, GatewayDownstreamConnectionEventDto, ReplaceApplicationRouteRulesDto, ReviewDto, SignatureListQuery, StatusChangeDto, TemplateListQuery, UpdateSmsApplicationDto, UpdateSmsDrainageInfoDto, UpdateSmsSignatureDto, UpdateSmsTemplateDto } from './sms-config.contracts';
|
||||
import { APPLICATION_DISABLE_GRACE_MS, DEFAULT_APPLICATION_DISABLE_SCAN_INTERVAL_MS, DEFAULT_DOWNSTREAM_HEARTBEAT_TIMEOUT_MS, UNRESOLVED_DOWNSTREAM_STATUSES, type TemplateVariableInput, estimateBillingUnits, generateApplicationPassword, getPositiveInteger, getPositiveIntegerEnv, hasReportValue, inferTemplateVariables, isRecord, normalizeApplicationCmppStatus, normalizeApplicationInterfaceType, normalizeApplicationPassword, normalizeApplicationQueuePriority, normalizeCmppAccessNumberConfig, normalizeSmsSignature, parseGatewayDate, reportValueParts, startOfToday, validateAndNormalizeTemplateVariables, validateCompleteSmsSignature } from './sms-config.helpers';
|
||||
import { SmsApplicationLifecycleService } from './application-lifecycle.service';
|
||||
import { SmsReportValidationService } from './report-validation.service';
|
||||
|
||||
/** R3 domain service. Kept framework-agnostic and composed behind SmsConfigService. */
|
||||
export class SmsAuditService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly lifecycle: SmsApplicationLifecycleService, private readonly reportValidation: SmsReportValidationService) {}
|
||||
listAuditRecords(targetType?: string, targetId?: string) {
|
||||
return this.prisma.auditRecord.findMany({
|
||||
where: {
|
||||
targetType,
|
||||
targetId,
|
||||
},
|
||||
include: {
|
||||
reviewer: { select: { id: true, username: true, displayName: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
approveSignature(signatureId: string, data: ReviewDto) {
|
||||
return this.reviewSignature(signatureId, 'approved', 'approve', data);
|
||||
}
|
||||
|
||||
rejectSignature(signatureId: string, data: ReviewDto) {
|
||||
return this.reviewSignature(signatureId, 'rejected', 'reject', data);
|
||||
}
|
||||
|
||||
approveTemplate(templateId: string, data: ReviewDto) {
|
||||
return this.reviewTemplate(templateId, 'approved', 'approve', data);
|
||||
}
|
||||
|
||||
rejectTemplate(templateId: string, data: ReviewDto) {
|
||||
return this.reviewTemplate(templateId, 'rejected', 'reject', data);
|
||||
}
|
||||
|
||||
async changeSignatureStatus(signatureId: string, data: StatusChangeDto, tenantId?: string) {
|
||||
const signature = await this.prisma.smsSignature.findUnique({ where: { id: signatureId } });
|
||||
if (!signature || (tenantId && signature.tenantId !== tenantId)) {
|
||||
throw new NotFoundException('Signature not found');
|
||||
}
|
||||
const status = data.status ?? 'deleted';
|
||||
const updated = await this.prisma.smsSignature.update({ where: { id: signatureId }, data: { auditStatus: status } });
|
||||
await this.lifecycle.writeOperationLog(signature.tenantId, data.operatorId, `sms_signature.${status}`, 'sms_signature', signatureId, {
|
||||
statusBefore: signature.auditStatus,
|
||||
statusAfter: status,
|
||||
reason: data.reason,
|
||||
});
|
||||
return updated;
|
||||
}
|
||||
|
||||
async changeTemplateStatus(templateId: string, data: StatusChangeDto, tenantId?: string) {
|
||||
const template = await this.prisma.smsTemplate.findUnique({ where: { id: templateId } });
|
||||
if (!template || (tenantId && template.tenantId !== tenantId)) {
|
||||
throw new NotFoundException('Template not found');
|
||||
}
|
||||
const status = data.status ?? 'deleted';
|
||||
const updated = await this.prisma.smsTemplate.update({ where: { id: templateId }, data: { auditStatus: status } });
|
||||
await this.lifecycle.writeOperationLog(template.tenantId, data.operatorId, `sms_template.${status}`, 'sms_template', templateId, {
|
||||
statusBefore: template.auditStatus,
|
||||
statusAfter: status,
|
||||
reason: data.reason,
|
||||
});
|
||||
return updated;
|
||||
}
|
||||
|
||||
async reviewSignature(signatureId: string, statusAfter: string, action: string, data: ReviewDto) {
|
||||
const signature = await this.prisma.smsSignature.findUnique({ where: { id: signatureId } });
|
||||
if (!signature) {
|
||||
throw new NotFoundException('Signature not found');
|
||||
}
|
||||
const reviewerId = await this.resolveReviewerId(data.reviewerId);
|
||||
|
||||
const updated = await this.prisma.smsSignature.update({
|
||||
where: { id: signatureId },
|
||||
data: {
|
||||
auditStatus: statusAfter,
|
||||
rejectReason: statusAfter === 'rejected' ? data.reason : null,
|
||||
},
|
||||
});
|
||||
await this.createAuditRecord({
|
||||
tenantId: signature.tenantId,
|
||||
targetType: 'sms_signature',
|
||||
targetId: signatureId,
|
||||
action,
|
||||
statusBefore: signature.auditStatus,
|
||||
statusAfter,
|
||||
reason: data.reason,
|
||||
reviewerId,
|
||||
});
|
||||
return updated;
|
||||
}
|
||||
|
||||
async reviewDrainageInfo(itemId: string, statusAfter: string, action: string, data: ReviewDto) {
|
||||
const item = await this.prisma.smsDrainageInfo.findUnique({ where: { id: itemId } });
|
||||
if (!item) throw new NotFoundException('Drainage info not found');
|
||||
if (!['pending', 'rejected'].includes(item.auditStatus)) {
|
||||
throw new BadRequestException('只有待审核或已驳回的引流信息可以审核');
|
||||
}
|
||||
if (statusAfter === 'rejected' && !data.reason?.trim()) {
|
||||
throw new BadRequestException('驳回引流信息时必须填写原因');
|
||||
}
|
||||
const reviewerId = await this.resolveReviewerId(data.reviewerId);
|
||||
const updated = await this.prisma.smsDrainageInfo.update({
|
||||
where: { id: itemId },
|
||||
data: {
|
||||
auditStatus: statusAfter,
|
||||
rejectReason: statusAfter === 'rejected' ? data.reason?.trim() : null,
|
||||
reviewedAt: new Date(),
|
||||
},
|
||||
include: { tenant: true, signature: true, application: true },
|
||||
});
|
||||
await this.createAuditRecord({
|
||||
tenantId: item.tenantId,
|
||||
targetType: 'sms_drainage_info',
|
||||
targetId: itemId,
|
||||
action,
|
||||
statusBefore: item.auditStatus,
|
||||
statusAfter,
|
||||
reason: data.reason,
|
||||
reviewerId,
|
||||
});
|
||||
if (statusAfter === 'approved') await this.reportValidation.activateDrainageReporting(itemId);
|
||||
else await this.reportValidation.suspendDrainageReporting(itemId, data.reason?.trim() || '引流信息运营审核驳回');
|
||||
return updated;
|
||||
}
|
||||
|
||||
async reviewTemplate(templateId: string, statusAfter: string, action: string, data: ReviewDto) {
|
||||
const template = await this.prisma.smsTemplate.findUnique({ where: { id: templateId } });
|
||||
if (!template) {
|
||||
throw new NotFoundException('Template not found');
|
||||
}
|
||||
const reviewerId = await this.resolveReviewerId(data.reviewerId);
|
||||
|
||||
const updated = await this.prisma.smsTemplate.update({
|
||||
where: { id: templateId },
|
||||
data: {
|
||||
auditStatus: statusAfter,
|
||||
rejectReason: statusAfter === 'rejected' ? data.reason : null,
|
||||
},
|
||||
});
|
||||
await this.createAuditRecord({
|
||||
tenantId: template.tenantId,
|
||||
targetType: 'sms_template',
|
||||
targetId: templateId,
|
||||
action,
|
||||
statusBefore: template.auditStatus,
|
||||
statusAfter,
|
||||
reason: data.reason,
|
||||
reviewerId,
|
||||
});
|
||||
return updated;
|
||||
}
|
||||
|
||||
async resolveReviewerId(reviewerId?: string) {
|
||||
if (!reviewerId) {
|
||||
return undefined;
|
||||
}
|
||||
const reviewer = await this.prisma.user.findUnique({ where: { id: reviewerId }, select: { id: true } });
|
||||
if (!reviewer) {
|
||||
throw new BadRequestException('reviewerId does not reference an existing user');
|
||||
}
|
||||
return reviewerId;
|
||||
}
|
||||
|
||||
createAuditRecord(data: Prisma.AuditRecordUncheckedCreateInput) {
|
||||
return this.prisma.auditRecord.create({ data });
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,11 @@ import {
|
||||
CreateSmsSignatureDto,
|
||||
CreateSmsTemplateDto,
|
||||
StatusChangeDto,
|
||||
SmsConfigService,
|
||||
UpdateSmsTemplateDto,
|
||||
UpdateSmsDrainageInfoDto,
|
||||
UpdateSmsSignatureDto,
|
||||
} from './sms-config.service';
|
||||
} from './sms-config.contracts';
|
||||
import { SmsConfigService } from './sms-config.service';
|
||||
|
||||
@ApiTags('client-sms-config')
|
||||
@Controller('client')
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import { BadRequestException, ForbiddenException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomInt, randomUUID } from 'node:crypto';
|
||||
import { isIpAllowed } from '../common/ip-allowlist';
|
||||
import { assertMoneyUnits } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { automaticDeliveryMode } from '../open-api/delivery-mode';
|
||||
import type { ApplicationListQuery, CreateSignatureMaterialDto, CreateSmsApplicationDto, CreateSmsDrainageInfoDto, CreateSmsSignatureDto, CreateSmsSignatureOptions, CreateSmsTemplateDto, CreateSmsTemplateOptions, DrainageInfoListQuery, GatewayDownstreamConnectionEventDto, ReplaceApplicationRouteRulesDto, ReviewDto, SignatureListQuery, StatusChangeDto, TemplateListQuery, UpdateSmsApplicationDto, UpdateSmsDrainageInfoDto, UpdateSmsSignatureDto, UpdateSmsTemplateDto } from './sms-config.contracts';
|
||||
import { APPLICATION_DISABLE_GRACE_MS, DEFAULT_APPLICATION_DISABLE_SCAN_INTERVAL_MS, DEFAULT_DOWNSTREAM_HEARTBEAT_TIMEOUT_MS, UNRESOLVED_DOWNSTREAM_STATUSES, type TemplateVariableInput, estimateBillingUnits, generateApplicationPassword, getPositiveInteger, getPositiveIntegerEnv, hasReportValue, inferTemplateVariables, isRecord, normalizeApplicationCmppStatus, normalizeApplicationInterfaceType, normalizeApplicationPassword, normalizeApplicationQueuePriority, normalizeCmppAccessNumberConfig, normalizeSmsSignature, parseGatewayDate, reportValueParts, startOfToday, validateAndNormalizeTemplateVariables, validateCompleteSmsSignature } from './sms-config.helpers';
|
||||
import { SmsReportValidationService } from './report-validation.service';
|
||||
import { SmsAuditService } from './audit.service';
|
||||
|
||||
/** R3 domain service. Kept framework-agnostic and composed behind SmsConfigService. */
|
||||
export class SmsDrainageService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly reportValidation: SmsReportValidationService, private readonly audit: SmsAuditService) {}
|
||||
async listClientDrainageInfos(tenantId?: string, itemId?: string) {
|
||||
return this.prisma.smsDrainageInfo.findMany({
|
||||
where: { id: itemId, tenantId, auditStatus: { not: 'deleted' } },
|
||||
select: {
|
||||
id: true,
|
||||
tenantId: true,
|
||||
signatureId: true,
|
||||
applicationId: true,
|
||||
siteName: true,
|
||||
url: true,
|
||||
remark: true,
|
||||
reportValues: true,
|
||||
auditStatus: true,
|
||||
rejectReason: true,
|
||||
submittedAt: true,
|
||||
reviewedAt: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
signature: { select: { id: true, name: true, auditStatus: true } },
|
||||
application: { select: { id: true, name: true, status: true } },
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
async getClientDrainageInfoView(itemId: string, tenantId?: string) {
|
||||
const [item] = await this.listClientDrainageInfos(tenantId, itemId);
|
||||
if (!item) throw new NotFoundException('Drainage info not found');
|
||||
return item;
|
||||
}
|
||||
|
||||
listDrainageInfos(query: DrainageInfoListQuery = {}) {
|
||||
return this.prisma.smsDrainageInfo.findMany({
|
||||
where: {
|
||||
tenantId: query.tenantId,
|
||||
signatureId: query.signatureId,
|
||||
auditStatus: query.status && query.status !== 'all' ? query.status : { not: 'deleted' },
|
||||
OR: query.keyword ? [
|
||||
{ siteName: { contains: query.keyword } },
|
||||
{ url: { contains: query.keyword } },
|
||||
{ signature: { name: { contains: query.keyword } } },
|
||||
{ tenant: { name: { contains: query.keyword } } },
|
||||
{ application: { name: { contains: query.keyword } } },
|
||||
] : undefined,
|
||||
},
|
||||
include: { tenant: true, signature: true, application: true, reportTasks: { include: { channel: true } } },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
async createDrainageInfo(signatureId: string, data: CreateSmsDrainageInfoDto, options: CreateSmsSignatureOptions = {}, tenantId?: string) {
|
||||
const signature = await this.prisma.smsSignature.findUnique({ where: { id: signatureId } });
|
||||
if (!signature) throw new NotFoundException('Signature not found');
|
||||
if (tenantId && signature.tenantId !== tenantId) throw new NotFoundException('Signature not found');
|
||||
if (signature.auditStatus !== 'approved') throw new BadRequestException('签名审核通过后才能新增引流信息');
|
||||
if (!data.siteName?.trim() || !data.url?.trim()) throw new BadRequestException('siteName and url are required');
|
||||
await this.reportValidation.validateDrainageReportValues(signature.applicationId ?? undefined, data.reportValues);
|
||||
const auditStatus = options.initialAuditStatus ?? 'pending';
|
||||
const item = await this.prisma.smsDrainageInfo.create({
|
||||
data: {
|
||||
tenantId: signature.tenantId,
|
||||
signatureId,
|
||||
applicationId: signature.applicationId,
|
||||
siteName: data.siteName.trim(),
|
||||
url: data.url.trim(),
|
||||
remark: data.remark,
|
||||
reportValues: data.reportValues as Prisma.InputJsonValue | undefined,
|
||||
auditStatus,
|
||||
reviewedAt: auditStatus === 'approved' ? new Date() : undefined,
|
||||
},
|
||||
include: { tenant: true, signature: true, application: true },
|
||||
});
|
||||
await this.audit.createAuditRecord({
|
||||
tenantId: item.tenantId,
|
||||
targetType: 'sms_drainage_info',
|
||||
targetId: item.id,
|
||||
action: auditStatus === 'approved' ? 'admin_create_approved' : 'submit',
|
||||
statusAfter: auditStatus,
|
||||
reason: auditStatus === 'approved' ? '运营端新建引流信息自动审核通过' : undefined,
|
||||
});
|
||||
if (auditStatus === 'approved') await this.reportValidation.activateDrainageReporting(item.id);
|
||||
return item;
|
||||
}
|
||||
|
||||
async updateDrainageInfo(itemId: string, data: UpdateSmsDrainageInfoDto, options: CreateSmsSignatureOptions = {}, tenantId?: string) {
|
||||
const current = await this.prisma.smsDrainageInfo.findUnique({ where: { id: itemId }, include: { signature: true } });
|
||||
if (!current) throw new NotFoundException('Drainage info not found');
|
||||
if (tenantId && current.tenantId !== tenantId) throw new NotFoundException('Drainage info not found');
|
||||
if (current.auditStatus === 'deleted') throw new BadRequestException('已删除的引流信息不能修改');
|
||||
if (data.siteName !== undefined && !data.siteName.trim()) throw new BadRequestException('siteName is required');
|
||||
if (data.url !== undefined && !data.url.trim()) throw new BadRequestException('url is required');
|
||||
const applicationId = current.signature.applicationId ?? current.applicationId ?? undefined;
|
||||
await this.reportValidation.validateDrainageReportValues(applicationId, data.reportValues ?? (isRecord(current.reportValues) ? current.reportValues : {}));
|
||||
const auditStatus = options.initialAuditStatus ?? 'pending';
|
||||
const updated = await this.prisma.smsDrainageInfo.update({
|
||||
where: { id: itemId },
|
||||
data: {
|
||||
applicationId,
|
||||
siteName: data.siteName?.trim(),
|
||||
url: data.url?.trim(),
|
||||
remark: data.remark,
|
||||
reportValues: data.reportValues as Prisma.InputJsonValue | undefined,
|
||||
auditStatus,
|
||||
rejectReason: null,
|
||||
submittedAt: new Date(),
|
||||
reviewedAt: auditStatus === 'approved' ? new Date() : null,
|
||||
materialVersion: { increment: 1 },
|
||||
pendingReport: true,
|
||||
reportChangedAt: new Date(),
|
||||
},
|
||||
include: { tenant: true, signature: true, application: true },
|
||||
});
|
||||
await this.audit.createAuditRecord({
|
||||
tenantId: current.tenantId,
|
||||
targetType: 'sms_drainage_info',
|
||||
targetId: itemId,
|
||||
action: auditStatus === 'approved' ? 'admin_update_approved' : 'update_submit',
|
||||
statusBefore: current.auditStatus,
|
||||
statusAfter: auditStatus,
|
||||
reason: auditStatus === 'approved' ? '运营端修改引流信息并自动审核通过' : undefined,
|
||||
});
|
||||
if (auditStatus === 'approved') await this.reportValidation.activateDrainageReporting(itemId);
|
||||
else await this.reportValidation.suspendDrainageReporting(itemId, '引流信息修改后等待运营审核');
|
||||
return updated;
|
||||
}
|
||||
|
||||
approveDrainageInfo(itemId: string, data: ReviewDto) {
|
||||
return this.audit.reviewDrainageInfo(itemId, 'approved', 'approve', data);
|
||||
}
|
||||
|
||||
rejectDrainageInfo(itemId: string, data: ReviewDto) {
|
||||
return this.audit.reviewDrainageInfo(itemId, 'rejected', 'reject', data);
|
||||
}
|
||||
|
||||
async changeDrainageInfoStatus(itemId: string, data: StatusChangeDto, tenantId?: string) {
|
||||
const current = await this.prisma.smsDrainageInfo.findUnique({ where: { id: itemId } });
|
||||
if (!current) throw new NotFoundException('Drainage info not found');
|
||||
if (tenantId && current.tenantId !== tenantId) throw new NotFoundException('Drainage info not found');
|
||||
const status = data.status ?? 'deleted';
|
||||
if (tenantId && status !== 'deleted') throw new BadRequestException('客户端只能删除引流信息,不能直接修改审核状态');
|
||||
const updated = await this.prisma.smsDrainageInfo.update({ where: { id: itemId }, data: { auditStatus: status } });
|
||||
if (status === 'deleted') await this.reportValidation.suspendDrainageReporting(itemId, data.reason ?? '引流信息已删除', 'abandoned');
|
||||
await this.audit.createAuditRecord({ tenantId: current.tenantId, targetType: 'sms_drainage_info', targetId: itemId, action: status, statusBefore: current.auditStatus, statusAfter: status, reason: data.reason });
|
||||
return updated;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { BadRequestException, ForbiddenException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomInt, randomUUID } from 'node:crypto';
|
||||
import { isIpAllowed } from '../common/ip-allowlist';
|
||||
import { assertMoneyUnits } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { automaticDeliveryMode } from '../open-api/delivery-mode';
|
||||
import type { ApplicationListQuery, CreateSignatureMaterialDto, CreateSmsApplicationDto, CreateSmsDrainageInfoDto, CreateSmsSignatureDto, CreateSmsSignatureOptions, CreateSmsTemplateDto, CreateSmsTemplateOptions, DrainageInfoListQuery, GatewayDownstreamConnectionEventDto, ReplaceApplicationRouteRulesDto, ReviewDto, SignatureListQuery, StatusChangeDto, TemplateListQuery, UpdateSmsApplicationDto, UpdateSmsDrainageInfoDto, UpdateSmsSignatureDto, UpdateSmsTemplateDto } from './sms-config.contracts';
|
||||
import { APPLICATION_DISABLE_GRACE_MS, DEFAULT_APPLICATION_DISABLE_SCAN_INTERVAL_MS, DEFAULT_DOWNSTREAM_HEARTBEAT_TIMEOUT_MS, UNRESOLVED_DOWNSTREAM_STATUSES, type TemplateVariableInput, estimateBillingUnits, generateApplicationPassword, getPositiveInteger, getPositiveIntegerEnv, hasReportValue, inferTemplateVariables, isRecord, normalizeApplicationCmppStatus, normalizeApplicationInterfaceType, normalizeApplicationPassword, normalizeApplicationQueuePriority, normalizeCmppAccessNumberConfig, normalizeSmsSignature, parseGatewayDate, reportValueParts, startOfToday, validateAndNormalizeTemplateVariables, validateCompleteSmsSignature } from './sms-config.helpers';
|
||||
import { SmsApplicationConfigService } from './application-config.service';
|
||||
|
||||
/** R3 domain service. Kept framework-agnostic and composed behind SmsConfigService. */
|
||||
export class SmsReportValidationService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly applications: SmsApplicationConfigService) {}
|
||||
async withReportRequirementSnapshot(applicationId?: string, drainageInfo?: Record<string, unknown>) {
|
||||
if (!drainageInfo) return drainageInfo;
|
||||
const fields = await this.applications.getApplicationReportFields(applicationId);
|
||||
return {
|
||||
...drainageInfo,
|
||||
reportRequirementSnapshot: {
|
||||
capturedAt: new Date().toISOString(),
|
||||
applicationId,
|
||||
fields: fields.map((field) => ({
|
||||
id: field.id,
|
||||
code: field.code,
|
||||
name: field.name,
|
||||
fieldType: field.fieldType,
|
||||
required: field.required,
|
||||
reportTypes: field.reportTypes,
|
||||
commonReportTypes: field.commonReportTypes,
|
||||
channels: field.channels,
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async syncSignatureReportValues(signatureId: string, applicationId?: string, drainageInfo?: Record<string, unknown>) {
|
||||
if (!drainageInfo) return;
|
||||
const fields = await this.applications.getApplicationReportFields(applicationId);
|
||||
const signatureValues = isRecord(drainageInfo.signatureReportValues) ? drainageInfo.signatureReportValues : {};
|
||||
for (const field of fields.filter((item) => item.reportTypes.some((type) => type === 'signature' || type === 'both'))) {
|
||||
const value = reportValueParts(signatureValues[field.code]);
|
||||
for (const channel of field.channels) {
|
||||
await this.prisma.signatureReportMaterial.upsert({
|
||||
where: { signatureId_channelId_fieldCode: { signatureId, channelId: channel.id, fieldCode: field.code } },
|
||||
update: value,
|
||||
create: { signatureId, channelId: channel.id, fieldCode: field.code, ...value },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async validateSignatureReportValues(applicationId?: string, drainageInfo?: Record<string, unknown>) {
|
||||
const fields = await this.applications.getApplicationReportFields(applicationId, 'signature');
|
||||
const signatureValues = isRecord(drainageInfo?.signatureReportValues) ? drainageInfo.signatureReportValues : {};
|
||||
const missingSignature = fields
|
||||
.filter((field) => field.required && field.reportTypes.some((type) => type === 'signature' || type === 'both'))
|
||||
.filter((field) => !hasReportValue(signatureValues[field.code]));
|
||||
if (missingSignature.length > 0) {
|
||||
throw new BadRequestException(`缺少必填签名报备资料:${missingSignature.map((field) => field.name).join('、')}`);
|
||||
}
|
||||
}
|
||||
|
||||
async validateDrainageReportValues(applicationId?: string, reportValues: Record<string, unknown> = {}) {
|
||||
const fields = await this.applications.getApplicationReportFields(applicationId, 'drainage');
|
||||
const missing = fields.filter((field) => field.required && !hasReportValue(reportValues[field.code]));
|
||||
if (missing.length > 0) {
|
||||
throw new BadRequestException(`引流信息缺少必填报备资料:${missing.map((field) => field.name).join('、')}`);
|
||||
}
|
||||
}
|
||||
|
||||
async activateDrainageReporting(itemId: string) {
|
||||
const item = await this.prisma.smsDrainageInfo.findUnique({ where: { id: itemId }, include: { signature: true } });
|
||||
if (!item) throw new NotFoundException('Drainage info not found');
|
||||
if (item.auditStatus !== 'approved') throw new BadRequestException('引流信息审核通过后才能进入通道报备');
|
||||
const applicationId = item.signature.applicationId ?? item.applicationId ?? undefined;
|
||||
if (!applicationId) return;
|
||||
const fields = (await this.applications.getApplicationReportFields(applicationId, 'drainage'))
|
||||
.filter((field) => field.reportTypes.some((type) => type === 'drainage' || type === 'both'));
|
||||
const channels = new Map(fields.flatMap((field) => field.channels).map((channel) => [channel.id, channel]));
|
||||
const values = isRecord(item.reportValues) ? item.reportValues : {};
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.drainageReportMaterial.deleteMany({ where: { signatureId: item.signatureId, drainageItemId: item.id } });
|
||||
for (const field of fields) {
|
||||
const value = reportValueParts(values[field.code]);
|
||||
for (const channel of field.channels) {
|
||||
await tx.drainageReportMaterial.create({
|
||||
data: { signatureId: item.signatureId, drainageItemId: item.id, channelId: channel.id, fieldCode: field.code, ...value },
|
||||
});
|
||||
}
|
||||
}
|
||||
const existingTasks = await tx.channelSignatureReportTask.findMany({ where: { drainageItemId: item.id, reportType: 'drainage' } });
|
||||
const existingByChannel = new Map(existingTasks.map((task) => [task.channelId, task]));
|
||||
for (const channel of channels.values()) {
|
||||
const existing = existingByChannel.get(channel.id);
|
||||
const task = existing
|
||||
? await tx.channelSignatureReportTask.update({ where: { id: existing.id }, data: { status: 'pending', reason: null } })
|
||||
: await tx.channelSignatureReportTask.create({ data: { tenantId: item.tenantId, signatureId: item.signatureId, channelId: channel.id, reportType: 'drainage', drainageItemId: item.id, status: 'pending' } });
|
||||
await tx.channelSignatureReportRecord.create({
|
||||
data: { taskId: task.id, channelId: channel.id, action: existing ? 'audit_approved_reset' : 'audit_approved_create', statusBefore: existing?.status, statusAfter: 'pending', reason: '引流信息运营审核通过' },
|
||||
});
|
||||
}
|
||||
for (const task of existingTasks.filter((current) => !channels.has(current.channelId) && current.status !== 'abandoned')) {
|
||||
await tx.channelSignatureReportTask.update({ where: { id: task.id }, data: { status: 'abandoned', reason: '应用当前路由已不包含此通道' } });
|
||||
await tx.channelSignatureReportRecord.create({ data: { taskId: task.id, channelId: task.channelId, action: 'route_removed', statusBefore: task.status, statusAfter: 'abandoned', reason: '应用当前路由已不包含此通道' } });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async suspendDrainageReporting(itemId: string, reason: string, statusAfter = 'waiting_review') {
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
const item = await tx.smsDrainageInfo.findUnique({ where: { id: itemId } });
|
||||
if (!item) throw new NotFoundException('Drainage info not found');
|
||||
await tx.drainageReportMaterial.deleteMany({ where: { signatureId: item.signatureId, drainageItemId: item.id } });
|
||||
const tasks = await tx.channelSignatureReportTask.findMany({ where: { drainageItemId: item.id, reportType: 'drainage' } });
|
||||
for (const task of tasks.filter((current) => current.status !== statusAfter)) {
|
||||
await tx.channelSignatureReportTask.update({ where: { id: task.id }, data: { status: statusAfter, reason } });
|
||||
await tx.channelSignatureReportRecord.create({ data: { taskId: task.id, channelId: task.channelId, action: 'audit_suspended', statusBefore: task.status, statusAfter, reason } });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
import { BadRequestException, ForbiddenException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomInt, randomUUID } from 'node:crypto';
|
||||
import { isIpAllowed } from '../common/ip-allowlist';
|
||||
import { assertMoneyUnits } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { automaticDeliveryMode } from '../open-api/delivery-mode';
|
||||
import type { ApplicationListQuery, CreateSignatureMaterialDto, CreateSmsApplicationDto, CreateSmsDrainageInfoDto, CreateSmsSignatureDto, CreateSmsSignatureOptions, CreateSmsTemplateDto, CreateSmsTemplateOptions, DrainageInfoListQuery, GatewayDownstreamConnectionEventDto, ReplaceApplicationRouteRulesDto, ReviewDto, SignatureListQuery, StatusChangeDto, TemplateListQuery, UpdateSmsApplicationDto, UpdateSmsDrainageInfoDto, UpdateSmsSignatureDto, UpdateSmsTemplateDto } from './sms-config.contracts';
|
||||
import { APPLICATION_DISABLE_GRACE_MS, DEFAULT_APPLICATION_DISABLE_SCAN_INTERVAL_MS, DEFAULT_DOWNSTREAM_HEARTBEAT_TIMEOUT_MS, UNRESOLVED_DOWNSTREAM_STATUSES, type TemplateVariableInput, estimateBillingUnits, generateApplicationPassword, getPositiveInteger, getPositiveIntegerEnv, hasReportValue, inferTemplateVariables, isRecord, normalizeApplicationCmppStatus, normalizeApplicationInterfaceType, normalizeApplicationPassword, normalizeApplicationQueuePriority, normalizeCmppAccessNumberConfig, normalizeSmsSignature, parseGatewayDate, reportValueParts, startOfToday, validateAndNormalizeTemplateVariables, validateCompleteSmsSignature } from './sms-config.helpers';
|
||||
import { SmsReportValidationService } from './report-validation.service';
|
||||
import { SmsAuditService } from './audit.service';
|
||||
|
||||
/** R3 domain service. Kept framework-agnostic and composed behind SmsConfigService. */
|
||||
export class SmsSignatureService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly reportValidation: SmsReportValidationService, private readonly audit: SmsAuditService) {}
|
||||
async listSignatures(queryOrTenantId?: string | SignatureListQuery) {
|
||||
const query = typeof queryOrTenantId === 'string' ? { tenantId: queryOrTenantId } : queryOrTenantId ?? {};
|
||||
const signatures = await this.prisma.smsSignature.findMany({
|
||||
where: {
|
||||
tenantId: query.tenantId,
|
||||
auditStatus: query.status && query.status !== 'all' ? query.status : { not: 'deleted' },
|
||||
tenant: query.enterpriseKeyword ? { name: { contains: query.enterpriseKeyword } } : undefined,
|
||||
application: query.applicationKeyword ? { name: { contains: query.applicationKeyword } } : undefined,
|
||||
name: query.signatureKeyword ? { contains: query.signatureKeyword } : undefined,
|
||||
drainageItems: query.drainageKeyword ? {
|
||||
some: {
|
||||
auditStatus: { not: 'deleted' },
|
||||
OR: [
|
||||
{ siteName: { contains: query.drainageKeyword } },
|
||||
{ url: { contains: query.drainageKeyword } },
|
||||
{ remark: { contains: query.drainageKeyword } },
|
||||
],
|
||||
},
|
||||
} : undefined,
|
||||
OR: query.keyword ? [
|
||||
{ name: { contains: query.keyword } },
|
||||
{ purpose: { contains: query.keyword } },
|
||||
{ tenant: { name: { contains: query.keyword } } },
|
||||
{ application: { name: { contains: query.keyword } } },
|
||||
] : undefined,
|
||||
},
|
||||
include: {
|
||||
materials: true,
|
||||
tenant: true,
|
||||
application: true,
|
||||
drainageItems: { where: { auditStatus: { not: 'deleted' } }, orderBy: { updatedAt: 'desc' } },
|
||||
reportTasks: { include: { channel: true, drainageInfo: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
...(query.page && query.pageSize ? {
|
||||
skip: (query.page - 1) * query.pageSize,
|
||||
take: query.pageSize,
|
||||
} : {}),
|
||||
});
|
||||
const applicationIds = signatures.map((signature) => signature.applicationId).filter((id): id is string => Boolean(id));
|
||||
const routes = applicationIds.length ? await this.prisma.channelRouteRule.findMany({
|
||||
where: { applicationId: { in: applicationIds }, status: 'active' },
|
||||
include: { group: { include: { items: { include: { channel: { include: { reportFields: true } } } } } } },
|
||||
}) : [];
|
||||
const hasCommonDrainageFields = await this.prisma.commonReportField.count({
|
||||
where: { status: 'active', reportType: 'drainage', drainageField: { status: 'active' } },
|
||||
}).then((count) => count > 0);
|
||||
return signatures.map((signature) => {
|
||||
const legacyPayload = isRecord(signature.drainageInfo) ? signature.drainageInfo : {};
|
||||
const drainageLinks = signature.drainageItems.map((item) => ({
|
||||
id: item.id,
|
||||
siteName: item.siteName,
|
||||
url: item.url,
|
||||
remark: item.remark ?? '',
|
||||
reportValues: isRecord(item.reportValues) ? item.reportValues : {},
|
||||
auditStatus: item.auditStatus,
|
||||
rejectReason: item.rejectReason,
|
||||
submittedAt: item.submittedAt.toISOString(),
|
||||
reviewedAt: item.reviewedAt?.toISOString(),
|
||||
createdAt: item.createdAt.toISOString(),
|
||||
updatedAt: item.updatedAt.toISOString(),
|
||||
}));
|
||||
return {
|
||||
...signature,
|
||||
name: normalizeSmsSignature(signature.name),
|
||||
drainageInfo: { ...legacyPayload, links: drainageLinks },
|
||||
reportTargets: (() => {
|
||||
const channels = routes.filter((route) => route.applicationId === signature.applicationId && route.group).flatMap((route) => route.group!.items.map((item) => item.channel)).filter((channel) => channel.status !== 'deleted');
|
||||
const taskByChannel = new Map((signature.reportTasks ?? []).filter((task) => task.reportType === 'signature').map((task) => [task.channelId, task]));
|
||||
return [...new Map(channels.map((channel) => [channel.id, channel])).values()].map((channel) => ({ channel, channelId: channel.id, status: taskByChannel.get(channel.id)?.status ?? 'pending', taskId: taskByChannel.get(channel.id)?.id }));
|
||||
})(),
|
||||
drainageReportTargets: Object.fromEntries(signature.drainageItems.map((drainageItem) => {
|
||||
const drainageItemId = drainageItem.id;
|
||||
const channels = routes
|
||||
.filter((route) => route.applicationId === signature.applicationId && route.group)
|
||||
.flatMap((route) => route.group!.items.map((item) => item.channel))
|
||||
.filter((channel) => channel.status !== 'deleted' && (hasCommonDrainageFields || channel.reportFields.some((field) => field.status === 'active' && ['drainage', 'both'].includes(field.reportType))));
|
||||
const taskByChannel = new Map((signature.reportTasks ?? []).filter((task) => task.reportType === 'drainage' && task.drainageItemId === drainageItemId).map((task) => [task.channelId, task]));
|
||||
return [drainageItemId, [...new Map(channels.map((channel) => [channel.id, channel])).values()].flatMap((channel) => {
|
||||
const task = taskByChannel.get(channel.id);
|
||||
return task ? [{ channel, channelId: channel.id, status: task.status, taskId: task.id }] : [];
|
||||
})];
|
||||
})),
|
||||
drainageCarrierReportSummary: Object.fromEntries(signature.drainageItems.map((drainageItem) => {
|
||||
const drainageItemId = drainageItem.id;
|
||||
const channels = routes
|
||||
.filter((route) => route.applicationId === signature.applicationId && route.group)
|
||||
.flatMap((route) => route.group!.items.map((item) => item.channel))
|
||||
.filter((channel) => channel.status !== 'deleted' && (hasCommonDrainageFields || channel.reportFields.some((field) => field.status === 'active' && ['drainage', 'both'].includes(field.reportType))));
|
||||
const targets = [...new Map(channels.map((channel) => [channel.id, channel])).values()];
|
||||
const taskByChannel = new Map((signature.reportTasks ?? []).filter((task) => task.reportType === 'drainage' && task.drainageItemId === drainageItemId).map((task) => [task.channelId, task]));
|
||||
return [drainageItemId, Object.fromEntries(['mobile', 'unicom', 'telecom'].map((carrier) => {
|
||||
const carrierTargets = targets.filter((channel) => channel.carrier === carrier || channel.carrier === 'all');
|
||||
const statuses = carrierTargets.flatMap((channel) => taskByChannel.get(channel.id)?.status ? [taskByChannel.get(channel.id)!.status] : []);
|
||||
const approved = statuses.filter((status) => status === 'approved').length;
|
||||
const status = !statuses.length ? 'not_applicable' : approved === statuses.length ? 'approved' : statuses.some((item) => ['failed', 'rejected'].includes(item)) ? 'failed' : statuses.some((item) => ['reporting', 'exporting'].includes(item)) || approved ? 'reporting' : statuses.some((item) => item === 'waiting_material') ? 'waiting_material' : 'pending';
|
||||
return [carrier, { status, approved, total: statuses.length }];
|
||||
}))];
|
||||
})),
|
||||
carrierReportSummary: Object.fromEntries(['mobile', 'unicom', 'telecom'].map((carrier) => {
|
||||
const configured = routes.filter((route) => route.applicationId === signature.applicationId && route.group).flatMap((route) => route.group!.items.map((item) => item.channel)).filter((channel) => channel.status !== 'deleted' && (channel.carrier === carrier || channel.carrier === 'all'));
|
||||
const targets = [...new Map(configured.map((channel) => [channel.id, channel])).values()];
|
||||
const taskByChannel = new Map((signature.reportTasks ?? []).filter((task) => task.reportType === 'signature').map((task) => [task.channelId, task]));
|
||||
const statuses = targets.map((channel) => taskByChannel.get(channel.id)?.status ?? 'pending');
|
||||
const approved = statuses.filter((status) => status === 'approved').length;
|
||||
const status = !targets.length ? 'not_applicable' : approved === targets.length ? 'approved' : statuses.some((item) => ['failed', 'rejected'].includes(item)) ? 'failed' : statuses.some((item) => ['reporting', 'exporting'].includes(item)) || approved ? 'reporting' : statuses.some((item) => item === 'waiting_material') ? 'waiting_material' : 'pending';
|
||||
return [carrier, { status, approved, total: targets.length }];
|
||||
})),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async listSignaturesPage(query: SignatureListQuery) {
|
||||
const page = Math.max(1, Math.floor(Number(query.page) || 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 10)));
|
||||
const where: Prisma.SmsSignatureWhereInput = {
|
||||
tenantId: query.tenantId,
|
||||
auditStatus: query.status && query.status !== 'all' ? query.status : { not: 'deleted' },
|
||||
tenant: query.enterpriseKeyword ? { name: { contains: query.enterpriseKeyword } } : undefined,
|
||||
application: query.applicationKeyword ? { name: { contains: query.applicationKeyword } } : undefined,
|
||||
name: query.signatureKeyword ? { contains: query.signatureKeyword } : undefined,
|
||||
drainageItems: query.drainageKeyword ? {
|
||||
some: {
|
||||
auditStatus: { not: 'deleted' },
|
||||
OR: [
|
||||
{ siteName: { contains: query.drainageKeyword } },
|
||||
{ url: { contains: query.drainageKeyword } },
|
||||
{ remark: { contains: query.drainageKeyword } },
|
||||
],
|
||||
},
|
||||
} : undefined,
|
||||
OR: query.keyword ? [
|
||||
{ name: { contains: query.keyword } },
|
||||
{ purpose: { contains: query.keyword } },
|
||||
{ tenant: { name: { contains: query.keyword } } },
|
||||
{ application: { name: { contains: query.keyword } } },
|
||||
] : undefined,
|
||||
};
|
||||
const [items, total] = await Promise.all([
|
||||
this.listSignatures({ ...query, page, pageSize }),
|
||||
this.prisma.smsSignature.count({ where }),
|
||||
]);
|
||||
return { items, total, page, pageSize };
|
||||
}
|
||||
|
||||
listSignatureOptions(tenantId?: string) {
|
||||
return this.prisma.smsSignature.findMany({
|
||||
where: { tenantId, auditStatus: { not: 'deleted' } },
|
||||
select: { id: true, tenantId: true, applicationId: true, name: true, auditStatus: true },
|
||||
orderBy: [{ name: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
}
|
||||
|
||||
async listClientSignatures(tenantId?: string, signatureId?: string, query: { keyword?: string; applicationId?: string; status?: string; page?: number; pageSize?: number } = {}) {
|
||||
const signatures = await this.prisma.smsSignature.findMany({
|
||||
where: {
|
||||
id: signatureId,
|
||||
tenantId,
|
||||
applicationId: query.applicationId,
|
||||
auditStatus: query.status || { notIn: ['deleted', 'disabled'] },
|
||||
OR: query.keyword?.trim() ? [
|
||||
{ name: { contains: query.keyword.trim() } },
|
||||
{ purpose: { contains: query.keyword.trim() } },
|
||||
{ application: { name: { contains: query.keyword.trim() } } },
|
||||
] : undefined,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
tenantId: true,
|
||||
applicationId: true,
|
||||
name: true,
|
||||
purpose: true,
|
||||
auditStatus: true,
|
||||
reportStatus: true,
|
||||
pendingReport: true,
|
||||
reportChangedAt: true,
|
||||
rejectReason: true,
|
||||
drainageInfo: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
application: { select: { id: true, name: true, status: true } },
|
||||
materials: {
|
||||
select: { id: true, fileObjectId: true, materialType: true, title: true, description: true, createdAt: true },
|
||||
},
|
||||
drainageItems: {
|
||||
where: { auditStatus: { not: 'deleted' } },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
select: {
|
||||
id: true,
|
||||
siteName: true,
|
||||
url: true,
|
||||
remark: true,
|
||||
reportValues: true,
|
||||
auditStatus: true,
|
||||
rejectReason: true,
|
||||
submittedAt: true,
|
||||
reviewedAt: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
},
|
||||
_count: { select: { reportMaterials: true } },
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
skip: query.page && query.pageSize ? (query.page - 1) * query.pageSize : undefined,
|
||||
take: query.pageSize,
|
||||
});
|
||||
return signatures.map((signature) => {
|
||||
const stored = isRecord(signature.drainageInfo) ? signature.drainageInfo : {};
|
||||
return {
|
||||
id: signature.id,
|
||||
tenantId: signature.tenantId,
|
||||
applicationId: signature.applicationId,
|
||||
name: normalizeSmsSignature(signature.name),
|
||||
purpose: signature.purpose,
|
||||
auditStatus: signature.auditStatus,
|
||||
reportStatus: signature.reportStatus,
|
||||
pendingReport: signature.pendingReport,
|
||||
reportChangedAt: signature.reportChangedAt,
|
||||
rejectReason: signature.rejectReason,
|
||||
createdAt: signature.createdAt,
|
||||
updatedAt: signature.updatedAt,
|
||||
application: signature.application,
|
||||
materials: signature.materials,
|
||||
submittedMaterialCount: signature.materials.length + signature._count.reportMaterials,
|
||||
reportValues: isRecord(stored.signatureReportValues) ? stored.signatureReportValues : {},
|
||||
drainageInfo: {
|
||||
links: signature.drainageItems.map((item) => ({
|
||||
...item,
|
||||
reportValues: isRecord(item.reportValues) ? item.reportValues : {},
|
||||
})),
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async getClientSignatureView(signatureId: string, tenantId?: string) {
|
||||
const [signature] = await this.listClientSignatures(tenantId, signatureId);
|
||||
if (!signature) throw new NotFoundException('Signature not found');
|
||||
return signature;
|
||||
}
|
||||
|
||||
async getClientSignatureWorkspace(tenantId?: string, query: { keyword?: string; applicationId?: string; status?: string; page?: number; pageSize?: number } = {}) {
|
||||
const page = Math.max(1, Math.floor(Number(query.page) || 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 10)));
|
||||
const filteredWhere: Prisma.SmsSignatureWhereInput = {
|
||||
tenantId,
|
||||
applicationId: query.applicationId,
|
||||
auditStatus: query.status || { notIn: ['deleted', 'disabled'] },
|
||||
OR: query.keyword?.trim() ? [
|
||||
{ name: { contains: query.keyword.trim() } },
|
||||
{ purpose: { contains: query.keyword.trim() } },
|
||||
{ application: { name: { contains: query.keyword.trim() } } },
|
||||
] : undefined,
|
||||
};
|
||||
const [items, total, statusCounts] = await Promise.all([
|
||||
this.listClientSignatures(tenantId, undefined, { ...query, page, pageSize }),
|
||||
this.prisma.smsSignature.count({ where: filteredWhere }),
|
||||
this.prisma.smsSignature.groupBy({
|
||||
by: ['auditStatus'],
|
||||
where: { tenantId, auditStatus: { notIn: ['deleted', 'disabled'] } },
|
||||
_count: { _all: true },
|
||||
}),
|
||||
]);
|
||||
const summary = { total: 0, pending: 0, approved: 0, rejected: 0, draft: 0 };
|
||||
for (const item of statusCounts) {
|
||||
const count = item._count._all;
|
||||
summary.total += count;
|
||||
if (item.auditStatus in summary && item.auditStatus !== 'total') {
|
||||
summary[item.auditStatus as keyof Omit<typeof summary, 'total'>] = count;
|
||||
}
|
||||
}
|
||||
return { items, summary, total, page, pageSize };
|
||||
}
|
||||
|
||||
async createSignature(data: CreateSmsSignatureDto, options: CreateSmsSignatureOptions = {}) {
|
||||
await this.reportValidation.validateSignatureReportValues(data.applicationId, data.drainageInfo);
|
||||
const drainageInfo = await this.reportValidation.withReportRequirementSnapshot(data.applicationId, data.drainageInfo);
|
||||
const name = validateCompleteSmsSignature(data.name);
|
||||
const signature = await this.prisma.smsSignature.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
applicationId: data.applicationId,
|
||||
name,
|
||||
purpose: data.purpose,
|
||||
auditStatus: options.initialAuditStatus,
|
||||
drainageInfo: drainageInfo as Prisma.InputJsonValue | undefined,
|
||||
},
|
||||
});
|
||||
await this.reportValidation.syncSignatureReportValues(signature.id, data.applicationId, drainageInfo);
|
||||
if (options.initialAuditStatus) {
|
||||
await this.audit.createAuditRecord({
|
||||
tenantId: signature.tenantId,
|
||||
targetType: 'sms_signature',
|
||||
targetId: signature.id,
|
||||
action: 'admin_create_approved',
|
||||
statusAfter: options.initialAuditStatus,
|
||||
reason: '运营端新建签名自动审核通过',
|
||||
});
|
||||
}
|
||||
return signature;
|
||||
}
|
||||
|
||||
async updateSignature(signatureId: string, data: UpdateSmsSignatureDto, tenantId?: string) {
|
||||
const signature = await this.prisma.smsSignature.findUnique({ where: { id: signatureId } });
|
||||
if (!signature || (tenantId && signature.tenantId !== tenantId)) {
|
||||
throw new NotFoundException('Signature not found');
|
||||
}
|
||||
await this.reportValidation.validateSignatureReportValues(data.applicationId ?? signature.applicationId ?? undefined, data.drainageInfo);
|
||||
const applicationId = data.applicationId ?? signature.applicationId ?? undefined;
|
||||
const drainageInfo = data.drainageInfo
|
||||
? await this.reportValidation.withReportRequirementSnapshot(applicationId, data.drainageInfo)
|
||||
: undefined;
|
||||
const name = data.name === undefined ? undefined : validateCompleteSmsSignature(data.name);
|
||||
const materialChanged = (data.applicationId !== undefined && data.applicationId !== signature.applicationId)
|
||||
|| (name !== undefined && name !== normalizeSmsSignature(signature.name))
|
||||
|| (data.purpose !== undefined && data.purpose !== signature.purpose)
|
||||
|| (data.drainageInfo !== undefined && JSON.stringify(data.drainageInfo) !== JSON.stringify(signature.drainageInfo ?? null));
|
||||
const auditStatus = materialChanged && signature.auditStatus === 'approved' ? 'pending' : data.auditStatus;
|
||||
const updated = await this.prisma.smsSignature.update({
|
||||
where: { id: signatureId },
|
||||
data: {
|
||||
applicationId: data.applicationId,
|
||||
name,
|
||||
purpose: data.purpose,
|
||||
auditStatus,
|
||||
rejectReason: auditStatus === 'pending' ? null : undefined,
|
||||
drainageInfo: drainageInfo as Prisma.InputJsonValue | undefined,
|
||||
materialVersion: { increment: 1 },
|
||||
pendingReport: true,
|
||||
reportChangedAt: new Date(),
|
||||
},
|
||||
include: { materials: true, tenant: true, application: true },
|
||||
});
|
||||
await this.reportValidation.syncSignatureReportValues(signatureId, updated.applicationId ?? undefined, drainageInfo);
|
||||
return updated;
|
||||
}
|
||||
|
||||
async updateClientSignature(signatureId: string, data: UpdateSmsSignatureDto, tenantId?: string) {
|
||||
const current = await this.prisma.smsSignature.findUnique({ where: { id: signatureId } });
|
||||
if (!current || (tenantId && current.tenantId !== tenantId)) throw new NotFoundException('Signature not found');
|
||||
if (!['draft', 'rejected', 'approved'].includes(current.auditStatus)) {
|
||||
throw new BadRequestException('当前审核状态不允许修改签名');
|
||||
}
|
||||
const updated = await this.updateSignature(signatureId, { ...data, auditStatus: 'pending' }, tenantId);
|
||||
await this.audit.createAuditRecord({
|
||||
tenantId: current.tenantId,
|
||||
targetType: 'sms_signature',
|
||||
targetId: signatureId,
|
||||
action: 'client_update_submit',
|
||||
statusBefore: current.auditStatus,
|
||||
statusAfter: 'pending',
|
||||
});
|
||||
return updated;
|
||||
}
|
||||
|
||||
createSignatureMaterial(data: CreateSignatureMaterialDto) {
|
||||
return this.prisma.signatureMaterial.create({
|
||||
data: {
|
||||
signatureId: data.signatureId,
|
||||
fileObjectId: data.fileObjectId,
|
||||
materialType: data.materialType,
|
||||
title: data.title,
|
||||
description: data.description,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async submitSignature(signatureId: string, tenantId?: string) {
|
||||
const signature = await this.prisma.smsSignature.findUnique({ where: { id: signatureId } });
|
||||
if (!signature || (tenantId && signature.tenantId !== tenantId)) {
|
||||
throw new NotFoundException('Signature not found');
|
||||
}
|
||||
|
||||
const updated = await this.prisma.smsSignature.update({
|
||||
where: { id: signatureId },
|
||||
data: { auditStatus: 'pending', rejectReason: null },
|
||||
});
|
||||
await this.audit.createAuditRecord({
|
||||
tenantId: signature.tenantId,
|
||||
targetType: 'sms_signature',
|
||||
targetId: signatureId,
|
||||
action: 'submit',
|
||||
statusBefore: signature.auditStatus,
|
||||
statusAfter: 'pending',
|
||||
});
|
||||
return updated;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
/** Stable request and query contracts shared by controllers and SMS configuration domains. */
|
||||
|
||||
export interface CreateSmsApplicationDto {
|
||||
tenantId: string;
|
||||
name: string;
|
||||
scene?: string;
|
||||
callbackUrl?: string;
|
||||
cmppAccount?: string;
|
||||
cmppEnterpriseCode?: string;
|
||||
cmppApplicationExtension?: string;
|
||||
cmppAccessNumberFillEnabled?: boolean;
|
||||
cmppAccessNumberFillPrefix?: string;
|
||||
passwordCipher?: string;
|
||||
interfaceEnabled?: boolean;
|
||||
interfaceType?: string;
|
||||
cmppMaxConnections?: number;
|
||||
cmppWindowSize?: number;
|
||||
dailyLimit?: number;
|
||||
customerUnitPrice?: number;
|
||||
queuePriority?: string;
|
||||
templateMismatchMode?: string;
|
||||
downstreamReceiptRetryEnabled?: boolean;
|
||||
downstreamUplinkRetryEnabled?: boolean;
|
||||
ipAllowlist?: string[];
|
||||
}
|
||||
|
||||
export type UpdateSmsApplicationDto = Partial<Omit<CreateSmsApplicationDto, 'tenantId'>> & {
|
||||
status?: string;
|
||||
};
|
||||
|
||||
export interface ReplaceApplicationRouteRulesDto {
|
||||
routes: Array<{
|
||||
carrier: string;
|
||||
groupId: string;
|
||||
priority?: number;
|
||||
status?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface CreateSmsSignatureDto {
|
||||
tenantId: string;
|
||||
applicationId?: string;
|
||||
name: string;
|
||||
purpose?: string;
|
||||
drainageInfo?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CreateSmsSignatureOptions {
|
||||
initialAuditStatus?: string;
|
||||
}
|
||||
|
||||
export type UpdateSmsSignatureDto = Partial<Omit<CreateSmsSignatureDto, 'tenantId'>> & {
|
||||
auditStatus?: string;
|
||||
};
|
||||
|
||||
export interface CreateSmsDrainageInfoDto {
|
||||
siteName: string;
|
||||
url: string;
|
||||
remark?: string;
|
||||
reportValues?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export type UpdateSmsDrainageInfoDto = Partial<CreateSmsDrainageInfoDto>;
|
||||
|
||||
export interface DrainageInfoListQuery {
|
||||
tenantId?: string;
|
||||
signatureId?: string;
|
||||
status?: string;
|
||||
keyword?: string;
|
||||
}
|
||||
|
||||
export interface CreateSignatureMaterialDto {
|
||||
signatureId: string;
|
||||
fileObjectId?: string;
|
||||
materialType: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface CreateSmsTemplateDto {
|
||||
tenantId: string;
|
||||
applicationId: string;
|
||||
signatureId?: string;
|
||||
name: string;
|
||||
content: string;
|
||||
category?: string;
|
||||
variables?: Array<{ name: string; example?: string; required?: boolean }>;
|
||||
}
|
||||
|
||||
export interface CreateSmsTemplateOptions {
|
||||
initialAuditStatus?: string;
|
||||
}
|
||||
|
||||
export type UpdateSmsTemplateDto = Partial<Omit<CreateSmsTemplateDto, 'tenantId' | 'signatureId'>> & {
|
||||
signatureId?: string | null;
|
||||
auditStatus?: string;
|
||||
};
|
||||
|
||||
export interface ReviewDto {
|
||||
reviewerId?: string;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface StatusChangeDto {
|
||||
status?: string;
|
||||
operatorId?: string;
|
||||
reason?: string;
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
export interface TemplateListQuery {
|
||||
tenantId?: string;
|
||||
status?: string;
|
||||
keyword?: string;
|
||||
enterpriseKeyword?: string;
|
||||
applicationKeyword?: string;
|
||||
nameKeyword?: string;
|
||||
contentKeyword?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface ApplicationListQuery {
|
||||
tenantId?: string;
|
||||
keyword?: string;
|
||||
enterpriseKeyword?: string;
|
||||
applicationKeyword?: string;
|
||||
status?: string;
|
||||
includeConnections?: boolean;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface SignatureListQuery {
|
||||
tenantId?: string;
|
||||
keyword?: string;
|
||||
status?: string;
|
||||
enterpriseKeyword?: string;
|
||||
applicationKeyword?: string;
|
||||
signatureKeyword?: string;
|
||||
drainageKeyword?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface GatewayDownstreamConnectionEventDto {
|
||||
account: string;
|
||||
connectionId: string;
|
||||
status: 'connected' | 'heartbeat' | 'submit' | 'deliver' | 'disconnected';
|
||||
remoteIp?: string;
|
||||
protocol?: string;
|
||||
connectedAt?: string;
|
||||
observedAt?: string;
|
||||
errorMessage?: string;
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { randomInt, randomUUID } from 'node:crypto';
|
||||
import type { CreateSmsApplicationDto } from './sms-config.contracts';
|
||||
|
||||
/** Pure normalization and report-value helpers shared by the R3 domain services. */
|
||||
export const APPLICATION_QUEUE_PRIORITIES = ['normal', 'priority'] as const;
|
||||
export type ApplicationQueuePriority = typeof APPLICATION_QUEUE_PRIORITIES[number];
|
||||
export const APPLICATION_INTERFACE_TYPES = ['cmpp20'] as const;
|
||||
export type ApplicationInterfaceType = typeof APPLICATION_INTERFACE_TYPES[number];
|
||||
export const DEFAULT_DOWNSTREAM_HEARTBEAT_TIMEOUT_MS = 90_000;
|
||||
export const APPLICATION_DISABLE_GRACE_MS = 72 * 60 * 60 * 1_000;
|
||||
export const DEFAULT_APPLICATION_DISABLE_SCAN_INTERVAL_MS = 60_000;
|
||||
export const UNRESOLVED_DOWNSTREAM_STATUSES = ['pending', 'awaiting_ack', 'failed', 'manual_requeueing'] as const;
|
||||
|
||||
export interface TemplateVariableInput {
|
||||
name: string;
|
||||
example?: string;
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
export function normalizeApplicationPassword(value: string | undefined) {
|
||||
const password = value?.trim() || generateApplicationPassword();
|
||||
if (password.length !== 16) {
|
||||
throw new BadRequestException('passwordCipher must be 16 characters');
|
||||
}
|
||||
return password;
|
||||
}
|
||||
|
||||
export function generateApplicationPassword() {
|
||||
return randomUUID().replace(/-/g, '').slice(0, 16);
|
||||
}
|
||||
|
||||
export function estimateBillingUnits(content: string) {
|
||||
const length = [...content].length;
|
||||
if (length <= 70) {
|
||||
return 1;
|
||||
}
|
||||
return Math.ceil(length / 67);
|
||||
}
|
||||
|
||||
export function inferTemplateVariables(content: string): TemplateVariableInput[] {
|
||||
const matches = content.match(/\$\{[a-zA-Z0-9_]+\}/g) ?? [];
|
||||
return [...new Set(matches)].map((match) => ({ name: match.slice(2, -1), required: true }));
|
||||
}
|
||||
|
||||
export function validateAndNormalizeTemplateVariables(
|
||||
content: string,
|
||||
supplied?: Array<{ name: string; example?: string; required?: boolean }>,
|
||||
): TemplateVariableInput[] {
|
||||
const names: string[] = [];
|
||||
let cursor = 0;
|
||||
while (true) {
|
||||
const start = content.indexOf('${', cursor);
|
||||
if (start < 0) break;
|
||||
const end = content.indexOf('}', start + 2);
|
||||
if (end < 0) throw new BadRequestException('模板变量未闭合');
|
||||
const name = content.slice(start + 2, end);
|
||||
if (!/^[A-Za-z][A-Za-z0-9_]{0,31}$/.test(name)) {
|
||||
throw new BadRequestException('模板变量名必须以英文字母开头,仅包含英文字母、数字和下划线,长度1至32位');
|
||||
}
|
||||
if (names.includes(name)) throw new BadRequestException(`模板变量 ${name} 重复`);
|
||||
names.push(name);
|
||||
cursor = end + 1;
|
||||
}
|
||||
if (!supplied) return names.map((name) => ({ name, required: true }));
|
||||
const suppliedNames = supplied.map((item) => item.name?.trim());
|
||||
if (suppliedNames.some((name) => !name || !/^[A-Za-z][A-Za-z0-9_]{0,31}$/.test(name))) {
|
||||
throw new BadRequestException('变量配置中包含非法变量名');
|
||||
}
|
||||
if (new Set(suppliedNames).size !== suppliedNames.length) throw new BadRequestException('变量配置中包含重复变量');
|
||||
if (suppliedNames.length !== names.length || suppliedNames.some((name) => !names.includes(name))) {
|
||||
throw new BadRequestException('变量配置必须与模板正文中的占位符完全一致');
|
||||
}
|
||||
return supplied.map((item) => ({ ...item, name: item.name.trim() }));
|
||||
}
|
||||
|
||||
export function normalizeSmsSignature(name: string) {
|
||||
const innerName = name.trim().replace(/^[【\[]+|[】\]]+$/g, '').trim();
|
||||
return innerName ? `【${innerName}】` : '';
|
||||
}
|
||||
|
||||
export function validateCompleteSmsSignature(name: string) {
|
||||
const value = name;
|
||||
if (/[\p{White_Space}\p{Cc}\p{Default_Ignorable_Code_Point}]/u.test(value)) {
|
||||
throw new BadRequestException('短信签名不能包含空格、换行或不可见字符');
|
||||
}
|
||||
const match = value.match(/^【([^【】]+)】$/);
|
||||
if (!match) {
|
||||
throw new BadRequestException('短信签名必须包含完整中文黑括号,例如:【某某科技】');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function startOfToday() {
|
||||
const date = new Date();
|
||||
date.setHours(0, 0, 0, 0);
|
||||
return date;
|
||||
}
|
||||
|
||||
export function normalizeApplicationQueuePriority(value?: string): ApplicationQueuePriority {
|
||||
const queuePriority = value ?? 'normal';
|
||||
if (!APPLICATION_QUEUE_PRIORITIES.includes(queuePriority as ApplicationQueuePriority)) {
|
||||
throw new BadRequestException('queuePriority must be normal or priority');
|
||||
}
|
||||
return queuePriority as ApplicationQueuePriority;
|
||||
}
|
||||
|
||||
export function normalizeApplicationInterfaceType(value?: string): ApplicationInterfaceType {
|
||||
const interfaceType = value ?? 'cmpp20';
|
||||
if (!APPLICATION_INTERFACE_TYPES.includes(interfaceType as ApplicationInterfaceType)) {
|
||||
throw new BadRequestException('interfaceType only supports cmpp20; HTTP interface is not available yet');
|
||||
}
|
||||
return interfaceType as ApplicationInterfaceType;
|
||||
}
|
||||
|
||||
export function normalizeCmppAccessNumberConfig(
|
||||
data: Pick<CreateSmsApplicationDto, 'cmppApplicationExtension' | 'cmppAccessNumberFillEnabled' | 'cmppAccessNumberFillPrefix'>,
|
||||
current?: {
|
||||
cmppApplicationExtension?: string | null;
|
||||
cmppAccessNumberFillEnabled?: boolean | null;
|
||||
cmppAccessNumberFillPrefix?: string | null;
|
||||
},
|
||||
) {
|
||||
const applicationExtension = (
|
||||
data.cmppApplicationExtension === undefined
|
||||
? current?.cmppApplicationExtension
|
||||
: data.cmppApplicationExtension
|
||||
)?.trim() || null;
|
||||
const fillEnabled = data.cmppAccessNumberFillEnabled
|
||||
?? current?.cmppAccessNumberFillEnabled
|
||||
?? false;
|
||||
const configuredPrefix = (
|
||||
data.cmppAccessNumberFillPrefix === undefined
|
||||
? current?.cmppAccessNumberFillPrefix
|
||||
: data.cmppAccessNumberFillPrefix
|
||||
)?.trim() || null;
|
||||
|
||||
if (applicationExtension && !/^\d+$/.test(applicationExtension)) {
|
||||
throw new BadRequestException('cmppApplicationExtension must contain digits only');
|
||||
}
|
||||
if (applicationExtension && applicationExtension.length > 21) {
|
||||
throw new BadRequestException('cmppApplicationExtension must not exceed 21 digits');
|
||||
}
|
||||
if (fillEnabled && !applicationExtension) {
|
||||
throw new BadRequestException('cmppApplicationExtension is required when access number filling is enabled');
|
||||
}
|
||||
if (fillEnabled && !configuredPrefix) {
|
||||
throw new BadRequestException('cmppAccessNumberFillPrefix is required when access number filling is enabled');
|
||||
}
|
||||
if (configuredPrefix && !/^\d+$/.test(configuredPrefix)) {
|
||||
throw new BadRequestException('cmppAccessNumberFillPrefix must contain digits only');
|
||||
}
|
||||
|
||||
const fillPrefix = fillEnabled ? configuredPrefix : null;
|
||||
const clientSrcId = applicationExtension
|
||||
? `${fillPrefix ?? ''}${applicationExtension}`
|
||||
: null;
|
||||
if (clientSrcId && clientSrcId.length > 21) {
|
||||
throw new BadRequestException('client CMPP Src_Id must not exceed 21 digits');
|
||||
}
|
||||
return { applicationExtension, fillEnabled, fillPrefix, clientSrcId };
|
||||
}
|
||||
|
||||
export function getPositiveInteger(value: number | undefined, fallback: number, fieldName: string) {
|
||||
if (value === undefined || value === null) {
|
||||
return fallback;
|
||||
}
|
||||
const normalized = Number(value);
|
||||
if (!Number.isInteger(normalized) || normalized <= 0) {
|
||||
throw new BadRequestException(`${fieldName} must be a positive integer`);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function normalizeApplicationCmppStatus(connections: Array<{ status: string }>, applicationStatus: string) {
|
||||
if (!['active', 'disabling'].includes(applicationStatus)) {
|
||||
return 'inactive';
|
||||
}
|
||||
if (connections.some((connection) => connection.status === 'connected')) {
|
||||
return 'connected';
|
||||
}
|
||||
if (connections.some((connection) => ['auth_failed', 'heartbeat_timeout', 'reconnecting'].includes(connection.status))) {
|
||||
return 'degraded';
|
||||
}
|
||||
return 'disconnected';
|
||||
}
|
||||
|
||||
export function getPositiveIntegerEnv(name: string, fallback: number) {
|
||||
const value = Number(process.env[name] ?? fallback);
|
||||
return Number.isInteger(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
|
||||
export function parseGatewayDate(value?: string) {
|
||||
if (!value) return undefined;
|
||||
const parsed = new Date(value);
|
||||
return Number.isNaN(parsed.getTime()) ? undefined : parsed;
|
||||
}
|
||||
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function reportValueParts(value: unknown) {
|
||||
if (isRecord(value) && typeof value.fileObjectId === 'string') {
|
||||
return { fieldValue: typeof value.fileName === 'string' ? value.fileName : undefined, fileObjectId: value.fileObjectId };
|
||||
}
|
||||
return { fieldValue: value === undefined || value === null ? undefined : String(value), fileObjectId: undefined };
|
||||
}
|
||||
|
||||
export function hasReportValue(value: unknown) {
|
||||
if (isRecord(value)) {
|
||||
return Boolean(value.fileObjectId || value.fieldValue || value.value);
|
||||
}
|
||||
return value !== undefined && value !== null && String(value).trim().length > 0;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,215 @@
|
||||
import { BadRequestException, ForbiddenException, Injectable, Logger, NotFoundException, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { randomInt, randomUUID } from 'node:crypto';
|
||||
import { isIpAllowed } from '../common/ip-allowlist';
|
||||
import { assertMoneyUnits } from '../common/money';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { automaticDeliveryMode } from '../open-api/delivery-mode';
|
||||
import type { ApplicationListQuery, CreateSignatureMaterialDto, CreateSmsApplicationDto, CreateSmsDrainageInfoDto, CreateSmsSignatureDto, CreateSmsSignatureOptions, CreateSmsTemplateDto, CreateSmsTemplateOptions, DrainageInfoListQuery, GatewayDownstreamConnectionEventDto, ReplaceApplicationRouteRulesDto, ReviewDto, SignatureListQuery, StatusChangeDto, TemplateListQuery, UpdateSmsApplicationDto, UpdateSmsDrainageInfoDto, UpdateSmsSignatureDto, UpdateSmsTemplateDto } from './sms-config.contracts';
|
||||
import { APPLICATION_DISABLE_GRACE_MS, DEFAULT_APPLICATION_DISABLE_SCAN_INTERVAL_MS, DEFAULT_DOWNSTREAM_HEARTBEAT_TIMEOUT_MS, UNRESOLVED_DOWNSTREAM_STATUSES, type TemplateVariableInput, estimateBillingUnits, generateApplicationPassword, getPositiveInteger, getPositiveIntegerEnv, hasReportValue, inferTemplateVariables, isRecord, normalizeApplicationCmppStatus, normalizeApplicationInterfaceType, normalizeApplicationPassword, normalizeApplicationQueuePriority, normalizeCmppAccessNumberConfig, normalizeSmsSignature, parseGatewayDate, reportValueParts, startOfToday, validateAndNormalizeTemplateVariables, validateCompleteSmsSignature } from './sms-config.helpers';
|
||||
import { SmsAuditService } from './audit.service';
|
||||
|
||||
/** R3 domain service. Kept framework-agnostic and composed behind SmsConfigService. */
|
||||
export class SmsTemplateService {
|
||||
constructor(private readonly prisma: PrismaService, private readonly audit: SmsAuditService) {}
|
||||
listTemplates(queryOrTenantId?: string | TemplateListQuery) {
|
||||
const query = typeof queryOrTenantId === 'string' ? { tenantId: queryOrTenantId } : queryOrTenantId ?? {};
|
||||
return this.prisma.smsTemplate.findMany({
|
||||
where: {
|
||||
tenantId: query.tenantId,
|
||||
auditStatus: query.status && query.status !== 'all' ? query.status : { not: 'deleted' },
|
||||
tenant: query.enterpriseKeyword ? { name: { contains: query.enterpriseKeyword } } : undefined,
|
||||
application: query.applicationKeyword ? { name: { contains: query.applicationKeyword } } : undefined,
|
||||
name: query.nameKeyword ? { contains: query.nameKeyword } : undefined,
|
||||
content: query.contentKeyword ? { contains: query.contentKeyword } : undefined,
|
||||
OR: query.keyword ? [
|
||||
{ name: { contains: query.keyword } },
|
||||
{ content: { contains: query.keyword } },
|
||||
{ category: { contains: query.keyword } },
|
||||
{ application: { name: { contains: query.keyword } } },
|
||||
{ tenant: { name: { contains: query.keyword } } },
|
||||
] : undefined,
|
||||
},
|
||||
include: { variables: true, application: true, tenant: true, signature: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
...(query.page && query.pageSize ? {
|
||||
skip: (query.page - 1) * query.pageSize,
|
||||
take: query.pageSize,
|
||||
} : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async listTemplatesPage(query: TemplateListQuery) {
|
||||
const page = Math.max(1, Math.floor(Number(query.page) || 1));
|
||||
const pageSize = Math.min(100, Math.max(1, Math.floor(Number(query.pageSize) || 10)));
|
||||
const where: Prisma.SmsTemplateWhereInput = {
|
||||
tenantId: query.tenantId,
|
||||
auditStatus: query.status && query.status !== 'all' ? query.status : { not: 'deleted' },
|
||||
tenant: query.enterpriseKeyword ? { name: { contains: query.enterpriseKeyword } } : undefined,
|
||||
application: query.applicationKeyword ? { name: { contains: query.applicationKeyword } } : undefined,
|
||||
name: query.nameKeyword ? { contains: query.nameKeyword } : undefined,
|
||||
content: query.contentKeyword ? { contains: query.contentKeyword } : undefined,
|
||||
OR: query.keyword ? [
|
||||
{ name: { contains: query.keyword } },
|
||||
{ content: { contains: query.keyword } },
|
||||
{ category: { contains: query.keyword } },
|
||||
{ application: { name: { contains: query.keyword } } },
|
||||
{ tenant: { name: { contains: query.keyword } } },
|
||||
] : undefined,
|
||||
};
|
||||
const [items, total] = await Promise.all([
|
||||
this.listTemplates({ ...query, page, pageSize }),
|
||||
this.prisma.smsTemplate.count({ where }),
|
||||
]);
|
||||
return { items, total, page, pageSize };
|
||||
}
|
||||
|
||||
listClientTemplates(tenantId: string | undefined, includeHistory = false) {
|
||||
return this.listTemplates({ tenantId, status: includeHistory ? 'all' : 'approved' });
|
||||
}
|
||||
|
||||
async createTemplate(data: CreateSmsTemplateDto, options: CreateSmsTemplateOptions = {}) {
|
||||
const variables = validateAndNormalizeTemplateVariables(data.content, data.variables);
|
||||
const application = await this.prisma.smsApplication.findUnique({ where: { id: data.applicationId }, select: { tenantId: true } });
|
||||
if (!application || application.tenantId !== data.tenantId) {
|
||||
throw new BadRequestException('applicationId does not belong to the template tenant');
|
||||
}
|
||||
await this.validateTemplateSignature(data.signatureId, data.tenantId, data.applicationId, data.content);
|
||||
return this.prisma.smsTemplate.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
applicationId: data.applicationId,
|
||||
signatureId: data.signatureId,
|
||||
name: data.name,
|
||||
content: data.content,
|
||||
category: data.category,
|
||||
auditStatus: options.initialAuditStatus,
|
||||
billingUnits: estimateBillingUnits(data.content),
|
||||
variables: {
|
||||
create: variables.map((variable: TemplateVariableInput) => ({
|
||||
name: variable.name,
|
||||
example: variable.example,
|
||||
required: variable.required ?? true,
|
||||
})),
|
||||
},
|
||||
},
|
||||
include: { variables: true, application: true, tenant: true, signature: true },
|
||||
});
|
||||
}
|
||||
|
||||
async updateTemplate(templateId: string, data: UpdateSmsTemplateDto, tenantId?: string) {
|
||||
const template = await this.prisma.smsTemplate.findUnique({ where: { id: templateId } });
|
||||
if (!template || (tenantId && template.tenantId !== tenantId)) {
|
||||
throw new NotFoundException('Template not found');
|
||||
}
|
||||
if (data.applicationId) {
|
||||
const application = await this.prisma.smsApplication.findUnique({ where: { id: data.applicationId }, select: { tenantId: true } });
|
||||
if (!application || application.tenantId !== template.tenantId) {
|
||||
throw new BadRequestException('applicationId does not belong to the template tenant');
|
||||
}
|
||||
}
|
||||
if (data.signatureId !== undefined || data.applicationId !== undefined || data.content !== undefined) {
|
||||
await this.validateTemplateSignature(
|
||||
data.signatureId === undefined ? template.signatureId : data.signatureId,
|
||||
template.tenantId,
|
||||
data.applicationId ?? template.applicationId,
|
||||
data.content ?? template.content,
|
||||
);
|
||||
}
|
||||
const variables = data.content !== undefined || data.variables !== undefined
|
||||
? validateAndNormalizeTemplateVariables(data.content ?? template.content, data.variables)
|
||||
: undefined;
|
||||
const materialChanged = (data.applicationId !== undefined && data.applicationId !== template.applicationId)
|
||||
|| (data.signatureId !== undefined && data.signatureId !== template.signatureId)
|
||||
|| (data.content !== undefined && data.content !== template.content)
|
||||
|| (data.category !== undefined && data.category !== template.category)
|
||||
|| data.variables !== undefined;
|
||||
const auditStatus = materialChanged && template.auditStatus === 'approved' ? 'pending' : data.auditStatus;
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
if (variables) {
|
||||
await tx.templateVariable.deleteMany({ where: { templateId } });
|
||||
}
|
||||
return tx.smsTemplate.update({
|
||||
where: { id: templateId },
|
||||
data: {
|
||||
applicationId: data.applicationId,
|
||||
signatureId: data.signatureId,
|
||||
name: data.name,
|
||||
content: data.content,
|
||||
category: data.category,
|
||||
auditStatus,
|
||||
rejectReason: auditStatus === 'pending' ? null : undefined,
|
||||
billingUnits: data.content ? estimateBillingUnits(data.content) : undefined,
|
||||
variables: variables ? {
|
||||
create: variables.map((variable) => ({
|
||||
name: variable.name,
|
||||
example: variable.example,
|
||||
required: variable.required ?? true,
|
||||
})),
|
||||
} : undefined,
|
||||
},
|
||||
include: { variables: true, application: true, tenant: true, signature: true },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async updateClientTemplate(templateId: string, data: UpdateSmsTemplateDto, tenantId?: string) {
|
||||
const current = await this.prisma.smsTemplate.findUnique({ where: { id: templateId } });
|
||||
if (!current || (tenantId && current.tenantId !== tenantId)) throw new NotFoundException('Template not found');
|
||||
if (!['draft', 'rejected', 'approved'].includes(current.auditStatus)) {
|
||||
throw new BadRequestException('当前审核状态不允许修改模板');
|
||||
}
|
||||
const updated = await this.updateTemplate(templateId, { ...data, auditStatus: 'pending' }, tenantId);
|
||||
await this.audit.createAuditRecord({
|
||||
tenantId: current.tenantId,
|
||||
targetType: 'sms_template',
|
||||
targetId: templateId,
|
||||
action: 'client_update_submit',
|
||||
statusBefore: current.auditStatus,
|
||||
statusAfter: 'pending',
|
||||
});
|
||||
return updated;
|
||||
}
|
||||
|
||||
async submitTemplate(templateId: string, tenantId?: string) {
|
||||
const template = await this.prisma.smsTemplate.findUnique({ where: { id: templateId } });
|
||||
if (!template || (tenantId && template.tenantId !== tenantId)) {
|
||||
throw new NotFoundException('Template not found');
|
||||
}
|
||||
await this.validateTemplateSignature(template.signatureId, template.tenantId, template.applicationId, template.content);
|
||||
|
||||
const updated = await this.prisma.smsTemplate.update({
|
||||
where: { id: templateId },
|
||||
data: { auditStatus: 'pending', rejectReason: null },
|
||||
});
|
||||
await this.audit.createAuditRecord({
|
||||
tenantId: template.tenantId,
|
||||
targetType: 'sms_template',
|
||||
targetId: templateId,
|
||||
action: 'submit',
|
||||
statusBefore: template.auditStatus,
|
||||
statusAfter: 'pending',
|
||||
});
|
||||
return updated;
|
||||
}
|
||||
|
||||
async validateTemplateSignature(signatureId: string | null | undefined, tenantId: string, applicationId: string, content: string) {
|
||||
if (!signatureId) {
|
||||
throw new BadRequestException('短信模板必须选择短信签名');
|
||||
}
|
||||
const signature = await this.prisma.smsSignature.findUnique({
|
||||
where: { id: signatureId },
|
||||
select: { tenantId: true, applicationId: true, name: true },
|
||||
});
|
||||
if (!signature || signature.tenantId !== tenantId) {
|
||||
throw new BadRequestException('signatureId does not belong to the template tenant');
|
||||
}
|
||||
if (signature.applicationId && signature.applicationId !== applicationId) {
|
||||
throw new BadRequestException('signatureId does not belong to the template application');
|
||||
}
|
||||
const signaturePrefix = normalizeSmsSignature(signature.name);
|
||||
if (!signaturePrefix || !content.startsWith(signaturePrefix)) {
|
||||
throw new BadRequestException(`模板内容必须以所选短信签名 ${signaturePrefix || signature.name} 开头`);
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"version": "R11",
|
||||
"stableEntry": "src/apps/admin/AdminChannelsPage.tsx",
|
||||
"stableExport": "AdminChannelsPage",
|
||||
"maxStableEntryLines": 300,
|
||||
"modules": {
|
||||
"src/apps/admin/channels/ChannelFormModal.tsx": ["ChannelFormModal"],
|
||||
"src/apps/admin/channels/SmsTestModal.tsx": ["SmsTestModal"],
|
||||
"src/apps/admin/channels/ChannelTable.tsx": ["ChannelTable"],
|
||||
"src/apps/admin/channels/ChannelLogModal.tsx": ["ChannelLogModal"],
|
||||
"src/apps/admin/channels/channelModel.ts": [
|
||||
"formatLogDetail",
|
||||
"resolveChannelStatus",
|
||||
"mapApiChannel",
|
||||
"mapUiStatusToApi",
|
||||
"buildChannelPayload"
|
||||
]
|
||||
},
|
||||
"apiCalls": {
|
||||
"src/apps/admin/AdminChannelsPage.tsx": [
|
||||
"listChannelsPage",
|
||||
"getSendQuality",
|
||||
"listChannelConnections",
|
||||
"updateChannel",
|
||||
"createChannel",
|
||||
"changeChannelStatus",
|
||||
"copyChannel",
|
||||
"listChannelConnectionLogs"
|
||||
],
|
||||
"src/apps/admin/channels/SmsTestModal.tsx": ["testChannel"]
|
||||
},
|
||||
"styleFile": "src/apps/admin/channels/AdminChannelsPage.css",
|
||||
"styleImport": "./channels/AdminChannelsPage.css",
|
||||
"pageStyleSelectors": [
|
||||
".sms-channel-page",
|
||||
".sms-channel-filter",
|
||||
".sms-channel-table",
|
||||
".sms-channel-total",
|
||||
".sms-channel-identity",
|
||||
".sms-channel-carrier-price",
|
||||
".sms-channel-status-cell",
|
||||
".sms-channel-quality",
|
||||
".sms-channel-rate",
|
||||
".sms-channel-actions",
|
||||
".sms-channel-pagination",
|
||||
".sms-channel-form",
|
||||
".sms-channel-radio-row",
|
||||
".sms-channel-inline-field",
|
||||
".sms-test-",
|
||||
".channel-log-",
|
||||
".channel-connection-summary"
|
||||
],
|
||||
"sharedSelectorsKeptGlobal": [],
|
||||
"sharedSelectorsKeptInAdmin": [".channel-confirm"],
|
||||
"interactionLabels": [
|
||||
"添加通道",
|
||||
"查询",
|
||||
"重置",
|
||||
"报备详情",
|
||||
"编辑",
|
||||
"复制通道",
|
||||
"发送测试",
|
||||
"连接日志"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"version": "R11",
|
||||
"stableEntry": "src/apps/admin/AdminEnterpriseApplicationsPage.tsx",
|
||||
"stableExport": "AdminEnterpriseApplicationsPage",
|
||||
"maxStableEntryLines": 300,
|
||||
"modules": {
|
||||
"src/apps/admin/enterprise-applications/EnterpriseApplicationFilter.tsx": [
|
||||
"EnterpriseApplicationFilter"
|
||||
],
|
||||
"src/apps/admin/enterprise-applications/EnterpriseApplicationTable.tsx": [
|
||||
"EnterpriseApplicationTable"
|
||||
],
|
||||
"src/apps/admin/enterprise-applications/ApplicationLifecycleModals.tsx": [
|
||||
"ConfirmModal",
|
||||
"DeactivateApplicationModal",
|
||||
"AddApplicationModal"
|
||||
],
|
||||
"src/apps/admin/enterprise-applications/ApplicationParamsModals.tsx": [
|
||||
"CmppParamsModal",
|
||||
"HttpParamsModal"
|
||||
],
|
||||
"src/apps/admin/enterprise-applications/CmppConnectionModal.tsx": [
|
||||
"CmppConnectionModal"
|
||||
],
|
||||
"src/apps/admin/enterprise-applications/applicationModel.ts": [
|
||||
"connectionStateMeta",
|
||||
"formatCmppParams",
|
||||
"mapConnection",
|
||||
"mapApplication"
|
||||
]
|
||||
},
|
||||
"apiCalls": {
|
||||
"src/apps/admin/AdminEnterpriseApplicationsPage.tsx": [
|
||||
"listEnterpriseApplicationsPage",
|
||||
"listTenants",
|
||||
"changeApplicationStatus",
|
||||
"getApplicationDeactivationPreview",
|
||||
"getApplicationCmppParams",
|
||||
"getApplicationHttpApiConfig"
|
||||
]
|
||||
},
|
||||
"styleFile": "src/apps/admin/enterprise-applications/AdminEnterpriseApplicationsPage.css",
|
||||
"styleImport": "./enterprise-applications/AdminEnterpriseApplicationsPage.css",
|
||||
"pageStyleSelectors": [
|
||||
".admin-application-filter",
|
||||
".cmpp-status-cell",
|
||||
".enterprise-app-actions",
|
||||
".cmpp-connection-detail",
|
||||
".cmpp-connection-summary",
|
||||
".cmpp-connection-list",
|
||||
".cmpp-connection-card",
|
||||
".cmpp-param-detail",
|
||||
".cmpp-param-grid",
|
||||
".cmpp-param-copy",
|
||||
".app-create-modal"
|
||||
],
|
||||
"sharedSelectorsKeptGlobal": [],
|
||||
"sharedSelectorsKeptInAdmin": [
|
||||
".admin-split-filter",
|
||||
".admin-split-filter__actions",
|
||||
".admin-confirm-text"
|
||||
],
|
||||
"sharedSelectorsKeptInComponents": [
|
||||
".template-modal-title",
|
||||
".form-grid"
|
||||
],
|
||||
"sharedSelectorsKeptInShell": [
|
||||
".section-stack"
|
||||
],
|
||||
"interactionLabels": [
|
||||
"企业名称",
|
||||
"企业应用名称",
|
||||
"状态",
|
||||
"查询",
|
||||
"重置",
|
||||
"添加应用",
|
||||
"短信应用",
|
||||
"彩信应用",
|
||||
"编辑",
|
||||
"停用",
|
||||
"启用",
|
||||
"删除",
|
||||
"CMPP参数",
|
||||
"HTTP参数",
|
||||
"新建企业应用",
|
||||
"CMPP连接详情"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
{
|
||||
"version": "R4",
|
||||
"source": "src/apps/admin/AdminEnterpriseSignaturesPage.tsx",
|
||||
"originalLines": 885,
|
||||
"movedFunctions": [
|
||||
{
|
||||
"name": "carrierLabel",
|
||||
"canonicalSha256": "cc074c9091c0c2198d8b38362242916c08457d2c7ecf9f0d7bb4c3a8e4912afd"
|
||||
},
|
||||
{
|
||||
"name": "CarrierReportTag",
|
||||
"canonicalSha256": "2ee4038f46fdb4c8e9af1fdbc5f7959f38d2360e081c7dd3b44d465be3b6cfef"
|
||||
},
|
||||
{
|
||||
"name": "signatureCardVisual",
|
||||
"canonicalSha256": "1cea544821c9c03b7c544644d5865e57810ae6f9c8d05d577ed104811ada63ec"
|
||||
},
|
||||
{
|
||||
"name": "AuditStatusTag",
|
||||
"canonicalSha256": "1a04a56dd4de4cb1988a15648738aa3cb8d8918dfac2ff15c159b663fa8756ee"
|
||||
},
|
||||
{
|
||||
"name": "readDrainagePayload",
|
||||
"canonicalSha256": "fa3d75286a89171511c9c4e52f4126b036128bbc91b15aedaa00360a4c7bbbcd"
|
||||
},
|
||||
{
|
||||
"name": "buildDrainagePayload",
|
||||
"canonicalSha256": "13ee432e93b20ba3dc104bd8be3cee31ae2092dbb244d6e12ad8eba018ad2d22"
|
||||
},
|
||||
{
|
||||
"name": "normalizeReportValues",
|
||||
"canonicalSha256": "ff050e5d4a1b2be8a606cb595a25d137bd0f08105e0f3cba8977dbb115612864"
|
||||
},
|
||||
{
|
||||
"name": "hasMissingRequiredReportValue",
|
||||
"canonicalSha256": "609c62b77ceee37afe961926fa897af0c3e156ce589709ae657a0038a38b481d"
|
||||
},
|
||||
{
|
||||
"name": "normalizeUploadedFile",
|
||||
"canonicalSha256": "f276b6ff6b3b9b6432ac638bd228c73923b00816e0f14dae5b43e0cb32393f08"
|
||||
},
|
||||
{
|
||||
"name": "normalizeCarrierStatus",
|
||||
"canonicalSha256": "5e4edd6bf9cacd5bcf6aa6197855780e03ab29cd3f5279b41a0eba2125ab1317"
|
||||
},
|
||||
{
|
||||
"name": "formatDate",
|
||||
"canonicalSha256": "fa6a491d6fa4f4e517cc9f3c07563424c9f7a8df30535274ddcbf6119c304b42"
|
||||
},
|
||||
{
|
||||
"name": "SignatureUploadBox",
|
||||
"canonicalSha256": "1e5c4d1e82c72ffd3bc1ddbd17628c1901d5ba81b0bb3ae161bcfb291a46dd98"
|
||||
},
|
||||
{
|
||||
"name": "DynamicReportFields",
|
||||
"canonicalSha256": "6370195b7a7afe5505003f233e31c07cbd3dac0ca55ce68b9859e83a827421f9"
|
||||
},
|
||||
{
|
||||
"name": "SignatureFormModal",
|
||||
"canonicalSha256": "664e1cd87309c64c03f9198543171bb519d448eec4a83cf890444fee16d6dd66"
|
||||
},
|
||||
{
|
||||
"name": "DrainageFormModal",
|
||||
"canonicalSha256": "0e63725f10e8021e0a7beb5a71f52773ce271faea137735d3fc184f07a39c6d6"
|
||||
},
|
||||
{
|
||||
"name": "SignatureReportModal",
|
||||
"canonicalSha256": "7439104e171e7d9eeb8449f497696b6d3736b881195c0b96a1a096079ba0789b"
|
||||
},
|
||||
{
|
||||
"name": "ChannelReportStatusModal",
|
||||
"canonicalSha256": "d32f8d7d3025ee286ed7898ed41a22404db3d684b80d23819965b3332e0e8310"
|
||||
},
|
||||
{
|
||||
"name": "DrainageReportModal",
|
||||
"canonicalSha256": "716a2d480a4b652ee951de0306854f1d8f6d72759d7b2fbffbfbb600abc8a789"
|
||||
},
|
||||
{
|
||||
"name": "DrainageReportStatusModal",
|
||||
"canonicalSha256": "ef692f08d2140e82e40fc12f716b15a902e3c66948140e8512f5a317c629215c"
|
||||
},
|
||||
{
|
||||
"name": "ConfirmModal",
|
||||
"canonicalSha256": "2f71bdc2f8044ca9b403affbb0cb3f31587e4c004a90e9e0836aa6143033b6da"
|
||||
}
|
||||
],
|
||||
"tableJsxSha256": "203ec16e0ca67f0dafea08d659e84db02dd8346d06a52f41378625e39a43def7",
|
||||
"apiCalls": [
|
||||
"listEnterpriseSignaturesPage",
|
||||
"listTenants",
|
||||
"listEnterpriseApplicationOptions",
|
||||
"updateEnterpriseSignature",
|
||||
"createEnterpriseSignature",
|
||||
"updateDrainageInfo",
|
||||
"createDrainageInfo",
|
||||
"changeDrainageInfoStatus"
|
||||
],
|
||||
"stateNames": [
|
||||
"activeTab",
|
||||
"applications",
|
||||
"deleteTarget",
|
||||
"drainageModal",
|
||||
"drainageReport",
|
||||
"drainageStatusTarget",
|
||||
"enterpriseKeyword",
|
||||
"appliedEnterpriseKeyword",
|
||||
"applicationKeyword",
|
||||
"appliedApplicationKeyword",
|
||||
"drainageKeyword",
|
||||
"appliedDrainageKeyword",
|
||||
"error",
|
||||
"expandedSignatureId",
|
||||
"signatureKeyword",
|
||||
"appliedSignatureKeyword",
|
||||
"signatureModal",
|
||||
"signatureReport",
|
||||
"reportStatusTarget",
|
||||
"signatures",
|
||||
"total",
|
||||
"tenants",
|
||||
"page",
|
||||
"importOpen",
|
||||
"message"
|
||||
],
|
||||
"files": [
|
||||
"signature.types.ts",
|
||||
"signature.helpers.tsx",
|
||||
"SignatureMaterialFields.tsx",
|
||||
"SignatureFormModal.tsx",
|
||||
"DrainageFormModal.tsx",
|
||||
"SignatureReportModals.tsx",
|
||||
"EnterpriseSignaturesTable.tsx"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
{
|
||||
"styleFile": "src/styles/admin.css",
|
||||
"globalStyleFile": "src/styles/global.css",
|
||||
"entryFile": "src/main.tsx",
|
||||
"marker": "Admin-only shared page patterns migrated from global.css in R11 step 8.",
|
||||
"minimumRuleCount": 117,
|
||||
"minimumSelectorCount": 141,
|
||||
"ownedClassPrefixes": [
|
||||
"admin-audit-",
|
||||
"admin-detail-metric-",
|
||||
"admin-report-filter-",
|
||||
"admin-security-",
|
||||
"admin-split-",
|
||||
"admin-system-",
|
||||
"admin-task-",
|
||||
"audit-filter-",
|
||||
"downstream-breakdown-",
|
||||
"downstream-bucket-"
|
||||
],
|
||||
"ownedExactClasses": [
|
||||
"admin-app-form-row",
|
||||
"admin-app-form-row--wide",
|
||||
"admin-confirm-text",
|
||||
"admin-uplink-empty-match",
|
||||
"audit-actions",
|
||||
"channel-confirm",
|
||||
"channel-field-config",
|
||||
"channel-field-config-title",
|
||||
"channel-field-section-head",
|
||||
"channel-report-empty",
|
||||
"enterprise-form-footer",
|
||||
"page-inline-hint",
|
||||
"report-history",
|
||||
"report-record-detail",
|
||||
"report-record-page",
|
||||
"report-task-table-card",
|
||||
"signature-alert",
|
||||
"sms-audit-filter"
|
||||
],
|
||||
"allowedContextClasses": [
|
||||
"mini-status-card",
|
||||
"page-heading"
|
||||
],
|
||||
"requiredSelectors": [
|
||||
".audit-filter-grid",
|
||||
".audit-filter-actions",
|
||||
".admin-task-filter",
|
||||
".admin-task-table-card .ui-table",
|
||||
".admin-security-filter",
|
||||
".admin-system-toolbar",
|
||||
".admin-system-modal-form",
|
||||
".admin-report-filter-grid--profit",
|
||||
".admin-split-filter",
|
||||
".admin-confirm-text",
|
||||
".downstream-breakdown-table",
|
||||
".channel-field-config",
|
||||
".signature-alert"
|
||||
],
|
||||
"usageRequirements": {
|
||||
"audit-filter-actions": 7,
|
||||
"admin-task-filter": 7,
|
||||
"admin-confirm-text": 5,
|
||||
"admin-task-table-card": 5,
|
||||
"admin-system-modal-form": 4,
|
||||
"admin-report-filter-grid": 3,
|
||||
"admin-security-filter": 3,
|
||||
"admin-split-filter": 3,
|
||||
"admin-system-page": 3,
|
||||
"downstream-breakdown-table": 2,
|
||||
"enterprise-form-footer": 2
|
||||
},
|
||||
"responsiveRequirements": [
|
||||
{
|
||||
"media": "(max-width: 780px)",
|
||||
"selector": ".admin-task-filter"
|
||||
},
|
||||
{
|
||||
"media": "(max-width: 780px)",
|
||||
"selector": ".admin-report-filter-grid"
|
||||
},
|
||||
{
|
||||
"media": "(max-width: 780px)",
|
||||
"selector": ".audit-filter-actions"
|
||||
},
|
||||
{
|
||||
"media": "(max-width: 360px)",
|
||||
"selector": ".audit-filter-actions"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
{
|
||||
"version": "R11",
|
||||
"stableEntry": "src/apps/admin/AdminSmsRecordsPage.tsx",
|
||||
"stableExport": "AdminSmsRecordsPage",
|
||||
"maxStableEntryLines": 220,
|
||||
"modules": {
|
||||
"src/apps/admin/sms-records/SmsRecordFilter.tsx": ["SmsRecordFilter"],
|
||||
"src/apps/admin/sms-records/SmsRecordList.tsx": ["SmsRecordList"],
|
||||
"src/apps/admin/sms-records/SendDetailModal.tsx": ["SendDetailModal"],
|
||||
"src/apps/admin/sms-records/smsRecordModel.ts": [
|
||||
"getDate",
|
||||
"getTime",
|
||||
"getClock",
|
||||
"getRecordStatus",
|
||||
"getRecordStatusLabel",
|
||||
"getReceiptNotice",
|
||||
"getCarrierLabel",
|
||||
"buildRouteRows",
|
||||
"downloadCsv",
|
||||
"defaultSmsRecordDateRange"
|
||||
]
|
||||
},
|
||||
"apiCalls": {
|
||||
"src/apps/admin/AdminSmsRecordsPage.tsx": [
|
||||
"listOperationMessages",
|
||||
"listTenants",
|
||||
"listEnterpriseApplicationOptions",
|
||||
"listMessageSegmentAudits",
|
||||
"exportOperationMessages"
|
||||
]
|
||||
},
|
||||
"styleFile": "src/apps/admin/sms-records/AdminSmsRecordsPage.css",
|
||||
"styleImport": "./sms-records/AdminSmsRecordsPage.css",
|
||||
"pageStyleSelectors": [
|
||||
".admin-sms-records-page",
|
||||
".admin-sms-record-filter",
|
||||
".admin-sms-record-table-card",
|
||||
".admin-sms-record-toolbar",
|
||||
".admin-sms-record-list",
|
||||
".admin-sms-record-card",
|
||||
".admin-sms-record-status",
|
||||
".admin-sms-record-detail-link",
|
||||
".admin-sms-send-detail",
|
||||
".admin-sms-detail-overview",
|
||||
".admin-sms-detail-notice",
|
||||
".admin-sms-detail-content",
|
||||
".admin-sms-detail-status-grid",
|
||||
".admin-sms-detail-failure",
|
||||
".admin-sms-segment-list",
|
||||
".admin-sms-segment-card",
|
||||
".admin-sms-route-list"
|
||||
],
|
||||
"sharedSelectorsKeptGlobal": [
|
||||
".muted"
|
||||
],
|
||||
"sharedSelectorsKeptInComponents": [
|
||||
".template-modal-title",
|
||||
".ui-table__empty"
|
||||
],
|
||||
"interactionLabels": [
|
||||
"企业",
|
||||
"应用",
|
||||
"提交日期",
|
||||
"手机号码",
|
||||
"运营商",
|
||||
"短信内容",
|
||||
"通道名称",
|
||||
"发送状态",
|
||||
"查询",
|
||||
"重置",
|
||||
"导出CSV",
|
||||
"查看发送详情",
|
||||
"发送详情",
|
||||
"通道发送与回执",
|
||||
"分片补偿审计"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"version": "R11",
|
||||
"stableEntry": "src/apps/admin/AdminSmsTaskProgressPage.tsx",
|
||||
"stableExport": "AdminSmsTaskProgressPage",
|
||||
"maxStableEntryLines": 220,
|
||||
"modules": {
|
||||
"src/apps/admin/sms-task-progress/SmsTaskFilter.tsx": ["SmsTaskFilter"],
|
||||
"src/apps/admin/sms-task-progress/SmsTaskTable.tsx": ["SmsTaskTable"],
|
||||
"src/apps/admin/sms-task-progress/TaskDetailModal.tsx": ["TaskDetailModal"],
|
||||
"src/apps/admin/sms-task-progress/TaskPhoneListModal.tsx": ["TaskPhoneListModal"],
|
||||
"src/apps/admin/sms-task-progress/TerminateTaskModal.tsx": ["TerminateTaskModal"],
|
||||
"src/apps/admin/sms-task-progress/taskModel.ts": [
|
||||
"mapTask",
|
||||
"getProgress",
|
||||
"getSuccessRate",
|
||||
"getRegionRate",
|
||||
"splitSignature"
|
||||
]
|
||||
},
|
||||
"apiCalls": {
|
||||
"src/apps/admin/AdminSmsTaskProgressPage.tsx": [
|
||||
"listAdminBatchTasksPage",
|
||||
"listTenants",
|
||||
"listEnterpriseApplicationOptions",
|
||||
"terminateAdminBatchTask"
|
||||
],
|
||||
"src/apps/admin/sms-task-progress/TaskPhoneListModal.tsx": [
|
||||
"listAdminBatchTaskMessages"
|
||||
]
|
||||
},
|
||||
"styleFile": "src/apps/admin/sms-task-progress/AdminSmsTaskProgressPage.css",
|
||||
"styleImport": "./sms-task-progress/AdminSmsTaskProgressPage.css",
|
||||
"pageStyleSelectors": [
|
||||
".admin-sms-task-page",
|
||||
".admin-task-template-row",
|
||||
".admin-task-detail-title",
|
||||
".admin-task-detail",
|
||||
".admin-task-metrics",
|
||||
".admin-task-metric",
|
||||
".admin-task-info-list",
|
||||
".admin-task-progress-card",
|
||||
".admin-task-progress-split",
|
||||
".admin-task-template-block",
|
||||
".admin-task-template",
|
||||
".admin-task-billing-note",
|
||||
".admin-task-card--full",
|
||||
".admin-carrier-grid",
|
||||
".admin-carrier-card",
|
||||
".admin-success-text"
|
||||
],
|
||||
"sharedSelectorsKeptGlobal": [
|
||||
".batch-progress"
|
||||
],
|
||||
"sharedSelectorsKeptInAdmin": [
|
||||
".admin-task-filter",
|
||||
".admin-task-table-card",
|
||||
".admin-task-id",
|
||||
".admin-task-enterprise",
|
||||
".admin-task-card"
|
||||
],
|
||||
"interactionLabels": [
|
||||
"发送批次号",
|
||||
"选择企业",
|
||||
"选择应用",
|
||||
"提交时间",
|
||||
"查询",
|
||||
"重置",
|
||||
"查看列表",
|
||||
"详情",
|
||||
"终止",
|
||||
"发送批次详情",
|
||||
"号码列表"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
{
|
||||
"version": "R11-step-6",
|
||||
"entry": "src/main.tsx",
|
||||
"component": "src/layouts/AppShell.tsx",
|
||||
"shellFile": "src/styles/shell.css",
|
||||
"legacyFiles": [
|
||||
"src/styles/global.css",
|
||||
"src/styles/components.css"
|
||||
],
|
||||
"importAfter": "@/styles/reset.css",
|
||||
"importBefore": "@/styles/global.css",
|
||||
"minimumRuleCount": 118,
|
||||
"shellClasses": [
|
||||
"app-shell",
|
||||
"app-shell--collapsed",
|
||||
"app-shell--mobile-nav-open",
|
||||
"sidebar",
|
||||
"sidebar--mobile-open",
|
||||
"sidebar-brand-row",
|
||||
"mobile-nav-close",
|
||||
"mobile-nav-toggle",
|
||||
"mobile-nav-backdrop",
|
||||
"mobile-topbar-brand",
|
||||
"brand-block",
|
||||
"brand-logo",
|
||||
"brand-logo--full",
|
||||
"brand-logo--compact",
|
||||
"side-nav",
|
||||
"side-nav-section",
|
||||
"side-nav-group-toggle",
|
||||
"side-nav-group-label",
|
||||
"side-nav-group-chevron",
|
||||
"side-nav-list",
|
||||
"side-nav-list--closed",
|
||||
"side-nav-label",
|
||||
"side-nav-label-text",
|
||||
"dev-status-badge",
|
||||
"side-nav-pending-badge",
|
||||
"sidebar-footer",
|
||||
"main-area",
|
||||
"topbar",
|
||||
"topbar-left",
|
||||
"topbar-actions",
|
||||
"desktop-nav-toggle",
|
||||
"topbar-help",
|
||||
"notice-menu-wrap",
|
||||
"notice-count",
|
||||
"notice-popover",
|
||||
"notice-popover__header",
|
||||
"user-menu",
|
||||
"user-menu-wrap",
|
||||
"user-menu-popover",
|
||||
"user-avatar",
|
||||
"page-content"
|
||||
],
|
||||
"legacyShellClasses": [
|
||||
"brand-copy",
|
||||
"brand-mark",
|
||||
"brand-subtitle"
|
||||
],
|
||||
"sharedLayoutSelectors": [
|
||||
".page-content",
|
||||
".page-stack",
|
||||
".page-heading",
|
||||
".page-heading > p",
|
||||
".page-heading__actions",
|
||||
".page-actions",
|
||||
".surface",
|
||||
".section-stack",
|
||||
".section-heading"
|
||||
],
|
||||
"requiredMediaQueries": [
|
||||
"(min-width: 781px)",
|
||||
"(max-width: 780px)",
|
||||
"(prefers-reduced-motion: reduce)"
|
||||
],
|
||||
"requiredRuleFragments": [
|
||||
{
|
||||
"selector": ".app-shell",
|
||||
"includes": [
|
||||
"display:grid",
|
||||
"grid-template-columns:var(--sidebar-width) minmax(0, 1fr)",
|
||||
"overflow:hidden"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".app-shell--collapsed",
|
||||
"includes": [
|
||||
"grid-template-columns:76px minmax(0, 1fr)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".sidebar",
|
||||
"media": "(max-width: 780px)",
|
||||
"includes": [
|
||||
"position:fixed",
|
||||
"transform:translateX(-105%)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".sidebar--mobile-open",
|
||||
"media": "(max-width: 780px)",
|
||||
"includes": [
|
||||
"transform:translateX(0)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".mobile-nav-backdrop",
|
||||
"media": "(max-width: 780px)",
|
||||
"includes": [
|
||||
"display:block",
|
||||
"position:fixed"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".page-content",
|
||||
"includes": [
|
||||
"overflow-y:auto",
|
||||
"width:100%"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".sidebar",
|
||||
"media": "(prefers-reduced-motion: reduce)",
|
||||
"includes": [
|
||||
"transition:none"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,928 @@
|
||||
{
|
||||
"version": "R5",
|
||||
"source": "api/src/channels/channels.service.ts",
|
||||
"generatedAt": "2026-07-31T02:40:10.189Z",
|
||||
"publicMethods": [
|
||||
{
|
||||
"name": "onModuleInit",
|
||||
"signature": "onModuleInit()",
|
||||
"canonicalBodySha256": "2a9debc88139a1a61f69060867abe7b4fcaf340ea3b40a19db9d4ae5aee7cfc2",
|
||||
"originalLines": [
|
||||
210,
|
||||
231
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "onModuleDestroy",
|
||||
"signature": "async onModuleDestroy()",
|
||||
"canonicalBodySha256": "9f72cbd51df2e3df22e08c15928e3382767eadfe9685e1db7dee2ed8a6d97155",
|
||||
"originalLines": [
|
||||
233,
|
||||
246
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "listChannels",
|
||||
"signature": "listChannels()",
|
||||
"canonicalBodySha256": "7ec25cd31ee4f261804a41a8781987abbfe246ac2118804b45efdef526c947b4",
|
||||
"originalLines": [
|
||||
248,
|
||||
253
|
||||
],
|
||||
"domain": "configuration"
|
||||
},
|
||||
{
|
||||
"name": "listChannelsPage",
|
||||
"signature": "async listChannelsPage(query: { keyword?: string; carrier?: string; status?: string; page?: number; pageSize?: number })",
|
||||
"canonicalBodySha256": "6b82d07ae76c4bfd979dbb319c64b8d8e0388df79e817b844d1e2700af7cc6be",
|
||||
"originalLines": [
|
||||
255,
|
||||
274
|
||||
],
|
||||
"domain": "configuration"
|
||||
},
|
||||
{
|
||||
"name": "createChannel",
|
||||
"signature": "async createChannel(data: CreateChannelDto)",
|
||||
"canonicalBodySha256": "eaee4eb581cb0891525f84c6912059785fd26cfff923e1973186f876b1e10745",
|
||||
"originalLines": [
|
||||
276,
|
||||
323
|
||||
],
|
||||
"domain": "configuration"
|
||||
},
|
||||
{
|
||||
"name": "updateChannel",
|
||||
"signature": "async updateChannel(channelId: string, data: UpdateChannelDto)",
|
||||
"canonicalBodySha256": "72eae5cdfca3c2563a6fa3f727056f582642ce3d6a8e35f24a47b1c1e53836d6",
|
||||
"originalLines": [
|
||||
325,
|
||||
413
|
||||
],
|
||||
"domain": "configuration"
|
||||
},
|
||||
{
|
||||
"name": "changeChannelStatus",
|
||||
"signature": "async changeChannelStatus(channelId: string, data: ChangeChannelStatusDto)",
|
||||
"canonicalBodySha256": "14ef7429e822ff520674699b449571424d9f7b0a13ce37a6c6fa9116449ac6d2",
|
||||
"originalLines": [
|
||||
415,
|
||||
444
|
||||
],
|
||||
"domain": "configuration"
|
||||
},
|
||||
{
|
||||
"name": "copyChannel",
|
||||
"signature": "async copyChannel(channelId: string, data: CopyChannelDto = {})",
|
||||
"canonicalBodySha256": "bdabf01a200cc5da9f9f17aee7df2fe0781bf79c36653cca9ddb8f84c7c63ed7",
|
||||
"originalLines": [
|
||||
446,
|
||||
530
|
||||
],
|
||||
"domain": "copy"
|
||||
},
|
||||
{
|
||||
"name": "deleteChannel",
|
||||
"signature": "async deleteChannel(channelId: string, data: ChangeChannelStatusDto = { status: 'deleted' })",
|
||||
"canonicalBodySha256": "1534ae0c91a6d12a97724d2d3f55b3e48469ad244e855be42aa93207be970d17",
|
||||
"originalLines": [
|
||||
532,
|
||||
534
|
||||
],
|
||||
"domain": "deletion"
|
||||
},
|
||||
{
|
||||
"name": "testChannel",
|
||||
"signature": "async testChannel(channelId: string, data: TestChannelDto = {})",
|
||||
"canonicalBodySha256": "e01b10f3981c66c5fab6cfd6d1b886abbb45e1fe53852b57c0903fcd826815d3",
|
||||
"originalLines": [
|
||||
536,
|
||||
636
|
||||
],
|
||||
"domain": "testing"
|
||||
},
|
||||
{
|
||||
"name": "listChannelMetrics",
|
||||
"signature": "listChannelMetrics(channelId: string)",
|
||||
"canonicalBodySha256": "bbe1b9191967c8eb13c413642786287382acbec93307d06ff843be1b9a163bcc",
|
||||
"originalLines": [
|
||||
638,
|
||||
644
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "listChannelConnections",
|
||||
"signature": "listChannelConnections(channelId: string)",
|
||||
"canonicalBodySha256": "07c644f24792d3c529daf39df4ac6d747e039c282d99d0f3cfffa8858a7ccf91",
|
||||
"originalLines": [
|
||||
646,
|
||||
651
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "listChannelConnectionLogs",
|
||||
"signature": "async listChannelConnectionLogs(channelId: string)",
|
||||
"canonicalBodySha256": "c01c6680974dc56813829bd6d47665e5be553ac6298f9207d19c951e4c540766",
|
||||
"originalLines": [
|
||||
653,
|
||||
687
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "listTenantConnections",
|
||||
"signature": "listTenantConnections(tenantId: string)",
|
||||
"canonicalBodySha256": "6aef43831f27c2ae7818dc449aadbaa7f521a6db54b78623b02d6bd0fc0a8810",
|
||||
"originalLines": [
|
||||
689,
|
||||
695
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "upsertConnectionState",
|
||||
"signature": "async upsertConnectionState(data: UpsertConnectionStateDto)",
|
||||
"canonicalBodySha256": "ce612114ed0abbf6653d11387d66c75c56fda22b8ceac7cdc3aece53cc999a8c",
|
||||
"originalLines": [
|
||||
697,
|
||||
786
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "markTimedOutConnectingChannels",
|
||||
"signature": "async markTimedOutConnectingChannels(now = new Date())",
|
||||
"canonicalBodySha256": "dbb713b158fa24088b5248a76eca5615c8a7fd3f89074d9627a6545622f55b70",
|
||||
"originalLines": [
|
||||
788,
|
||||
851
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "listGroups",
|
||||
"signature": "listGroups()",
|
||||
"canonicalBodySha256": "fc4ae9bd701db6f55108aa057f42a56b283901b3401903edb5464058d5a96374",
|
||||
"originalLines": [
|
||||
853,
|
||||
858
|
||||
],
|
||||
"domain": "groups"
|
||||
},
|
||||
{
|
||||
"name": "createGroup",
|
||||
"signature": "createGroup(data: CreateChannelGroupDto)",
|
||||
"canonicalBodySha256": "b5f50729da5cd843ba1a3ab5cd8ccc684d1baa06556610a030d91906dcf5d931",
|
||||
"originalLines": [
|
||||
860,
|
||||
875
|
||||
],
|
||||
"domain": "groups"
|
||||
},
|
||||
{
|
||||
"name": "addGroupItem",
|
||||
"signature": "async addGroupItem(data: CreateChannelGroupItemDto)",
|
||||
"canonicalBodySha256": "f34ae9a769d40a2ef7ccb6fab53d4a276190c71c2bee5084b1020a9bef85375a",
|
||||
"originalLines": [
|
||||
877,
|
||||
929
|
||||
],
|
||||
"domain": "groups"
|
||||
},
|
||||
{
|
||||
"name": "updateGroup",
|
||||
"signature": "async updateGroup(groupId: string, data: UpdateChannelGroupDto)",
|
||||
"canonicalBodySha256": "0a74b719119142424363c7b167f3b25daae018dbece386d863a4a0fcb7614645",
|
||||
"originalLines": [
|
||||
931,
|
||||
996
|
||||
],
|
||||
"domain": "groups"
|
||||
},
|
||||
{
|
||||
"name": "deleteGroup",
|
||||
"signature": "async deleteGroup(groupId: string)",
|
||||
"canonicalBodySha256": "ca89f1d6861fa4a5808e1d3e6a21062223faeab172246d5615d8447672105800",
|
||||
"originalLines": [
|
||||
998,
|
||||
1015
|
||||
],
|
||||
"domain": "groups"
|
||||
},
|
||||
{
|
||||
"name": "listRouteRules",
|
||||
"signature": "listRouteRules()",
|
||||
"canonicalBodySha256": "f4a905f76ab67b5ca8d66692b45ef17a2eaa8575329c871d40ec79a6d4b8a4ce",
|
||||
"originalLines": [
|
||||
1017,
|
||||
1022
|
||||
],
|
||||
"domain": "groups"
|
||||
},
|
||||
{
|
||||
"name": "createRouteRule",
|
||||
"signature": "async createRouteRule(data: CreateRouteRuleDto)",
|
||||
"canonicalBodySha256": "89d6bfc18ff419ac2a4e5eec92a2626e5c0d6e37728babe67a73924e5fcb0051",
|
||||
"originalLines": [
|
||||
1024,
|
||||
1057
|
||||
],
|
||||
"domain": "groups"
|
||||
},
|
||||
{
|
||||
"name": "listReportFields",
|
||||
"signature": "listReportFields(channelId?: string)",
|
||||
"canonicalBodySha256": "da3b95085c6d58739d4deda5ee7c0835fe181b84aba3473794a88653a6eb2def",
|
||||
"originalLines": [
|
||||
1059,
|
||||
1065
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "createReportField",
|
||||
"signature": "async createReportField(data: CreateReportFieldDto)",
|
||||
"canonicalBodySha256": "c5c854beda64f87d1237d46a9d9f06ba98366edddb0a28ad1bbec7a92fc20f06",
|
||||
"originalLines": [
|
||||
1067,
|
||||
1094
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "replaceReportFields",
|
||||
"signature": "async replaceReportFields(channelId: string, reportType: 'signature' | 'drainage', data: ReplaceReportFieldsDto)",
|
||||
"canonicalBodySha256": "fb1bc89d864d2423216d835e787821d4de5c2f6550573b8b20fdd966e5d41a5a",
|
||||
"originalLines": [
|
||||
1096,
|
||||
1142
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "listReportMaterials",
|
||||
"signature": "listReportMaterials(signatureId?: string, channelId?: string)",
|
||||
"canonicalBodySha256": "ff2661b65e206d3a79966f1c921f56b72c3fd8bd08d49a0a8bedff088ee5539e",
|
||||
"originalLines": [
|
||||
1144,
|
||||
1152
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "upsertReportMaterial",
|
||||
"signature": "upsertReportMaterial(data: CreateReportMaterialDto)",
|
||||
"canonicalBodySha256": "60704c21da36c28866e8ba12e4d3e8684785d87f34618710995525dbd77eaeb6",
|
||||
"originalLines": [
|
||||
1154,
|
||||
1175
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "listReportTasks",
|
||||
"signature": "async listReportTasks(tenantId?: string, status?: string, channelId?: string, reportType?: string)",
|
||||
"canonicalBodySha256": "a1374204cf233ff5389e27491674d89f946b184b9bb3722dd5fd1ed74073d21d",
|
||||
"originalLines": [
|
||||
1177,
|
||||
1303
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "listReportTasksPage",
|
||||
"signature": "async listReportTasksPage(query: {\n tenantId?: string;\n status?: string;\n channelId?: string;\n reportType?: string;\n keyword?: string;\n createdAtFrom?: string;\n createdAtTo?: string;\n page?: number;\n pageSize?: number;\n })",
|
||||
"canonicalBodySha256": "70ab547809d13c2c0a64898a5937444d819c1945ca1346e973059a8036e5a915",
|
||||
"originalLines": [
|
||||
1305,
|
||||
1360
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "createReportTask",
|
||||
"signature": "async createReportTask(data: CreateReportTaskDto)",
|
||||
"canonicalBodySha256": "0aca4b72828ddae3707cc1f12cf9a485868047195140783f269a70a0beb2286d",
|
||||
"originalLines": [
|
||||
1362,
|
||||
1384
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "changeReportTaskStatuses",
|
||||
"signature": "async changeReportTaskStatuses(data: ChangeReportTaskStatusesDto)",
|
||||
"canonicalBodySha256": "8427ebc2fa8246481b4232a45b647d28409a26d1a208176856b61690ae21da79",
|
||||
"originalLines": [
|
||||
1386,
|
||||
1422
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "createReportExport",
|
||||
"signature": "async createReportExport(taskId: string, data: CreateReportExportDto)",
|
||||
"canonicalBodySha256": "148dd68546b615108fec4ae54d00a435175adb7caa7ef82a3f98ebb6cc3016d8",
|
||||
"originalLines": [
|
||||
1447,
|
||||
1459
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "importReportReceipt",
|
||||
"signature": "async importReportReceipt(taskId: string, data: CreateReceiptImportDto)",
|
||||
"canonicalBodySha256": "47c55771a6f8cdc9ff23661d254521dd29905bb717562cbae9d643630d224a6d",
|
||||
"originalLines": [
|
||||
1461,
|
||||
1485
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "listReportRecords",
|
||||
"signature": "listReportRecords(taskId?: string, channelId?: string)",
|
||||
"canonicalBodySha256": "0dcea8c84fff26589de04fbd04a60913c46ab76a34f553d083db55525c327ffd",
|
||||
"originalLines": [
|
||||
1487,
|
||||
1493
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "listReportRecordsPage",
|
||||
"signature": "async listReportRecordsPage(query: {\n taskId?: string;\n channelId?: string;\n keyword?: string;\n reportType?: string;\n createdAtFrom?: string;\n createdAtTo?: string;\n page?: number;\n pageSize?: number;\n })",
|
||||
"canonicalBodySha256": "10516c3980113b0904b316e160cd1036dfd268cf8b16baf6bbfd791f4cebed32",
|
||||
"originalLines": [
|
||||
1495,
|
||||
1537
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "reconcileGatewayConnections",
|
||||
"signature": "async reconcileGatewayConnections(now = new Date())",
|
||||
"canonicalBodySha256": "95751f1fd97cd5991063a7a41e835e088df9754d6b735a3f1c796c2055d2879f",
|
||||
"originalLines": [
|
||||
1726,
|
||||
1773
|
||||
],
|
||||
"domain": "connection"
|
||||
}
|
||||
],
|
||||
"internalMethods": [
|
||||
{
|
||||
"name": "recomputeSignatureReportSummary",
|
||||
"signature": "private async recomputeSignatureReportSummary(tx: Prisma.TransactionClient, signatureId: string)",
|
||||
"canonicalBodySha256": "ced499f221e3132b85ed3152dda8d890a062bd6fbf4287db7d78410e03f746cf",
|
||||
"originalLines": [
|
||||
1424,
|
||||
1445
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "getReportTaskOrThrow",
|
||||
"signature": "private async getReportTaskOrThrow(taskId: string)",
|
||||
"canonicalBodySha256": "360c3d76c6b882765f4870ed5f56fdc3f09477d887f866d67876c2f64f504359",
|
||||
"originalLines": [
|
||||
1539,
|
||||
1548
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "updateReportTaskStatus",
|
||||
"signature": "private async updateReportTaskStatus(\n taskId: string,\n channelId: string,\n statusBefore: string,\n statusAfter: string,\n action: string,\n reason?: string,\n )",
|
||||
"canonicalBodySha256": "abcfd90557ef6c3ec91ac3ed43ff0d267520f7fc12c5e6a43c4d57545acdb692",
|
||||
"originalLines": [
|
||||
1550,
|
||||
1563
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "recordReportTask",
|
||||
"signature": "private recordReportTask(\n taskId: string,\n channelId: string,\n action: string,\n statusBefore: string | undefined,\n statusAfter: string,\n reason?: string,\n )",
|
||||
"canonicalBodySha256": "2128e08b3e3d52e396e0c58350b9d76e40d02e34e2f60bc75e413eca87f62a57",
|
||||
"originalLines": [
|
||||
1565,
|
||||
1583
|
||||
],
|
||||
"domain": "reporting"
|
||||
},
|
||||
{
|
||||
"name": "requestChannelConnection",
|
||||
"signature": "private async requestChannelConnection(\n channel: {\n id: string;\n code: string;\n name: string;\n gatewayHost: string;\n gatewayPort: number;\n account: string;\n passwordCipher: string;\n srcId: string;\n cmppVersion: string;\n rateLimitPerSecond: number;\n config?: Prisma.JsonValue | null;\n },\n reason: 'channel_created' | 'channel_enabled' | 'channel_updated' | 'gateway_restarted' | 'automatic_reconnect',\n operatorId?: string,\n )",
|
||||
"canonicalBodySha256": "df68d72a118a88e4ace78823e95d8af96079ccd03b756889c49d16adedb7a579",
|
||||
"originalLines": [
|
||||
1585,
|
||||
1709
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "reconnectActiveChannelsAfterGatewayRestart",
|
||||
"signature": "private async reconnectActiveChannelsAfterGatewayRestart()",
|
||||
"canonicalBodySha256": "e288503945449483bbd2120c0c36eff8b157c7045efe6fce9331ffba354dd958",
|
||||
"originalLines": [
|
||||
1711,
|
||||
1724
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "withGatewayReconcileLock",
|
||||
"signature": "private async withGatewayReconcileLock(channelId: string, action: () => Promise<void>)",
|
||||
"canonicalBodySha256": "8bbade14b639897f686c7cc3d4de32917b0a3525fbc27f08a44872c4824a3384",
|
||||
"originalLines": [
|
||||
1775,
|
||||
1793
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "requestChannelDisconnection",
|
||||
"signature": "private async requestChannelDisconnection(\n channel: { id: string },\n reason: 'channel_disabled' | 'channel_deleted' | 'inactive_channel_reconcile',\n operatorId?: string,\n )",
|
||||
"canonicalBodySha256": "02cfac1dc9953dfdbd95d63abd006f0e9b14be75a088a81c3773067a8719c92e",
|
||||
"originalLines": [
|
||||
1795,
|
||||
1852
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "getGatewayConnectionQueue",
|
||||
"signature": "private getGatewayConnectionQueue()",
|
||||
"canonicalBodySha256": "eb40aa7810cd4a26571eddfd2f21d7f2440b7e39fdb0657214ded056d8e286a3",
|
||||
"originalLines": [
|
||||
1854,
|
||||
1857
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "getGatewaySubmitQueue",
|
||||
"signature": "private getGatewaySubmitQueue()",
|
||||
"canonicalBodySha256": "d00641e15e3db84893cd302c767d6ac80a13e2ca3da5bc3d88f665fe3ffcacea",
|
||||
"originalLines": [
|
||||
1859,
|
||||
1862
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "getRedis",
|
||||
"signature": "private getRedis()",
|
||||
"canonicalBodySha256": "80f3524ea6442ba63f979b8daf0c19adbcec58a179e1deda3ce7fd3c7923cf62",
|
||||
"originalLines": [
|
||||
1864,
|
||||
1871
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "publishGatewaySubmitCommand",
|
||||
"signature": "private async publishGatewaySubmitCommand(command: unknown)",
|
||||
"canonicalBodySha256": "b6d027c12ca7d01a42a3ec81384b77fb07b16297ece386f9021e65d2148c4efc",
|
||||
"originalLines": [
|
||||
1873,
|
||||
1882
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "notifyGatewayConnect",
|
||||
"signature": "private async notifyGatewayConnect(command: Record<string, unknown>)",
|
||||
"canonicalBodySha256": "edc028c9fcb834e24cc9bc4fbc6aada5daff70674981cf5078d9db8631f007db",
|
||||
"originalLines": [
|
||||
1884,
|
||||
1901
|
||||
],
|
||||
"domain": "connection"
|
||||
},
|
||||
{
|
||||
"name": "notifyGatewayDisconnect",
|
||||
"signature": "private async notifyGatewayDisconnect(command: Record<string, unknown>)",
|
||||
"canonicalBodySha256": "8422aaf771157bcdd001c6b742eee437cb33c660872424845885c5850de1aaab",
|
||||
"originalLines": [
|
||||
1903,
|
||||
1920
|
||||
],
|
||||
"domain": "connection"
|
||||
}
|
||||
],
|
||||
"contracts": [
|
||||
{
|
||||
"name": "CreateChannelDto",
|
||||
"sha256": "5de2dff2a196fd99894e03223e169b87b8a9a8d5251c9fd5f700334c3cebbe00"
|
||||
},
|
||||
{
|
||||
"name": "UpdateChannelDto",
|
||||
"sha256": "63a98a44dac414fbb8063794d243f823b77dd63c213e677e7c3eb1c22fa92530"
|
||||
},
|
||||
{
|
||||
"name": "CreateChannelGroupDto",
|
||||
"sha256": "2d6c30f269ba7bf0c3d15d1a77175900edfad4184d4d469d0db0733878d4fd83"
|
||||
},
|
||||
{
|
||||
"name": "CreateChannelGroupItemDto",
|
||||
"sha256": "1a03b65c71ac8f52b84c87c599413bc747e8bb5402ecd23a91ad0ad1f513c2cb"
|
||||
},
|
||||
{
|
||||
"name": "UpdateChannelGroupDto",
|
||||
"sha256": "16c4ffdbd94c367e2932bee995d0b2c5357b57617ca2d48556efe896cd68e006"
|
||||
},
|
||||
{
|
||||
"name": "CreateRouteRuleDto",
|
||||
"sha256": "c0d24d5c1a266749098a7cecde488262dbebf9131429f018ec4bc05815b8c79d"
|
||||
},
|
||||
{
|
||||
"name": "CreateReportFieldDto",
|
||||
"sha256": "dff3ea95e4a5cfd9f880fa1ee8b5399452b3d4ac511e18ec5805f49856a061ef"
|
||||
},
|
||||
{
|
||||
"name": "ReplaceReportFieldsDto",
|
||||
"sha256": "3a8f0ca7d9f9113ad4612b50010d4138912b06851e84311a2d3f8b3f6c1b0adb"
|
||||
},
|
||||
{
|
||||
"name": "CreateReportMaterialDto",
|
||||
"sha256": "15a83e490bfefbc4c84cc0d70c9b18ab674ce2768577b0b3e7b19fa9fb40f3ac"
|
||||
},
|
||||
{
|
||||
"name": "CreateReportTaskDto",
|
||||
"sha256": "5ea18848e89c44f8ad9450af79f97a2cff7e3168fa62d23c6a881fbc61cea62b"
|
||||
},
|
||||
{
|
||||
"name": "ChangeReportTaskStatusesDto",
|
||||
"sha256": "028e467f76f796987e232b73d63f3d6babc6c15d7534f1cd4ceb5a67194107e4"
|
||||
},
|
||||
{
|
||||
"name": "CreateReportExportDto",
|
||||
"sha256": "e4ba2142b291c1939990c81b66dcef0cdc2747765c3c06a7a75becd1e4e08526"
|
||||
},
|
||||
{
|
||||
"name": "CreateReceiptImportDto",
|
||||
"sha256": "1c2a09ae37fba9adb03e5d6860757713d174eaed83b04aa2252d224d643e22cc"
|
||||
},
|
||||
{
|
||||
"name": "UpsertConnectionStateDto",
|
||||
"sha256": "432a9bdd2e0e9bcba7f9ae82c1bb45399881ada6faca3f8541dc4f43c3f58c1d"
|
||||
},
|
||||
{
|
||||
"name": "ChangeChannelStatusDto",
|
||||
"sha256": "61a8eab26aaf370ff6ceecc4d89810079857945386a1fdb3a10c99fd15d2c2fa"
|
||||
},
|
||||
{
|
||||
"name": "CopyChannelDto",
|
||||
"sha256": "9f0bbacd18c38a623dc3a2fc761506e91603f4a1b720a24000e76eff6e493039"
|
||||
},
|
||||
{
|
||||
"name": "TestChannelDto",
|
||||
"sha256": "fd1ed651d6a233fa044c4f5f2cd3e50aa046072ab6f39d810d89f15fead09820"
|
||||
}
|
||||
],
|
||||
"helpers": [
|
||||
{
|
||||
"name": "normalizeTestPhones",
|
||||
"sha256": "2f989fb549ddb0bf44ecc7912e0fd5a9b3c7fd8c99e5b7db4e8b97a11585d2b4"
|
||||
},
|
||||
{
|
||||
"name": "normalizeTestContent",
|
||||
"sha256": "c6aad6035f9afbe795cc1ba17b438d2ad5659fbe4b61900e8aa03ab29520e91e"
|
||||
},
|
||||
{
|
||||
"name": "calculateBillingUnits",
|
||||
"sha256": "a8e1449d3781c1bee1adfdeb2df5c2fff066990ca8260d827c8dfd2eb833452a"
|
||||
},
|
||||
{
|
||||
"name": "buildChannelTestSubmitCommand",
|
||||
"sha256": "d16842aed45059d881e4b844a5ec66b725fb9419cec4bcdc4fe3831cc5f49a2a"
|
||||
},
|
||||
{
|
||||
"name": "getConfigValue",
|
||||
"sha256": "6b5419962b5f1bc918a3d39f3d95a199bb663fd54372981090c51119cf49d1b0"
|
||||
},
|
||||
{
|
||||
"name": "getStringConfigValue",
|
||||
"sha256": "35b39e21df3d416c25682e29eda6d0e4626c35beae73e1fb47f77cf1bf9ef2ed"
|
||||
},
|
||||
{
|
||||
"name": "normalizeConnectionAction",
|
||||
"sha256": "8d0b596a85db2cb1816f909d180c390f10162f3d10d2cd16ce8eb7424ead399c"
|
||||
},
|
||||
{
|
||||
"name": "normalizeCmppVersion",
|
||||
"sha256": "220a9fbda9aeccab9c7331ee118d0f31fc1fca5bf0015e25c849e79d8bb12985"
|
||||
},
|
||||
{
|
||||
"name": "normalizeGatewayConnectionStatus",
|
||||
"sha256": "bf81060a9ddd788079bb1e22d3ffa64321a2df18c5fa902b20cdf1298cb40781"
|
||||
},
|
||||
{
|
||||
"name": "defaultChannelConnectionId",
|
||||
"sha256": "2ef3e882c598f1e5c003302f4f6143d67c151907b65af6f3eff06b1e89c91a3f"
|
||||
},
|
||||
{
|
||||
"name": "getDesiredConnections",
|
||||
"sha256": "d6e3f7b0134f0b94cc59c4b7ef117932980e5d4f86f9f9df6e7e63729232aee6"
|
||||
},
|
||||
{
|
||||
"name": "ChannelConnectionSettings",
|
||||
"sha256": "906b57eec65a23d27994c9e8130108cc95c4d4b1f169f05e61a39f76cb885abd"
|
||||
},
|
||||
{
|
||||
"name": "getRuntimeConfigInteger",
|
||||
"sha256": "0e595766faa70ba9a33716c10d7c7478f87d0543fc4c7e2b86c95bc5df30221d"
|
||||
},
|
||||
{
|
||||
"name": "channelConnectionSettingsChanged",
|
||||
"sha256": "1d9371059cc95c3080577fd9e7c71ba50b16f7ee3e01b70c486c61bb056c89e3"
|
||||
},
|
||||
{
|
||||
"name": "channelGroupAuditSnapshot",
|
||||
"sha256": "8ac6c3de6cf9f843b4635e8fb3ff89691b9b0762febe26a3887a5f17fa9de5b6"
|
||||
},
|
||||
{
|
||||
"name": "normalizeChannelRuntimeConfig",
|
||||
"sha256": "a979b4bcb5e7b8d1acfb0b99196a9c8dec7f834116140af170113b25da7d14d5"
|
||||
},
|
||||
{
|
||||
"name": "normalizeCmppServiceId",
|
||||
"sha256": "e1f620b4df0283aa08421ebe05c25c0cc1407edc105d54df27f655122423debf"
|
||||
},
|
||||
{
|
||||
"name": "normalizeChannelRateLimit",
|
||||
"sha256": "897aca7bc66a023e1d4ca2cf1ab5d3d9660128432b4726f88c878da2f55c5098"
|
||||
},
|
||||
{
|
||||
"name": "normalizeExtensionDigits",
|
||||
"sha256": "91e1526daad821cddc886cf0f8fe580aa8f7b8beeaef2be836d7c2ebd57eb96d"
|
||||
},
|
||||
{
|
||||
"name": "getPositiveRuntimeInteger",
|
||||
"sha256": "b2aff43304863e222db1788ee6177a3a8b14b0c5c3097b1ff3fda98e71fd50a2"
|
||||
},
|
||||
{
|
||||
"name": "bullmqConnection",
|
||||
"sha256": "1fe9095c9ed383419f640913f033ff0715d4e241c8114543097a51dbf1acaf67"
|
||||
},
|
||||
{
|
||||
"name": "getPositiveIntegerEnv",
|
||||
"sha256": "db5d7ea71b1dc0e9bb72724c533893117f27c689ce485b180a2409ae6a3eed2c"
|
||||
},
|
||||
{
|
||||
"name": "parseReceiptContent",
|
||||
"sha256": "068290aef6af4376b6f0ed012914716296dfc1a43d10f447b0939b8aea9a7ec8"
|
||||
},
|
||||
{
|
||||
"name": "splitReceiptLine",
|
||||
"sha256": "29768fe9359e8dfc2e280743d3a5eaa0374aaf311eccd3c4ede6ef4e9bf35299"
|
||||
},
|
||||
{
|
||||
"name": "stripReceiptCell",
|
||||
"sha256": "bc29e649d5381c1c0c060102cd3e421114f32475e7156260b915a9984acb5369"
|
||||
},
|
||||
{
|
||||
"name": "findReceiptStatusIndex",
|
||||
"sha256": "cdd4244f0265164ac134f1645e603d112dde73100975e6438c71b11b3dfa40e0"
|
||||
},
|
||||
{
|
||||
"name": "normalizeReceiptStatus",
|
||||
"sha256": "b92ba14156d4e61722d2539e9c6b16ac29f920799fcdd4fcb917feb135394375"
|
||||
},
|
||||
{
|
||||
"name": "deriveReceiptStatus",
|
||||
"sha256": "465c39b82cd2cb9ea99b399f7290dfec8859172c8ffb6ad09683656f058b0847"
|
||||
},
|
||||
{
|
||||
"name": "ChannelReportDeliveryRow",
|
||||
"sha256": "216600c3398717f2ad200d9352cd64920593d8a07f6127b528eda9daf9404f3c"
|
||||
},
|
||||
{
|
||||
"name": "summarizeChannelReportDelivery",
|
||||
"sha256": "411701471d807f3ee01f6894016cb61b03c88c8018bc15a8465ca8296005b9bf"
|
||||
},
|
||||
{
|
||||
"name": "sumReportDelivery",
|
||||
"sha256": "73583b6176cbcd2f4625332a852c458bacaf0e3ebf87c5a391739176a612db9f"
|
||||
},
|
||||
{
|
||||
"name": "percentage",
|
||||
"sha256": "0745594434cceab4d6e2c4098d996dd338b7406c1506b7fc01edc4fdf488b404"
|
||||
},
|
||||
{
|
||||
"name": "latestDate",
|
||||
"sha256": "6686352cea283be461c9b15e76d83725c501397ccb6fbb739f86b05ddd9eec43"
|
||||
},
|
||||
{
|
||||
"name": "currentShanghaiDayRange",
|
||||
"sha256": "2684fcc9f35792427c24ad6044b491f8a24ca717ad963e662698983910da1ce3"
|
||||
},
|
||||
{
|
||||
"name": "normalizeRetryTimeLimitMinutes",
|
||||
"sha256": "68869e767b9820f076a41bb347bcd93e8245f7e6d8be351bfe17378b0d9b83a3"
|
||||
},
|
||||
{
|
||||
"name": "normalizeSpreadsheetSize",
|
||||
"sha256": "bcf7f1849728cf246e41561df3239b5327ce5926c49da43c014337c6bfa4090a"
|
||||
},
|
||||
{
|
||||
"name": "normalizeBusinessCarrier",
|
||||
"sha256": "44f10156d5d0da501a56b477ea44c143f41f330fa49d48272bc993b1e698cfa6"
|
||||
},
|
||||
{
|
||||
"name": "normalizeChannelCarrier",
|
||||
"sha256": "eb8e4e1b7c192aa3b2cb57586c7415207c3531d31614d8608a5f80e5c64e77d4"
|
||||
},
|
||||
{
|
||||
"name": "isChannelCarrierCompatible",
|
||||
"sha256": "35350532169cf227d4222dc48bf0c0b232c1bd74b13a139d8cffd0564a7738f5"
|
||||
},
|
||||
{
|
||||
"name": "normalizeRegion",
|
||||
"sha256": "3775eb50779ce87f8982ce691b18f91d8ed145a5dc9c27c8a315b0f55cb09152"
|
||||
},
|
||||
{
|
||||
"name": "isRegionCompatible",
|
||||
"sha256": "bbe33cc0c45cb58dbd5ee2daf241df6485abe52713dba185ee4493462b00e1de"
|
||||
},
|
||||
{
|
||||
"name": "validateGroupItems",
|
||||
"sha256": "eaf0f6e54c38cbcc52fa8c970fe1d6f7729e3bb12b2366dca89c93da8088bd2c"
|
||||
},
|
||||
{
|
||||
"name": "normalizeReportType",
|
||||
"sha256": "22fbaaa9756d56f0665b2bd8571c3bea1c84144a8dc81855e982c757217a920a"
|
||||
},
|
||||
{
|
||||
"name": "summarizeReportStatuses",
|
||||
"sha256": "ca9c3f0eece4b9e04f30cbc317041c52d63dcbb74ef1f87021dae5b20ca154b0"
|
||||
},
|
||||
{
|
||||
"name": "normalizeLinkEvent",
|
||||
"sha256": "4843d9bd396f02c8e5dcca4eb4b7abaefe422b4caead5aa23ca331bc41f47376"
|
||||
}
|
||||
],
|
||||
"sharedDeclarations": [
|
||||
{
|
||||
"name": "GATEWAY_CONNECTION_QUEUE",
|
||||
"sha256": "e76ea45c5057f6597dc25a8b94a34c43a38f2d189577ba8fa04285d5a1f4902f"
|
||||
},
|
||||
{
|
||||
"name": "GATEWAY_SUBMIT_QUEUE",
|
||||
"sha256": "c69e4af1b3939a576aa63833947b10b86b87a646b373684d9726dfbaf4c95d8c"
|
||||
},
|
||||
{
|
||||
"name": "GATEWAY_SUBMIT_STREAM",
|
||||
"sha256": "70d662152ad15ff017e1f61aca86525554c5b6a83f97686529dca1a0eaf28849"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_GATEWAY_CONTROL_URL",
|
||||
"sha256": "e4b9884f5435352e666ee82acd2073917c0aea9215cb25c0ef18f1ca2cc1c88e"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_CHANNEL_CONNECTION_ID",
|
||||
"sha256": "26a18e1d0aaea4a67b919a10ea8e847ea14851a0106d153f545c22c124e41098"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_CONNECTING_TIMEOUT_MS",
|
||||
"sha256": "50748837da843f79079acee716b39498605a3129285f9e4d48576a05cb7180ad"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_CONNECTING_TIMEOUT_SCAN_MS",
|
||||
"sha256": "80bc3b12df7aef1b067931d0ed1cd07b9bb56f675543ed03524c51bf6ca64fc8"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_GATEWAY_STARTUP_RECONNECT_DELAY_MS",
|
||||
"sha256": "1b0a0499b6970c99be17ce4e4384e83eaf81b8c3323839e769c5f1a7f6ef6f93"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_GATEWAY_RECONCILE_INTERVAL_MS",
|
||||
"sha256": "a02067c10cce5264097823109e2cdd5a24f4d8a592d4b845f4180506c8879358"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_GATEWAY_CONTROL_TIMEOUT_MS",
|
||||
"sha256": "c7cb65a45b9e3e12bedd579190ca0a9b5a07dc74e314ede6874417dba1f51125"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_HEARTBEAT_INTERVAL_SECONDS",
|
||||
"sha256": "7b96e3a74159fe87eac349f0602d33c9982e1785c89aaec7ec72d5966c3cc449"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_HEARTBEAT_MISS_THRESHOLD",
|
||||
"sha256": "33d0d1bfbcafb1811d3a521c68d7dfff34c969314fa132badad9576030b2875d"
|
||||
},
|
||||
{
|
||||
"name": "HEARTBEAT_AUDIT_INTERVAL_MS",
|
||||
"sha256": "ed7d05fb517bf7ffe6dc5d16af7aa61dc70e6e69ef216706f013b783dfcc03aa"
|
||||
},
|
||||
{
|
||||
"name": "CONNECTING_TIMEOUT_ERROR",
|
||||
"sha256": "6b6c5057edff678a5f3d7fef7f5764354ee4b9e80cc9130de25e1baf5e50f33d"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_CMPP_VERSION",
|
||||
"sha256": "e2c460ac8b6427fa3874e3763c9ba98e5a13d9e14b039be1fccd3d4ae828d358"
|
||||
}
|
||||
],
|
||||
"domains": {
|
||||
"configuration": {
|
||||
"className": "ChannelConfigurationService",
|
||||
"file": "api/src/channels/channel-configuration.service.ts",
|
||||
"methods": [
|
||||
"listChannels",
|
||||
"listChannelsPage",
|
||||
"createChannel",
|
||||
"updateChannel",
|
||||
"changeChannelStatus"
|
||||
]
|
||||
},
|
||||
"connection": {
|
||||
"className": "ChannelConnectionService",
|
||||
"file": "api/src/channels/channel-connection.service.ts",
|
||||
"methods": [
|
||||
"onModuleInit",
|
||||
"onModuleDestroy",
|
||||
"listChannelMetrics",
|
||||
"listChannelConnections",
|
||||
"listChannelConnectionLogs",
|
||||
"listTenantConnections",
|
||||
"upsertConnectionState",
|
||||
"markTimedOutConnectingChannels",
|
||||
"requestChannelConnection",
|
||||
"reconnectActiveChannelsAfterGatewayRestart",
|
||||
"reconcileGatewayConnections",
|
||||
"withGatewayReconcileLock",
|
||||
"requestChannelDisconnection",
|
||||
"getGatewayConnectionQueue",
|
||||
"getGatewaySubmitQueue",
|
||||
"getRedis",
|
||||
"publishGatewaySubmitCommand",
|
||||
"notifyGatewayConnect",
|
||||
"notifyGatewayDisconnect"
|
||||
]
|
||||
},
|
||||
"testing": {
|
||||
"className": "ChannelTestService",
|
||||
"file": "api/src/channels/channel-test.service.ts",
|
||||
"methods": [
|
||||
"testChannel"
|
||||
]
|
||||
},
|
||||
"groups": {
|
||||
"className": "ChannelGroupRoutingService",
|
||||
"file": "api/src/channels/channel-group-routing.service.ts",
|
||||
"methods": [
|
||||
"listGroups",
|
||||
"createGroup",
|
||||
"addGroupItem",
|
||||
"updateGroup",
|
||||
"deleteGroup",
|
||||
"listRouteRules",
|
||||
"createRouteRule"
|
||||
]
|
||||
},
|
||||
"reporting": {
|
||||
"className": "ChannelReportingService",
|
||||
"file": "api/src/channels/channel-reporting.service.ts",
|
||||
"methods": [
|
||||
"listReportFields",
|
||||
"createReportField",
|
||||
"replaceReportFields",
|
||||
"listReportMaterials",
|
||||
"upsertReportMaterial",
|
||||
"listReportTasks",
|
||||
"listReportTasksPage",
|
||||
"createReportTask",
|
||||
"changeReportTaskStatuses",
|
||||
"recomputeSignatureReportSummary",
|
||||
"createReportExport",
|
||||
"importReportReceipt",
|
||||
"listReportRecords",
|
||||
"listReportRecordsPage",
|
||||
"getReportTaskOrThrow",
|
||||
"updateReportTaskStatus",
|
||||
"recordReportTask"
|
||||
]
|
||||
},
|
||||
"copy": {
|
||||
"className": "ChannelCopyService",
|
||||
"file": "api/src/channels/channel-copy.service.ts",
|
||||
"methods": [
|
||||
"copyChannel"
|
||||
]
|
||||
},
|
||||
"deletion": {
|
||||
"className": "ChannelDeletionService",
|
||||
"file": "api/src/channels/channel-deletion.service.ts",
|
||||
"methods": [
|
||||
"deleteChannel"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"styleFile": "src/styles/client.css",
|
||||
"globalStyleFile": "src/styles/global.css",
|
||||
"entryFile": "src/main.tsx",
|
||||
"marker": "Client-only cross-page patterns migrated from global.css in R11 step 9.",
|
||||
"ownedClasses": [
|
||||
"eyebrow"
|
||||
],
|
||||
"minimumRuleCount": 1,
|
||||
"minimumSelectorCount": 1,
|
||||
"usageRequirements": {
|
||||
"eyebrow": 2
|
||||
},
|
||||
"requiredGlobalContextSelectors": [
|
||||
".overview-hero .eyebrow"
|
||||
],
|
||||
"crossPortalClassesKeptGlobal": {
|
||||
"sms-send-title": {
|
||||
"minimumClientFiles": 9,
|
||||
"minimumAdminFiles": 1
|
||||
},
|
||||
"system-page-toolbar": {
|
||||
"minimumClientFiles": 3,
|
||||
"minimumAdminFiles": 1
|
||||
},
|
||||
"system-table-card": {
|
||||
"minimumClientFiles": 2,
|
||||
"minimumAdminFiles": 1
|
||||
}
|
||||
},
|
||||
"singlePageClassesKeptGlobal": [
|
||||
"client-signature-page",
|
||||
"sms-send-page",
|
||||
"enterprise-page",
|
||||
"send-detail-table",
|
||||
"template-card-grid"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"version": "R11-step-5",
|
||||
"entry": "src/main.tsx",
|
||||
"importOrder": [
|
||||
"@/styles/tokens.css",
|
||||
"@/styles/reset.css",
|
||||
"@/styles/shell.css",
|
||||
"@/styles/global.css",
|
||||
"@/styles/admin.css",
|
||||
"@/styles/client.css",
|
||||
"@/styles/components.css"
|
||||
],
|
||||
"applicationImport": "import { AppRoutes } from '@/routes/AppRoutes';",
|
||||
"tokensFile": "src/styles/tokens.css",
|
||||
"minimumTokenCount": 76,
|
||||
"requiredTokens": [
|
||||
"--color-brand",
|
||||
"--color-bg",
|
||||
"--color-surface",
|
||||
"--color-text",
|
||||
"--color-success",
|
||||
"--color-warning",
|
||||
"--color-danger",
|
||||
"--font-family",
|
||||
"--font-size-md",
|
||||
"--line-height-base",
|
||||
"--space-4",
|
||||
"--radius-md",
|
||||
"--shadow-md",
|
||||
"--focus-ring",
|
||||
"--transition-base",
|
||||
"--sidebar-width",
|
||||
"--topbar-height",
|
||||
"--control-height-md",
|
||||
"--z-modal"
|
||||
],
|
||||
"resetFile": "src/styles/reset.css",
|
||||
"sourceFile": "src/styles/global.css",
|
||||
"resetRuleHashes": {
|
||||
"*": "06a686d623d71b39cbece4a1d14e066e9fca18db0a088f919462faeb6d866b79",
|
||||
"html": "c5e097ee4c514843a085f38e8a4092cf8c791561496021e835fe8b075741b973",
|
||||
"body": "959e2ae61d9722a688f7bb11c48ef52ff9cad53367bfd719b4fb19c8113386fc",
|
||||
"a": "00e72791df6422df87fbc1aba2097c700dc3fbab83a5bdb1c04a89a03f4c4058",
|
||||
"button,input,textarea,select": "bba903ee69611779f6c456ba3d96685aeed0e4ba3422d17b1f21cda6c6cebc7c",
|
||||
"button": "ecfbb78629d7763f151589ad78e4e635758c53eeeb07a7bffef7c00d1785fe2a",
|
||||
"button:disabled,input:disabled,textarea:disabled,select:disabled": "09672a6b885e18268ff3715646b191eb2d842befcda5b0f5f6630d8201f825cc",
|
||||
":focus": "1f6d5babe8d9f56a802929a5c4da11bde3de6d636925eb3898e66c17714d13ea",
|
||||
":focus-visible": "f6de580d559ff9e468267d7f3173fc241cff1e65096402696e5ac407fbe8fbad",
|
||||
"h1,h2,h3,p": "de52e3be99f485f9aeba54183525162a236998888c83bd06c1e543b545afef30",
|
||||
"h1": "140b54a87d2ccdb060105bf2213e51ac5cc3592ee0992bfc80c830b59d1c78ac",
|
||||
"h2": "171665ed54789deace1ccfa93b2e7b0c4d9c3bf0ea02a935eddeb18abc99fef3",
|
||||
"h3": "2b6273b83065e5938f3bf8f1b14d6daba9bd9abecf09aea6d5c9ded4303f6aee"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
{
|
||||
"version": "R6",
|
||||
"source": "gateway/internal/inbound/server.go@HEAD-before-R6",
|
||||
"declarations": [
|
||||
{
|
||||
"name": "beginDownstreamSubmitBarrier",
|
||||
"kind": "func",
|
||||
"file": "acknowledgement.go",
|
||||
"sha256": "0ccbbba14c2ecff9da00681aa9e44181925e9f1793de1e793587ac931e3644e3"
|
||||
},
|
||||
{
|
||||
"name": "defaultDownstreamAckTimeout",
|
||||
"kind": "const",
|
||||
"file": "acknowledgement.go",
|
||||
"sha256": "92565b410c5f61c6b1a93eb40bc28be9131962f811e0ee912d69332aaefa12df"
|
||||
},
|
||||
{
|
||||
"name": "downstreamAckKey",
|
||||
"kind": "func",
|
||||
"file": "acknowledgement.go",
|
||||
"sha256": "a3ff3a57dd6952a9a859867136d8a532c9b9c99b60dfc1ba0f4aad8ea51f7bc0"
|
||||
},
|
||||
{
|
||||
"name": "downstreamAckRegistry",
|
||||
"kind": "var",
|
||||
"file": "acknowledgement.go",
|
||||
"sha256": "0f2c687864a9c57295739510f26ad343d7a5eb22e1f15fb7cdbb13d8e72d440c"
|
||||
},
|
||||
{
|
||||
"name": "downstreamAckTimeout",
|
||||
"kind": "func",
|
||||
"file": "acknowledgement.go",
|
||||
"sha256": "97d0878d73a6e1d6890207a776e536ad4bcd5efb8fc2bda49f930b23d3c740cc"
|
||||
},
|
||||
{
|
||||
"name": "downstreamAckTracker",
|
||||
"kind": "type",
|
||||
"file": "acknowledgement.go",
|
||||
"sha256": "53bfa44f334cc06acf6ce564d84d641dc6aafed6b57416023cef4c4ae86d2771"
|
||||
},
|
||||
{
|
||||
"name": "downstreamSubmitBarrier",
|
||||
"kind": "var",
|
||||
"file": "acknowledgement.go",
|
||||
"sha256": "211cb910963239f8660aa639607b955bbb54cc7d38484c6f89815c4127315cb3"
|
||||
},
|
||||
{
|
||||
"name": "downstreamSubmitResponsePending",
|
||||
"kind": "func",
|
||||
"file": "acknowledgement.go",
|
||||
"sha256": "9c43ecb4303ea8a70918a211f7e1ab1162947e98fe44b77d5e86f4995d5a16e2"
|
||||
},
|
||||
{
|
||||
"name": "handleDownstreamAcknowledgement",
|
||||
"kind": "func",
|
||||
"file": "acknowledgement.go",
|
||||
"sha256": "2bf1b5292111360bdda24e6c9348de739e95f2a9bbd56b8c3d2744e5b6ffe071"
|
||||
},
|
||||
{
|
||||
"name": "registerDownstreamAck",
|
||||
"kind": "func",
|
||||
"file": "acknowledgement.go",
|
||||
"sha256": "33a12b5d4ed3f949d2670a717af6e8febc54de4a1f008e3cbad6b43837b4779a"
|
||||
},
|
||||
{
|
||||
"name": "removeDownstreamAck",
|
||||
"kind": "func",
|
||||
"file": "acknowledgement.go",
|
||||
"sha256": "76d357d99c8b14dd04d0f6bf0c09699c6f75966f639f7499b26d854899d723a6"
|
||||
},
|
||||
{
|
||||
"name": "takeDownstreamAck",
|
||||
"kind": "func",
|
||||
"file": "acknowledgement.go",
|
||||
"sha256": "947085393b5a694df4b234040bafaa59ecfe86c3ade0404808f243ae55f0d6b8"
|
||||
},
|
||||
{
|
||||
"name": "authRequest",
|
||||
"kind": "type",
|
||||
"file": "authentication.go",
|
||||
"sha256": "0d3e6ab7ec4f418fefb88d2930b01c23eaff926097474c50ba678d553a1aa5a1"
|
||||
},
|
||||
{
|
||||
"name": "authResponse",
|
||||
"kind": "type",
|
||||
"file": "authentication.go",
|
||||
"sha256": "387ff32b3067a0eb342d09e1e5d3308f8359415171a2045f10dc56ca01205727"
|
||||
},
|
||||
{
|
||||
"name": "authenticate",
|
||||
"kind": "func",
|
||||
"file": "authentication.go",
|
||||
"sha256": "3dba30340070be6b78dcb1de963fde7a567701925684279c5b675ee9b197ec2c"
|
||||
},
|
||||
{
|
||||
"name": "cmppVersionName",
|
||||
"kind": "func",
|
||||
"file": "authentication.go",
|
||||
"sha256": "b9ab5ed0382868bb23cde01142e4245038ed22501fbef0605ff0c936df07149d"
|
||||
},
|
||||
{
|
||||
"name": "handleLogin",
|
||||
"kind": "func",
|
||||
"file": "authentication.go",
|
||||
"sha256": "bf3bdbcda7ddfd9f0e2ff53b436e151c94247b4ed40bcf60ec2f78fdb2559e64"
|
||||
},
|
||||
{
|
||||
"name": "setInboundConnectResponse",
|
||||
"kind": "func",
|
||||
"file": "authentication.go",
|
||||
"sha256": "4dbf12a8fda63789457f9f610871eec97da0122e23ba0e55d1db95a15f5c47ae"
|
||||
},
|
||||
{
|
||||
"name": "DownstreamReceipt",
|
||||
"kind": "type",
|
||||
"file": "delivery.go",
|
||||
"sha256": "772d9cc917b7f2968532480366634a595ba0b0f501d25b85eb0d799eec991eb0"
|
||||
},
|
||||
{
|
||||
"name": "DownstreamSendResult",
|
||||
"kind": "type",
|
||||
"file": "delivery.go",
|
||||
"sha256": "28af9ad91e045e2a11e5b91b9d989f7b7b09ef6cc3b2fa5cf420722fcbe5538b"
|
||||
},
|
||||
{
|
||||
"name": "DownstreamUplink",
|
||||
"kind": "type",
|
||||
"file": "delivery.go",
|
||||
"sha256": "22be370c5a551b5739b0d4f849ad2990febf0db57ec3ae89ec699f9a95895c80"
|
||||
},
|
||||
{
|
||||
"name": "PushReceipt",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "321b26a357ae633278d92cc87e7f2f796af12c22b165eb19ba5c3e2b80dc67ce"
|
||||
},
|
||||
{
|
||||
"name": "PushReceiptWithResult",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "ecc96ae40af974c3faedbe991fa01e71d9ed79c3fccaf964526a726cd6853487"
|
||||
},
|
||||
{
|
||||
"name": "PushUplink",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "47f42edc03b663ba189defc91207da76263837535f1292fe52c9dbf542a4c8a0"
|
||||
},
|
||||
{
|
||||
"name": "PushUplinkWithResult",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "2ec907ba43d4906b92c0aae693eb19f1e3a26d7a61d1efaa93e9258a11482ad0"
|
||||
},
|
||||
{
|
||||
"name": "cmppReceiptStatus",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "ba6b72b46f9869fe22005f7d48b2668b0aa2242bf5a01203d8c62b2b778ed8cb"
|
||||
},
|
||||
{
|
||||
"name": "downstreamDeliverMessageID",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "a58e6d0da35b374361518f7573f5f92b987eddd2f6753bc1e6e4312986cff7ed"
|
||||
},
|
||||
{
|
||||
"name": "downstreamDeliverMetadata",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "a510caae34ffc46577985cd8b538e5924a3f4a43dcfedf8d60678c497d185912"
|
||||
},
|
||||
{
|
||||
"name": "downstreamDeliverPacket",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "721de5632b72041a6102687cf4dece41b854c5bb34150c586a01c662b2cb1bbf"
|
||||
},
|
||||
{
|
||||
"name": "downstreamDeliveryLifecycleEvent",
|
||||
"kind": "type",
|
||||
"file": "delivery.go",
|
||||
"sha256": "4acf5485100e1bc6bb19a8004a3b1b7796fd8a6192fe2899e163abed7d134b69"
|
||||
},
|
||||
{
|
||||
"name": "errorMessageWithCode",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "56e4380e43ee3fb9f99e6daf6e468583077372ffe0049133589907b87ab5aa3d"
|
||||
},
|
||||
{
|
||||
"name": "findReceiptSession",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "af27e3accceff7023b09bb7f4ba716978edf89e3a9a4981c41439e279cf3bb5a"
|
||||
},
|
||||
{
|
||||
"name": "findSession",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "cd9ddd0acd71bdd0ac32d2f2892f37c1461181038f193f9f9411a48b64dd0f22"
|
||||
},
|
||||
{
|
||||
"name": "pushReceiptWithResult",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "ed0be61791a471b59a92601aa34f47b9d72c606096863493bb1dbb89a2d5e0a9"
|
||||
},
|
||||
{
|
||||
"name": "recoverReceiptSession",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "b64f7eb8d7817580ddbdb88008169fa2f1f239bbf2d1cf3d976129da40799bee"
|
||||
},
|
||||
{
|
||||
"name": "reportDownstreamDelivery",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "ea3bb61fb23718fc8d3b5ce2d75984eb00bc7f965612655f08951fc83d8147d9"
|
||||
},
|
||||
{
|
||||
"name": "sendDownstream",
|
||||
"kind": "func",
|
||||
"file": "delivery.go",
|
||||
"sha256": "1f85300328d803f5efab654f3038e7da59444a53feb5c41db1833b8d1824c2cc"
|
||||
},
|
||||
{
|
||||
"name": "flushOnlineAccounts",
|
||||
"kind": "func",
|
||||
"file": "pending_recovery.go",
|
||||
"sha256": "692d49fcb9ff3e116ce9476f826445996de00e5f714f21a5fa56a28afba18a10"
|
||||
},
|
||||
{
|
||||
"name": "flushPending",
|
||||
"kind": "func",
|
||||
"file": "pending_recovery.go",
|
||||
"sha256": "e4e2cfaa9471e132360fd9fdd8e83e03142f6fb450b76ada4b368b5cc6ae1fd2"
|
||||
},
|
||||
{
|
||||
"name": "logRecoveryCandidates",
|
||||
"kind": "func",
|
||||
"file": "pending_recovery.go",
|
||||
"sha256": "cd44224d2b6f4b4dbadc9a37d94a285d900c3e8323e36d57cea2f578ba818f24"
|
||||
},
|
||||
{
|
||||
"name": "pendingDelivery",
|
||||
"kind": "type",
|
||||
"file": "pending_recovery.go",
|
||||
"sha256": "fd6d25266aecc90ec7f68c88699c444e74b21215a518775678bbd84d28181c81"
|
||||
},
|
||||
{
|
||||
"name": "pendingDeliveryRequest",
|
||||
"kind": "type",
|
||||
"file": "pending_recovery.go",
|
||||
"sha256": "f7e72647951c29203eae90189368434d2bdcc3473f2a3ba7eb05f6ba489bc221"
|
||||
},
|
||||
{
|
||||
"name": "pendingFlushInterval",
|
||||
"kind": "func",
|
||||
"file": "pending_recovery.go",
|
||||
"sha256": "2b11f99b604ff894fba202947ab656b0578f55d0c291fee418574c099852a796"
|
||||
},
|
||||
{
|
||||
"name": "pendingFlushResult",
|
||||
"kind": "type",
|
||||
"file": "pending_recovery.go",
|
||||
"sha256": "6cb42b62fed78024a6401657e0bb48969fced040da914d043aac49bf7332caa1"
|
||||
},
|
||||
{
|
||||
"name": "pushPendingDelivery",
|
||||
"kind": "func",
|
||||
"file": "pending_recovery.go",
|
||||
"sha256": "a228f8e0ad2f43a68a9308b31d457294a3b967cfbcd8acb6b9117ccd92e027c7"
|
||||
},
|
||||
{
|
||||
"name": "recoverPendingCandidates",
|
||||
"kind": "func",
|
||||
"file": "pending_recovery.go",
|
||||
"sha256": "3c4949a98f31e60b1f38a83d3eec4b0fc28719d7300848bb0ed561c77f119e82"
|
||||
},
|
||||
{
|
||||
"name": "recoveryFailureCategory",
|
||||
"kind": "func",
|
||||
"file": "pending_recovery.go",
|
||||
"sha256": "b1686eeb07ede06fd5f77bee6fe203e5e5ea99a394bd318127c419f0924ce4b4"
|
||||
},
|
||||
{
|
||||
"name": "runPendingFlusher",
|
||||
"kind": "func",
|
||||
"file": "pending_recovery.go",
|
||||
"sha256": "5b2031765192bd9818931d8418e2790a491e6d76275cd71994d2df023617973a"
|
||||
},
|
||||
{
|
||||
"name": "syncRecoveryStatus",
|
||||
"kind": "func",
|
||||
"file": "pending_recovery.go",
|
||||
"sha256": "b63dfdf300570e510d45b2ac71cd0ebf06af9cf6b157db2fc436a7fa0e4345d0"
|
||||
},
|
||||
{
|
||||
"name": "emitProtocolLog",
|
||||
"kind": "func",
|
||||
"file": "protocol_log.go",
|
||||
"sha256": "2f162fe182184f1f2c940e48e5cb35680b41ef828cf375def5839e8713b1a079"
|
||||
},
|
||||
{
|
||||
"name": "protocolLogEvent",
|
||||
"kind": "type",
|
||||
"file": "protocol_log.go",
|
||||
"sha256": "67492ad6e52c6b57c52d8cf37c5564d4fafbd3655aaad706548da412e93fccaf"
|
||||
},
|
||||
{
|
||||
"name": "protocolSendResultCode",
|
||||
"kind": "func",
|
||||
"file": "protocol_log.go",
|
||||
"sha256": "f338ef80a1f9baeac7c3ce42f4d89ae629724de3121c13f6568f3b64a1f53472"
|
||||
},
|
||||
{
|
||||
"name": "protocolSendStatus",
|
||||
"kind": "func",
|
||||
"file": "protocol_log.go",
|
||||
"sha256": "c18f5b646d2b08fe6bf0d007293b1abe432a552ff19f0a27aee29ad765ba2451"
|
||||
},
|
||||
{
|
||||
"name": "protocolSubmitResponseDetail",
|
||||
"kind": "func",
|
||||
"file": "protocol_log.go",
|
||||
"sha256": "db6055b3e156e733b195f197f4f6ea324dc188f59cf6511a5617c6ba6f8c75aa"
|
||||
},
|
||||
{
|
||||
"name": "recordDownstreamProtocol",
|
||||
"kind": "func",
|
||||
"file": "protocol_log.go",
|
||||
"sha256": "4a4e70075e619a094abaa5a13885938544a7055f3aa582a861cd5b0e596495c3"
|
||||
},
|
||||
{
|
||||
"name": "submitResponseProtocolLogger",
|
||||
"kind": "func",
|
||||
"file": "protocol_log.go",
|
||||
"sha256": "94441a243f14e376d6e4f0ac00358752f43a0928f7215943b8e81d0bb9fd3969"
|
||||
},
|
||||
{
|
||||
"name": "ListenAndServe",
|
||||
"kind": "func",
|
||||
"file": "server.go",
|
||||
"sha256": "c57e5d860f6bdbb7d47a5414e0d186fe34cf61c42f94fc2b1ab5739b6272c272"
|
||||
},
|
||||
{
|
||||
"name": "Server",
|
||||
"kind": "type",
|
||||
"file": "server.go",
|
||||
"sha256": "9dacd52458fb19e19752e201de3b9c9b6e8fd9ba93afda454e7d7444b17148f5"
|
||||
},
|
||||
{
|
||||
"name": "defaultHTTPTimeout",
|
||||
"kind": "const",
|
||||
"file": "server.go",
|
||||
"sha256": "247aaf1070a6886f01059677dad739e69cb9dd10bd55d6397ba5fb9d385fe39a"
|
||||
},
|
||||
{
|
||||
"name": "DisconnectAccount",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "306c822ca618b5d47dd002595e0896b87d86c26a0b35ef7ea6b032df8cefe66b"
|
||||
},
|
||||
{
|
||||
"name": "downstreamConnectionEvent",
|
||||
"kind": "type",
|
||||
"file": "sessions.go",
|
||||
"sha256": "d56a2bde011b9499ca6436f1da858f66f8aab02b790fe41aef7b49a70190be7e"
|
||||
},
|
||||
{
|
||||
"name": "downstreamRegistry",
|
||||
"kind": "var",
|
||||
"file": "sessions.go",
|
||||
"sha256": "c1cf77d72cbe4ceff9def118bfdbfbe54417e6156e9af3345a87cd6c4a02fe05"
|
||||
},
|
||||
{
|
||||
"name": "downstreamSession",
|
||||
"kind": "type",
|
||||
"file": "sessions.go",
|
||||
"sha256": "36d85eab72c673e4e4d47a2b60e68d96561ecb93b0a851de850280706e6779bc"
|
||||
},
|
||||
{
|
||||
"name": "findSessionByConn",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "5563363dae78b586715ee48b3e6eb93a3ea397116a40e1bb99d0b1ce1072f255"
|
||||
},
|
||||
{
|
||||
"name": "forgetDownstream",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "7e5b930ff7d1b7400936504d91cc850bce8334ac0953370da3b2d6786d4e6372"
|
||||
},
|
||||
{
|
||||
"name": "gatewayInstanceID",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "0175fef1017de9e0c65adfe894375a463e8769185c8f7b17d7acbe96993edcb0"
|
||||
},
|
||||
{
|
||||
"name": "handleActivity",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "7ec78fd7054aca6c55fd4b3a16bf8fa3b3a9c53e398a4164f06a39018fbaa5aa"
|
||||
},
|
||||
{
|
||||
"name": "handleConnectionClosed",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "a3ed1e51c1057fa9f4a899de266f1750257ad9b7742d319cf5dac22a3341afd0"
|
||||
},
|
||||
{
|
||||
"name": "onlineAccounts",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "fbbdd0bbe4e222a7d7e83302986bedefb4dcc762bbd9b31e2a886c0ef5f1564f"
|
||||
},
|
||||
{
|
||||
"name": "rememberAccount",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "50ee995075641dcb3bb7dd2d1aefd72e1ec7fb352ad69862e8504db91c78eafd"
|
||||
},
|
||||
{
|
||||
"name": "rememberDownstream",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "0803f1f2b2c69d47ac4adf0ec3d48fc122b5c994318dda93738b9c4d5ea56f64"
|
||||
},
|
||||
{
|
||||
"name": "removePresence",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "4a5332055b810da8432712f2e4d0566d2245ca638401288f9ea616686de13af2"
|
||||
},
|
||||
{
|
||||
"name": "reportConnection",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "6cdbadc05d0f7afe3dd2a5e77965380474949734ab05eddb463b31753a9064fc"
|
||||
},
|
||||
{
|
||||
"name": "reportConnectionChecked",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "af5321ddf095bd00f3c790796ae3731bd0aa7b1c52d07bc9e909354bf731df1d"
|
||||
},
|
||||
{
|
||||
"name": "reportConnectionOrDisconnect",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "61cf0ec3ac4278be5ccbd112d196aec662ae20f6aebd6079ac7102e83b1e7008"
|
||||
},
|
||||
{
|
||||
"name": "touchPresence",
|
||||
"kind": "func",
|
||||
"file": "sessions.go",
|
||||
"sha256": "d3f55aaaf52c33e3b6916f9e0d4e91754c88b28b997ae80b8d647fb07a3f7fc4"
|
||||
},
|
||||
{
|
||||
"name": "decodeContent",
|
||||
"kind": "func",
|
||||
"file": "submit.go",
|
||||
"sha256": "a66a6cc45a405c028cf41c7946dc89c6b1a313019863d6aa4b0a468d3ce7ef3f"
|
||||
},
|
||||
{
|
||||
"name": "decodeInboundSubmitContent",
|
||||
"kind": "func",
|
||||
"file": "submit.go",
|
||||
"sha256": "84f72bc74d7953096788001675d426bde14285a4a617e0524c0d194ce8744fe6"
|
||||
},
|
||||
{
|
||||
"name": "handleSubmit",
|
||||
"kind": "func",
|
||||
"file": "submit.go",
|
||||
"sha256": "fcb1d5ada61ff28a39976506e6a14f1fc09f840eaa4033ec9ea3fb9b8f0882f0"
|
||||
},
|
||||
{
|
||||
"name": "inboundLongMessageFragment",
|
||||
"kind": "type",
|
||||
"file": "submit.go",
|
||||
"sha256": "65fccbf8525f98948c307291bced71dff6c31e0f6a4015dcde4a9a45fc85c236"
|
||||
},
|
||||
{
|
||||
"name": "inboundSubmitPacket",
|
||||
"kind": "type",
|
||||
"file": "submit.go",
|
||||
"sha256": "50984034ef07833dcc2f4c4156cfe7f0add8767ae2b4d376001931e4f211e9d5"
|
||||
},
|
||||
{
|
||||
"name": "messageIDFrom",
|
||||
"kind": "func",
|
||||
"file": "submit.go",
|
||||
"sha256": "a5b5d130552b844568055e06e96d6d0aa9a421ef61fb8e4ff4fb6e5b6cecc984"
|
||||
},
|
||||
{
|
||||
"name": "normalizeInboundSubmit",
|
||||
"kind": "func",
|
||||
"file": "submit.go",
|
||||
"sha256": "e9f6b5bee5fe114d0fefee910d818bafa6834a00709fade7f4e0468f821e69fd"
|
||||
},
|
||||
{
|
||||
"name": "setInboundSubmitResponse",
|
||||
"kind": "func",
|
||||
"file": "submit.go",
|
||||
"sha256": "a21d1418c08aeb65a545f2e9d713f9a6c3fd720e80f996757f9af8d5bc982cc4"
|
||||
},
|
||||
{
|
||||
"name": "submit",
|
||||
"kind": "func",
|
||||
"file": "submit.go",
|
||||
"sha256": "b541d2c1d7e5592a6b8ad213d0cdbb81fcc98702023f1d5a4d35207476767ae7"
|
||||
},
|
||||
{
|
||||
"name": "submitRequest",
|
||||
"kind": "type",
|
||||
"file": "submit.go",
|
||||
"sha256": "8b622eefb6255f762b332a1d161269b116c234018a32cc881b9bde138a8fb1cd"
|
||||
},
|
||||
{
|
||||
"name": "submitResponse",
|
||||
"kind": "type",
|
||||
"file": "submit.go",
|
||||
"sha256": "aa2f05c154f7d6682d4214e8f16063784edabc7d60380c167f7a3b0c01cdfbea"
|
||||
},
|
||||
{
|
||||
"name": "submitResponseMessage",
|
||||
"kind": "type",
|
||||
"file": "submit.go",
|
||||
"sha256": "4a3b3c59d27627712d40e5caecb760d1dfefab51377c9ff45479850f46e4e9cf"
|
||||
},
|
||||
{
|
||||
"name": "apiBaseURL",
|
||||
"kind": "func",
|
||||
"file": "transport.go",
|
||||
"sha256": "96f0f2b1f3807bc966ff1b5e81917e2dfe09c64b1e13037563a2a83bb448c06a"
|
||||
},
|
||||
{
|
||||
"name": "defaultString",
|
||||
"kind": "func",
|
||||
"file": "transport.go",
|
||||
"sha256": "e3f1c7ba3d2aa985b2df53748e307f4e2769815d3cb8500dc616b929cee1e38a"
|
||||
},
|
||||
{
|
||||
"name": "formatRFC3339Nano",
|
||||
"kind": "func",
|
||||
"file": "transport.go",
|
||||
"sha256": "fd069087ad8497197f55a98ecfb9e5b1234ce641a0fb0a9161f8c320f436dd37"
|
||||
},
|
||||
{
|
||||
"name": "post",
|
||||
"kind": "func",
|
||||
"file": "transport.go",
|
||||
"sha256": "10fac868d1fe77fe2c261f14692245b6a08b573ee460cde0c7a77f6ee3ca77b1"
|
||||
},
|
||||
{
|
||||
"name": "remoteIP",
|
||||
"kind": "func",
|
||||
"file": "transport.go",
|
||||
"sha256": "84831ab34bb3ac39f998829ea9e4b61f92711c9c4eafa5ab214ddadefd969bd4"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
{
|
||||
"version": "r2",
|
||||
"baselineCommit": "0af671b4ed4713912e703defd08791f164d4eb25",
|
||||
"generatedAt": "2026-07-31",
|
||||
"contracts": {
|
||||
"MessageQuery": "07530ba61641758c96b5cd91dcdaba8692d5da4d9657d66e71009e7abf338f13",
|
||||
"TraceQuery": "636138d9593d61b2936eb32231d071b4682ca1d36cbf6a2b07d3b71b4f5d8453",
|
||||
"OperationLogQuery": "084d60f6487a2b38264211bf030950baacd2bc9b218e992867fb0e429dae7ece",
|
||||
"GatewaySubmitDeadLetterQuery": "d40dea1cc7d5ee369ab16a49cada5c6bcfae2b21fc66459c49d9377374aa1445",
|
||||
"DownstreamDeliveryQuery": "fd5b570bce0723aa6e848dd74ee326f3fb920dca86d5a60ffb8b1ed743343027",
|
||||
"DownstreamDeliveryDashboardQuery": "62f06aba6ac8bc90b0885a70bcc6038901c1727438e7e9b70c16bfa88b2c7f08",
|
||||
"DownstreamRecoveryStatusQuery": "74f3018a6d582a4ffde9711217fcc32d42131a9e262ae9b39b3025bd03d2b7f3",
|
||||
"MessageSegmentAuditQuery": "90cf141034feb9fec50d54a2f6c0b5491d6e38cc05e87a687e9caa487f018f84",
|
||||
"SignatureQualityQuery": "880bf2a7d74d94f552e50d9d0e19dbe95e893f7deaac16bb831ec4c9171ce663"
|
||||
},
|
||||
"methods": [
|
||||
{
|
||||
"name": "listBatchTasks",
|
||||
"group": "messages",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "1a807b62cd5a6553fb7736503ad2fdba03dbbed36578d69c6a4d3ea42cc33131",
|
||||
"bodySha256": "ab7f0cf4b606772d574549e552e081b36e339e3a800d82e7a948ab6dd7e090e8"
|
||||
},
|
||||
{
|
||||
"name": "listClientBatchTasks",
|
||||
"group": "messages",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "0561e37c80d66c53cca310d05db707b14a640f7c184e309c3a7ef4d7d0aec3af",
|
||||
"bodySha256": "530af84aa681bcfdb3b2a7d919955ee3e047d3d5d5c77a96700796aef7db38eb"
|
||||
},
|
||||
{
|
||||
"name": "listMessages",
|
||||
"group": "messages",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "566e0533151b80b2d94ca77b1c65ab6faf5d94defc4467ebc521636a92a1a8c2",
|
||||
"bodySha256": "e422326e97868efacff02ea767a7b4f71ed18231c85315674c9f267c2a13cffb"
|
||||
},
|
||||
{
|
||||
"name": "listMessagesPage",
|
||||
"group": "messages",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "fbae7a944bd2cd8c398c4d1f1a72ca272cbb9b4d17eb1092acaadd681a5fe7a8",
|
||||
"bodySha256": "1bef139de372ce4335e69898f7a078a9ced9d531d545fbae02ec68e8085c56e7"
|
||||
},
|
||||
{
|
||||
"name": "exportMessages",
|
||||
"group": "messages",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "37075fd6448d81f6acc25efe9a3670c8d6ec962add6a0b1e3115a31c05f8d7a6",
|
||||
"bodySha256": "649439bf58c411100dcc24d634c7f2c87c6323c74cfc76539f853485c3c59461"
|
||||
},
|
||||
{
|
||||
"name": "listClientMessages",
|
||||
"group": "messages",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "585b2dcab9df6f95965e9df59965bdb525a516fde88b2fcfa2719a8374df2ec2",
|
||||
"bodySha256": "af305e69074e100706864afdc83fcc29c63222b0628c2dc514a18ff74273c763"
|
||||
},
|
||||
{
|
||||
"name": "listClientMessagesPage",
|
||||
"group": "messages",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "2655a52bcb2755a944e7fb95d2d12169b487bc965719739376fe7447dcfe2770",
|
||||
"bodySha256": "3ea79e41bfe3f9ca09774754ba9213213184153a4ce93bff6f68d085e99baa9b"
|
||||
},
|
||||
{
|
||||
"name": "listUplinkMessages",
|
||||
"group": "uplink",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "3384d96065b6fa29c5785d27b5193488b7deb27f2d6fe1482abfdb94cf5e1096",
|
||||
"bodySha256": "f5a949d7587ff83ca40f0fe1f68677e3dafd3d634ea11086ae633de2b93320cf"
|
||||
},
|
||||
{
|
||||
"name": "listClientUplinkMessages",
|
||||
"group": "uplink",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "a06d90bad32600a836a5d823f91914c70e8937bdecb5d140108de348f08ed7bd",
|
||||
"bodySha256": "bec584ee827d27e65225377e1baa41982f241181804e74c0aa4eae560ed8c861"
|
||||
},
|
||||
{
|
||||
"name": "listUplinkMessagesPage",
|
||||
"group": "uplink",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "0ee52e770b7e79b26667d3846e36bc7b1e46352b92c8a48f7f1c1d03dc78b9ac",
|
||||
"bodySha256": "c067c19488d4f74acc04e3af3e8956cecbf511571e4f3b8315a06ade21a58ff9"
|
||||
},
|
||||
{
|
||||
"name": "monitor",
|
||||
"group": "uplink",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "b3e5732d2f136021b62b5bd35c2cb332bfcdfc7a9cb5d4cf6288835152314287",
|
||||
"bodySha256": "58758622feed4546da827b2b2e5d7a4e73c926349c258819604302626940250b"
|
||||
},
|
||||
{
|
||||
"name": "dashboard",
|
||||
"group": "dashboard",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "7bea6ce2744f19d6a6c7ec2078e986b9f36aa8ac139c83a9bf21f2554550a3b0",
|
||||
"bodySha256": "50f10c48dcb9a0e7a7fdeae445fcd6a930a51894a76ce9834e306a70a598c574"
|
||||
},
|
||||
{
|
||||
"name": "clientDashboard",
|
||||
"group": "dashboard",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "56ce59f4e54b1811ade9a04040bafed17a454371dfd6e8780a8c268e6d59f30e",
|
||||
"bodySha256": "6f257604b3a6bf2e6b9da84b9c76b8b3f26f0987038a2ff1cfec06c7024aa2ec"
|
||||
},
|
||||
{
|
||||
"name": "statistics",
|
||||
"group": "quality",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "3e4afcc84ee2dfc40e52ef4bea80fc737c23204b40c0522363e276469f96947b",
|
||||
"bodySha256": "723a194c3ef3bfc732d36d0ab4b6ebce178782fab7f5d4b6b12a8e0906cf51ed"
|
||||
},
|
||||
{
|
||||
"name": "sendQuality",
|
||||
"group": "quality",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "7fa4cd6bcee4092390a38d693aa30c7980781ca1baa73dd07a3a61f097774e9c",
|
||||
"bodySha256": "730b291f2fa96a9bcb054589a1341bc21f8ade161d232141d74f77eb426c4522"
|
||||
},
|
||||
{
|
||||
"name": "signatureQuality",
|
||||
"group": "quality",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "6b9c3761674cb0d01000caca5e12cf91a6e526757592ffb783fc673c178b204c",
|
||||
"bodySha256": "c85644b03f607339c2eae5390b01fb520264e87f16d0439c81a0c101b4277fa2"
|
||||
},
|
||||
{
|
||||
"name": "auditLogs",
|
||||
"group": "logs",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "d4ad56308f1d27e5e131b75c74f03484ae21c1a85d26efc7c5fa2237e94da41e",
|
||||
"bodySha256": "32646b12989c4a313558779d74fd7a75fbc3d8a965b5e9f4da9830f2a08ee785"
|
||||
},
|
||||
{
|
||||
"name": "systemLogs",
|
||||
"group": "logs",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "a2e578db34e6100b6257fd1ed6beabf28d732f014e9fc8f8cf914587f0feb5b2",
|
||||
"bodySha256": "d0a1fc83b2c306f52679129b235db79ed88ae1ac30af6e27793b6891af3933e8"
|
||||
},
|
||||
{
|
||||
"name": "exportSystemLogs",
|
||||
"group": "logs",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "101ded394553c05cd4ed3f80f95a1716bdfb505029ba38f7d04d3f20564b88c3",
|
||||
"bodySha256": "5f95e55b1095be6370b9327e622e3881c415d34af6f926a94ec8c0bd91ba75dc"
|
||||
},
|
||||
{
|
||||
"name": "resolveClientTenantId",
|
||||
"group": "logs",
|
||||
"isPrivate": true,
|
||||
"signatureSha256": "2935888aed8bbcfbd04f73f68c1feed70ca3dc0b3b31ef38bd34b479e656b51d",
|
||||
"bodySha256": "292a41d7e213a6d85c44061f2e04aeed8b18e9b61f2cf6656802cb89f9e32611"
|
||||
},
|
||||
{
|
||||
"name": "listGatewaySubmitDeadLetters",
|
||||
"group": "downstream",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "fe33722f549a09191d3132c67c2664b5ce9df518aac70aaf3234b5abaef5e0d8",
|
||||
"bodySha256": "c9552eb39c44c863d7d916191245620274275229e3f7246ad2596a46ce28560b"
|
||||
},
|
||||
{
|
||||
"name": "listDownstreamDeliveries",
|
||||
"group": "downstream",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "5fe6e1847a711fbcf547934513367ba591e6364d630b89a7133f8400cd0a1c84",
|
||||
"bodySha256": "9f5f8efa141a4efcb057586008c6d942a346ac1b64889e381d4ce23155fe06e9"
|
||||
},
|
||||
{
|
||||
"name": "downstreamDeliveryDashboard",
|
||||
"group": "downstream",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "a47a03bfeada0a7ccc284a8a13f9a6481213f9c4d3bd8a9ffc6567396290a376",
|
||||
"bodySha256": "88412a45bdf75fb2b99873191ca0637deffa6b4fb23e345915ef58ee152f83c0"
|
||||
},
|
||||
{
|
||||
"name": "listDownstreamRecoveryStatuses",
|
||||
"group": "downstream",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "cdf304441b834467417e60cf9476589910f84697fae2ec8a911519b202142baa",
|
||||
"bodySha256": "1db9498db2129d8977604c199de2bf07bcf28fec9f370a7c272aba3cf876c575"
|
||||
},
|
||||
{
|
||||
"name": "listMessageSegmentAudits",
|
||||
"group": "downstream",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "fe617d8ba6907506f7d0327d5e0dfed23cd50681c55eeae66291e12058c2d26e",
|
||||
"bodySha256": "9644db4083b0d960060664254d86449f06ad5bed577941ca52a08983fb470045"
|
||||
},
|
||||
{
|
||||
"name": "getDownstreamRecoveryStatus",
|
||||
"group": "downstream",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "00f7598b8bf8b997df01d5ae2471c9941e224342c47d8a77c5701754ee4d4c26",
|
||||
"bodySha256": "55d9da10bc9357e05f2de7fff47d269e5f64e28791d93d1ee1bae2c8d3d731dd"
|
||||
},
|
||||
{
|
||||
"name": "exportDownstreamRecoveryStatuses",
|
||||
"group": "downstream",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "cbf335de93fb85ef3b530f0fcdccb2b1457c2f114a4ae5213db62cfdea98b9e3",
|
||||
"bodySha256": "3ae45777799c1982ff787886a2a26c896fb1511cd6e51563a9f2fd95feccdb1b"
|
||||
},
|
||||
{
|
||||
"name": "auditSummary",
|
||||
"group": "trace",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "ae3db8f6fd9e940bf1bd246e80732dce2cd2a855df5c3acfafa072886e5e9ded",
|
||||
"bodySha256": "f722254cbd78802ae4b5842e66c4f72b73db18c0701b95575635067dd8aaf11a"
|
||||
},
|
||||
{
|
||||
"name": "trace",
|
||||
"group": "trace",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "8d9526bf0683b53c79615d70f2eaa4a33e5e83c4f455c30467361e97b3f20393",
|
||||
"bodySha256": "eda2d1e0f98a5bf0c25678aaf30efedbe1ce1d90128877b86d3d655f3d2397cb"
|
||||
},
|
||||
{
|
||||
"name": "reconciliation",
|
||||
"group": "trace",
|
||||
"isPrivate": false,
|
||||
"signatureSha256": "c6d1db8ff18f46f60f3fa5d3c4a8390469bf1f190d245a8a8b07e7fcf6ae0cbb",
|
||||
"bodySha256": "f1bded76987def7292858bc303485a64403f2c28fe4c2f1a7eed359c30a4f8f6"
|
||||
},
|
||||
{
|
||||
"name": "countPendingAudits",
|
||||
"group": "dashboard",
|
||||
"isPrivate": true,
|
||||
"signatureSha256": "033be4c74aaaf745ad29c524f528e8db97706034dd907860c56b91b6a599aba3",
|
||||
"bodySha256": "ee021da1d250f65d7956bcab163a310b74cf1530cb1baf5a78052d1aeef8d654"
|
||||
},
|
||||
{
|
||||
"name": "gatewayDownstreamRecoveryStatusDelegate",
|
||||
"group": "downstream",
|
||||
"isPrivate": true,
|
||||
"signatureSha256": "f0aae13f430c40e5c0d948b153c60b8a8bac832f8183d5fde9ebd6ded520067e",
|
||||
"bodySha256": "9b451cd926f3bcfa471aebf4744967d6cdb35726fe5bce64424ae105022b765f"
|
||||
}
|
||||
],
|
||||
"helpers": {
|
||||
"messageWhere": "8d73104a7035970fceee92d95f2f76960c64aa5e1862be3441879d666d57a947",
|
||||
"recognizedCarrierValues": "d60957621e921bf9f5df8fdef616f4e2a0b16be78623c85316a65bae83025bdb",
|
||||
"carrierWhere": "1c7947c02a1a5cd3aaeda4a586421f6d7d63ae2f912cb11292831af2ffa4c379",
|
||||
"startOfShanghaiDay": "12eb964ff5ab3680837cf50bccabe5e8e7af733c248d06cb57f20c0c65ce0b4e",
|
||||
"endOfShanghaiDay": "36fcf2c3f6e7e0144305f1c175d03ab82b3ee43c3b3880e43ad14aa203d8cb4a",
|
||||
"qualityBusinessDay": "2031fe0fc330b7374596cf340afe6c25ab85499de471d41a2ffb20e5be284def",
|
||||
"shanghaiDateKey": "aa52e688283b13746a62628c7967b3ac0dbbd4418833701531e0a1004880aaf2",
|
||||
"normalizeGroupBy": "d1f3b5e846fd9e0904a0e25d5bf9c6a1bb34f3e2d4b4c30fb683c1aa666f6c44",
|
||||
"returnedTransactionWhere": "9048c20c268204b4bd5ffd14e075b915d846da11f6f13d836f87b47f8eb2e46e",
|
||||
"createdAtRange": "c1d64506752fba90d17a47531e7939ff57fcdde101b05d1ac6395d9c5bf7c251",
|
||||
"downstreamAlertPendingMinutes": "49a6e5a6ad05ccf4db538a639aa027c300c60b5748721cecc8cbc847d163fa7a",
|
||||
"downstreamAlertRecentFailedHours": "66bbfb5ae98bf65119dd05d6c3fde97856c4b279f39d1dcd926d447b9e480b72",
|
||||
"downstreamAlertWindows": "8b3ff0f8cf2a629ea488361404d30c027f0d9ed3c692b942b1d3bbda299c5cd2",
|
||||
"downstreamAlertWhere": "d0699b58ae58f4357560aeca47acaf2de6c66b5a57a70d66dbddd63fbbe253e6",
|
||||
"stalledPendingWhere": "2a2266a9f8888d0a21b0f6123aaf99ab9597419e79ff08115584b39b778473ef",
|
||||
"downstreamDeliveryScopedWhere": "edf3bd93334fb31744ef28b59b1d15171c88e5c30ae27b2e998a2796cda38e05",
|
||||
"parseDateBoundary": "62b768f59c084c4b8c4384700c98a88430cb10d8b27554c2cd730eb23e87bc23",
|
||||
"downstreamRecoveryStatusWhere": "a9d59fac3bad87291ac9c0fb7206df82b7722b5d199fe31521efb97ade44931e",
|
||||
"escapeCsvCell": "abcd0660648ee2978f2634aeda4de084298828b44d68d4cfbfa72e0a414724b7",
|
||||
"formatCsvDate": "c52b4517a846bbd1a6010e20e0a8d2413b4e6c478ba830e05af109139cd00ff0",
|
||||
"formatExportTimestamp": "1ed41fc5ffbc208bbe6752b186ac2b2111f700d7b15bf1197aaf0e8057811bac",
|
||||
"clientApplicationView": "8af7f3d67d4c38930a4a5cd59e0048881a996de07220c561b65f8b4f97b3b931",
|
||||
"clientReceiptView": "365eca8e3936433d0d71da2bc83d0e4ae27a7b15e7233dacf49eddd397b71baf",
|
||||
"clientMessageView": "3bf33efe7c5c94b64148ff44172dd18997147b458703825277b98b24b0bbc37d",
|
||||
"clientBatchTaskView": "b7d1fd9955f6b1362f8f2ff69e72315c6bda7e58c962ba1fa6667b54c9b71204",
|
||||
"clientUplinkView": "b9c0093e74b93764de8759710614acf44282b48be1ae154ae459cbaa771b1d03",
|
||||
"clientAccountView": "d97dd44290b999f97fcad7448e2129746de5080342899d448ace3335ea70ac0f",
|
||||
"clientRechargeView": "0554a521fd9f7d89aa146185fa8655aeb577f743ebed3ce8bdd9b617f7d4192c",
|
||||
"summarizeMessageGroups": "4eee30accc8c33587ed16cc9a404fde33ae321325a33e7c3dcd207c82f1e69eb",
|
||||
"groupDownstreamByType": "1d38bd9ee894dce37eaeb51986220713d3d72c2cfb04be13021d985d354298ed",
|
||||
"groupDownstreamByApplication": "540d5247bd99115b6d338ee3a4a91a005047a44eef7d492dbb23aab7fc753ab1",
|
||||
"positiveInteger": "6febd4b21ae047e3c37128677bb6d908f703bc1cbfe7029c2c54c5e9e239a303",
|
||||
"operationLogLevelWhere": "88ffdb591f2ed3dbb931e5dada32d05f9899e02d2f8e18d7711a5e6ba5b35b03",
|
||||
"normalizeOperationLog": "f1949cfa395f9d2efe7ecc7f31a058b3fc4e837f08cdaa22cbbc521765cfdda7",
|
||||
"sanitizeGatewaySubmitException": "3392287e5af7d5557ecbc957820011f81135c1f24ac8eed750c6f9c2fec82203",
|
||||
"redactGatewayCommandValue": "475f1a557191626e29311fe578277350817ac3d246c821922b2bc7ee305827e7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"version": "r0",
|
||||
"baselineCommit": "0af671b4ed4713912e703defd08791f164d4eb25",
|
||||
"purpose": "Freeze the cross-process contracts and characterization gates before production code is split.",
|
||||
"contracts": [
|
||||
{
|
||||
"kind": "redis-stream",
|
||||
"schema": "docs/contracts/gateway-queue-messages.schema.json",
|
||||
"examples": [
|
||||
"docs/contracts/examples/submit-command.json",
|
||||
"docs/contracts/examples/submit-result.json",
|
||||
"docs/contracts/examples/receipt-event.json",
|
||||
"docs/contracts/examples/uplink-event.json"
|
||||
],
|
||||
"validator": "tools/spike/validate-gateway-queue-contract.mjs"
|
||||
},
|
||||
{
|
||||
"kind": "cmpp-packet",
|
||||
"tests": [
|
||||
"gateway/internal/cmpp/gocmpp_integration_test.go",
|
||||
"gateway/internal/upstream/submit_packet_test.go",
|
||||
"gateway/internal/inbound/server_test.go"
|
||||
],
|
||||
"invariants": [
|
||||
"CMPP 2.0 and 3.0 packets remain separately encoded and decoded.",
|
||||
"SubmitResp preserves the request Sequence_Id.",
|
||||
"Deliver receipts preserve Msg_Id and require a non-zero business acknowledgement."
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "gateway-reconnect",
|
||||
"tests": [
|
||||
"gateway/internal/upstream/reconnect_integration_test.go",
|
||||
"gateway/internal/upstream/connection_loss_test.go"
|
||||
],
|
||||
"invariants": [
|
||||
"Network reconnect uses capped backoff.",
|
||||
"Authentication failures use slow retry.",
|
||||
"An explicit disconnect does not start an automatic reconnect."
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "send-and-billing",
|
||||
"tests": [
|
||||
"api/src/send-chain/send-chain.service.spec.ts",
|
||||
"api/src/billing/billing.service.spec.ts"
|
||||
],
|
||||
"invariants": [
|
||||
"Concurrent claims cause one enqueue, retry, downstream delivery, or refund.",
|
||||
"Stale events cannot downgrade a later terminal state.",
|
||||
"Freeze, charge, release, and refund operations retain their idempotency keys."
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
{
|
||||
"version": "R4",
|
||||
"source": "api/src/report-materials/report-materials.service.ts",
|
||||
"generatedAt": "2026-07-31T02:11:40.149Z",
|
||||
"publicMethods": [
|
||||
{
|
||||
"name": "buildOfficialTemplate",
|
||||
"signature": "async buildOfficialTemplate(reportType: 'signature' | 'drainage', operatorId?: string)",
|
||||
"canonicalBodySha256": "507a97f3e067489fb16a33a040612f5a5e4524227ca8f9d8361e24d1b2baf785",
|
||||
"originalLines": [
|
||||
99,
|
||||
120
|
||||
],
|
||||
"domain": "officialExport"
|
||||
},
|
||||
{
|
||||
"name": "exportPending",
|
||||
"signature": "async exportPending(query: { reportType?: 'signature' | 'drainage'; tenantId?: string; applicationId?: string }, operatorId?: string)",
|
||||
"canonicalBodySha256": "f9f1cca955a9ce267f6b9c9a6d6c0b81be994908668705da1591bc550ee07cfe",
|
||||
"originalLines": [
|
||||
122,
|
||||
139
|
||||
],
|
||||
"domain": "officialExport"
|
||||
},
|
||||
{
|
||||
"name": "listPending",
|
||||
"signature": "async listPending(query: { reportType?: 'signature' | 'drainage'; tenantId?: string; applicationId?: string } & PagedQuery)",
|
||||
"canonicalBodySha256": "ecd97e4e397b63e7578645100bae82af66a9494ddefb4c1a627d8c30208ffdd9",
|
||||
"originalLines": [
|
||||
141,
|
||||
151
|
||||
],
|
||||
"domain": "pendingQuery"
|
||||
},
|
||||
{
|
||||
"name": "listImportProfiles",
|
||||
"signature": "listImportProfiles(reportType?: 'signature' | 'drainage')",
|
||||
"canonicalBodySha256": "37b13cca9ffb528b106871cdd3c89023f6d0f9e053080e6891d4271e35e2525d",
|
||||
"originalLines": [
|
||||
198,
|
||||
204
|
||||
],
|
||||
"domain": "importParser"
|
||||
},
|
||||
{
|
||||
"name": "saveImportProfile",
|
||||
"signature": "async saveImportProfile(data: CreateImportProfileDto)",
|
||||
"canonicalBodySha256": "6712ab96ded2c18120377b7b0c49193d374a858a2916b898df8b161bbbad4795",
|
||||
"originalLines": [
|
||||
206,
|
||||
229
|
||||
],
|
||||
"domain": "importParser"
|
||||
},
|
||||
{
|
||||
"name": "analyzeImport",
|
||||
"signature": "async analyzeImport(file: { originalname: string; mimetype: string; size: number; buffer: Buffer }, options: AnalyzeImportOptions)",
|
||||
"canonicalBodySha256": "ba5429c8b3fedce0de7420f9c9773215e5a6888cbb72a2b25eec152decb14aa4",
|
||||
"originalLines": [
|
||||
231,
|
||||
297
|
||||
],
|
||||
"domain": "importParser"
|
||||
},
|
||||
{
|
||||
"name": "commitImport",
|
||||
"signature": "async commitImport(batchId: string, data: ImportCommitDto)",
|
||||
"canonicalBodySha256": "8f68974ad5f7ae0231167e1801b5a3e2dccdcc78b691075967ab5838f62ec1dc",
|
||||
"originalLines": [
|
||||
299,
|
||||
383
|
||||
],
|
||||
"domain": "importReview"
|
||||
},
|
||||
{
|
||||
"name": "listImportReviewBatches",
|
||||
"signature": "async listImportReviewBatches(query: PagedQuery & { reportType?: 'signature' | 'drainage'; status?: string } = {})",
|
||||
"canonicalBodySha256": "6373de6acab0f6f12d99b000965ad798bd8c9aaeddcceece74080b033da5364e",
|
||||
"originalLines": [
|
||||
385,
|
||||
436
|
||||
],
|
||||
"domain": "importReview"
|
||||
},
|
||||
{
|
||||
"name": "reviewImportItems",
|
||||
"signature": "async reviewImportItems(batchId: string, data: ReviewImportItemsDto)",
|
||||
"canonicalBodySha256": "5303e3a9f6d0313edc69cd5fa6d93cb1408ebe782cbbe3f9e210f3ade939f27f",
|
||||
"originalLines": [
|
||||
438,
|
||||
504
|
||||
],
|
||||
"domain": "importReview"
|
||||
},
|
||||
{
|
||||
"name": "listBatches",
|
||||
"signature": "async listBatches(query: PagedQuery = {})",
|
||||
"canonicalBodySha256": "a9b65be1a5e9fa64a9aa863c70f3d19f7fe1d175fc8c3494b22c48d9ba425279",
|
||||
"originalLines": [
|
||||
506,
|
||||
546
|
||||
],
|
||||
"domain": "batchGeneration"
|
||||
},
|
||||
{
|
||||
"name": "createBatch",
|
||||
"signature": "async createBatch(data: CreateReportBatchDto)",
|
||||
"canonicalBodySha256": "59da60790350e19299b7fc80b9dd0d1763f118fb6f82fe3a09b458a3cb02db94",
|
||||
"originalLines": [
|
||||
548,
|
||||
618
|
||||
],
|
||||
"domain": "batchGeneration"
|
||||
},
|
||||
{
|
||||
"name": "preflightBatch",
|
||||
"signature": "async preflightBatch(data: Pick<CreateReportBatchDto, 'items'>)",
|
||||
"canonicalBodySha256": "6eb007143fbba353d39a3cca80f93cc4ba9fb9f6bab5182449dc2ca462234c9e",
|
||||
"originalLines": [
|
||||
620,
|
||||
637
|
||||
],
|
||||
"domain": "batchGeneration"
|
||||
}
|
||||
],
|
||||
"internalMethods": [
|
||||
{
|
||||
"name": "findPendingItems",
|
||||
"signature": "private async findPendingItems(query: { reportType?: 'signature' | 'drainage'; tenantId?: string; applicationId?: string } & PagedQuery)",
|
||||
"canonicalBodySha256": "6a4b0b9953f5499afc60605d6f68a17893dad51b89348f25799846ba7ae57f4e",
|
||||
"originalLines": [
|
||||
153,
|
||||
196
|
||||
],
|
||||
"domain": "pendingQuery"
|
||||
},
|
||||
{
|
||||
"name": "stageSignatureRow",
|
||||
"signature": "private async stageSignatureRow(tenantId: string, applicationId: string | undefined, mappings: ImportMapping[], values: Record<string, unknown>)",
|
||||
"canonicalBodySha256": "c9431e56ee3c93b416c17830feff3eee66dc5a0940d6a28b29f21f7d897a23b3",
|
||||
"originalLines": [
|
||||
639,
|
||||
665
|
||||
],
|
||||
"domain": "importReview"
|
||||
},
|
||||
{
|
||||
"name": "stageDrainageRow",
|
||||
"signature": "private async stageDrainageRow(tenantId: string, applicationId: string | undefined, mappings: ImportMapping[], values: Record<string, unknown>)",
|
||||
"canonicalBodySha256": "2a174fcb79e93e9abc293ad9205f9aa7d2c740731a250e75e598394b7c083d7c",
|
||||
"originalLines": [
|
||||
667,
|
||||
691
|
||||
],
|
||||
"domain": "importReview"
|
||||
},
|
||||
{
|
||||
"name": "applyImportItem",
|
||||
"signature": "private async applyImportItem(\n batch: { tenantId: string; applicationId: string | null; reportType: string },\n item: { reportType: string; targetId: string | null; payload: Prisma.JsonValue },\n reviewerId: string,\n )",
|
||||
"canonicalBodySha256": "2c016f04fb0a0aa2f6658a721a0e2c298a6c93d0d9111caf8f9adbdda5233d41",
|
||||
"originalLines": [
|
||||
693,
|
||||
756
|
||||
],
|
||||
"domain": "importReview"
|
||||
},
|
||||
{
|
||||
"name": "prepareBatchItem",
|
||||
"signature": "private async prepareBatchItem(batchId: string, selected: CreateReportBatchDto['items'][number], inspection: ReportBatchInspection)",
|
||||
"canonicalBodySha256": "f61ad17413f40c65437264b8ddf412de9184ebfcbd6fbc23cab5c2a7617e9674",
|
||||
"originalLines": [
|
||||
758,
|
||||
777
|
||||
],
|
||||
"domain": "batchGeneration"
|
||||
},
|
||||
{
|
||||
"name": "inspectBatchItem",
|
||||
"signature": "private async inspectBatchItem(selected: CreateReportBatchDto['items'][number]): Promise<ReportBatchInspection>",
|
||||
"canonicalBodySha256": "e04d7e20b23ac726eff80d6847290676b390b016013315523f05d58bf5fbece9",
|
||||
"originalLines": [
|
||||
779,
|
||||
858
|
||||
],
|
||||
"domain": "batchGeneration"
|
||||
},
|
||||
{
|
||||
"name": "claimBatchOperation",
|
||||
"signature": "private async claimBatchOperation(idempotencyKey: string, fingerprint: string, userId?: string)",
|
||||
"canonicalBodySha256": "c14878a5728ae576e703f7429bc83e947f922e85aeae349e62bb52ae3cf230d4",
|
||||
"originalLines": [
|
||||
860,
|
||||
873
|
||||
],
|
||||
"domain": "batchOperation"
|
||||
},
|
||||
{
|
||||
"name": "completeBatchOperation",
|
||||
"signature": "private async completeBatchOperation(operationId: string, batchId: string, result: Record<string, unknown>)",
|
||||
"canonicalBodySha256": "f4500197f33a4d023fbd735b9f38fbcd18fdd8fdca4419174b04f903531abdfb",
|
||||
"originalLines": [
|
||||
875,
|
||||
877
|
||||
],
|
||||
"domain": "batchOperation"
|
||||
},
|
||||
{
|
||||
"name": "failBatchOperation",
|
||||
"signature": "private async failBatchOperation(operationId: string, message: string, batchId?: string)",
|
||||
"canonicalBodySha256": "eb33a3102646844242592cb51dde16a455ca0055ee61e9c97f43ce07e51c12f8",
|
||||
"originalLines": [
|
||||
879,
|
||||
882
|
||||
],
|
||||
"domain": "batchOperation"
|
||||
},
|
||||
{
|
||||
"name": "exportChannelBatch",
|
||||
"signature": "private async exportChannelBatch(batchId: string, channelId: string, items: Array<Awaited<ReturnType<ReportMaterialsService['prepareBatchItem']>>>)",
|
||||
"canonicalBodySha256": "ea0df6daed595dfd4bea01ab6e4f51f3dd0bb6883e6e18c1c38e5997c0a9007c",
|
||||
"originalLines": [
|
||||
884,
|
||||
943
|
||||
],
|
||||
"domain": "channelExport"
|
||||
},
|
||||
{
|
||||
"name": "recordTask",
|
||||
"signature": "private recordTask(taskId: string, channelId: string, statusBefore: string | undefined, statusAfter: string, reason?: string)",
|
||||
"canonicalBodySha256": "9d1ce8db45c7623800d3117e2d246823dd7eb13e0970a5fa14f0392e8e4489eb",
|
||||
"originalLines": [
|
||||
945,
|
||||
947
|
||||
],
|
||||
"domain": "channelExport"
|
||||
}
|
||||
],
|
||||
"contracts": [
|
||||
{
|
||||
"name": "ImportMapping",
|
||||
"sha256": "a0d06f96f2f99f135d8d86eaeb3f3a7525fa24224d5664e80567da75cdecee06"
|
||||
},
|
||||
{
|
||||
"name": "CreateImportProfileDto",
|
||||
"sha256": "6ffebbc39754d4b9df71a47d09c55f139ea33f9c4c0e26d8fa9c9756f7d642e6"
|
||||
},
|
||||
{
|
||||
"name": "ImportCommitDto",
|
||||
"sha256": "7c4c7b25184101b781037d97e93c5b4c1f836259153cc7cb26ded7f9bcf504c1"
|
||||
},
|
||||
{
|
||||
"name": "ReviewImportItemsDto",
|
||||
"sha256": "73be0348645a4316428eec4bd39d0ef02f84cef43c24530200d6c896cfae40e7"
|
||||
},
|
||||
{
|
||||
"name": "PagedQuery",
|
||||
"sha256": "78ddbb3a41b07a37729b80c84e969cf3344d44c19bdebff93b593bacf2b51293"
|
||||
},
|
||||
{
|
||||
"name": "CreateReportBatchDto",
|
||||
"sha256": "530b306e1f237c522e4a202ed1d43bca6e527eb6dd44afa113988de54fdad35f"
|
||||
},
|
||||
{
|
||||
"name": "ReportBatchTarget",
|
||||
"sha256": "a91a765ad37d69e0f797c2b9c4b692789765b539a6b13d212f1a93cd5b1b4e65"
|
||||
},
|
||||
{
|
||||
"name": "ReportBatchInspection",
|
||||
"sha256": "e00a2a0750dad4c413466426a2710a2ea59c2c8b369e61726db3f175b700cc00"
|
||||
},
|
||||
{
|
||||
"name": "AnalyzeImportOptions",
|
||||
"sha256": "74e5e84a09befe64caada9f8574a52dde7e30770a7ffe4b99e417c60c6eda40b"
|
||||
},
|
||||
{
|
||||
"name": "EmbeddedImage",
|
||||
"sha256": "9db22983b69311e82b0899663cd1534dd72510f14259ba37693bd63bc9bad59b"
|
||||
}
|
||||
],
|
||||
"helpers": [
|
||||
{
|
||||
"name": "profileData",
|
||||
"sha256": "e61848d9a038403295c40d26588ca44c32d4372529726ad9f2e22232474efc69"
|
||||
},
|
||||
{
|
||||
"name": "validateProfile",
|
||||
"sha256": "6fe77bdd3830c93b40d9f3d3282f0fdd2c5afa8f025504ba57f9f8113a725947"
|
||||
},
|
||||
{
|
||||
"name": "loadWorkbook",
|
||||
"sha256": "46ce8da23dce75f31ab29d00c0dae8e063d14cb72ccfbec95333bb1064bbcf39"
|
||||
},
|
||||
{
|
||||
"name": "assertSafeWorkbook",
|
||||
"sha256": "5ed20a1e12793355949b5cf951b4113c9c61517bf5a97491cc22671ee6ccaa56"
|
||||
},
|
||||
{
|
||||
"name": "safeSpreadsheetText",
|
||||
"sha256": "5a7db626de509e78628fc87ebf20e43d227e6ce3fefdf48bd82dd040ffd35683"
|
||||
},
|
||||
{
|
||||
"name": "readEmbeddedImages",
|
||||
"sha256": "9fbd0df019528353aa7fc5220a279b23711d36fa61f78e0880d8bb2cc6228f4d"
|
||||
},
|
||||
{
|
||||
"name": "suggestMappings",
|
||||
"sha256": "79abe1b569ffb867fd39ace7e731f1885dd113ac470d8b8dea315775d0eb3c28"
|
||||
},
|
||||
{
|
||||
"name": "remapProfileColumns",
|
||||
"sha256": "4b58e11d2e3d97a1b352109a9be7c26aa25bdecdbb5e542a0fb241e46c7f657a"
|
||||
},
|
||||
{
|
||||
"name": "signatureCoreMapping",
|
||||
"sha256": "5d4b0bdc68886cb022eecbf4eb4721613df74210d3165fd737b9badea00e5729"
|
||||
},
|
||||
{
|
||||
"name": "drainageCoreMapping",
|
||||
"sha256": "256323027325923786e84c308eeebcd0dde0e0b5d27a563d10e794d318b7bddd"
|
||||
},
|
||||
{
|
||||
"name": "normalizeHeader",
|
||||
"sha256": "b30ab7e6903b8e8411e3195c23581379badb6241bd518e327eb10ad0358e0c5c"
|
||||
},
|
||||
{
|
||||
"name": "normalizeFieldCode",
|
||||
"sha256": "49387c9ca040ea2cbc5a4732652c4389f32be8169536f9e132225579dff839fa"
|
||||
},
|
||||
{
|
||||
"name": "clamp",
|
||||
"sha256": "0aaed2dc249288c7f197e033b858c35aa10a0a2642203d5d92c94bd5db323926"
|
||||
},
|
||||
{
|
||||
"name": "normalizePage",
|
||||
"sha256": "f04be3697001d814b86457cdd93eb6a83cff1b712327a4e74960c2436b784b19"
|
||||
},
|
||||
{
|
||||
"name": "normalizePageSize",
|
||||
"sha256": "af1c28386f9802cb9c7cc3dddc712c1559d92d2c777b2bbce65d12cb1c5ecc38"
|
||||
},
|
||||
{
|
||||
"name": "dateRange",
|
||||
"sha256": "a0029a9c2eac718e2c7d63b30a7b3b65c504f859838ac9de7499ec1103ae1e89"
|
||||
},
|
||||
{
|
||||
"name": "cellText",
|
||||
"sha256": "a6f5fd540e5cbcbc8fc1ef1dfb4b8203e16212bb2d7c4a8b3aa0068f296f8981"
|
||||
},
|
||||
{
|
||||
"name": "transformValue",
|
||||
"sha256": "584b33bf430cd5c47e6e9a36b88a75519335125e80b0b63e3139e5f156333118"
|
||||
},
|
||||
{
|
||||
"name": "mappedCoreValue",
|
||||
"sha256": "a34b22e2cfbe93445eeedcfbf4f0b60d9ee0f5ed872c069e6db260a58dda723f"
|
||||
},
|
||||
{
|
||||
"name": "dynamicValues",
|
||||
"sha256": "a955844529a42a1f0bd73645bb4407980c7ae570bcd7d52a738fcae46f444d9b"
|
||||
},
|
||||
{
|
||||
"name": "jsonRecord",
|
||||
"sha256": "2f7c1984863c82abc61e7f753bd5bf1d752802d4ab552dd7ee03d6ddd7844ce1"
|
||||
},
|
||||
{
|
||||
"name": "hasValue",
|
||||
"sha256": "ae0550bd772c41447e7f975cb12a4812bc7ccde1ade718cd4fa1b3ae6af34583"
|
||||
},
|
||||
{
|
||||
"name": "isFileRef",
|
||||
"sha256": "37413460e45e152f80c3b49e82addfc332dacf0d3585cffe8868e8b93f2da87b"
|
||||
},
|
||||
{
|
||||
"name": "resolveExportValue",
|
||||
"sha256": "c6aae47afc4ece039eb97053ed491136a38563506deb0246a3d0c37784b7bccc"
|
||||
},
|
||||
{
|
||||
"name": "applyExportTransform",
|
||||
"sha256": "197b0126b8a8cf69d0087e45ec221ad608c7e5e2e94d8a2735adebfdcd801fad"
|
||||
},
|
||||
{
|
||||
"name": "styleHeader",
|
||||
"sha256": "8c419d0cd3fcbd2f84d4b079ae025557560fa479d59b5d3aca4970c65319d496"
|
||||
},
|
||||
{
|
||||
"name": "normalizeImageExtension",
|
||||
"sha256": "8c2f57eedc5c5294001b6a842581cf4b3cb9a61dbe392c700e0672416692fddc"
|
||||
},
|
||||
{
|
||||
"name": "imageContentType",
|
||||
"sha256": "589cd67492e900039830c1c6694cc910b726bf78e3b275d53664965842b122c7"
|
||||
},
|
||||
{
|
||||
"name": "safeFileName",
|
||||
"sha256": "948e0371435a10f79bc24a9c70ed0911bff050c209cba794e42b713fecd50a34"
|
||||
},
|
||||
{
|
||||
"name": "normalizeBatchIdempotencyKey",
|
||||
"sha256": "e2f921d15dc1300b15c23089fd63c6c1ecafdfb11fbce93cdb3f7dd7b3a7b760"
|
||||
},
|
||||
{
|
||||
"name": "jsonStringArray",
|
||||
"sha256": "469f80e2ba2119bfa26c19e371224b239c2df8ab6bdbe75f5906ab2047744622"
|
||||
},
|
||||
{
|
||||
"name": "jsonSafe",
|
||||
"sha256": "3f72a3704848a68c9488c3b692c4f6144e64a7f6cb51ca3ad2ba5d7d92cd3e4f"
|
||||
}
|
||||
],
|
||||
"domains": {
|
||||
"officialExport": {
|
||||
"className": "ReportOfficialExportService",
|
||||
"file": "api/src/report-materials/official-export.service.ts",
|
||||
"methods": [
|
||||
"buildOfficialTemplate",
|
||||
"exportPending"
|
||||
]
|
||||
},
|
||||
"importParser": {
|
||||
"className": "ReportImportParserService",
|
||||
"file": "api/src/report-materials/import-parser.service.ts",
|
||||
"methods": [
|
||||
"listImportProfiles",
|
||||
"saveImportProfile",
|
||||
"analyzeImport"
|
||||
]
|
||||
},
|
||||
"importReview": {
|
||||
"className": "ReportImportReviewService",
|
||||
"file": "api/src/report-materials/import-review.service.ts",
|
||||
"methods": [
|
||||
"commitImport",
|
||||
"listImportReviewBatches",
|
||||
"reviewImportItems",
|
||||
"stageSignatureRow",
|
||||
"stageDrainageRow",
|
||||
"applyImportItem"
|
||||
]
|
||||
},
|
||||
"pendingQuery": {
|
||||
"className": "ReportPendingQueryService",
|
||||
"file": "api/src/report-materials/pending-query.service.ts",
|
||||
"methods": [
|
||||
"listPending",
|
||||
"findPendingItems"
|
||||
]
|
||||
},
|
||||
"batchGeneration": {
|
||||
"className": "ReportBatchGenerationService",
|
||||
"file": "api/src/report-materials/batch-generation.service.ts",
|
||||
"methods": [
|
||||
"listBatches",
|
||||
"createBatch",
|
||||
"preflightBatch",
|
||||
"prepareBatchItem",
|
||||
"inspectBatchItem"
|
||||
]
|
||||
},
|
||||
"channelExport": {
|
||||
"className": "ReportChannelExportService",
|
||||
"file": "api/src/report-materials/channel-export.service.ts",
|
||||
"methods": [
|
||||
"exportChannelBatch",
|
||||
"recordTask"
|
||||
]
|
||||
},
|
||||
"batchOperation": {
|
||||
"className": "ReportBatchOperationService",
|
||||
"file": "api/src/report-materials/batch-operation.service.ts",
|
||||
"methods": [
|
||||
"claimBatchOperation",
|
||||
"completeBatchOperation",
|
||||
"failBatchOperation"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
{
|
||||
"version": "R10",
|
||||
"generatedAt": "2026-07-31",
|
||||
"source": "api/src/send-chain/send-chain.service.ts at R9 local baseline",
|
||||
"facade": "api/src/send-chain/send-completion.service.ts",
|
||||
"methods": [
|
||||
{
|
||||
"name": "handleSubmitSegmentResult",
|
||||
"file": "send-gateway-result.service.ts",
|
||||
"bodySha256": "1a508cba1eb3547bfeabdecdbc0e62bf4971807212439b0adf1f2b52a2699878"
|
||||
},
|
||||
{
|
||||
"name": "resolveSubmitRecordForGatewaySegmentResult",
|
||||
"file": "send-gateway-result.service.ts",
|
||||
"bodySha256": "a4e233c6b4c13858355573e3d61e77f07ef141e20d3a98c0108d6ff27157f3e2"
|
||||
},
|
||||
{
|
||||
"name": "handleSubmitResult",
|
||||
"file": "send-gateway-result.service.ts",
|
||||
"bodySha256": "6184170748eb3934496b060ea3b6704f1d1a831e7ffde7e7f8b73a7c223a869c"
|
||||
},
|
||||
{
|
||||
"name": "resolveSubmitRecordForGatewayResult",
|
||||
"file": "send-gateway-result.service.ts",
|
||||
"bodySha256": "a904de3a2fe6c9ad1a6aa50982a9dfb1633b6a27466f421c978afe72ba974b8b"
|
||||
},
|
||||
{
|
||||
"name": "smsMessageSegmentAuditDelegate",
|
||||
"file": "send-gateway-result.service.ts",
|
||||
"bodySha256": "c907ad9b162874735ecdf0d024f18a4ff15cf8f1be3a95c628b3bfe793230b65"
|
||||
},
|
||||
{
|
||||
"name": "recordSubmitSegments",
|
||||
"file": "send-gateway-result.service.ts",
|
||||
"bodySha256": "897c27559d20613b5fd87a22f2748658f31c4bf9435935a523e21d5d1100206f"
|
||||
},
|
||||
{
|
||||
"name": "findMessageByGatewayEvent",
|
||||
"file": "send-gateway-result.service.ts",
|
||||
"bodySha256": "8212cecfa19b3be90ce565c9f4446183bf06073c633683e0f94ea4e104b23760"
|
||||
},
|
||||
{
|
||||
"name": "requireMessageByGatewayEvent",
|
||||
"file": "send-gateway-result.service.ts",
|
||||
"bodySha256": "76757dad543ee12c9622a25fbfdace943e9be537d5e68f1592768c4504eb5617"
|
||||
},
|
||||
{
|
||||
"name": "intakeReceipt",
|
||||
"file": "send-receipt.service.ts",
|
||||
"bodySha256": "42cad611473ebb973beca6b4f5c05192dc1e2e35ee9f85e2d7cb86b35129a32b"
|
||||
},
|
||||
{
|
||||
"name": "processPendingUpstreamReceiptInbox",
|
||||
"file": "send-receipt.service.ts",
|
||||
"bodySha256": "3614b8aabb5640a94b4b2f8a65c9dff3425a7578e753410413eead52c33f747f"
|
||||
},
|
||||
{
|
||||
"name": "processUpstreamReceiptInboxRecord",
|
||||
"file": "send-receipt.service.ts",
|
||||
"bodySha256": "5882e14d9474e6c940a9a28d6a9b78f4e9e46184caa616971674dfb9efd1b70d"
|
||||
},
|
||||
{
|
||||
"name": "runUpstreamReceiptInboxScan",
|
||||
"file": "send-receipt.service.ts",
|
||||
"bodySha256": "a1bda2f26563c0cfe5cb5564aa5ef34f513e2c99bb302a0a0ad7917b4887c7ed"
|
||||
},
|
||||
{
|
||||
"name": "handleReceipt",
|
||||
"file": "send-receipt.service.ts",
|
||||
"bodySha256": "e3b63dc74af50db96d899c805124c7974067ca729e44a1ec8a558569e81fbd6c"
|
||||
},
|
||||
{
|
||||
"name": "recordReceiptSegment",
|
||||
"file": "send-receipt.service.ts",
|
||||
"bodySha256": "acb776e7ee67b07c9e635411ef2a4286db60366fd6b20083be870c9314dab8f0"
|
||||
},
|
||||
{
|
||||
"name": "aggregateReceiptSegments",
|
||||
"file": "send-receipt.service.ts",
|
||||
"bodySha256": "7dc565bd0847462bd0e23b5f072a4f82fd6daa88f164485138ce653d8cf936b8"
|
||||
},
|
||||
{
|
||||
"name": "resolveReceiptMessage",
|
||||
"file": "send-receipt.service.ts",
|
||||
"bodySha256": "caadd32d37d3b72e2b7e526f86cdb422c054c2ed9c910a4b4d1d1f3eb1c6b522"
|
||||
},
|
||||
{
|
||||
"name": "recordGatewaySubmitDeadLetter",
|
||||
"file": "send-retry.service.ts",
|
||||
"bodySha256": "85180d382ba99b9e714d406ab14f30de91445fa2a7a695acebf9ee359716fdff"
|
||||
},
|
||||
{
|
||||
"name": "requeueGatewaySubmitDeadLetter",
|
||||
"file": "send-retry.service.ts",
|
||||
"bodySha256": "e1092c28b657e522a4bf77d833c694460c871bb82424f2604b01d204a00dcdc0"
|
||||
},
|
||||
{
|
||||
"name": "recoverStaleGatewaySubmitRequeues",
|
||||
"file": "send-retry.service.ts",
|
||||
"bodySha256": "cc36a00787acfc00a1e1797ce83550d4de0441e1b83025d16624ba966577a6ba"
|
||||
},
|
||||
{
|
||||
"name": "retryMessageIfAllowed",
|
||||
"file": "send-retry.service.ts",
|
||||
"bodySha256": "6892322b81983c99ad9063e334b435ab369eb5a6fd0268e09ef3772cd56bc484"
|
||||
},
|
||||
{
|
||||
"name": "chargeAcceptedMessage",
|
||||
"file": "send-accounting.service.ts",
|
||||
"bodySha256": "4ca42fd6ea6e41509a1ff6d62164a1dcfa81f62256386cdb49294451162312dc"
|
||||
},
|
||||
{
|
||||
"name": "releaseMessageReservation",
|
||||
"file": "send-accounting.service.ts",
|
||||
"bodySha256": "0838524d280b3c9b0c0146ea53b8b35e77295d8f626325a80b62e8f2a9faa607"
|
||||
},
|
||||
{
|
||||
"name": "refundMessage",
|
||||
"file": "send-accounting.service.ts",
|
||||
"bodySha256": "4cca77a11bbdc419107f4e5c12a7d73190901c323dde0492f7489cac337759cb"
|
||||
},
|
||||
{
|
||||
"name": "listPendingDownstreamDeliveries",
|
||||
"file": "send-downstream-state.service.ts",
|
||||
"bodySha256": "1c5e0bc271fcbfdf8a0c55e2870e9ddb41ffbbf24d3fe0c2285b4806e4854012"
|
||||
},
|
||||
{
|
||||
"name": "markDownstreamDeliveryDelivered",
|
||||
"file": "send-downstream-state.service.ts",
|
||||
"bodySha256": "5fe521d4d5e50ec0a6b4ddda45f6dc67633da792161975837e6bb32c4025daaf"
|
||||
},
|
||||
{
|
||||
"name": "markDownstreamDeliverySent",
|
||||
"file": "send-downstream-state.service.ts",
|
||||
"bodySha256": "08bd1cbc9c5662c158b598acb80374f36b9b7f623907345ff6821fd65b843167"
|
||||
},
|
||||
{
|
||||
"name": "acknowledgeDownstreamDelivery",
|
||||
"file": "send-downstream-state.service.ts",
|
||||
"bodySha256": "5c53b04f37e891e77159256663e72071229ccb867b1d53ad1e0c9f6ec9595af6"
|
||||
},
|
||||
{
|
||||
"name": "markDownstreamDeliveryFailed",
|
||||
"file": "send-downstream-state.service.ts",
|
||||
"bodySha256": "1b072fef54577d5de077a7086386c218a20b6d79c2171319e2e4c7fee99eddc5"
|
||||
},
|
||||
{
|
||||
"name": "recordGatewayDownstreamRecoveryStatus",
|
||||
"file": "send-downstream-state.service.ts",
|
||||
"bodySha256": "0375019b79ceba79a39067c9d27b249c1a1554813ae8c272d9f7711d986d463d"
|
||||
},
|
||||
{
|
||||
"name": "requeueDownstreamDelivery",
|
||||
"file": "send-downstream-state.service.ts",
|
||||
"bodySha256": "1e680512bd7a02735a8fd3713ec22d83cbc70505d494fd06a57cd628d8df6e99"
|
||||
},
|
||||
{
|
||||
"name": "recoverStaleDownstreamManualRequeues",
|
||||
"file": "send-downstream-state.service.ts",
|
||||
"bodySha256": "0c6142754daff8df2e0bd7f1d323fd1ca0c9b2d83bc195cb664e21b119b8a972"
|
||||
},
|
||||
{
|
||||
"name": "batchRequeueDownstreamDeliveries",
|
||||
"file": "send-downstream-state.service.ts",
|
||||
"bodySha256": "00af2d3af7cde4791190d0eebb50d97fca6e9a1c1b595fefe2d13bdc18dffebd"
|
||||
},
|
||||
{
|
||||
"name": "handleUplink",
|
||||
"file": "send-downstream-delivery.service.ts",
|
||||
"bodySha256": "a0623ca0407ecab8b1b558e1784fe299a4a01008209bc1ff4bc60afed2c3e280"
|
||||
},
|
||||
{
|
||||
"name": "claimUplinkMatchCandidate",
|
||||
"file": "send-downstream-delivery.service.ts",
|
||||
"bodySha256": "4330127ec62d2653ba0411a824378dec30ea657d0b688927d867d750932b67b5"
|
||||
},
|
||||
{
|
||||
"name": "queueAndTryDownstreamDelivery",
|
||||
"file": "send-downstream-delivery.service.ts",
|
||||
"bodySha256": "0b5f6f5e9ffebad5ddda003962efdabb0daeb2ec5942a246bdf9d922f274d4ac"
|
||||
},
|
||||
{
|
||||
"name": "resolveUplinkMatch",
|
||||
"file": "send-downstream-delivery.service.ts",
|
||||
"bodySha256": "2f017f39bb6332b43f78da2cbc8195bcec9e926d585f95f05b1da4b5df51b9cb"
|
||||
},
|
||||
{
|
||||
"name": "recordCmppFailureReceipt",
|
||||
"file": "send-downstream-delivery.service.ts",
|
||||
"bodySha256": "d48ecabfcce62787668486a8f14b3ea7afc935d5d5d910651fc1ddf8d8ac3952"
|
||||
},
|
||||
{
|
||||
"name": "postGatewayControl",
|
||||
"file": "send-downstream-delivery.service.ts",
|
||||
"bodySha256": "0f991ecb7f58268b5d44d2b32ddd940f0ce16420d8a7c94534e2eaaf36e38d5f"
|
||||
},
|
||||
{
|
||||
"name": "markUnknownTimeout",
|
||||
"file": "send-timeout.service.ts",
|
||||
"bodySha256": "6f254ffbf05067483801cdd2c131f32cb9aaaf755d19f3aff065fe99b8d7753b"
|
||||
},
|
||||
{
|
||||
"name": "markExpiredDownstreamDeliveries",
|
||||
"file": "send-timeout.service.ts",
|
||||
"bodySha256": "6d06c11e68394df57b0cb981ba566e5ce34924c85b14b4add93e8d3856a0d02d"
|
||||
},
|
||||
{
|
||||
"name": "runReceiptTimeoutScan",
|
||||
"file": "send-timeout.service.ts",
|
||||
"bodySha256": "5e2942916813d62218dd63f51d05554ce9e455d1b3283704c3fd54dc124a4e5f"
|
||||
}
|
||||
],
|
||||
"domains": [
|
||||
{
|
||||
"file": "send-gateway-result.service.ts",
|
||||
"className": "SendGatewayResultService",
|
||||
"methodCount": 8
|
||||
},
|
||||
{
|
||||
"file": "send-receipt.service.ts",
|
||||
"className": "SendReceiptService",
|
||||
"methodCount": 8
|
||||
},
|
||||
{
|
||||
"file": "send-retry.service.ts",
|
||||
"className": "SendRetryService",
|
||||
"methodCount": 4
|
||||
},
|
||||
{
|
||||
"file": "send-accounting.service.ts",
|
||||
"className": "SendAccountingService",
|
||||
"methodCount": 3
|
||||
},
|
||||
{
|
||||
"file": "send-downstream-state.service.ts",
|
||||
"className": "SendDownstreamStateService",
|
||||
"methodCount": 9
|
||||
},
|
||||
{
|
||||
"file": "send-downstream-delivery.service.ts",
|
||||
"className": "SendDownstreamDeliveryService",
|
||||
"methodCount": 6
|
||||
},
|
||||
{
|
||||
"file": "send-timeout.service.ts",
|
||||
"className": "SendTimeoutService",
|
||||
"methodCount": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
{
|
||||
"version": "R8",
|
||||
"source": "api/src/send-chain/send-chain.service.ts@workspace-before-R8",
|
||||
"contracts": [
|
||||
{
|
||||
"name": "CreateBatchTaskDto",
|
||||
"kind": "interface",
|
||||
"sha256": "70414ba63f4da4a501e60c2ba69d785113692d14c775289e6740065e5124fdf8"
|
||||
},
|
||||
{
|
||||
"name": "CreateHttpBatchTaskDto",
|
||||
"kind": "type",
|
||||
"sha256": "a83aa71a11c756d84afa7b5ccb1af46d9008f59a77fd5329236beef752309abe"
|
||||
},
|
||||
{
|
||||
"name": "GatewayInboundAuthDto",
|
||||
"kind": "interface",
|
||||
"sha256": "1e55f6a2a393cd72c7aca2b4a1e18e293ae20f513412f627197515448c8da166"
|
||||
},
|
||||
{
|
||||
"name": "GatewayInboundSubmitDto",
|
||||
"kind": "interface",
|
||||
"sha256": "28f99a1e29385b64c3a6b4eab2e5befa3fc6cd8a6995090e0865f5af6871246a"
|
||||
},
|
||||
{
|
||||
"name": "GatewayInboundSingleSubmitResult",
|
||||
"kind": "interface",
|
||||
"sha256": "6e71836ba8c38cc0634e5540a70d8a2cfb98c1b11f0e5ef8749f57a81fd3443b"
|
||||
},
|
||||
{
|
||||
"name": "GatewaySubmitResultDto",
|
||||
"kind": "interface",
|
||||
"sha256": "a403995091710ac369b727fbcd5191515da7e10df5aad631dedb6dbcf751fe49"
|
||||
},
|
||||
{
|
||||
"name": "GatewaySubmitSegmentResultDto",
|
||||
"kind": "interface",
|
||||
"sha256": "11ecd1395daac263757bc364a5551a7c8b41307622f446d191b25628fa287410"
|
||||
},
|
||||
{
|
||||
"name": "GatewayReceiptEventDto",
|
||||
"kind": "interface",
|
||||
"sha256": "d2f68b459392e50e481dadaed9cd222087175b266613d265dd1b41a235cfd539"
|
||||
},
|
||||
{
|
||||
"name": "GatewayUplinkEventDto",
|
||||
"kind": "interface",
|
||||
"sha256": "4b81ac70af7584956c706877bbea932d62851c79fd2e8e333e4a8b1023eedf98"
|
||||
},
|
||||
{
|
||||
"name": "UplinkMatchCandidateInput",
|
||||
"kind": "type",
|
||||
"sha256": "a82efe64ba28740ad691ed645ed7e8ea205a555bf68ac3a18ffec9e36251b929"
|
||||
},
|
||||
{
|
||||
"name": "GatewayPendingDeliveryQueryDto",
|
||||
"kind": "interface",
|
||||
"sha256": "8208ddf3a047c684e513f1828d5be0af617b28b84f1bb6b75c3e8822f58341bd"
|
||||
},
|
||||
{
|
||||
"name": "GatewayDownstreamSentDto",
|
||||
"kind": "interface",
|
||||
"sha256": "a1d45c4dd241159afc02e87c3441c4e31cb06e6853ee13a5f22a75f9a5156464"
|
||||
},
|
||||
{
|
||||
"name": "GatewayDownstreamAcknowledgedDto",
|
||||
"kind": "interface",
|
||||
"sha256": "d91e0bebf4abcd7f5506b75b2106d7899fa4d6c120e28c5db5f7c8e4d472bf87"
|
||||
},
|
||||
{
|
||||
"name": "GatewayDownstreamFailureType",
|
||||
"kind": "type",
|
||||
"sha256": "f0d4da34c9194b679816527b87f7077c78f85ffde37aabb81f76f91ddcf5ef4a"
|
||||
},
|
||||
{
|
||||
"name": "GatewayControlDeliveryResult",
|
||||
"kind": "type",
|
||||
"sha256": "916a1700848b5dd369196c105bdc99928e186608baf140ae0860d34e0725ea34"
|
||||
},
|
||||
{
|
||||
"name": "GatewaySubmitDeadLetterDto",
|
||||
"kind": "interface",
|
||||
"sha256": "ee032743d02f7f76c073695b5579ccd9884b5d94e016a17e548227a6f36ed4e2"
|
||||
},
|
||||
{
|
||||
"name": "RequeueGatewaySubmitExceptionDto",
|
||||
"kind": "interface",
|
||||
"sha256": "0b0973656d0cecb25ac9c8c6ed863fbebfbb26178a6056c956f72e29f4d9dc94"
|
||||
},
|
||||
{
|
||||
"name": "GatewayDownstreamRecoveryStatusDto",
|
||||
"kind": "interface",
|
||||
"sha256": "0c3b31cc6cce50dec8454e8427ba1f369d2f81ad7e583e564d62bab1db46260f"
|
||||
},
|
||||
{
|
||||
"name": "TimeoutUnknownDto",
|
||||
"kind": "interface",
|
||||
"sha256": "231ca785c112103fa9432a19f0cb79745da52126b76055498678a6ebdc053a83"
|
||||
},
|
||||
{
|
||||
"name": "ImportPreviewDto",
|
||||
"kind": "interface",
|
||||
"sha256": "0123d0e98b1355a64c317254e9e0d8776ad7a4043da8e3ada245ea8a5ea2f352"
|
||||
},
|
||||
{
|
||||
"name": "ConfirmImportDto",
|
||||
"kind": "interface",
|
||||
"sha256": "ce98fe82a9d5052d8d8654b60985225240985c5473194f71987af92e311c0b89"
|
||||
},
|
||||
{
|
||||
"name": "SendJob",
|
||||
"kind": "interface",
|
||||
"sha256": "57a692f8dae8e37ba3758f7afd75056ea629ed58c20139ebd60144cb99fd4177"
|
||||
},
|
||||
{
|
||||
"name": "QueuePriority",
|
||||
"kind": "type",
|
||||
"sha256": "ca80dc4d2708054b7388426c1ca71a3e84db3ed08999ed89f9f791878fa03f70"
|
||||
},
|
||||
{
|
||||
"name": "RoutedChannel",
|
||||
"kind": "type",
|
||||
"sha256": "d82fe045e8ae72380f575ecbd47ab9849d6eb2b85e74a27e6f116a019da7f2a4"
|
||||
}
|
||||
],
|
||||
"helpers": [
|
||||
{
|
||||
"name": "SEND_QUEUE",
|
||||
"kind": "const",
|
||||
"sha256": "11a3c2aaf41c2ffe7ae251b5b5da00591624e21d345324563844e59f517b67d3"
|
||||
},
|
||||
{
|
||||
"name": "GATEWAY_SUBMIT_QUEUE",
|
||||
"kind": "const",
|
||||
"sha256": "c69e4af1b3939a576aa63833947b10b86b87a646b373684d9726dfbaf4c95d8c"
|
||||
},
|
||||
{
|
||||
"name": "GATEWAY_SUBMIT_STREAM",
|
||||
"kind": "const",
|
||||
"sha256": "70d662152ad15ff017e1f61aca86525554c5b6a83f97686529dca1a0eaf28849"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_DOWNSTREAM_RETRY_DELAY_MS",
|
||||
"kind": "const",
|
||||
"sha256": "5c216981884a2422ee8765d00745e99414d52976df4b68e90e5f2bc6bf22d090"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_DOWNSTREAM_RETRY_MAX_DELAY_MS",
|
||||
"kind": "const",
|
||||
"sha256": "02a1e63eb1887f5f924a5ed2f87f09edaf7eed54e419a9ce4c5afe1f52a061fa"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_DOWNSTREAM_MAX_RETRIES",
|
||||
"kind": "const",
|
||||
"sha256": "fa2107f33e9c2173a8cb91140c59a28193ca88d8c8bb9b14788af5427e406c38"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_DOWNSTREAM_PENDING_TIMEOUT_HOURS",
|
||||
"kind": "const",
|
||||
"sha256": "f7038a98205b1fe6f30df3e3af01a74336408cce7acc92f9254b737d608ca189"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_RECEIPT_TIMEOUT_HOURS",
|
||||
"kind": "const",
|
||||
"sha256": "3ffc70f45997ee0a68bb4ff1a041bf4408c0c71a3a3dc8517a6c152d20e4c931"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_RECEIPT_TIMEOUT_SCAN_INTERVAL_MS",
|
||||
"kind": "const",
|
||||
"sha256": "833d0c26f3f6e57b7f451a4bd0472c33ba99fdb8dc2479bea7b50759efcbf948"
|
||||
},
|
||||
{
|
||||
"name": "RECEIPT_TIMEOUT_INITIAL_DELAY_MS",
|
||||
"kind": "const",
|
||||
"sha256": "d8ffa15508dad01de044034ddefbd379ac8a654a5f2e90dcfa05c0bb45990359"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_SCHEDULED_DISPATCH_SCAN_INTERVAL_MS",
|
||||
"kind": "const",
|
||||
"sha256": "86cc465a9fea068fa0f945d645a5129a17b021baa9daa05dc5ee666b669a6aca"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_SCHEDULED_DISPATCH_STALE_MS",
|
||||
"kind": "const",
|
||||
"sha256": "3337c4f2b53a6ca4a3b65326482f08c4d04be84324acc109d39cca65d2cb89ea"
|
||||
},
|
||||
{
|
||||
"name": "SCHEDULED_DISPATCH_INITIAL_DELAY_MS",
|
||||
"kind": "const",
|
||||
"sha256": "61ee979c2d1d57cf977180c198cdb3e4a65683a6149619153db69ca72fa12d8b"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_GATEWAY_SUBMIT_REQUEUE_STALE_MS",
|
||||
"kind": "const",
|
||||
"sha256": "934da39a488b3a640c1649f8fb8a5a0a06b6e7c12896f4f7bf5756d1db53f6d7"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_DOWNSTREAM_MANUAL_REQUEUE_STALE_MS",
|
||||
"kind": "const",
|
||||
"sha256": "90e094f303fc32dbe7c5264b516cf69ae471ebe445344f991f38bff411dfe9fd"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_INBOUND_LONG_MESSAGE_SCAN_INTERVAL_MS",
|
||||
"kind": "const",
|
||||
"sha256": "a8e7362d181929843a1a4602f75077e22fd39a4566a435ea46edcd8a14289cca"
|
||||
},
|
||||
{
|
||||
"name": "INBOUND_LONG_MESSAGE_SCAN_INITIAL_DELAY_MS",
|
||||
"kind": "const",
|
||||
"sha256": "596cac172bef8509c819282e30e2312477148c9740ee3c818ec6428408695fb9"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_INBOUND_LONG_MESSAGE_PROCESSING_STALE_SECONDS",
|
||||
"kind": "const",
|
||||
"sha256": "9025a5ff2f673eabdd15d6f4a4a81af9485ea96680d4db637eb04a0287d7e9dc"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_UPSTREAM_RECEIPT_INBOX_SCAN_INTERVAL_MS",
|
||||
"kind": "const",
|
||||
"sha256": "6f32cbb21fe7511234b8227fadca11e58ede0c902ce25c45ecbd6122c9cc9ded"
|
||||
},
|
||||
{
|
||||
"name": "UPSTREAM_RECEIPT_INBOX_INITIAL_DELAY_MS",
|
||||
"kind": "const",
|
||||
"sha256": "a763a37b4e3af5ba91267b8c901097cd384aa618b13b7e5459788c791e83520d"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_UPSTREAM_RECEIPT_INBOX_PROCESSING_STALE_MS",
|
||||
"kind": "const",
|
||||
"sha256": "dac7d3fd5cd652cef9b59fd7458b9af13e27e32748c72618934fe21cb89b96d3"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_ATTEMPTS",
|
||||
"kind": "const",
|
||||
"sha256": "4b15ce126f631f5120298ff35a6e9a521db51c773b863914231cef27e4fa4d55"
|
||||
},
|
||||
{
|
||||
"name": "DEFAULT_UPSTREAM_RECEIPT_INBOX_MAX_AGE_HOURS",
|
||||
"kind": "const",
|
||||
"sha256": "1f58c45b6f69eec7b09c071d5cbc6b38332fdd5f7db08aa9e62f89cc6914c552"
|
||||
},
|
||||
{
|
||||
"name": "GATEWAY_SUBMIT_REQUEUE_IDEMPOTENCY_TTL_SECONDS",
|
||||
"kind": "const",
|
||||
"sha256": "a0c1f68b87266d20ab33df0192bb0cf0265276c7fa2ef2adc9b910efdc42f791"
|
||||
},
|
||||
{
|
||||
"name": "BULLMQ_PRIORITY",
|
||||
"kind": "const",
|
||||
"sha256": "6ad900e1addfdabe932080b8f7e8976f28257bd1d838c4490b4410dd669988fd"
|
||||
},
|
||||
{
|
||||
"name": "gatewaySubmitRequeueKey",
|
||||
"kind": "function",
|
||||
"sha256": "08f7ddf26ee168fe054ba96e425023b234447a6fe7ceb129e825eb2cbca6d5e5"
|
||||
},
|
||||
{
|
||||
"name": "drainageRejectionReason",
|
||||
"kind": "function",
|
||||
"sha256": "4bc0aa5e5c7f96549cd8bad93d3b25fd5e65e6b017ae9bf83baa5c47cab08c02"
|
||||
},
|
||||
{
|
||||
"name": "statusFromRisk",
|
||||
"kind": "function",
|
||||
"sha256": "4fb98f5add40278521c314dac20ec3c233b73c589714f11146964a3752ebce3a"
|
||||
},
|
||||
{
|
||||
"name": "parseSchedule",
|
||||
"kind": "function",
|
||||
"sha256": "e335aca59919111f2727b4e07cc8d50ab9443a3f06b83af807ea17d84ece861c"
|
||||
},
|
||||
{
|
||||
"name": "isObjectRecord",
|
||||
"kind": "function",
|
||||
"sha256": "c26e34d94f53b7befe62971546edd54d5a392b12aa10848e66a295624eff0c67"
|
||||
},
|
||||
{
|
||||
"name": "asDateOrNull",
|
||||
"kind": "function",
|
||||
"sha256": "f755f5ae6babe0e6626c07a9822190fb808a74fffefe69012c269da5b0650e43"
|
||||
},
|
||||
{
|
||||
"name": "downstreamRetryDelayMs",
|
||||
"kind": "function",
|
||||
"sha256": "8bab0089029e48a1027b4b4533b7c7fa0587b15e761bf566ce772b80c858f44a"
|
||||
},
|
||||
{
|
||||
"name": "downstreamAckTimeoutMs",
|
||||
"kind": "function",
|
||||
"sha256": "99d3c8f3192498f344f3bec496e0997c77740c56ea973081af1ac0acd8b52374"
|
||||
},
|
||||
{
|
||||
"name": "downstreamRetryBaseDelayMs",
|
||||
"kind": "function",
|
||||
"sha256": "2e4227ae9b787adfed98922c757e26d5b7776a225da2007d909d119476c391aa"
|
||||
},
|
||||
{
|
||||
"name": "downstreamRetryMaxDelayMs",
|
||||
"kind": "function",
|
||||
"sha256": "aa34e8a657c24224b0290222944c1b82302126921d268516d637301a4e21923f"
|
||||
},
|
||||
{
|
||||
"name": "downstreamMaxRetries",
|
||||
"kind": "function",
|
||||
"sha256": "0642b4d1609abd898d392af18ebfb074335e71fd8eea0f8fd695ae698672aaaa"
|
||||
},
|
||||
{
|
||||
"name": "downstreamPendingTimeoutHours",
|
||||
"kind": "function",
|
||||
"sha256": "41eefd652ad90dc265b22c42485f171dcd164038b69adfa1dd187fa6edfd53ea"
|
||||
},
|
||||
{
|
||||
"name": "downstreamControlFailureMessage",
|
||||
"kind": "function",
|
||||
"sha256": "1f98e86fb2dbb6cfbf48ee4e16edcad0517c4b0da9cd51bb05b7059056da03f3"
|
||||
},
|
||||
{
|
||||
"name": "parseImportRows",
|
||||
"kind": "function",
|
||||
"sha256": "abab46d40b8a7e9363dbbe7c0c7cee8412446099195ee58c08e5212855215fe7"
|
||||
},
|
||||
{
|
||||
"name": "splitImportLine",
|
||||
"kind": "function",
|
||||
"sha256": "574735eeefcc95e240fbcf9426025302382318a599fdd2207b23519637209bc8"
|
||||
},
|
||||
{
|
||||
"name": "cellByHeader",
|
||||
"kind": "function",
|
||||
"sha256": "b867ffb1936e164311b56d4735d45c8b4d9719f55e1bef4b2b3b6036d4a27470"
|
||||
},
|
||||
{
|
||||
"name": "normalizeCarrier",
|
||||
"kind": "function",
|
||||
"sha256": "d9cf3cca1702c7cd0dfc75f5aa58daa7759acbba66a1884471f710bb024ac06a"
|
||||
},
|
||||
{
|
||||
"name": "normalizeQueuePriority",
|
||||
"kind": "function",
|
||||
"sha256": "bcd2ddee1f71a873966e30bb6dcdb8b09c47998bd6c4846c8fa8db248e38df3c"
|
||||
},
|
||||
{
|
||||
"name": "getPositiveConfigInteger",
|
||||
"kind": "function",
|
||||
"sha256": "7bf2cf0a512143da511716327721a235ba60b40decb50a3dc28555e583af76f0"
|
||||
},
|
||||
{
|
||||
"name": "getNonNegativeConfigInteger",
|
||||
"kind": "function",
|
||||
"sha256": "b7782a614fa04dd858411ed86f39301313da4d35c5a66d96993266e939621cd8"
|
||||
},
|
||||
{
|
||||
"name": "isCarrierCompatible",
|
||||
"kind": "function",
|
||||
"sha256": "5353ca585ca05dd07f82eedd240a2a0c2e22d0361cc8636dd0a25ed010ccbdc5"
|
||||
},
|
||||
{
|
||||
"name": "normalizeRegion",
|
||||
"kind": "function",
|
||||
"sha256": "3775eb50779ce87f8982ce691b18f91d8ed145a5dc9c27c8a315b0f55cb09152"
|
||||
},
|
||||
{
|
||||
"name": "matchTemplateContent",
|
||||
"kind": "function",
|
||||
"sha256": "793a46db4cd6b5387214597f034bc14068d9733710b7a4d42124ee8503095243"
|
||||
},
|
||||
{
|
||||
"name": "escapeRegularExpression",
|
||||
"kind": "function",
|
||||
"sha256": "8c895b59e4a50a28f11a62883bf68be67a4672fca55774f3060c7992acce734a"
|
||||
},
|
||||
{
|
||||
"name": "isNationalChannel",
|
||||
"kind": "function",
|
||||
"sha256": "29f495b1163cc240bccbfc6a490fb04aa892ec65dc40d599f14fbd8f0628f625"
|
||||
},
|
||||
{
|
||||
"name": "isProvinceChannel",
|
||||
"kind": "function",
|
||||
"sha256": "ad1d1f53cfc50c474d455fb021fba6ae31887c911d3691d80e2dbfbf6731d73f"
|
||||
},
|
||||
{
|
||||
"name": "validateInboundApplicationSrcId",
|
||||
"kind": "function",
|
||||
"sha256": "35e9e29d174f3bc265fb26b1222480e071a16c02e8898fc6b88ba493145350cf"
|
||||
},
|
||||
{
|
||||
"name": "composeUpstreamSrcId",
|
||||
"kind": "function",
|
||||
"sha256": "f02d16cd4a722d53b3295d40b24fa0e5e8191475a050b08b99ea256d20746176"
|
||||
},
|
||||
{
|
||||
"name": "positiveInteger",
|
||||
"kind": "function",
|
||||
"sha256": "f461d0cb8b5dd9a131337cf2114f0db83ea5a449f752b03c429e8d19e5d95b78"
|
||||
},
|
||||
{
|
||||
"name": "parseOptionalSequenceId",
|
||||
"kind": "function",
|
||||
"sha256": "45c7cb2852b6e491ea4ca51c9198bf4e681a728b44ac71cdf226f119795d7ac6"
|
||||
},
|
||||
{
|
||||
"name": "normalizeSubmitStatus",
|
||||
"kind": "function",
|
||||
"sha256": "c63234b410942e86f3f8c8dfb65028f75f1e3fe9499e614d578d2c4f4a6ddcb9"
|
||||
},
|
||||
{
|
||||
"name": "normalizeReceiptStatus",
|
||||
"kind": "function",
|
||||
"sha256": "5db75635aac978593035af0746422d4842a01008a6d7223c960659120c91d740"
|
||||
},
|
||||
{
|
||||
"name": "downstreamDeliveryAttemptKey",
|
||||
"kind": "function",
|
||||
"sha256": "e62c0e52d6484f1599ffc3aaad21871efe8dd29d4cdc4bc6f49f5e95b9c7ad4b"
|
||||
},
|
||||
{
|
||||
"name": "shanghaiDateKey",
|
||||
"kind": "function",
|
||||
"sha256": "6bd70c1020b95c8013b29490754a8f2ac243c2d97c7b3fcf043d87cba6bb3296"
|
||||
},
|
||||
{
|
||||
"name": "bullmqConnection",
|
||||
"kind": "function",
|
||||
"sha256": "1fe9095c9ed383419f640913f033ff0715d4e241c8114543097a51dbf1acaf67"
|
||||
},
|
||||
{
|
||||
"name": "matchesApplicationSecret",
|
||||
"kind": "function",
|
||||
"sha256": "5ff5731f341a2a5ca427f3c232d74b2ef0d54280aba8bf4b4728274dde9b0e4e"
|
||||
},
|
||||
{
|
||||
"name": "octetString",
|
||||
"kind": "function",
|
||||
"sha256": "c3c7e6248530121ba0792d8918f43f0869d62fb94e1627f1c0173462fd0c4499"
|
||||
},
|
||||
{
|
||||
"name": "hasRecoveryAuditStateChanged",
|
||||
"kind": "function",
|
||||
"sha256": "de4073a3dfd772f0cbb9d57255618cc5f54543ac378325ab35558617749c28ca"
|
||||
},
|
||||
{
|
||||
"name": "normalizeRecoveryFailureCategory",
|
||||
"kind": "function",
|
||||
"sha256": "69f4f1dd9c09e4d84277a92eb28cf6d117ac10fa649faf7898ceb0cd0c68a9c5"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
{
|
||||
"version": "R9",
|
||||
"generatedAt": "2026-07-31",
|
||||
"source": "api/src/send-chain/send-chain.service.ts at R8 local baseline",
|
||||
"target": "api/src/send-chain/send-*.service.ts via send-submission.service.ts compatibility facade",
|
||||
"methods": [
|
||||
{
|
||||
"name": "createBatchTask",
|
||||
"bodySha256": "c7baccb2b49a95ef4b36a97f6f56c987f0ac60c45ed634cd050201f2a9bce8b5",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "createHttpBatchTask",
|
||||
"bodySha256": "9c5a8d4a1a257e418f8abf83b7ae4fc10148e966a77d45e78568207eeabf92a6",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "getBatchTask",
|
||||
"bodySha256": "ce25b495f876e746e7b707410e699479bb7d9cb27c2a749c89dd45a956a23c07",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "previewImport",
|
||||
"bodySha256": "c722c90e014ee4b7301e8c7a01591b0573574f15b49df5fc9498067235613013",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "confirmImport",
|
||||
"bodySha256": "48ed35f8271892be111909dcce3ddf0705e3054ca38a236c416e9b8d41747864",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "enqueueBatchTask",
|
||||
"bodySha256": "909972eb0accfb6e31b9fd6118750005c4a6671577ef5b5c9222a341dac59800",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "handleReviewDecision",
|
||||
"bodySha256": "62f118fa543b8db59773300c5218008c25ae779ab9e0a888aac26c7e85ed3db1",
|
||||
"file": "send-review-continuation.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "dispatchDueScheduledTasks",
|
||||
"bodySha256": "8fd154bd1318b362b844a97a42cde360623ecb372bd476b92baa54db8a4be768",
|
||||
"file": "send-scheduled-dispatch.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "runScheduledDispatchScan",
|
||||
"bodySha256": "02167ffcf1972ee2d85e40d933f0c02fe031300e973fa4307dfd1678a14f27ba",
|
||||
"file": "send-scheduled-dispatch.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "startWorker",
|
||||
"bodySha256": "82fe6e5b27f95b15f4a5c218cb6c30e99a9128c293192e7443657d8b245f84d6",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "processSendJob",
|
||||
"bodySha256": "cec399a6552c118a77530f760e2c05b4d2d1fd01c9bdc477f342e0015d461207",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "authenticateInboundApplication",
|
||||
"bodySha256": "2630dd1066b5a3e86c805d13102973e1c928ca2747bd0c3741481d03169eba2f",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "submitInboundMessage",
|
||||
"bodySha256": "281e33a732f80e4ede6cc9d04a5b206a9348e17e66dee33d53f2d8d1d9bb9472",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "recoverCompletedInboundLongMessageResponse",
|
||||
"bodySha256": "d98dd2a7606f45711f9dafbcbf4668c27a4d17a9343ee790ebe2c8b36ff5e49c",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "submitCompleteInboundMessage",
|
||||
"bodySha256": "10e2140580e4bae2055853981de65f4adf82c228b647dbb56fce7c39469acaf3",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "collectInboundLongMessageFragment",
|
||||
"bodySha256": "5b4e7f795966462fccb8c4c7a2cfae649ef19ee1b8176e7356eb2d621526ba41",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "expireInboundLongMessages",
|
||||
"bodySha256": "2328633d6c410089b3be4e38245d238a783015e3411baee0f8202a9c953aa427",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "submitInboundSingleMessage",
|
||||
"bodySha256": "df97548b1710b217f118cc297104d6c5cc845acc40947df4180036b8d284d847",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "evaluateRiskWithPhoneFrequency",
|
||||
"bodySha256": "2e9fab56cd8ae85856fae2e88bb49c1ac1438feea79b7410069554c4fb494782",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "submitMessageToGateway",
|
||||
"bodySha256": "4a928eab5727ba457ee1d4a202e719b6e389361ab2be8ad13ccf146dcebdc141",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "selectChannelForMessage",
|
||||
"bodySha256": "3ab89dbfea42c99a898e7ea62742b200a18615e7aed541c2978af913b9689c68",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "findApplicationRoute",
|
||||
"bodySha256": "110dd4b6d716ee0b08306a16818617b73fba8c6148ae6b7bc87480a2a3f75b54",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "identifyCarrier",
|
||||
"bodySha256": "18e82894203d50d9b2371b9da0ac06fc34e83dd5600d3411f3a09a912955f0b4",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "identifyProvince",
|
||||
"bodySha256": "56d1859733bfe44b6d32295f5706d06b64f1bb03e797e8c894f98b012a71fa35",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "resolveUnitPrice",
|
||||
"bodySha256": "1d14202d83fcc9baa4e56ff2e33771db81f64159852142fadfeae4a89eb5e5c9",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "resolveQueuePriority",
|
||||
"bodySha256": "752b13877a4b7a5f89f95cc7f52718e0c473a7c70cb0b99eec63370790540b89",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "resolveApplicationAccessNumber",
|
||||
"bodySha256": "948dbcb3106c96c1c2aa3fe4e914590b38f3961d720357b2df3ede07e80663f5",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "findInboundApplication",
|
||||
"bodySha256": "6d0bfcb122d0d824f7db542ed3d6a84d034d816f412c61cf96a38510d1738023",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "resolveInboundTemplateCandidate",
|
||||
"bodySha256": "0bd1ccad86d18797132a4f142b24bcfff080021c76217f946301befc81b51b4e",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "resolveInboundSignatureCandidate",
|
||||
"bodySha256": "716a526ea36f92012670c48e3f9cf4a2453435bed6b1943a310e603531998412",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "resolveTemplateMessageClassification",
|
||||
"bodySha256": "f2b99e2e9d7fa00172b3cca72f080493fbf6f090f378784611388320254575f7",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "resolveDrainageInfoMatch",
|
||||
"bodySha256": "31c393cd6b5b641776dc50cee46fe79cc5243adb57c6296a1b0cd8b346896021",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "attachMessageToReviewTask",
|
||||
"bodySha256": "55485f011465ae62006552c1343822623a8d914d2989f74b3e809eea659539c2",
|
||||
"file": "send-inbound-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "classifyRejectedPhones",
|
||||
"bodySha256": "cd9fe84399dcf83d4e7926c4c3900f04fb84a526135009e5af17b417bf81b108",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "validateSendResources",
|
||||
"bodySha256": "3c96b0edae411fb291cc9f52b0c3de8681c00f870c9e25cfd458703257639f00",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "reserveDailySendQuota",
|
||||
"bodySha256": "2f3132ec25ad778d24ca8129263e2a4db9120697160f908fd247c9824dc7bc49",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "tryReserveDailySendQuota",
|
||||
"bodySha256": "3de44b2c155cb25a8c327b465235d1ec627b375f5fa521e2c0fc0a9f3b62b3b5",
|
||||
"file": "send-batch-entry.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "ensureSignatureReportedForChannel",
|
||||
"bodySha256": "8c2c5c6f4ef9a26a4643f215c5e590e25d91642946094705e6c1fc7070e0bbd3",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "resolveMessageSignatureId",
|
||||
"bodySha256": "4c67a20f76e520afc23756ae475a365769c6eaea18c453a7516f2502c26b756a",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "waitForChannelRateLimit",
|
||||
"bodySha256": "7706917a2535caf85fa17cbe8732179211ebca96ac233ba986c1e713f78f26b8",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "refreshTaskProgress",
|
||||
"bodySha256": "3c5521193128d2d738abf37b7bd6213bfb7c60973d85daa28e4d9f28e2ea81e3",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "getSendQueue",
|
||||
"bodySha256": "9dca5a9008ebd0c472db8807e64be409aed46e5dd289638149f56a4b23970d7e",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "getGatewayQueue",
|
||||
"bodySha256": "0f24d7cbf91cf33b9620c6f6197edddfe64cc49e8d9e237eb656e84fb9965c66",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "getRedis",
|
||||
"bodySha256": "f487638a6b656e0d297ed0f6f3181face99b71895dec42762c834bf1d20dc635",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
},
|
||||
{
|
||||
"name": "publishGatewaySubmitCommand",
|
||||
"bodySha256": "ad68171579e3790c3f9176f6a2c9fd900783da5ae6ded9593f3e156ea0e297de",
|
||||
"file": "send-gateway-submit.service.ts"
|
||||
}
|
||||
],
|
||||
"domains": [
|
||||
{
|
||||
"file": "send-batch-entry.service.ts",
|
||||
"className": "SendBatchEntryService",
|
||||
"methodCount": 13
|
||||
},
|
||||
{
|
||||
"file": "send-inbound-entry.service.ts",
|
||||
"className": "SendInboundEntryService",
|
||||
"methodCount": 13
|
||||
},
|
||||
{
|
||||
"file": "send-review-continuation.service.ts",
|
||||
"className": "SendReviewContinuationService",
|
||||
"methodCount": 1
|
||||
},
|
||||
{
|
||||
"file": "send-scheduled-dispatch.service.ts",
|
||||
"className": "SendScheduledDispatchService",
|
||||
"methodCount": 2
|
||||
},
|
||||
{
|
||||
"file": "send-gateway-submit.service.ts",
|
||||
"className": "SendGatewaySubmitService",
|
||||
"methodCount": 16
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
{
|
||||
"version": "R11-step-7",
|
||||
"entry": "src/main.tsx",
|
||||
"componentsFile": "src/styles/components.css",
|
||||
"legacyFile": "src/styles/global.css",
|
||||
"minimumRuleCount": 259,
|
||||
"minimumSelectorCount": 291,
|
||||
"compatibilityMarker": "Shared table, form, and modal compatibility primitives migrated in R11 step 7.",
|
||||
"canonicalMarker": "Canonical reusable component rules.",
|
||||
"responsiveMarker": "Shared responsive table and form behavior migrated in R11 step 7.",
|
||||
"genericClasses": [
|
||||
"table-cell-note",
|
||||
"modal-footer-actions",
|
||||
"icon-button",
|
||||
"table-subline",
|
||||
"table-link",
|
||||
"table-actions",
|
||||
"table-mono-id",
|
||||
"table-strong-text",
|
||||
"table-long-text",
|
||||
"table-long-text--sms-template",
|
||||
"template-modal-title",
|
||||
"form-grid",
|
||||
"form-grid--two",
|
||||
"radio-row"
|
||||
],
|
||||
"allowedStateClasses": [
|
||||
"has-dot",
|
||||
"is-disabled"
|
||||
],
|
||||
"requiredComponentBindings": {
|
||||
"src/components/ui/Button.tsx": [
|
||||
"ui-button"
|
||||
],
|
||||
"src/components/ui/Input.tsx": [
|
||||
"ui-field",
|
||||
"ui-input"
|
||||
],
|
||||
"src/components/ui/Select.tsx": [
|
||||
"ui-select",
|
||||
"ui-select__dropdown"
|
||||
],
|
||||
"src/components/ui/Table.tsx": [
|
||||
"ui-table-wrap",
|
||||
"ui-table",
|
||||
"ui-table__empty"
|
||||
],
|
||||
"src/components/ui/Modal.tsx": [
|
||||
"ui-modal",
|
||||
"ui-modal__mask",
|
||||
"ui-modal__panel",
|
||||
"ui-modal__header",
|
||||
"ui-modal__body",
|
||||
"ui-modal__footer"
|
||||
]
|
||||
},
|
||||
"requiredRuleFragments": [
|
||||
{
|
||||
"selector": ".icon-button",
|
||||
"includes": [
|
||||
"display:inline-flex",
|
||||
"height:var(--control-height-md)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".ui-table-wrap",
|
||||
"includes": [
|
||||
"max-width:100%",
|
||||
"border:1px solid var(--color-border)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".ui-table",
|
||||
"includes": [
|
||||
"border-collapse:collapse",
|
||||
"width:100%"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".ui-modal",
|
||||
"includes": [
|
||||
"display:grid",
|
||||
"position:fixed",
|
||||
"z-index:var(--z-modal)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".ui-modal__panel",
|
||||
"includes": [
|
||||
"min-width:min(520px, calc(100vw - 48px))",
|
||||
"transform:translate(-50%, -50%)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".form-grid",
|
||||
"includes": [
|
||||
"display:grid",
|
||||
"gap:var(--space-4)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".radio-row",
|
||||
"includes": [
|
||||
"display:flex",
|
||||
"gap:var(--space-6)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".form-grid--two",
|
||||
"media": "(max-width: 780px)",
|
||||
"includes": [
|
||||
"grid-template-columns:1fr"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".table-actions",
|
||||
"media": "(max-width: 780px)",
|
||||
"includes": [
|
||||
"flex-wrap:wrap"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".ui-table",
|
||||
"media": "(max-width: 780px)",
|
||||
"includes": [
|
||||
"display:block",
|
||||
"min-width:0 !important"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".ui-table td",
|
||||
"media": "(max-width: 780px)",
|
||||
"includes": [
|
||||
"display:grid",
|
||||
"grid-template-columns:minmax(84px, 0.42fr) minmax(0, 1fr)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"selector": ".ui-modal__panel",
|
||||
"media": "(max-width: 780px)",
|
||||
"includes": [
|
||||
"width:calc(100vw - 24px)"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,455 @@
|
||||
{
|
||||
"version": "R7",
|
||||
"source": "gateway/internal/upstream/manager.go@HEAD-before-R7",
|
||||
"declarations": [
|
||||
{
|
||||
"name": "connection",
|
||||
"kind": "type",
|
||||
"file": "connection.go",
|
||||
"sha256": "4df1abc8aaf424b2a5f500dc795a481d22b3759ca4c1a23fb4c619d4104b9ac4"
|
||||
},
|
||||
{
|
||||
"name": "submitPartResponse",
|
||||
"kind": "type",
|
||||
"file": "connection.go",
|
||||
"sha256": "98f6612c555a8189ff6b32811807cbb566a21de3889359afc11fdebec0a4dd1f"
|
||||
},
|
||||
{
|
||||
"name": "close",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "connection.go",
|
||||
"sha256": "c56f9c0839b6efad46968e5b7669b60dc757b1aa3b3db4793101667be90e88c7"
|
||||
},
|
||||
{
|
||||
"name": "ensureConnected",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "connection.go",
|
||||
"sha256": "588082992ce35ee45ef1635c1332d50ab2d642313b65c176edf5c169a3e84d82"
|
||||
},
|
||||
{
|
||||
"name": "handleConnectionLoss",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "connection.go",
|
||||
"sha256": "c6fdad8cc5cead7b87490d4075b2dbd7a4abdb693669b8dac6484d87f42c1762"
|
||||
},
|
||||
{
|
||||
"name": "identity",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "connection.go",
|
||||
"sha256": "755d4df355d64e7faf4d75f09ad64a52efecb2770724a1af1f3efa8862eb5456"
|
||||
},
|
||||
{
|
||||
"name": "matches",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "connection.go",
|
||||
"sha256": "7ebd52a39510f1108159a1666357a0e71ffe2f95df7cd1612d63a95ef600e81b"
|
||||
},
|
||||
{
|
||||
"name": "readLoop",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "connection.go",
|
||||
"sha256": "5a4cd84fb6eb546dce10790fb8e09872a8308608ca2c7d6dbd773d6af4fbbade"
|
||||
},
|
||||
{
|
||||
"name": "sendResponse",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "connection.go",
|
||||
"sha256": "af80603adc9ad0a9757c042b2bfcc88582f4e4ad96ac4142e67833ddcb348bce"
|
||||
},
|
||||
{
|
||||
"name": "decodeContent",
|
||||
"kind": "func",
|
||||
"file": "deliver.go",
|
||||
"sha256": "a66a6cc45a405c028cf41c7946dc89c6b1a313019863d6aa4b0a468d3ce7ef3f"
|
||||
},
|
||||
{
|
||||
"name": "deliverPacket",
|
||||
"kind": "type",
|
||||
"file": "deliver.go",
|
||||
"sha256": "ec8b102d29392592af2b840927171a8037b9254fa1e02c50840b552db0f4efb4"
|
||||
},
|
||||
{
|
||||
"name": "deliverPacketFromCMPP2",
|
||||
"kind": "func",
|
||||
"file": "deliver.go",
|
||||
"sha256": "d8a8210f0a756eaa4354ca74089b8af02c7839c35434e49e616c69c3fe22f02f"
|
||||
},
|
||||
{
|
||||
"name": "deliverPacketFromCMPP3",
|
||||
"kind": "func",
|
||||
"file": "deliver.go",
|
||||
"sha256": "31354345d9e3ed87658fc8f8b353a4a3607eff191e836b1f10913a8a2f22e34c"
|
||||
},
|
||||
{
|
||||
"name": "receiptStatus",
|
||||
"kind": "func",
|
||||
"file": "deliver.go",
|
||||
"sha256": "28f650601bb209e123371e8f04cd2e7103686c3b425ea60a6abf5440595c8fb8"
|
||||
},
|
||||
{
|
||||
"name": "commandFor",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "deliver.go",
|
||||
"sha256": "ec725550863714d1a18497ff7fea01dfa8987fa81d72dd7bbcb65c168a7dde5b"
|
||||
},
|
||||
{
|
||||
"name": "decodeUplinkContent",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "deliver.go",
|
||||
"sha256": "49bef95beb72d7b780c95d54d7fe7264e820610277a01bc38575d27cc1758b6d"
|
||||
},
|
||||
{
|
||||
"name": "handleDeliver",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "deliver.go",
|
||||
"sha256": "a4fe7d49043e2454548bdf4efdd2e312688f467e83ae9c4a4c0beff158471a52"
|
||||
},
|
||||
{
|
||||
"name": "handleHeartbeatResponse",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "flow_control.go",
|
||||
"sha256": "8b677a42a3d62d16e59f0e8bf1faaeae170bcf8f17e00c9b4c0cb3f6f05b52ed"
|
||||
},
|
||||
{
|
||||
"name": "heartbeatLoop",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "flow_control.go",
|
||||
"sha256": "b89ac640cf9b3b888ecf73c4848119b347e0fda2edb4ac1983ebda0dc7da8e57"
|
||||
},
|
||||
{
|
||||
"name": "releaseWindow",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "flow_control.go",
|
||||
"sha256": "5bb5aa24192d85ad7a0619ef2f702b0f76975a8e73dbe75e8179af5c767da53d"
|
||||
},
|
||||
{
|
||||
"name": "sendHeartbeat",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "flow_control.go",
|
||||
"sha256": "9c0164b3257072cc7c4c1827f3213baf2e8d73a077323b83e0278d0f1213be28"
|
||||
},
|
||||
{
|
||||
"name": "tryAcquireWindow",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "flow_control.go",
|
||||
"sha256": "e766bd3e3554d6b03496652ffb3e16779cc1a5743ab2e016c030f16858651b8c"
|
||||
},
|
||||
{
|
||||
"name": "acquireConnection",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "flow_control.go",
|
||||
"sha256": "63edb09faf3d5fe19dc1f1e80251e11188707a79e4cb97b854e7a2642653844d"
|
||||
},
|
||||
{
|
||||
"name": "tryAcquireConnection",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "flow_control.go",
|
||||
"sha256": "11378d52c134e485d434cc396d31d6188a1d2abb322e92cadfd6ec2eddb73c23"
|
||||
},
|
||||
{
|
||||
"name": "ConnectionState",
|
||||
"kind": "type",
|
||||
"file": "manager.go",
|
||||
"sha256": "adc946f31d60738834305e2d1b2c94514ffd57decc6dcf49069eabe6f5adc61c"
|
||||
},
|
||||
{
|
||||
"name": "Manager",
|
||||
"kind": "type",
|
||||
"file": "manager.go",
|
||||
"sha256": "c7ead8b037bc87ad9800650ce191f5fcee9648b8805a133b9506743c762ea608"
|
||||
},
|
||||
{
|
||||
"name": "defaultChannelConnectionID",
|
||||
"kind": "func",
|
||||
"file": "manager.go",
|
||||
"sha256": "1344ae4c7831f4b85b01ab0b69a1d01ff6029c3475973e55a694227bd0081de8"
|
||||
},
|
||||
{
|
||||
"name": "defaultConnectTimeout",
|
||||
"kind": "const",
|
||||
"file": "manager.go",
|
||||
"sha256": "4cd56f6b6b4d26dce6682233198d91f895440b0945c16dc2e734419de269a9e0"
|
||||
},
|
||||
{
|
||||
"name": "normalizeUpstreamConfig",
|
||||
"kind": "func",
|
||||
"file": "manager.go",
|
||||
"sha256": "6922f679a80f15b0562408284baa1633530321748f82064b4599486ebccf33e9"
|
||||
},
|
||||
{
|
||||
"name": "validateConnectChannelCommand",
|
||||
"kind": "func",
|
||||
"file": "manager.go",
|
||||
"sha256": "e74d75116b7189530160608369ee9fa0c11b8aea3608b1da039cc032a51a3738"
|
||||
},
|
||||
{
|
||||
"name": "ConnectChannel",
|
||||
"kind": "func",
|
||||
"receiver": "Manager",
|
||||
"file": "manager.go",
|
||||
"sha256": "376f150d5375e8068768e5ac6910e96336ae72b7a8967c65de68c44e0d66832f"
|
||||
},
|
||||
{
|
||||
"name": "DisconnectChannel",
|
||||
"kind": "func",
|
||||
"receiver": "Manager",
|
||||
"file": "manager.go",
|
||||
"sha256": "68eba625ebce875254dd12d9140675bd80a2aac02dbbda947ebb2795cd6aaa8d"
|
||||
},
|
||||
{
|
||||
"name": "connectionFor",
|
||||
"kind": "func",
|
||||
"receiver": "Manager",
|
||||
"file": "manager.go",
|
||||
"sha256": "90fd44cb9a3a3bc5860fa4c41b1bc230f1a8b49150948a6482f3a3e16341d2a2"
|
||||
},
|
||||
{
|
||||
"name": "ensureDefaultsLocked",
|
||||
"kind": "func",
|
||||
"receiver": "Manager",
|
||||
"file": "manager.go",
|
||||
"sha256": "1050738b55672cee730f87d7c2e00f555e2c59242319b8970009e318480f7b80"
|
||||
},
|
||||
{
|
||||
"name": "newConnectionPool",
|
||||
"kind": "func",
|
||||
"receiver": "Manager",
|
||||
"file": "manager.go",
|
||||
"sha256": "0e4ce662f1d076aaad3ee28415395f9447b2675c5f9ac21daf5e188857f3f95b"
|
||||
},
|
||||
{
|
||||
"name": "connectionPool",
|
||||
"kind": "type",
|
||||
"file": "pool.go",
|
||||
"sha256": "6b89ef24af5a726ace99d569dda5b7d8d48530337924d8eb8fd5712d41147098"
|
||||
},
|
||||
{
|
||||
"name": "close",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "pool.go",
|
||||
"sha256": "2e88c346d26e134071e1d5235249521e3a87df25ef4b441cb04baa549e485d83"
|
||||
},
|
||||
{
|
||||
"name": "countActiveConnections",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "pool.go",
|
||||
"sha256": "fe0888a6894a67b9558711e4ae8ab81953fe49d9bd3e07548dcaacdf75b208dc"
|
||||
},
|
||||
{
|
||||
"name": "ensureConnected",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "pool.go",
|
||||
"sha256": "471b79729cb8a28ff77837a42a8fef87a7f9ca638ef05fcb6d584195deffbc33"
|
||||
},
|
||||
{
|
||||
"name": "matches",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "pool.go",
|
||||
"sha256": "cef5bfa15168f238cd67f459796764a573553923de9392af55341e961c614fc7"
|
||||
},
|
||||
{
|
||||
"name": "protocolLogEvent",
|
||||
"kind": "type",
|
||||
"file": "protocol_log.go",
|
||||
"sha256": "5be7ca704c11594b6b72edbd83b2baac11d22bffd9a1e6c9698a6c07d909a008"
|
||||
},
|
||||
{
|
||||
"name": "emitDeliverResponse",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "protocol_log.go",
|
||||
"sha256": "96e9ea5776f20d97663b0c1502a65c5d49e9dc53ac28bad5b8df54bac18825d9"
|
||||
},
|
||||
{
|
||||
"name": "emitProtocolLog",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "protocol_log.go",
|
||||
"sha256": "d44dcf7c538cfd3578a6756d89e23dcad53aa76627a52b781fd7e59e6e3ed302"
|
||||
},
|
||||
{
|
||||
"name": "connectionErrorCategory",
|
||||
"kind": "func",
|
||||
"file": "reconnect.go",
|
||||
"sha256": "6598e63e63ede1035651cee20e085ee5408b328391d2a0c49a59d4c1d74a4d04"
|
||||
},
|
||||
{
|
||||
"name": "isTemporaryReadTimeout",
|
||||
"kind": "func",
|
||||
"file": "reconnect.go",
|
||||
"sha256": "4d25d0d0ab0650d549518bca0b1a8f766dff8d6346aec288bfdfff5357350fe6"
|
||||
},
|
||||
{
|
||||
"name": "reconnectDelay",
|
||||
"kind": "func",
|
||||
"file": "reconnect.go",
|
||||
"sha256": "30acd31250bac730a3a561a3b91829ffc28890c9d94718db524ffb20ab8cbc5d"
|
||||
},
|
||||
{
|
||||
"name": "resetReconnectState",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "reconnect.go",
|
||||
"sha256": "5373b80c609ab33f99296c5a69b8d1e7a35309eeaabff0160a7ee110d472cf60"
|
||||
},
|
||||
{
|
||||
"name": "scheduleReconnect",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "reconnect.go",
|
||||
"sha256": "d5a5b113f90b81192d1e2e9e08cc0105ea66044eaf13834cc7cffd9393d46c9f"
|
||||
},
|
||||
{
|
||||
"name": "signalReconnect",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "reconnect.go",
|
||||
"sha256": "d8d747a45e8f8a7647e73482ad8057e36bd081489d2e8181fe905b2cb5808faa"
|
||||
},
|
||||
{
|
||||
"name": "startSupervisor",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "reconnect.go",
|
||||
"sha256": "e4d0455ac0c62f5e3e5dee516415d200e7e33e419df8e9ff5e5c741648bd65da"
|
||||
},
|
||||
{
|
||||
"name": "stopped",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "reconnect.go",
|
||||
"sha256": "4dd236bbdf5e30f3d188a5de75e0c8d1b781d758f50287b8fe4ee55a02136368"
|
||||
},
|
||||
{
|
||||
"name": "superviseReconnects",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "reconnect.go",
|
||||
"sha256": "081deef84986116b80d635c1ab202a90a668f1e6ea4b556d0222e217b9867df8"
|
||||
},
|
||||
{
|
||||
"name": "encodeContent",
|
||||
"kind": "func",
|
||||
"file": "submit.go",
|
||||
"sha256": "961071e5ad611ee1c9f55f68dbb2d6ba5d3dbddc7daf9027b76e7292cb492d89"
|
||||
},
|
||||
{
|
||||
"name": "protocolVersion",
|
||||
"kind": "func",
|
||||
"file": "submit.go",
|
||||
"sha256": "aaef75fad9276b48e18ed22a23bd2a6b05e983b9a8ec8c3de216656b1f81e38d"
|
||||
},
|
||||
{
|
||||
"name": "submitRequestFields",
|
||||
"kind": "type",
|
||||
"file": "submit.go",
|
||||
"sha256": "dbf2cb6c377f487d543d8f08a1167e0ca77f038fd0d86dcff1d982542b9cbc7f"
|
||||
},
|
||||
{
|
||||
"name": "submitResult",
|
||||
"kind": "func",
|
||||
"file": "submit.go",
|
||||
"sha256": "01a16e0be0695baab3a5cb7056b3d8b2fa51dcaa56caec75a8f277c490d9d8c8"
|
||||
},
|
||||
{
|
||||
"name": "submitSegmentResult",
|
||||
"kind": "func",
|
||||
"file": "submit.go",
|
||||
"sha256": "a5dfdaf6b4a9b5f222d3a370f4310d9ba271ebb3546f0b3969ba679821e6c815"
|
||||
},
|
||||
{
|
||||
"name": "validateSubmitCommand",
|
||||
"kind": "func",
|
||||
"file": "submit.go",
|
||||
"sha256": "b4786c6e421a7fd188d2c2e84b2acfa39dc3e62c79ac8f32262f1a6f078ee14c"
|
||||
},
|
||||
{
|
||||
"name": "Submit",
|
||||
"kind": "func",
|
||||
"receiver": "Manager",
|
||||
"file": "submit.go",
|
||||
"sha256": "81d3554f05c38d91cde37b4fa918c2d30d7f4e6da2265c2fe0f9b499650375f3"
|
||||
},
|
||||
{
|
||||
"name": "submitPart",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "submit.go",
|
||||
"sha256": "38407f46b9d5626ba5c854a17d5831727e920e7cc881bb1004a9167c53420363"
|
||||
},
|
||||
{
|
||||
"name": "submitRequestPacket",
|
||||
"kind": "func",
|
||||
"receiver": "connection",
|
||||
"file": "submit.go",
|
||||
"sha256": "14b2fd65a4c407817bc86d0e79524296ccb8b325a289cc44fb2227b9c5834a2a"
|
||||
},
|
||||
{
|
||||
"name": "submit",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "submit.go",
|
||||
"sha256": "9efe1c726215a512d7039c852fdca06544f603ed810daae3fe291cc51038315b"
|
||||
},
|
||||
{
|
||||
"name": "defaultInt",
|
||||
"kind": "func",
|
||||
"file": "transport.go",
|
||||
"sha256": "cec47c9a91ab21247e5c62b0c36f24449f622f338bc449e14aaa8cbb9888e295"
|
||||
},
|
||||
{
|
||||
"name": "defaultString",
|
||||
"kind": "func",
|
||||
"file": "transport.go",
|
||||
"sha256": "e3f1c7ba3d2aa985b2df53748e307f4e2769815d3cb8500dc616b929cee1e38a"
|
||||
},
|
||||
{
|
||||
"name": "postJSON",
|
||||
"kind": "func",
|
||||
"file": "transport.go",
|
||||
"sha256": "f173638019db247e64783989125e3b66dbb258e086b08d6049fcb1bc3178f22b"
|
||||
},
|
||||
{
|
||||
"name": "post",
|
||||
"kind": "func",
|
||||
"receiver": "Manager",
|
||||
"file": "transport.go",
|
||||
"sha256": "0c93f5e542efa601b46f7917ed226dc89d22c0a9a5b37e6a4b73d7134fab8d66"
|
||||
},
|
||||
{
|
||||
"name": "reportState",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "transport.go",
|
||||
"sha256": "b9d7b1bb926d9d38cbc04c5d08c7fe29acf8bc3534b193e5394b4a739ab49499"
|
||||
},
|
||||
{
|
||||
"name": "snapshotState",
|
||||
"kind": "func",
|
||||
"receiver": "connectionPool",
|
||||
"file": "transport.go",
|
||||
"sha256": "d11c9e2197c8023946979487e53969babf01afa0773d0cdf7aa11286f95bd4b3"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1827,6 +1827,7 @@
|
||||
## 运营看板与短信记录运营商筛选(2026-07-29)
|
||||
|
||||
- 运营看板“今日发送趋势”按 `Asia/Shanghai` 自然日固定返回 00:00 至 23:00 共 24 个小时桶,以折线图同时展示每小时业务短信提交总条数和最终状态为 `delivered` 的成功条数;无数据小时必须补零,不使用前端静态数据。
|
||||
- `SmsMessageRecord.queuedAt` 为 PostgreSQL `timestamp without time zone` 且保存 UTC 时间,小时分桶必须先按 UTC 解释该字段,再转换为 `Asia/Shanghai` 提取小时;结果不得依赖 PostgreSQL 会话时区,不得把北京时间 09:00 的记录显示在 01:00。
|
||||
- 运营看板“审核处理趋势”更名为“审核处理速度”。按企业认证、短信审核、模板、签名、引流信息五类展示北京时间当天已完成审核数量及平均处理时长;处理时长为同一审核事项本轮审核完成时间减本轮提交时间,无有效提交时间或出现负时长的记录不参与平均值。
|
||||
- 签名通道发送质量明细的运营商概览固定按移动、联通、电信排列;未识别运营商如有数据排在三大运营商之后,数据库聚合返回顺序不得直接作为展示顺序。
|
||||
- 运营端短信记录新增运营商筛选,选项为全部、移动、联通、电信、未识别。筛选必须由真实后端和 PostgreSQL 执行,并同时作用于分页总数、当前页和 CSV 导出;“未识别”包含空运营商及不属于三大运营商标准/兼容值的历史记录。
|
||||
@@ -1836,3 +1837,36 @@
|
||||
- 短信审核列表将“发送企业 / 企业应用”、“提交时间 / 审核来源”和“号码数量 / 状态”分别合并为三个上下分层的信息格,相关信息不得删除或改为仅在详情中展示。
|
||||
- 短信内容列应设置为列表主要宽列,桌面端目标宽度不小于 440px;当可用宽度不足时由表格容器横向滚动,不得通过压缩内容列造成短信正文难以阅读。
|
||||
- 号码数量继续使用真实审核任务关联短信记录数量,并保留打开真实号码分页列表的交互;本次仅调整展示布局,不改变审核查询、批量选择、通过或驳回流程。
|
||||
|
||||
## 号码发送频次风控(2026-07-30)
|
||||
|
||||
- 系统内置并启用两条全局兜底规则:同一企业应用、同一手机号码在北京时间自然日内最多提交 10 条业务短信;在按北京时间时钟对齐的固定 5 分钟周期内最多提交 5 条业务短信。达到阈值的短信仍允许提交,下一条开始直接拒绝。
|
||||
- 两条规则独立计数、独立命中;任一规则命中即直接拒绝该号码。首版处理动作固定为直接拒绝,不进入人工审核,也不提供放行后继续发送的自动动作。
|
||||
- 隔离键固定为`applicationId + phoneNumber + ruleCode`。同一号码在不同企业应用下互不影响;同一企业的不同应用也分别计数。
|
||||
- 计数单位为业务短信号码记录:一次任务向同一号码提交一条短信计 1 条,长短信分片和通道失败补发不重复计数。格式非法、黑名单命中或整个任务已被前置风控拒绝的号码不进入号码频次计数。
|
||||
- 24 小时规则使用`Asia/Shanghai`自然日 00:00:00 至次日 00:00:00;5 分钟规则使用 00、05、10 等整 5 分钟对齐周期。进入下一周期时该周期计数自动从 0 开始,不采用命中时刻向后滚动的滑动窗口。
|
||||
- 运营可分别为企业应用新增两条规则的个性化阈值;应用规则启用时覆盖同码全局兜底规则,未配置或停用时继续使用全局兜底。号码频控阈值只能是大于 0 的整数,周期、时区、对齐方式及直接拒绝动作首版不可修改。
|
||||
- 命中时必须持久化企业、应用、号码、规则、阈值、触发值、周期起止、来源和触发时间。命中后的同周期提交继续拒绝,但不得重复生成相同的活跃触发记录。
|
||||
- 风控规则页提供真实后端分页的号码频次触发记录,支持按当前应用范围、号码和拦截中/周期已到期/已人工解除状态查询。
|
||||
- 运营可对单条触发记录执行“解除并清零”,必须填写原因并记录操作人、时间和审计日志。解除只清零该应用、号码、规则的当前计数,不删除历史记录,也不影响另一条频控规则;同周期再次超过阈值时生成新一代触发记录。
|
||||
- 计数占用、首次命中记录及活跃命中关联必须由 PostgreSQL 原子完成,并能承受同一应用、同一号码的并发提交;不得使用进程内 Map、Redis 临时键、浏览器 localStorage、静态数据或 Mock 作为正式实现。
|
||||
|
||||
## 平台级号码频控白名单(2026-07-30)
|
||||
|
||||
- 运营端在风控规则页维护平台级号码频控白名单。处于启用状态的号码,在全平台所有企业及所有应用下均豁免`PHONE_FREQUENCY_24H`和`PHONE_FREQUENCY_5M`两类号码频控,包括企业应用个性化覆盖规则。
|
||||
- 白名单不豁免号码格式校验、企业/应用黑名单、敏感词和内容审核、模板与签名审核、余额、应用日限额、路由、报备及其他风控规则;首版不提供企业级或应用级白名单。
|
||||
- 白名单提供真实后端和数据库分页的增删改查,号码在平台内唯一,支持启用、停用、号码筛选和已删除历史查询。用途说明必填,备注选填;新增、修改、启停和删除均记录操作人、时间、修改前后内容及操作审计。
|
||||
- 新增或恢复启用白名单时,清零该号码在所有企业应用及两类规则下的当前计数,并解除尚未到期的活跃命中;修改号码时同时清零旧号码和新号码;启停切换或删除时同样清零,确保号码退出白名单后从零开始重新计数。历史命中和白名单记录不得物理删除。
|
||||
- 白名单有效期间的提交不写入号码频控状态、不增加计数、不产生号码频控命中。白名单写操作事务返回后发起的新请求必须遵循新状态;已经在写操作前进入频控事务的并发请求允许按其已读取的事务快照完成。
|
||||
- 批量发送时白名单必须按号码集合分块查询,不得逐号码访问数据库;正式实现不得使用 Mock、静态数组或浏览器 localStorage。
|
||||
|
||||
## 客户端工作台与短信发送体验完善(2026-07-30)
|
||||
|
||||
- 客户端短信服务工作台的账户状态必须基于当前企业真实认证记录展示“已认证”或“未认证”,不得使用账户启停状态代替认证状态;企业主体展示真实企业名称。签名数量统计当前企业未删除、未禁用的真实签名。
|
||||
- 模板状态和签名状态分别展示当前企业真实待审核数量并可进入对应菜单;“服务提醒”改为“批量任务”,展示当前企业来源为客户端且状态为`pending_review`的真实批量任务数,并可进入批量任务菜单。
|
||||
- 客户端“今日发送趋势”复用真实 Dashboard 24 个北京时间小时桶,同时展示提交量和成功量;UTC 存储时间必须先按 UTC 解释再转换为`Asia/Shanghai`,不得依赖数据库或浏览器本地时区。
|
||||
- 签名与引流信息页点击“重置”时,即使筛选条件已经为空,也必须回到第一页并重新请求真实后端,以获取最新签名审核、报备和引流信息状态。
|
||||
- 运营端企业认证审核和短信模板审核首次打开及点击重置后,默认查询待审核状态。
|
||||
- 短信发送页的字数和预计条数必须随编辑后的实际短信内容即时重新计算;单条短信不超过70个Unicode字符计1条,长短信按每67个字符计费,预计条数为单号码计费条数乘有效号码数。单价单位显示为“元/条”。
|
||||
- 提交发送任务失败时使用页面中央弹窗展示真实后端错误;定时发送控件提供按北京时间计算的“今天”按钮,并以浅色背景标出北京时间当天。提交给后端的定时时间必须显式携带`+08:00`时区。
|
||||
- 提交任务成功后弹窗展示真实任务编号和发送号码数。“继续发送短信”清空当前发送表单和导入内容;“查看任务进度”进入批量任务页面并按任务编号定位本次任务。
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user