Compare commits

...

3 Commits

Author SHA1 Message Date
liufumingren
2f838186de chore: sync updates and daylog 2026-03-26 2026-03-25 23:26:10 +08:00
liufumingren
b9e94f1035 chore: 提交当前工作区改动 2026-03-25 18:12:04 +08:00
liufumingren
67c6856d75 chore: commit current workspace changes 2026-03-25 13:17:51 +08:00
64 changed files with 6255 additions and 4062 deletions

View File

@ -475,4 +475,120 @@ npx egg-bin test test/app/controller/system.user.info.web.test.js test/app/contr
1. 先查 `user.info` 返回中的 `employees_id`、`store_id`、`platform_code`
2. 确认请求头是否为 `platform=web`、`project=all`
3. 若仍为空,检查账号角色授权与当前激活角色是否存在
## 13. setting.account 接口说明(system)
适用入口:`POST /system?method=setting.account.xxx`
### 13.1 setting.account.list
用途:查询当前主体下工号列表(默认只返回启用工号)。
入参(body):
- `status`(number,可选):状态筛选,默认 `1`
- `includeDisabled`(boolean,可选):`true` 时包含停用工号
返回(`data[]` 关键字段):
- `employee_id`:工号 ID
- `account_id`:账号 ID
- `store_id`:主体 ID
- `real_name`:工号姓名
- `status`:工号状态(`1` 启用 / `0` 停用)
- `username` / `phone` / `email`:账号基础信息
- `avatar_file_id` / `avatar_url`:头像信息
### 13.2 setting.account.add
用途:新增工号;手机号存在则复用账号,不存在则创建账号并绑定工号。
入参(body):
- `phone`(string,必填):11 位手机号
- `real_name`(string,必填):工号姓名
- `role_id`(number,可选):不传时继承当前操作人工号角色
- `username`(string,可选):仅新建账号时生效
- `password`(string,可选):仅新建账号时生效,默认 `111111`
- `email`(string,可选):仅新建账号时生效
返回(`data` 关键字段):
- `employee_id` / `account_id` / `role_id`
- `is_new_account`:是否本次新建账号
- `phone` / `username`
错误码:
- `400`:参数错误、手机号格式错误、保留名称限制
- `409`:账号禁用、重复绑定、用户名冲突
### 13.3 setting.account.delete
用途:停用工号绑定,不删除底层账号。
入参(body):
- `employee_id`(number,必填)
返回(`data`):
- `employee_id` / `account_id`
- `status`:固定 `deleted`
- `already_deleted`(可选):原本已是停用状态
### 13.4 setting.account.update
用途:更新工号姓名和/或头像引用。
入参(body):
- `employee_id`(number,必填)
- `real_name`(string,可选)
- `file_id`(number,可选):头像文件 ID
约束:`real_name` 与 `file_id` 至少传一个。
返回(`data`):
- 更新后的工号完整信息(同 list 列表项结构)
### 13.5 代码分层约定
- 对外 method 包装层:`app/service/systemMethods/setting/account.js`
- 业务实现层:`app/service/systems/setting/account.js`
- 约定:非暴露辅助函数与业务逻辑统一下沉到 `systems`,`systemMethods` 只保留出口包装。
## 14. where 参数统一规范(强制)
适用范围:所有包含 `where` 筛选条件的 `/system` 接口。
### 14.1 标准结构
`where` 必须使用统一条件对象格式:
```json
{
"where": {
"item_code": { "operator": "like", "value": "SKU" },
"status": { "operator": "eq", "value": "created" },
"quantity": { "operator": "ge", "type": "number", "value": "10" },
"create_at": { "operator": "between", "type": "date", "value": ["2026-03-01", "2026-03-31"] },
"quickWhere": { "operator": "like", "type": "text", "value": "关键字" }
}
}
```
### 14.2 统一处理入口
- `where` 统一在 `app/service/main.js` 中处理:`prepareWhereContext(data, options)`。
- 处理后上下文约定:
- `ctx.where`:标准化后的 where 条件对象(含 `operator/value/type`)
- `ctx.whereValue`:仅提取 value 的兼容对象(给旧逻辑渐进兼容)
- `ctx.whereParsed`:基于 `app/lib/query_condition_parser.js` 解析后的动态条件结构
### 14.3 实施规则
- 所有 method 层(`systemMethods`)收到 `where` 后,必须先调用 `prepareWhereContext`。
- 所有 systems 层查询逻辑优先读取 `ctx.where` / `ctx.whereParsed`,不得重复定义另一套 where 规则。
- 历史简写结构(如 `where: { status: 1 }`)允许输入,但会在 main 层自动标准化为条件对象。
### 14.4 回归覆盖建议
- 至少验证:空 where、eq、like、in、between、quickWhere。
- 对日志中高频接口优先回归:
- `print.getList`
- `storage.entry.list`
- `stock.warehouse.list`

View File

@ -6,8 +6,7 @@
- AI项目协作工具箱:`AI_TOOLBOX.md`
- Method 路由映射说明:`AI_METHOD_ROUTING.md`
- Model 层级清单:`temp/docs/modelList.md`
- Method 输出一致性回归记录:`temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md`
- stock.warehouse.list 前端查询规则:`docs/stock-stockWarehouse-query-rules.md`
- system 接口文档源:`methods/system.json`
- qimen 接口文档源:`methods/qimen.json`
- 日报:`day.log`
@ -40,7 +39,7 @@
- `README.md`:项目入口文档,提供整体说明与规范入口。
- `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。
- `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。
- `temp/docs/modelList.md`:model 层级结构与关键说明清单。
- `docs/stock-stockWarehouse-query-rules.md`:stock.warehouse.list 的 where 构造规则与失败返回说明。
- `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。
- `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。
- `day.log`:每日工作留痕。
@ -201,6 +200,16 @@ npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- 全局业务 Header(如 `platform`、`project`)设置
- 方法级在线 POST 调试
### user.getBindWechatCode 调用约定(微信绑定码)
- 默认行为:立即返回当前状态(不会长等待,适合页面初始化)。
- 显式长轮询:仅当 body 传 `waitForChange=true`(或兼容字段 `longPoll=true`)时启用。
- 长轮询时长:后端单次最长等待 60 秒;60 秒内状态变化会立即返回。
- 超时返回:若 60 秒内无变化,返回当前状态并提示超时。
- 初始化强制立即返回:可传 `init=true`(兼容 `isInit=true`、`firstLoad=true`)。
- 可选等待参数:`waitTimeoutMs`,后端自动封顶 60000。
- 前端超时建议:HTTP 超时设置为 120000ms(2 分钟),覆盖网络抖动与重试开销。
## 接口响应规范(system)
更新时间:2026-03-22

View File

@ -0,0 +1,288 @@
'use strict';
function isPlainObject(value) {
return value && typeof value === 'object' && !Array.isArray(value);
}
function isEmptyValue(value) {
if (value === undefined || value === null) {
return true;
}
if (typeof value === 'string' && value.trim() === '') {
return true;
}
if (Array.isArray(value) && value.length === 0) {
return true;
}
return false;
}
function normalizeDate(value) {
if (value === undefined || value === null) {
return value;
}
if (typeof value === 'string') {
return value.trim();
}
if (value instanceof Date) {
if (isNaN(value.getTime())) return value;
return value.toISOString().slice(0, 19).replace('T', ' ');
}
if (typeof value === 'number') {
const date = new Date(value);
if (isNaN(date.getTime())) return value;
return date.toISOString().slice(0, 19).replace('T', ' ');
}
return value;
}
function processConditionValue(value, type) {
if (value === undefined || value === null) {
return value;
}
switch (type) {
case 'boolean':
if (value === true || value === 'true' || value === 'Y' || value === 'y') {
return 'Y';
}
if (value === false || value === 'false' || value === 'N' || value === 'n') {
return 'N';
}
return value;
case 'date':
case 'daterange':
if (Array.isArray(value)) {
return value.map(v => normalizeDate(v));
}
return normalizeDate(value);
case 'number': {
const num = parseFloat(value);
return isNaN(num) ? value : num;
}
case 'text':
if (Array.isArray(value)) {
return value.map(item => String(item).trim()).filter(Boolean);
}
return String(value).split(',').map(item => item.trim()).filter(Boolean);
default:
return value;
}
}
function buildSequelizeCondition(fieldKey, condition, app) {
if (!isPlainObject(condition)) {
return { ok: false, reason: 'condition 必须是对象' };
}
const { Sequelize } = app;
const {
operator = 'eq', value, type,
} = condition;
const fieldName = condition.field || fieldKey;
const processedValue = processConditionValue(value, type);
const op = String(operator || 'eq').toLowerCase();
switch (op) {
case 'eq':
return { ok: true, condition: { [fieldName]: processedValue } };
case 'ne':
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.ne]: processedValue } } };
case 'contains':
case 'like':
if (Array.isArray(processedValue) && processedValue.length > 0) {
return {
ok: true,
condition: {
[Sequelize.Op.or]: processedValue.map(val => ({
[fieldName]: {
[Sequelize.Op.like]: `%${val}%`,
},
})),
},
};
}
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `%${processedValue}%` } } };
case 'startswith':
if (Array.isArray(processedValue) && processedValue.length > 0) {
return {
ok: true,
condition: {
[Sequelize.Op.or]: processedValue.map(val => ({
[fieldName]: {
[Sequelize.Op.like]: `${val}%`,
},
})),
},
};
}
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `${processedValue}%` } } };
case 'endswith':
if (Array.isArray(processedValue) && processedValue.length > 0) {
return {
ok: true,
condition: {
[Sequelize.Op.or]: processedValue.map(val => ({
[fieldName]: {
[Sequelize.Op.like]: `%${val}`,
},
})),
},
};
}
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `%${processedValue}` } } };
case 'gt':
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.gt]: processedValue } } };
case 'lt':
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.lt]: processedValue } } };
case 'ge':
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.gte]: processedValue } } };
case 'le':
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.lte]: processedValue } } };
case 'in':
if (!Array.isArray(processedValue)) {
return { ok: false, reason: `${fieldName} 的 in 操作符要求 value 为数组` };
}
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.in]: processedValue } } };
case 'notin':
if (!Array.isArray(processedValue)) {
return { ok: false, reason: `${fieldName} 的 notin 操作符要求 value 为数组` };
}
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notIn]: processedValue } } };
case 'between':
if (!Array.isArray(processedValue) || processedValue.length !== 2) {
return { ok: false, reason: `${fieldName} 的 between 操作符要求 value 为长度为2的数组` };
}
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.between]: processedValue } } };
case 'notbetween':
if (!Array.isArray(processedValue) || processedValue.length !== 2) {
return { ok: false, reason: `${fieldName} 的 notbetween 操作符要求 value 为长度为2的数组` };
}
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notBetween]: processedValue } } };
case 'isnull':
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.is]: null } } };
case 'isnotnull':
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.not]: null } } };
case 'regexp':
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.regexp]: processedValue } } };
case 'notregexp':
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notRegexp]: processedValue } } };
default:
return { ok: true, condition: { [fieldName]: processedValue } };
}
}
function parseWhereConditions(options = {}) {
const {
where,
app,
specialFieldMap = {},
} = options;
if (where === undefined || where === null) {
return {
ok: true,
result: {
dynamicConditions: [],
bucketConditions: {},
bucketFlags: {},
rawConditionsByField: {},
},
};
}
if (!isPlainObject(where)) {
return { ok: false, reason: 'where 必须是对象' };
}
const dynamicConditions = [];
const bucketConditions = {};
const bucketFlags = {};
const rawConditionsByField = {};
for (const [ fieldKey, condition ] of Object.entries(where)) {
if (!isPlainObject(condition)) {
return { ok: false, reason: `字段 ${fieldKey} 条件必须是对象` };
}
if (isEmptyValue(condition.value)) {
continue;
}
const mapped = specialFieldMap[fieldKey] || {};
const normalizedCondition = {
...condition,
};
if (mapped.field) {
normalizedCondition.field = mapped.field;
}
const built = buildSequelizeCondition(fieldKey, normalizedCondition, app);
if (!built.ok) {
return {
ok: false,
reason: `字段 ${fieldKey} 解析失败: ${built.reason}`,
};
}
if (mapped.bucket) {
if (!bucketConditions[mapped.bucket]) {
bucketConditions[mapped.bucket] = [];
}
bucketConditions[mapped.bucket].push(built.condition);
bucketFlags[mapped.bucket] = true;
rawConditionsByField[fieldKey] = normalizedCondition;
continue;
}
dynamicConditions.push(built.condition);
}
return {
ok: true,
result: {
dynamicConditions,
bucketConditions,
bucketFlags,
rawConditionsByField,
},
};
}
module.exports = {
isEmptyValue,
normalizeDate,
processConditionValue,
buildSequelizeCondition,
parseWhereConditions,
};

View File

@ -6,6 +6,10 @@ class UserApiService extends Service {
async getUserByTempCode(data) {
return await this.ctx.service.systems.auth.user.getUserByTempCode(data);
}
async bindAccountByTempCode(data) {
return await this.ctx.service.systems.auth.user.bindAccountByTempCode(data);
}
}
module.exports = UserApiService;

View File

@ -1,6 +1,7 @@
'use strict';
const Service = require('egg').Service;
const { parseWhereConditions } = require('../lib/query_condition_parser');
class MainService extends Service {
constructor(ctx) {
@ -85,6 +86,119 @@ class MainService extends Service {
};
}
isPlainObject(value) {
return value && typeof value === 'object' && !Array.isArray(value);
}
normalizeWhereCondition(fieldKey, condition) {
const isQuickWhere = fieldKey === 'quickWhere';
if (this.isPlainObject(condition)) {
const hasStandardKeys = [ 'value', 'operator', 'type', 'field', 'values' ]
.some(key => Object.prototype.hasOwnProperty.call(condition, key));
if (hasStandardKeys) {
const normalized = {
...condition,
};
if (!Object.prototype.hasOwnProperty.call(normalized, 'value') && Object.prototype.hasOwnProperty.call(normalized, 'values')) {
normalized.value = normalized.values;
delete normalized.values;
}
if (!Object.prototype.hasOwnProperty.call(normalized, 'operator') || !normalized.operator) {
normalized.operator = Array.isArray(normalized.value) ? 'in' : (isQuickWhere ? 'like' : 'eq');
}
if (isQuickWhere) {
normalized.operator = normalized.operator || 'like';
normalized.type = normalized.type || 'text';
}
if ((normalized.operator === 'between' || normalized.operator === 'notbetween') && this.isPlainObject(normalized.value)) {
const start = normalized.value.start ?? normalized.value.from ?? normalized.value.begin;
const end = normalized.value.end ?? normalized.value.to ?? normalized.value.finish;
normalized.value = [ start, end ];
}
return normalized;
}
}
if (isQuickWhere) {
return {
operator: 'like',
type: 'text',
value: condition,
};
}
return {
operator: Array.isArray(condition) ? 'in' : 'eq',
value: condition,
};
}
normalizeWhereParams(whereInput = {}) {
if (!this.isPlainObject(whereInput)) {
return {};
}
const normalized = {};
for (const [ fieldKey, condition ] of Object.entries(whereInput)) {
normalized[fieldKey] = this.normalizeWhereCondition(fieldKey, condition);
}
return normalized;
}
extractWhereValues(normalizedWhere = {}) {
if (!this.isPlainObject(normalizedWhere)) {
return {};
}
const whereValues = {};
for (const [ fieldKey, condition ] of Object.entries(normalizedWhere)) {
if (this.isPlainObject(condition) && Object.prototype.hasOwnProperty.call(condition, 'value')) {
whereValues[fieldKey] = condition.value;
} else {
whereValues[fieldKey] = condition;
}
}
return whereValues;
}
prepareWhereContext(data = {}, options = {}) {
const specialFieldMap = this.isPlainObject(options.specialFieldMap) ? options.specialFieldMap : {};
const rawWhere = this.isPlainObject(data && data.where) ? data.where : {};
const normalizedWhere = this.normalizeWhereParams(rawWhere);
const parsed = parseWhereConditions({
where: normalizedWhere,
app: this.app,
specialFieldMap,
});
if (!parsed.ok) {
throw new Error(`where 参数解析失败: ${parsed.reason}`);
}
const whereValues = this.extractWhereValues(normalizedWhere);
this.ctx.whereRaw = rawWhere;
this.ctx.where = normalizedWhere;
this.ctx.whereValue = whereValues;
this.ctx.whereParsed = parsed.result;
if (this.isPlainObject(data)) {
data.where = normalizedWhere;
}
return {
where: normalizedWhere,
whereValue: whereValues,
parsed: parsed.result,
};
}
async findQimenAppWithContract(appkey, customerId, warehouseCode) {
const { app } = this;
const cacheKey = `contract:${appkey}:${customerId}:${warehouseCode}`;

View File

@ -16,10 +16,11 @@ class ArchiveOrderService extends OrderBaseService {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const whereData = data.where || {};
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasOutboundFilter = whereData.outbound_status !== undefined && whereData.outbound_status !== null && whereData.outbound_status !== '';
const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status');
if (!hasOutboundFilter) {
where.outbound_status = 'fin';
}

View File

@ -39,6 +39,34 @@ class OrderBaseService extends MainService {
}
}
getWhereCondition(whereData = {}, key) {
const condition = whereData[key];
if (condition && typeof condition === 'object' && Object.prototype.hasOwnProperty.call(condition, 'value')) {
return condition;
}
return {
operator: 'eq',
value: condition,
};
}
getWhereValue(whereData = {}, key) {
return this.getWhereCondition(whereData, key).value;
}
getWhereOperator(whereData = {}, key, defaultOperator = 'eq') {
const condition = this.getWhereCondition(whereData, key);
return String(condition.operator || defaultOperator).toLowerCase();
}
hasWhereValue(whereData = {}, key) {
const value = this.getWhereValue(whereData, key);
if (value === undefined || value === null) return false;
if (typeof value === 'string' && value.trim() === '') return false;
if (Array.isArray(value) && value.length === 0) return false;
return true;
}
buildWhere(whereData = {}, warehouseId) {
const { Op } = this.app.Sequelize;
const where = { warehouse_id: warehouseId };
@ -64,35 +92,68 @@ class OrderBaseService extends MainService {
];
for (const key of eqFields) {
if (whereData[key] !== undefined && whereData[key] !== null && whereData[key] !== '') {
where[key] = whereData[key];
if (!this.hasWhereValue(whereData, key)) {
continue;
}
const value = this.getWhereValue(whereData, key);
const operator = this.getWhereOperator(whereData, key);
if (operator === 'in') {
where[key] = {
[Op.in]: Array.isArray(value) ? value : [ value ],
};
} else if (operator === 'notin') {
where[key] = {
[Op.notIn]: Array.isArray(value) ? value : [ value ],
};
} else if (operator === 'ne') {
where[key] = {
[Op.ne]: value,
};
} else if (operator === 'like' || operator === 'contains') {
where[key] = {
[Op.like]: `%${value}%`,
};
} else {
where[key] = value;
}
}
if (whereData.delivery_order_code) {
where.delivery_order_code = { [Op.like]: `%${whereData.delivery_order_code}%` };
if (this.hasWhereValue(whereData, 'delivery_order_code')) {
const value = this.getWhereValue(whereData, 'delivery_order_code');
const operator = this.getWhereOperator(whereData, 'delivery_order_code', 'like');
if (operator === 'eq') {
where.delivery_order_code = value;
} else {
where.delivery_order_code = { [Op.like]: `%${value}%` };
}
}
if (Array.isArray(whereData.delivery_order_codes) && whereData.delivery_order_codes.length > 0) {
where.delivery_order_code = { [Op.in]: whereData.delivery_order_codes };
const deliveryOrderCodes = this.getWhereValue(whereData, 'delivery_order_codes');
if (Array.isArray(deliveryOrderCodes) && deliveryOrderCodes.length > 0) {
where.delivery_order_code = { [Op.in]: deliveryOrderCodes };
}
if (whereData.logistics_name) {
where.logistics_name = { [Op.like]: `%${whereData.logistics_name}%` };
if (this.hasWhereValue(whereData, 'logistics_name')) {
const value = this.getWhereValue(whereData, 'logistics_name');
where.logistics_name = { [Op.like]: `%${value}%` };
}
if (whereData.buyer_nick) {
where.buyer_nick = { [Op.like]: `%${whereData.buyer_nick}%` };
if (this.hasWhereValue(whereData, 'buyer_nick')) {
const value = this.getWhereValue(whereData, 'buyer_nick');
where.buyer_nick = { [Op.like]: `%${value}%` };
}
if (whereData.mobile) {
where.mobile = { [Op.like]: `%${whereData.mobile}%` };
if (this.hasWhereValue(whereData, 'mobile')) {
const value = this.getWhereValue(whereData, 'mobile');
where.mobile = { [Op.like]: `%${value}%` };
}
this.applyDateRange(where, 'create_at', whereData.create_at_start, whereData.create_at_end);
this.applyDateRange(where, 'place_order_time', whereData.place_order_time_start, whereData.place_order_time_end);
this.applyDateRange(where, 'pay_time', whereData.pay_time_start, whereData.pay_time_end);
this.applyDateRange(where, 'delivery_time', whereData.delivery_time_start, whereData.delivery_time_end);
this.applyDateRange(where, 'create_at', this.getWhereValue(whereData, 'create_at_start'), this.getWhereValue(whereData, 'create_at_end'));
this.applyDateRange(where, 'place_order_time', this.getWhereValue(whereData, 'place_order_time_start'), this.getWhereValue(whereData, 'place_order_time_end'));
this.applyDateRange(where, 'pay_time', this.getWhereValue(whereData, 'pay_time_start'), this.getWhereValue(whereData, 'pay_time_end'));
this.applyDateRange(where, 'delivery_time', this.getWhereValue(whereData, 'delivery_time_start'), this.getWhereValue(whereData, 'delivery_time_end'));
return where;
}

View File

@ -17,10 +17,11 @@ class DeliveryOrderService extends OrderBaseService {
const warehouseId = this.ensureWarehouseId(data);
const { Op } = this.app.Sequelize;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const whereData = data.where || {};
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasOutboundFilter = whereData.outbound_status !== undefined && whereData.outbound_status !== null && whereData.outbound_status !== '';
const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status');
if (!hasOutboundFilter) {
where.outbound_status = { [Op.ne]: 'none' };
}

View File

@ -17,7 +17,8 @@ class ExpectionOrderService extends OrderBaseService {
const warehouseId = this.ensureWarehouseId(data);
const { Op } = this.app.Sequelize;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const whereData = data.where || {};
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasExceptionFilter = [
@ -31,7 +32,7 @@ class ExpectionOrderService extends OrderBaseService {
'claim_status',
'outbound_status',
'intercept_status',
].some(key => whereData[key] !== undefined && whereData[key] !== null && whereData[key] !== '');
].some(key => this.hasWhereValue(whereData, key));
if (!hasExceptionFilter) {
where[Op.or] = [

View File

@ -16,7 +16,9 @@ class OrderIndexService extends OrderBaseService {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const where = this.buildWhere(data.where || {}, warehouseId);
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
@ -97,7 +99,9 @@ class OrderIndexService extends OrderBaseService {
const warehouseId = this.ensureWarehouseId(data);
const { Sequelize } = this.app;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const where = this.buildWhere(data.where || {}, warehouseId);
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const total = await DeliveryModel.count({ where });
const byStatusRows = await DeliveryModel.findAll({

View File

@ -17,11 +17,12 @@ class PendingOrderService extends OrderBaseService {
const warehouseId = this.ensureWarehouseId(data);
const { Op } = this.app.Sequelize;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const whereData = data.where || {};
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasStatusFilter = whereData.status !== undefined && whereData.status !== null && whereData.status !== '';
const hasOutboundFilter = whereData.outbound_status !== undefined && whereData.outbound_status !== null && whereData.outbound_status !== '';
const hasStatusFilter = this.hasWhereValue(whereData, 'status');
const hasOutboundFilter = this.hasWhereValue(whereData, 'outbound_status');
if (!hasStatusFilter) {
where.status = { [Op.in]: [ 'pedding', 'created' ] };

View File

@ -17,19 +17,26 @@ class ReviewOrderService extends OrderBaseService {
const warehouseId = this.ensureWarehouseId(data);
const { Op } = this.app.Sequelize;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const whereData = data.where || {};
this.prepareWhereContext(data);
const whereData = this.ctx.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasInspectionFilter = whereData.inspection_status !== undefined && whereData.inspection_status !== null && whereData.inspection_status !== '';
const hasInspectionFilter = this.hasWhereValue(whereData, 'inspection_status');
if (!hasInspectionFilter) {
where.inspection_status = { [Op.ne]: 'none' };
}
if (whereData.operator_name) {
where.operator_name = { [Op.like]: `%${whereData.operator_name}%` };
if (this.hasWhereValue(whereData, 'operator_name')) {
const operatorName = this.getWhereValue(whereData, 'operator_name');
where.operator_name = { [Op.like]: `%${operatorName}%` };
}
this.applyDateRange(where, 'operate_time', whereData.operate_time_start, whereData.operate_time_end);
this.applyDateRange(
where,
'operate_time',
this.getWhereValue(whereData, 'operate_time_start'),
this.getWhereValue(whereData, 'operate_time_end')
);
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({

View File

@ -205,12 +205,14 @@ class PrintService extends MainService {
const { ctx } = this;
console.log('ctx.user in PrintService constructor', ctx.user);
const warehouse_id = ctx.user.store_id;
// TODO: 需根据实际分页和条件查询调整
const { page = 1, pageSize = 20, where = {} } = data;
const requestData = data && typeof data === 'object' ? data : {};
const { whereValue } = this.prepareWhereContext(requestData);
const { page = 1, pageSize = 20 } = requestData;
// 字段过滤
const filter = {};
[ 'id', 'name', 'computer_id', 'custom_barcode' ].forEach(key => {
if (where[key]) filter[key] = where[key];
const value = whereValue[key];
if (value !== undefined && value !== null && value !== '') filter[key] = value;
});
filter.warehouse_id = warehouse_id;
filter.deleted = 0;
@ -276,7 +278,7 @@ class PrintService extends MainService {
totalPages: Math.ceil(total / pageSize),
},
queryInfo: {
conditions: where,
conditions: this.ctx.where || {},
hasBarcodeSearch: false,
sortField: 'id',
sortOrder: 'DESC',

View File

@ -0,0 +1,60 @@
'use strict';
const MainService = require('../../main');
class accountService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getAccountInfo,updatePassword,list,add,delete,update';
const _noNeedLog = '*';
const _noNeedAuth = 'getAccountInfo,updatePassword,list,add,delete,update';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async callSystemAccount(methodName, data, defaultMessage) {
const { service } = this;
try {
const result = await service.systems.setting.account[methodName](data);
return this.success('ok', result);
} catch (error) {
return this.fail(error.message || defaultMessage, {
code: Number(error.code) || 500,
});
}
}
/**
* 账号列表。
* @param {*} data
*/
async list(data = {}) {
return this.callSystemAccount('list', data, '获取工号列表失败');
}
/**
* 新增工号。
* @param {*} data
*/
async add(data = {}) {
return this.callSystemAccount('add', data, '添加工号失败');
}
/**
* 删除工号。
* @param {*} data
*/
async delete(data = {}) {
return this.callSystemAccount('delete', data, '删除工号失败');
}
/**
* 更新工号。
* @param {*} data
*/
async update(data = {}) {
return this.callSystemAccount('update', data, '更新工号失败');
}
}
module.exports = accountService;

View File

@ -6,9 +6,9 @@ class printTemplateService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,save,listTemplatesByType';
const _noNeedRight = 'list,save,create,delete,listTemplatesByType';
const _noNeedLog = '*';
const _noNeedAuth = 'list,save,listTemplatesByType';
const _noNeedAuth = 'list,save,create,delete,listTemplatesByType';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async list(data) {
@ -22,6 +22,52 @@ class printTemplateService extends MainService {
const result = await service.systems.setting.printTemplate.save(data);
return this.success('ok', result);
}
async create(data) {
const { service } = this;
const { template_name, business_type, page_width, page_height } = data || {};
if (!template_name || String(template_name).trim() === '') {
return this.fail('template_name 参数不能为空', { code: 400 });
}
if (!business_type || String(business_type).trim() === '') {
return this.fail('business_type 参数不能为空', { code: 400 });
}
if (page_width === undefined || page_width === null || page_width === '') {
return this.fail('page_width 参数不能为空', { code: 400 });
}
if (page_height === undefined || page_height === null || page_height === '') {
return this.fail('page_height 参数不能为空', { code: 400 });
}
try {
const result = await service.systems.setting.printTemplate.createTemplate(data);
return this.success('ok', result);
} catch (error) {
if (error.message === '同一业务类型和平台下已存在自定义模板') {
return this.fail(error.message, { code: 409 });
}
return this.fail(error.message || '创建打印模板失败', { code: 500 });
}
}
async delete(data) {
const { service } = this;
const { id } = data || {};
const templateId = Number(id);
if (!templateId || Number.isNaN(templateId)) {
return this.fail('id 参数不能为空', { code: 400 });
}
try {
const result = await service.systems.setting.printTemplate.deleteTemplate(templateId);
return this.success('ok', result);
} catch (error) {
if (error.message === '模板不存在或无权限') {
return this.fail(error.message, { code: 404 });
}
return this.fail(error.message || '删除打印模板失败', { code: 500 });
}
}
async listTemplatesByType(data) {
const { service } = this;
console.log('接收到根据业务类型查询模板请求:', data);

View File

@ -1,361 +0,0 @@
'use strict';
const MainService = require('../main');
class indexService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'fastWhereTree,stockWarehouse,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search';
const _noNeedLog = 'fastWhereTree,stockWarehouse,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search';
const _noNeedAuth = 'fastWhereTree,stockWarehouse,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async stockWarehouse(data) {
const { service } = this;
const { pagination, where } = data;
console.log('where', where);
const result = await service.systems.stockStore.getWarehouseStock(where, pagination);
return this.success('ok', result);
}
async getProhibitedType() {
const { service } = this;
const result = await service.systems.stockStore.getProhibitedType();
return this.success('ok', { data: result, code: 200 });
}
async getInfo(data) {
const { service } = this;
const result = await service.systems.stockStore.getInfo(data);
return this.success('ok', { data: result, code: 200 });
}
async saveWarehouseStock(data) {
const { service } = this;
const result = await service.systems.stockStore.saveWarehouseStock(data);
return this.success('ok', { data: result, code: 200 });
}
async createWarehouseStock(data) {
const { service } = this;
const result = await service.systems.stockStore.createWarehouseStock(data);
return this.success('ok', { data: result, code: 200 });
}
async getBarcodes(data) {
const { service } = this;
const result = await service.systems.stockStore.getBarcodes(data);
return this.success('ok', { data: result, code: 200 });
}
async saveWarehouseStockBarcode(data) {
const { service } = this;
const result = await service.systems.stockStore.saveWarehouseStockBarcode(data);
return this.success('ok', { data: result, code: 200 });
}
async getStoreStocks(data) {
const { service } = this;
const result = await service.systems.stockStore.getStoreStocks(data);
return this.success('ok', { data: result, code: 200 });
}
async bindItem(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.bindItem(data);
return this.success('绑定成功', { data: result, code: 200 });
} catch (e) {
return this.success(e.message, { code: 200 });
}
}
async unbindItem(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.unbindItem(data);
return this.success('解绑成功', { data: result, code: 200 });
} catch (e) {
return this.success(e.message, { code: 200 });
}
}
async checkItemCodeUnique(data) {
const { ctx, service } = this;
const { id, item_code, store_id } = data;
console.log(data);
try {
if (!item_code || !store_id) {
return this.fail('参数错误');
}
const data = await service.systems.stockStore.checkItemCodeUnique(id, item_code, store_id, ctx.user.store_id);
return this.success('获取成功', { data, code: 200 });
} catch (error) {
return this.fail(error.message);
}
}
async queryStockLogs(data) {
console.log('请求');
const { ctx } = this;
try {
const { service } = this;
data.warehouseId = ctx.user.store_id;
const result = await service.systems.operationLog.queryStockLogs(data);
return this.success('ok', { data: result, code: 200 });
} catch (e) {
console.log(e);
return this.success(e.message, { code: 200 });
}
}
async handleBatchDelete(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.handleBatchDelete(data);
return this.success(result.message, { data: result.data, code: result.code });
} catch (e) {
console.log(e);
return this.success(e.message, { code: 200 });
}
}
async deleteUnit(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.deleteUnit(data);
return this.success(result.message, { data: result.data, code: result.code });
} catch (e) {
console.log(e);
return this.success(e.message, { code: 200 });
}
}
async deleteProhibited(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.deleteProhibited(data);
return this.success(result.message, { data: result.data, code: result.code });
} catch (e) {
console.log(e);
return this.success(e.message, { code: 200 });
}
}
async handleBatchChange(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.handleBatchChange(data);
return this.success(result.message, { data: result.data, code: result.code });
} catch (e) {
console.log(e);
return this.success(e.message, { code: 405 });
}
}
async getStockUnits() {
console.log('query_getStockUnits');
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
try {
// 构建查询条件
const where = {
[ctx.app.Sequelize.Op.or]: [
{ warehouse_id: null }, // 系统预设单位
{ warehouse_id }, // 本仓库的单位
],
};
const units = await ctx.model.StockUnit.findAll({
where,
order: [
[ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null)
[ 'created_at', 'DESC' ], // 按创建时间倒序
],
});
return this.success('ok', { data: units, code: 200 });
} catch (error) {
console.log(error);
return this.fail(error.message);
}
}
async getUnitList() {
console.log('query_getUnitList');
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
try {
// 构建查询条件
const where = {
warehouse_id,
};
const units = await ctx.model.StockUnit.findAll({
where,
order: [
[ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null)
[ 'created_at', 'DESC' ], // 按创建时间倒序
],
});
return this.success('ok', { data: units, code: 200 });
} catch (error) {
console.log(error);
return this.fail(error.message);
}
}
async createProhibited(data) {
console.log('createProhibited', data);
const { ctx } = this;
const warehouse_id = ctx.user.store_id || null;
const { name } = data;
// 参数验证
if (!name || name.trim() === '') {
ctx.body = {
code: 400,
message: '违禁品类型名称不能为空',
};
return;
}
const trimmedName = name.trim();
try {
// 1. 检查是否是系统预设单位(warehouse_id为null)
const systemUnit = await ctx.model.ProhibitedType.findOne({
where: {
type_name: trimmedName,
warehouse_id: null,
},
});
if (systemUnit) {
ctx.body = {
code: 400,
message: '该违禁品类型是系统预设,不允许添加',
};
return;
}
// 2. 检查当前仓库是否已存在相同名称的单位
const existUnit = await ctx.model.ProhibitedType.findOne({
where: {
type_name: trimmedName,
warehouse_id,
},
});
if (existUnit) {
ctx.body = {
code: 400,
message: '该违禁品类型名称已存在',
};
return;
}
// 3. 创建单位
const unit = await ctx.model.ProhibitedType.create({
type_name: trimmedName,
warehouse_id,
});
// 4. 获取更新后的单位列表
const where = {};
if (warehouse_id) {
where[ctx.app.Sequelize.Op.or] = [
{ warehouse_id: null }, // 系统预设单位
{ warehouse_id }, // 当前仓库的单位
];
} else {
where.warehouse_id = null; // 只显示系统预设单位
}
const units = await ctx.model.ProhibitedType.findAll({
where,
order: [
[ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null)
[ 'created_at', 'DESC' ], // 按创建时间倒序
],
});
return this.success('添加成功', { code: 200 });
} catch (error) {
console.log(error);
return this.success('创建违禁品类型失败', { code: 405 });
}
}
async createUnit() {
const { ctx } = this;
const warehouse_id = ctx.user.store_id || null;
const { name } = ctx.request.body;
// 参数验证
if (!name || name.trim() === '') {
ctx.body = {
code: 400,
message: '单位名称不能为空',
};
return;
}
const trimmedName = name.trim();
try {
// 1. 检查是否是系统预设单位(warehouse_id为null)
const systemUnit = await ctx.model.StockUnit.findOne({
where: {
name: trimmedName,
warehouse_id: null,
},
});
if (systemUnit) {
ctx.body = {
code: 400,
message: '该单位是系统预设单位,不允许添加',
};
return;
}
// 2. 检查当前仓库是否已存在相同名称的单位
const existUnit = await ctx.model.StockUnit.findOne({
where: {
name: trimmedName,
warehouse_id,
},
});
if (existUnit) {
ctx.body = {
code: 400,
message: '该单位名称已存在',
};
return;
}
// 3. 创建单位
const unit = await ctx.model.StockUnit.create({
name: trimmedName,
warehouse_id,
});
// 4. 获取更新后的单位列表
const where = {};
if (warehouse_id) {
where[ctx.app.Sequelize.Op.or] = [
{ warehouse_id: null }, // 系统预设单位
{ warehouse_id }, // 当前仓库的单位
];
} else {
where.warehouse_id = null; // 只显示系统预设单位
}
const units = await ctx.model.StockUnit.findAll({
where,
order: [
[ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null)
[ 'created_at', 'DESC' ], // 按创建时间倒序
],
});
return this.success('添加成功', { code: 200 });
} catch (error) {
return this.success('创建库存单位失败', { code: 200 });
}
}
async search(data) {
const { service } = this;
const result = await service.systems.stockStore.search(data);
return this.success('ok', result);
}
}
module.exports = indexService;

View File

@ -0,0 +1 @@
//此处放组合商品明细的逻辑链路

View File

@ -0,0 +1,21 @@
'use strict';
const MainService = require('../../main');
class StockIndexService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'stockWarehouse';
const _noNeedLog = 'stockWarehouse';
const _noNeedAuth = 'stockWarehouse';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
// Legacy alias: stock.stockWarehouse -> stock.warehouse.list
async stockWarehouse(data = {}) {
return await this.ctx.service.systemMethods.stock.warehouse.list(data);
}
}
module.exports = StockIndexService;

View File

@ -0,0 +1 @@
//此处放货主商品明细的逻辑链路

View File

@ -0,0 +1,483 @@
'use strict';
const MainService = require('../../main');
class WarehouseService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search';
const _noNeedLog = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search';
const _noNeedAuth = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 仓库商品列表查询。
* @param {Object} data 请求体
* @param {Object} [data.pagination] 分页参数
* @param {Object} [data.where] 筛选条件
* @return {Promise<Object>} 统一成功包装响应
*/
async list(data = {}) {
const { service } = this;
const { pagination } = data;
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
barcode: {
bucket: 'barcode',
},
prohibited_type: {
bucket: 'prohibited',
field: 'id',
},
},
});
const result = await service.systems.stockStore.getWarehouseStock(where, pagination);
return this.success('ok', result);
}
/**
* 查询违禁品类型列表(系统预设 + 当前仓库)。
* @return {Promise<Object>} data 为违禁品类型数组
*/
async getProhibitedType() {
const { service } = this;
const result = await service.systems.stockStore.getProhibitedType();
return this.success('ok', { data: result, code: 200 });
}
/**
* 按商品条件获取仓库商品详情。
* @param {Object} data 请求体(常见包含 id/item_code)
* @return {Promise<Object>} data 为单个商品详情对象
*/
async getInfo(data) {
const { service } = this;
const result = await service.systems.stockStore.getInfo(data);
return this.success('ok', { data: result, code: 200 });
}
/**
* 更新仓库商品资料。
* @param {Object} data 请求体(含商品主键与可编辑字段)
* @return {Promise<Object>} data 为更新结果
*/
async saveWarehouseStock(data) {
const { service } = this;
const result = await service.systems.stockStore.saveWarehouseStock(data);
return this.success('ok', { data: result, code: 200 });
}
/**
* 新建仓库商品资料。
* @param {Object} data 请求体(必填字段见 stockStore 校验)
* @return {Promise<Object>} data 为新建结果
*/
async createWarehouseStock(data) {
const { service } = this;
const result = await service.systems.stockStore.createWarehouseStock(data);
return this.success('ok', { data: result, code: 200 });
}
/**
* 查询商品条码列表。
* @param {Object} data 请求体(支持分页与关键字)
* @return {Promise<Object>} data 为条码分页结果
*/
async getBarcodes(data) {
const { service } = this;
const result = await service.systems.stockStore.getBarcodes(data);
return this.success('ok', { data: result, code: 200 });
}
/**
* 保存商品条码信息。
* @param {Object} data 请求体(包含 stock_id 与条码字段)
* @return {Promise<Object>} data 为保存结果
*/
async saveWarehouseStockBarcode(data) {
const { service } = this;
const result = await service.systems.stockStore.saveWarehouseStockBarcode(data);
return this.success('ok', { data: result, code: 200 });
}
/**
* 查询仓库与货主商品关联列表。
* @param {Object} data 请求体(支持筛选/分页)
* @return {Promise<Object>} data 为关联分页结果
*/
async getStoreStocks(data) {
const { service } = this;
const result = await service.systems.stockStore.getStoreStocks(data);
return this.success('ok', { data: result, code: 200 });
}
/**
* 绑定货主商品。
* @param {Object} data 请求体(关联关系参数)
* @return {Promise<Object>} 成功或失败均返回 success 包装,message 给出结果
*/
async bindItem(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.bindItem(data);
return this.success('绑定成功', { data: result, code: 200 });
} catch (e) {
return this.success(e.message, { code: 200 });
}
}
/**
* 解绑货主商品。
* @param {Object} data 请求体(关联关系参数)
* @return {Promise<Object>} 成功或失败均返回 success 包装,message 给出结果
*/
async unbindItem(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.unbindItem(data);
return this.success('解绑成功', { data: result, code: 200 });
} catch (e) {
return this.success(e.message, { code: 200 });
}
}
/**
* 校验商品编码唯一性。
* @param {Object} data 请求体
* @param {number} [data.id] 商品ID(编辑场景)
* @param {string} data.item_code 商品编码
* @param {number} data.store_id 货主ID
* @return {Promise<Object>} data 为布尔或冲突详情
*/
async checkItemCodeUnique(data) {
const { ctx, service } = this;
const { id, item_code, store_id } = data;
console.log(data);
try {
if (!item_code || !store_id) {
return this.fail('参数错误');
}
const result = await service.systems.stockStore.checkItemCodeUnique(id, item_code, store_id, ctx.user.store_id);
return this.success('获取成功', { data: result, code: 200 });
} catch (error) {
return this.fail(error.message);
}
}
/**
* 查询库存操作日志。
* @param {Object} data 请求体(会自动注入当前 warehouseId)
* @return {Promise<Object>} data 为日志分页结果
*/
async queryStockLogs(data) {
console.log('请求');
const { ctx } = this;
try {
const { service } = this;
data.warehouseId = ctx.user.store_id;
const result = await service.systems.operationLog.queryStockLogs(data);
return this.success('ok', { data: result, code: 200 });
} catch (e) {
console.log(e);
return this.success(e.message, { code: 200 });
}
}
/**
* 批量删除仓库商品资料(软删除)。
* @param {Object} data 请求体(含 ids)
* @return {Promise<Object>} data 为删除结果,message 为业务提示
*/
async handleBatchDelete(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.handleBatchDelete(data);
return this.success(result.message, { data: result.data, code: result.code });
} catch (e) {
console.log(e);
return this.success(e.message, { code: 200 });
}
}
/**
* 删除库存单位。
* @param {Object} data 请求体(含单位ID)
* @return {Promise<Object>} data 为删除结果,message 为业务提示
*/
async deleteUnit(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.deleteUnit(data);
return this.success(result.message, { data: result.data, code: result.code });
} catch (e) {
console.log(e);
return this.success(e.message, { code: 200 });
}
}
/**
* 删除违禁品类型。
* @param {Object} data 请求体(含类型ID)
* @return {Promise<Object>} data 为删除结果,message 为业务提示
*/
async deleteProhibited(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.deleteProhibited(data);
return this.success(result.message, { data: result.data, code: result.code });
} catch (e) {
console.log(e);
return this.success(e.message, { code: 200 });
}
}
/**
* 批量修改商品资料字段。
* @param {Object} data 请求体(含 ids/method/value)
* @return {Promise<Object>} data 为修改结果,message 为业务提示
*/
async handleBatchChange(data) {
const { service } = this;
try {
const result = await service.systems.stockStore.handleBatchChange(data);
return this.success(result.message, { data: result.data, code: result.code });
} catch (e) {
console.log(e);
return this.success(e.message, { code: 405 });
}
}
/**
* 查询可用库存单位(系统预设 + 仓库自定义)。
* @return {Promise<Object>} data 为单位数组
*/
async getStockUnits() {
console.log('query_getStockUnits');
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
try {
const where = {
[ctx.app.Sequelize.Op.or]: [
{ warehouse_id: null },
{ warehouse_id },
],
};
const units = await ctx.model.StockUnit.findAll({
where,
order: [
[ 'warehouse_id', 'ASC' ],
[ 'created_at', 'DESC' ],
],
});
return this.success('ok', { data: units, code: 200 });
} catch (error) {
console.log(error);
return this.fail(error.message);
}
}
/**
* 查询当前仓库自定义单位列表。
* @return {Promise<Object>} data 为单位数组
*/
async getUnitList() {
console.log('query_getUnitList');
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
try {
const where = {
warehouse_id,
};
const units = await ctx.model.StockUnit.findAll({
where,
order: [
[ 'warehouse_id', 'ASC' ],
[ 'created_at', 'DESC' ],
],
});
return this.success('ok', { data: units, code: 200 });
} catch (error) {
console.log(error);
return this.fail(error.message);
}
}
/**
* 新增违禁品类型。
* @param {Object} data 请求体
* @param {string} data.name 违禁品类型名称
* @return {Promise<Object|void>} 成功返回 success;参数校验失败时直接写入 ctx.body
*/
async createProhibited(data) {
console.log('createProhibited', data);
const { ctx } = this;
const warehouse_id = ctx.user.store_id || null;
const { name } = data;
if (!name || name.trim() === '') {
ctx.body = {
code: 400,
message: '违禁品类型名称不能为空',
};
return;
}
const trimmedName = name.trim();
try {
const systemUnit = await ctx.model.ProhibitedType.findOne({
where: {
type_name: trimmedName,
warehouse_id: null,
},
});
if (systemUnit) {
ctx.body = {
code: 400,
message: '该违禁品类型是系统预设,不允许添加',
};
return;
}
const existUnit = await ctx.model.ProhibitedType.findOne({
where: {
type_name: trimmedName,
warehouse_id,
},
});
if (existUnit) {
ctx.body = {
code: 400,
message: '该违禁品类型名称已存在',
};
return;
}
await ctx.model.ProhibitedType.create({
type_name: trimmedName,
warehouse_id,
});
const where = {};
if (warehouse_id) {
where[ctx.app.Sequelize.Op.or] = [
{ warehouse_id: null },
{ warehouse_id },
];
} else {
where.warehouse_id = null;
}
await ctx.model.ProhibitedType.findAll({
where,
order: [
[ 'warehouse_id', 'ASC' ],
[ 'created_at', 'DESC' ],
],
});
return this.success('添加成功', { code: 200 });
} catch (error) {
console.log(error);
return this.success('创建违禁品类型失败', { code: 405 });
}
}
/**
* 新增库存单位。
* @return {Promise<Object|void>} 成功返回 success;参数校验失败时直接写入 ctx.body
*/
async createUnit() {
const { ctx } = this;
const warehouse_id = ctx.user.store_id || null;
const { name } = ctx.request.body;
if (!name || name.trim() === '') {
ctx.body = {
code: 400,
message: '单位名称不能为空',
};
return;
}
const trimmedName = name.trim();
try {
const systemUnit = await ctx.model.StockUnit.findOne({
where: {
name: trimmedName,
warehouse_id: null,
},
});
if (systemUnit) {
ctx.body = {
code: 400,
message: '该单位是系统预设单位,不允许添加',
};
return;
}
const existUnit = await ctx.model.StockUnit.findOne({
where: {
name: trimmedName,
warehouse_id,
},
});
if (existUnit) {
ctx.body = {
code: 400,
message: '该单位名称已存在',
};
return;
}
await ctx.model.StockUnit.create({
name: trimmedName,
warehouse_id,
});
const where = {};
if (warehouse_id) {
where[ctx.app.Sequelize.Op.or] = [
{ warehouse_id: null },
{ warehouse_id },
];
} else {
where.warehouse_id = null;
}
await ctx.model.StockUnit.findAll({
where,
order: [
[ 'warehouse_id', 'ASC' ],
[ 'created_at', 'DESC' ],
],
});
return this.success('添加成功', { code: 200 });
} catch (error) {
return this.success('创建库存单位失败', { code: 200 });
}
}
/**
* 快捷搜索仓库商品。
* @param {Object} data 请求体(含 keyword)
* @return {Promise<Object>} data 为搜索结果数组
*/
async search(data) {
const { service } = this;
const result = await service.systems.stockStore.search(data);
return this.success('ok', result);
}
}
module.exports = WarehouseService;

View File

@ -0,0 +1,119 @@
'use strict';
const MainService = require('../../main');
/**
* 系统方法层:storage.entry(入库单相关接口包装层)。
* 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。
* 注意:当前实现仅为包装层,实际业务逻辑完全依赖底层 service 的方法实现。
*/
class entryService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,get,create,addDetail,deleteDetail,detailChange,cancel,completeEntry';
const _noNeedLog = 'list,get,addDetail,deleteDetail,detailChange';
const _noNeedAuth = 'list,get,create,addDetail,deleteDetail,detailChange,cancel,completeEntry';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 入库单列表查询。
* @param {Object} data 请求体
* @param {Object} [data.pagination] 分页参数
* @param {Object} [data.where] 动态筛选条件
* @param {Object} [data.sort] 排序参数
* @return {Promise<Object>} 统一 success 包装
*/
async list(data = {}) {
const { service } = this;
const { pagination, sort } = data;
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
const result = await service.systems.storage.entry.list(where, pagination, sort);
return this.success('ok', result);
}
/**
* 查询入库单详情。
* @param {Object} data 请求体
* @param {number} [data.id] 入库单ID
* @param {string} [data.entry_order_code] 入库单号
* @return {Promise<Object>} 统一 success 包装
*/
async get(data = {}) {
const { service } = this;
const result = await service.systems.storage.entry.get(data);
return this.success('ok', result);
}
/**
* 新建入库单。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一 success 包装
*/
async create(data = {}) {
const { service } = this;
const result = await service.systems.storage.entry.create(data);
return this.success('ok', result);
}
/**
* 新增入库明细。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一 success 包装
*/
async addDetail(data = {}) {
const { service } = this;
const result = await service.systems.storage.entry.addDetail(data);
return this.success('ok', result);
}
/**
* 删除入库明细。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一 success 包装
*/
async deleteDetail(data = {}) {
const { service } = this;
const result = await service.systems.storage.entry.deleteDetail(data);
return this.success('ok', result);
}
/**
* 修改入库明细。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一 success 包装
*/
async detailChange(data = {}) {
const { service } = this;
const result = await service.systems.storage.entry.detailChange(data);
return this.success('ok', result);
}
/**
* 作废入库单。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一 success 包装
*/
async cancel(data = {}) {
const { service } = this;
const result = await service.systems.storage.entry.cancel(data);
return this.success('ok', result);
}
/**
* 完成入库单。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一 success 包装
*/
async completeEntry(data = {}) {
const { service } = this;
const result = await service.systems.storage.entry.completeEntry(data);
return this.success('ok', result);
}
}
module.exports = entryService;

View File

@ -1,7 +1,11 @@
'use strict';
const MainService = require('../../main');
/**
* 系统方法层:storage.receiving(收货单相关接口包装层)。
* 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。
* 注意:当前实现仅为包装层,实际业务逻辑完全依赖底层 service 的方法实现。
*/
class configService extends MainService {
constructor(ctx) {
super(ctx);
@ -11,71 +15,166 @@ class configService extends MainService {
const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 收货单列表查询(system method 包装层)。
* @param {Object} data 请求体
* @param {Object} [data.pagination] 分页参数
* @param {Object} [data.where] 筛选条件
* @return {Promise<Object>} 统一成功包装响应
*/
async getReceivingList(data) {
const { service } = this;
const { pagination, where } = data;
console.log('where', where);
console.log('service.systems.storage.receiving', service.systems.storage.index.index);
const result = await service.systems.storage.receiving.getReceivingList(where, pagination);
const { pagination, sort } = data;
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort);
return this.success('ok', result);
}
/**
* 收货单详情查询(分页返回明细)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {Object} data.pagination 明细分页参数
* @return {Promise<Object>} 统一成功包装响应
*/
async getReceivingDetail(data) {
const { service } = this;
const result = await service.systems.storage.receiving.getReceivingDetail(data);
return this.success('ok', result);
}
/**
* 批量作废收货单。
* @param {Object} data 请求体
* @param {number[]} data.ids 收货单ID数组
* @return {Promise<Object>} 统一成功包装响应
*/
async batchCancelReceiving(data){
const { service } = this;
const result = await service.systems.storage.receiving.batchCancelReceiving(data);
return this.success('ok', result);
}
/**
* 创建收货单。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async create(data) {
const { service } = this;
const result = await service.systems.storage.receiving.create(data);
return this.success('创建失败', result);
}
/**
* 添加收货商品(当前依赖底层 addItem 实现)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {Object} data.item 商品信息
* @return {Promise<Object>} 统一成功包装响应
*/
async addItem(data) {
const { service } = this;
const { id, item } = data;
const result = await service.systems.storage.receiving.addItem(id, item);
return this.success('ok', result);
}
/**
* 删除收货商品(当前依赖底层 removeItem 实现)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {number} data.item_id 商品明细ID
* @return {Promise<Object>} 统一成功包装响应
*/
async removeItem(data) {
const { service } = this;
const { id, item_id } = data;
const result = await service.systems.storage.receiving.removeItem(id, item_id);
return this.success('ok', result);
}
/**
* 保存收货单(兼容接口)。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async saveReceiving(data) {
const { service } = this;
const result = await service.systems.storage.receiving.saveReceiving(data);
return this.success('ok', result);
}
/**
* 查询收货单完整信息(含明细与图片)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @return {Promise<Object>} 统一成功包装响应
*/
async get(data) {
const { service } = this;
const result = await service.systems.storage.receiving.get(data);
return this.success('ok', result);
}
/**
* 新增一条收货明细(默认空模板)。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async addDetail(data) {
const { service } = this;
const result = await service.systems.storage.receiving.addDetail(data);
return this.success('ok', result);
}
/**
* 删除收货明细。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async deleteDetail(data) {
const { service } = this;
const result = await service.systems.storage.receiving.deleteDetail(data);
return this.success('ok', result);
}
/**
* 修改收货明细字段。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async detailChange(data) {
const { service } = this;
const result = await service.systems.storage.receiving.detailChange(data);
return this.success('ok', result);
}
/**
* 作废收货单(单条)。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async cancel(data) {
const { service } = this;
const result = await service.systems.storage.receiving.invalid(data);
return this.success('ok', result);
}
/**
* 完成收货单并触发入库处理。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {string} [data.remark] 完成备注
* @return {Promise<Object>} 统一成功包装响应
*/
async completeReceiving(data) {
const { service } = this;
const result = await service.systems.storage.receiving.completeReceiving(data);

View File

@ -7,6 +7,8 @@ const WECHAT_BIND_CACHE_PREFIX = 'user:wechat:bind:';
const WECHAT_BIND_CODE_CACHE_PREFIX = 'user:wechat:bind:code:';
const WECHAT_BIND_CACHE_TTL_SECONDS = 600;
const WECHAT_BIND_RECHECK_INTERVAL_MS = 5000;
const WECHAT_BIND_EVENT_CHANNEL_PREFIX = 'user:wechat:bind:event:';
const WECHAT_BIND_LONG_POLL_TIMEOUT_MS = 60000;
class UserService extends Service {
constructor(ctx) {
@ -99,6 +101,210 @@ class UserService extends Service {
return rows[0];
}
getWechatBindEventChannel(accountId) {
return `${WECHAT_BIND_EVENT_CHANNEL_PREFIX}${accountId}`;
}
getWechatLongPollTimeoutMs(rawTimeoutMs) {
const timeoutMs = Number(rawTimeoutMs);
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
return WECHAT_BIND_LONG_POLL_TIMEOUT_MS;
}
return Math.min(timeoutMs, WECHAT_BIND_LONG_POLL_TIMEOUT_MS);
}
shouldUseWechatBindLongPoll(data = {}, state = null) {
if (!state || state.status === 'bound') {
return false;
}
if (data.forceRefresh) {
return false;
}
if (data.isInit === true || data.init === true || data.firstLoad === true) {
return false;
}
const explicitEnable = data.longPoll === true || data.waitForChange === true;
return explicitEnable;
}
async publishWechatBindEvent(accountId, payload = {}) {
const { app } = this;
if (!accountId) {
return;
}
const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null;
if (!cacheRedis) {
return;
}
const channel = this.getWechatBindEventChannel(accountId);
const eventData = {
account_id: accountId,
event_at: new Date().toISOString(),
...payload,
};
try {
await cacheRedis.publish(channel, JSON.stringify(eventData));
} catch (error) {
app.coreLogger.warn(`发布微信绑定事件失败: ${error.message}`);
}
}
async waitForWechatBindEvent(accountId, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) {
const { app } = this;
const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null;
if (!cacheRedis || !accountId || typeof cacheRedis.duplicate !== 'function') {
return {
timed_out: true,
reason: 'redis_not_available',
};
}
const channel = this.getWechatBindEventChannel(accountId);
const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs);
const subscriber = cacheRedis.duplicate();
return await new Promise(resolve => {
let settled = false;
let timer = null;
const cleanup = () => {
subscriber.removeListener('message', onMessage);
subscriber.removeListener('error', onError);
Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => {
if (typeof subscriber.quit === 'function') {
Promise.resolve(subscriber.quit()).catch(() => {
if (typeof subscriber.disconnect === 'function') {
subscriber.disconnect();
}
});
return;
}
if (typeof subscriber.disconnect === 'function') {
subscriber.disconnect();
}
});
};
const finalize = result => {
if (settled) {
return;
}
settled = true;
if (timer) {
clearTimeout(timer);
}
cleanup();
resolve(result);
};
const onMessage = (messageChannel, message) => {
if (messageChannel !== channel) {
return;
}
let eventData = null;
try {
eventData = message ? JSON.parse(message) : null;
} catch (error) {
eventData = { raw: message };
}
finalize({
timed_out: false,
reason: 'event',
event: eventData,
});
};
const onError = error => {
app.coreLogger.warn(`订阅微信绑定事件失败: ${error.message}`);
finalize({
timed_out: true,
reason: 'subscribe_error',
});
};
timer = setTimeout(() => {
finalize({
timed_out: true,
reason: 'timeout',
});
}, waitMs);
subscriber.on('message', onMessage);
subscriber.on('error', onError);
Promise.resolve(subscriber.subscribe(channel)).catch(error => {
app.coreLogger.warn(`订阅微信绑定频道失败: ${error.message}`);
finalize({
timed_out: true,
reason: 'subscribe_failed',
});
});
});
}
async refreshWechatBindState(accountId, cachedState = null) {
const now = Date.now();
const cacheKey = this.getWechatBindCacheKey(accountId);
const ye4sBinding = await this.findYe4sBindingByAccountId(accountId);
if (ye4sBinding) {
const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : '';
const bindState = {
account_id: accountId,
status: 'bound',
code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(),
updated_at: new Date().toISOString(),
next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: ye4sBinding.id || null,
};
await Promise.all([
this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS),
this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS),
]);
const hasChanged = !cachedState || cachedState.status !== 'bound' || cachedState.code !== bindState.code;
if (hasChanged) {
await this.publishWechatBindEvent(accountId, {
status: 'bound',
code: bindState.code,
source: 'db',
});
}
return {
state: bindState,
source: 'db',
message: '账号已绑定微信',
};
}
const code = (cachedState && cachedState.code) || this.createWechatBindCode();
const pendingState = {
account_id: accountId,
status: 'pending',
code,
updated_at: new Date().toISOString(),
next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: null,
};
await Promise.all([
this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS),
this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS),
]);
return {
state: pendingState,
source: code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated',
message: '账号未绑定,已生成绑定码',
};
}
/**
* 用户登录(重构版)
* @param {string} username - 用户名/手机号/邮箱
@ -256,6 +462,7 @@ class UserService extends Service {
const cacheKey = this.getWechatBindCacheKey(accountId);
const forceRefresh = !!data.forceRefresh;
const now = Date.now();
const waitTimeoutMs = this.getWechatLongPollTimeoutMs(data.waitTimeoutMs);
let cachedState = null;
try {
@ -266,57 +473,55 @@ class UserService extends Service {
if (cachedState && !forceRefresh) {
const nextCheckAt = Number(cachedState.next_db_check_at || 0);
if (nextCheckAt > now) {
let refreshedState = null;
if (nextCheckAt <= now) {
refreshedState = await this.refreshWechatBindState(accountId, cachedState);
cachedState = refreshedState.state;
}
if (this.shouldUseWechatBindLongPoll(data, cachedState)) {
const waitResult = await this.waitForWechatBindEvent(accountId, waitTimeoutMs);
try {
cachedState = await this.app.getCacheAsync(cacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`);
}
const nextState = await this.refreshWechatBindState(accountId, cachedState);
const timeoutMessage = waitResult.timed_out ? '等待绑定状态变化超时,返回当前状态' : nextState.message;
return {
success: true,
code: 200,
data: this.formatBindWechatData(cachedState, 'cache'),
message: '获取绑定码成功(缓存)',
data: this.formatBindWechatData(nextState.state, nextState.source),
message: timeoutMessage,
};
}
}
const ye4sBinding = await this.findYe4sBindingByAccountId(accountId);
if (ye4sBinding) {
const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : '';
const bindState = {
account_id: accountId,
status: 'bound',
code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(),
updated_at: new Date().toISOString(),
next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: ye4sBinding.id || null,
};
await this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS);
await this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS);
if (refreshedState) {
return {
success: true,
code: 200,
data: this.formatBindWechatData(refreshedState.state, refreshedState.source),
message: refreshedState.message,
};
}
return {
success: true,
code: 200,
data: this.formatBindWechatData(bindState, 'db'),
message: '账号已绑定微信',
data: this.formatBindWechatData(cachedState, 'cache'),
message: '获取绑定码成功(缓存)',
};
}
const code = (cachedState && cachedState.code) || this.createWechatBindCode();
const pendingState = {
account_id: accountId,
status: 'pending',
code,
updated_at: new Date().toISOString(),
next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: null,
};
await this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS);
await this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS);
const refreshed = await this.refreshWechatBindState(accountId, cachedState);
return {
success: true,
code: 200,
data: this.formatBindWechatData(pendingState, code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated'),
message: '账号未绑定,已生成绑定码',
data: this.formatBindWechatData(refreshed.state, refreshed.source),
message: refreshed.message,
};
} catch (error) {
app.coreLogger.error(`获取微信绑定码失败: ${error.message}`);
@ -395,8 +600,15 @@ class UserService extends Service {
next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: ye4sUser.id || null,
};
await this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS);
await this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS);
await Promise.all([
this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS),
this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS),
]);
await this.publishWechatBindEvent(wmsAccountId, {
status: 'bound',
code,
source: 'api',
});
return {
success: true,
@ -429,6 +641,127 @@ class UserService extends Service {
}
}
/**
* 账号绑定:供 ye4s 扫码后回调,按临时码绑定到指定 ye4s_user.id
* @param {Object} data
* @return {Object}
*/
async bindAccountByTempCode(data = {}) {
const { ctx, app } = this;
try {
const code = typeof data.code === 'string' ? data.code.trim() : '';
const rawYe4sUserId = data.ye4s_user_id ?? data.ye4sUserId;
const ye4sUserId = Number(rawYe4sUserId);
if (!code) {
return {
success: false,
code: 0,
data: null,
message: '缺少绑定码 code',
};
}
if (!this.parseWechatBindCode(code)) {
return {
success: false,
code: 0,
data: null,
message: '无效的绑定码格式',
};
}
if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) {
return {
success: false,
code: 0,
data: null,
message: '缺少有效的 ye4s_user_id',
};
}
const userResult = await this.getUserByTempCode({ code });
if (!userResult || !userResult.success) {
return {
success: false,
code: 0,
data: null,
message: userResult && userResult.message ? userResult.message : '绑定码不存在或已过期',
};
}
const accountId = Number(userResult.data && userResult.data.account_id);
if (!Number.isFinite(accountId) || accountId <= 0) {
return {
success: false,
code: 0,
data: null,
message: '绑定码未匹配到有效账号',
};
}
const ye4sClient = ctx.app.mysql.get('ye4s');
const ye4sUser = await ye4sClient.get('ye4s_user', { id: ye4sUserId });
if (!ye4sUser) {
return {
success: false,
code: 0,
data: null,
message: 'ye4s 用户不存在',
};
}
const updateRet = await ye4sClient.update('ye4s_user', {
id: ye4sUserId,
wms_account_id: accountId,
tmp_code: code,
});
const boundState = {
account_id: accountId,
status: 'bound',
code,
updated_at: new Date().toISOString(),
next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: ye4sUserId,
};
await Promise.all([
this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS),
this.setWechatBindCache(this.getWechatBindCacheKey(accountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS),
]);
await this.publishWechatBindEvent(accountId, {
status: 'bound',
code,
source: 'gateway-bind',
});
return {
success: true,
code: 200,
data: {
account_id: accountId,
ye4s_user_id: ye4sUserId,
code,
status: 'bound',
source: 'gateway-bind',
affected_rows: Number(updateRet && updateRet.affectedRows ? updateRet.affectedRows : 0),
updated_at: boundState.updated_at,
},
message: '绑定成功',
};
} catch (error) {
app.coreLogger.error(`账号绑定失败: ${error.message}`);
return {
success: false,
code: 0,
data: null,
message: '绑定失败,请稍后重试',
};
}
}
/**
* 解绑微信:清理 ye4s_user 中与当前账号关联的数据
* @return {Object}
@ -460,13 +793,19 @@ class UserService extends Service {
for (const row of bindRows) {
const rowCode = typeof row.tmp_code === 'string' ? row.tmp_code.trim() : '';
if (rowCode) {
await this.setWechatBindCodeCache(rowCode, null, 1);
await this.setWechatBindCodeCache(rowCode, {
account_id: accountId,
status: 'unbound',
code: rowCode,
updated_at: new Date().toISOString(),
next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: row.id || null,
}, WECHAT_BIND_CACHE_TTL_SECONDS);
}
try {
const ret = await ye4sClient.update('ye4s_user', {
id: row.id,
wms_account_id: null,
tmp_code: null,
});
affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0);
} catch (err) {
@ -474,7 +813,6 @@ class UserService extends Service {
const ret = await ye4sClient.update('ye4s_user', {
id: row.id,
wms_account_id: 0,
tmp_code: '',
});
affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0);
}
@ -483,9 +821,20 @@ class UserService extends Service {
const cacheKey = this.getWechatBindCacheKey(accountId);
const cachedState = await this.app.getCacheAsync(cacheKey);
if (cachedState && cachedState.code) {
await this.setWechatBindCodeCache(cachedState.code, null, 1);
await this.setWechatBindCodeCache(cachedState.code, {
account_id: accountId,
status: 'unbound',
code: cachedState.code,
updated_at: new Date().toISOString(),
next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: cachedState.ye4s_user_id || null,
}, WECHAT_BIND_CACHE_TTL_SECONDS);
}
await this.setWechatBindCache(cacheKey, null, 1);
await this.publishWechatBindEvent(accountId, {
status: 'unbound',
source: 'unbind',
});
return {
success: true,

View File

@ -0,0 +1,418 @@
'use strict';
const Service = require('egg').Service;
const RESERVED_EMPLOYEE_NAME = '测试工号保留';
class SettingAccountService extends Service {
createError(message, code = 500) {
const error = new Error(message);
error.code = code;
return error;
}
getCurrentStoreId() {
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
if (!Number.isFinite(storeId) || storeId <= 0) {
throw this.createError('未识别到当前主体,无法操作工号', 400);
}
return storeId;
}
getCurrentEmployeeId() {
const employeeId = Number(this.ctx.user && this.ctx.user.employees_id);
if (!Number.isFinite(employeeId) || employeeId <= 0) {
return null;
}
return employeeId;
}
getWmsClient() {
return this.ctx.app.mysql.get('wms');
}
normalizePhone(phone) {
return typeof phone === 'string' ? phone.trim() : '';
}
isValidPhone(phone) {
return /^1[3-9]\d{9}$/.test(phone);
}
normalizeName(name) {
return typeof name === 'string' ? name.trim() : '';
}
normalizeUsername(username) {
return typeof username === 'string' ? username.trim() : '';
}
generateUsername() {
const suffix = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
return `acct_${suffix}`;
}
async findRawAccountByPhone(phone) {
const rows = await this.getWmsClient().select('wms_account', {
where: { phone },
columns: [ 'id', 'username', 'phone', 'email', 'real_name', 'status' ],
limit: 1,
});
return rows && rows.length > 0 ? rows[0] : null;
}
async findRawAccountByUsername(username) {
const rows = await this.getWmsClient().select('wms_account', {
where: { username },
columns: [ 'id', 'username', 'phone', 'email', 'real_name', 'status' ],
limit: 1,
});
return rows && rows.length > 0 ? rows[0] : null;
}
async getAvatarMeta(employeeId) {
const { ctx } = this;
const avatarRef = await ctx.model.FileReference.findOne({
where: {
business_type: 'avater',
business_id: String(employeeId),
},
include: [
{
model: ctx.model.File,
as: 'file',
attributes: [ 'id', 'file_url', 'file_name' ],
required: false,
},
],
order: [[ 'created_at', 'DESC' ]],
});
return {
avatar_file_id: Number(avatarRef && avatarRef.file_id ? avatarRef.file_id : 0) || null,
avatar_url: avatarRef && avatarRef.file ? avatarRef.file.file_url : '',
avatar_name: avatarRef && avatarRef.file ? avatarRef.file.file_name : '',
};
}
async resolveRoleId(data = {}) {
const { ctx } = this;
const explicitRoleId = Number(data.role_id || data.roleId || 0);
if (Number.isFinite(explicitRoleId) && explicitRoleId > 0) {
const role = await ctx.model.Role.findOne({
where: {
id: explicitRoleId,
status: 1,
},
});
if (!role) {
throw this.createError('指定角色不存在或已禁用', 400);
}
return explicitRoleId;
}
const currentEmployeeId = this.getCurrentEmployeeId();
if (!currentEmployeeId) {
throw this.createError('未识别到当前操作人工号,无法继承角色', 400);
}
const currentRole = await ctx.model.EmployeeRole.findOne({
where: { employee_id: currentEmployeeId },
order: [[ 'id', 'ASC' ]],
});
if (!currentRole) {
throw this.createError('当前操作人工号未绑定角色,无法创建新工号', 400);
}
return Number(currentRole.role_id);
}
async formatEmployeeRow(employee) {
const account = await this.getWmsClient().get('wms_account', {
id: employee.account_id,
});
const avatar = await this.getAvatarMeta(employee.id);
return {
employee_id: Number(employee.id),
account_id: Number(employee.account_id),
store_id: Number(employee.store_id),
real_name: employee.real_name || '',
status: Number(employee.status),
created_at: employee.created_at,
updated_at: employee.updated_at,
username: account && account.username ? account.username : '',
phone: account && account.phone ? account.phone : '',
email: account && account.email ? account.email : '',
account_real_name: account && account.real_name ? account.real_name : '',
...avatar,
};
}
async list(data = {}) {
const { ctx } = this;
const storeId = this.getCurrentStoreId();
const statusFilter = data.includeDisabled === true
? undefined
: (data.status === 0 || data.status === '0' ? 0 : 1);
const where = {
store_id: storeId,
};
if (statusFilter === 0 || statusFilter === 1) {
where.status = statusFilter;
}
const employees = await ctx.model.AccountStoreEmployee.findAll({
where,
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
});
const list = [];
for (const employee of employees) {
list.push(await this.formatEmployeeRow(employee));
}
return {
code: 200,
data: list,
};
}
async add(data = {}) {
const { ctx, service } = this;
let createdAccountId = 0;
try {
const storeId = this.getCurrentStoreId();
const phone = this.normalizePhone(data.phone);
const realName = this.normalizeName(data.real_name || data.realName);
const password = typeof data.password === 'string' && data.password.trim()
? data.password.trim()
: '111111';
if (!phone) {
throw this.createError('phone 参数不能为空', 400);
}
if (!this.isValidPhone(phone)) {
throw this.createError('phone 格式不正确', 400);
}
if (!realName) {
throw this.createError('real_name 参数不能为空', 400);
}
if (realName === RESERVED_EMPLOYEE_NAME) {
throw this.createError(`新增工号禁止直接使用保留名称 ${RESERVED_EMPLOYEE_NAME}`, 400);
}
const roleId = await this.resolveRoleId(data);
let account = await this.findRawAccountByPhone(phone);
if (account && Number(account.status) !== 1) {
throw this.createError('该手机号对应账号已禁用,无法新增工号', 409);
}
if (!account) {
let username = this.normalizeUsername(data.username);
if (!username) {
username = this.generateUsername();
}
const existingUsername = await this.findRawAccountByUsername(username);
if (existingUsername) {
throw this.createError('username 已存在', 409);
}
const salt = service.systems.auth.user.generateSalt();
const passwordHash = await service.systems.auth.user.encryptPassword(password, salt);
const email = typeof data.email === 'string' && data.email.trim()
? data.email.trim()
: `${username}@autotest.local`;
const insertRet = await this.getWmsClient().insert('wms_account', {
username,
phone,
email,
password_hash: passwordHash,
real_name: realName,
status: 1,
salt,
created_at: new Date(),
updated_at: new Date(),
});
createdAccountId = Number(insertRet && insertRet.insertId ? insertRet.insertId : 0);
account = await this.getWmsClient().get('wms_account', { id: createdAccountId });
}
const activeBinding = await ctx.model.AccountStoreEmployee.findOne({
where: {
account_id: account.id,
store_id: storeId,
status: 1,
},
});
if (activeBinding) {
throw this.createError('该手机号已绑定当前主体工号', 409);
}
const { employee, employeeRole } = await service.systems.store.ensureEmployeeRoleBinding({
accountId: Number(account.id),
storeId,
roleId,
realName,
});
await service.systems.auth.user.clearUserCache(Number(account.id));
const formatted = await this.formatEmployeeRow(employee);
return {
code: 200,
data: {
...formatted,
role_id: Number(employeeRole.role_id),
is_new_account: createdAccountId > 0,
},
};
} catch (error) {
if (createdAccountId > 0) {
await this.getWmsClient().delete('wms_account', { id: createdAccountId });
}
throw error;
}
}
async delete(data = {}) {
const { ctx, service } = this;
const storeId = this.getCurrentStoreId();
const currentEmployeeId = this.getCurrentEmployeeId();
const employeeId = Number(data.employee_id || data.id || 0);
if (!employeeId) {
throw this.createError('employee_id 参数不能为空', 400);
}
if (currentEmployeeId && employeeId === currentEmployeeId) {
throw this.createError('不允许删除当前登录工号', 400);
}
const employee = await ctx.model.AccountStoreEmployee.findOne({
where: {
id: employeeId,
store_id: storeId,
},
});
if (!employee) {
throw this.createError('工号不存在或无权限删除', 404);
}
if (Number(employee.status) !== 1) {
return {
code: 200,
data: {
employee_id: employeeId,
account_id: Number(employee.account_id),
status: 'deleted',
already_deleted: true,
},
};
}
await employee.update({
status: 0,
updated_at: new Date(),
});
await ctx.model.AccountPlatformActive.destroy({
where: {
employee_id: employeeId,
},
});
await service.systems.auth.user.clearUserCache(Number(employee.account_id));
return {
code: 200,
data: {
employee_id: employeeId,
account_id: Number(employee.account_id),
status: 'deleted',
},
};
}
async update(data = {}) {
const { ctx, service } = this;
const storeId = this.getCurrentStoreId();
const employeeId = Number(data.employee_id || data.id || 0);
const hasRealName = Object.prototype.hasOwnProperty.call(data, 'real_name') || Object.prototype.hasOwnProperty.call(data, 'realName');
const hasFileId = Object.prototype.hasOwnProperty.call(data, 'file_id') || Object.prototype.hasOwnProperty.call(data, 'avatar_file_id') || Object.prototype.hasOwnProperty.call(data, 'fileId');
const realName = this.normalizeName(data.real_name || data.realName);
const fileId = Number(data.file_id || data.avatar_file_id || data.fileId || 0);
if (!employeeId) {
throw this.createError('employee_id 参数不能为空', 400);
}
if (!hasRealName && !hasFileId) {
throw this.createError('至少需要更新 real_name 或 file_id', 400);
}
if (hasRealName && !realName) {
throw this.createError('real_name 参数不能为空', 400);
}
if (hasFileId && !fileId) {
throw this.createError('file_id 参数不能为空', 400);
}
const employee = await ctx.model.AccountStoreEmployee.findOne({
where: {
id: employeeId,
store_id: storeId,
status: 1,
},
});
if (!employee) {
throw this.createError('工号不存在或无权限更新', 404);
}
if (hasRealName && realName !== employee.real_name) {
await employee.update({
real_name: realName,
updated_at: new Date(),
});
}
if (hasFileId) {
const file = await ctx.model.File.findOne({
where: {
id: fileId,
is_deleted: false,
},
});
if (!file) {
throw this.createError('头像文件不存在', 404);
}
await service.systems.file.ReferenceFile({
id: employeeId,
type: 'avater',
images: [
{
file_id: fileId,
sort_order: 0,
},
],
});
}
await service.systems.auth.user.clearUserCache(Number(employee.account_id));
const refreshed = await ctx.model.AccountStoreEmployee.findByPk(employeeId);
return {
code: 200,
data: await this.formatEmployeeRow(refreshed),
};
}
}
module.exports = SettingAccountService;

View File

@ -169,7 +169,131 @@ class PrintTemplateService extends Service {
ctx.logger.error('保存打印模板失败:', error);
throw new Error('保存打印模板失败');
}
}/**
}
async createTemplate(data = {}) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const now = new Date();
const {
template_name,
business_type,
page_width,
page_height,
template_content = [],
is_default = false,
} = data;
const platform = 'default';
const template_type = 'CUSTOM';
const template_url = '';
const existingTemplate = await ctx.model.PrintTemplate.findOne({
where: {
business_type,
platform,
template_type,
warehouse_id: warehouseId,
},
order: [[ 'id', 'DESC' ]],
});
if (existingTemplate) {
if (existingTemplate.status === 'ACTIVE') {
throw new Error('同一业务类型和平台下已存在自定义模板');
}
await existingTemplate.update({
template_name,
page_width,
page_height,
template_content,
template_url,
is_default,
status: 'ACTIVE',
delete_at: null,
update_at: now,
});
return {
message: '模板创建成功',
code: 200,
data: {
id: existingTemplate.id,
},
};
}
let created;
try {
created = await ctx.model.PrintTemplate.create({
template_name,
business_type,
page_width,
page_height,
template_content,
platform,
template_type,
template_url,
is_default,
warehouse_id: warehouseId,
status: 'ACTIVE',
create_at: now,
update_at: now,
delete_at: null,
}, {
validate: false,
});
} catch (error) {
if (error?.name === 'SequelizeUniqueConstraintError') {
throw new Error('同一业务类型和平台下已存在自定义模板');
}
const details = Array.isArray(error?.errors)
? error.errors.map(item => `${item.path || 'unknown'}:${item.message}`).join(';')
: '';
const errMsg = [ error?.name, error?.message, details ].filter(Boolean).join(' | ');
throw new Error(errMsg || '模板创建失败');
}
return {
message: '模板创建成功',
code: 200,
data: {
id: created.id,
},
};
}
async deleteTemplate(id) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const template = await ctx.model.PrintTemplate.findOne({
where: {
id,
warehouse_id: warehouseId,
status: 'ACTIVE',
},
});
if (!template) {
throw new Error('模板不存在或无权限');
}
await template.update({
status: 'DISABLED',
delete_at: new Date(),
update_at: new Date(),
});
return {
message: '模板删除成功',
code: 200,
data: {
id,
},
};
}
/**
* 获取所有业务类型(用于下拉选择)- 支持分组展示
* @return {Object} 业务类型及打印项列表,包含分组信息
*/

View File

@ -1,5 +1,12 @@
'use strict';
const Service = require('egg').Service;
const {
parseWhereConditions,
buildSequelizeCondition: buildSequelizeConditionUtil,
processConditionValue: processConditionValueUtil,
isEmptyValue: isEmptyValueUtil,
normalizeDate: normalizeDateUtil,
} = require('../../lib/query_condition_parser');
class stockStoreService extends Service {
constructor(ctx) {
@ -201,7 +208,7 @@ class stockStoreService extends Service {
// ⭐ 关键修复:使用 raw: true 获取纯对象
const itemInfo = await ctx.model.StockStore.findByPk(itemId, {
attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code' ], // 按需增加字段
attributes: ['id', 'stock_id', 'warehouse_code', 'item_code'], // 按需增加字段
raw: true, // ⭐ 必须:转换为纯 JavaScript 对象
});
@ -238,7 +245,7 @@ class stockStoreService extends Service {
app.logger.warn('缓存服务异常,降级直接查询数据库', itemId);
try {
const itemInfo = await ctx.model.StockStore.findByPk(itemId, {
attributes: [ 'id', 'stock_id', 'warehouse_code', 'item_code' ],
attributes: ['id', 'stock_id', 'warehouse_code', 'item_code'],
raw: true,
});
return itemInfo || null;
@ -538,7 +545,7 @@ class stockStoreService extends Service {
action: isLocking ? 'lock' : 'unlock',
quantity: absQty,
beforeLocked: isLocking ? stockRecord.locked_quantity - absQty : stockRecord.locked_quantity +
absQty,
absQty,
afterLocked: stockRecord.locked_quantity,
totalQuantity: stockRecord.quantity,
available: stockRecord.quantity - stockRecord.locked_quantity,
@ -847,7 +854,7 @@ class stockStoreService extends Service {
store_id: sourceData.store_id,
deleted_at: null,
},
attributes: [ 'id' ],
attributes: ['id'],
raw: true,
});
@ -958,7 +965,7 @@ class stockStoreService extends Service {
warehouse_id: warehouseId,
is_valid: 'Y',
},
attributes: [ 'id' ],
attributes: ['id'],
raw: true,
});
@ -1040,7 +1047,7 @@ class stockStoreService extends Service {
where: {},
order: [],
attributes: {
exclude: [ 'deleted_at' ],
exclude: ['deleted_at'],
},
};
const barcodeQueryOptions = {
@ -1064,64 +1071,90 @@ class stockStoreService extends Service {
prohibitedQueryOptions.where[Op.and] = [];
// 检测并处理条码查询条件
let hasBarcodeCondition = false;
let hasProhibitedCondition = false;
let barcodeCondition = null;
let parsedBarcodeInput = null;
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
? ctx.where
: (where && typeof where === 'object' ? where : {});
// 处理动态查询条件
if (where && Object.keys(where).length > 0) {
const dynamicConditions = [];
const prohibitedConditions = [];
const barcodedynamicConditions = [];
if (normalizedWhere && Object.keys(normalizedWhere).length > 0) {
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: {
barcode: {
bucket: 'barcode',
},
prohibited_type: {
bucket: 'prohibited',
field: 'id',
},
},
});
for (const fieldKey in where) {
const condition = where[fieldKey];
if (this.isEmptyValue(condition.value)) {
continue;
if (!parsed.ok) {
return {
code: 400,
data: {
list: [],
pagination: {
page: parseInt(page),
pageSize: parseInt(pageSize),
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total_quantity: 0,
total_locked: 0,
total_available: 0,
total_items: 0,
},
},
message: `筛选条件解析失败: ${parsed.reason}`,
};
}
// 检查是否是条码查询
if (fieldKey === 'barcode') {
hasBarcodeCondition = true;
barcodeCondition = this.buildSequelizeCondition(fieldKey, condition, app);
if (barcodeCondition) {
barcodedynamicConditions.push(barcodeCondition);
}
continue; // 暂不添加到动态条件中
}
if (fieldKey === 'prohibited_type') {
condition.field = 'id';
hasProhibitedCondition = true;
const prohibitedCondition = this.buildSequelizeCondition('id', condition, app);
if (prohibitedCondition) {
prohibitedConditions.push(prohibitedCondition);
}
continue;
}
// 其他字段的处理
const sequelizeCondition = this.buildSequelizeCondition(fieldKey, condition, app);
if (sequelizeCondition) {
dynamicConditions.push(sequelizeCondition);
}
parsedResult = parsed.result;
}
const {
dynamicConditions,
bucketConditions,
bucketFlags,
rawConditionsByField,
} = parsedResult;
const barcodeDynamicConditions = bucketConditions.barcode || [];
const prohibitedConditions = bucketConditions.prohibited || [];
hasBarcodeCondition = Boolean(bucketFlags.barcode);
hasProhibitedCondition = Boolean(bucketFlags.prohibited);
barcodeCondition = barcodeDynamicConditions[0] || null;
parsedBarcodeInput = rawConditionsByField.barcode || null;
if (dynamicConditions.length > 0) {
queryOptions.where[Op.and].push({
[Op.and]: dynamicConditions,
});
}
if (barcodedynamicConditions.length > 0) {
if (barcodeDynamicConditions.length > 0) {
barcodeQueryOptions.where[Op.and].push({
[Op.and]: barcodedynamicConditions,
[Op.and]: barcodeDynamicConditions,
});
}
if (prohibitedConditions.length > 0) {
prohibitedQueryOptions.where[Op.and].push({
[Op.and]: prohibitedConditions,
});
}
}
// 如果有条码查询条件,先查询匹配的库存ID
@ -1131,11 +1164,11 @@ class stockStoreService extends Service {
let barcodeValues = [];
// 根据不同的条件格式提取条码值
if (where.barcode.value) {
if (Array.isArray(where.barcode.value)) {
barcodeValues = where.barcode.value;
} else if (typeof where.barcode.value === 'string') {
barcodeValues = [ where.barcode.value ];
if (parsedBarcodeInput && parsedBarcodeInput.value) {
if (Array.isArray(parsedBarcodeInput.value)) {
barcodeValues = parsedBarcodeInput.value;
} else if (typeof parsedBarcodeInput.value === 'string') {
barcodeValues = [ parsedBarcodeInput.value ];
}
}
@ -1143,7 +1176,8 @@ class stockStoreService extends Service {
// 构建条码查询条件
const barcodeWhere = {};
if (where.barcode.operator === 'eq') {
const barcodeOperator = String(parsedBarcodeInput.operator || 'like').toLowerCase();
if (barcodeOperator === 'eq') {
// 精确查询
if (barcodeValues.length === 1) {
barcodeWhere.barcode = barcodeValues[0];
@ -1152,7 +1186,7 @@ class stockStoreService extends Service {
[Op.in]: barcodeValues,
};
}
} else if (where.barcode.operator === 'like') {
} else if (barcodeOperator === 'like') {
// 模糊查询
if (barcodeValues.length === 1) {
barcodeWhere.barcode = {
@ -1175,8 +1209,8 @@ class stockStoreService extends Service {
// 查询匹配的条码,获取库存ID
const matchedBarcodes = await ctx.model.StockBarcode.findAll({
...barcodeQueryOptions,
attributes: [ 'stock_id' ],
group: [ 'stock_id' ], // 使用 GROUP BY 去重
attributes: ['stock_id'],
group: ['stock_id'], // 使用 GROUP BY 去重
raw: true,
});
@ -1224,25 +1258,25 @@ class stockStoreService extends Service {
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at';
const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
queryOptions.order.push([ actualSortField, actualSortOrder ]);
queryOptions.order.push([actualSortField, actualSortOrder]);
// 计算分页偏移量
const offset = (page - 1) * pageSize;
// 执行查询:获取总数和数据
const [ total, data ] = await Promise.all([
const [total, data] = await Promise.all([
// 获取总数
ctx.model.StockWarehouse.count({
where: queryOptions.where,
include: [ctx.model.StoreWarehouse.buildStoreStockInclude({
warehouseId: ctx.user.store_id,
required: true,
attributes: [ 'store_remask' ],
attributes: ['store_remask'],
}), {
...prohibitedQueryOptions,
model: ctx.model.ProhibitedType,
as: 'prohibited',
attributes: [ 'type_name' ],
attributes: ['type_name'],
required: hasProhibitedCondition,
}],
distinct: true,
@ -1254,12 +1288,12 @@ class stockStoreService extends Service {
include: [ctx.model.StoreWarehouse.buildStoreStockInclude({
warehouseId: ctx.user.store_id,
required: true,
attributes: [ 'store_remask' ],
attributes: ['store_remask'],
}), {
...prohibitedQueryOptions,
model: ctx.model.ProhibitedType,
as: 'prohibited',
attributes: [ 'type_name' ],
attributes: ['type_name'],
required: hasProhibitedCondition,
}],
limit: parseInt(pageSize),
@ -1297,7 +1331,7 @@ class stockStoreService extends Service {
include: [{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
attributes: ['file_url'],
required: true,
}],
});
@ -1346,7 +1380,7 @@ class stockStoreService extends Service {
// 如果有条码查询,添加匹配统计
...(hasBarcodeCondition && {
barcode_matched_count: matchedStockIds.length,
barcode_search_value: where.barcode.value,
barcode_search_value: parsedBarcodeInput ? parsedBarcodeInput.value : null,
}),
};
@ -1365,7 +1399,7 @@ class stockStoreService extends Service {
},
summary,
queryInfo: {
conditions: where,
conditions: normalizedWhere,
sortField: actualSortField,
sortOrder: actualSortOrder,
hasBarcodeSearch: hasBarcodeCondition,
@ -1408,180 +1442,11 @@ class stockStoreService extends Service {
* @return {Object|null} Sequelize条件对象
*/
buildSequelizeCondition(fieldKey, condition, app) {
const {
Sequelize,
} = app;
const {
operator = 'eq', value, type, isMultiple,
} = condition;
// 处理字段名
const fieldName = condition.field || fieldKey;
// 特殊值处理
const processedValue = this.processConditionValue(value, type);
// 根据操作符构建条件
switch (operator.toLowerCase()) {
case 'eq':
return {
[fieldName]: processedValue,
};
case 'ne':
return {
[fieldName]: {
[Sequelize.Op.ne]: processedValue,
},
};
case 'contains':
case 'like':
// 处理多值情况
if (Array.isArray(processedValue) && processedValue.length > 0) {
// 多个值使用 OR 连接
return {
[Sequelize.Op.or]: processedValue.map(val => ({
[fieldName]: {
[Sequelize.Op.like]: `%${val}%`,
},
})),
};
}
// 单个值正常处理
return {
[fieldName]: {
[Sequelize.Op.like]: `%${processedValue}%`,
},
};
case 'startswith':
// 处理多值情况
if (Array.isArray(processedValue) && processedValue.length > 0) {
return {
[Sequelize.Op.or]: processedValue.map(val => ({
[fieldName]: {
[Sequelize.Op.like]: `${val}%`,
},
})),
};
}
return {
[fieldName]: {
[Sequelize.Op.like]: `${processedValue}%`,
},
};
case 'endswith':
// 处理多值情况
if (Array.isArray(processedValue) && processedValue.length > 0) {
return {
[Sequelize.Op.or]: processedValue.map(val => ({
[fieldName]: {
[Sequelize.Op.like]: `%${val}`,
},
})),
};
}
return {
[fieldName]: {
[Sequelize.Op.like]: `%${processedValue}`,
},
};
case 'gt':
return {
[fieldName]: {
[Sequelize.Op.gt]: processedValue,
},
};
case 'lt':
return {
[fieldName]: {
[Sequelize.Op.lt]: processedValue,
},
};
case 'ge':
return {
[fieldName]: {
[Sequelize.Op.gte]: processedValue,
},
};
case 'le':
return {
[fieldName]: {
[Sequelize.Op.lte]: processedValue,
},
};
case 'in':
return Array.isArray(processedValue) ? {
[fieldName]: {
[Sequelize.Op.in]: processedValue,
},
} :
null;
case 'notin':
return Array.isArray(processedValue) ? {
[fieldName]: {
[Sequelize.Op.notIn]: processedValue,
},
} :
null;
case 'between':
return Array.isArray(processedValue) && processedValue.length === 2 ? {
[fieldName]: {
[Sequelize.Op.between]: processedValue,
},
} :
null;
case 'notbetween':
return Array.isArray(processedValue) && processedValue.length === 2 ? {
[fieldName]: {
[Sequelize.Op.notBetween]: processedValue,
},
} :
null;
case 'isnull':
return {
[fieldName]: {
[Sequelize.Op.is]: null,
},
};
case 'isnotnull':
return {
[fieldName]: {
[Sequelize.Op.not]: null,
},
};
case 'regexp':
return {
[fieldName]: {
[Sequelize.Op.regexp]: processedValue,
},
};
case 'notregexp':
return {
[fieldName]: {
[Sequelize.Op.notRegexp]: processedValue,
},
};
default:
// 默认使用等于操作符
return {
[fieldName]: processedValue,
};
const parsed = buildSequelizeConditionUtil(fieldKey, condition, app);
if (!parsed.ok) {
return null;
}
return parsed.condition;
}
/**
@ -1591,38 +1456,11 @@ class stockStoreService extends Service {
* @return {any} 处理后的值
*/
processConditionValue(value, type) {
if (value === undefined || value === null) {
return value;
}
return processConditionValueUtil(value, type);
}
switch (type) {
case 'boolean':
// 处理布尔值:true/Y -> 'Y', false/N -> 'N'
if (value === true || value === 'true' || value === 'Y' || value === 'y') {
return 'Y';
}
if (value === false || value === 'false' || value === 'N' || value === 'n') {
return 'N';
}
return value;
case 'date':
case 'daterange':
// 确保日期格式正确
if (Array.isArray(value)) {
return value.map(v => this.normalizeDate(v));
}
return this.normalizeDate(value);
case 'number':
// 转换为数字
const num = parseFloat(value);
return isNaN(num) ? value : num;
case 'text':
return value.split(',');
default:
return value;
}
normalizeDate(value) {
return normalizeDateUtil(value);
}
@ -1652,19 +1490,7 @@ class stockStoreService extends Service {
* @return {boolean} 是否为空
*/
isEmptyValue(value) {
if (value === undefined || value === null) {
return true;
}
if (typeof value === 'string' && value.trim() === '') {
return true;
}
if (Array.isArray(value) && value.length === 0) {
return true;
}
return false;
return isEmptyValueUtil(value);
}
async getProhibitedType() {
const {
@ -1690,9 +1516,9 @@ class stockStoreService extends Service {
],
},
order: [
[ 'warehouse_id', 'ASC' ], // 系统预设在前(warehouse_id为null)
[ 'sort_order', 'ASC' ], // 按排序字段
[ 'created_at', 'ASC' ], // 按创建时间
['warehouse_id', 'ASC'], // 系统预设在前(warehouse_id为null)
['sort_order', 'ASC'], // 按排序字段
['created_at', 'ASC'], // 按创建时间
],
attributes: [
'id',
@ -1733,7 +1559,7 @@ class stockStoreService extends Service {
include: [{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'id' ],
attributes: ['id'],
where: {
warehouse_id: warehouseId,
},
@ -1747,7 +1573,7 @@ class stockStoreService extends Service {
const { ctx, service, app } = this;
const { Op } = app.Sequelize;
const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit' ];
const canChangeFlide = ['brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit'];
const { ids, method, value } = ctx.request.body;
console.log('批量修改参数', ctx.request.body);
@ -1779,7 +1605,7 @@ class stockStoreService extends Service {
warehouse_id: warehouseId,
delete_at: null,
},
attributes: [ 'id' ],
attributes: ['id'],
});
if (existingRefs.length !== ids.length) {
@ -1825,7 +1651,7 @@ class stockStoreService extends Service {
}
// 验证三个管理标识字段
const managementFields = [ 'is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt' ];
const managementFields = ['is_sn_mgmt', 'is_shelf_life_mgmt', 'is_batch_mgmt'];
updateData = {
update_at: new Date(),
update_by: ctx.user.id || ctx.user.username,
@ -1835,7 +1661,7 @@ class stockStoreService extends Service {
if (value[field] === undefined) {
return { message: `管理标识缺少 ${field} 字段`, code: 405 };
}
if (![ 'Y', 'N' ].includes(value[field])) {
if (!['Y', 'N'].includes(value[field])) {
return { message: `管理标识 ${field} 的值必须是 Y 或 N`, code: 405 };
}
updateData[field] = value[field];
@ -1857,7 +1683,7 @@ class stockStoreService extends Service {
}
// 5. 执行批量更新
const [ affectedRows ] = await ctx.model.StockWarehouse.update(updateData, {
const [affectedRows] = await ctx.model.StockWarehouse.update(updateData, {
where: {
id: { [Op.in]: ids },
warehouse_id: warehouseId,
@ -1986,7 +1812,7 @@ class stockStoreService extends Service {
include: [{
model: ctx.model.StockWarehouse,
as: 'warehouse_stock',
attributes: [ 'id', 'store_id' ],
attributes: ['id', 'store_id'],
where: {
warehouse_id: warehouseId,
},
@ -2030,7 +1856,7 @@ class stockStoreService extends Service {
StockStoreWhere[Op.or] = likeConditions;
}
const offset = (page - 1) * pageSize;
[ total, barcodes ] = await Promise.all([
[total, barcodes] = await Promise.all([
ctx.model.StockStore.count({
where: StockStoreWhere,
attributes: [
@ -2039,7 +1865,7 @@ class stockStoreService extends Service {
include: [{
model: ctx.model.StockWarehouse,
as: 'warehouse_stock',
attributes: [ 'id' ],
attributes: ['id'],
where: StockWarehouseWhere,
required: false,
}],
@ -2055,7 +1881,7 @@ class stockStoreService extends Service {
include: [{
model: ctx.model.StockWarehouse,
as: 'warehouse_stock',
attributes: [ 'id' ],
attributes: ['id'],
where: StockWarehouseWhere,
required: false,
}],
@ -2306,7 +2132,7 @@ class stockStoreService extends Service {
});
// 6. 执行更新
const [ affectedRows ] = await ctx.model.StockWarehouse.update(updateData, {
const [affectedRows] = await ctx.model.StockWarehouse.update(updateData, {
where: {
id,
warehouse_id: ctx.user.store_id,
@ -2459,7 +2285,7 @@ class stockStoreService extends Service {
}
validateSaveParams(data, isEdit = true) {
const requiredFields = [ 'item_code', 'item_name', 'stock_unit', 'gross_weight' ];
const requiredFields = ['item_code', 'item_name', 'stock_unit', 'gross_weight'];
if (!data.id && isEdit) {
throw new Error('缺失必要参数: id');
}
@ -2474,7 +2300,7 @@ class stockStoreService extends Service {
}
// 数值类型验证
const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight' ];
const numericFields = ['length', 'width', 'height', 'volume', 'gross_weight', 'net_weight'];
for (const field of numericFields) {
if (data[field] && isNaN(Number(data[field]))) {
throw new Error(`${field} 必须是有效的数字`);
@ -2508,7 +2334,7 @@ class stockStoreService extends Service {
};
const space = await ctx.model.StockWarehouse.findOne({
where,
attributes: [ 'id' ],
attributes: ['id'],
});
// 如果没有找到重复的条码,返回唯一
@ -2546,11 +2372,11 @@ class stockStoreService extends Service {
{
model: ctx.model.Storage,
as: 'storage',
attributes: [ 'id', 'quantity' ],
attributes: ['id', 'quantity'],
required: false, // 使用left join,因为可能没有库存记录
},
],
attributes: [ 'id', 'item_name', 'quantity', 'return_quantity' ],
attributes: ['id', 'item_name', 'quantity', 'return_quantity'],
});
console.log('查询到的商品资料:', JSON.stringify(products, null, 2));
@ -2616,7 +2442,7 @@ class stockStoreService extends Service {
const result = await ctx.model.transaction(async t => {
// 软删除商品资料
const [ affectedCount ] = await ctx.model.StockWarehouse.update(
const [affectedCount] = await ctx.model.StockWarehouse.update(
{
deleted_at: new Date(),
updated_at: new Date(),
@ -2760,7 +2586,7 @@ class stockStoreService extends Service {
includeConditions.push({
model: app.model.StockBarcode,
as: 'barcodes',
attributes: [ 'barcode' ],
attributes: ['barcode'],
required: false, // 使用LEFT JOIN
where: {
barcode: { [Op.like]: searchKeyword },
@ -2780,14 +2606,14 @@ class stockStoreService extends Service {
includeConditions.push({
model: app.model.StockBarcode,
as: 'barcodes',
attributes: [ 'barcode' ],
attributes: ['barcode'],
required: false,
});
}
includeConditions.push(app.model.StoreWarehouse.buildStoreStockInclude({
warehouseId,
required: false,
attributes: [ 'store_id', 'store_remask' ],
attributes: ['store_id', 'store_remask'],
}));
// 执行查询
@ -2799,7 +2625,7 @@ class stockStoreService extends Service {
'sku_property', 'stock_unit', 'quantity',
'locked_quantity', 'brand_name', 'item_type',
],
order: [[ 'create_at', 'DESC' ]],
order: [['create_at', 'DESC']],
limit: 50,
include: includeConditions,
subQuery: false, // 避免子查询,提高性能

View File

@ -0,0 +1,687 @@
'use strict';
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
class EntryService extends Service {
/**
* 入库单列表查询,复用 where 解构工具。
* @param {Object} where 筛选条件对象
* @param {Object} pageParams 分页参数
* @param {Object} sortParams 排序参数
* @return {Promise<Object>} code/data/message 结构
*/
async list(where = {}, pageParams = {}, sortParams = {}) {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
const page = Math.max(Number(pageParams.page) || 1, 1);
const pageSize = Math.max(Number(pageParams.pageSize) || 20, 1);
const sortField = sortParams.sortField || 'created_at';
const sortOrder = String(sortParams.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
const validSortFields = [
'id',
'entry_order_code',
'order_type',
'order_status',
'order_create_time',
'created_at',
'updated_at',
'total_order_lines',
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
const baseWhere = {
warehouse_id: ctx.user.store_id,
is_enabled: 1,
deleted_at: null,
};
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
? { ...ctx.where }
: (where && typeof where === 'object' ? { ...where } : {});
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
if (!parsed.ok) {
return {
code: 400,
message: `筛选条件解析失败: ${parsed.reason}`,
data: {
list: [],
pagination: {
page,
pageSize,
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total: 0,
pending: 0,
creating: 0,
created: 0,
completed: 0,
cancelled: 0,
},
},
};
}
parsedResult = parsed.result;
}
const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere
|| null;
const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object'
? quickWhereInput.value
: null;
const andConditions = [ baseWhere ];
if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') {
const kw = String(quickWhereValue).trim();
andConditions.push({
[Op.or]: [
{ entry_order_code: { [Op.like]: `%${kw}%` } },
{ purchase_order_code: { [Op.like]: `%${kw}%` } },
{ supplier_name: { [Op.like]: `%${kw}%` } },
{ store_name: { [Op.like]: `%${kw}%` } },
{ warehouse_name: { [Op.like]: `%${kw}%` } },
],
});
}
const dynamicConditions = parsedResult.dynamicConditions || [];
if (dynamicConditions.length > 0) {
andConditions.push({ [Op.and]: dynamicConditions });
}
const finalWhere = { [Op.and]: andConditions };
const include = [
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ 'id', 'company_name' ],
required: false,
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'company_name' ],
required: false,
},
];
const { count, rows } = await ctx.model.EntryOrder.findAndCountAll({
where: finalWhere,
include,
order: [[ actualSortField, sortOrder ]],
limit: pageSize,
offset: (page - 1) * pageSize,
distinct: true,
});
const statusRows = await ctx.model.EntryOrder.findAll({
attributes: [
'order_status',
[ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ],
],
where: finalWhere,
group: [ 'order_status' ],
raw: true,
});
const summary = {
total: count,
pending: 0,
creating: 0,
created: 0,
completed: 0,
cancelled: 0,
};
statusRows.forEach(item => {
const statusKey = String(item.order_status || '').toLowerCase();
if (Object.prototype.hasOwnProperty.call(summary, statusKey)) {
summary[statusKey] = Number(item.count) || 0;
}
});
return {
code: 200,
message: '查询成功',
data: {
list: rows,
pagination: {
page,
pageSize,
total: count,
totalPages: Math.ceil(count / pageSize),
hasPrevious: page > 1,
hasNext: page < Math.ceil(count / pageSize),
},
summary,
},
};
}
/**
* 查询入库单详情。
* @param {Object} data 请求体
* @return {Promise<Object>} code/data/message 结构
*/
async get(data = {}) {
const { ctx } = this;
const id = Number(data.id || 0);
const entryOrderCode = data.entry_order_code ? String(data.entry_order_code).trim() : '';
if (!id && !entryOrderCode) {
return {
code: 400,
message: 'id 或 entry_order_code 至少传一个',
data: null,
};
}
const where = {
warehouse_id: ctx.user.store_id,
is_enabled: 1,
deleted_at: null,
};
if (id) {
where.id = id;
} else {
where.entry_order_code = entryOrderCode;
}
const entryOrder = await ctx.model.EntryOrder.findOne({
where,
include: [
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ 'id', 'company_name' ],
required: false,
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'company_name' ],
required: false,
},
{
model: ctx.model.EntryItems,
as: 'items',
include: [
{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'id', 'item_code', 'item_name' ],
required: false,
},
],
required: false,
},
],
});
if (!entryOrder) {
return {
code: 0,
message: '入库单不存在或无权访问',
data: null,
};
}
return {
code: 200,
message: '查询成功',
data: {
entryOrder,
},
};
}
generateOrderCode() {
const randomPart = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
return `ENT${Date.now()}${randomPart}`;
}
/**
* 创建入库单。
* @param {Object} data 请求体
* @return {Promise<Object>} code/data/message 结构
*/
async create(data = {}) {
const { ctx } = this;
const allowedOrderTypes = new Set([ 'SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK' ]);
const orderType = String(data.order_type || '').trim();
const storeId = Number(data.store_id || ctx.user.store_id || 0);
if (!orderType) {
return {
code: 400,
message: 'order_type 必填',
data: null,
};
}
if (!allowedOrderTypes.has(orderType)) {
return {
code: 400,
message: 'order_type 不合法',
data: null,
};
}
if (!storeId) {
return {
code: 400,
message: 'store_id 必填',
data: null,
};
}
const entryOrderCode = data.entry_order_code && String(data.entry_order_code).trim() !== ''
? String(data.entry_order_code).trim()
: this.generateOrderCode();
const exists = await ctx.model.EntryOrder.findOne({
where: {
entry_order_code: entryOrderCode,
warehouse_id: ctx.user.store_id,
store_id: storeId,
deleted_at: null,
},
});
if (exists) {
return {
code: 409,
message: '入库单号已存在',
data: {
id: exists.id,
entry_order_code: exists.entry_order_code,
},
};
}
const order = await ctx.model.EntryOrder.create({
entry_order_code: entryOrderCode,
order_type: orderType,
purchase_order_code: data.purchase_order_code || '',
total_order_lines: Number(data.total_order_lines || 0),
order_create_time: data.order_create_time ? new Date(data.order_create_time) : new Date(),
expect_start_time: data.expect_start_time ? new Date(data.expect_start_time) : null,
expect_end_time: data.expect_end_time ? new Date(data.expect_end_time) : null,
logistics_code: data.logistics_code || '',
logistics_name: data.logistics_name || '',
express_code: data.express_code || '',
supplier_code: data.supplier_code || '',
supplier_name: data.supplier_name || '',
source_type: 'API',
order_status: 'CREATED',
sync_status: 'PENDING',
sync_message: '',
is_enabled: 1,
warehouse_id: ctx.user.store_id,
store_id: storeId,
remark: data.remark || '',
created_at: new Date(),
updated_at: new Date(),
});
return {
code: 200,
message: '创建成功',
data: {
id: order.id,
entry_order_code: order.entry_order_code,
},
};
}
async getOwnedEntryOrderById(id) {
const { ctx } = this;
return await ctx.model.EntryOrder.findOne({
where: {
id,
warehouse_id: ctx.user.store_id,
is_enabled: 1,
deleted_at: null,
},
});
}
/**
* 新增入库明细。
* @param {Object} data 请求体
* @return {Promise<Object>} code/data/message 结构
*/
async addDetail(data = {}) {
const { ctx } = this;
const orderId = Number(data.order_id || 0);
const count = Number(data.count || 0);
if (!orderId) {
return {
code: 400,
message: 'order_id 必填',
data: null,
};
}
if (!count || count <= 0) {
return {
code: 400,
message: 'count 必须大于 0',
data: null,
};
}
const entryOrder = await this.getOwnedEntryOrderById(orderId);
if (!entryOrder) {
return {
code: 404,
message: '入库单不存在或无权访问',
data: null,
};
}
if (entryOrder.order_status === 'CANCELLED' || entryOrder.order_status === 'COMPLETED') {
return {
code: 400,
message: '当前状态不允许新增明细',
data: null,
};
}
const maxLineNo = Number(await ctx.model.EntryItems.max('order_line_no', {
where: { order_id: orderId },
})) || 0;
const detail = await ctx.model.EntryItems.create({
order_id: orderId,
order_line_no: maxLineNo + 1,
item_code: data.item_code || '',
item_id: data.item_id || null,
stock_id: data.stock_id || data.item_id || null,
count,
inventory_type: data.inventory_type || 'ZP',
received_quantity: 0,
confirm_quantity: 0,
owner_code: data.owner_code || '',
out_biz_code: data.out_biz_code || '',
});
await entryOrder.update({
total_order_lines: maxLineNo + 1,
updated_at: new Date(),
});
return {
code: 200,
message: '新增明细成功',
data: {
id: detail.id,
order_id: orderId,
},
};
}
/**
* 删除入库明细。
* @param {Object} data 请求体
* @return {Promise<Object>} code/data/message 结构
*/
async deleteDetail(data = {}) {
const { ctx } = this;
const detailId = Number(data.id || 0);
if (!detailId) {
return {
code: 400,
message: 'id 必填',
data: null,
};
}
const detail = await ctx.model.EntryItems.findByPk(detailId);
if (!detail) {
return {
code: 404,
message: '明细不存在',
data: null,
};
}
const entryOrder = await this.getOwnedEntryOrderById(detail.order_id);
if (!entryOrder) {
return {
code: 404,
message: '入库单不存在或无权访问',
data: null,
};
}
if (Number(detail.received_quantity || 0) > 0) {
return {
code: 400,
message: '已有收货数量的明细不允许删除',
data: null,
};
}
await detail.destroy();
const lineCount = await ctx.model.EntryItems.count({ where: { order_id: entryOrder.id } });
await entryOrder.update({
total_order_lines: lineCount,
updated_at: new Date(),
});
return {
code: 200,
message: '删除明细成功',
data: {
id: detailId,
},
};
}
/**
* 修改入库明细。
* @param {Object} data 请求体
* @return {Promise<Object>} code/data/message 结构
*/
async detailChange(data = {}) {
const { ctx } = this;
const detailId = Number(data.id || 0);
if (!detailId) {
return {
code: 400,
message: 'id 必填',
data: null,
};
}
const detail = await ctx.model.EntryItems.findByPk(detailId);
if (!detail) {
return {
code: 404,
message: '明细不存在',
data: null,
};
}
const entryOrder = await this.getOwnedEntryOrderById(detail.order_id);
if (!entryOrder) {
return {
code: 404,
message: '入库单不存在或无权访问',
data: null,
};
}
const updateData = {};
const mutableFields = [ 'item_code', 'item_id', 'inventory_type', 'stock_id', 'out_biz_code', 'owner_code' ];
for (const field of mutableFields) {
if (Object.prototype.hasOwnProperty.call(data, field)) {
updateData[field] = data[field];
}
}
if (Object.prototype.hasOwnProperty.call(data, 'count')) {
const count = Number(data.count);
if (!count || count <= 0) {
return {
code: 400,
message: 'count 必须大于 0',
data: null,
};
}
if (Number(detail.received_quantity || 0) > count) {
return {
code: 400,
message: 'count 不能小于已收货数量',
data: null,
};
}
updateData.count = count;
}
if (Object.keys(updateData).length === 0) {
return {
code: 400,
message: '没有可更新字段',
data: null,
};
}
await detail.update(updateData);
return {
code: 200,
message: '修改明细成功',
data: {
id: detail.id,
},
};
}
/**
* 作废入库单。
* @param {Object} data 请求体
* @return {Promise<Object>} code/data/message 结构
*/
async cancel(data = {}) {
const orderId = Number(data.id || 0);
if (!orderId) {
return {
code: 400,
message: 'id 必填',
data: null,
};
}
const entryOrder = await this.getOwnedEntryOrderById(orderId);
if (!entryOrder) {
return {
code: 404,
message: '入库单不存在或无权访问',
data: null,
};
}
if (entryOrder.order_status === 'COMPLETED') {
return {
code: 400,
message: '已完成入库单不允许作废',
data: null,
};
}
await entryOrder.update({
order_status: 'CANCELLED',
updated_at: new Date(),
});
return {
code: 200,
message: '作废成功',
data: {
id: entryOrder.id,
},
};
}
/**
* 完成入库单。
* @param {Object} data 请求体
* @return {Promise<Object>} code/data/message 结构
*/
async completeEntry(data = {}) {
const { ctx } = this;
const orderId = Number(data.id || 0);
if (!orderId) {
return {
code: 400,
message: 'id 必填',
data: null,
};
}
const entryOrder = await this.getOwnedEntryOrderById(orderId);
if (!entryOrder) {
return {
code: 404,
message: '入库单不存在或无权访问',
data: null,
};
}
if (entryOrder.order_status === 'CANCELLED') {
return {
code: 400,
message: '已作废入库单不允许完成',
data: null,
};
}
const detailCount = await ctx.model.EntryItems.count({ where: { order_id: orderId } });
if (detailCount <= 0) {
return {
code: 400,
message: '请先添加入库明细',
data: null,
};
}
await entryOrder.update({
order_status: 'COMPLETED',
updated_at: new Date(),
});
return {
code: 200,
message: '完成成功',
data: {
id: entryOrder.id,
},
};
}
}
module.exports = EntryService;

View File

@ -1,7 +1,17 @@
'use strict';
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
class ReceivingService extends Service {
/**
* 查询收货单列表。
* @param {Object} where 动态筛选条件
* @param {Object} [pageParams] 分页参数
* @param {number} [pageParams.page=1] 页码
* @param {number} [pageParams.pageSize=20] 每页条数
* @param {Object} [sortParams] 排序参数
* @return {Promise<Object>} 列表、分页与汇总信息
*/
async getReceivingList(where, pageParams = {}, sortParams = {}) {
const {
ctx,
@ -14,159 +24,153 @@ class ReceivingService extends Service {
const {
Op,
} = Sequelize;
console.log(pageParams);
const {
page = 1,
pageSize = 20,
} = pageParams;
try {
// 设置默认参数
const {
sortField = 'id',
sortOrder = 'DESC',
} = sortParams;
// 构建基础查询条件
const queryOptions = {
where: {},
where: {
[Op.and]: [
{
warehouse_id: ctx.user.store_id,
},
],
},
order: [],
attributes: {
exclude: ['deleted_at'],
exclude: [ 'deleted_at' ],
},
};
const prohibitedQueryOptions = {
where: {},
};
// 添加默认条件
queryOptions.where[Op.and] = [{
warehouse_id: ctx.user.store_id,
},
];
prohibitedQueryOptions.where[Op.and] = [];
// 检测并处理条码查询条件
const hasBarcodeCondition = false;
const barcodeCondition = null;
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
? ctx.where
: (where && typeof where === 'object' ? where : {});
// 处理动态查询条件
if (where && Object.keys(where).length > 0) {
const dynamicConditions = [];
const prohibitedConditions = [];
const barcodedynamicConditions = [];
let parsedResult = ctx.whereParsed;
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
const parsed = parseWhereConditions({
where: normalizedWhere,
app,
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
for (const fieldKey in where) {
const condition = where[fieldKey];
if (this.isEmptyValue(condition.value)) {
continue;
}
// 检查是否是快捷查询,快捷查询字段
if (fieldKey === 'quickWhere') {
dynamicConditions.push({
[Op.or]: {
store_name: {
[Sequelize.Op.like]: `%${condition.value}%`,
},
receiving_number: {
[Sequelize.Op.like]: `%${condition.value}%`,
},
tracking_number: {
[Sequelize.Op.like]: `%${condition.value}%`,
},
creator_snapshot: {
[Sequelize.Op.like]: `%${condition.value}%`,
},
license_plate: {
[Sequelize.Op.like]: `%${condition.value}%`,
},
}
});
continue; // 暂不添加到动态条件中
}
// 其他字段的处理
const sequelizeCondition = this.buildSequelizeCondition(fieldKey, condition, app);
console.log('sequelizeCondition', fieldKey, condition, sequelizeCondition);
if (sequelizeCondition) {
dynamicConditions.push(sequelizeCondition);
}
}
if (dynamicConditions.length > 0) {
queryOptions.where[Op.and].push({
[Op.and]: dynamicConditions,
});
if (!parsed.ok) {
return {
code: 400,
data: {
list: [],
pagination: {
page: parseInt(page),
pageSize: parseInt(pageSize),
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total_quantity: 0,
total_locked: 0,
total_available: 0,
total_items: 0,
},
},
message: `筛选条件解析失败: ${parsed.reason}`,
};
}
parsedResult = parsed.result;
}
// 处理排序
const validSortFields = [
'id', 'item_code', 'quantity', 'locked_quantity',
'tag_price', 'retail_price', 'create_at', 'update_at',
];
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| normalizedWhere.quickWhere;
if (quickWhereRaw && !this.isEmptyValue(quickWhereRaw.value)) {
const quickValue = String(quickWhereRaw.value).trim();
dynamicConditions.push({
[Op.or]: {
store_name: {
[Sequelize.Op.like]: `%${quickValue}%`,
},
receiving_number: {
[Sequelize.Op.like]: `%${quickValue}%`,
},
tracking_number: {
[Sequelize.Op.like]: `%${quickValue}%`,
},
creator_snapshot: {
[Sequelize.Op.like]: `%${quickValue}%`,
},
license_plate: {
[Sequelize.Op.like]: `%${quickValue}%`,
},
},
});
}
if (dynamicConditions.length > 0) {
queryOptions.where[Op.and].push({
[Op.and]: dynamicConditions,
});
}
const validSortFields = [
'id', 'receiving_number', 'status', 'create_at', 'update_at', 'store_id',
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at';
const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
queryOptions.order.push([actualSortField, actualSortOrder]);
queryOptions.order.push([ actualSortField, actualSortOrder ]);
// 计算分页偏移量
const offset = (page - 1) * pageSize;
const include = [
{
model: ctx.model.StoreWarehouse,
as: 'store',
attributes: [ 'store_remask' ],
where: {
use_status: 1,
warehouse_id: ctx.user.store_id,
},
required: false,
},
{
model: ctx.model.AccountStoreEmployee,
as: 'creator',
attributes: [ 'real_name' ],
required: true,
},
];
// 执行查询:获取总数和数据
const [total, data] = await Promise.all([
// 获取总数
const [ total, data ] = await Promise.all([
ctx.model.Receiving.count({
where: queryOptions.where,
include: [{
model: ctx.model.StoreWarehouse,
as: 'store',
attributes: ['store_remask'],
where: {
use_status: 1,
warehouse_id: ctx.user.store_id,
},
required: false,
}, {
model: ctx.model.AccountStoreEmployee,
as: 'creator',
attributes: ['real_name'],
required: true,
}],
include,
distinct: true,
}),
// 获取分页数据
ctx.model.Receiving.findAll({
...queryOptions,
include: [{
model: ctx.model.StoreWarehouse,
as: 'store',
attributes: ['store_remask'],
where: {
use_status: 1,
warehouse_id: ctx.user.store_id,
},
required: false,
}, {
model: ctx.model.AccountStoreEmployee,
as: 'creator',
attributes: ['real_name'],
required: true,
}],
include,
limit: parseInt(pageSize),
offset: parseInt(offset),
distinct: true, // 确保去重
distinct: true,
raw: true,
}),
]);
// 计算分页信息
const totalPages = Math.ceil(total / pageSize);
const hasPrevious = page > 1;
const hasNext = page < totalPages;
// 批量查询条码信息
const stockIds = data.map(item => item.id);
let images = [];
if (stockIds.length > 0) {
@ -177,30 +181,23 @@ class ReceivingService extends Service {
[Op.in]: stockIds,
},
},
include: [{
model: ctx.model.File,
as: 'file',
attributes: ['file_url'],
required: true,
}],
include: [
{
model: ctx.model.File,
as: 'file',
attributes: [ 'file_url' ],
required: true,
},
],
});
}
// 处理数据,添加一些计算字段
const processedData = data.map(item => {
const availableQuantity = Math.max(0, item.quantity - item.locked_quantity);
const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed(
2) : 0;
const {
cos,
} = config;
const {
cdnurl,
} = cos;
const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed(2) : 0;
const itemImages = images
.filter(images => parseInt(images.business_id) === item.id)
.map(images => images.file.file_url);
.filter(row => parseInt(row.business_id) === item.id)
.map(row => row.file.file_url);
return {
...item,
images: itemImages,
@ -209,26 +206,16 @@ class ReceivingService extends Service {
lock_rate_display: `${lockRate}%`,
create_at_display: item.create_at ? this.formatDate(item.create_at) : '',
update_at_display: item.update_at ? this.formatDate(item.update_at) : '',
// 标记是否通过条码查询匹配
is_barcode_matched: hasBarcodeCondition && matchedStockIds.includes(item.id),
};
});
// 添加汇总信息
const summary = {
total_quantity: data.reduce((sum, item) => sum + item.quantity, 0),
total_locked: data.reduce((sum, item) => sum + item.locked_quantity, 0),
total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item
.locked_quantity), 0),
total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item.locked_quantity), 0),
total_items: data.length,
// 如果有条码查询,添加匹配统计
...(hasBarcodeCondition && {
barcode_matched_count: matchedStockIds.length,
barcode_search_value: where.barcode.value,
}),
};
return {
code: 200,
data: {
@ -243,15 +230,14 @@ class ReceivingService extends Service {
},
summary,
queryInfo: {
conditions: where,
conditions: normalizedWhere,
sortField: actualSortField,
sortOrder: actualSortOrder,
hasBarcodeSearch: hasBarcodeCondition,
hasBarcodeSearch: false,
},
},
message: '查询成功',
};
} catch (error) {
ctx.logger.error('[StockService.getWarehouseStock] 查询失败:', error);
return {
@ -277,8 +263,12 @@ class ReceivingService extends Service {
};
}
}
/*
* 获取收货单详情
/**
* 获取收货单详情(主单 + 明细分页 + 图片)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {Object} data.pagination 分页参数
* @return {Promise<Object>} 详情数据
*/
async getReceivingDetail(data) {
const { id, pagination } = data;
@ -358,7 +348,12 @@ class ReceivingService extends Service {
return { code: 500, message: '服务器错误', data: {} };
}
}
//批量作废
/**
* 批量作废收货单。
* @param {Object} data 请求体
* @param {number[]} data.ids 收货单ID数组
* @return {Promise<Object>} 作废处理结果
*/
async batchCancelReceiving(data) {
const { ids } = data;
const { ctx } = this;
@ -638,6 +633,12 @@ class ReceivingService extends Service {
return value;
}
}
/**
* 创建收货单并生成收货单号。
* @param {Object} data 创建参数
* @return {Promise<Object>} 新建结果(含 id 与 receiving_number)
*/
async create(data) {
const {
delivery_method,
@ -753,6 +754,13 @@ class ReceivingService extends Service {
};
}
}
/**
* 查询单个收货单完整信息(含明细、图片)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @return {Promise<Object>} 单据详情
*/
async get(data) {
const { id } = data;
const { ctx, app } = this;
@ -881,6 +889,13 @@ class ReceivingService extends Service {
return { code: 500, message: '服务器错误', data: {} };
}
}
/**
* 向收货单新增一条默认明细。
* @param {Object} data 请求体
* @param {number} data.receiving_id 收货单ID
* @return {Promise<Object>} 明细列表与默认选中ID
*/
async addDetail(data) {
const ctx = this.ctx;
const { receiving_id } = data;
@ -1303,6 +1318,12 @@ class ReceivingService extends Service {
}
}
/**
* 删除收货单明细并回算统计。
* @param {Object} data 请求体
* @param {number} data.detail_id 明细ID
* @return {Promise<Object>} 删除结果
*/
async deleteDetail(data) {
const ctx = this.ctx;
const { detail_id } = data;
@ -1408,6 +1429,11 @@ class ReceivingService extends Service {
};
}
}
/**
* 修改收货明细信息并触发库存/统计联动。
* @param {Object} data 请求体
* @return {Promise<Object>} 修改结果
*/
async detailChange(data) {
const { ctx, app } = this;
const warehouseId = ctx.user.store_id;
@ -1752,6 +1778,13 @@ class ReceivingService extends Service {
throw error;
}
}
/**
* 完成收货单:校验明细、更新状态并写入库存。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {string} [data.remark] 完成备注
* @return {Promise<Object>} 完成结果
*/
async completeReceiving(data) {
const { ctx, app } = this;
const warehouseId = ctx.user.store_id;

BIN
day.log

Binary file not shown.

View File

@ -0,0 +1,167 @@
# stock.warehouse.list 前端查询规则
## 目的
本文档约束 `stock.warehouse.list` 的 `where` 构造格式,便于前端统一构建查询条件,并与后端解析器保持一致。
## 接口入口
- 路由:`POST /system`
- method:`stock.warehouse.list`
## 请求体结构
```json
{
"pagination": {
"page": 1,
"pageSize": 20
},
"where": {
"item_code": {
"operator": "like",
"value": "SKU",
"type": "text"
}
}
}
```
## where 字段规则
`where` 必须是对象,且每个字段值也必须是对象。
正确示例:
```json
{
"where": {
"item_name": {
"operator": "like",
"value": "鞋",
"type": "text"
}
}
}
```
错误示例(会返回解析失败原因):
```json
{
"where": {
"item_name": "鞋"
}
}
```
## 条件对象结构
每个 `where.<field>` 支持:
- `operator`:操作符,默认 `eq`
- `value`:查询值
- `type`:值类型(可选)
- `field`:映射到真实字段(一般不需要前端传)
### 支持操作符
- `eq`
- `ne`
- `like` / `contains`
- `startswith`
- `endswith`
- `gt`
- `lt`
- `ge`
- `le`
- `in`
- `notin`
- `between`
- `notbetween`
- `isnull`
- `isnotnull`
- `regexp`
- `notregexp`
### 支持 type
- `boolean`:转换为 `Y/N`
- `number`:转换为数字
- `date`:日期字符串归一化
- `daterange`:日期数组归一化
- `text`:逗号分隔字符串拆分数组
## 特殊字段说明
### barcode
- 在条码表中先匹配,再回灌 `stock_id` 过滤主表。
- 推荐:`operator=eq|like`。
### prohibited_type
- 传入的是违禁品类型 `id`。
- 后端会映射到关联模型进行过滤。
## 空值处理
以下值会被视为“空条件”并跳过:
- `null`
- `undefined`
- `""`
- `[]`
## 排序规则
后端只接受以下排序字段:
- `id`
- `item_code`
- `item_name`
- `quantity`
- `locked_quantity`
- `tag_price`
- `retail_price`
- `create_at`
- `update_at`
当传入非法排序字段时,会回退为:
- `sortField=create_at`
- `sortOrder=DESC`
## 失败返回(解构失败)
当 `where` 结构不合法时,返回示例:
```json
{
"code": 400,
"message": "筛选条件解析失败: 字段 item_code 条件必须是对象",
"data": {
"list": [],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 0,
"totalPages": 0,
"hasPrevious": false,
"hasNext": false
},
"summary": {
"total_quantity": 0,
"total_locked": 0,
"total_available": 0,
"total_items": 0
}
}
}
```
## 前端建议
- 对 `in/notin/between/notbetween` 先做数组校验,再发请求。
- 对 `where` 做 schema 校验,避免后端 400。
- 对空输入不构造条件,减少无效查询。

View File

@ -46,6 +46,50 @@
}
],
"errors": []
},
{
"method": "user.bindAccountByTempCode",
"description": "根据绑定码将 ye4s 用户绑定到 WMS 账号(供 ye4s 扫码后回调)",
"isNeedAuth": false,
"isNeedLogin": false,
"headers": [],
"params": [
{
"name": "code",
"type": "string",
"required": true,
"source": "body",
"description": "绑定码(由 user.getBindWechatCode 生成)"
},
{
"name": "ye4s_user_id",
"type": "number",
"required": true,
"source": "body",
"description": "ye4s 用户ID(例如扫码用户ID)"
}
],
"response": [
{
"name": "account_id",
"type": "number",
"required": true,
"description": "绑定目标 WMS 账号ID"
},
{
"name": "ye4s_user_id",
"type": "number",
"required": true,
"description": "被绑定的 ye4s 用户ID"
},
{
"name": "status",
"type": "string",
"required": true,
"description": "绑定状态,固定为 bound"
}
],
"errors": []
}
]
}

File diff suppressed because it is too large Load Diff

View File

@ -1,135 +1,23 @@
Model 重构总计划(数据库 + Migrations + Models)
更新时间: 2026-03-23
当前状态: 执行中(阶段 1-5 已完成,阶段 6 进行中)
负责人:
目标截止时间:
执行分支:
Model 重构总计划(已完成归档)
更新时间: 2026-03-25
当前状态: 已完成
[事务归属]
- 本子事务已纳入 `todo.txt` 总事务看板统一管理。
- 主里程碑对齐总事务 DDL(2026-04-15),以总事务验收为最终关闭条件。
[最终目标]
- 梳理数据库中所有表结构并形成统一基线。
- 补全并对齐 database/migrations 目录下的迁移文件。
- 规范所有 model 的命名与内部关联。
- 清理所有 model 内部能力(移除死代码、职责收敛、保持模型层可预测)。
[完成状态]
- [x] 阶段 1: 全量盘点与基线建立
- [x] 阶段 2: Migration 补全与执行顺序设计
- [x] 阶段 3: Model 命名规范化
- [x] 阶段 4: 关联关系规范化
- [x] 阶段 5: Model 内部能力清理
- [x] 阶段 6: 验证与交接
[执行规则]
- [x] 本文件用于规划拆解,已完成初始化。
- [x] 已收到新任务,开始执行阶段 1。
- [x] 进入代码改动前,先核对目标 service 的真实调用链。
- [x] 若 service 已被 system/qimen 入口使用,则必须同步更新对应 API 文档。
- [x] 所有联动修改需记录到 temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md,便于后续复盘。
- [x] 任何模型/关联改动前,使用测试账号执行 method 基线回放(配置与样本来源必须可追溯)。
- [x] 任何模型/关联改动后,执行同一批 method 对比回放并输出比对报告。
- [x] 新增交付条件:修改前后 method 输出结果一致(允许仅屏蔽 token/timestamp 等波动字段)。
- [x] 后续所有接口返回数据检测,统一使用“自动生成的 Egg.js 标注测试脚本”执行校验。
[收口说明]
- [x] 本文件由执行计划切换为归档摘要,不再保留阶段性过程清单。
- [x] 本任务相关临时文档已从 `temp/docs/` 清理。
- [x] 本任务相关临时中间文件已从 `temp/` 清理。
- [x] README 中对已清理临时文档的入口已移除。
[阶段 1: 全量盘点与基线建立]
- [x] 1.1 盘点所有数据表(字段、主键、索引、约束、注释)。
- [x] 1.2 盘点所有 model 文件(app/model 下文件、导出名、表映射)。
- [x] 1.3 盘点 model 关联(belongsTo/hasMany/hasOne/belongsToMany 与外键使用)。
- [x] 1.4 产出 DB 结构与 model 定义差异报告。
- [x] 1.5 在根目录生成 temp/docs/modelList.md,构建 model 层级结构与说明。
- [x] 1.6 在 README.md 增加对 temp/docs/modelList.md 的引用说明。
交付物:
- temp/docs/table_schema_inventory.md
- temp/docs/model_inventory.md
- temp/docs/model_association_inventory.md
- temp/docs/schema_model_gap_report.md
- temp/docs/modelList.md
退出标准:
- 100% 数据表与 100% model 文件覆盖完成。
- temp/docs/modelList.md 可用于快速定位模型层级与职责。
[阶段 2: Migration 补全与执行顺序设计]
- [x] 2.1 审核现有 database/migrations 的命名、顺序、幂等性。
- [x] 2.2 根据阶段 1 差异清单补齐缺失迁移任务。
- [x] 2.3 设计迁移执行顺序(先结构后索引/约束,必要时分批回填数据)。
- [x] 2.4 为每个迁移定义可执行回滚步骤。
- [x] 2.5 形成 local/test 环境演练方案。
交付物:
- temp/docs/migration_gap_list.md
- temp/docs/migration_execution_plan.md
- temp/docs/rollback_plan.md
退出标准:
- 每个结构差异都有明确迁移归属与回滚路径。
[阶段 3: Model 命名规范化]
- [x] 3.1 定义命名规范(文件名、类名、model key、表映射、alias)。
- [x] 3.2 产出非规范命名的重命名映射表。
- [x] 3.3 评估跨层影响(service/controller/query 调用点)。
- [x] 3.4 制定兼容策略(临时别名或分批重命名)。
交付物:
- temp/docs/model_naming_standard.md
- temp/docs/model_rename_map.md
- temp/docs/rename_impact_report.md
退出标准:
- 所有命名不规范项有明确修复路径与影响说明。
[阶段 4: 关联关系规范化]
- [x] 4.1 逐项校验关联定义与真实外键关系一致性(详见 temp/docs/association_fk_consistency_report.md)。
- [x] 4.2 统一 alias 命名与双向关联完整性。
- [x] 4.3 清理重复或冲突关联。
- [x] 4.4 形成 eager-loading 与 N+1 风险规约(详见 temp/docs/association_eager_loading_n_plus_one_guideline.md)。
交付物:
- temp/docs/association_fix_plan.md
- temp/docs/association_validation_checklist.md
退出标准:
- 关联关系可预测、无冲突、与数据库关系一致。
[阶段 5: Model 内部能力清理]
- [x] 5.1 识别应迁移到 service 层的方法能力(见 temp/docs/model_cleanup_list.md 第一批清单)。
- [x] 5.2 清理 model 内死代码与调试代码(已完成:P2 两批无调用静态方法清理 + P1 四组方法迁移并回收 model 同名方法)。
- [x] 5.3 规范 hooks/scopes/virtual fields 的使用边界(盘点完成并已产出 temp/docs/model_boundary_rules.md)。
- [x] 5.4 固化模型层边界规则(新增 script/model-boundary-check.cjs 并接入 npm run check:model-boundary)。
交付物:
- temp/docs/model_cleanup_list.md
- temp/docs/model_boundary_rules.md
退出标准:
- 模型层聚焦于数据映射与轻量领域行为,职责边界清晰。
[阶段 6: 验证与交接]
- [ ] 6.1 在干净库上回放 migration 全流程。
- [ ] 6.2 验证 model CRUD 与关联查询正确性。
- [ ] 6.3 执行关键 API 冒烟回归(包含 method-output 基线/对比)。
- [ ] 6.4 更新最终文档(README + methods + 内部交接文档)。
交付物:
- verification_report.md
- handover_notes.md
退出标准:
- 无迁移漂移、无关联错配、无阻断回归问题。
[风险]
- 历史遗留表或隐式依赖未被识别。
- 环境间数据漂移导致验证结果不一致。
- 命名调整引发跨层调用副作用。
[依赖]
- 稳定可访问的数据库环境(盘点与验证)。
- 统一确认的命名与关联规范。
- 可执行的迁移窗口与回滚窗口。
[下一步]
- 阶段 4 的 4.1-4.4 已完成(含 receiving 第一批收敛与 N+1/eager-loading 规约落地)。
- 高优先差异项推进: 已完成 store_warehouse/stock_warehouse 第二批收敛(stock_store include 语义约束补齐),并通过门禁。
- 高优先差异项推进: 已完成 role / role_permission / permission 第三批收敛(启用状态过滤 + 去重),并通过门禁。
- 已完成“DB 约束补齐”执行: `wms_role_permission.permission_id -> wms_permission.id` 外键已生效,SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`。
- 已完成数据清洗与备份: 4 条 permission 孤儿、3 条 role.store_id=0 哨兵数据均已处理(备份表见 `temp/docs/role_permission_fk_data_cleanup_plan.md`)。
- 已完成 `wms_role.store_id` 外键策略落地:外键 `fk_wms_role_store` 已生效(ON DELETE SET NULL),SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js`。
- 已完成 store_warehouse / stock_warehouse 模型层复合键语义治理(统一 include 构造器 + constraints:false 显式化)。
- 已完成阶段 4 收尾检查(第 1 项):全量 include alias 一致性扫描(service alias 与 model alias 差集=0)。
- 已完成阶段 4 收尾检查(第 2 项):permission.parent_id 自关联约束策略已落地(root=NULL + FK)。
- 已完成阶段 5.1:识别应迁移到 service 层的方法能力(第一批清单见 temp/docs/model_cleanup_list.md)。
- 已完成阶段 5.2 第一批 P2 清理:ApiApp / InterfaceType / PrintItem,门禁通过。
- 已完成阶段 5.2 第二批 P2 清理:I18nTranslation / StockStore,门禁通过。
- 已完成阶段 5.2 P1 第一组:EntryOrder / EntryItems 8 个方法迁移到 service 并回收 model 同名方法。
- 已完成阶段 5.2 P1 第二组:Storage 10 个方法迁移到 service 并回收 model 同名方法。
- 已完成阶段 5.2 P1 第三组:Role / RolePermission 7 个方法迁移到 service 并回收 model 同名方法。
- 已完成阶段 5.2 P1 第四组:Store 5 个方法迁移到 service 并回收 model 同名方法。
- 已完成阶段 5.3:hooks/scopes/virtual fields 边界盘点与规则固化(见 temp/docs/model_boundary_rules.md)。
- 已完成阶段 5.4:新增 model 边界检查脚本并接入 npm 命令与 CI(check:model-boundary)。
- 已复跑阶段 5.4 门禁命令:`npm run check:model-boundary`,结果 PASS(files=45, hooks=2, scopeFiles=1, virtualLines=0)。
- 过程门禁:compare mismatch=0;generated regression 与 smoke 持续通过;新增 model-boundary 检查门禁。
- 下一步进入阶段 6.1:在干净库上回放 migration 全流程。
[追溯方式]
- 需要查看过程细节时,优先使用 git 历史、`todo.txt` 总事务看板与 `versioning/` 本地版本记录。

View File

@ -111,7 +111,7 @@ function scanFile(filePath) {
relPath,
line: i + 1,
type: 'disallowed-hook',
message: '发现未登记的模型 hook,请先更新 temp/docs/model_boundary_rules.md 与 allowlist',
message: '发现未登记的模型 hook,请先更新模型边界规则与 allowlist',
content: line.trim(),
});
}
@ -124,7 +124,7 @@ function scanFile(filePath) {
relPath,
line: i + 1,
type: 'disallowed-scopes',
message: '发现未登记的 scopes 定义,请先更新 temp/docs/model_boundary_rules.md 与 allowlist',
message: '发现未登记的 scopes 定义,请先更新模型边界规则与 allowlist',
content: line.trim(),
});
}
@ -137,7 +137,7 @@ function scanFile(filePath) {
relPath,
line: i + 1,
type: 'disallowed-virtual-field',
message: '发现未登记的 virtual 字段定义,请先更新 temp/docs/model_boundary_rules.md 与 allowlist',
message: '发现未登记的 virtual 字段定义,请先更新模型边界规则与 allowlist',
content: line.trim(),
});
}

112
stock.todo Normal file
View File

@ -0,0 +1,112 @@
# stock.todo
## 任务目标
- 提取 `app/service/systemMethods/stock/warehouse.js` 迁移前 method 的历史测试请求记录。
- 精简并保留新接口(`stock.warehouse.*`)的测试入口。
- 根据输入/输出补全 `warehouse.js` 方法头注释和 API 文档 `description`。
## 迁移方法映射(旧 -> 新)
- `stock.stockWarehouse` -> `stock.warehouse.list`
- `stock.getProhibitedType` -> `stock.warehouse.getProhibitedType`
- `stock.getInfo` -> `stock.warehouse.getInfo`
- `stock.saveWarehouseStock` -> `stock.warehouse.saveWarehouseStock`
- `stock.createWarehouseStock` -> `stock.warehouse.createWarehouseStock`
- `stock.getBarcodes` -> `stock.warehouse.getBarcodes`
- `stock.saveWarehouseStockBarcode` -> `stock.warehouse.saveWarehouseStockBarcode`
- `stock.getStoreStocks` -> `stock.warehouse.getStoreStocks`
- `stock.bindItem` -> `stock.warehouse.bindItem`
- `stock.unbindItem` -> `stock.warehouse.unbindItem`
- `stock.checkItemCodeUnique` -> `stock.warehouse.checkItemCodeUnique`
- `stock.queryStockLogs` -> `stock.warehouse.queryStockLogs`
- `stock.handleBatchDelete` -> `stock.warehouse.handleBatchDelete`
- `stock.deleteUnit` -> `stock.warehouse.deleteUnit`
- `stock.deleteProhibited` -> `stock.warehouse.deleteProhibited`
- `stock.handleBatchChange` -> `stock.warehouse.handleBatchChange`
- `stock.getStockUnits` -> `stock.warehouse.getStockUnits`
- `stock.getUnitList` -> `stock.warehouse.getUnitList`
- `stock.createProhibited` -> `stock.warehouse.createProhibited`
- `stock.createUnit` -> `stock.warehouse.createUnit`
- `stock.search` -> `stock.warehouse.search`
## 历史测试请求记录提取(迁移前/过渡期)
来源:`node_modules/.mochawesome-reports/mochawesome.json`(2026-03-25)
### 记录1:新列表接口请求
- case: `system.stock.warehouse.namespaced.test.js`
- method: `stock.warehouse.list`
- request:
```json
{
"pagination": { "page": 1, "pageSize": 5 },
"where": {}
}
```
- expected:
```json
{
"httpStatus": 200,
"flag": "success",
"code": 200,
"data": {
"list": "Array",
"pagination": "Object"
}
}
```
### 记录2:旧入口退场验证请求(历史)
- case: `system.stock.warehouse.namespaced.test.js`(精简前)
- method: `stock.stockWarehouse`
- request:
```json
{
"pagination": { "page": 1, "pageSize": 5 },
"where": {}
}
```
- expected:
```json
{
"httpStatus": 500,
"flag": "failure",
"code": 500,
"message": "方法 stockWarehouse 不存在"
}
```
### 记录3:where 条件解析服务级样本
来源:`test/app/service/systems/stock_store.stockWarehouse.conditions.test.js`
- input:
```json
{
"where": {
"item_code": { "operator": "like", "value": "SKU" },
"barcode": { "operator": "like", "value": "BC" },
"prohibited_type": { "operator": "eq", "value": 2 },
"quantity": { "operator": "ge", "type": "number", "value": "2" }
},
"pagination": { "page": 1, "pageSize": 10 },
"sort": { "sortField": "quantity", "sortOrder": "ASC" }
}
```
- expected:
```json
{
"code": 200,
"message": "查询成功",
"data.pagination.page": 1,
"data.pagination.pageSize": 10,
"data.queryInfo.hasBarcodeSearch": true
}
```
## 新接口精简测试方案
- 保留:`test/app/controller/system.stock.warehouse.namespaced.test.js`
- 用例:只验证 `stock.warehouse.list` 请求成功与核心返回结构。
- 下沉:复杂 where/operator 组合继续由 service 级测试覆盖。
## 执行结果
- [x] `warehouse.js` 方法头注释补充(输入/输出声明)
- [x] 新接口测试用例精简
- [x] `methods/system.json` 的 `stock.warehouse.*` description 语义化更新(21项)
- [x] 回归测试复跑并记录结果(`8 passing`)

View File

@ -1,94 +0,0 @@
# Method 输出一致性回放说明
更新时间: 2026-03-22
## 1. 新交付条件
- 所有模型/关联相关改动,必须先执行 method 输出基线回放。
- 改动完成后,必须对同一批 method 执行 compare 回放。
- 交付标准: 修改前后 method 输出一致。
- 允许屏蔽波动字段: token、timestamp、last_login_at、created_at、updated_at、iat、exp。
## 2. 测试账号
- username: liufumingren
- password: 111111
## 3. 方法使用来源
- method 定义来源: methods/system.json
- 回放脚本会从该配置中读取 method 分组、描述、参数定义,作为样本元数据。
## 4. 测试数据来源
- 主来源表: wms_system_log
- 参考日志表:
- wms_api_log
- wms_operation_log
- wms_account_login_log
- 样本选择原则:
- 优先同账号(liufumingren)
- 优先只读方法(get/list/query/detail/info/stats)
- 优先较新数据(按日志 id 倒序)
- 优先方法去重
## 5. 执行脚本
脚本文件:
- script/method-output-regression.cjs
命令:
```powershell
# 修改前执行,生成基线
node .\script\method-output-regression.cjs baseline 8
# 修改后执行,对比输出
node .\script\method-output-regression.cjs compare
```
输出文件:
- temp/method-output/method-output-baseline.json
- temp/method-output/method-output-baseline.md
- temp/method-output/method-output-compare.json
## 6. 本次基线执行结果(修改前)
执行时间:
- baseline: 2026-03-22T13:56:52Z
- compare: 2026-03-22T13:56:57Z
样本数:
- 8
样本 method(来自 temp/method-output/method-output-baseline.md):
- storage.receiving.getReceivingDetail (sourceId: 10790)
- order.getOrderModels (sourceId: 10783)
- print.getList (sourceId: 10611)
- print.getComputerPrinter (sourceId: 10579)
- print.getItem (sourceId: 10578)
- print.getComputer (sourceId: 10577)
- store.getStoreRoles (sourceId: 10553)
- index.getExpressList (sourceId: 9820)
比对结果:
- total: 8
- mismatch: 0
- pass: true
说明:
- 当前样本中既包含 200 成功响应,也包含 403 权限响应。
- 403 响应同样纳入一致性校验范围(用于防止权限链路被意外改变)。
## 7. 后续执行要求
- 每次开始改动前,先运行 baseline 并保留输出文件。
- 每次改动后,必须运行 compare。
- 若 mismatch > 0,禁止进入交付,需先排查差异并补充说明。

View File

@ -1,791 +0,0 @@
# Service 使用与 API 文档联动审计
更新时间: 2026-03-22
适用阶段: Model 重构阶段 4 及后续代码改造
目的: 在修改 service 前,先确认真实使用链路;若 service 已被使用,则必须同步更新 service、对应 API 文档,并在本文件中记录变更,便于后续复盘。
## 1. 执行规则
- 任何计划修改的 service,必须先确认是否被 systemMethods、qimenMethods、controller 或其他 service 使用。
- 只要存在真实调用链,就不能只改底层 service,必须一起评估上游入口与返回结构。
- 对外暴露为 system/qimen method 的能力,必须同步更新 methods/system.json 或 methods/qimen.json。
- 每次实际修改完成后,必须在本文件末尾追加一条变更记录。
## 2. 本轮已确认的高风险 service 使用链路
### 2.1 账号-仓库-角色关联链路
#### A. app/service/systems/store.js
关键风险:
- 直接使用不存在的 ctx.model.AccountStoreRole。
- 影响门店申请审核、角色分配、角色列表查询。
已确认调用点:
- app/service/systems/store.js:464
- app/service/systems/store.js:679
- app/service/systems/store.js:690
上游 system method:
- app/service/systemMethods/store.js:35 -> store.getStoreRoles
- app/service/systemMethods/store.js:45 -> store.auditApply
对应 API 文档:
- methods/system.json:1976 -> store.getStoreRoles
- methods/system.json:1993 -> store.auditApply
联动要求:
- 若将 AccountStoreRole 收敛为 AccountStoreEmployee 或其他真实模型,必须同步更新:
- app/service/systems/store.js
- app/service/systemMethods/store.js
- methods/system.json 中 store.getStoreRoles / store.auditApply 的参数、返回结构描述
#### B. app/service/systems/auth/user.js
关键风险:
- 当前已部分切到 AccountStoreEmployee,但变量名和注释仍保留 accountStoreRole 旧语义。
- 平台激活逻辑会联动 user.login、user.info、user.changeRole。
已确认调用点:
- app/service/systems/auth/user.js:118 -> changeRole
- app/service/systems/auth/user.js:195 -> info
- app/service/systems/auth/user.js:328 -> findById
- app/service/systems/auth/user.js:877 -> ensurePlatformActiveRole
上游 system method:
- app/service/systemMethods/user.js:11 -> user.login
- app/service/systemMethods/user.js:24 -> user.info
- app/service/systemMethods/user.js:29 -> user.changeRole
对应 API 文档:
- methods/system.json:2016 附近 -> user.login
- methods/system.json:2051 附近 -> user.info
- methods/system.json:2067 附近 -> user.changeRole
联动要求:
- 若修改 activeEmployeeId、employee_id、role_id、roles 列表结构,必须同步更新:
- app/service/systems/auth/user.js
- app/service/systemMethods/user.js
- methods/system.json 中 user.login / user.info / user.changeRole 的返回字段说明
#### C. app/service/systems/account_platform.js
关键风险:
- 该 service 当前直接依赖 AccountStoreRole 幽灵 key。
- 虽然尚未发现对外直接暴露的 system method,但它承载的平台激活角色语义与 auth.user 高度耦合。
已确认调用点:
- app/service/systems/account_platform.js:13 -> switchActiveRole
- app/service/systems/account_platform.js:77 -> getActiveRoleByPlatform
- app/service/systems/account_platform.js:159 -> getMultiplePlatformActiveRoles
- app/service/systems/account_platform.js:219 -> getAllPlatformActives
- app/service/systems/account_platform.js:309 -> getAvailableRoles
间接受影响入口:
- app/service/systems/auth/user.js:58
- app/service/systems/auth/user.js:304
- app/service/systems/auth/user.js:877
文档联动策略:
- 当前没有独立 method 文档入口。
- 若修改本 service 的输入/输出语义,必须回写到 user.login / user.info / user.changeRole 的 API 文档,因为这些接口会消费平台激活角色结果。
### 2.2 动态分表工厂链路
#### A. app/service/systemMethods/order.js
关键风险:
- 依赖 OrderDeliveryFactory / OrderItemsFactory 获取动态模型。
- 若工厂 key、返回模型或字段映射调整,会直接影响系统订单接口。
已确认调用点:
- app/service/systemMethods/order.js:18 -> getOrderModels
- app/service/systemMethods/order.js:98 -> list
- 其他 order.* 方法共享同一组动态模型入口
对应 API 文档:
- methods/system.json:422 -> order.getOrderModels
- methods/system.json:439 -> order.list
- methods/system.json:471 -> order.detail
- methods/system.json:503 -> order.listItems
- methods/system.json:535 -> order.stats
- methods/system.json:560 -> order.updateStatus
- methods/system.json:676 -> order.updateDeliveryTime
联动要求:
- 若修改动态模型获取方式、字段名或订单明细结构,必须同步更新上述 order.* 文档。
#### B. app/service/systems/delivery_order.js 与 app/service/qimenMethods/deliveryorder.js
关键风险:
- qimen 发货单接口直接依赖 OrderDeliveryFactory。
- 若动态分表模型的 key 或查询字段变化,Qimen 接口会受影响。
已确认调用点:
- app/service/systems/delivery_order.js:14
- app/service/systems/delivery_order.js:311
- app/service/qimenMethods/deliveryorder.js:7
- app/service/qimenMethods/deliveryorder.js:8
对应 API 文档:
- methods/qimen.json:14 -> deliveryorder.batchcreate
- methods/qimen.json:88 -> deliveryorder.create
- methods/qimen.json:162 -> deliveryorder.query
联动要求:
- 若修改 deliveryorder 查询、创建、历史表读取逻辑,必须同步更新 qimen deliveryorder.* 文档。
#### C. app/service/apiMethods/test.js
关键风险:
- 存在错误调用名 WmsOrderDeliveryFactory / WmsOrderItemsFactory。
- 这是内部调试链路,不是正式 API 文档入口,但必须与正式工厂 key 保持一致。
已确认调用点:
- app/service/apiMethods/test.js:50
- app/service/apiMethods/test.js:51
联动要求:
- 改动时同步修正为 OrderDeliveryFactory / OrderItemsFactory。
- 无需更新 methods 文档,但必须在本文件记录修复事实。
## 3. 本轮结论
- 即将进入的关联治理不是纯 model 内部调整,至少会影响 store、user、account_platform、order、deliveryorder 这几条真实业务链路。
- 因此后续任何代码改动都不能只改 model。
- 必须按“model -> service -> systemMethods/qimenMethods -> methods 文档 -> 变更记录”的顺序联动处理。
## 4. 修改前检查清单
- 确认目标 service 是否被上游调用。
- 确认上游调用属于 system 还是 qimen 入口。
- 确认 methods/system.json 或 methods/qimen.json 是否存在对应 method。
- 若返回结构变化,先记录旧字段,再补文档。
- 修改完成后,在本文件追加一条变更记录。
## 5. 变更记录模板
### YYYY-MM-DD HH:mm
- 修改范围:
- 涉及 service:
- 上游入口:
- 更新的 API 文档:
- 返回结构变化:
- 兼容处理:
- 验证方式:
## 6. 当前记录
### 2026-03-22 关联治理准备
- 修改范围: 阶段 4 开始前的 service 使用与文档联动审计
- 涉及 service:
- app/service/systems/store.js
- app/service/systems/auth/user.js
- app/service/systems/account_platform.js
- app/service/systemMethods/order.js
- app/service/systems/delivery_order.js
- app/service/qimenMethods/deliveryorder.js
- app/service/apiMethods/test.js
- 上游入口:
- system: store.getStoreRoles, store.auditApply, user.login, user.info, user.changeRole, order.*
- qimen: deliveryorder.batchcreate, deliveryorder.create, deliveryorder.query
- 更新的 API 文档: 尚未改动代码,本轮只完成审计与联动范围确认
- 返回结构变化: 暂无
- 兼容处理: 暂无
- 验证方式: 通过 service 调用搜索、system/qimen method 搜索、methods 文档映射完成静态核对
### 2026-03-22 关联治理执行(第一批)
- 修改范围: 修复 store 链路中 AccountStoreRole 幽灵模型引用
- 涉及 service:
- app/service/systems/store.js
- 上游入口:
- system: store.getStoreRoles, store.auditApply
- 更新的 API 文档:
- methods/system.json
- store.getStoreRoles: 补充 code 参数定义
- store.auditApply: 补充 audit_status/code/store_id/role_ids/reject_reason 参数定义
- 返回结构变化: 无(维持原有 code/message/data 结构)
- 兼容处理:
- 将账号-门店关系绑定到 AccountStoreEmployee
- 将角色绑定落到 EmployeeRole(employee_id + role_id)
- 保持接口出参与状态码行为不变
- 验证方式:
- 运行生成的改造前回归样例测试
- 运行 method-output compare 对比报告
### 2026-03-22 关联治理执行(第二批)
- 修改范围: 修复 account_platform 链路中 AccountStoreRole 幽灵模型引用
- 涉及 service:
- app/service/systems/account_platform.js
- 上游入口:
- 间接影响 system: user.login, user.info, user.changeRole
- 更新的 API 文档:
- 无直接 method 文档变更(本批未新增/修改 system method 参数)
- 返回结构变化: 无(维持 role_id/role_name/role_code/store_id/store_name/store_code 字段)
- 兼容处理:
- switchActiveRole 保持历史参数名 accountStoreRoleId,内部按 employee_id 落库
- include 链路由 AccountStoreRole 改为 AccountStoreEmployee + EmployeeRole + Role + Store
- getAvailableRoles 改为从 AccountStoreEmployee/EmployeeRole 聚合返回
- 验证方式:
- npx egg-bin test test/app/controller/system.method-output.pre-refactor.generated.test.js
- node .\\script\\method-output-regression.cjs compare
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
### 2026-03-22 关联治理执行(第三批)
- 修改范围: 清理 model 层残留命名污染(不改接口结构)
- 涉及 service/model:
- app/model/account.js
- app/model/role.js
- 上游入口:
- 间接影响 system 全链路(仅模型关联定义清理)
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 仅移除 AccountStoreRole 的遗留注释/无效解构,不调整现有 alias
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- npx egg-bin test test/app/controller/system.method-output.batch3.generated.test.js
### 2026-03-22 样例漂移策略更新
- 发现现象:
- 固定历史样例 `system.method-output.pre-refactor.generated.test.js` 因权限/业务数据变化出现与历史快照不一致。
- 策略调整:
- 每批改造前重新冻结当批 baseline,并生成当批 Egg.js 样例测试。
- 历史快照保留审计用途,不作为后续批次唯一门禁。
- 当前批次快照:
- run/method-output-baseline-batch3-20260322_224649.json
- test/app/controller/system.method-output.batch3.generated.test.js
### 2026-03-22 关联治理执行(第四批)
- 修改范围: 统一 alias 命名并引入双轨兼容(复数标准名 + 历史别名保留)
- 涉及 service/model:
- app/model/account.js
- app/model/account_store_employee.js
- app/model/role.js
- app/model/store.js
- app/service/systems/account_platform.js
- app/service/systems/auth/user.js
- 上游入口:
- 间接影响 system: user.login, user.info, user.changeRole, store.getStoreRoles
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 新增标准 alias:accountStoreEmployees / employeeRoles
- 保留历史 alias:accountStoreRoles / accountStoreEmployee / employeeRole
- service 查询切换到新 alias,并在读取层面对旧 alias 做回退兼容
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
### 2026-03-23 关联治理执行(第四批补充收敛)
- 修改范围: service 层去除旧 alias 回退依赖,统一使用新 alias(保留 model 兼容别名)
- 涉及 service:
- app/service/systems/account_platform.js
- app/service/systems/auth/user.js
- 上游入口:
- 间接影响 system: user.login, user.info, user.changeRole, store.getStoreRoles
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- account_platform 内部读取改为 employeeRoles 单轨
- model 层兼容 alias 继续保留,避免外部未迁移调用中断
- auth/user 中 accountStoreRole 变量语义更新为 accountStoreEmployee
- 验证方式:
- node .\\script\\method-output-regression.cjs baseline 8
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
### 2026-03-23 关联治理执行(第五批)
- 修改范围: 移除 model 层重复兼容 alias,完成重复关联清理
- 涉及 model:
- app/model/account.js
- app/model/account_store_employee.js
- app/model/role.js
- app/model/store.js
- 上游入口:
- 间接影响 system: user.login, user.info, user.changeRole, store.getStoreRoles
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 删除旧 alias:accountStoreRoles / employeeRole / accountStoreEmployee(Store.hasMany 语义)
- 保留必要单数 alias:AccountPlatformActive.belongsTo(AccountStoreEmployee).as = accountStoreEmployee
- 验证方式:
- node .\\script\\method-output-regression.cjs baseline 8
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
### 2026-03-23 关联治理执行(4.1 全量一致性校验)
- 修改范围: 对 app/model 全量关联定义与数据库真实外键进行一致性审计(无业务代码改动)
- 审计产物:
- association_fk_consistency_report.md
- temp/association-fk-audit.json
- 审计结论:
- DB 外键 51 条,模型关联 89 条,可直接匹配 53 条
- 模型定义但 DB 无外键约束 28 条
- DB 有外键但模型未声明 13 条
- 动态模型/示例占位无法静态解析 5 条
- 影响判断:
- 当前 system 输出门禁未受影响,但存在“模型语义与 DB 约束不完全对齐”的技术债
- 已将高优先级差异并入后续 4.4 规约与治理清单
### 2026-03-23 关联治理执行(第六批:receiving 高优先差异第一批)
- 修改范围: 处理 receiving 链路高优先差异,移除无效模型关联并收敛仓库维度查询条件
- 涉及 service/model:
- app/model/receiving.js
- app/model/receiving_detail.js
- app/service/systems/storage/receiving.js
- 上游入口:
- 间接影响 system: storage.receiving.getReceivingDetail 及 receiving 相关查询/更新链路
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 删除无效关联: `Receiving.hasMany(Storage, foreignKey: 'receiving_id')`
- 删除无效关联: `ReceivingDetail.hasMany(Storage, foreignKey: 'receiving_detail_id')`
- `StoreWarehouse` include/query 统一增加 `warehouse_id + use_status` 过滤,避免跨仓库错关联
- `create` 流程 `store_name` 统一使用 `store_remask`
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 验证结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 关联治理执行(第七批:4.4 规约文档落地)
- 修改范围: 形成并落地 eager-loading 与 N+1 风险规约(文档治理,无业务代码改动)
- 涉及文档:
- association_eager_loading_n_plus_one_guideline.md
- association_validation_checklist.md
- model_todo.txt
- 上游入口:
- 无直接 system/qimen 行为变更
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 兼容处理:
- 将关联查询的最小约束(include attributes、上下文 where、门禁流程)固化为统一规约
- 验证方式:
- 以第六批回归结果作为当前代码基线(compare mismatch=0,tests 14 passing)
### 2026-03-23 关联治理执行(第八批:store_warehouse/stock_warehouse 语义收敛)
- 修改范围: 修复 stock_store 链路中 `StoreWarehouse` 仅按 `store_id` 关联导致的跨仓误匹配风险
- 涉及 service/model:
- app/service/systems/stock_store.js
- 上游入口:
- 间接影响 system: stock.* 查询链路(库存列表/搜索)
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- `store_stock` include 在 count/findAll/search 三处统一增加 `warehouse_id + use_status` 过滤
- 保持 `required` 策略不变(列表仍 required=true,搜索路径 required=false)
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 验证结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 关联治理执行(第九批:role/permission 语义收敛)
- 修改范围: 修复 auth/user 权限链路对禁用角色/权限的过滤缺失问题
- 涉及 service/model:
- app/service/systems/auth/user.js
- 上游入口:
- 间接影响 system: user.info(权限与菜单加载链路)
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无(仅收敛为“启用角色/启用权限可见”)
- 兼容处理:
- `getPermissions/getMenus` 在 EmployeeRole 查询中增加 Role.status=1 过滤
- Permission 查询增加 status=1 过滤
- role_id 与 permission_id 查询集合去重
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 验证结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 关联治理执行(第十批:role_permission 外键迁移落地)
- 修改范围: 落地 `role_permission.permission_id -> permission.id` 的可执行迁移脚本与模型类型对齐
- 涉及 service/model/migration:
- database/migrations/20260323103000-align-role-permission-fk.js
- app/model/role_permission.js
- 上游入口:
- 无直接 system/qimen 返回结构变化
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 兼容处理:
- 迁移脚本包含保护性校验:存在孤儿数据时直接失败,避免静默脏写
- down 提供外键回滚与字段类型回退
- 审计发现:
- `wms_role_permission.permission_id` 存在 4 条孤儿记录(id: 2, 3, 6, 10)
- `wms_role.store_id` 存在 3 条 `0` 哨兵值(当前不满足直接加 FK 条件)
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 实际执行结果:
- 已创建备份表并落库:
- `wms_role_permission_orphan_backup_20260323`(4 条)
- `wms_role_store_zero_backup_20260323`(3 条)
- 已清洗数据:
- 删除 `wms_role_permission.permission_id` 孤儿 4 条
- 将 `wms_role.store_id=0` 修正为 `NULL` 共 3 条
- 已执行 DDL:
- `wms_role_permission.permission_id` -> `int(11)`
- 新增外键 `fk_wms_role_permission_permission`(ON UPDATE RESTRICT, ON DELETE CASCADE)
- SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`
- 迁移后复核: 孤儿计数=0,role_store_zero=0
- 回归结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 关联治理执行(第十一批:role.store_id 外键策略落地)
- 修改范围: 落地 `wms_role.store_id -> wms_store.id` 外键策略(NULL 语义)
- 涉及 migration:
- database/migrations/20260323113000-add-role-store-fk.js
- 上游入口:
- 无直接 system/qimen 返回结构变化
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 兼容处理:
- `store_id` 字段类型对齐为 `bigint(20) unsigned NULL`
- 新增索引 `idx_store_id`
- 外键策略采用 `ON DELETE SET NULL`,保留历史角色记录的 NULL 语义
- 实际执行结果:
- 外键 `fk_wms_role_store` 已生效(ON UPDATE RESTRICT, ON DELETE SET NULL)
- `wms_role` 孤儿数据复核: 0
- SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js`
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 关联治理执行(第十二批:store_warehouse/stock_warehouse 模型层语义治理)
- 修改范围: 收敛 `store_stock` 关联的模型层复合键表达,统一 include 构造入口
- 涉及 service/model:
- app/model/store_warehouse.js
- app/model/stock_warehouse.js
- app/model/receiving.js
- app/service/systems/stock_store.js
- app/service/systems/storage/receiving.js
- 上游入口:
- 间接影响 system: stock.* / storage.receiving.* 查询链路
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- StoreWarehouse 新增 `buildScopedWhere` 与 `buildStoreStockInclude`,统一生成 `warehouse_id + use_status` 约束
- 复合键语义关联统一显式 `constraints:false`,避免单列外键误解
- service 查询改为复用模型构造器,保持原有 `required` 语义不变
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 关联治理执行(第十三批:include alias 一致性收尾扫描)
- 修改范围: 阶段 4 收尾检查(全量 include alias 一致性扫描,无业务代码改动)
- 涉及范围:
- app/model/**/*.js(association `as` 定义)
- app/service/**/*.js(include `as` 使用)
- 上游入口:
- 无直接 system/qimen 行为变更
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 扫描方法:
- 全量检索 model association 与 service include 的 alias 使用
- 执行自动差集比对(service alias - model alias)
- 扫描结果:
- model alias 总数: 48
- 差集可疑项: 0
- 结论: 未发现 include alias 不一致问题
- 验证方式:
- 通过一次性 Node 差集脚本执行 `service alias - model alias` 自动比对(临时脚本未入库)
### 2026-03-23 关联治理执行(第十四批:permission.parent_id 自关联约束落地)
- 修改范围: 落地 `wms_permission.parent_id -> wms_permission.id` 自关联外键,并统一根节点语义
- 涉及 service/model/migration:
- database/migrations/20260323123000-add-permission-parent-fk.js
- app/model/permission.js
- app/service/systems/auth/user.js
- 上游入口:
- 间接影响 system: user.info(菜单树构建)
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 根节点语义由 `parent_id=0` 规范为 `parent_id IS NULL`
- 模型 setter 兼容历史输入:`0 -> NULL`
- 菜单树构建逻辑根判断由 `parent_id===0` 收敛为 `!parent_id`
- 实际执行结果:
- 落库复核:`root_zero_after=0`、`root_null_after=42`、`orphan_after=0`
- 外键 `fk_wms_permission_parent` 已生效(ON UPDATE RESTRICT, ON DELETE SET NULL)
- SequelizeMeta 已登记 `20260323123000-add-permission-parent-fk.js`
- 触发器状态:目标库因权限限制(binlog + SUPER)未创建触发器,采用应用层归一化方案替代
- 验证方式:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 模型能力治理执行(第十五批:阶段 5.1 清理清单盘点)
- 修改范围: 阶段 5.1(识别应迁移到 service 层的方法能力,文档治理)
- 涉及文档:
- model_cleanup_list.md
- model_todo.txt
- 上游入口:
- 无直接 system/qimen 行为变更
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 盘点结论:
- 模型方法总数: 102
- 第一批应迁移(P1)聚焦: EntryOrder / EntryItems / Storage / RolePermission / Store
- 第一批无调用可清理(P2)已形成清单,待阶段 5.2 执行删除前复核
- 验证方式:
- 静态扫描 model 方法清单与引用关系(仅文档盘点,无业务代码改动)
### 2026-03-23 模型能力治理执行(第十六批:阶段 5.2 第一批无调用方法清理)
- 修改范围: 清理 model 层第一批无调用静态方法(低风险)
- 涉及 model:
- app/model/api_app.js
- app/model/interface_type.js
- app/model/print_item.js
- 上游入口:
- 无直接 system/qimen 行为变更
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 兼容处理:
- 清理前执行全局引用复核,确认仅在定义处出现
- 仅删除静态 helper,不触碰关联定义与实例方法
- 删除项:
- ApiApp.findByAppKey / ApiApp.findByQimenConfig
- InterfaceType.findByCode / InterfaceType.findEnabled
- PrintItem.getGroupFields / PrintItem.getTableConfigs
- 验证方式:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 模型能力治理执行(第十七批:阶段 5.2 第二批无调用方法清理)
- 修改范围: 清理 model 层第二批无调用静态方法(低风险)
- 涉及 model:
- app/model/i18n_translation.js
- app/model/stock_store.js
- 上游入口:
- 无直接 system/qimen 行为变更
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 兼容处理:
- 清理前完成删除前引用复核(service/controller/test/script 全仓扫描)
- 仅删除静态 helper,不触碰关联定义、字段定义与实例方法
- 删除项:
- I18nTranslation.getTranslation / I18nTranslation.batchGetTranslations / I18nTranslation.getProjectTranslations / I18nTranslation.upsertTranslation / I18nTranslation.getUntranslated
- StockStore.findByItemCode / StockStore.findByStore
- 验证方式:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- generated regression: 8 passing
- smoke: 6 passing
- tests: 14 passing
### 2026-03-23 模型能力治理执行(第十八批:阶段 5.2 P1 第一组迁移)
- 修改范围: 将 EntryOrder / EntryItems 的内部静态方法迁移到 service,收敛 model 职责
- 涉及 service/model:
- app/service/systems/entry_order.js
- app/model/entry_order.js
- app/model/entry_items.js
- 上游入口:
- 无直接新增 system/qimen method;属于内部服务能力收敛
- 更新的 API 文档:
- 无(对外接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 迁移 EntryOrder.findByOrderCode/findByStatus/getStatsByWarehouse/updateSyncStatus/updateOrderStatus/calculateReceivedQuantities
- 迁移 EntryItems.batchUpdateReceived/getOrderProgress
- 验证方式:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- generated regression: 8 passing
- smoke: 6 passing
- tests: 14 passing
### 2026-03-23 模型能力治理执行(第十九批:阶段 5.2 P1 第二组迁移)
- 修改范围: 将 Storage 的内部静态方法迁移到 service,收敛 model 职责
- 涉及 service/model:
- app/service/systems/storage/index.js
- app/model/storage.js
- 上游入口:
- 无直接新增 system/qimen method;属于内部服务能力收敛
- 更新的 API 文档:
- 无(对外接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 迁移 Storage.findByStockAndBatch/findBySpace/findAvailableByWarehouse/findExpiringSoon/updateQuantity/lockQuantity/unlockQuantity/allocateQuantity/getStockSummary/getSpaceUsage
- 验证方式:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- generated regression: 8 passing
- smoke: 7 passing
- tests: 15 passing
### 2026-03-23 模型能力治理执行(第二十批:阶段 5.2 P1 第三组迁移)
- 修改范围: 将 Role / RolePermission 的权限编排方法迁移到 service,收敛 model 职责
- 涉及 service/model:
- app/service/systems/auth/role_permission.js
- app/model/role.js
- app/model/role_permission.js
- 上游入口:
- 无直接新增 system/qimen method;属于内部服务能力收敛
- 更新的 API 文档:
- 无(对外接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 迁移 Role.assignPermissions/getPermissionTree/getPermissionIds
- 迁移 RolePermission.bulkAssign/clearRolePermissions/getRolePermissions/hasPermission
- 验证方式:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- generated regression: 8 passing
- smoke: 7 passing
- tests: 15 passing
### 2026-03-23 模型能力治理执行(第二十一批:阶段 5.2 P1 第四组迁移)
- 修改范围: 将 Store 的校验与查询助手方法迁移到 service,收敛 model 职责
- 涉及 service/model:
- app/service/systems/store.js
- app/model/store.js
- 上游入口:
- 无直接新增 system/qimen method;属于内部服务能力收敛
- 更新的 API 文档:
- 无(对外接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 迁移 Store.validateStoreData/checkCompanyNameExists/findByAccountId/findAllEnabled/findAllWarehouses
- 验证方式:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- generated regression: 8 passing
- smoke: 7 passing
- tests: 15 passing
### 2026-03-23 系统接口兼容修复(第二十二批:project 请求头校验)
- 修改范围: 修复 system 请求上下文校验对历史 project=wms 请求头的误拒绝
- 涉及 service:
- app/service/system.js
- 变更内容:
- `ALLOWED_PROJECTS` 增加 `wms/scm/other`,保持与历史调用兼容
- 触发原因:
- generated regression 与 smoke 在无业务代码变更时统一出现 400(`project 不支持: wms`)
- 验证方式:
- 直接调用 `user.login`(platform=web, project=wms)回归
- compare + generated regression + smoke 全量重跑
- 回归结果:
- login: HTTP 200
- compare: total=8, mismatch=0
- generated regression: 8 passing
- smoke: 7 passing
- tests: 15 passing

View File

@ -1,102 +0,0 @@
# Association Eager-Loading 与 N+1 规约
更新时间: 2026-03-23
适用阶段: Model 重构阶段 4.4
范围: app/service/**/*.js 中涉及 Sequelize 关联查询的代码
## 1. 目标
- 降低关联查询的 SQL 次数与响应时间抖动。
- 统一 eager-loading 写法,避免 include 漂移导致错关联。
- 在不改变外部接口返回结构的前提下收敛查询成本。
## 2. 术语
- eager-loading: 通过 include 一次性加载关联数据。
- N+1: 先查 1 次主数据,再按每条主数据各查 1 次关联,导致总查询次数随 N 线性增长。
- 关联上下文约束: 在 include.where 中补齐业务维度(如 warehouse_id、use_status),避免跨上下文错关联。
## 3. 强制规则
1. 列表查询禁止在循环内按行查询关联表。
2. 只要关联数据是展示必需字段,优先使用 include 一次加载。
3. include 必须显式声明 attributes,禁止默认全字段拉取。
4. include 需要业务上下文约束时,必须补齐 where 条件(典型: warehouse_id + use_status)。
5. hasMany/hasOne/belongsTo 的 as 必须与 model 定义一致,禁止临时字符串别名。
6. 分页列表若包含 hasMany,优先控制返回列并评估 distinct/subQuery,防止计数与分页漂移。
7. count 与 findAll 不一致时,必须拆分并保持 where/include 语义一致。
## 4. 推荐写法
### 4.1 反模式(N+1)
```js
const list = await Model.findAll({ where });
for (const row of list) {
row.child = await Child.findOne({ where: { id: row.child_id } });
}
```
### 4.2 规约写法(eager-loading)
```js
const list = await Model.findAll({
where,
attributes: [ 'id', 'name', 'child_id' ],
include: [
{
model: Child,
as: 'child',
attributes: [ 'id', 'name' ],
required: false,
},
],
});
```
### 4.3 仓库维度约束(本仓库高频场景)
```js
include: [
{
model: ctx.model.StoreWarehouse,
as: 'store_stock',
attributes: [ 'store_id', 'store_remask' ],
where: {
warehouse_id: warehouseId,
use_status: 1,
},
required: false,
},
]
```
## 5. 当前代码落地点
- receiving 链路已按规约补齐仓库维度过滤,避免 StoreWarehouse 跨仓匹配。
- receiving 与 receiving_detail 已移除无效 Storage hasMany 关联,避免误导 include 设计。
- 后续优先治理:
- store_warehouse 与 stock_warehouse 的 store_id 语义对齐
- role / role_permission / permission 的关联约束与 include 一致性
## 6. 变更门禁
每批涉及关联查询的改动,至少执行以下门禁:
1. node .\\script\\method-output-regression.cjs compare
2. node .\\script\\tmp-generate-method-regression-test.cjs
3. npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
4. npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
交付标准:
- compare 结果 mismatch=0
- 生成回归与关键冒烟测试全部通过
## 7. PR 自检清单
- [ ] 是否存在循环内数据库查询。
- [ ] include 是否补齐 attributes。
- [ ] include.where 是否补齐业务上下文约束。
- [ ] as 是否与 model 关联定义一致。
- [ ] 是否完成 method-output compare 与回归测试。

View File

@ -1,61 +0,0 @@
# Association Fix Plan
更新时间: 2026-03-23
适用阶段: Model 重构阶段 4(关联关系规范化)
## 1. 目标
- 统一 alias 命名规则(belongsTo/hasOne 用单数,hasMany/belongsToMany 用复数)。
- 清理重复或冲突关联定义,避免 include 歧义。
- 保持 system/qimen 输出结构不变,通过 baseline/compare 门禁验证。
## 2. 已完成修复
### 2.1 幽灵模型收敛(已完成)
- 将 AccountStoreRole 相关调用链迁移到 AccountStoreEmployee + EmployeeRole + Role + Store。
- 覆盖主链路:
- app/service/systems/store.js
- app/service/systems/account_platform.js
- app/service/systems/auth/user.js
### 2.2 alias 标准化(已完成)
- 新标准 alias:
- accountStoreEmployees
- employeeRoles
- 已完成调用迁移:
- account_platform 服务 include 与读取逻辑统一为 employeeRoles
- auth/user 服务 include 统一为 employeeRoles
### 2.3 重复关联清理(已完成)
- 已移除以下重复兼容 alias 定义:
- Account.accountStoreRoles
- AccountStoreEmployee.employeeRole
- Role.employeeRole
- Store.accountStoreEmployee
- 保留必要单数 alias(belongsTo 语义):
- AccountPlatformActive.accountStoreEmployee
## 3. 验证策略
每批改动执行以下门禁:
1. node .\\script\\method-output-regression.cjs baseline 8
2. node .\\script\\method-output-regression.cjs compare
3. node .\\script\\tmp-generate-method-regression-test.cjs
4. npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
5. npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
## 4. 当前状态
- 输出一致性门禁:通过(mismatch=0)。
- 关键冒烟测试:通过。
- 对外 API 参数/返回:无结构变更。
## 5. 剩余工作
- 全量扫描其余模型类方法中的 include alias 一致性(已完成,差集扫描异常项 0 个)。
- 评估并落地 permission.parent_id 自关联约束策略(已完成:root 语义归一为 NULL + 自关联 FK)。
- 进入阶段 5:Model 内部能力清理与边界固化。

View File

@ -1,65 +0,0 @@
# Association FK Consistency Report
更新时间: 2026-03-23T03:08:35.772Z
数据库: wms
## Summary
- DB 外键数: 51
- 模型关联数: 89
- 可直接匹配外键: 53
- 模型定义但 DB 无外键约束: 28
- 无法解析到模型表映射: 5
- DB 存在但模型未声明的外键: 13
## Missing Constraints (Top 20)
- wms_receiving.creator_id->wms_account_store_employee.id (app/model/account_store_employee.js, hasMany, as=Receiving)
- wms_api_app.warehouse_id->wms_store.id (app/model/api_app.js, belongsTo, as=warehouse)
- wms_fast_where.pid->wms_fast_where.id (app/model/fast_where.js, belongsTo, as=parent)
- wms_fast_where.pid->wms_fast_where.id (app/model/fast_where.js, hasMany, as=children)
- wms_location_space.zone_id->wms_location_zone.id (app/model/location_space.js, belongsTo, as=zone)
- wms_receiving_detail.space_id->wms_location_space.id (app/model/location_space.js, hasMany, as=receiving)
- wms_location_space.zone_id->wms_location_zone.id (app/model/location_zone.js, hasMany, as=spaces)
- wms_location_zone.warehouse_id->wms_location_zone.warehouse_id (app/model/location_zone.js, belongsTo, as=pickStartPoint)
- wms_permission.parent_id->wms_permission.id (app/model/permission.js, hasMany, as=children)
- wms_permission.parent_id->wms_permission.id (app/model/permission.js, belongsTo, as=parent)
- wms_receiving.warehouse_id->wms_store.id (app/model/receiving.js, belongsTo, as=warehouse)
- wms_receiving.creator_id->wms_account_store_employee.id (app/model/receiving.js, belongsTo, as=creator)
- wms_storage.receiving_id->wms_receiving.id (app/model/receiving.js, hasMany, as=storage_records)
- wms_receiving.store_id->wms_store_warehouse.store_id (app/model/receiving.js, belongsTo, as=store)
- wms_receiving_detail.system_product_id->wms_stock_warehouse.id (app/model/receiving_detail.js, belongsTo, as=system_product)
- wms_storage.receiving_detail_id->wms_receiving_detail.id (app/model/receiving_detail.js, hasMany, as=storage_details)
- wms_receiving_detail.space_id->wms_location_space.id (app/model/receiving_detail.js, belongsTo, as=receiving_space)
- wms_role.store_id->wms_store.id (app/model/role.js, belongsTo, as=store)
- wms_role_permission.permission_id->wms_permission.id (app/model/role_permission.js, belongsTo, as=permission)
- wms_stock_warehouse.store_id->wms_store_warehouse.store_id (app/model/stock_warehouse.js, belongsTo, as=store_stock)
## Unresolved Associations (Top 20)
- app/model/order_delivery_factory.js: DynamicModel -> ItemsModel (type=hasMany, fk=order_id)
- app/model/order_delivery_factory.js: ItemsModel -> DynamicModel (type=belongsTo, fk=order_id)
- app/model/order_delivery_factory.js: DynamicModel -> this.app.model.Store (type=belongsTo, fk=store_id)
- app/model/order_delivery_factory.js: DynamicModel -> this.app.model.Store (type=belongsTo, fk=warehouse_id)
- app/model/print_item.js: PrintItem -> app.model.OtherModel (type=belongsTo, fk=xxx)
## DB-only Foreign Keys (Top 20)
- wms_account_login_log.user_id->wms_account.id
- wms_embargo_policies.warehouse_id->wms_store.id
- wms_express_setting.express_code->wms_express.code
- wms_express_setting.warehouse_id->wms_store.id
- wms_order_delivery.store_id->wms_store.id
- wms_order_delivery.warehouse_id->wms_store.id
- wms_order_express.order_id->wms_order_delivery.id
- wms_order_express_print_data.express_id->wms_order_express.id
- wms_order_items.order_id->wms_order_delivery.id
- wms_stock_warehouse.warehouse_id->wms_store.id
- wms_store_join.account_id->wms_account.id
- wms_store_join.store_id->wms_store.id
- wms_system_log.store_id->wms_store.id
## Notes
- belongsToMany 通过中间表映射,未纳入本次“直接外键”匹配。
- 动态分表工厂中的关联(order_delivery_factory/order_items_factory)不做静态表级强校验。

View File

@ -1,165 +0,0 @@
# Association Validation Checklist
更新时间: 2026-03-23
范围: app/model/*.js + 核心系统 service 调用链
## 1. 核心检查项
- [x] AccountStoreRole 幽灵引用已移除(服务主链路)。
- [x] AccountStoreEmployee <-> EmployeeRole <-> Role 关系可用。
- [x] hasMany alias 复数化(employeeRoles/accountStoreEmployees)。
- [x] 重复兼容 alias 已清理(主链路)。
- [x] 对外接口输出一致(baseline/compare mismatch=0)。
- [x] 关键登录与用户信息链路测试通过。
## 2. 关键模型校验结果
| 模型 | 关键关联 | 结果 | 备注 |
| --- | --- | --- | --- |
| Account | hasMany AccountStoreEmployee as accountStoreEmployees | PASS | 已移除 accountStoreRoles |
| AccountStoreEmployee | hasMany EmployeeRole as employeeRoles | PASS | 已移除 employeeRole |
| Role | hasMany EmployeeRole as employeeRoles | PASS | 已移除 employeeRole |
| Store | hasMany AccountStoreEmployee as accountStoreEmployees | PASS | 已移除 accountStoreEmployee |
| AccountPlatformActive | belongsTo AccountStoreEmployee as accountStoreEmployee | PASS | belongsTo 单数语义保留 |
## 3. 服务调用链校验结果
| 服务 | 校验项 | 结果 |
| --- | --- | --- |
| systems/account_platform | include/读取 employeeRoles 一致 | PASS |
| systems/auth/user | include alias 使用 employeeRoles | PASS |
| systems/store | 角色绑定链路使用 EmployeeRole | PASS |
| systems/storage/receiving | StoreWarehouse 关联补 warehouse_id/use_status 过滤,避免跨仓错关联 | PASS |
## 4. 验证记录
- method-output compare: mismatch=0
- generated test: 8 passing
- smoke test (login/info/home): 6 passing
## 5. 4.1 全量审计结果(2026-03-23)
- 审计报告: association_fk_consistency_report.md
- DB 外键: 51
- 模型关联: 89
- 可直接匹配: 53
- 模型定义但 DB 无外键约束: 28
- DB 有外键但模型未声明: 13
- 动态模型/示例占位导致无法静态解析: 5
高优先级差异(建议先处理):
- receiving / receiving_detail / storage 三表关联的 FK 约束缺失项(第一批已处理:删除无效 hasMany(Storage) 关联,并修正 service include 过滤)
- store_warehouse 与 stock_warehouse/receiving 的 store_id 外键语义差异(已完成服务层与模型层双收敛)
- role / role_permission / permission 的部分 FK 未在 DB 层约束(核心约束已补齐,remaining: permission.parent_id 自关联约束策略评估)
### 5.1 高优先差异处理进展(receiving 第一批)
- 处理内容:
- 移除 `Receiving.hasMany(Storage, foreignKey: 'receiving_id')` 无效关联(storage 表不存在 receiving_id)。
- 移除 `ReceivingDetail.hasMany(Storage, foreignKey: 'receiving_detail_id')` 无效关联(storage 表不存在 receiving_detail_id)。
- `systems/storage/receiving` 多处 `StoreWarehouse` include/query 增加 `warehouse_id + use_status` 过滤,规避跨仓库错关联。
- `create` 流程中 `store_name` 改为来源 `store_remask`,与仓库门店展示语义对齐。
- 验证结果:
- method-output compare: mismatch=0
- generated regression + smoke: 14 passing
### 5.2 高优先差异处理进展(store_warehouse/stock_warehouse 第二批)
- 处理内容:
- `systems/stock_store` 的 `store_stock` include 全量补齐 `warehouse_id + use_status` 条件,避免仅按 `store_id` 关联导致跨仓误匹配。
- 覆盖 count/findAll/search 三处核心查询路径,保持原有返回结构不变。
- 验证结果:
- method-output compare: mismatch=0
- generated regression + smoke: 14 passing
### 5.3 高优先差异处理进展(role/permission 第三批)
- 处理内容:
- `systems/auth/user` 的权限与菜单查询链路补齐 `Role.status=1` 约束,仅启用角色参与授权。
- 权限查询补齐 `Permission.status=1` 约束,禁用权限不再进入 `user.permissions` 与菜单树。
- 对 role_id/permission_id 增加去重处理,避免重复关联导致的冗余查询和重复路径。
- 验证结果:
- method-output compare: mismatch=0
- generated regression + smoke: 14 passing
### 5.4 DB 约束补齐进展(role_permission 第四批)
- 处理内容:
- 新增迁移 `database/migrations/20260323103000-align-role-permission-fk.js`:
- 将 `wms_role_permission.permission_id` 对齐为 `int(11)`(与 `wms_permission.id` 一致)。
- 在无孤儿数据时添加 `fk_wms_role_permission_permission` 外键(ON DELETE CASCADE, ON UPDATE RESTRICT)。
- 同步模型字段类型: `app/model/role_permission.js` 的 `permission_id` 改为 `INTEGER`。
- 执行结果:
- 已完成数据清洗:`wms_role_permission.permission_id` 孤儿记录 4 条已备份并删除;`wms_role.store_id=0` 的 3 条记录已备份并修正为 `NULL`。
- 已执行迁移核心动作:`permission_id` 类型已对齐为 `int(11)`,且外键 `fk_wms_role_permission_permission` 已生效。
- SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`。
- 门禁结果:method-output compare mismatch=0,generated regression + smoke: 14 passing。
### 5.5 DB 约束补齐进展(role.store_id 第五批)
- 处理内容:
- 新增迁移 `database/migrations/20260323113000-add-role-store-fk.js`:
- 将 `wms_role.store_id` 对齐为 `bigint(20) unsigned NULL`。
- 补充索引 `idx_store_id`。
- 添加外键 `fk_wms_role_store`(ON UPDATE RESTRICT, ON DELETE SET NULL)。
- 执行结果:
- `wms_role.store_id` 外键已生效,孤儿计数=0。
- SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js`。
- 门禁结果:method-output compare mismatch=0,generated regression + smoke: 14 passing。
### 5.6 模型层复合键语义治理进展(store_warehouse/stock_warehouse 第六批)
- 处理内容:
- `StoreWarehouse` 模型新增统一构造器:`buildScopedWhere` / `buildStoreStockInclude`,收敛 `store_stock` include 的复合键语义。
- `StockWarehouse.belongsTo(StoreWarehouse as store_stock)` 与 `StoreWarehouse.hasMany(StockWarehouse as store_stock)` 显式标记 `constraints: false`,避免误导为单列外键。
- `Receiving.belongsTo(StoreWarehouse as store)` 显式标记 `constraints: false`,与 `store_id + warehouse_id` 业务语义对齐。
- `systems/stock_store` 与 `systems/storage/receiving` 已改为复用模型构造器,减少散落条件。
- 验证结果:
- method-output compare: mismatch=0
- generated regression + smoke: 14 passing
### 5.7 DB 约束补齐进展(permission.parent_id 第七批)
- 处理内容:
- 新增迁移 `database/migrations/20260323123000-add-permission-parent-fk.js`:
- 将 `wms_permission.parent_id` 根节点语义从 `0` 规范为 `NULL`。
- 添加自关联外键 `fk_wms_permission_parent`(ON UPDATE RESTRICT, ON DELETE SET NULL)。
- 模型与服务语义对齐:
- `Permission.parent_id` 改为 `allowNull: true` / `defaultValue: null`,并在 setter 中兼容输入 `0 -> NULL`。
- 权限树构建根节点判断由 `parent_id===0` 收敛为 `!parent_id`(兼容历史与新语义)。
- 执行结果:
- 数据复核: `root_zero_after=0`、`root_null_after=42`、`orphan_after=0`。
- 外键生效: `fk_wms_permission_parent` 已存在。
- SequelizeMeta 已登记 `20260323123000-add-permission-parent-fk.js`。
- 触发器策略: 目标库因权限限制(binlog + SUPER)未创建触发器,改由应用层归一化 `0 -> NULL`。
- 验证结果:
- method-output compare: mismatch=0
- generated regression + smoke: 14 passing
## 6. 后续检查
- [x] 全量扫描其余模型类方法中的 include 别名一致性(service as 与 model as 差集扫描结果: 0)。
- [x] 补充 N+1 风险清单与 eager-loading 建议(见 association_eager_loading_n_plus_one_guideline.md)。
### 6.1 include alias 一致性收尾扫描(2026-03-23)
- 扫描范围:
- `app/model/**/*.js` 中 association `as` 定义
- `app/service/**/*.js` 中 include `as` 使用
- 扫描方式:
- 先做全量检索(model association / service include)
- 再做集合差集(service alias - model alias)自动比对
- 扫描结论:
- model alias 总数: 48
- 差集可疑项: 0
- 结论: 未发现 include alias 不一致问题,可关闭阶段 4 收尾检查第 1 项。
## 7. 4.4 规约落地记录(2026-03-23)
- 规约文档: association_eager_loading_n_plus_one_guideline.md
- 已固化要求:
- 禁止循环内逐条查询关联表(N+1)。
- include 必须声明 attributes。
- 仓库链路 include 必须补齐 warehouse_id + use_status 约束。
- 涉及关联查询改动必须执行 compare + generated test + smoke。

View File

@ -1,76 +0,0 @@
# migration_execution_plan
更新时间: 2026-03-22
## 1. 执行原则
- 先解决 SequelizeMeta 漂移,再补新增 migration。
- 先补静态基表,再补关联表,再补日志/配置/打印等扩展表。
- 动态分表与视图单独治理,不混入普通 createTable 批次。
- 所有 migration 需保证幂等,避免现有环境重复执行报错。
## 2. 推荐顺序
### 步骤 1: 漂移核对
- 核对以下 4 个未进入 SequelizeMeta 的 migration 与当前数据库实际结构是否一致:
- 20251111083733-create-wms-stock-store.js
- 20251112085825-create-wms-entry-order.js
- 20251112085844-create-wms-entry-items.js
- 20260322061000-add-delivery-time-to-order-delivery-tables.js
- 若结构已存在且一致,优先制定“补登记基线方案”而不是直接重跑。
### 步骤 2: 补齐有 model 的静态表 migration
优先级建议:
1. 权限与组织类
2. 库位与库存类
3. 打印类
4. 日志与国际化类
### 步骤 3: 补齐无 model 但业务依赖的表 migration
优先补以下类型:
- system_log / api_log
- print_log / print_batch / printer_config
- platform_print_config
- wave_batch / wave_operation_log
- order_operation_log
### 步骤 4: 动态分表治理
- 为 order_delivery/order_items 动态分表建立统一 migration 策略。
- 后续迁移以“母表 + 动态建表 SQL 模板/工厂策略同步”为主,不逐仓库表固化。
### 步骤 5: 视图治理
- 为以下视图补充 create/drop migration:
- v_pick_space
- vw_warehouse_quota
## 3. 建议批次
- 批次 A: 漂移核对与基线修正
- 批次 B: 静态核心表 migration 补齐
- 批次 C: 日志/配置/打印扩展表 migration 补齐
- 批次 D: 动态分表与视图治理
## 4. local/test 演练方案
### local
- 先在本地库回放已有 migration。
- 再逐批执行新增 migration。
- 每批完成后执行 schema 对比与关键 API 冒烟。
### test
- 按 local 已验证通过的批次顺序执行。
- 保留每批执行前后的表结构快照。
- 若发现 drift 或兼容问题,先暂停后续批次。
## 5. 阶段 2 目标
- 明确每类表的 migration 补齐范围。
- 明确执行顺序和批次边界。
- 为后续正式补 migration 提供可直接执行的方案基础。

View File

@ -1,107 +0,0 @@
# migration_gap_list
更新时间: 2026-03-22
## 1. 现状摘要
- migration 文件数: 11
- SequelizeMeta 已执行数: 7
- 仓库文件与执行记录差值: 4
- createTable 覆盖表数: 10
- DB 物理表数: 68
- 视图数: 2
## 2. 命名与顺序审计
- 现有 migration 文件命名整体符合“时间戳-动作-对象.js”规范。
- 当前 migration 主要集中在 2025-11 和 2026-03 两个时间段。
- 当前主要问题不是命名,而是覆盖率不足和执行状态漂移。
## 3. 执行状态漂移
以下 migration 文件存在于仓库,但未记录在 SequelizeMeta:
- 20251111083733-create-wms-stock-store.js
- 20251112085825-create-wms-entry-order.js
- 20251112085844-create-wms-entry-items.js
- 20260322061000-add-delivery-time-to-order-delivery-tables.js
说明:
- 当前数据库中相关表或字段已存在,说明存在“结构已生效但 migration 未登记”或“迁移在其他环境/手工执行过”的漂移风险。
- 后续处理时不能直接盲跑这些 migration,必须先做结构一致性核对。
## 4. 有 model 但缺 create migration 的表
- wms_account_platform_active (app/model/account_platform_active.js)
- wms_account_store_employee (app/model/account_store_employee.js)
- wms_employee_role (app/model/employee_role.js)
- wms_fast_where (app/model/fast_where.js)
- wms_file (app/model/file.js)
- wms_file_reference (app/model/file_reference.js)
- wms_i18n_keys (app/model/i18n_key.js)
- wms_i18n_translations (app/model/i18n_translation.js)
- wms_location_space (app/model/location_space.js)
- wms_location_type (app/model/location_type.js)
- wms_location_zone (app/model/location_zone.js)
- wms_operation_log (app/model/operation_log.js)
- wms_order_delivery (app/model/order_delivery.js)
- wms_order_items (app/model/order_items.js)
- wms_permission (app/model/permission.js)
- wms_platform (app/model/platform.js)
- wms_platfrom_setting (app/model/platform_setting.js)
- wms_print_computer (app/model/print_computer.js)
- wms_print_items (app/model/print_item.js)
- wms_print_record (app/model/print_record.js)
- wms_print_station_express (app/model/print_station_express.js)
- wms_print_stations (app/model/print_stations.js)
- wms_print_template (app/model/print_template.js)
- wms_prohibited_type (app/model/prohibited_type.js)
- wms_qimen_log (app/model/qimen_log.js)
- wms_receiving (app/model/receiving.js)
- wms_receiving_detail (app/model/receiving_detail.js)
- wms_role (app/model/role.js)
- wms_role_permission (app/model/role_permission.js)
- wms_stock_barcodes (app/model/stock_barcode.js)
- wms_stock_unit (app/model/stock_unit.js)
- wms_stock_warehouse (app/model/stock_warehouse.js)
- wms_storage (app/model/storage.js)
- wms_store_join (app/model/store_join.js)
## 5. 无 model 且无 create migration 的 DB 表
- SequelizeMeta
- wms_api_log
- wms_embargo_policies
- wms_express
- wms_express_print_record
- wms_express_setting
- wms_order_delivery_100000
- wms_order_delivery_1000028
- wms_order_express
- wms_order_express_print_data
- wms_order_items_100000
- wms_order_items_1000028
- wms_order_operation
- wms_order_operation_log
- wms_order_picking
- wms_picking_strategy
- wms_platform_print_config
- wms_print_batch
- wms_print_log
- wms_printer_config
- wms_system_config
- wms_system_log
- wms_wave_batch
- wms_wave_operation_log
## 6. 特殊对象说明
- 动态分表:
- wms_order_delivery_*
- wms_order_items_*
这类表不建议逐张固化 create migration,应通过“母表迁移 + 动态建表策略”统一治理。
- 视图:
- vw_warehouse_quota
- v_pick_space
需要单独使用 view migration 管理。
- SequelizeMeta 属于迁移元数据表,不纳入业务模型补齐范围。

View File

@ -1,105 +0,0 @@
# modelList
更新时间: 2026-03-22
扫描范围: app/model/*.js
模型文件数: 45
## 1. 目标
- 用于快速查看模型层级结构。
- 用于后续 model 命名规范、关联规范、迁移补全的基线输入。
## 2. 模型层级结构
```text
app/model/
├─ 账号与权限
│ ├─ account.js
│ ├─ account_platform_active.js
│ ├─ account_store_employee.js
│ ├─ employee_role.js
│ ├─ permission.js
│ ├─ role.js
│ └─ role_permission.js
├─ 组织与仓库
│ ├─ store.js
│ ├─ store_join.js
│ ├─ store_warehouse.js
│ ├─ storage.js
│ ├─ receiving.js
│ ├─ receiving_detail.js
│ ├─ entry_order.js
│ └─ entry_items.js
├─ 库位与查询
│ ├─ location_type.js
│ ├─ location_zone.js
│ ├─ location_space.js
│ └─ fast_where.js
├─ 库存与商品
│ ├─ stock_store.js
│ ├─ stock_warehouse.js
│ ├─ stock_unit.js
│ ├─ stock_barcode.js
│ └─ prohibited_type.js
├─ 订单与履约
│ ├─ order_delivery.js
│ ├─ order_items.js
│ ├─ order_delivery_factory.js
│ └─ order_items_factory.js
├─ 打印能力
│ ├─ print_template.js
│ ├─ print_item.js
│ ├─ print_record.js
│ ├─ print_stations.js
│ ├─ print_station_express.js
│ └─ print_computer.js
├─ 开放平台与接口
│ ├─ api_app.js
│ ├─ qimen_app.js
│ ├─ qimen_log.js
│ ├─ platform.js
│ ├─ platform_setting.js
│ └─ interface_type.js
└─ 文件、日志与国际化
├─ file.js
├─ file_reference.js
├─ operation_log.js
├─ i18n_key.js
└─ i18n_translation.js
```
## 3. 关键说明
### 3.1 动态分表模型
- order_delivery_factory.js
- 负责按 warehouse 维度动态创建/获取发货单模型。
- order_items_factory.js
- 负责按 warehouse 维度动态创建/获取订单商品模型。
说明:
- 这两个文件不是普通静态 Sequelize 定义文件,而是动态模型工厂能力。
### 3.2 典型关联模型
- fast_where.js
- 自关联: parent/children。
- location_zone.js
- 自关联 + 与 Store、LocationSpace 的关联。
- i18n_translation.js
- 关联 i18n_key。
- prohibited_type.js
- 关联 Store、StockWarehouse。
- stock_barcode.js
- 关联 StockWarehouse。
### 3.3 命名现状观察
- define 名称存在 snake_case 与 PascalCase 混用。
- 部分模型文件命名与 define 名称不完全一致。
- 后续需结合 model_naming_standard 做统一收敛。
## 4. 后续维护规则
- 每次新增/删除/重命名 model 文件后,需同步更新本文件。
- 每次新增/调整关联后,需同步更新本文件的关键说明章节。

View File

@ -1,52 +0,0 @@
# model_association_inventory
Updated: 2026-03-22
Source: app/model/*.js
| key | file | associations |
| --- | --- | --- |
| account_platform_active | app/model/account_platform_active.js | - |
| account_store_employee | app/model/account_store_employee.js | - |
| account | app/model/account.js | - |
| api_app | app/model/api_app.js | - |
| employee_role | app/model/employee_role.js | - |
| entry_items | app/model/entry_items.js | - |
| entry_order | app/model/entry_order.js | - |
| fast_where | app/model/fast_where.js | belongsTo->FastWhere, hasMany->FastWhere |
| file_reference | app/model/file_reference.js | - |
| file | app/model/file.js | - |
| i18n_key | app/model/i18n_key.js | - |
| i18n_translation | app/model/i18n_translation.js | belongsTo->I18nKey |
| interface_type | app/model/interface_type.js | - |
| location_space | app/model/location_space.js | - |
| location_type | app/model/location_type.js | belongsTo->Store |
| location_zone | app/model/location_zone.js | belongsTo->LocationZone, hasMany->LocationZone, belongsTo->Store, hasMany->LocationSpace |
| operation_log | app/model/operation_log.js | - |
| order_delivery_factory | app/model/order_delivery_factory.js | - |
| order_delivery | app/model/order_delivery.js | - |
| order_items_factory | app/model/order_items_factory.js | - |
| order_items | app/model/order_items.js | - |
| permission | app/model/permission.js | - |
| platform_setting | app/model/platform_setting.js | - |
| platform | app/model/platform.js | - |
| print_computer | app/model/print_computer.js | - |
| print_item | app/model/print_item.js | - |
| print_record | app/model/print_record.js | - |
| print_station_express | app/model/print_station_express.js | - |
| print_stations | app/model/print_stations.js | - |
| print_template | app/model/print_template.js | - |
| prohibited_type | app/model/prohibited_type.js | belongsTo->Store, hasMany->StockWarehouse |
| qimen_app | app/model/qimen_app.js | - |
| qimen_log | app/model/qimen_log.js | - |
| receiving_detail | app/model/receiving_detail.js | - |
| receiving | app/model/receiving.js | - |
| role_permission | app/model/role_permission.js | - |
| role | app/model/role.js | - |
| stock_barcode | app/model/stock_barcode.js | belongsTo->StockWarehouse |
| stock_store | app/model/stock_store.js | - |
| stock_unit | app/model/stock_unit.js | - |
| stock_warehouse | app/model/stock_warehouse.js | - |
| storage | app/model/storage.js | - |
| store_join | app/model/store_join.js | - |
| store_warehouse | app/model/store_warehouse.js | - |
| store | app/model/store.js | - |

View File

@ -1,105 +0,0 @@
# model_boundary_rules
更新时间: 2026-03-23
适用范围: app/model/**/*.js
目标: 约束 model 层仅承担数据映射与轻量领域行为,避免业务编排回流到模型层。
## 1. 当前盘点结果(阶段 5.3)
- hooks:
- app/model/entry_items.js
- EntryItems.beforeSave
- EntryItems.beforeUpdate
- scopes:
- app/model/print_item.js
- tableFields
- groupFields
- active
- byBusiness
- byPlatform
- virtual fields:
- 当前未检出 DataTypes.VIRTUAL / VIRTUAL 字段定义。
结论:
- 目前模型层 hooks/scopes 使用量较低,适合在当前阶段一次性固化边界规则。
## 2. 模型层职责边界
模型层允许:
- 表结构映射(字段、索引、注释、主键、表名映射)。
- 关联定义(belongsTo/hasMany/hasOne/belongsToMany)与关联语义辅助。
- 轻量实例行为(如 isEnabled/isExpired/getProgress 等纯实例判断)。
- 与单行数据一致性相关的同步校验(例如数量非负、上下限关系)。
模型层禁止:
- 跨表业务编排(批量流转、聚合统计、分配策略、权限树组装)。
- 事务边界控制(begin/commit/rollback)与重试策略。
- 外部副作用(调用第三方接口、写 Redis、发消息、发通知)。
- 依赖请求上下文(ctx、当前登录人、租户动态鉴权)。
## 3. Hooks 规则
允许场景:
- 单行数据写入前的确定性校验。
- 无 I/O 的轻量数据规整(例如 trim、默认值兜底)。
禁止场景:
- hook 中查询其他 model 决定业务分支。
- hook 中进行跨记录批处理或库存/权限编排。
- hook 中访问 service、http、cache、mq。
实现要求:
- 必须保持幂等与可重复执行安全。
- 必须是低成本逻辑,避免在热路径引入重查询。
- 错误信息聚焦数据约束,不承载业务流程语义。
## 4. Scopes 规则
允许场景:
- 静态筛选片段复用(状态、业务类型、平台等)。
- 参数化但纯查询片段的 where 条件构造。
禁止场景:
- 将权限判断或业务流程分支下沉到 scope。
- 在 scope 中拼装复杂 include 链并耦合排序/分页策略。
- 在 scope 中引入时间窗口策略或上下文依赖(如当前用户、当前 project)。
实现要求:
- scope 输出应稳定、可预期、可独立单测。
- 命名必须体现过滤语义,不使用模糊命名。
## 5. Virtual Fields 规则
允许场景:
- 展示层只读衍生值(字段拼接、标签映射、轻量格式化)。
禁止场景:
- virtual getter 内进行数据库查询或异步调用。
- 承载鉴权、状态流转或可写业务语义。
实现要求:
- 明确只读语义,不作为持久化字段参与写入。
- 若需要跨表推导,改由 service 返回 DTO 字段。
## 6. 现有代码归属说明
- app/model/entry_items.js hooks 保留原因:
- 仅执行已收货数量与计划数量的单行一致性校验。
- 未引入跨表查询、事务或副作用,符合模型边界。
- app/model/print_item.js scopes 保留原因:
- 仅复用静态筛选条件,不承载业务编排。
- 范围清晰,可作为查询片段复用。
## 7. 变更准入清单(新增/修改 model 时必须检查)
- 是否引入了跨表编排逻辑?若是,必须移至 app/service/systems/*。
- 是否引入了事务控制?若是,必须移至 service。
- 是否新增 hook 且包含 I/O?若是,不允许合入。
- 是否新增 scope 且耦合业务流程/鉴权?若是,不允许合入。
- 是否新增 virtual 并依赖查询/异步?若是,不允许合入。
## 8. 与阶段计划的映射
- 阶段 5.3: 已完成(盘点 + 规则固化)。
- 阶段 5.4: 基于本文件持续执行审查,作为后续模型改动的门禁依据。

View File

@ -1,292 +0,0 @@
# model_cleanup_list
更新时间: 2026-03-23
阶段: 5.4 模型边界规则固化与门禁脚本接入(已执行)
## 1. 盘点结论
- 扫描范围: app/model/**/*.js
- 检出方法总数: 102(实例 + 静态)
- 高优先候选(应迁移到 service): 24
- 低风险可移除候选(当前未发现业务调用): 18
- 保留在模型层(轻量领域判断/展示映射): 22
说明:
- 本次调用扫描采用“静态方法名精确匹配”策略(Model.method(...))。
- 对“应迁移”项,目标是把跨表编排、状态机、批量事务、库存分配等逻辑从 model 剥离到 systems service。
## 2. 第一批应迁移(P1)
### 2.1 入库单聚合与状态流转
- 文件: app/model/entry_order.js
- 候选方法:
- findByOrderCode
- findByStatus
- getStatsByWarehouse
- updateSyncStatus
- updateOrderStatus
- calculateReceivedQuantities
- 迁移目标:
- app/service/systems/entry_order.js
- 原因:
- 含分页查询、跨表 include、状态流转约束、聚合统计,属于业务编排而非数据映射。
### 2.2 入库明细批量更新与进度汇总
- 文件: app/model/entry_items.js
- 候选方法:
- batchUpdateReceived
- getOrderProgress
- 迁移目标:
- app/service/systems/entry_order.js(或 app/service/systems/storage/receiving.js)
- 原因:
- 含事务控制、批量更新和跨记录校验,属于服务层职责。
### 2.3 库存分配/锁定编排
- 文件: app/model/storage.js
- 候选方法:
- updateQuantity
- lockQuantity
- unlockQuantity
- allocateQuantity
- getStockSummary
- getSpaceUsage
- findByStockAndBatch
- findBySpace
- findAvailableByWarehouse
- findExpiringSoon
- 迁移目标:
- app/service/systems/stock_store.js
- app/service/systems/storage/receiving.js
- 原因:
- 涉及库存扣减/锁定语义、聚合统计和业务筛选,属于库存域服务。
### 2.4 角色权限写入与查询编排
- 文件: app/model/role.js
- 候选方法:
- assignPermissions
- getPermissionTree
- getPermissionIds
- 文件: app/model/role_permission.js
- 候选方法:
- bulkAssign
- clearRolePermissions
- getRolePermissions
- hasPermission
- 迁移目标:
- app/service/systems/auth/user.js
- 新增 app/service/systems/auth/role_permission.js(推荐)
- 原因:
- 包含权限关系写操作、树构建和权限判定,应集中在鉴权服务边界。
### 2.5 商家数据校验与查询助手
- 文件: app/model/store.js
- 候选方法:
- validateStoreData
- checkCompanyNameExists
- findByAccountId
- findAllEnabled
- findAllWarehouses
- 迁移目标:
- app/service/systems/store.js
- 原因:
- 请求参数校验和查询策略属于服务层,不应下沉到 model。
## 3. 可移除候选(P2,先验证后删)
- 已执行(第一批):
- app/model/api_app.js: `findByAppKey`、`findByQimenConfig`(已删除)
- app/model/interface_type.js: `findByCode`、`findEnabled`(已删除)
- app/model/print_item.js: `getGroupFields`、`getTableConfigs`(已删除)
- 门禁结果: compare mismatch=0,generated regression + smoke=14 passing
- app/model/i18n_translation.js:
- getTranslation
- batchGetTranslations
- getProjectTranslations
- upsertTranslation
- getUntranslated
- app/model/interface_type.js:
- findByCode
- findEnabled
- app/model/print_item.js:
- getGroupFields
- getTableConfigs
- app/model/api_app.js:
- findByAppKey
- findByQimenConfig
- app/model/stock_store.js:
- findByItemCode
- findByStore
说明:
- 上述方法本轮未检出业务层调用,建议先完成一次“删除前引用复核”再执行清理。
## 4. 保留在模型层(P3)
建议保留:
- 轻量实例判断(isEnabled/isHidden/isExpired 等)。
- 纯格式/展示映射(getTypeName/getRoleTypeName/getScopeName)。
- 与关联语义绑定的 include 构造器(StoreWarehouse.buildStoreStockInclude)。
## 5. 阶段状态(截至 2026-03-23)
1. 已完成 P1 四组迁移(EntryOrder/EntryItems、Storage、Role/RolePermission、Store)到 service。
2. 已完成 P2 第二批清理(I18nTranslation / StockStore),并通过门禁。
3. 已完成 5.3:完成 hooks/scopes/virtual fields 全量盘点并形成规则。
4. 已完成 5.4:新增可执行门禁脚本并接入 npm/CI。
## 6. 已执行(P2 第二批)
- 执行时间: 2026-03-23
- 删除范围:
- app/model/i18n_translation.js
- app/model/stock_store.js
- 删除方法:
- I18nTranslation.getTranslation
- I18nTranslation.batchGetTranslations
- I18nTranslation.getProjectTranslations
- I18nTranslation.upsertTranslation
- I18nTranslation.getUntranslated
- StockStore.findByItemCode
- StockStore.findByStore
- 门禁结果:
- compare mismatch=0
- generated regression=8 passing
- smoke=6 passing
- tests=14 passing
## 7. 已执行(P1 第一组)
- 执行时间: 2026-03-23
- 迁移范围:
- app/model/entry_order.js
- app/model/entry_items.js
- app/service/systems/entry_order.js
- 迁移方法:
- EntryOrder.findByOrderCode
- EntryOrder.findByStatus
- EntryOrder.getStatsByWarehouse
- EntryOrder.updateSyncStatus
- EntryOrder.updateOrderStatus
- EntryOrder.calculateReceivedQuantities
- EntryItems.batchUpdateReceived
- EntryItems.getOrderProgress
- 门禁结果:
- compare mismatch=0
- generated regression=8 passing
- smoke=6 passing
- tests=14 passing
## 8. 已执行(P1 第二组)
- 执行时间: 2026-03-23
- 迁移范围:
- app/model/storage.js
- app/service/systems/storage/index.js
- 迁移方法:
- Storage.findByStockAndBatch
- Storage.findBySpace
- Storage.findAvailableByWarehouse
- Storage.findExpiringSoon
- Storage.updateQuantity
- Storage.lockQuantity
- Storage.unlockQuantity
- Storage.allocateQuantity
- Storage.getStockSummary
- Storage.getSpaceUsage
- 门禁结果:
- compare mismatch=0
- generated regression=8 passing
- smoke=7 passing
- tests=15 passing
## 9. 已执行(P1 第三组)
- 执行时间: 2026-03-23
- 迁移范围:
- app/model/role.js
- app/model/role_permission.js
- app/service/systems/auth/role_permission.js
- 迁移方法:
- Role.assignPermissions
- Role.getPermissionTree
- Role.getPermissionIds
- RolePermission.bulkAssign
- RolePermission.clearRolePermissions
- RolePermission.getRolePermissions
- RolePermission.hasPermission
- 门禁结果:
- compare mismatch=0
- generated regression=8 passing
- smoke=7 passing
- tests=15 passing
## 10. 已执行(P1 第四组)
- 执行时间: 2026-03-23
- 迁移范围:
- app/model/store.js
- app/service/systems/store.js
- 迁移方法:
- Store.validateStoreData
- Store.checkCompanyNameExists
- Store.findByAccountId
- Store.findAllEnabled
- Store.findAllWarehouses
- 门禁结果:
- compare mismatch=0
- generated regression=8 passing
- smoke=7 passing
- tests=15 passing
## 11. 已执行(5.3 边界规范)
- 执行时间: 2026-03-23
- 扫描范围:
- app/model/**/*.js
- 扫描结果:
- hooks: 2 处(EntryItems.beforeSave / EntryItems.beforeUpdate)
- scopes: 1 处定义(PrintItem.scopes)
- virtual fields: 0
- 产出文档:
- model_boundary_rules.md
- 执行结论:
- 现有 hooks/scopes 均符合“单行一致性校验/静态筛选片段”边界。
- 后续新增或修改模型逻辑时,按 model_boundary_rules.md 作为合入门禁。
## 12. 已执行(5.4 门禁脚本验证)
- 执行时间: 2026-03-23
- 执行命令:
- npm run check:model-boundary
- 结果摘要:
- [MODEL-BOUNDARY] files=45
- [MODEL-BOUNDARY] hooks=2
- [MODEL-BOUNDARY] scopeFiles=1
- [MODEL-BOUNDARY] virtualLines=0
- [MODEL-BOUNDARY] PASS
- 结论:
- 模型边界检查脚本可稳定执行,已具备本地与 CI 统一门禁能力。
## 13. 已执行(5.4 门禁固化)
- 执行时间: 2026-03-23
- 新增脚本:
- script/model-boundary-check.cjs
- 覆盖规则:
- 禁止 model 直接调用 service
- 禁止 model 外部 HTTP 调用
- 禁止 model 读写 Redis/缓存
- 禁止 model 通过 ctx.model 进行跨模型编排
- 禁止 model 定义事务控制逻辑
- hooks/scopes/virtual 使用 allowlist 准入
- 接入方式:
- npm run check:model-boundary
- npm run ci(已串联)
- 执行结论:
- 模型层边界已具备自动化门禁能力,后续新增越界代码可在本地与 CI 及时阻断。

View File

@ -1,53 +0,0 @@
# model_inventory
Updated: 2026-03-22
Source: app/model/*.js
Count: 45
| key | file | defineName | tableName | kind |
| --- | --- | --- | --- | --- |
| account_platform_active | app/model/account_platform_active.js | account_platform_active | wms_account_platform_active | Model |
| account_store_employee | app/model/account_store_employee.js | wms_account_store_employee | wms_account_store_employee | Model |
| account | app/model/account.js | account | wms_account | Model |
| api_app | app/model/api_app.js | api_app | wms_api_app | Model |
| employee_role | app/model/employee_role.js | employee_role | wms_employee_role | Model |
| entry_items | app/model/entry_items.js | wms_entry_items | wms_entry_items | Model |
| entry_order | app/model/entry_order.js | wms_entry_order | wms_entry_order | Model |
| fast_where | app/model/fast_where.js | fast_where | wms_fast_where | Model |
| file_reference | app/model/file_reference.js | wms_file_reference | wms_file_reference | Model |
| file | app/model/file.js | wms_file | wms_file | Model |
| i18n_key | app/model/i18n_key.js | wms_i18n_key | wms_i18n_keys | Model |
| i18n_translation | app/model/i18n_translation.js | wms_i18n_translation | wms_i18n_translations | Model |
| interface_type | app/model/interface_type.js | interface_type | wms_interface_type | Model |
| location_space | app/model/location_space.js | wms_location_space | wms_location_space | Model |
| location_type | app/model/location_type.js | location_type | wms_location_type | Model |
| location_zone | app/model/location_zone.js | wms_location_zone | wms_location_zone | Model |
| operation_log | app/model/operation_log.js | operation_log | wms_operation_log | Model |
| order_delivery_factory | app/model/order_delivery_factory.js | - | - | Factory |
| order_delivery | app/model/order_delivery.js | order_delivery | wms_order_delivery | Model |
| order_items_factory | app/model/order_items_factory.js | - | - | Factory |
| order_items | app/model/order_items.js | wms_order_items | wms_order_items | Model |
| permission | app/model/permission.js | permission | wms_permission | Model |
| platform_setting | app/model/platform_setting.js | platform_setting | wms_platfrom_setting | Model |
| platform | app/model/platform.js | platform | wms_platform | Model |
| print_computer | app/model/print_computer.js | print_computer | wms_print_computer | Model |
| print_item | app/model/print_item.js | print_item | wms_print_items | Model |
| print_record | app/model/print_record.js | PrintRecord | wms_print_record | Model |
| print_station_express | app/model/print_station_express.js | print_station_express | wms_print_station_express | Model |
| print_stations | app/model/print_stations.js | print_stations | wms_print_stations | Model |
| print_template | app/model/print_template.js | print_template | wms_print_template | Model |
| prohibited_type | app/model/prohibited_type.js | prohibitedType | wms_prohibited_type | Model |
| qimen_app | app/model/qimen_app.js | qimen_app | wms_qimen_apps | Model |
| qimen_log | app/model/qimen_log.js | qimen_log | wms_qimen_log | Model |
| receiving_detail | app/model/receiving_detail.js | wms_receiving_detail | wms_receiving_detail | Model |
| receiving | app/model/receiving.js | wms_receiving | wms_receiving | Model |
| role_permission | app/model/role_permission.js | role_permission | wms_role_permission | Model |
| role | app/model/role.js | role | wms_role | Model |
| stock_barcode | app/model/stock_barcode.js | stock_barcodes | wms_stock_barcodes | Model |
| stock_store | app/model/stock_store.js | stock_store | wms_stock_store | Model |
| stock_unit | app/model/stock_unit.js | wms_stock_unit | wms_stock_unit | Model |
| stock_warehouse | app/model/stock_warehouse.js | stock_warehouse | wms_stock_warehouse | Model |
| storage | app/model/storage.js | wms_storage | wms_storage | Model |
| store_join | app/model/store_join.js | StoreJoin | wms_store_join | Model |
| store_warehouse | app/model/store_warehouse.js | store_warehouse | wms_store_warehouse | Model |
| store | app/model/store.js | store | wms_store | Model |

View File

@ -1,184 +0,0 @@
# Model 命名规范
更新时间: 2026-03-22
适用范围: app/model、app/service、app/controller 中的 app.model / ctx.model 调用
## 1. 目标
- 统一 model 文件名、运行时 key、defineName、tableName、关联 alias 的命名规则。
- 将“可直接收敛的风格问题”和“会影响业务语义的结构问题”拆开处理。
- 为阶段 4 的关联规范化和阶段 5 的模型能力清理提供稳定基线。
## 2. 五层命名对象
当前仓库里,单个模型至少同时存在以下 5 个命名层:
1. 文件名: app/model 下的文件名。
2. 运行时 key: 代码里通过 app.model.Xxx / ctx.model.Xxx 使用的名称。
3. defineName: Sequelize 的 app.model.define(name, attributes, options) 第一个参数。
4. tableName: options.tableName,对应数据库真实对象名。
5. alias: 关联查询里的 as 字段。
后续规范要求这 5 层职责分离,不再互相混用。
## 3. 统一规则
### 3.1 文件名
- 一律使用 snake_case。
- 文件名表达“模型职责”,不表达数据库前缀。
- 工厂模型必须以 _factory 结尾。
- 除非是稳定历史兼容项,否则不在文件名中保留 wms 前缀。
示例:
- account_store_employee.js
- platform_setting.js
- order_delivery_factory.js
### 3.2 运行时 key
- 一律使用 PascalCase。
- 运行时 key 由文件名去掉扩展名后转为 PascalCase。
- 这是 service/controller/model 之间的主兼容面,优先级高于 defineName。
- 工厂模型保留 Factory 后缀。
示例:
- account_store_employee.js -> AccountStoreEmployee
- platform_setting.js -> PlatformSetting
- order_delivery_factory.js -> OrderDeliveryFactory
### 3.3 defineName
- 静态模型的 defineName 必须与运行时 key 保持一致。
- 不再使用 snake_case、wms_ 前缀或局部 lowerCamelCase 作为 defineName。
- 动态分表模型允许在运行时使用真实 tableName 作为 defineName,但外部只允许通过工厂 key 获取,不直接在业务层引用动态 defineName。
示例:
- PlatformSetting: 正确
- platform_setting: 不再推荐
- prohibitedType: 不再推荐
- wms_account_store_employee: 不再推荐
### 3.4 tableName
- tableName 只负责映射数据库真实对象。
- 一律保持数据库现状,不因 model 命名规范化而强制修改表名。
- 物理表继续保留现有 wms_ 前缀、复数形式、历史拼写问题。
- 视图、动态分表、历史表单独记录,不纳入静态命名统一的修改范围。
示例:
- PlatformSetting -> tableName: wms_platfrom_setting
- StockBarcode -> tableName: wms_stock_barcodes
- PrintStations -> tableName: wms_print_stations
说明:
- tableName 中的历史拼写错误属于数据库治理问题,不属于本阶段命名规范化问题。
### 3.5 alias
- belongsTo / hasOne 使用 lowerCamelCase 单数。
- hasMany / belongsToMany 使用 lowerCamelCase 复数。
- alias 反映关联语义,不复用旧表名或旧模型名。
- alias 必须与真实关系一致,不能把 employee 关系继续命名为 role。
示例:
- belongsTo(Store, { as: 'store' })
- hasMany(EmployeeRole, { as: 'employeeRoles' })
- belongsTo(AccountStoreEmployee, { as: 'accountStoreEmployee' })
## 4. 兼容优先级
按风险从高到低分三类处理:
### A 类: 运行时 key 不存在或调用错误
- 必须先修。
- 这类问题会直接导致运行时取不到模型,或拿到错误关联。
- 典型例子:
- AccountStoreRole
- WmsOrderDeliveryFactory
- WmsOrderItemsFactory
### B 类: defineName 不规范但运行时可用
- 可分批修。
- 前提是 tableName 已显式声明,且不存在依赖 defineName 字符串的外部逻辑。
- 典型例子:
- platform_setting
- qimen_app
- qimen_log
- prohibitedType
- stock_barcodes
### C 类: alias 与业务语义不一致
- 必须与阶段 4 一起处理。
- 不能只改 alias 文本,需要一起核对外键、include、返回结构。
- 典型例子:
- accountStoreRoles
- accountStoreRole
- employeeRole
## 5. 仓库内落地规则
### 5.1 本项目允许保留的历史兼容项
以下项目前阶段不因“风格统一”而强制改文件名:
- print_stations.js
- 原因: 运行时大量使用 PrintStations,且 tableName 为 wms_print_stations。
- store_join.js
- 原因: 运行时与 defineName 已一致,当前主要问题不在命名层。
- order_delivery_factory.js / order_items_factory.js
- 原因: 工厂职责明确,外部兼容面稳定。
### 5.2 本项目必须执行的统一动作
- 所有静态模型的 defineName 逐步收敛到 PascalCase 运行时 key。
- 所有业务代码统一通过 ctx.model.Xxx / app.model.Xxx 的 PascalCase key 调用。
- 任何 include/as 字段都必须与当前模型关联定义一致。
- 不再新增任何带 wms 前缀的 defineName。
- 不再新增任何与真实语义不一致的 alias。
## 6. 参考示例
### 6.1 标准静态模型
- 文件名: platform_setting.js
- 运行时 key: PlatformSetting
- defineName: PlatformSetting
- tableName: wms_platfrom_setting
### 6.2 标准关联模型
- 文件名: account_store_employee.js
- 运行时 key: AccountStoreEmployee
- defineName: AccountStoreEmployee
- tableName: wms_account_store_employee
- alias:
- belongsTo(Account, { as: 'account' })
- belongsTo(Store, { as: 'store' })
- hasMany(EmployeeRole, { as: 'employeeRoles' })
### 6.3 标准工厂模型
- 文件名: order_delivery_factory.js
- 运行时 key: OrderDeliveryFactory
- 对外入口:
- ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId)
- ctx.model.OrderDeliveryFactory.getHistoryModel(warehouseId)
- 约束:
- 业务代码不直接引用动态表 defineName。
## 7. 执行边界
- 本阶段先统一标准、映射和影响面,不直接大规模改名。
- 运行时 key 修复优先于 defineName 收敛。
- alias 修复必须与关联关系校验一起推进。
- 数据库表名不在本阶段统一修改范围内。

View File

@ -1,100 +0,0 @@
# Model 重命名映射表
更新时间: 2026-03-22
来源:
- model_inventory.md
- app/model/*.js
- app/service/**/*.js
- app/controller/**/*.js
## 1. 使用说明
- 本表只记录阶段 3 已确认的命名规范化项。
- 变更级别分为 4 类:
- P0-调用修复: 现有代码引用错误或运行时 key 不存在,必须先修。
- P1-defineName 收敛: 只调整 defineName,不动文件名和 tableName。
- P2-alias 收敛: 需要和关联定义一起调整。
- 保持不动: 暂不建议改动。
## 2. P0: 必须先修的运行时调用
| 当前调用/命名 | 建议标准名 | 变更级别 | 原因 | 备注 |
| --- | --- | --- | --- | --- |
| WmsOrderDeliveryFactory | OrderDeliveryFactory | P0-调用修复 | 仓库内主流调用均为 OrderDeliveryFactory,当前写法与文件名不匹配 | 先修 app/service/apiMethods/test.js |
| WmsOrderItemsFactory | OrderItemsFactory | P0-调用修复 | 仓库内主流调用均为 OrderItemsFactory,当前写法与文件名不匹配 | 先修 app/service/apiMethods/test.js |
| AccountStoreRole | AccountStoreEmployee 或补回独立模型 | P0-调用修复 | 仓库内无 account_store_role.js,且当前表结构已落到 account_store_employee + employee_role | 需要先确认目标数据关系 |
| accountStoreRole | accountStoreEmployee | P0-调用修复 | AccountPlatformActive 当前关联 alias 为 accountStoreEmployee,service 仍按 accountStoreRole 取值 | 要与 include 返回结构一起改 |
## 3. P1: defineName 收敛为运行时 key
以下项优先采用“只改 defineName,不改文件名、不改 tableName”的方式收敛。
| 文件 | 当前运行时 key | 当前 defineName | 建议 defineName | 变更级别 |
| --- | --- | --- | --- | --- |
| app/model/account_platform_active.js | AccountPlatformActive | account_platform_active | AccountPlatformActive | P1-defineName 收敛 |
| app/model/account_store_employee.js | AccountStoreEmployee | wms_account_store_employee | AccountStoreEmployee | P1-defineName 收敛 |
| app/model/account.js | Account | account | Account | P1-defineName 收敛 |
| app/model/api_app.js | ApiApp | api_app | ApiApp | P1-defineName 收敛 |
| app/model/employee_role.js | EmployeeRole | employee_role | EmployeeRole | P1-defineName 收敛 |
| app/model/entry_items.js | EntryItems | wms_entry_items | EntryItems | P1-defineName 收敛 |
| app/model/entry_order.js | EntryOrder | wms_entry_order | EntryOrder | P1-defineName 收敛 |
| app/model/fast_where.js | FastWhere | fast_where | FastWhere | P1-defineName 收敛 |
| app/model/file_reference.js | FileReference | wms_file_reference | FileReference | P1-defineName 收敛 |
| app/model/file.js | File | wms_file | File | P1-defineName 收敛 |
| app/model/i18n_key.js | I18nKey | wms_i18n_key | I18nKey | P1-defineName 收敛 |
| app/model/i18n_translation.js | I18nTranslation | wms_i18n_translation | I18nTranslation | P1-defineName 收敛 |
| app/model/interface_type.js | InterfaceType | interface_type | InterfaceType | P1-defineName 收敛 |
| app/model/location_space.js | LocationSpace | wms_location_space | LocationSpace | P1-defineName 收敛 |
| app/model/location_type.js | LocationType | location_type | LocationType | P1-defineName 收敛 |
| app/model/location_zone.js | LocationZone | wms_location_zone | LocationZone | P1-defineName 收敛 |
| app/model/operation_log.js | OperationLog | operation_log | OperationLog | P1-defineName 收敛 |
| app/model/order_delivery.js | OrderDelivery | order_delivery | OrderDelivery | P1-defineName 收敛 |
| app/model/order_items.js | OrderItems | wms_order_items | OrderItems | P1-defineName 收敛 |
| app/model/permission.js | Permission | permission | Permission | P1-defineName 收敛 |
| app/model/platform_setting.js | PlatformSetting | platform_setting | PlatformSetting | P1-defineName 收敛 |
| app/model/platform.js | Platform | platform | Platform | P1-defineName 收敛 |
| app/model/print_computer.js | PrintComputer | print_computer | PrintComputer | P1-defineName 收敛 |
| app/model/print_item.js | PrintItem | print_item | PrintItem | P1-defineName 收敛 |
| app/model/print_station_express.js | PrintStationExpress | print_station_express | PrintStationExpress | P1-defineName 收敛 |
| app/model/print_stations.js | PrintStations | print_stations | PrintStations | P1-defineName 收敛 |
| app/model/print_template.js | PrintTemplate | print_template | PrintTemplate | P1-defineName 收敛 |
| app/model/prohibited_type.js | ProhibitedType | prohibitedType | ProhibitedType | P1-defineName 收敛 |
| app/model/qimen_app.js | QimenApp | qimen_app | QimenApp | P1-defineName 收敛 |
| app/model/qimen_log.js | QimenLog | qimen_log | QimenLog | P1-defineName 收敛 |
| app/model/receiving_detail.js | ReceivingDetail | wms_receiving_detail | ReceivingDetail | P1-defineName 收敛 |
| app/model/receiving.js | Receiving | wms_receiving | Receiving | P1-defineName 收敛 |
| app/model/role_permission.js | RolePermission | role_permission | RolePermission | P1-defineName 收敛 |
| app/model/role.js | Role | role | Role | P1-defineName 收敛 |
| app/model/stock_barcode.js | StockBarcode | stock_barcodes | StockBarcode | P1-defineName 收敛 |
| app/model/stock_store.js | StockStore | stock_store | StockStore | P1-defineName 收敛 |
| app/model/stock_unit.js | StockUnit | wms_stock_unit | StockUnit | P1-defineName 收敛 |
| app/model/stock_warehouse.js | StockWarehouse | stock_warehouse | StockWarehouse | P1-defineName 收敛 |
| app/model/storage.js | Storage | wms_storage | Storage | P1-defineName 收敛 |
| app/model/store_warehouse.js | StoreWarehouse | store_warehouse | StoreWarehouse | P1-defineName 收敛 |
| app/model/store.js | Store | store | Store | P1-defineName 收敛 |
## 4. 保持不动或低优先级处理项
| 文件 | 当前运行时 key | 当前 defineName | 建议 | 说明 |
| --- | --- | --- | --- | --- |
| app/model/order_delivery_factory.js | OrderDeliveryFactory | 动态 tableName | 保持不动 | 工厂模型,不参与静态 defineName 收敛 |
| app/model/order_items_factory.js | OrderItemsFactory | 动态 tableName | 保持不动 | 工厂模型,不参与静态 defineName 收敛 |
| app/model/print_record.js | PrintRecord | PrintRecord | 保持不动 | 已符合标准 |
| app/model/store_join.js | StoreJoin | StoreJoin | 保持不动 | 已符合标准 |
## 5. P2: alias 收敛候选
| 位置 | 当前 alias | 建议 alias | 变更级别 | 说明 |
| --- | --- | --- | --- | --- |
| app/model/account.js | accountStoreRoles | accountStoreEmployees | P2-alias 收敛 | 当前关联对象实际为 AccountStoreEmployee |
| app/model/account_platform_active.js | accountStoreEmployee | accountStoreEmployee | 保持 | 当前 alias 合理,问题在 service 调用侧 |
| app/model/account_store_employee.js | employeeRole | employeeRoles | P2-alias 收敛 | hasMany 建议使用复数 |
| app/model/store.js | accountStoreEmployee | accountStoreEmployees | P2-alias 收敛 | hasMany 建议使用复数 |
| app/model/role.js | employeeRole | employeeRoles | P2-alias 收敛 | hasMany 建议使用复数 |
## 6. 执行顺序建议
1. 先修 P0 调用错误,保证所有 ctx.model / app.model 均能拿到正确对象。
2. 再做 P1 defineName 收敛,限定在显式声明了 tableName 的静态模型。
3. 最后做 P2 alias 收敛,并与阶段 4 的关联核对同步执行。

View File

@ -1,168 +0,0 @@
# Model 命名影响评估报告
更新时间: 2026-03-22
范围:
- app/model/*.js
- app/service/**/*.js
- app/controller/**/*.js
## 1. 结论摘要
当前命名问题分成两层:
1. 真正会影响运行的调用错误。
2. 还能运行,但会持续制造理解成本和后续重构风险的 defineName/alias 漂移。
本轮确认的最高优先级风险有 3 个:
### 1.1 AccountStoreRole 是仓库内不存在的运行时 key
- 代码大量使用 ctx.model.AccountStoreRole。
- app/model 下没有对应的 account_store_role.js。
- 现有 schema 已落到 AccountStoreEmployee + EmployeeRole 两层关系。
- 这不是单纯命名风格问题,而是“旧关系名残留到新模型结构”的兼容断层。
### 1.2 动态分表工厂存在一组错误调用名
- 仓库主流调用是 OrderDeliveryFactory / OrderItemsFactory。
- 仅 app/service/apiMethods/test.js 仍在使用 WmsOrderDeliveryFactory / WmsOrderItemsFactory。
- 这会导致测试/调试路径与正式业务路径使用不同的模型入口。
### 1.3 alias 已经切到 employee 语义,但 service 仍按 role 语义取值
- app/model/account_platform_active.js 中 alias 是 accountStoreEmployee。
- 但 app/service/systems/account_platform.js 仍按 accountStoreRole 进行 include 和结果读取。
- 这说明 model 层与 service 层对同一关系的语义认知已经分叉。
## 2. 关键证据
### 2.1 不存在的 model key: AccountStoreRole
受影响位置:
- app/service/systems/account_platform.js:21
- app/service/systems/account_platform.js:102
- app/service/systems/account_platform.js:169
- app/service/systems/account_platform.js:226
- app/service/systems/account_platform.js:321
- app/service/systems/store.js:464
- app/service/systems/store.js:679
- app/service/systems/store.js:690
- app/model/role.js:151
现状说明:
- app/model/account_store_employee.js:6 定义的是 AccountStoreEmployee,表为 wms_account_store_employee。
- app/model/account_store_employee.js:82-99 说明当前关系是 AccountStoreEmployee -> EmployeeRole -> Role。
- app/model/account_platform_active.js:79-86 已把激活关系关联到 AccountStoreEmployee。
风险判断:
- 如果继续沿用 AccountStoreRole,后续关联收敛会同时破坏 include、字段读取、缓存结构与返回结构。
- 该问题必须在正式改 defineName 之前先做数据关系确认。
建议动作:
1. 先确认“平台激活”想绑定的是员工记录还是员工-角色明细。
2. 若绑定员工记录,则将 AccountStoreRole 全量替换为 AccountStoreEmployee,并改造 role 读取路径。
3. 若绑定员工-角色明细,则需要新增独立模型,而不是继续使用幽灵 key。
### 2.2 动态工厂 key 调用漂移
正常调用样本:
- app/service/systemMethods/order.js:22-23
- app/service/systems/delivery_order.js:14
- app/service/systems/delivery_order.js:311
- app/service/qimenMethods/deliveryorder.js:7-8
异常调用样本:
- app/service/apiMethods/test.js:50
- app/service/apiMethods/test.js:51
风险判断:
- 正式链路与调试链路的 model 入口不一致,后续如果只修主链路,测试链路会继续漂移。
- 这是低成本高收益修复项,应优先纳入第一批代码修正。
建议动作:
1. 将 WmsOrderDeliveryFactory 改为 OrderDeliveryFactory。
2. 将 WmsOrderItemsFactory 改为 OrderItemsFactory。
3. 回归验证动态表 current/history 获取能力是否一致。
### 2.3 alias 与语义漂移
证据位置:
- app/model/account.js:139 使用 alias accountStoreRoles,但实际模型是 AccountStoreEmployee。
- app/model/account_platform_active.js:84 使用 alias accountStoreEmployee。
- app/model/account_store_employee.js:95 使用 hasMany(EmployeeRole, { as: 'employeeRole' })。
- app/model/role.js:171 使用 hasMany(EmployeeRole, { as: 'employeeRole' })。
- app/service/systems/account_platform.js:102-136 仍按 accountStoreRole 读取嵌套字段。
风险判断:
- 当前 alias 命名混合了“员工关系”和“角色关系”两种语义。
- 若不先统一语义,后续只做名字替换会把问题从命名层转移到数据层。
建议动作:
1. 阶段 4 先梳理 employee、role、store 三者的真实关系。
2. hasMany alias 收敛为复数形式,如 employeeRoles、accountStoreEmployees。
3. service 层返回结构与 include 路径同步改名,避免只改 model 不改消费方。
## 3. defineName 漂移影响
以下问题当前通常不会直接导致运行失败,但会持续造成阅读成本与重构误判:
| 文件 | 证据 | 当前情况 | 风险 |
| --- | --- | --- | --- |
| app/model/platform_setting.js | :7 | defineName 为 platform_setting,运行时 key 为 PlatformSetting | 阅读时容易误以为 key 与 defineName 同名 |
| app/model/qimen_app.js | :6 | defineName 为 qimen_app,运行时 key 为 QimenApp | service 调用与模型定义风格分裂 |
| app/model/qimen_log.js | :8 | defineName 为 qimen_log,运行时 key 为 QimenLog | 日志模型定位成本高 |
| app/model/account_store_employee.js | :6 | defineName 为 wms_account_store_employee,运行时 key 为 AccountStoreEmployee | 将表名语义混入模型名 |
| app/model/stock_barcode.js | :6 | defineName 为 stock_barcodes,运行时 key 为 StockBarcode | 单复数与 key 同时漂移 |
| app/model/prohibited_type.js | :6 | defineName 为 prohibitedType,运行时 key 为 ProhibitedType | lowerCamelCase 与 PascalCase 混用 |
| app/model/print_stations.js | :5 | defineName 为 print_stations,运行时 key 为 PrintStations | 虽可运行,但风格不统一 |
影响判断:
- 新增 include、调试 SQL、追踪关联时,很容易把 defineName、key、tableName 当成同一件事。
- 后续如果继续新增 snake_case defineName,会放大维护面。
建议动作:
1. 先完成 P0 调用修复。
2. 再按 model_rename_map.md 分批将 defineName 收敛到 PascalCase。
3. 每次改 defineName 后,回归关联加载与 SQL 日志输出,确认未引入隐式副作用。
## 4. 稳定项与例外项
以下命名虽然不完全理想,但当前不建议仅因风格而改动:
- app/model/print_record.js
- defineName 已为 PrintRecord,运行时 key 与之保持一致。
- app/model/store_join.js
- defineName 已为 StoreJoin,当前问题主要不在命名层。
- app/model/order_delivery_factory.js
- 工厂模型对外 key 稳定,重点是调用方统一。
- app/model/order_items_factory.js
- 工厂模型对外 key 稳定,重点是调用方统一。
- app/model/print_stations.js
- 文件名和表名均为复数,当前更适合先保留为历史兼容项,不单独改文件名。
## 5. 推荐执行顺序
1. 第一批: 修正不存在的运行时 key 和错误工厂调用名。
2. 第二批: 收敛静态模型 defineName,保持 tableName 不变。
3. 第三批: 在关联核对完成后统一 alias 和 include 路径。
4. 第四批: 更新测试、README、modelList.md、关联清单等文档。
## 6. 对后续阶段的输入
- 阶段 4 需要重点核对 AccountPlatformActive、AccountStoreEmployee、EmployeeRole、Role、Store 的外键与 include 结构。
- 阶段 5 需要顺带清理与命名漂移绑定的死代码、调试日志和旧语义变量名。
- 阶段 6 验证时必须覆盖平台激活、仓库角色分配、动态订单分表、打印链路四类高风险场景。

View File

@ -1,104 +0,0 @@
# role_permission_fk_data_cleanup_plan
更新时间: 2026-03-23
目标: 清理 role/permission 相关孤儿数据,解除 `20260323103000-align-role-permission-fk.js` 执行阻塞。
## 1. 审计现状
- `wms_role_permission.permission_id` 孤儿记录: 4 条(id: 2, 3, 6, 10)
- `wms_role.store_id` 非法哨兵值: 3 条(store_id = 0)
- 字段类型差异:
- `wms_permission.id`: `int(11)`
- `wms_role_permission.permission_id`: `bigint(20) unsigned`(迁移已处理为对齐)
## 2. 执行顺序
1. 备份孤儿数据
2. 删除 `wms_role_permission` 孤儿行
3. 规范 `wms_role.store_id = 0` 为 `NULL`(仅对可空字段)
4. 复核计数
5. 执行迁移 `20260323103000-align-role-permission-fk.js`
## 3. 推荐 SQL(先在测试环境执行)
### 3.1 备份 role_permission 孤儿行
```sql
CREATE TABLE IF NOT EXISTS wms_role_permission_orphan_backup_20260323 AS
SELECT rp.*
FROM wms_role_permission rp
LEFT JOIN wms_permission p ON p.id = rp.permission_id
WHERE p.id IS NULL;
```
### 3.2 删除 role_permission 孤儿行
```sql
DELETE rp
FROM wms_role_permission rp
LEFT JOIN wms_permission p ON p.id = rp.permission_id
WHERE p.id IS NULL;
```
### 3.3 规范 role.store_id 哨兵值
```sql
UPDATE wms_role
SET store_id = NULL
WHERE store_id = 0;
```
### 3.4 复核
```sql
SELECT 'rp_perm_orphan' AS metric, COUNT(*) AS cnt
FROM wms_role_permission rp
LEFT JOIN wms_permission p ON p.id = rp.permission_id
WHERE p.id IS NULL
UNION ALL
SELECT 'role_store_zero' AS metric, COUNT(*) AS cnt
FROM wms_role
WHERE store_id = 0;
```
## 4. 回滚思路
- 若删除孤儿行后需要回滚,可从备份表恢复:
```sql
INSERT INTO wms_role_permission (id, role_id, permission_id, created_at)
SELECT id, role_id, permission_id, created_at
FROM wms_role_permission_orphan_backup_20260323;
```
- `wms_role.store_id` 从 `0 -> NULL` 回滚需结合业务语义,不建议盲目全量回写 `0`。
## 5. 交付门禁
清洗和迁移完成后,执行:
1. `node .\\script\\method-output-regression.cjs compare`
2. `node .\\script\\tmp-generate-method-regression-test.cjs`
3. `npx egg-bin test temp/generated-tests/system.method-output.generated.test.js`
4. `npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js`
通过标准:
- compare: mismatch=0
- 回归测试: 全部通过
## 6. 执行记录(2026-03-23)
- 备份执行结果:
- `wms_role_permission_orphan_backup_20260323`: 4 行
- `wms_role_store_zero_backup_20260323`: 3 行
- 清洗执行结果:
- role_permission 孤儿删除: 4 行
- role.store_id=0 -> NULL: 3 行
- 迁移执行结果:
- `wms_role_permission.permission_id` 已对齐为 `int(11)`
- 外键 `fk_wms_role_permission_permission` 已生效
- SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`
- 门禁结果:
- method-output compare: mismatch=0
- generated regression + smoke: 14 passing

View File

@ -1,49 +0,0 @@
# rollback_plan
更新时间: 2026-03-22
## 1. 通用回滚规则
- 所有新增 migration 必须提供 down。
- 对现网已有表,down 不应默认直接 drop 整表。
- 优先回滚新增字段、索引、约束,避免误删存量数据。
- 涉及数据回填的 migration,必须保留影响范围快照或备份。
## 2. 分类型回滚策略
### 建表 migration
- 新环境可使用 dropTable 回滚。
- 现网已有表不建议通过 down 删除,应改为“标记基线 + 停止继续执行”。
### 加字段 migration
- down 使用 dropColumn。
- 执行前需确认字段不被线上代码强依赖。
### 索引 migration
- down 使用 removeIndex。
- 若为性能补丁索引,回滚前需评估查询退化风险。
### 视图 migration
- down 使用 drop view。
- 回滚前确认是否有查询依赖视图。
### 动态分表策略 migration
- 只回滚策略与模板,不批量 drop 已创建的仓库动态表。
- 已存在分表应通过单独治理,不纳入统一 down 删除范围。
## 3. 当前优先风险
- 未进入 SequelizeMeta 的 migration 不能按常规 down 处理,必须先确认其是否已在数据库中手工生效。
- order_delivery/order_items 主表与动态表结构存在差异,回滚时必须区分主表与动态表。
- 日志类表通常已有存量数据,回滚需要避免整表删除。
## 4. 建议执行前准备
- 每批 migration 执行前导出目标表结构快照。
- 若涉及数据变更,先做行数统计与影响范围确认。
- 为每批次准备单独回滚脚本,不依赖临场拼写 SQL。

View File

@ -1,93 +0,0 @@
# 根目录 Markdown 使用方与清理结果
生成时间: 2026-03-24
## 保留在根目录
- `README.md`
- 使用方: `model_todo.txt`
- 动作: 保留(项目入口文档)
- `AI_TOOLBOX.md`
- 使用方: `README.md`
- 动作: 保留(AI 协作工具箱)
- `AI_METHOD_ROUTING.md`
- 使用方: `AI_TOOLBOX.md`, `README.md`, `script/tmp-update-ai-method-routing.cjs`
- 动作: 保留(路由映射主文档)
## 迁移到 temp/docs(需要保留)
- `METHOD_OUTPUT_REGRESSION_20260322.md`
- 原使用方: `README.md`
- 新路径: `temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md`
- `SERVICE_API_CHANGE_AUDIT_20260322.md`
- 原使用方: `model_todo.txt`
- 新路径: `temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md`
- `association_eager_loading_n_plus_one_guideline.md`
- 原使用方: `association_validation_checklist.md`, `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md`
- 新路径: `temp/docs/association_eager_loading_n_plus_one_guideline.md`
- `association_fix_plan.md`
- 原使用方: `model_todo.txt`
- 新路径: `temp/docs/association_fix_plan.md`
- `association_fk_consistency_report.md`
- 原使用方: `association_validation_checklist.md`, `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md`, `temp/audit-association-fk.cjs`
- 新路径: `temp/docs/association_fk_consistency_report.md`
- `association_validation_checklist.md`
- 原使用方: `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md`
- 新路径: `temp/docs/association_validation_checklist.md`
- `migration_execution_plan.md`
- 原使用方: `model_todo.txt`
- 新路径: `temp/docs/migration_execution_plan.md`
- `migration_gap_list.md`
- 原使用方: `model_todo.txt`
- 新路径: `temp/docs/migration_gap_list.md`
- `modelList.md`
- 原使用方: `model_todo.txt`, `README.md`, `rename_impact_report.md`
- 新路径: `temp/docs/modelList.md`
- `model_association_inventory.md`
- 原使用方: `model_todo.txt`
- 新路径: `temp/docs/model_association_inventory.md`
- `model_boundary_rules.md`
- 原使用方: `model_cleanup_list.md`, `model_todo.txt`, `script/model-boundary-check.cjs`
- 新路径: `temp/docs/model_boundary_rules.md`
- `model_cleanup_list.md`
- 原使用方: `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md`
- 新路径: `temp/docs/model_cleanup_list.md`
- `model_inventory.md`
- 原使用方: `model_rename_map.md`, `model_todo.txt`
- 新路径: `temp/docs/model_inventory.md`
- `model_naming_standard.md`
- 原使用方: `model_todo.txt`
- 新路径: `temp/docs/model_naming_standard.md`
- `model_rename_map.md`
- 原使用方: `model_todo.txt`, `rename_impact_report.md`
- 新路径: `temp/docs/model_rename_map.md`
- `rename_impact_report.md`
- 原使用方: `model_todo.txt`
- 新路径: `temp/docs/rename_impact_report.md`
- `role_permission_fk_data_cleanup_plan.md`
- 原使用方: `model_todo.txt`
- 新路径: `temp/docs/role_permission_fk_data_cleanup_plan.md`
- `rollback_plan.md`
- 原使用方: `model_todo.txt`
- 新路径: `temp/docs/rollback_plan.md`
- `schema_model_gap_report.md`
- 原使用方: `model_todo.txt`
- 新路径: `temp/docs/schema_model_gap_report.md`
- `table_schema_inventory.md`
- 原使用方: `model_todo.txt`
- 新路径: `temp/docs/table_schema_inventory.md`
## 已清理(不需要)
- `tmp-order-schema-workflow.md`
- 原使用方: 无
- 动作: 已从根目录删除(历史临时流程文档)
## 引用更新范围
- `README.md`
- `model_todo.txt`
- `script/model-boundary-check.cjs`
- `temp/audit-association-fk.cjs`
所有上述文件中的旧根目录引用已替换为 `temp/docs/*` 新路径。

View File

@ -1,98 +0,0 @@
# schema_model_gap_report
Updated: 2026-03-22
## Scope
- DB source: information_schema.TABLES / COLUMNS / STATISTICS
- Model source: app/model/*.js (tableName option)
## Count
- Model files: 45
- Model with tableName: 43
- DB tables: 68
- modelOnly table count: 0
- dbOnly table count: 25
## modelOnly tables
- none
## dbOnly tables
- SequelizeMeta
- wms_account_login_log
- wms_api_log
- wms_embargo_policies
- wms_express
- wms_express_print_record
- wms_express_setting
- wms_order_delivery_100000
- wms_order_delivery_1000028
- wms_order_express
- wms_order_express_print_data
- wms_order_items_100000
- wms_order_items_1000028
- wms_order_operation
- wms_order_operation_log
- wms_order_picking
- wms_picking_strategy
- wms_platform_print_config
- wms_print_batch
- wms_print_log
- wms_printer_config
- wms_system_config
- wms_system_log
- wms_wave_batch
- wms_wave_operation_log
## Model mapping snapshot
| key | file | defineName | tableName |
| --- | --- | --- | --- |
| account | app/model/account.js | account | wms_account |
| account_platform_active | app/model/account_platform_active.js | account_platform_active | wms_account_platform_active |
| account_store_employee | app/model/account_store_employee.js | wms_account_store_employee | wms_account_store_employee |
| api_app | app/model/api_app.js | api_app | wms_api_app |
| employee_role | app/model/employee_role.js | employee_role | wms_employee_role |
| entry_items | app/model/entry_items.js | wms_entry_items | wms_entry_items |
| entry_order | app/model/entry_order.js | wms_entry_order | wms_entry_order |
| fast_where | app/model/fast_where.js | fast_where | wms_fast_where |
| file | app/model/file.js | wms_file | wms_file |
| file_reference | app/model/file_reference.js | wms_file_reference | wms_file_reference |
| i18n_key | app/model/i18n_key.js | wms_i18n_key | wms_i18n_keys |
| i18n_translation | app/model/i18n_translation.js | wms_i18n_translation | wms_i18n_translations |
| interface_type | app/model/interface_type.js | interface_type | wms_interface_type |
| location_space | app/model/location_space.js | wms_location_space | wms_location_space |
| location_type | app/model/location_type.js | location_type | wms_location_type |
| location_zone | app/model/location_zone.js | wms_location_zone | wms_location_zone |
| operation_log | app/model/operation_log.js | operation_log | wms_operation_log |
| order_delivery | app/model/order_delivery.js | order_delivery | wms_order_delivery |
| order_delivery_factory | app/model/order_delivery_factory.js | - | - |
| order_items | app/model/order_items.js | wms_order_items | wms_order_items |
| order_items_factory | app/model/order_items_factory.js | - | - |
| permission | app/model/permission.js | permission | wms_permission |
| platform | app/model/platform.js | platform | wms_platform |
| platform_setting | app/model/platform_setting.js | platform_setting | wms_platfrom_setting |
| print_computer | app/model/print_computer.js | print_computer | wms_print_computer |
| print_item | app/model/print_item.js | print_item | wms_print_items |
| print_record | app/model/print_record.js | PrintRecord | wms_print_record |
| print_station_express | app/model/print_station_express.js | print_station_express | wms_print_station_express |
| print_stations | app/model/print_stations.js | print_stations | wms_print_stations |
| print_template | app/model/print_template.js | print_template | wms_print_template |
| prohibited_type | app/model/prohibited_type.js | prohibitedType | wms_prohibited_type |
| qimen_app | app/model/qimen_app.js | qimen_app | wms_qimen_apps |
| qimen_log | app/model/qimen_log.js | qimen_log | wms_qimen_log |
| receiving | app/model/receiving.js | wms_receiving | wms_receiving |
| receiving_detail | app/model/receiving_detail.js | wms_receiving_detail | wms_receiving_detail |
| role | app/model/role.js | role | wms_role |
| role_permission | app/model/role_permission.js | role_permission | wms_role_permission |
| stock_barcode | app/model/stock_barcode.js | stock_barcodes | wms_stock_barcodes |
| stock_store | app/model/stock_store.js | stock_store | wms_stock_store |
| stock_unit | app/model/stock_unit.js | wms_stock_unit | wms_stock_unit |
| stock_warehouse | app/model/stock_warehouse.js | stock_warehouse | wms_stock_warehouse |
| storage | app/model/storage.js | wms_storage | wms_storage |
| store | app/model/store.js | store | wms_store |
| store_join | app/model/store_join.js | StoreJoin | wms_store_join |
| store_warehouse | app/model/store_warehouse.js | store_warehouse | wms_store_warehouse |

View File

@ -1,85 +0,0 @@
# table_schema_inventory
Updated: 2026-03-22
Database: wms
Object count: 70
## Summary
- Tables: 68
- Views: 2
## Objects
| object | type | engine | collation | rows | columns | pk_cols | auto_inc | index_count |
| --- | --- | --- | --- | ---: | ---: | ---: | ---: | ---: |
| SequelizeMeta | TABLE | InnoDB | utf8_unicode_ci | 7 | 1 | 1 | 0 | 2 |
| vw_warehouse_quota | VIEW | - | - | - | 5 | 0 | 0 | 0 |
| v_pick_space | VIEW | - | - | - | 44 | 0 | 0 | 0 |
| wms_account | TABLE | InnoDB | utf8mb4_general_ci | 2 | 13 | 1 | 1 | 5 |
| wms_account_login_log | TABLE | InnoDB | utf8mb4_general_ci | 108 | 7 | 1 | 1 | 2 |
| wms_account_platform_active | TABLE | InnoDB | utf8mb4_general_ci | 3 | 5 | 2 | 0 | 5 |
| wms_account_store_employee | TABLE | InnoDB | utf8mb4_general_ci | 5 | 8 | 1 | 1 | 5 |
| wms_api_app | TABLE | InnoDB | utf8mb4_unicode_ci | 4 | 22 | 1 | 1 | 6 |
| wms_api_log | TABLE | InnoDB | utf8mb4_general_ci | 421 | 10 | 1 | 1 | 1 |
| wms_embargo_policies | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 13 | 1 | 1 | 5 |
| wms_employee_role | TABLE | InnoDB | utf8mb4_general_ci | 4 | 3 | 1 | 1 | 4 |
| wms_entry_items | TABLE | InnoDB | utf8mb4_general_ci | 2 | 12 | 1 | 1 | 3 |
| wms_entry_order | TABLE | InnoDB | utf8mb4_unicode_ci | 5 | 28 | 1 | 1 | 10 |
| wms_express | TABLE | InnoDB | utf8mb4_general_ci | 0 | 2 | 1 | 0 | 1 |
| wms_express_print_record | TABLE | InnoDB | utf8mb4_general_ci | 0 | 31 | 1 | 1 | 13 |
| wms_express_setting | TABLE | InnoDB | utf8mb4_general_ci | 0 | 4 | 1 | 1 | 3 |
| wms_fast_where | TABLE | InnoDB | utf8mb4_general_ci | 38 | 9 | 1 | 1 | 1 |
| wms_file | TABLE | InnoDB | utf8mb4_unicode_ci | 5806 | 20 | 1 | 1 | 8 |
| wms_file_reference | TABLE | InnoDB | utf8mb4_unicode_ci | 8299 | 8 | 1 | 1 | 5 |
| wms_i18n_keys | TABLE | InnoDB | utf8mb4_general_ci | 182 | 10 | 1 | 1 | 4 |
| wms_i18n_translations | TABLE | InnoDB | utf8mb4_general_ci | 421 | 11 | 1 | 1 | 5 |
| wms_interface_type | TABLE | InnoDB | utf8mb4_unicode_ci | 2 | 9 | 1 | 1 | 2 |
| wms_location_space | TABLE | InnoDB | utf8mb4_general_ci | 1898 | 38 | 1 | 1 | 13 |
| wms_location_type | TABLE | InnoDB | utf8mb4_general_ci | 5 | 10 | 1 | 1 | 3 |
| wms_location_zone | TABLE | InnoDB | utf8mb4_general_ci | 20 | 30 | 1 | 1 | 10 |
| wms_operation_log | TABLE | InnoDB | utf8mb4_general_ci | 2856 | 12 | 1 | 1 | 8 |
| wms_order_delivery | TABLE | InnoDB | utf8mb4_general_ci | 0 | 54 | 1 | 1 | 4 |
| wms_order_delivery_100000 | TABLE | InnoDB | utf8mb4_general_ci | 10 | 72 | 1 | 1 | 9 |
| wms_order_delivery_1000028 | TABLE | InnoDB | utf8mb4_general_ci | 0 | 72 | 1 | 1 | 9 |
| wms_order_express | TABLE | InnoDB | utf8mb4_general_ci | 0 | 13 | 1 | 1 | 2 |
| wms_order_express_print_data | TABLE | InnoDB | utf8mb4_general_ci | 0 | 6 | 1 | 1 | 2 |
| wms_order_items | TABLE | InnoDB | utf8mb4_general_ci | 0 | 15 | 1 | 1 | 2 |
| wms_order_items_100000 | TABLE | InnoDB | utf8mb4_unicode_ci | 11 | 18 | 1 | 1 | 9 |
| wms_order_items_1000028 | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 18 | 1 | 1 | 9 |
| wms_order_operation | TABLE | InnoDB | utf8mb4_general_ci | 0 | 1 | 1 | 1 | 1 |
| wms_order_operation_log | TABLE | InnoDB | utf8mb4_general_ci | 0 | 15 | 1 | 1 | 6 |
| wms_order_picking | TABLE | InnoDB | utf8mb4_general_ci | 0 | 1 | 1 | 1 | 1 |
| wms_permission | TABLE | InnoDB | utf8mb4_general_ci | 40 | 15 | 1 | 1 | 4 |
| wms_picking_strategy | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 25 | 1 | 1 | 3 |
| wms_platform | TABLE | InnoDB | utf8mb4_general_ci | 13 | 3 | 1 | 0 | 1 |
| wms_platform_print_config | TABLE | InnoDB | utf8mb4_general_ci | 7 | 12 | 1 | 1 | 3 |
| wms_platfrom_setting | TABLE | InnoDB | utf8mb4_general_ci | 0 | 4 | 1 | 1 | 4 |
| wms_printer_config | TABLE | InnoDB | utf8mb4_general_ci | 0 | 11 | 1 | 1 | 4 |
| wms_print_batch | TABLE | InnoDB | utf8mb4_general_ci | 0 | 16 | 1 | 1 | 6 |
| wms_print_computer | TABLE | InnoDB | utf8mb4_general_ci | 0 | 4 | 1 | 1 | 1 |
| wms_print_items | TABLE | InnoDB | utf8mb4_general_ci | 39 | 24 | 1 | 1 | 5 |
| wms_print_log | TABLE | InnoDB | utf8mb4_general_ci | 0 | 12 | 1 | 1 | 5 |
| wms_print_record | TABLE | InnoDB | utf8mb4_general_ci | 277 | 13 | 1 | 1 | 6 |
| wms_print_stations | TABLE | InnoDB | utf8mb4_unicode_ci | 3 | 11 | 1 | 1 | 7 |
| wms_print_station_express | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 10 | 1 | 1 | 5 |
| wms_print_template | TABLE | InnoDB | utf8mb4_general_ci | 4 | 15 | 1 | 1 | 4 |
| wms_prohibited_type | TABLE | InnoDB | utf8mb4_unicode_ci | 13 | 9 | 1 | 1 | 4 |
| wms_qimen_apps | TABLE | InnoDB | utf8mb4_general_ci | 27 | 4 | 1 | 1 | 2 |
| wms_qimen_log | TABLE | InnoDB | utf8mb4_general_ci | 27756 | 14 | 1 | 1 | 1 |
| wms_receiving | TABLE | InnoDB | utf8mb4_unicode_ci | 43 | 25 | 1 | 1 | 9 |
| wms_receiving_detail | TABLE | InnoDB | utf8mb4_unicode_ci | 38 | 26 | 1 | 1 | 8 |
| wms_role | TABLE | InnoDB | utf8mb4_general_ci | 5 | 13 | 1 | 1 | 6 |
| wms_role_permission | TABLE | InnoDB | utf8mb4_general_ci | 72 | 4 | 1 | 1 | 4 |
| wms_stock_barcodes | TABLE | InnoDB | utf8mb4_unicode_ci | 25992 | 6 | 1 | 1 | 3 |
| wms_stock_store | TABLE | InnoDB | utf8mb4_unicode_ci | 472 | 34 | 1 | 1 | 11 |
| wms_stock_unit | TABLE | InnoDB | utf8mb4_general_ci | 11 | 4 | 1 | 1 | 3 |
| wms_stock_warehouse | TABLE | InnoDB | utf8mb4_unicode_ci | 25718 | 41 | 1 | 1 | 6 |
| wms_storage | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 20 | 1 | 1 | 8 |
| wms_store | TABLE | InnoDB | utf8mb4_unicode_ci | 121 | 20 | 1 | 1 | 5 |
| wms_store_join | TABLE | InnoDB | utf8mb4_unicode_ci | 4 | 14 | 1 | 1 | 7 |
| wms_store_warehouse | TABLE | InnoDB | utf8mb4_general_ci | 119 | 21 | 1 | 1 | 8 |
| wms_system_config | TABLE | InnoDB | utf8mb4_general_ci | 1 | 5 | 1 | 1 | 1 |
| wms_system_log | TABLE | InnoDB | utf8mb4_general_ci | 4591 | 14 | 1 | 1 | 2 |
| wms_wave_batch | TABLE | InnoDB | utf8mb4_general_ci | 0 | 20 | 1 | 1 | 5 |
| wms_wave_operation_log | TABLE | InnoDB | utf8mb4_general_ci | 0 | 11 | 1 | 1 | 5 |

View File

@ -0,0 +1,67 @@
'use strict';
const assert = require('node:assert/strict');
const {
getAuthToken,
invokeSystemMethod,
invokeGatewayMethod,
} = require('../../support/system_method_client');
const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID || 28);
describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => {
it('should bind, unbind, and bind again for ye4s user', async () => {
const { token } = await getAuthToken();
const infoRes = await invokeSystemMethod('user.info', {}, token);
assert.equal(infoRes.status, 200);
assert.equal(infoRes.body.flag, 'success');
const accountId = Number(infoRes.body?.data?.id);
assert.ok(Number.isFinite(accountId) && accountId > 0);
const bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', {
forceRefresh: true,
init: true,
}, token);
assert.equal(bindCodeRes.status, 200);
assert.equal(bindCodeRes.body.flag, 'success');
const code = String(bindCodeRes.body?.data?.code || '');
assert.ok(code.length > 10);
const bindRes1 = await invokeGatewayMethod('user.bindAccountByTempCode', {
code,
ye4s_user_id: YE4S_TEST_USER_ID,
});
assert.equal(bindRes1.status, 200);
assert.equal(bindRes1.body.flag, 'success');
assert.equal(bindRes1.body.code, 200);
assert.equal(Number(bindRes1.body?.data?.account_id), accountId);
assert.equal(Number(bindRes1.body?.data?.ye4s_user_id), YE4S_TEST_USER_ID);
assert.equal(bindRes1.body?.data?.status, 'bound');
const unbindRes = await invokeSystemMethod('user.unbindWechat', {}, token);
assert.equal(unbindRes.status, 200);
assert.equal(unbindRes.body.flag, 'success');
assert.equal(unbindRes.body.code, 200);
assert.equal(unbindRes.body?.data?.status, 'unbound');
assert.equal(Number(unbindRes.body?.data?.account_id), accountId);
const bindRes2 = await invokeGatewayMethod('user.bindAccountByTempCode', {
code,
ye4s_user_id: YE4S_TEST_USER_ID,
});
assert.equal(bindRes2.status, 200);
assert.equal(bindRes2.body.flag, 'success');
assert.equal(bindRes2.body.code, 200);
assert.equal(Number(bindRes2.body?.data?.account_id), accountId);
assert.equal(Number(bindRes2.body?.data?.ye4s_user_id), YE4S_TEST_USER_ID);
assert.equal(bindRes2.body?.data?.status, 'bound');
const verifyRes = await invokeGatewayMethod('user.getUserByTempCode', { code });
assert.equal(verifyRes.status, 200);
assert.equal(verifyRes.body.flag, 'success');
assert.equal(verifyRes.body.code, 200);
assert.equal(Number(verifyRes.body?.data?.account_id), accountId);
assert.equal(verifyRes.body?.data?.status, 'bound');
});
});

View File

@ -0,0 +1,184 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const {
getAuthToken,
invokeSystemMethod,
TOKEN_FILE,
} = require('../../support/system_method_client');
const EXTRA_HEADERS = {
platform: 'web',
project: 'all',
};
const RESERVED_EMPLOYEE_NAME = '测试工号保留';
const RETAIN_PHONE = process.env.SYSTEM_TEST_ACCOUNT_RETAIN_PHONE || '13999002888';
const RETAIN_USERNAME = process.env.SYSTEM_TEST_ACCOUNT_RETAIN_USERNAME || 'autotest_acc_mgmt_keep';
const EXISTING_FILE_ID = Number(process.env.SYSTEM_TEST_EXISTING_FILE_ID || 0);
const STATE_FILE = process.env.SYSTEM_TEST_ACCOUNT_STATE_FILE || 'temp/account-management-test-state.json';
function buildTempPhone() {
return `139${String(Date.now()).slice(-8)}`;
}
async function getUserInfo(token) {
const res = await invokeSystemMethod('user.info', {}, token, EXTRA_HEADERS);
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'success');
assert.equal(res.body.code, 200);
return res.body.data;
}
describe('test/app/controller/system.setting.account.test.js', () => {
let token = '';
let existingFileId = 0;
let tokenFileExistedBefore = false;
let retainedEmployeeId = 0;
let retainedAccountId = 0;
let tempEmployeeId = 0;
let tempAccountId = 0;
let tempPhone = '';
let tempUsername = '';
async function listAccounts() {
const res = await invokeSystemMethod('setting.account.list', {}, token, EXTRA_HEADERS);
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'success');
assert.equal(res.body.code, 200);
const list = Array.isArray(res.body.data) ? res.body.data : [];
return list;
}
async function ensureRetainedEmployee() {
const currentList = await listAccounts();
const existing = currentList.find(item => item && (item.phone === RETAIN_PHONE || item.username === RETAIN_USERNAME || item.real_name === RESERVED_EMPLOYEE_NAME));
if (existing) {
retainedEmployeeId = Number(existing.employee_id);
retainedAccountId = Number(existing.account_id);
return existing;
}
const addRes = await invokeSystemMethod('setting.account.add', {
phone: RETAIN_PHONE,
username: RETAIN_USERNAME,
password: '111111',
real_name: '测试工号预留初始化',
}, token, EXTRA_HEADERS);
assert.equal(addRes.status, 200);
assert.equal(addRes.body.flag, 'success');
assert.equal(addRes.body.code, 200);
retainedEmployeeId = Number(addRes.body?.data?.employee_id || 0);
retainedAccountId = Number(addRes.body?.data?.account_id || 0);
assert.ok(retainedEmployeeId > 0);
assert.ok(retainedAccountId > 0);
return addRes.body.data;
}
before(async () => {
tokenFileExistedBefore = fs.existsSync(TOKEN_FILE);
const auth = await getAuthToken();
token = auth.token;
const userInfo = await getUserInfo(token);
assert.ok(Number(userInfo.store_id || 0) > 0, '当前账号未识别到主体 store_id');
existingFileId = EXISTING_FILE_ID;
assert.ok(existingFileId > 0, '已有文件ID无效');
});
after(async () => {
if (!tokenFileExistedBefore && fs.existsSync(TOKEN_FILE)) {
fs.rmSync(TOKEN_FILE, { force: true });
}
});
it('error-1 should reject add when real_name is reserved name', async () => {
const res = await invokeSystemMethod('setting.account.add', {
phone: buildTempPhone(),
username: `autotest_acc_mgmt_reserved_${Date.now()}`,
real_name: RESERVED_EMPLOYEE_NAME,
}, token, EXTRA_HEADERS);
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'failure');
assert.equal(res.body.code, 400);
assert.match(String(res.body.message || ''), /保留名称/);
});
it('normal-1 should add temp employee, delete it, and keep one retained employee with avatar and final name', async () => {
const retained = await ensureRetainedEmployee();
assert.ok(Number(retained.employee_id || retainedEmployeeId) > 0);
tempPhone = buildTempPhone();
tempUsername = `autotest_acc_mgmt_tmp_${Date.now()}`;
const tempRealName = `测试工号临时_${Date.now()}`;
const addTempRes = await invokeSystemMethod('setting.account.add', {
phone: tempPhone,
username: tempUsername,
password: '111111',
real_name: tempRealName,
}, token, EXTRA_HEADERS);
assert.equal(addTempRes.status, 200);
assert.equal(addTempRes.body.flag, 'success');
assert.equal(addTempRes.body.code, 200);
tempEmployeeId = Number(addTempRes.body?.data?.employee_id || 0);
tempAccountId = Number(addTempRes.body?.data?.account_id || 0);
assert.ok(tempEmployeeId > 0);
assert.ok(tempAccountId > 0);
assert.equal(addTempRes.body?.data?.phone, tempPhone);
assert.equal(addTempRes.body?.data?.real_name, tempRealName);
const deleteTempRes = await invokeSystemMethod('setting.account.delete', {
employee_id: tempEmployeeId,
}, token, EXTRA_HEADERS);
assert.equal(deleteTempRes.status, 200);
assert.equal(deleteTempRes.body.flag, 'success');
assert.equal(deleteTempRes.body.code, 200);
assert.equal(Number(deleteTempRes.body?.data?.employee_id), tempEmployeeId);
assert.equal(deleteTempRes.body?.data?.status, 'deleted');
const updateRetainedRes = await invokeSystemMethod('setting.account.update', {
employee_id: retainedEmployeeId,
real_name: RESERVED_EMPLOYEE_NAME,
file_id: existingFileId,
}, token, EXTRA_HEADERS);
assert.equal(updateRetainedRes.status, 200);
assert.equal(updateRetainedRes.body.flag, 'success');
assert.equal(updateRetainedRes.body.code, 200);
assert.equal(Number(updateRetainedRes.body?.data?.employee_id), retainedEmployeeId);
assert.equal(updateRetainedRes.body?.data?.real_name, RESERVED_EMPLOYEE_NAME);
assert.equal(Number(updateRetainedRes.body?.data?.avatar_file_id), existingFileId);
assert.ok(String(updateRetainedRes.body?.data?.avatar_url || '').length > 0);
const list = await listAccounts();
const retainedRow = list.find(item => Number(item.employee_id) === retainedEmployeeId);
const deletedTempRow = list.find(item => Number(item.employee_id) === tempEmployeeId);
assert.ok(retainedRow, '保留工号未出现在列表中');
assert.equal(retainedRow.real_name, RESERVED_EMPLOYEE_NAME);
assert.equal(Number(retainedRow.avatar_file_id), existingFileId);
assert.ok(String(retainedRow.avatar_url || '').length > 0);
assert.equal(deletedTempRow, undefined, '已删除的临时工号仍出现在有效列表中');
fs.mkdirSync(require('node:path').dirname(STATE_FILE), { recursive: true });
fs.writeFileSync(STATE_FILE, JSON.stringify({
retainedEmployeeId,
retainedAccountId,
tempEmployeeId,
tempAccountId,
tempPhone,
tempUsername,
existingFileId,
tokenFileExistedBefore,
}, null, 2), 'utf8');
});
});

View File

@ -0,0 +1,155 @@
'use strict';
const assert = require('node:assert/strict');
const {
getAuthToken,
invokeSystemMethod,
} = require('../../support/system_method_client');
const EXTRA_HEADERS = {
platform: 'web',
project: 'all',
};
describe('test/app/controller/system.setting.printTemplate.test.js', () => {
let token = '';
let businessType = '';
let createdTemplateId = 0;
const uniqueName = `autotest_template_${Date.now()}`;
before(async () => {
const auth = await getAuthToken();
token = auth.token;
const treeRes = await invokeSystemMethod('setting.printTemplate.list', {}, token, EXTRA_HEADERS);
assert.equal(treeRes.status, 200);
assert.equal(treeRes.body.flag, 'success');
const presetTree = Array.isArray(treeRes.body?.presetTree) ? treeRes.body.presetTree : [];
assert.ok(presetTree.length > 0, '缺少可用业务类型,无法执行打印模板测试');
for (const item of presetTree) {
if (!item || !item.businessType) {
continue;
}
const listRes = await invokeSystemMethod('setting.printTemplate.listTemplatesByType', {
businessType: item.businessType,
}, token, EXTRA_HEADERS);
assert.equal(listRes.status, 200);
assert.equal(listRes.body.flag, 'success');
const templates = Array.isArray(listRes.body?.data) ? listRes.body.data : [];
const hasDefaultCustomTemplate = templates.some(template =>
template
&& template.platform === 'default'
&& template.template_type === 'CUSTOM'
&& template.warehouse_id !== null
);
if (!hasDefaultCustomTemplate) {
businessType = item.businessType;
break;
}
}
assert.ok(businessType, '当前账号下所有业务类型都已存在默认 CUSTOM 模板,无法执行创建测试');
});
it('normal-1 should create print template successfully', async () => {
const createRes = await invokeSystemMethod('setting.printTemplate.create', {
template_name: uniqueName,
business_type: businessType,
page_width: 100,
page_height: 180,
}, token, EXTRA_HEADERS);
assert.equal(createRes.status, 200);
assert.equal(createRes.body.flag, 'success');
assert.equal(createRes.body.code, 200);
const templateId = Number(createRes.body?.data?.id);
assert.ok(templateId > 0, '创建成功但未返回模板ID');
createdTemplateId = templateId;
assert.match(createRes.body.message, /模板创建成功|ok/);
});
it('normal-2 should list created template by business type', async () => {
const listRes = await invokeSystemMethod('setting.printTemplate.listTemplatesByType', {
businessType,
}, token, EXTRA_HEADERS);
assert.equal(listRes.status, 200);
assert.equal(listRes.body.flag, 'success');
assert.equal(listRes.body.code, 200);
const templates = Array.isArray(listRes.body?.data) ? listRes.body.data : [];
const hit = templates.find(item => Number(item.id) === createdTemplateId);
assert.ok(hit, '按业务类型查询未包含新建模板');
assert.equal(hit.template_name, uniqueName);
assert.equal(hit.platform, 'default');
assert.equal(hit.template_type, 'CUSTOM');
assert.equal(hit.template_url, '');
});
it('normal-3 should delete created template successfully', async () => {
const deleteRes = await invokeSystemMethod('setting.printTemplate.delete', {
id: createdTemplateId,
}, token, EXTRA_HEADERS);
assert.equal(deleteRes.status, 200);
assert.equal(deleteRes.body.flag, 'success');
assert.equal(deleteRes.body.code, 200);
assert.equal(Number(deleteRes.body?.data?.id), createdTemplateId);
assert.match(deleteRes.body.message, /模板删除成功|ok/);
const listRes = await invokeSystemMethod('setting.printTemplate.listTemplatesByType', {
businessType,
}, token, EXTRA_HEADERS);
assert.equal(listRes.status, 200);
assert.equal(listRes.body.flag, 'success');
const templates = Array.isArray(listRes.body?.data) ? listRes.body.data : [];
const hit = templates.find(item => Number(item.id) === createdTemplateId);
assert.equal(hit, undefined, '删除后模板仍出现在查询结果中');
});
it('error-1 should fail when create without page_width', async () => {
const res = await invokeSystemMethod('setting.printTemplate.create', {
template_name: `${uniqueName}_missing_width`,
business_type: businessType,
page_height: 180,
}, token, EXTRA_HEADERS);
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'failure');
assert.equal(res.body.code, 400);
assert.match(res.body.message, /page_width/);
});
it('error-2 should fail when create without page_height', async () => {
const res = await invokeSystemMethod('setting.printTemplate.create', {
template_name: `${uniqueName}_missing_height`,
business_type: businessType,
page_width: 100,
}, token, EXTRA_HEADERS);
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'failure');
assert.equal(res.body.code, 400);
assert.match(res.body.message, /page_height/);
});
it('error-3 should fail when delete the same template twice', async () => {
const res = await invokeSystemMethod('setting.printTemplate.delete', {
id: createdTemplateId,
}, token, EXTRA_HEADERS);
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'failure');
assert.equal(res.body.code, 404);
assert.match(res.body.message, /模板不存在或无权限/);
});
});

View File

@ -0,0 +1,84 @@
'use strict';
const assert = require('node:assert/strict');
const {
getAuthToken,
invokeSystemMethod,
} = require('../../support/system_method_client');
const EXTRA_HEADERS = {
platform: 'web',
project: 'all',
};
const FALLBACK_ROLE_IDS = [ 4, 6, 30 ];
async function switchToWarehouseRole(token) {
let currentToken = token;
const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS);
assert.equal(infoRes.status, 200);
assert.equal(infoRes.body.flag, 'success');
assert.equal(infoRes.body.code, 200);
const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : [];
const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id));
const candidateRoleIds = [ ...new Set([
...warehouseRoles.map(item => Number(item.id)),
...FALLBACK_ROLE_IDS,
].filter(Boolean)) ];
assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色');
for (const roleId of candidateRoleIds) {
const changeRes = await invokeSystemMethod('user.changeRole', {
roleId,
}, currentToken, EXTRA_HEADERS);
if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) {
continue;
}
currentToken = changeRes.body?.data?.token || currentToken;
const listRes = await invokeSystemMethod('stock.warehouse.list', {
pagination: { page: 1, pageSize: 1 },
where: {},
}, currentToken, EXTRA_HEADERS);
if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) {
return {
token: currentToken,
roleId,
};
}
}
throw new Error('未找到可访问仓库商品列表的仓库角色');
}
describe('test/app/controller/system.stock.warehouse.namespaced.test.js', () => {
it('should query stock warehouse list via namespaced method', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRole(token);
const payload = {
pagination: {
page: 1,
pageSize: 5,
},
where: {},
};
const namespacedRes = await invokeSystemMethod('stock.warehouse.list', payload, switched.token, EXTRA_HEADERS);
assert.equal(namespacedRes.status, 200);
assert.equal(namespacedRes.body.flag, 'success');
assert.equal(namespacedRes.body.code, 200);
const namespacedData = namespacedRes.body.data;
assert.ok(namespacedData, '新入口缺少 data');
assert.ok(Array.isArray(namespacedData.list), '新入口 list 不是数组');
assert.ok(namespacedData.pagination, '新入口缺少 pagination');
});
});

View File

@ -0,0 +1,239 @@
'use strict';
const assert = require('node:assert/strict');
const {
getAuthToken,
invokeSystemMethod,
} = require('../../support/system_method_client');
const EXTRA_HEADERS = {
platform: 'web',
project: 'all',
};
const FALLBACK_ROLE_IDS = [ 4, 6, 30 ];
function normalizeListPayload(data) {
if (data && Array.isArray(data.list)) return data;
if (data && data.data && Array.isArray(data.data.list)) return data.data;
return null;
}
function extractDataObject(data) {
if (!data) return null;
if (data && typeof data === 'object' && data.data && typeof data.data === 'object') {
return data.data;
}
return data;
}
async function switchToWarehouseRole(token) {
let currentToken = token;
const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS);
assert.equal(infoRes.status, 200);
assert.equal(infoRes.body.flag, 'success');
assert.equal(infoRes.body.code, 200);
const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : [];
const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id));
const candidateRoleIds = [ ...new Set([
...warehouseRoles.map(item => Number(item.id)),
...FALLBACK_ROLE_IDS,
].filter(Boolean)) ];
assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色');
for (const roleId of candidateRoleIds) {
const changeRes = await invokeSystemMethod('user.changeRole', {
roleId,
}, currentToken, EXTRA_HEADERS);
if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) {
continue;
}
currentToken = changeRes.body?.data?.token || currentToken;
const listRes = await invokeSystemMethod('storage.entry.list', {
pagination: { page: 1, pageSize: 10 },
where: {},
}, currentToken, EXTRA_HEADERS);
if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) {
return {
token: currentToken,
roleId,
};
}
}
throw new Error('未找到可访问入库单的仓库角色');
}
describe('test/app/controller/system.storage.entry.test.js', () => {
it('should query entry list', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRole(token);
const res = await invokeSystemMethod('storage.entry.list', {
pagination: {
page: 1,
pageSize: 10,
},
where: {},
}, switched.token, EXTRA_HEADERS);
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'success');
assert.equal(res.body.code, 200);
const payload = normalizeListPayload(res.body.data);
assert.ok(payload, '返回结构中缺少入库单列表 payload');
assert.ok(Array.isArray(payload.list), '入库单 list 不是数组');
assert.ok(payload.pagination, '入库单 pagination 缺失');
assert.equal(typeof payload.pagination.total, 'number', 'pagination.total 不是 number');
});
it('should create entry and run detail lifecycle then cancel', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRole(token);
const createRes = await invokeSystemMethod('storage.entry.create', {
order_type: 'QTRK',
purchase_order_code: `PO-${Date.now()}`,
remark: 'integration-test-cancel',
}, switched.token, EXTRA_HEADERS);
assert.equal(createRes.status, 200);
assert.equal(createRes.body.flag, 'success');
assert.equal(createRes.body.code, 200);
const createData = extractDataObject(createRes.body.data) || {};
const orderId = Number(createData.id || createRes.body.id || 0);
assert.ok(orderId > 0, `创建入库单未返回有效 id: ${JSON.stringify(createRes.body)}`);
const getRes = await invokeSystemMethod('storage.entry.get', {
id: orderId,
}, switched.token, EXTRA_HEADERS);
assert.equal(getRes.status, 200);
assert.equal(getRes.body.flag, 'success');
assert.equal(getRes.body.code, 200);
const getData = extractDataObject(getRes.body.data) || {};
const entryOrder = getData.entryOrder || {};
assert.equal(Number(entryOrder.id), orderId);
const addRes = await invokeSystemMethod('storage.entry.addDetail', {
order_id: orderId,
count: 2,
item_code: `SKU-${Date.now().toString().slice(-6)}`,
inventory_type: 'ZP',
}, switched.token, EXTRA_HEADERS);
assert.equal(addRes.status, 200);
assert.equal(addRes.body.flag, 'success');
assert.equal(addRes.body.code, 200);
const addData = extractDataObject(addRes.body.data) || {};
const detailId = Number(addData.id || addRes.body.id || 0);
assert.ok(detailId > 0, `新增明细未返回有效 id: ${JSON.stringify(addRes.body)}`);
const changeRes = await invokeSystemMethod('storage.entry.detailChange', {
id: detailId,
count: 3,
item_code: `SKU-CHG-${Date.now().toString().slice(-6)}`,
}, switched.token, EXTRA_HEADERS);
assert.equal(changeRes.status, 200);
assert.equal(changeRes.body.flag, 'success');
assert.equal(changeRes.body.code, 200);
const deleteRes = await invokeSystemMethod('storage.entry.deleteDetail', {
id: detailId,
}, switched.token, EXTRA_HEADERS);
assert.equal(deleteRes.status, 200);
assert.equal(deleteRes.body.flag, 'success');
assert.equal(deleteRes.body.code, 200);
const cancelRes = await invokeSystemMethod('storage.entry.cancel', {
id: orderId,
}, switched.token, EXTRA_HEADERS);
assert.equal(cancelRes.status, 200);
assert.equal(cancelRes.body.flag, 'success');
assert.equal(cancelRes.body.code, 200);
});
it('should complete entry after adding detail', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRole(token);
const createRes = await invokeSystemMethod('storage.entry.create', {
order_type: 'QTRK',
purchase_order_code: `PO-COMP-${Date.now()}`,
remark: 'integration-test-complete',
}, switched.token, EXTRA_HEADERS);
assert.equal(createRes.status, 200);
assert.equal(createRes.body.flag, 'success');
assert.equal(createRes.body.code, 200);
const createData = extractDataObject(createRes.body.data) || {};
const orderId = Number(createData.id || createRes.body.id || 0);
assert.ok(orderId > 0, `创建入库单未返回有效 id: ${JSON.stringify(createRes.body)}`);
const addRes = await invokeSystemMethod('storage.entry.addDetail', {
order_id: orderId,
count: 1,
item_code: `SKU-COMP-${Date.now().toString().slice(-6)}`,
inventory_type: 'ZP',
}, switched.token, EXTRA_HEADERS);
assert.equal(addRes.status, 200);
assert.equal(addRes.body.flag, 'success');
assert.equal(addRes.body.code, 200);
const completeRes = await invokeSystemMethod('storage.entry.completeEntry', {
id: orderId,
}, switched.token, EXTRA_HEADERS);
assert.equal(completeRes.status, 200);
assert.equal(completeRes.body.flag, 'success');
assert.equal(completeRes.body.code, 200);
});
it('should reject invalid params for create/get/addDetail', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRole(token);
const createBadRes = await invokeSystemMethod('storage.entry.create', {
purchase_order_code: `PO-BAD-${Date.now()}`,
}, switched.token, EXTRA_HEADERS);
assert.equal(createBadRes.status, 200);
assert.equal(createBadRes.body.flag, 'success');
assert.equal(createBadRes.body.code, 400);
assert.match(String(createBadRes.body.message || ''), /order_type 必填/);
const getBadRes = await invokeSystemMethod('storage.entry.get', {}, switched.token, EXTRA_HEADERS);
assert.equal(getBadRes.status, 200);
assert.equal(getBadRes.body.flag, 'success');
assert.equal(getBadRes.body.code, 400);
assert.match(String(getBadRes.body.message || ''), /至少传一个/);
const addBadRes = await invokeSystemMethod('storage.entry.addDetail', {
order_id: 0,
count: 0,
}, switched.token, EXTRA_HEADERS);
assert.equal(addBadRes.status, 200);
assert.equal(addBadRes.body.flag, 'success');
assert.equal(addBadRes.body.code, 400);
assert.match(String(addBadRes.body.message || ''), /order_id 必填|count 必须大于 0/);
});
});

View File

@ -0,0 +1,230 @@
'use strict';
const assert = require('node:assert/strict');
const {
getAuthToken,
invokeSystemMethod,
} = require('../../support/system_method_client');
const EXTRA_HEADERS = {
platform: 'web',
project: 'all',
};
const FALLBACK_ROLE_IDS = [ 4, 6, 30 ];
function normalizeListPayload(data) {
if (data && Array.isArray(data.list)) return data;
if (data && data.data && Array.isArray(data.data.list)) return data.data;
return null;
}
function normalizeDetailPayload(data) {
if (data && data.receiving) return data;
if (data && data.data && data.data.receiving) return data.data;
return null;
}
async function switchToWarehouseRole(token) {
let currentToken = token;
const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS);
assert.equal(infoRes.status, 200);
assert.equal(infoRes.body.flag, 'success');
assert.equal(infoRes.body.code, 200);
const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : [];
const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id));
const candidateRoleIds = [ ...new Set([
...warehouseRoles.map(item => Number(item.id)),
...FALLBACK_ROLE_IDS,
].filter(Boolean)) ];
assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色');
for (const roleId of candidateRoleIds) {
const changeRes = await invokeSystemMethod('user.changeRole', {
roleId,
}, currentToken, EXTRA_HEADERS);
if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) {
continue;
}
currentToken = changeRes.body?.data?.token || currentToken;
const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', {
pagination: { page: 1, pageSize: 10 },
where: {},
}, currentToken, EXTRA_HEADERS);
if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) {
return {
token: currentToken,
roleId,
};
}
}
throw new Error('未找到可访问收货单的仓库角色');
}
describe('test/app/controller/system.storage.receiving.test.js', () => {
it('should query receiving list', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRole(token);
const res = await invokeSystemMethod('storage.receiving.getReceivingList', {
pagination: {
page: 1,
pageSize: 10,
},
where: {},
}, switched.token, EXTRA_HEADERS);
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'success');
assert.equal(res.body.code, 200);
const payload = normalizeListPayload(res.body.data);
assert.ok(payload, '返回结构中缺少收货单列表 payload');
assert.ok(Array.isArray(payload.list), '收货单 list 不是数组');
assert.ok(payload.pagination, '收货单 pagination 缺失');
assert.equal(typeof payload.pagination.total, 'number', 'pagination.total 不是 number');
});
it('should query receiving detail when list has records', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRole(token);
const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', {
pagination: {
page: 1,
pageSize: 10,
},
where: {},
}, switched.token, EXTRA_HEADERS);
assert.equal(listRes.status, 200);
assert.equal(listRes.body.flag, 'success');
assert.equal(listRes.body.code, 200);
const payload = normalizeListPayload(listRes.body.data);
assert.ok(payload, '返回结构中缺少收货单列表 payload');
const first = Array.isArray(payload.list) && payload.list.length > 0 ? payload.list[0] : null;
if (!first || !first.id) {
return;
}
const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', {
id: Number(first.id),
pagination: {
page: 1,
pageSize: 10,
},
}, switched.token, EXTRA_HEADERS);
assert.equal(detailRes.status, 200);
assert.equal(detailRes.body.flag, 'success');
assert.equal(detailRes.body.code, 200);
const detailPayload = normalizeDetailPayload(detailRes.body.data);
assert.ok(detailPayload, '返回结构中缺少收货单详情 payload');
assert.ok(detailPayload.receiving, 'receiving 字段缺失');
assert.equal(Number(detailPayload.receiving.id), Number(first.id));
});
it('should create and then batch cancel receiving order', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRole(token);
let createdId = null;
try {
const uniquePlate = `ITEST-${Date.now().toString().slice(-6)}`;
const createRes = await invokeSystemMethod('storage.receiving.create', {
delivery_method: 'truck',
license_plate: uniquePlate,
loading_method: 'with_pallet',
remark: 'integration-test',
total_boxes: 0,
total_pallets: 0,
}, switched.token, EXTRA_HEADERS);
assert.equal(createRes.status, 200);
assert.equal(createRes.body.flag, 'success');
assert.equal(createRes.body.code, 200);
createdId = Number(createRes.body.id || createRes.body?.data?.id || 0);
assert.ok(createdId > 0, `创建成功但未返回有效 id: ${JSON.stringify(createRes.body)}`);
const cancelRes = await invokeSystemMethod('storage.receiving.batchCancelReceiving', {
ids: [ createdId ],
}, switched.token, EXTRA_HEADERS);
assert.equal(cancelRes.status, 200);
assert.equal(cancelRes.body.flag, 'success');
assert.equal(cancelRes.body.code, 200);
assert.match(String(cancelRes.body.message || ''), /成功/);
} finally {
if (createdId > 0) {
await invokeSystemMethod('storage.receiving.batchCancelReceiving', {
ids: [ createdId ],
}, switched.token, EXTRA_HEADERS);
}
}
});
it('should reject getReceivingDetail with invalid id', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRole(token);
const res = await invokeSystemMethod('storage.receiving.getReceivingDetail', {
id: -1,
pagination: {
page: 1,
pageSize: 10,
},
}, switched.token, EXTRA_HEADERS);
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'success');
assert.equal(res.body.code, 0);
assert.match(String(res.body.message || ''), /无记录|无权访问|不存在/);
});
it('should reject create with invalid loading_method enum', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRole(token);
const res = await invokeSystemMethod('storage.receiving.create', {
delivery_method: 'truck',
license_plate: `ITEST-ERR-${Date.now().toString().slice(-6)}`,
loading_method: 'manual',
remark: 'invalid-enum-test',
total_boxes: 0,
total_pallets: 0,
}, switched.token, EXTRA_HEADERS);
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'success');
assert.equal(res.body.code, 0);
assert.match(String(res.body.message || ''), /创建失败|Data truncated|loading_method/);
});
it('should reject batchCancelReceiving with nonexistent ids', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRole(token);
const res = await invokeSystemMethod('storage.receiving.batchCancelReceiving', {
ids: [ 999999999 ],
}, switched.token, EXTRA_HEADERS);
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'success');
assert.equal(res.body.code, 0);
assert.match(String(res.body.message || ''), /不存在|无权访问|状态不允许/);
});
});

View File

@ -0,0 +1,320 @@
'use strict';
const assert = require('node:assert/strict');
const StockStoreService = require('../../../../app/service/systems/stock_store');
function createTestContext(options = {}) {
const calls = {
countArgs: null,
findArgs: null,
barcodeCalls: [],
fileRefArgs: null,
};
const Op = {
and: '$and',
or: '$or',
ne: '$ne',
like: '$like',
gt: '$gt',
lt: '$lt',
gte: '$gte',
lte: '$lte',
in: '$in',
notIn: '$notIn',
between: '$between',
notBetween: '$notBetween',
is: '$is',
not: '$not',
regexp: '$regexp',
notRegexp: '$notRegexp',
};
const rows = options.rows || [ {
id: 1,
item_code: 'SKU-1',
goods_code: 'G-1',
item_name: '商品A',
quantity: 10,
locked_quantity: 2,
create_at: '2026-01-01 10:00:00',
update_at: '2026-01-01 10:00:00',
} ];
const model = {
StoreWarehouse: {
buildStoreStockInclude(params = {}) {
return {
as: 'store_stock',
required: Boolean(params.required),
attributes: params.attributes || [],
where: {
warehouse_id: params.warehouseId,
},
};
},
},
ProhibitedType: {},
StockWarehouse: {
async count(args) {
calls.countArgs = args;
return options.total == null ? rows.length : options.total;
},
async findAll(args) {
calls.findArgs = args;
return rows;
},
},
StockBarcode: {
async findAll(args) {
calls.barcodeCalls.push(args);
const attrs = Array.isArray(args.attributes) ? args.attributes : [];
if (attrs.includes('stock_id')) {
if (options.matchedBarcodeRows) {
return options.matchedBarcodeRows;
}
return [ { stock_id: 1 } ];
}
if (options.barcodes) {
return options.barcodes;
}
return [ { stock_id: 1, barcode: 'BC-1' } ];
},
},
FileReference: {
async findAll(args) {
calls.fileRefArgs = args;
return options.images || [];
},
},
};
const app = {
Sequelize: { Op },
model,
logger: {
debug() {},
warn() {},
error() {},
},
config: {
cos: {
cdnurl: '',
},
},
};
const ctx = {
app,
model,
user: {
store_id: 100000,
},
logger: {
error() {},
},
};
return {
app,
ctx,
model,
calls,
Op,
};
}
function createServiceHarness(options = {}) {
const harness = createTestContext(options);
const service = new StockStoreService(harness.ctx);
return {
...harness,
service,
};
}
describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js', () => {
it('should build Sequelize condition for all supported operators', () => {
const { service, app, Op } = createServiceHarness();
const cases = [
[ 'eq', { field: 'item_code', value: 'SKU' }, { item_code: 'SKU' } ],
[ 'ne', { value: 'SKU' }, { item_code: { [Op.ne]: 'SKU' } } ],
[ 'like', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU%' } } ],
[ 'contains', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU%' } } ],
[ 'startswith', { value: 'SKU' }, { item_code: { [Op.like]: 'SKU%' } } ],
[ 'endswith', { value: 'SKU' }, { item_code: { [Op.like]: '%SKU' } } ],
[ 'gt', { value: 10 }, { item_code: { [Op.gt]: 10 } } ],
[ 'lt', { value: 10 }, { item_code: { [Op.lt]: 10 } } ],
[ 'ge', { value: 10 }, { item_code: { [Op.gte]: 10 } } ],
[ 'le', { value: 10 }, { item_code: { [Op.lte]: 10 } } ],
[ 'in', { value: [ 'A', 'B' ] }, { item_code: { [Op.in]: [ 'A', 'B' ] } } ],
[ 'notin', { value: [ 'A', 'B' ] }, { item_code: { [Op.notIn]: [ 'A', 'B' ] } } ],
[ 'between', { value: [ 1, 2 ] }, { item_code: { [Op.between]: [ 1, 2 ] } } ],
[ 'notbetween', { value: [ 1, 2 ] }, { item_code: { [Op.notBetween]: [ 1, 2 ] } } ],
[ 'isnull', { value: null }, { item_code: { [Op.is]: null } } ],
[ 'isnotnull', { value: null }, { item_code: { [Op.not]: null } } ],
[ 'regexp', { value: '^SKU' }, { item_code: { [Op.regexp]: '^SKU' } } ],
[ 'notregexp', { value: '^SKU' }, { item_code: { [Op.notRegexp]: '^SKU' } } ],
];
for (const [ operator, input, expected ] of cases) {
const actual = service.buildSequelizeCondition('item_code', {
operator,
...input,
}, app);
assert.deepEqual(actual, expected, `operator=${operator}`);
}
});
it('should normalize boolean, number and text values', () => {
const { service } = createServiceHarness();
assert.equal(service.processConditionValue(true, 'boolean'), 'Y');
assert.equal(service.processConditionValue('false', 'boolean'), 'N');
assert.equal(service.processConditionValue('12.5', 'number'), 12.5);
assert.deepEqual(service.processConditionValue('A,B,C', 'text'), [ 'A', 'B', 'C' ]);
});
it('should support date and daterange condition extraction', () => {
const { service, app, Op } = createServiceHarness();
const dateEq = service.buildSequelizeCondition('create_at', {
operator: 'eq',
type: 'date',
value: '2026-03-25',
}, app);
assert.ok(dateEq.create_at);
const between = service.buildSequelizeCondition('create_at', {
operator: 'between',
type: 'daterange',
value: [ '2026-03-01', '2026-03-31' ],
}, app);
assert.deepEqual(between, {
create_at: {
[Op.between]: [ '2026-03-01', '2026-03-31' ],
},
});
});
it('should parse where and return list with barcode/prohibited branches', async () => {
const { service, calls, Op } = createServiceHarness();
const result = await service.getWarehouseStock({
item_code: {
operator: 'like',
value: 'SKU',
},
barcode: {
operator: 'like',
value: 'BC',
},
prohibited_type: {
operator: 'eq',
value: 2,
},
quantity: {
operator: 'ge',
type: 'number',
value: '2',
},
}, {
page: 1,
pageSize: 10,
}, {
sortField: 'quantity',
sortOrder: 'ASC',
});
assert.equal(result.code, 200);
assert.equal(result.message, '查询成功');
assert.equal(result.data.pagination.page, 1);
assert.equal(result.data.pagination.pageSize, 10);
assert.equal(result.data.queryInfo.hasBarcodeSearch, true);
assert.ok(calls.countArgs);
assert.ok(calls.findArgs);
assert.ok(Array.isArray(calls.barcodeCalls));
assert.ok(calls.barcodeCalls.length >= 2, '应包含条码匹配查询和条码回填查询');
const stockWhere = calls.findArgs.where;
assert.ok(stockWhere[Op.and], '应存在 AND 组合条件');
const includeList = calls.findArgs.include;
const prohibitedInclude = includeList.find(item => item.as === 'prohibited');
assert.ok(prohibitedInclude, '应包含 prohibited 关联');
assert.equal(prohibitedInclude.required, true, '含 prohibited_type 时应为必需关联');
});
it('should short-circuit when barcode has no matched stock ids', async () => {
const { service, calls } = createServiceHarness({
matchedBarcodeRows: [],
rows: [ {
id: 99,
} ],
});
const result = await service.getWarehouseStock({
barcode: {
operator: 'eq',
value: 'NOT-FOUND',
},
}, {
page: 1,
pageSize: 20,
});
assert.equal(result.code, 200);
assert.deepEqual(result.data.list, []);
assert.equal(result.data.pagination.total, 0);
assert.equal(calls.countArgs, null);
assert.equal(calls.findArgs, null);
});
it('should ignore empty where values and fallback invalid sort field', async () => {
const { service, calls } = createServiceHarness();
const result = await service.getWarehouseStock({
item_name: {
operator: 'like',
value: ' ',
},
store_id: {
operator: 'in',
value: [],
},
item_code: {
operator: 'like',
value: 'SKU-1',
},
}, {
page: 2,
pageSize: 5,
}, {
sortField: 'unknown_field',
sortOrder: 'UNKNOWN',
});
assert.equal(result.code, 200);
assert.deepEqual(calls.findArgs.order, [ [ 'create_at', 'DESC' ] ]);
assert.equal(result.data.pagination.page, 2);
assert.equal(result.data.pagination.pageSize, 5);
});
it('should return failure reason when where deconstruction is invalid', async () => {
const { service } = createServiceHarness();
const result = await service.getWarehouseStock({
item_code: 'SKU-1',
}, {
page: 1,
pageSize: 20,
});
assert.equal(result.code, 400);
assert.match(result.message, /筛选条件解析失败/);
assert.match(result.message, /字段 item_code 条件必须是对象/);
});
});

View File

@ -5,6 +5,7 @@ const path = require('node:path');
const assert = require('node:assert/strict');
const BASE_URL = process.env.SYSTEM_TEST_BASE_URL || 'http://127.0.0.1:6060';
const BASE_GATEWAY_URL = process.env.SYSTEM_TEST_GATEWAY_BASE_URL || BASE_URL;
const TOKEN_FILE = process.env.SYSTEM_TEST_TOKEN_FILE
|| path.join(process.cwd(), 'test', '.runtime', 'system_user_token.json');
const USERNAME = process.env.SYSTEM_TEST_USERNAME || 'liufumingren';
@ -127,11 +128,39 @@ async function getAuthToken(options = {}) {
};
}
async function invokeGatewayMethod(method, body = {}) {
const timestamp = nowSec();
const url = `${BASE_GATEWAY_URL}/internal/v1/gateway?method=${encodeURIComponent(method)}&v=1.0&timestamp=${timestamp}`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
const text = await response.text();
let json;
try {
json = JSON.parse(text);
} catch {
throw new Error(`Invalid JSON from gateway ${method}: ${text}`);
}
return {
status: response.status,
body: json,
};
}
module.exports = {
BASE_URL,
BASE_GATEWAY_URL,
TOKEN_FILE,
USERNAME,
invokeSystemMethod,
invokeGatewayMethod,
getAuthToken,
readCachedToken,
};