diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index 8f7af4f..2ecaf48 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -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` \ No newline at end of file diff --git a/app/service/apiMethods/user.js b/app/service/apiMethods/user.js index fabcc1c..4ba9f2a 100644 --- a/app/service/apiMethods/user.js +++ b/app/service/apiMethods/user.js @@ -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; \ No newline at end of file diff --git a/app/service/main.js b/app/service/main.js index e12c300..e0e518f 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -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}`; diff --git a/app/service/systemMethods/order/archiveOrder.js b/app/service/systemMethods/order/archiveOrder.js index e304684..5f11efc 100644 --- a/app/service/systemMethods/order/archiveOrder.js +++ b/app/service/systemMethods/order/archiveOrder.js @@ -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'; } diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index 89ea602..9734701 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -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; } diff --git a/app/service/systemMethods/order/deliveryOrder.js b/app/service/systemMethods/order/deliveryOrder.js index 1acd085..1094439 100644 --- a/app/service/systemMethods/order/deliveryOrder.js +++ b/app/service/systemMethods/order/deliveryOrder.js @@ -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' }; } diff --git a/app/service/systemMethods/order/expectionOrder.js b/app/service/systemMethods/order/expectionOrder.js index 0f066ac..f32cfac 100644 --- a/app/service/systemMethods/order/expectionOrder.js +++ b/app/service/systemMethods/order/expectionOrder.js @@ -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] = [ diff --git a/app/service/systemMethods/order/index.js b/app/service/systemMethods/order/index.js index 7bf532b..bb2a236 100644 --- a/app/service/systemMethods/order/index.js +++ b/app/service/systemMethods/order/index.js @@ -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({ diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 4c8d655..912dbce 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -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' ] }; diff --git a/app/service/systemMethods/order/reviewOrder.js b/app/service/systemMethods/order/reviewOrder.js index ad994b8..be546c6 100644 --- a/app/service/systemMethods/order/reviewOrder.js +++ b/app/service/systemMethods/order/reviewOrder.js @@ -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({ diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 8b32985..302f241 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -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', diff --git a/app/service/systemMethods/setting/account.js b/app/service/systemMethods/setting/account.js new file mode 100644 index 0000000..cf89f05 --- /dev/null +++ b/app/service/systemMethods/setting/account.js @@ -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; \ No newline at end of file diff --git a/app/service/systemMethods/stock/index.js b/app/service/systemMethods/stock/index.js new file mode 100644 index 0000000..0ea6c58 --- /dev/null +++ b/app/service/systemMethods/stock/index.js @@ -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; diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index 87c2acb..acd29ce 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -21,7 +21,18 @@ class WarehouseService extends MainService { */ async list(data = {}) { const { service } = this; - const { pagination, where } = data; + 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); } diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js new file mode 100644 index 0000000..da68a84 --- /dev/null +++ b/app/service/systemMethods/storage/entry.js @@ -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} 统一 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} 统一 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} 统一 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} 统一 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} 统一 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} 统一 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} 统一 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} 统一 success 包装 + */ + async completeEntry(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.completeEntry(data); + return this.success('ok', result); + } +} +module.exports = entryService; \ No newline at end of file diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index f91ef63..839b8ee 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -1,7 +1,11 @@ 'use strict'; const MainService = require('../../main'); - +/** + * 系统方法层:storage.receiving(收货单相关接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。 + * 注意:当前实现仅为包装层,实际业务逻辑完全依赖底层 service 的方法实现。 + */ class configService extends MainService { constructor(ctx) { super(ctx); @@ -21,10 +25,15 @@ class configService extends MainService { */ 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); } diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 848d1ff..ea88807 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -641,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} @@ -672,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) { @@ -686,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); } @@ -695,7 +821,14 @@ 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, { diff --git a/app/service/systems/setting/account.js b/app/service/systems/setting/account.js new file mode 100644 index 0000000..27f273e --- /dev/null +++ b/app/service/systems/setting/account.js @@ -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; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 8d7959d..36fc6e8 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -1075,44 +1075,53 @@ class stockStoreService extends Service { let barcodeCondition = null; let parsedBarcodeInput = null; - // 处理动态查询条件 - if (where && Object.keys(where).length > 0) { - const parsed = parseWhereConditions({ - where, - app, - specialFieldMap: { - barcode: { - bucket: 'barcode', - }, - prohibited_type: { - bucket: 'prohibited', - field: 'id', - }, - }, - }); + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? ctx.where + : (where && typeof where === 'object' ? where : {}); - if (!parsed.ok) { - return { - code: 400, - data: { - list: [], - pagination: { - page: parseInt(page), - pageSize: parseInt(pageSize), - total: 0, - totalPages: 0, - hasPrevious: false, - hasNext: false, + // 处理动态查询条件 + 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', }, - summary: { - total_quantity: 0, - total_locked: 0, - total_available: 0, - total_items: 0, + prohibited_type: { + bucket: 'prohibited', + field: 'id', }, }, - message: `筛选条件解析失败: ${parsed.reason}`, - }; + }); + + 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 { @@ -1120,7 +1129,7 @@ class stockStoreService extends Service { bucketConditions, bucketFlags, rawConditionsByField, - } = parsed.result; + } = parsedResult; const barcodeDynamicConditions = bucketConditions.barcode || []; const prohibitedConditions = bucketConditions.prohibited || []; @@ -1390,7 +1399,7 @@ class stockStoreService extends Service { }, summary, queryInfo: { - conditions: where, + conditions: normalizedWhere, sortField: actualSortField, sortOrder: actualSortOrder, hasBarcodeSearch: hasBarcodeCondition, diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js new file mode 100644 index 0000000..9f18bd1 --- /dev/null +++ b/app/service/systems/storage/entry.js @@ -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} 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} 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} 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} 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} 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} 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} 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} 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; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index ec2def5..28f8d6f 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -1,6 +1,7 @@ 'use strict'; const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); class ReceivingService extends Service { /** * 查询收货单列表。 @@ -23,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) { @@ -186,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, @@ -218,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: { @@ -252,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 { diff --git a/day.log b/day.log index 5701f90..2031b05 100644 Binary files a/day.log and b/day.log differ diff --git a/methods/gateway.json b/methods/gateway.json index 6f37cb6..1ddc55f 100644 --- a/methods/gateway.json +++ b/methods/gateway.json @@ -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": [] } ] } diff --git a/methods/system.json b/methods/system.json index 107531f..d7c9e13 100644 --- a/methods/system.json +++ b/methods/system.json @@ -490,7 +490,7 @@ "type": "object", "required": false, "source": "body", - "description": "where 参数" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 delivery_order_code、status、outbound_status、buyer_nick、mobile 与日期区间字段。示例:where.delivery_order_code={operator:like,value:SO202603}; where.status={operator:in,value:[created,pedding]}。" } ], "response": [], @@ -579,7 +579,7 @@ "type": "object", "required": false, "source": "body", - "description": "where 参数" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;统计口径与 order.list 共用筛选字段。示例:where.status={operator:eq,value:fin}; where.create_time_start={value:2026-03-01}; where.create_time_end={value:2026-03-31}。" } ], "response": [], @@ -611,7 +611,7 @@ "type": "object", "required": false, "source": "body", - "description": "where 参数,支持 inspection_status/operator_name/operate_time_start/operate_time_end" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、operator_name、operate_time_start、operate_time_end 等字段。示例:where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" } ], "response": [], @@ -844,7 +844,7 @@ "type": "object", "required": false, "source": "body", - "description": "where 参数,支持 inspection_status/operator_name/operate_time_start/operate_time_end" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、operator_name、operate_time_start、operate_time_end 等字段。示例:where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" } ], "response": [], @@ -936,7 +936,7 @@ "type": "object", "required": false, "source": "body", - "description": "where 参数,默认 outbound_status != none" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传 outbound_status 时默认过滤 outbound_status != none。示例:where.outbound_status={operator:in,value:[created,processing]}; where.store_id={operator:eq,value:1001}。" } ], "response": [], @@ -968,7 +968,7 @@ "type": "object", "required": false, "source": "body", - "description": "where 参数,默认 status in [pedding, created] 且 outbound_status = none" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传时默认 status in [pedding, created] 且 outbound_status = none。示例:where.status={operator:in,value:[pedding,created]}; where.outbound_status={operator:eq,value:none}。" } ], "response": [], @@ -1000,7 +1000,7 @@ "type": "object", "required": false, "source": "body", - "description": "where 参数,默认筛选各流程 error 或拦截 exception" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传时默认筛选各流程 error 或拦截 exception。示例:where.status={operator:eq,value:error}; where.outbound_status={operator:eq,value:exception}。" } ], "response": [], @@ -1032,7 +1032,7 @@ "type": "object", "required": false, "source": "body", - "description": "where 参数,默认 outbound_status = fin" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传 outbound_status 时默认过滤 outbound_status = fin。示例:where.outbound_status={operator:eq,value:fin}; where.store_id={operator:eq,value:1001}。" } ], "response": [], @@ -1194,7 +1194,7 @@ "type": "object", "required": false, "source": "body", - "description": "where 参数" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;当前支持 id、name、computer_id、custom_barcode。示例:where.name={operator:like,value:热敏}; where.computer_id={operator:eq,value:PC-01}。" } ], "response": [], @@ -1655,6 +1655,370 @@ } ] }, + { + "groupName": "账号管理模块", + "module": "setting.account", + "list": [ + { + "method": "setting.account.list", + "description": "查询当前主体下的工号基础信息列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "status", + "type": "number", + "required": false, + "source": "body", + "description": "状态筛选,默认 1,仅查有效工号" + }, + { + "name": "includeDisabled", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含已删除工号" + } + ], + "response": [ + { + "name": "data[]", + "type": "object", + "required": true, + "description": "工号列表项" + }, + { + "name": "data[].employee_id", + "type": "number", + "required": true, + "description": "工号ID" + }, + { + "name": "data[].account_id", + "type": "number", + "required": true, + "description": "账号ID" + }, + { + "name": "data[].store_id", + "type": "number", + "required": true, + "description": "主体ID" + }, + { + "name": "data[].real_name", + "type": "string", + "required": true, + "description": "工号姓名" + }, + { + "name": "data[].status", + "type": "number", + "required": true, + "description": "工号状态:1=启用,0=停用" + }, + { + "name": "data[].username", + "type": "string", + "required": true, + "description": "账号用户名" + }, + { + "name": "data[].phone", + "type": "string", + "required": true, + "description": "账号手机号" + }, + { + "name": "data[].email", + "type": "string", + "required": true, + "description": "账号邮箱" + }, + { + "name": "data[].avatar_file_id", + "type": "number", + "required": false, + "description": "头像文件ID,为空表示未设置" + }, + { + "name": "data[].avatar_url", + "type": "string", + "required": true, + "description": "头像访问地址" + } + ], + "errors": [ + { + "code": "400", + "description": "当前登录态缺少主体上下文(store_id)" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.account.add", + "description": "新增工号,按手机号复用或创建账号后绑定到当前主体", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "phone", + "type": "string", + "required": true, + "source": "body", + "description": "手机号,作为账号复用/创建依据" + }, + { + "name": "real_name", + "type": "string", + "required": true, + "source": "body", + "description": "工号姓名,新增时禁止直接使用保留名称" + }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "新账号用户名,不传时系统自动生成" + }, + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "新账号密码,不传默认 111111" + }, + { + "name": "role_id", + "type": "number", + "required": false, + "source": "body", + "description": "工号角色,不传时继承当前操作人工号角色" + }, + { + "name": "email", + "type": "string", + "required": false, + "source": "body", + "description": "新账号邮箱,不传时按 username 自动生成" + } + ], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "description": "新增或复用后的工号ID" + }, + { + "name": "account_id", + "type": "number", + "required": true, + "description": "绑定账号ID" + }, + { + "name": "role_id", + "type": "number", + "required": true, + "description": "绑定后的角色ID" + }, + { + "name": "is_new_account", + "type": "boolean", + "required": true, + "description": "是否为本次新建账号" + }, + { + "name": "phone", + "type": "string", + "required": true, + "description": "绑定账号手机号" + }, + { + "name": "username", + "type": "string", + "required": true, + "description": "绑定账号用户名" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、手机号格式错误、或直接使用保留名称" + }, + { + "code": "409", + "description": "手机号对应账号已禁用、手机号已绑定当前主体工号、或用户名重复" + }, + { + "code": "500", + "description": "新增失败" + } + ] + }, + { + "method": "setting.account.delete", + "description": "删除工号绑定关系,仅停用工号,不删除账号", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "source": "body", + "description": "要删除的工号ID" + } + ], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "description": "被停用的工号ID" + }, + { + "name": "account_id", + "type": "number", + "required": true, + "description": "关联账号ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 deleted" + }, + { + "name": "already_deleted", + "type": "boolean", + "required": false, + "description": "可选,true 表示该工号原本已停用" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或尝试删除当前登录工号" + }, + { + "code": "404", + "description": "工号不存在或无权限删除" + }, + { + "code": "500", + "description": "删除失败" + } + ] + }, + { + "method": "setting.account.update", + "description": "更新工号姓名和头像引用", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "source": "body", + "description": "要更新的工号ID" + }, + { + "name": "real_name", + "type": "string", + "required": false, + "source": "body", + "description": "更新后的工号姓名" + }, + { + "name": "file_id", + "type": "number", + "required": false, + "source": "body", + "description": "已有文件ID,作为头像引用" + } + ], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "description": "更新后的工号ID" + }, + { + "name": "real_name", + "type": "string", + "required": true, + "description": "更新后的工号姓名" + }, + { + "name": "avatar_file_id", + "type": "number", + "required": false, + "description": "更新后的头像文件ID" + }, + { + "name": "avatar_url", + "type": "string", + "required": true, + "description": "更新后的头像地址" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误,未提供更新项" + }, + { + "code": "404", + "description": "工号或头像文件不存在" + }, + { + "code": "500", + "description": "更新失败" + } + ] + } + ] + }, { "groupName": "商品模块", "module": "stock", @@ -1685,7 +2049,7 @@ "type": "object", "required": false, "source": "body", - "description": "where 参数" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、barcode、prohibited_type 等商品筛选字段。示例:where.barcode={operator:like,value:69}; where.prohibited_type={operator:eq,value:liquid}。" } ], "response": [], @@ -2109,7 +2473,7 @@ "type": "object", "required": false, "source": "body", - "description": "筛选参数,支持 quickWhere、status、store_id、日期区间等" + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、status、store_id、日期区间等字段。示例:where.status={operator:eq,value:finished}; where.store_id={operator:eq,value:1001}; where.create_time_start={value:2026-03-01}。" } ], "response": [ @@ -2502,6 +2866,428 @@ "params": [], "response": [], "errors": [] + }, + { + "method": "storage.entry.list", + "description": "入库单列表查询", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status、store_id、order_type、日期区间等字段。示例:where.order_status={operator:eq,value:waiting}; where.order_type={operator:eq,value:purchase}; where.create_time_start={value:2026-03-01}。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField/sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "入库单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "状态汇总(total、pending、creating、created、completed、cancelled)" + } + ], + "errors": [ + { + "code": "400", + "description": "筛选条件格式错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "storage.entry.get", + "description": "查询入库单详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "入库单ID,与 entry_order_code 二选一" + }, + { + "name": "entry_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "入库单号,与 id 二选一" + } + ], + "response": [ + { + "name": "entryOrder", + "type": "object", + "required": true, + "description": "入库单详情(含 items 明细)" + } + ], + "errors": [ + { + "code": "400", + "description": "id 与 entry_order_code 均未传" + }, + { + "code": "0", + "description": "无记录或无权访问" + } + ] + }, + { + "method": "storage.entry.create", + "description": "创建入库单", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_type", + "type": "string", + "required": true, + "source": "body", + "description": "业务类型:SCRK/LYRK/CCRK/CGRK/DBRK/QTRK/B2BRK/XNRK" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID,不传默认使用当前用户 store_id" + }, + { + "name": "entry_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "入库单号,不传时系统自动生成" + }, + { + "name": "purchase_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "采购单号" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + } + ], + "errors": [ + { + "code": "400", + "description": "参数缺失或业务类型不合法" + }, + { + "code": "409", + "description": "入库单号已存在" + } + ] + }, + { + "method": "storage.entry.addDetail", + "description": "新增入库明细", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + }, + { + "name": "count", + "type": "number", + "required": true, + "source": "body", + "description": "计划入库数量,必须大于0" + }, + { + "name": "item_code", + "type": "string", + "required": false, + "source": "body", + "description": "商品编码" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建明细ID" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "所属入库单ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法或状态不允许新增明细" + }, + { + "code": "404", + "description": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.deleteDetail", + "description": "删除入库明细", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "明细ID" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "删除成功的明细ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法或明细已有收货数量" + }, + { + "code": "404", + "description": "明细或入库单不存在" + } + ] + }, + { + "method": "storage.entry.detailChange", + "description": "修改入库明细", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "明细ID" + }, + { + "name": "count", + "type": "number", + "required": false, + "source": "body", + "description": "计划入库数量,必须大于0且不能小于已收货数量" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "修改成功的明细ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法或没有可更新字段" + }, + { + "code": "404", + "description": "明细或入库单不存在" + } + ] + }, + { + "method": "storage.entry.cancel", + "description": "作废入库单", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "作废成功的入库单ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法或已完成单据不允许作废" + }, + { + "code": "404", + "description": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.completeEntry", + "description": "完成入库单", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "完成成功的入库单ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法、已作废或缺少明细" + }, + { + "code": "404", + "description": "入库单不存在或无权访问" + } + ] } ] }, diff --git a/test/app/controller/gateway.user.bindAccountByTempCode.test.js b/test/app/controller/gateway.user.bindAccountByTempCode.test.js new file mode 100644 index 0000000..36246ef --- /dev/null +++ b/test/app/controller/gateway.user.bindAccountByTempCode.test.js @@ -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'); + }); +}); diff --git a/test/app/controller/system.setting.account.test.js b/test/app/controller/system.setting.account.test.js new file mode 100644 index 0000000..167f86b --- /dev/null +++ b/test/app/controller/system.setting.account.test.js @@ -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'); + }); +}); diff --git a/test/app/controller/system.storage.entry.test.js b/test/app/controller/system.storage.entry.test.js new file mode 100644 index 0000000..46f58f0 --- /dev/null +++ b/test/app/controller/system.storage.entry.test.js @@ -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/); + }); +}); diff --git a/test/support/system_method_client.js b/test/support/system_method_client.js index 68c3649..62a7bd1 100644 --- a/test/support/system_method_client.js +++ b/test/support/system_method_client.js @@ -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×tamp=${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, };