Compare commits
14 Commits
1537c1ac10
...
81350c0d6b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81350c0d6b | ||
|
|
b2ae5683e1 | ||
|
|
888d026145 | ||
|
|
510b87632a | ||
|
|
3c53b3c8fa | ||
|
|
972c912e53 | ||
|
|
f40370baca | ||
|
|
b485f8e9f1 | ||
|
|
5b3180ff34 | ||
|
|
19c3fe09a7 | ||
|
|
7ff7285222 | ||
|
|
aedd815e17 | ||
|
|
a69fd3f393 | ||
|
|
52aa76af60 |
115
app/model/camera.js
Normal file
115
app/model/camera.js
Normal file
@ -0,0 +1,115 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, INTEGER, DATE, TINYINT } = app.Sequelize;
|
||||
|
||||
const Camera = app.model.define('camera', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
server_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属录像服务器ID,关联 wms_camera_server.id',
|
||||
},
|
||||
channel_id: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '通道编号(DVR/NVR 上的物理通道号)',
|
||||
},
|
||||
channel_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '通道原始名称',
|
||||
},
|
||||
ip: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '摄像头IP地址',
|
||||
},
|
||||
port: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: 'SDK管理端口(通常2020/8000)',
|
||||
},
|
||||
model: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '摄像头型号',
|
||||
},
|
||||
serial_number: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '摄像头序列号',
|
||||
},
|
||||
stream_type: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: '码流类型(auto/main/sub)',
|
||||
},
|
||||
custom_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '自定义摄像头名称',
|
||||
},
|
||||
status: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:0-禁用 1-启用',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_camera',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
comment: '摄像头表',
|
||||
indexes: [
|
||||
{ name: 'idx_warehouse_id', fields: ['warehouse_id'] },
|
||||
{ name: 'idx_server_id', fields: ['server_id'] },
|
||||
{ name: 'uk_server_channel', unique: true, fields: ['server_id', 'channel_id', 'deleted_at'] },
|
||||
{ name: 'idx_status', fields: ['status'] },
|
||||
{ name: 'idx_deleted_at', fields: ['deleted_at'] },
|
||||
],
|
||||
});
|
||||
|
||||
Camera.associate = () => {
|
||||
app.model.Camera.belongsTo(app.model.CameraServer, {
|
||||
foreignKey: 'server_id',
|
||||
targetKey: 'id',
|
||||
as: 'server',
|
||||
});
|
||||
};
|
||||
|
||||
return Camera;
|
||||
};
|
||||
100
app/model/camera_server.js
Normal file
100
app/model/camera_server.js
Normal file
@ -0,0 +1,100 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, INTEGER, DATE, TINYINT } = app.Sequelize;
|
||||
|
||||
const CameraServer = app.model.define('camera_server', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
name: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '服务器名称',
|
||||
},
|
||||
brand: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '品牌(如 Hikvision/Dahua)',
|
||||
},
|
||||
public_ip: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '公网IP',
|
||||
},
|
||||
internal_ip: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '内网IP',
|
||||
},
|
||||
public_port: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '远程/公网端口',
|
||||
},
|
||||
internal_port: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '本地/内网端口',
|
||||
},
|
||||
username: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '登录账号',
|
||||
},
|
||||
password: {
|
||||
type: STRING(200),
|
||||
allowNull: true,
|
||||
comment: '登录密码',
|
||||
},
|
||||
status: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:0-禁用 1-启用',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_camera_server',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
comment: '录像服务器表',
|
||||
indexes: [
|
||||
{ name: 'idx_warehouse_id', fields: ['warehouse_id'] },
|
||||
{ name: 'idx_status', fields: ['status'] },
|
||||
{ name: 'idx_deleted_at', fields: ['deleted_at'] },
|
||||
],
|
||||
});
|
||||
|
||||
return CameraServer;
|
||||
};
|
||||
@ -180,6 +180,12 @@ module.exports = app => {
|
||||
defaultValue: 0,
|
||||
comment: '是否隐藏物品信息',
|
||||
},
|
||||
is_enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: true,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用(1=启用,0=停用)',
|
||||
},
|
||||
shipperno: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
|
||||
@ -81,9 +81,10 @@ module.exports = app => {
|
||||
comment: '体积(m³)',
|
||||
},
|
||||
max_weight: {
|
||||
type: DECIMAL(10, 2),
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '最大承重(kg)',
|
||||
defaultValue: 0,
|
||||
comment: '最大承重(g)',
|
||||
},
|
||||
space_status: {
|
||||
type: ENUM('AVAILABLE', 'OCCUPIED', 'RESERVED', 'MAINTENANCE', 'DISABLED'),
|
||||
@ -110,10 +111,10 @@ module.exports = app => {
|
||||
comment: '当前库存数量',
|
||||
},
|
||||
current_weight: {
|
||||
type: DECIMAL(10, 2),
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '当前重量(kg)',
|
||||
comment: '当前重量(g)',
|
||||
},
|
||||
current_volume: {
|
||||
type: DECIMAL(10, 2),
|
||||
|
||||
@ -391,10 +391,10 @@ module.exports = app => {
|
||||
comment: '商品总数',
|
||||
},
|
||||
items_weight: {
|
||||
type: DECIMAL(10, 2),
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0.00,
|
||||
comment: '总重量(kg)',
|
||||
defaultValue: 0,
|
||||
comment: '总重量(g)',
|
||||
},
|
||||
items_hash: {
|
||||
type: CHAR(32),
|
||||
|
||||
@ -133,9 +133,10 @@ module.exports = app => {
|
||||
comment: '包材名称快照',
|
||||
},
|
||||
weighing_weight: {
|
||||
type: DECIMAL(10, 3),
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '称重重量(kg)',
|
||||
defaultValue: 0,
|
||||
comment: '称重重量(g)',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_order_express',
|
||||
|
||||
164
app/model/pack_task.js
Normal file
164
app/model/pack_task.js
Normal file
@ -0,0 +1,164 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, INTEGER, DATE, TINYINT, TEXT, JSON: JSON_TYPE } = app.Sequelize;
|
||||
|
||||
const PackTask = app.model.define('pack_task', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
order_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '订单ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
workbench_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '工作台ID,关联 wms_workbench.id',
|
||||
},
|
||||
wave_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '波次ID',
|
||||
},
|
||||
wave_no: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '波次号',
|
||||
},
|
||||
waybill_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '运单号',
|
||||
},
|
||||
pack_quantity: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '打包数量(件数)',
|
||||
},
|
||||
item_quantity: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '商品总数量',
|
||||
},
|
||||
sku_count: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '商品种类数(SKU数)',
|
||||
},
|
||||
pack_mode: {
|
||||
type: TINYINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '打包模式:1=散单 2=团购',
|
||||
},
|
||||
status: {
|
||||
type: TINYINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '任务状态:0=待处理 1=打包中 2=已完成 3=异常',
|
||||
},
|
||||
start_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '开始打包时间',
|
||||
},
|
||||
end_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '结束打包时间',
|
||||
},
|
||||
operator_text: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '作业人员(自由文本,如多人逗号分隔)',
|
||||
},
|
||||
device_ids: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
comment: '设备ID列表,如 [1,2,3]',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
meta: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
comment: '扩展信息JSON',
|
||||
},
|
||||
create_time: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
update_time: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_pack_task',
|
||||
timestamps: true,
|
||||
createdAt: 'create_time',
|
||||
updatedAt: 'update_time',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
comment: '打包任务表(含作业记录)',
|
||||
indexes: [
|
||||
{ name: 'idx_order_id', fields: [ 'order_id' ] },
|
||||
{ name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] },
|
||||
{ name: 'idx_workbench_id', fields: [ 'workbench_id' ] },
|
||||
{ name: 'idx_wave_id', fields: [ 'wave_id' ] },
|
||||
{ name: 'idx_waybill_code', fields: [ 'waybill_code' ] },
|
||||
{ name: 'idx_pack_mode_status', fields: [ 'pack_mode', 'status' ] },
|
||||
{ name: 'idx_start_time', fields: [ 'start_time' ] },
|
||||
{ name: 'idx_status', fields: [ 'status' ] },
|
||||
],
|
||||
});
|
||||
|
||||
PackTask.associate = () => {
|
||||
app.model.PackTask.belongsTo(app.model.Workbench, {
|
||||
foreignKey: 'workbench_id',
|
||||
targetKey: 'id',
|
||||
as: 'workbench',
|
||||
});
|
||||
app.model.PackTask.hasMany(app.model.PackTaskVideo, {
|
||||
foreignKey: 'pack_task_id',
|
||||
sourceKey: 'id',
|
||||
as: 'videos',
|
||||
});
|
||||
app.model.PackTask.hasMany(app.model.PackTaskPacker, {
|
||||
foreignKey: 'pack_task_id',
|
||||
sourceKey: 'id',
|
||||
as: 'packers',
|
||||
});
|
||||
app.model.PackTask.hasMany(app.model.OrderExpress, {
|
||||
foreignKey: 'order_id',
|
||||
sourceKey: 'order_id',
|
||||
as: 'expresses',
|
||||
});
|
||||
};
|
||||
|
||||
return PackTask;
|
||||
};
|
||||
78
app/model/pack_task_packer.js
Normal file
78
app/model/pack_task_packer.js
Normal file
@ -0,0 +1,78 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, DATE, TINYINT } = app.Sequelize;
|
||||
|
||||
const PackTaskPacker = app.model.define('pack_task_packer', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
pack_task_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '打包任务ID,关联 wms_pack_task.id',
|
||||
},
|
||||
account_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '账号ID,关联 wms_account.id',
|
||||
},
|
||||
account_name: {
|
||||
type: STRING(128),
|
||||
allowNull: false,
|
||||
comment: '账号姓名快照',
|
||||
},
|
||||
seq: {
|
||||
type: TINYINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '排序序号',
|
||||
},
|
||||
create_time: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
update_time: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_pack_task_packer',
|
||||
timestamps: true,
|
||||
createdAt: 'create_time',
|
||||
updatedAt: 'update_time',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
comment: '打包任务-打包人关系表',
|
||||
indexes: [
|
||||
{ name: 'uix_pack_task_account', fields: [ 'pack_task_id', 'account_id' ], unique: true },
|
||||
{ name: 'idx_account_id', fields: [ 'account_id' ] },
|
||||
{ name: 'idx_pack_task_id', fields: [ 'pack_task_id' ] },
|
||||
],
|
||||
});
|
||||
|
||||
PackTaskPacker.associate = () => {
|
||||
app.model.PackTaskPacker.belongsTo(app.model.PackTask, {
|
||||
foreignKey: 'pack_task_id',
|
||||
targetKey: 'id',
|
||||
as: 'packTask',
|
||||
});
|
||||
app.model.PackTaskPacker.belongsTo(app.model.Account, {
|
||||
foreignKey: 'account_id',
|
||||
targetKey: 'id',
|
||||
as: 'account',
|
||||
});
|
||||
};
|
||||
|
||||
return PackTaskPacker;
|
||||
};
|
||||
83
app/model/pack_task_video.js
Normal file
83
app/model/pack_task_video.js
Normal file
@ -0,0 +1,83 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, DATE } = app.Sequelize;
|
||||
|
||||
const PackTaskVideo = app.model.define('pack_task_video', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
pack_task_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '打包任务ID,关联 wms_pack_task.id',
|
||||
},
|
||||
camera_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '摄像头设备ID,关联 wms_camera.id',
|
||||
},
|
||||
video_url: {
|
||||
type: STRING(500),
|
||||
allowNull: false,
|
||||
comment: '视频地址(录像回放URL)',
|
||||
},
|
||||
status: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'created',
|
||||
comment: '状态:created-已创建 recording-录制中 completed-已完成 failed-失败',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_pack_task_video',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
comment: '打包任务视频记录表',
|
||||
indexes: [
|
||||
{ name: 'idx_pack_task_id', fields: [ 'pack_task_id' ] },
|
||||
{ name: 'idx_camera_id', fields: [ 'camera_id' ] },
|
||||
{ name: 'idx_deleted_at', fields: [ 'deleted_at' ] },
|
||||
],
|
||||
});
|
||||
|
||||
PackTaskVideo.associate = () => {
|
||||
app.model.PackTaskVideo.belongsTo(app.model.PackTask, {
|
||||
foreignKey: 'pack_task_id',
|
||||
targetKey: 'id',
|
||||
as: 'packTask',
|
||||
});
|
||||
app.model.PackTaskVideo.belongsTo(app.model.Camera, {
|
||||
foreignKey: 'camera_id',
|
||||
targetKey: 'id',
|
||||
as: 'camera',
|
||||
});
|
||||
};
|
||||
|
||||
return PackTaskVideo;
|
||||
};
|
||||
@ -57,9 +57,10 @@ module.exports = app => {
|
||||
comment: '高度(cm)',
|
||||
},
|
||||
weight: {
|
||||
type: DECIMAL(10, 3),
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '重量(kg)',
|
||||
defaultValue: 0,
|
||||
comment: '重量(g)',
|
||||
},
|
||||
cost_price: {
|
||||
type: DECIMAL(10, 2),
|
||||
|
||||
@ -72,9 +72,9 @@ module.exports = app => {
|
||||
comment: '高(cm)快照',
|
||||
},
|
||||
weight: {
|
||||
type: DECIMAL(10, 2),
|
||||
type: INTEGER(11),
|
||||
defaultValue: 0,
|
||||
comment: '重量(kg)快照',
|
||||
comment: '重量(g)快照',
|
||||
},
|
||||
bind_count: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { INTEGER, BIGINT, STRING, DATE } = app.Sequelize;
|
||||
const { INTEGER, BIGINT, STRING, DATE, BOOLEAN } = app.Sequelize;
|
||||
|
||||
const PrintComputer = app.model.define('print_computer', {
|
||||
id: {
|
||||
@ -32,6 +32,42 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '上次登录时间',
|
||||
},
|
||||
is_recording: {
|
||||
type: BOOLEAN,
|
||||
allowNull: false,
|
||||
defaultValue: false,
|
||||
comment: '是否作为录制电脑,1-是,0-否',
|
||||
},
|
||||
recording_size_value: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '录制大小数值',
|
||||
},
|
||||
recording_size_unit: {
|
||||
type: STRING(10),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '录制存储单位:KB/MB/GB/TB',
|
||||
},
|
||||
remote_play_url: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '远程播放地址',
|
||||
},
|
||||
recording_directory: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '录制目录路径',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_print_computer',
|
||||
freezeTableName: true,
|
||||
|
||||
@ -136,6 +136,12 @@ module.exports = app => {
|
||||
defaultValue: 0,
|
||||
comment: '软删除标记:0-未删除,1-已删除',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
subject_config: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
|
||||
@ -105,7 +105,10 @@ module.exports = app => {
|
||||
type: DECIMAL(10, 2),
|
||||
},
|
||||
weight: {
|
||||
type: INTEGER,
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '重量(g)',
|
||||
},
|
||||
box_remainder: {
|
||||
type: INTEGER,
|
||||
@ -114,10 +117,10 @@ module.exports = app => {
|
||||
comment: '箱余数',
|
||||
},
|
||||
box_weight: {
|
||||
type: DECIMAL(10, 2),
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: '0.00',
|
||||
comment: '箱重量(kg)',
|
||||
defaultValue: 0,
|
||||
comment: '箱重量(g)',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_receiving_detail',
|
||||
|
||||
@ -130,22 +130,16 @@ module.exports = app => {
|
||||
comment: '体积',
|
||||
},
|
||||
gross_weight: {
|
||||
type: DECIMAL(10, 2),
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
defaultValue: 0.00,
|
||||
validate: {
|
||||
min: 0,
|
||||
},
|
||||
comment: '毛重',
|
||||
defaultValue: 0,
|
||||
comment: '毛重(g)',
|
||||
},
|
||||
net_weight: {
|
||||
type: DECIMAL(10, 2),
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
defaultValue: 0.00,
|
||||
validate: {
|
||||
min: 0,
|
||||
},
|
||||
comment: '净重',
|
||||
defaultValue: 0,
|
||||
comment: '净重(g)',
|
||||
},
|
||||
category_id: {
|
||||
type: INTEGER(11),
|
||||
|
||||
@ -11,9 +11,9 @@ module.exports = app => {
|
||||
comment: '主键ID',
|
||||
},
|
||||
transaction_type: {
|
||||
type: ENUM('INBOUND', 'OUTBOUND', 'LOCK'),
|
||||
type: ENUM('INBOUND', 'OUTBOUND', 'LOCK', 'UNLOCK'),
|
||||
allowNull: false,
|
||||
comment: '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定',
|
||||
comment: '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定 UNLOCK取消锁定',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
|
||||
@ -72,14 +72,14 @@ module.exports = app => {
|
||||
comment: '体积',
|
||||
},
|
||||
gross_weight: {
|
||||
type: DECIMAL(10, 2),
|
||||
defaultValue: 0.00,
|
||||
comment: '毛重',
|
||||
type: INTEGER(11),
|
||||
defaultValue: 0,
|
||||
comment: '毛重(g)',
|
||||
},
|
||||
net_weight: {
|
||||
type: DECIMAL(10, 2),
|
||||
defaultValue: 0.00,
|
||||
comment: '净重',
|
||||
type: INTEGER(11),
|
||||
defaultValue: 0,
|
||||
comment: '净重(g)',
|
||||
},
|
||||
item_type: {
|
||||
type: STRING(10),
|
||||
@ -170,10 +170,12 @@ module.exports = app => {
|
||||
box_gross_weight: {
|
||||
type: INTEGER(11),
|
||||
defaultValue: 0,
|
||||
comment: '箱毛重(g)',
|
||||
},
|
||||
box_net_weight: {
|
||||
type: INTEGER(11),
|
||||
defaultValue: 0,
|
||||
comment: '箱净重(g)',
|
||||
},
|
||||
box_height: {
|
||||
type: DECIMAL(10, 2),
|
||||
|
||||
82
app/model/workbench.js
Normal file
82
app/model/workbench.js
Normal file
@ -0,0 +1,82 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, DATE, TINYINT, ENUM, JSON: JSON_TYPE } = app.Sequelize;
|
||||
|
||||
const Workbench = app.model.define('workbench', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
name: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '工作台名称(用户自定义)',
|
||||
},
|
||||
barcode: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '工作台条码(用户自定义,仓库内唯一)',
|
||||
},
|
||||
status: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:0-禁用 1-启用',
|
||||
},
|
||||
type: {
|
||||
type: ENUM('personal', 'group'),
|
||||
allowNull: false,
|
||||
defaultValue: 'personal',
|
||||
comment: '工作台类型:personal-个人工作台 group-团体工作台',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
device_ids: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
comment: '设备ID列表,如 [1,2,3],触发打包任务时透传到 wms_pack_task.device_ids',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_workbench',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
comment: '工作台表',
|
||||
indexes: [
|
||||
{ name: 'idx_warehouse_id', fields: ['warehouse_id'] },
|
||||
{ name: 'idx_barcode', fields: ['barcode'] },
|
||||
{ name: 'uk_warehouse_barcode', unique: true, fields: ['warehouse_id', 'barcode', 'deleted_at'] },
|
||||
{ name: 'idx_deleted_at', fields: ['deleted_at'] },
|
||||
],
|
||||
});
|
||||
|
||||
return Workbench;
|
||||
};
|
||||
@ -2,6 +2,69 @@
|
||||
|
||||
const SHORT_TASK_QUERY_TIMEOUT_MS = 15000;
|
||||
const SHORT_TASK_EXECUTION_TIMEOUT_MS = 30000;
|
||||
const EXECUTION_LOG_CACHE_KEY = 'schedule:sync_outbound_orders_to_delivery:last_execution';
|
||||
const EXECUTION_LOG_CACHE_TTL = 300; // 5 分钟
|
||||
|
||||
/**
|
||||
* 将本次执行日志写入缓存。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @param {Object} logEntry 日志条目。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function writeExecutionLogToCache(ctx, logEntry) {
|
||||
try {
|
||||
if (ctx.app && typeof ctx.app.setCacheAsync === 'function') {
|
||||
await ctx.app.setCacheAsync(EXECUTION_LOG_CACHE_KEY, logEntry, EXECUTION_LOG_CACHE_TTL);
|
||||
}
|
||||
} catch (err) {
|
||||
// 缓存写入失败不影响主流程
|
||||
ctx.logger.warn(`[sync-outbound-orders-to-delivery] 写入执行日志缓存失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取错误详情,方便定位问题位置。
|
||||
*
|
||||
* @param {Error} error 错误对象。
|
||||
* @return {Object} 错误详情。
|
||||
*/
|
||||
function extractErrorDetail(error) {
|
||||
if (!error) return {};
|
||||
|
||||
const detail = {
|
||||
name: error.name || '',
|
||||
message: error.message || '',
|
||||
code: error.code || '',
|
||||
};
|
||||
|
||||
// Sequelize 父级错误(通常包含 SQL 信息)
|
||||
if (error.parent) {
|
||||
detail.parent = {
|
||||
name: error.parent.name || '',
|
||||
message: error.parent.message || '',
|
||||
code: error.parent.code || '',
|
||||
sql: error.parent.sql || '',
|
||||
};
|
||||
}
|
||||
|
||||
// SequelizeValidationError 的 fields 列表
|
||||
if (Array.isArray(error.errors)) {
|
||||
detail.validation_errors = error.errors.map(e => ({
|
||||
message: e.message,
|
||||
type: e.type,
|
||||
path: e.path,
|
||||
value: String(e.value ?? ''),
|
||||
}));
|
||||
}
|
||||
|
||||
// 堆栈前 3 行(定位调用链)
|
||||
if (error.stack) {
|
||||
detail.stack_top = error.stack.split('\n').slice(0, 4).map(s => s.trim());
|
||||
}
|
||||
|
||||
return detail;
|
||||
}
|
||||
|
||||
/**
|
||||
* 每 1 分钟在单 worker 中同步一次正常出库订单到配送表。
|
||||
@ -31,21 +94,51 @@ module.exports = {
|
||||
|
||||
ctx.app._syncOutboundOrdersToDeliveryRunning = true;
|
||||
|
||||
const startedAt = Date.now();
|
||||
let status = 'success';
|
||||
let errorMessage = '';
|
||||
let errorDetail = null;
|
||||
let result = null;
|
||||
|
||||
try {
|
||||
const result = await ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery({
|
||||
result = await ctx.service.systems.orderDeliveryMigration.syncOutboundOrdersToDelivery({
|
||||
queryTimeoutMs: SHORT_TASK_QUERY_TIMEOUT_MS,
|
||||
executionTimeoutMs: SHORT_TASK_EXECUTION_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
if (result && result.retryableFailure) {
|
||||
status = 'retryable_failure';
|
||||
errorMessage = `retryableFailureType=${result.retryableFailureType}, timeoutCount=${result.timeoutCount || 0}`;
|
||||
ctx.logger.warn(`[sync-outbound-orders-to-delivery] 正常迁移遇到 ${result.retryableFailureType},已标记 ${result.timeoutCount || 0} 条订单为出库超时`);
|
||||
} else if (result && result.totalCreated > 0) {
|
||||
ctx.logger.info(`[sync-outbound-orders-to-delivery] 同步 ${result.totalCreated} 条已出库订单`);
|
||||
}
|
||||
|
||||
// 始终输出汇总日志(含 0 条场景,确认定时任务在跑)
|
||||
ctx.logger.info(`[sync-outbound-orders-to-delivery] 本轮完成 selected=${result ? result.totalSelected : 0} created=${result ? result.totalCreated : 0} skipped=${result ? result.totalSkipped : 0} timeout=${result ? result.totalTimeout : 0}`);
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[sync-outbound-orders-to-delivery] 同步失败: ${error.message}`);
|
||||
status = 'error';
|
||||
errorMessage = error.message;
|
||||
errorDetail = extractErrorDetail(error);
|
||||
ctx.logger.error(`[sync-outbound-orders-to-delivery] 同步失败: ${error.message}`, errorDetail);
|
||||
} finally {
|
||||
ctx.app._syncOutboundOrdersToDeliveryRunning = false;
|
||||
}
|
||||
|
||||
// 写入执行日志到缓存
|
||||
const logEntry = {
|
||||
executed_at: new Date().toISOString(),
|
||||
duration_ms: Date.now() - startedAt,
|
||||
status,
|
||||
error_message: errorMessage,
|
||||
error_detail: errorDetail,
|
||||
total_selected: result ? result.totalSelected : 0,
|
||||
total_created: result ? result.totalCreated : 0,
|
||||
total_skipped: result ? result.totalSkipped : 0,
|
||||
total_timeout: result ? result.totalTimeout : 0,
|
||||
warehouse_ids: result ? result.warehouseIds : [],
|
||||
};
|
||||
await writeExecutionLogToCache(ctx, logEntry);
|
||||
ctx.logger.info(`[sync-outbound-orders-to-delivery] 执行日志已写入缓存 key=${EXECUTION_LOG_CACHE_KEY}`);
|
||||
},
|
||||
};
|
||||
|
||||
@ -46,7 +46,7 @@ module.exports = {
|
||||
|
||||
for (const warehouseId of warehouseIds) {
|
||||
try {
|
||||
const submitPayload = await ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse(warehouseId, { wait: true });
|
||||
const submitPayload = await ctx.service.systemMethods.order.wave.submitWaveStrategyQuickScanForWarehouse(warehouseId, { wait: true, forceRescan: true });
|
||||
const submitMessage = String(submitPayload && submitPayload.message || '').trim();
|
||||
const submitState = String(submitPayload && submitPayload.state || '').trim();
|
||||
const isReusedRunningTask = submitMessage.includes('已有快速扫描任务在运行中')
|
||||
|
||||
@ -14,8 +14,10 @@ class systemService extends Service {
|
||||
const classs = servicePath.split('.');
|
||||
let systemMethods = this.ctx.service.systemMethods;
|
||||
for (let i = 0; i < classs.length; i++) {
|
||||
const className = classs[i];
|
||||
systemMethods = systemMethods[className];
|
||||
const rawClassName = classs[i];
|
||||
// Egg.js 将文件名 snake_case 自动转为 camelCase,需做对应转换
|
||||
const camelName = rawClassName.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
||||
systemMethods = systemMethods[camelName] || systemMethods[rawClassName];
|
||||
}
|
||||
// 检查服务是否存在
|
||||
if (!systemMethods) {
|
||||
|
||||
54
app/service/systemMethods/camera.js
Normal file
54
app/service/systemMethods/camera.js
Normal file
@ -0,0 +1,54 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
class CameraService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,detail';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'list,detail';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
async list(data) {
|
||||
try {
|
||||
const result = await this.service.systems.camera.list(data || {});
|
||||
return this.success('获取成功', result);
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
async detail(data) {
|
||||
try {
|
||||
const { id } = data || {};
|
||||
if (!id) return this.fail('ID不能为空');
|
||||
return this.success('获取成功', await this.service.systems.camera.detail(parseInt(id)));
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
async create(data) {
|
||||
try {
|
||||
return this.success('创建成功', await this.service.systems.camera.create(data));
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
async update(data) {
|
||||
try {
|
||||
const { id, ...fields } = data || {};
|
||||
if (!id) return this.fail('ID不能为空');
|
||||
return this.success('更新成功', await this.service.systems.camera.update(parseInt(id), fields));
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
async delete(data) {
|
||||
try {
|
||||
const { id } = data || {};
|
||||
if (!id) return this.fail('ID不能为空');
|
||||
await this.service.systems.camera.delete(parseInt(id));
|
||||
return this.success('删除成功');
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CameraService;
|
||||
54
app/service/systemMethods/cameraServer.js
Normal file
54
app/service/systemMethods/cameraServer.js
Normal file
@ -0,0 +1,54 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
class CameraServerService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,detail';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'list,detail';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
async list(data) {
|
||||
try {
|
||||
const result = await this.service.systems.cameraServer.list(data || {});
|
||||
return this.success('获取成功', result);
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
async detail(data) {
|
||||
try {
|
||||
const { id } = data || {};
|
||||
if (!id) return this.fail('ID不能为空');
|
||||
return this.success('获取成功', await this.service.systems.cameraServer.detail(parseInt(id)));
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
async create(data) {
|
||||
try {
|
||||
return this.success('创建成功', await this.service.systems.cameraServer.create(data));
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
async update(data) {
|
||||
try {
|
||||
const { id, ...fields } = data || {};
|
||||
if (!id) return this.fail('ID不能为空');
|
||||
return this.success('更新成功', await this.service.systems.cameraServer.update(parseInt(id), fields));
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
async delete(data) {
|
||||
try {
|
||||
const { id } = data || {};
|
||||
if (!id) return this.fail('ID不能为空');
|
||||
await this.service.systems.cameraServer.delete(parseInt(id));
|
||||
return this.success('删除成功');
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CameraServerService;
|
||||
@ -47,11 +47,11 @@ class dashboardService extends MainService {
|
||||
}
|
||||
|
||||
// 跨仓并行查询并汇总
|
||||
const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseStats(wid).catch(() => null)));
|
||||
const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseStats(wid, storeId).catch(() => null)));
|
||||
return this.success('ok', this.mergeStoreStats(results.filter(Boolean)));
|
||||
}
|
||||
|
||||
async queryWarehouseStats(warehouseId) {
|
||||
async queryWarehouseStats(warehouseId, storeId = null) {
|
||||
const { ctx } = this;
|
||||
const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
const { Sequelize } = ctx.app;
|
||||
@ -61,9 +61,10 @@ class dashboardService extends MainService {
|
||||
step: { [Op.in]: [ 1, 2, 3 ] },
|
||||
outbound_status: { [Op.ne]: 'padding' },
|
||||
status: { [Op.ne]: 'cancel' },
|
||||
store_id: { [Op.in]: [] }, // 占位,后续填充
|
||||
};
|
||||
delete pendingBase.store_id;
|
||||
if (storeId) {
|
||||
pendingBase.store_id = storeId;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
@ -89,7 +90,7 @@ class dashboardService extends MainService {
|
||||
model.count({ where: { ...pendingBase, print_status: 'none' } }),
|
||||
model.count({ where: { ...pendingBase, pick_status: 'none' } }),
|
||||
model.count({ where: { ...pendingBase, outbound_status: { [Op.ne]: 'fin' } } }),
|
||||
model.count({ where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: { [Op.gte]: todayStart, [Op.lt]: todayEnd } } }),
|
||||
model.count({ where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: { [Op.gte]: todayStart, [Op.lt]: todayEnd }, ...(storeId ? { store_id: storeId } : {}) } }),
|
||||
model.count({ where: { ...pendingBase, intercept_status: { [Op.not]: null, [Op.ne]: 'none' } } }),
|
||||
model.count({ where: { ...pendingBase, step: 3 } }),
|
||||
]);
|
||||
|
||||
@ -1053,9 +1053,9 @@ class indexService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl';
|
||||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder';
|
||||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder';
|
||||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getImages,getMessageDetail,searchSpace,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
async fastWhereTree(data) {
|
||||
@ -1069,6 +1069,11 @@ class indexService extends MainService {
|
||||
const result = await service.systems.store.loadStores();
|
||||
return this.success('ok', { stores: result, code: 200 });
|
||||
}
|
||||
async loadWarehouses() {
|
||||
const { service } = this;
|
||||
const result = await service.systems.store.loadWarehouses();
|
||||
return this.success('ok', { warehouses: result, code: 200 });
|
||||
}
|
||||
async getCOSUploadConfig(datas) {
|
||||
const { service } = this;
|
||||
const { data } = datas;
|
||||
|
||||
@ -581,13 +581,24 @@ class OrderBaseService extends MainService {
|
||||
async getOrderModel(moduleName = 'order', warehouseId = null) {
|
||||
const { ctx } = this;
|
||||
const config = this.getModuleConfig(moduleName);
|
||||
const contextWarehouseId = this.getWarehouseId();
|
||||
let contextWarehouseId = this.getWarehouseId();
|
||||
|
||||
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
|
||||
const hasContextWarehouseId = contextWarehouseId !== null
|
||||
&& contextWarehouseId !== undefined
|
||||
&& contextWarehouseId !== '';
|
||||
const hasParamWarehouseId = warehouseId !== null
|
||||
&& warehouseId !== undefined
|
||||
&& warehouseId !== '';
|
||||
|
||||
if (!hasContextWarehouseId && !hasParamWarehouseId) {
|
||||
throw new Error('缺少当前用户仓库上下文 store_id');
|
||||
}
|
||||
|
||||
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
|
||||
if (!hasContextWarehouseId) {
|
||||
contextWarehouseId = warehouseId;
|
||||
}
|
||||
|
||||
if (hasContextWarehouseId && hasParamWarehouseId
|
||||
&& String(warehouseId) !== String(contextWarehouseId)) {
|
||||
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
|
||||
}
|
||||
@ -646,15 +657,26 @@ class OrderBaseService extends MainService {
|
||||
*/
|
||||
async getOrderModelByTableType(tableType = 'current', warehouseId = this.getWarehouseId()) {
|
||||
const { ctx } = this;
|
||||
const contextWarehouseId = this.getWarehouseId();
|
||||
let contextWarehouseId = this.getWarehouseId();
|
||||
const normalizedTableType = this.resolveOrderTableType({ tableType });
|
||||
const actualWarehouseId = warehouseId ?? contextWarehouseId;
|
||||
|
||||
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
|
||||
const hasContextWarehouseId = contextWarehouseId !== null
|
||||
&& contextWarehouseId !== undefined
|
||||
&& contextWarehouseId !== '';
|
||||
const hasActualWarehouseId = actualWarehouseId !== null
|
||||
&& actualWarehouseId !== undefined
|
||||
&& actualWarehouseId !== '';
|
||||
|
||||
if (!hasContextWarehouseId && !hasActualWarehouseId) {
|
||||
throw new Error('缺少当前用户仓库上下文 store_id');
|
||||
}
|
||||
|
||||
if (actualWarehouseId !== null && actualWarehouseId !== undefined && actualWarehouseId !== ''
|
||||
if (!hasContextWarehouseId) {
|
||||
contextWarehouseId = actualWarehouseId;
|
||||
}
|
||||
|
||||
if (hasContextWarehouseId && hasActualWarehouseId
|
||||
&& String(actualWarehouseId) !== String(contextWarehouseId)) {
|
||||
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
|
||||
}
|
||||
@ -680,15 +702,26 @@ class OrderBaseService extends MainService {
|
||||
*/
|
||||
async getOrderItemsModelByTableType(tableType = 'current', warehouseId = this.getWarehouseId()) {
|
||||
const { ctx } = this;
|
||||
const contextWarehouseId = this.getWarehouseId();
|
||||
let contextWarehouseId = this.getWarehouseId();
|
||||
const normalizedTableType = this.resolveOrderTableType({ tableType });
|
||||
const actualWarehouseId = warehouseId ?? contextWarehouseId;
|
||||
|
||||
if (contextWarehouseId === null || contextWarehouseId === undefined || contextWarehouseId === '') {
|
||||
const hasContextWarehouseId = contextWarehouseId !== null
|
||||
&& contextWarehouseId !== undefined
|
||||
&& contextWarehouseId !== '';
|
||||
const hasActualWarehouseId = actualWarehouseId !== null
|
||||
&& actualWarehouseId !== undefined
|
||||
&& actualWarehouseId !== '';
|
||||
|
||||
if (!hasContextWarehouseId && !hasActualWarehouseId) {
|
||||
throw new Error('缺少当前用户仓库上下文 store_id');
|
||||
}
|
||||
|
||||
if (actualWarehouseId !== null && actualWarehouseId !== undefined && actualWarehouseId !== ''
|
||||
if (!hasContextWarehouseId) {
|
||||
contextWarehouseId = actualWarehouseId;
|
||||
}
|
||||
|
||||
if (hasContextWarehouseId && hasActualWarehouseId
|
||||
&& String(actualWarehouseId) !== String(contextWarehouseId)) {
|
||||
throw new Error('订单工作台仓库ID必须来自当前用户上下文 store_id,禁止传入外部仓库ID。');
|
||||
}
|
||||
|
||||
@ -436,7 +436,7 @@ class OrderIndexService extends OrderBaseService {
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} [data.waybill_code] 运单号,多运单场景或运单号模式必填。
|
||||
* @param {number|string} data.order_id 订单ID,传 0 时切换为运单号模式。
|
||||
* @param {number|string} data.weighing_weight 称重重量(kg)。
|
||||
* @param {number|string} data.weighing_weight 称重重量(g)。
|
||||
* @return {Promise<Object>} 统一成功/失败结构。
|
||||
* 订单模式单订单:{data: {order_id, waybill_code, weighing_weight}};
|
||||
* 订单模式团购批量:{data: {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name}};
|
||||
|
||||
94
app/service/systemMethods/order/packing.js
Normal file
94
app/service/systemMethods/order/packing.js
Normal file
@ -0,0 +1,94 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
/**
|
||||
* 系统方法层:order.packing(打包任务接口包装层)。
|
||||
* 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。
|
||||
* 注意:当前实现仅为包装层,实际业务逻辑完全依赖底层 service 的方法实现。
|
||||
*/
|
||||
class OrderPackingMethodService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,get';
|
||||
const _noNeedLog = 'list,get';
|
||||
const _noNeedAuth = 'list,get';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打包任务列表查询(仓库侧 system method 包装层)。
|
||||
* 按仓库维度查询打包任务,支持分页、筛选、排序。
|
||||
*
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.pagination] 分页参数 { page, pageSize }
|
||||
* @param {Object} [data.where] 筛选条件。
|
||||
* 支持字段:status(任务状态)、pack_mode(打包模式)、waybill_code(运单号)、wave_no(波次号)、
|
||||
* order_id(订单ID)、workbench_id(工作台ID)、quickWhere(快捷搜索:波次号直接匹配 + 运单号通过express→order→wave链路解析)、
|
||||
* start_time_start / start_time_end(开始打包时间范围)。
|
||||
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder }
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
async list(data = {}) {
|
||||
const { service } = this;
|
||||
const { pagination, sort } = data;
|
||||
const { where } = this.prepareWhereContext(data, {
|
||||
specialFieldMap: {
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
},
|
||||
});
|
||||
const result = await service.systems.orderPacking.list(where, pagination, sort);
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打包任务详情查询(仓库侧 system method 包装层)。
|
||||
*
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 打包任务ID
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
async get(data = {}) {
|
||||
const { service } = this;
|
||||
const { id } = data;
|
||||
const result = await service.systems.orderPacking.get({ id });
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置打包任务结束时间(仓库侧 system method 包装层)。
|
||||
* 若任务状态不是已完成,则同步更新状态为已完成。
|
||||
* 前端默认值逻辑:已有结束时间→当前时间;无结束时间→开始时间+5分钟。
|
||||
*
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 打包任务ID
|
||||
* @param {string} data.end_time 结束时间(ISO 8601 或日期字符串)
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
async setEndTime(data = {}) {
|
||||
const { service } = this;
|
||||
const { id, end_time } = data;
|
||||
const result = await service.systems.orderPacking.setEndTime({ id, end_time });
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制重新录制打包任务视频(仓库侧 system method 包装层)。
|
||||
* 将该任务推送到录制电脑,通过打印服务触发重新录制。
|
||||
*
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 打包任务ID
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
async forceRecord(data = {}) {
|
||||
const { service } = this;
|
||||
const { id } = data;
|
||||
const result = await service.systems.orderPacking.forceRecord({ id });
|
||||
return this.success('ok', result);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderPackingMethodService;
|
||||
@ -3191,7 +3191,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
data: {
|
||||
model: 'deepseek-chat',
|
||||
model: 'deepseek-v4-pro',
|
||||
messages: [
|
||||
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
|
||||
{ role: 'user', content: prompt },
|
||||
@ -3207,6 +3207,7 @@ class PendingOrderService extends OrderBaseService {
|
||||
}
|
||||
|
||||
const content = result.data.choices?.[0]?.message?.content || '';
|
||||
this.ctx.logger.info('[parseAddress] DeepSeek原始返回content: %s', content);
|
||||
|
||||
// 清理可能的 markdown 代码块标记
|
||||
let jsonStr = content.trim();
|
||||
|
||||
@ -12,7 +12,7 @@ class OrderPrintService extends OrderBaseService {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
|
||||
const _noNeedLog = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
|
||||
const _noNeedLog = 'getWavePrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
|
||||
const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -10,9 +10,9 @@ class RecheckOrderService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck';
|
||||
const _noNeedRight = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,queryRecheckOrderSingleList';
|
||||
const _noNeedLog = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck';
|
||||
const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck';
|
||||
const _noNeedAuth = 'scanOrder,scanTask,scanWaybill,confirmRecheck,recheckOrderList,confirmIntercept,batchQuickRecheck,queryRecheckOrderSingleList';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -751,6 +751,9 @@ class RecheckOrderService extends OrderBaseService {
|
||||
images: Array.isArray(item.images) ? [ ...item.images ] : [],
|
||||
has_shared_barcode: Boolean(item.has_shared_barcode),
|
||||
plan_qty: Number(item.plan_qty || 0),
|
||||
store_id: item.store_id != null ? Number(item.store_id) : 0,
|
||||
owner_code: String(item.owner_code || '').trim(),
|
||||
store_remark: String(item.store_remark || '').trim(),
|
||||
}));
|
||||
|
||||
// 构建拦截订单列表
|
||||
@ -761,9 +764,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
intercept_status: String(order.intercept_status || '').trim(),
|
||||
}));
|
||||
|
||||
// 提取正常(非拦截)订单的 ID 列表
|
||||
const orderIds = normalOrders.map(order => Number(order.order_id || 0)).filter(id => id > 0);
|
||||
|
||||
// 计算波次内复核统计(基于非拦截订单的 recheck_status 实时聚合)
|
||||
const reviewedCount = normalOrders.filter(o => String(o.recheck_status || '').trim() === 'fin').length;
|
||||
const unreviewedCount = normalOrders.length - reviewedCount;
|
||||
@ -786,8 +786,9 @@ class RecheckOrderService extends OrderBaseService {
|
||||
update_time: waveView.update_time,
|
||||
order_count: waveView.order_count,
|
||||
box_no: Number(tw.box_no || 0),
|
||||
order_ids: orderIds,
|
||||
stocks,
|
||||
store_id: sampleOrder ? Number(sampleOrder.store_id || 0) : 0,
|
||||
store_remark: sampleOrder ? String(sampleOrder.store_remark || '').trim() : '',
|
||||
reviewed_count: reviewedCount,
|
||||
unreviewed_count: unreviewedCount,
|
||||
printed_count: printedCount,
|
||||
@ -1043,7 +1044,7 @@ class RecheckOrderService extends OrderBaseService {
|
||||
const waybillMap = new Map();
|
||||
if (orderIds.length > 0 && ctx.model && ctx.model.OrderExpress) {
|
||||
const expressRows = await ctx.model.OrderExpress.findAll({
|
||||
where: { order_id: orderIds },
|
||||
where: { order_id: orderIds, warehouse_id: warehouseId },
|
||||
attributes: [ 'order_id', 'waybill_code' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
@ -1118,6 +1119,7 @@ class RecheckOrderService extends OrderBaseService {
|
||||
order_type: String(row.order_type || '').trim(),
|
||||
status: Number(row.status || 0),
|
||||
logistics_name: String(row.logistics_name || '').trim(),
|
||||
store_id: Number(row.store_id || 0),
|
||||
store_remark: storeRemarkMap.has(Number(row.store_id || 0))
|
||||
? storeRemarkMap.get(Number(row.store_id || 0))
|
||||
: '',
|
||||
@ -1257,7 +1259,7 @@ class RecheckOrderService extends OrderBaseService {
|
||||
where: {
|
||||
order_id: { [this.app.Sequelize.Op.in]: orderIds },
|
||||
},
|
||||
attributes: [ 'order_id', 'stock_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot' ],
|
||||
attributes: [ 'order_id', 'stock_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot', 'owner_code' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
@ -1297,6 +1299,32 @@ class RecheckOrderService extends OrderBaseService {
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 批量查询货主备注名(wms_store_warehouse.store_remask),按 store_id 映射
|
||||
const storeRemarkMapByStock = new Map();
|
||||
if (stockMap.size > 0 && this.ctx.model && this.ctx.model.StoreWarehouse) {
|
||||
const storeIdsForRemark = [ ...new Set(
|
||||
[ ...stockMap.values() ]
|
||||
.map(detail => Number(detail.store_id || 0))
|
||||
.filter(id => id > 0)
|
||||
) ];
|
||||
if (storeIdsForRemark.length > 0) {
|
||||
const swRows = await this.ctx.model.StoreWarehouse.findAll({
|
||||
where: {
|
||||
store_id: { [this.app.Sequelize.Op.in]: storeIdsForRemark },
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const sw of (Array.isArray(swRows) ? swRows : [])) {
|
||||
const sid = Number(sw.store_id || 0);
|
||||
if (sid > 0 && !storeRemarkMapByStock.has(sid)) {
|
||||
storeRemarkMapByStock.set(sid, String(sw.store_remask || '').trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 检测共享条码:查询当前所有条码是否也出现在其他 stock_id 中
|
||||
const sharedBarcodeSet = new Set();
|
||||
if (barcodeMap.size > 0) {
|
||||
@ -1369,6 +1397,9 @@ class RecheckOrderService extends OrderBaseService {
|
||||
images,
|
||||
has_shared_barcode: hasSharedBarcode,
|
||||
plan_qty: Number(item.plan_qty || 0),
|
||||
store_id: stockInfo.store_id != null ? Number(stockInfo.store_id) : 0,
|
||||
owner_code: String(item.owner_code || '').trim(),
|
||||
store_remark: storeRemarkMapByStock.get(stockInfo.store_id != null ? Number(stockInfo.store_id) : 0) || '',
|
||||
};
|
||||
});
|
||||
|
||||
@ -3145,7 +3176,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
o.weight_type,
|
||||
o.status,
|
||||
o.create_at,
|
||||
o.pick_time,
|
||||
o.recheck_time
|
||||
FROM ${orderTableName} o
|
||||
${whereClause}
|
||||
@ -3191,7 +3221,6 @@ class RecheckOrderService extends OrderBaseService {
|
||||
weight_type: this.formatWeightTypeLabel(row?.weight_type),
|
||||
status: Number(row?.status || 0),
|
||||
create_at: row?.create_at || null,
|
||||
pick_time: row?.pick_time || null,
|
||||
recheck_time: row?.recheck_time || null,
|
||||
}));
|
||||
|
||||
@ -3927,6 +3956,7 @@ class RecheckOrderService extends OrderBaseService {
|
||||
await orderModel.update(
|
||||
{
|
||||
recheck_status: 'fin',
|
||||
print_status: 'fin',
|
||||
recheck_time: now,
|
||||
updated_at: now,
|
||||
},
|
||||
|
||||
@ -21,7 +21,7 @@ const BATCH_ALLOCATE_EXPRESS_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
|
||||
const BATCH_ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX = 'wave:batch-allocate-storage:';
|
||||
const BATCH_ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
|
||||
const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_KEY_PREFIX = 'wave:quick-scan:task:';
|
||||
const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_TTL_SECONDS = 60 * 60 * 24;
|
||||
const WAVE_STRATEGY_QUICK_SCAN_TASK_CACHE_TTL_SECONDS = 60 * 5;
|
||||
const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_CACHE_KEY_PREFIX = 'wave:quick-scan:lock:';
|
||||
const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_TTL_SECONDS = 60 * 60 * 2;
|
||||
const WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX = 'wave:strategy-list:';
|
||||
@ -5244,6 +5244,7 @@ class WaveService extends OrderBaseService {
|
||||
const normalizedOptions = this.isPlainObject(options) ? options : {};
|
||||
const orderIds = this.normalizeIdsInput(normalizedOptions.orderIds);
|
||||
const wait = this.normalizeBoolean(normalizedOptions.wait, false);
|
||||
const forceRescan = this.normalizeBoolean(normalizedOptions.forceRescan, false);
|
||||
|
||||
const runningTask = await this.getWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId);
|
||||
if (runningTask && runningTask.task_id) {
|
||||
@ -5282,6 +5283,7 @@ class WaveService extends OrderBaseService {
|
||||
error: '',
|
||||
error_code: '',
|
||||
result: null,
|
||||
...(forceRescan ? { force_rescan: true } : {}),
|
||||
});
|
||||
|
||||
await this.setWaveStrategyQuickScanWarehouseLock(normalizedWarehouseId, taskId, {
|
||||
@ -5294,6 +5296,7 @@ class WaveService extends OrderBaseService {
|
||||
taskId,
|
||||
warehouseId: normalizedWarehouseId,
|
||||
...(orderIds.length > 0 ? { orderIds } : {}),
|
||||
...(forceRescan ? { forceRescan } : {}),
|
||||
});
|
||||
|
||||
const finalProgress = await this.getWaveStrategyQuickScanTaskProgress(taskId) || {};
|
||||
@ -5310,6 +5313,7 @@ class WaveService extends OrderBaseService {
|
||||
taskId,
|
||||
warehouseId: normalizedWarehouseId,
|
||||
...(orderIds.length > 0 ? { orderIds } : {}),
|
||||
...(forceRescan ? { forceRescan } : {}),
|
||||
}).catch(error => {
|
||||
this.ctx.logger.error('[wave.waveStrategyQuickScan] 后台任务异常', {
|
||||
taskId,
|
||||
@ -5396,9 +5400,10 @@ class WaveService extends OrderBaseService {
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {number} strategyVersion 当前策略版本号。
|
||||
* @param {Array<number|string>} [orderIds=[]] 限定扫描订单ID数组。
|
||||
* @param {boolean} [forceRescan=false] 是否强制全量重扫(忽略版本号条件)。
|
||||
* @return {Object} 订单查询 where 条件。
|
||||
*/
|
||||
buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds = []) {
|
||||
buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds = [], forceRescan = false) {
|
||||
const normalizedOrderIds = this.normalizeIdsInput(orderIds);
|
||||
const where = {
|
||||
warehouse_id: warehouseId,
|
||||
@ -5407,11 +5412,14 @@ class WaveService extends OrderBaseService {
|
||||
intercept_status: 'none',
|
||||
lock_status: 'none',
|
||||
print_status: { [Op.ne]: 'fin' },
|
||||
[Op.or]: [
|
||||
};
|
||||
|
||||
if (!forceRescan) {
|
||||
where[Op.or] = [
|
||||
{ wave_strategy_version: { [Op.ne]: strategyVersion } },
|
||||
{ wave_strategy_version: { [Op.is]: null } },
|
||||
],
|
||||
};
|
||||
];
|
||||
}
|
||||
|
||||
if (normalizedOrderIds.length > 0) {
|
||||
where.id = {
|
||||
@ -5704,6 +5712,7 @@ class WaveService extends OrderBaseService {
|
||||
const strategyVersion = this.normalizeWaveStrategyQuickScanVersion(normalizedOptions.strategyVersion);
|
||||
const taskId = String(normalizedOptions.taskId || '').trim();
|
||||
const orderIds = this.normalizeIdsInput(normalizedOptions.orderIds);
|
||||
const forceRescan = this.normalizeBoolean(normalizedOptions.forceRescan, false);
|
||||
|
||||
const strategyRows = await this.getWaveStrategyQuickScanStrategyRows(warehouseId);
|
||||
const strategyList = this.normalizeWaveStrategyQuickScanList(strategyRows);
|
||||
@ -5724,7 +5733,7 @@ class WaveService extends OrderBaseService {
|
||||
'sys_platform_code',
|
||||
'source_platform_code',
|
||||
],
|
||||
where: this.buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds),
|
||||
where: this.buildWaveStrategyQuickScanOrderWhere(warehouseId, strategyVersion, orderIds, forceRescan),
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -5874,6 +5883,10 @@ class WaveService extends OrderBaseService {
|
||||
? normalizedParams.order_ids
|
||||
: normalizedParams.ids;
|
||||
const orderIds = this.normalizeIdsInput(rawOrderIds);
|
||||
const forceRescan = this.normalizeBoolean(
|
||||
normalizedParams.forceRescan ?? normalizedParams.force_rescan,
|
||||
false
|
||||
);
|
||||
|
||||
const subjectConfig = await this.getWarehouseSubjectConfig(warehouseId);
|
||||
const strategyVersion = this.normalizeWaveStrategyQuickScanVersion(
|
||||
@ -5885,6 +5898,7 @@ class WaveService extends OrderBaseService {
|
||||
strategyVersion,
|
||||
orderIds,
|
||||
taskId: normalizedTaskId,
|
||||
forceRescan,
|
||||
});
|
||||
|
||||
if (scanResult.totalOrderCount === 0) {
|
||||
|
||||
81
app/service/systemMethods/printComputer.js
Normal file
81
app/service/systemMethods/printComputer.js
Normal file
@ -0,0 +1,81 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
class PrintComputerService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = '';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = '';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印电脑列表。
|
||||
* @param {Object} data 查询参数 { pagination, where }
|
||||
* @return {Promise<Object>} 列表数据与分页信息
|
||||
*/
|
||||
async list(data) {
|
||||
try {
|
||||
const result = await this.service.systems.printComputer.list(data || {});
|
||||
return this.success('获取成功', result);
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新打印电脑。
|
||||
* @param {Object} data { id, name? }
|
||||
* @return {Promise<Object>} 更新后的电脑记录
|
||||
*/
|
||||
async update(data) {
|
||||
try {
|
||||
const { id, ...fields } = data || {};
|
||||
if (!id) return this.fail('ID不能为空');
|
||||
return this.success('更新成功', await this.service.systems.printComputer.update(parseInt(id), fields));
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置录制电脑(会先取消同仓库下其他录制电脑)。
|
||||
* @param {Object} data { id, recording_size_value, recording_size_unit, remote_play_url, recording_directory }
|
||||
* @return {Promise<Object>} 设置结果
|
||||
*/
|
||||
async setRecording(data) {
|
||||
try {
|
||||
const { id, ...fields } = data || {};
|
||||
if (!id) return this.fail('ID不能为空');
|
||||
return this.success('设置录制成功', await this.service.systems.printComputer.setRecording(parseInt(id), fields));
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消录制电脑。
|
||||
* @param {Object} data { id }
|
||||
* @return {Promise<Object>} 取消结果
|
||||
*/
|
||||
async cancelRecording(data) {
|
||||
try {
|
||||
const { id } = data || {};
|
||||
if (!id) return this.fail('ID不能为空');
|
||||
return this.success('取消录制成功', await this.service.systems.printComputer.cancelRecording(parseInt(id)));
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
/**
|
||||
* 软删除打印电脑。
|
||||
* @param {Object} data { id }
|
||||
* @return {Promise<Object>} 删除结果
|
||||
*/
|
||||
async delete(data) {
|
||||
try {
|
||||
const { id } = data || {};
|
||||
if (!id) return this.fail('ID不能为空');
|
||||
await this.service.systems.printComputer.delete(parseInt(id));
|
||||
return this.success('删除成功');
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PrintComputerService;
|
||||
@ -110,6 +110,9 @@ class expressInterfaceService extends MainService {
|
||||
shop_name: {
|
||||
field: 'shop_name',
|
||||
},
|
||||
is_enabled: {
|
||||
field: 'is_enabled',
|
||||
},
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
@ -269,6 +272,8 @@ class expressInterfaceService extends MainService {
|
||||
providerType,
|
||||
providerid,
|
||||
providerId,
|
||||
is_enabled: isEnabledSnake,
|
||||
isEnabled: isEnabledCamel,
|
||||
...rest
|
||||
} = data || {};
|
||||
|
||||
@ -328,6 +333,9 @@ class expressInterfaceService extends MainService {
|
||||
if (providerid !== undefined || providerId !== undefined) {
|
||||
payload.providerid = providerid !== undefined ? providerid : providerId;
|
||||
}
|
||||
if (isEnabledSnake !== undefined || isEnabledCamel !== undefined) {
|
||||
payload.is_enabled = isEnabledSnake !== undefined ? isEnabledSnake : isEnabledCamel;
|
||||
}
|
||||
|
||||
return await this.callSystemExpressInterface('update', payload, '更新快递接口失败');
|
||||
}
|
||||
|
||||
@ -108,6 +108,8 @@ class ShopsMethodService extends MainService {
|
||||
id,
|
||||
shop_id: shopId,
|
||||
shopId: shopIdCamel,
|
||||
shop_name: shopName,
|
||||
shopName: shopNameCamel,
|
||||
custom_name: customName,
|
||||
customName: customNameCamel,
|
||||
platform_code: platformCode,
|
||||
@ -118,6 +120,10 @@ class ShopsMethodService extends MainService {
|
||||
id: id !== undefined ? id : (shopId !== undefined ? shopId : shopIdCamel),
|
||||
};
|
||||
|
||||
if (shopName !== undefined || shopNameCamel !== undefined) {
|
||||
payload.shop_name = shopName !== undefined ? shopName : shopNameCamel;
|
||||
}
|
||||
|
||||
if (customName !== undefined || customNameCamel !== undefined) {
|
||||
payload.custom_name = customName !== undefined ? customName : customNameCamel;
|
||||
}
|
||||
|
||||
@ -36,7 +36,8 @@ class StockTransactionMethodService extends MainService {
|
||||
start_time: startTime,
|
||||
end_time: endTime,
|
||||
store_ids: storeIds,
|
||||
stock_ids: stockIds,
|
||||
stock_ids: stockIdsRaw,
|
||||
stock_id: stockIdRaw,
|
||||
keyword,
|
||||
ids,
|
||||
transaction_type: transactionType,
|
||||
@ -48,6 +49,11 @@ class StockTransactionMethodService extends MainService {
|
||||
order_id: orderId,
|
||||
} = whereValue;
|
||||
|
||||
// 兼容 stock_id(单数)和 stock_ids(数组)
|
||||
const stockIds = stockIdsRaw !== undefined
|
||||
? stockIdsRaw
|
||||
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
|
||||
|
||||
const { sort = {} } = data;
|
||||
const {
|
||||
sort_field: sortFieldSnake,
|
||||
@ -86,9 +92,8 @@ class StockTransactionMethodService extends MainService {
|
||||
|
||||
/**
|
||||
* 货主侧商品出入库流水列表查询。
|
||||
* 按货主 store_id 限定数据范围。
|
||||
* 按当前登录货主的 store_id(ctx.user.store_id)限定数据范围,不接受外部传入 store_id,防止跨货主查询。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.store_id 货主ID(必传)
|
||||
* @param {Object} [data.pagination] 分页参数
|
||||
* @param {Object} [data.where] 查询条件
|
||||
* @param {Object} [data.sort] 排序参数
|
||||
@ -96,9 +101,9 @@ class StockTransactionMethodService extends MainService {
|
||||
*/
|
||||
async storeList(data = {}) {
|
||||
const { service } = this;
|
||||
const storeId = Number(data.store_id);
|
||||
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
|
||||
if (!Number.isInteger(storeId) || storeId <= 0) {
|
||||
return this.failure('store_id 不能为空');
|
||||
return this.failure('无法获取当前货主身份,请重新登录');
|
||||
}
|
||||
|
||||
const { pagination } = data;
|
||||
@ -180,7 +185,8 @@ class StockTransactionMethodService extends MainService {
|
||||
start_time: startTime,
|
||||
end_time: endTime,
|
||||
store_ids: storeIds,
|
||||
stock_ids: stockIds,
|
||||
stock_ids: stockIdsRaw,
|
||||
stock_id: stockIdRaw,
|
||||
keyword,
|
||||
ids,
|
||||
transaction_type: transactionType,
|
||||
@ -192,6 +198,11 @@ class StockTransactionMethodService extends MainService {
|
||||
order_id: orderId,
|
||||
} = whereValue;
|
||||
|
||||
// 兼容 stock_id(单数)和 stock_ids(数组)
|
||||
const stockIds = stockIdsRaw !== undefined
|
||||
? stockIdsRaw
|
||||
: (stockIdRaw !== undefined ? [ stockIdRaw ] : null);
|
||||
|
||||
const { sort = {} } = data;
|
||||
const sortOption = {
|
||||
sortField: sort.sortField || sort.sort_field,
|
||||
@ -270,15 +281,15 @@ class StockTransactionMethodService extends MainService {
|
||||
/**
|
||||
* 货主侧提交商品流水导出任务。
|
||||
* 与 storeList 使用相同查询条件,异步执行,立即返回任务ID。
|
||||
* store_id 从当前登录上下文(ctx.user.store_id)获取,不接受外部传入,防止跨货主查询。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.store_id 货主ID(必传)
|
||||
* @return {Promise<Object>} 统一 success 包装(返回任务ID)
|
||||
*/
|
||||
async exportStore(data = {}) {
|
||||
const { service } = this;
|
||||
const storeId = Number(data.store_id);
|
||||
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
|
||||
if (!Number.isInteger(storeId) || storeId <= 0) {
|
||||
return this.failure('store_id 不能为空');
|
||||
return this.failure('无法获取当前货主身份,请重新登录');
|
||||
}
|
||||
|
||||
const { whereValue = {} } = this.prepareWhereContext(data);
|
||||
|
||||
@ -9,9 +9,9 @@ class WarehouseService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail';
|
||||
const _noNeedLog = 'list,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail';
|
||||
const _noNeedAuth = 'list,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail';
|
||||
const _noNeedRight = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail';
|
||||
const _noNeedLog = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail';
|
||||
const _noNeedAuth = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -79,6 +79,159 @@ class WarehouseService extends MainService {
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 外仓商品列表查询。
|
||||
* - 传入 warehouse_id:按指定仓库维度查询
|
||||
* - 不传 warehouse_id:按当前货主维度查询(store_id = ctx.user.store_id)
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} [data.warehouse_id] 仓库ID(可选)
|
||||
* @param {Object} [data.pagination] 分页参数
|
||||
* @param {Object} [data.where] 筛选条件
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
async externalList(data = {}) {
|
||||
const { service, ctx } = this;
|
||||
const warehouseId = Number(data.warehouse_id || data.warehouseId || 0);
|
||||
const { pagination } = data;
|
||||
const sort = data.sort || {};
|
||||
const sortParams = {
|
||||
sortField: sort.sortField || sort.sort_field || 'id',
|
||||
sortOrder: sort.sortOrder || sort.sort_order || 'DESC',
|
||||
};
|
||||
if (this.isPlainObject(data)) {
|
||||
const rawWhere = this.isPlainObject(data.where) ? data.where : {};
|
||||
data.where = this.normalizeWarehouseRecycleWhere(rawWhere);
|
||||
}
|
||||
// 传入 warehouse_id 时合并到 where 条件中
|
||||
if (warehouseId > 0) {
|
||||
data.where = {
|
||||
...(data.where || {}),
|
||||
warehouse_id: { operator: 'eq', value: warehouseId },
|
||||
};
|
||||
}
|
||||
const { where } = this.prepareWhereContext(data, {
|
||||
specialFieldMap: {
|
||||
barcode: {
|
||||
bucket: 'barcode',
|
||||
},
|
||||
prohibited_type: {
|
||||
bucket: 'prohibited',
|
||||
field: 'id',
|
||||
},
|
||||
has_bound_item: {
|
||||
bucket: 'storeOutStock',
|
||||
field: 'stock_id',
|
||||
},
|
||||
},
|
||||
});
|
||||
// 始终按当前货主维度查(store_id = self)
|
||||
const result = await service.systems.stockStore.getWarehouseStock(where, pagination, sortParams, 0, ctx.user.store_id);
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交外仓商品导出任务(复用 externalList 的筛选语义与排序规则)。
|
||||
* - 传入 warehouse_id:按指定仓库维度导出
|
||||
* - 不传 warehouse_id:按当前货主维度导出(store_id = ctx.user.store_id)
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} [data.warehouse_id] 仓库ID(可选)
|
||||
* @param {Object} [data.where] 筛选条件
|
||||
* @param {Object} [data.sort] 排序参数
|
||||
* @param {string} [data.sort.sortField] 排序字段(兼容:sort_field)
|
||||
* @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order)
|
||||
* @return {Promise<Object>} 统一成功包装响应,data 为导出任务信息
|
||||
*/
|
||||
async externalExport(data = {}) {
|
||||
const { service, ctx } = this;
|
||||
const warehouseId = Number(data.warehouse_id || data.warehouseId || 0);
|
||||
const sort = data.sort || {};
|
||||
const sortField = sort.sortField || sort.sort_field;
|
||||
const sortOrder = sort.sortOrder || sort.sort_order;
|
||||
const sortParams = {
|
||||
...(sortField ? { sortField } : {}),
|
||||
...(sortOrder ? { sortOrder } : {}),
|
||||
};
|
||||
|
||||
if (this.isPlainObject(data)) {
|
||||
const rawWhere = this.isPlainObject(data.where) ? data.where : {};
|
||||
data.where = this.normalizeWarehouseRecycleWhere(rawWhere);
|
||||
}
|
||||
// 传入 warehouse_id 时合并到 where 条件中
|
||||
if (warehouseId > 0) {
|
||||
data.where = {
|
||||
...(data.where || {}),
|
||||
warehouse_id: { operator: 'eq', value: warehouseId },
|
||||
};
|
||||
}
|
||||
const { where } = this.prepareWhereContext(data, {
|
||||
specialFieldMap: {
|
||||
barcode: {
|
||||
bucket: 'barcode',
|
||||
},
|
||||
prohibited_type: {
|
||||
bucket: 'prohibited',
|
||||
field: 'id',
|
||||
},
|
||||
has_bound_item: {
|
||||
bucket: 'storeOutStock',
|
||||
field: 'stock_id',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const taskId = this.generateExportTaskId('external');
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
message: '外仓导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 10,
|
||||
message: '外仓导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
// 始终按当前货主维度导出(store_id = self)
|
||||
const result = await service.systems.stockStore.exportExternalWarehouseStock(where, sortParams, warehouseId, ctx.user.store_id);
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
message: '外仓导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '外仓导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交仓库商品导出任务(复用 list 的筛选语义与排序规则)。
|
||||
* @param {Object} data 请求体
|
||||
@ -224,13 +377,15 @@ class WarehouseService extends MainService {
|
||||
|
||||
/**
|
||||
* 生成仓库商品导出任务ID。
|
||||
* @param {string} [prefix=''] 任务类型前缀(如 'external')
|
||||
* @return {string} 导出任务ID
|
||||
*/
|
||||
generateExportTaskId() {
|
||||
generateExportTaskId(prefix = '') {
|
||||
const warehouseId = this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
return `stock_warehouse_export_${warehouseId}_${timestamp}_${randomToken}`;
|
||||
const typePrefix = prefix ? `${prefix}_` : '';
|
||||
return `stock_warehouse_${typePrefix}export_${warehouseId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -644,7 +799,22 @@ class WarehouseService extends MainService {
|
||||
* @return {Promise<Object>} data 为关联分页结果
|
||||
*/
|
||||
async getStoreStocks(data) {
|
||||
const { service } = this;
|
||||
const { ctx, service } = this;
|
||||
// 校验归属:stock_warehouse 的 store_id 或 warehouse_id 匹配当前主体即可放行
|
||||
const stockId = Number(data.stock_id || 0);
|
||||
if (stockId > 0) {
|
||||
const stock = await ctx.model.StockWarehouse.findOne({
|
||||
where: { id: stockId },
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!stock
|
||||
|| (stock.store_id !== ctx.user.store_id && stock.warehouse_id !== ctx.user.store_id)) {
|
||||
return this.fail('无权限查看该商品的绑定信息', { code: 403 });
|
||||
}
|
||||
// 使用实际的 warehouse_id 查询
|
||||
data._warehouseId = stock.warehouse_id;
|
||||
}
|
||||
const result = await service.systems.stockStore.getStoreStocks(data);
|
||||
return this.success('ok', { data: result, code: 200 });
|
||||
}
|
||||
@ -730,10 +900,24 @@ class WarehouseService extends MainService {
|
||||
* @return {Promise<Object>} data 为日志分页结果
|
||||
*/
|
||||
async queryStockLogs(data) {
|
||||
const { ctx } = this;
|
||||
const { ctx, service } = this;
|
||||
try {
|
||||
const { service } = this;
|
||||
data.warehouseId = ctx.user.store_id;
|
||||
const stockId = Number(data.id || 0);
|
||||
if (stockId > 0) {
|
||||
// 校验 stock_warehouse:store_id 或 warehouse_id 匹配当前主体即可放行
|
||||
const stock = await ctx.model.StockWarehouse.findOne({
|
||||
where: { id: stockId },
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!stock
|
||||
|| (stock.store_id !== ctx.user.store_id && stock.warehouse_id !== ctx.user.store_id)) {
|
||||
return this.fail('无权限查看该商品的库存日志', { code: 403 });
|
||||
}
|
||||
data.warehouseId = stock.warehouse_id;
|
||||
} else {
|
||||
data.warehouseId = ctx.user.store_id;
|
||||
}
|
||||
const result = await service.systems.operationLog.queryStockLogs(data);
|
||||
return this.success('ok', { data: result, code: 200 });
|
||||
} catch (e) {
|
||||
|
||||
@ -1,5 +1,9 @@
|
||||
'use strict';
|
||||
const MainService = require('../../main');
|
||||
|
||||
const ENTRY_EXPORT_TASK_CACHE_KEY_PREFIX = 'entry_export_task_';
|
||||
const ENTRY_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
|
||||
|
||||
/**
|
||||
* 系统方法层:storage.entry(入库单相关接口包装层)。
|
||||
* 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。
|
||||
@ -9,9 +13,9 @@ class entryService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,get,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,quickInbound,receivingCompare,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList';
|
||||
const _noNeedLog = 'list,get,getPrintData,reviewEntry,containerList';
|
||||
const _noNeedAuth = 'list,get,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,bindReceiving,quickInbound,receivingCompare,unbindReceiving,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList';
|
||||
const _noNeedRight = 'list,listStore,get,getStore,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,quickInbound,receivingCompare,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList,export,exportTaskProgress,storeExport,storeExportTaskProgress';
|
||||
const _noNeedLog = 'list,listStore,get,getStore,getPrintData,reviewEntry,export,exportTaskProgress,storeExport,storeExportTaskProgress';
|
||||
const _noNeedAuth = 'list,listStore,get,getStore,cancel,getPrintData,getDirectInboundItems,addItem,commit,removeItem,bindReceiving,quickInbound,receivingCompare,unbindReceiving,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList,export,exportTaskProgress,storeExport,storeExportTaskProgress';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -37,6 +41,40 @@ class entryService extends MainService {
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 货主侧入库单列表查询。
|
||||
* 与 list 共享底层逻辑,但以货主维度(store_id)过滤,不使用仓库维度(warehouse_id)。
|
||||
* 货主登录后仅能看到自己货主下的入库单。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.pagination] 分页参数
|
||||
* @param {Object} [data.where] 动态筛选条件
|
||||
* @param {Object} [data.sort] 排序参数
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async listStore(data = {}) {
|
||||
const { service } = this;
|
||||
const { pagination, sort } = data;
|
||||
const { where } = this.prepareWhereContext(data, {
|
||||
specialFieldMap: {
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
},
|
||||
});
|
||||
const result = await service.systems.storage.entry.list(where, pagination, sort, 'store');
|
||||
|
||||
// 裁剪货主侧冗余字段:货主自己的 store_name/store 关联、奇门编码
|
||||
if (result && result.data && Array.isArray(result.data.list)) {
|
||||
result.data.list.forEach(item => {
|
||||
delete item.store_name;
|
||||
delete item.store;
|
||||
delete item.qimen_owner_code;
|
||||
delete item.qimen_warehouse_code;
|
||||
});
|
||||
}
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询入库单详情(与原 storage.directInbound.getItems 输出格式一致)。
|
||||
* 返回入库单基本信息(id、entry_order_code、order_status、store_remask)、
|
||||
@ -53,6 +91,22 @@ class entryService extends MainService {
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 货主侧查询入库单详情。与 get 共享底层逻辑,
|
||||
* 但以货主维度(store_id)校验权限(不使用 warehouse_id),
|
||||
* 货主登录后仅能查看自己货主下的入库单明细。
|
||||
* 返回结构与 get 一致。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 入库单ID(必填)
|
||||
* @return {Promise<Object>} 统一 success 包装
|
||||
*/
|
||||
async getStore(data = {}) {
|
||||
const { service } = this;
|
||||
const { id } = data || {};
|
||||
const result = await service.systems.storage.entry.get({ id }, 'store');
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 作废入库单。
|
||||
* 支持传入单个 id 或批量 ids,保持透传给业务层处理。
|
||||
@ -379,5 +433,359 @@ class entryService extends MainService {
|
||||
return this.fail(result?.message || '审核失败', result, 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交入库单导出任务(复用 list 的筛选语义与排序规则)。
|
||||
* 导出分为两个 sheet:Sheet1=入库单列表,Sheet2=入库单明细(按入库单分页拉取写入流)。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 筛选条件(与 list 一致)
|
||||
* @param {Object} [data.sort] 排序参数
|
||||
* @return {Promise<Object>} 统一成功包装响应,data 为导出任务信息
|
||||
*/
|
||||
async export(data = {}) {
|
||||
const { service } = this;
|
||||
const { where, sort } = data || {};
|
||||
|
||||
const taskId = this.generateExportTaskId();
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
message: '导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 5,
|
||||
message: '导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await service.systems.storage.entry.exportEntryOrders({
|
||||
where: this.isPlainObject(where) ? { ...where } : {},
|
||||
sort: this.isPlainObject(sort) ? { ...sort } : {},
|
||||
onProgress: async progress => {
|
||||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: safeProgress.status || 'running',
|
||||
progress: safeProgress.progress,
|
||||
message: safeProgress.message || '导出任务执行中',
|
||||
result: safeProgress.result || null,
|
||||
error: '',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
message: '导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询入库单导出任务进度。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
async exportTaskProgress(data = {}) {
|
||||
const taskId = this.normalizeExportTaskId(data);
|
||||
if (!taskId) {
|
||||
return this.success('ok', {
|
||||
task_id: '',
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const cachedTask = await this.getExportTaskProgress(taskId);
|
||||
if (!cachedTask) {
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
|
||||
const downloadUrl = String(
|
||||
safeResult.url
|
||||
|| safeResult.cdnUrl
|
||||
|| safeResult.cosUrl
|
||||
|| safeResult.fileKey
|
||||
|| ''
|
||||
);
|
||||
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
...cachedTask,
|
||||
download_url: downloadUrl,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成入库单导出任务ID。
|
||||
* @param {string} [prefix=''] 任务类型前缀(如 'store')
|
||||
* @return {string} 导出任务ID
|
||||
*/
|
||||
generateExportTaskId(prefix = '') {
|
||||
const storeId = this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
const typePrefix = prefix ? `${prefix}_` : '';
|
||||
return `entry_${typePrefix}export_${storeId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化入库单导出任务ID。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {string} 归一化后的任务ID
|
||||
*/
|
||||
normalizeExportTaskId(data = {}) {
|
||||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取入库单导出任务缓存键。
|
||||
* @param {string} taskId 任务ID
|
||||
* @return {string} 缓存键
|
||||
*/
|
||||
getExportTaskCacheKey(taskId = '') {
|
||||
const normalizedTaskId = String(taskId || '').trim();
|
||||
if (!normalizedTaskId) {
|
||||
return '';
|
||||
}
|
||||
return `${ENTRY_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入入库单导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID
|
||||
* @param {Object} payload 任务状态载荷
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async setExportTaskProgress(taskId = '', payload = {}) {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||||
const progressPayload = {
|
||||
task_id: String(taskId || '').trim(),
|
||||
status: String(safePayload.status || 'submitted').trim() || 'submitted',
|
||||
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
|
||||
message: String(safePayload.message || ''),
|
||||
result: safePayload.result ?? null,
|
||||
error: String(safePayload.error || ''),
|
||||
update_time: Date.now(),
|
||||
};
|
||||
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, progressPayload, ENTRY_EXPORT_TASK_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
this.ctx.logger.warn(`[storage.entry.export] 写入导出任务缓存失败: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取入库单导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID
|
||||
* @return {Promise<Object|null>} 任务缓存
|
||||
*/
|
||||
async getExportTaskProgress(taskId = '') {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
if (!this.isPlainObject(cached)) {
|
||||
return null;
|
||||
}
|
||||
return cached;
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
this.ctx.logger.warn(`[storage.entry.export] 读取导出任务缓存失败: ${errorMessage}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交货主侧入库单导出任务(复用 listStore 的筛选语义与排序规则)。
|
||||
* 导出分为两个 sheet:Sheet1=入库单列表,Sheet2=入库单明细(按入库单分页拉取写入流)。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 筛选条件(与 listStore 一致)
|
||||
* @param {Object} [data.sort] 排序参数
|
||||
* @return {Promise<Object>} 统一成功包装响应,data 为导出任务信息
|
||||
*/
|
||||
async storeExport(data = {}) {
|
||||
const { service } = this;
|
||||
const { where, sort } = data || {};
|
||||
|
||||
const taskId = this.generateExportTaskId('store');
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
message: '货主侧入库单导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 5,
|
||||
message: '货主侧入库单导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await service.systems.storage.entry.exportStoreEntryOrders({
|
||||
where: this.isPlainObject(where) ? { ...where } : {},
|
||||
sort: this.isPlainObject(sort) ? { ...sort } : {},
|
||||
onProgress: async progress => {
|
||||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: safeProgress.status || 'running',
|
||||
progress: safeProgress.progress,
|
||||
message: safeProgress.message || '货主侧入库单导出任务执行中',
|
||||
result: safeProgress.result || null,
|
||||
error: '',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
message: '货主侧入库单导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '货主侧入库单导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询货主侧入库单导出任务进度。
|
||||
* 复用 exportTaskProgress 的缓存查询逻辑,任务 ID 前缀不同。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
async storeExportTaskProgress(data = {}) {
|
||||
const taskId = this.normalizeExportTaskId(data);
|
||||
if (!taskId) {
|
||||
return this.success('ok', {
|
||||
task_id: '',
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const cachedTask = await this.getExportTaskProgress(taskId);
|
||||
if (!cachedTask) {
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
|
||||
const downloadUrl = String(
|
||||
safeResult.url
|
||||
|| safeResult.cdnUrl
|
||||
|| safeResult.cosUrl
|
||||
|| safeResult.fileKey
|
||||
|| ''
|
||||
);
|
||||
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
...cachedTask,
|
||||
download_url: downloadUrl,
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
module.exports = entryService;
|
||||
|
||||
@ -1,6 +1,9 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
const RECEIVING_EXPORT_TASK_CACHE_KEY_PREFIX = 'receiving_export_task_';
|
||||
const RECEIVING_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
|
||||
/**
|
||||
* 系统方法层:storage.receiving(收货单相关接口包装层)。
|
||||
* 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。
|
||||
@ -10,9 +13,9 @@ class configService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail';
|
||||
const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail';
|
||||
const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail';
|
||||
const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress';
|
||||
const _noNeedLog = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail,export,exportTaskProgress';
|
||||
const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -39,6 +42,55 @@ class configService extends MainService {
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 货主侧收货单列表查询(system method 包装层)。
|
||||
* 以当前平台激活的货主 store_id 为维度查询收货单。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.pagination] 分页参数
|
||||
* @param {Object} [data.where] 筛选条件
|
||||
* @param {Object} [data.sort] 排序参数
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
async getStoreReceivingList(data) {
|
||||
const { ctx, app } = this;
|
||||
const { pagination, sort } = data;
|
||||
|
||||
// 从平台激活上下文获取 store_id(使用原生查询避免 AccountPlatformActive 无 id 列兼容问题)
|
||||
const platformRows = await app.model.query(
|
||||
'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' +
|
||||
'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' +
|
||||
'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1',
|
||||
{
|
||||
replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' },
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
|
||||
if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) {
|
||||
return this.fail('未获取到货主平台激活上下文,请先切换至货主角色');
|
||||
}
|
||||
|
||||
const storeId = platformRows[0].store_id;
|
||||
|
||||
const { where } = this.prepareWhereContext(data, {
|
||||
specialFieldMap: {
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { service } = this;
|
||||
const result = await service.systems.storage.receiving.getStoreReceivingList(
|
||||
where,
|
||||
storeId,
|
||||
pagination,
|
||||
sort
|
||||
);
|
||||
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 收货单详情查询(分页返回明细)。
|
||||
* @param {Object} data 请求体
|
||||
@ -280,5 +332,252 @@ class configService extends MainService {
|
||||
return this.success('查询成功', result.data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交收货单导出任务(复用 getStoreReceivingList 的筛选语义与排序规则)。
|
||||
* 导出分为两个 sheet:Sheet1=收货单列表,Sheet2=收货单明细。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 筛选条件(与 getStoreReceivingList 一致)
|
||||
* @param {Object} [data.sort] 排序参数
|
||||
* @return {Promise<Object>} 统一成功包装响应,data 为导出任务信息
|
||||
*/
|
||||
async export(data = {}) {
|
||||
const { ctx, app, service } = this;
|
||||
|
||||
// 从平台激活上下文获取 store_id
|
||||
const platformRows = await app.model.query(
|
||||
'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' +
|
||||
'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' +
|
||||
'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1',
|
||||
{
|
||||
replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' },
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
|
||||
if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) {
|
||||
return this.fail('未获取到货主平台激活上下文,请先切换至货主角色');
|
||||
}
|
||||
|
||||
const storeId = platformRows[0].store_id;
|
||||
const { sort = {} } = data;
|
||||
|
||||
const { where } = this.prepareWhereContext(data, {
|
||||
specialFieldMap: {
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const taskId = this.generateExportTaskId();
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
message: '收货单导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 5,
|
||||
message: '收货单导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await service.systems.storage.receiving.exportReceivingList({
|
||||
where,
|
||||
storeId,
|
||||
sort,
|
||||
onProgress: async progress => {
|
||||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: safeProgress.status || 'running',
|
||||
progress: safeProgress.progress,
|
||||
message: safeProgress.message || '收货单导出任务执行中',
|
||||
result: safeProgress.result || null,
|
||||
error: '',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
message: '收货单导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '收货单导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询收货单导出任务进度。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
async exportTaskProgress(data = {}) {
|
||||
const taskId = this.normalizeExportTaskId(data);
|
||||
if (!taskId) {
|
||||
return this.success('ok', {
|
||||
task_id: '',
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const cachedTask = await this.getExportTaskProgress(taskId);
|
||||
if (!cachedTask) {
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
|
||||
const downloadUrl = String(
|
||||
safeResult.url
|
||||
|| safeResult.cdnUrl
|
||||
|| safeResult.cosUrl
|
||||
|| safeResult.fileKey
|
||||
|| ''
|
||||
);
|
||||
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
...cachedTask,
|
||||
download_url: downloadUrl,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成收货单导出任务ID。
|
||||
* @return {string} 导出任务ID
|
||||
*/
|
||||
generateExportTaskId() {
|
||||
const storeId = this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
return `receiving_export_${storeId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化收货单导出任务ID。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {string} 归一化后的任务ID
|
||||
*/
|
||||
normalizeExportTaskId(data = {}) {
|
||||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取收货单导出任务缓存键。
|
||||
* @param {string} taskId 任务ID
|
||||
* @return {string} 缓存键
|
||||
*/
|
||||
getExportTaskCacheKey(taskId = '') {
|
||||
const normalizedTaskId = String(taskId || '').trim();
|
||||
if (!normalizedTaskId) {
|
||||
return '';
|
||||
}
|
||||
return `${RECEIVING_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入收货单导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID
|
||||
* @param {Object} payload 任务状态载荷
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async setExportTaskProgress(taskId = '', payload = {}) {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||||
const progressPayload = {
|
||||
task_id: String(taskId || '').trim(),
|
||||
status: String(safePayload.status || 'submitted').trim() || 'submitted',
|
||||
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
|
||||
message: String(safePayload.message || ''),
|
||||
result: safePayload.result ?? null,
|
||||
error: String(safePayload.error || ''),
|
||||
update_time: Date.now(),
|
||||
};
|
||||
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, progressPayload, RECEIVING_EXPORT_TASK_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
this.ctx.logger.warn(`[storage.receiving.export] 写入导出任务缓存失败: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取收货单导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID
|
||||
* @return {Promise<Object|null>} 任务缓存
|
||||
*/
|
||||
async getExportTaskProgress(taskId = '') {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
if (!this.isPlainObject(cached)) {
|
||||
return null;
|
||||
}
|
||||
return cached;
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
this.ctx.logger.warn(`[storage.receiving.export] 读取导出任务缓存失败: ${errorMessage}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
module.exports = configService;
|
||||
|
||||
@ -2,6 +2,9 @@
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
const PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_KEY_PREFIX = 'print_quantity_log_export_task_';
|
||||
const PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
|
||||
|
||||
|
||||
/**
|
||||
* 规范仓库配置方法入参,避免把原始引用直接传给下游服务。
|
||||
@ -26,9 +29,9 @@ class StoreWarehouseStoreService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig';
|
||||
const _noNeedRight = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig';
|
||||
const _noNeedAuth = 'list,sign,confirmSign,unbind,rename,openAccount,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig,queryPrintQuantityLogs,queryStorePrintQuantityLogs,exportPrintQuantityLogs,exportStorePrintQuantityLogs,exportStorePrintQuantityLogsTaskProgress,adjustPrintQuantity';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -417,6 +420,444 @@ class StoreWarehouseStoreService extends MainService {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交面单余额变更日志导出任务。
|
||||
* 入参条件与 queryPrintQuantityLogs 的 where 语义一致,异步执行,立即返回 task_id。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {number|string} data.store_id 货主ID(必填)。
|
||||
* @param {Object} [data.where] 动态筛选条件,与 queryPrintQuantityLogs 的 where 语义一致。
|
||||
* @return {Promise<Object>} 统一响应结果(包含 task_id)。
|
||||
*/
|
||||
async exportPrintQuantityLogs(data = {}) {
|
||||
const { service } = this;
|
||||
const targetService = service && service.systems && service.systems.storeWarehouse;
|
||||
|
||||
if (!targetService || typeof targetService.exportPrintQuantityLogs !== 'function') {
|
||||
return this.fail('导出面单余额变更日志失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const requestData = normalizeStoreWarehousePayload(data);
|
||||
const { where } = this.prepareWhereContext(requestData);
|
||||
const { store_id } = requestData;
|
||||
|
||||
const taskId = this.generateExportTaskId();
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
message: '导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 10,
|
||||
message: '导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await targetService.exportPrintQuantityLogs({
|
||||
store_id,
|
||||
where,
|
||||
});
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
message: '导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '导出面单余额变更日志失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询面单余额变更日志导出任务进度。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)。
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async exportPrintQuantityLogsTaskProgress(data = {}) {
|
||||
const taskId = this.normalizeExportTaskId(data);
|
||||
if (!taskId) {
|
||||
return this.success('ok', {
|
||||
task_id: '',
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const cachedTask = await this.getExportTaskProgress(taskId);
|
||||
if (!cachedTask) {
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
|
||||
const downloadUrl = String(
|
||||
safeResult.url
|
||||
|| safeResult.cdnUrl
|
||||
|| safeResult.cosUrl
|
||||
|| safeResult.fileKey
|
||||
|| ''
|
||||
);
|
||||
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
...cachedTask,
|
||||
download_url: downloadUrl,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 货主侧查询面单余额变更日志(自动从平台激活上下文获取 store_id)。
|
||||
* 无需显式传入 store_id,系统自动从当前用户激活的货主平台上下文中获取。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {Object} [data.where] 动态筛选条件。
|
||||
* @param {Object} [data.pagination] 分页对象。
|
||||
* @param {number|string} [data.pagination.page] 页码。
|
||||
* @param {number|string} [data.pagination.page_size] 每页条数。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async queryStorePrintQuantityLogs(data = {}) {
|
||||
const { ctx, app, service } = this;
|
||||
|
||||
// 从平台激活上下文获取 store_id
|
||||
const platformRows = await app.model.query(
|
||||
'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' +
|
||||
'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' +
|
||||
'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1',
|
||||
{
|
||||
replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' },
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
|
||||
if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) {
|
||||
return this.fail('未获取到货主平台激活上下文,请先切换至货主角色');
|
||||
}
|
||||
|
||||
const storeId = platformRows[0].store_id;
|
||||
const targetService = service && service.systems && service.systems.storeWarehouse;
|
||||
|
||||
if (!targetService || typeof targetService.queryPrintQuantityLogs !== 'function') {
|
||||
return this.fail('查询面单余额变更日志失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const requestData = normalizeStoreWarehousePayload(data);
|
||||
const { where } = this.prepareWhereContext(requestData);
|
||||
const rawPagination = requestData.pagination && typeof requestData.pagination === 'object'
|
||||
? requestData.pagination
|
||||
: {};
|
||||
const { page, page_size } = rawPagination;
|
||||
|
||||
const result = await targetService.queryPrintQuantityLogs({
|
||||
store_id: storeId,
|
||||
where,
|
||||
pagination: { page, page_size },
|
||||
});
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '查询面单余额变更日志失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 货主侧提交面单余额变更日志导出任务(自动从平台激活上下文获取 store_id)。
|
||||
* 入参条件与 queryStorePrintQuantityLogs 的 where 语义一致,异步执行,立即返回 task_id。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {Object} [data.where] 动态筛选条件。
|
||||
* @return {Promise<Object>} 统一响应结果(包含 task_id)。
|
||||
*/
|
||||
async exportStorePrintQuantityLogs(data = {}) {
|
||||
const { ctx, app, service } = this;
|
||||
|
||||
// 从平台激活上下文获取 store_id
|
||||
const platformRows = await app.model.query(
|
||||
'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' +
|
||||
'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' +
|
||||
'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1',
|
||||
{
|
||||
replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' },
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
|
||||
if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) {
|
||||
return this.fail('未获取到货主平台激活上下文,请先切换至货主角色');
|
||||
}
|
||||
|
||||
const storeId = platformRows[0].store_id;
|
||||
const targetService = service && service.systems && service.systems.storeWarehouse;
|
||||
|
||||
if (!targetService || typeof targetService.exportPrintQuantityLogs !== 'function') {
|
||||
return this.fail('导出面单余额变更日志失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const requestData = normalizeStoreWarehousePayload(data);
|
||||
const { where } = this.prepareWhereContext(requestData);
|
||||
|
||||
const taskId = this.generateExportTaskId('store');
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
message: '货主侧导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 10,
|
||||
message: '货主侧导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await targetService.exportPrintQuantityLogs({
|
||||
store_id: storeId,
|
||||
where,
|
||||
});
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
message: '货主侧导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '货主侧导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '导出面单余额变更日志失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 货主侧查询面单余额变更日志导出任务进度。
|
||||
* 复用 exportPrintQuantityLogsTaskProgress 的缓存查询逻辑。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)。
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async exportStorePrintQuantityLogsTaskProgress(data = {}) {
|
||||
const taskId = this.normalizeExportTaskId(data);
|
||||
if (!taskId) {
|
||||
return this.success('ok', {
|
||||
task_id: '',
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const cachedTask = await this.getExportTaskProgress(taskId);
|
||||
if (!cachedTask) {
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
status: 'not_found',
|
||||
progress: 0,
|
||||
message: '任务不存在',
|
||||
result: null,
|
||||
error: '',
|
||||
download_url: '',
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
|
||||
const downloadUrl = String(
|
||||
safeResult.url
|
||||
|| safeResult.cdnUrl
|
||||
|| safeResult.cosUrl
|
||||
|| safeResult.fileKey
|
||||
|| ''
|
||||
);
|
||||
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
...cachedTask,
|
||||
download_url: downloadUrl,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成导出任务ID。
|
||||
* @param {string} [prefix=''] 任务类型前缀(如 'store')
|
||||
* @return {string} 导出任务ID。
|
||||
*/
|
||||
generateExportTaskId(prefix = '') {
|
||||
const storeId = this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
const typePrefix = prefix ? `${prefix}_` : '';
|
||||
return `print_qty_log_${typePrefix}export_${storeId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范导出任务ID。
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {string} 归一化后的任务ID。
|
||||
*/
|
||||
normalizeExportTaskId(data = {}) {
|
||||
const normalizedData = this.isPlainObject(data) ? data : {};
|
||||
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取导出任务缓存键。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @return {string} 缓存键。
|
||||
*/
|
||||
getExportTaskCacheKey(taskId = '') {
|
||||
const normalizedTaskId = String(taskId || '').trim();
|
||||
if (!normalizedTaskId) {
|
||||
return '';
|
||||
}
|
||||
return `${PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @param {Object} payload 任务状态载荷。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async setExportTaskProgress(taskId = '', payload = {}) {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const safePayload = this.isPlainObject(payload) ? payload : {};
|
||||
const progressPayload = {
|
||||
task_id: String(taskId || '').trim(),
|
||||
status: String(safePayload.status || 'submitted').trim() || 'submitted',
|
||||
progress: Number.isFinite(Number(safePayload.progress))
|
||||
? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress))))
|
||||
: 0,
|
||||
message: String(safePayload.message || ''),
|
||||
result: safePayload.result ?? null,
|
||||
error: String(safePayload.error || ''),
|
||||
update_time: Date.now(),
|
||||
};
|
||||
|
||||
try {
|
||||
await this.app.setCacheAsync(cacheKey, progressPayload, PRINT_QUANTITY_LOG_EXPORT_TASK_CACHE_TTL_SECONDS);
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[storeWarehouse.store.exportPrintQuantityLogs] 写入导出任务缓存失败: %s',
|
||||
error && error.message ? error.message : error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取导出任务进度缓存。
|
||||
* @param {string} taskId 任务ID。
|
||||
* @return {Promise<Object|null>} 任务缓存。
|
||||
*/
|
||||
async getExportTaskProgress(taskId = '') {
|
||||
const cacheKey = this.getExportTaskCacheKey(taskId);
|
||||
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const cached = await this.app.getCacheAsync(cacheKey);
|
||||
if (!this.isPlainObject(cached)) {
|
||||
return null;
|
||||
}
|
||||
return cached;
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[storeWarehouse.store.exportPrintQuantityLogs] 读取导出任务缓存失败: %s',
|
||||
error && error.message ? error.message : error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = StoreWarehouseStoreService;
|
||||
|
||||
137
app/service/systemMethods/workbench.js
Normal file
137
app/service/systemMethods/workbench.js
Normal file
@ -0,0 +1,137 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
class WorkbenchService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = 'business';
|
||||
const _noNeedRight = 'list,detail,checkBarcode,business';
|
||||
const _noNeedLog = 'list,detail,checkBarcode';
|
||||
const _noNeedAuth = 'list,detail,checkBarcode,business';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 工作台列表(分页 + 筛选)
|
||||
*/
|
||||
async list(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const result = await service.systems.workbench.list(data || {});
|
||||
return this.success('获取成功', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工作台详情
|
||||
*/
|
||||
async detail(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const { id } = data || {};
|
||||
if (!id) return this.fail('工作台ID不能为空');
|
||||
const record = await service.systems.workbench.detail(parseInt(id));
|
||||
return this.success('获取成功', record);
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建工作台
|
||||
*/
|
||||
async create(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const record = await service.systems.workbench.create(data);
|
||||
return this.success('创建成功', record);
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新工作台
|
||||
*/
|
||||
async update(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const { id, ...fields } = data || {};
|
||||
if (!id) return this.fail('工作台ID不能为空');
|
||||
const record = await service.systems.workbench.update(parseInt(id), fields);
|
||||
return this.success('更新成功', record);
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除工作台(软删除)
|
||||
*/
|
||||
async delete(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const { id } = data || {};
|
||||
if (!id) return this.fail('工作台ID不能为空');
|
||||
await service.systems.workbench.delete(parseInt(id));
|
||||
return this.success('删除成功');
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工作台业务入口(免登录、免鉴权)
|
||||
* @param {Object} data - { name, data }
|
||||
*/
|
||||
async business(data) {
|
||||
const { ctx, service } = this;
|
||||
const { name, data: bizData } = data || {};
|
||||
ctx.logger.info('[Workbench.business] 收到业务请求 name=%s data=%j', name, bizData);
|
||||
try {
|
||||
const result = await service.systems.workbench.business(name, bizData);
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
ctx.logger.error('[Workbench.business] 业务处理失败 name=%s error=%s', name, error.message);
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 工作台绑定摄像头
|
||||
*/
|
||||
async bindCamera(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const { id, camera_ids } = data || {};
|
||||
if (!id) return this.fail('工作台ID不能为空');
|
||||
const record = await service.systems.workbench.bindCamera(parseInt(id), camera_ids);
|
||||
return this.success('绑定成功', record);
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查条码是否已存在
|
||||
*/
|
||||
async checkBarcode(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const { barcode, excludeId } = data || {};
|
||||
if (!barcode) return this.fail('条码不能为空');
|
||||
const exists = await service.systems.workbench.checkBarcodeExists(
|
||||
String(barcode).trim(),
|
||||
excludeId ? parseInt(excludeId) : undefined
|
||||
);
|
||||
return this.success('ok', { exists });
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WorkbenchService;
|
||||
126
app/service/systems/camera.js
Normal file
126
app/service/systems/camera.js
Normal file
@ -0,0 +1,126 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
class CameraService extends Service {
|
||||
async list(params = {}) {
|
||||
const { ctx } = this;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
const warehouseId = ctx.user.store_id;
|
||||
const { pagination = {}, where = {} } = params;
|
||||
|
||||
const page = Math.max(1, parseInt(pagination.page) || 1);
|
||||
const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20));
|
||||
|
||||
const queryWhere = { warehouse_id: warehouseId };
|
||||
if (where.server_id) queryWhere.server_id = parseInt(where.server_id);
|
||||
if (where.custom_name) queryWhere.custom_name = { [Op.like]: `%${where.custom_name}%` };
|
||||
if (where.status !== undefined && where.status !== null && where.status !== '') {
|
||||
queryWhere.status = parseInt(where.status);
|
||||
}
|
||||
|
||||
const { count, rows } = await ctx.model.Camera.findAndCountAll({
|
||||
where: queryWhere,
|
||||
include: [{
|
||||
model: ctx.model.CameraServer,
|
||||
as: 'server',
|
||||
attributes: ['id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status'],
|
||||
required: false,
|
||||
}],
|
||||
order: [['created_at', 'DESC']],
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
});
|
||||
|
||||
return { list: rows, pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize), hasPrevious: page > 1, hasNext: page * pageSize < count } };
|
||||
}
|
||||
|
||||
async detail(id) {
|
||||
const { ctx } = this;
|
||||
const record = await ctx.model.Camera.findOne({
|
||||
where: { id, warehouse_id: ctx.user.store_id },
|
||||
include: [{
|
||||
model: ctx.model.CameraServer,
|
||||
as: 'server',
|
||||
attributes: ['id', 'name', 'brand', 'public_ip', 'internal_ip', 'public_port', 'internal_port', 'status'],
|
||||
required: false,
|
||||
}],
|
||||
});
|
||||
if (!record) throw new Error('摄像头不存在或无权访问');
|
||||
return record;
|
||||
}
|
||||
|
||||
async create(data) {
|
||||
const { ctx } = this;
|
||||
if (!data.server_id) throw new Error('所属服务器ID不能为空');
|
||||
if (data.channel_id === undefined || data.channel_id === null) throw new Error('通道编号不能为空');
|
||||
if (data.custom_name !== undefined && data.custom_name !== null && String(data.custom_name).trim() === '') {
|
||||
throw new Error('自定义名称不能为空');
|
||||
}
|
||||
return await ctx.model.Camera.create({
|
||||
warehouse_id: ctx.user.store_id,
|
||||
server_id: parseInt(data.server_id),
|
||||
channel_id: parseInt(data.channel_id),
|
||||
channel_name: data.channel_name || null,
|
||||
ip: data.ip || null,
|
||||
port: data.port !== undefined && data.port !== null ? parseInt(data.port) : null,
|
||||
model: data.model || null,
|
||||
serial_number: data.serial_number || null,
|
||||
stream_type: data.stream_type || null,
|
||||
custom_name: data.custom_name || null,
|
||||
status: data.status !== undefined ? parseInt(data.status) : 1,
|
||||
remark: data.remark || null,
|
||||
});
|
||||
}
|
||||
|
||||
async update(id, data) {
|
||||
const { ctx } = this;
|
||||
const record = await ctx.model.Camera.findOne({ where: { id, warehouse_id: ctx.user.store_id } });
|
||||
if (!record) throw new Error('摄像头不存在或无权操作');
|
||||
|
||||
const fields = {};
|
||||
if (data.server_id !== undefined) fields.server_id = parseInt(data.server_id);
|
||||
if (data.channel_id !== undefined) fields.channel_id = parseInt(data.channel_id);
|
||||
if (data.channel_name !== undefined) fields.channel_name = data.channel_name;
|
||||
if (data.ip !== undefined) fields.ip = data.ip;
|
||||
if (data.port !== undefined) fields.port = data.port !== null ? parseInt(data.port) : null;
|
||||
if (data.model !== undefined) fields.model = data.model;
|
||||
if (data.serial_number !== undefined) fields.serial_number = data.serial_number;
|
||||
if (data.stream_type !== undefined) fields.stream_type = data.stream_type;
|
||||
if (data.custom_name !== undefined) {
|
||||
if (data.custom_name !== null && String(data.custom_name).trim() === '') {
|
||||
throw new Error('自定义名称不能为空');
|
||||
}
|
||||
fields.custom_name = data.custom_name;
|
||||
}
|
||||
if (data.status !== undefined) fields.status = parseInt(data.status);
|
||||
if (data.remark !== undefined) fields.remark = data.remark;
|
||||
if (Object.keys(fields).length === 0) throw new Error('没有需要更新的字段');
|
||||
|
||||
await record.update(fields);
|
||||
return record;
|
||||
}
|
||||
|
||||
async delete(id) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = ctx.user.store_id;
|
||||
const record = await ctx.model.Camera.findOne({ where: { id, warehouse_id: warehouseId } });
|
||||
if (!record) throw new Error('摄像头不存在或无权操作');
|
||||
|
||||
// 检查是否被工作台绑定
|
||||
const boundWorkbenches = await ctx.model.Workbench.findAll({
|
||||
where: { warehouse_id: warehouseId },
|
||||
attributes: ['id', 'name'],
|
||||
});
|
||||
for (const wb of boundWorkbenches) {
|
||||
const deviceIds = Array.isArray(wb.device_ids) ? wb.device_ids : [];
|
||||
if (deviceIds.includes(id)) {
|
||||
throw new Error(`摄像头已被工作台「${wb.name}」绑定,请先解绑后再删除`);
|
||||
}
|
||||
}
|
||||
|
||||
await record.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CameraService;
|
||||
127
app/service/systems/cameraServer.js
Normal file
127
app/service/systems/cameraServer.js
Normal file
@ -0,0 +1,127 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
class CameraServerService extends Service {
|
||||
async list(params = {}) {
|
||||
const { ctx } = this;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
const warehouseId = ctx.user.store_id;
|
||||
const { pagination = {}, where = {} } = params;
|
||||
|
||||
const page = Math.max(1, parseInt(pagination.page) || 1);
|
||||
const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20));
|
||||
|
||||
const queryWhere = { warehouse_id: warehouseId };
|
||||
if (where.name) queryWhere.name = { [Op.like]: `%${where.name}%` };
|
||||
if (where.status !== undefined && where.status !== null && where.status !== '') {
|
||||
queryWhere.status = parseInt(where.status);
|
||||
}
|
||||
|
||||
const { count, rows } = await ctx.model.CameraServer.findAndCountAll({
|
||||
where: queryWhere,
|
||||
order: [['created_at', 'DESC']],
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
});
|
||||
|
||||
return { list: rows, pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize), hasPrevious: page > 1, hasNext: page * pageSize < count } };
|
||||
}
|
||||
|
||||
async detail(id) {
|
||||
const { ctx } = this;
|
||||
const record = await ctx.model.CameraServer.findOne({ where: { id, warehouse_id: ctx.user.store_id } });
|
||||
if (!record) throw new Error('录像服务器不存在或无权访问');
|
||||
return record;
|
||||
}
|
||||
|
||||
async create(data) {
|
||||
const { ctx } = this;
|
||||
if (!data.name || !String(data.name).trim()) throw new Error('服务器名称不能为空');
|
||||
|
||||
// 规范化 IP 和端口
|
||||
const publicIp = data.public_ip ? String(data.public_ip).trim() : '';
|
||||
const internalIp = data.internal_ip ? String(data.internal_ip).trim() : '';
|
||||
const publicPort = data.public_port !== undefined && data.public_port !== null ? parseInt(data.public_port) : null;
|
||||
const internalPort = data.internal_port !== undefined && data.internal_port !== null ? parseInt(data.internal_port) : null;
|
||||
|
||||
// IP-端口配对校验:有 IP 则端口必填
|
||||
if (publicIp && !publicPort) throw new Error('公网端口不能为空');
|
||||
if (internalIp && !internalPort) throw new Error('内网端口不能为空');
|
||||
|
||||
// 至少一组 IP+端口 完整
|
||||
const hasPublic = !!(publicIp && publicPort);
|
||||
const hasInternal = !!(internalIp && internalPort);
|
||||
if (!hasPublic && !hasInternal) throw new Error('至少需要填写一组公网IP+端口或内网IP+端口');
|
||||
|
||||
return await ctx.model.CameraServer.create({
|
||||
warehouse_id: ctx.user.store_id,
|
||||
name: String(data.name).trim(),
|
||||
brand: data.brand || null,
|
||||
public_ip: publicIp || null,
|
||||
internal_ip: internalIp || null,
|
||||
public_port: publicPort,
|
||||
internal_port: internalPort,
|
||||
username: data.username || null,
|
||||
password: data.password || null,
|
||||
status: data.status !== undefined ? parseInt(data.status) : 1,
|
||||
remark: data.remark || null,
|
||||
});
|
||||
}
|
||||
|
||||
async update(id, data) {
|
||||
const { ctx } = this;
|
||||
const record = await ctx.model.CameraServer.findOne({ where: { id, warehouse_id: ctx.user.store_id } });
|
||||
if (!record) throw new Error('录像服务器不存在或无权操作');
|
||||
|
||||
const fields = {};
|
||||
if (data.name !== undefined) fields.name = String(data.name).trim();
|
||||
if (data.brand !== undefined) fields.brand = data.brand;
|
||||
if (data.public_ip !== undefined) fields.public_ip = data.public_ip ? String(data.public_ip).trim() : null;
|
||||
if (data.internal_ip !== undefined) fields.internal_ip = data.internal_ip ? String(data.internal_ip).trim() : null;
|
||||
if (data.public_port !== undefined) fields.public_port = data.public_port !== null ? parseInt(data.public_port) : null;
|
||||
if (data.internal_port !== undefined) fields.internal_port = data.internal_port !== null ? parseInt(data.internal_port) : null;
|
||||
if (data.username !== undefined) fields.username = data.username;
|
||||
if (data.password !== undefined) fields.password = data.password;
|
||||
if (data.status !== undefined) fields.status = parseInt(data.status);
|
||||
if (data.remark !== undefined) fields.remark = data.remark;
|
||||
if (Object.keys(fields).length === 0) throw new Error('没有需要更新的字段');
|
||||
|
||||
// 合并新旧值,校验最终状态
|
||||
const mergedPublicIp = data.public_ip !== undefined ? fields.public_ip : record.public_ip;
|
||||
const mergedInternalIp = data.internal_ip !== undefined ? fields.internal_ip : record.internal_ip;
|
||||
const mergedPublicPort = data.public_port !== undefined ? fields.public_port : record.public_port;
|
||||
const mergedInternalPort = data.internal_port !== undefined ? fields.internal_port : record.internal_port;
|
||||
|
||||
// IP-端口配对校验
|
||||
if (mergedPublicIp && !mergedPublicPort) throw new Error('公网端口不能为空');
|
||||
if (mergedInternalIp && !mergedInternalPort) throw new Error('内网端口不能为空');
|
||||
|
||||
// 至少一组 IP+端口 完整
|
||||
const hasPublic = !!(mergedPublicIp && mergedPublicPort);
|
||||
const hasInternal = !!(mergedInternalIp && mergedInternalPort);
|
||||
if (!hasPublic && !hasInternal) throw new Error('至少需要填写一组公网IP+端口或内网IP+端口');
|
||||
|
||||
await record.update(fields);
|
||||
return record;
|
||||
}
|
||||
|
||||
async delete(id) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = ctx.user.store_id;
|
||||
const record = await ctx.model.CameraServer.findOne({ where: { id, warehouse_id: warehouseId } });
|
||||
if (!record) throw new Error('录像服务器不存在或无权操作');
|
||||
|
||||
// 检查是否有关联摄像头
|
||||
const cameraCount = await ctx.model.Camera.count({
|
||||
where: { server_id: id, warehouse_id: warehouseId },
|
||||
});
|
||||
if (cameraCount > 0) {
|
||||
throw new Error(`录像服务器下存在 ${cameraCount} 个摄像头,请先删除摄像头后再删除服务器`);
|
||||
}
|
||||
|
||||
await record.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CameraServerService;
|
||||
@ -1180,15 +1180,19 @@ class DeliveryOrderService extends Service {
|
||||
continue;
|
||||
}
|
||||
let wms_stock = null;
|
||||
// 手工单:调用方直接传入 stockId 时跳过 stock_store 查表,直接使用
|
||||
// 手工单:调用方直接传入 stockId 时需查 StockStore 获取完整信息(含 gross_weight)
|
||||
if (line.stockId && line.stockId > 0) {
|
||||
wms_stock = {
|
||||
id: line.stockId,
|
||||
stock_id: line.stockId,
|
||||
item_name: line.itemName || '',
|
||||
item_code: line.itemCode || '',
|
||||
gross_weight: 0,
|
||||
};
|
||||
wms_stock = await app.model.StockStore.findByPk(line.stockId, { transaction });
|
||||
if (!wms_stock) {
|
||||
// 降级:查不到记录时用调用方传入的字段构造最小对象
|
||||
wms_stock = {
|
||||
id: line.stockId,
|
||||
stock_id: line.stockId,
|
||||
item_name: line.itemName || '',
|
||||
item_code: line.itemCode || '',
|
||||
gross_weight: 0,
|
||||
};
|
||||
}
|
||||
} else if (!line.itemId) {
|
||||
// 查找唯一键(appKey 为空时不作为条件,兼容内部手动建单场景)
|
||||
const stockWhere = {
|
||||
@ -1242,6 +1246,24 @@ class DeliveryOrderService extends Service {
|
||||
// ===== Sort: 按 stockId 升序排序,保证所有事务加锁顺序一致,从根本上消除死锁 =====
|
||||
resolvedItems.sort((a, b) => a.stockId - b.stockId);
|
||||
|
||||
// ===== 批量查询 wms_stock_warehouse 获取仓库侧称重毛重 =====
|
||||
const stockIds = [...new Set(resolvedItems.map(item => item.stockId).filter(Boolean))];
|
||||
const warehouseWeightMap = new Map();
|
||||
if (stockIds.length > 0) {
|
||||
const warehouseRecords = await app.model.StockWarehouse.findAll({
|
||||
where: { id: stockIds },
|
||||
attributes: ['id', 'gross_weight'],
|
||||
transaction,
|
||||
raw: true,
|
||||
});
|
||||
for (const record of warehouseRecords) {
|
||||
const gw = parseFloat(record.gross_weight) || 0;
|
||||
if (gw > 0) {
|
||||
warehouseWeightMap.set(record.id, gw);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ===== Phase 2: 锁定阶段(按排序后顺序逐个加锁)=====
|
||||
for (const item of resolvedItems) {
|
||||
const lockResult = await ctx.service.systems.stockStore.lockItemStorages(
|
||||
@ -1260,7 +1282,11 @@ class DeliveryOrderService extends Service {
|
||||
const totalQtyForStock = (stockQuantityMap.get(item.stockId) || 0) + item.planQty;
|
||||
stockQuantityMap.set(item.stockId, totalQtyForStock);
|
||||
|
||||
const weight = parseFloat(item.wms_stock.gross_weight) || 0;
|
||||
// 优先取 wms_stock_warehouse.gross_weight(仓库称重),其次取 wms_stock_store.gross_weight
|
||||
const warehouseWeight = warehouseWeightMap.get(item.stockId);
|
||||
const weight = (warehouseWeight != null && warehouseWeight > 0)
|
||||
? warehouseWeight
|
||||
: (parseFloat(item.wms_stock.gross_weight) || 0);
|
||||
stockWeightMap.set(item.stockId, weight);
|
||||
|
||||
// 所有检查通过,准备订单行数据
|
||||
@ -1319,8 +1345,6 @@ class DeliveryOrderService extends Service {
|
||||
return sum + (weight * qty);
|
||||
}, 0);
|
||||
source_order_codes = new Set(lineData.map(line => line.source_order_code).filter(code => code)); // 订单来源去重集合
|
||||
// 格式化重量(保留2位小数)
|
||||
total_weight = parseFloat(total_weight.toFixed(2));
|
||||
|
||||
ctx.logger.debug('[订单统计信息]', {
|
||||
orderId,
|
||||
|
||||
@ -632,6 +632,9 @@ class ExpressService extends Service {
|
||||
id: {
|
||||
[Op.in]: normalizedOrderIds,
|
||||
},
|
||||
status: {
|
||||
[Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
@ -695,7 +698,12 @@ class ExpressService extends Service {
|
||||
order_flag: normalizedErrorMessage,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where,
|
||||
where: {
|
||||
...where,
|
||||
status: {
|
||||
[Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@ -1788,6 +1796,11 @@ class ExpressService extends Service {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 停用的快递接口不允许分配运单号
|
||||
if (Number(item.is_enabled) !== 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const candidateCodes = [
|
||||
normalizeCode(item.sys_express_code),
|
||||
normalizeCode(item.express_code),
|
||||
@ -2046,7 +2059,7 @@ class ExpressService extends Service {
|
||||
items: this.normalizeWaybillAsyncItems(orderDelivery.items),
|
||||
items_count: this.normalizeWaybillAsyncNumber(orderDelivery.items_count),
|
||||
items_total: this.normalizeWaybillAsyncNumber(orderDelivery.items_total),
|
||||
items_weight: this.normalizeWaybillAsyncNumber(orderDelivery.items_weight),
|
||||
items_weight: this.normalizeWaybillAsyncNumber(orderDelivery.items_weight), // 单位 g,传递给下游快递平台
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@ -708,7 +708,7 @@ class ExpressPlatformService extends MainService {
|
||||
procode: order.procode || '普通商品',
|
||||
codpaymoney: order.ar_amount ?? null,
|
||||
packagemoney: order.item_amount ?? null,
|
||||
weight: Number(order.items_weight) || 0,
|
||||
weight: Number(order.items_weight) || 0, // 单位 g,需确认 PolyAPI 期望单位
|
||||
supporpaymoney: order.total_amount ?? null,
|
||||
length: Number(order.length) || 0,
|
||||
width: Number(order.width) || 0,
|
||||
@ -743,7 +743,7 @@ class ExpressPlatformService extends MainService {
|
||||
receiver: {
|
||||
name: order.name || '',
|
||||
company: order.company || '',
|
||||
phone: order.mobile || order.tel || '',
|
||||
phone: order.sys_platform_code === 'KS' ? undefined : (order.mobile || order.tel || ''),
|
||||
mobile: order.mobile || order.tel || '',
|
||||
country: order.country_code || 'CN',
|
||||
province: order.province || '',
|
||||
|
||||
@ -373,23 +373,26 @@ class InboundDirectLogService extends Service {
|
||||
// CREATED 人工导入允许超过计划数量
|
||||
const isManualImport = entryOrder.order_status === 'CREATED' && !isBindingMode;
|
||||
if (!isManualImport) {
|
||||
const newTotal = existingTotal + effectiveQuantity;
|
||||
if (newTotal > totalPlanQty) {
|
||||
const maxAllowed = totalPlanQty - existingTotal;
|
||||
if (maxAllowed <= 0) {
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
code: 400,
|
||||
message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${effectiveQuantity},合计 ${newTotal}`,
|
||||
message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${effectiveQuantity},合计 ${existingTotal + effectiveQuantity}`,
|
||||
data: {
|
||||
stock_id: stockId,
|
||||
plan_quantity: totalPlanQty,
|
||||
existing_quantity: existingTotal,
|
||||
requested_quantity: effectiveQuantity,
|
||||
exceeded_by: newTotal - totalPlanQty,
|
||||
exceeded_by: effectiveQuantity,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
if (effectiveQuantity > maxAllowed) {
|
||||
effectiveQuantity = maxAllowed;
|
||||
}
|
||||
}
|
||||
|
||||
// 剩余可入库数 = 计划数 - max(已收货量, 已写入 direct_log 的待入库量)
|
||||
@ -853,7 +856,7 @@ class InboundDirectLogService extends Service {
|
||||
itemId: item.item_id || '',
|
||||
inventoryType: item.inventory_type || 'ZP',
|
||||
planQty: Number(item.count) || 0,
|
||||
actualQty: Number(item.count) || 0,
|
||||
actualQty: stockSummary[String(item.stock_id)] || 0,
|
||||
}));
|
||||
|
||||
const syncResult = await this.qimenEntrySync({
|
||||
@ -957,11 +960,18 @@ class InboundDirectLogService extends Service {
|
||||
transaction,
|
||||
});
|
||||
|
||||
// 同一 stock_id 只写一次库存
|
||||
if (processedStockIds.has(String(stockId))) continue;
|
||||
processedStockIds.add(String(stockId));
|
||||
if (!isBinding) {
|
||||
nonBindingStockProcessed.add(String(stockId));
|
||||
// 同一 stock_id 只写一次 StockWarehouse 总库存(聚合量),但 Storage 按入库记录逐条写入
|
||||
const isStockWarehouseDone = processedStockIds.has(String(stockId));
|
||||
if (isStockWarehouseDone && !isBinding) {
|
||||
// 非绑定模式:StockWarehouse 已写但 Storage 还未写,不能 continue,继续写 Storage
|
||||
} else if (isStockWarehouseDone) {
|
||||
continue;
|
||||
}
|
||||
if (!isStockWarehouseDone) {
|
||||
processedStockIds.add(String(stockId));
|
||||
if (!isBinding) {
|
||||
nonBindingStockProcessed.add(String(stockId));
|
||||
}
|
||||
}
|
||||
|
||||
// 使用入库单号作为批次号;若有收货绑定则使用收货明细信息
|
||||
@ -972,137 +982,162 @@ class InboundDirectLogService extends Service {
|
||||
const batchNo = eo.entry_order_code;
|
||||
const inventoryType = item.inventory_type || 'ZP';
|
||||
|
||||
// 从该 stock_id 的入库记录中取第一个非空 space_id,兜底 1
|
||||
const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id);
|
||||
const spaceId = logForSpace ? Number(logForSpace.space_id) : 1;
|
||||
// StockWarehouse 总库存:每个 stock_id 聚合写入一次
|
||||
if (!isStockWarehouseDone) {
|
||||
// 锁定并更新 StockWarehouse 总库存
|
||||
const stockRecord = await ctx.model.StockWarehouse.findOne({
|
||||
where: { id: stockId, is_valid: 'Y', deleted_at: null },
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
transaction,
|
||||
});
|
||||
|
||||
// 锁定并更新 StockWarehouse 总库存
|
||||
const stockRecord = await ctx.model.StockWarehouse.findOne({
|
||||
where: { id: stockId, is_valid: 'Y', deleted_at: null },
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
transaction,
|
||||
});
|
||||
if (stockRecord) {
|
||||
const beforeQuantity = Number(stockRecord.quantity) || 0;
|
||||
const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||||
|
||||
if (stockRecord) {
|
||||
const beforeQuantity = Number(stockRecord.quantity) || 0;
|
||||
const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||||
await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true });
|
||||
await stockRecord.reload({ transaction });
|
||||
|
||||
await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true });
|
||||
await stockRecord.reload({ transaction });
|
||||
const afterQuantity = Number(stockRecord.quantity) || 0;
|
||||
const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||||
|
||||
const afterQuantity = Number(stockRecord.quantity) || 0;
|
||||
const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0;
|
||||
// 写入库存流水(聚合维度)
|
||||
await ctx.service.systems.stockTransaction.create({
|
||||
transaction_type: 'INBOUND',
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
stock_id: stockId,
|
||||
quantity: inboundQty,
|
||||
batch_no: batchNo,
|
||||
inventory_type: inventoryType,
|
||||
order_type: eo.order_type,
|
||||
order_no: eo.entry_order_code,
|
||||
entry_order_id: eo.id,
|
||||
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
|
||||
operator_name: ctx.user?.employees_name || '',
|
||||
remark: '导入/PDA直接入库提交',
|
||||
before_quantity: beforeQuantity,
|
||||
after_quantity: afterQuantity,
|
||||
before_locked_quantity: beforeLockedQuantity,
|
||||
after_locked_quantity: afterLockedQuantity,
|
||||
created_at: new Date(),
|
||||
}, { transaction });
|
||||
}
|
||||
}
|
||||
|
||||
// 写入库存流水
|
||||
await ctx.service.systems.stockTransaction.create({
|
||||
/**
|
||||
* 写入 Storage 库位库存 + storage_transaction 的通用函数
|
||||
* @param {number} spaceId 库位ID
|
||||
* @param {number} qty 入库数量
|
||||
* @param {number|null} rdId 收货单ID
|
||||
* @param {string|null} prodDate 生产日期
|
||||
* @param {string|null} expDate 到期日期
|
||||
*/
|
||||
const writeStorageRecord = async (spaceId, qty, rdId, prodDate, expDate) => {
|
||||
if (qty <= 0) return;
|
||||
|
||||
const sRecord = await ctx.model.Storage.findOne({
|
||||
where: {
|
||||
space_id: spaceId,
|
||||
stock_id: stockId,
|
||||
batch_no: batchNo,
|
||||
inventory_type: inventoryType,
|
||||
is_enabled: 1,
|
||||
delete_at: null,
|
||||
},
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
transaction,
|
||||
});
|
||||
|
||||
let sId = null;
|
||||
let sBeforeQty = 0;
|
||||
let sAfterQty = 0;
|
||||
|
||||
if (sRecord) {
|
||||
sBeforeQty = Number(sRecord.quantity) || 0;
|
||||
sAfterQty = sBeforeQty + qty;
|
||||
|
||||
await ctx.model.Storage.update({
|
||||
quantity: app.Sequelize.literal(`quantity + ${qty}`),
|
||||
available_quantity: app.Sequelize.literal(`available_quantity + ${qty}`),
|
||||
entry_order_id: eo.id,
|
||||
inbound_time: new Date(),
|
||||
inbound_order_no: eo.entry_order_code,
|
||||
production_date: prodDate,
|
||||
expiry_date: expDate,
|
||||
receiving_id: rdId,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: { id: sRecord.id },
|
||||
transaction,
|
||||
});
|
||||
sId = sRecord.id;
|
||||
} else {
|
||||
sBeforeQty = 0;
|
||||
sAfterQty = qty;
|
||||
|
||||
const createdStorage = await ctx.model.Storage.create({
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
space_id: spaceId,
|
||||
stock_id: stockId,
|
||||
batch_no: effectiveBatchNo,
|
||||
inventory_type: inventoryType,
|
||||
quantity: qty,
|
||||
locked_quantity: 0,
|
||||
available_quantity: qty,
|
||||
inbound_time: new Date(),
|
||||
inbound_order_no: eo.entry_order_code,
|
||||
receiving_id: rdId,
|
||||
entry_order_id: eo.id,
|
||||
supplier_id: null,
|
||||
supplier_batch_no: null,
|
||||
production_date: prodDate,
|
||||
expiry_date: expDate,
|
||||
is_enabled: 1,
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
}, { transaction });
|
||||
sId = createdStorage.id;
|
||||
}
|
||||
|
||||
// 写入库位维度库存流水
|
||||
await ctx.model.StorageTransaction.create({
|
||||
transaction_type: 'INBOUND',
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
stock_id: stockId,
|
||||
quantity: inboundQty,
|
||||
batch_no: batchNo,
|
||||
storage_id: sId,
|
||||
space_id: spaceId,
|
||||
quantity: qty,
|
||||
before_quantity: sBeforeQty,
|
||||
after_quantity: sAfterQty,
|
||||
batch_no: effectiveBatchNo,
|
||||
inventory_type: inventoryType,
|
||||
order_type: eo.order_type,
|
||||
order_type: 'entry_order',
|
||||
order_no: eo.entry_order_code,
|
||||
entry_order_id: eo.id,
|
||||
order_id: eo.id,
|
||||
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
|
||||
operator_name: ctx.user?.employees_name || '',
|
||||
remark: '导入/PDA直接入库提交',
|
||||
before_quantity: beforeQuantity,
|
||||
after_quantity: afterQuantity,
|
||||
before_locked_quantity: beforeLockedQuantity,
|
||||
after_locked_quantity: afterLockedQuantity,
|
||||
created_at: new Date(),
|
||||
}, { transaction });
|
||||
}
|
||||
};
|
||||
|
||||
// 创建/更新 Storage 库位库存
|
||||
const storageRecord = await ctx.model.Storage.findOne({
|
||||
where: {
|
||||
space_id: spaceId,
|
||||
stock_id: stockId,
|
||||
batch_no: batchNo,
|
||||
inventory_type: inventoryType,
|
||||
is_enabled: 1,
|
||||
delete_at: null,
|
||||
},
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
transaction,
|
||||
});
|
||||
|
||||
let storageId = null;
|
||||
let storageBeforeQty = 0;
|
||||
let storageAfterQty = 0;
|
||||
|
||||
if (storageRecord) {
|
||||
storageBeforeQty = Number(storageRecord.quantity) || 0;
|
||||
storageAfterQty = storageBeforeQty + inboundQty;
|
||||
|
||||
await ctx.model.Storage.update({
|
||||
quantity: app.Sequelize.literal(`quantity + ${inboundQty}`),
|
||||
available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`),
|
||||
entry_order_id: eo.id,
|
||||
inbound_time: new Date(),
|
||||
inbound_order_no: eo.entry_order_code,
|
||||
production_date: rdProductionDate,
|
||||
expiry_date: rdExpiryDate,
|
||||
receiving_id: rdReceivingId,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: { id: storageRecord.id },
|
||||
transaction,
|
||||
});
|
||||
storageId = storageRecord.id;
|
||||
if (isBinding) {
|
||||
// 绑定模式:按 entryItem 维度写 Storage(与收货明细绑定,space_id 取第一条入库记录的库位)
|
||||
const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id);
|
||||
const spaceId = logForSpace ? Number(logForSpace.space_id) : 1;
|
||||
await writeStorageRecord(spaceId, inboundQty, rdReceivingId, rdProductionDate, rdExpiryDate);
|
||||
} else {
|
||||
storageBeforeQty = 0;
|
||||
storageAfterQty = inboundQty;
|
||||
|
||||
const createdStorage = await ctx.model.Storage.create({
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
space_id: spaceId,
|
||||
stock_id: stockId,
|
||||
batch_no: effectiveBatchNo,
|
||||
inventory_type: inventoryType,
|
||||
quantity: inboundQty,
|
||||
locked_quantity: 0,
|
||||
available_quantity: inboundQty,
|
||||
inbound_time: new Date(),
|
||||
inbound_order_no: eo.entry_order_code,
|
||||
receiving_id: rdReceivingId,
|
||||
entry_order_id: eo.id,
|
||||
supplier_id: null,
|
||||
supplier_batch_no: null,
|
||||
production_date: rdProductionDate,
|
||||
expiry_date: rdExpiryDate,
|
||||
is_enabled: 1,
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
}, { transaction });
|
||||
storageId = createdStorage.id;
|
||||
// 非绑定模式:按每个 InboundDirectLog 记录独立写 Storage,每条记录保有自己指定的 space_id 和 quantity
|
||||
const stockDirectLogs = directLogs.filter(l => String(l.stock_id) === String(stockId) && Number(l.quantity) > 0);
|
||||
for (const dlog of stockDirectLogs) {
|
||||
const dlogSpaceId = dlog.space_id || 1;
|
||||
const dlogQty = Number(dlog.quantity) || 0;
|
||||
await writeStorageRecord(dlogSpaceId, dlogQty, null, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
// 写入库位维度库存流水
|
||||
await ctx.model.StorageTransaction.create({
|
||||
transaction_type: 'INBOUND',
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
stock_id: stockId,
|
||||
storage_id: storageId,
|
||||
space_id: spaceId,
|
||||
quantity: inboundQty,
|
||||
before_quantity: storageBeforeQty,
|
||||
after_quantity: storageAfterQty,
|
||||
batch_no: effectiveBatchNo,
|
||||
inventory_type: inventoryType,
|
||||
order_type: 'entry_order',
|
||||
order_no: eo.entry_order_code,
|
||||
order_id: eo.id,
|
||||
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
|
||||
operator_name: ctx.user?.employees_name || '',
|
||||
remark: '导入/PDA直接入库提交',
|
||||
created_at: new Date(),
|
||||
}, { transaction });
|
||||
}
|
||||
|
||||
// 将 pending 绑定升级为 committed(在 InboundDirectLog 中更新状态)
|
||||
|
||||
@ -76,7 +76,7 @@ class LocationService extends Service {
|
||||
width: cellWidth,
|
||||
height: cellHeight,
|
||||
volume: cellLength * cellWidth * cellHeight / 1000000, // cm³转m³
|
||||
max_weight: 100, // 默认100kg
|
||||
max_weight: 100000, // 默认100000g
|
||||
space_status: 'AVAILABLE',
|
||||
is_enabled: true,
|
||||
relative_x: relativeX,
|
||||
|
||||
@ -1115,7 +1115,7 @@ class LocationZoneService extends Service {
|
||||
width: cellWidth,
|
||||
height: cellHeight,
|
||||
volume: cellLength * cellWidth * cellHeight / 1000000,
|
||||
max_weight: 100,
|
||||
max_weight: 100000,
|
||||
space_status: 'AVAILABLE',
|
||||
is_enabled: true,
|
||||
relative_x: relativeX,
|
||||
|
||||
@ -483,6 +483,9 @@ async function markPendingExceptionInternal(service, orderModel, orderId, wareho
|
||||
where: {
|
||||
id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
status: {
|
||||
[Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@ -50,7 +50,7 @@ const ORDER_EXPORT_COLUMNS = Object.freeze([
|
||||
{ header: '商品种数', key: 'items_count', width: 12 },
|
||||
{ header: '商品件数', key: 'items_total', width: 12 },
|
||||
{ header: '商品重量', key: 'items_weight', width: 12 },
|
||||
{ header: '称重重量(kg)', key: 'weighing_weight', width: 14 },
|
||||
{ header: '称重重量(g)', key: 'weighing_weight', width: 14 },
|
||||
{ header: '订单金额', key: 'total_amount', width: 14 },
|
||||
{ header: '实收金额', key: 'got_amount', width: 14 },
|
||||
{ header: '创建时间', key: 'create_at', width: 20 },
|
||||
@ -99,7 +99,7 @@ const ORDER_EXPORT_ITEM_COLUMNS = Object.freeze([
|
||||
{ header: '商品种数', key: 'items_count', width: 12 },
|
||||
{ header: '商品件数', key: 'items_total', width: 12 },
|
||||
{ header: '商品重量', key: 'items_weight', width: 12 },
|
||||
{ header: '称重重量(kg)', key: 'weighing_weight', width: 14 },
|
||||
{ header: '称重重量(g)', key: 'weighing_weight', width: 14 },
|
||||
{ header: '订单金额', key: 'total_amount', width: 14 },
|
||||
{ header: '实收金额', key: 'got_amount', width: 14 },
|
||||
{ header: '创建时间', key: 'create_at', width: 20 },
|
||||
|
||||
@ -199,9 +199,9 @@ class OrderExpressService extends Service {
|
||||
/**
|
||||
* 规范化并校验称重重量。
|
||||
*
|
||||
* 允许最多 3 位小数,且必须大于 0。
|
||||
* 必须为正整数(单位 g),且必须大于 0。
|
||||
*
|
||||
* @param {number|string} weighingWeight 称重重量。
|
||||
* @param {number|string} weighingWeight 称重重量(g)。
|
||||
* @return {number} 合法重量数值。
|
||||
*/
|
||||
normalizeWeighingWeight(weighingWeight) {
|
||||
@ -210,8 +210,8 @@ class OrderExpressService extends Service {
|
||||
}
|
||||
|
||||
const normalizedWeightText = String(weighingWeight).trim();
|
||||
if (!/^\d+(?:\.\d{1,3})?$/.test(normalizedWeightText)) {
|
||||
throw this.createBusinessError('weighing_weight 格式非法,最多支持 3 位小数', 400);
|
||||
if (!/^\d+$/.test(normalizedWeightText)) {
|
||||
throw this.createBusinessError('weighing_weight 格式非法,必须为正整数(单位 g)', 400);
|
||||
}
|
||||
|
||||
const normalizedWeight = Number(normalizedWeightText);
|
||||
@ -263,7 +263,7 @@ class OrderExpressService extends Service {
|
||||
* @param {Object} payload 入参对象。
|
||||
* @param {number|string} payload.orderId 订单ID。
|
||||
* @param {string} [payload.waybillCode] 运单号,多运单场景必填。
|
||||
* @param {number|string} payload.weighingWeight 称重重量(kg)。
|
||||
* @param {number|string} payload.weighingWeight 称重重量(g)。
|
||||
* @return {Promise<Object>} 单订单返回 {order_id, waybill_code, weighing_weight, items_weight};
|
||||
* 团购批量返回 {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name, items_weight}。
|
||||
*/
|
||||
@ -645,9 +645,7 @@ class OrderExpressService extends Service {
|
||||
});
|
||||
}
|
||||
const entry = splitMap.get(bk);
|
||||
entry.weighing_weight = Number(
|
||||
(entry.weighing_weight + Number(row.weighing_weight || 0)).toFixed(3)
|
||||
);
|
||||
entry.weighing_weight = entry.weighing_weight + Number(row.weighing_weight || 0);
|
||||
// 优先取非空的 waybill_code 作为该拆单的代表运单号
|
||||
if (!entry.waybill_code && row.waybill_code) {
|
||||
entry.waybill_code = row.waybill_code;
|
||||
@ -655,9 +653,7 @@ class OrderExpressService extends Service {
|
||||
}
|
||||
|
||||
const splits = [ ...splitMap.values() ];
|
||||
const totalWeight = Number(
|
||||
splits.reduce((sum, s) => sum + s.weighing_weight, 0).toFixed(3)
|
||||
);
|
||||
const totalWeight = splits.reduce((sum, s) => sum + s.weighing_weight, 0);
|
||||
// split_count:仅统计 waybill_code 不为空的 business_key
|
||||
const splitCount = splits.filter(s => s.waybill_code !== null).length;
|
||||
|
||||
|
||||
578
app/service/systems/order_packing.js
Normal file
578
app/service/systems/order_packing.js
Normal file
@ -0,0 +1,578 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/**
|
||||
* 打包任务服务层(仓库侧)。
|
||||
* 负责打包任务列表查询、详情查询等仓库维度的打包管理业务逻辑。
|
||||
* 数据来源:wms_pack_task 表。
|
||||
*/
|
||||
class OrderPackingService extends Service {
|
||||
/**
|
||||
* 获取仓库的录制电脑 ID(带缓存)。
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @return {Promise<number|null>} 录制电脑ID,找不到返回 null
|
||||
*/
|
||||
async _getRecordingComputerId(warehouseId) {
|
||||
const cacheKey = `_recordingComputer_${warehouseId}`;
|
||||
if (this[cacheKey] !== undefined) {
|
||||
return this[cacheKey];
|
||||
}
|
||||
const row = await this.ctx.model.PrintComputer.findOne({
|
||||
where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null },
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
this[cacheKey] = row ? row.id : null;
|
||||
return this[cacheKey];
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建视频完整 URL。
|
||||
* 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath}
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @param {number|null} recordingComputerId 录制电脑ID
|
||||
* @param {string} videoPath 视频路径
|
||||
* @return {string} 完整 URL
|
||||
*/
|
||||
_buildVideoUrl(warehouseId, recordingComputerId, videoPath) {
|
||||
if (!videoPath || !recordingComputerId) {
|
||||
return videoPath || '';
|
||||
}
|
||||
return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${videoPath}`;
|
||||
}
|
||||
/**
|
||||
* 打包任务列表查询(仓库侧)。
|
||||
* 按仓库维度(warehouse_id)查询打包任务,支持分页、筛选、排序。
|
||||
*
|
||||
* @param {Object} where 筛选条件对象
|
||||
* @param {Object} [where.status] 任务状态:0=待处理 1=打包中 2=已完成 3=异常
|
||||
* @param {Object} [where.pack_mode] 打包模式:1=散单 2=团购
|
||||
* @param {Object} [where.waybill_code] 运单号(模糊匹配)
|
||||
* @param {Object} [where.wave_no] 波次号(模糊匹配)
|
||||
* @param {Object} [where.order_id] 订单ID(精确匹配)
|
||||
* @param {Object} [where.workbench_id] 工作台ID(精确匹配)
|
||||
* @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查)
|
||||
* @param {Object} [where.start_time_start] 开始打包时间起始
|
||||
* @param {Object} [where.start_time_end] 开始打包时间结束
|
||||
* @param {Object} pagination 分页参数 { page, pageSize }
|
||||
* @param {Object} sort 排序参数 { sortField, sortOrder }
|
||||
* @return {Promise<Object>} 打包任务列表与分页信息
|
||||
*/
|
||||
async list(where = {}, pagination = {}, sort = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
const page = Math.max(Number(pagination.page) || 1, 1);
|
||||
const pageSize = Math.max(Number(pagination.pageSize) || 20, 1);
|
||||
|
||||
// 仓库上下文
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
if (!warehouseId) {
|
||||
return {
|
||||
code: 400,
|
||||
message: '用户未绑定仓库,无法查询打包任务',
|
||||
data: {
|
||||
list: [],
|
||||
pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 构建查询条件
|
||||
const queryWhere = { warehouse_id: warehouseId };
|
||||
|
||||
// 状态筛选
|
||||
if (where.status !== undefined && where.status !== null) {
|
||||
const statusValue = where.status?.value ?? where.status;
|
||||
if (statusValue !== '' && statusValue !== undefined && statusValue !== null) {
|
||||
queryWhere.status = Number(statusValue);
|
||||
}
|
||||
}
|
||||
|
||||
// 打包模式筛选
|
||||
if (where.pack_mode !== undefined && where.pack_mode !== null) {
|
||||
const packModeValue = where.pack_mode?.value ?? where.pack_mode;
|
||||
if (packModeValue !== '' && packModeValue !== undefined && packModeValue !== null) {
|
||||
queryWhere.pack_mode = Number(packModeValue);
|
||||
}
|
||||
}
|
||||
|
||||
// 运单号模糊匹配
|
||||
if (where.waybill_code) {
|
||||
const waybillValue = where.waybill_code?.value ?? where.waybill_code;
|
||||
if (waybillValue && String(waybillValue).trim()) {
|
||||
queryWhere.waybill_code = { [Op.like]: `%${String(waybillValue).trim()}%` };
|
||||
}
|
||||
}
|
||||
|
||||
// 波次号模糊匹配
|
||||
if (where.wave_no) {
|
||||
const waveNoValue = where.wave_no?.value ?? where.wave_no;
|
||||
if (waveNoValue && String(waveNoValue).trim()) {
|
||||
queryWhere.wave_no = { [Op.like]: `%${String(waveNoValue).trim()}%` };
|
||||
}
|
||||
}
|
||||
|
||||
// 订单ID精确匹配
|
||||
if (where.order_id !== undefined && where.order_id !== null) {
|
||||
const orderIdValue = where.order_id?.value ?? where.order_id;
|
||||
if (orderIdValue !== '' && orderIdValue !== undefined && orderIdValue !== null) {
|
||||
queryWhere.order_id = Number(orderIdValue);
|
||||
}
|
||||
}
|
||||
|
||||
// 工作台ID精确匹配
|
||||
if (where.workbench_id !== undefined && where.workbench_id !== null) {
|
||||
const workbenchIdValue = where.workbench_id?.value ?? where.workbench_id;
|
||||
if (workbenchIdValue !== '' && workbenchIdValue !== undefined && workbenchIdValue !== null) {
|
||||
queryWhere.workbench_id = Number(workbenchIdValue);
|
||||
}
|
||||
}
|
||||
|
||||
// 快捷搜索:支持波次号直接模糊匹配 + 运单号通过 express → order → wave 链路解析
|
||||
if (where.quickWhere) {
|
||||
const quickValue = where.quickWhere?.value ?? where.quickWhere;
|
||||
if (quickValue && String(quickValue).trim()) {
|
||||
const kw = String(quickValue).trim();
|
||||
const orConditions = [];
|
||||
|
||||
// 1. 波次号直接模糊匹配(用户可能直接搜波次号)
|
||||
orConditions.push({ wave_no: { [Op.like]: `%${kw}%` } });
|
||||
|
||||
// 2. 运单号解析:express → order → wave
|
||||
// 团购波次 → 按 wave_no 查 packing 表;散单 → 按 order_id 查 packing 表
|
||||
const expressRecords = await ctx.model.OrderExpress.findAll({
|
||||
where: {
|
||||
waybill_code: { [Op.like]: `%${kw}%` },
|
||||
warehouse_id: warehouseId,
|
||||
delete_at: null,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (expressRecords.length > 0) {
|
||||
const orderIds = [ ...new Set(expressRecords.map(r => r.order_id).filter(Boolean)) ];
|
||||
|
||||
if (orderIds.length > 0) {
|
||||
// 查 order_delivery 分表获取 wave_id(current + dispatch)
|
||||
const orderDeliveryFactory = ctx.model.OrderDeliveryFactory;
|
||||
const orderTableModels = [
|
||||
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
|
||||
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
|
||||
];
|
||||
const orderRecords = [];
|
||||
for (const entry of orderTableModels) {
|
||||
try {
|
||||
const model = await entry.getModel();
|
||||
if (!model) continue;
|
||||
const rows = await model.findAll({
|
||||
where: { id: { [Op.in]: orderIds }, warehouse_id: warehouseId },
|
||||
attributes: [ 'id', 'wave_id' ],
|
||||
raw: true,
|
||||
});
|
||||
orderRecords.push(...rows);
|
||||
} catch (_err) { continue; }
|
||||
}
|
||||
|
||||
// order_id → wave_id 映射
|
||||
const orderWaveMap = new Map();
|
||||
const noWaveOrderIds = [];
|
||||
orderRecords.forEach(o => {
|
||||
if (o.wave_id > 0) {
|
||||
orderWaveMap.set(o.id, o.wave_id);
|
||||
} else {
|
||||
noWaveOrderIds.push(o.id);
|
||||
}
|
||||
});
|
||||
|
||||
// 未匹配到 order_delivery 的 order_id 也按散单处理
|
||||
const matchedOrderIds = new Set(orderRecords.map(o => o.id));
|
||||
orderIds.forEach(oid => {
|
||||
if (!matchedOrderIds.has(oid)) {
|
||||
noWaveOrderIds.push(oid);
|
||||
}
|
||||
});
|
||||
|
||||
const waveIds = [ ...new Set(orderWaveMap.values()) ];
|
||||
|
||||
if (waveIds.length > 0) {
|
||||
// 查 wms_wave_batch 获取 wave_type 和 wave_no
|
||||
const waveRecords = await ctx.model.WaveBatch.findAll({
|
||||
where: { wave_id: { [Op.in]: waveIds } },
|
||||
attributes: [ 'wave_id', 'wave_no', 'wave_type' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// wave_id → { wave_no, wave_type } 映射
|
||||
const waveMap = new Map();
|
||||
waveRecords.forEach(w => {
|
||||
waveMap.set(w.wave_id, { wave_no: w.wave_no, wave_type: w.wave_type });
|
||||
});
|
||||
|
||||
// 分离:团购波次号 / 散单订单ID
|
||||
const groupBuyWaveNos = [];
|
||||
const singleOrderIds = [ ...noWaveOrderIds ];
|
||||
|
||||
orderRecords.forEach(o => {
|
||||
const waveInfo = waveMap.get(o.wave_id);
|
||||
if (waveInfo) {
|
||||
if (waveInfo.wave_type === 1) {
|
||||
// 团购 → 按波次号查 packing 表
|
||||
if (waveInfo.wave_no) {
|
||||
groupBuyWaveNos.push(waveInfo.wave_no);
|
||||
}
|
||||
} else {
|
||||
// 散单(wave_type=2) → 按 order_id 查 packing 表
|
||||
singleOrderIds.push(o.id);
|
||||
}
|
||||
} else {
|
||||
// wave_id 在 wms_wave_batch 中不存在,按散单处理
|
||||
singleOrderIds.push(o.id);
|
||||
}
|
||||
});
|
||||
|
||||
if (groupBuyWaveNos.length > 0) {
|
||||
orConditions.push({ wave_no: { [Op.in]: [ ...new Set(groupBuyWaveNos) ] } });
|
||||
}
|
||||
if (singleOrderIds.length > 0) {
|
||||
orConditions.push({ order_id: { [Op.in]: [ ...new Set(singleOrderIds) ] } });
|
||||
}
|
||||
} else {
|
||||
// 所有订单都没有波次(wave_id = 0),全部按散单处理
|
||||
orConditions.push({ order_id: { [Op.in]: orderIds } });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
queryWhere[Op.or] = orConditions;
|
||||
}
|
||||
}
|
||||
|
||||
// 开始打包时间范围
|
||||
if (where.start_time_start) {
|
||||
const startTimeStart = where.start_time_start?.value ?? where.start_time_start;
|
||||
if (startTimeStart) {
|
||||
queryWhere.start_time = { ...(queryWhere.start_time || {}), [Op.gte]: new Date(startTimeStart) };
|
||||
}
|
||||
}
|
||||
if (where.start_time_end) {
|
||||
const startTimeEnd = where.start_time_end?.value ?? where.start_time_end;
|
||||
if (startTimeEnd) {
|
||||
queryWhere.start_time = { ...(queryWhere.start_time || {}), [Op.lte]: new Date(startTimeEnd) };
|
||||
}
|
||||
}
|
||||
|
||||
// 排序
|
||||
const sortField = sort.sortField || 'create_time';
|
||||
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||||
const validSortFields = [ 'id', 'order_id', 'warehouse_id', 'workbench_id', 'wave_id', 'pack_quantity', 'pack_mode', 'status', 'start_time', 'end_time', 'create_time', 'update_time' ];
|
||||
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_time';
|
||||
|
||||
// 查询(含工作台、视频和运单关联)
|
||||
const { count, rows } = await ctx.model.PackTask.findAndCountAll({
|
||||
where: queryWhere,
|
||||
order: [[ actualSortField, sortOrder ]],
|
||||
limit: pageSize,
|
||||
offset: (page - 1) * pageSize,
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Workbench,
|
||||
as: 'workbench',
|
||||
attributes: [ 'id', 'name', 'type', 'barcode' ],
|
||||
},
|
||||
{
|
||||
model: ctx.model.PackTaskVideo,
|
||||
as: 'videos',
|
||||
attributes: [ 'id', 'video_url', 'camera_id', 'status' ],
|
||||
required: false,
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Camera,
|
||||
as: 'camera',
|
||||
attributes: [ 'id', 'custom_name', 'channel_name' ],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
model: ctx.model.OrderExpress,
|
||||
as: 'expresses',
|
||||
attributes: [ 'id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_name', 'platform_code', 'status' ],
|
||||
where: { warehouse_id: warehouseId, delete_at: null },
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// 扁平化输出
|
||||
const recordingComputerId = await this._getRecordingComputerId(warehouseId);
|
||||
const list = rows.map(row => {
|
||||
const plain = row.get({ plain: true });
|
||||
return {
|
||||
...plain,
|
||||
workbench_name: plain.workbench?.name || null,
|
||||
workbench_type: plain.workbench?.type || null,
|
||||
workbench_barcode: plain.workbench?.barcode || null,
|
||||
videos: (plain.videos || []).map(v => ({
|
||||
id: v.id,
|
||||
video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url),
|
||||
status: v.status || null,
|
||||
camera_id: v.camera_id,
|
||||
camera_name: v.camera?.custom_name || v.camera?.channel_name || null,
|
||||
})),
|
||||
expresses: (plain.expresses || []).map(e => ({
|
||||
id: e.id,
|
||||
waybill_code: e.waybill_code,
|
||||
logistics_code: e.logistics_code,
|
||||
logistics_name: e.logistics_name,
|
||||
logistics_interface_name: e.logistics_interface_name || null,
|
||||
platform_code: e.platform_code || null,
|
||||
status: e.status,
|
||||
})),
|
||||
workbench: undefined,
|
||||
};
|
||||
});
|
||||
|
||||
const totalPages = Math.ceil(count / pageSize) || 0;
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
message: 'ok',
|
||||
data: {
|
||||
list,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total: count,
|
||||
totalPages,
|
||||
hasPrevious: page > 1,
|
||||
hasNext: page < totalPages,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 打包任务详情查询。
|
||||
* 按 id + warehouse_id 查询单条打包任务记录。
|
||||
*
|
||||
* @param {Object} options 查询参数
|
||||
* @param {number} options.id 打包任务ID
|
||||
* @return {Promise<Object>} 打包任务详情
|
||||
*/
|
||||
async get(options = {}) {
|
||||
const { ctx } = this;
|
||||
const { id } = options;
|
||||
|
||||
if (!id) {
|
||||
return { code: 400, message: '打包任务ID不能为空', data: null };
|
||||
}
|
||||
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
if (!warehouseId) {
|
||||
return { code: 400, message: '用户未绑定仓库,无法查询打包任务', data: null };
|
||||
}
|
||||
|
||||
const record = await ctx.model.PackTask.findOne({
|
||||
where: { id: Number(id), warehouse_id: warehouseId },
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Workbench,
|
||||
as: 'workbench',
|
||||
attributes: [ 'id', 'name', 'type', 'barcode' ],
|
||||
},
|
||||
{
|
||||
model: ctx.model.PackTaskVideo,
|
||||
as: 'videos',
|
||||
attributes: [ 'id', 'video_url', 'camera_id', 'status' ],
|
||||
required: false,
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Camera,
|
||||
as: 'camera',
|
||||
attributes: [ 'id', 'custom_name', 'channel_name' ],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
model: ctx.model.OrderExpress,
|
||||
as: 'expresses',
|
||||
attributes: [ 'id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_name', 'platform_code', 'status' ],
|
||||
where: { warehouse_id: warehouseId, delete_at: null },
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (!record) {
|
||||
return { code: 404, message: '打包任务不存在或无权访问', data: null };
|
||||
}
|
||||
|
||||
const plain = record.get({ plain: true });
|
||||
const recordingComputerId = await this._getRecordingComputerId(warehouseId);
|
||||
const data = {
|
||||
...plain,
|
||||
workbench_name: plain.workbench?.name || null,
|
||||
workbench_type: plain.workbench?.type || null,
|
||||
workbench_barcode: plain.workbench?.barcode || null,
|
||||
videos: (plain.videos || []).map(v => ({
|
||||
id: v.id,
|
||||
video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url),
|
||||
status: v.status || null,
|
||||
camera_id: v.camera_id,
|
||||
camera_name: v.camera?.custom_name || v.camera?.channel_name || null,
|
||||
})),
|
||||
expresses: (plain.expresses || []).map(e => ({
|
||||
id: e.id,
|
||||
waybill_code: e.waybill_code,
|
||||
logistics_code: e.logistics_code,
|
||||
logistics_name: e.logistics_name,
|
||||
logistics_interface_name: e.logistics_interface_name || null,
|
||||
platform_code: e.platform_code || null,
|
||||
status: e.status,
|
||||
})),
|
||||
workbench: undefined,
|
||||
};
|
||||
|
||||
return { code: 200, message: 'ok', data };
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置打包任务结束时间。
|
||||
* 按 id + warehouse_id 查找任务,更新结束时间。
|
||||
* 若任务状态不是已完成(2),则同时将状态更新为已完成。
|
||||
*
|
||||
* @param {Object} options 操作参数
|
||||
* @param {number} options.id 打包任务ID
|
||||
* @param {string} options.end_time 结束时间(ISO 8601 或日期字符串)
|
||||
* @return {Promise<Object>} 操作结果
|
||||
*/
|
||||
async setEndTime(options = {}) {
|
||||
const { ctx } = this;
|
||||
const { id, end_time } = options;
|
||||
|
||||
if (!id) {
|
||||
return { code: 400, message: '打包任务ID不能为空', data: null };
|
||||
}
|
||||
if (!end_time) {
|
||||
return { code: 400, message: '结束时间不能为空', data: null };
|
||||
}
|
||||
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
if (!warehouseId) {
|
||||
return { code: 400, message: '用户未绑定仓库,无法操作打包任务', data: null };
|
||||
}
|
||||
|
||||
const record = await ctx.model.PackTask.findOne({
|
||||
where: { id: Number(id), warehouse_id: warehouseId },
|
||||
});
|
||||
|
||||
if (!record) {
|
||||
return { code: 404, message: '打包任务不存在或无权访问', data: null };
|
||||
}
|
||||
|
||||
const updates = { end_time: new Date(end_time) };
|
||||
|
||||
// 若任务状态不是已完成(2),同步更新为已完成
|
||||
if (record.status !== 2) {
|
||||
updates.status = 2;
|
||||
}
|
||||
|
||||
await record.update(updates);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
message: '结束时间设置成功',
|
||||
data: {
|
||||
id: record.id,
|
||||
end_time: updates.end_time,
|
||||
status: updates.status,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制重新录制打包任务视频。
|
||||
* 将任务推送到录制电脑,通过打印服务触发重新录制。
|
||||
*
|
||||
* @param {Object} options 操作参数
|
||||
* @param {number} options.id 打包任务ID
|
||||
* @return {Promise<Object>} 操作结果 { code, message, data }
|
||||
*/
|
||||
async forceRecord(options = {}) {
|
||||
const { ctx } = this;
|
||||
const { id } = options;
|
||||
|
||||
if (!id) {
|
||||
return { code: 400, message: '打包任务ID不能为空', data: null };
|
||||
}
|
||||
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
if (!warehouseId) {
|
||||
return { code: 400, message: '用户未绑定仓库,无法操作打包任务', data: null };
|
||||
}
|
||||
|
||||
// 1. 查找打包任务
|
||||
const packTask = await ctx.model.PackTask.findOne({
|
||||
where: { id: Number(id), warehouse_id: warehouseId },
|
||||
});
|
||||
if (!packTask) {
|
||||
return { code: 404, message: '打包任务不存在或无权访问', data: null };
|
||||
}
|
||||
|
||||
// 2. 查找仓库的录制电脑
|
||||
const recordingComputer = await ctx.model.PrintComputer.findOne({
|
||||
where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null },
|
||||
raw: true,
|
||||
});
|
||||
if (!recordingComputer) {
|
||||
return { code: 400, message: '该仓库无录制电脑,无法强制录制', data: null };
|
||||
}
|
||||
|
||||
// 3. 检查录制电脑是否在线
|
||||
const redisPrinter = ctx.app.redis.get('printer');
|
||||
const onlineKey = `warehouse:${warehouseId}:printer:${recordingComputer.id}`;
|
||||
const onlineInfo = await redisPrinter.get(onlineKey);
|
||||
if (!onlineInfo) {
|
||||
return { code: 400, message: '该仓库录制电脑不在线,无法强制录制', data: null };
|
||||
}
|
||||
|
||||
// 4. 重置视频记录状态为 created,触发重新录制
|
||||
await ctx.model.PackTaskVideo.update(
|
||||
{ status: 'created', video_url: '' },
|
||||
{ where: { pack_task_id: Number(id), deleted_at: null } }
|
||||
);
|
||||
|
||||
// 5. 通知打印服务推送强制录制任务
|
||||
const printServiceUrl = ctx.app.config.printService.url;
|
||||
try {
|
||||
await ctx.curl(`${printServiceUrl}/record/force`, {
|
||||
method: 'POST',
|
||||
contentType: 'json',
|
||||
data: {
|
||||
pack_task_id: Number(id),
|
||||
warehouse_id: warehouseId,
|
||||
computer_id: recordingComputer.id,
|
||||
camera_ids: packTask.device_ids || [],
|
||||
},
|
||||
dataType: 'json',
|
||||
timeout: 10000,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`通知打印服务强制录制 pack_task_id=${id} 失败: ${err.message}`);
|
||||
return { code: 500, message: `通知打印服务失败: ${err.message}`, data: null };
|
||||
}
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
message: '强制录制任务已推送',
|
||||
data: {
|
||||
pack_task_id: Number(id),
|
||||
computer_id: recordingComputer.id,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OrderPackingService;
|
||||
@ -179,9 +179,9 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
* 同时从 wms_stock_barcodes 表批量查询每个 stock_id 对应的全部条码,
|
||||
* 注入到打印项的 barcodes 数组中,供 resolveItemBarcodeText 优先读取。
|
||||
*
|
||||
* stock_id 优先读取 wms_picking.stock_id(20260708 新增列),
|
||||
* 兜底读取 wms_order_items.stock_id / item_snapshot.stock_id,
|
||||
* 消除对 order_items 明细表的强依赖,使配送表订单打印链路也能正常获取商品信息。
|
||||
* 商品信息(item_name / barcode / stock_id / quantity)全部从 wms_picking
|
||||
* 直读,不再反查 order_items 表,彻底消除因订单迁移导致 order_item_id
|
||||
* 错配的风险。
|
||||
*
|
||||
* @param {Array<Object>} orderRows 订单列表。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
@ -223,35 +223,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
const orderItemIds = Array.from(new Set(normalizedPickingRows
|
||||
.map(row => Number(row && row.order_item_id || 0))
|
||||
.filter(orderItemId => Number.isInteger(orderItemId) && orderItemId > 0)));
|
||||
|
||||
const orderItemModelFactory = this.ctx.model && this.ctx.model.OrderItemsFactory;
|
||||
const orderItemModel = orderItemModelFactory && typeof orderItemModelFactory.getCurrentModel === 'function'
|
||||
? await orderItemModelFactory.getCurrentModel(warehouseId)
|
||||
: null;
|
||||
|
||||
const orderItemRows = orderItemModel && typeof orderItemModel.findAll === 'function' && orderItemIds.length > 0
|
||||
? await orderItemModel.findAll({
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: orderItemIds,
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot', 'stock_id' ],
|
||||
raw: true,
|
||||
})
|
||||
: [];
|
||||
|
||||
const orderItemMap = new Map();
|
||||
for (const row of Array.isArray(orderItemRows) ? orderItemRows : []) {
|
||||
const orderItemId = Number(row && row.id || 0);
|
||||
if (orderItemId > 0) {
|
||||
orderItemMap.set(orderItemId, row);
|
||||
}
|
||||
}
|
||||
|
||||
// 库位兜底:space_name 为空时通过 space_id 补查 location_space 表
|
||||
const locationFallbackSpaceIds = Array.from(new Set(normalizedPickingRows
|
||||
.filter(row => !String(row && row.space_name || '').trim())
|
||||
.map(row => Number(row && row.space_id || 0))
|
||||
@ -274,6 +246,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
const locationMap = new Map((Array.isArray(locationRows) ? locationRows : [])
|
||||
.map(row => [ Number(row && row.id || 0), row ]));
|
||||
|
||||
// 按 order_id 分组 picking 行
|
||||
const pickingRowsByOrderId = new Map();
|
||||
for (const row of normalizedPickingRows) {
|
||||
const orderId = Number(row && row.order_id || 0);
|
||||
@ -286,29 +259,17 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
pickingRowsByOrderId.set(orderId, list);
|
||||
}
|
||||
|
||||
// 阶段一:收集 stock_id(优先 picking.stock_id,兜底 order_items.stock_id)
|
||||
// 阶段一:从 picking.stock_id 收集所有 stock_id
|
||||
const allStockIds = new Set();
|
||||
|
||||
// 1a) 从 wms_picking 直接收集 stock_id(新增路径,绕过 order_items 明细表)
|
||||
for (const row of normalizedPickingRows) {
|
||||
const stockId = Number(row && row.stock_id || 0);
|
||||
if (stockId > 0) {
|
||||
allStockIds.add(stockId);
|
||||
}
|
||||
}
|
||||
|
||||
// 1b) 从 order_items 兜底收集 stock_id(兼容 picking.stock_id 为 NULL 的旧数据)
|
||||
for (const row of Array.isArray(orderItemRows) ? orderItemRows : []) {
|
||||
const itemSnapshot = this.normalizeItemSnapshot(row.item_snapshot);
|
||||
const stockId = Number(row.stock_id || itemSnapshot.stock_id || 0);
|
||||
if (stockId > 0) {
|
||||
allStockIds.add(stockId);
|
||||
}
|
||||
}
|
||||
|
||||
const uniqueStockIds = Array.from(allStockIds);
|
||||
|
||||
// 阶段二:批量查询 wms_stock_warehouse 获取商品编码与名称(新增直读路径)
|
||||
// 阶段二:批量查询 wms_stock_warehouse 获取商品编码与名称
|
||||
const stockWarehouseMap = new Map();
|
||||
if (uniqueStockIds.length > 0) {
|
||||
const stockWarehouseModel = this.ctx.model && this.ctx.model.StockWarehouse;
|
||||
@ -327,7 +288,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
}
|
||||
}
|
||||
|
||||
// 阶段三:构建所有打印项(使用 stock_warehouse 直读数据)
|
||||
// 阶段三:构建所有打印项(全部从 picking + stock_warehouse 直取)
|
||||
const printItemsByOrderId = new Map();
|
||||
|
||||
for (const orderRow of rows) {
|
||||
@ -338,9 +299,8 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
}
|
||||
|
||||
const printItems = pickingList.map(pickingRow => {
|
||||
const orderItemId = Number(pickingRow && pickingRow.order_item_id || 0);
|
||||
const orderItemRow = orderItemMap.get(orderItemId) || {};
|
||||
const itemSnapshot = this.normalizeItemSnapshot(orderItemRow.item_snapshot);
|
||||
const stockId = Number(pickingRow && pickingRow.stock_id || 0);
|
||||
const stockInfo = stockId > 0 ? stockWarehouseMap.get(stockId) : null;
|
||||
const locationRow = locationMap.get(Number(pickingRow && pickingRow.space_id || 0)) || {};
|
||||
const pickLocation = this.getFirstNonEmptyFieldText({
|
||||
space_name: pickingRow && pickingRow.space_name,
|
||||
@ -349,40 +309,12 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
custom_barcode: locationRow.custom_barcode,
|
||||
}, [ 'space_name', 'space_code', 'custom_name', 'custom_barcode' ]);
|
||||
|
||||
// stock_id 优先级:picking.stock_id > order_items.stock_id > item_snapshot.stock_id
|
||||
const pickingStockId = Number(pickingRow && pickingRow.stock_id || 0);
|
||||
const orderItemStockId = Number(orderItemRow.stock_id || itemSnapshot.stock_id || 0);
|
||||
const stockId = pickingStockId > 0 ? pickingStockId : orderItemStockId;
|
||||
|
||||
// 从 stock_warehouse 直读商品编码与名称(新增路径,绕过 order_items)
|
||||
const stockInfo = stockId > 0 ? stockWarehouseMap.get(stockId) : null;
|
||||
|
||||
// item_name 优先级:stock_warehouse > order_items > item_snapshot
|
||||
const itemName = this.getFirstNonEmptyFieldText({
|
||||
stock_item_name: stockInfo && stockInfo.item_name,
|
||||
snapshot_item_name: itemSnapshot.item_name,
|
||||
snapshot_name: itemSnapshot.name,
|
||||
snapshot_title: itemSnapshot.title,
|
||||
item_name: orderItemRow.item_name,
|
||||
}, [ 'stock_item_name', 'snapshot_item_name', 'snapshot_name', 'snapshot_title', 'item_name' ]);
|
||||
|
||||
// barcode 优先级:stock_warehouse.item_code > item_snapshot > order_items.item_code
|
||||
const barcode = this.getFirstNonEmptyFieldText({
|
||||
stock_item_code: stockInfo && stockInfo.item_code,
|
||||
barcode: itemSnapshot.barcode,
|
||||
item_barcode: itemSnapshot.item_barcode,
|
||||
bar_code: itemSnapshot.bar_code,
|
||||
item_code: orderItemRow.item_code,
|
||||
sku_code: itemSnapshot.sku_code,
|
||||
sku: itemSnapshot.sku,
|
||||
}, [ 'stock_item_code', 'barcode', 'item_barcode', 'bar_code', 'item_code', 'sku_code', 'sku' ]);
|
||||
|
||||
const quantity = Number(pickingRow && pickingRow.quantity || orderItemRow.plan_qty || 0);
|
||||
const quantity = Number(pickingRow && pickingRow.quantity || 0);
|
||||
|
||||
return {
|
||||
order_item_id: orderItemId,
|
||||
item_name: itemName,
|
||||
barcode,
|
||||
order_item_id: Number(pickingRow && pickingRow.order_item_id || 0),
|
||||
item_name: stockInfo ? String(stockInfo.item_name || '').trim() : '',
|
||||
barcode: stockInfo ? String(stockInfo.item_code || '').trim() : '',
|
||||
quantity: quantity > 0 ? quantity : 0,
|
||||
pick_location: pickLocation,
|
||||
stock_id: stockId > 0 ? stockId : undefined,
|
||||
@ -681,7 +613,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
const orderIds = unlockedOrderRows
|
||||
.map(row => Number(row && row.id || 0))
|
||||
.filter(orderId => Number.isInteger(orderId) && orderId > 0);
|
||||
const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIds);
|
||||
const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIds, normalizedWarehouseId);
|
||||
this.assertBusinessWaybillCompleteness(orderIds, orderExpressRows);
|
||||
const cainiaoEnrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows(
|
||||
unlockedOrderRows,
|
||||
@ -856,7 +788,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
const orderIdsForExpress = validOrderRows
|
||||
.map(row => Number(row && row.id || 0))
|
||||
.filter(orderId => Number.isInteger(orderId) && orderId > 0);
|
||||
const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIdsForExpress);
|
||||
const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIdsForExpress, normalizedWarehouseId);
|
||||
this.assertBusinessWaybillCompleteness(orderIdsForExpress, orderExpressRows);
|
||||
const cainiaoEnrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows(
|
||||
validOrderRows,
|
||||
@ -1599,7 +1531,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
* logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、
|
||||
* warehouse_id、printinfo、signature、encryptprintinfo、ver。
|
||||
*/
|
||||
async queryOrderExpressByOrderIds(orderIds = []) {
|
||||
async queryOrderExpressByOrderIds(orderIds = [], warehouseId) {
|
||||
if (!Array.isArray(orderIds) || orderIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
@ -1632,6 +1564,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
order_id: {
|
||||
[Op.in]: normalizedOrderIds,
|
||||
},
|
||||
warehouse_id: warehouseId,
|
||||
business_key: 1,
|
||||
},
|
||||
order: [[ 'order_id', 'ASC' ], [ 'business_key', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
|
||||
@ -1187,6 +1187,7 @@ class OrderStorageAllocationService extends MainService {
|
||||
order_item_id: toNumber(orderItem.id, 0),
|
||||
warehouse_id: warehouseId,
|
||||
storage_id: storageRow.id,
|
||||
stock_id: toNumber(storageRow.stock_id, 0) || null,
|
||||
quantity: allocationQuantity,
|
||||
space_id: toNumber(storageRow.space_id, 0) || null,
|
||||
space_name: String(storageRow.space_name || '').trim(),
|
||||
@ -1656,6 +1657,10 @@ class OrderStorageAllocationService extends MainService {
|
||||
sync_status: {
|
||||
[ctx.app.Sequelize.Op.notIn]: [ 'fin' ],
|
||||
},
|
||||
// 排除已取消的订单,防止已取消订单被回传
|
||||
status: {
|
||||
[ctx.app.Sequelize.Op.notIn]: [ 'cancel' ],
|
||||
},
|
||||
},
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
|
||||
@ -137,7 +137,7 @@ class PickSystemService extends Service {
|
||||
[this.app.Sequelize.Op.in]: orderItemIds,
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'item_code', 'item_name', 'stock_id', 'plan_qty', 'item_snapshot' ],
|
||||
attributes: [ 'id', 'item_code', 'item_name', 'stock_id', 'plan_qty', 'item_snapshot', 'owner_code' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
@ -323,6 +323,10 @@ class PickSystemService extends Service {
|
||||
total_qty: 0,
|
||||
box_allocations: [],
|
||||
details: [],
|
||||
store_id: detail.store_id != null ? Number(detail.store_id) : 0,
|
||||
owner_code: String(detail.owner_code || '').trim(),
|
||||
store_remark: String(detail.store_remark || '').trim(),
|
||||
stock: detail.stock || null,
|
||||
});
|
||||
}
|
||||
const groupItem = groupMap.get(groupKey);
|
||||
@ -495,6 +499,9 @@ class PickSystemService extends Service {
|
||||
stock_id: Number(groupItem && groupItem.stock_id || 0),
|
||||
total_qty: Number(groupItem && groupItem.total_qty || 0),
|
||||
box_allocations: boxAllocations,
|
||||
store_id: groupItem.store_id != null ? Number(groupItem.store_id) : 0,
|
||||
owner_code: String(groupItem.owner_code || '').trim(),
|
||||
store_remark: String(groupItem.store_remark || '').trim(),
|
||||
};
|
||||
});
|
||||
|
||||
@ -1196,6 +1203,36 @@ class PickSystemService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 批量查询货主备注名(wms_store_warehouse.store_remask),按 store_id 映射
|
||||
const storeRemarkMap = new Map();
|
||||
if (stockDetailMap.size > 0 && ctx.model && ctx.model.StoreWarehouse) {
|
||||
const storeIdsForRemark = [ ...new Set(
|
||||
[ ...stockDetailMap.values() ]
|
||||
.map(detail => Number(detail.store_id || 0))
|
||||
.filter(id => id > 0)
|
||||
) ];
|
||||
if (storeIdsForRemark.length > 0) {
|
||||
try {
|
||||
const swRows = await ctx.model.StoreWarehouse.findAll({
|
||||
where: {
|
||||
store_id: { [this.app.Sequelize.Op.in]: storeIdsForRemark },
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const sw of (Array.isArray(swRows) ? swRows : [])) {
|
||||
const sid = Number(sw.store_id || 0);
|
||||
if (sid > 0 && !storeRemarkMap.has(sid)) {
|
||||
storeRemarkMap.set(sid, String(sw.store_remask || '').trim());
|
||||
}
|
||||
}
|
||||
} catch (remarkError) {
|
||||
ctx.logger.warn(`[pick.wavePickTaskDetail] 查询货主备注失败: ${remarkError.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedBoxRows = Array.isArray(boxRows) ? boxRows : [];
|
||||
const boxMapByNo = new Map(normalizedBoxRows
|
||||
.map(row => [ Number(row && row.box_no || 0), row ])
|
||||
@ -1221,7 +1258,17 @@ class PickSystemService extends Service {
|
||||
stock_unit: String(itemSnapshot.stock_unit || '').trim(),
|
||||
barcodes: [],
|
||||
image_url: [],
|
||||
store_id: 0,
|
||||
};
|
||||
// 确保 owner_code 在 stock 对象上(getStockDetails 不含此字段,需从 order_items 补)
|
||||
if (!stock.owner_code) {
|
||||
stock.owner_code = String(orderItemRow.owner_code || '').trim();
|
||||
}
|
||||
// 确保 store_remark 在 stock 对象上(getStockDetails 不含此字段,需从 wms_store_warehouse 补)
|
||||
const stockStoreId = stock.store_id != null ? Number(stock.store_id) : 0;
|
||||
if (!stock.store_remark) {
|
||||
stock.store_remark = storeRemarkMap.get(stockStoreId) || '';
|
||||
}
|
||||
|
||||
return {
|
||||
order_id: Number(row && row.order_id || 0),
|
||||
@ -1243,6 +1290,9 @@ class PickSystemService extends Service {
|
||||
stock_id: stockId,
|
||||
plan_qty: Number(orderItemRow.plan_qty || 0),
|
||||
item_snapshot: orderItemRow.item_snapshot || null,
|
||||
store_id: stockStoreId,
|
||||
owner_code: String(stock.owner_code || '').trim(),
|
||||
store_remark: String(stock.store_remark || '').trim(),
|
||||
stock,
|
||||
};
|
||||
});
|
||||
|
||||
319
app/service/systems/printComputer.js
Normal file
319
app/service/systems/printComputer.js
Normal file
@ -0,0 +1,319 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
class PrintComputerService extends Service {
|
||||
/**
|
||||
* 通知打印服务刷新电脑信息并推送给客户端。
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @param {number} computerId 电脑ID
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async notifyRefreshInfo(warehouseId, computerId) {
|
||||
const printServiceUrl = this.ctx.app.config.printService.url;
|
||||
try {
|
||||
await this.ctx.curl(`${printServiceUrl}/auth/refreshInfo`, {
|
||||
method: 'POST',
|
||||
contentType: 'json',
|
||||
data: { warehouse: warehouseId, computerId },
|
||||
dataType: 'json',
|
||||
});
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn(`通知打印服务刷新电脑 ${computerId} 信息失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印电脑列表(仓库隔离,分页+筛选)。
|
||||
* @param {Object} params 查询参数
|
||||
* @param {Object} [params.pagination] 分页 { page, pageSize }
|
||||
* @param {Object} [params.where] 筛选 { is_recording, is_online }
|
||||
* @return {Promise<Object>} { list, pagination }
|
||||
*/
|
||||
async list(params = {}) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = ctx.user.store_id;
|
||||
const { pagination = {}, where = {} } = params;
|
||||
|
||||
const page = Math.max(1, parseInt(pagination.page) || 1);
|
||||
const pageSize = Math.min(200, Math.max(1, parseInt(pagination.pageSize) || 20));
|
||||
|
||||
const queryWhere = {
|
||||
warehouse_id: warehouseId,
|
||||
deleted_at: null,
|
||||
};
|
||||
|
||||
// DB 层筛选:is_recording
|
||||
if (where.is_recording !== undefined && where.is_recording !== null && where.is_recording !== '') {
|
||||
queryWhere.is_recording = parseInt(where.is_recording) === 1;
|
||||
}
|
||||
|
||||
// is_online 筛选参数
|
||||
const filterOnline = where.is_online !== undefined && where.is_online !== null && where.is_online !== '';
|
||||
const onlineValue = filterOnline ? parseInt(where.is_online) : null;
|
||||
|
||||
const redisPrinter = ctx.app.redis.get('printer');
|
||||
|
||||
if (filterOnline) {
|
||||
// 有在线状态筛选:先查全量 DB,Redis 标注后内存过滤再分页
|
||||
const allRows = await ctx.model.PrintComputer.findAll({
|
||||
where: queryWhere,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// Redis 标注在线状态
|
||||
const enriched = await Promise.all(allRows.map(async row => {
|
||||
const onlineKey = `warehouse:${warehouseId}:printer:${row.id}`;
|
||||
const onlineInfo = await redisPrinter.get(onlineKey);
|
||||
row.is_online = onlineInfo ? 1 : 0;
|
||||
return row;
|
||||
}));
|
||||
|
||||
// 内存过滤
|
||||
const filtered = enriched.filter(row => row.is_online === onlineValue);
|
||||
const total = filtered.length;
|
||||
const list = filtered.slice((page - 1) * pageSize, page * pageSize);
|
||||
|
||||
return {
|
||||
list,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalPages: Math.ceil(total / pageSize),
|
||||
hasPrevious: page > 1,
|
||||
hasNext: page * pageSize < total,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 无在线状态筛选:DB 分页查询
|
||||
const { count, rows } = await ctx.model.PrintComputer.findAndCountAll({
|
||||
where: queryWhere,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
});
|
||||
|
||||
// 从 Redis 读取在线状态并附加到每条记录
|
||||
const list = await Promise.all(rows.map(async row => {
|
||||
const plain = row.get ? row.get({ plain: true }) : row;
|
||||
const onlineKey = `warehouse:${warehouseId}:printer:${plain.id}`;
|
||||
const onlineInfo = await redisPrinter.get(onlineKey);
|
||||
plain.is_online = onlineInfo ? 1 : 0;
|
||||
return plain;
|
||||
}));
|
||||
|
||||
return {
|
||||
list,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total: count,
|
||||
totalPages: Math.ceil(count / pageSize),
|
||||
hasPrevious: page > 1,
|
||||
hasNext: page * pageSize < count,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新打印电脑。
|
||||
* @param {number} id 电脑ID
|
||||
* @param {Object} data 要更新的字段 { name }
|
||||
* @return {Promise<Object>} 更新后的记录
|
||||
*/
|
||||
async update(id, data) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = ctx.user.store_id;
|
||||
|
||||
const record = await ctx.model.PrintComputer.findOne({
|
||||
where: { id, warehouse_id: warehouseId, deleted_at: null },
|
||||
});
|
||||
if (!record) throw new Error('打印电脑不存在或无权操作');
|
||||
|
||||
const fields = {};
|
||||
if (data.name !== undefined) {
|
||||
const name = String(data.name).trim();
|
||||
if (!name) throw new Error('电脑名称不能为空');
|
||||
fields.name = name;
|
||||
}
|
||||
|
||||
if (Object.keys(fields).length === 0) throw new Error('没有需要更新的字段');
|
||||
|
||||
await record.update(fields);
|
||||
|
||||
// 通知打印服务推送最新信息给客户端
|
||||
await this.notifyRefreshInfo(warehouseId, id);
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置录制电脑。
|
||||
* 会将同仓库下其他已设为录制的电脑取消,再设置当前电脑为录制。
|
||||
* @param {number} id 电脑ID
|
||||
* @param {Object} data { recording_size_value, recording_size_unit, remote_play_url, recording_directory }
|
||||
* @return {Promise<Object>} 更新后的记录
|
||||
*/
|
||||
async setRecording(id, data) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = ctx.user.store_id;
|
||||
|
||||
// 参数校验
|
||||
if (data.recording_size_value === undefined || data.recording_size_value === null) {
|
||||
throw new Error('录制大小不能为空');
|
||||
}
|
||||
const sizeValue = parseInt(data.recording_size_value);
|
||||
if (!Number.isInteger(sizeValue) || sizeValue <= 0) {
|
||||
throw new Error('录制大小必须为正整数');
|
||||
}
|
||||
|
||||
const VALID_UNITS = [ 'KB', 'MB', 'GB', 'TB' ];
|
||||
const unit = String(data.recording_size_unit || '').trim().toUpperCase();
|
||||
if (!VALID_UNITS.includes(unit)) {
|
||||
throw new Error(`存储单位不合法,支持:${VALID_UNITS.join('/')}`);
|
||||
}
|
||||
|
||||
const url = String(data.remote_play_url || '').trim();
|
||||
if (!/^https?:\/\/.+/.test(url)) {
|
||||
throw new Error('远程播放地址必须以 http:// 或 https:// 开头');
|
||||
}
|
||||
|
||||
const directory = String(data.recording_directory || '').trim();
|
||||
if (!directory) {
|
||||
throw new Error('录制目录不能为空');
|
||||
}
|
||||
|
||||
// 校验目标电脑存在
|
||||
const record = await ctx.model.PrintComputer.findOne({
|
||||
where: { id, warehouse_id: warehouseId, deleted_at: null },
|
||||
});
|
||||
if (!record) throw new Error('打印电脑不存在或无权操作');
|
||||
|
||||
// 先将同仓库下其他已设为录制的电脑取消
|
||||
const [ affectedCount ] = await ctx.model.PrintComputer.update(
|
||||
{
|
||||
is_recording: false,
|
||||
recording_size_value: null,
|
||||
recording_size_unit: null,
|
||||
remote_play_url: null,
|
||||
recording_directory: null,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
is_recording: true,
|
||||
deleted_at: null,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// 设置当前电脑为录制
|
||||
await record.update({
|
||||
is_recording: true,
|
||||
recording_size_value: sizeValue,
|
||||
recording_size_unit: unit,
|
||||
remote_play_url: url,
|
||||
recording_directory: directory,
|
||||
});
|
||||
|
||||
// 通知打印服务推送最新信息:当前电脑 + 被取消的其他电脑
|
||||
await this.notifyRefreshInfo(warehouseId, id);
|
||||
// 查询被取消的其他电脑ID并逐一通知
|
||||
if (affectedCount > 0) {
|
||||
const cancelledComputers = await ctx.model.PrintComputer.findAll({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
is_recording: false,
|
||||
deleted_at: null,
|
||||
id: { [ctx.app.Sequelize.Op.ne]: id },
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
limit: affectedCount,
|
||||
});
|
||||
for (const comp of cancelledComputers) {
|
||||
await this.notifyRefreshInfo(warehouseId, comp.id);
|
||||
}
|
||||
}
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消录制电脑。
|
||||
* @param {number} id 电脑ID
|
||||
* @return {Promise<Object>} 更新后的记录
|
||||
*/
|
||||
async cancelRecording(id) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = ctx.user.store_id;
|
||||
|
||||
const record = await ctx.model.PrintComputer.findOne({
|
||||
where: { id, warehouse_id: warehouseId, deleted_at: null },
|
||||
});
|
||||
if (!record) throw new Error('打印电脑不存在或无权操作');
|
||||
|
||||
await record.update({
|
||||
is_recording: false,
|
||||
recording_size_value: null,
|
||||
recording_size_unit: null,
|
||||
remote_play_url: null,
|
||||
recording_directory: null,
|
||||
});
|
||||
|
||||
// 通知打印服务推送最新信息给客户端
|
||||
await this.notifyRefreshInfo(warehouseId, id);
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
/**
|
||||
* 软删除打印电脑。
|
||||
* 若存在未删除的关联打印台,则拒绝删除。
|
||||
* @param {number} id 电脑ID
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async delete(id) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = ctx.user.store_id;
|
||||
|
||||
const record = await ctx.model.PrintComputer.findOne({
|
||||
where: { id, warehouse_id: warehouseId, deleted_at: null },
|
||||
});
|
||||
if (!record) throw new Error('打印电脑不存在或无权操作');
|
||||
|
||||
// 检查是否有关联的未删除打印台
|
||||
const stationCount = await ctx.model.PrintStations.count({
|
||||
where: {
|
||||
computer_id: id,
|
||||
warehouse_id: warehouseId,
|
||||
deleted_at: null,
|
||||
},
|
||||
});
|
||||
|
||||
if (stationCount > 0) {
|
||||
throw new Error(`该电脑下存在 ${stationCount} 个未删除的打印台,请先删除打印台后再删除电脑`);
|
||||
}
|
||||
|
||||
await record.update({ deleted_at: new Date() });
|
||||
|
||||
// 通知打印服务注销电脑连接
|
||||
const printServiceUrl = ctx.app.config.printService.url;
|
||||
try {
|
||||
await ctx.curl(`${printServiceUrl}/auth/logout`, {
|
||||
method: 'POST',
|
||||
contentType: 'json',
|
||||
data: { warehouse: warehouseId, computerId: id },
|
||||
dataType: 'json',
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.warn(`通知打印服务注销电脑 ${id} 失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PrintComputerService;
|
||||
@ -307,6 +307,9 @@ class SettingExpressInterfaceService extends Service {
|
||||
shop_name: {
|
||||
field: 'shop_name',
|
||||
},
|
||||
is_enabled: {
|
||||
field: 'is_enabled',
|
||||
},
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
@ -366,12 +369,16 @@ class SettingExpressInterfaceService extends Service {
|
||||
includes[0].attributes = [ 'code', 'name' ];
|
||||
}
|
||||
|
||||
if (full && ctx.model && ctx.model.Shop) {
|
||||
includes.push({
|
||||
if (ctx.model && ctx.model.Shop) {
|
||||
const shopInclude = {
|
||||
model: ctx.model.Shop,
|
||||
as: 'shop',
|
||||
required: false,
|
||||
});
|
||||
};
|
||||
if (!full) {
|
||||
shopInclude.attributes = [ 'id', 'shop_name' ];
|
||||
}
|
||||
includes.push(shopInclude);
|
||||
}
|
||||
|
||||
return includes;
|
||||
@ -742,6 +749,7 @@ class SettingExpressInterfaceService extends Service {
|
||||
weight_type: row.weight_type === undefined || row.weight_type === null ? null : Number(row.weight_type),
|
||||
viewer: this.normalizeOptionalText(row.viewer, 'viewer', 50),
|
||||
client_id: this.normalizeOptionalText(row.client_id, 'client_id', 50),
|
||||
is_enabled: row.is_enabled === undefined || row.is_enabled === null ? null : Number(row.is_enabled),
|
||||
is_share: row.is_share === undefined || row.is_share === null ? null : Number(row.is_share),
|
||||
ispickup: row.ispickup === undefined || row.ispickup === null ? null : Number(row.ispickup),
|
||||
shipperno: this.normalizeOptionalText(row.shipperno, 'shipperno', 255),
|
||||
@ -754,7 +762,11 @@ class SettingExpressInterfaceService extends Service {
|
||||
town_name: this.normalizeOptionalText(row.town_name, 'town_name', 255),
|
||||
site_code: this.normalizeOptionalText(row.site_code, 'site_code', 255),
|
||||
product_type: this.normalizeOptionalText(row.product_type, 'product_type', 50),
|
||||
shop_name: this.normalizeOptionalText(row.shop_name, 'shop_name', 255),
|
||||
shop_name: this.normalizeOptionalText(
|
||||
(row.shop && row.shop.shop_name) || row.shop_name,
|
||||
'shop_name',
|
||||
255
|
||||
),
|
||||
express,
|
||||
express_name: express ? express.name : null,
|
||||
express_polyapi_extra_info: express ? express.polyapi_extra_info : null,
|
||||
@ -1075,7 +1087,7 @@ class SettingExpressInterfaceService extends Service {
|
||||
'sys_express_code',
|
||||
'sender_name', 'sender_tel', 'weight', 'viewer', 'client_id', 'is_share',
|
||||
'province_name', 'city_name', 'district_name', 'site_code',
|
||||
'product_type', 'weight_type', 'shop_name', 'address', 'town_name', 'ispickup', 'shipperno', 'template_url', 'ext_data',
|
||||
'product_type', 'weight_type', 'shop_name', 'address', 'town_name', 'ispickup', 'shipperno', 'template_url', 'ext_data', 'is_enabled',
|
||||
],
|
||||
order: [[ 'weight', 'ASC' ], [ 'id', 'DESC' ]],
|
||||
offset,
|
||||
@ -1353,6 +1365,8 @@ class SettingExpressInterfaceService extends Service {
|
||||
|| Object.prototype.hasOwnProperty.call(data, 'shopName');
|
||||
const hasExtData = Object.prototype.hasOwnProperty.call(data, 'ext_data')
|
||||
|| Object.prototype.hasOwnProperty.call(data, 'extData');
|
||||
const hasIsEnabled = Object.prototype.hasOwnProperty.call(data, 'is_enabled')
|
||||
|| Object.prototype.hasOwnProperty.call(data, 'isEnabled');
|
||||
|
||||
if (!hasName && !hasExpressCode && !hasPlatformCode && !hasSysExpressCode
|
||||
&& !hasSenderName && !hasSenderTel && !hasWeight && !hasWeightType
|
||||
@ -1360,7 +1374,7 @@ class SettingExpressInterfaceService extends Service {
|
||||
&& !hasProviderType && !hasProviderId && !hasViewer && !hasClientId && !hasIsPickup
|
||||
&& !hasShipperNo && !hasTemplateUrl && !hasProvinceName && !hasCityName
|
||||
&& !hasDistrictName && !hasAddress && !hasTownName && !hasSiteCode
|
||||
&& !hasProductType && !hasShopName && !hasExtData) {
|
||||
&& !hasProductType && !hasShopName && !hasExtData && !hasIsEnabled) {
|
||||
throw this.createError('至少需要提供一个可更新字段', 400);
|
||||
}
|
||||
|
||||
@ -1556,6 +1570,14 @@ class SettingExpressInterfaceService extends Service {
|
||||
);
|
||||
}
|
||||
|
||||
if (hasIsEnabled) {
|
||||
updates.is_enabled = this.normalizeFlag(
|
||||
data.is_enabled !== undefined ? data.is_enabled : data.isEnabled,
|
||||
'is_enabled',
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
if (hasExpressCode || hasPlatformCode || hasSysExpressCode) {
|
||||
updates.sys_express_code = await this.resolveSysExpressCode({
|
||||
expressCode: nextExpressCode,
|
||||
|
||||
@ -373,8 +373,10 @@ class ShopsService extends Service {
|
||||
const where = {
|
||||
warehouse_id: warehouseId,
|
||||
platform_code: platformCode,
|
||||
shop_name: shopName,
|
||||
...buildNotDeletedShopWhere(app),
|
||||
shop_name: {
|
||||
[Op.eq]: shopName,
|
||||
[Op.notLike]: `${DELETED_SHOP_NAME_PREFIX}%`,
|
||||
},
|
||||
};
|
||||
|
||||
if (excludeId !== null) {
|
||||
@ -537,9 +539,11 @@ class ShopsService extends Service {
|
||||
|| Object.prototype.hasOwnProperty.call(data, 'platformCode');
|
||||
const hasCustomName = Object.prototype.hasOwnProperty.call(data, 'custom_name')
|
||||
|| Object.prototype.hasOwnProperty.call(data, 'customName');
|
||||
const hasShopName = Object.prototype.hasOwnProperty.call(data, 'shop_name')
|
||||
|| Object.prototype.hasOwnProperty.call(data, 'shopName');
|
||||
|
||||
if (!hasPlatformCode && !hasCustomName) {
|
||||
throw this.createError('仅允许修改 platform_code 或 custom_name', 400);
|
||||
if (!hasPlatformCode && !hasCustomName && !hasShopName) {
|
||||
throw this.createError('仅允许修改 platform_code、custom_name 或 shop_name', 400);
|
||||
}
|
||||
|
||||
if (hasPlatformCode) {
|
||||
@ -556,8 +560,16 @@ class ShopsService extends Service {
|
||||
);
|
||||
}
|
||||
|
||||
if (hasShopName) {
|
||||
updates.shop_name = this.normalizeText(
|
||||
data.shop_name !== undefined ? data.shop_name : data.shopName,
|
||||
'shop_name',
|
||||
{ required: true, maxLength: 100 }
|
||||
);
|
||||
}
|
||||
|
||||
const nextPlatformCode = updates.platform_code || shop.platform_code;
|
||||
const nextShopName = shop.shop_name;
|
||||
const nextShopName = updates.shop_name || shop.shop_name;
|
||||
|
||||
await this.ensureShopNameUnique({
|
||||
warehouseId: this.getCurrentWarehouseId(),
|
||||
@ -697,16 +709,22 @@ class ShopsService extends Service {
|
||||
attributes: [ 'get_auth_platform_name' ],
|
||||
});
|
||||
|
||||
const platName = printPlatform ? printPlatform.get_auth_platform_name : platformCode;
|
||||
const requestData = {
|
||||
RedirectCodeUrl: callbackUrl,
|
||||
command: 'saveShop',
|
||||
platName,
|
||||
shopName: shopPlain.shop_name,
|
||||
};
|
||||
if (platName === '电商京东') {
|
||||
requestData.VenderID = shopPlain.id;
|
||||
}
|
||||
|
||||
const respone = await ctx.curl(authUrl, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 5000,
|
||||
data: {
|
||||
RedirectCodeUrl: callbackUrl,
|
||||
command: 'saveShop',
|
||||
platName: printPlatform ? printPlatform.get_auth_platform_name : platformCode,
|
||||
shopName: shopPlain.shop_name,
|
||||
},
|
||||
data: requestData,
|
||||
});
|
||||
if (respone.data && respone.data.code === 0) {
|
||||
const sessionKey = respone.data.data || null;
|
||||
|
||||
@ -151,8 +151,8 @@ class stockStoreService extends Service {
|
||||
width: parseFloat(stockData.width) || 0,
|
||||
height: parseFloat(stockData.height) || 0,
|
||||
volume: parseFloat(stockData.volume) || 0,
|
||||
grossWeight: parseFloat(stockData.gross_weight) || 0,
|
||||
netWeight: parseFloat(stockData.net_weight) || 0,
|
||||
grossWeight: parseFloat(stockData.gross_weight) || 0, // 单位 g,Qimen 接口输出
|
||||
netWeight: parseFloat(stockData.net_weight) || 0, // 单位 g,Qimen 接口输出
|
||||
|
||||
// 分类信息
|
||||
categoryId: stockData.category_id || 0,
|
||||
@ -732,9 +732,9 @@ class stockStoreService extends Service {
|
||||
// 写入流水(除非显式跳过)
|
||||
const skipLog = meta.skipTransactionLog === true;
|
||||
if (!skipLog && ctx.service && ctx.service.systems && ctx.service.systems.stockTransaction) {
|
||||
// 锁定操作使用 LOCK 类型,释放操作使用 OUTBOUND
|
||||
// 锁定操作使用 LOCK 类型,释放操作(如取消订单)使用 UNLOCK
|
||||
await ctx.service.systems.stockTransaction.create({
|
||||
transaction_type: isLocking ? 'LOCK' : 'OUTBOUND',
|
||||
transaction_type: isLocking ? 'LOCK' : 'UNLOCK',
|
||||
warehouse_id: stockRecord.warehouse_id,
|
||||
store_id: stockRecord.store_id,
|
||||
stock_id: stockId,
|
||||
@ -1589,7 +1589,7 @@ class stockStoreService extends Service {
|
||||
* @param {string} sortParams.sortOrder - 排序方式,默认'DESC'
|
||||
* @return {Promise<Object>} 返回查询结果
|
||||
*/
|
||||
async getWarehouseStock(where, pageParams = {}, sortParams = {}) {
|
||||
async getWarehouseStock(where, pageParams = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) {
|
||||
const {
|
||||
ctx,
|
||||
app,
|
||||
@ -1601,6 +1601,15 @@ class stockStoreService extends Service {
|
||||
Op,
|
||||
} = Sequelize;
|
||||
|
||||
// 仓库ID:优先使用外部传入,否则取当前用户上下文
|
||||
const warehouseId = Number.isFinite(externalWarehouseId) && externalWarehouseId > 0
|
||||
? externalWarehouseId
|
||||
: ctx.user.store_id;
|
||||
// 货主ID:外部传入时按货主维度查询(不限定仓库)
|
||||
const storeId = Number.isFinite(externalStoreId) && externalStoreId > 0
|
||||
? externalStoreId
|
||||
: 0;
|
||||
|
||||
try {
|
||||
// 设置默认参数
|
||||
const {
|
||||
@ -1631,16 +1640,30 @@ class stockStoreService extends Service {
|
||||
where: {},
|
||||
};
|
||||
// 添加默认条件
|
||||
queryOptions.where[Op.and] = [{
|
||||
warehouse_id: ctx.user.store_id,
|
||||
},
|
||||
{
|
||||
is_valid: 'Y',
|
||||
},
|
||||
{
|
||||
deleted_at: null,
|
||||
},
|
||||
];
|
||||
if (storeId > 0) {
|
||||
// 按货主维度查询(不限定仓库)
|
||||
queryOptions.where[Op.and] = [{
|
||||
store_id: storeId,
|
||||
},
|
||||
{
|
||||
is_valid: 'Y',
|
||||
},
|
||||
{
|
||||
deleted_at: null,
|
||||
},
|
||||
];
|
||||
} else {
|
||||
queryOptions.where[Op.and] = [{
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
{
|
||||
is_valid: 'Y',
|
||||
},
|
||||
{
|
||||
deleted_at: null,
|
||||
},
|
||||
];
|
||||
}
|
||||
barcodeQueryOptions.where[Op.and] = [];
|
||||
prohibitedQueryOptions.where[Op.and] = [];
|
||||
storeOutStockQueryOptions.where[Op.and] = [];
|
||||
@ -1675,6 +1698,9 @@ class stockStoreService extends Service {
|
||||
bucket: 'storeOutStock',
|
||||
field: 'stock_id',
|
||||
},
|
||||
keyword: {
|
||||
bucket: 'keyword',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@ -1691,12 +1717,6 @@ class stockStoreService extends Service {
|
||||
hasPrevious: false,
|
||||
hasNext: false,
|
||||
},
|
||||
summary: {
|
||||
total_quantity: 0,
|
||||
total_locked: 0,
|
||||
total_available: 0,
|
||||
total_items: 0,
|
||||
},
|
||||
},
|
||||
message: `筛选条件解析失败: ${parsed.reason}`,
|
||||
};
|
||||
@ -1726,6 +1746,22 @@ class stockStoreService extends Service {
|
||||
boundItemValue = rawConditionsByField.has_bound_item.value;
|
||||
}
|
||||
|
||||
// keyword 快捷搜索:模糊匹配商品编码/名称/货物编码
|
||||
const keywordInput = rawConditionsByField.keyword || null;
|
||||
const keywordValue = keywordInput && typeof keywordInput === 'object'
|
||||
? keywordInput.value
|
||||
: keywordInput;
|
||||
if (keywordValue !== undefined && keywordValue !== null && String(keywordValue).trim() !== '') {
|
||||
const kw = `%${String(keywordValue).trim()}%`;
|
||||
queryOptions.where[Op.and].push({
|
||||
[Op.or]: [
|
||||
{ item_code: { [Op.like]: kw } },
|
||||
{ item_name: { [Op.like]: kw } },
|
||||
{ goods_code: { [Op.like]: kw } },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
if (dynamicConditions.length > 0) {
|
||||
queryOptions.where[Op.and].push({
|
||||
[Op.and]: dynamicConditions,
|
||||
@ -1838,12 +1874,6 @@ class stockStoreService extends Service {
|
||||
hasPrevious: false,
|
||||
hasNext: false,
|
||||
},
|
||||
summary: {
|
||||
total_quantity: 0,
|
||||
total_locked: 0,
|
||||
total_available: 0,
|
||||
total_items: 0,
|
||||
},
|
||||
},
|
||||
message: '查询成功',
|
||||
};
|
||||
@ -1861,12 +1891,16 @@ class stockStoreService extends Service {
|
||||
// 处理排序
|
||||
const validSortFields = [
|
||||
'id', 'item_code', 'item_name', 'quantity', 'locked_quantity',
|
||||
'tag_price', 'retail_price', 'create_at', 'update_at',
|
||||
'tag_price', 'retail_price', 'create_at', 'update_at', 'available_quantity',
|
||||
];
|
||||
|
||||
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_at';
|
||||
const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||||
queryOptions.order.push([ actualSortField, actualSortOrder ]);
|
||||
if (actualSortField === 'available_quantity') {
|
||||
queryOptions.order.push([ Sequelize.literal('(quantity - locked_quantity)'), actualSortOrder ]);
|
||||
} else {
|
||||
queryOptions.order.push([ actualSortField, actualSortOrder ]);
|
||||
}
|
||||
|
||||
// 计算分页偏移量
|
||||
const offset = (page - 1) * pageSize;
|
||||
@ -1881,12 +1915,41 @@ class stockStoreService extends Service {
|
||||
);
|
||||
|
||||
// 构建 include 数组
|
||||
const includes = [
|
||||
ctx.model.StoreWarehouse.buildStoreStockInclude({
|
||||
warehouseId: ctx.user.store_id,
|
||||
let storeStockInclude;
|
||||
|
||||
if (storeId > 0) {
|
||||
// 按货主维度查询:确保 store_warehouse 关联同时匹配 store_id 和 warehouse_id,避免一对多导致行重复
|
||||
storeStockInclude = {
|
||||
model: ctx.model.StoreWarehouse,
|
||||
as: 'store_stock',
|
||||
attributes: [ 'warehouse_remask' ],
|
||||
where: {
|
||||
store_id: storeId,
|
||||
warehouse_use_status: 1,
|
||||
[Op.and]: Sequelize.where(
|
||||
Sequelize.col('stock_warehouse.warehouse_id'),
|
||||
'=',
|
||||
Sequelize.col('store_stock.warehouse_id')
|
||||
),
|
||||
},
|
||||
required: false,
|
||||
include: [{
|
||||
model: ctx.model.Store,
|
||||
as: 'warehouse',
|
||||
attributes: [ 'company_name' ],
|
||||
required: false,
|
||||
}],
|
||||
};
|
||||
} else {
|
||||
storeStockInclude = ctx.model.StoreWarehouse.buildStoreStockInclude({
|
||||
warehouseId,
|
||||
required: true,
|
||||
attributes: [ 'store_remask' ],
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const includes = [
|
||||
storeStockInclude,
|
||||
{
|
||||
...prohibitedQueryOptions,
|
||||
model: ctx.model.ProhibitedType,
|
||||
@ -1968,21 +2031,23 @@ class stockStoreService extends Service {
|
||||
barcodeMap.get(sid).push(bc);
|
||||
}
|
||||
|
||||
// 按 business_id 分组图片(有图片即认为 is_images=Y)
|
||||
const imageStockIdSet = new Set();
|
||||
// 按 stock_id 分组图片
|
||||
const imageMap = new Map();
|
||||
for (const row of imageRows) {
|
||||
const sid = Number(row.business_id);
|
||||
const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || '';
|
||||
if (url) {
|
||||
imageStockIdSet.add(sid);
|
||||
if (!url) continue;
|
||||
if (!imageMap.has(sid)) {
|
||||
imageMap.set(sid, []);
|
||||
}
|
||||
imageMap.get(sid).push(url);
|
||||
}
|
||||
|
||||
for (const item of data) {
|
||||
const sid = item.id;
|
||||
stockDetailsMap.set(sid, {
|
||||
barcodes: barcodeMap.get(sid) || [],
|
||||
images: [],
|
||||
images: imageMap.get(sid) || [],
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -1997,8 +2062,18 @@ class stockStoreService extends Service {
|
||||
const stockDetail = stockDetailsMap.get(item.id);
|
||||
const itemBarcodes = stockDetail ? stockDetail.barcodes : [];
|
||||
const itemImages = stockDetail ? stockDetail.images : [];
|
||||
// 货主维度:仓库备注兜底仓库主体名
|
||||
let warehouseRemask = '';
|
||||
if (storeId > 0) {
|
||||
warehouseRemask = (item['store_stock.warehouse_remask'] || '')
|
||||
|| (item['store_stock.warehouse.company_name'] || '');
|
||||
delete item['store_stock.warehouse_remask'];
|
||||
delete item['store_stock.warehouse'];
|
||||
delete item['store_stock.warehouse.company_name'];
|
||||
}
|
||||
return {
|
||||
...item,
|
||||
...(storeId > 0 ? { warehouse_remask: warehouseRemask } : {}),
|
||||
barcodes: itemBarcodes,
|
||||
images: itemImages,
|
||||
available_quantity: availableQuantity,
|
||||
@ -2011,20 +2086,6 @@ class stockStoreService extends Service {
|
||||
};
|
||||
});
|
||||
|
||||
// 添加汇总信息
|
||||
const summary = {
|
||||
total_quantity: data.reduce((sum, item) => sum + item.quantity, 0),
|
||||
total_locked: data.reduce((sum, item) => sum + item.locked_quantity, 0),
|
||||
total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item
|
||||
.locked_quantity), 0),
|
||||
total_items: data.length,
|
||||
// 如果有条码查询,添加匹配统计
|
||||
...(hasBarcodeCondition && {
|
||||
barcode_matched_count: matchedStockIds.length,
|
||||
barcode_search_value: parsedBarcodeInput ? parsedBarcodeInput.value : null,
|
||||
}),
|
||||
};
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
@ -2037,7 +2098,6 @@ class stockStoreService extends Service {
|
||||
hasPrevious,
|
||||
hasNext,
|
||||
},
|
||||
summary,
|
||||
queryInfo: {
|
||||
conditions: normalizedWhere,
|
||||
sortField: actualSortField,
|
||||
@ -2062,12 +2122,6 @@ class stockStoreService extends Service {
|
||||
hasPrevious: false,
|
||||
hasNext: false,
|
||||
},
|
||||
summary: {
|
||||
total_quantity: 0,
|
||||
total_locked: 0,
|
||||
total_available: 0,
|
||||
total_items: 0,
|
||||
},
|
||||
},
|
||||
message: `查询失败: ${error.message}`,
|
||||
};
|
||||
@ -2197,6 +2251,131 @@ class stockStoreService extends Service {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出外仓商品列表。
|
||||
* 说明:复用 getWarehouseStock 的外部货主维度筛选语义,分页拉取全量数据后生成 Excel 并上传。
|
||||
* @param {Object} where 筛选条件
|
||||
* @param {Object} sortParams 排序参数
|
||||
* @param {string} [sortParams.sortField] 排序字段
|
||||
* @param {string} [sortParams.sortOrder] 排序方向(ASC|DESC)
|
||||
* @param {number} [externalWarehouseId=0] 外部仓库ID(0 表示按货主维度查)
|
||||
* @param {number} [externalStoreId=0] 外部货主ID
|
||||
* @return {Promise<Object>} 导出上传结果(含 url/fileKey 等)
|
||||
*/
|
||||
async exportExternalWarehouseStock(where = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) {
|
||||
const { ctx } = this;
|
||||
const warehouseId = externalWarehouseId > 0 ? externalWarehouseId : (ctx.user && ctx.user.store_id ? ctx.user.store_id : 'common');
|
||||
const pageSize = 500;
|
||||
let page = 1;
|
||||
let hasNext = true;
|
||||
const rows = [];
|
||||
|
||||
while (hasNext) {
|
||||
const pageResult = await this.getWarehouseStock(where, {
|
||||
page,
|
||||
pageSize,
|
||||
}, sortParams, externalWarehouseId, externalStoreId);
|
||||
|
||||
if (!pageResult || pageResult.code !== 200) {
|
||||
throw new Error(pageResult && pageResult.message ? pageResult.message : '导出外仓商品失败');
|
||||
}
|
||||
|
||||
const list = pageResult.data && Array.isArray(pageResult.data.list) ? pageResult.data.list : [];
|
||||
|
||||
// 收集可能的 storeIds,用于回退查询 store_remask(优先取 item.store_id,其次 item['store_warehouse.store_id'])
|
||||
const storeIds = [];
|
||||
for (const item of list) {
|
||||
const sid = item.store_id || item['store_warehouse.store_id'];
|
||||
if (sid && !storeIds.includes(Number(sid))) {
|
||||
storeIds.push(Number(sid));
|
||||
}
|
||||
}
|
||||
|
||||
// 查询 StoreWarehouse 获取 store_remask(如果可用)
|
||||
const storeMap = new Map();
|
||||
try {
|
||||
if (storeIds.length > 0 && ctx.model && ctx.model.StoreWarehouse) {
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
const storeWhere = { store_id: { [Op.in]: storeIds } };
|
||||
if (externalWarehouseId > 0) {
|
||||
storeWhere.warehouse_id = externalWarehouseId;
|
||||
}
|
||||
const storeRows = await ctx.model.StoreWarehouse.findAll({
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
where: storeWhere,
|
||||
raw: true,
|
||||
});
|
||||
for (const r of storeRows || []) {
|
||||
storeMap.set(Number(r.store_id), r.store_remask);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
ctx && ctx.logger && ctx.logger.warn && ctx.logger.warn('[exportExternalWarehouseStock] 查询 StoreWarehouse 失败', e && e.message);
|
||||
}
|
||||
|
||||
for (const item of list) {
|
||||
const storeId = Number(item.store_id || item['store_warehouse.store_id'] || 0);
|
||||
const storeRemask = item.store_remask || item['store_warehouse.store_remask'] || storeMap.get(storeId) || '';
|
||||
rows.push({
|
||||
id: item.id,
|
||||
item_code: item.item_code,
|
||||
goods_code: item.goods_code || '',
|
||||
item_name: item.item_name,
|
||||
brand_name: item.brand_name || '',
|
||||
sku_property: item.sku_property || '',
|
||||
stock_unit: item.stock_unit || '',
|
||||
tag_price: item.tag_price || '',
|
||||
retail_price: item.retail_price || '',
|
||||
gross_weight: item.gross_weight || '',
|
||||
store_remask: storeRemask,
|
||||
barcodes: Array.isArray(item.barcodes) ? item.barcodes.join(',') : '',
|
||||
quantity: item.quantity,
|
||||
locked_quantity: item.locked_quantity,
|
||||
available_quantity: item.available_quantity,
|
||||
lock_rate_display: item.lock_rate_display,
|
||||
create_at_display: item.create_at_display,
|
||||
update_at_display: item.update_at_display,
|
||||
});
|
||||
}
|
||||
|
||||
hasNext = Boolean(pageResult.data && pageResult.data.pagination && pageResult.data.pagination.hasNext);
|
||||
page += 1;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}${String(now.getMilliseconds()).padStart(3, '0')}`;
|
||||
|
||||
return await ctx.service.systems.excel.generateAndUpload({
|
||||
filename: `外仓商品导出_${dateToken}.xlsx`,
|
||||
dir: `exports/stock/warehouse/${warehouseId}`,
|
||||
category: 'document',
|
||||
sheets: [{
|
||||
name: '外仓商品',
|
||||
columns: [
|
||||
{ header: 'SKU', key: 'id' },
|
||||
{ header: '商品编码', key: 'item_code' },
|
||||
{ header: '货物编码', key: 'goods_code' },
|
||||
{ header: '商品名称', key: 'item_name' },
|
||||
{ header: '品牌', key: 'brand_name' },
|
||||
{ header: '规格', key: 'sku_property' },
|
||||
{ header: '库存单位', key: 'stock_unit' },
|
||||
{ header: '标价', key: 'tag_price' },
|
||||
{ header: '零售价', key: 'retail_price' },
|
||||
{ header: '毛重', key: 'gross_weight' },
|
||||
{ header: '货主', key: 'store_remask' },
|
||||
{ header: '条码', key: 'barcodes' },
|
||||
{ header: '库存', key: 'quantity' },
|
||||
{ header: '锁定库存', key: 'locked_quantity' },
|
||||
{ header: '可用库存', key: 'available_quantity' },
|
||||
{ header: '锁定率', key: 'lock_rate_display' },
|
||||
{ header: '创建时间', key: 'create_at_display' },
|
||||
{ header: '更新时间', key: 'update_at_display' },
|
||||
],
|
||||
rows,
|
||||
}],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建Sequelize查询条件
|
||||
* @param {string} fieldKey - 字段键名
|
||||
@ -2394,10 +2573,10 @@ class stockStoreService extends Service {
|
||||
};
|
||||
|
||||
} else if (method === 'gross_weight') {
|
||||
// 毛重应该是数字
|
||||
const updateValue = parseFloat(value);
|
||||
if (isNaN(updateValue) || updateValue < 0) {
|
||||
return { message: '毛重必须是有效的正数', code: 405 };
|
||||
// 毛重必须为正整数(单位 g)
|
||||
const updateValue = parseInt(value, 10);
|
||||
if (isNaN(updateValue) || updateValue < 0 || !Number.isInteger(Number(value))) {
|
||||
return { message: '毛重必须是有效的正整数(单位 g)', code: 405 };
|
||||
}
|
||||
updateData = {
|
||||
gross_weight: updateValue,
|
||||
@ -2555,7 +2734,8 @@ class stockStoreService extends Service {
|
||||
const {
|
||||
stock_id = null, store_id = null, page = 1, pageSize = 20, item_code = '', item_name = '',
|
||||
} = data || {};
|
||||
const warehouseId = ctx.user.store_id;
|
||||
// 优先使用 systemMethods 层校验后传入的 warehouse_id
|
||||
const warehouseId = Number(data._warehouseId || 0) || ctx.user.store_id;
|
||||
let barcodes = [];
|
||||
let warehouseStock = null;
|
||||
let total = 0;
|
||||
@ -2649,12 +2829,26 @@ class stockStoreService extends Service {
|
||||
}),
|
||||
]);
|
||||
}
|
||||
// 批量查询奇门应用名称
|
||||
const appKeys = [...new Set(barcodes.map(item => item.app_key).filter(Boolean))];
|
||||
const qimenAppMap = new Map();
|
||||
if (appKeys.length > 0) {
|
||||
const qimenApps = await ctx.model.QimenApp.findAll({
|
||||
where: { app_key: appKeys },
|
||||
attributes: [ 'app_key', 'name' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const app of qimenApps) {
|
||||
qimenAppMap.set(app.app_key, app.name || '');
|
||||
}
|
||||
}
|
||||
|
||||
const results = barcodes.map(item => {
|
||||
return {
|
||||
app_key: item.app_key,
|
||||
create_from: item.create_from === 'qimen' ? '奇门' : 'API',
|
||||
id: item.id,
|
||||
app_name: item.app_key,
|
||||
app_name: qimenAppMap.get(item.app_key) || item.app_key,
|
||||
item_code: item.item_code,
|
||||
stock_id: item['warehouse_stock.id'],
|
||||
hasBind: !!item.stock_id,
|
||||
|
||||
@ -36,7 +36,8 @@ class StockWarehouseService extends Service {
|
||||
async getStockDetails(stockIds, options = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { cacheTTL = DEFAULT_STOCK_DETAIL_CACHE_TTL } = options;
|
||||
const warehouseId = options.warehouseId != null ? options.warehouseId : ctx.user.store_id;
|
||||
// 用 !== undefined 代替 != null:显式传 null 表示跳过 warehouse 过滤(如货主侧查询)
|
||||
const warehouseId = options.warehouseId !== undefined ? options.warehouseId : ctx.user.store_id;
|
||||
|
||||
if (!Array.isArray(stockIds) || stockIds.length === 0) {
|
||||
return [];
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -465,13 +465,10 @@ class InventoryService extends Service {
|
||||
});
|
||||
|
||||
if (isFullTransfer) {
|
||||
// 全量移库且合并:删除原记录
|
||||
await ctx.model.Storage.update({
|
||||
is_enabled: 0,
|
||||
delete_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
// 全量移库且合并:硬删除原记录,释放唯一键
|
||||
await ctx.model.Storage.destroy({
|
||||
where: { id: storageId },
|
||||
force: true,
|
||||
transaction,
|
||||
});
|
||||
srcSpaceDelta.qtyDelta -= srcRecord.quantity;
|
||||
@ -930,13 +927,10 @@ class InventoryService extends Service {
|
||||
});
|
||||
|
||||
if (isFullTransfer) {
|
||||
// 全量:软删除原记录
|
||||
await ctx.model.Storage.update({
|
||||
is_enabled: 0,
|
||||
delete_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
// 全量:硬删除原记录,释放唯一键
|
||||
await ctx.model.Storage.destroy({
|
||||
where: { id: srcRecord.id },
|
||||
force: true,
|
||||
transaction,
|
||||
});
|
||||
} else {
|
||||
@ -1157,6 +1151,21 @@ class InventoryService extends Service {
|
||||
return { code: 409, message: '库存记录被锁定,请稍后重试', data: null };
|
||||
}
|
||||
|
||||
if (error.name === 'SequelizeUniqueConstraintError') {
|
||||
return {
|
||||
code: 409,
|
||||
message: '目标库位已存在该商品同批次同类型的库存记录,合并移库失败,请稍后重试或使用 transferLocation 逐条移库',
|
||||
data: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (error.name === 'SequelizeValidationError') {
|
||||
ctx.logger.error('[inventory.transferByProduct] Sequelize 校验失败', {
|
||||
errors: error.errors?.map(e => ({ path: e.path, message: e.message, value: e.value })),
|
||||
});
|
||||
return { code: 400, message: `数据校验失败: ${error.errors?.map(e => e.message).join('; ') || error.message}`, data: null };
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@ -71,11 +71,12 @@ class StorageManagementService extends Service {
|
||||
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
const orderItemModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||||
|
||||
// 2) 查询当前仓库所有未完成储位分配的订单
|
||||
// 2) 查询当前仓库所有未完成储位分配的订单(排除待审核 step=1)
|
||||
const pendingOrders = await orderModel.findAll({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
storage_status: { [Op.ne]: 'fin' },
|
||||
step: { [Op.ne]: 1 },
|
||||
delete_at: null,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
|
||||
@ -1,9 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('node:crypto');
|
||||
const fs = require('node:fs');
|
||||
const fsp = require('node:fs/promises');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const ExcelJS = require('exceljs');
|
||||
const Service = require('egg').Service;
|
||||
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
const RECEIVING_EXPORT_PAGE_SIZE = 200;
|
||||
const RECEIVING_ITEMS_FETCH_BATCH_SIZE = 100;
|
||||
|
||||
function getStartOfDayMs(value) {
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return null;
|
||||
@ -366,8 +375,8 @@ class ReceivingService extends Service {
|
||||
available_quantity: availableQuantity,
|
||||
lock_rate: parseFloat(lockRate),
|
||||
lock_rate_display: `${lockRate}%`,
|
||||
create_at_display: item.create_at ? this.formatDate(item.create_at) : '',
|
||||
update_at_display: item.update_at ? this.formatDate(item.update_at) : '',
|
||||
create_at_display: item.created_at ? this.app.formatDate(item.created_at) : '',
|
||||
update_at_display: item.updated_at ? this.app.formatDate(item.updated_at) : '',
|
||||
};
|
||||
});
|
||||
|
||||
@ -425,6 +434,201 @@ class ReceivingService extends Service {
|
||||
};
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 货主侧收货单列表查询。
|
||||
* 以 store_id 为维度查询收货单,支持分页、多条件筛选与排序。
|
||||
* @param {Object} where 动态筛选条件
|
||||
* @param {number} storeId 货主ID(必填)
|
||||
* @param {Object} [pageParams] 分页参数
|
||||
* @param {number} [pageParams.page=1] 页码
|
||||
* @param {number} [pageParams.pageSize=20] 每页条数
|
||||
* @param {Object} [sortParams] 排序参数
|
||||
* @param {string} [sortParams.sortField='created_at'] 排序字段
|
||||
* @param {string} [sortParams.sortOrder='DESC'] 排序方向
|
||||
* @return {Promise<Object>} 列表、分页与汇总信息
|
||||
*/
|
||||
async getStoreReceivingList(where, storeId, pageParams = {}, sortParams = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Sequelize } = app;
|
||||
const { Op } = Sequelize;
|
||||
const { page = 1, pageSize = 20 } = pageParams;
|
||||
const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams;
|
||||
|
||||
try {
|
||||
const queryOptions = {
|
||||
where: {
|
||||
[Op.and]: [
|
||||
{ store_id: storeId },
|
||||
],
|
||||
},
|
||||
order: [],
|
||||
attributes: {
|
||||
exclude: [ 'deleted_at' ],
|
||||
},
|
||||
};
|
||||
|
||||
const normalizedWhere = where && typeof where === 'object' ? where : {};
|
||||
let parsedResult = ctx.whereParsed;
|
||||
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
|
||||
const parsed = parseWhereConditions({
|
||||
where: normalizedWhere,
|
||||
app,
|
||||
specialFieldMap: {
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!parsed.ok) {
|
||||
return {
|
||||
code: 400,
|
||||
data: {
|
||||
list: [],
|
||||
pagination: { page: Number(page), pageSize: Number(pageSize), total: 0, totalPages: 0, hasPrevious: false, hasNext: false },
|
||||
summary: { total_quantity: 0, total_locked: 0, total_available: 0, total_items: 0 },
|
||||
},
|
||||
message: `筛选条件解析失败: ${parsed.reason}`,
|
||||
};
|
||||
}
|
||||
parsedResult = parsed.result;
|
||||
}
|
||||
|
||||
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
|
||||
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|
||||
|| normalizedWhere.quickWhere;
|
||||
|
||||
if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') {
|
||||
const quickValue = String(quickWhereRaw.value).trim();
|
||||
dynamicConditions.push({
|
||||
[Op.or]: {
|
||||
store_name: { [Sequelize.Op.like]: `%${quickValue}%` },
|
||||
receiving_number: { [Sequelize.Op.like]: `%${quickValue}%` },
|
||||
tracking_number: { [Sequelize.Op.like]: `%${quickValue}%` },
|
||||
creator_snapshot: { [Sequelize.Op.like]: `%${quickValue}%` },
|
||||
license_plate: { [Sequelize.Op.like]: `%${quickValue}%` },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (dynamicConditions.length > 0) {
|
||||
queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions });
|
||||
}
|
||||
|
||||
const validSortFields = [ 'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id' ];
|
||||
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
|
||||
const actualSortOrder = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||||
queryOptions.order.push([ actualSortField, actualSortOrder ]);
|
||||
|
||||
const offset = (page - 1) * pageSize;
|
||||
|
||||
const [ total, data ] = await Promise.all([
|
||||
ctx.model.Receiving.count({
|
||||
where: queryOptions.where,
|
||||
distinct: true,
|
||||
}),
|
||||
ctx.model.Receiving.findAll({
|
||||
...queryOptions,
|
||||
limit: Number(pageSize),
|
||||
offset: Number(offset),
|
||||
distinct: true,
|
||||
raw: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
const totalPages = Math.ceil(total / pageSize);
|
||||
const hasPrevious = page > 1;
|
||||
const hasNext = page < totalPages;
|
||||
|
||||
// 获取收货单图片
|
||||
const stockIds = data.map(item => item.id);
|
||||
let images = [];
|
||||
if (stockIds.length > 0) {
|
||||
images = await ctx.model.FileReference.findAll({
|
||||
where: {
|
||||
business_type: 'receiving',
|
||||
business_id: { [Op.in]: stockIds },
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.File,
|
||||
as: 'file',
|
||||
attributes: [ 'file_url' ],
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
const processedData = data.map(item => {
|
||||
const availableQuantity = Math.max(0, item.total_quantity || 0);
|
||||
const itemImages = images
|
||||
.filter(row => Number(row.business_id) === item.id)
|
||||
.map(row => row.file.file_url);
|
||||
// 从 creator_snapshot 解析操作人姓名
|
||||
let creatorName = '';
|
||||
try {
|
||||
if (item.creator_snapshot) {
|
||||
const snapshot = JSON.parse(item.creator_snapshot);
|
||||
creatorName = snapshot.name || '';
|
||||
}
|
||||
} catch (_) {
|
||||
// ignore parse error
|
||||
}
|
||||
return {
|
||||
...item,
|
||||
images: itemImages,
|
||||
available_quantity: availableQuantity,
|
||||
lock_rate: 0,
|
||||
lock_rate_display: '0%',
|
||||
creator_name: creatorName,
|
||||
create_at_display: item.created_at ? this.app.formatDate(item.created_at) : '',
|
||||
update_at_display: item.updated_at ? this.app.formatDate(item.updated_at) : '',
|
||||
};
|
||||
});
|
||||
|
||||
const summary = {
|
||||
total_quantity: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0),
|
||||
total_locked: 0,
|
||||
total_available: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0),
|
||||
total_items: data.length,
|
||||
};
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
list: processedData,
|
||||
pagination: {
|
||||
page: Number(page),
|
||||
pageSize: Number(pageSize),
|
||||
total,
|
||||
totalPages,
|
||||
hasPrevious,
|
||||
hasNext,
|
||||
},
|
||||
summary,
|
||||
queryInfo: {
|
||||
conditions: normalizedWhere,
|
||||
sortField: actualSortField,
|
||||
sortOrder: actualSortOrder,
|
||||
hasBarcodeSearch: false,
|
||||
},
|
||||
},
|
||||
message: '查询成功',
|
||||
};
|
||||
} catch (error) {
|
||||
ctx.logger.error('[ReceivingService.getStoreReceivingList] 查询失败:', error);
|
||||
return {
|
||||
code: 500,
|
||||
data: {
|
||||
list: [],
|
||||
pagination: { page: Number(page || 1), pageSize: Number(pageSize || 20), total: 0, totalPages: 0, hasPrevious: false, hasNext: false },
|
||||
summary: { total_quantity: 0, total_locked: 0, total_available: 0, total_items: 0 },
|
||||
},
|
||||
message: `查询失败: ${error.message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 获取收货单详情(主单 + 明细分页 + 图片)。
|
||||
* @param {Object} data 请求体
|
||||
@ -2904,11 +3108,11 @@ class ReceivingService extends Service {
|
||||
async deleteDetail(data) {
|
||||
const ctx = this.ctx;
|
||||
const { detail_id } = data;
|
||||
const creator_id = ctx.user.employees_id;
|
||||
const warehouse_id = ctx.user.store_id;
|
||||
// 验证明细是否存在
|
||||
// 验证明细是否存在(通过收货单的 warehouse_id 做权限校验,不限制 creator_id,
|
||||
// 以允许同一仓库下不同操作员删除彼此创建的明细,与 get 方法行为保持一致)
|
||||
const detail = await ctx.model.ReceivingDetail.findOne({
|
||||
where: { id: detail_id, creator_id },
|
||||
where: { id: detail_id },
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Receiving,
|
||||
@ -4507,6 +4711,433 @@ class ReceivingService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出收货单列表(双 sheet:收货单列表 + 收货单明细)。
|
||||
* 复用 getStoreReceivingList 的筛选与排序语义,分页拉取全量数据后生成 Excel 并上传。
|
||||
* @param {Object} options 导出选项
|
||||
* @param {Object} [options.where] 筛选条件
|
||||
* @param {number} options.storeId 货主ID
|
||||
* @param {Object} [options.sort] 排序参数
|
||||
* @param {Function} [options.onProgress] 进度回调
|
||||
* @return {Promise<Object>} 上传结果与统计信息
|
||||
*/
|
||||
async exportReceivingList(options = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Sequelize } = app;
|
||||
const { Op } = Sequelize;
|
||||
const safeOptions = options && typeof options === 'object' ? options : {};
|
||||
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
|
||||
const storeId = Number(safeOptions.storeId);
|
||||
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
|
||||
const progressHandler = typeof safeOptions.onProgress === 'function'
|
||||
? safeOptions.onProgress
|
||||
: async () => {};
|
||||
|
||||
if (!storeId) {
|
||||
throw new Error('货主ID不能为空,无法导出');
|
||||
}
|
||||
|
||||
const sortField = sort.sortField || 'created_at';
|
||||
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||||
const validSortFields = [
|
||||
'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id',
|
||||
];
|
||||
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
|
||||
|
||||
// 构建 where 条件(与 getStoreReceivingList 一致)
|
||||
const queryOptions = {
|
||||
where: { [Op.and]: [{ store_id: storeId }] },
|
||||
};
|
||||
|
||||
const normalizedWhere = { ...where };
|
||||
const parsed = parseWhereConditions({
|
||||
where: normalizedWhere,
|
||||
app,
|
||||
specialFieldMap: {
|
||||
quickWhere: { bucket: 'quick' },
|
||||
},
|
||||
});
|
||||
|
||||
if (!parsed.ok) {
|
||||
throw new Error(`筛选条件解析失败: ${parsed.reason}`);
|
||||
}
|
||||
const parsedResult = parsed.result;
|
||||
|
||||
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
|
||||
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|
||||
|| normalizedWhere.quickWhere;
|
||||
|
||||
if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') {
|
||||
const quickValue = String(quickWhereRaw.value).trim();
|
||||
dynamicConditions.push({
|
||||
[Op.or]: {
|
||||
store_name: { [Op.like]: `%${quickValue}%` },
|
||||
receiving_number: { [Op.like]: `%${quickValue}%` },
|
||||
tracking_number: { [Op.like]: `%${quickValue}%` },
|
||||
creator_snapshot: { [Op.like]: `%${quickValue}%` },
|
||||
license_plate: { [Op.like]: `%${quickValue}%` },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (dynamicConditions.length > 0) {
|
||||
queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions });
|
||||
}
|
||||
|
||||
// ---- 分页拉取收货单列表 ----
|
||||
const totalCount = await ctx.model.Receiving.count({
|
||||
where: queryOptions.where,
|
||||
distinct: true,
|
||||
});
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: totalCount > 0 ? 10 : 85,
|
||||
message: totalCount > 0 ? `已命中 ${totalCount} 条收货单,开始导出` : '未命中数据,开始生成空文件',
|
||||
});
|
||||
|
||||
const allReceivingOrders = [];
|
||||
let page = 1;
|
||||
let fetchedCount = 0;
|
||||
|
||||
while (fetchedCount < totalCount) {
|
||||
const rows = await ctx.model.Receiving.findAll({
|
||||
where: queryOptions.where,
|
||||
order: [[ actualSortField, sortOrder ]],
|
||||
limit: RECEIVING_EXPORT_PAGE_SIZE,
|
||||
offset: (page - 1) * RECEIVING_EXPORT_PAGE_SIZE,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!Array.isArray(rows) || rows.length === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
allReceivingOrders.push(...rows);
|
||||
fetchedCount += rows.length;
|
||||
page += 1;
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)),
|
||||
message: `正在拉取收货单列表,已完成 ${fetchedCount}/${totalCount}`,
|
||||
});
|
||||
}
|
||||
|
||||
// ---- 批量拉取收货单明细 ----
|
||||
const allReceivingIds = allReceivingOrders.map(r => Number(r.id)).filter(Boolean);
|
||||
/** @type {Map<number, Array<Object>>} receiving_id → details */
|
||||
const detailsMap = new Map();
|
||||
|
||||
if (allReceivingIds.length > 0) {
|
||||
const batchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE;
|
||||
const totalBatches = Math.ceil(allReceivingIds.length / batchSize);
|
||||
|
||||
for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += batchSize) {
|
||||
const batchIds = allReceivingIds.slice(batchIdx, batchIdx + batchSize);
|
||||
|
||||
const details = await ctx.model.ReceivingDetail.findAll({
|
||||
where: { receiving_id: { [Op.in]: batchIds } },
|
||||
order: [[ 'receiving_id', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
for (const detail of details) {
|
||||
const rid = Number(detail.receiving_id);
|
||||
if (!detailsMap.has(rid)) {
|
||||
detailsMap.set(rid, []);
|
||||
}
|
||||
detailsMap.get(rid).push(detail);
|
||||
}
|
||||
|
||||
const currentBatch = Math.floor(batchIdx / batchSize) + 1;
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)),
|
||||
message: `正在拉取收货单明细,已完成批次 ${currentBatch}/${totalBatches}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: 55,
|
||||
message: '正在生成 Excel 文件...',
|
||||
});
|
||||
|
||||
// ---- 生成 Excel(流式写入,两个 Sheet) ----
|
||||
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-receiving-export-'));
|
||||
const now = new Date();
|
||||
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
|
||||
const filename = `收货单导出_${dateToken}.xlsx`;
|
||||
const filePath = path.join(tempDir, filename);
|
||||
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
|
||||
filename: filePath,
|
||||
useStyles: false,
|
||||
useSharedStrings: false,
|
||||
});
|
||||
|
||||
const normalizeCellValue = value => {
|
||||
if (value === null || value === undefined) return '';
|
||||
if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString();
|
||||
return value;
|
||||
};
|
||||
|
||||
const statusLabelMap = {
|
||||
receiving: '收货中',
|
||||
completed: '已完成',
|
||||
cancelled: '已作废',
|
||||
};
|
||||
|
||||
const detailStatusLabelMap = {
|
||||
all_matched: '全部匹配',
|
||||
partial_matched: '部分匹配',
|
||||
unmatched: '未匹配',
|
||||
};
|
||||
|
||||
const storageStatusLabelMap = {
|
||||
none: '未入库',
|
||||
waiting: '等待入库',
|
||||
partial: '部分入库',
|
||||
all: '全部入库',
|
||||
};
|
||||
|
||||
const deliveryMethodLabelMap = {
|
||||
truck: '货车',
|
||||
express: '快递',
|
||||
air_freight: '空运',
|
||||
sea_freight: '海运',
|
||||
other: '其他',
|
||||
};
|
||||
|
||||
const loadingMethodLabelMap = {
|
||||
with_pallet: '带托盘',
|
||||
without_pallet: '不带托盘',
|
||||
};
|
||||
|
||||
// Sheet 1: 收货单列表
|
||||
const sheet1 = workbook.addWorksheet('收货单列表');
|
||||
const receivingColumns = [
|
||||
{ header: '收货单ID', key: 'id', width: 10 },
|
||||
{ header: '收货单号', key: 'receiving_number', width: 22 },
|
||||
{ header: '货主', key: 'store_name', width: 20 },
|
||||
{ header: '收货状态', key: 'status_label', width: 12 },
|
||||
{ header: '明细匹配状态', key: 'detail_status_label', width: 14 },
|
||||
{ header: '入库状态', key: 'storage_status_label', width: 12 },
|
||||
{ header: '来货方式', key: 'delivery_method_label', width: 12 },
|
||||
{ header: '车牌号', key: 'license_plate', width: 14 },
|
||||
{ header: '快递单号', key: 'tracking_number', width: 22 },
|
||||
{ header: '装卸方式', key: 'loading_method_label', width: 12 },
|
||||
{ header: '总商品种类', key: 'total_items', width: 12 },
|
||||
{ header: '总数量', key: 'total_quantity', width: 12 },
|
||||
{ header: '总箱数', key: 'total_boxes', width: 10 },
|
||||
{ header: '总托盘数', key: 'total_pallets', width: 10 },
|
||||
{ header: '审核状态', key: 'is_review_label', width: 10 },
|
||||
{ header: '创建人', key: 'creator_name', width: 14 },
|
||||
{ header: '备注', key: 'remark', width: 30 },
|
||||
{ header: '收货开始时间', key: 'receiving_start_time', width: 20 },
|
||||
{ header: '收货结束时间', key: 'receiving_end_time', width: 20 },
|
||||
{ header: '创建时间', key: 'created_at', width: 20 },
|
||||
{ header: '更新时间', key: 'updated_at', width: 20 },
|
||||
];
|
||||
sheet1.columns = receivingColumns;
|
||||
|
||||
for (const row of allReceivingOrders) {
|
||||
let creatorName = '';
|
||||
try {
|
||||
if (row.creator_snapshot) {
|
||||
const snapshot = JSON.parse(row.creator_snapshot);
|
||||
creatorName = snapshot.name || '';
|
||||
}
|
||||
} catch (_) { /* ignore */ }
|
||||
|
||||
sheet1.addRow({
|
||||
id: row.id,
|
||||
receiving_number: normalizeCellValue(row.receiving_number),
|
||||
store_name: normalizeCellValue(row.store_name),
|
||||
status_label: statusLabelMap[row.status] || row.status || '',
|
||||
detail_status_label: detailStatusLabelMap[row.detail_status] || row.detail_status || '',
|
||||
storage_status_label: storageStatusLabelMap[row.storage_status] || row.storage_status || '',
|
||||
delivery_method_label: deliveryMethodLabelMap[row.delivery_method] || row.delivery_method || '',
|
||||
license_plate: normalizeCellValue(row.license_plate),
|
||||
tracking_number: normalizeCellValue(row.tracking_number),
|
||||
loading_method_label: loadingMethodLabelMap[row.loading_method] || row.loading_method || '',
|
||||
total_items: row.total_items,
|
||||
total_quantity: row.total_quantity,
|
||||
total_boxes: row.total_boxes,
|
||||
total_pallets: row.total_pallets,
|
||||
is_review_label: row.is_review === 1 ? '已审核' : '未审核',
|
||||
creator_name: creatorName,
|
||||
remark: normalizeCellValue(row.remark),
|
||||
receiving_start_time: normalizeCellValue(row.receiving_start_time),
|
||||
receiving_end_time: normalizeCellValue(row.receiving_end_time),
|
||||
created_at: normalizeCellValue(row.created_at),
|
||||
updated_at: normalizeCellValue(row.updated_at),
|
||||
}).commit();
|
||||
}
|
||||
sheet1.commit();
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: 70,
|
||||
message: '正在写入收货单明细...',
|
||||
});
|
||||
|
||||
// Sheet 2: 收货单明细
|
||||
const sheet2 = workbook.addWorksheet('收货单明细');
|
||||
const detailColumns = [
|
||||
{ header: '收货单号', key: 'receiving_number', width: 22 },
|
||||
{ header: '收货单ID', key: 'receiving_id', width: 12 },
|
||||
{ header: '明细ID', key: 'detail_id', width: 10 },
|
||||
{ header: '商品名称', key: 'product_name', width: 28 },
|
||||
{ header: '商品条码', key: 'barcode', width: 20 },
|
||||
{ header: '系统商品ID', key: 'system_product_id', width: 14 },
|
||||
{ header: '实际收货数量', key: 'actual_quantity', width: 14 },
|
||||
{ header: '箱数', key: 'box_quantity', width: 10 },
|
||||
{ header: '托盘数', key: 'pallet_quantity', width: 10 },
|
||||
{ header: '收货状态', key: 'receiving_status_label', width: 12 },
|
||||
{ header: '入库状态', key: 'storage_status_label', width: 12 },
|
||||
{ header: '已入库数量', key: 'stored_quantity', width: 12 },
|
||||
{ header: '批次号', key: 'batch_number', width: 16 },
|
||||
{ header: '生产日期', key: 'production_date', width: 14 },
|
||||
{ header: '到期日期', key: 'expiry_date', width: 14 },
|
||||
{ header: '备注', key: 'remark', width: 30 },
|
||||
{ header: '创建时间', key: 'created_at', width: 20 },
|
||||
];
|
||||
sheet2.columns = detailColumns;
|
||||
|
||||
// 构建 receiving_number 映射
|
||||
const receivingCodeMap = new Map();
|
||||
for (const row of allReceivingOrders) {
|
||||
receivingCodeMap.set(Number(row.id), row.receiving_number || '');
|
||||
}
|
||||
|
||||
const detailReceivingStatusLabelMap = {
|
||||
pending: '待收货',
|
||||
receiving: '收货中',
|
||||
completed: '已完成',
|
||||
cancelled: '已作废',
|
||||
};
|
||||
|
||||
const detailStorageStatusLabelMap = {
|
||||
none: '未入库',
|
||||
waiting: '等待入库',
|
||||
partial: '部分入库',
|
||||
all: '全部入库',
|
||||
};
|
||||
|
||||
// 按收货单分页写入明细
|
||||
const itemBatchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE;
|
||||
let itemWrittenCount = 0;
|
||||
const totalReceivingOrders = allReceivingIds.length;
|
||||
|
||||
for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += itemBatchSize) {
|
||||
const batchIds = allReceivingIds.slice(batchIdx, batchIdx + itemBatchSize);
|
||||
|
||||
for (const rid of batchIds) {
|
||||
const receivingNumber = receivingCodeMap.get(rid) || '';
|
||||
const details = detailsMap.get(rid) || [];
|
||||
|
||||
for (const detail of details) {
|
||||
sheet2.addRow({
|
||||
receiving_number: receivingNumber,
|
||||
receiving_id: rid,
|
||||
detail_id: detail.id,
|
||||
product_name: normalizeCellValue(detail.product_name),
|
||||
barcode: normalizeCellValue(detail.barcode),
|
||||
system_product_id: normalizeCellValue(detail.system_product_id),
|
||||
actual_quantity: detail.actual_quantity,
|
||||
box_quantity: detail.box_quantity,
|
||||
pallet_quantity: detail.pallet_quantity,
|
||||
receiving_status_label: detailReceivingStatusLabelMap[detail.receiving_status] || detail.receiving_status || '',
|
||||
storage_status_label: detailStorageStatusLabelMap[detail.storage_status] || detail.storage_status || '',
|
||||
stored_quantity: detail.stored_quantity,
|
||||
batch_number: normalizeCellValue(detail.batch_number),
|
||||
production_date: normalizeCellValue(detail.production_date),
|
||||
expiry_date: normalizeCellValue(detail.expiry_date),
|
||||
remark: normalizeCellValue(detail.remark),
|
||||
created_at: normalizeCellValue(detail.created_at),
|
||||
}).commit();
|
||||
}
|
||||
|
||||
itemWrittenCount += 1;
|
||||
}
|
||||
|
||||
const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1;
|
||||
const totalBatches = Math.ceil(totalReceivingOrders / itemBatchSize);
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)),
|
||||
message: `正在写入收货单明细,已完成 ${itemWrittenCount}/${totalReceivingOrders} 条收货单`,
|
||||
});
|
||||
}
|
||||
sheet2.commit();
|
||||
|
||||
await workbook.commit();
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: 92,
|
||||
message: '正在上传文件...',
|
||||
});
|
||||
|
||||
// ---- 上传文件 ----
|
||||
const uploadService = ctx?.service?.systems?.upload;
|
||||
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
|
||||
throw new Error('上传服务不可用');
|
||||
}
|
||||
|
||||
const stat = await fsp.stat(filePath);
|
||||
const randomToken = crypto.randomBytes(6).toString('hex');
|
||||
const uploadKey = `exports/receiving/${storeId}/${Date.now()}_${randomToken}.xlsx`;
|
||||
const uploadStream = fs.createReadStream(filePath);
|
||||
uploadStream.filename = filename;
|
||||
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||||
uploadStream.fileSize = stat.size;
|
||||
|
||||
const uploadResult = await uploadService.uploadFile(uploadStream, {
|
||||
key: uploadKey,
|
||||
category: 'document',
|
||||
mimetype: 'xls,xlsx,csv',
|
||||
});
|
||||
|
||||
let fileRecord = null;
|
||||
if (typeof uploadService.uploadSuccessNotify === 'function') {
|
||||
fileRecord = await uploadService.uploadSuccessNotify({
|
||||
url: uploadResult.fileName,
|
||||
fileKey: uploadResult.fileName,
|
||||
fileName: filename,
|
||||
fileType: 'document',
|
||||
mimeType: uploadStream.mimeType,
|
||||
fileSize: stat.size,
|
||||
userId: ctx.userId,
|
||||
description: `收货单导出(货主${storeId}),共${totalCount}条收货单`,
|
||||
});
|
||||
}
|
||||
|
||||
// 清理临时文件
|
||||
try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ }
|
||||
|
||||
const uploadInfo = fileRecord || uploadResult;
|
||||
const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url
|
||||
? uploadInfo.url
|
||||
: (typeof uploadResult === 'object' ? uploadResult.fileName : '');
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: 100,
|
||||
message: '导出完成',
|
||||
result: { url: fileUrl, fileKey: uploadKey, total: totalCount },
|
||||
});
|
||||
|
||||
return {
|
||||
url: fileUrl,
|
||||
fileKey: uploadKey,
|
||||
total: totalCount,
|
||||
totalDetails: allReceivingIds.reduce((sum, rid) => sum + (detailsMap.get(rid) || []).length, 0),
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = ReceivingService;
|
||||
|
||||
@ -353,7 +353,7 @@ class StorageReportService extends Service {
|
||||
if (normalizedStockIds.length > 0) {
|
||||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||||
normalizedStockIds,
|
||||
{}
|
||||
{ warehouseId } // store 模式下为 null → 跳过 warehouse 过滤
|
||||
);
|
||||
for (const detail of stockDetails) {
|
||||
const sid = Number(detail.id);
|
||||
@ -515,11 +515,15 @@ class StorageReportService extends Service {
|
||||
* @param {string} [sort.sortField] 排序字段
|
||||
* @param {string} [sort.sortOrder] 排序顺序
|
||||
* @param {string} [exportMode] 导出模式:'item' 导出全部(含锁定),不传/其他值则排除锁定类型记录
|
||||
* @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度
|
||||
* @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤)
|
||||
* @param {string} [keyword=''] 商品关键字(模糊匹配)
|
||||
* @return {Promise<Object>} excel 上传结果
|
||||
*/
|
||||
async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '') {
|
||||
async export(startTime, endTime, bySpace = false, storeIds = [], sort = null, exportMode = '', searchMode = 'warehouse', stockIds = null, keyword = '') {
|
||||
const { ctx, app } = this;
|
||||
const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort);
|
||||
const isStoreMode = searchMode === 'store';
|
||||
const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort, searchMode, stockIds, keyword);
|
||||
if (!searchResult || searchResult.code !== 200) {
|
||||
return searchResult;
|
||||
}
|
||||
@ -527,15 +531,26 @@ class StorageReportService extends Service {
|
||||
const summaryList = Array.isArray(searchResult.data && searchResult.data.list)
|
||||
? searchResult.data.list
|
||||
: [];
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
const rawPrimaryId = Number(ctx.user && ctx.user.store_id);
|
||||
const storeId = isStoreMode ? rawPrimaryId : null;
|
||||
const warehouseId = isStoreMode ? null : rawPrimaryId;
|
||||
const startTimeMs = toTimeMs(startTime);
|
||||
const endTimeMs = toTimeMs(endTime);
|
||||
const normalizedStoreIds = normalizeStoreIds(storeIds);
|
||||
const isBySpace = normalizeBoolean(bySpace);
|
||||
|
||||
const whereClauses = [ 't.warehouse_id = :warehouseId' ];
|
||||
// 主维度:仓库模式用 warehouse_id,货主模式用 store_id
|
||||
const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id';
|
||||
const primaryDimVal = isStoreMode ? storeId : warehouseId;
|
||||
const primaryDimAlias = isStoreMode ? 'storeId' : 'warehouseId';
|
||||
// 辅助维度:仓库模式用 store_id(货主过滤),货主模式用 warehouse_id(仓库过滤)
|
||||
const secondaryIds = normalizedStoreIds;
|
||||
const secondaryDimCol = isStoreMode ? 'warehouse_id' : 'store_id';
|
||||
const secondaryDimAlias = isStoreMode ? 'warehouseIds' : 'storeIds';
|
||||
|
||||
const whereClauses = [ `t.${primaryDimCol} = :${primaryDimAlias}` ];
|
||||
const replacements = {
|
||||
warehouseId,
|
||||
[primaryDimAlias]: primaryDimVal,
|
||||
};
|
||||
|
||||
if (startTimeMs !== null) {
|
||||
@ -548,9 +563,9 @@ class StorageReportService extends Service {
|
||||
replacements.endTime = endTime;
|
||||
}
|
||||
|
||||
if (normalizedStoreIds.length > 0) {
|
||||
whereClauses.push('t.store_id IN (:storeIds)');
|
||||
replacements.storeIds = normalizedStoreIds;
|
||||
if (secondaryIds.length > 0) {
|
||||
whereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||||
replacements[secondaryDimAlias] = secondaryIds;
|
||||
}
|
||||
|
||||
const normalizedExportMode = String(exportMode || '').trim();
|
||||
@ -623,6 +638,8 @@ class StorageReportService extends Service {
|
||||
{ header: '结束时间', key: 'end_time' },
|
||||
{ header: '货主ID', key: 'store_id' },
|
||||
{ header: '货主名称', key: 'store_name' },
|
||||
{ header: '仓库ID', key: 'warehouse_id' },
|
||||
{ header: '仓库名称', key: 'warehouse_name' },
|
||||
{ header: '商品库存ID', key: 'stock_id' },
|
||||
{ header: '商品编码', key: 'item_code' },
|
||||
{ header: '商品名称', key: 'item_name' },
|
||||
@ -644,6 +661,8 @@ class StorageReportService extends Service {
|
||||
end_time: item.end_time || '',
|
||||
store_id: toNumber(item.store_id),
|
||||
store_name: item.store_name || '',
|
||||
warehouse_id: toNumber(item.warehouse_id),
|
||||
warehouse_name: item.warehouse_name || '',
|
||||
stock_id: toNumber(item.stock_id),
|
||||
item_code: item.item_code || '',
|
||||
item_name: item.item_name || '',
|
||||
@ -663,10 +682,8 @@ class StorageReportService extends Service {
|
||||
const detailSheetRows = safeDetailRows.map(item => {
|
||||
const stockId = toNumber(item.stock_id);
|
||||
const storeId = toNumber(item.store_id);
|
||||
const spaceId = toNumber(item.space_id);
|
||||
const stock = maps.stockMap.get(stockId) || {};
|
||||
const store = maps.storeMap.get(storeId) || {};
|
||||
const space = maps.spaceMap.get(spaceId) || {};
|
||||
const barcodeSet = maps.barcodeMap.get(stockId);
|
||||
|
||||
const entryOrderId = toNumber(item.entry_order_id);
|
||||
@ -691,8 +708,6 @@ class StorageReportService extends Service {
|
||||
item_code: stock.item_code || '',
|
||||
item_name: stock.item_name || '',
|
||||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||||
space_id: spaceId,
|
||||
space_name: space.custom_name || space.space_code || '',
|
||||
quantity: toNumber(item.quantity),
|
||||
before_quantity: toNumber(item.before_quantity),
|
||||
after_quantity: toNumber(item.after_quantity),
|
||||
@ -725,8 +740,6 @@ class StorageReportService extends Service {
|
||||
{ header: '商品编码', key: 'item_code' },
|
||||
{ header: '商品名称', key: 'item_name' },
|
||||
{ header: '条码', key: 'barcode' },
|
||||
{ header: '库位ID', key: 'space_id' },
|
||||
{ header: '库位名称', key: 'space_name' },
|
||||
{ header: '变动数量', key: 'quantity' },
|
||||
{ header: '变更前库存', key: 'before_quantity' },
|
||||
{ header: '变更后库存', key: 'after_quantity' },
|
||||
@ -750,7 +763,7 @@ class StorageReportService extends Service {
|
||||
|
||||
return await ctx.service.systems.excel.generateAndUpload({
|
||||
filename: this.buildExportFilename(startTime, endTime),
|
||||
dir: `exports/storage/report/${warehouseId || 'common'}`,
|
||||
dir: `exports/storage/report/${warehouseId || storeId || 'common'}`,
|
||||
category: 'document',
|
||||
sheets: [
|
||||
{
|
||||
@ -767,6 +780,66 @@ class StorageReportService extends Service {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据关键字解析匹配的 stock_id 列表。
|
||||
* 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、条码(barcode)模糊匹配。
|
||||
* @param {string} keyword 搜索关键字
|
||||
* @param {string} primaryDimCol 主维度列名(warehouse_id 或 store_id)
|
||||
* @param {number} primaryDimVal 主维度值
|
||||
* @return {Promise<number[]>} 匹配的 stock_id 列表
|
||||
*/
|
||||
async _resolveKeywordToStockIds(keyword, primaryDimCol, primaryDimVal) {
|
||||
const { ctx, app } = this;
|
||||
const normalizedKeyword = String(keyword || '').trim();
|
||||
if (!normalizedKeyword) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const likePattern = `%${normalizedKeyword}%`;
|
||||
// 如果 keyword 为纯数字,同时支持按 stock_id(SKU ID)精确匹配
|
||||
const exactStockId = /^\d+$/.test(normalizedKeyword) ? Number(normalizedKeyword) : null;
|
||||
|
||||
// 从 wms_stock_warehouse 按 item_code / item_name / goods_code / id(SKU) 模糊匹配
|
||||
const extraIdCondition = exactStockId !== null ? 'OR sw.id = :exactStockId' : '';
|
||||
const stockRows = await ctx.model.query(`
|
||||
SELECT DISTINCT sw.id AS stock_id
|
||||
FROM wms_stock_warehouse sw
|
||||
WHERE sw.${primaryDimCol} = :primaryDimVal
|
||||
AND (
|
||||
sw.item_code LIKE :keyword
|
||||
OR sw.item_name LIKE :keyword
|
||||
OR sw.goods_code LIKE :keyword
|
||||
${extraIdCondition}
|
||||
)
|
||||
`, {
|
||||
replacements: { primaryDimVal, keyword: likePattern, exactStockId },
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
});
|
||||
|
||||
// 从 wms_stock_barcodes 按 barcode 模糊匹配
|
||||
const barcodeRows = await ctx.model.query(`
|
||||
SELECT DISTINCT sb.stock_id
|
||||
FROM wms_stock_barcodes sb
|
||||
INNER JOIN wms_stock_warehouse sw ON sw.id = sb.stock_id AND sw.${primaryDimCol} = :primaryDimVal
|
||||
WHERE sb.barcode LIKE :keyword
|
||||
`, {
|
||||
replacements: { primaryDimVal, keyword: likePattern },
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
});
|
||||
|
||||
const stockIdSet = new Set();
|
||||
for (const row of stockRows) {
|
||||
const sid = Number(row.stock_id);
|
||||
if (sid > 0) stockIdSet.add(sid);
|
||||
}
|
||||
for (const row of barcodeRows) {
|
||||
const sid = Number(row.stock_id);
|
||||
if (sid > 0) stockIdSet.add(sid);
|
||||
}
|
||||
|
||||
return [ ...stockIdSet ];
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询库存流水统计报表。
|
||||
* 规则:
|
||||
@ -779,22 +852,46 @@ class StorageReportService extends Service {
|
||||
* @param {string|Date|null} startTime 开始时间(闭区间下限)
|
||||
* @param {string|Date|null} endTime 结束时间(闭区间上限)
|
||||
* @param {boolean|string|number} [bySpace=false] 是否按库位返回
|
||||
* @param {Array<number|string>|number|string|null} [storeIds=[]] 货主ID列表
|
||||
* @param {Array<number|string>|number|string|null} [storeIds=[]] 货主ID列表(store模式为仓库ID列表)
|
||||
* @param {Object} [sort] 排序参数
|
||||
* @param {string} [sort.sortField] 排序字段(begin_total、inbound_total、outbound_total、end_total)
|
||||
* @param {string} [sort.sortOrder] 排序顺序(ASC、DESC,大小写不敏感)
|
||||
* @param {string} [searchMode='warehouse'] 查询维度:'warehouse' 按仓库维度(默认),'store' 按货主维度
|
||||
* @param {number[]} [stockIds=null] 商品库存ID列表(精确过滤),与 keyword 互斥
|
||||
* @param {string} [keyword=''] 商品关键字(按 item_code/item_name/goods_code/barcode 模糊匹配),与 stockIds 互斥
|
||||
* @return {Promise<Object>} code/data/message 结构
|
||||
*/
|
||||
async search(startTime, endTime, bySpace = false, storeIds = [], sort = null) {
|
||||
async search(startTime, endTime, bySpace = false, storeIds = [], sort = null, searchMode = 'warehouse', stockIds = null, keyword = '') {
|
||||
const { ctx, app } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
if (!warehouseId) {
|
||||
const isStoreMode = searchMode === 'store';
|
||||
const rawPrimaryId = Number(ctx.user && ctx.user.store_id);
|
||||
const storeId = isStoreMode ? rawPrimaryId : null;
|
||||
const warehouseId = isStoreMode ? null : rawPrimaryId;
|
||||
|
||||
if (!isStoreMode && !warehouseId) {
|
||||
return {
|
||||
code: 400,
|
||||
message: '用户未绑定仓库',
|
||||
data: { list: [] },
|
||||
};
|
||||
}
|
||||
if (isStoreMode && !storeId) {
|
||||
return {
|
||||
code: 400,
|
||||
message: '用户未绑定货主',
|
||||
data: { list: [] },
|
||||
};
|
||||
}
|
||||
|
||||
// 主维度:仓库模式用 warehouse_id,货主模式用 store_id
|
||||
const primaryDimCol = isStoreMode ? 'store_id' : 'warehouse_id';
|
||||
const primaryDimVal = isStoreMode ? storeId : warehouseId;
|
||||
const primaryDimAlias = isStoreMode ? 'storeId' : 'warehouseId';
|
||||
|
||||
// 辅助维度:仓库模式用 store_id(货主过滤),货主模式用 warehouse_id(仓库过滤)
|
||||
const secondaryIds = normalizeStoreIds(storeIds);
|
||||
const secondaryDimCol = isStoreMode ? 'warehouse_id' : 'store_id';
|
||||
const secondaryDimAlias = isStoreMode ? 'warehouseIds' : 'storeIds';
|
||||
|
||||
const startTimeMs = toTimeMs(startTime);
|
||||
const endTimeMs = toTimeMs(endTime);
|
||||
@ -824,25 +921,51 @@ class StorageReportService extends Service {
|
||||
}
|
||||
|
||||
const isBySpace = normalizeBoolean(bySpace);
|
||||
const normalizedStoreIds = normalizeStoreIds(storeIds);
|
||||
|
||||
// 归一化 stock_ids:优先使用 keyword 解析,其次使用显式传入的 stockIds
|
||||
let resolvedStockIds = null;
|
||||
const normalizedKeyword = String(keyword || '').trim();
|
||||
if (normalizedKeyword) {
|
||||
resolvedStockIds = await this._resolveKeywordToStockIds(normalizedKeyword, primaryDimCol, primaryDimVal);
|
||||
if (resolvedStockIds.length === 0) {
|
||||
return {
|
||||
code: 200,
|
||||
message: '查询成功',
|
||||
data: { list: [] },
|
||||
};
|
||||
}
|
||||
} else if (stockIds !== null && stockIds !== undefined) {
|
||||
const rawIds = Array.isArray(stockIds) ? stockIds : [ stockIds ];
|
||||
resolvedStockIds = [ ...new Set(
|
||||
rawIds.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)
|
||||
) ];
|
||||
if (resolvedStockIds.length === 0) {
|
||||
return {
|
||||
code: 200,
|
||||
message: '查询成功',
|
||||
data: { list: [] },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let baseStockRows = [];
|
||||
let baseStorageRows = [];
|
||||
if (!isBySpace) {
|
||||
const baseWhereClauses = [ 'sw.warehouse_id = :warehouseId' ];
|
||||
const baseWhereClauses = [ `sw.${primaryDimCol} = :${primaryDimAlias}` ];
|
||||
const baseReplacements = {
|
||||
warehouseId,
|
||||
[primaryDimAlias]: primaryDimVal,
|
||||
};
|
||||
|
||||
if (normalizedStoreIds.length > 0) {
|
||||
baseWhereClauses.push('sw.store_id IN (:storeIds)');
|
||||
baseReplacements.storeIds = normalizedStoreIds;
|
||||
if (secondaryIds.length > 0) {
|
||||
baseWhereClauses.push(`sw.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||||
baseReplacements[secondaryDimAlias] = secondaryIds;
|
||||
}
|
||||
|
||||
baseStockRows = await ctx.model.query(`
|
||||
SELECT
|
||||
sw.id AS stock_id,
|
||||
sw.store_id,
|
||||
sw.warehouse_id,
|
||||
sw.quantity
|
||||
FROM wms_stock_warehouse sw
|
||||
WHERE ${baseWhereClauses.join(' AND ')}
|
||||
@ -851,6 +974,12 @@ class StorageReportService extends Service {
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
});
|
||||
|
||||
// 如果指定了 stock_id 过滤,仅保留匹配的 stock 行
|
||||
if (resolvedStockIds !== null) {
|
||||
const stockIdSet = new Set(resolvedStockIds);
|
||||
baseStockRows = baseStockRows.filter(row => stockIdSet.has(Number(row.stock_id)));
|
||||
}
|
||||
|
||||
if (!Array.isArray(baseStockRows) || baseStockRows.length === 0) {
|
||||
return {
|
||||
code: 200,
|
||||
@ -859,14 +988,14 @@ class StorageReportService extends Service {
|
||||
};
|
||||
}
|
||||
} else {
|
||||
const baseWhereClauses = [ 's.warehouse_id = :warehouseId', 's.delete_at IS NULL' ];
|
||||
const baseWhereClauses = [ `s.${primaryDimCol} = :${primaryDimAlias}`, 's.delete_at IS NULL' ];
|
||||
const baseReplacements = {
|
||||
warehouseId,
|
||||
[primaryDimAlias]: primaryDimVal,
|
||||
};
|
||||
|
||||
if (normalizedStoreIds.length > 0) {
|
||||
baseWhereClauses.push('s.store_id IN (:storeIds)');
|
||||
baseReplacements.storeIds = normalizedStoreIds;
|
||||
if (secondaryIds.length > 0) {
|
||||
baseWhereClauses.push(`s.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||||
baseReplacements[secondaryDimAlias] = secondaryIds;
|
||||
}
|
||||
|
||||
baseStorageRows = await ctx.model.query(`
|
||||
@ -874,21 +1003,28 @@ class StorageReportService extends Service {
|
||||
s.stock_id,
|
||||
COALESCE(s.space_id, 0) AS space_id,
|
||||
s.store_id,
|
||||
s.warehouse_id,
|
||||
SUM(s.quantity) AS quantity
|
||||
FROM wms_storage s
|
||||
WHERE ${baseWhereClauses.join(' AND ')}
|
||||
GROUP BY s.stock_id, COALESCE(s.space_id, 0), s.store_id
|
||||
GROUP BY s.stock_id, COALESCE(s.space_id, 0), s.store_id, s.warehouse_id
|
||||
`, {
|
||||
replacements: baseReplacements,
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
});
|
||||
|
||||
// 如果指定了 stock_id 过滤,仅保留匹配的 stock 行
|
||||
if (resolvedStockIds !== null) {
|
||||
const stockIdSet = new Set(resolvedStockIds);
|
||||
baseStorageRows = baseStorageRows.filter(row => stockIdSet.has(Number(row.stock_id)));
|
||||
}
|
||||
|
||||
baseStorageRows = Array.isArray(baseStorageRows) ? baseStorageRows : [];
|
||||
}
|
||||
|
||||
const rangeWhereClauses = [ 't.warehouse_id = :warehouseId' ];
|
||||
const rangeWhereClauses = [ `t.${primaryDimCol} = :${primaryDimAlias}` ];
|
||||
const rangeReplacements = {
|
||||
warehouseId,
|
||||
[primaryDimAlias]: primaryDimVal,
|
||||
};
|
||||
|
||||
if (startTimeMs !== null) {
|
||||
@ -901,9 +1037,9 @@ class StorageReportService extends Service {
|
||||
rangeReplacements.endTime = endTime;
|
||||
}
|
||||
|
||||
if (normalizedStoreIds.length > 0) {
|
||||
rangeWhereClauses.push('t.store_id IN (:storeIds)');
|
||||
rangeReplacements.storeIds = normalizedStoreIds;
|
||||
if (secondaryIds.length > 0) {
|
||||
rangeWhereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||||
rangeReplacements[secondaryDimAlias] = secondaryIds;
|
||||
}
|
||||
|
||||
if (!isBySpace) {
|
||||
@ -963,17 +1099,17 @@ class StorageReportService extends Service {
|
||||
let preStartSnapshotRows = [];
|
||||
if (startTimeMs !== null) {
|
||||
const preStartWhereClauses = [
|
||||
't.warehouse_id = :warehouseId',
|
||||
`t.${primaryDimCol} = :${primaryDimAlias}`,
|
||||
't.created_at < :startTime',
|
||||
];
|
||||
const preStartReplacements = {
|
||||
warehouseId,
|
||||
[primaryDimAlias]: primaryDimVal,
|
||||
startTime,
|
||||
};
|
||||
|
||||
if (normalizedStoreIds.length > 0) {
|
||||
preStartWhereClauses.push('t.store_id IN (:storeIds)');
|
||||
preStartReplacements.storeIds = normalizedStoreIds;
|
||||
if (secondaryIds.length > 0) {
|
||||
preStartWhereClauses.push(`t.${secondaryDimCol} IN (:${secondaryDimAlias})`);
|
||||
preStartReplacements[secondaryDimAlias] = secondaryIds;
|
||||
}
|
||||
|
||||
if (!isBySpace) {
|
||||
@ -1039,6 +1175,7 @@ class StorageReportService extends Service {
|
||||
.map(row => {
|
||||
const stockId = Number(row.stock_id);
|
||||
const storeId = Number(row.store_id);
|
||||
const whId = Number(row.warehouse_id) || 0;
|
||||
const stockStoreKey = `${stockId}_${storeId}`;
|
||||
const snapshot = edgeByStockStore.get(stockStoreKey);
|
||||
const rangeSum = rangeSumByStockStore.get(stockStoreKey);
|
||||
@ -1059,11 +1196,13 @@ class StorageReportService extends Service {
|
||||
end_time: endTime || null,
|
||||
stock_id: stockId,
|
||||
store_id: storeId,
|
||||
warehouse_id: whId,
|
||||
begin_total: beginTotal,
|
||||
end_total: endTotal,
|
||||
inbound_total: toNumber(rangeSum && rangeSum.inbound_total),
|
||||
outbound_total: toNumber(rangeSum && rangeSum.outbound_total),
|
||||
store_name: '',
|
||||
warehouse_name: '',
|
||||
item_name: '',
|
||||
barcode: '',
|
||||
item_code: '',
|
||||
@ -1071,16 +1210,19 @@ class StorageReportService extends Service {
|
||||
})
|
||||
.filter(item => item.stock_id > 0 && item.store_id > 0);
|
||||
|
||||
const stockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
|
||||
const groupedStockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
|
||||
const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ];
|
||||
const warehouseIdList = [ ...new Set(groupedList.map(item => item.warehouse_id).filter(Boolean)) ];
|
||||
|
||||
// 复用 getStockDetails 获取商品名称和条码
|
||||
// store 模式下不传 warehouseId,避免用 store_id 误当 warehouse_id 过滤导致查不到商品
|
||||
const stockDetailOpts = isStoreMode ? { warehouseId: null } : {};
|
||||
const stockMap = new Map();
|
||||
const barcodesByStock = new Map();
|
||||
if (stockIds.length > 0) {
|
||||
if (groupedStockIds.length > 0) {
|
||||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||||
stockIds,
|
||||
{}
|
||||
groupedStockIds,
|
||||
stockDetailOpts
|
||||
);
|
||||
for (const detail of stockDetails) {
|
||||
const sid = Number(detail.id);
|
||||
@ -1115,15 +1257,29 @@ class StorageReportService extends Service {
|
||||
|
||||
const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ]));
|
||||
|
||||
const warehouseRows = warehouseIdList.length > 0
|
||||
? await ctx.model.Store.findAll({
|
||||
where: {
|
||||
id: warehouseIdList,
|
||||
},
|
||||
attributes: [ 'id', 'company_name' ],
|
||||
raw: true,
|
||||
})
|
||||
: [];
|
||||
|
||||
const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ]));
|
||||
|
||||
const list = groupedList
|
||||
.map(item => {
|
||||
const stock = stockMap.get(item.stock_id) || {};
|
||||
const store = storeMap.get(item.store_id) || {};
|
||||
const warehouse = warehouseMap.get(item.warehouse_id) || {};
|
||||
const barcodeSet = barcodesByStock.get(item.stock_id);
|
||||
|
||||
return {
|
||||
...item,
|
||||
store_name: store.company_name || '',
|
||||
warehouse_name: warehouse.company_name || '',
|
||||
item_name: stock.item_name || '',
|
||||
item_code: stock.item_code || '',
|
||||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||||
@ -1146,6 +1302,7 @@ class StorageReportService extends Service {
|
||||
const stockId = Number(row.stock_id);
|
||||
const spaceId = Number(row.space_id) || 0;
|
||||
const storeId = Number(row.store_id);
|
||||
const whId = Number(row.warehouse_id) || 0;
|
||||
if (!stockId || !storeId) {
|
||||
continue;
|
||||
}
|
||||
@ -1155,6 +1312,7 @@ class StorageReportService extends Service {
|
||||
stock_id: stockId,
|
||||
space_id: spaceId,
|
||||
store_id: storeId,
|
||||
warehouse_id: whId,
|
||||
quantity: toNumber(row.quantity),
|
||||
});
|
||||
}
|
||||
@ -1163,6 +1321,7 @@ class StorageReportService extends Service {
|
||||
const stockId = Number(row.stock_id);
|
||||
const spaceId = Number(row.space_id) || 0;
|
||||
const storeId = Number(row.store_id);
|
||||
const whId = Number(row.warehouse_id) || 0;
|
||||
if (!stockId || !storeId) {
|
||||
continue;
|
||||
}
|
||||
@ -1173,6 +1332,7 @@ class StorageReportService extends Service {
|
||||
stock_id: stockId,
|
||||
space_id: spaceId,
|
||||
store_id: storeId,
|
||||
warehouse_id: whId,
|
||||
quantity: 0,
|
||||
});
|
||||
}
|
||||
@ -1226,6 +1386,7 @@ class StorageReportService extends Service {
|
||||
const stockId = Number(row.stock_id);
|
||||
const spaceId = Number(row.space_id) || 0;
|
||||
const storeId = Number(row.store_id);
|
||||
const whId = Number(row.warehouse_id) || 0;
|
||||
const baseKey = `${stockId}_${spaceId}_${storeId}`;
|
||||
const snapshot = edgeByBaseKey.get(baseKey) || {
|
||||
begin_total: 0,
|
||||
@ -1247,12 +1408,14 @@ class StorageReportService extends Service {
|
||||
end_time: endTime || null,
|
||||
stock_id: stockId,
|
||||
store_id: storeId,
|
||||
warehouse_id: whId,
|
||||
...(isBySpace ? { space_id: spaceId } : {}),
|
||||
begin_total: 0,
|
||||
end_total: 0,
|
||||
inbound_total: 0,
|
||||
outbound_total: 0,
|
||||
store_name: '',
|
||||
warehouse_name: '',
|
||||
item_name: '',
|
||||
barcode: '',
|
||||
item_code: '',
|
||||
@ -1274,19 +1437,22 @@ class StorageReportService extends Service {
|
||||
}
|
||||
|
||||
const groupedList = [ ...groupedMap.values() ];
|
||||
const stockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
|
||||
const groupedStockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ];
|
||||
const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ];
|
||||
const warehouseIdList = [ ...new Set(groupedList.map(item => item.warehouse_id).filter(Boolean)) ];
|
||||
const spaceIds = isBySpace
|
||||
? [ ...new Set(groupedList.map(item => item.space_id).filter(id => Number(id) > 0)) ]
|
||||
: [];
|
||||
|
||||
// 复用 getStockDetails 获取商品名称和条码
|
||||
// store 模式下不传 warehouseId,避免用 store_id 误当 warehouse_id 过滤导致查不到商品
|
||||
const stockDetailOptsSpace = isStoreMode ? { warehouseId: null } : {};
|
||||
const stockMap = new Map();
|
||||
const barcodesByStock = new Map();
|
||||
if (stockIds.length > 0) {
|
||||
if (groupedStockIds.length > 0) {
|
||||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||||
stockIds,
|
||||
{}
|
||||
groupedStockIds,
|
||||
stockDetailOptsSpace
|
||||
);
|
||||
for (const detail of stockDetails) {
|
||||
const sid = Number(detail.id);
|
||||
@ -1309,7 +1475,7 @@ class StorageReportService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
const [ storeRows, spaceRows ] = await Promise.all([
|
||||
const [ storeRows, spaceRows, warehouseRows ] = await Promise.all([
|
||||
storeIdList.length > 0
|
||||
? ctx.model.Store.findAll({
|
||||
where: {
|
||||
@ -1328,21 +1494,33 @@ class StorageReportService extends Service {
|
||||
raw: true,
|
||||
})
|
||||
: [],
|
||||
warehouseIdList.length > 0
|
||||
? ctx.model.Store.findAll({
|
||||
where: {
|
||||
id: warehouseIdList,
|
||||
},
|
||||
attributes: [ 'id', 'company_name' ],
|
||||
raw: true,
|
||||
})
|
||||
: [],
|
||||
]);
|
||||
|
||||
const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ]));
|
||||
const spaceMap = new Map(spaceRows.map(item => [ Number(item.id), item ]));
|
||||
const warehouseMap = new Map(warehouseRows.map(item => [ Number(item.id), item ]));
|
||||
|
||||
const list = groupedList
|
||||
.map(item => {
|
||||
const stock = stockMap.get(item.stock_id) || {};
|
||||
const store = storeMap.get(item.store_id) || {};
|
||||
const warehouse = warehouseMap.get(item.warehouse_id) || {};
|
||||
const barcodeSet = barcodesByStock.get(item.stock_id);
|
||||
const space = isBySpace ? (spaceMap.get(Number(item.space_id)) || {}) : null;
|
||||
|
||||
const merged = {
|
||||
...item,
|
||||
store_name: store.company_name || '',
|
||||
warehouse_name: warehouse.company_name || '',
|
||||
item_name: stock.item_name || '',
|
||||
item_code: stock.item_code || '',
|
||||
barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '',
|
||||
|
||||
@ -948,24 +948,62 @@ class StoreService extends Service {
|
||||
const { ctx } = this;
|
||||
|
||||
try {
|
||||
const stores = await ctx.model.StoreWarehouse.findAll({
|
||||
const rows = await ctx.model.StoreWarehouse.findAll({
|
||||
where: {
|
||||
warehouse_use_status: 1,
|
||||
warehouse_id: ctx.user.store_id,
|
||||
},
|
||||
attributes: [
|
||||
[ 'store_id', 'value' ], // store_id 字段别名为 value
|
||||
[ 'store_remask', 'label' ], // store_remask 字段别名为 label
|
||||
attributes: [ 'store_id', 'store_remask' ],
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Store,
|
||||
as: 'store',
|
||||
attributes: [ 'company_name' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
raw: true, // 可选:返回纯JSON数据
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return stores;
|
||||
return rows.map(row => ({
|
||||
value: row.store_id,
|
||||
label: row.store_remask || (row['store.company_name'] || ''),
|
||||
}));
|
||||
} catch (error) {
|
||||
ctx.logger.error('[Service.loadStores] 查询失败:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async loadWarehouses() {
|
||||
const { ctx } = this;
|
||||
|
||||
try {
|
||||
const rows = await ctx.model.StoreWarehouse.findAll({
|
||||
where: {
|
||||
store_use_status: 1,
|
||||
store_id: ctx.user.store_id,
|
||||
},
|
||||
attributes: [ 'warehouse_id', 'warehouse_remask' ],
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Store,
|
||||
as: 'warehouse',
|
||||
attributes: [ 'company_name' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return rows.map(row => ({
|
||||
value: row.warehouse_id,
|
||||
label: row.warehouse_remask || (row['warehouse.company_name'] || ''),
|
||||
}));
|
||||
} catch (error) {
|
||||
ctx.logger.error('[Service.loadWarehouses] 查询失败:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = StoreService;
|
||||
|
||||
@ -1,6 +1,11 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('node:crypto');
|
||||
const fs = require('node:fs');
|
||||
const fsp = require('node:fs/promises');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const ExcelJS = require('exceljs');
|
||||
const Service = require('egg').Service;
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
@ -1448,12 +1453,9 @@ class SettingStoreWarehouseService extends Service {
|
||||
const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200);
|
||||
const offset = (page - 1) * pageSize;
|
||||
|
||||
// OR 查询两边,兼容新旧签约数据
|
||||
// 仓库查看自己签约的货主列表:仓库在 warehouse_id 方,货主在 store_id 方
|
||||
const where = {
|
||||
[Op.or]: [
|
||||
{ store_id: currentSubject.id },
|
||||
{ warehouse_id: currentSubject.id },
|
||||
],
|
||||
warehouse_id: currentSubject.id,
|
||||
};
|
||||
|
||||
const relationId = this.resolveRelationId(data);
|
||||
@ -1461,16 +1463,10 @@ class SettingStoreWarehouseService extends Service {
|
||||
where.id = relationId;
|
||||
}
|
||||
|
||||
const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true });
|
||||
const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.store_id, 'counterparty_id', { allowEmpty: true });
|
||||
if (counterpartyId) {
|
||||
// 对方可能在 store_id 或 warehouse_id,两边都过滤
|
||||
where[Op.and] = where[Op.and] || [];
|
||||
where[Op.and].push({
|
||||
[Op.or]: [
|
||||
{ store_id: counterpartyId, warehouse_id: currentSubject.id },
|
||||
{ warehouse_id: counterpartyId, store_id: currentSubject.id },
|
||||
],
|
||||
});
|
||||
// 对方(货主)在 store_id 方
|
||||
where.store_id = counterpartyId;
|
||||
}
|
||||
|
||||
const authStatus = this.normalizeAuthStatus(data.auth_status);
|
||||
@ -1478,16 +1474,9 @@ class SettingStoreWarehouseService extends Service {
|
||||
where.auth_status = authStatus;
|
||||
}
|
||||
|
||||
const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status;
|
||||
const rawUseStatus = data.use_status !== undefined ? data.use_status : data.warehouse_use_status;
|
||||
if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') {
|
||||
// 同时过滤 store_use_status 和 warehouse_use_status
|
||||
where[Op.and] = where[Op.and] || [];
|
||||
where[Op.and].push({
|
||||
[Op.or]: [
|
||||
{ store_use_status: Number(rawUseStatus), store_id: currentSubject.id },
|
||||
{ warehouse_use_status: Number(rawUseStatus), warehouse_id: currentSubject.id },
|
||||
],
|
||||
});
|
||||
where.warehouse_use_status = Number(rawUseStatus);
|
||||
}
|
||||
|
||||
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
|
||||
@ -1568,12 +1557,9 @@ class SettingStoreWarehouseService extends Service {
|
||||
const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200);
|
||||
const offset = (page - 1) * pageSize;
|
||||
|
||||
// OR 查询两边,兼容新旧签约数据
|
||||
// 货主查看自己签约的仓库列表:货主在 store_id 方,仓库在 warehouse_id 方
|
||||
const where = {
|
||||
[Op.or]: [
|
||||
{ store_id: currentSubject.id },
|
||||
{ warehouse_id: currentSubject.id },
|
||||
],
|
||||
store_id: currentSubject.id,
|
||||
};
|
||||
|
||||
const relationId = this.resolveRelationId(data);
|
||||
@ -1583,14 +1569,8 @@ class SettingStoreWarehouseService extends Service {
|
||||
|
||||
const counterpartyId = this.toPositiveNumber(data.counterparty_id || data.warehouse_id, 'counterparty_id', { allowEmpty: true });
|
||||
if (counterpartyId) {
|
||||
// 对方可能在 store_id 或 warehouse_id,两边都过滤
|
||||
where[Op.and] = where[Op.and] || [];
|
||||
where[Op.and].push({
|
||||
[Op.or]: [
|
||||
{ store_id: counterpartyId, warehouse_id: currentSubject.id },
|
||||
{ warehouse_id: counterpartyId, store_id: currentSubject.id },
|
||||
],
|
||||
});
|
||||
// 对方(仓库)在 warehouse_id 方
|
||||
where.warehouse_id = counterpartyId;
|
||||
}
|
||||
|
||||
const authStatus = this.normalizeAuthStatus(data.auth_status);
|
||||
@ -1600,14 +1580,7 @@ class SettingStoreWarehouseService extends Service {
|
||||
|
||||
const rawUseStatus = data.use_status !== undefined ? data.use_status : data.store_use_status;
|
||||
if (rawUseStatus !== undefined && rawUseStatus !== null && rawUseStatus !== '') {
|
||||
// 同时过滤 store_use_status 和 warehouse_use_status
|
||||
where[Op.and] = where[Op.and] || [];
|
||||
where[Op.and].push({
|
||||
[Op.or]: [
|
||||
{ store_use_status: Number(rawUseStatus), store_id: currentSubject.id },
|
||||
{ warehouse_use_status: Number(rawUseStatus), warehouse_id: currentSubject.id },
|
||||
],
|
||||
});
|
||||
where.store_use_status = Number(rawUseStatus);
|
||||
}
|
||||
|
||||
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
|
||||
@ -2213,6 +2186,34 @@ class SettingStoreWarehouseService extends Service {
|
||||
limit: pageSize,
|
||||
});
|
||||
|
||||
// 收集所有需要回填姓名的操作人 ID
|
||||
const accountIdSet = new Set();
|
||||
for (const item of rows) {
|
||||
const payload = item && typeof item.get === 'function'
|
||||
? item.get({ plain: true })
|
||||
: (item || {});
|
||||
if (payload.operator_id) accountIdSet.add(Number(payload.operator_id));
|
||||
if (payload.created_by) accountIdSet.add(Number(payload.created_by));
|
||||
}
|
||||
const accountIds = Array.from(accountIdSet).filter(id => Number.isFinite(id) && id > 0);
|
||||
|
||||
// 批量查询账号姓名
|
||||
let accountNameMap = {};
|
||||
if (accountIds.length > 0) {
|
||||
try {
|
||||
const accounts = await ctx.model.Account.findAll({
|
||||
attributes: [ 'id', 'real_name' ],
|
||||
where: { id: { [Op.in]: accountIds } },
|
||||
raw: true,
|
||||
});
|
||||
for (const acc of accounts) {
|
||||
accountNameMap[Number(acc.id)] = acc.real_name || '';
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[queryPrintQuantityLogs] 批量查询操作人姓名失败,不影响主流程: %s', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
const total = Number(count || 0);
|
||||
const totalPages = total > 0 ? Math.ceil(total / pageSize) : 0;
|
||||
|
||||
@ -2224,6 +2225,13 @@ class SettingStoreWarehouseService extends Service {
|
||||
? item.get({ plain: true })
|
||||
: (item || {});
|
||||
|
||||
const operatorId = payload.operator_id !== undefined && payload.operator_id !== null
|
||||
? Number(payload.operator_id)
|
||||
: null;
|
||||
const createdBy = payload.created_by !== undefined && payload.created_by !== null
|
||||
? Number(payload.created_by)
|
||||
: null;
|
||||
|
||||
return {
|
||||
id: Number(payload.id || 0),
|
||||
contract_id: Number(payload.contract_id || 0),
|
||||
@ -2242,12 +2250,10 @@ class SettingStoreWarehouseService extends Service {
|
||||
balance_before: Number(payload.balance_before || 0),
|
||||
balance_after: Number(payload.balance_after || 0),
|
||||
reason: payload.reason || '',
|
||||
operator_id: payload.operator_id !== undefined && payload.operator_id !== null
|
||||
? Number(payload.operator_id)
|
||||
: null,
|
||||
created_by: payload.created_by !== undefined && payload.created_by !== null
|
||||
? Number(payload.created_by)
|
||||
: null,
|
||||
operator_id: operatorId,
|
||||
operator_name: operatorId ? (accountNameMap[operatorId] || '') : '',
|
||||
created_by: createdBy,
|
||||
created_by_name: createdBy ? (accountNameMap[createdBy] || '') : '',
|
||||
created_at: payload.created_at || null,
|
||||
updated_at: payload.updated_at || null,
|
||||
};
|
||||
@ -2264,6 +2270,182 @@ class SettingStoreWarehouseService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出面单余额变更日志。
|
||||
* 查询所有匹配条件的记录,生成 Excel 文件上传至 COS,返回下载信息。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {number|string} data.store_id 货主ID(必填)。
|
||||
* @param {Object} [data.where] 动态筛选条件,与 queryPrintQuantityLogs 的 where 语义一致。
|
||||
* @return {Promise<Object>} 包含 url、fileKey、filename 的对象。
|
||||
*/
|
||||
async exportPrintQuantityLogs(data = {}) {
|
||||
const { ctx } = this;
|
||||
const currentSubject = await this.getCurrentSubject();
|
||||
const storeId = this.toPositiveNumber(data.store_id, 'store_id');
|
||||
|
||||
if (!currentSubject.isWarehouse && Number(currentSubject.id) !== Number(storeId)) {
|
||||
throw this.createError('仅可导出当前货主的面单余额变更日志', 403);
|
||||
}
|
||||
|
||||
const where = {
|
||||
store_id: Number(storeId),
|
||||
};
|
||||
|
||||
if (currentSubject.isWarehouse) {
|
||||
where.warehouse_id = Number(currentSubject.id);
|
||||
}
|
||||
|
||||
const dynamicConditions = this.ctx.whereParsed && Array.isArray(this.ctx.whereParsed.dynamicConditions)
|
||||
? this.ctx.whereParsed.dynamicConditions.filter(Boolean)
|
||||
: [];
|
||||
|
||||
if (dynamicConditions.length > 0) {
|
||||
where[Op.and] = dynamicConditions;
|
||||
}
|
||||
|
||||
// 查询全部匹配记录
|
||||
const rows = await ctx.model.StoreWarehousePrintQuantityLog.findAll({
|
||||
where,
|
||||
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 收集操作人 ID,批量查询姓名
|
||||
const accountIdSet = new Set();
|
||||
for (const item of rows) {
|
||||
if (item.operator_id) accountIdSet.add(Number(item.operator_id));
|
||||
if (item.created_by) accountIdSet.add(Number(item.created_by));
|
||||
}
|
||||
const accountIds = Array.from(accountIdSet).filter(id => Number.isFinite(id) && id > 0);
|
||||
const accountNameMap = {};
|
||||
if (accountIds.length > 0) {
|
||||
const accounts = await ctx.model.Account.findAll({
|
||||
attributes: [ 'id', 'real_name' ],
|
||||
where: { id: { [Op.in]: accountIds } },
|
||||
raw: true,
|
||||
});
|
||||
for (const acc of accounts) {
|
||||
accountNameMap[Number(acc.id)] = acc.real_name || '';
|
||||
}
|
||||
}
|
||||
|
||||
// 生成 Excel
|
||||
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'print_qty_log_export_'));
|
||||
const filename = `面单余额变更日志_${storeId}_${Date.now()}.xlsx`;
|
||||
const filePath = path.join(tempDir, filename);
|
||||
|
||||
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
|
||||
filename: filePath,
|
||||
useStyles: true,
|
||||
useSharedStrings: true,
|
||||
});
|
||||
const worksheet = workbook.addWorksheet('面单余额变更日志');
|
||||
|
||||
worksheet.columns = [
|
||||
{ header: '记录ID', key: 'id', width: 10 },
|
||||
{ header: '签约关系ID', key: 'contract_id', width: 14 },
|
||||
{ header: '货主ID', key: 'store_id', width: 10 },
|
||||
{ header: '仓库ID', key: 'warehouse_id', width: 10 },
|
||||
{ header: '变更类型', key: 'change_type_label', width: 12 },
|
||||
{ header: '业务来源类型', key: 'business_type_label', width: 14 },
|
||||
{ header: '业务关联ID', key: 'business_id', width: 14 },
|
||||
{ header: '变更数量', key: 'change_quantity', width: 12 },
|
||||
{ header: '变更前余额', key: 'balance_before', width: 14 },
|
||||
{ header: '变更后余额', key: 'balance_after', width: 14 },
|
||||
{ header: '变更原因', key: 'reason', width: 30 },
|
||||
{ header: '操作人', key: 'operator_name', width: 14 },
|
||||
{ header: '创建人', key: 'created_by_name', width: 14 },
|
||||
{ header: '创建时间', key: 'created_at', width: 22 },
|
||||
{ header: '更新时间', key: 'updated_at', width: 22 },
|
||||
];
|
||||
|
||||
for (const item of rows) {
|
||||
const operatorId = item.operator_id !== undefined && item.operator_id !== null
|
||||
? Number(item.operator_id)
|
||||
: null;
|
||||
const createdBy = item.created_by !== undefined && item.created_by !== null
|
||||
? Number(item.created_by)
|
||||
: null;
|
||||
|
||||
worksheet.addRow({
|
||||
id: Number(item.id || 0),
|
||||
contract_id: Number(item.contract_id || 0),
|
||||
store_id: Number(item.store_id || 0),
|
||||
warehouse_id: Number(item.warehouse_id || 0),
|
||||
change_type_label: CHANGE_TYPE_LABEL_MAP[item.change_type] || item.change_type || '',
|
||||
business_type_label: item.business_type
|
||||
? (BUSINESS_TYPE_LABEL_MAP[item.business_type] || item.business_type)
|
||||
: '-',
|
||||
business_id: item.business_id !== undefined && item.business_id !== null
|
||||
? Number(item.business_id)
|
||||
: '',
|
||||
change_quantity: Number(item.change_quantity || 0),
|
||||
balance_before: Number(item.balance_before || 0),
|
||||
balance_after: Number(item.balance_after || 0),
|
||||
reason: item.reason || '',
|
||||
operator_name: operatorId ? (accountNameMap[operatorId] || '') : '',
|
||||
created_by_name: createdBy ? (accountNameMap[createdBy] || '') : '',
|
||||
created_at: item.created_at ? String(item.created_at) : '',
|
||||
updated_at: item.updated_at ? String(item.updated_at) : '',
|
||||
}).commit();
|
||||
}
|
||||
|
||||
worksheet.commit();
|
||||
await workbook.commit();
|
||||
|
||||
// 上传至 COS
|
||||
const uploadService = ctx.service && ctx.service.systems && ctx.service.systems.upload;
|
||||
let uploadResult = {};
|
||||
if (uploadService && typeof uploadService.uploadFile === 'function') {
|
||||
const stat = await fsp.stat(filePath);
|
||||
const uploadStream = fs.createReadStream(filePath);
|
||||
uploadStream.filename = filename;
|
||||
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||||
uploadStream.fileSize = stat.size;
|
||||
|
||||
uploadResult = await uploadService.uploadFile(uploadStream, {
|
||||
key: `export/print_quantity_log/${storeId}/${filename}`,
|
||||
category: 'document',
|
||||
mimetype: 'xls,xlsx,csv',
|
||||
});
|
||||
|
||||
if (typeof uploadService.uploadSuccessNotify === 'function') {
|
||||
await uploadService.uploadSuccessNotify({
|
||||
url: uploadResult.fileName,
|
||||
fileKey: uploadResult.fileName,
|
||||
fileName: filename,
|
||||
fileType: 'document',
|
||||
mimeType: uploadStream.mimeType,
|
||||
fileSize: stat.size,
|
||||
category: 'document',
|
||||
businessType: 'printQuantityLogExport',
|
||||
businessId: String(storeId),
|
||||
uploaderType: ctx.user?.role || 'system_api',
|
||||
uploaderDept: ctx.user?.department || '',
|
||||
}).catch(err => {
|
||||
ctx.logger.warn('[storeWarehouse.exportPrintQuantityLogs] 上传通知失败: %s', err.message);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 清理临时文件
|
||||
try {
|
||||
await fsp.rm(tempDir, { recursive: true, force: true });
|
||||
} catch (cleanErr) {
|
||||
ctx.logger.warn('[storeWarehouse.exportPrintQuantityLogs] 清理临时文件失败: %s', cleanErr.message);
|
||||
}
|
||||
|
||||
return {
|
||||
filename,
|
||||
fileKey: uploadResult.fileName || '',
|
||||
url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '',
|
||||
cdnUrl: uploadResult.cdnUrl || uploadResult.url || '',
|
||||
cosUrl: uploadResult.cosUrl || '',
|
||||
total_count: rows.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取策略配置字段。
|
||||
*
|
||||
@ -2465,12 +2647,15 @@ class SettingStoreWarehouseService extends Service {
|
||||
let qimenCustomerId = null;
|
||||
let qimenWarehouseCode = null;
|
||||
|
||||
// 外部入参优先,未传入时才从 qimen_app 表解析
|
||||
const externalCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100);
|
||||
|
||||
if (isQimenWms) {
|
||||
qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100);
|
||||
if (!qimenAppKey) {
|
||||
throw this.createError('奇门接口类型下 qimen_app_key 参数不能为空', 400);
|
||||
}
|
||||
qimenCustomerId = await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction });
|
||||
qimenCustomerId = externalCustomerId || await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction });
|
||||
qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100);
|
||||
if (!qimenWarehouseCode) {
|
||||
throw this.createError('奇门接口类型下 qimen_warehouse_code 参数不能为空', 400);
|
||||
@ -2478,9 +2663,8 @@ class SettingStoreWarehouseService extends Service {
|
||||
} else {
|
||||
// OPEN_API: 奇门字段可选输入
|
||||
qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100) || null;
|
||||
qimenCustomerId = qimenAppKey
|
||||
? await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction })
|
||||
: null;
|
||||
qimenCustomerId = externalCustomerId
|
||||
|| (qimenAppKey ? await this.resolveQimenCustomerIdByAppKey(qimenAppKey, { transaction }) : null);
|
||||
qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100) || null;
|
||||
}
|
||||
|
||||
|
||||
@ -26,11 +26,16 @@ class WaybillService extends MainService {
|
||||
this.throwError('运单号不能为空');
|
||||
}
|
||||
|
||||
const userWarehouseId = ctx.user && ctx.user.store_id ? ctx.user.store_id : null;
|
||||
const expressWhere = {
|
||||
waybill_code: String(waybillCode).trim(),
|
||||
status: 1,
|
||||
};
|
||||
if (userWarehouseId) {
|
||||
expressWhere.warehouse_id = userWarehouseId;
|
||||
}
|
||||
const record = await ctx.model.OrderExpress.findOne({
|
||||
where: {
|
||||
waybill_code: String(waybillCode).trim(),
|
||||
status: 1,
|
||||
},
|
||||
where: expressWhere,
|
||||
attributes: [ 'order_id', 'warehouse_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
1265
app/service/systems/workbench.js
Normal file
1265
app/service/systems/workbench.js
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为 wms_stock_transaction.transaction_type ENUM 增加 UNLOCK。
|
||||
* UNLOCK:库存释放流水(如取消订单释放创建锁)。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
await sequelize.query(`
|
||||
ALTER TABLE wms_stock_transaction
|
||||
MODIFY COLUMN transaction_type ENUM(
|
||||
'INBOUND', 'OUTBOUND', 'LOCK', 'UNLOCK'
|
||||
) NOT NULL COMMENT '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定 UNLOCK解锁'
|
||||
`);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
await sequelize.query(`
|
||||
ALTER TABLE wms_stock_transaction
|
||||
MODIFY COLUMN transaction_type ENUM(
|
||||
'INBOUND', 'OUTBOUND', 'LOCK'
|
||||
) NOT NULL COMMENT '出入库类型:INBOUND入库 OUTBOUND出库 LOCK锁定'
|
||||
`);
|
||||
},
|
||||
};
|
||||
163
database/migrations/20260712-add-store-receiving-permission.js
Normal file
163
database/migrations/20260712-add-store-receiving-permission.js
Normal file
@ -0,0 +1,163 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 货主侧收货单页面权限及 API 权限迁移。
|
||||
*
|
||||
* 变更内容:
|
||||
* 1. 新增 web_pages 权限:收货单(货主) — 货主平台侧收货单列表页面
|
||||
* 2. 新增 api 权限:account_platform.getStoreReceivingList — 货主侧收货单查询接口
|
||||
* 3. 将上述权限授权给 货主管理员(store_admin_default, id=5) 角色
|
||||
*
|
||||
* 幂等设计:
|
||||
* - 先查后插(按 path + type 唯一性判断)
|
||||
* - 角色权限更新使用 JSON 数组合并去重
|
||||
*/
|
||||
|
||||
const TABLE_PERMISSION = 'wms_permission';
|
||||
const TABLE_ROLE = 'wms_role';
|
||||
|
||||
const STORE_ADMIN_ROLE_ID = 5;
|
||||
|
||||
/** @type {{path: string, name: string|null, meta_title: string, type: string, parent_id: number|null, sort: number}[]} */
|
||||
const NEW_PERMISSIONS = [
|
||||
{
|
||||
path: 'receiving_owner',
|
||||
name: 'OwnerReceiving',
|
||||
meta_title: '收货单(货主)',
|
||||
type: 'web_pages',
|
||||
parent_id: 18, // 库存
|
||||
sort: 0,
|
||||
component: '@/views/storage/receiving_owner/index',
|
||||
},
|
||||
{
|
||||
path: 'storage.receiving.getStoreReceivingList',
|
||||
name: 'storage.receiving.getStoreReceivingList',
|
||||
meta_title: '货主侧收货单列表查询',
|
||||
type: 'api',
|
||||
parent_id: null,
|
||||
sort: 0,
|
||||
component: null,
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 获取角色当前权限 ID 数组。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {number} roleId 角色ID
|
||||
* @return {Promise<number[]>} 权限ID数组
|
||||
*/
|
||||
async function getRolePermissionIds(queryInterface, roleId) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
`SELECT permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`,
|
||||
{ replacements: { roleId } }
|
||||
);
|
||||
if (!rows || rows.length === 0) return [];
|
||||
|
||||
const raw = rows[0].permissions;
|
||||
if (!raw) return [];
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed.map(Number).filter(n => Number.isFinite(n) && n > 0);
|
||||
}
|
||||
} catch (_) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存角色权限。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {number} roleId 角色ID
|
||||
* @param {number[]} permissionIds 权限ID数组
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function saveRolePermissions(queryInterface, roleId, permissionIds) {
|
||||
const unique = Array.from(new Set(permissionIds)).sort((a, b) => a - b);
|
||||
const json = JSON.stringify(unique);
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE \`${TABLE_ROLE}\` SET permissions = :permissions, updated_at = NOW() WHERE id = :roleId`,
|
||||
{ replacements: { roleId, permissions: json } }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 正向迁移。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
module.exports.up = async queryInterface => {
|
||||
const insertedIds = [];
|
||||
|
||||
for (const perm of NEW_PERMISSIONS) {
|
||||
const [ existing ] = await queryInterface.sequelize.query(
|
||||
`SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type LIMIT 1`,
|
||||
{ replacements: { path: perm.path, type: perm.type } }
|
||||
);
|
||||
|
||||
if (existing && existing.length > 0) {
|
||||
console.log(`[Migration] 权限已存在,跳过: ${perm.path} (type=${perm.type}, id=${existing[0].id})`);
|
||||
insertedIds.push(existing[0].id);
|
||||
continue;
|
||||
}
|
||||
|
||||
const [ result ] = await queryInterface.sequelize.query(
|
||||
`INSERT INTO \`${TABLE_PERMISSION}\` (path, name, component, meta_title, type, parent_id, sort, status, created_at, update_at)
|
||||
VALUES (:path, :name, :component, :meta_title, :type, :parent_id, :sort, 1, NOW(), NOW())`,
|
||||
{ replacements: { ...perm } }
|
||||
);
|
||||
|
||||
const newId = result;
|
||||
console.log(`[Migration] 新增权限: ${perm.path} (type=${perm.type}, id=${newId})`);
|
||||
insertedIds.push(newId);
|
||||
}
|
||||
|
||||
// 更新 货主管理员 角色权限
|
||||
const currentIds = await getRolePermissionIds(queryInterface, STORE_ADMIN_ROLE_ID);
|
||||
const mergedIds = Array.from(new Set([ ...currentIds, ...insertedIds ])).sort((a, b) => a - b);
|
||||
|
||||
console.log(`[Migration] 货主管理员(id=${STORE_ADMIN_ROLE_ID}) 权限更新: [${currentIds.join(',')}] -> [${mergedIds.join(',')}]`);
|
||||
await saveRolePermissions(queryInterface, STORE_ADMIN_ROLE_ID, mergedIds);
|
||||
|
||||
console.log(`[Migration] 完成:新增 ${insertedIds.length} 条权限,角色权限已更新`);
|
||||
};
|
||||
|
||||
/**
|
||||
* 回滚迁移。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
module.exports.down = async queryInterface => {
|
||||
// 1. 从角色权限中移除新增的权限 ID
|
||||
const pathsToRemove = NEW_PERMISSIONS.map(p => p.path);
|
||||
|
||||
const [ permRows ] = await queryInterface.sequelize.query(
|
||||
`SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path IN (:paths) AND type IN (:types)`,
|
||||
{
|
||||
replacements: {
|
||||
paths: pathsToRemove,
|
||||
types: NEW_PERMISSIONS.map(p => p.type),
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const idsToRemove = permRows.map(r => r.id);
|
||||
const currentIds = await getRolePermissionIds(queryInterface, STORE_ADMIN_ROLE_ID);
|
||||
const filteredIds = currentIds.filter(id => !idsToRemove.includes(id));
|
||||
|
||||
await saveRolePermissions(queryInterface, STORE_ADMIN_ROLE_ID, filteredIds);
|
||||
console.log(`[Migration Rollback] 角色权限已移除: ${idsToRemove.join(',')}`);
|
||||
|
||||
// 2. 删除新增的权限记录
|
||||
for (const perm of NEW_PERMISSIONS) {
|
||||
await queryInterface.sequelize.query(
|
||||
`DELETE FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type`,
|
||||
{ replacements: { path: perm.path, type: perm.type } }
|
||||
);
|
||||
console.log(`[Migration Rollback] 已删除权限: ${perm.path}`);
|
||||
}
|
||||
};
|
||||
@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
// 紧急修复:将 wms_order_delivery_1000028 自增值提升至 15000+
|
||||
// 原因:表重建后 AUTO_INCREMENT 被重置为 151,与历史水位差距过大
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_order_delivery_1000028 AUTO_INCREMENT = 15000"
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
// 回滚:重置为默认(MAX(id)+1)
|
||||
await queryInterface.sequelize.query(
|
||||
'ALTER TABLE wms_order_delivery_1000028 AUTO_INCREMENT = 1'
|
||||
);
|
||||
},
|
||||
};
|
||||
89
database/migrations/20260715160000-create-wms-workbench.js
Normal file
89
database/migrations/20260715160000-create-wms-workbench.js
Normal file
@ -0,0 +1,89 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_workbench';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME);
|
||||
if (exists) return;
|
||||
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
name: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: false,
|
||||
comment: '工作台名称(用户自定义)',
|
||||
},
|
||||
barcode: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '工作台条码(用户自定义,仓库内唯一)',
|
||||
},
|
||||
status: {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:0-禁用 1-启用',
|
||||
},
|
||||
remark: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
});
|
||||
|
||||
// 仓库隔离查询
|
||||
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], {
|
||||
name: 'idx_warehouse_id',
|
||||
});
|
||||
|
||||
// 条码检索
|
||||
await queryInterface.addIndex(TABLE_NAME, ['barcode'], {
|
||||
name: 'idx_barcode',
|
||||
});
|
||||
|
||||
// 仓库级别唯一条码(含软删除,遵循 location_space 同款模式)
|
||||
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id', 'barcode', 'deleted_at'], {
|
||||
unique: true,
|
||||
name: 'uk_warehouse_barcode',
|
||||
});
|
||||
|
||||
// 软删除查询优化
|
||||
await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], {
|
||||
name: 'idx_deleted_at',
|
||||
});
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_workbench';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'type', {
|
||||
type: Sequelize.ENUM('personal', 'group'),
|
||||
allowNull: false,
|
||||
defaultValue: 'personal',
|
||||
comment: '工作台类型:personal-个人工作台 group-团体工作台',
|
||||
after: 'status',
|
||||
});
|
||||
},
|
||||
|
||||
down: async (queryInterface) => {
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'type');
|
||||
},
|
||||
};
|
||||
160
database/migrations/20260715180000-extend-wms-pack-task.js
Normal file
160
database/migrations/20260715180000-extend-wms-pack-task.js
Normal file
@ -0,0 +1,160 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_pack_task';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
// 1. 仓库隔离
|
||||
await queryInterface.addColumn(TABLE_NAME, 'warehouse_id', {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '仓库ID',
|
||||
after: 'order_id',
|
||||
});
|
||||
|
||||
// 2. 工作台关联
|
||||
await queryInterface.addColumn(TABLE_NAME, 'workbench_id', {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '工作台ID,关联 wms_workbench.id',
|
||||
after: 'warehouse_id',
|
||||
});
|
||||
|
||||
// 3. 波次信息
|
||||
await queryInterface.addColumn(TABLE_NAME, 'wave_id', {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '波次ID',
|
||||
after: 'workbench_id',
|
||||
});
|
||||
await queryInterface.addColumn(TABLE_NAME, 'wave_no', {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: '波次号',
|
||||
after: 'wave_id',
|
||||
});
|
||||
|
||||
// 4. 运单号
|
||||
await queryInterface.addColumn(TABLE_NAME, 'waybill_code', {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: '运单号',
|
||||
after: 'wave_no',
|
||||
});
|
||||
|
||||
// 5. 打包数量
|
||||
await queryInterface.addColumn(TABLE_NAME, 'pack_quantity', {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '打包数量(件数)',
|
||||
after: 'waybill_code',
|
||||
});
|
||||
|
||||
// 6. 作业时间
|
||||
await queryInterface.addColumn(TABLE_NAME, 'start_time', {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '开始打包时间',
|
||||
after: 'pack_quantity',
|
||||
});
|
||||
await queryInterface.addColumn(TABLE_NAME, 'end_time', {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '结束打包时间',
|
||||
after: 'start_time',
|
||||
});
|
||||
|
||||
// 7. 作业人员(兼容多人的自由文本)
|
||||
await queryInterface.addColumn(TABLE_NAME, 'operator_text', {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
comment: '作业人员(自由文本,如多人逗号分隔)',
|
||||
after: 'end_time',
|
||||
});
|
||||
|
||||
// 8. 设备IDS(JSON列表)
|
||||
await queryInterface.addColumn(TABLE_NAME, 'device_ids', {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '设备ID列表,如 [1,2,3]',
|
||||
after: 'operator_text',
|
||||
});
|
||||
|
||||
// 9. 包材信息
|
||||
await queryInterface.addColumn(TABLE_NAME, 'package_material_id', {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '包材ID,关联 wms_package_material.id',
|
||||
after: 'device_ids',
|
||||
});
|
||||
await queryInterface.addColumn(TABLE_NAME, 'package_material_snapshot', {
|
||||
type: Sequelize.STRING(200),
|
||||
allowNull: true,
|
||||
comment: '包材快照(编码+名称)',
|
||||
after: 'package_material_id',
|
||||
});
|
||||
|
||||
// 10. 称重
|
||||
await queryInterface.addColumn(TABLE_NAME, 'weighing_weight', {
|
||||
type: Sequelize.DECIMAL(10, 3),
|
||||
allowNull: true,
|
||||
comment: '打包称重(kg)',
|
||||
after: 'package_material_snapshot',
|
||||
});
|
||||
|
||||
// 11. 异常
|
||||
await queryInterface.addColumn(TABLE_NAME, 'abnormal_reason', {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '异常原因',
|
||||
after: 'weighing_weight',
|
||||
});
|
||||
|
||||
// 12. 备注
|
||||
await queryInterface.addColumn(TABLE_NAME, 'remark', {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
after: 'abnormal_reason',
|
||||
});
|
||||
|
||||
// 13. 修改 status 注释以包含更多状态
|
||||
await queryInterface.changeColumn(TABLE_NAME, 'status', {
|
||||
type: Sequelize.TINYINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '任务状态:0=待处理 1=打包中 2=已完成 3=异常',
|
||||
});
|
||||
|
||||
// ======== 索引 ========
|
||||
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { name: 'idx_warehouse_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, ['workbench_id'], { name: 'idx_workbench_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, ['wave_id'], { name: 'idx_wave_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, ['waybill_code'], { name: 'idx_waybill_code' });
|
||||
await queryInterface.addIndex(TABLE_NAME, ['start_time'], { name: 'idx_start_time' });
|
||||
await queryInterface.addIndex(TABLE_NAME, ['status'], { name: 'idx_status' });
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
const cols = [
|
||||
'remark', 'abnormal_reason', 'weighing_weight',
|
||||
'package_material_snapshot', 'package_material_id',
|
||||
'device_ids', 'operator_text', 'end_time', 'start_time',
|
||||
'pack_quantity', 'waybill_code', 'wave_no', 'wave_id',
|
||||
'workbench_id', 'warehouse_id',
|
||||
];
|
||||
for (const col of cols) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, col);
|
||||
}
|
||||
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_status');
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_start_time');
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_waybill_code');
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_wave_id');
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_workbench_id');
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_id');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,36 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_pack_task';
|
||||
|
||||
module.exports = {
|
||||
up: async queryInterface => {
|
||||
// 打包人信息已由 wms_pack_task_packer 子表承载,删除主表冗余字段
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'primary_packer_emp_id');
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'primary_packer_emp_no');
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'primary_packer_name');
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'packers_snapshot');
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'primary_packer_emp_id', {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '主打包人工号ID',
|
||||
});
|
||||
await queryInterface.addColumn(TABLE_NAME, 'primary_packer_emp_no', {
|
||||
type: Sequelize.STRING(64),
|
||||
allowNull: true,
|
||||
comment: '主打包人工号',
|
||||
});
|
||||
await queryInterface.addColumn(TABLE_NAME, 'primary_packer_name', {
|
||||
type: Sequelize.STRING(128),
|
||||
allowNull: true,
|
||||
comment: '主打包人姓名',
|
||||
});
|
||||
await queryInterface.addColumn(TABLE_NAME, 'packers_snapshot', {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '打包人快照:散单对象/团购数组',
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,36 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_pack_task';
|
||||
|
||||
module.exports = {
|
||||
up: async queryInterface => {
|
||||
// 包材/称重/异常已由 wms_order_express 表(按运单号维度)承载,删除冗余
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'package_material_id');
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'package_material_snapshot');
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'weighing_weight');
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'abnormal_reason');
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'package_material_id', {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '包材ID,关联 wms_package_material.id',
|
||||
});
|
||||
await queryInterface.addColumn(TABLE_NAME, 'package_material_snapshot', {
|
||||
type: Sequelize.STRING(200),
|
||||
allowNull: true,
|
||||
comment: '包材快照(编码+名称)',
|
||||
});
|
||||
await queryInterface.addColumn(TABLE_NAME, 'weighing_weight', {
|
||||
type: Sequelize.DECIMAL(10, 3),
|
||||
allowNull: true,
|
||||
comment: '打包称重(kg)',
|
||||
});
|
||||
await queryInterface.addColumn(TABLE_NAME, 'abnormal_reason', {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '异常原因',
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_workbench';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'device_ids', {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '设备ID列表,如 [1,2,3],触发打包任务时透传到 wms_pack_task.device_ids',
|
||||
after: 'remark',
|
||||
});
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'device_ids');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,98 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_camera_server';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME);
|
||||
if (exists) return;
|
||||
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
name: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: false,
|
||||
comment: '服务器名称',
|
||||
},
|
||||
brand: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: '品牌(如 Hikvision/Dahua)',
|
||||
},
|
||||
public_ip: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: '公网IP',
|
||||
},
|
||||
internal_ip: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: '内网IP',
|
||||
},
|
||||
port: {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: 80,
|
||||
comment: '端口号',
|
||||
},
|
||||
username: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '登录账号',
|
||||
},
|
||||
password: {
|
||||
type: Sequelize.STRING(200),
|
||||
allowNull: true,
|
||||
comment: '登录密码',
|
||||
},
|
||||
status: {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:0-禁用 1-启用',
|
||||
},
|
||||
remark: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { name: 'idx_warehouse_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, ['status'], { name: 'idx_status' });
|
||||
await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { name: 'idx_deleted_at' });
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
88
database/migrations/20260715220001-create-wms-camera.js
Normal file
88
database/migrations/20260715220001-create-wms-camera.js
Normal file
@ -0,0 +1,88 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_camera';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME);
|
||||
if (exists) return;
|
||||
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
server_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属录像服务器ID,关联 wms_camera_server.id',
|
||||
},
|
||||
channel_id: {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '通道编号(DVR/NVR 上的物理通道号)',
|
||||
},
|
||||
channel_name: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '通道原始名称',
|
||||
},
|
||||
custom_name: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '自定义摄像头名称',
|
||||
},
|
||||
status: {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:0-禁用 1-启用',
|
||||
},
|
||||
remark: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(TABLE_NAME, ['warehouse_id'], { name: 'idx_warehouse_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, ['server_id'], { name: 'idx_server_id' });
|
||||
// 同一服务器下通道号唯一
|
||||
await queryInterface.addIndex(TABLE_NAME, ['server_id', 'channel_id', 'deleted_at'], {
|
||||
unique: true,
|
||||
name: 'uk_server_channel',
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_NAME, ['status'], { name: 'idx_status' });
|
||||
await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { name: 'idx_deleted_at' });
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,72 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_pack_task_video';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME);
|
||||
if (exists) return;
|
||||
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
pack_task_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '打包任务ID,关联 wms_pack_task.id',
|
||||
},
|
||||
camera_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '摄像头设备ID,关联 wms_camera.id',
|
||||
},
|
||||
video_url: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: false,
|
||||
comment: '视频地址(录像回放URL)',
|
||||
},
|
||||
status: {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:0-无效 1-有效',
|
||||
},
|
||||
remark: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(TABLE_NAME, ['pack_task_id'], { name: 'idx_pack_task_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, ['camera_id'], { name: 'idx_camera_id' });
|
||||
await queryInterface.addIndex(TABLE_NAME, ['deleted_at'], { name: 'idx_deleted_at' });
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_camera';
|
||||
|
||||
/**
|
||||
* 新增摄像头设备信息字段:IP、SDK端口、型号、序列号、码流类型。
|
||||
* 用于保存 NVR 服务器返回的摄像头详细设备信息。
|
||||
*/
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const columns = [
|
||||
{
|
||||
name: 'ip',
|
||||
def: { type: Sequelize.STRING(50), allowNull: true, comment: '摄像头IP地址', after: 'channel_name' },
|
||||
},
|
||||
{
|
||||
name: 'port',
|
||||
def: { type: Sequelize.INTEGER.UNSIGNED, allowNull: true, comment: 'SDK管理端口(通常2020/8000)', after: 'ip' },
|
||||
},
|
||||
{
|
||||
name: 'model',
|
||||
def: { type: Sequelize.STRING(100), allowNull: true, comment: '摄像头型号', after: 'port' },
|
||||
},
|
||||
{
|
||||
name: 'serial_number',
|
||||
def: { type: Sequelize.STRING(100), allowNull: true, comment: '摄像头序列号', after: 'model' },
|
||||
},
|
||||
{
|
||||
name: 'stream_type',
|
||||
def: { type: Sequelize.STRING(20), allowNull: true, comment: '码流类型(auto/main/sub)', after: 'serial_number' },
|
||||
},
|
||||
];
|
||||
|
||||
for (const col of columns) {
|
||||
const tableInfo = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (!tableInfo[col.name]) {
|
||||
await queryInterface.addColumn(TABLE_NAME, col.name, col.def);
|
||||
console.log(`[Migration] wms_camera.${col.name} 已添加`);
|
||||
} else {
|
||||
console.log(`[Migration] wms_camera.${col.name} 已存在,跳过`);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
const columns = ['stream_type', 'serial_number', 'model', 'port', 'ip'];
|
||||
for (const col of columns) {
|
||||
const tableInfo = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (tableInfo[col]) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, col);
|
||||
console.log(`[Migration] wms_camera.${col} 已移除`);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,89 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_camera_server';
|
||||
|
||||
/**
|
||||
* 将 wms_camera_server.port 拆分为 public_port(远程/公网端口)和 internal_port(本地/内网端口)。
|
||||
* 原因:远程访问端口和本地访问端口通常不同(如 NAT 映射),需要分别存储。
|
||||
*/
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const tableInfo = await queryInterface.describeTable(TABLE_NAME);
|
||||
|
||||
// 1. 添加 public_port
|
||||
if (!tableInfo.public_port) {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'public_port', {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '远程/公网端口',
|
||||
after: 'internal_ip',
|
||||
});
|
||||
console.log('[Migration] wms_camera_server.public_port 已添加');
|
||||
} else {
|
||||
console.log('[Migration] wms_camera_server.public_port 已存在,跳过');
|
||||
}
|
||||
|
||||
// 2. 添加 internal_port
|
||||
if (!tableInfo.internal_port) {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'internal_port', {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '本地/内网端口',
|
||||
after: 'public_port',
|
||||
});
|
||||
console.log('[Migration] wms_camera_server.internal_port 已添加');
|
||||
} else {
|
||||
console.log('[Migration] wms_camera_server.internal_port 已存在,跳过');
|
||||
}
|
||||
|
||||
// 3. 将旧 port 数据迁移到 public_port 和 internal_port(保留旧值,后续可按需调整)
|
||||
if (tableInfo.port) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE ${TABLE_NAME} SET public_port = port, internal_port = port WHERE port IS NOT NULL`
|
||||
);
|
||||
console.log('[Migration] wms_camera_server.port 数据已复制到 public_port 和 internal_port');
|
||||
|
||||
// 4. 删除旧 port 列
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'port');
|
||||
console.log('[Migration] wms_camera_server.port 列已删除');
|
||||
} else {
|
||||
console.log('[Migration] wms_camera_server.port 列不存在,跳过迁移和删除');
|
||||
}
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
const tableInfo = await queryInterface.describeTable(TABLE_NAME);
|
||||
|
||||
// 恢复 port 列
|
||||
if (!tableInfo.port) {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'port', {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: 80,
|
||||
comment: '端口号',
|
||||
after: 'internal_ip',
|
||||
});
|
||||
console.log('[Migration] wms_camera_server.port 列已恢复');
|
||||
}
|
||||
|
||||
// 将 public_port 数据回写到 port(优先使用 internal_port)
|
||||
if (tableInfo.public_port || tableInfo.internal_port) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE ${TABLE_NAME} SET port = COALESCE(internal_port, public_port) WHERE internal_port IS NOT NULL OR public_port IS NOT NULL`
|
||||
);
|
||||
console.log('[Migration] port 数据已从 public_port/internal_port 回写');
|
||||
}
|
||||
|
||||
// 删除 public_port
|
||||
if (tableInfo.public_port) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'public_port');
|
||||
console.log('[Migration] wms_camera_server.public_port 列已删除');
|
||||
}
|
||||
|
||||
// 删除 internal_port
|
||||
if (tableInfo.internal_port) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'internal_port');
|
||||
console.log('[Migration] wms_camera_server.internal_port 列已删除');
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 修复:客服组-主管 补充缺失权限,使其不低于下属(客服组-员工)
|
||||
*
|
||||
* 背景:
|
||||
* 迁移 20260608033847 的设计意图是「客服组-主管」与「客服组-员工」权限一致。
|
||||
* 但后续新增权限时,主管遗漏了 5 个权限,导致员工(162个) > 主管(159个) 的越级现象。
|
||||
*
|
||||
* 变更:
|
||||
* - 客服组-主管 (id=28) 补充 [62, 63, 363, 396, 397] 共 5 个权限
|
||||
* - 补后:主管 164 个权限 > 员工 162 个权限(主管额外保留 309, 392)
|
||||
*
|
||||
* 补充权限明细:
|
||||
* | ID | 路径 | 名称 | 类型 |
|
||||
* |-----|-----------------------------------------------|-------------|-----------|
|
||||
* | 62 | stock.saveWarehouseStock | 保存商品资料 | api |
|
||||
* | 63 | stock.saveWarehouseStockBarcode | 修改商品条码 | api |
|
||||
* | 363 | storeWarehouse.store.queryPrintQuantityLogs | 货主面单余额 | api |
|
||||
* | 396 | shipperSigning | 外部仓库 | web_pages |
|
||||
* | 397 | storeWarehouse.store.confirmSign | 签约确定 | api |
|
||||
*/
|
||||
|
||||
const TABLE = 'wms_role';
|
||||
const ROLE_ID = 28;
|
||||
|
||||
const NEW_PERMISSIONS = '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,54,62,63,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,278,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,356,357,361,363,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384,386,387,388,389,390,391,392,396,397,416,417,418,420,421,422,424,425,426,427,428,429,430,431,432]';
|
||||
|
||||
const OLD_PERMISSIONS = '[1,4,8,9,11,12,13,14,15,17,18,19,20,21,22,24,25,26,27,29,30,38,39,40,41,43,44,45,46,47,48,49,50,54,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,244,254,255,256,278,281,283,290,291,292,293,294,295,296,297,298,299,300,303,304,305,306,307,308,309,333,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,356,357,361,367,368,369,370,371,372,373,374,375,376,377,379,380,381,382,383,384,386,387,388,389,390,391,392,416,417,418,420,421,422,424,425,426,427,428,429,430,431,432]';
|
||||
|
||||
/**
|
||||
* @param {import('sequelize').QueryInterface} queryInterface
|
||||
*/
|
||||
module.exports.up = async queryInterface => {
|
||||
const [result] = await queryInterface.sequelize.query(
|
||||
`UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW()
|
||||
WHERE id = :id AND is_system = 1`,
|
||||
{ replacements: { id: ROLE_ID, permissions: NEW_PERMISSIONS } }
|
||||
);
|
||||
|
||||
const affected = result?.affectedRows ?? result?.rowCount ?? result?.changedRows ?? 0;
|
||||
console.log(`[Migration] 客服组-主管(id=${ROLE_ID}) 权限补充:补充 5 个权限,实际更新 ${affected} 行`);
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {import('sequelize').QueryInterface} queryInterface
|
||||
*/
|
||||
module.exports.down = async queryInterface => {
|
||||
const [result] = await queryInterface.sequelize.query(
|
||||
`UPDATE \`${TABLE}\` SET permissions = :permissions, updated_at = NOW()
|
||||
WHERE id = :id AND is_system = 1`,
|
||||
{ replacements: { id: ROLE_ID, permissions: OLD_PERMISSIONS } }
|
||||
);
|
||||
|
||||
const affected = result?.affectedRows ?? result?.rowCount ?? result?.changedRows ?? 0;
|
||||
console.log(`[Migration] 客服组-主管(id=${ROLE_ID}) 权限回滚:实际回滚 ${affected} 行`);
|
||||
};
|
||||
@ -0,0 +1,17 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
// 去掉 creator_id 列的 ZEROFILL 属性,避免零填充字符串导致查询匹配问题
|
||||
await queryInterface.sequelize.query(
|
||||
'ALTER TABLE wms_receiving_detail MODIFY COLUMN creator_id bigint(20) unsigned NOT NULL'
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
// 回滚:恢复 ZEROFILL 属性
|
||||
await queryInterface.sequelize.query(
|
||||
'ALTER TABLE wms_receiving_detail MODIFY COLUMN creator_id bigint(20) unsigned zerofill NOT NULL'
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,17 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
// 在"数据"(id=16)菜单下新增"打包流水"页面权限
|
||||
await queryInterface.sequelize.query(`
|
||||
INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status, created_at, update_at, type)
|
||||
VALUES (449, 'PackingFlow', '@/views/storage/packingflow/index', 'PackingFlow', '', '打包流水', '', 0, 0, 16, 1, 1, NOW(), NOW(), 'web_pages')
|
||||
`);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.query(`
|
||||
DELETE FROM wms_permission WHERE id = 449 AND path = 'PackingFlow'
|
||||
`);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,36 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
// 给客服及以上角色追加 打包流水(449) 和 复核流水(450) 权限
|
||||
// 排除 permissions='*' 的角色(已有全部权限)
|
||||
await queryInterface.sequelize.query(`
|
||||
UPDATE wms_role
|
||||
SET permissions = JSON_ARRAY_APPEND(permissions, '$', 449, '$', 450),
|
||||
updated_at = NOW()
|
||||
WHERE id IN (5, 8, 26, 27, 28, 29, 30, 31, 32, 33, 34)
|
||||
AND permissions IS NOT NULL
|
||||
AND permissions != '*'
|
||||
AND permissions != '[]'
|
||||
AND JSON_VALID(permissions) = 1
|
||||
AND JSON_CONTAINS(permissions, '449', '$') = 0
|
||||
`);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
// 回滚:从角色权限中移除 449 和 450
|
||||
await queryInterface.sequelize.query(`
|
||||
UPDATE wms_role
|
||||
SET permissions = JSON_REMOVE(
|
||||
JSON_REMOVE(permissions, JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '449'))),
|
||||
JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '450'))
|
||||
),
|
||||
updated_at = NOW()
|
||||
WHERE id IN (5, 8, 26, 27, 28, 29, 30, 31, 32, 33, 34)
|
||||
AND permissions IS NOT NULL
|
||||
AND permissions != '*'
|
||||
AND JSON_VALID(permissions) = 1
|
||||
AND JSON_CONTAINS(permissions, '449', '$') = 1
|
||||
`);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,76 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_pack_task_packer';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
// 0. 清空已有数据(字段结构变更,emp 字段无法映射到新字段)
|
||||
await queryInterface.bulkDelete(TABLE_NAME, {});
|
||||
|
||||
// 1. 删除旧索引
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'uix_pack_task_emp');
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_emp_id');
|
||||
|
||||
// 2. 删除旧字段
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'emp_id');
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'emp_no');
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'emp_name');
|
||||
|
||||
// 3. 新增 account 字段
|
||||
await queryInterface.addColumn(TABLE_NAME, 'account_id', {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '账号ID,关联 wms_account.id',
|
||||
});
|
||||
await queryInterface.addColumn(TABLE_NAME, 'account_name', {
|
||||
type: Sequelize.STRING(128),
|
||||
allowNull: false,
|
||||
comment: '账号姓名快照',
|
||||
});
|
||||
|
||||
// 4. 建新索引
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'pack_task_id', 'account_id' ], {
|
||||
name: 'uix_pack_task_account',
|
||||
unique: true,
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'account_id' ], {
|
||||
name: 'idx_account_id',
|
||||
});
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
// 1. 删除新索引
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'uix_pack_task_account');
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_account_id');
|
||||
|
||||
// 2. 删除新字段
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'account_id');
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'account_name');
|
||||
|
||||
// 3. 恢复旧字段
|
||||
await queryInterface.addColumn(TABLE_NAME, 'emp_id', {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '打包人工号ID',
|
||||
});
|
||||
await queryInterface.addColumn(TABLE_NAME, 'emp_no', {
|
||||
type: Sequelize.STRING(64),
|
||||
allowNull: false,
|
||||
comment: '打包人工号',
|
||||
});
|
||||
await queryInterface.addColumn(TABLE_NAME, 'emp_name', {
|
||||
type: Sequelize.STRING(128),
|
||||
allowNull: false,
|
||||
comment: '打包人姓名',
|
||||
});
|
||||
|
||||
// 4. 恢复旧索引
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'pack_task_id', 'emp_id' ], {
|
||||
name: 'uix_pack_task_emp',
|
||||
unique: true,
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'emp_id' ], {
|
||||
name: 'idx_emp_id',
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,202 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 面单余额变更日志导出权限迁移。
|
||||
*
|
||||
* 变更内容:
|
||||
* 1. 新增 2 条 api 权限记录:
|
||||
* - storeWarehouse.store.exportPrintQuantityLogs — 导出面单余额变更日志
|
||||
* - storeWarehouse.store.exportPrintQuantityLogsTaskProgress — 查询导出任务进度
|
||||
* 2. 将上述权限授权给 财务以上角色组:
|
||||
* - 货主管理员 (id=5)
|
||||
* - 经理 (id=8)
|
||||
* (超级管理员 id=2/7 的 permissions='*' 无需更新)
|
||||
*
|
||||
* 幂等设计:
|
||||
* - 先查后插(按 path + type 唯一性判断)
|
||||
* - 角色权限更新使用 JSON 数组合并去重
|
||||
*/
|
||||
|
||||
const TABLE_PERMISSION = 'wms_permission';
|
||||
const TABLE_ROLE = 'wms_role';
|
||||
|
||||
/** 需要授权的角色ID(财务以上:货主管理员 + 经理) */
|
||||
const TARGET_ROLE_IDS = [5, 8];
|
||||
|
||||
/** @type {{path: string, name: string, meta_title: string, type: string}[]} */
|
||||
const NEW_PERMISSIONS = [
|
||||
{
|
||||
path: 'storeWarehouse.store.exportPrintQuantityLogs',
|
||||
name: 'storeWarehouse.store.exportPrintQuantityLogs',
|
||||
meta_title: '导出面单余额变更日志',
|
||||
type: 'api',
|
||||
},
|
||||
{
|
||||
path: 'storeWarehouse.store.exportPrintQuantityLogsTaskProgress',
|
||||
name: 'storeWarehouse.store.exportPrintQuantityLogsTaskProgress',
|
||||
meta_title: '查询面单余额导出任务进度',
|
||||
type: 'api',
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 获取角色当前权限 ID 数组。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {number} roleId 角色ID
|
||||
* @return {Promise<number[]>} 权限ID数组
|
||||
*/
|
||||
async function getRolePermissionIds(queryInterface, roleId) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
`SELECT permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`,
|
||||
{ replacements: { roleId } }
|
||||
);
|
||||
if (!rows || rows.length === 0) return [];
|
||||
|
||||
const raw = rows[0].permissions;
|
||||
if (!raw || raw === '*') return [];
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed.map(Number).filter(n => Number.isFinite(n) && n > 0);
|
||||
}
|
||||
} catch (_) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存角色权限。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {number} roleId 角色ID
|
||||
* @param {number[]} permissionIds 权限ID数组
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function saveRolePermissions(queryInterface, roleId, permissionIds) {
|
||||
const unique = Array.from(new Set(permissionIds)).sort((a, b) => a - b);
|
||||
const json = JSON.stringify(unique);
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE \`${TABLE_ROLE}\` SET permissions = :permissions, updated_at = NOW() WHERE id = :roleId`,
|
||||
{ replacements: { roleId, permissions: json } }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 正向迁移。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
module.exports.up = async queryInterface => {
|
||||
// ─── 1. 插入新权限记录 ─────────────────────────────────
|
||||
const insertedIds = [];
|
||||
|
||||
for (const perm of NEW_PERMISSIONS) {
|
||||
const [ existing ] = await queryInterface.sequelize.query(
|
||||
`SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type LIMIT 1`,
|
||||
{ replacements: { path: perm.path, type: perm.type } }
|
||||
);
|
||||
|
||||
if (existing && existing.length > 0) {
|
||||
console.log(`[Migration] 权限已存在: ${perm.path} (id=${existing[0].id})`);
|
||||
insertedIds.push(Number(existing[0].id));
|
||||
continue;
|
||||
}
|
||||
|
||||
const [ result ] = await queryInterface.sequelize.query(
|
||||
`INSERT INTO \`${TABLE_PERMISSION}\` (path, name, meta_title, type, status, created_at, update_at)
|
||||
VALUES (:path, :name, :meta_title, :type, 1, NOW(), NOW())`,
|
||||
{ replacements: { path: perm.path, name: perm.name, meta_title: perm.meta_title, type: perm.type } }
|
||||
);
|
||||
|
||||
const newId = Number(result);
|
||||
insertedIds.push(newId);
|
||||
console.log(`[Migration] 新增权限: ${perm.path} (id=${newId})`);
|
||||
}
|
||||
|
||||
// ─── 2. 授权给财务以上角色组 ──────────────────────────
|
||||
for (const roleId of TARGET_ROLE_IDS) {
|
||||
const [ roleRows ] = await queryInterface.sequelize.query(
|
||||
`SELECT id, permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`,
|
||||
{ replacements: { roleId } }
|
||||
);
|
||||
|
||||
if (!roleRows || roleRows.length === 0) {
|
||||
console.log(`[Migration] 角色不存在: id=${roleId}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const raw = roleRows[0].permissions;
|
||||
// 跳过 permissions='*' 的角色(已拥有全部权限)
|
||||
if (raw === '*') {
|
||||
console.log(`[Migration] 角色 id=${roleId} 已有全部权限(*),跳过`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const currentIds = await getRolePermissionIds(queryInterface, roleId);
|
||||
const newIds = insertedIds.filter(id => !currentIds.includes(id));
|
||||
|
||||
if (newIds.length === 0) {
|
||||
console.log(`[Migration] 角色 id=${roleId} 已拥有目标权限,跳过`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const merged = [ ...currentIds, ...newIds ];
|
||||
await saveRolePermissions(queryInterface, roleId, merged);
|
||||
console.log(`[Migration] 角色 id=${roleId} 授权成功,新增权限: [${newIds.join(', ')}]`);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[Migration] 面单余额导出权限迁移完成:` +
|
||||
`新增 ${NEW_PERMISSIONS.length} 条权限,授权 ${TARGET_ROLE_IDS.length} 个角色`
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* 回滚迁移。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
module.exports.down = async queryInterface => {
|
||||
// ─── 1. 从角色权限中移除新增的权限ID ─────────────────
|
||||
const allPaths = NEW_PERMISSIONS.map(p => p.path);
|
||||
|
||||
for (const roleId of TARGET_ROLE_IDS) {
|
||||
const [ roleRows ] = await queryInterface.sequelize.query(
|
||||
`SELECT id, permissions FROM \`${TABLE_ROLE}\` WHERE id = :roleId`,
|
||||
{ replacements: { roleId } }
|
||||
);
|
||||
|
||||
if (!roleRows || roleRows.length === 0) continue;
|
||||
|
||||
const raw = roleRows[0].permissions;
|
||||
if (!raw || raw === '*') continue;
|
||||
|
||||
const currentIds = await getRolePermissionIds(queryInterface, roleId);
|
||||
// 查询需要移除的权限ID
|
||||
const [ permRows ] = await queryInterface.sequelize.query(
|
||||
`SELECT id FROM \`${TABLE_PERMISSION}\` WHERE path IN (:paths) AND type = 'api'`,
|
||||
{ replacements: { paths: allPaths } }
|
||||
);
|
||||
const removeIds = permRows.map(r => Number(r.id));
|
||||
const filtered = currentIds.filter(id => !removeIds.includes(id));
|
||||
|
||||
if (filtered.length !== currentIds.length) {
|
||||
await saveRolePermissions(queryInterface, roleId, filtered);
|
||||
console.log(`[Migration] 角色 id=${roleId} 已移除导出权限`);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 2. 删除新增的权限记录 ───────────────────────────
|
||||
for (const perm of NEW_PERMISSIONS) {
|
||||
await queryInterface.sequelize.query(
|
||||
`DELETE FROM \`${TABLE_PERMISSION}\` WHERE path = :path AND type = :type`,
|
||||
{ replacements: { path: perm.path, type: perm.type } }
|
||||
);
|
||||
console.log(`[Migration] 已删除权限: ${perm.path}`);
|
||||
}
|
||||
|
||||
console.log('[Migration] 面单余额导出权限回滚完成');
|
||||
};
|
||||
@ -0,0 +1,17 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('wms_express_interface', 'is_enabled', {
|
||||
type: Sequelize.TINYINT(1),
|
||||
allowNull: true,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用(1=启用,0=停用)',
|
||||
after: 'is_hide_goods',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn('wms_express_interface', 'is_enabled');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 为打印台电脑表新增"是否作为录制电脑"字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('wms_print_computer', 'is_recording', {
|
||||
type: Sequelize.BOOLEAN,
|
||||
allowNull: false,
|
||||
defaultValue: false,
|
||||
comment: '是否作为录制电脑,1-是,0-否',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚删除打印台电脑表的"是否作为录制电脑"字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn('wms_print_computer', 'is_recording');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,171 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 统一所有重量字段为 INT 类型,单位统一为 g(克)。
|
||||
*
|
||||
* 说明:原字段注释/类型写错(注释标 kg 实际存的是 g),
|
||||
* 数据本身已为克,迁移只做类型转换 + 注释修正,不做数值缩放。
|
||||
*
|
||||
* 涉及表/字段:
|
||||
* wms_location_space : max_weight, current_weight (DECIMAL → INT)
|
||||
* wms_order_delivery_100000* : items_weight (DECIMAL → INT)
|
||||
* wms_order_express : weighing_weight (DECIMAL(10,3) → INT)
|
||||
* wms_package_material : weight (DECIMAL(10,3) → INT)
|
||||
* wms_package_material_item_relation: weight (DECIMAL → INT)
|
||||
* wms_receiving_detail : box_weight (DECIMAL → INT)
|
||||
* wms_receiving_detail : weight (已为INT, 仅更新注释)
|
||||
* wms_stock_store : gross_weight, net_weight (DECIMAL → INT)
|
||||
* wms_stock_warehouse : gross_weight, net_weight (DECIMAL → INT)
|
||||
* wms_stock_warehouse : box_gross_weight, box_net_weight (已为INT, 仅更新注释)
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
// ===================== wms_location_space =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_location_space MODIFY COLUMN max_weight INT(11) DEFAULT 0 COMMENT '最大承重(g)'"
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_location_space MODIFY COLUMN current_weight INT(11) DEFAULT 0 COMMENT '当前重量(g)'"
|
||||
);
|
||||
|
||||
// ===================== wms_order_delivery 分表 =====================
|
||||
const orderDeliveryTables = [
|
||||
'wms_order_delivery_100000',
|
||||
'wms_order_delivery_100000_dispatch',
|
||||
'wms_order_delivery_100000_history',
|
||||
'wms_order_delivery_100000_outsourced',
|
||||
'wms_order_delivery_1000028',
|
||||
'wms_order_delivery_1000028_dispatch',
|
||||
'wms_order_delivery_1000028_history',
|
||||
'wms_order_delivery_1000028_outsourced',
|
||||
];
|
||||
|
||||
for (const table of orderDeliveryTables) {
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${table}\` MODIFY COLUMN items_weight INT(11) NOT NULL DEFAULT 0 COMMENT '总重量(g)'`
|
||||
);
|
||||
}
|
||||
|
||||
// ===================== wms_order_express =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_order_express MODIFY COLUMN weighing_weight INT(11) DEFAULT 0 COMMENT '称重重量(g)'"
|
||||
);
|
||||
|
||||
// ===================== wms_package_material =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_package_material MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量(g)'"
|
||||
);
|
||||
|
||||
// ===================== wms_package_material_item_relation =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_package_material_item_relation MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量(g)快照'"
|
||||
);
|
||||
|
||||
// ===================== wms_receiving_detail =====================
|
||||
// weight: 已为 INT(g),仅补注释
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_receiving_detail MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量(g)'"
|
||||
);
|
||||
// box_weight: DECIMAL → INT(g)
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_receiving_detail MODIFY COLUMN box_weight INT(11) NOT NULL DEFAULT 0 COMMENT '箱重量(g)'"
|
||||
);
|
||||
|
||||
// ===================== wms_stock_store =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_stock_store MODIFY COLUMN gross_weight INT(11) DEFAULT 0 COMMENT '毛重(g)'"
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_stock_store MODIFY COLUMN net_weight INT(11) DEFAULT 0 COMMENT '净重(g)'"
|
||||
);
|
||||
|
||||
// ===================== wms_stock_warehouse =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_stock_warehouse MODIFY COLUMN gross_weight INT(11) DEFAULT 0 COMMENT '毛重(g)'"
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_stock_warehouse MODIFY COLUMN net_weight INT(11) DEFAULT 0 COMMENT '净重(g)'"
|
||||
);
|
||||
// box_gross_weight / box_net_weight: 已为INT, 仅补注释
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_gross_weight INT(11) DEFAULT 0 COMMENT '箱毛重(g)'"
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_net_weight INT(11) DEFAULT 0 COMMENT '箱净重(g)'"
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
// ===================== wms_location_space =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_location_space MODIFY COLUMN max_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '最大承重(kg)'"
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_location_space MODIFY COLUMN current_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '当前重量(kg)'"
|
||||
);
|
||||
|
||||
// ===================== wms_order_delivery 分表 =====================
|
||||
const orderDeliveryTables = [
|
||||
'wms_order_delivery_100000',
|
||||
'wms_order_delivery_100000_dispatch',
|
||||
'wms_order_delivery_100000_history',
|
||||
'wms_order_delivery_100000_outsourced',
|
||||
'wms_order_delivery_1000028',
|
||||
'wms_order_delivery_1000028_dispatch',
|
||||
'wms_order_delivery_1000028_history',
|
||||
'wms_order_delivery_1000028_outsourced',
|
||||
];
|
||||
|
||||
for (const table of orderDeliveryTables) {
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${table}\` MODIFY COLUMN items_weight DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '总重量(kg)'`
|
||||
);
|
||||
}
|
||||
|
||||
// ===================== wms_order_express =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_order_express MODIFY COLUMN weighing_weight DECIMAL(10,3) DEFAULT 0.000 COMMENT '称重重量(kg)'"
|
||||
);
|
||||
|
||||
// ===================== wms_package_material =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_package_material MODIFY COLUMN weight DECIMAL(10,3) DEFAULT 0.000 COMMENT '重量(kg)'"
|
||||
);
|
||||
|
||||
// ===================== wms_package_material_item_relation =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_package_material_item_relation MODIFY COLUMN weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '重量(kg)快照'"
|
||||
);
|
||||
|
||||
// ===================== wms_receiving_detail =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_receiving_detail MODIFY COLUMN weight INT(11) DEFAULT 0 COMMENT '重量g'"
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_receiving_detail MODIFY COLUMN box_weight DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '箱重量(kg)'"
|
||||
);
|
||||
|
||||
// ===================== wms_stock_store =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_stock_store MODIFY COLUMN gross_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '毛重'"
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_stock_store MODIFY COLUMN net_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '净重'"
|
||||
);
|
||||
|
||||
// ===================== wms_stock_warehouse =====================
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_stock_warehouse MODIFY COLUMN gross_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '毛重'"
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_stock_warehouse MODIFY COLUMN net_weight DECIMAL(10,2) DEFAULT 0.00 COMMENT '净重'"
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_gross_weight INT(11) DEFAULT 0 COMMENT '箱毛重'"
|
||||
);
|
||||
await queryInterface.sequelize.query(
|
||||
"ALTER TABLE wms_stock_warehouse MODIFY COLUMN box_net_weight INT(11) DEFAULT 0 COMMENT '箱净重'"
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 为打印台电脑表新增软删除时间字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('wms_print_computer', 'deleted_at', {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '软删除时间',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚删除打印台电脑表的软删除时间字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn('wms_print_computer', 'deleted_at');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 为打印台表新增软删除时间字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('wms_print_stations', 'deleted_at', {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '软删除时间',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚删除打印台表的软删除时间字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn('wms_print_stations', 'deleted_at');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,86 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 新增打印电脑模块 API 权限,并授权客服主管及以上角色。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
const now = new Date();
|
||||
|
||||
// 1. 插入 3 条 API 权限
|
||||
const permissions = [
|
||||
{ path: 'print_computer.list', name: '打印电脑-列表', type: 'api', status: 1, created_at: now, update_at: now },
|
||||
{ path: 'print_computer.update', name: '打印电脑-更新', type: 'api', status: 1, created_at: now, update_at: now },
|
||||
{ path: 'print_computer.delete', name: '打印电脑-删除', type: 'api', status: 1, created_at: now, update_at: now },
|
||||
];
|
||||
|
||||
await queryInterface.bulkInsert('wms_permission', permissions);
|
||||
|
||||
// 2. 查询刚插入的权限 ID
|
||||
const [rows] = await queryInterface.sequelize.query(
|
||||
`SELECT id FROM wms_permission WHERE path IN ('print_computer.list', 'print_computer.update', 'print_computer.delete') ORDER BY id`
|
||||
);
|
||||
const ids = rows.map(r => r.id);
|
||||
if (ids.length !== 3) {
|
||||
throw new Error(`权限插入异常:期望 3 条,实际 ${ids.length} 条`);
|
||||
}
|
||||
|
||||
// 3. 授权客服主管及以上角色(排除 permissions='*' 的超级管理员角色)
|
||||
const roleIds = [2, 5, 7, 8, 22, 26, 28, 29];
|
||||
for (const permId of ids) {
|
||||
await queryInterface.sequelize.query(`
|
||||
UPDATE wms_role
|
||||
SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(${permId} AS UNSIGNED)),
|
||||
updated_at = NOW()
|
||||
WHERE id IN (${roleIds.join(',')})
|
||||
AND permissions IS NOT NULL
|
||||
AND permissions != '*'
|
||||
AND permissions != '[]'
|
||||
AND JSON_VALID(permissions) = 1
|
||||
AND JSON_CONTAINS(permissions, '${permId}', '$') = 0
|
||||
`);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚:删除权限记录并从角色权限中移除。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
const paths = ['print_computer.list', 'print_computer.update', 'print_computer.delete'];
|
||||
|
||||
// 1. 查询权限 ID
|
||||
const [rows] = await queryInterface.sequelize.query(
|
||||
`SELECT id FROM wms_permission WHERE path IN ('${paths.join("','")}')`
|
||||
);
|
||||
const ids = rows.map(r => r.id);
|
||||
|
||||
// 2. 从角色权限中移除
|
||||
const roleIds = [2, 5, 7, 8, 22, 26, 28, 29];
|
||||
for (const permId of ids) {
|
||||
await queryInterface.sequelize.query(`
|
||||
UPDATE wms_role
|
||||
SET permissions = JSON_REMOVE(
|
||||
permissions,
|
||||
JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '${permId}'))
|
||||
),
|
||||
updated_at = NOW()
|
||||
WHERE id IN (${roleIds.join(',')})
|
||||
AND permissions IS NOT NULL
|
||||
AND permissions != '*'
|
||||
AND JSON_VALID(permissions) = 1
|
||||
AND JSON_CONTAINS(permissions, '${permId}', '$') = 1
|
||||
`);
|
||||
}
|
||||
|
||||
// 3. 删除权限记录
|
||||
await queryInterface.bulkDelete('wms_permission', {
|
||||
path: { [Sequelize.Op.in]: paths },
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 为打印电脑表新增录制相关字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('wms_print_computer', 'recording_size_value', {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '录制大小数值',
|
||||
});
|
||||
await queryInterface.addColumn('wms_print_computer', 'recording_size_unit', {
|
||||
type: Sequelize.STRING(10),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '录制存储单位:KB/MB/GB/TB',
|
||||
});
|
||||
await queryInterface.addColumn('wms_print_computer', 'remote_play_url', {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '远程播放地址',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚删除录制相关字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn('wms_print_computer', 'remote_play_url');
|
||||
await queryInterface.removeColumn('wms_print_computer', 'recording_size_unit');
|
||||
await queryInterface.removeColumn('wms_print_computer', 'recording_size_value');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,82 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 新增打印电脑录制相关 API 权限,并授权客服主管及以上角色。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
const now = new Date();
|
||||
|
||||
// 1. 插入 2 条 API 权限
|
||||
const permissions = [
|
||||
{ path: 'print_computer.setRecording', name: '打印电脑-设置录制', type: 'api', status: 1, created_at: now, update_at: now },
|
||||
{ path: 'print_computer.cancelRecording', name: '打印电脑-取消录制', type: 'api', status: 1, created_at: now, update_at: now },
|
||||
];
|
||||
|
||||
await queryInterface.bulkInsert('wms_permission', permissions);
|
||||
|
||||
// 2. 查询刚插入的权限 ID
|
||||
const [rows] = await queryInterface.sequelize.query(
|
||||
`SELECT id FROM wms_permission WHERE path IN ('print_computer.setRecording', 'print_computer.cancelRecording') ORDER BY id`
|
||||
);
|
||||
const ids = rows.map(r => r.id);
|
||||
if (ids.length !== 2) {
|
||||
throw new Error(`权限插入异常:期望 2 条,实际 ${ids.length} 条`);
|
||||
}
|
||||
|
||||
// 3. 授权客服主管及以上角色
|
||||
const roleIds = [2, 5, 7, 8, 22, 26, 28, 29];
|
||||
for (const permId of ids) {
|
||||
await queryInterface.sequelize.query(`
|
||||
UPDATE wms_role
|
||||
SET permissions = JSON_ARRAY_APPEND(permissions, '$', CAST(${permId} AS UNSIGNED)),
|
||||
updated_at = NOW()
|
||||
WHERE id IN (${roleIds.join(',')})
|
||||
AND permissions IS NOT NULL
|
||||
AND permissions != '*'
|
||||
AND permissions != '[]'
|
||||
AND JSON_VALID(permissions) = 1
|
||||
AND JSON_CONTAINS(permissions, '${permId}', '$') = 0
|
||||
`);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚:删除权限记录并从角色权限中移除。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
const paths = ['print_computer.setRecording', 'print_computer.cancelRecording'];
|
||||
|
||||
const [rows] = await queryInterface.sequelize.query(
|
||||
`SELECT id FROM wms_permission WHERE path IN ('${paths.join("','")}')`
|
||||
);
|
||||
const ids = rows.map(r => r.id);
|
||||
|
||||
const roleIds = [2, 5, 7, 8, 22, 26, 28, 29];
|
||||
for (const permId of ids) {
|
||||
await queryInterface.sequelize.query(`
|
||||
UPDATE wms_role
|
||||
SET permissions = JSON_REMOVE(
|
||||
permissions,
|
||||
JSON_UNQUOTE(JSON_SEARCH(permissions, 'one', '${permId}'))
|
||||
),
|
||||
updated_at = NOW()
|
||||
WHERE id IN (${roleIds.join(',')})
|
||||
AND permissions IS NOT NULL
|
||||
AND permissions != '*'
|
||||
AND JSON_VALID(permissions) = 1
|
||||
AND JSON_CONTAINS(permissions, '${permId}', '$') = 1
|
||||
`);
|
||||
}
|
||||
|
||||
await queryInterface.bulkDelete('wms_permission', {
|
||||
path: { [Sequelize.Op.in]: paths },
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 为打印电脑表新增录制目录字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('wms_print_computer', 'recording_directory', {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '录制目录路径,如 D:/record',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚删除录制目录字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn('wms_print_computer', 'recording_directory');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,36 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 为打包任务表新增"商品数量"和"商品种类数"字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('wms_pack_task', 'item_quantity', {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '商品总数量',
|
||||
});
|
||||
|
||||
await queryInterface.addColumn('wms_pack_task', 'sku_count', {
|
||||
type: Sequelize.INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '商品种类数(SKU数)',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚删除打包任务表的"商品数量"和"商品种类数"字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例
|
||||
* @return {Promise<void>} 无返回值
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn('wms_pack_task', 'sku_count');
|
||||
await queryInterface.removeColumn('wms_pack_task', 'item_quantity');
|
||||
},
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user