feat(subject): 主体到期暂停设备上报,新增续期订单与支付回调

- 主体状态缓存(Redis 优先、进程内兜底):设备心跳与上报判断不再查库,续期/停用后主动失效
- 上报写接口按缓存校验期限:过期 403 subject_expired、停用 subject_disabled、主体缺失 subject_missing
- 心跳与 /api/scanner/me 返回 subject 状态,桌面端据此暂停推送并在续期后自动补传积压
- 新增续期订单(subject_orders)与接口,支付回调 POST /api/pay/notify 幂等、支持 HMAC 签名,
  另提供内部令牌模拟支付用于联调
- 顺带提交工作区中已完成的「登录协议」后端改动(agreement):与本次改动共用 router.js / config.default.js

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-10-20 18:55:57 +08:00
parent 424389a97a
commit 7b11f7052d
31 changed files with 2234 additions and 34 deletions

View File

@ -455,13 +455,13 @@ node scripts/backfill-snapshot.js --dry-run
| POST | `/api/scanner/bind` | **管理侧**:把设备绑定到账号,body: `{ sn, username }` 或 `{ sn, userId }` |
| POST | `/api/scanner/unbind` | **管理侧**:解绑,body: `{ sn }`(设备可再扫码重新认领) |
| GET | `/api/scanner/me` | **需 JWT**:返回当前设备信息(自检连通性) |
| POST | `/api/scanner/heartbeat` | **需 JWT**:保活,刷新 `last_seen_at` 并返回服务端时间 |
| POST | `/api/scanner/heartbeat` | **需 JWT**:保活,刷新 `last_seen_at`;返回 `serverTime` + **`subject`(主体状态,读缓存)**,设备据此判断是否已续期 |
| GET | `/api/scanners?page=&pageSize=&keyword=&userId=&status=` | 设备列表(带绑定账号;管理侧) |
| GET | `/api/scanners/:id` | 扫描器详情 |
| DELETE | `/api/scanners/:id` | 软删除扫描器 |
| POST | `/api/scan/channels` | **需扫描器 JWT**:中控上报通道,body: `{ channels: [{ channelId, channelName }], replace?: boolean }`(单条也可)→ `{ created, updated, invalid, errors, removed, unbound }`。`replace: true` = 全量对账:本中控下不在列表里的通道软删并解绑工作台,允许 `channels: []` |
| POST | `/api/scan/channels` | **需扫描器 JWT**(主体过期/停用 → 403 `subject_expired` / `subject_disabled`):中控上报通道,body: `{ channels: [{ channelId, channelName }], replace?: boolean }`(单条也可)→ `{ created, updated, invalid, errors, removed, unbound }`。`replace: true` = 全量对账:本中控下不在列表里的通道软删并解绑工作台,允许 `channels: []` |
| GET | `/api/scan/channels?page=&pageSize=&keyword=&status=` | **需扫描器 JWT**:当前中控已登记的通道 |
| POST | `/api/scan/records` | **需扫描器 JWT**:中控上报扫码,body: `{ records: [{ barcode, scanTime, channelId }] }` → `{ received, inserted, updated, duplicated, suppressed, invalid, unknownChannels }`(`updated` = 24 小时内同一运单被覆盖为最新扫描时间的条数;`suppressed` = 比库里已有记录更旧、被忽略的条数) |
| POST | `/api/scan/records` | **需扫描器 JWT**(主体过期/停用 → 403 `subject_expired` / `subject_disabled`):中控上报扫码,body: `{ records: [{ barcode, scanTime, channelId }] }` → `{ received, inserted, updated, duplicated, suppressed, invalid, unknownChannels }`(`updated` = 24 小时内同一运单被覆盖为最新扫描时间的条数;`suppressed` = 比库里已有记录更旧、被忽略的条数) |
| GET | `/api/scan/records?page=&pageSize=&channelId=&barcode=&startTime=&endTime=` | **需扫描器 JWT**:当前中控上报的扫码记录 |
扫码上报的两个接口都**不会因为重复而报错**(幂等):完全重复的条数计入 `duplicated`,
@ -470,6 +470,14 @@ node scripts/backfill-snapshot.js --dry-run
上报还支持 `records` 传 JSON 字符串(部分设备端会这么塞);上报成功会顺手刷新中控心跳与通道的 `last_report_at`,
遇到未登记的通道会自动补建一行(`channel_name` 留空,同时记 WARN 日志)。
**主体期限与设备上报**:设备所属主体过期/停用时,`POST /api/scan/records`、`POST /api/scan/channels`
返回 **403**(`status` = `subject_expired` / `subject_disabled`),设备端应**暂停推送但保留本地积压**;
`POST /api/scanner/heartbeat` 不受期限拦截,返回体里的 `subject.expired` 是恢复依据 —— 续期后最多 1 分钟
设备就会自动恢复并补传(服务端按 设备+通道+条码+秒 去重,整批重发安全)。
主体状态走 `service/subject_state.js` 缓存(Redis 优先,不可用时退化为进程内 TTL),
**心跳与上报判断都不额外查库**;续期/停用后由写库方主动失效缓存(`SUBJECT_STATE_CACHE_TTL`,默认 30 秒)。
统一响应格式:成功 `{ "ok": true, "data": ... }`;失败 `{ "ok": false, "message": "..." }`(由 `app/middleware/error_handler.js` 保证 4xx/5xx 也返回 JSON);
**接口路径写错(没匹配到路由)也是 JSON**:`404 { ok:false, message:'接口不存在' }`(不会再返 HTML 404 页把客户端的 JSON 解析弄挂)。
@ -793,6 +801,43 @@ await this.ctx.service.cache.remember('user:1', 60, () => loadFromMysql());
| GET | `/api/subject/member-bind?code=` | 绑定码状态(**公开**,手机扫码页轮询) |
| POST | `/api/subject/member-bind/confirm` | 手机端确认绑定 `{ code }`(需 user JWT)→ 该账号成为成员 |
### 续期订单与支付回调
**下单不会立刻续期**,只有支付渠道回调成功后才把主体期限顺延(幂等,重复回调不重复续期)。
| 方法 | 路径 | 说明 |
|---|---|---|
| GET | `/api/web/subjects/:id/orders` | 订单列表(成员可见,`{ total, page, pageSize, list }`) |
| POST | `/api/web/subjects/:id/orders` | 下单 `{ days, amount?, remark? }`(仅管理员)→ `{ orderNo, days, amount, status:0待支付, ... }`;`amount` 不传时按 `PAY_AMOUNT_PER_DAY` 自动算,都没配则金额为空(不校验) |
| POST | `/api/pay/notify` | **公开的渠道回调** `{ orderNo, transactionId?, amount?, channel?, paidAt? }` → `{ duplicated, order }`;订单不存在 404、金额不符 422、签名错 400 |
| POST | `/api/internal/subject-orders/:orderNo/pay` | **内部令牌**:模拟支付成功(不需要签名),方便联调/补单 |
签名:配置了 `PAY_CALLBACK_SECRET` 时,回调必须带
`X-Pay-Sign = hex(HMAC-SHA256(secret, "orderNo\ntransactionId\namount"))`;
未配置密钥且 `PAY_MOCK=true` 时允许不带签名直接回调(开发/测试默认开启;**生产默认关闭**,
需要显式设 `PAY_MOCK=true`,否则回调返回 503 `pay_not_configured`)。
续期规则与 `PUT /api/web/subjects/:id` 的 `extendDays` 一致:**未过期在原到期时间上顺延,已过期从当前时间起算**;
回调成功后会主动失效主体状态缓存,设备下一次上报/心跳立即看到新期限。
**模拟一次付费续期**(本地/测试):
```bash
# 1) 下单(需要主体管理员用户令牌)
curl -X POST http://127.0.0.1:7300/api/web/subjects/1/orders \
-H "Authorization: Bearer <user-jwt>" -H "Content-Type: application/json" \
-d '{"days":30,"amount":99}'
# 2a) 模拟渠道回调(PAY_MOCK=true 时不需要签名)
curl -X POST http://127.0.0.1:7300/api/pay/notify \
-H "Content-Type: application/json" \
-d '{"orderNo":"<上一步的 orderNo>","transactionId":"TXN-1","amount":99}'
# 2b) 或者走运维接口(内部令牌)
curl -X POST http://127.0.0.1:7300/api/internal/subject-orders/<orderNo>/pay \
-H "X-Internal-Token: <INTERNAL_TOKEN>"
```
二维码:`GET /api/wechat/qrcode.svg?code=<码>&mode=member`(内容是 `<站点>/wechat?bind=<码>`,前端扫码页显示「确认绑定」)。
### 主体上下文(统一处理)
@ -816,4 +861,48 @@ await this.ctx.service.cache.remember('user:1', 60, () => loadFromMysql());
**「一个主体只允许一台设备在线」**:`activate` 会把同主体下**其他**设备的 `token_jti` 全部轮换(旧 JWT 立即失效),
并在返回的 `kicked` 里列出被踢的设备;同一 SN 重复开启只是换发令牌,不会新建记录。
设备令牌用于设备侧上报:`POST /api/scan/channels`、`POST /api/scan/records`(`scannerAuth`,不需要主体 header)。
设备令牌用于设备侧上报:`POST /api/scan/channels`、`POST /api/scan/records`(`scannerAuth` + `subjectActive`,
不需要主体 header;所属主体过期/停用 → 403 `subject_expired` / `subject_disabled`)。
## 用户协议(2026-10-20)
三张表(迁移 `20261020220000-create-agreement-tables`,示例数据 `20261020221000-seed-user-agreement`):
| 表 | 用途 |
|---|---|
| `agreements` | 协议定义:`code` / `name` / `required` / `current_version_id` |
| `agreement_versions` | 版本正文:`version` / `content` / `content_type` / `status` / `published_at` |
| `user_agreements` | 用户同意记录:`user_id + agreement_id + version_id` 唯一,另存版本号快照与来源/IP/UA |
接口:
- `GET /api/agreements/current`(公开)→ 当前启用的协议 + 已发布版本正文(登录前展示)
- `POST /api/web/auth/login` 增加 `client` / `agreements`:
- `client='mini_program'` 时,必须带 `agreements: [{ code, versionId }]` 且版本等于当前版本,
否则 **428** `{ ok:false, status:'agreement_required', data:{ agreements } }`;
- 登录成功后按 `user_id + agreement_id + version_id` 落库(同一版本重复登录只更新 `agreed_at` / 来源),响应里带 `agreements`。
- 强制范围由 `AGREEMENT_ENFORCE` 控制:默认 `mini_program`(只拦小程序客户端);`all` = 所有客户端;`off` = 不校验(仍记录主动提交的同意)。
没有管理界面,发布新版本直接执行 SQL(示例):
```sql
SET @aid = (SELECT id FROM agreements WHERE code = 'user_agreement');
INSERT INTO agreement_versions
(agreement_id, version, title, summary, content, content_type, status, published_at, effective_at, created_at, updated_at)
VALUES
(@aid, '1.1.0', '用户协议', '更新说明', '新的协议正文', 'text', 1, NOW(), NOW(), NOW(), NOW());
SET @vid = LAST_INSERT_ID();
UPDATE agreements SET current_version_id = @vid, updated_at = NOW() WHERE id = @aid;
```
发布后,小程序下次登录会收到 428 → 自动拉新正文、要求重新阅读并勾选;旧版本的同意记录保留。
查某个用户同意过哪些版本:
```sql
SELECT agreement_id, version_id, version, source, agreed_at
FROM user_agreements WHERE user_id = ? ORDER BY agreed_at DESC;
```
⚠️ 种子迁移里的协议正文是**占位示例**,正式上线前务必替换为法务确认后的文本。

View File

@ -0,0 +1,20 @@
'use strict';
const { Controller } = require('egg');
/**
* 协议(公开接口)
*
* 协议正文要在登录前展示,所以不挂鉴权;「同意」由登录接口落库(`/api/web/auth/login`)。
* 没有管理界面:新版本按 backend/README 的 SQL 直接在库里发布。
*/
class AgreementController extends Controller {
/** GET /api/agreements/current —— 当前启用的协议 + 已发布版本 */
async current() {
const { ctx } = this;
const agreements = await ctx.service.agreement.listCurrent();
ctx.body = { ok: true, data: { agreements } };
}
}
module.exports = AgreementController;

View File

@ -17,25 +17,53 @@ class DeviceSelfController extends Controller {
async me() {
const { ctx } = this;
const data = await ctx.service.scanner.findById(ctx.state.scanner.id);
ctx.body = { ok: true, data };
const subject = await subjectStateOf(ctx, ctx.state.scanner);
ctx.body = { ok: true, data: Object.assign({}, data, { subject }) };
}
/**
* POST /api/scanner/heartbeat —— 设备心跳(需 JWT)
* 用于设备与服务之间的连通性保活,同时刷新 IP 与心跳时间
* 用于设备与服务之间的连通性保活,同时刷新 IP 与心跳时间。
*
* **不因主体过期返回 403**:设备靠这个接口探测「是否已续期」,
* 返回的 `subject.expired` 才是上报循环暂停/恢复的依据(状态读缓存,不额外查库)。
*/
async heartbeat() {
const { ctx } = this;
const data = await ctx.service.scanner.heartbeat(ctx.state.scanner, ctx.ip);
const subject = await subjectStateOf(ctx, ctx.state.scanner);
ctx.body = {
ok: true,
data: {
sn: data.sn,
lastSeenAt: data.lastSeenAt,
serverTime: new Date().toISOString(),
subject,
},
};
}
}
/**
* 设备所属主体的状态(从 `service.subjectState` 缓存读,不查数据库)
* 没挂主体的历史设备返回 null。
*/
async function subjectStateOf(ctx, scanner) {
const subjectId = scanner && Number(scanner.subjectId);
if (!subjectId) return null;
const state = await ctx.service.subjectState.get(subjectId);
if (!state) return null;
return {
id: state.id,
name: state.name,
status: state.status,
expireAt: state.expireAt,
expired: state.expired,
disabled: state.disabled,
remainingSeconds: state.remainingSeconds,
};
}
module.exports = DeviceSelfController;

View File

@ -0,0 +1,26 @@
'use strict';
const { Controller } = require('egg');
/**
* 运维/内部:模拟支付成功(`POST /api/internal/subject-orders/:orderNo/pay`)
*
* 需要内部令牌(`middleware/internalAuth()`),不需要渠道签名;
* 与真实回调走同一个 `service.subjectOrder.payNotify()`,所以续期结果完全一致。
*/
class InternalSubjectOrderController extends Controller {
async pay() {
const { ctx } = this;
const orderNo = String(ctx.params.orderNo || '').trim();
if (!orderNo) ctx.throw(400, 'orderNo 不能为空');
const data = await ctx.service.subjectOrder.payNotify({
orderNo,
transactionId: `MOCK-${Date.now()}`,
channel: 'mock',
});
ctx.body = { ok: true, data };
}
}
module.exports = InternalSubjectOrderController;

View File

@ -0,0 +1,65 @@
'use strict';
const { Controller } = require('egg');
const crypto = require('crypto');
/**
* 支付渠道通知(`POST /api/pay/notify`,**公开接口**)
*
* 渠道接入前先用它模拟「已付款」:带上订单号与金额调用即可续期(见 README)。
*
* 请求体(兼容常见的两种命名):
* `{ orderNo | out_trade_no, transactionId | trade_no, amount | total_amount, channel?, paidAt? }`
*
* 签名:配置了 `config.pay.callbackSecret`(env `PAY_CALLBACK_SECRET`)时,
* 必须带 header `X-Pay-Sign = HMAC-SHA256(secret, "orderNo\ntransactionId\namount")`(hex)。
* 未配置密钥且 `PAY_MOCK=true` 时允许不带签名(仅开发/测试)。
*
* 响应:`{ ok: true, data: { duplicated, order } }`;订单号不存在 404,金额不符 422。
*/
class PayNotifyController extends Controller {
async index() {
const { ctx } = this;
const body = ctx.request.body || {};
const orderNo = String(body.orderNo || body.out_trade_no || '').trim();
const transactionId = body.transactionId || body.transaction_id || body.trade_no || null;
const amount = body.amount !== undefined && body.amount !== null ? body.amount : body.total_amount;
const channel = body.channel || 'mock';
const payCfg = this.config.pay || {};
const secret = String(payCfg.callbackSecret || '');
if (secret) {
const expected = crypto
.createHmac('sha256', secret)
.update(`${orderNo}\n${transactionId || ''}\n${amount === undefined || amount === null ? '' : amount}`)
.digest('hex');
const actual = String(ctx.get('x-pay-sign') || '').trim().toLowerCase();
if (!actual || !safeEqual(actual, expected)) {
ctx.logger.warn('[pay] 回调签名校验失败:orderNo=%s', orderNo);
ctx.status = 400;
ctx.body = { ok: false, status: 'sign_invalid', message: '支付回调签名校验失败' };
return;
}
} else if (!payCfg.mock) {
ctx.status = 503;
ctx.body = { ok: false, status: 'pay_not_configured', message: '未配置支付回调密钥(PAY_CALLBACK_SECRET)' };
return;
} else {
ctx.logger.warn('[pay] 模拟回调(未配置 PAY_CALLBACK_SECRET,PAY_MOCK=%s):orderNo=%s', payCfg.mock, orderNo);
}
const data = await ctx.service.subjectOrder.payNotify({ orderNo, transactionId, amount, channel });
ctx.body = { ok: true, data };
}
}
/** 定长比较,避免按字符提前返回 */
function safeEqual(a, b) {
const left = Buffer.from(String(a));
const right = Buffer.from(String(b));
return left.length === right.length && crypto.timingSafeEqual(left, right);
}
module.exports = PayNotifyController;

View File

@ -14,6 +14,56 @@ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
* 统一响应:成功 `{ ok:true, data }`;失败 `{ ok:false, status?, message }`。
*/
class WebAuthController extends Controller {
/** 客户端标识(只认白名单,避免任意字符串进库) */
normalizeClient(value) {
const client = String(value || '').trim().toLowerCase();
return [ 'mini_program', 'web', 'h5' ].includes(client) ? client : '';
}
/** 当前配置下,这个客户端是否必须先同意协议 */
shouldEnforceAgreement(client) {
const mode = String(this.app.config.agreement.enforce || 'mini_program').toLowerCase();
if ([ 'off', 'false', '0', 'no' ].includes(mode)) return false;
if (mode === 'all') return true;
return client === 'mini_program';
}
/**
* 校验协议同意情况
* 通过 → 返回可落库的 `[{ agreementId, code, versionId, version }]`;
* 不通过 → 直接写 428 响应并返回 null(客户端拿到最新协议后重新展示)
*/
async requireAgreements(input) {
const { ctx } = this;
const required = await ctx.service.agreement.requiredVersions();
const check = ctx.service.agreement.verifyAcceptance(required, input);
if (check.ok) return check.accepted;
ctx.status = 428;
ctx.body = {
ok: false,
status: 'agreement_required',
message: '请阅读并同意用户协议后再登录',
data: { agreements: required },
};
return null;
}
/** 落库同意记录(失败不阻断登录,只记错误日志) */
async recordAgreements(user, accepted, client) {
const { ctx } = this;
try {
return await ctx.service.agreement.record(user.id, accepted, {
source: client || 'unknown',
ip: ctx.ip,
userAgent: String(ctx.get('user-agent') || ''),
});
} catch (err) {
ctx.logger.error('[web] 记录协议同意失败, userId=%s: %s', user.id, err.message);
return [];
}
}
/**
* 签发令牌 + 返回脱敏用户(登录 / 注册成功后都走它)
*
@ -38,18 +88,29 @@ class WebAuthController extends Controller {
/**
* POST /api/web/auth/login
* body: `{ account, password }`(account 支持 用户名 / 手机号 / 邮箱)
* → `{ token, tokenType, expiresIn, user, subjects }`
* body: `{ account, password, client?, agreements? }`
* - account 支持 用户名 / 手机号 / 邮箱
* - client = 'mini_program' 时必须同意当前协议版本(见 config.agreement.enforce)
* - agreements = `[{ code, versionId }]`,登录成功后按用户 + 版本落库
* → `{ token, tokenType, expiresIn, user, subjects, agreements? }`
*/
async login() {
const { ctx } = this;
const { account, password } = ctx.request.body || {};
const body = ctx.request.body || {};
const { account, password } = body;
const client = this.normalizeClient(body.client);
if (!account || !password) {
ctx.status = 422;
ctx.body = { ok: false, message: '请填写账号和密码' };
return;
}
let accepted = null;
if (this.shouldEnforceAgreement(client)) {
accepted = await this.requireAgreements(body.agreements);
if (!accepted) return;
}
const user = await ctx.service.auth.login(String(account).trim(), password);
if (!user) {
ctx.status = 401;
@ -57,8 +118,13 @@ class WebAuthController extends Controller {
return;
}
ctx.logger.info('[web] %s 登录成功(API)', user.username || account);
ctx.body = { ok: true, data: await this.issue(user) };
ctx.logger.info('[web] %s 登录成功(API, client=%s)', user.username || account, client || 'unknown');
const data = await this.issue(user);
if (accepted) {
data.agreements = await this.recordAgreements(user, accepted, client);
ctx.logger.info('[web] 用户 %s 同意协议:%s', user.id, accepted.map(item => `${item.code}@${item.version}`).join(', '));
}
ctx.body = { ok: true, data };
}
/**

View File

@ -0,0 +1,56 @@
'use strict';
const { Controller } = require('egg');
/** 路径参数转正整数,非法返回 null */
function toId(value) {
const id = Number(value);
return Number.isInteger(id) && id > 0 ? id : null;
}
/**
* web 主体端:续期订单(`/api/web/subjects/:id/orders`)
*
* 鉴权:`middleware.apiAuth()` + 服务层校验「当前用户是不是该主体成员 / 管理员」。
* **不挂 `subjectAuth`**:主体过期后仍然要能下单续期。
*
* 下单不会立刻续期;等支付渠道回调 `POST /api/pay/notify` 后才顺延期限。
*/
class WebSubjectOrderController extends Controller {
/** GET /api/web/subjects/:id/orders —— 订单列表 */
async index() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const { page, pageSize } = ctx.query;
const data = await ctx.service.subjectOrder.list({
subjectId: id,
userId: ctx.state.user.id,
page,
pageSize,
});
ctx.body = { ok: true, data };
}
/** POST /api/web/subjects/:id/orders —— { days, amount?, remark? } */
async create() {
const { ctx } = this;
const id = toId(ctx.params.id);
if (!id) ctx.throw(400, 'id 必须是正整数');
const { days, amount, remark } = ctx.request.body || {};
const data = await ctx.service.subjectOrder.create({
subjectId: id,
userId: ctx.state.user.id,
days,
amount,
remark,
});
ctx.status = 201;
ctx.body = { ok: true, data };
}
}
module.exports = WebSubjectOrderController;

View File

@ -0,0 +1,54 @@
'use strict';
/**
* 协议同意校验(纯函数,不依赖 Sequelize,方便单测)
*/
/** 客户端提交的 `agreements` → Map(code → versionId);非法项直接忽略 */
function normalizeAccepted(list) {
const map = new Map();
if (!Array.isArray(list)) return map;
for (const item of list) {
if (!item || typeof item !== 'object') continue;
const code = String(item.code || '').trim();
const versionId = Number(item.versionId === undefined ? item.version_id : item.versionId);
if (!code || !Number.isInteger(versionId) || versionId <= 0) continue;
map.set(code, versionId);
}
return map;
}
/**
* 校验客户端同意的是不是「当前生效版本」
*
* @param {Array} required 当前必须同意的协议(service.agreement.listCurrent 的输出)
* @param {Array} accepted 客户端提交的 `[{ code, versionId }]`
* @return {{ok:boolean, missing:Array, accepted:Array}} accepted 里是可直接落库的条目
*/
function verifyAcceptance(required, accepted) {
const list = Array.isArray(required) ? required : [];
const submitted = normalizeAccepted(accepted);
const missing = [];
const matched = [];
for (const item of list) {
if (!item || !item.version || !item.version.id) continue;
const versionId = Number(item.version.id);
if (submitted.get(item.code) !== versionId) {
missing.push({ code: item.code, name: item.name, versionId });
continue;
}
matched.push({
agreementId: Number(item.id),
code: item.code,
name: item.name,
versionId,
version: item.version.version,
});
}
return { ok: missing.length === 0, missing, accepted: matched };
}
module.exports = { normalizeAccepted, verifyAcceptance };

View File

@ -0,0 +1,57 @@
'use strict';
/**
* 设备上报时的主体可用性检查(**必须在 scannerAuth 之后**)
*
* 用法:`router.post('/api/scan/records', scannerAuth, subjectActive(), controller...)`
*
* - 设备没有归属主体(历史数据 `subject_id` 为空)→ 放行,保持老设备可用;
* - 主体已停用 → 403 `subject_disabled`;
* - 主体已过期 → 403 `subject_expired`(带 expireAt,设备据此暂停上报并等待续期)。
*
* 状态来自 `service.subjectState` 缓存,**不查数据库**;续期后由写库方主动失效缓存。
* 心跳 / `me` 这两个接口不挂本中间件 —— 它们就是设备用来探测「是否已续期」的通道。
*/
module.exports = () => {
return async function subjectActive(ctx, next) {
const scanner = ctx.state.scanner;
const subjectId = scanner && Number(scanner.subjectId);
// 老数据(设备没挂主体)保持原行为,不做限制
if (!subjectId) return next();
const state = await ctx.service.subjectState.get(subjectId);
if (!state) {
ctx.status = 403;
ctx.body = { ok: false, status: 'subject_missing', message: '设备所属主体不存在,请联系管理员' };
return;
}
if (state.disabled) {
ctx.status = 403;
ctx.body = { ok: false, status: 'subject_disabled', message: '主体已被停用,请联系管理员' };
return;
}
if (state.expired) {
ctx.status = 403;
ctx.body = {
ok: false,
status: 'subject_expired',
message: `主体「${state.name}」使用期限已到(${formatDate(state.expireAt)}),请联系管理员续期`,
expireAt: state.expireAt,
remainingSeconds: 0,
};
return;
}
await next();
};
};
/** yyyy-MM-dd HH:mm(服务器本地时间,仅用于提示文案) */
function formatDate(value) {
if (!value) return '';
const date = new Date(value);
const pad = num => String(num).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}

View File

@ -0,0 +1,37 @@
'use strict';
/**
* 协议(agreements)
*
* 一行 = 一种协议(用户协议 / 隐私政策……),版本正文在 `agreement_versions`,
* `current_version_id` 指向当前生效版本(不设外键,避免与版本表互相依赖)。
*/
module.exports = (app) => {
const { BIGINT, STRING, TINYINT, INTEGER, DATE } = app.Sequelize;
const Agreement = app.model.define('agreement', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
code: { type: STRING(64), allowNull: false, unique: true, comment: '协议标识(user_agreement 等)' },
name: { type: STRING(128), allowNull: false, comment: '协议名称(展示用)' },
description: { type: STRING(255), allowNull: true, comment: '简介' },
required: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '登录是否必须同意:1是 0否' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1启用 0停用' },
sortNo: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '展示排序(小的在前)' },
currentVersionId: { type: BIGINT.UNSIGNED, allowNull: true, comment: '当前生效版本 agreement_versions.id' },
}, {
tableName: 'agreements',
paranoid: true,
comment: '协议定义表',
});
Agreement.associate = function() {
app.model.Agreement.hasMany(app.model.AgreementVersion, { foreignKey: 'agreement_id', as: 'versions' });
app.model.Agreement.belongsTo(app.model.AgreementVersion, {
foreignKey: 'current_version_id',
as: 'currentVersion',
constraints: false,
});
};
return Agreement;
};

View File

@ -0,0 +1,36 @@
'use strict';
/**
* 协议版本(agreement_versions)
*
* 正文存 `content`(默认纯文本,`content_type='text'`;后续要富文本可改 'html'),
* `status`:0 草稿 / 1 已发布 / 2 已归档。只有「已发布」且被 `agreements.current_version_id`
* 指向的版本才会下发给客户端。
*/
module.exports = (app) => {
const { BIGINT, STRING, TINYINT, TEXT, DATE } = app.Sequelize;
const AgreementVersion = app.model.define('agreement_version', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
agreementId: { type: BIGINT.UNSIGNED, allowNull: false, comment: 'agreements.id' },
version: { type: STRING(32), allowNull: false, comment: '版本号(1.0.0)' },
title: { type: STRING(128), allowNull: false, comment: '版本标题' },
summary: { type: STRING(255), allowNull: true, comment: '变更摘要' },
content: { type: TEXT('long'), allowNull: false, comment: '协议正文' },
contentType: { type: STRING(16), allowNull: false, defaultValue: 'text', comment: '正文类型:text / html' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:0草稿 1已发布 2已归档' },
publishedAt: { type: DATE, allowNull: true, comment: '发布时间' },
effectiveAt: { type: DATE, allowNull: true, comment: '生效时间' },
}, {
tableName: 'agreement_versions',
paranoid: true,
comment: '协议版本表',
});
AgreementVersion.associate = function() {
app.model.AgreementVersion.belongsTo(app.model.Agreement, { foreignKey: 'agreement_id', as: 'agreement' });
app.model.AgreementVersion.hasMany(app.model.UserAgreement, { foreignKey: 'version_id', as: 'userAgreements' });
};
return AgreementVersion;
};

View File

@ -0,0 +1,41 @@
'use strict';
/**
* 主体续期订单(subject_orders)
*
* 一行 = 一次「续期 N 天」的下单记录:
* - `status`:0 待支付 / 1 已支付 / 2 已关闭
* - `amount` 为空表示不校验金额(内部续期 / 免费赠送)
* - 支付成功后由 `service/subject_order.js#payNotify` 把主体期限顺延,
* 并记录续期前后的到期时间(`expireBefore` / `expireAfter`)方便对账
*/
module.exports = (app) => {
const { BIGINT, STRING, TINYINT, INTEGER, DECIMAL, DATE } = app.Sequelize;
const SubjectOrder = app.model.define('subject_order', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
orderNo: { type: STRING(32), allowNull: false, unique: true, comment: '订单号(对外唯一)' },
subjectId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体 subjects.id' },
userId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '下单用户 users.id' },
days: { type: INTEGER.UNSIGNED, allowNull: false, comment: '续期天数' },
amount: { type: DECIMAL(10, 2), allowNull: true, comment: '应付金额(为空表示不校验)' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '状态:0待支付 1已支付 2已关闭' },
channel: { type: STRING(16), allowNull: true, comment: '支付渠道(mock 等)' },
transactionId: { type: STRING(64), allowNull: true, comment: '渠道流水号' },
paidAt: { type: DATE, allowNull: true, comment: '支付时间' },
expireBefore: { type: DATE, allowNull: true, comment: '续期前的到期时间' },
expireAfter: { type: DATE, allowNull: true, comment: '续期后的到期时间' },
remark: { type: STRING(255), allowNull: true, comment: '备注' },
}, {
tableName: 'subject_orders',
paranoid: true,
comment: '主体续期订单表',
});
SubjectOrder.associate = function() {
app.model.SubjectOrder.belongsTo(app.model.Subject, { foreignKey: 'subject_id', as: 'subject' });
app.model.SubjectOrder.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' });
};
return SubjectOrder;
};

View File

@ -0,0 +1,35 @@
'use strict';
/**
* 用户协议同意记录(user_agreements)
*
* 一行 = 某个用户同意过某个协议的某个版本(同一版本重复登录只更新时间,不重复插入)。
* 版本号同时冗余一列 `version`,方便协议版本被改名/归档后仍能审计当时同意的是哪一版。
*/
module.exports = (app) => {
const { BIGINT, STRING, DATE } = app.Sequelize;
const UserAgreement = app.model.define('user_agreement', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
userId: { type: BIGINT.UNSIGNED, allowNull: false, comment: 'users.id' },
agreementId: { type: BIGINT.UNSIGNED, allowNull: false, comment: 'agreements.id' },
versionId: { type: BIGINT.UNSIGNED, allowNull: false, comment: 'agreement_versions.id' },
version: { type: STRING(32), allowNull: false, comment: '同意时的版本号快照' },
source: { type: STRING(32), allowNull: true, comment: '来源:mini_program / web / h5' },
ip: { type: STRING(64), allowNull: true, comment: '同意时的客户端 IP' },
userAgent: { type: STRING(255), allowNull: true, comment: '同意时的 User-Agent' },
agreedAt: { type: DATE, allowNull: false, comment: '同意时间' },
}, {
tableName: 'user_agreements',
paranoid: true,
comment: '用户协议同意记录表',
});
UserAgreement.associate = function() {
app.model.UserAgreement.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' });
app.model.UserAgreement.belongsTo(app.model.Agreement, { foreignKey: 'agreement_id', as: 'agreement' });
app.model.UserAgreement.belongsTo(app.model.AgreementVersion, { foreignKey: 'version_id', as: 'versionInfo' });
};
return UserAgreement;
};

View File

@ -8,6 +8,7 @@ module.exports = (app) => {
const { router, controller, middleware } = app;
const apiAuth = middleware.apiAuth();
const subjectAuth = middleware.subjectAuth();
const subjectActive = middleware.subjectActive();
const internalAuth = middleware.internalAuth();
const scannerAuth = middleware.scannerAuth();
@ -29,6 +30,9 @@ module.exports = (app) => {
// version.json **必须走路由**:static 命中后不会 next(),改不了缓存头(会被缓存一年)。
router.get('/download/version.json', controller.download.version);
// ---------- 协议(公开读取;同意记录在登录时落库) ----------
router.get('/api/agreements/current', controller.agreement.current);
// ---------- web 用户端(前端 SPA 调;登录/注册等公开,其余要令牌) ----------
router.post('/api/web/auth/login', controller.web.auth.login);
router.post('/api/web/auth/register/code', controller.web.auth.sendRegisterCode);
@ -52,6 +56,11 @@ module.exports = (app) => {
// 给未绑定账号/微信的成员生成绑定码(手机扫码后绑定)
router.post('/api/web/subjects/:id/members/:memberId/bind-code', apiAuth, controller.web.subject.memberBindCode);
// 续期订单:下单不改变期限,支付结果由渠道回调 `POST /api/pay/notify` 驱动
// ⚠️ 不挂 subjectAuth:主体已过期也要能下单续期
router.get('/api/web/subjects/:id/orders', apiAuth, controller.web.subjectOrder.index);
router.post('/api/web/subjects/:id/orders', apiAuth, controller.web.subjectOrder.create);
// 成员绑定:手机扫码页(公开查状态)+ 登录后确认绑定
router.get('/api/subject/member-bind', controller.auth.memberBind.status);
router.post('/api/subject/member-bind/confirm', apiAuth, controller.auth.memberBind.confirm);
@ -142,6 +151,13 @@ module.exports = (app) => {
router.get('/api/scanners/:id', internalAuth, controller.internal.device.show);
router.delete('/api/scanners/:id', internalAuth, controller.internal.device.destroy);
// ---------- 支付渠道通知(公开,签名见 config.pay)----------
// 渠道接入前用它可以模拟「已付款」:{ orderNo, transactionId, amount } → 续期
router.post('/api/pay/notify', controller.pay.notify.index);
// 运维模拟支付(内部令牌,不需要渠道签名)
router.post('/api/internal/subject-orders/:orderNo/pay', internalAuth, controller.internal.subjectOrder.pay);
// ---------- 公开的登录接口(auth)----------
// 登录码二维码(SVG,本地生成;前端登录页直接 img 引用)
router.get('/api/wechat/qrcode.svg', controller.auth.wechat.qrcode);
@ -165,8 +181,9 @@ module.exports = (app) => {
// ---------- 设备态(device):需长期 JWT ----------
router.get('/api/scanner/me', scannerAuth, controller.device.self.me);
router.post('/api/scanner/heartbeat', scannerAuth, controller.device.self.heartbeat);
router.post('/api/scan/channels', scannerAuth, controller.device.scan.reportChannels);
// 上报(写)额外检查主体是否过期/停用:过期后返回 403 subject_expired,设备暂停推送并靠心跳探测续期
router.post('/api/scan/channels', scannerAuth, subjectActive, controller.device.scan.reportChannels);
router.get('/api/scan/channels', scannerAuth, controller.device.scan.channels);
router.post('/api/scan/records', scannerAuth, controller.device.scan.reportRecords);
router.post('/api/scan/records', scannerAuth, subjectActive, controller.device.scan.reportRecords);
router.get('/api/scan/records', scannerAuth, controller.device.scan.records);
};

View File

@ -0,0 +1,114 @@
'use strict';
const { Service } = require('egg');
const { verifyAcceptance } = require('../lib/agreement');
/**
* 协议服务
*
* - `listCurrent()`:所有启用协议 + 当前已发布版本(公开接口下发)
* - `requiredVersions()`:其中「登录必须同意」的协议
* - `verifyAcceptance()`:校验客户端提交的版本是不是当前版本(纯函数,见 app/lib/agreement.js)
* - `record()`:把同意记录落库(同一用户 + 同一版本只更新时间)
*/
class AgreementService extends Service {
get Agreement() {
return this.app.model.Agreement;
}
get AgreementVersion() {
return this.app.model.AgreementVersion;
}
get UserAgreement() {
return this.app.model.UserAgreement;
}
/** 启用中、且有已发布当前版本的协议 */
async listCurrent() {
const rows = await this.Agreement.findAll({
where: { status: 1 },
include: [{
model: this.AgreementVersion,
as: 'currentVersion',
required: true,
where: { status: 1 },
}],
order: [[ 'sortNo', 'ASC' ], [ 'id', 'ASC' ]],
});
return rows.map(row => this.toPublic(row.toJSON()));
}
/** 登录必须同意的协议(没有配置时返回空数组 → 登录不受影响) */
async requiredVersions() {
const list = await this.listCurrent();
return list.filter(item => item.required && item.version);
}
verifyAcceptance(required, accepted) {
return verifyAcceptance(required, accepted);
}
/** 落库:返回本次记录(客户端可用于回显已同意的版本) */
async record(userId, accepted, meta = {}) {
const now = new Date();
const source = String(meta.source || '').slice(0, 32) || null;
const ip = String(meta.ip || '').slice(0, 64) || null;
const userAgent = String(meta.userAgent || '').slice(0, 255) || null;
const recorded = [];
for (const item of accepted) {
const [ row, created ] = await this.UserAgreement.findOrCreate({
where: {
userId,
agreementId: item.agreementId,
versionId: item.versionId,
},
defaults: {
version: item.version,
source,
ip,
userAgent,
agreedAt: now,
},
});
if (!created) {
await row.update({ version: item.version, source, ip, userAgent, agreedAt: now });
}
recorded.push({
code: item.code,
versionId: item.versionId,
version: item.version,
agreedAt: (created ? now : row.agreedAt) || now,
});
}
return recorded;
}
/** 模型 → 公开结构(不要把 status / 内部字段都丢给客户端) */
toPublic(row) {
const version = row.currentVersion;
if (!version) return null;
return {
id: Number(row.id),
code: row.code,
name: row.name,
description: row.description || '',
required: Number(row.required) === 1,
sortNo: Number(row.sortNo || 0),
version: {
id: Number(version.id),
version: version.version,
title: version.title,
summary: version.summary || '',
content: version.content,
contentType: version.contentType || 'text',
publishedAt: version.publishedAt,
effectiveAt: version.effectiveAt,
},
};
}
}
module.exports = AgreementService;

View File

@ -227,6 +227,8 @@ class SubjectService extends Service {
}
await subject.update(fields);
// 名称 / 状态 / 期限都可能变,让设备心跳与上报判断立刻读到新值
await this.ctx.service.subjectState.invalidate(subjectId);
const member = await this.memberOf(subject.id, userId);
return this.present(subject, {
role: member ? Number(member.role) : 2,

View File

@ -0,0 +1,191 @@
'use strict';
const { Service } = require('egg');
const crypto = require('crypto');
const DAY_MS = 24 * 3600 * 1000;
const STATUS_TEXT = { 0: '待支付', 1: '已支付', 2: '已关闭' };
/**
* 主体续期订单 service
*
* 流程:`create()` 下单(待支付)→ 支付渠道回调 `payNotify()` → 标记已支付 + 主体顺延 + 清状态缓存。
*
* 关键约定:
* - **支付靠回调驱动**:下单不改变期限,只有 `payNotify()` 成功才续期;
* - **幂等**:同一订单重复回调只续期一次(第二次返回 `duplicated: true`);
* - 续期基数与 `service.subject.update` 一致:未过期在原到期时间上顺延,已过期从当前时间起算。
*/
class SubjectOrderService extends Service {
get Order() {
return this.app.model.SubjectOrder;
}
get Subject() {
return this.app.model.Subject;
}
/** 创建订单(管理员):只建单,不动期限 */
async create({ subjectId, userId, days, amount, remark, channel = 'mock' } = {}) {
const { subject } = await this.ctx.service.subject.ensureAdmin(subjectId, userId);
const grantDays = Number(days);
if (!Number.isInteger(grantDays) || grantDays <= 0 || grantDays > 3650) {
this.ctx.throw(422, '续期天数必须是 1~3650 的整数');
}
const payCfg = this.config.pay || {};
const perDay = Number(payCfg.amountPerDay || 0);
let price = null;
if (amount !== undefined && amount !== null && amount !== '') {
price = Number(amount);
if (!Number.isFinite(price) || price < 0) this.ctx.throw(422, '金额不合法');
} else if (perDay > 0) {
price = Math.round(perDay * grantDays * 100) / 100;
}
const order = await this.Order.create({
orderNo: generateOrderNo(),
subjectId: Number(subject.id),
userId: Number(userId),
days: grantDays,
amount: price,
status: 0,
channel: channel || 'mock',
expireBefore: subject.expireAt,
remark: remark || null,
});
this.ctx.logger.info('[order] 用户 %s 为主体 %s 创建续期订单 %s(%s 天,金额 %s)',
userId, subject.id, order.orderNo, grantDays, price);
return this.present(order);
}
/** 某主体的订单列表(成员可见) */
async list({ subjectId, userId, page = 1, pageSize = 20 } = {}) {
await this.ctx.service.subject.findForUser(subjectId, userId);
const size = Math.min(Math.max(Number(pageSize) || 20, 1), 100);
const current = Math.max(Number(page) || 1, 1);
const result = await this.Order.findAndCountAll({
where: { subjectId: Number(subjectId) },
order: [[ 'id', 'DESC' ]],
limit: size,
offset: (current - 1) * size,
});
return {
total: result.count,
page: current,
pageSize: size,
list: result.rows.map(row => this.present(row)),
};
}
/**
* 支付通知(渠道回调):标记已支付 + 主体续期 + 失效状态缓存
*
* @param {object} params { orderNo, transactionId?, amount?, channel?, paidAt? }
* @return {Promise<object>} { duplicated, order }
*/
async payNotify({ orderNo, transactionId, amount, channel, paidAt } = {}) {
const no = String(orderNo || '').trim();
if (!no) this.ctx.throw(422, 'orderNo 不能为空');
if (no.length > 32) this.ctx.throw(422, 'orderNo 不合法');
const transaction = await this.app.model.transaction();
try {
const order = await this.Order.findOne({
where: { orderNo: no },
transaction,
lock: transaction.LOCK.UPDATE,
});
if (!order) this.ctx.throw(404, '订单不存在');
// 已支付:幂等返回(重复回调不重复续期)
if (Number(order.status) === 1) {
await transaction.rollback();
return { duplicated: true, order: this.present(order) };
}
if (Number(order.status) !== 0) this.ctx.throw(409, '订单状态不允许支付');
const paid = amount === undefined || amount === null || amount === '' ? null : Number(amount);
if (paid !== null) {
if (!Number.isFinite(paid) || paid < 0) this.ctx.throw(422, '支付金额不合法');
if (order.amount !== null && order.amount !== undefined && Math.abs(paid - Number(order.amount)) > 0.001) {
this.ctx.throw(422, '支付金额与订单金额不一致');
}
}
const subject = await this.Subject.findByPk(Number(order.subjectId), {
transaction,
lock: transaction.LOCK.UPDATE,
});
if (!subject) this.ctx.throw(404, '订单对应的主体不存在');
const beforeMs = subject.expireAt ? new Date(subject.expireAt).getTime() : Date.now();
const baseMs = beforeMs <= Date.now() ? Date.now() : beforeMs;
const expireAfter = new Date(baseMs + Number(order.days) * DAY_MS);
await subject.update({ expireAt: expireAfter }, { transaction });
await order.update({
status: 1,
channel: channel || order.channel || null,
transactionId: transactionId ? String(transactionId).slice(0, 64) : null,
paidAt: paidAt ? new Date(paidAt) : new Date(),
expireBefore: order.expireBefore || new Date(beforeMs),
expireAfter,
}, { transaction });
await transaction.commit();
// 续期后必须失效缓存:否则设备心跳/上报会继续看到「已过期」,最多延迟一个 TTL
await this.ctx.service.subjectState.invalidate(order.subjectId);
this.ctx.logger.info('[order] 订单 %s 已支付,主体 %s 续期 %s 天:%s → %s',
order.orderNo, order.subjectId, order.days,
new Date(beforeMs).toISOString(), expireAfter.toISOString());
return { duplicated: false, order: this.present(order) };
} catch (err) {
try {
await transaction.rollback();
} catch (_) {
// 忽略:事务可能已经被上面的分支回滚过
}
throw err;
}
}
present(order, extra = {}) {
return Object.assign({
id: Number(order.id),
orderNo: order.orderNo,
subjectId: Number(order.subjectId),
userId: Number(order.userId),
days: Number(order.days),
amount: order.amount === null || order.amount === undefined ? null : Number(order.amount),
status: Number(order.status),
statusText: STATUS_TEXT[Number(order.status)] || '未知',
channel: order.channel || null,
transactionId: order.transactionId || null,
paidAt: order.paidAt || null,
expireBefore: order.expireBefore || null,
expireAfter: order.expireAfter || null,
remark: order.remark || null,
createdAt: order.createdAt || null,
}, extra);
}
}
/** 订单号:SO + 年月日时分秒 + 6 位随机(32 位以内) */
function generateOrderNo() {
const now = new Date();
const pad = num => String(num).padStart(2, '0');
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`
+ `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
return `SO${stamp}${String(crypto.randomInt(0, 1000000)).padStart(6, '0')}`;
}
module.exports = SubjectOrderService;

View File

@ -0,0 +1,104 @@
'use strict';
const { Service } = require('egg');
/**
* 进程内兜底缓存:Redis 不可用(或单测没起 Redis)时,也保证高频读路径不查库。
* key = subjectId,value = { value, expiresAt }
*/
const localCache = new Map();
const LOCAL_MAX = 2000;
/**
* 主体状态缓存(**只给高频读路径用**:设备心跳、上报过期判断)
*
* - 只缓存判断「过期 / 停用」需要的几个字段,不缓存成员关系(角色校验仍走数据库);
* - Redis 命中优先(多实例共享),Redis 不可用时退化为进程内 TTL 缓存;
* - 续期 / 改名 / 停用后必须调用 `invalidate()`,否则最多有一个 TTL 的延迟。
*/
class SubjectStateService extends Service {
get ttlSeconds() {
const cfg = this.config.subject || {};
const ttl = Number(cfg.stateCacheTtl);
return Number.isFinite(ttl) && ttl > 0 ? ttl : 30;
}
get Subject() {
return this.app.model.Subject;
}
cacheKey(subjectId) {
return `subject:state:${Number(subjectId)}`;
}
/**
* 读主体状态(缓存命中不回源);主体不存在返回 null
* @param {number|string} subjectId
* @return {Promise<object|null>}
*/
async get(subjectId) {
const id = Number(subjectId);
if (!Number.isInteger(id) || id <= 0) return null;
const cachedLocal = localCache.get(id);
if (cachedLocal && cachedLocal.expiresAt > Date.now()) return decorate(cachedLocal.value);
const cached = await this.ctx.service.cache.get(this.cacheKey(id));
if (cached) {
rememberLocal(id, cached, this.ttlSeconds);
return decorate(cached);
}
const row = await this.Subject.findByPk(id);
if (!row) return null;
const value = {
id: Number(row.id),
name: row.name,
adminUserId: Number(row.adminUserId),
status: Number(row.status),
expireAt: row.expireAt ? new Date(row.expireAt).toISOString() : null,
};
await this.ctx.service.cache.set(this.cacheKey(id), value, this.ttlSeconds);
rememberLocal(id, value, this.ttlSeconds);
return decorate(value);
}
/** 续期 / 改名 / 停用 / 删除之后调用(写库成功后),避免继续读到旧状态 */
async invalidate(subjectId) {
const id = Number(subjectId);
if (!id) return;
localCache.delete(id);
await this.ctx.service.cache.del(this.cacheKey(id));
}
/** 单测用:清空进程内缓存,避免用例之间互相污染 */
clearLocalCache() {
localCache.clear();
}
}
/** 每次读取都按服务器当前时间派生 expired / remainingSeconds(缓存里只存静态字段) */
function decorate(value) {
const expireMs = value.expireAt ? new Date(value.expireAt).getTime() : null;
const now = Date.now();
return Object.assign({}, value, {
expired: expireMs !== null && expireMs <= now,
disabled: Number(value.status) !== 1,
remainingSeconds: expireMs === null ? null : Math.max(0, Math.floor((expireMs - now) / 1000)),
});
}
function rememberLocal(id, value, ttlSeconds) {
if (localCache.size >= LOCAL_MAX) {
const now = Date.now();
for (const [ key, item ] of localCache) {
if (item.expiresAt <= now) localCache.delete(key);
}
if (localCache.size >= LOCAL_MAX) localCache.clear();
}
localCache.set(id, { value, expiresAt: Date.now() + ttlSeconds * 1000 });
}
module.exports = SubjectStateService;

View File

@ -59,10 +59,22 @@ module.exports = (appInfo) => {
.filter(id => Number.isInteger(id) && id > 0),
};
// ==================== 协议(登录前同意) ====================
// 三张表:agreements / agreement_versions / user_agreements(见 database/migrations)
// enforce:
// 'mini_program'(默认)→ 只有声明 client=mini_program 的登录必须带当前协议版本
// 'all' → 所有客户端都必须(Web 登录表单也要先接入协议,否则会被 428 拦住)
// 'off' → 不校验(仍会记录主动提交的同意版本)
config.agreement = {
enforce: String(env.AGREEMENT_ENFORCE || 'mini_program').trim().toLowerCase(),
};
// ==================== 主体(租户)====================
// 新建主体默认赠送的试用天数(app/service/subject.js 用)
config.subject = {
trialDays: Number(env.SUBJECT_TRIAL_DAYS || 7),
// 主体状态(过期 / 停用)缓存秒数:设备心跳与上报判断都读它,续期后由写库方主动失效
stateCacheTtl: Number(env.SUBJECT_STATE_CACHE_TTL || 30),
};
// ==================== 服务端口 ==================== // 本地默认 **7300**(曾用 7001;避免与别的项目撞,也方便和前端 7301 排在一起)
@ -155,6 +167,20 @@ module.exports = (appInfo) => {
throw new Error('[config] 生产环境必须通过环境变量 JWT_SECRET 指定 JWT 签名密钥');
}
// ==================== 支付(续期订单) ====================
// 真实支付渠道还没接:先把「订单 + 支付通知回调」的契约定下来,
// 渠道接入后只要按同样格式回调 `POST /api/pay/notify` 即可完成续期。
config.pay = {
// 模拟模式:允许不带签名直接回调(仅开发/测试;生产默认关闭,需要显式 PAY_MOCK=true)
mock: env.PAY_MOCK === undefined
? appInfo.env !== 'prod'
: !/^(0|false|no|off)$/i.test(String(env.PAY_MOCK)),
// 回调签名密钥(HMAC-SHA256);配了就必须带 X-Pay-Sign
callbackSecret: env.PAY_CALLBACK_SECRET || '',
// 每天默认价格(0 = 不校验金额,方便内部测试)
amountPerDay: Number(env.PAY_AMOUNT_PER_DAY || 0),
};
// ==================== 业务配置 ====================
config.cache = {
// 缓存 key 前缀,多项目共用一个 Redis 时用来隔离

View File

@ -0,0 +1,39 @@
'use strict';
/**
* 主体续期订单
*
* 真实支付渠道还没接:先把「下单 → 渠道回调 → 主体续期」的链路落库,
* 回调格式见 `app/controller/pay/notify.js`(模拟回调见 README)。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, TINYINT, INTEGER, DECIMAL, DATE } = Sequelize;
await queryInterface.createTable('subject_orders', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
order_no: { type: STRING(32), allowNull: false, unique: true, comment: '订单号(对外唯一)' },
subject_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '主体 subjects.id' },
user_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '下单用户 users.id' },
days: { type: INTEGER.UNSIGNED, allowNull: false, comment: '续期天数' },
amount: { type: DECIMAL(10, 2), allowNull: true, comment: '应付金额(为空表示不校验)' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '状态:0待支付 1已支付 2已关闭' },
channel: { type: STRING(16), allowNull: true, comment: '支付渠道(mock 等)' },
transaction_id: { type: STRING(64), allowNull: true, comment: '渠道流水号' },
paid_at: { type: DATE, allowNull: true, comment: '支付时间' },
expire_before: { type: DATE, allowNull: true, comment: '续期前的到期时间' },
expire_after: { type: DATE, allowNull: true, comment: '续期后的到期时间' },
remark: { type: STRING(255), allowNull: true, comment: '备注' },
created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
deleted_at: { type: DATE, allowNull: true },
}, { comment: '主体续期订单表' });
await queryInterface.addIndex('subject_orders', [ 'subject_id' ], { name: 'idx_subject_orders_subject' });
await queryInterface.addIndex('subject_orders', [ 'status' ], { name: 'idx_subject_orders_status' });
},
async down(queryInterface) {
await queryInterface.dropTable('subject_orders');
},
};

View File

@ -0,0 +1,108 @@
'use strict';
/**
* 协议 / 协议版本 / 用户协议同意记录
*
* 协议内容没有管理界面:新增版本直接走 SQL(见 backend/README「用户协议」一节),
* 这里只负责三张表的结构与索引。
*/
module.exports = {
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, TINYINT, INTEGER, TEXT, DATE } = Sequelize;
await queryInterface.createTable('agreements', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
code: { type: STRING(64), allowNull: false, unique: true, comment: '协议标识(user_agreement 等)' },
name: { type: STRING(128), allowNull: false, comment: '协议名称(展示用)' },
description: { type: STRING(255), allowNull: true, comment: '简介' },
required: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '登录是否必须同意:1是 0否' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1启用 0停用' },
sort_no: { type: INTEGER.UNSIGNED, allowNull: false, defaultValue: 0, comment: '展示排序' },
// 不建外键:agreements ↔ agreement_versions 互相引用,建表顺序会互相依赖
current_version_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '当前生效版本 agreement_versions.id' },
created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
deleted_at: { type: DATE, allowNull: true },
}, { comment: '协议定义表' });
await queryInterface.addIndex('agreements', [ 'status' ], { name: 'idx_agreements_status' });
await queryInterface.createTable('agreement_versions', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
agreement_id: {
type: BIGINT.UNSIGNED,
allowNull: false,
references: { model: 'agreements', key: 'id' },
onUpdate: 'CASCADE',
onDelete: 'RESTRICT',
comment: 'agreements.id',
},
version: { type: STRING(32), allowNull: false, comment: '版本号(1.0.0)' },
title: { type: STRING(128), allowNull: false, comment: '版本标题' },
summary: { type: STRING(255), allowNull: true, comment: '变更摘要' },
content: { type: TEXT('long'), allowNull: false, comment: '协议正文' },
content_type: { type: STRING(16), allowNull: false, defaultValue: 'text', comment: '正文类型:text / html' },
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:0草稿 1已发布 2已归档' },
published_at: { type: DATE, allowNull: true, comment: '发布时间' },
effective_at: { type: DATE, allowNull: true, comment: '生效时间' },
created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
deleted_at: { type: DATE, allowNull: true },
}, { comment: '协议版本表' });
await queryInterface.addIndex('agreement_versions', [ 'agreement_id', 'version' ], {
name: 'uk_agreement_versions_agreement_version',
unique: true,
});
await queryInterface.addIndex('agreement_versions', [ 'status' ], { name: 'idx_agreement_versions_status' });
await queryInterface.createTable('user_agreements', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, allowNull: false },
user_id: {
type: BIGINT.UNSIGNED,
allowNull: false,
references: { model: 'users', key: 'id' },
onUpdate: 'CASCADE',
onDelete: 'CASCADE',
comment: 'users.id',
},
agreement_id: {
type: BIGINT.UNSIGNED,
allowNull: false,
references: { model: 'agreements', key: 'id' },
onUpdate: 'CASCADE',
onDelete: 'RESTRICT',
comment: 'agreements.id',
},
version_id: {
type: BIGINT.UNSIGNED,
allowNull: false,
references: { model: 'agreement_versions', key: 'id' },
onUpdate: 'CASCADE',
onDelete: 'RESTRICT',
comment: 'agreement_versions.id',
},
version: { type: STRING(32), allowNull: false, comment: '同意时的版本号快照' },
source: { type: STRING(32), allowNull: true, comment: '来源:mini_program / web / h5' },
ip: { type: STRING(64), allowNull: true, comment: '同意时的客户端 IP' },
user_agent: { type: STRING(255), allowNull: true, comment: '同意时的 User-Agent' },
agreed_at: { type: DATE, allowNull: false, comment: '同意时间' },
created_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
updated_at: { type: DATE, allowNull: false, defaultValue: Sequelize.literal('CURRENT_TIMESTAMP') },
deleted_at: { type: DATE, allowNull: true },
}, { comment: '用户协议同意记录表' });
await queryInterface.addIndex('user_agreements', [ 'user_id', 'agreement_id', 'version_id' ], {
name: 'uk_user_agreements_user_agreement_version',
unique: true,
});
await queryInterface.addIndex('user_agreements', [ 'user_id' ], { name: 'idx_user_agreements_user' });
await queryInterface.addIndex('user_agreements', [ 'agreement_id' ], { name: 'idx_user_agreements_agreement' });
},
async down(queryInterface) {
await queryInterface.dropTable('user_agreements');
await queryInterface.dropTable('agreement_versions');
await queryInterface.dropTable('agreements');
},
};

View File

@ -0,0 +1,151 @@
'use strict';
/** 内置示例协议:正式上线前请用 SQL 替换成法务确认后的正文(见 backend/README) */
const AGREEMENT_CODE = 'user_agreement';
const VERSION = '1.0.0';
const CONTENT = `【示例文本】本协议为系统内置示例,正式上线前请替换为经法务确认的正式文本。
云仓视频溯源系统用户协议
欢迎使用云仓视频溯源系统(以下简称“本系统”)。在注册、登录或使用本系统前,请您仔细阅读并充分理解本协议全部内容,特别是免除或限制责任的条款。您勾选“我已阅读并同意”并登录,即表示您已阅读、理解并同意受本协议约束。
一、服务说明
1. 本系统为仓储打包环节提供视频溯源、扫码记录、设备与摄像头管理等服务。
2. 具体功能以本系统实际提供为准;部分功能可能需要另行开通或付费。
二、账号与安全
1. 您应使用真实、合法的信息注册账号,并妥善保管账号及密码。
2. 通过您的账号进行的操作视为您本人的行为,由此产生的后果由您承担。
3. 发现账号被盗用或存在安全风险时,请立即修改密码并通知我们。
三、用户信息与授权
1. 为向您提供服务,我们需要收集必要的账号信息、设备信息与操作记录。
2. 您同意我们按照《隐私政策》处理您的个人信息;本协议与隐私政策不一致的,以隐私政策为准。
3. 未经您同意,我们不会向无关第三方提供您的个人信息,法律法规另有规定的除外。
四、视频与业务数据
1. 您应确保对上传、录制或接入的视频及业务数据拥有合法权利,不得侵犯他人合法权益。
2. 视频与扫码记录仅用于打包溯源、纠纷核查等业务目的,您应在必要期限后自行清理。
3. 您不得利用本系统从事违法活动,或录制、传播法律禁止的内容。
五、使用规范
1. 不得干扰、破坏本系统的正常运行,不得利用技术手段批量抓取数据。
2. 不得将账号出借、转让或出售给他人使用。
3. 违反上述约定的,我们有权限制或终止服务,并保留追究法律责任的权利。
六、知识产权
本系统及其相关的软件、界面、文档等知识产权归我们或相关权利人所有。未经许可,您不得复制、修改、反编译或用于本协议约定之外的用途。
七、服务变更、中断与终止
1. 我们可能根据业务需要调整服务内容,并通过系统公告等方式通知您。
2. 因系统维护、升级或不可抗力导致服务中断的,我们将尽力提前通知并尽快恢复。
3. 您违反本协议或法律法规的,我们有权暂停或终止向您提供服务。
八、免责声明
1. 因您自身操作不当、设备故障、网络异常或不可抗力造成的损失,我们在法律允许的范围内不承担责任。
2. 本系统按“现状”提供,我们不对服务的绝对不间断、无差错作出保证。
九、协议的变更
1. 我们可能适时修订本协议,修订后的协议将在系统内公布。
2. 协议生效后,您继续使用本系统即视为接受修订后的协议;如您不同意,请停止使用。
十、法律适用与争议解决
本协议适用中华人民共和国法律。因本协议产生的争议,双方应友好协商解决;协商不成的,任何一方可向我们所在地有管辖权的人民法院提起诉讼。
十一、联系我们
如您对本协议有任何疑问,可通过系统内的联系方式与我们联系。
(完)`;
async function findOne(queryInterface, sql, replacements) {
const [rows] = await queryInterface.sequelize.query(sql, { replacements });
return rows[0] || null;
}
module.exports = {
async up(queryInterface) {
const now = new Date();
let agreement = await findOne(
queryInterface,
'SELECT id FROM agreements WHERE code = ? LIMIT 1',
[ AGREEMENT_CODE ],
);
if (!agreement) {
await queryInterface.bulkInsert('agreements', [{
code: AGREEMENT_CODE,
name: '用户协议',
description: '使用云仓视频溯源系统前需阅读并同意的服务协议',
required: 1,
status: 1,
sort_no: 10,
current_version_id: null,
created_at: now,
updated_at: now,
}]);
agreement = await findOne(
queryInterface,
'SELECT id FROM agreements WHERE code = ? LIMIT 1',
[ AGREEMENT_CODE ],
);
}
let version = await findOne(
queryInterface,
'SELECT id FROM agreement_versions WHERE agreement_id = ? AND version = ? LIMIT 1',
[ agreement.id, VERSION ],
);
if (!version) {
await queryInterface.bulkInsert('agreement_versions', [{
agreement_id: agreement.id,
version: VERSION,
title: '用户协议',
summary: '首版协议',
content: CONTENT,
content_type: 'text',
status: 1,
published_at: now,
effective_at: now,
created_at: now,
updated_at: now,
}]);
version = await findOne(
queryInterface,
'SELECT id FROM agreement_versions WHERE agreement_id = ? AND version = ? LIMIT 1',
[ agreement.id, VERSION ],
);
}
await queryInterface.sequelize.query(
'UPDATE agreements SET current_version_id = ?, updated_at = ? WHERE id = ?',
{ replacements: [ version.id, now, agreement.id ] },
);
},
async down(queryInterface) {
const agreement = await findOne(
queryInterface,
'SELECT id FROM agreements WHERE code = ? LIMIT 1',
[ AGREEMENT_CODE ],
);
if (!agreement) return;
await queryInterface.sequelize.query(
'UPDATE agreements SET current_version_id = NULL WHERE id = ?',
{ replacements: [ agreement.id ] },
);
await queryInterface.sequelize.query(
'DELETE FROM user_agreements WHERE agreement_id = ?',
{ replacements: [ agreement.id ] },
);
await queryInterface.sequelize.query(
'DELETE FROM agreement_versions WHERE agreement_id = ?',
{ replacements: [ agreement.id ] },
);
await queryInterface.sequelize.query(
'DELETE FROM agreements WHERE id = ?',
{ replacements: [ agreement.id ] },
);
},
};

View File

@ -0,0 +1,158 @@
'use strict';
const { app, mock, assert } = require('egg-mock/bootstrap');
const jwt = require('jsonwebtoken');
/** 假实例:update 时把字段同时合并回实例自身 */
const instance = data => {
const obj = {
toJSON: () => data,
update: async fields => {
Object.assign(data, fields);
Object.assign(obj, fields);
},
};
return Object.assign(obj, data);
};
/** 与服务端一致的密钥/签发者,造一个中控(扫描器)JWT */
function signToken() {
return jwt.sign(
{ sub: '1', sn: 'SN-HUB-01', typ: 'scanner', jti: 'jti-1' },
app.config.jwt.secret,
{
algorithm: 'HS256',
expiresIn: '365d',
issuer: app.config.jwt.issuer,
audience: app.config.jwt.audience,
},
);
}
/**
* 设备上报的主体期限限制
*
* 重点:
* - 过期 / 停用 → 写接口 403(`subject_expired` / `subject_disabled`);
* - 状态读 `service.subjectState` 缓存,**连续请求只查一次库**;
* - 心跳是探测通道:不因过期返回 403,并返回 `subject.expired` 供设备暂停/恢复;
* - 续期后失效缓存,下一次请求立即恢复。
*/
describe('test/app/controller/subject-expiry.test.js', () => {
const SUBJECT_ID = 21;
const token = () => `Bearer ${signToken()}`;
const authScanner = () => instance({
id: 1,
sn: 'SN-HUB-01',
status: 1,
tokenJti: 'jti-1',
subjectId: SUBJECT_ID,
userId: 1,
});
const authSubject = expireAt => instance({
id: SUBJECT_ID,
name: '测试主体',
adminUserId: 1,
status: 1,
expireAt,
});
beforeEach(() => {
app.createAnonymousContext().service.subjectState.clearLocalCache();
});
/** 正常入库所需的最小模型集合 */
function mockModels({ subject, reads }) {
mock(app, 'model', {
User: {},
Scanner: { async findByPk() { return authScanner(); } },
Subject: {
async findByPk() {
if (reads) reads.count++;
return typeof subject === 'function' ? subject() : subject;
},
},
ScanChannel: {
async findAll() { return []; },
async bulkCreate(items) { return items; },
async update() { return [ 1 ]; },
},
ScanRecord: {
async findAll() { return []; },
async bulkCreate(items) { return items; },
},
});
}
const body = { records: [{ barcode: 'B1', scanTime: '2026-10-20 10:00:00', channelId: '1' }] };
it('主体过期:上报 403 subject_expired,且第二次请求命中缓存不再查库', async () => {
const reads = { count: 0 };
mockModels({ subject: authSubject(new Date(Date.now() - 60 * 1000)), reads });
const first = await app.httpRequest().post('/api/scan/records').set('Authorization', token()).send(body).expect(403);
assert(first.body.status === 'subject_expired', JSON.stringify(first.body));
assert(first.body.remainingSeconds === 0);
assert(reads.count === 1, `首次应查库一次,实际 ${reads.count}`);
const second = await app.httpRequest().post('/api/scan/records').set('Authorization', token()).send(body).expect(403);
assert(second.body.status === 'subject_expired');
assert(reads.count === 1, `第二次应命中缓存(仍为 1 次),实际 ${reads.count}`);
});
it('主体停用:上报 403 subject_disabled', async () => {
mockModels({ subject: instance({ id: SUBJECT_ID, name: '停用主体', adminUserId: 1, status: 0, expireAt: new Date(Date.now() + 86400000) }) });
const res = await app.httpRequest().post('/api/scan/channels').set('Authorization', token())
.send({ channels: [{ channelId: 'C1', channelName: '通道一' }] }).expect(403);
assert(res.body.status === 'subject_disabled', JSON.stringify(res.body));
});
it('主体不存在:上报 403 subject_missing(不静默放行)', async () => {
mockModels({ subject: null });
const res = await app.httpRequest().post('/api/scan/records').set('Authorization', token()).send(body).expect(403);
assert(res.body.status === 'subject_missing', JSON.stringify(res.body));
});
it('续期后失效缓存:下一批上报立即恢复', async () => {
let expireAt = new Date(Date.now() - 60 * 1000);
const reads = { count: 0 };
mockModels({ subject: () => authSubject(expireAt), reads });
await app.httpRequest().post('/api/scan/records').set('Authorization', token()).send(body).expect(403);
// 模拟续期:写库 + 失效缓存
expireAt = new Date(Date.now() + 30 * 86400000);
await app.createAnonymousContext().service.subjectState.invalidate(SUBJECT_ID);
const res = await app.httpRequest().post('/api/scan/records').set('Authorization', token()).send(body).expect(200);
assert(res.body.data.received === 1, JSON.stringify(res.body));
assert(reads.count === 2, `续期后应重新回源一次,实际 ${reads.count}`);
});
it('心跳返回主体状态(供设备暂停/恢复),且连续心跳不重复查库', async () => {
const reads = { count: 0 };
mockModels({ subject: authSubject(new Date(Date.now() + 2 * 3600 * 1000)), reads });
const first = await app.httpRequest().post('/api/scanner/heartbeat').set('Authorization', token()).expect(200);
assert(first.body.data.subject, JSON.stringify(first.body));
assert(first.body.data.subject.expired === false);
assert(first.body.data.subject.remainingSeconds > 0);
assert(typeof first.body.data.serverTime === 'string');
const second = await app.httpRequest().post('/api/scanner/heartbeat').set('Authorization', token()).expect(200);
assert(second.body.data.subject.expired === false);
assert(reads.count === 1, `心跳应读缓存(仍为 1 次),实际 ${reads.count}`);
});
it('心跳在主体过期时仍 200,并明确返回 expired=true', async () => {
mockModels({ subject: authSubject(new Date(Date.now() - 1000)) });
const res = await app.httpRequest().post('/api/scanner/heartbeat').set('Authorization', token()).expect(200);
assert(res.body.data.subject.expired === true, JSON.stringify(res.body));
assert(res.body.data.subject.remainingSeconds === 0);
});
});

View File

@ -0,0 +1,202 @@
'use strict';
const { app, mock, assert } = require('egg-mock/bootstrap');
const crypto = require('crypto');
/** 假实例:update 时把字段同时合并回实例自身(present 读的是实例属性) */
const instance = data => {
const obj = {
toJSON: () => data,
update: async fields => {
Object.assign(data, fields);
Object.assign(obj, fields);
},
};
return Object.assign(obj, data);
};
const USER = { id: 1, username: 'admin', nickname: '管理员', status: 1 };
const SUBJECT_ID = 21;
/**
* 续期订单 + 支付回调
*
* 重点:
* - 下单只建单(待支付),不动期限;
* - 支付回调才续期,并**失效主体状态缓存**(设备心跳/上报立刻看到新期限);
* - 重复回调幂等(`duplicated: true`,不重复续期);
* - 配了回调密钥就校验签名。
*/
describe('test/app/controller/subject-order.test.js', () => {
const token = () => `Bearer ${app.createAnonymousContext().service.jwt.signUser(USER)}`;
const auth = () => ({ Authorization: token() });
const subjectRow = expireAt => instance({
id: SUBJECT_ID,
name: '测试主体',
adminUserId: 1,
status: 1,
expireAt,
});
const orderRow = (overrides = {}) => instance(Object.assign({
id: 100,
orderNo: 'SO20261020120000000001',
subjectId: SUBJECT_ID,
userId: 1,
days: 30,
amount: 99,
status: 0,
channel: 'mock',
transactionId: null,
paidAt: null,
expireBefore: new Date(Date.now() - 86400000),
expireAfter: null,
remark: null,
createdAt: new Date(),
}, overrides));
function fakeTransaction(log = []) {
return {
LOCK: { UPDATE: 'UPDATE' },
async commit() { log.push('commit'); },
async rollback() { log.push('rollback'); },
};
}
function mockModels({ memberRole = 1, subject, order, log } = {}) {
mock(app, 'model', {
User: { async findByPk() { return instance(Object.assign({}, USER)); } },
SubjectMember: {
async findOne() {
return instance({ id: 11, subjectId: SUBJECT_ID, userId: 1, name: '管理员', role: memberRole, status: 1 });
},
},
Subject: {
async findByPk() { return typeof subject === 'function' ? subject() : subject; },
},
SubjectOrder: {
async create(fields) { return orderRow(Object.assign({ id: 101 }, fields)); },
async findOne() { return typeof order === 'function' ? order() : order; },
async findAndCountAll() { return { rows: [ orderRow() ], count: 1 }; },
},
transaction: async () => fakeTransaction(log),
});
}
beforeEach(() => {
app.createAnonymousContext().service.subjectState.clearLocalCache();
});
it('POST /api/web/subjects/:id/orders:管理员下单 → 201(待支付,不动期限)', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() - 86400000)) });
const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ days: 30, amount: 99 }).expect(201);
assert(res.body.data.orderNo, JSON.stringify(res.body));
assert(res.body.data.status === 0 && res.body.data.days === 30);
assert(res.body.data.amount === 99);
});
it('POST /api/web/subjects/:id/orders:普通成员不能下单(403)', async () => {
mockModels({
memberRole: 2,
subject: instance({ id: SUBJECT_ID, name: '别人的主体', adminUserId: 99, status: 1, expireAt: new Date(Date.now() + 86400000) }),
});
await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ days: 30 }).expect(403);
});
it('POST /api/web/subjects/:id/orders:天数非法 → 422', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)) });
await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ days: 0 }).expect(422);
await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ days: 3651 }).expect(422);
});
it('POST /api/pay/notify:支付成功后主体续期,且缓存失效(设备立刻看到新期限)', async () => {
const log = [];
const order = orderRow();
const subject = subjectRow(new Date(Date.now() - 86400000));
mockModels({ subject: () => subject, order: () => order, log });
// 先预热缓存:此刻是「已过期」
const before = await app.createAnonymousContext().service.subjectState.get(SUBJECT_ID);
assert(before.expired === true, JSON.stringify(before));
const res = await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: order.orderNo, transactionId: 'TXN-1', amount: 99 })
.expect(200);
assert(res.body.data.duplicated === false, JSON.stringify(res.body));
assert(res.body.data.order.status === 1);
assert(log.includes('commit'));
const after = await app.createAnonymousContext().service.subjectState.get(SUBJECT_ID);
assert(after.expired === false, JSON.stringify(after));
assert(after.remainingSeconds > 29 * 86400, `续期 30 天后应剩余约 30 天,实际 ${after.remainingSeconds}`);
});
it('POST /api/pay/notify:重复回调幂等(不重复续期)', async () => {
const log = [];
const order = orderRow({ status: 1 });
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => order, log });
const res = await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: order.orderNo, amount: 99 })
.expect(200);
assert(res.body.data.duplicated === true, JSON.stringify(res.body));
assert(log.includes('rollback'), '已支付的订单应回滚事务,不做任何写入');
});
it('POST /api/pay/notify:金额不符 → 422;订单不存在 → 404', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => orderRow() });
await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: 'SO20261020120000000001', amount: 1 })
.expect(422);
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => null });
await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: 'SO-NOT-EXIST' })
.expect(404);
});
it('POST /api/pay/notify:配了回调密钥必须带正确签名', async () => {
mock(app.config.pay, 'callbackSecret', 's3cret');
mock(app.config.pay, 'mock', false);
mockModels({ subject: subjectRow(new Date(Date.now() - 1000)), order: () => orderRow() });
await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: 'SO20261020120000000001', transactionId: 'TXN-1', amount: 99 })
.expect(400);
const sign = crypto.createHmac('sha256', 's3cret')
.update('SO20261020120000000001\nTXN-1\n99')
.digest('hex');
await app.httpRequest().post('/api/pay/notify')
.set('X-Pay-Sign', sign)
.send({ orderNo: 'SO20261020120000000001', transactionId: 'TXN-1', amount: 99 })
.expect(200);
});
it('POST /api/internal/subject-orders/:orderNo/pay:运维模拟支付(内部令牌)', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() - 1000)), order: () => orderRow() });
await app.httpRequest()
.post('/api/internal/subject-orders/SO20261020120000000001/pay')
.expect(401);
const res = await app.httpRequest()
.post('/api/internal/subject-orders/SO20261020120000000001/pay')
.set('X-Internal-Token', 'test-internal-token')
.expect(200);
assert(res.body.data.order.status === 1, JSON.stringify(res.body));
});
});

View File

@ -69,6 +69,60 @@ describe('test/app/controller/web.test.js', () => {
assert(res.body.ok === false, JSON.stringify(res.body));
});
const requiredAgreement = {
id: 9,
code: 'user_agreement',
name: '用户协议',
required: true,
version: { id: 11, version: '1.0.0', title: '用户协议', content: '正文' },
};
it('POST /api/web/auth/login:小程序未同意协议 → 428 agreement_required', async () => {
mock(app, 'redis', createFakeRedis().client);
mockUser();
app.mockService('agreement', 'requiredVersions', async () => [ requiredAgreement ]);
const res = await app.httpRequest()
.post('/api/web/auth/login')
.send({ account: 'admin', password: 'secret-pass', client: 'mini_program' })
.expect(428);
assert(res.body.status === 'agreement_required', JSON.stringify(res.body));
assert(res.body.data.agreements[0].code === 'user_agreement', JSON.stringify(res.body));
});
it('POST /api/web/auth/login:小程序同意当前版本 → 记录版本并登录成功', async () => {
mock(app, 'redis', createFakeRedis().client);
mockUser();
let recorded = null;
app.mockService('agreement', 'requiredVersions', async () => [ requiredAgreement ]);
app.mockService('agreement', 'record', async (userId, accepted) => {
recorded = { userId, accepted };
return accepted.map(item => ({
code: item.code,
versionId: item.versionId,
version: item.version,
agreedAt: new Date().toISOString(),
}));
});
const res = await app.httpRequest()
.post('/api/web/auth/login')
.send({
account: 'admin',
password: 'secret-pass',
client: 'mini_program',
agreements: [{ code: 'user_agreement', versionId: 11 }],
})
.expect(200);
assert(res.body.ok === true, JSON.stringify(res.body));
assert(recorded && recorded.userId === 1, JSON.stringify(recorded));
assert(recorded.accepted[0].versionId === 11 && recorded.accepted[0].version === '1.0.0', JSON.stringify(recorded));
assert(res.body.data.agreements[0].version === '1.0.0', JSON.stringify(res.body.data));
});
it('GET /api/web/me / PUT /api/web/me / PUT /api/web/me/password:都按令牌里的用户操作', async () => {
mock(app, 'redis', createFakeRedis().client);
let updated = null;

View File

@ -0,0 +1,60 @@
'use strict';
const assert = require('assert');
const { normalizeAccepted, verifyAcceptance } = require('../../../app/lib/agreement');
describe('test/app/lib/agreement.test.js', () => {
const required = [
{ id: 1, code: 'user_agreement', name: '用户协议', version: { id: 11, version: '1.0.0' } },
{ id: 2, code: 'privacy_policy', name: '隐私政策', version: { id: 21, version: '2.0.0' } },
];
it('normalizeAccepted:忽略非法项,按 code 取版本', () => {
const map = normalizeAccepted([
{ code: 'user_agreement', versionId: 11 },
{ code: ' ', versionId: 12 },
{ code: 'bad', versionId: 0 },
{ code: 'x', version_id: 21 },
null,
]);
assert.strictEqual(map.get('user_agreement'), 11);
assert.strictEqual(map.get('x'), 21);
assert.strictEqual(map.size, 2);
});
it('verifyAcceptance:一个都没同意 → ok=false,missing 列出全部', () => {
const result = verifyAcceptance(required, []);
assert.strictEqual(result.ok, false);
assert.strictEqual(result.missing.length, 2);
assert.strictEqual(result.accepted.length, 0);
});
it('verifyAcceptance:版本不是当前版本 → ok=false', () => {
const result = verifyAcceptance(required, [
{ code: 'user_agreement', versionId: 99 },
{ code: 'privacy_policy', versionId: 21 },
]);
assert.strictEqual(result.ok, false);
assert.deepStrictEqual(result.missing.map(item => item.code), [ 'user_agreement' ]);
});
it('verifyAcceptance:全部匹配 → 返回可落库条目', () => {
const result = verifyAcceptance(required, [
{ code: 'user_agreement', versionId: 11 },
{ code: 'privacy_policy', versionId: 21 },
{ code: 'extra', versionId: 1 },
]);
assert.strictEqual(result.ok, true);
assert.strictEqual(result.missing.length, 0);
assert.deepStrictEqual(result.accepted, [
{ agreementId: 1, code: 'user_agreement', name: '用户协议', versionId: 11, version: '1.0.0' },
{ agreementId: 2, code: 'privacy_policy', name: '隐私政策', versionId: 21, version: '2.0.0' },
]);
});
it('verifyAcceptance:没有必须同意的协议 → 直接通过', () => {
const result = verifyAcceptance([], []);
assert.strictEqual(result.ok, true);
assert.strictEqual(result.accepted.length, 0);
});
});

View File

@ -126,7 +126,13 @@ dotnet publish -c Release -r win-x64 -p:ServerBaseUrl=https://trace.example.com
逐台静默执行:
1. 用 8000 私有协议写 NTP(`NET_DVR_SET_NTPCFG`,与桌面端**同一个 NTP 地址**);
2. 立即生效:`NET_DVR_SET_TIMECFG` 把设备时间直接校准到 NTP 时间;
3. 回读 NTP 配置与设备时间,在窗口里逐台返回结果(✔/✘ + 偏差)。
3. **顺带把该录像机下的摄像头逐个校时**(`GET /api/web/nvrs/:id/channels` 拿通道号 →
`NET_DVR_SET_TIMECFG` 带通道号,录像机转发给 IPC),逐个通道报成功/失败;
4. 回读 NTP 配置与设备时间,在窗口里逐台返回结果(✔/✘ + 偏差 + 摄像头 n/m)。
- **为什么必须单独校摄像头**:画面里烧的 OSD 时间是**摄像头自己**的时钟,录像机录像用的是
录像机时钟 —— 两者互不相干。只校录像机时,有的 IPC 会自己跟随,有的不会(现场实测
通道 34 的 OSD 比录像机快 13 小时、通道 45 差约 2 年),回放再对齐也改不了这两行字。
个别第三方 IPC 会拒绝校时,窗口里会列出具体通道和错误(不影响其它通道)。
- 启动时校一次 + 运行期间默认每 **30 分钟**校一次;偏差小于 **0.2 秒**不调整。
- 实现:`Services/NtpClient.cs`(UDP 123 SNTP)+ `Services/ClockSyncService.cs`
(打开 `SeSystemtimePrivilege` 后调用 `SetSystemTime`);NVR 侧在 `HikDeviceService.GetNtpConfig/SetNtpConfig/SetDeviceTime`。
@ -513,6 +519,39 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command"
> 日志里能看到 `[playback] 录像机 … 与本机时钟相差 X 秒`。本机时间不准(比如 Windows
> 时间服务没开、慢了几秒)时,短回放窗口会把面单截到窗口外 —— 这一步就是防这个。
### 多路对齐(预览 / 合并下载)
几路回放是**各自独立连录像机**的,天然会有两处时间差,都要单独处理:
1. **开播时间差(预览)**:各路 RTSP 建链快慢不同,先出帧的那路会一直“跑在前面”。
`PlaybackPreviewWindow` 的做法是**先一起等、再按帧一起放**:
- ffmpeg **每出一帧回调一次**(`HikFfmpegService.Subscribe`)按顺序进各自队列。
⚠️ 不能定时去取“最新一帧”:ffmpeg 定位到关键帧后会把「关键帧→请求时间」整段一次吐出来,
只留最新帧会把这串前面全丢掉,那一路的“第一帧”其实是 1~2 秒后的画面(现象:小窗一出现就超前);
- 每一路都出过第一帧(最多等 12 秒,超时当这路没录像)后才开始播,每 40ms 从**每路队列各取一帧**,
先上线的那路放的就是等同步时攒下的积压 → 几路自然停在同一内容位置;
- 队列超过 220 帧(≈9 秒)就丢到 50 帧(≈2 秒),设备推得比实时快也不会越播越晚。
日志里出现 `[playback] 多路回放开始同步播放(各路基线帧数:…)` 就说明生效了。
**播到请求窗口就一起停**:录像机不会按 `endtime` 主动断流,各路停的时机还不一样
(实测一路到点停止、另一路还在往后推,看着就是一个窗先冻住),
所以到 `EndTime - StartTime` 时统一收尾、释放设备会话,标题变成「回放结束」。
2. **录制起点差(下载 / 合并 / 预览)**:回放是从“请求时间所在**关键帧**”开始推的,
各通道 GOP 位置不同 → 同一时间点开始拉的两段录像,第一帧能差好几秒;
不处理就会两格画面错开。
**用 `NET_DVR_GetPlayBackOsdTime` 读第一帧的真实内容时间**(8000 协议,实测可用):
- 下载:`PullPlaybackToFile` 在第一包数据到达时读一次,`偏移 = 首帧 OSD − 请求时间`,
合并时提前的路用 `trim` 切头、晚开始的路用 `setpts` 后移
(日志 `[playback] 通道N 首帧 OSD=hh:mm:ss,比请求时间早/晚 X 秒`);
- 预览:RTSP 侧拿不到内容时间,所以开窗前先用 `ProbePlaybackOsdStart` 每路探一次,
按 OSD 差值推迟出图(日志 `[playback] 预览按 OSD 起点对齐:…`)。
- 拿不到 OSD(固件不支持/无数据)才退回「时长反推」(`提前量 = 文件时长 − 请求窗口`);
偏差超过 60 秒视为通道时钟异常,不做对齐,绝不把画面推歪。
⚠️ 曾经只用「时长反推」,实测同一个窗口拉两次会得到 36.1s / 42.1s 两种结果
(关键帧起止 + 流在哪断都不固定),头和尾分不开 → 会随机差 2~4 秒,已弃用为首选。
3. **摄像头自身的时钟**:画面里烧的 OSD 时间是**摄像头自己**打的,和录像机的录像时间轴无关。
两个摄像头时钟不一致时,即便回放已经对齐,两格 OSD 也会差几小时甚至几年 ——
这不是回放错位,要在录像机里开「摄像机校时(IPC 校时)」或给 IPC 配 NTP 才能一致。
查询日志只记结论(`[pack-query] 运单号 → found=… records=… streams=…`),不再写完整 JSON;
要排查原始数据看后端日志或页面。
@ -631,7 +670,7 @@ reg query "HKCU\Software\Classes\yuncang\shell\open\command"
| IP 变化 | `ScanService.ApplyDiscoveredIps` | 每次发现结果回来就刷新各通道 `LastIp`,变了立即用新地址重连(DHCP 续租后不会卡在旧 IP) || 通道配置 | `Services/Scan/ChannelStore.cs` | `%LOCALAPPDATA%\YuncangTrace\channels.json`(服务模式:`%ProgramData%\YuncangTrace\channels.json`),通道号取最小空号、删除后不复用;**不再有团购/散单字段**(团散在「工作台」区分) |
| 编排 | `Services/Scan/ScanService.cs` | 启动→连接**全部**通道(没有启用/停用开关,加了就连);**通道一旦变动(增/删)自动同步到服务器**:`POST /api/scan/channels`(带 `replace: true`,全量对账)→ `GET /api/scan/channels` 回查确认 → 缺了就退避重试(1s→30s)直到服务器真的有;**删除通道会让服务器软删该通道并解绑工作台**(`removed` / `unbound`),删到 0 个也会推空列表 |
| 扫码记录 | `Services/Scan/ScanRecordStore.cs` | `%LOCALAPPDATA%\YuncangTrace\scan-records.json`(服务模式:`%ProgramData%\YuncangTrace\scan-records.json`),每个通道最多 5000 条;**先落本地、服务器确认后才标「已上传」**,没确认的一直重试,断网不丢;连续扫描只刷新「最近一次扫到的时间」;**扫到后 5 分钟没再扫到同一个码才上报**,上报的就是最后一次扫描时间;同一运单 24 小时内再次扫到会**重新激活同一条本地记录**(不新增行),下一轮上报覆盖服务器记录 |
| 上报队列 | `Services/DeviceService.cs` | 条码静默满 5 分钟后后台攒批(50 条/批)推 `POST /api/scan/records`,失败不标记、指数退避重发(服务端按 设备+通道+条码+秒 精确去重;**同一运单 24 小时内只保留一条,后上报的新时间会覆盖旧记录的时间与工作台快照**) |
| 上报队列 | `Services/DeviceService.cs` | 条码静默满 5 分钟后后台攒批(50 条/批)推 `POST /api/scan/records`,失败不标记、指数退避重发(服务端按 设备+通道+条码+秒 精确去重;**同一运单 24 小时内只保留一条,后上报的新时间会覆盖旧记录的时间与工作台快照**)。**主体过期/停用或令牌失效 → 暂停推送**(保留本地积压、不做无意义重试),暂停期间每 60 秒只发一次心跳;心跳返回 `subject.expired=false`(续费)后自动恢复并补传 |
### 添加通道(设备名 + 通道号)

View File

@ -262,7 +262,10 @@ public static class AgentHost
{
try
{
await api.HeartbeatAsync(settings.DeviceToken, ct).ConfigureAwait(false);
var beat = await api.HeartbeatAsync(settings.DeviceToken, ct).ConfigureAwait(false);
// 心跳顺带同步主体状态:过期/停用 → 上报循环暂停(GUI/服务两种模式都走这里)
device.ApplySubjectState(beat?.Subject);
if (lastHeartbeatAt is null)
{

View File

@ -12,13 +12,28 @@ namespace YuncangTrace.LocalService.Services;
/// <summary>接口调用失败(能拿到后端的 message 就透出去)</summary>
public sealed class ApiException : Exception
{
public ApiException(string message, int statusCode = 0) : base(message)
public ApiException(string message, int statusCode = 0, string? status = null, DateTimeOffset? expireAt = null)
: base(message)
{
StatusCode = statusCode;
Status = status;
ExpireAt = expireAt;
}
/// <summary>HTTP 状态码(网络层失败为 0)</summary>
public int StatusCode { get; }
/// <summary>后端 envelope 里的 `status`(如 `subject_expired` / `subject_disabled`)</summary>
public string? Status { get; }
/// <summary>主体到期时间(仅 `subject_expired` 时有)</summary>
public DateTimeOffset? ExpireAt { get; }
/// <summary>主体已过期:上报循环应暂停,等心跳探测到续期后再恢复</summary>
public bool IsSubjectExpired => Status == "subject_expired";
/// <summary>主体不可用(过期 / 停用 / 被删):都不该继续上报</summary>
public bool IsSubjectUnavailable => Status is "subject_expired" or "subject_disabled" or "subject_missing";
}
/// <summary>登录用户(后端 `/api/web/auth/login` 返回的 user 子集)</summary>
@ -59,6 +74,15 @@ public sealed record NvrCredential(int Id, string Name, string Host, int Port, s
/// <summary>录像机(列表用,不含密码)</summary>
public sealed record ApiNvr(int Id, string Name, string Host, int Port, string? SerialNumber);
/// <summary>摄像头 = 录像机上的一个通道(校时按 <see cref="ChannelNo"/> 走)</summary>
public sealed record ApiCamera(int Id, int ChannelNo, string Name, string? ChannelName)
{
/// <summary>界面显示名</summary>
public string Display => string.IsNullOrWhiteSpace(Name)
? (string.IsNullOrWhiteSpace(ChannelName) ? $"通道{ChannelNo}" : ChannelName!)
: Name;
}
/// <summary>激活设备服务的结果</summary>
public sealed record DeviceActivation(
int Id,
@ -81,6 +105,23 @@ public sealed record DeviceTokenRefresh(
string RefreshToken,
string? RefreshExpiresIn);
/// <summary>设备所属主体状态(心跳返回;`Expired` 由服务端按缓存计算,客户端不要用本地时间判断)</summary>
public sealed record DeviceSubjectState(
int Id,
string? Name,
int Status,
DateTimeOffset? ExpireAt,
bool Expired,
bool Disabled,
long? RemainingSeconds);
/// <summary>设备心跳结果:保活信息 + 主体租约状态</summary>
public sealed record DeviceHeartbeat(
string? Sn,
DateTimeOffset? LastSeenAt,
DateTimeOffset? ServerTime,
DeviceSubjectState? Subject);
/// <summary>
/// 后端接口客户端(登录 / 主体 / 设备服务 / 上报)
///
@ -119,7 +160,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
var token = GetString(data.Value, "token") ?? throw new ApiException("登录返回里没有令牌");
var user = ReadUser(data.Value);
@ -144,7 +185,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
var code = GetString(data.Value, "code") ?? throw new ApiException("没有拿到登录码");
var qrUrl = GetString(data.Value, "qrUrl") ?? $"/api/wechat/qrcode.svg?code={code}";
@ -160,7 +201,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
var status = GetString(data.Value, "status") ?? "pending";
if (status != "confirmed")
@ -229,7 +270,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
return ReadSubjects(data.Value, "list");
}
@ -243,7 +284,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
var devices = new List<ApiDevice>();
if (data.Value.TryGetProperty("list", out var list) && list.ValueKind == JsonValueKind.Array)
@ -274,7 +315,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
var kicked = new List<ApiDevice>();
if (data.Value.TryGetProperty("kicked", out var kickedElement) && kickedElement.ValueKind == JsonValueKind.Array)
@ -317,7 +358,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
return new DeviceTokenRefresh(
GetString(data.Value, "sn") ?? sn,
@ -336,18 +377,42 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
}
/// <summary>设备心跳(`POST /api/scanner/heartbeat`):刷新服务端 `last_seen_at`</summary>
public async Task HeartbeatAsync(string deviceToken, CancellationToken ct = default)
/// <summary>
/// 设备心跳(`POST /api/scanner/heartbeat`):刷新服务端 `last_seen_at`,
/// 同时带回主体状态(`subject.expired`),上报循环据此暂停/恢复。
/// </summary>
public async Task<DeviceHeartbeat?> HeartbeatAsync(string deviceToken, CancellationToken ct = default)
{
using var response = await SendDeviceAsync("/api/scanner/heartbeat", deviceToken, "{}", "设备心跳", ct)
.ConfigureAwait(false);
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
return new DeviceHeartbeat(
GetString(data.Value, "sn"),
GetDateTime(data.Value, "lastSeenAt"),
GetDateTime(data.Value, "serverTime"),
ReadSubjectState(data.Value));
}
/// <summary>解析心跳里的 `subject`(老服务端没有这个字段时返回 null)</summary>
private static DeviceSubjectState? ReadSubjectState(JsonElement data)
{
if (!data.TryGetProperty("subject", out var subject) || subject.ValueKind != JsonValueKind.Object) return null;
return new DeviceSubjectState(
GetInt(subject, "id"),
GetString(subject, "name"),
GetInt(subject, "status"),
GetDateTime(subject, "expireAt"),
subject.TryGetProperty("expired", out var expired) && expired.ValueKind == JsonValueKind.True,
subject.TryGetProperty("disabled", out var disabled) && disabled.ValueKind == JsonValueKind.True,
GetLong(subject, "remainingSeconds"));
}
/// <summary>
@ -366,7 +431,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
}
/// <summary>上报一条扫码记录(设备令牌;`POST /api/scan/records`,服务端按 设备+通道+条码+秒 去重)</summary>
@ -396,7 +461,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
}
/// <summary>
@ -415,7 +480,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
return data.Value;
}
@ -436,7 +501,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
if (!data.Value.TryGetProperty("list", out var list) || list.ValueKind != JsonValueKind.Array) break;
@ -470,7 +535,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
return new NvrCredential(
GetInt(data.Value, "id"),
@ -481,6 +546,36 @@ public sealed class ApiClient
GetString(data.Value, "password") ?? string.Empty);
}
/// <summary>
/// 取某台录像机下已导入的摄像头(用户令牌;`GET /api/web/nvrs/:id/channels`)。
///
/// 校时要按**通道号**逐个下发给 IPC,所以这里只关心 `channelNo`。
/// </summary>
public async Task<IReadOnlyList<ApiCamera>> CamerasOfNvrAsync(string token, int subjectId, int nvrId,
CancellationToken ct = default)
{
using var response = await SendAuthorizedAsync(HttpMethod.Get, $"/api/web/nvrs/{nvrId}/channels",
token, subjectId, null, "查摄像头列表", ct).ConfigureAwait(false);
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw Failure(response, text, message);
var result = new List<ApiCamera>();
if (!data.Value.TryGetProperty("list", out var list) || list.ValueKind != JsonValueKind.Array) return result;
foreach (var item in list.EnumerateArray())
{
result.Add(new ApiCamera(
GetInt(item, "id"),
GetInt(item, "channelNo"),
GetString(item, "name") ?? string.Empty,
GetString(item, "channelName")));
}
return result;
}
/// <summary>查服务器上当前中控已登记的通道(设备令牌;`GET /api/scan/channels`),返回 channelId 集合</summary>
public async Task<HashSet<string>> ChannelsAsync(string deviceToken, CancellationToken ct = default)
{
@ -491,7 +586,7 @@ public sealed class ApiClient
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var (data, message) = ReadEnvelope(response, text);
if (data is null) throw new ApiException(message, (int)response.StatusCode);
if (data is null) throw Failure(response, text, message);
if (data.Value.TryGetProperty("list", out var list) && list.ValueKind == JsonValueKind.Array)
{
@ -561,6 +656,29 @@ public sealed class ApiClient
}
}
/// <summary>
/// 失败响应 → 异常:除 HTTP 状态码外,把 envelope 里的 `status` / `expireAt`
/// 一起带出来(上报循环据此区分「网络失败」与「主体过期」)。
/// </summary>
private static ApiException Failure(HttpResponseMessage response, string text, string message)
{
string? status = null;
DateTimeOffset? expireAt = null;
try
{
using var document = JsonDocument.Parse(string.IsNullOrWhiteSpace(text) ? "{}" : text);
status = GetString(document.RootElement, "status");
expireAt = GetDateTime(document.RootElement, "expireAt");
}
catch (JsonException)
{
// 非 JSON:只保留 HTTP 状态码与 message
}
return new ApiException(message, (int)response.StatusCode, status, expireAt);
}
/// <summary>解析 `{ ok, data, message }`:成功返回 data(JSON 片段),失败返回 message</summary>
private static (JsonElement? Data, string Message) ReadEnvelope(HttpResponseMessage response, string text)
{
@ -642,4 +760,21 @@ public sealed class ApiClient
_ => 0,
};
}
private static long? GetLong(JsonElement element, string property)
{
if (!element.TryGetProperty(property, out var value)) return null;
return value.ValueKind switch
{
JsonValueKind.Number => value.TryGetInt64(out var number) ? number : null,
JsonValueKind.String => long.TryParse(value.GetString(), out var parsed) ? parsed : null,
_ => null,
};
}
private static DateTimeOffset? GetDateTime(JsonElement element, string property)
{
var text = GetString(element, property);
return !string.IsNullOrWhiteSpace(text) && DateTimeOffset.TryParse(text, out var parsed) ? parsed : null;
}
}

View File

@ -33,6 +33,22 @@ public sealed class DeviceService
private Task? _uploadTask;
private int _uploadRetryMs = 1000;
// 主体不可用(过期 / 停用)或设备令牌失效时暂停上报:
// 暂停期间只发心跳探测(心跳不受期限拦截),续费后自动恢复并补传积压。
private const int PauseNone = 0;
private const int PauseSubject = 1;
private const int PauseUnauthorized = 2;
private static readonly TimeSpan PauseProbeInterval = TimeSpan.FromSeconds(60);
private readonly object _pauseGate = new();
private int _pauseState = PauseNone;
private string _pauseMessage = string.Empty;
private int _probeFailures;
private DateTime _lastProbeAt = DateTime.MinValue;
/// <summary>暂停上报期间探测「是否已续期」时触发(ScanService 用来补一次通道对账)</summary>
public event Action? SubjectResumed;
// 面单一直放在扫码器上时会持续「更新最近扫描时间」(每 1~2 秒一次)——
// 这种事件不能每条都写日志,否则一天几万行;同一个 通道+条码 5 分钟记一次。
private static readonly ConcurrentDictionary<string, DateTime> TouchedLogAt = new();
@ -58,6 +74,36 @@ public sealed class DeviceService
/// <summary>上报状态(给界面看的一句话;空串 = 一切正常)</summary>
public string UploadStatus { get; private set; } = string.Empty;
/// <summary>是否已暂停上报(主体过期/停用,或设备令牌失效)</summary>
public bool UploadPaused
{
get { lock (_pauseGate) return _pauseState != PauseNone; }
}
/// <summary>
/// 心跳/上报拿到的视图:同步主体状态。
/// - 过期 / 停用 → 暂停上报(不消费队列、不标记已上传);
/// - 恢复可用 → 立刻补传积压(服务端幂等,整批重发安全)。
/// </summary>
public void ApplySubjectState(DeviceSubjectState? subject)
{
if (subject is null) return;
if (subject.Disabled)
{
Pause(PauseSubject, $"主体「{subject.Name}」已停用");
return;
}
if (subject.Expired)
{
var deadline = subject.ExpireAt is null ? string.Empty : $"({subject.ExpireAt:yyyy-MM-dd HH:mm})";
Pause(PauseSubject, $"主体「{subject.Name}」使用期限已到{deadline}");
return;
}
Resume("主体已续期/恢复,开始补传积压的扫码记录");
}
/// <summary>是否已开启(本地标记 + 有令牌)</summary>
public bool Enabled => _settings.DeviceServiceEnabled && !string.IsNullOrWhiteSpace(_settings.DeviceToken);
@ -111,6 +157,9 @@ public sealed class DeviceService
AppLog.Write($"[device] 设备服务已开启:{result.Sn}(id={result.Id},踢下线 {result.Kicked.Count} 台)");
// 重新开启 = 重新鉴权:清掉暂停状态并马上补传积压
Resume("设备服务已重新开启,恢复上报");
// 拉起扫码记录上报循环(断网期间的积压会一次性补上去)
EnsureUploadLoop();
TriggerUpload();
@ -269,6 +318,11 @@ public sealed class DeviceService
}
_uploadCts = null;
_uploadTask = null;
lock (_pauseGate)
{
_pauseState = PauseNone;
_pauseMessage = string.Empty;
}
UploadStatus = string.Empty;
ScanRecordStore.Flush();
}
@ -291,6 +345,9 @@ public sealed class DeviceService
/// 失败时**不标记**那批记录,等退避(1s→2s→5s→10s→30s 封顶)后重发;
/// 服务端按 设备+通道+条码+秒 去重、同一运单 24 小时内覆盖成最新时间,
/// 所以整批重发不会造成重复落库,也不会把时间改回过去。
///
/// **主体过期/停用或令牌失效时不推送**:队列原样保留,每 60 秒只发一次心跳探测,
/// 续期(或重新开启设备服务)后自动恢复并把积压补传上去。
/// </summary>
private async Task UploadLoopAsync(CancellationToken ct)
{
@ -307,6 +364,12 @@ public sealed class DeviceService
while (!ct.IsCancellationRequested && Enabled)
{
if (UploadPaused)
{
await WaitAndProbeAsync(ct).ConfigureAwait(false);
continue;
}
var batch = ScanRecordStore.Pending(50);
if (batch.Count == 0)
{
@ -330,6 +393,16 @@ public sealed class DeviceService
{
break;
}
catch (ApiException ex) when (ex.IsSubjectUnavailable)
{
// 主体不可用:不重试、不丢队列,改为等心跳探测到续期
Pause(PauseSubject, ex.Message);
}
catch (ApiException ex) when (ex.StatusCode == 401)
{
// 令牌失效(被踢下线/重新扫码过):重新开启设备服务之前无法恢复
Pause(PauseUnauthorized, "设备令牌已失效(可能已在其他设备开启),请重新开启设备服务");
}
catch (Exception ex)
{
UploadStatus = $"上报失败(待上传 {ScanRecordStore.PendingCount()} 条),{_uploadRetryMs / 1000} 秒后重试";
@ -347,4 +420,109 @@ public sealed class DeviceService
}
}
}
/// <summary>暂停期间:等一会儿 → 只发心跳探测主体是否已恢复;令牌失效时不再探测</summary>
private async Task WaitAndProbeAsync(CancellationToken ct)
{
bool unauthorized;
lock (_pauseGate) unauthorized = _pauseState == PauseUnauthorized;
// 有积压就 60 秒探一次(续费后 1 分钟内自动补传);没积压就 5 分钟探一次,别浪费请求。
// 用 _uploadSignal 等待:重新开启设备服务 / 手动「立即上传」会立刻唤醒,不用干等。
var interval = ScanRecordStore.PendingCount() > 0 ? PauseProbeInterval : TimeSpan.FromMinutes(5);
try
{
await _uploadSignal.WaitAsync(interval, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
RefreshPausedStatus();
// 已被 Resume(重新鉴权/续期事件)唤醒:直接回到上报循环,不重复探测
if (!UploadPaused) return;
if (!Enabled || unauthorized) return;
// 同一分钟内不重复探测(扫码会频繁唤醒,不需要每次都发心跳)
if (DateTime.UtcNow - _lastProbeAt < PauseProbeInterval) return;
_lastProbeAt = DateTime.UtcNow;
try
{
var beat = await _api.HeartbeatAsync(_settings.DeviceToken, ct).ConfigureAwait(false);
_probeFailures = 0;
ApplySubjectState(beat?.Subject);
}
catch (OperationCanceledException)
{
throw;
}
catch (ApiException ex) when (ex.StatusCode == 401)
{
Pause(PauseUnauthorized, "设备令牌已失效(可能已在其他设备开启),请重新开启设备服务");
}
catch (Exception ex)
{
// 网络问题:保持暂停,下个周期再探测;只偶尔记一行,别刷屏
if (++_probeFailures % 10 == 1)
{
AppLog.Write($"[scan] 暂停期间心跳探测失败(继续等待,本地记录不受影响):{ex.Message}");
}
}
}
private void Pause(int state, string message)
{
var pending = ScanRecordStore.PendingCount();
var changed = false;
lock (_pauseGate)
{
changed = _pauseState != state || _pauseMessage != message;
_pauseState = state;
_pauseMessage = message;
UploadStatus = $"{message}(待上传 {pending} 条,恢复后自动补传)";
}
if (changed)
{
_lastProbeAt = DateTime.MinValue;
AppLog.Write($"[scan] {message},已暂停上报(本地记录保留,待上传 {pending} 条)");
}
}
private void Resume(string message)
{
var changed = false;
lock (_pauseGate)
{
changed = _pauseState != PauseNone;
_pauseState = PauseNone;
_pauseMessage = string.Empty;
UploadStatus = string.Empty;
}
if (!changed) return;
_uploadRetryMs = 1000;
_probeFailures = 0;
_lastProbeAt = DateTime.MinValue;
AppLog.Write($"[scan] {message}");
SubjectResumed?.Invoke();
SignalUpload();
}
/// <summary>刷新暂停提示里的「待上传 N 条」(暂停期间会继续扫码/积压)</summary>
private void RefreshPausedStatus()
{
var pending = ScanRecordStore.PendingCount();
lock (_pauseGate)
{
if (_pauseState == PauseNone) return;
UploadStatus = $"{_pauseMessage}(待上传 {pending} 条,恢复后自动补传)";
}
}
}

View File

@ -84,6 +84,8 @@ public sealed class ScanService
public ScanService(DeviceService device)
{
_device = device;
// 主体续期/恢复后补一次通道对账(暂停期间通道变动不会推上去)
_device.SubjectResumed += () => RequestChannelSync();
}
/// <summary>通道同步状态(给界面看的一句话)</summary>
@ -522,6 +524,13 @@ public sealed class ScanService
{
return;
}
catch (ApiException ex) when (ex.IsSubjectUnavailable)
{
// 主体过期/停用:不进入退避重试(否则每 30 秒撞一次墙),等续期事件再同步
SetSyncStatus("主体已到期/停用,通道同步暂停(恢复后自动重试)");
AppLog.Write($"[scan] 通道同步暂停:{ex.Message}");
return;
}
catch (Exception ex)
{
SetSyncStatus($"通道同步失败,{_syncRetryMs / 1000} 秒后重试");