chore: 提交当前工作区改动

This commit is contained in:
liufumingren 2026-03-25 18:12:04 +08:00
parent 67c6856d75
commit b9e94f1035
19 changed files with 2933 additions and 781 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -11,6 +11,14 @@ class configService extends MainService {
const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 收货单列表查询(system method 包装层)。
* @param {Object} data 请求体
* @param {Object} [data.pagination] 分页参数
* @param {Object} [data.where] 筛选条件
* @return {Promise<Object>} 统一成功包装响应
*/
async getReceivingList(data) {
const { service } = this;
const { pagination, where } = data;
@ -19,63 +27,145 @@ class configService extends MainService {
const result = await service.systems.storage.receiving.getReceivingList(where, pagination);
return this.success('ok', result);
}
/**
* 收货单详情查询(分页返回明细)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {Object} data.pagination 明细分页参数
* @return {Promise<Object>} 统一成功包装响应
*/
async getReceivingDetail(data) {
const { service } = this;
const result = await service.systems.storage.receiving.getReceivingDetail(data);
return this.success('ok', result);
}
/**
* 批量作废收货单。
* @param {Object} data 请求体
* @param {number[]} data.ids 收货单ID数组
* @return {Promise<Object>} 统一成功包装响应
*/
async batchCancelReceiving(data){
const { service } = this;
const result = await service.systems.storage.receiving.batchCancelReceiving(data);
return this.success('ok', result);
}
/**
* 创建收货单。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async create(data) {
const { service } = this;
const result = await service.systems.storage.receiving.create(data);
return this.success('创建失败', result);
}
/**
* 添加收货商品(当前依赖底层 addItem 实现)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {Object} data.item 商品信息
* @return {Promise<Object>} 统一成功包装响应
*/
async addItem(data) {
const { service } = this;
const { id, item } = data;
const result = await service.systems.storage.receiving.addItem(id, item);
return this.success('ok', result);
}
/**
* 删除收货商品(当前依赖底层 removeItem 实现)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {number} data.item_id 商品明细ID
* @return {Promise<Object>} 统一成功包装响应
*/
async removeItem(data) {
const { service } = this;
const { id, item_id } = data;
const result = await service.systems.storage.receiving.removeItem(id, item_id);
return this.success('ok', result);
}
/**
* 保存收货单(兼容接口)。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async saveReceiving(data) {
const { service } = this;
const result = await service.systems.storage.receiving.saveReceiving(data);
return this.success('ok', result);
}
/**
* 查询收货单完整信息(含明细与图片)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @return {Promise<Object>} 统一成功包装响应
*/
async get(data) {
const { service } = this;
const result = await service.systems.storage.receiving.get(data);
return this.success('ok', result);
}
/**
* 新增一条收货明细(默认空模板)。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async addDetail(data) {
const { service } = this;
const result = await service.systems.storage.receiving.addDetail(data);
return this.success('ok', result);
}
/**
* 删除收货明细。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async deleteDetail(data) {
const { service } = this;
const result = await service.systems.storage.receiving.deleteDetail(data);
return this.success('ok', result);
}
/**
* 修改收货明细字段。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async detailChange(data) {
const { service } = this;
const result = await service.systems.storage.receiving.detailChange(data);
return this.success('ok', result);
}
/**
* 作废收货单(单条)。
* @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应
*/
async cancel(data) {
const { service } = this;
const result = await service.systems.storage.receiving.invalid(data);
return this.success('ok', result);
}
/**
* 完成收货单并触发入库处理。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {string} [data.remark] 完成备注
* @return {Promise<Object>} 统一成功包装响应
*/
async completeReceiving(data) {
const { service } = this;
const result = await service.systems.storage.receiving.completeReceiving(data);

View File

@ -7,6 +7,8 @@ const WECHAT_BIND_CACHE_PREFIX = 'user:wechat:bind:';
const WECHAT_BIND_CODE_CACHE_PREFIX = 'user:wechat:bind:code:';
const WECHAT_BIND_CACHE_TTL_SECONDS = 600;
const WECHAT_BIND_RECHECK_INTERVAL_MS = 5000;
const WECHAT_BIND_EVENT_CHANNEL_PREFIX = 'user:wechat:bind:event:';
const WECHAT_BIND_LONG_POLL_TIMEOUT_MS = 60000;
class UserService extends Service {
constructor(ctx) {
@ -99,6 +101,210 @@ class UserService extends Service {
return rows[0];
}
getWechatBindEventChannel(accountId) {
return `${WECHAT_BIND_EVENT_CHANNEL_PREFIX}${accountId}`;
}
getWechatLongPollTimeoutMs(rawTimeoutMs) {
const timeoutMs = Number(rawTimeoutMs);
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
return WECHAT_BIND_LONG_POLL_TIMEOUT_MS;
}
return Math.min(timeoutMs, WECHAT_BIND_LONG_POLL_TIMEOUT_MS);
}
shouldUseWechatBindLongPoll(data = {}, state = null) {
if (!state || state.status === 'bound') {
return false;
}
if (data.forceRefresh) {
return false;
}
if (data.isInit === true || data.init === true || data.firstLoad === true) {
return false;
}
const explicitEnable = data.longPoll === true || data.waitForChange === true;
return explicitEnable;
}
async publishWechatBindEvent(accountId, payload = {}) {
const { app } = this;
if (!accountId) {
return;
}
const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null;
if (!cacheRedis) {
return;
}
const channel = this.getWechatBindEventChannel(accountId);
const eventData = {
account_id: accountId,
event_at: new Date().toISOString(),
...payload,
};
try {
await cacheRedis.publish(channel, JSON.stringify(eventData));
} catch (error) {
app.coreLogger.warn(`发布微信绑定事件失败: ${error.message}`);
}
}
async waitForWechatBindEvent(accountId, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) {
const { app } = this;
const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null;
if (!cacheRedis || !accountId || typeof cacheRedis.duplicate !== 'function') {
return {
timed_out: true,
reason: 'redis_not_available',
};
}
const channel = this.getWechatBindEventChannel(accountId);
const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs);
const subscriber = cacheRedis.duplicate();
return await new Promise(resolve => {
let settled = false;
let timer = null;
const cleanup = () => {
subscriber.removeListener('message', onMessage);
subscriber.removeListener('error', onError);
Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => {
if (typeof subscriber.quit === 'function') {
Promise.resolve(subscriber.quit()).catch(() => {
if (typeof subscriber.disconnect === 'function') {
subscriber.disconnect();
}
});
return;
}
if (typeof subscriber.disconnect === 'function') {
subscriber.disconnect();
}
});
};
const finalize = result => {
if (settled) {
return;
}
settled = true;
if (timer) {
clearTimeout(timer);
}
cleanup();
resolve(result);
};
const onMessage = (messageChannel, message) => {
if (messageChannel !== channel) {
return;
}
let eventData = null;
try {
eventData = message ? JSON.parse(message) : null;
} catch (error) {
eventData = { raw: message };
}
finalize({
timed_out: false,
reason: 'event',
event: eventData,
});
};
const onError = error => {
app.coreLogger.warn(`订阅微信绑定事件失败: ${error.message}`);
finalize({
timed_out: true,
reason: 'subscribe_error',
});
};
timer = setTimeout(() => {
finalize({
timed_out: true,
reason: 'timeout',
});
}, waitMs);
subscriber.on('message', onMessage);
subscriber.on('error', onError);
Promise.resolve(subscriber.subscribe(channel)).catch(error => {
app.coreLogger.warn(`订阅微信绑定频道失败: ${error.message}`);
finalize({
timed_out: true,
reason: 'subscribe_failed',
});
});
});
}
async refreshWechatBindState(accountId, cachedState = null) {
const now = Date.now();
const cacheKey = this.getWechatBindCacheKey(accountId);
const ye4sBinding = await this.findYe4sBindingByAccountId(accountId);
if (ye4sBinding) {
const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : '';
const bindState = {
account_id: accountId,
status: 'bound',
code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(),
updated_at: new Date().toISOString(),
next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: ye4sBinding.id || null,
};
await Promise.all([
this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS),
this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS),
]);
const hasChanged = !cachedState || cachedState.status !== 'bound' || cachedState.code !== bindState.code;
if (hasChanged) {
await this.publishWechatBindEvent(accountId, {
status: 'bound',
code: bindState.code,
source: 'db',
});
}
return {
state: bindState,
source: 'db',
message: '账号已绑定微信',
};
}
const code = (cachedState && cachedState.code) || this.createWechatBindCode();
const pendingState = {
account_id: accountId,
status: 'pending',
code,
updated_at: new Date().toISOString(),
next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: null,
};
await Promise.all([
this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS),
this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS),
]);
return {
state: pendingState,
source: code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated',
message: '账号未绑定,已生成绑定码',
};
}
/**
* 用户登录(重构版)
* @param {string} username - 用户名/手机号/邮箱
@ -256,6 +462,7 @@ class UserService extends Service {
const cacheKey = this.getWechatBindCacheKey(accountId);
const forceRefresh = !!data.forceRefresh;
const now = Date.now();
const waitTimeoutMs = this.getWechatLongPollTimeoutMs(data.waitTimeoutMs);
let cachedState = null;
try {
@ -266,57 +473,55 @@ class UserService extends Service {
if (cachedState && !forceRefresh) {
const nextCheckAt = Number(cachedState.next_db_check_at || 0);
if (nextCheckAt > now) {
let refreshedState = null;
if (nextCheckAt <= now) {
refreshedState = await this.refreshWechatBindState(accountId, cachedState);
cachedState = refreshedState.state;
}
if (this.shouldUseWechatBindLongPoll(data, cachedState)) {
const waitResult = await this.waitForWechatBindEvent(accountId, waitTimeoutMs);
try {
cachedState = await this.app.getCacheAsync(cacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`);
}
const nextState = await this.refreshWechatBindState(accountId, cachedState);
const timeoutMessage = waitResult.timed_out ? '等待绑定状态变化超时,返回当前状态' : nextState.message;
return {
success: true,
code: 200,
data: this.formatBindWechatData(cachedState, 'cache'),
message: '获取绑定码成功(缓存)',
data: this.formatBindWechatData(nextState.state, nextState.source),
message: timeoutMessage,
};
}
}
const ye4sBinding = await this.findYe4sBindingByAccountId(accountId);
if (ye4sBinding) {
const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : '';
const bindState = {
account_id: accountId,
status: 'bound',
code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(),
updated_at: new Date().toISOString(),
next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: ye4sBinding.id || null,
};
await this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS);
await this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS);
if (refreshedState) {
return {
success: true,
code: 200,
data: this.formatBindWechatData(refreshedState.state, refreshedState.source),
message: refreshedState.message,
};
}
return {
success: true,
code: 200,
data: this.formatBindWechatData(bindState, 'db'),
message: '账号已绑定微信',
data: this.formatBindWechatData(cachedState, 'cache'),
message: '获取绑定码成功(缓存)',
};
}
const code = (cachedState && cachedState.code) || this.createWechatBindCode();
const pendingState = {
account_id: accountId,
status: 'pending',
code,
updated_at: new Date().toISOString(),
next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: null,
};
await this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS);
await this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS);
const refreshed = await this.refreshWechatBindState(accountId, cachedState);
return {
success: true,
code: 200,
data: this.formatBindWechatData(pendingState, code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated'),
message: '账号未绑定,已生成绑定码',
data: this.formatBindWechatData(refreshed.state, refreshed.source),
message: refreshed.message,
};
} catch (error) {
app.coreLogger.error(`获取微信绑定码失败: ${error.message}`);
@ -395,8 +600,15 @@ class UserService extends Service {
next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS,
ye4s_user_id: ye4sUser.id || null,
};
await this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS);
await this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS);
await Promise.all([
this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS),
this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS),
]);
await this.publishWechatBindEvent(wmsAccountId, {
status: 'bound',
code,
source: 'api',
});
return {
success: true,
@ -486,6 +698,10 @@ class UserService extends Service {
await this.setWechatBindCodeCache(cachedState.code, null, 1);
}
await this.setWechatBindCache(cacheKey, null, 1);
await this.publishWechatBindEvent(accountId, {
status: 'unbound',
source: 'unbind',
});
return {
success: true,

View File

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

View File

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

View File

@ -2,6 +2,15 @@
const Service = require('egg').Service;
class ReceivingService extends Service {
/**
* 查询收货单列表。
* @param {Object} where 动态筛选条件
* @param {Object} [pageParams] 分页参数
* @param {number} [pageParams.page=1] 页码
* @param {number} [pageParams.pageSize=20] 每页条数
* @param {Object} [sortParams] 排序参数
* @return {Promise<Object>} 列表、分页与汇总信息
*/
async getReceivingList(where, pageParams = {}, sortParams = {}) {
const {
ctx,
@ -277,8 +286,12 @@ class ReceivingService extends Service {
};
}
}
/*
* 获取收货单详情
/**
* 获取收货单详情(主单 + 明细分页 + 图片)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {Object} data.pagination 分页参数
* @return {Promise<Object>} 详情数据
*/
async getReceivingDetail(data) {
const { id, pagination } = data;
@ -358,7 +371,12 @@ class ReceivingService extends Service {
return { code: 500, message: '服务器错误', data: {} };
}
}
//批量作废
/**
* 批量作废收货单。
* @param {Object} data 请求体
* @param {number[]} data.ids 收货单ID数组
* @return {Promise<Object>} 作废处理结果
*/
async batchCancelReceiving(data) {
const { ids } = data;
const { ctx } = this;
@ -638,6 +656,12 @@ class ReceivingService extends Service {
return value;
}
}
/**
* 创建收货单并生成收货单号。
* @param {Object} data 创建参数
* @return {Promise<Object>} 新建结果(含 id 与 receiving_number)
*/
async create(data) {
const {
delivery_method,
@ -753,6 +777,13 @@ class ReceivingService extends Service {
};
}
}
/**
* 查询单个收货单完整信息(含明细、图片)。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @return {Promise<Object>} 单据详情
*/
async get(data) {
const { id } = data;
const { ctx, app } = this;
@ -881,6 +912,13 @@ class ReceivingService extends Service {
return { code: 500, message: '服务器错误', data: {} };
}
}
/**
* 向收货单新增一条默认明细。
* @param {Object} data 请求体
* @param {number} data.receiving_id 收货单ID
* @return {Promise<Object>} 明细列表与默认选中ID
*/
async addDetail(data) {
const ctx = this.ctx;
const { receiving_id } = data;
@ -1303,6 +1341,12 @@ class ReceivingService extends Service {
}
}
/**
* 删除收货单明细并回算统计。
* @param {Object} data 请求体
* @param {number} data.detail_id 明细ID
* @return {Promise<Object>} 删除结果
*/
async deleteDetail(data) {
const ctx = this.ctx;
const { detail_id } = data;
@ -1408,6 +1452,11 @@ class ReceivingService extends Service {
};
}
}
/**
* 修改收货明细信息并触发库存/统计联动。
* @param {Object} data 请求体
* @return {Promise<Object>} 修改结果
*/
async detailChange(data) {
const { ctx, app } = this;
const warehouseId = ctx.user.store_id;
@ -1752,6 +1801,13 @@ class ReceivingService extends Service {
throw error;
}
}
/**
* 完成收货单:校验明细、更新状态并写入库存。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {string} [data.remark] 完成备注
* @return {Promise<Object>} 完成结果
*/
async completeReceiving(data) {
const { ctx, app } = this;
const warehouseId = ctx.user.store_id;

View File

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

View File

@ -9,25 +9,55 @@
"type": "string",
"required": true,
"description": "客户端平台标识,如 web/pda/app",
"list":[
{"value":"web","name":"网页端"},
{"value":"pda","name":"PDA端"},
{"value":"app","name":"APP端"},
{"value":"wx","name":"微信端"},
{"value":"miniProgram","name":"小程序端"},
{"value":"other","name":"其他"}
"list": [
{
"value": "web",
"name": "网页端"
},
{
"value": "pda",
"name": "PDA端"
},
{
"value": "app",
"name": "APP端"
},
{
"value": "wx",
"name": "微信端"
},
{
"value": "miniProgram",
"name": "小程序端"
},
{
"value": "other",
"name": "其他"
}
]
},
{
"type":"string",
"required":true,
"name":"project",
"description":"项目标识,如 all/warehouse/store/tms",
"list":[
{"value":"all","name":"全部"},
{"value":"warehouse","name":"仓库"},
{"value":"store","name":"货主"},
{"value":"tms","name":"物流"}
"type": "string",
"required": true,
"name": "project",
"description": "项目标识,如 all/warehouse/store/tms",
"list": [
{
"value": "all",
"name": "全部"
},
{
"value": "warehouse",
"name": "仓库"
},
{
"value": "store",
"name": "货主"
},
{
"value": "tms",
"name": "物流"
}
]
}
],
@ -1488,6 +1518,116 @@
"response": [],
"errors": []
},
{
"method": "setting.printTemplate.create",
"description": "创建打印模板(platform 固定为 default,template_type 固定为 CUSTOM,template_url 固定为空字符串)",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "template_name",
"type": "string",
"required": true,
"source": "body",
"description": "模板名称"
},
{
"name": "business_type",
"type": "string",
"required": true,
"source": "body",
"description": "业务类型"
},
{
"name": "page_width",
"type": "number",
"required": true,
"source": "body",
"description": "页面宽度(mm)"
},
{
"name": "page_height",
"type": "number",
"required": true,
"source": "body",
"description": "页面高度(mm)"
},
{
"name": "template_content",
"type": "array",
"required": false,
"source": "body",
"description": "模板内容,可省略;省略时默认创建空模板内容"
}
],
"response": [
{
"name": "id",
"type": "number",
"required": true,
"description": "新建模板ID"
}
],
"errors": [
{
"code": "400",
"description": "参数错误(缺少 template_name、business_type、page_width 或 page_height)"
},
{
"code": "409",
"description": "同一业务类型和平台下已存在自定义模板"
}
]
},
{
"method": "setting.printTemplate.delete",
"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": "参数错误(缺少 id)"
},
{
"code": "404",
"description": "模板不存在或无权限"
}
]
},
{
"method": "setting.printTemplate.listTemplatesByType",
"description": "按业务类型查询模板",
@ -1516,12 +1656,12 @@
]
},
{
"groupName": "库存模块",
"groupName": "商品模块",
"module": "stock",
"list": [
{
"method": "stock.stockWarehouse",
"description": "stock.stockWarehouse 接口",
"method": "stock.warehouse.list",
"description": "仓库商品列表查询(支持 where 条件与分页)",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -1552,8 +1692,8 @@
"errors": []
},
{
"method": "stock.getProhibitedType",
"description": "stock.getProhibitedType 接口",
"method": "stock.warehouse.getProhibitedType",
"description": "查询违禁品类型列表(系统预设+仓库自定义)",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -1569,8 +1709,8 @@
"errors": []
},
{
"method": "stock.getInfo",
"description": "stock.getInfo 接口",
"method": "stock.warehouse.getInfo",
"description": "查询仓库商品详情",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -1586,8 +1726,8 @@
"errors": []
},
{
"method": "stock.saveWarehouseStock",
"description": "stock.saveWarehouseStock 接口",
"method": "stock.warehouse.saveWarehouseStock",
"description": "更新仓库商品资料",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
@ -1603,8 +1743,8 @@
"errors": []
},
{
"method": "stock.createWarehouseStock",
"description": "stock.createWarehouseStock 接口",
"method": "stock.warehouse.createWarehouseStock",
"description": "新建仓库商品资料",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
@ -1620,8 +1760,8 @@
"errors": []
},
{
"method": "stock.getBarcodes",
"description": "stock.getBarcodes 接口",
"method": "stock.warehouse.getBarcodes",
"description": "查询商品条码列表",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -1637,8 +1777,8 @@
"errors": []
},
{
"method": "stock.saveWarehouseStockBarcode",
"description": "stock.saveWarehouseStockBarcode 接口",
"method": "stock.warehouse.saveWarehouseStockBarcode",
"description": "保存商品条码信息",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
@ -1654,8 +1794,8 @@
"errors": []
},
{
"method": "stock.getStoreStocks",
"description": "stock.getStoreStocks 接口",
"method": "stock.warehouse.getStoreStocks",
"description": "查询仓库商品与货主关联列表",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -1671,8 +1811,8 @@
"errors": []
},
{
"method": "stock.bindItem",
"description": "stock.bindItem 接口",
"method": "stock.warehouse.bindItem",
"description": "绑定货主商品关系",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
@ -1688,8 +1828,8 @@
"errors": []
},
{
"method": "stock.unbindItem",
"description": "stock.unbindItem 接口",
"method": "stock.warehouse.unbindItem",
"description": "解绑货主商品关系",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
@ -1705,8 +1845,8 @@
"errors": []
},
{
"method": "stock.checkItemCodeUnique",
"description": "stock.checkItemCodeUnique 接口",
"method": "stock.warehouse.checkItemCodeUnique",
"description": "校验商品编码在货主维度唯一性",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -1744,8 +1884,8 @@
"errors": []
},
{
"method": "stock.queryStockLogs",
"description": "stock.queryStockLogs 接口",
"method": "stock.warehouse.queryStockLogs",
"description": "查询库存操作日志",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -1769,8 +1909,8 @@
"errors": []
},
{
"method": "stock.handleBatchDelete",
"description": "stock.handleBatchDelete 接口",
"method": "stock.warehouse.handleBatchDelete",
"description": "批量删除仓库商品资料",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
@ -1786,8 +1926,8 @@
"errors": []
},
{
"method": "stock.deleteUnit",
"description": "stock.deleteUnit 接口",
"method": "stock.warehouse.deleteUnit",
"description": "删除库存单位",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
@ -1803,8 +1943,8 @@
"errors": []
},
{
"method": "stock.deleteProhibited",
"description": "stock.deleteProhibited 接口",
"method": "stock.warehouse.deleteProhibited",
"description": "删除违禁品类型",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
@ -1820,8 +1960,8 @@
"errors": []
},
{
"method": "stock.handleBatchChange",
"description": "stock.handleBatchChange 接口",
"method": "stock.warehouse.handleBatchChange",
"description": "批量修改仓库商品字段",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
@ -1837,8 +1977,8 @@
"errors": []
},
{
"method": "stock.getStockUnits",
"description": "stock.getStockUnits 接口",
"method": "stock.warehouse.getStockUnits",
"description": "查询可用库存单位(系统+仓库)",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -1854,8 +1994,8 @@
"errors": []
},
{
"method": "stock.getUnitList",
"description": "stock.getUnitList 接口",
"method": "stock.warehouse.getUnitList",
"description": "查询当前仓库自定义单位列表",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -1871,8 +2011,8 @@
"errors": []
},
{
"method": "stock.createProhibited",
"description": "stock.createProhibited 接口",
"method": "stock.warehouse.createProhibited",
"description": "新增违禁品类型",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
@ -1896,8 +2036,8 @@
"errors": []
},
{
"method": "stock.createUnit",
"description": "stock.createUnit 接口",
"method": "stock.warehouse.createUnit",
"description": "新增库存单位",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
@ -1921,8 +2061,8 @@
"errors": []
},
{
"method": "stock.search",
"description": "stock.search 接口",
"method": "stock.warehouse.search",
"description": "仓库商品关键字搜索",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -1940,8 +2080,8 @@
]
},
{
"groupName": "入库模块",
"module": "storage.receiving",
"groupName": "库存模块",
"module": "storage",
"list": [
{
"method": "storage.receiving.getReceivingList",
@ -1962,18 +2102,42 @@
"type": "object",
"required": false,
"source": "body",
"description": "pagination 参数"
"description": "分页参数,支持 page/pageSize"
},
{
"name": "where",
"type": "object",
"required": false,
"source": "body",
"description": "where 参数"
"description": "筛选参数,支持 quickWhere、status、store_id、日期区间等"
}
],
"response": [],
"errors": []
"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_quantity、total_locked、total_available、total_items)"
}
],
"errors": [
{
"code": "500",
"description": "查询失败"
}
]
},
{
"method": "storage.receiving.getReceivingDetail",
@ -1988,9 +2152,40 @@
"description": "Bearer token"
}
],
"params": [],
"response": [],
"errors": []
"params": [
{
"name": "id",
"type": "number",
"required": true,
"source": "body",
"description": "收货单ID"
},
{
"name": "pagination",
"type": "object",
"required": true,
"source": "body",
"description": "明细分页参数,支持 page/pageSize"
}
],
"response": [
{
"name": "receiving",
"type": "object",
"required": true,
"description": "收货单详情(含 details、images、pagination)"
}
],
"errors": [
{
"code": "0",
"description": "无记录或无权访问"
},
{
"code": "500",
"description": "服务器错误"
}
]
},
{
"method": "storage.receiving.batchCancelReceiving",
@ -2005,9 +2200,33 @@
"description": "Bearer token"
}
],
"params": [],
"response": [],
"errors": []
"params": [
{
"name": "ids",
"type": "array",
"required": true,
"source": "body",
"description": "待作废收货单ID数组"
}
],
"response": [
{
"name": "message",
"type": "string",
"required": true,
"description": "批量作废处理结果"
}
],
"errors": [
{
"code": "0",
"description": "部分单据不存在、无权访问或状态不允许作废"
},
{
"code": "500",
"description": "服务器错误"
}
]
},
{
"method": "storage.receiving.create",
@ -2022,9 +2241,84 @@
"description": "Bearer token"
}
],
"params": [],
"response": [],
"errors": []
"params": [
{
"name": "delivery_method",
"type": "string",
"required": true,
"source": "body",
"description": "到货方式:truck/express/air_freight/sea_freight/other"
},
{
"name": "loading_method",
"type": "string",
"required": true,
"source": "body",
"description": "装卸方式:with_pallet/without_pallet"
},
{
"name": "license_plate",
"type": "string",
"required": false,
"source": "body",
"description": "车牌号(delivery_method=truck 时建议传)"
},
{
"name": "tracking_number",
"type": "string",
"required": false,
"source": "body",
"description": "物流单号(非 truck/other 场景建议传)"
},
{
"name": "store_id",
"type": "number",
"required": false,
"source": "body",
"description": "货主ID"
},
{
"name": "total_boxes",
"type": "number",
"required": false,
"source": "body",
"description": "总箱数"
},
{
"name": "total_pallets",
"type": "number",
"required": false,
"source": "body",
"description": "总托盘数"
},
{
"name": "remark",
"type": "string",
"required": false,
"source": "body",
"description": "备注"
}
],
"response": [
{
"name": "id",
"type": "number",
"required": true,
"description": "新建收货单ID"
},
{
"name": "receiving_number",
"type": "string",
"required": true,
"description": "收货单号"
}
],
"errors": [
{
"code": "0",
"description": "创建失败(如字段枚举不合法、数据库约束异常)"
}
]
},
{
"method": "storage.receiving.addItem",
@ -2212,7 +2506,7 @@
]
},
{
"groupName": "门店模块",
"groupName": "主体模块",
"module": "store",
"list": [
{
@ -2412,7 +2706,7 @@
},
{
"method": "user.getBindWechatCode",
"description": "获取微信绑定码(支持轮询,缓存优先)",
"description": "获取微信绑定码(默认立即返回;显式开启长轮询后,最长等待60秒,状态变化立即返回)",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -2430,6 +2724,34 @@
"required": false,
"source": "body",
"description": "是否强制刷新状态,true 时跳过缓存等待窗口"
},
{
"name": "waitForChange",
"type": "boolean",
"required": false,
"source": "body",
"description": "是否显式开启长轮询等待(推荐字段);true 时进入最长60秒等待"
},
{
"name": "longPoll",
"type": "boolean",
"required": false,
"source": "body",
"description": "长轮询开关(兼容字段);true 时进入最长60秒等待"
},
{
"name": "waitTimeoutMs",
"type": "number",
"required": false,
"source": "body",
"description": "等待超时毫秒数;后端自动封顶60000"
},
{
"name": "init",
"type": "boolean",
"required": false,
"source": "body",
"description": "初始化请求标记;true 时强制立即返回,不进入长等待"
}
],
"response": [],
@ -3308,4 +3630,4 @@
}
]
}
}
}

112
stock.todo Normal file
View File

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

View File

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

View File

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

View File

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

View File

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