Files
go-sms-V2/web/mocks/handlers.ts
T

1061 lines
58 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */ // msw resolver 泛型放平(见 ok/fail 注释)
import { http, HttpResponse } from 'msw'
import type { LoginData } from '../src/api/types'
import type { SmsTemplate } from '../src/api/sms'
// ---- 模板种子(D20 模板管理;与后端 template_sms 状态机 0待审/1通过/-1拒绝 对齐) ----
let templateNextID = 4
const templateDB: SmsTemplate[] = [
{ id: 1, account_id: 1001, name: '验证码通知', content: '【店】您的验证码是{code},5 分钟内有效。', variables: 'code', status: 1, audit_at: '2026-09-10 10:00:00', reason: '' },
{ id: 2, account_id: 1001, name: '会员日营销', content: '【店】亲爱的{name},会员日全场 8 折,退订回T。', variables: 'name', status: 0, audit_at: null, reason: '' },
{ id: 3, account_id: 1001, name: '物流到达', content: '【店】您的订单{order}已到站,凭码{code}取件。', variables: 'order,code', status: -1, audit_at: '2026-09-09 15:00:00', reason: '变量过多,请精简' },
]
interface Account { password: string; user: LoginData['user'] }
const accounts: Record<string, Account> = {
admin: {
password: 'admin123',
user: { account_id: 1, username: 'admin', roles: ['admin'], permissions: ['*'] },
},
customer: {
password: '123456',
user: { account_id: 1001, username: 'customer', roles: ['customer'], permissions: ['message:write', 'stats:read'] },
},
}
function ok<T>(data: T): HttpResponse<any> {
// 非泛型返回:msw v2 resolver 泛型对 HttpResponse<ApiResp<T>> 严格不兼容
// (曾用 ApiResp<never> 万配吞掉 37 处下游错),放平为基类让调用处推断。
return HttpResponse.json({ code: 'ISC:000', msg: '成功', data })
}
function fail(code: string, msg: string, status?: number): HttpResponse<any> {
return HttpResponse.json({ code, msg, data: null }, { status })
}
// ---- 账号资源(内存模拟 DB,与后端 Day 21+ 契约对齐) ----
export interface MockAccount {
id: number
username: string
real_name: string
role: string
status: number
business: number
balance: number
credit_balance: number
created_at: string
}
const accountDB: MockAccount[] = [
{ id: 1, username: 'admin', real_name: '平台管理员', role: 'admin', status: 1, business: 63, balance: 99999, credit_balance: 0, created_at: '2026-01-01 10:00:00' },
{ id: 1001, username: 'customer', real_name: '示例客户', role: 'customer', status: 1, business: 1, balance: 5000, credit_balance: 1000, created_at: '2026-03-15 14:20:00' },
{ id: 1002, username: 'vip-shop', real_name: '优选商城', role: 'customer', status: 1, business: 5, balance: 1200, credit_balance: 500, created_at: '2026-05-02 09:11:00' } as MockAccount,
{ id: 1003, username: 'old-user', real_name: '沉默账号', role: 'customer', status: 0, business: 1, balance: 0, credit_balance: 0, created_at: '2025-12-01 08:00:00' },
]
let nextID = 2000
const balanceLogs = [
{ id: 1, account_id: 1001, biz_type: 'credit', amount: 1000, balance_after: 5000, operator: 'admin', remark: '开户授信', created_at: '2026-03-15 14:20:00' },
{ id: 2, account_id: 1001, biz_type: 'recharge', amount: 5000, balance_after: 5000, operator: 'admin', remark: '首次充值', created_at: '2026-03-16 10:00:00' },
{ id: 3, account_id: 1001, biz_type: 'deduct', amount: -120, balance_after: 4880, operator: '-', remark: '发送扣费', created_at: '2026-03-17 12:30:00' },
]
const roleList = [
{ code: 'admin', name: '管理员', is_built_in: 1, permissions: ['*'] },
{ code: 'ops', name: '客户运维', is_built_in: 1, permissions: ['account:write', 'channel:write', 'message:write', 'audit:write'] },
{ code: 'service', name: '客服', is_built_in: 1, permissions: ['account:read', 'message:read', 'stats:read'] },
{ code: 'group', name: '集团', is_built_in: 1, permissions: ['account:read', 'message:write'] },
{ code: 'customer', name: '客户', is_built_in: 1, permissions: ['message:write', 'stats:read'] },
]
const loginAudit = [
{ id: 1, username: 'admin', ip: '192.168.1.10', ok: 1, login_at: '2026-09-03 08:30:00' },
{ id: 2, username: 'customer', ip: '10.20.30.40', ok: 1, login_at: '2026-09-03 09:12:00' },
{ id: 3, username: 'hacker', ip: '172.16.0.9', ok: 0, fail_reason: '密码错误(3/5)', login_at: '2026-09-03 09:15:00' },
]
// ---- 上家资源(D11;与后端 ChannelUpstream 实体契约对齐) ----
export interface MockUpstream {
id: number
name: string
contact: string
phone: string
category: string
status: number
remark: string
}
const upstreamDB: MockUpstream[] = [
{ id: 1, name: '移动集团直连', contact: '王经理', phone: '13800001001', category: '运营商直连', status: 1, remark: 'CMPP 2.0' },
{ id: 2, name: '联信第三方', contact: '李工', phone: '021-66881002', category: '第三方通道', status: 1, remark: 'HTTP 通道' },
{ id: 3, name: '电信福建', contact: '陈经理', phone: '13900001003', category: '运营商直连', status: 0, remark: 'SGIP' },
]
let upstreamNextID = 100
// ---- 通道/组/策略/报备资源(D12-D16;契约对齐后端阶段 3) ----
interface MockChannel {
id: number
name: string
code: string
protocol: 'cmpp' | 'http' | 'sgip' | 'smpp'
upstream_id: number
upstream_name?: string
host: string
port: number
username: string
password?: string
speed: number
conn_count: number
status: number
is_default: number
priority: number
weight: number
day_limit: number
night_limit: number
sign_mode: number
ext_length: number
black_keywords: string
block_regions: string
template_mode: number
remark: string
created_at: string
// Day 31 扩展:协议接入参数
sp_id?: string
protocol_version?: number
heartbeat_interval?: number
reconnect_max?: number
service_id?: string
// Day 31 扩展:运营属性
carrier?: string
billing_length?: number
payment_type?: string
billing_mode?: string
price?: number
category?: string
mo_forward_channel_id?: number
number_rule?: number
code_truncate?: number
ext_params?: string
service_remark?: string
}
const channelDB: MockChannel[] = [
{ id: 1, name: '移动全国', code: 'CM-001', protocol: 'cmpp', upstream_id: 1, upstream_name: '移动集团直连', host: '10.0.1.10', port: 7890, username: 'go-sms', password: 'pw-cm-001', speed: 500, conn_count: 4, status: 1, is_default: 1, priority: 10, weight: 7, day_limit: 1000000, night_limit: 100, sign_mode: 0, ext_length: 8, black_keywords: '', block_regions: '新疆,西藏', template_mode: 0, remark: '主力通道', created_at: '2026-06-01 09:00:00', sp_id: '901234', protocol_version: 20, heartbeat_interval: 30, reconnect_max: 30, service_id: 'SVC01', carrier: 'cmcc', billing_length: 70, payment_type: 'prepay_monthly', billing_mode: 'success_unknown', price: 0.045, category: '验证码', mo_forward_channel_id: 0, number_rule: 0, code_truncate: 0, ext_params: '', service_remark: '移动直连,故障联系张经理' },
{ id: 2, name: '联信HTTP', code: 'HX-201', protocol: 'http', upstream_id: 2, upstream_name: '联信第三方', host: 'https://api.lianxin.cn/sms', port: 443, username: 'hxuser', password: 'pw-hx-201', speed: 200, conn_count: 2, status: 1, is_default: 0, priority: 5, weight: 3, day_limit: 200000, night_limit: 0, sign_mode: 1, ext_length: 0, black_keywords: '发票,代开', block_regions: '', template_mode: 1, remark: '', created_at: '2026-06-12 14:30:00', sp_id: '', protocol_version: 0, heartbeat_interval: 30, reconnect_max: 30, service_id: '', carrier: 'cmcc,cucc,ctcc', billing_length: 67, payment_type: 'prepay_realtime', billing_mode: 'success', price: 0.05, category: '营销', mo_forward_channel_id: 1, number_rule: 1, code_truncate: 3, ext_params: 'timeout=5', service_remark: '' },
{ id: 3, name: '电信SGIP', code: 'DX-301', protocol: 'sgip', upstream_id: 3, upstream_name: '电信福建', host: '10.0.3.10', port: 8801, username: 'sp001', password: 'pw-dx-301', speed: 300, conn_count: 2, status: 0, is_default: 0, priority: 3, weight: 1, day_limit: 0, night_limit: 0, sign_mode: 0, ext_length: 6, black_keywords: '', block_regions: '', template_mode: 0, remark: '停用备用', created_at: '2026-07-01 10:00:00', sp_id: '12345', protocol_version: 12, heartbeat_interval: 60, reconnect_max: 60, service_id: '', carrier: 'ctcc', billing_length: 70, payment_type: 'postpaid_monthly', billing_mode: 'success_unknown', price: 0.038, category: '通知', mo_forward_channel_id: 0, number_rule: 2, code_truncate: 0, ext_params: '', service_remark: '' },
]
let channelNextID = 100
interface MockGroupItem {
id: number
group_id: number
channel_id: number
channel_name?: string
step: 1 | 2 | 3 | 4
priority: number
weight: number
region: string
carrier: string
keyword: string
}
interface MockGroup {
id: number
name: string
remark: string
status: number
items: MockGroupItem[]
created_at: string
}
const groupDB: MockGroup[] = [
{
id: 1, name: '主路由组', remark: '全国短信', status: 1, created_at: '2026-06-20 09:00:00',
items: [
{ id: 1, group_id: 1, channel_id: 1, step: 3, priority: 0, weight: 7, region: '', carrier: '', keyword: '' },
{ id: 2, group_id: 1, channel_id: 2, step: 3, priority: 0, weight: 3, region: '', carrier: '', keyword: '' },
{ id: 3, group_id: 1, channel_id: 1, step: 4, priority: 1, weight: 0, region: '', carrier: '', keyword: '' },
],
},
]
let groupItemNextID = 100
function chanName(id: number): string {
return channelDB.find((c) => c.id === id)?.name ?? `通道#${id}`
}
const blacklistDB = [
{ id: 1, mobile: '13700000001', account_id: 0, source: 1, operator: 'admin', created_at: '2026-06-01 10:00:00' },
{ id: 2, mobile: '13700000002', account_id: 0, source: 2, operator: '-', created_at: '2026-06-03 11:00:00' },
]
let blNext = 100
const whitelistDB = [
{ id: 1, mobile: '13800000001', account_id: 1001, source: 1, operator: 'admin', created_at: '2026-06-05 09:00:00' },
]
let wlNext = 100
const keywordDB = [
{ id: 1, word: '发票', level: 1, status: 1, operator: 'admin', created_at: '2026-05-01 09:00:00' },
{ id: 2, word: '贷款', level: 2, status: 1, operator: 'admin', created_at: '2026-05-01 09:05:00' },
{ id: 3, word: '验证码', level: 3, status: 1, operator: 'admin', created_at: '2026-05-02 10:00:00' },
]
let kwNext = 100
const freqDB = [
{ id: 1, account_id: 0, dim: 1, window_unit: 1, max_count: 10, status: 1, created_at: '2026-05-10 09:00:00' },
{ id: 2, account_id: 0, dim: 2, window_unit: 2, max_count: 5, status: 1, created_at: '2026-05-11 09:00:00' },
]
let freqNext = 100
const blockedDB = [
{ id: 1, channel_id: 1, code: '10657_BAD01', remark: '投诉码号', created_at: '2026-06-01 09:00:00' },
]
let bcNext = 100
const routeRuleDB = [
{ id: 1, account_id: 0, channel_id: 2, channel_name: '联信HTTP', rule_type: 'keyword', rule_config: 'VIP', priority: 100, status: 1, created_at: '2026-06-15 09:00:00' },
{ id: 2, account_id: 0, channel_id: 1, channel_name: '移动全国', rule_type: 'region', rule_config: '北京,上海', priority: 50, status: 1, created_at: '2026-06-16 09:00:00' },
]
let rrNext = 100
const reportDB = [
{ id: 1, type: 'sign', content: '【优选商城】', account_id: 1001, status: 1, operator: 'admin', created_at: '2026-06-18 09:00:00' },
{ id: 2, type: 'code', content: '10690001', account_id: 1001, status: 0, operator: '-', created_at: '2026-06-19 09:00:00' },
]
let repNext = 100
// 发送任务(D19;1=定时待发可改期/取消,2=群发待发仅取消,3=定时已完成,4=个性发送中)
const sendTaskDB = [
{ id: 1, task_no: 'T20260911-0001', account_id: 1001, send_type: 3, content: '【优选商城】会员日 5 折,明早 10 点开抢,拒收请回复R', sign: '优选商城', mobile_count: 3200, success_count: 0, fail_count: 0, fee_total: 32, audit_status: 1, status: 0, schedule_at: '2026-09-12 10:00', created_at: '2026-09-11 09:00:00' },
{ id: 2, task_no: 'T20260911-0002', account_id: 1001, send_type: 1, content: '【优选商城】周末大促全场满 300 减 50,拒收请回复R', sign: '优选商城', mobile_count: 8600, success_count: 0, fail_count: 0, fee_total: 86, audit_status: 0, status: 0, schedule_at: null, created_at: '2026-09-11 10:30:00' },
{ id: 3, task_no: 'T20260910-0003', account_id: 1001, send_type: 3, content: '【优选商城】签到有礼连续 7 天领 10 元券,拒收请回复R', sign: '优选商城', mobile_count: 1500, success_count: 1500, fail_count: 0, fee_total: 15, audit_status: 1, status: 2, schedule_at: '2026-09-10 08:00', created_at: '2026-09-09 18:00:00' },
{ id: 4, task_no: 'T20260911-0004', account_id: 1001, send_type: 2, content: '【优选商城】您关注的商品已降价,拒收请回复R', sign: '优选商城', mobile_count: 500, success_count: 320, fail_count: 12, fee_total: 5, audit_status: 3, status: 1, schedule_at: null, created_at: '2026-09-11 11:00:00' },
{ id: 5, task_no: 'T20260909-0005', account_id: 1002, send_type: 1, content: '【本地生活】新客立减 15 元,拒收请回复R', sign: '本地生活', mobile_count: 2100, success_count: 0, fail_count: 0, fee_total: 21, audit_status: 2, status: 0, schedule_at: null, created_at: '2026-09-09 14:00:00' },
{ id: 6, task_no: 'T20260908-0006', account_id: 1002, send_type: 3, content: '【本地生活】中秋礼盒预售定金翻倍,拒收请回复R', sign: '本地生活', mobile_count: 900, success_count: 0, fail_count: 0, fee_total: 9, audit_status: 4, status: 0, schedule_at: '2026-09-10 09:00', created_at: '2026-09-08 09:00:00' },
{ id: 7, task_no: 'T20260909-0007', account_id: 1002, send_type: 1, content: '【本地生活】老带新双方各得 20 元券,拒收请回复R', sign: '本地生活', mobile_count: 1300, success_count: 0, fail_count: 0, fee_total: 13, audit_status: 0, status: 0, schedule_at: null, created_at: '2026-09-09 08:00:00' },
]
let submitNextID = 100 // /send/submit mock 自增任务 ID
// Day 46/D22:任务明细种子(task_id=4 个性任务——状态/错误码/扩展码/回传数据多样化,
// 供结果反馈页逐号核对与 CSV 导出验收)。
const sendDetailDB = [
{ id: 9001, task_id: 4, account_id: 1001, mobile: '13800000001', content: '【优选商城】您关注的商品已降价 30 元,拒收请回复R', province: '广东', carrier: '移动', status: 2, error_code: '', ext_code: '6688', call_data: 'order-1001', fee: 1, created_at: '2026-09-11 11:00:01' },
{ id: 9002, task_id: 4, account_id: 1001, mobile: '13800000002', content: '【优选商城】您关注的商品已降价 50 元,拒收请回复R', province: '浙江', carrier: '联通', status: 3, error_code: 'ISC:007', ext_code: '6688', call_data: 'order-1002', fee: 1, created_at: '2026-09-11 11:00:01' },
{ id: 9003, task_id: 4, account_id: 1001, mobile: '13800000003', content: '【优选商城】您关注的商品已降价 10 元,拒收请回复R', province: '北京', carrier: '移动', status: 5, error_code: 'ISC:006', ext_code: '6688', call_data: 'order-1003', fee: 0, created_at: '2026-09-11 11:00:01' },
{ id: 9004, task_id: 4, account_id: 1001, mobile: '13800000004', content: '【优选商城】您关注的商品已降价 20 元,拒收请回复R', province: '上海', carrier: '电信', status: 4, error_code: 'NO_ROUTE', ext_code: '6688', call_data: 'order-1004', fee: 1, created_at: '2026-09-11 11:00:01' },
{ id: 9005, task_id: 4, account_id: 1001, mobile: '13800000005', content: '【优选商城】您关注的商品已降价 8 元,拒收请回复R', province: '江苏', carrier: '移动', status: 1, error_code: '', ext_code: '6689', call_data: '', fee: 1, created_at: '2026-09-11 11:00:02' },
// Day46/W5 修复循环:5→10 条(六状态全覆盖),演示 page_size 切 5/10 的真实翻页
{ id: 9006, task_id: 4, account_id: 1001, mobile: '13800000006', content: '【优选商城】您关注的商品已降价 6 元,拒收请回复R', province: '上海', carrier: '联通', status: 0, error_code: '', ext_code: '6689', call_data: '', fee: 1, created_at: '2026-09-11 11:00:03' },
{ id: 9007, task_id: 4, account_id: 1001, mobile: '13800000007', content: '【优选商城】您关注的商品已降价 7 元,拒收请回复R', province: '广东', carrier: '电信', status: 1, error_code: '', ext_code: '6689', call_data: '', fee: 1, created_at: '2026-09-11 11:00:03' },
{ id: 9008, task_id: 4, account_id: 1001, mobile: '13800000008', content: '【优选商城】您关注的商品已降价 9 元,拒收请回复R', province: '浙江', carrier: '移动', status: 2, error_code: '', ext_code: '6689', call_data: '', fee: 1, created_at: '2026-09-11 11:00:03' },
{ id: 9009, task_id: 4, account_id: 1001, mobile: '13800000009', content: '【优选商城】您关注的商品已降价 11 元,拒收请回复R', province: '北京', carrier: '联通', status: 2, error_code: '', ext_code: '6689', call_data: '', fee: 1, created_at: '2026-09-11 11:00:03' },
{ id: 9010, task_id: 4, account_id: 1001, mobile: '13800000010', content: '【优选商城】您关注的商品已降价 12 元,拒收请回复R', province: '上海', carrier: '移动', status: 2, error_code: '', ext_code: '6689', call_data: '', fee: 1, created_at: '2026-09-11 11:00:03' },
]
const delay = (ms: number) => new Promise((r) => setTimeout(r, ms))
// Day 62:api-config mock 模块态(PUT 后 GET 回读验证前端联动)。
const apiCfgState = {
report_url: '',
uplink_url: '',
speed_limit: 100,
ext_code: 'UT:0012',
cmpp_password: 'bc7eebbfa8cf33d2d8071b3077682b27',
cmpp_max_conns: 0,
cmpp_speed: 0,
}
// Day 63:账号通道绑定(channel-steer)模块态。
const steerState = new Map<number, { rule_id: number; channel_id: number }>()
let steerRuleSeq = 100
export const handlers = [
http.post('*/api/v1/auth/login', async ({ request }) => {
const body = (await request.json()) as { username: string; password: string }
const acc = accounts[body.username]
if (!acc || acc.password !== body.password) {
return fail('ISC:401', '未认证', 401)
}
return ok<LoginData>({ token: `mock-token-${acc.user.username}-${Date.now()}`, user: acc.user })
}),
http.get('*/api/v1/it/biz-error', () => fail('ISC:006', '黑名单')),
// 账号列表(分页 + username/role/status 过滤)
// Day46/W6 修复循环:账号详情(账号+业务配置)——前端 AccountDetail 原本地硬编码 audit_mode:0,
// 改接本端点(与后端 GET /accounts/:id 契约对齐);audit_mode 0免审/1人工审核/2自动审核(黑词)。
http.get('*/api/v1/accounts/:id', ({ params }) => {
const acc = accountDB.find((a) => a.id === Number(params.id))
if (!acc) return fail('ISC:404', '账号不存在', 404)
const biz = [
{ bit: 1, code: 'sms', label: '国内短信' },
{ bit: 2, code: 'intl', label: '国际短信' },
{ bit: 4, code: 'video', label: '视频短信' },
{ bit: 8, code: 'csp', label: 'CSP 5G' },
{ bit: 16, code: 'nullfilter', label: '空号过滤' },
{ bit: 32, code: 'shortlink', label: '短链' },
]
const modes: Record<string, number> = { sms: 2, intl: 1, video: 2 } // 1001(仅 sms)演示「自动审核(黑词)」
const configs = biz.filter((b) => acc.business & b.bit).map((b) => ({
account_id: acc.id,
business: b.code,
protocol: 'http',
audit_mode: modes[b.code] ?? 0,
}))
return ok({ account: acc, configs })
}),
// Day 62:外部 API 配置(CMPP 密码/账号级配额/交付块;模块态支持 PUT 回读验证)。
http.get('*/api/v1/accounts/:id/api-config', () =>
ok({
account_id: 0,
business: 'sms',
...apiCfgState,
cmpp_max_conns_effective: apiCfgState.cmpp_max_conns || 50,
cmpp_speed_effective: apiCfgState.cmpp_speed || 50,
secret_issued: true,
secret_fingerprint: apiCfgState.cmpp_password.slice(0, 8),
cmpp_access: { port: '7890', version: 'CMPP 2.0', default_max_conns: 50, default_speed: 50 },
}),
),
http.put('*/api/v1/accounts/:id/api-config', async ({ request }) => {
const body = (await request.json()) as {
report_url?: string; uplink_url?: string; speed_limit?: number; ext_code?: string
reset_secret?: boolean; custom_secret?: string; cmpp_max_conns?: number; cmpp_speed?: number
}
// 配额:0=不修改;-1=恢复默认(置 0);正数=设置。
for (const [k, v] of [['cmpp_max_conns', body.cmpp_max_conns], ['cmpp_speed', body.cmpp_speed]] as const) {
if (v === -1) apiCfgState[k] = 0
else if (v && v > 0) apiCfgState[k] = v
}
let result = { secret: '', cmpp_password: '' }
const plain = body.custom_secret || (body.reset_secret ? 'newsecret32hexdemo00000000000' : '')
if (plain) {
// 演示用伪 MD5(真实后端为 MD5(明文);mock 不引 crypto 依赖)。
apiCfgState.cmpp_password = 'f' + plain.slice(0, 31).padEnd(31, '0')
result = { secret: plain, cmpp_password: apiCfgState.cmpp_password }
}
return ok(result)
}),
// Day 63:账号通道绑定(channel-steer;模块态支持绑定/切换/解绑回读验证)。
http.get('*/api/v1/accounts/:id/channel-steer', ({ params }) => {
const id = Number(params.id)
const st = steerState.get(id)
if (!st) {
return ok({ account_id: id, rule_id: 0, channel_id: 0, channel_name: '', channel_code: '', channel_status: 0 })
}
const ch = channelDB.find((c) => c.id === st.channel_id)
return ok({
account_id: id, rule_id: st.rule_id, channel_id: st.channel_id,
channel_name: ch?.name ?? '通道不存在/已删除',
channel_code: ch?.code ?? '', channel_status: ch?.status ?? 0,
})
}),
http.put('*/api/v1/accounts/:id/channel-steer', async ({ request, params }) => {
const id = Number(params.id)
const body = (await request.json()) as { channel_id?: number }
const cid = body.channel_id ?? -1
if (cid < 0) return fail('ISC:400', 'channel_id 须为非负整数', 400)
if (cid > 0) {
const ch = channelDB.find((c) => c.id === cid)
if (!ch) return fail('ISC:404', '通道不存在', 404)
if (ch.status !== 1) return fail('ISC:400', '通道已停用', 400)
const rule = { rule_id: ++steerRuleSeq, channel_id: cid }
steerState.set(id, rule)
return ok({ account_id: id, rule_id: rule.rule_id, channel_id: cid })
}
steerState.delete(id)
return ok({ account_id: id, rule_id: 0 })
}),
http.get('*/api/v1/accounts', async ({ request }) => {
await delay(120)
const url = new URL(request.url)
const page = Number(url.searchParams.get('page') ?? 1)
const size = Number(url.searchParams.get('page_size') ?? 10)
const username = url.searchParams.get('username') ?? ''
const role = url.searchParams.get('role') ?? ''
const status = url.searchParams.get('status') ?? ''
let rows = accountDB.filter(
(a) =>
(!username || a.username.includes(username)) &&
(!role || a.role === role) &&
(!status || String(a.status) === status),
)
const total = rows.length
rows = rows.slice((page - 1) * size, page * size)
return ok({ list: rows, total })
}),
// 开户(业务位掩码)
http.post('*/api/v1/accounts', async ({ request }) => {
const body = (await request.json()) as Partial<MockAccount> & { password: string; business: number }
if (!body.username || !body.password || !body.role || !body.business) {
return fail('ISC:400', '参数错误: username/password/role/business 必填')
}
if (accountDB.some((a) => a.username === body.username)) {
return fail('ISC:400', `用户名 ${body.username} 已存在`)
}
const acc: MockAccount = {
id: nextID++, username: body.username, real_name: body.real_name ?? '', role: body.role,
status: 1, business: body.business, balance: 0, credit_balance: body.credit_balance ?? 0,
created_at: new Date().toISOString().slice(0, 19).replace('T', ' '),
}
accountDB.push(acc)
return ok({ id: acc.id, username: acc.username })
}),
// 更新
http.put('*/api/v1/accounts/:id', async ({ params, request }) => {
const id = Number(params.id)
const acc = accountDB.find((a) => a.id === id)
if (!acc) return fail('ISC:404', '资源不存在', 404)
const body = (await request.json()) as Partial<MockAccount>
Object.assign(acc, body)
return ok(acc)
}),
// 状态切换
http.put('*/api/v1/accounts/:id/status', async ({ params, request }) => {
const id = Number(params.id)
const acc = accountDB.find((a) => a.id === id)
if (!acc) return fail('ISC:404', '资源不存在', 404)
const body = (await request.json()) as { status: number }
acc.status = body.status
return ok(acc)
}),
// 删除(有发送记录拒绝:示例中 balance≠0 视为活跃)
http.delete('*/api/v1/accounts/:id', ({ params }) => {
const id = Number(params.id)
const idx = accountDB.findIndex((a) => a.id === id)
if (idx < 0) return fail('ISC:404', '资源不存在', 404)
if (accountDB[idx].balance > 0) {
return fail('ISC:032', '发送限制: 活跃账号不可删除(沉默或 60 天未发送可删)')
}
accountDB.splice(idx, 1)
return ok({ id })
}),
// 充值(余额累加 + 流水)
http.post('*/api/v1/accounts/:id/recharge', async ({ params, request }) => {
const id = Number(params.id)
const acc = accountDB.find((a) => a.id === id)
if (!acc) return fail('ISC:404', '资源不存在', 404)
// Issue#3:契约对齐真实后端 rechargeReq{amount, remark}(amount>0 必填)
const body = (await request.json()) as { amount: number; remark: string }
if (!body.amount || body.amount <= 0) return fail('ISC:400', '充值条数必须大于 0')
acc.balance += body.amount
balanceLogs.push({
id: balanceLogs.length + 1, account_id: id, biz_type: 'recharge', amount: body.amount,
balance_after: acc.balance, operator: 'admin', remark: body.remark || '后台充值',
created_at: new Date().toISOString().slice(0, 19).replace('T', ' '),
})
return ok({ balance: acc.balance })
}),
// 余额流水
http.get('*/api/v1/accounts/:id/balance_logs', ({ params }) => {
const id = Number(params.id)
return ok({ list: balanceLogs.filter((l) => l.account_id === id), total: balanceLogs.filter((l) => l.account_id === id).length })
}),
// 角色与权限
http.get('*/api/v1/roles', () => ok({ list: roleList, total: roleList.length })),
// 登录审计
http.get('*/api/v1/audit/logins', ({ request }) => {
const url = new URL(request.url)
const username = url.searchParams.get('username') ?? ''
const rows = loginAudit.filter((l) => !username || l.username.includes(username))
return ok({ list: rows, total: rows.length })
}),
// ---- 上家 CRUD(D11) ----
http.get('*/api/v1/channels/upstreams', ({ request }) => {
const url = new URL(request.url)
const page = Number(url.searchParams.get('page') ?? 1)
const size = Number(url.searchParams.get('page_size') ?? 10)
const name = url.searchParams.get('name') ?? ''
const rows = upstreamDB.filter((u) => !name || u.name.includes(name))
const start = (page - 1) * size
return ok({ total: rows.length, list: rows.slice(start, start + size) })
}),
http.post('*/api/v1/channels/upstreams', async ({ request }) => {
const body = (await request.json()) as Partial<MockUpstream>
if (!body.name || !body.contact || !/^1\d{10}$|^0\d{2,3}-?\d{7,8}$/.test(body.phone ?? '')) {
return fail('ISC:400', '名称/联系人必填,电话格式不合法')
}
const created: MockUpstream = {
id: upstreamNextID++, name: body.name, contact: body.contact, phone: body.phone ?? '',
category: body.category ?? '第三方通道', status: 1, remark: body.remark ?? '',
}
upstreamDB.push(created)
return ok(created)
}),
http.put('*/api/v1/channels/upstreams/:id', async ({ request, params }) => {
const id = Number(params.id)
const body = (await request.json()) as Partial<MockUpstream>
const row = upstreamDB.find((u) => u.id === id)
if (!row) return fail('ISC:404', '上家不存在', 404)
if (body.phone && !/^1\d{10}$|^0\d{2,3}-?\d{7,8}$/.test(body.phone)) {
return fail('ISC:400', '电话格式不合法')
}
Object.assign(row, body)
return ok(row)
}),
http.delete('*/api/v1/channels/upstreams/:id', ({ params }) => {
const id = Number(params.id)
const idx = upstreamDB.findIndex((u) => u.id === id)
if (idx < 0) return fail('ISC:404', '上家不存在', 404)
upstreamDB.splice(idx, 1)
return ok({ id })
}),
// ---- 通道 CRUD(D12) ----
http.get('*/api/v1/channels', ({ request }) => {
const url = new URL(request.url)
const name = url.searchParams.get('name') ?? ''
const protocol = url.searchParams.get('protocol') ?? ''
const status = url.searchParams.get('status') ?? ''
const rows = channelDB.filter(
(c) => (!name || c.name.includes(name)) && (!protocol || c.protocol === protocol) && (!status || c.status === Number(status)),
)
return ok({ total: rows.length, list: rows })
}),
http.get('*/api/v1/channels/:id', ({ params }) => {
const ch = channelDB.find((c) => c.id === Number(params.id))
if (!ch) return fail('ISC:404', '通道不存在', 404)
return ok(ch)
}),
http.post('*/api/v1/channels', async ({ request }) => {
const body = (await request.json()) as Partial<MockChannel>
if (!body.name || !body.code || !body.host) return fail('ISC:400', '名称/通道号/地址必填')
if (channelDB.some((c) => c.code === body.code)) return fail('ISC:400', '通道编码已存在')
// Day 31:与真实后端对齐的校验(sp_id ≤6B / CMPP3.0 拒绝)
const spId = String(body.sp_id ?? '')
if (spId.length > 6) return fail('ISC:400', '企业代码(sp_id)不得超过 6 字节')
if (body.protocol === 'cmpp' && body.protocol_version === 30) {
return fail('ISC:400', 'CMPP 3.0 协议栈未实现(当前仅支持 2.0)')
}
const proto = body.protocol ?? 'http'
const defaultVersion = proto === 'cmpp' ? 20 : proto === 'sgip' ? 12 : proto === 'smpp' ? 34 : 0
const created: MockChannel = {
id: channelNextID++, name: body.name, code: body.code, protocol: proto,
upstream_id: body.upstream_id ?? 0, host: body.host, port: body.port ?? 7890,
username: body.username ?? '', speed: body.speed ?? 100, conn_count: body.conn_count ?? 1,
status: 1, is_default: body.is_default ?? 0, priority: body.priority ?? 0, weight: body.weight ?? 1,
day_limit: body.day_limit ?? 0, night_limit: body.night_limit ?? 0, sign_mode: body.sign_mode ?? 0,
ext_length: body.ext_length ?? 0, black_keywords: body.black_keywords ?? '',
block_regions: body.block_regions ?? '', template_mode: body.template_mode ?? 0,
remark: body.remark ?? '', created_at: new Date().toISOString().slice(0, 19).replace('T', ' '),
sp_id: spId, protocol_version: body.protocol_version ?? defaultVersion,
heartbeat_interval: body.heartbeat_interval ?? 30, reconnect_max: body.reconnect_max ?? 30,
service_id: body.service_id ?? '',
carrier: body.carrier ?? '', billing_length: body.billing_length ?? 70,
payment_type: body.payment_type ?? '', billing_mode: body.billing_mode ?? '',
price: body.price ?? 0, category: body.category ?? '',
mo_forward_channel_id: body.mo_forward_channel_id ?? 0, number_rule: body.number_rule ?? 0,
code_truncate: body.code_truncate ?? 0, ext_params: body.ext_params ?? '',
service_remark: body.service_remark ?? '',
}
channelDB.push(created)
return ok(created)
}),
http.put('*/api/v1/channels/:id', async ({ request, params }) => {
const ch = channelDB.find((c) => c.id === Number(params.id))
if (!ch) return fail('ISC:404', '通道不存在', 404)
Object.assign(ch, (await request.json()) as Partial<MockChannel>)
return ok(ch)
}),
http.delete('*/api/v1/channels/:id', ({ params }) => {
const id = Number(params.id)
const ch = channelDB.find((c) => c.id === id)
if (!ch) return fail('ISC:404', '通道不存在', 404)
if (ch.status === 1) return fail('ISC:400', '通道启用中,须先停用再删除')
channelDB.splice(channelDB.indexOf(ch), 1)
return ok({ id })
}),
http.post('*/api/v1/channels/:id/test', ({ params }) => {
const ch = channelDB.find((c) => c.id === Number(params.id))
if (!ch) return fail('ISC:404', '通道不存在', 404)
if (ch.status !== 1) return fail('ISC:400', '通道已停用,无法测试')
return ok({ ok: true, latency_ms: 42, message: `连通正常(${ch.protocol.toUpperCase()}) msg_id=${Date.now() % 100000}` })
}),
// ---- Day 39:链路状态/回执复核 ----
http.get('*/api/v1/channels/:id/link-status', ({ params }) => {
const ch = channelDB.find((c) => c.id === Number(params.id))
if (!ch) return fail('ISC:404', '通道不存在', 404)
if (ch.protocol !== 'cmpp' || ch.status !== 1)
return ok({ channel_id: ch.id, running: false, total: 0, healthy: 0 })
return ok({ channel_id: ch.id, running: true, total: ch.conn_count ?? 2, healthy: ch.conn_count ?? 2, started_at: new Date(Date.now() - 3600_000).toISOString().slice(0, 19).replace('T', ' ') })
}),
http.get('*/api/v1/channels/:id/receipts', ({ params }) => {
const ch = channelDB.find((c) => c.id === Number(params.id))
if (!ch) return fail('ISC:404', '通道不存在', 404)
const t = (off: number) => new Date(Date.now() - off * 60_000).toISOString().slice(0, 19).replace('T', ' ')
return ok({
channel_id: ch.id,
total: 3,
list: [
{ channel_id: ch.id, msg_id: `${Date.now() % 1000000}`, is_report: true, stat: 'DELIVRD', submit_time: '0910113021', done_time: '0910113029', dest: '13800001111', at: t(1) },
{ channel_id: ch.id, msg_id: `${(Date.now() - 1) % 1000000}`, is_report: true, stat: 'UNDELIV', submit_time: '0910112810', done_time: '0910112902', dest: '13900002222', at: t(4) },
{ channel_id: ch.id, msg_id: `${(Date.now() - 2) % 1000000}`, is_report: false, src: '13700003333', content: 'TD', at: t(9) },
],
})
}),
// ---- 通道组(D14) ----
http.get('*/api/v1/channel-groups', () => {
return ok({ total: groupDB.length, list: groupDB.map((g) => ({ ...g, items: g.items.map((i) => ({ ...i, channel_name: chanName(i.channel_id) })) })) })
}),
http.post('*/api/v1/channel-groups', async ({ request }) => {
const body = (await request.json()) as { name: string; remark?: string }
if (!body.name) return fail('ISC:400', '名称必填')
const g: MockGroup = { id: Date.now() % 100000, name: body.name, remark: body.remark ?? '', status: 1, items: [], created_at: new Date().toISOString().slice(0, 19).replace('T', ' ') }
groupDB.push(g)
return ok(g)
}),
http.delete('*/api/v1/channel-groups/:id', ({ params }) => {
const g = groupDB.find((x) => x.id === Number(params.id))
if (!g) return fail('ISC:404', '组不存在', 404)
if (g.items.length > 0) return fail('ISC:400', `组内仍有 ${g.items.length} 个成员,须先移除`)
groupDB.splice(groupDB.indexOf(g), 1)
return ok({ id: g.id })
}),
http.post('*/api/v1/channel-groups/:id/items', async ({ request, params }) => {
const g = groupDB.find((x) => x.id === Number(params.id))
if (!g) return fail('ISC:404', '组不存在', 404)
const body = (await request.json()) as Partial<MockGroupItem>
if (!body.channel_id) return fail('ISC:400', '请选择通道')
if (g.items.some((i) => i.channel_id === body.channel_id)) return fail('ISC:400', '该通道已在组内')
if (body.step === 3) {
if (!body.weight || body.weight < 1 || body.weight > 100) return fail('ISC:400', '权重须为 1-100')
const sum = g.items.filter((i) => i.step === 3).reduce((a, i) => a + i.weight, 0) + body.weight
if (sum > 100) return fail('ISC:400', `权重和将达 ${sum}%(>100%),拒绝添加`)
}
const it: MockGroupItem = {
id: groupItemNextID++, group_id: g.id, channel_id: body.channel_id, step: body.step ?? 3,
priority: body.priority ?? 0, weight: body.weight ?? 0, region: body.region ?? '',
carrier: body.carrier ?? '', keyword: body.keyword ?? '',
}
g.items.push(it)
return ok({ ...it, channel_name: chanName(it.channel_id) })
}),
http.put('*/api/v1/channel-groups/:id/items/:itemId', async ({ request, params }) => {
const g = groupDB.find((x) => x.id === Number(params.id))
const it = g?.items.find((i) => i.id === Number(params.itemId))
if (!g || !it) return fail('ISC:404', '成员不存在', 404)
Object.assign(it, (await request.json()) as Partial<MockGroupItem>)
return ok({ ...it, channel_name: chanName(it.channel_id) })
}),
http.delete('*/api/v1/channel-groups/:id/items/:itemId', ({ params }) => {
const g = groupDB.find((x) => x.id === Number(params.id))
const idx = g?.items.findIndex((i) => i.id === Number(params.itemId)) ?? -1
if (!g || idx < 0) return fail('ISC:404', '成员不存在', 404)
g.items.splice(idx, 1)
return ok({ id: Number(params.itemId) })
}),
// ---- 策略中心(D15) ----
http.get('*/api/v1/policies/blacklist', ({ request }) => {
const url = new URL(request.url)
const mobile = url.searchParams.get('mobile') ?? ''
const rows = blacklistDB.filter((b) => !mobile || b.mobile.includes(mobile))
return ok({ total: rows.length, list: rows })
}),
http.post('*/api/v1/policies/blacklist', async ({ request }) => {
const body = (await request.json()) as { mobile: string }
if (!/^1\d{10}$/.test(body.mobile ?? '')) return fail('ISC:400', '手机号格式不合法')
if (blacklistDB.some((b) => b.mobile === body.mobile)) return fail('ISC:400', '已在黑名单')
const row = { id: blNext++, mobile: body.mobile, account_id: 0, source: 1, operator: 'admin', created_at: new Date().toISOString().slice(0, 19).replace('T', ' ') }
blacklistDB.push(row)
return ok(row)
}),
http.post('*/api/v1/policies/blacklist/import', async ({ request }) => {
const body = (await request.json()) as { mobiles: string[] }
let imported = 0
for (const m of body.mobiles ?? []) {
if (/^1\d{10}$/.test(m) && !blacklistDB.some((b) => b.mobile === m)) {
blacklistDB.push({ id: blNext++, mobile: m, account_id: 0, source: 1, operator: 'admin', created_at: new Date().toISOString().slice(0, 19).replace('T', ' ') })
imported++
}
}
return ok({ imported })
}),
http.delete('*/api/v1/policies/blacklist/:id', ({ params }) => {
const idx = blacklistDB.findIndex((b) => b.id === Number(params.id))
if (idx < 0) return fail('ISC:404', '不存在', 404)
blacklistDB.splice(idx, 1)
return ok({ id: Number(params.id) })
}),
http.get('*/api/v1/policies/whitelist', () => ok({ total: whitelistDB.length, list: whitelistDB })),
http.post('*/api/v1/policies/whitelist', async ({ request }) => {
const body = (await request.json()) as { mobile: string }
if (!/^1\d{10}$/.test(body.mobile ?? '')) return fail('ISC:400', '手机号格式不合法')
const row = { id: wlNext++, mobile: body.mobile, account_id: 0, source: 1, operator: 'admin', created_at: new Date().toISOString().slice(0, 19).replace('T', ' ') }
whitelistDB.push(row)
return ok(row)
}),
http.delete('*/api/v1/policies/whitelist/:id', ({ params }) => {
const idx = whitelistDB.findIndex((b) => b.id === Number(params.id))
if (idx < 0) return fail('ISC:404', '不存在', 404)
whitelistDB.splice(idx, 1)
return ok({ id: Number(params.id) })
}),
http.get('*/api/v1/policies/keywords', ({ request }) => {
const url = new URL(request.url)
const level = url.searchParams.get('level') ?? ''
const rows = keywordDB.filter((k) => !level || k.level === Number(level))
return ok({ total: rows.length, list: rows })
}),
http.post('*/api/v1/policies/keywords', async ({ request }) => {
const body = (await request.json()) as { word: string; level: number }
if (!body.word) return fail('ISC:400', '关键字必填')
const row = { id: kwNext++, word: body.word, level: body.level ?? 1, status: 1, operator: 'admin', created_at: new Date().toISOString().slice(0, 19).replace('T', ' ') }
keywordDB.push(row)
return ok(row)
}),
http.delete('*/api/v1/policies/keywords/:id', ({ params }) => {
const idx = keywordDB.findIndex((k) => k.id === Number(params.id))
if (idx < 0) return fail('ISC:404', '不存在', 404)
keywordDB.splice(idx, 1)
return ok({ id: Number(params.id) })
}),
http.get('*/api/v1/policies/frequencies', () => ok({ total: freqDB.length, list: freqDB })),
http.post('*/api/v1/policies/frequencies', async ({ request }) => {
const body = (await request.json()) as Partial<{ dim: number; window_unit: number; max_count: number }>
if (!body.max_count || body.max_count < 1) return fail('ISC:400', '最大条数须 ≥1')
const row = { id: freqNext++, account_id: 0, dim: (body.dim ?? 1) as 1 | 2, window_unit: (body.window_unit ?? 1) as 1 | 2, max_count: body.max_count, status: 1, created_at: new Date().toISOString().slice(0, 19).replace('T', ' ') }
freqDB.push(row)
return ok(row)
}),
http.put('*/api/v1/policies/frequencies/:id', async ({ request, params }) => {
const row = freqDB.find((f) => f.id === Number(params.id))
if (!row) return fail('ISC:404', '不存在', 404)
Object.assign(row, (await request.json()) as Record<string, unknown>)
return ok(row)
}),
http.get('*/api/v1/policies/blocked-codes', () => ok({ total: blockedDB.length, list: blockedDB })),
http.post('*/api/v1/policies/blocked-codes', async ({ request }) => {
const body = (await request.json()) as { channel_id: number; code: string }
if (!body.channel_id || !body.code) return fail('ISC:400', '通道与码号必填')
const row = { id: bcNext++, channel_id: body.channel_id, code: body.code, remark: '', created_at: new Date().toISOString().slice(0, 19).replace('T', ' ') }
blockedDB.push(row)
return ok(row)
}),
http.delete('*/api/v1/policies/blocked-codes/:id', ({ params }) => {
const idx = blockedDB.findIndex((b) => b.id === Number(params.id))
if (idx < 0) return fail('ISC:404', '不存在', 404)
blockedDB.splice(idx, 1)
return ok({ id: Number(params.id) })
}),
http.get('*/api/v1/policies/route-rules', () => ok({ total: routeRuleDB.length, list: routeRuleDB })),
http.post('*/api/v1/policies/route-rules', async ({ request }) => {
const body = (await request.json()) as Partial<{ rule_type: string; rule_config: string; channel_id: number; priority: number }>
if (!body.rule_config || !body.channel_id) return fail('ISC:400', '匹配值与通道必填')
const row = { id: rrNext++, account_id: 0, channel_id: body.channel_id, channel_name: chanName(body.channel_id), rule_type: body.rule_type ?? 'keyword', rule_config: body.rule_config, priority: body.priority ?? 0, status: 1, created_at: new Date().toISOString().slice(0, 19).replace('T', ' ') }
routeRuleDB.push(row)
return ok(row)
}),
http.put('*/api/v1/policies/route-rules/:id', async ({ request, params }) => {
const row = routeRuleDB.find((r) => r.id === Number(params.id))
if (!row) return fail('ISC:404', '不存在', 404)
Object.assign(row, (await request.json()) as Record<string, unknown>)
return ok(row)
}),
http.delete('*/api/v1/policies/route-rules/:id', ({ params }) => {
const idx = routeRuleDB.findIndex((r) => r.id === Number(params.id))
if (idx < 0) return fail('ISC:404', '不存在', 404)
routeRuleDB.splice(idx, 1)
return ok({ id: Number(params.id) })
}),
// ---- 签名/码号报备(D16;状态机 0 待审 → 1 通过 / 2 驳回,驳回可重提) ----
http.get('*/api/v1/policies/reports', () => ok({ total: reportDB.length, list: reportDB })),
http.post('*/api/v1/policies/reports', async ({ request }) => {
const body = (await request.json()) as { type: string; content: string }
if (body.type !== 'sign' && body.type !== 'code') return fail('ISC:400', '类型仅 sign/code')
if (!body.content) return fail('ISC:400', '内容必填')
const row = { id: repNext++, type: body.type, content: body.content, account_id: 0, status: 0, operator: '-', created_at: new Date().toISOString().slice(0, 19).replace('T', ' ') }
reportDB.push(row)
return ok(row)
}),
http.post('*/api/v1/policies/reports/:id/review', async ({ request, params }) => {
const row = reportDB.find((r) => r.id === Number(params.id))
if (!row) return fail('ISC:404', '不存在', 404)
if (row.status !== 0) return fail('ISC:400', `当前状态 ${row.status} 非待审,不可审核`)
const body = (await request.json()) as { approve: boolean }
row.status = body.approve ? 1 : 2
row.operator = 'admin'
return ok(row)
}),
http.post('*/api/v1/policies/reports/:id/resubmit', ({ params }) => {
const row = reportDB.find((r) => r.id === Number(params.id))
if (!row) return fail('ISC:404', '不存在', 404)
if (row.status !== 2) return fail('ISC:400', '仅驳回状态可重新提报')
row.status = 0
row.operator = '-'
return ok(row)
}),
// ---- 审核中心(Day 45/D21;counts/batch-review 静态段必须先于 :id 通配注册——
// MSW 按注册顺序匹配,与 gin 静态优先行为不同,Day44 已踩坑固化) ----
http.get('*/api/v1/audits/messages/counts', () => {
const by: Record<string, number> = {}
let total = 0
for (const t of sendTaskDB) {
by[String(t.audit_status)] = (by[String(t.audit_status)] ?? 0) + 1
total++
}
return ok({ total, by_status: by })
}),
http.post('*/api/v1/audits/messages/batch-review', async ({ request }) => {
const body = (await request.json()) as { ids: number[]; pass: boolean; reason?: string }
if (!body.ids?.length) return fail('ISC:400', 'ids 不能为空')
if (!body.pass && !body.reason) return fail('ISC:400', '批量拒绝原因必填')
let okCnt = 0
for (const id of body.ids) {
const row = sendTaskDB.find((t) => t.id === id)
if (row && row.audit_status === 0) {
row.audit_status = body.pass ? 1 : 2
okCnt++
}
}
return ok({ ok: okCnt, total: body.ids.length })
}),
http.get('*/api/v1/audits/messages', ({ request }) => {
const url = new URL(request.url)
const audit = url.searchParams.get('audit_status')
let rows = [...sendTaskDB]
if (audit !== null && Number(audit) >= 0) rows = rows.filter((t) => t.audit_status === Number(audit))
return ok({ total: rows.length, list: rows })
}),
http.post('*/api/v1/audits/messages/:id/approve', ({ params }) => {
const row = sendTaskDB.find((t) => t.id === Number(params.id))
if (!row) return fail('ISC:404', '任务不存在', 404)
if (row.audit_status !== 0) return fail('ISC:037', '任务非待审状态,不可审核', 409)
row.audit_status = 1
return ok({ task: row })
}),
http.post('*/api/v1/audits/messages/:id/reject', async ({ request, params }) => {
const row = sendTaskDB.find((t) => t.id === Number(params.id))
if (!row) return fail('ISC:404', '任务不存在', 404)
const body = (await request.json()) as { reason?: string }
if (!body.reason) return fail('ISC:400', '拒绝原因必填')
if (row.audit_status !== 0) return fail('ISC:037', '任务非待审状态,不可审核', 409)
row.audit_status = 2
return ok({ task: row })
}),
// ---- 发送任务(D19;/send/tasks 列表/取消/改期;状态机与后端 Day 43 对齐) ----
http.get('*/api/v1/send/tasks', ({ request }) => {
const url = new URL(request.url)
const status = url.searchParams.get('status')
const sendType = url.searchParams.get('send_type')
const audit = url.searchParams.get('audit_status')
let rows = [...sendTaskDB]
if (status !== null && Number(status) >= 0) rows = rows.filter((t) => t.status === Number(status))
if (sendType !== null && Number(sendType) > 0) rows = rows.filter((t) => t.send_type === Number(sendType))
if (audit !== null && Number(audit) >= 0) rows = rows.filter((t) => t.audit_status === Number(audit))
return ok({ total: rows.length, list: rows })
}),
http.post('*/api/v1/send/tasks/:id/cancel', ({ params }) => {
const row = sendTaskDB.find((t) => t.id === Number(params.id))
if (!row) return fail('ISC:404', '任务不存在', 404)
if (row.status !== 0) return fail('ISC:038', '仅待发任务可取消', 409)
row.status = 3
return ok(row)
}),
http.put('*/api/v1/send/tasks/:id/reschedule', async ({ request, params }) => {
const row = sendTaskDB.find((t) => t.id === Number(params.id))
if (!row) return fail('ISC:404', '任务不存在', 404)
if (row.send_type !== 3 || row.status !== 0) return fail('ISC:038', '仅定时待发任务可改期', 409)
const body = (await request.json()) as { send_at: string }
if (!body.send_at) return fail('ISC:400', 'send_at 必填')
if (new Date(body.send_at.replace(' ', 'T')).getTime() <= Date.now())
return fail('ISC:400', '改期时刻须在未来')
row.schedule_at = body.send_at
return ok(row)
}),
// Day 46/D22:任务明细分页(状态/错误码过滤;与后端 ReviewService.TaskDetails 对齐)
http.get('*/api/v1/send/tasks/:id/details', ({ request, params }) => {
const taskID = Number(params.id)
if (!sendTaskDB.some((t) => t.id === taskID)) return fail('ISC:404', '任务不存在', 404)
const url = new URL(request.url)
const status = url.searchParams.get('status')
const errCode = url.searchParams.get('error_code')
let rows = sendDetailDB.filter((d) => d.task_id === taskID)
if (status !== null && Number(status) >= 0) rows = rows.filter((d) => d.status === Number(status))
if (errCode) rows = rows.filter((d) => d.error_code === errCode)
const page = Number(url.searchParams.get('page') ?? '1')
const size = Number(url.searchParams.get('page_size') ?? '50')
const start = (page - 1) * size
return ok({ total: rows.length, list: rows.slice(start, start + size) })
}),
// ---- 发送提交/预估(Day 43 修复循环;mock 模式一致性,bypass 会打真代理) ----
http.post('*/api/v1/send/estimate', async ({ request }) => {
const body = (await request.json()) as { mobiles: string[]; content?: string; send_type?: number; send_at?: string }
if (!body.mobiles?.length) return fail('ISC:400', '号码列表为空')
if (!body.content) return fail('ISC:400', '内容为空')
if (body.send_type === 3 && !body.send_at) return fail('ISC:400', '定时发送须指定 send_at')
const uniq = [...new Set(body.mobiles)]
const segments = body.content.length <= 70 ? 1 : Math.ceil(body.content.length / 67)
return ok({ valid_count: uniq.length, chars: body.content.length, segments, total_fee: uniq.length * segments })
}),
http.post('*/api/v1/send/submit', async ({ request }) => {
const body = (await request.json()) as {
task_no?: string; mobiles: string[]; content: string
send_type?: number; send_at?: string
}
if (body.task_no && sendTaskDB.some((t) => t.task_no === body.task_no))
return fail('ISC:400', `任务号已存在: ${body.task_no}`)
const segments = body.content.length <= 70 ? 1 : Math.ceil(body.content.length / 67)
const uniq = [...new Set(body.mobiles)]
const id = ++submitNextID
const taskNo = body.task_no ?? `T${new Date().toISOString().replace(/[-:TZ.]/g, '').slice(0, 14)}-${String(id).padStart(4, '0')}`
sendTaskDB.push({
id, task_no: taskNo, account_id: 1001, send_type: body.send_type === 3 ? 3 : 1,
content: body.content, sign: '', mobile_count: uniq.length, success_count: 0, fail_count: 0,
fee_total: uniq.length * segments, audit_status: 1, status: 0,
schedule_at: body.send_type === 3 ? body.send_at ?? null : null,
created_at: new Date().toISOString().slice(0, 19).replace('T', ' '),
})
return ok({
task_no: taskNo, task_id: id, audit_status: 1, audit_hint: '审核通过,等待调度',
valid_count: uniq.length, segments, total_fee: uniq.length * segments,
schedule_at: body.send_type === 3 ? body.send_at : undefined,
})
}),
// ---- 模板管理(D20;/templates CRUD+单个/批量审核;状态机与后端 Day41/44 对齐) ----
// 注意:batch-review 静态段必须先于 :id 通配注册(MSW 按注册顺序匹配;gin 则静态优先无此坑)。
http.put('*/api/v1/templates/batch-review', async ({ request }) => {
const body = (await request.json()) as { ids: number[]; pass: boolean; reason?: string }
if (!Array.isArray(body.ids) || body.ids.length === 0) return fail('ISC:400', 'ids 非空数组')
if (body.ids.length > 100) return fail('ISC:400', '单批最多 100 条')
let okCount = 0
for (const id of body.ids) {
const row = templateDB.find((t) => t.id === id && t.status === 0)
if (!row) continue // 已审跳过(与后端 WHERE status=0 同语义)
row.status = body.pass ? 1 : -1
row.audit_at = new Date().toISOString().slice(0, 19).replace('T', ' ')
if (body.reason) row.reason = body.reason
okCount++
}
return ok({ ok: okCount, total: body.ids.length })
}),
http.get('*/api/v1/templates', ({ request }) => {
const url = new URL(request.url)
const status = url.searchParams.get('status')
const name = url.searchParams.get('name') ?? ''
let rows = [...templateDB]
if (status !== null && status !== '') rows = rows.filter((t) => t.status === Number(status))
if (name) rows = rows.filter((t) => t.name.includes(name))
return ok({ total: rows.length, list: rows })
}),
http.post('*/api/v1/templates', async ({ request }) => {
const body = (await request.json()) as { account_id: number; name: string; content: string }
if (!body.name || !body.content) return fail('ISC:400', '名称/内容必填')
const vars = [...new Set([...body.content.matchAll(/\{(\w{1,32})\}/g)].map((m) => m[1]))]
if (vars.length > 10) return fail('ISC:400', `变量 ${vars.length} 个超上限 10`)
const row: SmsTemplate = {
id: ++templateNextID, account_id: body.account_id || 1001, name: body.name, content: body.content,
variables: vars.join(','), status: 0, audit_at: null, reason: '',
}
templateDB.push(row)
return ok(row)
}),
http.put('*/api/v1/templates/:id', async ({ request, params }) => {
const row = templateDB.find((t) => t.id === Number(params.id))
if (!row) return fail('ISC:404', '模板不存在', 404)
const body = (await request.json()) as { name?: string; content?: string }
if (body.name) row.name = body.name
if (body.content && body.content !== row.content) {
row.content = body.content
row.status = 0 // 内容变更回待审
row.audit_at = null
row.reason = ''
const vars = [...new Set([...body.content.matchAll(/\{(\w{1,32})\}/g)].map((m) => m[1]))]
row.variables = vars.join(',')
}
return ok({ id: row.id })
}),
http.delete('*/api/v1/templates/:id', ({ params }) => {
const i = templateDB.findIndex((t) => t.id === Number(params.id))
if (i < 0) return fail('ISC:404', '模板不存在', 404)
if (templateDB[i].status === 1) return fail('ISC:400', '通过态模板不可删除,请先拒审')
templateDB.splice(i, 1)
return ok({ id: Number(params.id) })
}),
http.put('*/api/v1/templates/:id/review', async ({ request, params }) => {
const row = templateDB.find((t) => t.id === Number(params.id))
if (!row) return fail('ISC:404', '模板不存在', 404)
const body = (await request.json()) as { pass: boolean; reason?: string }
row.status = body.pass ? 1 : -1
row.audit_at = new Date().toISOString().slice(0, 19).replace('T', ' ')
if (body.reason) row.reason = body.reason
return ok({ id: row.id })
}),
// ---- 号码文件导入(Day 44;Mock 简化:文本行解析,表头/去重/非法计数与后端同规则) ----
// 注:不依赖 request.formData()——jsdom/undici 环境下 File 实例缺 text()/stream(),
// 手工拆 multipart 原文提取 filename+内容,浏览器 axios/XHR 与测试手工体均兼容。
http.post('*/api/v1/files/numbers/import', async ({ request }) => {
const raw = await request.text()
const ct = request.headers.get('content-type') ?? ''
const bm = /boundary=(.+)$/.exec(ct)
if (!bm || !raw) return fail('ISC:400', '缺少文件(file 字段)')
const fnameM = /filename="([^"]*)"/.exec(raw)
const fname = fnameM?.[1] ?? ''
if (!fname) return fail('ISC:400', '缺少文件(file 字段)')
if (!/\.(txt|csv|xlsx)$/i.test(fname)) return fail('ISC:400', `不支持的文件格式(仅 txt/csv/xlsx)`)
const part = raw.split(`--${bm[1]}`)[1] ?? ''
const content = (part.split(/\r?\n\r?\n/).slice(1).join('\n\n') || '').replace(/\r?\n$/, '')
const lines = content.split(/\r?\n/).map((l) => l.trim().split(/[,\t]/)[0]?.trim() ?? '').filter(Boolean)
if (!lines.length) return fail('ISC:400', '文件为空或无数据行')
const isMobile = (s: string) => /^1[3-9]\d{9}$/.test(s.replace(/^\+86/, ''))
const seen = new Set<string>()
const mobiles: string[] = []
let duplicated = 0, invalid = 0, headerSkipped = false
lines.forEach((line, i) => {
const n = line.replace(/^\+86/, '')
if (!isMobile(n)) {
if (i === 0 && lines.length > 1 && lines.slice(1).some((x) => isMobile(x.replace(/^\+86/, '')))) {
headerSkipped = true
return
}
invalid++
return
}
if (seen.has(n)) { duplicated++; return }
seen.add(n)
mobiles.push(n)
})
if (!mobiles.length) return fail('ISC:400', '文件中未解析到合法手机号')
if (mobiles.length > 10000) return fail('ISC:400', `号码 ${mobiles.length} 超单次上限 10000`)
return ok({
total: lines.length, valid: mobiles.length, duplicated, invalid, header_skipped: headerSkipped,
mobiles, preview: mobiles.slice(0, 50),
object_key: `numbers/mock/${Date.now()}${fname.slice(fname.lastIndexOf('.'))}`,
})
}),
// ---- 工作台统计(FE-Design-Audit B1;real 模式对应网关 /api/v1/stats/*) ----
http.get('/api/v1/stats/summary', () => ok({
today_sent: 1_286_430,
yesterday_sent: 1_164_880,
success_rate: 0.9832,
success_rate_delta: 0.0021,
balance_alert_count: 3,
pending_audit_count: 12,
})),
http.get('/api/v1/stats/trend', ({ request }) => {
const days = Number(new URL(request.url).searchParams.get('days') ?? 7)
const base: Array<[string, number, number]> = [
['09-18', 986_200, 962_410], ['09-19', 1_102_450, 1_078_940], ['09-20', 1_258_900, 1_230_710],
['09-21', 1_402_300, 1_376_250], ['09-22', 1_189_760, 1_158_120], ['09-23', 1_164_880, 1_141_590],
['09-24', 1_286_430, 1_264_730],
]
return ok(base.slice(-days).map(([date, sent, success]) => ({ date, sent, success })))
}),
]