chore: initialize wms project
This commit is contained in:
commit
63b4536766
1
.eslintignore
Normal file
1
.eslintignore
Normal file
@ -0,0 +1 @@
|
|||||||
|
coverage
|
||||||
17
.gitattributes
vendored
Normal file
17
.gitattributes
vendored
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
|
|
||||||
|
*.bat text eol=crlf
|
||||||
|
*.cmd text eol=crlf
|
||||||
|
*.ps1 text eol=crlf
|
||||||
|
|
||||||
|
*.png binary
|
||||||
|
*.jpg binary
|
||||||
|
*.jpeg binary
|
||||||
|
*.gif binary
|
||||||
|
*.bmp binary
|
||||||
|
*.ico binary
|
||||||
|
*.pdf binary
|
||||||
|
*.zip binary
|
||||||
|
*.rar binary
|
||||||
|
*.7z binary
|
||||||
|
*.node binary
|
||||||
25
.gitignore
vendored
Normal file
25
.gitignore
vendored
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
logs/
|
||||||
|
run/
|
||||||
|
node_modules/
|
||||||
|
coverage/
|
||||||
|
.nyc_output/
|
||||||
|
typings/
|
||||||
|
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
config/config.local.js
|
||||||
|
database/config.json
|
||||||
|
|
||||||
|
native/addons/*.node
|
||||||
|
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
*.sw*
|
||||||
|
*.un~
|
||||||
10
.sequelizerc
Normal file
10
.sequelizerc
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
"config": path.join(__dirname, 'database/config.json'),
|
||||||
|
"migrations-path": path.join(__dirname, 'database/migrations'),
|
||||||
|
"seeders-path": path.join(__dirname, 'database/seeders'),
|
||||||
|
"models-path": path.join(__dirname, 'app/model'),
|
||||||
|
};
|
||||||
143
Apifox/print.json
Normal file
143
Apifox/print.json
Normal file
@ -0,0 +1,143 @@
|
|||||||
|
{
|
||||||
|
"openapi": "3.0.1",
|
||||||
|
"info": {
|
||||||
|
"title": "打印相关接口",
|
||||||
|
"description": "print service methods",
|
||||||
|
"version": "1.0.0"
|
||||||
|
},
|
||||||
|
"paths": {
|
||||||
|
"/system": {
|
||||||
|
"post": {
|
||||||
|
"summary": "打印台相关接口",
|
||||||
|
"operationId": "printStationOperations",
|
||||||
|
"description": "根据method参数执行不同的打印台操作",
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"name": "method",
|
||||||
|
"in": "query",
|
||||||
|
"description": "调用方法名,如print.getList、print.getItem、print.updateItem、print.del、print.getComputer、print.getComputerPrinter、print.savePrinters",
|
||||||
|
"required": true,
|
||||||
|
"schema": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"print.getList",
|
||||||
|
"print.getItem",
|
||||||
|
"print.updateItem",
|
||||||
|
"print.del",
|
||||||
|
"print.getComputer",
|
||||||
|
"print.getComputerPrinter",
|
||||||
|
"print.savePrinters"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "v",
|
||||||
|
"in": "query",
|
||||||
|
"description": "版本号",
|
||||||
|
"required": false,
|
||||||
|
"schema": {
|
||||||
|
"type": "string",
|
||||||
|
"example": "2.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "timestamp",
|
||||||
|
"in": "query",
|
||||||
|
"description": "时间戳",
|
||||||
|
"required": false,
|
||||||
|
"schema": {
|
||||||
|
"type": "string",
|
||||||
|
"example": "1646908800000"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"requestBody": {
|
||||||
|
"required": false,
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"page": { "type": "integer", "example": 1 },
|
||||||
|
"pageSize": { "type": "integer", "example": 20 },
|
||||||
|
"where": {
|
||||||
|
"type": "object",
|
||||||
|
"example": { "name": "A台" }
|
||||||
|
},
|
||||||
|
"id": { "type": "integer", "example": 1 },
|
||||||
|
"name": { "type": "string", "example": "A台" },
|
||||||
|
"computer_id": { "type": "integer", "example": 2 },
|
||||||
|
"custom_barcode": { "type": "string", "example": "123456" },
|
||||||
|
"ids": {
|
||||||
|
"type": "array",
|
||||||
|
"items": { "type": "integer" },
|
||||||
|
"example": [1,2]
|
||||||
|
},
|
||||||
|
"default": { "type": "string", "example": "打印机名称" },
|
||||||
|
"express": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"express_id": { "type": "integer" },
|
||||||
|
"name": { "type": "string" }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"example": [{ "express_id": 1, "name": "顺丰" }]
|
||||||
|
},
|
||||||
|
"print_station_id": { "type": "integer", "example": 1 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "成功响应",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"code": { "type": "integer", "description": "状态码" },
|
||||||
|
"message": { "type": "string", "description": "返回信息" },
|
||||||
|
"data": { "type": "object", "description": "返回数据" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"400": {
|
||||||
|
"description": "错误请求",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"code": { "type": "integer" },
|
||||||
|
"message": { "type": "string" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"401": {
|
||||||
|
"description": "未授权"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"security": [
|
||||||
|
{ "bearer": [] }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"components": {
|
||||||
|
"securitySchemes": {
|
||||||
|
"bearer": {
|
||||||
|
"type": "http",
|
||||||
|
"scheme": "bearer",
|
||||||
|
"bearerFormat": "JWT"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
107
Apifox/test.json
Normal file
107
Apifox/test.json
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
{
|
||||||
|
"openapi": "3.0.1",
|
||||||
|
"info": {
|
||||||
|
"title": "默认模块",
|
||||||
|
"description": "",
|
||||||
|
"version": "1.0.0"
|
||||||
|
},
|
||||||
|
"tags": [],
|
||||||
|
"paths": {
|
||||||
|
"/system": {
|
||||||
|
"post": {
|
||||||
|
"summary": "未命名接口",
|
||||||
|
"deprecated": false,
|
||||||
|
"description": "",
|
||||||
|
"tags": [],
|
||||||
|
"parameters": [
|
||||||
|
{
|
||||||
|
"name": "method",
|
||||||
|
"in": "query",
|
||||||
|
"description": "",
|
||||||
|
"required": false,
|
||||||
|
"example": "user.login",
|
||||||
|
"schema": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "v",
|
||||||
|
"in": "query",
|
||||||
|
"description": "",
|
||||||
|
"required": false,
|
||||||
|
"example": "2.0",
|
||||||
|
"schema": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "timestamp",
|
||||||
|
"in": "query",
|
||||||
|
"description": "",
|
||||||
|
"required": false,
|
||||||
|
"example": "{{$date.now}}",
|
||||||
|
"schema": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"requestBody": {
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"userName": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"passWord": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"userName",
|
||||||
|
"passWord"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"example": {
|
||||||
|
"userName": "夫立伟",
|
||||||
|
"passWord": "Ut cillum veniam"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"responses": {
|
||||||
|
"200": {
|
||||||
|
"description": "",
|
||||||
|
"content": {
|
||||||
|
"application/json": {
|
||||||
|
"schema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"headers": {}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"security": [
|
||||||
|
{
|
||||||
|
"bearer": []
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"components": {
|
||||||
|
"schemas": {},
|
||||||
|
"responses": {},
|
||||||
|
"securitySchemes": {
|
||||||
|
"bearer": {
|
||||||
|
"type": "http",
|
||||||
|
"scheme": "bearer"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"servers": [],
|
||||||
|
"security": []
|
||||||
|
}
|
||||||
31
README.md
Normal file
31
README.md
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
# qimen
|
||||||
|
|
||||||
|
奇门wms
|
||||||
|
|
||||||
|
## QuickStart
|
||||||
|
|
||||||
|
<!-- add docs here for user -->
|
||||||
|
|
||||||
|
see [egg docs][egg] for more detail.
|
||||||
|
|
||||||
|
### Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm i
|
||||||
|
npm run dev
|
||||||
|
open http://localhost:7001/
|
||||||
|
```
|
||||||
|
|
||||||
|
### Deploy
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm start
|
||||||
|
npm stop
|
||||||
|
```
|
||||||
|
|
||||||
|
### npm scripts
|
||||||
|
|
||||||
|
- Use `npm run lint` to check code style.
|
||||||
|
- Use `npm test` to run unit test.
|
||||||
|
|
||||||
|
[egg]: https://eggjs.org
|
||||||
82
app.js
Normal file
82
app.js
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
// app.js
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const businessDict = require('./app/dict/businessDict.js');
|
||||||
|
|
||||||
|
// 直接导出函数,而不是类
|
||||||
|
module.exports = app => {
|
||||||
|
// 设置全局应用根目录
|
||||||
|
global.APP_ROOT = path.resolve(__dirname, './');
|
||||||
|
app.appRoot = APP_ROOT;
|
||||||
|
// ========== 挂载字典到 app ==========
|
||||||
|
app.businessDict = businessDict;
|
||||||
|
|
||||||
|
// 添加字典工具方法
|
||||||
|
app.getBusinessTypeName = code => {
|
||||||
|
const dict = app.businessDict.BUSINESS_TYPE || {};
|
||||||
|
for (const key in dict) {
|
||||||
|
if (dict[key].code === code) {
|
||||||
|
return dict[key].name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
};
|
||||||
|
|
||||||
|
app.getOperationCodeName = code => {
|
||||||
|
return app.businessDict.OPERATION_CODE?.[code] || code;
|
||||||
|
};
|
||||||
|
app.getPlatformName = code => {
|
||||||
|
return app.businessDict.PLATFORM_CODE?.[code] || code;
|
||||||
|
};
|
||||||
|
|
||||||
|
app.getExternalLogTypeName = type => {
|
||||||
|
return app.businessDict.EXTERNAL_LOG_TYPE?.[type] || type;
|
||||||
|
};
|
||||||
|
|
||||||
|
app.logger.info('✅ 业务字典已挂载到 app');
|
||||||
|
// 初始化工厂
|
||||||
|
app.beforeStart(async () => {
|
||||||
|
// skip factory init when model layer is absent (e.g. during tests)
|
||||||
|
if (!app.model) {
|
||||||
|
app.logger.info('⚠️ skipping factory init: app.model not available');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const OrderDeliveryFactory = require('./app/model/order_delivery_factory');
|
||||||
|
const OrderItemsFactory = require('./app/model/order_items_factory');
|
||||||
|
app.OrderDeliveryFactory = OrderDeliveryFactory(app);
|
||||||
|
app.model.OrderDeliveryFactory = app.OrderDeliveryFactory;
|
||||||
|
app.OrderItemsFactory = OrderItemsFactory(app);
|
||||||
|
app.model.OrderItemsFactory = app.OrderItemsFactory;
|
||||||
|
app.logger.info('✅ 工厂类初始化完成');
|
||||||
|
} catch (error) {
|
||||||
|
|
||||||
|
app.logger.error('❌ 工厂类初始化失败:', error);
|
||||||
|
}
|
||||||
|
// 验证缓存方法
|
||||||
|
if (typeof app.setCacheAsync === 'function') {
|
||||||
|
app.setCacheAsync('system', 'eggjs');
|
||||||
|
const system = await app.getCacheAsync('system');
|
||||||
|
app.logger.info('✅ 缓存方法验证通过' + system);
|
||||||
|
}
|
||||||
|
app.logger.info('✅ l类型' + typeof app.Message);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 扩展 Date 原型
|
||||||
|
Date.prototype.format = function(formatStr = 'YYYY-MM-DD HH:mm:ss') {
|
||||||
|
const year = this.getFullYear();
|
||||||
|
const month = String(this.getMonth() + 1).padStart(2, '0');
|
||||||
|
const day = String(this.getDate()).padStart(2, '0');
|
||||||
|
const hours = String(this.getHours()).padStart(2, '0');
|
||||||
|
const minutes = String(this.getMinutes()).padStart(2, '0');
|
||||||
|
const seconds = String(this.getSeconds()).padStart(2, '0');
|
||||||
|
|
||||||
|
return formatStr
|
||||||
|
.replace('YYYY', year)
|
||||||
|
.replace('MM', month)
|
||||||
|
.replace('DD', day)
|
||||||
|
.replace('HH', hours)
|
||||||
|
.replace('mm', minutes)
|
||||||
|
.replace('ss', seconds);
|
||||||
|
};
|
||||||
|
};
|
||||||
169
app/controller/api_v2.js
Normal file
169
app/controller/api_v2.js
Normal file
@ -0,0 +1,169 @@
|
|||||||
|
const { Controller } = require('egg');
|
||||||
|
|
||||||
|
class ApiV2Controller extends Controller {
|
||||||
|
async index() {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
ctx.query_count = 1;
|
||||||
|
const startTime = Date.now();
|
||||||
|
const logData = {
|
||||||
|
method: '',
|
||||||
|
v: '',
|
||||||
|
url: ctx.request.href,
|
||||||
|
created_at: new Date(),
|
||||||
|
body: '',
|
||||||
|
headers: JSON.stringify(ctx.headers),
|
||||||
|
result: '',
|
||||||
|
use_time: 0,
|
||||||
|
auth: '',
|
||||||
|
store_id: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const getParams = ctx.query;
|
||||||
|
logData.method = getParams.method || '';
|
||||||
|
logData.v = getParams.v || '';
|
||||||
|
// 验证必要参数
|
||||||
|
if (!service.system.validateParams(getParams)) {
|
||||||
|
const errorMsg = '参数缺失或错误';
|
||||||
|
const response = this.errorResponse(errorMsg, 'json');
|
||||||
|
logData.result = response;
|
||||||
|
service.system.saveLog(logData, startTime);
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/json';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const authHeader = ctx.headers.authorization;
|
||||||
|
ctx.device = ctx.headers.device;
|
||||||
|
ctx.project = ctx.headers.project;
|
||||||
|
|
||||||
|
// 处理method参数
|
||||||
|
const method = getParams.method;
|
||||||
|
const methods = method.split('.');
|
||||||
|
const actionName = methods.pop();
|
||||||
|
const className = methods
|
||||||
|
.map((item, index) =>
|
||||||
|
(index === methods.length - 1 ? item : item)
|
||||||
|
)
|
||||||
|
.join('.');
|
||||||
|
|
||||||
|
// 获取JSON数据
|
||||||
|
let jsonData = '';
|
||||||
|
if (ctx.request.rawBody) {
|
||||||
|
jsonData = ctx.request.rawBody;
|
||||||
|
} else {
|
||||||
|
jsonData = await new Promise((resolve, reject) => {
|
||||||
|
let data = '';
|
||||||
|
ctx.req.on('data', chunk => {
|
||||||
|
data += chunk;
|
||||||
|
});
|
||||||
|
ctx.req.on('end', () => {
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
ctx.req.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
jsonData = jsonData ? String(jsonData) : '';
|
||||||
|
logData.body = jsonData;
|
||||||
|
if (!jsonData || jsonData.trim() === '') {
|
||||||
|
throw new Error('json数据为空');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
jsonData = JSON.parse(jsonData);
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error('json数据解析错误');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调用扁平 dispatcher 服务
|
||||||
|
const { isLog, result } = await service.dispatcher.invoke(
|
||||||
|
getParams.method,
|
||||||
|
jsonData,
|
||||||
|
authHeader,
|
||||||
|
ctx
|
||||||
|
);
|
||||||
|
logData.result = typeof result === 'string' ? result : JSON.stringify(result);
|
||||||
|
if (ctx.user) {
|
||||||
|
logData.auth = JSON.stringify(ctx.user);
|
||||||
|
logData.store_id = ctx.user.store_id;
|
||||||
|
}
|
||||||
|
// 保存原来的日志逻辑仍然通过 system.saveLog
|
||||||
|
if (isLog) {
|
||||||
|
service.system.saveLog(logData, startTime);
|
||||||
|
}
|
||||||
|
if (result.status && result.status !== 200) {
|
||||||
|
// propagate failure message
|
||||||
|
ctx.body = result.message ? { message: result.message } : result.data;
|
||||||
|
} else {
|
||||||
|
ctx.body = result.data;
|
||||||
|
}
|
||||||
|
ctx.type = 'application/json';
|
||||||
|
ctx.status = result.status || 200;
|
||||||
|
} catch (error) {
|
||||||
|
ctx.status = 500;
|
||||||
|
console.log(error);
|
||||||
|
const response = this.errorResponse('接口错误: ' + error.message, 'json');
|
||||||
|
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
|
||||||
|
service.system.saveLog(logData, startTime);
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/json';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateParams(params) {
|
||||||
|
const required = [ 'method', 'v', 'format', 'timestamp' ];
|
||||||
|
|
||||||
|
for (const field of required) {
|
||||||
|
if (!params[field]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof params.method !== 'string' || !params.method.includes('.')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
errorResponse(message, format = 'json') {
|
||||||
|
const timestamp = Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
|
if (format.toLowerCase() === 'xml') {
|
||||||
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<response>
|
||||||
|
<flag>failure</flag>
|
||||||
|
<code>0</code>
|
||||||
|
<message>${this.escapeXml(message)}</message>
|
||||||
|
</response>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
flag: false,
|
||||||
|
message,
|
||||||
|
code: 0,
|
||||||
|
timestamp,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
escapeXml(unsafe) {
|
||||||
|
if (!unsafe) return '';
|
||||||
|
return unsafe.replace(/[<>&'\"]/g, c => {
|
||||||
|
switch (c) {
|
||||||
|
case '<':
|
||||||
|
return '<';
|
||||||
|
case '>':
|
||||||
|
return '>';
|
||||||
|
case '&':
|
||||||
|
return '&';
|
||||||
|
case "'":
|
||||||
|
return ''';
|
||||||
|
case '"':
|
||||||
|
return '"';
|
||||||
|
default:
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ApiV2Controller;
|
||||||
118
app/controller/auth.js
Normal file
118
app/controller/auth.js
Normal file
@ -0,0 +1,118 @@
|
|||||||
|
const Controller = require('egg').Controller;
|
||||||
|
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
|
||||||
|
class AuthController extends Controller {
|
||||||
|
async printerSetting() {
|
||||||
|
const { ctx } = this;
|
||||||
|
const redis = this.app.redis;
|
||||||
|
if (ctx.method === 'GET') {
|
||||||
|
const code = ctx.params.code || '';
|
||||||
|
if (!code) {
|
||||||
|
ctx.body = { error: '缺少code参数' };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const bindValue = await redis.get('printer').get(`bind:${code}`);
|
||||||
|
if (!bindValue) {
|
||||||
|
ctx.body = { error: '无效code或未绑定' };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await redis.get('printer').setex(`binding:${code}`, 300, bindValue);
|
||||||
|
await ctx.render('printer_setting.html', {
|
||||||
|
title: '打印台设置',
|
||||||
|
code,
|
||||||
|
bindValue,
|
||||||
|
});
|
||||||
|
} else if (ctx.method === 'POST') {
|
||||||
|
const { code, printer, warehouse } = ctx.request.body;
|
||||||
|
if (!code || !printer || !warehouse) {
|
||||||
|
ctx.body = { success: false, error: '参数缺失' };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 获取临时binding:code
|
||||||
|
const bindingValue = await redis.get('printer').get(`binding:${code}`);
|
||||||
|
if (!bindingValue) {
|
||||||
|
ctx.body = { success: false, error: '超时或未绑定' };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 反序列化bindingValue
|
||||||
|
let bindingValueObj = bindingValue;
|
||||||
|
try {
|
||||||
|
bindingValueObj = JSON.parse(bindingValue);
|
||||||
|
} catch (e) {
|
||||||
|
bindingValueObj = bindingValue;
|
||||||
|
}
|
||||||
|
// 使用 Store model 校验仓库id
|
||||||
|
const Store = ctx.model.Store;
|
||||||
|
const warehouseInfo = await Store.findOne({ where: { id: warehouse } });
|
||||||
|
console.log('warehouseInfo:', warehouseInfo);
|
||||||
|
if (!warehouseInfo || warehouseInfo.project !== 'warehouse') {
|
||||||
|
ctx.body = { success: false, error: '仓库id校验失败' };
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 查找仓库id下是否有重名的电脑
|
||||||
|
const PrintComputer = ctx.model.PrintComputer;
|
||||||
|
let computerId = null;
|
||||||
|
const existComputer = await PrintComputer.findOne({ where: { warehouse_id: warehouse, name: printer } });
|
||||||
|
if (existComputer) {
|
||||||
|
if (existComputer.status === 1) {
|
||||||
|
ctx.body = { success: false, error: '该仓库下打印台名称已存在且可用' };
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
computerId = existComputer.id;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 创建新打印电脑
|
||||||
|
console.log('创建新打印电脑:', { warehouse_id: warehouse, name: printer, status: 0 });
|
||||||
|
const newComputer = await PrintComputer.create({ warehouse_id: warehouse, name: printer, status: 0 });
|
||||||
|
console.log('newComputer:', newComputer);
|
||||||
|
computerId = newComputer.id;
|
||||||
|
}
|
||||||
|
// 调用打印服务 /auth/bind,使用egg内置curl
|
||||||
|
const printServiceUrl = ctx.app.config.printService.url;
|
||||||
|
let printServiceResult = null;
|
||||||
|
try {
|
||||||
|
const res = await ctx.curl(`${printServiceUrl}/auth/bind`, {
|
||||||
|
method: 'POST',
|
||||||
|
contentType: 'json',
|
||||||
|
data: { code, printer, warehouse, roomId: bindingValueObj.uniqueId, computerId },
|
||||||
|
dataType: 'json',
|
||||||
|
});
|
||||||
|
printServiceResult = res.data;
|
||||||
|
} catch (err) {
|
||||||
|
console.log('调用打印服务失败:', err);
|
||||||
|
printServiceResult = { success: false, error: '打印服务通讯失败' };
|
||||||
|
}
|
||||||
|
console.log('printServiceResult:', printServiceResult);
|
||||||
|
// 判断打印服务返回结果
|
||||||
|
if (printServiceResult && printServiceResult.status === 'fail') {
|
||||||
|
ctx.body = {
|
||||||
|
success: false,
|
||||||
|
msg: printServiceResult.message || '打印服务失败',
|
||||||
|
code,
|
||||||
|
printer,
|
||||||
|
warehouse,
|
||||||
|
bindingValue: bindingValueObj,
|
||||||
|
printServiceResult
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log('printServiceResult:', printServiceResult);
|
||||||
|
ctx.body = {
|
||||||
|
success: true,
|
||||||
|
msg: '参数已接收',
|
||||||
|
code,
|
||||||
|
printer,
|
||||||
|
warehouse,
|
||||||
|
bindingValue: bindingValueObj,
|
||||||
|
computerId,
|
||||||
|
printServiceResult
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
ctx.body = { msg: '不支持的请求方法' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = AuthController;
|
||||||
587
app/controller/home.js
Normal file
587
app/controller/home.js
Normal file
@ -0,0 +1,587 @@
|
|||||||
|
const {
|
||||||
|
Controller,
|
||||||
|
} = require('egg');
|
||||||
|
|
||||||
|
class HomeController extends Controller {
|
||||||
|
async testSendData(){
|
||||||
|
await this.ctx.service.systems.print.index.test();
|
||||||
|
this.ctx.body = 'ok';
|
||||||
|
}
|
||||||
|
async index() {
|
||||||
|
const {
|
||||||
|
ctx,
|
||||||
|
} = this;
|
||||||
|
ctx.body = 'pong';
|
||||||
|
}
|
||||||
|
async v1() {
|
||||||
|
const {
|
||||||
|
ctx,
|
||||||
|
service,
|
||||||
|
} = this;
|
||||||
|
const startTime = Date.now();
|
||||||
|
// 初始化日志数据
|
||||||
|
const logData = {
|
||||||
|
app_key: '',
|
||||||
|
method: '',
|
||||||
|
sign: '',
|
||||||
|
costomer_id: '',
|
||||||
|
v: '',
|
||||||
|
url: ctx.request.href,
|
||||||
|
created_at: new Date(),
|
||||||
|
body: '',
|
||||||
|
result: '',
|
||||||
|
use_time: 0,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const getParams = ctx.query;
|
||||||
|
logData.method = getParams.method || '';
|
||||||
|
logData.v = getParams.v || '';
|
||||||
|
// 验证必要参数
|
||||||
|
if (!this.validateParams(getParams)) {
|
||||||
|
const errorMsg = '参数缺失或错误';
|
||||||
|
const response = this.errorResponse(errorMsg, 'json');
|
||||||
|
logData.result = response;
|
||||||
|
await this.saveLog(logData, startTime);
|
||||||
|
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/json';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理method参数
|
||||||
|
const method = getParams.method;
|
||||||
|
const methods = method.split('.');
|
||||||
|
const actionName = methods.pop();
|
||||||
|
const className = methods.map((item, index) =>
|
||||||
|
(index === methods.length - 1 ? item : item)
|
||||||
|
).join('.');
|
||||||
|
|
||||||
|
// 获取XML数据
|
||||||
|
let jsonData = '';
|
||||||
|
if (ctx.request.rawBody) {
|
||||||
|
// 使用 rawBody 获取原始请求体
|
||||||
|
jsonData = ctx.request.rawBody;
|
||||||
|
} else {
|
||||||
|
// 如果没有 rawBody,尝试从流中读取
|
||||||
|
jsonData = await new Promise((resolve, reject) => {
|
||||||
|
let data = '';
|
||||||
|
ctx.req.on('data', chunk => {
|
||||||
|
data += chunk;
|
||||||
|
});
|
||||||
|
ctx.req.on('end', () => {
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
ctx.req.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 确保 xmlData 是字符串
|
||||||
|
jsonData = jsonData ? String(jsonData) : '';
|
||||||
|
logData.body = jsonData;
|
||||||
|
if (!jsonData || jsonData.trim() === '') {
|
||||||
|
throw new Error('json数据为空');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
jsonData = JSON.parse(jsonData);
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error('json数据解析错误');
|
||||||
|
}
|
||||||
|
// 调用业务方法
|
||||||
|
const result = await service.api.callMethod(className, actionName, jsonData, getParams.format);
|
||||||
|
|
||||||
|
// 记录成功响应
|
||||||
|
logData.result = typeof result === 'string' ? result : JSON.stringify(result);
|
||||||
|
await this.saveLog(logData, startTime);
|
||||||
|
|
||||||
|
ctx.body = result;
|
||||||
|
ctx.type = getParams.format === 'xml' ? 'application/xml' : 'application/json';
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('调用接口失败返回数据', error);
|
||||||
|
const response = this.errorResponse('接口错误: ' + error.message, ctx.query.format || 'json');
|
||||||
|
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
|
||||||
|
await this.saveLog(logData, startTime);
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = ctx.query.format === 'xml' ? 'application/xml' : 'application/json';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async qimen() {
|
||||||
|
const {
|
||||||
|
ctx,
|
||||||
|
service,
|
||||||
|
} = this;
|
||||||
|
const startTime = Date.now();
|
||||||
|
|
||||||
|
// 初始化日志数据
|
||||||
|
const logData = {
|
||||||
|
from_key: '',
|
||||||
|
to_key: this.app.config.qimen.appKey,
|
||||||
|
method: '',
|
||||||
|
sign: '',
|
||||||
|
costomer_id: '',
|
||||||
|
v: '',
|
||||||
|
url: ctx.request.href,
|
||||||
|
created_at: new Date(),
|
||||||
|
body: '',
|
||||||
|
result: '',
|
||||||
|
use_time: 0,
|
||||||
|
};
|
||||||
|
const getParams = ctx.query;
|
||||||
|
// 记录基础日志信息
|
||||||
|
logData.from_key = getParams.app_key || '';
|
||||||
|
logData.method = getParams.method || '';
|
||||||
|
logData.sign = getParams.sign || '';
|
||||||
|
logData.costomer_id = getParams.customerId || getParams.customer_id || '';
|
||||||
|
logData.v = getParams.v || '';
|
||||||
|
ctx.qimenLogId = await service.qimen.saveQimenLog(logData, startTime);
|
||||||
|
try {
|
||||||
|
|
||||||
|
// 验证必要参数
|
||||||
|
if (!this.validateQimenParams(getParams)) {
|
||||||
|
const errorMsg = '参数缺失或错误';
|
||||||
|
const response = this.errorResponse(errorMsg, 'xml');
|
||||||
|
await service.qimen.saveQimenLogResult(response);
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/xml';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理method参数
|
||||||
|
const method = getParams.method;
|
||||||
|
const methods = method.split('.');
|
||||||
|
const actionName = methods.pop();
|
||||||
|
const className = methods.map((item, index) =>
|
||||||
|
(index === methods.length - 1 ? item : item)
|
||||||
|
).join('.');
|
||||||
|
|
||||||
|
const appkey = getParams.app_key;
|
||||||
|
const customerId = getParams.customerId;
|
||||||
|
|
||||||
|
// 获取XML数据
|
||||||
|
let xmlData = '';
|
||||||
|
if (ctx.request.rawBody) {
|
||||||
|
// 使用 rawBody 获取原始请求体
|
||||||
|
xmlData = ctx.request.rawBody;
|
||||||
|
} else {
|
||||||
|
// 如果没有 rawBody,尝试从流中读取
|
||||||
|
xmlData = await new Promise((resolve, reject) => {
|
||||||
|
let data = '';
|
||||||
|
ctx.req.on('data', chunk => {
|
||||||
|
data += chunk;
|
||||||
|
});
|
||||||
|
ctx.req.on('end', () => {
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
ctx.req.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 确保 xmlData 是字符串
|
||||||
|
xmlData = xmlData ? String(xmlData) : '';
|
||||||
|
|
||||||
|
if (!xmlData || xmlData.trim() === '') {
|
||||||
|
throw new Error('XML数据为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析XML数据
|
||||||
|
const xmlArray = await service.qimen.parseXmlToArray(xmlData);
|
||||||
|
xmlArray.app_key = appkey;
|
||||||
|
let warehouseCode = xmlArray.request.warehouseCode || '';
|
||||||
|
const ownerCode = customerId;
|
||||||
|
|
||||||
|
await service.qimen.saveQimenLogBody(xmlData);
|
||||||
|
const erpName = await service.qimen.getErpName(appkey);
|
||||||
|
let api_info = {
|
||||||
|
warehouseCode: '',
|
||||||
|
ownerCode: '',
|
||||||
|
};
|
||||||
|
if (!warehouseCode || !customerId) {
|
||||||
|
// 入库单提取
|
||||||
|
try {
|
||||||
|
warehouseCode = xmlArray.request?.entryOrder?.warehouseCode ||
|
||||||
|
xmlArray.request?.deliveryOrder?.warehouseCode ||
|
||||||
|
'';
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
if (warehouseCode && customerId) {
|
||||||
|
// 验证接口是否存在且启用
|
||||||
|
api_info = await service.qimen.validateApi(appkey, customerId, warehouseCode);
|
||||||
|
if (!api_info) {
|
||||||
|
const errorMsg = `奇门${erpName}客户编码${customerId}仓库编码${warehouseCode}未绑定到你的货主或未启用,请联系仓库绑定`;
|
||||||
|
const response = this.errorResponse(errorMsg, 'xml');
|
||||||
|
await service.qimen.saveQimenLogResult(response);
|
||||||
|
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/xml';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (api_info.contract_auth_status != 2) {
|
||||||
|
const errorMsg = `货主与仓库签约状态异常,请到WMS核实签约状态${api_info.contract_auth_status}`;
|
||||||
|
const response = this.errorResponse(errorMsg, 'xml');
|
||||||
|
await service.qimen.saveQimenLogResult(response);
|
||||||
|
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/xml';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (api_info.warehouse_status == 0) {
|
||||||
|
const errorMsg = '仓库状态异常,请联系仓库核实WMS状态';
|
||||||
|
const response = this.errorResponse(errorMsg, 'xml');
|
||||||
|
await service.qimen.saveQimenLogResult(response);
|
||||||
|
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/xml';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const currentTime = new Date();
|
||||||
|
const authEndTime = new Date(api_info.warehouse_auth_end);
|
||||||
|
const authEndTime2 = new Date(api_info.auth_end);
|
||||||
|
if (authEndTime2 < currentTime) {
|
||||||
|
const errorMsg = '与仓库合约过期,请到WMS重新发起仓库续约';
|
||||||
|
const response = this.errorResponse(errorMsg, 'xml');
|
||||||
|
await service.qimen.saveQimenLogResult(response);
|
||||||
|
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/xml';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (authEndTime < currentTime) {
|
||||||
|
const errorMsg = '仓库订阅过期,请联系仓库核实状态';
|
||||||
|
const response = this.errorResponse(errorMsg, 'xml');
|
||||||
|
await service.qimen.saveQimenLogResult(response);
|
||||||
|
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/xml';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调用业务方法
|
||||||
|
const result = await service.qimen.callMethod(className, actionName, xmlArray, api_info.store_id,
|
||||||
|
api_info.warehouse_id, appkey, customerId, warehouseCode, getParams.format);
|
||||||
|
// 记录成功响应
|
||||||
|
const logData_result = typeof result === 'string' ? result : JSON.stringify(result);
|
||||||
|
await service.qimen.saveQimenLogResult(logData_result);
|
||||||
|
|
||||||
|
ctx.body = result;
|
||||||
|
ctx.type = getParams.format === 'xml' ? 'application/xml' : 'application/json';
|
||||||
|
} catch (error) {
|
||||||
|
const response = this.errorResponse('奇门接口错误: ' + error.message, ctx.query.format || 'xml');
|
||||||
|
await service.qimen.saveQimenLogResult(response);
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = ctx.query.format === 'xml' ? 'application/xml' : 'application/json';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateParams(params) {
|
||||||
|
const required = [ 'method', 'v', 'format', 'timestamp' ];
|
||||||
|
|
||||||
|
for (const field of required) {
|
||||||
|
if (!params[field]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证method格式
|
||||||
|
if (typeof params.method !== 'string' || !params.method.includes('.')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
validateQimenParams(params) {
|
||||||
|
const required = [ 'app_key', 'method', 'v', 'format', 'sign_method', 'sign', 'timestamp' ];
|
||||||
|
|
||||||
|
for (const field of required) {
|
||||||
|
if (!params[field]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证method格式
|
||||||
|
if (typeof params.method !== 'string' || !params.method.includes('.')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
errorResponse(message, format = 'json') {
|
||||||
|
const timestamp = Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
|
if (format.toLowerCase() === 'xml') {
|
||||||
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<response>
|
||||||
|
<flag>failure</flag>
|
||||||
|
<code>0</code>
|
||||||
|
<message>${this.escapeXml(message)}</message>
|
||||||
|
</response>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
flag: false,
|
||||||
|
message,
|
||||||
|
code: 0,
|
||||||
|
timestamp,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
escapeXml(unsafe) {
|
||||||
|
if (!unsafe) return '';
|
||||||
|
return unsafe.replace(/[<>&'"]/g, c => {
|
||||||
|
switch (c) {
|
||||||
|
case '<':
|
||||||
|
return '<';
|
||||||
|
case '>':
|
||||||
|
return '>';
|
||||||
|
case '&':
|
||||||
|
return '&';
|
||||||
|
case '\'':
|
||||||
|
return ''';
|
||||||
|
case '"':
|
||||||
|
return '"';
|
||||||
|
default:
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async saveLog(logData, startTime) {
|
||||||
|
const {
|
||||||
|
ctx,
|
||||||
|
} = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 限制日志内容长度
|
||||||
|
if (logData.body && logData.body.length > 65535) {
|
||||||
|
logData.body = logData.body.substring(0, 65535);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (logData.result && logData.result.length > 65535) {
|
||||||
|
logData.result = logData.result.substring(0, 65535);
|
||||||
|
}
|
||||||
|
|
||||||
|
logData.use_time = Date.now() - startTime;
|
||||||
|
|
||||||
|
// 使用 egg-mysql 保存日志到数据库
|
||||||
|
const result = await ctx.app.mysql.get('wms').insert('wms_api_log', {
|
||||||
|
method: logData.method || '',
|
||||||
|
v: logData.v || '',
|
||||||
|
url: logData.url || '',
|
||||||
|
created_at: ctx.app.mysql.get('wms').literals.now,
|
||||||
|
body: logData.body || '',
|
||||||
|
result: logData.result || '',
|
||||||
|
use_time: logData.use_time || 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('保存奇门接口日志失败: ' + error.message);
|
||||||
|
// 可以选择记录到文件日志作为备用
|
||||||
|
ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async pda() {
|
||||||
|
const {
|
||||||
|
ctx,
|
||||||
|
service,
|
||||||
|
} = this;
|
||||||
|
ctx.query_count = 1;
|
||||||
|
const startTime = Date.now();
|
||||||
|
const logData = {
|
||||||
|
method: '',
|
||||||
|
v: '',
|
||||||
|
url: ctx.request.href,
|
||||||
|
created_at: new Date(),
|
||||||
|
body: '',
|
||||||
|
headers: JSON.stringify(ctx.headers),
|
||||||
|
result: '',
|
||||||
|
use_time: 0,
|
||||||
|
auth: '',
|
||||||
|
store_id: null,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const getParams = ctx.query;
|
||||||
|
logData.method = getParams.method || '';
|
||||||
|
logData.v = getParams.v || '';
|
||||||
|
// 验证必要参数
|
||||||
|
if (!service.system.validateParams(getParams)) {
|
||||||
|
const errorMsg = '参数缺失或错误';
|
||||||
|
const response = this.errorResponse(errorMsg, 'json');
|
||||||
|
logData.result = response;
|
||||||
|
service.system.saveLog(logData, startTime);
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/json';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const authHeader = ctx.headers.authorization;
|
||||||
|
|
||||||
|
// 处理method参数
|
||||||
|
const method = getParams.method;
|
||||||
|
const methods = method.split('.');
|
||||||
|
const actionName = methods.pop();
|
||||||
|
const className = methods.map((item, index) =>
|
||||||
|
(index === methods.length - 1 ? item : item)
|
||||||
|
).join('.');
|
||||||
|
|
||||||
|
// 获取JSON数据
|
||||||
|
let jsonData = '';
|
||||||
|
if (ctx.request.rawBody) {
|
||||||
|
// 使用 rawBody 获取原始请求体
|
||||||
|
jsonData = ctx.request.rawBody;
|
||||||
|
} else {
|
||||||
|
// 如果没有 rawBody,尝试从流中读取
|
||||||
|
jsonData = await new Promise((resolve, reject) => {
|
||||||
|
let data = '';
|
||||||
|
ctx.req.on('data', chunk => {
|
||||||
|
data += chunk;
|
||||||
|
});
|
||||||
|
ctx.req.on('end', () => {
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
ctx.req.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 确保 jsonData 是字符串
|
||||||
|
jsonData = jsonData ? String(jsonData) : '';
|
||||||
|
logData.body = jsonData;
|
||||||
|
if (!jsonData || jsonData.trim() === '') {
|
||||||
|
throw new Error('json数据为空');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
jsonData = JSON.parse(jsonData);
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error('json数据解析错误');
|
||||||
|
}
|
||||||
|
// 调用业务方法
|
||||||
|
const { isLog, result } = await service.system.callMethod(className, actionName, jsonData, authHeader);
|
||||||
|
// 记录成功响应
|
||||||
|
logData.result = typeof result === 'string' ? result : JSON.stringify(result);
|
||||||
|
if (ctx.user) {
|
||||||
|
logData.auth = JSON.stringify(ctx.user);
|
||||||
|
logData.store_id = ctx.user.store_id;
|
||||||
|
}
|
||||||
|
if (isLog) {
|
||||||
|
service.system.saveLog(logData, startTime);
|
||||||
|
}
|
||||||
|
ctx.body = result.data;
|
||||||
|
ctx.type = 'application/json';
|
||||||
|
ctx.status = result.status || 200;
|
||||||
|
} catch (error) {
|
||||||
|
ctx.status = 500;
|
||||||
|
console.log(error);
|
||||||
|
const response = this.errorResponse('接口错误: ' + error.message, 'json');
|
||||||
|
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
|
||||||
|
service.system.saveLog(logData, startTime);
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/json';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async store() {
|
||||||
|
|
||||||
|
}
|
||||||
|
async warehouse() {
|
||||||
|
|
||||||
|
}
|
||||||
|
async system() {
|
||||||
|
const {
|
||||||
|
ctx,
|
||||||
|
service,
|
||||||
|
} = this;
|
||||||
|
ctx.query_count = 1;
|
||||||
|
const startTime = Date.now();
|
||||||
|
const logData = {
|
||||||
|
method: '',
|
||||||
|
v: '',
|
||||||
|
url: ctx.request.href,
|
||||||
|
created_at: new Date(),
|
||||||
|
body: '',
|
||||||
|
headers: JSON.stringify(ctx.headers),
|
||||||
|
result: '',
|
||||||
|
use_time: 0,
|
||||||
|
auth: '',
|
||||||
|
store_id: null,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const getParams = ctx.query;
|
||||||
|
logData.method = getParams.method || '';
|
||||||
|
logData.v = getParams.v || '';
|
||||||
|
// 验证必要参数
|
||||||
|
if (!service.system.validateParams(getParams)) {
|
||||||
|
const errorMsg = '参数缺失或错误';
|
||||||
|
const response = this.errorResponse(errorMsg, 'json');
|
||||||
|
logData.result = response;
|
||||||
|
service.system.saveLog(logData, startTime);
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/json';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const authHeader = ctx.headers.authorization;
|
||||||
|
ctx.device = ctx.headers.device;
|
||||||
|
ctx.project = ctx.headers.project;
|
||||||
|
|
||||||
|
// 处理method参数
|
||||||
|
const method = getParams.method;
|
||||||
|
const methods = method.split('.');
|
||||||
|
const actionName = methods.pop();
|
||||||
|
const className = methods.map((item, index) =>
|
||||||
|
(index === methods.length - 1 ? item : item)
|
||||||
|
).join('.');
|
||||||
|
|
||||||
|
// 获取JSON数据
|
||||||
|
let jsonData = '';
|
||||||
|
if (ctx.request.rawBody) {
|
||||||
|
// 使用 rawBody 获取原始请求体
|
||||||
|
jsonData = ctx.request.rawBody;
|
||||||
|
} else {
|
||||||
|
// 如果没有 rawBody,尝试从流中读取
|
||||||
|
jsonData = await new Promise((resolve, reject) => {
|
||||||
|
let data = '';
|
||||||
|
ctx.req.on('data', chunk => {
|
||||||
|
data += chunk;
|
||||||
|
});
|
||||||
|
ctx.req.on('end', () => {
|
||||||
|
resolve(data);
|
||||||
|
});
|
||||||
|
ctx.req.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 确保 jsonData 是字符串
|
||||||
|
jsonData = jsonData ? String(jsonData) : '';
|
||||||
|
logData.body = jsonData;
|
||||||
|
if (!jsonData || jsonData.trim() === '') {
|
||||||
|
throw new Error('json数据为空');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
jsonData = JSON.parse(jsonData);
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error('json数据解析错误');
|
||||||
|
}
|
||||||
|
// 调用业务方法
|
||||||
|
const { isLog, result } = await service.system.callMethod(className, actionName, jsonData, authHeader);
|
||||||
|
// 记录成功响应
|
||||||
|
logData.result = typeof result === 'string' ? result : JSON.stringify(result);
|
||||||
|
if (ctx.user) {
|
||||||
|
logData.auth = JSON.stringify(ctx.user);
|
||||||
|
logData.store_id = ctx.user.store_id;
|
||||||
|
}
|
||||||
|
if (isLog) {
|
||||||
|
service.system.saveLog(logData, startTime);
|
||||||
|
}
|
||||||
|
ctx.body = result.data;
|
||||||
|
ctx.type = 'application/json';
|
||||||
|
ctx.status = result.status || 200;
|
||||||
|
} catch (error) {
|
||||||
|
ctx.status = 500;
|
||||||
|
console.log(error);
|
||||||
|
const response = this.errorResponse('接口错误: ' + error.message, 'json');
|
||||||
|
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
|
||||||
|
service.system.saveLog(logData, startTime);
|
||||||
|
ctx.body = response;
|
||||||
|
ctx.type = 'application/json';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = HomeController;
|
||||||
12
app/controller/template.js
Normal file
12
app/controller/template.js
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
const {
|
||||||
|
Controller,
|
||||||
|
} = require('egg');
|
||||||
|
|
||||||
|
class TemplateController extends Controller {
|
||||||
|
async xml() {
|
||||||
|
const { service, ctx } = this;
|
||||||
|
const result = await service.systems.setting.printTemplate.getXmlByTemplate(ctx.params.id);
|
||||||
|
ctx.body = result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = TemplateController;
|
||||||
190
app/dict/businessDict.js
Normal file
190
app/dict/businessDict.js
Normal file
@ -0,0 +1,190 @@
|
|||||||
|
// app/dict/businessDict.js
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
|
||||||
|
PLATFORM_CODE: {
|
||||||
|
web: '网页后台',
|
||||||
|
SYSTEM: '系统',
|
||||||
|
pda: 'PDA',
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* 业务类型字典
|
||||||
|
*/
|
||||||
|
BUSINESS_TYPE: {
|
||||||
|
PRODUCT: { code: 'product', name: '商品管理' },
|
||||||
|
ORDER: { code: 'order', name: '订单管理' },
|
||||||
|
STOCK: { code: 'stock', name: '库存管理' },
|
||||||
|
WAVE: { code: 'wave', name: '波次管理' },
|
||||||
|
EXPRESS: { code: 'express', name: '快递管理' },
|
||||||
|
STORAGE: { code: 'storage', name: '仓储管理' },
|
||||||
|
LOCATION: { code: 'location', name: '库位管理' },
|
||||||
|
USER: { code: 'user', name: '用户管理' },
|
||||||
|
SYSTEM: { code: 'system', name: '系统管理' },
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 操作动作字典
|
||||||
|
*/
|
||||||
|
OPERATION_ACTION: {
|
||||||
|
CREATE: '创建',
|
||||||
|
UPDATE: '更新',
|
||||||
|
DELETE: '删除',
|
||||||
|
OTHER: '其他',
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 操作编码字典
|
||||||
|
*/
|
||||||
|
OPERATION_CODE: {
|
||||||
|
// 商品管理
|
||||||
|
CREATE: '创建',
|
||||||
|
UPDATE: '更新',
|
||||||
|
DELETE: '删除',
|
||||||
|
ENABLE: '启用',
|
||||||
|
DISABLE: '禁用',
|
||||||
|
IMPORT: '导入',
|
||||||
|
EXPORT: '导出',
|
||||||
|
|
||||||
|
// 订单管理
|
||||||
|
ORDER_CREATE: '创建订单',
|
||||||
|
ORDER_UPDATE: '更新订单',
|
||||||
|
ORDER_CANCEL: '取消订单',
|
||||||
|
ORDER_CONFIRM: '确认订单',
|
||||||
|
ORDER_PRINT: '打印订单',
|
||||||
|
ORDER_PICKING: '开始拣货',
|
||||||
|
ORDER_PACKED: '订单打包',
|
||||||
|
ORDER_SHIPPED: '订单发货',
|
||||||
|
ORDER_COMPLETE: '订单完成',
|
||||||
|
|
||||||
|
// 库存管理
|
||||||
|
STOCK_IN: '商品入库',
|
||||||
|
STOCK_OUT: '商品出库',
|
||||||
|
STOCK_ADJUST: '库存调整',
|
||||||
|
STOCK_TRANSFER: '库存调拨',
|
||||||
|
STOCK_CHECK: '库存盘点',
|
||||||
|
STOCK_LOCK: '锁定库存',
|
||||||
|
STOCK_UNLOCK: '解锁库存',
|
||||||
|
STOCK_QUERY: '库存查询',
|
||||||
|
|
||||||
|
// 波次管理
|
||||||
|
WAVE_CREATE: '创建波次',
|
||||||
|
WAVE_CONFIRM: '确认波次',
|
||||||
|
WAVE_START: '开始波次',
|
||||||
|
WAVE_COMPLETE: '完成波次',
|
||||||
|
WAVE_CANCEL: '取消波次',
|
||||||
|
|
||||||
|
// 快递管理
|
||||||
|
EXPRESS_CREATE: '创建快递单',
|
||||||
|
EXPRESS_UPDATE: '更新快递信息',
|
||||||
|
EXPRESS_CANCEL: '取消快递单',
|
||||||
|
EXPRESS_QUERY: '查询快递',
|
||||||
|
|
||||||
|
// 库位管理
|
||||||
|
LOCATION_CREATE: '创建库位',
|
||||||
|
LOCATION_UPDATE: '更新库位',
|
||||||
|
LOCATION_DELETE: '删除库位',
|
||||||
|
LOCATION_ENABLE: '启用库位',
|
||||||
|
LOCATION_DISABLE: '禁用库位',
|
||||||
|
|
||||||
|
// 用户管理
|
||||||
|
USER_LOGIN: '用户登录',
|
||||||
|
USER_LOGOUT: '用户退出',
|
||||||
|
USER_CREATE: '创建用户',
|
||||||
|
USER_UPDATE: '更新用户',
|
||||||
|
USER_DELETE: '删除用户',
|
||||||
|
|
||||||
|
// 系统管理
|
||||||
|
CONFIG_UPDATE: '更新配置',
|
||||||
|
ROLE_CREATE: '创建角色',
|
||||||
|
ROLE_UPDATE: '更新角色',
|
||||||
|
ROLE_DELETE: '删除角色',
|
||||||
|
PERMISSION_UPDATE: '更新权限',
|
||||||
|
UPDATE_IMAGES: '更新图片',
|
||||||
|
UPDATE_BARCODE: '更新条码',
|
||||||
|
BIND: '绑定',
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 外部日志类型
|
||||||
|
*/
|
||||||
|
EXTERNAL_LOG_TYPE: {
|
||||||
|
REQUEST: 'HTTP请求',
|
||||||
|
API: 'API调用',
|
||||||
|
QIMEN: '奇门接口',
|
||||||
|
ERP: 'ERP接口',
|
||||||
|
WMS: 'WMS接口',
|
||||||
|
TMS: 'TMS接口',
|
||||||
|
NONE: '无',
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 操作状态
|
||||||
|
*/
|
||||||
|
OPERATION_STATUS: {
|
||||||
|
SUCCESS: '成功',
|
||||||
|
FAILED: '失败',
|
||||||
|
PROCESSING: '处理中',
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 仓库状态
|
||||||
|
*/
|
||||||
|
WAREHOUSE_STATUS: {
|
||||||
|
ACTIVE: '启用',
|
||||||
|
INACTIVE: '停用',
|
||||||
|
MAINTENANCE: '维护中',
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订单状态
|
||||||
|
*/
|
||||||
|
ORDER_STATUS: {
|
||||||
|
PENDING: '待处理',
|
||||||
|
CONFIRMED: '已确认',
|
||||||
|
PICKING: '拣货中',
|
||||||
|
PACKED: '已打包',
|
||||||
|
SHIPPED: '已发货',
|
||||||
|
COMPLETED: '已完成',
|
||||||
|
CANCELLED: '已取消',
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有业务类型选项
|
||||||
|
*/
|
||||||
|
getBusinessTypeOptions() {
|
||||||
|
return Object.values(this.BUSINESS_TYPE).map(item => ({
|
||||||
|
label: item.name,
|
||||||
|
value: item.code,
|
||||||
|
}));
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取指定业务类型的操作编码
|
||||||
|
* @param businessType
|
||||||
|
*/
|
||||||
|
getOperationCodesByBusinessType(businessType) {
|
||||||
|
const prefix = businessType.toUpperCase() + '_';
|
||||||
|
const result = {};
|
||||||
|
|
||||||
|
for (const [ key, value ] of Object.entries(this.OPERATION_CODE)) {
|
||||||
|
if (key.startsWith(prefix)) {
|
||||||
|
result[key] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证操作编码是否属于指定业务类型
|
||||||
|
* @param code
|
||||||
|
* @param businessType
|
||||||
|
*/
|
||||||
|
validateOperationCode(code, businessType) {
|
||||||
|
if (!businessType) return true;
|
||||||
|
|
||||||
|
const prefix = businessType.toUpperCase() + '_';
|
||||||
|
return code.startsWith(prefix);
|
||||||
|
},
|
||||||
|
};
|
||||||
63
app/extend/application.js
Normal file
63
app/extend/application.js
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
class MessageClass {
|
||||||
|
async action() {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const soap = require('soap');
|
||||||
|
const MESSAGE_CLASS = Symbol('Application#Message');
|
||||||
|
module.exports = {
|
||||||
|
async wsdl(methodName, args) {
|
||||||
|
try {
|
||||||
|
const wsdlUrl = "http://ye4s.com/webservice/ws?wsdl";
|
||||||
|
const obj = {};
|
||||||
|
args.forEach((value, index) => {
|
||||||
|
obj['arg' + index] = value;
|
||||||
|
});
|
||||||
|
const client = await soap.createClientAsync(wsdlUrl);
|
||||||
|
const result = await client[methodName + 'Async'](obj);
|
||||||
|
return result[0];
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error calling SOAP service:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async setCacheAsync(cacheKey, data, expireSeconds = 300) {
|
||||||
|
const cacheRedis = this.redis && this.redis.get ? this.redis.get('cache') : null;
|
||||||
|
if (!cacheRedis) {
|
||||||
|
this.logger.warn('[RedisNotAvailable] Cannot set cache, Redis client is not available');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await cacheRedis.setex(cacheKey, expireSeconds, JSON.stringify(data));
|
||||||
|
this.logger.debug('[CacheSet] Successfully set cache', cacheKey);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error('[CacheSetError] Failed to set cache', error.message, cacheKey);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async getCacheAsync(cacheKey) {
|
||||||
|
const cacheRedis = this.redis && this.redis.get ? this.redis.get('cache') : null;
|
||||||
|
if (!cacheRedis) {
|
||||||
|
this.logger.warn('[RedisNotAvailable] Cannot get cache, Redis client is not available');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await cacheRedis.get(cacheKey);
|
||||||
|
if (data) {
|
||||||
|
return JSON.parse(data);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error('[CacheGetError] Failed to get cache', error.message, cacheKey);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
get Message() {
|
||||||
|
if (!this[MESSAGE_CLASS]) {
|
||||||
|
// 返回类本身,不是实例
|
||||||
|
this[MESSAGE_CLASS] = MessageClass;
|
||||||
|
}
|
||||||
|
return this[MESSAGE_CLASS];
|
||||||
|
},
|
||||||
|
};
|
||||||
189
app/model/account.js
Normal file
189
app/model/account.js
Normal file
@ -0,0 +1,189 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, STRING, INTEGER, DATE, TINYINT, fn } = app.Sequelize;
|
||||||
|
|
||||||
|
const Account = app.model.define('account', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '账号ID',
|
||||||
|
},
|
||||||
|
username: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
unique: 'idx_username',
|
||||||
|
validate: {
|
||||||
|
notEmpty: {
|
||||||
|
msg: '用户名不能为空',
|
||||||
|
},
|
||||||
|
len: {
|
||||||
|
args: [ 3, 50 ],
|
||||||
|
msg: '用户名长度应在3-50个字符之间',
|
||||||
|
},
|
||||||
|
is: {
|
||||||
|
args: /^[a-zA-Z0-9_]+$/,
|
||||||
|
msg: '用户名只能包含字母、数字和下划线',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '用户名',
|
||||||
|
},
|
||||||
|
email: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: {
|
||||||
|
msg: '邮箱不能为空',
|
||||||
|
},
|
||||||
|
isEmail: {
|
||||||
|
msg: '请输入有效的邮箱地址',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '邮箱',
|
||||||
|
},
|
||||||
|
password_hash: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '密码哈希',
|
||||||
|
},
|
||||||
|
real_name: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: {
|
||||||
|
msg: '真实姓名不能为空',
|
||||||
|
},
|
||||||
|
len: {
|
||||||
|
args: [ 2, 50 ],
|
||||||
|
msg: '真实姓名长度应在2-50个字符之间',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '真实姓名',
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: TINYINT(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
validate: {
|
||||||
|
isIn: {
|
||||||
|
args: [[ 0, 1 ]],
|
||||||
|
msg: '状态值不合法,0-封号,1-启用',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '状态:0-封号,1-启用',
|
||||||
|
},
|
||||||
|
last_login_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '最后登录时间',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: fn('NOW'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: fn('NOW'),
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
salt: {
|
||||||
|
type: STRING(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '密码盐',
|
||||||
|
},
|
||||||
|
last_login_ip: {
|
||||||
|
type: STRING(15),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '最后登录ip',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_account',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: true,
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
comment: '平台账号表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'idx_username',
|
||||||
|
fields: [ 'username' ],
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_phone',
|
||||||
|
fields: [ 'phone' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_email',
|
||||||
|
fields: [ 'email' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_status',
|
||||||
|
fields: [ 'status' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系
|
||||||
|
Account.associate = function(models) {
|
||||||
|
const { AccountStoreEmployee, AccountPlatformActive } = app.model;
|
||||||
|
/* if (models.AccountStoreRole) {
|
||||||
|
|
||||||
|
}*/
|
||||||
|
Account.hasMany(AccountStoreEmployee, {
|
||||||
|
foreignKey: 'account_id',
|
||||||
|
as: 'accountStoreRoles',
|
||||||
|
});
|
||||||
|
Account.hasMany(AccountPlatformActive, {
|
||||||
|
foreignKey: 'account_id',
|
||||||
|
as: 'platformActives',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法
|
||||||
|
Account.prototype.toJSON = function() {
|
||||||
|
const values = { ...this.get() };
|
||||||
|
// 只有在需要返回给客户端时才删除敏感字段
|
||||||
|
if (this._hideSensitive !== false) {
|
||||||
|
delete values.password_hash;
|
||||||
|
delete values.salt;
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 验证密码
|
||||||
|
Account.prototype.verifyPassword = async function(password) {
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
// 检查 password_hash 是否存在
|
||||||
|
if (!this.password_hash) {
|
||||||
|
console.error('password_hash is undefined for user:', this.id);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查 salt 是否存在
|
||||||
|
if (!this.salt) {
|
||||||
|
console.error('salt is undefined for user:', this.id);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hash = crypto
|
||||||
|
.createHash('sha256')
|
||||||
|
.update(password + (this.salt || ''))
|
||||||
|
.digest('hex');
|
||||||
|
|
||||||
|
console.log(`计算后的hash: ${hash}`);
|
||||||
|
console.log(`数据库中的password_hash: ${this.password_hash}`);
|
||||||
|
console.log(`是否匹配: ${hash === this.password_hash}`);
|
||||||
|
|
||||||
|
return hash === this.password_hash;
|
||||||
|
};
|
||||||
|
|
||||||
|
return Account;
|
||||||
|
};
|
||||||
91
app/model/account_platform_active.js
Normal file
91
app/model/account_platform_active.js
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, STRING, DATE } = app.Sequelize;
|
||||||
|
|
||||||
|
const AccountPlatformActive = app.model.define('account_platform_active', {
|
||||||
|
account_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '账号ID',
|
||||||
|
},
|
||||||
|
employee_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '账号仓库角色关联ID',
|
||||||
|
},
|
||||||
|
platform_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
len: [ 1, 50 ],
|
||||||
|
},
|
||||||
|
comment: '平台编码(web、pda、mini、app等)',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_account_platform_active',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: true,
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
paranoid: false, // 明确禁用软删除
|
||||||
|
comment: '账号平台激活状态表',
|
||||||
|
// 无主键ID,使用组合主键
|
||||||
|
id: false,
|
||||||
|
// 指定组合主键
|
||||||
|
primaryKey: [ 'account_id', 'platform_code' ],
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_account_platform',
|
||||||
|
fields: [ 'account_id', 'platform_code' ],
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'uk_account_store_role_platform',
|
||||||
|
fields: [ 'employee_id', 'platform_code' ],
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_account_id',
|
||||||
|
fields: [ 'account_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_platform_code',
|
||||||
|
fields: [ 'platform_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_employee_id',
|
||||||
|
fields: [ 'employee_id' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系 - 注释掉或删除,统一在 app.js 中处理
|
||||||
|
AccountPlatformActive.associate = function(models) {
|
||||||
|
const { Account, AccountStoreEmployee } = app.model;
|
||||||
|
AccountPlatformActive.belongsTo(Account, {
|
||||||
|
foreignKey: 'account_id',
|
||||||
|
as: 'account',
|
||||||
|
});
|
||||||
|
AccountPlatformActive.belongsTo(AccountStoreEmployee, {
|
||||||
|
foreignKey: 'employee_id',
|
||||||
|
as: 'accountStoreEmployee',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return AccountPlatformActive;
|
||||||
|
};
|
||||||
111
app/model/account_store_employee.js
Normal file
111
app/model/account_store_employee.js
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, STRING, DATE, TINYINT } = app.Sequelize;
|
||||||
|
|
||||||
|
const AccountStoreEmployee = app.model.define('wms_account_store_employee', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '关联ID',
|
||||||
|
},
|
||||||
|
account_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '账号ID',
|
||||||
|
},
|
||||||
|
store_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库ID',
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: TINYINT(4),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
validate: {
|
||||||
|
isIn: {
|
||||||
|
args: [[ 0, 1 ]],
|
||||||
|
msg: '状态值不合法,0-已解除,1-有效',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '状态:0-已解除,1-有效',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
real_name: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '工号的真实姓名',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_account_store_employee',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: true,
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
comment: '账号仓库角色关联表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_account_store_role',
|
||||||
|
fields: [ 'account_id', 'store_id' ],
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_account_id',
|
||||||
|
fields: [ 'account_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_store_id',
|
||||||
|
fields: [ 'store_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_status',
|
||||||
|
fields: [ 'status' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系
|
||||||
|
AccountStoreEmployee.associate = function(models) {
|
||||||
|
const { Account, Store, Role, AccountPlatformActive, EmployeeRole, Receiving } = app.model;
|
||||||
|
AccountStoreEmployee.belongsTo(Account, {
|
||||||
|
foreignKey: 'account_id',
|
||||||
|
as: 'account',
|
||||||
|
});
|
||||||
|
AccountStoreEmployee.belongsTo(Store, {
|
||||||
|
foreignKey: 'store_id',
|
||||||
|
as: 'store',
|
||||||
|
});
|
||||||
|
AccountStoreEmployee.hasMany(AccountPlatformActive, {
|
||||||
|
foreignKey: 'employee_id',
|
||||||
|
as: 'platformActives',
|
||||||
|
});
|
||||||
|
AccountStoreEmployee.hasMany(EmployeeRole, {
|
||||||
|
foreignKey: 'employee_id',
|
||||||
|
as: 'employeeRole',
|
||||||
|
});
|
||||||
|
AccountStoreEmployee.hasMany(Receiving, {
|
||||||
|
foreignKey: 'creator_id',
|
||||||
|
as: 'Receiving',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:检查是否有效
|
||||||
|
AccountStoreEmployee.prototype.isValid = function() {
|
||||||
|
return this.status === 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
return AccountStoreEmployee;
|
||||||
|
};
|
||||||
309
app/model/api_app.js
Normal file
309
app/model/api_app.js
Normal file
@ -0,0 +1,309 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, STRING, INTEGER, JSON, TINYINT, DATE } = app.Sequelize;
|
||||||
|
|
||||||
|
const ApiApp = app.model.define('api_app', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '应用ID',
|
||||||
|
},
|
||||||
|
app_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
len: [ 1, 200 ],
|
||||||
|
},
|
||||||
|
comment: '应用名称',
|
||||||
|
},
|
||||||
|
interface_type_id: {
|
||||||
|
type: INTEGER(10),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '接口类型ID',
|
||||||
|
references: {
|
||||||
|
model: 'interface_type',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
contract_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '合约ID,关联wms_store_warehouse.id(货主接口使用)',
|
||||||
|
references: {
|
||||||
|
model: 'store_warehouse',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '仓库ID(仓库接口使用)',
|
||||||
|
},
|
||||||
|
self_app_key: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
unique: 'uk_self_app_key',
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 100 ],
|
||||||
|
},
|
||||||
|
comment: '自身AppKey(开放接口使用,系统生成)',
|
||||||
|
},
|
||||||
|
self_app_secret: {
|
||||||
|
type: STRING(500),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 500 ],
|
||||||
|
},
|
||||||
|
comment: '自身AppSecret(开放接口使用,系统生成)',
|
||||||
|
},
|
||||||
|
self_ip_whitelist: {
|
||||||
|
type: JSON,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '自身IP白名单',
|
||||||
|
},
|
||||||
|
qimen_app_key: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 100 ],
|
||||||
|
},
|
||||||
|
comment: '奇门对方AppKey',
|
||||||
|
},
|
||||||
|
qimen_customer_id: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 100 ],
|
||||||
|
},
|
||||||
|
comment: '奇门客户ID',
|
||||||
|
},
|
||||||
|
qimen_warehouse_code: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 100 ],
|
||||||
|
},
|
||||||
|
comment: '奇门仓库编码',
|
||||||
|
},
|
||||||
|
api_version: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: '1.0',
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 50 ],
|
||||||
|
},
|
||||||
|
comment: 'API版本',
|
||||||
|
},
|
||||||
|
sign_method: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'md5',
|
||||||
|
validate: {
|
||||||
|
isIn: [[ 'md5', 'hmac', 'sha256' ]],
|
||||||
|
len: [ 0, 50 ],
|
||||||
|
},
|
||||||
|
comment: '签名方法',
|
||||||
|
},
|
||||||
|
rate_limit: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 1000,
|
||||||
|
validate: {
|
||||||
|
min: 1,
|
||||||
|
max: 100000,
|
||||||
|
},
|
||||||
|
comment: '速率限制(次/分钟)',
|
||||||
|
},
|
||||||
|
timeout_seconds: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 30,
|
||||||
|
validate: {
|
||||||
|
min: 1,
|
||||||
|
max: 300,
|
||||||
|
},
|
||||||
|
comment: '超时时间(秒)',
|
||||||
|
},
|
||||||
|
contact_person: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 100 ],
|
||||||
|
},
|
||||||
|
comment: '联系人',
|
||||||
|
},
|
||||||
|
contact_phone: {
|
||||||
|
type: STRING(20),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 20 ],
|
||||||
|
},
|
||||||
|
comment: '联系电话',
|
||||||
|
},
|
||||||
|
email: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
isEmail: true,
|
||||||
|
len: [ 0, 100 ],
|
||||||
|
},
|
||||||
|
comment: '邮箱',
|
||||||
|
},
|
||||||
|
is_enabled: {
|
||||||
|
type: TINYINT(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
validate: {
|
||||||
|
isIn: [[ 0, 1 ]],
|
||||||
|
},
|
||||||
|
comment: '是否启用',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_api_app',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: true,
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
comment: 'API应用配置表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_app_name_interface',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'app_name', 'interface_type_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'uk_self_app_key',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'self_app_key' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'uk_interface_warehouse',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'qimen_app_key', 'qimen_customer_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'uk_interface_contract',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'interface_type_id', 'contract_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_interface_type_id',
|
||||||
|
fields: [ 'interface_type_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse_id',
|
||||||
|
fields: [ 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_is_enabled',
|
||||||
|
fields: [ 'is_enabled' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_created_at',
|
||||||
|
fields: [ 'created_at' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_interface_enabled',
|
||||||
|
fields: [ 'interface_type_id', 'is_enabled' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 定义关联关系
|
||||||
|
ApiApp.associate = function() {
|
||||||
|
const { InterfaceType, StoreWarehouse, Store, InterfaceLog } = app.model;
|
||||||
|
|
||||||
|
// 关联接口类型
|
||||||
|
ApiApp.belongsTo(InterfaceType, {
|
||||||
|
foreignKey: 'interface_type_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'interface_type',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联合约(商家仓库授权关系)
|
||||||
|
ApiApp.belongsTo(StoreWarehouse, {
|
||||||
|
foreignKey: 'contract_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'contract',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联仓库
|
||||||
|
ApiApp.belongsTo(Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'warehouse',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 检查应用是否可用
|
||||||
|
ApiApp.prototype.isAvailable = function() {
|
||||||
|
return this.is_enabled === 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 检查IP是否在白名单中
|
||||||
|
ApiApp.prototype.isIpAllowed = function(ip) {
|
||||||
|
if (!this.self_ip_whitelist || !Array.isArray(this.self_ip_whitelist)) {
|
||||||
|
return true; // 如果没有设置白名单,允许所有IP
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.self_ip_whitelist.includes(ip);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 生成签名(示例)
|
||||||
|
ApiApp.prototype.generateSignature = function(params) {
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const sortedParams = Object.keys(params).sort().map(key => `${key}${params[key]}`)
|
||||||
|
.join('');
|
||||||
|
|
||||||
|
switch (this.sign_method) {
|
||||||
|
case 'md5':
|
||||||
|
return crypto.createHash('md5').update(sortedParams + this.self_app_secret).digest('hex');
|
||||||
|
case 'hmac':
|
||||||
|
return crypto.createHmac('sha256', this.self_app_secret).update(sortedParams).digest('hex');
|
||||||
|
case 'sha256':
|
||||||
|
return crypto.createHash('sha256').update(sortedParams + this.self_app_secret).digest('hex');
|
||||||
|
default:
|
||||||
|
return crypto.createHash('md5').update(sortedParams + this.self_app_secret).digest('hex');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 验证签名
|
||||||
|
ApiApp.prototype.verifySignature = function(params, signature) {
|
||||||
|
const generatedSignature = this.generateSignature(params);
|
||||||
|
return generatedSignature === signature;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法 - 根据AppKey查找
|
||||||
|
ApiApp.findByAppKey = async function(appKey) {
|
||||||
|
return await this.findOne({
|
||||||
|
where: { self_app_key: appKey },
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法 - 根据奇门配置查找
|
||||||
|
ApiApp.findByQimenConfig = async function(appKey, customerId) {
|
||||||
|
return await this.findOne({
|
||||||
|
where: {
|
||||||
|
qimen_app_key: appKey,
|
||||||
|
qimen_customer_id: customerId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return ApiApp;
|
||||||
|
};
|
||||||
60
app/model/employee_role.js
Normal file
60
app/model/employee_role.js
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT } = app.Sequelize;
|
||||||
|
|
||||||
|
const EmployeeRole = app.model.define('employee_role', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
employee_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '员工ID',
|
||||||
|
},
|
||||||
|
role_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '角色ID',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_employee_role', // 指定实际表名
|
||||||
|
timestamps: false, // 不自动添加 createdAt 和 updatedAt
|
||||||
|
comment: '员工角色关联表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_employee_role',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'employee_id', 'role_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_employee_id',
|
||||||
|
fields: [ 'employee_id' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系
|
||||||
|
EmployeeRole.associate = function() {
|
||||||
|
const { AccountStoreEmployee, Role } = app.model;
|
||||||
|
|
||||||
|
// 关联员工表
|
||||||
|
EmployeeRole.belongsTo(AccountStoreEmployee, {
|
||||||
|
foreignKey: 'employee_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'employee',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联角色表
|
||||||
|
EmployeeRole.belongsTo(Role, {
|
||||||
|
foreignKey: 'role_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'role',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return EmployeeRole;
|
||||||
|
};
|
||||||
298
app/model/entry_items.js
Normal file
298
app/model/entry_items.js
Normal file
@ -0,0 +1,298 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, BIGINT } = app.Sequelize;
|
||||||
|
|
||||||
|
const EntryItems = app.model.define('wms_entry_items', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '入库明细ID',
|
||||||
|
},
|
||||||
|
order_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '入库单ID',
|
||||||
|
references: {
|
||||||
|
model: 'wms_entry_order',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
out_biz_code: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '外部业务编码',
|
||||||
|
},
|
||||||
|
order_line_no: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '订单行号',
|
||||||
|
},
|
||||||
|
owner_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货主编码',
|
||||||
|
},
|
||||||
|
item_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '商品编码',
|
||||||
|
},
|
||||||
|
item_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '商品ID',
|
||||||
|
},
|
||||||
|
count: {
|
||||||
|
type: INTEGER(12),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '计划入库数量',
|
||||||
|
validate: {
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
inventory_type: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '库存类型',
|
||||||
|
},
|
||||||
|
stock_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '商品SKU ID',
|
||||||
|
references: {
|
||||||
|
model: 'wms_stock_warehouse',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
received_quantity: {
|
||||||
|
type: INTEGER(12),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '已收货数量',
|
||||||
|
validate: {
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
confirm_quantity: {
|
||||||
|
type: INTEGER(12),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '已通知数量',
|
||||||
|
validate: {
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_entry_items',
|
||||||
|
comment: '入库明细表',
|
||||||
|
timestamps: false,
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'order_id',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'order_id', 'order_line_no' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_stock_id',
|
||||||
|
fields: [ 'stock_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_item_code',
|
||||||
|
fields: [ 'item_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_order_id',
|
||||||
|
fields: [ 'order_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_received_quantity',
|
||||||
|
fields: [ 'received_quantity' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系
|
||||||
|
EntryItems.associate = function() {
|
||||||
|
const { EntryItems, EntryOrder, StockWarehouse } = app.model;
|
||||||
|
|
||||||
|
// 关联入库单
|
||||||
|
EntryItems.belongsTo(EntryOrder, {
|
||||||
|
foreignKey: 'order_id',
|
||||||
|
as: 'order',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联商品SKU
|
||||||
|
EntryItems.belongsTo(StockWarehouse, {
|
||||||
|
foreignKey: 'stock_id',
|
||||||
|
as: 'stock',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 验证收货数量
|
||||||
|
EntryItems.prototype.validateReceiveQuantity = function(quantity) {
|
||||||
|
if (quantity <= 0) {
|
||||||
|
throw new Error('收货数量必须大于0');
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentReceived = this.received_quantity || 0;
|
||||||
|
const planQuantity = this.count || 0;
|
||||||
|
const newReceived = currentReceived + quantity;
|
||||||
|
|
||||||
|
if (newReceived > planQuantity) {
|
||||||
|
throw new Error(`收货数量超过计划数量:计划${planQuantity},已收${currentReceived},本次${quantity},合计${newReceived}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 更新收货数量(带验证)
|
||||||
|
EntryItems.prototype.updateReceivedQuantity = async function(quantity, options = {}) {
|
||||||
|
// 验证数量
|
||||||
|
this.validateReceiveQuantity(quantity);
|
||||||
|
|
||||||
|
// 更新数量
|
||||||
|
const newReceived = (this.received_quantity || 0) + quantity;
|
||||||
|
|
||||||
|
await this.update({
|
||||||
|
received_quantity: newReceived,
|
||||||
|
}, options);
|
||||||
|
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 获取剩余可收货数量
|
||||||
|
EntryItems.prototype.getRemainingQuantity = function() {
|
||||||
|
const planQuantity = this.count || 0;
|
||||||
|
const receivedQuantity = this.received_quantity || 0;
|
||||||
|
return Math.max(0, planQuantity - receivedQuantity);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 是否已完成收货
|
||||||
|
EntryItems.prototype.isCompleted = function() {
|
||||||
|
const planQuantity = this.count || 0;
|
||||||
|
const receivedQuantity = this.received_quantity || 0;
|
||||||
|
return receivedQuantity >= planQuantity;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 获取收货进度
|
||||||
|
EntryItems.prototype.getProgress = function() {
|
||||||
|
const planQuantity = this.count || 0;
|
||||||
|
const receivedQuantity = this.received_quantity || 0;
|
||||||
|
|
||||||
|
if (planQuantity === 0) return 0;
|
||||||
|
|
||||||
|
return {
|
||||||
|
received: receivedQuantity,
|
||||||
|
plan: planQuantity,
|
||||||
|
remaining: Math.max(0, planQuantity - receivedQuantity),
|
||||||
|
percent: Math.min(100, Math.round((receivedQuantity / planQuantity) * 100)),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// 静态方法 - 批量更新收货数量(带验证)
|
||||||
|
EntryItems.batchUpdateReceived = async function(app, updates, options = {}) {
|
||||||
|
const transaction = options.transaction || await app.model.transaction();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 先检查所有更新是否合法
|
||||||
|
for (const update of updates) {
|
||||||
|
const { id, quantity } = update;
|
||||||
|
const item = await app.model.EntryItems.findByPk(id, { transaction });
|
||||||
|
|
||||||
|
if (!item) {
|
||||||
|
throw new Error(`入库明细 ${id} 不存在`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证数量
|
||||||
|
item.validateReceiveQuantity(quantity);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行更新
|
||||||
|
for (const update of updates) {
|
||||||
|
const { id, quantity } = update;
|
||||||
|
const item = await app.model.EntryItems.findByPk(id, { transaction });
|
||||||
|
|
||||||
|
const newReceived = (item.received_quantity || 0) + quantity;
|
||||||
|
await item.update({
|
||||||
|
received_quantity: newReceived,
|
||||||
|
}, { transaction });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!options.transaction) {
|
||||||
|
await transaction.commit();
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
if (!options.transaction) {
|
||||||
|
await transaction.rollback();
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 静态方法 - 获取入库单总进度
|
||||||
|
EntryItems.getOrderProgress = async function(app, orderId) {
|
||||||
|
const items = await app.model.EntryItems.findAll({
|
||||||
|
where: { order_id: orderId },
|
||||||
|
attributes: [
|
||||||
|
[ app.Sequelize.fn('SUM', app.Sequelize.col('count')), 'total_plan' ],
|
||||||
|
[ app.Sequelize.fn('SUM', app.Sequelize.col('received_quantity')), 'total_received' ],
|
||||||
|
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'item_count' ],
|
||||||
|
],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = items[0] || {};
|
||||||
|
const totalPlan = parseInt(result.total_plan) || 0;
|
||||||
|
const totalReceived = parseInt(result.total_received) || 0;
|
||||||
|
|
||||||
|
return {
|
||||||
|
total_plan: totalPlan,
|
||||||
|
total_received: totalReceived,
|
||||||
|
total_remaining: Math.max(0, totalPlan - totalReceived),
|
||||||
|
item_count: parseInt(result.item_count) || 0,
|
||||||
|
progress_percent: totalPlan > 0 ? Math.min(100, Math.round((totalReceived / totalPlan) * 100)) : 0,
|
||||||
|
is_completed: totalReceived >= totalPlan,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// 钩子函数 - 保存前验证
|
||||||
|
EntryItems.beforeSave(async (instance, options) => {
|
||||||
|
const received = instance.received_quantity || 0;
|
||||||
|
const plan = instance.count || 0;
|
||||||
|
|
||||||
|
if (received > plan) {
|
||||||
|
throw new Error(`已收货数量(${received})不能超过计划数量(${plan})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (received < 0) {
|
||||||
|
throw new Error('已收货数量不能为负数');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (plan < 0) {
|
||||||
|
throw new Error('计划数量不能为负数');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 钩子函数 - 更新前验证
|
||||||
|
EntryItems.beforeUpdate(async (instance, options) => {
|
||||||
|
// 如果更新了received_quantity,进行验证
|
||||||
|
if (instance.changed('received_quantity')) {
|
||||||
|
const received = instance.received_quantity || 0;
|
||||||
|
const plan = instance.count || 0;
|
||||||
|
|
||||||
|
if (received > plan) {
|
||||||
|
throw new Error(`已收货数量(${received})不能超过计划数量(${plan})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (received < 0) {
|
||||||
|
throw new Error('已收货数量不能为负数');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return EntryItems;
|
||||||
|
};
|
||||||
511
app/model/entry_order.js
Normal file
511
app/model/entry_order.js
Normal file
@ -0,0 +1,511 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, BIGINT, ENUM, TEXT, TINYINT, DATE } = app.Sequelize;
|
||||||
|
|
||||||
|
const EntryOrder = app.model.define('wms_entry_order', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '入库单ID',
|
||||||
|
},
|
||||||
|
entry_order_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '入库单号',
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
order_type: {
|
||||||
|
type: ENUM('SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK'),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '业务类型',
|
||||||
|
},
|
||||||
|
purchase_order_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '采购单号',
|
||||||
|
},
|
||||||
|
total_order_lines: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '单据总行数',
|
||||||
|
},
|
||||||
|
order_create_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '订单创建时间',
|
||||||
|
},
|
||||||
|
expect_start_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '预期到货时间',
|
||||||
|
},
|
||||||
|
expect_end_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '最迟预期到货时间',
|
||||||
|
},
|
||||||
|
logistics_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '物流公司编码',
|
||||||
|
},
|
||||||
|
logistics_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '物流公司名称',
|
||||||
|
},
|
||||||
|
express_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '运单号',
|
||||||
|
},
|
||||||
|
supplier_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '供应商编码',
|
||||||
|
},
|
||||||
|
supplier_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '供应商名称',
|
||||||
|
},
|
||||||
|
source_type: {
|
||||||
|
type: ENUM('WMS', 'API', 'QM'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'API',
|
||||||
|
comment: '来源类型',
|
||||||
|
},
|
||||||
|
order_status: {
|
||||||
|
type: ENUM('PENDING', 'CONFIRMED', 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED', 'CREATED', 'CREATING'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'PENDING',
|
||||||
|
comment: '订单状态',
|
||||||
|
},
|
||||||
|
sync_status: {
|
||||||
|
type: ENUM('PENDING', 'SUCCESS', 'FAILED'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'PENDING',
|
||||||
|
comment: '同步状态',
|
||||||
|
},
|
||||||
|
sync_message: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '同步返回信息',
|
||||||
|
},
|
||||||
|
is_enabled: {
|
||||||
|
type: TINYINT(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
comment: '是否启用',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库ID',
|
||||||
|
references: {
|
||||||
|
model: 'wms_store',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
store_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '货主ID',
|
||||||
|
references: {
|
||||||
|
model: 'wms_store',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
remark: {
|
||||||
|
type: STRING(500),
|
||||||
|
allowNull: true,
|
||||||
|
comment: 'ERP备注',
|
||||||
|
},
|
||||||
|
store_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货主名称快照',
|
||||||
|
},
|
||||||
|
warehouse_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '仓库名称快照',
|
||||||
|
},
|
||||||
|
deleted_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '删除时间',
|
||||||
|
},
|
||||||
|
qimen_owner_code: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '奇门货主code',
|
||||||
|
},
|
||||||
|
qimen_warehouse_code: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '奇门仓库code',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_entry_order',
|
||||||
|
comment: '入库单主表',
|
||||||
|
timestamps: false,
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_entry_order_code',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'entry_order_code', 'warehouse_id', 'store_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_order_type',
|
||||||
|
fields: [ 'order_type' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_order_status',
|
||||||
|
fields: [ 'order_status' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_sync_status',
|
||||||
|
fields: [ 'sync_status' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_source',
|
||||||
|
fields: [ 'source_type' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_create_time',
|
||||||
|
fields: [ 'order_create_time' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse_store',
|
||||||
|
fields: [ 'warehouse_id', 'store_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_is_enabled',
|
||||||
|
fields: [ 'is_enabled' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_deleted_at',
|
||||||
|
fields: [ 'deleted_at' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系
|
||||||
|
EntryOrder.associate = function() {
|
||||||
|
const { EntryOrder, Store, EntryItems } = app.model;
|
||||||
|
|
||||||
|
// 关联仓库
|
||||||
|
EntryOrder.belongsTo(Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
as: 'warehouse',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联货主
|
||||||
|
EntryOrder.belongsTo(Store, {
|
||||||
|
foreignKey: 'store_id',
|
||||||
|
as: 'store',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联入库明细
|
||||||
|
EntryOrder.hasMany(EntryItems, {
|
||||||
|
foreignKey: 'order_id',
|
||||||
|
as: 'items',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法
|
||||||
|
EntryOrder.prototype.isPending = function() {
|
||||||
|
return this.order_status === 'PENDING';
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.prototype.isConfirmed = function() {
|
||||||
|
return this.order_status === 'CONFIRMED';
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.prototype.isCompleted = function() {
|
||||||
|
return this.order_status === 'COMPLETED';
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.prototype.isCancelled = function() {
|
||||||
|
return this.order_status === 'CANCELLED';
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.prototype.isPartialReceived = function() {
|
||||||
|
return this.order_status === 'PARTIAL_RECEIVED';
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.prototype.canConfirm = function() {
|
||||||
|
return [ 'PENDING', 'CREATED' ].includes(this.order_status);
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.prototype.canCancel = function() {
|
||||||
|
return [ 'PENDING', 'CONFIRMED', 'CREATED' ].includes(this.order_status);
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.prototype.canComplete = function() {
|
||||||
|
return [ 'CONFIRMED', 'PARTIAL_RECEIVED' ].includes(this.order_status);
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.prototype.isSyncSuccess = function() {
|
||||||
|
return this.sync_status === 'SUCCESS';
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.prototype.isSyncFailed = function() {
|
||||||
|
return this.sync_status === 'FAILED';
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.prototype.isEnabled = function() {
|
||||||
|
return this.is_enabled === 1 && !this.deleted_at;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 静态方法
|
||||||
|
EntryOrder.findByOrderCode = async function(app, entryOrderCode, warehouseId, storeId) {
|
||||||
|
return await app.model.EntryOrder.findOne({
|
||||||
|
where: {
|
||||||
|
entry_order_code: entryOrderCode,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
store_id: storeId,
|
||||||
|
is_enabled: 1,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: app.model.Store,
|
||||||
|
as: 'warehouse',
|
||||||
|
attributes: [ 'store_name', 'store_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: app.model.Store,
|
||||||
|
as: 'store',
|
||||||
|
attributes: [ 'store_name' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: app.model.EntryItems,
|
||||||
|
as: 'items',
|
||||||
|
include: [{
|
||||||
|
model: app.model.StockWarehouse,
|
||||||
|
as: 'stock',
|
||||||
|
attributes: [ 'product_code', 'product_name' ],
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.findByStatus = async function(app, status, params = {}) {
|
||||||
|
const { warehouse_id, store_id, start_date, end_date, page = 1, pageSize = 20 } = params;
|
||||||
|
|
||||||
|
const where = {
|
||||||
|
order_status: status,
|
||||||
|
is_enabled: 1,
|
||||||
|
deleted_at: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (warehouse_id) {
|
||||||
|
where.warehouse_id = warehouse_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (store_id) {
|
||||||
|
where.store_id = store_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start_date || end_date) {
|
||||||
|
where.created_at = {};
|
||||||
|
if (start_date) {
|
||||||
|
where.created_at[app.Sequelize.Op.gte] = start_date;
|
||||||
|
}
|
||||||
|
if (end_date) {
|
||||||
|
where.created_at[app.Sequelize.Op.lte] = end_date;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const { count, rows } = await app.model.EntryOrder.findAndCountAll({
|
||||||
|
where,
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: app.model.Store,
|
||||||
|
as: 'warehouse',
|
||||||
|
attributes: [ 'store_name' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: app.model.Store,
|
||||||
|
as: 'store',
|
||||||
|
attributes: [ 'store_name' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
order: [[ 'created_at', 'DESC' ]],
|
||||||
|
offset: (page - 1) * pageSize,
|
||||||
|
limit: parseInt(pageSize),
|
||||||
|
distinct: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
list: rows,
|
||||||
|
pagination: {
|
||||||
|
page: parseInt(page),
|
||||||
|
pageSize: parseInt(pageSize),
|
||||||
|
total: count,
|
||||||
|
totalPages: Math.ceil(count / pageSize),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.getStatsByWarehouse = async function(app, warehouseId, startDate, endDate) {
|
||||||
|
const where = {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
is_enabled: 1,
|
||||||
|
deleted_at: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (startDate || endDate) {
|
||||||
|
where.created_at = {};
|
||||||
|
if (startDate) {
|
||||||
|
where.created_at[app.Sequelize.Op.gte] = startDate;
|
||||||
|
}
|
||||||
|
if (endDate) {
|
||||||
|
where.created_at[app.Sequelize.Op.lte] = endDate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await app.model.EntryOrder.findAll({
|
||||||
|
attributes: [
|
||||||
|
'order_status',
|
||||||
|
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'count' ],
|
||||||
|
[ app.Sequelize.fn('SUM', app.Sequelize.col('total_order_lines')), 'total_lines' ],
|
||||||
|
],
|
||||||
|
where,
|
||||||
|
group: [ 'order_status' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const stats = {
|
||||||
|
pending: 0,
|
||||||
|
confirmed: 0,
|
||||||
|
partial_received: 0,
|
||||||
|
completed: 0,
|
||||||
|
cancelled: 0,
|
||||||
|
total: 0,
|
||||||
|
total_lines: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
result.forEach(item => {
|
||||||
|
const status = item.order_status.toLowerCase();
|
||||||
|
if (stats[status] !== undefined) {
|
||||||
|
stats[status] = parseInt(item.count) || 0;
|
||||||
|
}
|
||||||
|
stats.total += parseInt(item.count) || 0;
|
||||||
|
stats.total_lines += parseInt(item.total_lines) || 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
return stats;
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.updateSyncStatus = async function(app, orderId, status, message = null) {
|
||||||
|
const order = await app.model.EntryOrder.findByPk(orderId);
|
||||||
|
|
||||||
|
if (!order) {
|
||||||
|
throw new Error('入库单不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateData = {
|
||||||
|
sync_status: status,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (message !== null) {
|
||||||
|
updateData.sync_message = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await order.update(updateData);
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.updateOrderStatus = async function(app, orderId, status) {
|
||||||
|
const order = await app.model.EntryOrder.findByPk(orderId);
|
||||||
|
|
||||||
|
if (!order) {
|
||||||
|
throw new Error('入库单不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
const validTransitions = {
|
||||||
|
PENDING: [ 'CONFIRMED', 'CANCELLED' ],
|
||||||
|
CONFIRMED: [ 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED' ],
|
||||||
|
PARTIAL_RECEIVED: [ 'COMPLETED', 'CANCELLED' ],
|
||||||
|
CREATED: [ 'PENDING', 'CANCELLED' ],
|
||||||
|
CREATING: [ 'PENDING', 'CANCELLED' ],
|
||||||
|
};
|
||||||
|
|
||||||
|
const allowedTransitions = validTransitions[order.order_status];
|
||||||
|
if (!allowedTransitions || !allowedTransitions.includes(status)) {
|
||||||
|
throw new Error(`状态从${order.order_status}转换到${status}不被允许`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await order.update({ order_status: status });
|
||||||
|
};
|
||||||
|
|
||||||
|
EntryOrder.calculateReceivedQuantities = async function(app, orderId) {
|
||||||
|
// 这里需要根据实际业务逻辑计算已收货数量
|
||||||
|
// 通常需要查询入库明细和实际收货记录
|
||||||
|
|
||||||
|
// 示例:查询入库明细
|
||||||
|
const items = await app.model.EntryItems.findAll({
|
||||||
|
where: { order_id: orderId },
|
||||||
|
attributes: [
|
||||||
|
'id',
|
||||||
|
'count',
|
||||||
|
[ app.Sequelize.literal('(SELECT SUM(quantity) FROM wms_storage WHERE inbound_order_no = wms_entry_order.entry_order_code AND item_id = wms_entry_items.item_id)'), 'received' ],
|
||||||
|
],
|
||||||
|
include: [{
|
||||||
|
model: app.model.EntryOrder,
|
||||||
|
as: 'order',
|
||||||
|
attributes: [ 'entry_order_code' ],
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
|
||||||
|
let totalExpected = 0;
|
||||||
|
let totalReceived = 0;
|
||||||
|
let allReceived = true;
|
||||||
|
let anyReceived = false;
|
||||||
|
|
||||||
|
items.forEach(item => {
|
||||||
|
const expected = item.count || 0;
|
||||||
|
const received = item.received || 0;
|
||||||
|
|
||||||
|
totalExpected += expected;
|
||||||
|
totalReceived += received;
|
||||||
|
|
||||||
|
if (expected > 0 && received < expected) {
|
||||||
|
allReceived = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (received > 0) {
|
||||||
|
anyReceived = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
total_expected: totalExpected,
|
||||||
|
total_received: totalReceived,
|
||||||
|
all_received: allReceived,
|
||||||
|
any_received: anyReceived,
|
||||||
|
percentage: totalExpected > 0 ? Math.round((totalReceived / totalExpected) * 100) : 0,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
return EntryOrder;
|
||||||
|
};
|
||||||
94
app/model/fast_where.js
Normal file
94
app/model/fast_where.js
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, TEXT, DATE } = app.Sequelize;
|
||||||
|
|
||||||
|
const FastWhere = app.model.define('fast_where', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER.UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
label: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '条件/组名称',
|
||||||
|
},
|
||||||
|
value: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '查询条件,json需要序列化',
|
||||||
|
get() {
|
||||||
|
const rawValue = this.getDataValue('value');
|
||||||
|
if (!rawValue) return null;
|
||||||
|
try {
|
||||||
|
return JSON.parse(rawValue);
|
||||||
|
} catch (error) {
|
||||||
|
app.logger.error('[FastWhere] JSON parse error:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
set(value) {
|
||||||
|
if (value) {
|
||||||
|
this.setDataValue('value', JSON.stringify(value));
|
||||||
|
} else {
|
||||||
|
this.setDataValue('value', null);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
pid: {
|
||||||
|
type: INTEGER,
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '父级id,方便树结构',
|
||||||
|
},
|
||||||
|
icon: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: 'icon编码',
|
||||||
|
},
|
||||||
|
type: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '查询类别',
|
||||||
|
},
|
||||||
|
createdAt: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
field: 'created_at',
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updatedAt: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
field: 'updated_at',
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
// 模型配置
|
||||||
|
tableName: 'wms_fast_where', // 数据库表名
|
||||||
|
timestamps: true, // 自动维护时间戳
|
||||||
|
freezeTableName: true, // 禁用表名复数化
|
||||||
|
underscored: true, // 字段使用下划线命名
|
||||||
|
comment: '快速查询条件表',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 定义模型关联关系(如果需要)
|
||||||
|
FastWhere.associate = function() {
|
||||||
|
// 自关联:父级关系
|
||||||
|
app.model.FastWhere.belongsTo(app.model.FastWhere, {
|
||||||
|
foreignKey: 'pid',
|
||||||
|
as: 'parent',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 自关联:子级关系
|
||||||
|
app.model.FastWhere.hasMany(app.model.FastWhere, {
|
||||||
|
foreignKey: 'pid',
|
||||||
|
as: 'children',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return FastWhere;
|
||||||
|
};
|
||||||
165
app/model/file.js
Normal file
165
app/model/file.js
Normal file
@ -0,0 +1,165 @@
|
|||||||
|
// app/model/file.js
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, INTEGER, STRING, TEXT, DATE, BOOLEAN } = app.Sequelize;
|
||||||
|
|
||||||
|
const File = app.model.define('wms_file', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '文件唯一ID',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库ID(核心统计维度)',
|
||||||
|
references: {
|
||||||
|
model: 'wms_store',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
file_key: {
|
||||||
|
type: STRING(500),
|
||||||
|
allowNull: false,
|
||||||
|
unique: true,
|
||||||
|
comment: '存储路径/对象键(如cos/2024/03/file.jpg)',
|
||||||
|
},
|
||||||
|
file_url: {
|
||||||
|
type: STRING(500),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '完整访问URL',
|
||||||
|
},
|
||||||
|
file_name: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '原始文件名',
|
||||||
|
},
|
||||||
|
file_size: {
|
||||||
|
type: INTEGER.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '文件大小(字节)',
|
||||||
|
},
|
||||||
|
file_type: {
|
||||||
|
type: STRING(50),
|
||||||
|
defaultValue: '',
|
||||||
|
comment: '文件类型:inventory_image, delivery_note, inspection_video',
|
||||||
|
},
|
||||||
|
mime_type: {
|
||||||
|
type: STRING(100),
|
||||||
|
defaultValue: '',
|
||||||
|
comment: 'MIME类型',
|
||||||
|
},
|
||||||
|
md5_hash: {
|
||||||
|
type: STRING(32),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: '',
|
||||||
|
unique: true,
|
||||||
|
comment: '文件MD5(去重依据)',
|
||||||
|
},
|
||||||
|
sha1_hash: {
|
||||||
|
type: STRING(40),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: '',
|
||||||
|
comment: '文件SHA1(二次校验)',
|
||||||
|
},
|
||||||
|
storage_mode: {
|
||||||
|
type: STRING(20),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'cos',
|
||||||
|
comment: '存储方式:cos/oss/local',
|
||||||
|
},
|
||||||
|
storage_class: {
|
||||||
|
type: STRING(20),
|
||||||
|
defaultValue: 'standard',
|
||||||
|
comment: '存储级别:standard/ia/archive',
|
||||||
|
},
|
||||||
|
uploader_id: {
|
||||||
|
type: STRING(64),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '上传者ID(用户ID/员工工号)',
|
||||||
|
},
|
||||||
|
uploader_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '上传者姓名(快照)',
|
||||||
|
},
|
||||||
|
uploader_dept: {
|
||||||
|
type: STRING(100),
|
||||||
|
defaultValue: '',
|
||||||
|
comment: '上传者部门(快照)',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
defaultValue: null,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
is_deleted: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: false,
|
||||||
|
field: 'is_deleted',
|
||||||
|
comment: '软删除标记',
|
||||||
|
},
|
||||||
|
deleted_at: {
|
||||||
|
type: DATE,
|
||||||
|
defaultValue: null,
|
||||||
|
comment: '删除时间',
|
||||||
|
},
|
||||||
|
deleted_by: {
|
||||||
|
type: STRING(64),
|
||||||
|
defaultValue: null,
|
||||||
|
comment: '删除操作人',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_file',
|
||||||
|
comment: 'WMS文件资源中枢表',
|
||||||
|
timestamps: false, // 使用自定义的created_at/updated_at
|
||||||
|
paranoid: false, // 使用自定义的软删除字段
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse',
|
||||||
|
fields: [ 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_uploader',
|
||||||
|
fields: [ 'uploader_type', 'uploader_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_created',
|
||||||
|
fields: [ 'created_at' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_type_warehouse',
|
||||||
|
fields: [ 'file_type', 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联定义(如果需要)
|
||||||
|
File.associate = function() {
|
||||||
|
const { Store, FileReference } = app.model;
|
||||||
|
|
||||||
|
// 属于一个仓库
|
||||||
|
File.belongsTo(Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
as: 'warehouse',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 有多个业务引用
|
||||||
|
File.hasMany(FileReference, {
|
||||||
|
foreignKey: 'file_id',
|
||||||
|
as: 'references',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return File;
|
||||||
|
};
|
||||||
102
app/model/file_reference.js
Normal file
102
app/model/file_reference.js
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
// app/model/file_reference.js
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, INTEGER, STRING, TEXT, DATE, BOOLEAN, JSON: JSON_TYPE } = app.Sequelize;
|
||||||
|
|
||||||
|
const FileReference = app.model.define('wms_file_reference', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
file_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '文件ID',
|
||||||
|
references: {
|
||||||
|
model: 'wms_file',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库ID(冗余,优化查询)',
|
||||||
|
references: {
|
||||||
|
model: 'wms_store',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
business_type: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '业务类型:sku_image/packing_list/inspection_report',
|
||||||
|
},
|
||||||
|
business_id: {
|
||||||
|
type: STRING(64),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '业务ID(如SKU编码、出库单号)',
|
||||||
|
},
|
||||||
|
display_order: {
|
||||||
|
type: INTEGER.UNSIGNED,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '显示顺序',
|
||||||
|
},
|
||||||
|
created_by: {
|
||||||
|
type: STRING(64),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '关联创建者',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_file_reference',
|
||||||
|
comment: 'WMS文件业务关联表',
|
||||||
|
timestamps: false, // 使用自定义的created_at
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_business_file',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'business_module', 'business_type', 'business_id', 'file_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_file_id',
|
||||||
|
fields: [ 'file_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse_business',
|
||||||
|
fields: [ 'warehouse_id', 'business_module', 'business_type' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_business',
|
||||||
|
fields: [ 'business_module', 'business_id' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联定义
|
||||||
|
FileReference.associate = function() {
|
||||||
|
const { File, Store } = app.model;
|
||||||
|
|
||||||
|
// 属于一个文件
|
||||||
|
FileReference.belongsTo(File, {
|
||||||
|
foreignKey: 'file_id',
|
||||||
|
as: 'file',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 属于一个仓库
|
||||||
|
FileReference.belongsTo(Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
as: 'warehouse',
|
||||||
|
});
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
return FileReference;
|
||||||
|
};
|
||||||
49
app/model/i18n_key.js
Normal file
49
app/model/i18n_key.js
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
// app/model/i18n_key.js
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, DATE } = app.Sequelize;
|
||||||
|
|
||||||
|
const I18nKey = app.model.define('wms_i18n_key', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER.UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
},
|
||||||
|
key_name: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '国际化键名',
|
||||||
|
},
|
||||||
|
project: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'wms',
|
||||||
|
comment: '项目标识',
|
||||||
|
},
|
||||||
|
module: {
|
||||||
|
type: STRING(100),
|
||||||
|
defaultValue: 'common',
|
||||||
|
comment: '业务模块',
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: STRING(500),
|
||||||
|
comment: '键值描述',
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: INTEGER,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
comment: '键值状态',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_i18n_keys',
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
underscored: true,
|
||||||
|
paranoid: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return I18nKey;
|
||||||
|
};
|
||||||
182
app/model/i18n_translation.js
Normal file
182
app/model/i18n_translation.js
Normal file
@ -0,0 +1,182 @@
|
|||||||
|
// app/model/i18n_translation.js
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, DATE, Op } = app.Sequelize;
|
||||||
|
|
||||||
|
// 直接在文件中定义常量
|
||||||
|
const CONSTANTS = {
|
||||||
|
TRANSLATION_STATUS: {
|
||||||
|
UNTRANSLATED: 0,
|
||||||
|
PENDING_REVIEW: 1,
|
||||||
|
APPROVED: 2,
|
||||||
|
},
|
||||||
|
LANGUAGES: [ 'zh-CN', 'en-US', 'ja-JP' ],
|
||||||
|
};
|
||||||
|
|
||||||
|
const I18nTranslation = app.model.define('wms_i18n_translation', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER.UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
},
|
||||||
|
key_id: {
|
||||||
|
type: INTEGER.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '键ID',
|
||||||
|
},
|
||||||
|
language: {
|
||||||
|
type: STRING(10),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '语言代码',
|
||||||
|
},
|
||||||
|
translation: {
|
||||||
|
type: STRING(500),
|
||||||
|
comment: '翻译内容',
|
||||||
|
},
|
||||||
|
translation_status: {
|
||||||
|
type: INTEGER,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: CONSTANTS.TRANSLATION_STATUS.UNTRANSLATED,
|
||||||
|
comment: '翻译状态',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_i18n_translations',
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
underscored: true,
|
||||||
|
paranoid: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系
|
||||||
|
I18nTranslation.associate = function() {
|
||||||
|
app.model.I18nTranslation.belongsTo(app.model.I18nKey, {
|
||||||
|
foreignKey: 'key_id',
|
||||||
|
as: 'key',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 挂载常量到模型(可选)
|
||||||
|
I18nTranslation.CONSTANTS = CONSTANTS;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取翻译
|
||||||
|
* @param keyId
|
||||||
|
* @param language
|
||||||
|
*/
|
||||||
|
I18nTranslation.getTranslation = async function(keyId, language) {
|
||||||
|
return await this.findOne({
|
||||||
|
where: { key_id: keyId, language },
|
||||||
|
include: [{
|
||||||
|
model: app.model.I18nKey,
|
||||||
|
as: 'key',
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量获取翻译
|
||||||
|
* @param keyIds
|
||||||
|
* @param language
|
||||||
|
*/
|
||||||
|
I18nTranslation.batchGetTranslations = async function(keyIds, language) {
|
||||||
|
const records = await this.findAll({
|
||||||
|
where: {
|
||||||
|
key_id: keyIds,
|
||||||
|
language,
|
||||||
|
},
|
||||||
|
include: [{
|
||||||
|
model: app.model.I18nKey,
|
||||||
|
as: 'key',
|
||||||
|
attributes: [ 'key_name' ],
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 返回键值对
|
||||||
|
const result = {};
|
||||||
|
records.forEach(record => {
|
||||||
|
if (record.key) {
|
||||||
|
result[record.key.key_name] = record.translation || record.key.key_name;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取项目翻译
|
||||||
|
* @param project
|
||||||
|
* @param language
|
||||||
|
*/
|
||||||
|
I18nTranslation.getProjectTranslations = async function(project, language) {
|
||||||
|
const records = await this.findAll({
|
||||||
|
include: [{
|
||||||
|
model: app.model.I18nKey,
|
||||||
|
as: 'key',
|
||||||
|
where: { project },
|
||||||
|
attributes: [ 'key_name' ],
|
||||||
|
}],
|
||||||
|
where: { language },
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = {};
|
||||||
|
records.forEach(record => {
|
||||||
|
if (record.key && record.key.key_name) {
|
||||||
|
result[record.key.key_name] = record.translation || record.key.key_name;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建或更新翻译
|
||||||
|
* @param keyId
|
||||||
|
* @param language
|
||||||
|
* @param translation
|
||||||
|
*/
|
||||||
|
I18nTranslation.upsertTranslation = async function(keyId, language, translation) {
|
||||||
|
const [ record, created ] = await this.findOrCreate({
|
||||||
|
where: { key_id: keyId, language },
|
||||||
|
defaults: {
|
||||||
|
key_id: keyId,
|
||||||
|
language,
|
||||||
|
translation: translation || null,
|
||||||
|
translation_status: translation ? CONSTANTS.TRANSLATION_STATUS.PENDING_REVIEW : CONSTANTS.TRANSLATION_STATUS.UNTRANSLATED,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!created) {
|
||||||
|
record.translation = translation || null;
|
||||||
|
record.translation_status = translation ? CONSTANTS.TRANSLATION_STATUS.PENDING_REVIEW : CONSTANTS.TRANSLATION_STATUS.UNTRANSLATED;
|
||||||
|
await record.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
return record;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取未翻译列表
|
||||||
|
* @param language
|
||||||
|
* @param project
|
||||||
|
*/
|
||||||
|
I18nTranslation.getUntranslated = async function(language, project) {
|
||||||
|
return await this.findAll({
|
||||||
|
include: [{
|
||||||
|
model: app.model.I18nKey,
|
||||||
|
as: 'key',
|
||||||
|
where: { project },
|
||||||
|
}],
|
||||||
|
where: {
|
||||||
|
language,
|
||||||
|
[Op.or]: [
|
||||||
|
{ translation: null },
|
||||||
|
{ translation: '' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return I18nTranslation;
|
||||||
|
};
|
||||||
143
app/model/interface_type.js
Normal file
143
app/model/interface_type.js
Normal file
@ -0,0 +1,143 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { INTEGER, STRING, TEXT, ENUM, TINYINT, DATE } = app.Sequelize;
|
||||||
|
|
||||||
|
const InterfaceType = app.model.define('interface_type', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER(10),
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '接口类型ID',
|
||||||
|
},
|
||||||
|
interface_code: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
unique: 'uk_interface_code',
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
len: [ 1, 100 ],
|
||||||
|
},
|
||||||
|
comment: '接口编码,唯一标识',
|
||||||
|
},
|
||||||
|
interface_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
len: [ 1, 200 ],
|
||||||
|
},
|
||||||
|
comment: '接口名称',
|
||||||
|
},
|
||||||
|
interface_category: {
|
||||||
|
type: ENUM('QM_WMS', 'OPEN_API'),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
isIn: [[ 'QM_WMS', 'OPEN_API' ]],
|
||||||
|
},
|
||||||
|
comment: '接口类别:QM_WMS-奇门仓储, OPEN_API-开放接口',
|
||||||
|
},
|
||||||
|
entry_url: {
|
||||||
|
type: STRING(500),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
len: [ 1, 500 ],
|
||||||
|
},
|
||||||
|
comment: '入口链接',
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '接口描述',
|
||||||
|
},
|
||||||
|
is_enabled: {
|
||||||
|
type: TINYINT(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
validate: {
|
||||||
|
isIn: [[ 0, 1 ]],
|
||||||
|
},
|
||||||
|
comment: '是否启用',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_interface_type',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: true,
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
comment: '接口类型配置表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_interface_code',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'interface_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_interface_category',
|
||||||
|
fields: [ 'interface_category' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_is_enabled',
|
||||||
|
fields: [ 'is_enabled' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_interface_name',
|
||||||
|
fields: [ 'interface_name' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_category_enabled',
|
||||||
|
fields: [ 'interface_category', 'is_enabled' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
// 类方法 - 根据接口编码查找
|
||||||
|
InterfaceType.findByCode = async function(interfaceCode) {
|
||||||
|
return await this.findOne({
|
||||||
|
where: { interface_code: interfaceCode },
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法 - 获取启用的接口列表
|
||||||
|
InterfaceType.findEnabled = async function(category = null) {
|
||||||
|
const where = { is_enabled: 1 };
|
||||||
|
if (category) {
|
||||||
|
where.interface_category = category;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.findAll({
|
||||||
|
where,
|
||||||
|
order: [[ 'interface_name', 'ASC' ]],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 检查接口是否可用
|
||||||
|
InterfaceType.prototype.isAvailable = function() {
|
||||||
|
return this.is_enabled === 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 获取接口分类名称
|
||||||
|
InterfaceType.prototype.getCategoryName = function() {
|
||||||
|
const categoryMap = {
|
||||||
|
QM_WMS: '奇门仓储',
|
||||||
|
OPEN_API: '开放接口',
|
||||||
|
};
|
||||||
|
return categoryMap[this.interface_category] || this.interface_category;
|
||||||
|
};
|
||||||
|
|
||||||
|
return InterfaceType;
|
||||||
|
};
|
||||||
253
app/model/location_space.js
Normal file
253
app/model/location_space.js
Normal file
@ -0,0 +1,253 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, DATE, BOOLEAN, ENUM, DECIMAL, BIGINT } = app.Sequelize;
|
||||||
|
|
||||||
|
const LocationSpace = app.model.define('wms_location_space', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '仓位ID',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库ID',
|
||||||
|
},
|
||||||
|
zone_id: {
|
||||||
|
type: INTEGER(10).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '所属分区ID',
|
||||||
|
},
|
||||||
|
location_type_id: {
|
||||||
|
type: INTEGER(10).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓位类型ID',
|
||||||
|
},
|
||||||
|
space_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓位编码',
|
||||||
|
},
|
||||||
|
custom_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '自定义名称',
|
||||||
|
},
|
||||||
|
custom_barcode: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '自定义条码',
|
||||||
|
},
|
||||||
|
row_no: {
|
||||||
|
type: STRING(10),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '排号',
|
||||||
|
},
|
||||||
|
column_no: {
|
||||||
|
type: STRING(10),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '列号',
|
||||||
|
},
|
||||||
|
level_no: {
|
||||||
|
type: STRING(10),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '层号',
|
||||||
|
},
|
||||||
|
cell_no: {
|
||||||
|
type: STRING(10),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '格号',
|
||||||
|
},
|
||||||
|
length: {
|
||||||
|
type: DECIMAL(8, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '长度(cm)',
|
||||||
|
},
|
||||||
|
width: {
|
||||||
|
type: DECIMAL(8, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '宽度(cm)',
|
||||||
|
},
|
||||||
|
height: {
|
||||||
|
type: DECIMAL(8, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '高度(cm)',
|
||||||
|
},
|
||||||
|
volume: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '体积(m³)',
|
||||||
|
},
|
||||||
|
max_weight: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '最大承重(kg)',
|
||||||
|
},
|
||||||
|
space_status: {
|
||||||
|
type: ENUM('AVAILABLE', 'OCCUPIED', 'RESERVED', 'MAINTENANCE', 'DISABLED'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'AVAILABLE',
|
||||||
|
comment: '仓位状态',
|
||||||
|
},
|
||||||
|
is_enabled: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: true,
|
||||||
|
comment: '是否启用',
|
||||||
|
},
|
||||||
|
current_sku_count: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '当前SKU种类数',
|
||||||
|
},
|
||||||
|
current_quantity: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '当前库存数量',
|
||||||
|
},
|
||||||
|
current_weight: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '当前重量(kg)',
|
||||||
|
},
|
||||||
|
current_volume: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '当前体积(m³)',
|
||||||
|
},
|
||||||
|
pick_sequence: {
|
||||||
|
type: INTEGER(10),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '拣货顺序',
|
||||||
|
},
|
||||||
|
pick_zone_id: {
|
||||||
|
type: INTEGER(10),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '所属拣货分区ID',
|
||||||
|
},
|
||||||
|
is_preferred_pick: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: false,
|
||||||
|
comment: '是否优先拣货位',
|
||||||
|
},
|
||||||
|
distance_from_start: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '距起始点距离(mm)',
|
||||||
|
},
|
||||||
|
pick_time_estimate: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '预估拣货时间(秒)',
|
||||||
|
},
|
||||||
|
pick_priority: {
|
||||||
|
type: INTEGER(3),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 50,
|
||||||
|
comment: '拣货优先级(1-100)',
|
||||||
|
},
|
||||||
|
last_picked_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '最后拣货时间',
|
||||||
|
},
|
||||||
|
pick_count: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '拣货次数',
|
||||||
|
},
|
||||||
|
relative_x: {
|
||||||
|
type: DECIMAL(8, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '在货架内的X坐标(cm)',
|
||||||
|
},
|
||||||
|
relative_y: {
|
||||||
|
type: DECIMAL(8, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '在货架内的Y坐标(cm)',
|
||||||
|
},
|
||||||
|
relative_z: {
|
||||||
|
type: DECIMAL(8, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '在货架内的Z坐标(cm)',
|
||||||
|
},
|
||||||
|
created_by: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '创建人',
|
||||||
|
},
|
||||||
|
updated_by: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '更新人',
|
||||||
|
},
|
||||||
|
deleted_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '软删除时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_location_space',
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
paranoid: true,
|
||||||
|
deletedAt: 'deleted_at',
|
||||||
|
comment: '仓位格子表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_warehouse_space_code',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'warehouse_id', 'space_code', 'deleted_at' ],
|
||||||
|
},
|
||||||
|
{ name: 'uk_custom_barcode', unique: true, fields: [ 'custom_barcode' ] },
|
||||||
|
{ fields: [ 'warehouse_id', 'zone_id' ] },
|
||||||
|
{ fields: [ 'location_type_id' ] },
|
||||||
|
{ fields: [ 'space_status' ] },
|
||||||
|
{ fields: [ 'is_enabled' ] },
|
||||||
|
{ fields: [ 'row_no', 'column_no', 'level_no' ] },
|
||||||
|
{ fields: [ 'zone_id' ] },
|
||||||
|
{ fields: [ 'warehouse_id', 'pick_sequence', 'space_status' ] },
|
||||||
|
{ fields: [ 'pick_priority', 'space_status' ] },
|
||||||
|
{ fields: [ 'last_picked_at' ] },
|
||||||
|
{ fields: [ 'pick_zone_id' ] },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系
|
||||||
|
LocationSpace.associate = function() {
|
||||||
|
const { LocationSpace, LocationZone, Store, LocationType, ReceivingDetail } = app.model;
|
||||||
|
LocationSpace.belongsTo(LocationZone, {
|
||||||
|
as: 'zone',
|
||||||
|
foreignKey: 'zone_id',
|
||||||
|
});
|
||||||
|
|
||||||
|
LocationSpace.belongsTo(Store, {
|
||||||
|
as: 'warehouse',
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
});
|
||||||
|
|
||||||
|
LocationSpace.belongsTo(LocationType, {
|
||||||
|
as: 'locationType',
|
||||||
|
foreignKey: 'location_type_id',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联系统商品
|
||||||
|
LocationSpace.hasMany(ReceivingDetail, {
|
||||||
|
as: 'receiving',
|
||||||
|
foreignKey: 'space_id',
|
||||||
|
});
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
return LocationSpace;
|
||||||
|
};
|
||||||
80
app/model/location_type.js
Normal file
80
app/model/location_type.js
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
// app/model/wms_location_type.js
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, BOOLEAN, DATE, ENUM, BIGINT } = app.Sequelize;
|
||||||
|
|
||||||
|
const LocationType = app.model.define('location_type', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER(10).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '类型ID',
|
||||||
|
},
|
||||||
|
type_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
unique: 'uk_type_code',
|
||||||
|
comment: '类型编码',
|
||||||
|
},
|
||||||
|
type_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '类型名称',
|
||||||
|
},
|
||||||
|
temperature_zone: {
|
||||||
|
type: ENUM('NORMAL', 'COLD', 'FROZEN', 'DANGEROUS'),
|
||||||
|
defaultValue: 'NORMAL',
|
||||||
|
comment: '温区',
|
||||||
|
},
|
||||||
|
is_active: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: true,
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: STRING(500),
|
||||||
|
comment: '描述',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
},
|
||||||
|
allow_allocation: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
comment: '是否允许分配储位',
|
||||||
|
},
|
||||||
|
allow_transfer_out: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
comment: '是否允许移出',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
comment: '仓库ID',
|
||||||
|
references: {
|
||||||
|
model: 'wms_store',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_location_type',
|
||||||
|
timestamps: false, // 不使用 Sequelize 的默认时间戳
|
||||||
|
comment: '库位类型表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'warehouse_id',
|
||||||
|
fields: [ 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 定义关联关系
|
||||||
|
LocationType.associate = function() {
|
||||||
|
app.model.LocationType.belongsTo(app.model.Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
constraints: false, // 如果 wms_store 表不存在,设置为 false
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return LocationType;
|
||||||
|
};
|
||||||
245
app/model/location_zone.js
Normal file
245
app/model/location_zone.js
Normal file
@ -0,0 +1,245 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, DATE, BOOLEAN, ENUM, TEXT, BIGINT } = app.Sequelize;
|
||||||
|
|
||||||
|
const LocationZone = app.model.define('wms_location_zone', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER(10).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '分区ID',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '仓库ID',
|
||||||
|
},
|
||||||
|
zone_code: {
|
||||||
|
type: STRING(5),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '分区编码(最多5位字母或数字)',
|
||||||
|
},
|
||||||
|
zone_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '分区名称',
|
||||||
|
},
|
||||||
|
zone_type: {
|
||||||
|
type: ENUM('warehouse', 'area', 'rack', 'pick_start'),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '分区类型',
|
||||||
|
},
|
||||||
|
parent_id: {
|
||||||
|
type: INTEGER(10).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '父分区ID',
|
||||||
|
},
|
||||||
|
is_active: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: true,
|
||||||
|
comment: '是否启用',
|
||||||
|
},
|
||||||
|
x: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '左下角x坐标(mm)',
|
||||||
|
},
|
||||||
|
y: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '左下角y坐标(mm)',
|
||||||
|
},
|
||||||
|
z: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '左下角z坐标(mm)',
|
||||||
|
},
|
||||||
|
length: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '长度(mm)',
|
||||||
|
},
|
||||||
|
width: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '宽度(mm)',
|
||||||
|
},
|
||||||
|
height: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '高度(mm)',
|
||||||
|
},
|
||||||
|
rack_columns: {
|
||||||
|
type: INTEGER(3).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 1,
|
||||||
|
comment: '货架列数',
|
||||||
|
},
|
||||||
|
rack_rows: {
|
||||||
|
type: INTEGER(3).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货架层数',
|
||||||
|
},
|
||||||
|
rack_levels: {
|
||||||
|
type: INTEGER(3).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货架分格数',
|
||||||
|
},
|
||||||
|
cell_width: {
|
||||||
|
type: INTEGER(11).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货架长度',
|
||||||
|
},
|
||||||
|
cell_height: {
|
||||||
|
type: INTEGER(11).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货架高度',
|
||||||
|
},
|
||||||
|
cell_length: {
|
||||||
|
type: INTEGER(11).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货架深度',
|
||||||
|
},
|
||||||
|
direction: {
|
||||||
|
type: ENUM('north', 'south', 'east', 'west'),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货架朝向',
|
||||||
|
},
|
||||||
|
color: {
|
||||||
|
type: STRING(20),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: '#3B82F6',
|
||||||
|
comment: '显示颜色',
|
||||||
|
},
|
||||||
|
path_sequence: {
|
||||||
|
type: INTEGER(10).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '拣货路径排序序号',
|
||||||
|
},
|
||||||
|
pick_distance: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '距离起始点的拣货距离(mm)',
|
||||||
|
},
|
||||||
|
aisles: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '通道在货架的列的位置',
|
||||||
|
get() {
|
||||||
|
const rawValue = this.getDataValue('aisles');
|
||||||
|
try {
|
||||||
|
return rawValue ? rawValue.split(',') : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
set(value) {
|
||||||
|
const normalized = value
|
||||||
|
? value.join(',')
|
||||||
|
: null;
|
||||||
|
|
||||||
|
this.setDataValue('aisles', normalized);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
neighbor_zone_ids: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '相邻分区ID列表(JSON数组)',
|
||||||
|
get() {
|
||||||
|
const rawValue = this.getDataValue('neighbor_zone_ids');
|
||||||
|
try {
|
||||||
|
return rawValue ? JSON.parse(rawValue) : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
set(value) {
|
||||||
|
this.setDataValue('neighbor_zone_ids',
|
||||||
|
value ? JSON.stringify(value) : null
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
is_passable: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: true,
|
||||||
|
comment: '是否可通行',
|
||||||
|
},
|
||||||
|
zone_category: {
|
||||||
|
type: ENUM('storage', 'operational', 'obstacle'),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'storage',
|
||||||
|
comment: '区域分类',
|
||||||
|
},
|
||||||
|
deleted_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '软删除时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_location_zone',
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
paranoid: true, // 软删除
|
||||||
|
deletedAt: 'deleted_at',
|
||||||
|
comment: '库位分区表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_warehouse_zone_code',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'warehouse_id', 'zone_code', 'deleted_at' ],
|
||||||
|
},
|
||||||
|
{ fields: [ 'warehouse_id', 'parent_id' ] },
|
||||||
|
{ fields: [ 'deleted_at' ] },
|
||||||
|
{ fields: [ 'zone_type' ] },
|
||||||
|
{ fields: [ 'is_active' ] },
|
||||||
|
{ fields: [ 'parent_id' ] },
|
||||||
|
{ fields: [ 'warehouse_id', 'path_sequence', 'is_active' ] },
|
||||||
|
{ fields: [ 'zone_category' ] },
|
||||||
|
{ fields: [ 'warehouse_id', 'pick_distance' ] },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系
|
||||||
|
LocationZone.associate = function() {
|
||||||
|
// 自关联 - 父分区
|
||||||
|
app.model.LocationZone.belongsTo(app.model.LocationZone, {
|
||||||
|
as: 'parent',
|
||||||
|
foreignKey: 'parent_id',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 自关联 - 子分区
|
||||||
|
app.model.LocationZone.hasMany(app.model.LocationZone, {
|
||||||
|
as: 'children',
|
||||||
|
foreignKey: 'parent_id',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联仓库
|
||||||
|
app.model.LocationZone.belongsTo(app.model.Store, {
|
||||||
|
as: 'warehouse',
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联仓位
|
||||||
|
app.model.LocationZone.hasMany(app.model.LocationSpace, {
|
||||||
|
as: 'spaces',
|
||||||
|
foreignKey: 'zone_id',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联起始拣货点
|
||||||
|
app.model.LocationZone.belongsTo(app.model.LocationZone, {
|
||||||
|
as: 'pickStartPoint',
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
targetKey: 'warehouse_id',
|
||||||
|
scope: {
|
||||||
|
zone_type: 'pick_start',
|
||||||
|
is_active: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return LocationZone;
|
||||||
|
};
|
||||||
109
app/model/operation_log.js
Normal file
109
app/model/operation_log.js
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
// app/model/operation_log.js
|
||||||
|
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, BIGINT, DATE, ENUM, JSON } = app.Sequelize;
|
||||||
|
|
||||||
|
const OperationLog = app.model.define('operation_log', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
business_type: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '业务类型: product, order, stock, wave, express, storage',
|
||||||
|
},
|
||||||
|
business_id: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '业务ID',
|
||||||
|
},
|
||||||
|
operation_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '操作编码',
|
||||||
|
},
|
||||||
|
operator_id: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '操作人ID(用户ID/系统ID)',
|
||||||
|
},
|
||||||
|
operator_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '操作人名称',
|
||||||
|
},
|
||||||
|
external_log_type: {
|
||||||
|
type: ENUM('REQUEST', 'API', 'QIMEN', 'NONE'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'NONE',
|
||||||
|
comment: '外部日志类型',
|
||||||
|
},
|
||||||
|
external_log_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '外部日志ID',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '仓库ID',
|
||||||
|
},
|
||||||
|
before_changes: {
|
||||||
|
type: JSON,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '变更前数据',
|
||||||
|
},
|
||||||
|
platform_code: {
|
||||||
|
type: STRING(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '操作端',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_operation_log', // 数据库中的实际表名
|
||||||
|
timestamps: false, // 不使用默认的 createdAt 和 updatedAt
|
||||||
|
comment: 'WMS业务操作日志表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
unique: true,
|
||||||
|
name: 'uk_business_operation',
|
||||||
|
fields: [ 'business_type', 'business_id', 'id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_business_type_id_time',
|
||||||
|
fields: [ 'business_type', 'business_id', 'created_at' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_operation_code_time',
|
||||||
|
fields: [ 'operation_code', 'created_at' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_operator_time',
|
||||||
|
fields: [ 'operator_id', 'created_at' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse_time',
|
||||||
|
fields: [ 'warehouse_id', 'created_at' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_external_log',
|
||||||
|
fields: [ 'external_log_type', 'external_log_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_created_at',
|
||||||
|
fields: [ 'created_at' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return OperationLog;
|
||||||
|
};
|
||||||
461
app/model/order_delivery.js
Normal file
461
app/model/order_delivery.js
Normal file
@ -0,0 +1,461 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { Sequelize, model } = app;
|
||||||
|
const { STRING, BIGINT, DECIMAL, TEXT, ENUM, DATE, INTEGER, CHAR, SMALLINT } = Sequelize;
|
||||||
|
|
||||||
|
// 状态机枚举定义
|
||||||
|
const StatusEnum = {
|
||||||
|
STATUS: [ 'pedding', 'created', 'cancel', 'error' ],
|
||||||
|
SYNC_STATUS: [ 'padding', 'fin', 'error' ],
|
||||||
|
POST_STATUS: [ 'padding', 'fin', 'timeout', 'error', 'none' ],
|
||||||
|
STORAGE_STATUS: [ 'padding', 'fin', 'error', 'none' ],
|
||||||
|
PICK_STATUS: [ 'padding', 'fin', 'error', 'none' ],
|
||||||
|
PACK_STATUS: [ 'none', 'padding', 'fin', 'error' ],
|
||||||
|
INSPECTION_STATUS: [ 'none', 'padding', 'running', 'fin', 'error' ],
|
||||||
|
PRINT_STATUS: [ 'none', 'padding', 'fin', 'error' ],
|
||||||
|
CLAIM_STATUS: [ 'none', 'padding', 'fin', 'error' ],
|
||||||
|
OUTBOUND_STATUS: [ 'none', 'padding', 'fin', 'error' ],
|
||||||
|
LOCK_STATUS: [ 'none', 'warehouse', 'store' ],
|
||||||
|
INTERCEPT_STATUS: [
|
||||||
|
'none', 'requesting', 'requested', 'intercepting',
|
||||||
|
'intercepted_in_transit', 'intercepted_at_warehouse',
|
||||||
|
'returning', 'returned', 'delivered_by_mistake',
|
||||||
|
'timeout', 'cancelled', 'failed', 'exception',
|
||||||
|
],
|
||||||
|
URGENCY: [ 'Y', 'N' ],
|
||||||
|
INVOICE: [ 'Y', 'N' ],
|
||||||
|
};
|
||||||
|
|
||||||
|
// 基础模型定义
|
||||||
|
const baseModel = {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
},
|
||||||
|
delivery_order_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '发货单号',
|
||||||
|
},
|
||||||
|
pre_delivery_order_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '预发货单号',
|
||||||
|
},
|
||||||
|
pre_delivery_order_id: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '预发货单ID',
|
||||||
|
},
|
||||||
|
order_type: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '订单类型',
|
||||||
|
},
|
||||||
|
warehouse_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '仓库编码',
|
||||||
|
},
|
||||||
|
order_flag: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '订单标记',
|
||||||
|
},
|
||||||
|
source_platform_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '来源平台编码',
|
||||||
|
},
|
||||||
|
source_platform_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '来源平台名称',
|
||||||
|
},
|
||||||
|
create_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
delete_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '删除时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
place_order_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '店铺创建订单时间',
|
||||||
|
},
|
||||||
|
pay_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '支付时间',
|
||||||
|
},
|
||||||
|
pay_no: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '支付单号',
|
||||||
|
},
|
||||||
|
service_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '集包服务编码',
|
||||||
|
},
|
||||||
|
operator_name: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: 'ERP审核人',
|
||||||
|
},
|
||||||
|
operate_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: 'ERP审核时间',
|
||||||
|
},
|
||||||
|
shop_nick: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '店铺名称',
|
||||||
|
},
|
||||||
|
seller_nick: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '卖家名称',
|
||||||
|
},
|
||||||
|
buyer_nick: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '买家名称',
|
||||||
|
},
|
||||||
|
total_amount: {
|
||||||
|
type: DECIMAL(18, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '订单总金额',
|
||||||
|
},
|
||||||
|
item_amount: {
|
||||||
|
type: DECIMAL(18, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '商品总金额',
|
||||||
|
},
|
||||||
|
discount_amount: {
|
||||||
|
type: DECIMAL(18, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '订单折扣金额',
|
||||||
|
},
|
||||||
|
freight: {
|
||||||
|
type: DECIMAL(18, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '快递费用',
|
||||||
|
},
|
||||||
|
ar_amount: {
|
||||||
|
type: DECIMAL(18, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '应收金额',
|
||||||
|
},
|
||||||
|
got_amount: {
|
||||||
|
type: DECIMAL(18, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '已收金额',
|
||||||
|
},
|
||||||
|
service_fee: {
|
||||||
|
type: DECIMAL(18, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: 'COD服务费',
|
||||||
|
},
|
||||||
|
logistics_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '物流公司编码',
|
||||||
|
},
|
||||||
|
logistics_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '物流公司名称',
|
||||||
|
},
|
||||||
|
express_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '面单号前置',
|
||||||
|
},
|
||||||
|
logistics_area_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '快递区域编码, 大头笔信息',
|
||||||
|
},
|
||||||
|
delivery_type: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '发货服务类型',
|
||||||
|
},
|
||||||
|
is_urgency: {
|
||||||
|
type: ENUM(...StatusEnum.URGENCY),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'N',
|
||||||
|
comment: '是否紧急',
|
||||||
|
},
|
||||||
|
invoice_flag: {
|
||||||
|
type: ENUM(...StatusEnum.INVOICE),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'N',
|
||||||
|
comment: '是否需要发票',
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: ENUM(...StatusEnum.STATUS),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'created',
|
||||||
|
comment: '订单状态',
|
||||||
|
},
|
||||||
|
name: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '收件人姓名',
|
||||||
|
},
|
||||||
|
zip_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '收件人邮编',
|
||||||
|
},
|
||||||
|
tel: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '收件人电话',
|
||||||
|
},
|
||||||
|
mobile: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '收件人移动电话',
|
||||||
|
},
|
||||||
|
email: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '收件人邮箱',
|
||||||
|
},
|
||||||
|
country_code: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '国家编码',
|
||||||
|
},
|
||||||
|
province: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '省份',
|
||||||
|
},
|
||||||
|
city: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '城市',
|
||||||
|
},
|
||||||
|
area: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '区',
|
||||||
|
},
|
||||||
|
town: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '镇',
|
||||||
|
},
|
||||||
|
detail_address: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '详细地址',
|
||||||
|
},
|
||||||
|
id_type: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '证件类型',
|
||||||
|
},
|
||||||
|
id_number: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '证件号码',
|
||||||
|
},
|
||||||
|
oaid: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: 'OAID',
|
||||||
|
},
|
||||||
|
sync_status: {
|
||||||
|
type: ENUM(...StatusEnum.SYNC_STATUS),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'padding',
|
||||||
|
comment: '同步状态',
|
||||||
|
},
|
||||||
|
store_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货主ID',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '仓库ID',
|
||||||
|
},
|
||||||
|
from_key: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '来源键',
|
||||||
|
},
|
||||||
|
items: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '商品JSON字符串',
|
||||||
|
},
|
||||||
|
items_count: {
|
||||||
|
type: SMALLINT(5).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '商品种类数',
|
||||||
|
},
|
||||||
|
items_total: {
|
||||||
|
type: INTEGER(10).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '商品总数',
|
||||||
|
},
|
||||||
|
items_weight: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0.00,
|
||||||
|
comment: '总重量(kg)',
|
||||||
|
},
|
||||||
|
items_hash: {
|
||||||
|
type: CHAR(32),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: '',
|
||||||
|
comment: 'MD5哈希值(32位)',
|
||||||
|
},
|
||||||
|
items_crc: {
|
||||||
|
type: INTEGER(10).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: 'CRC32校验码',
|
||||||
|
},
|
||||||
|
wave_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '波次ID,0表示未分配',
|
||||||
|
},
|
||||||
|
// 状态机字段
|
||||||
|
post_status: {
|
||||||
|
type: ENUM(...StatusEnum.POST_STATUS),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'none',
|
||||||
|
comment: '分配快递号状态机',
|
||||||
|
},
|
||||||
|
storage_status: {
|
||||||
|
type: ENUM(...StatusEnum.STORAGE_STATUS),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'none',
|
||||||
|
comment: '分配储位状态机',
|
||||||
|
},
|
||||||
|
pick_status: {
|
||||||
|
type: ENUM(...StatusEnum.PICK_STATUS),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'none',
|
||||||
|
comment: '拣货状态机',
|
||||||
|
},
|
||||||
|
pack_status: {
|
||||||
|
type: ENUM(...StatusEnum.PACK_STATUS),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'none',
|
||||||
|
comment: '打包状态机',
|
||||||
|
},
|
||||||
|
inspection_status: {
|
||||||
|
type: ENUM(...StatusEnum.INSPECTION_STATUS),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'none',
|
||||||
|
comment: '检验状态机',
|
||||||
|
},
|
||||||
|
print_status: {
|
||||||
|
type: ENUM(...StatusEnum.PRINT_STATUS),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: null,
|
||||||
|
comment: '打印状态机',
|
||||||
|
},
|
||||||
|
claim_status: {
|
||||||
|
type: ENUM(...StatusEnum.CLAIM_STATUS),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'none',
|
||||||
|
comment: '领取状态机',
|
||||||
|
},
|
||||||
|
outbound_status: {
|
||||||
|
type: ENUM(...StatusEnum.OUTBOUND_STATUS),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'none',
|
||||||
|
comment: '出库状态机',
|
||||||
|
},
|
||||||
|
lock_status: {
|
||||||
|
type: ENUM(...StatusEnum.LOCK_STATUS),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: null,
|
||||||
|
comment: '锁定状态机',
|
||||||
|
},
|
||||||
|
intercept_status: {
|
||||||
|
type: ENUM(...StatusEnum.INTERCEPT_STATUS),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: null,
|
||||||
|
comment: '拦截状态机',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// 主表模型
|
||||||
|
const OrderDelivery = model.define('order_delivery', baseModel, {
|
||||||
|
tableName: 'wms_order_delivery',
|
||||||
|
timestamps: false,
|
||||||
|
comment: '仓库发货单常用表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'idx_current_store_id',
|
||||||
|
fields: [ 'store_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_current_warehouse_id',
|
||||||
|
fields: [ 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_current_delivery_code',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'delivery_order_code', 'store_id', 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_items',
|
||||||
|
fields: [ 'items' ],
|
||||||
|
length: 50,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_items_hash',
|
||||||
|
fields: [ 'items_hash' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_hash_crc',
|
||||||
|
fields: [ 'items_hash', 'items_crc', 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'wave_id',
|
||||||
|
fields: [ 'status', 'wave_id' ],
|
||||||
|
},
|
||||||
|
// 状态机索引
|
||||||
|
{
|
||||||
|
name: 'idx_statuses_composite',
|
||||||
|
fields: [
|
||||||
|
'status',
|
||||||
|
'post_status',
|
||||||
|
'pick_status',
|
||||||
|
'pack_status',
|
||||||
|
'outbound_status',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
return OrderDelivery;
|
||||||
|
};
|
||||||
420
app/model/order_delivery_factory.js
Normal file
420
app/model/order_delivery_factory.js
Normal file
@ -0,0 +1,420 @@
|
|||||||
|
// app/model/wms_order_delivery_factory.js
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { Sequelize, model } = app;
|
||||||
|
|
||||||
|
class OrderDeliveryFactory {
|
||||||
|
constructor() {
|
||||||
|
this.modelCache = new Map();
|
||||||
|
this.app = app;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前表模型
|
||||||
|
* @param warehouseId
|
||||||
|
*/
|
||||||
|
async getCurrentModel(warehouseId) {
|
||||||
|
return await this.getOrCreateModel(warehouseId, 'current');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取历史表模型
|
||||||
|
* @param warehouseId
|
||||||
|
*/
|
||||||
|
async getHistoryModel(warehouseId) {
|
||||||
|
return await this.getOrCreateModel(warehouseId, 'history');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据表名直接获取模型
|
||||||
|
* @param tableName
|
||||||
|
*/
|
||||||
|
async getModelByTableName(tableName) {
|
||||||
|
const cacheKey = `table_${tableName}`;
|
||||||
|
|
||||||
|
if (this.modelCache.has(cacheKey)) {
|
||||||
|
return this.modelCache.get(cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const tableExists = await this.checkTableExists(tableName);
|
||||||
|
if (!tableExists) {
|
||||||
|
throw new Error(`表 ${tableName} 不存在`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseAttributes = this.app.model.OrderDelivery.rawAttributes;
|
||||||
|
const DynamicModel = this.app.model.define(tableName, baseAttributes, {
|
||||||
|
tableName,
|
||||||
|
timestamps: false,
|
||||||
|
comment: tableName.includes('_history') ? '仓库发货单历史表' : '仓库发货单常用表',
|
||||||
|
});
|
||||||
|
|
||||||
|
this.modelCache.set(cacheKey, DynamicModel);
|
||||||
|
return DynamicModel;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
this.app.logger.error(`获取模型失败 ${tableName}:`, error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取或创建模型
|
||||||
|
* @param warehouseId
|
||||||
|
* @param type
|
||||||
|
*/
|
||||||
|
async getOrCreateModel(warehouseId, type = 'current') {
|
||||||
|
const tableName = this.generateTableName(warehouseId, type);
|
||||||
|
const cacheKey = `${warehouseId}_${type}`;
|
||||||
|
|
||||||
|
// 检查缓存
|
||||||
|
if (this.modelCache.has(cacheKey)) {
|
||||||
|
return this.modelCache.get(cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 检查表是否存在,不存在则创建
|
||||||
|
const tableExists = await this.checkTableExists(tableName);
|
||||||
|
if (!tableExists) {
|
||||||
|
await this.createPhysicalTable(warehouseId, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建模型实例
|
||||||
|
const baseAttributes = this.app.model.OrderDelivery.rawAttributes;
|
||||||
|
const modelOptions = this.getModelOptions(tableName, warehouseId, type);
|
||||||
|
|
||||||
|
const DynamicModel = this.app.model.define(tableName, baseAttributes, modelOptions);
|
||||||
|
|
||||||
|
// 设置关联关系
|
||||||
|
this.setupAssociations(DynamicModel, warehouseId, type);
|
||||||
|
|
||||||
|
// 缓存模型
|
||||||
|
this.modelCache.set(cacheKey, DynamicModel);
|
||||||
|
this.app.logger.info(`创建动态模型成功: ${tableName}`);
|
||||||
|
|
||||||
|
return DynamicModel;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
this.app.logger.error(`创建动态模型失败 ${tableName}:`, error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取模型配置选项
|
||||||
|
* @param tableName
|
||||||
|
* @param warehouseId
|
||||||
|
* @param type
|
||||||
|
*/
|
||||||
|
getModelOptions(tableName, warehouseId, type) {
|
||||||
|
const options = {
|
||||||
|
tableName,
|
||||||
|
timestamps: false,
|
||||||
|
comment: type === 'history'
|
||||||
|
? `仓库${warehouseId}发货单历史表`
|
||||||
|
: `仓库${warehouseId}发货单常用表`,
|
||||||
|
indexes: this.getIndexes(warehouseId, type),
|
||||||
|
};
|
||||||
|
|
||||||
|
// 历史表添加归档时间字段
|
||||||
|
if (type === 'history') {
|
||||||
|
options.fields = Object.keys(this.app.model.OrderDelivery.rawAttributes);
|
||||||
|
options.fields.push('archive_time');
|
||||||
|
}
|
||||||
|
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取索引配置
|
||||||
|
* @param warehouseId
|
||||||
|
* @param type
|
||||||
|
*/
|
||||||
|
getIndexes(warehouseId, type) {
|
||||||
|
const prefix = `${warehouseId}_${type}`;
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: `idx_${prefix}_store_id`,
|
||||||
|
fields: [ 'store_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${prefix}_warehouse_id`,
|
||||||
|
fields: [ 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${prefix}_delivery_code`,
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'delivery_order_code', 'store_id', 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${prefix}_items`,
|
||||||
|
fields: [ 'items' ],
|
||||||
|
length: 50,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${prefix}_items_hash`,
|
||||||
|
fields: [ 'items_hash' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${prefix}_hash_crc`,
|
||||||
|
fields: [ 'items_hash', 'items_crc', 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${prefix}_wave`,
|
||||||
|
fields: [ 'status', 'wave_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${prefix}_statuses`,
|
||||||
|
fields: [
|
||||||
|
'status',
|
||||||
|
'post_status',
|
||||||
|
'pick_status',
|
||||||
|
'pack_status',
|
||||||
|
'outbound_status',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置关联关系
|
||||||
|
* @param DynamicModel
|
||||||
|
* @param warehouseId
|
||||||
|
* @param type
|
||||||
|
*/
|
||||||
|
async setupAssociations(DynamicModel, warehouseId, type) {
|
||||||
|
try {
|
||||||
|
// 如果存在商品模型工厂,建立关联
|
||||||
|
if (this.app.model.OrderItemsFactory) {
|
||||||
|
const ItemsModel = await this.app.model.OrderItemsFactory.getOrCreateModel(warehouseId, type);
|
||||||
|
|
||||||
|
// 发货单 -> 商品 (1:N)
|
||||||
|
DynamicModel.hasMany(ItemsModel, {
|
||||||
|
foreignKey: 'order_id',
|
||||||
|
sourceKey: 'id',
|
||||||
|
as: 'orderItems',
|
||||||
|
constraints: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 商品 -> 发货单 (N:1)
|
||||||
|
ItemsModel.belongsTo(DynamicModel, {
|
||||||
|
foreignKey: 'order_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'delivery',
|
||||||
|
constraints: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关联店铺表
|
||||||
|
if (this.app.model.Store) {
|
||||||
|
DynamicModel.belongsTo(this.app.model.Store, {
|
||||||
|
foreignKey: 'store_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'store',
|
||||||
|
constraints: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
DynamicModel.belongsTo(this.app.model.Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'warehouse',
|
||||||
|
constraints: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
this.app.logger.warn('设置关联关系失败:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查表是否存在
|
||||||
|
* @param tableName
|
||||||
|
*/
|
||||||
|
async checkTableExists(tableName) {
|
||||||
|
const sequelize = this.app.model;
|
||||||
|
const queryInterface = sequelize.getQueryInterface();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const tables = await queryInterface.showAllTables();
|
||||||
|
return tables.includes(tableName);
|
||||||
|
} catch (error) {
|
||||||
|
// 备用方案:使用原始查询
|
||||||
|
const checkSQL = `
|
||||||
|
SELECT TABLE_NAME
|
||||||
|
FROM INFORMATION_SCHEMA.TABLES
|
||||||
|
WHERE TABLE_SCHEMA = DATABASE()
|
||||||
|
AND TABLE_NAME = ?
|
||||||
|
`;
|
||||||
|
|
||||||
|
const [ results ] = await sequelize.query(checkSQL, {
|
||||||
|
replacements: [ tableName ],
|
||||||
|
});
|
||||||
|
return results.length > 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建物理表
|
||||||
|
* @param warehouseId
|
||||||
|
* @param type
|
||||||
|
*/
|
||||||
|
async createPhysicalTable(warehouseId, type = 'current') {
|
||||||
|
const tableName = this.generateTableName(warehouseId, type);
|
||||||
|
const tableComment = type === 'history'
|
||||||
|
? `仓库${warehouseId}发货单历史表`
|
||||||
|
: `仓库${warehouseId}发货单常用表`;
|
||||||
|
|
||||||
|
// 添加历史表特有的字段
|
||||||
|
const historyFields = type === 'history' ?
|
||||||
|
',\n`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : '';
|
||||||
|
|
||||||
|
// 状态机枚举值
|
||||||
|
const statusEnums = this.getStatusEnumValues();
|
||||||
|
|
||||||
|
const createTableSQL = `
|
||||||
|
CREATE TABLE \`${tableName}\` (
|
||||||
|
\`id\` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
\`delivery_order_code\` varchar(50) DEFAULT NULL COMMENT '发货单号',
|
||||||
|
\`pre_delivery_order_code\` varchar(50) DEFAULT NULL COMMENT '预发货单号',
|
||||||
|
\`pre_delivery_order_id\` varchar(50) DEFAULT NULL COMMENT '预发货单ID',
|
||||||
|
\`order_type\` varchar(50) DEFAULT NULL COMMENT '订单类型',
|
||||||
|
\`warehouse_code\` varchar(50) DEFAULT NULL COMMENT '仓库编码',
|
||||||
|
\`order_flag\` varchar(200) DEFAULT NULL COMMENT '订单标记',
|
||||||
|
\`source_platform_code\` varchar(50) DEFAULT NULL COMMENT '来源平台编码',
|
||||||
|
\`source_platform_name\` varchar(200) DEFAULT NULL COMMENT '来源平台名称',
|
||||||
|
\`create_at\` datetime DEFAULT NULL COMMENT '创建时间',
|
||||||
|
\`delete_at\` datetime DEFAULT NULL COMMENT '删除时间',
|
||||||
|
\`updated_at\` datetime DEFAULT NULL COMMENT '更新时间',
|
||||||
|
\`place_order_time\` datetime DEFAULT NULL COMMENT '店铺创建订单时间',
|
||||||
|
\`pay_time\` datetime DEFAULT NULL COMMENT '支付时间',
|
||||||
|
\`pay_no\` varchar(50) DEFAULT NULL COMMENT '支付单号',
|
||||||
|
\`service_code\` varchar(50) DEFAULT NULL COMMENT '集包服务编码',
|
||||||
|
\`operator_name\` varchar(50) DEFAULT NULL COMMENT 'ERP审核人',
|
||||||
|
\`operate_time\` datetime DEFAULT NULL COMMENT 'ERP审核时间',
|
||||||
|
\`shop_nick\` varchar(200) DEFAULT NULL COMMENT '店铺名称',
|
||||||
|
\`seller_nick\` varchar(200) DEFAULT NULL COMMENT '卖家名称',
|
||||||
|
\`buyer_nick\` varchar(200) DEFAULT NULL COMMENT '买家名称',
|
||||||
|
\`total_amount\` decimal(18,2) DEFAULT NULL COMMENT '订单总金额',
|
||||||
|
\`item_amount\` decimal(18,2) DEFAULT NULL COMMENT '商品总金额',
|
||||||
|
\`discount_amount\` decimal(18,2) DEFAULT NULL COMMENT '订单折扣金额',
|
||||||
|
\`freight\` decimal(18,2) DEFAULT NULL COMMENT '快递费用',
|
||||||
|
\`ar_amount\` decimal(18,2) DEFAULT NULL COMMENT '应收金额',
|
||||||
|
\`got_amount\` decimal(18,2) DEFAULT NULL COMMENT '已收金额',
|
||||||
|
\`service_fee\` decimal(18,2) DEFAULT NULL COMMENT 'COD服务费',
|
||||||
|
\`logistics_code\` varchar(50) DEFAULT NULL COMMENT '物流公司编码',
|
||||||
|
\`logistics_name\` varchar(200) DEFAULT NULL COMMENT '物流公司名称',
|
||||||
|
\`express_code\` varchar(50) DEFAULT NULL COMMENT '面单号前置',
|
||||||
|
\`logistics_area_code\` varchar(50) DEFAULT NULL COMMENT '快递区域编码, 大头笔信息',
|
||||||
|
\`delivery_type\` varchar(255) DEFAULT NULL COMMENT '发货服务类型',
|
||||||
|
\`is_urgency\` enum('Y','N') DEFAULT 'N' COMMENT '是否紧急',
|
||||||
|
\`invoice_flag\` enum('Y','N') DEFAULT 'N' COMMENT '是否需要发票',
|
||||||
|
\`status\` enum('pedding','created','cancel','error') DEFAULT 'created' COMMENT '状态',
|
||||||
|
\`name\` text COMMENT '收件人姓名',
|
||||||
|
\`zip_code\` varchar(50) DEFAULT NULL COMMENT '收件人邮编',
|
||||||
|
\`tel\` text COMMENT '收件人电话',
|
||||||
|
\`mobile\` text COMMENT '收件人移动电话',
|
||||||
|
\`email\` text COMMENT '收件人邮箱',
|
||||||
|
\`country_code\` varchar(255) DEFAULT NULL COMMENT '国家编码',
|
||||||
|
\`province\` varchar(255) DEFAULT NULL COMMENT '省份',
|
||||||
|
\`city\` varchar(255) DEFAULT NULL COMMENT '城市',
|
||||||
|
\`area\` varchar(255) DEFAULT NULL COMMENT '区',
|
||||||
|
\`town\` varchar(255) DEFAULT NULL COMMENT '镇',
|
||||||
|
\`detail_address\` varchar(255) DEFAULT NULL COMMENT '详细地址',
|
||||||
|
\`id_type\` varchar(255) DEFAULT NULL COMMENT '证件类型',
|
||||||
|
\`id_number\` int(11) DEFAULT NULL COMMENT '证件号码',
|
||||||
|
\`oaid\` text COMMENT 'OAID',
|
||||||
|
\`sync_status\` enum('padding','fin','error') DEFAULT 'padding' COMMENT '同步状态',
|
||||||
|
\`store_id\` bigint(20) UNSIGNED DEFAULT NULL COMMENT '货主id',
|
||||||
|
\`warehouse_id\` bigint(20) UNSIGNED DEFAULT NULL COMMENT '仓库id',
|
||||||
|
\`from_key\` int(11) DEFAULT NULL COMMENT '来源键',
|
||||||
|
\`items\` text COMMENT '商品结构字符串',
|
||||||
|
\`items_count\` smallint(5) UNSIGNED NOT NULL DEFAULT '0' COMMENT '商品种类数',
|
||||||
|
\`items_total\` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '商品总数',
|
||||||
|
\`items_weight\` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '总重量',
|
||||||
|
\`items_hash\` char(32) NOT NULL DEFAULT '' COMMENT '哈希值',
|
||||||
|
\`items_crc\` int(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '校验码',
|
||||||
|
\`wave_id\` bigint(20) NOT NULL DEFAULT '0' COMMENT '波次ID,0表示未分配',
|
||||||
|
\`post_status\` enum('padding','fin','timeout','error','none') DEFAULT 'none' COMMENT '分配快递号状态机',
|
||||||
|
\`storage_status\` enum('padding','fin','error','none') DEFAULT 'none' COMMENT '分配储位状态机',
|
||||||
|
\`pick_status\` enum('padding','fin','error','none') DEFAULT 'none' COMMENT '拣货状态机',
|
||||||
|
\`pack_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '打包状态机',
|
||||||
|
\`inspection_status\` enum('none','padding','running','fin','error') DEFAULT 'none' COMMENT '检验状态机',
|
||||||
|
\`print_status\` enum('none','padding','fin','error') DEFAULT NULL COMMENT '打印状态机',
|
||||||
|
\`claim_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '领取状态机',
|
||||||
|
\`outbound_status\` enum('none','padding','fin','error') DEFAULT 'none' COMMENT '出库状态机',
|
||||||
|
\`lock_status\` enum('none','warehouse','store') DEFAULT NULL COMMENT '锁定状态机',
|
||||||
|
\`intercept_status\` enum('none','requesting','requested','intercepting','intercepted_in_transit','intercepted_at_warehouse','returning','returned','delivered_by_mistake','timeout','cancelled','failed','exception') DEFAULT NULL COMMENT '拦截状态机'
|
||||||
|
${historyFields},
|
||||||
|
PRIMARY KEY (\`id\`),
|
||||||
|
UNIQUE KEY \`idx_${warehouseId}_${type}_delivery_code\` (\`delivery_order_code\`,\`store_id\`,\`warehouse_id\`),
|
||||||
|
KEY \`idx_${warehouseId}_${type}_store_id\` (\`store_id\`),
|
||||||
|
KEY \`idx_${warehouseId}_${type}_warehouse_id\` (\`warehouse_id\`),
|
||||||
|
KEY \`idx_${warehouseId}_${type}_items\` (\`items\`(50)),
|
||||||
|
KEY \`idx_${warehouseId}_${type}_items_hash\` (\`items_hash\`),
|
||||||
|
KEY \`idx_${warehouseId}_${type}_hash_crc\` (\`items_hash\`,\`items_crc\`,\`warehouse_id\`),
|
||||||
|
KEY \`idx_${warehouseId}_${type}_wave\` (\`status\`,\`wave_id\`),
|
||||||
|
KEY \`idx_${warehouseId}_${type}_statuses\` (\`status\`,\`post_status\`,\`pick_status\`,\`pack_status\`,\`outbound_status\`)
|
||||||
|
${type === 'history' ? `,KEY \`idx_${warehouseId}_history_archive_time\` (\`archive_time\`)` : ''}
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='${tableComment}';
|
||||||
|
`;
|
||||||
|
|
||||||
|
await this.app.model.query(createTableSQL);
|
||||||
|
this.app.logger.info(`创建物理表成功: ${tableName}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取状态枚举值
|
||||||
|
*/
|
||||||
|
getStatusEnumValues() {
|
||||||
|
return {
|
||||||
|
status: [ 'created', 'cancel', 'error' ],
|
||||||
|
sync_status: [ 'padding', 'fin', 'error' ],
|
||||||
|
post_status: [ 'padding', 'fin', 'timeout', 'error', 'none' ],
|
||||||
|
storage_status: [ 'padding', 'fin', 'error', 'none' ],
|
||||||
|
pick_status: [ 'padding', 'fin', 'error', 'none' ],
|
||||||
|
pack_status: [ 'none', 'padding', 'fin', 'error' ],
|
||||||
|
inspection_status: [ 'none', 'padding', 'running', 'fin', 'error' ],
|
||||||
|
print_status: [ 'none', 'padding', 'fin', 'error' ],
|
||||||
|
claim_status: [ 'none', 'padding', 'fin', 'error' ],
|
||||||
|
outbound_status: [ 'none', 'padding', 'fin', 'error' ],
|
||||||
|
lock_status: [ 'none', 'warehouse', 'store' ],
|
||||||
|
intercept_status: [
|
||||||
|
'none', 'requesting', 'requested', 'intercepting',
|
||||||
|
'intercepted_in_transit', 'intercepted_at_warehouse',
|
||||||
|
'returning', 'returned', 'delivered_by_mistake',
|
||||||
|
'timeout', 'cancelled', 'failed', 'exception',
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成表名
|
||||||
|
* @param warehouseId
|
||||||
|
* @param type
|
||||||
|
*/
|
||||||
|
generateTableName(warehouseId, type) {
|
||||||
|
const suffix = type === 'history' ? '_history' : '';
|
||||||
|
return `wms_order_delivery_${warehouseId}${suffix}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理模型缓存
|
||||||
|
*/
|
||||||
|
clearCache() {
|
||||||
|
this.modelCache.clear();
|
||||||
|
this.app.logger.info('模型缓存已清理');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有缓存的模型
|
||||||
|
*/
|
||||||
|
getCachedModels() {
|
||||||
|
return Array.from(this.modelCache.entries());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new OrderDeliveryFactory();
|
||||||
|
};
|
||||||
145
app/model/order_items.js
Normal file
145
app/model/order_items.js
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
// model/order_items.js
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { Sequelize, model } = app;
|
||||||
|
const { STRING, BIGINT, DECIMAL, TEXT, INTEGER, JSON } = Sequelize;
|
||||||
|
|
||||||
|
const OrderItems = model.define('wms_order_items', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
},
|
||||||
|
order_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '订单ID',
|
||||||
|
},
|
||||||
|
actual_price: {
|
||||||
|
type: DECIMAL(18, 2),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0.00,
|
||||||
|
comment: '实际价格',
|
||||||
|
},
|
||||||
|
retail_price: {
|
||||||
|
type: DECIMAL(18, 2),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '零售价格',
|
||||||
|
},
|
||||||
|
ext_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '外部编码',
|
||||||
|
},
|
||||||
|
inventory_type: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '库存类型',
|
||||||
|
},
|
||||||
|
item_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '商品编码',
|
||||||
|
},
|
||||||
|
item_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '商品ID',
|
||||||
|
},
|
||||||
|
item_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '商品名称',
|
||||||
|
},
|
||||||
|
order_line_no: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '订单行号',
|
||||||
|
},
|
||||||
|
owner_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货主编码',
|
||||||
|
},
|
||||||
|
plan_qty: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '计划数量',
|
||||||
|
},
|
||||||
|
source_order_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '源订单编码',
|
||||||
|
},
|
||||||
|
sub_source_order_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '子源订单编码',
|
||||||
|
},
|
||||||
|
extend_props: {
|
||||||
|
type: JSON, // 改为JSON类型,便于查询
|
||||||
|
allowNull: true,
|
||||||
|
comment: '扩展属性(JSON格式)',
|
||||||
|
},
|
||||||
|
stock_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '库存ID',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: Sequelize.DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: Sequelize.NOW,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: Sequelize.DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: Sequelize.NOW,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_order_items',
|
||||||
|
timestamps: true, // 启用时间戳
|
||||||
|
underscored: true, // 使用下划线命名
|
||||||
|
paranoid: false, // 不启用软删除
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'idx_order_id',
|
||||||
|
fields: [ 'order_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_item_id',
|
||||||
|
fields: [ 'item_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_item_code',
|
||||||
|
fields: [ 'item_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_source_order_code',
|
||||||
|
fields: [ 'source_order_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_stock_id',
|
||||||
|
fields: [ 'stock_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_owner_code',
|
||||||
|
fields: [ 'owner_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_order_item',
|
||||||
|
fields: [ 'order_id', 'item_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_created_at',
|
||||||
|
fields: [ 'created_at' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
comment: '订单商品明细表',
|
||||||
|
});
|
||||||
|
|
||||||
|
return OrderItems;
|
||||||
|
};
|
||||||
301
app/model/order_items_factory.js
Normal file
301
app/model/order_items_factory.js
Normal file
@ -0,0 +1,301 @@
|
|||||||
|
// order_items_factory.js
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { Sequelize, model } = app;
|
||||||
|
|
||||||
|
class OrderItemsFactory {
|
||||||
|
constructor() {
|
||||||
|
this.modelCache = new Map();
|
||||||
|
this.app = app;
|
||||||
|
this.creatingTables = new Map(); // 防止并发创建表
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前表模型
|
||||||
|
* @param warehouseId
|
||||||
|
*/
|
||||||
|
async getCurrentModel(warehouseId) {
|
||||||
|
return await this.getOrCreateModel(warehouseId, 'current');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取历史表模型
|
||||||
|
* @param warehouseId
|
||||||
|
*/
|
||||||
|
async getHistoryModel(warehouseId) {
|
||||||
|
return await this.getOrCreateModel(warehouseId, 'history');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取或创建模型
|
||||||
|
* @param warehouseId
|
||||||
|
* @param type
|
||||||
|
*/
|
||||||
|
async getOrCreateModel(warehouseId, type = 'current') {
|
||||||
|
const cacheKey = `${warehouseId}_${type}`;
|
||||||
|
|
||||||
|
// 检查缓存
|
||||||
|
if (this.modelCache.has(cacheKey)) {
|
||||||
|
return this.modelCache.get(cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tableName = this.generateTableName(warehouseId, type);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 防止并发创建表
|
||||||
|
if (this.creatingTables.has(cacheKey)) {
|
||||||
|
await this.creatingTables.get(cacheKey);
|
||||||
|
return this.modelCache.get(cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
const createPromise = this.createModelWithRetry(warehouseId, type, tableName, cacheKey);
|
||||||
|
this.creatingTables.set(cacheKey, createPromise);
|
||||||
|
|
||||||
|
const dynamicModel = await createPromise;
|
||||||
|
this.creatingTables.delete(cacheKey);
|
||||||
|
|
||||||
|
return dynamicModel;
|
||||||
|
} catch (error) {
|
||||||
|
this.creatingTables.delete(cacheKey);
|
||||||
|
this.app.logger.error(`获取订单商品模型失败 ${tableName}:`, error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 带重试的模型创建
|
||||||
|
* @param warehouseId
|
||||||
|
* @param type
|
||||||
|
* @param tableName
|
||||||
|
* @param cacheKey
|
||||||
|
* @param retryCount
|
||||||
|
*/
|
||||||
|
async createModelWithRetry(warehouseId, type, tableName, cacheKey, retryCount = 3) {
|
||||||
|
for (let i = 0; i < retryCount; i++) {
|
||||||
|
try {
|
||||||
|
// 检查表是否存在
|
||||||
|
const tableExists = await this.checkTableExists(tableName);
|
||||||
|
if (!tableExists) {
|
||||||
|
await this.createPhysicalTable(warehouseId, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建模型实例
|
||||||
|
const mainModel = this.app.model.OrderItems;
|
||||||
|
const attributes = { ...mainModel.rawAttributes };
|
||||||
|
|
||||||
|
// 移除主键的autoIncrement属性,避免动态表冲突
|
||||||
|
if (attributes.id) {
|
||||||
|
delete attributes.id.autoIncrement;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DynamicModel = this.app.model.define(tableName, attributes, {
|
||||||
|
tableName,
|
||||||
|
timestamps: true,
|
||||||
|
underscored: true,
|
||||||
|
paranoid: false,
|
||||||
|
indexes: this.generateIndexes(warehouseId),
|
||||||
|
comment: type === 'history'
|
||||||
|
? `仓库${warehouseId}订单商品历史表`
|
||||||
|
: `仓库${warehouseId}订单商品常用表`,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 复制关联关系
|
||||||
|
this.copyAssociations(mainModel, DynamicModel);
|
||||||
|
|
||||||
|
// 缓存模型
|
||||||
|
this.modelCache.set(cacheKey, DynamicModel);
|
||||||
|
this.app.logger.info(`创建订单商品动态模型成功: ${tableName}`);
|
||||||
|
|
||||||
|
return DynamicModel;
|
||||||
|
} catch (error) {
|
||||||
|
if (i === retryCount - 1) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
this.app.logger.warn(`创建模型失败,第${i + 1}次重试:`, error.message);
|
||||||
|
await this.sleep(500); // 等待500ms后重试
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 复制关联关系
|
||||||
|
* @param sourceModel
|
||||||
|
* @param targetModel
|
||||||
|
*/
|
||||||
|
copyAssociations(sourceModel, targetModel) {
|
||||||
|
if (sourceModel.associations) {
|
||||||
|
Object.keys(sourceModel.associations).forEach(key => {
|
||||||
|
const association = sourceModel.associations[key];
|
||||||
|
const options = { ...association.options };
|
||||||
|
|
||||||
|
// 避免动态表的外键约束问题
|
||||||
|
options.constraints = false;
|
||||||
|
|
||||||
|
if (association.associationType === 'BelongsTo') {
|
||||||
|
targetModel.belongsTo(
|
||||||
|
association.target,
|
||||||
|
{
|
||||||
|
...options,
|
||||||
|
foreignKey: association.foreignKey,
|
||||||
|
as: association.as,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成索引配置
|
||||||
|
* @param warehouseId
|
||||||
|
*/
|
||||||
|
generateIndexes(warehouseId) {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
name: `idx_${warehouseId}_order_id`,
|
||||||
|
fields: [ 'order_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${warehouseId}_item_id`,
|
||||||
|
fields: [ 'item_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${warehouseId}_item_code`,
|
||||||
|
fields: [ 'item_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${warehouseId}_source_order_code`,
|
||||||
|
fields: [ 'source_order_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${warehouseId}_stock_id`,
|
||||||
|
fields: [ 'stock_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${warehouseId}_owner_code`,
|
||||||
|
fields: [ 'owner_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${warehouseId}_order_item`,
|
||||||
|
fields: [ 'order_id', 'item_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `idx_${warehouseId}_created_at`,
|
||||||
|
fields: [ 'created_at' ],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查表是否存在
|
||||||
|
* @param tableName
|
||||||
|
*/
|
||||||
|
async checkTableExists(tableName) {
|
||||||
|
try {
|
||||||
|
const [ results ] = await this.app.model.query(
|
||||||
|
`SELECT 1 FROM information_schema.tables
|
||||||
|
WHERE table_schema = DATABASE()
|
||||||
|
AND table_name = :tableName`,
|
||||||
|
{
|
||||||
|
replacements: { tableName },
|
||||||
|
type: Sequelize.QueryTypes.SELECT,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return !!results;
|
||||||
|
} catch (error) {
|
||||||
|
this.app.logger.error('检查表是否存在失败:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建物理表
|
||||||
|
* @param warehouseId
|
||||||
|
* @param type
|
||||||
|
*/
|
||||||
|
async createPhysicalTable(warehouseId, type = 'current') {
|
||||||
|
const tableName = this.generateTableName(warehouseId, type);
|
||||||
|
const tableComment = type === 'history'
|
||||||
|
? `仓库${warehouseId}订单商品历史表`
|
||||||
|
: `仓库${warehouseId}订单商品常用表`;
|
||||||
|
|
||||||
|
// 历史表特有字段
|
||||||
|
const historyFields = type === 'history' ?
|
||||||
|
',`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : '';
|
||||||
|
|
||||||
|
const createTableSQL = `
|
||||||
|
CREATE TABLE IF NOT EXISTS \`${tableName}\` (
|
||||||
|
\`id\` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
||||||
|
\`order_id\` bigint(20) unsigned DEFAULT NULL COMMENT '订单ID',
|
||||||
|
\`actual_price\` decimal(18,2) NOT NULL DEFAULT '0.00' COMMENT '实际价格',
|
||||||
|
\`retail_price\` decimal(18,2) DEFAULT NULL COMMENT '零售价格',
|
||||||
|
\`ext_code\` varchar(50) DEFAULT NULL COMMENT '外部编码',
|
||||||
|
\`inventory_type\` varchar(50) DEFAULT NULL COMMENT '库存类型',
|
||||||
|
\`item_code\` varchar(50) DEFAULT NULL COMMENT '商品编码',
|
||||||
|
\`item_id\` bigint(20) DEFAULT NULL COMMENT '商品ID',
|
||||||
|
\`item_name\` varchar(200) DEFAULT NULL COMMENT '商品名称',
|
||||||
|
\`order_line_no\` varchar(50) DEFAULT NULL COMMENT '订单行号',
|
||||||
|
\`owner_code\` varchar(50) DEFAULT NULL COMMENT '货主编码',
|
||||||
|
\`plan_qty\` int(11) DEFAULT NULL COMMENT '计划数量',
|
||||||
|
\`source_order_code\` varchar(50) DEFAULT NULL COMMENT '源订单编码',
|
||||||
|
\`sub_source_order_code\` varchar(50) DEFAULT NULL COMMENT '子源订单编码',
|
||||||
|
\`extend_props\` json DEFAULT NULL COMMENT '扩展属性(JSON格式)',
|
||||||
|
\`stock_id\` bigint(20) DEFAULT NULL COMMENT '库存ID',
|
||||||
|
\`created_at\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
\`updated_at\` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
|
||||||
|
${historyFields},
|
||||||
|
PRIMARY KEY (\`id\`),
|
||||||
|
KEY \`idx_${warehouseId}_order_id\` (\`order_id\`),
|
||||||
|
KEY \`idx_${warehouseId}_item_id\` (\`item_id\`),
|
||||||
|
KEY \`idx_${warehouseId}_item_code\` (\`item_code\`),
|
||||||
|
KEY \`idx_${warehouseId}_source_order_code\` (\`source_order_code\`),
|
||||||
|
KEY \`idx_${warehouseId}_stock_id\` (\`stock_id\`),
|
||||||
|
KEY \`idx_${warehouseId}_owner_code\` (\`owner_code\`),
|
||||||
|
KEY \`idx_${warehouseId}_order_item\` (\`order_id\`, \`item_id\`),
|
||||||
|
KEY \`idx_${warehouseId}_created_at\` (\`created_at\`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='${tableComment}';
|
||||||
|
`;
|
||||||
|
|
||||||
|
await this.app.model.query(createTableSQL);
|
||||||
|
this.app.logger.info(`创建订单商品物理表成功: ${tableName}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成表名
|
||||||
|
* @param warehouseId
|
||||||
|
* @param type
|
||||||
|
*/
|
||||||
|
generateTableName(warehouseId, type) {
|
||||||
|
const suffix = type === 'history' ? '_history' : '';
|
||||||
|
return `wms_order_items_${warehouseId}${suffix}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除缓存
|
||||||
|
* @param warehouseId
|
||||||
|
* @param type
|
||||||
|
*/
|
||||||
|
clearCache(warehouseId, type) {
|
||||||
|
const cacheKey = `${warehouseId}_${type}`;
|
||||||
|
this.modelCache.delete(cacheKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除所有缓存
|
||||||
|
*/
|
||||||
|
clearAllCache() {
|
||||||
|
this.modelCache.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 休眠函数
|
||||||
|
* @param ms
|
||||||
|
*/
|
||||||
|
sleep(ms) {
|
||||||
|
return new Promise(resolve => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new OrderItemsFactory();
|
||||||
|
};
|
||||||
276
app/model/permission.js
Normal file
276
app/model/permission.js
Normal file
@ -0,0 +1,276 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { INTEGER, STRING, DATE, TINYINT, ENUM } = app.Sequelize;
|
||||||
|
|
||||||
|
const Permission = app.model.define('permission', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '权限ID',
|
||||||
|
},
|
||||||
|
path: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: {
|
||||||
|
msg: '路由路径不能为空',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '路由路径',
|
||||||
|
},
|
||||||
|
component: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '组件路径',
|
||||||
|
},
|
||||||
|
name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '路由名称',
|
||||||
|
},
|
||||||
|
redirect: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '重定向路径',
|
||||||
|
},
|
||||||
|
meta_title: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '页面标题',
|
||||||
|
},
|
||||||
|
meta_icon: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '图标',
|
||||||
|
},
|
||||||
|
hidden: {
|
||||||
|
type: TINYINT(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
validate: {
|
||||||
|
isIn: {
|
||||||
|
args: [[ 0, 1 ]],
|
||||||
|
msg: '隐藏字段只能是0或1',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '是否隐藏(0:显示,1:隐藏)',
|
||||||
|
},
|
||||||
|
always_show: {
|
||||||
|
type: TINYINT(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
validate: {
|
||||||
|
isIn: {
|
||||||
|
args: [[ 0, 1 ]],
|
||||||
|
msg: '始终显示字段只能是0或1',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '是否始终显示',
|
||||||
|
},
|
||||||
|
parent_id: {
|
||||||
|
type: INTEGER,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '父级ID',
|
||||||
|
},
|
||||||
|
sort: {
|
||||||
|
type: INTEGER,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '排序',
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: TINYINT(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
validate: {
|
||||||
|
isIn: {
|
||||||
|
args: [[ 0, 1 ]],
|
||||||
|
msg: '状态只能是0或1',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '状态(0:禁用,1:启用)',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
update_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
type: {
|
||||||
|
type: ENUM('web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'web_pages',
|
||||||
|
comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块)',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_permission',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: true,
|
||||||
|
timestamps: true,
|
||||||
|
paranoid: false, // 明确禁用软删除
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'update_at',
|
||||||
|
comment: '权限路由表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'idx_parent_id',
|
||||||
|
fields: [ 'parent_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_status',
|
||||||
|
fields: [ 'status' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系 - 自关联,构建树形结构
|
||||||
|
Permission.associate = function(models) {
|
||||||
|
const { Role, Permission, RolePermission } = app.model;
|
||||||
|
// 子权限
|
||||||
|
Permission.hasMany(Permission, {
|
||||||
|
foreignKey: 'parent_id',
|
||||||
|
as: 'children',
|
||||||
|
scope: {
|
||||||
|
status: 1,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 父权限
|
||||||
|
Permission.belongsTo(Permission, {
|
||||||
|
foreignKey: 'parent_id',
|
||||||
|
as: 'parent',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 角色权限关联
|
||||||
|
Permission.belongsToMany(Role, {
|
||||||
|
through: RolePermission,
|
||||||
|
foreignKey: 'permission_id',
|
||||||
|
otherKey: 'role_id',
|
||||||
|
as: 'roles',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:获取类型对应的中文名称
|
||||||
|
Permission.prototype.getTypeName = function() {
|
||||||
|
const typeMap = {
|
||||||
|
web_pages: '电脑端页面',
|
||||||
|
pda_pages: 'PDA页面',
|
||||||
|
btns: '按钮权限',
|
||||||
|
api: '接口权限',
|
||||||
|
miniprogram_pages: '小程序页面',
|
||||||
|
block: '功能模块',
|
||||||
|
};
|
||||||
|
return typeMap[this.type] || this.type;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:检查是否启用
|
||||||
|
Permission.prototype.isEnabled = function() {
|
||||||
|
return this.status === 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:检查是否隐藏
|
||||||
|
Permission.prototype.isHidden = function() {
|
||||||
|
return this.hidden === 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:根据类型获取权限列表
|
||||||
|
Permission.findByType = async function(type, includeChildren = false) {
|
||||||
|
const where = { status: 1 };
|
||||||
|
|
||||||
|
if (type) {
|
||||||
|
where.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
where,
|
||||||
|
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
||||||
|
};
|
||||||
|
|
||||||
|
if (includeChildren) {
|
||||||
|
options.include = [{
|
||||||
|
model: this.associations.children.target,
|
||||||
|
as: 'children',
|
||||||
|
where: { status: 1 },
|
||||||
|
required: false,
|
||||||
|
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.findAll(options);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:构建树形结构的权限列表
|
||||||
|
Permission.getTreeByType = async function(type) {
|
||||||
|
const permissions = await this.findByType(type);
|
||||||
|
return this.buildPermissionTree(permissions);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 静态方法:构建权限树
|
||||||
|
Permission.buildPermissionTree = function(permissions) {
|
||||||
|
const permissionMap = new Map();
|
||||||
|
const rootPermissions = [];
|
||||||
|
|
||||||
|
// 创建映射
|
||||||
|
permissions.forEach(permission => {
|
||||||
|
permissionMap.set(permission.id, {
|
||||||
|
id: permission.id,
|
||||||
|
path: permission.path,
|
||||||
|
component: permission.component,
|
||||||
|
name: permission.name,
|
||||||
|
redirect: permission.redirect,
|
||||||
|
meta: {
|
||||||
|
title: permission.meta_title,
|
||||||
|
icon: permission.meta_icon,
|
||||||
|
},
|
||||||
|
hidden: permission.hidden === 1,
|
||||||
|
alwaysShow: permission.always_show === 1,
|
||||||
|
sort: permission.sort,
|
||||||
|
type: permission.type,
|
||||||
|
children: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 构建树形结构
|
||||||
|
permissions.forEach(permission => {
|
||||||
|
const node = permissionMap.get(permission.id);
|
||||||
|
|
||||||
|
if (permission.parent_id === 0) {
|
||||||
|
rootPermissions.push(node);
|
||||||
|
} else {
|
||||||
|
const parent = permissionMap.get(permission.parent_id);
|
||||||
|
if (parent) {
|
||||||
|
parent.children.push(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 排序
|
||||||
|
const sortTree = nodes => {
|
||||||
|
if (!nodes || nodes.length === 0) return;
|
||||||
|
|
||||||
|
nodes.sort((a, b) => {
|
||||||
|
return a.sort - b.sort || a.id - b.id;
|
||||||
|
});
|
||||||
|
|
||||||
|
nodes.forEach(node => {
|
||||||
|
if (node.children && node.children.length > 0) {
|
||||||
|
sortTree(node.children);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
sortTree(rootPermissions);
|
||||||
|
|
||||||
|
return rootPermissions;
|
||||||
|
};
|
||||||
|
|
||||||
|
return Permission;
|
||||||
|
};
|
||||||
35
app/model/platform.js
Normal file
35
app/model/platform.js
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING } = app.Sequelize;
|
||||||
|
|
||||||
|
const Platform = app.model.define('platform', {
|
||||||
|
code: {
|
||||||
|
type: STRING(50),
|
||||||
|
primaryKey: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '平台代码',
|
||||||
|
},
|
||||||
|
name: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '平台名称',
|
||||||
|
},
|
||||||
|
default_express_interface: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '默认快递接口',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_platform',
|
||||||
|
freezeTableName: true,
|
||||||
|
timestamps: false,
|
||||||
|
underscored: true,
|
||||||
|
comment: '平台表',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 移除 associate 方法,稍后在单独的初始化文件中定义关联
|
||||||
|
// 或者在控制器中动态定义关联
|
||||||
|
|
||||||
|
return Platform;
|
||||||
|
};
|
||||||
66
app/model/platform_setting.js
Normal file
66
app/model/platform_setting.js
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, BIGINT, INTEGER } = app.Sequelize;
|
||||||
|
|
||||||
|
// 修改这里的变量名,与文件名一致
|
||||||
|
const PlatformSetting = app.model.define('platform_setting', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
platform_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '平台代码',
|
||||||
|
},
|
||||||
|
code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '设置代码',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库ID',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_platfrom_setting',
|
||||||
|
freezeTableName: true,
|
||||||
|
timestamps: false,
|
||||||
|
comment: '平台设置表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'platform_code',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'platform_code', 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'warehouse_id',
|
||||||
|
fields: [ 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
// 定义关联关系
|
||||||
|
PlatformSetting.associate = function() {
|
||||||
|
const { Store, Platform } = app.model;
|
||||||
|
|
||||||
|
// 关联仓库
|
||||||
|
PlatformSetting.belongsTo(Platform, {
|
||||||
|
foreignKey: 'platform_code',
|
||||||
|
targetKey: 'code',
|
||||||
|
as: 'platform',
|
||||||
|
});
|
||||||
|
// 关联仓库
|
||||||
|
PlatformSetting.belongsTo(Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'warehouse',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
// 返回正确的变量名
|
||||||
|
return PlatformSetting;
|
||||||
|
};
|
||||||
39
app/model/print_computer.js
Normal file
39
app/model/print_computer.js
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { INTEGER, BIGINT, STRING } = app.Sequelize;
|
||||||
|
|
||||||
|
const PrintComputer = app.model.define('print_computer', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '仓库ID',
|
||||||
|
},
|
||||||
|
name: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '打印台名称',
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: INTEGER(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
comment: '状态,1-已激活,0-未激活',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_print_computer',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: false,
|
||||||
|
timestamps: false,
|
||||||
|
comment: '打印台电脑表',
|
||||||
|
});
|
||||||
|
|
||||||
|
return PrintComputer;
|
||||||
|
};
|
||||||
273
app/model/print_item.js
Normal file
273
app/model/print_item.js
Normal file
@ -0,0 +1,273 @@
|
|||||||
|
// app/model/print_item.js
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, BOOLEAN, TEXT, JSON, DATE } = app.Sequelize;
|
||||||
|
|
||||||
|
const PrintItem = app.model.define('print_item', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
business_type: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '业务类型',
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
platform: {
|
||||||
|
type: STRING(30),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '平台',
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
field_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '字段名(显示名称)',
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
field_code: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '字段代码(英文标识)',
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
is: /^[a-zA-Z_][a-zA-Z0-9_]*$/, // 验证字段代码格式
|
||||||
|
},
|
||||||
|
},
|
||||||
|
field_type: {
|
||||||
|
type: STRING(30),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '字段类型',
|
||||||
|
validate: {
|
||||||
|
isIn: [[ 'text', 'number', 'date', 'datetime', 'select', 'checkbox', 'textarea', 'image', 'barcode', 'qrcode' ]],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// 新增:是否渲染为表格
|
||||||
|
is_table: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
defaultValue: false,
|
||||||
|
comment: '是否渲染为表格:0-否,1-是',
|
||||||
|
field: 'is_table',
|
||||||
|
},
|
||||||
|
// 新增:表格配置
|
||||||
|
table_config: {
|
||||||
|
type: JSON,
|
||||||
|
comment: '表格配置',
|
||||||
|
},
|
||||||
|
// 新增:分组字段
|
||||||
|
group_field: {
|
||||||
|
type: STRING(100),
|
||||||
|
comment: '分组字段',
|
||||||
|
validate: {
|
||||||
|
is: /^[a-zA-Z_][a-zA-Z0-9_]*$/,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// 新增:分组标题(国际化key)
|
||||||
|
group_label: {
|
||||||
|
type: STRING(100),
|
||||||
|
comment: '分组标题',
|
||||||
|
},
|
||||||
|
// 新增:分组排序
|
||||||
|
group_sort: {
|
||||||
|
type: INTEGER,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '分组排序',
|
||||||
|
},
|
||||||
|
required: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
defaultValue: false,
|
||||||
|
comment: '是否必填:0-否,1-是',
|
||||||
|
field: 'required',
|
||||||
|
},
|
||||||
|
default_value: {
|
||||||
|
type: STRING(500),
|
||||||
|
comment: '默认值',
|
||||||
|
},
|
||||||
|
sort_order: {
|
||||||
|
type: INTEGER,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '排序序号',
|
||||||
|
},
|
||||||
|
regex_pattern: {
|
||||||
|
type: STRING(200),
|
||||||
|
comment: '正则验证规则',
|
||||||
|
},
|
||||||
|
max_length: {
|
||||||
|
type: INTEGER,
|
||||||
|
comment: '最大长度',
|
||||||
|
},
|
||||||
|
min_length: {
|
||||||
|
type: INTEGER,
|
||||||
|
comment: '最小长度',
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
type: JSON,
|
||||||
|
comment: '选项(用于下拉框等)',
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: STRING(500),
|
||||||
|
comment: '字段描述',
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: INTEGER,
|
||||||
|
defaultValue: 1,
|
||||||
|
comment: '状态:0-禁用,1-启用',
|
||||||
|
validate: {
|
||||||
|
isIn: [[ 0, 1 ]],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
created_by: {
|
||||||
|
type: STRING(50),
|
||||||
|
comment: '创建人',
|
||||||
|
},
|
||||||
|
updated_by: {
|
||||||
|
type: STRING(50),
|
||||||
|
comment: '更新人',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
comment: '创建时间',
|
||||||
|
get() {
|
||||||
|
const rawValue = this.getDataValue('created_at');
|
||||||
|
return rawValue ? rawValue : null;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
comment: '更新时间',
|
||||||
|
get() {
|
||||||
|
const rawValue = this.getDataValue('updated_at');
|
||||||
|
return rawValue ? rawValue : null;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_print_items',
|
||||||
|
timestamps: false, // 因为表里已经有 created_at 和 updated_at 字段,但我们手动管理
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
paranoid: false,
|
||||||
|
deletedAt: false,
|
||||||
|
comment: '打印项配置表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'business_type', 'platform', 'field_code' ],
|
||||||
|
name: 'uk_business_platform_field',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'business_type' ],
|
||||||
|
name: 'idx_business_type',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'platform' ],
|
||||||
|
name: 'idx_platform',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'status' ],
|
||||||
|
name: 'idx_status',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
// 添加作用域
|
||||||
|
scopes: {
|
||||||
|
// 表格字段
|
||||||
|
tableFields: {
|
||||||
|
where: {
|
||||||
|
is_table: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// 分组字段
|
||||||
|
groupFields: {
|
||||||
|
where: {
|
||||||
|
group_field: {
|
||||||
|
[app.Sequelize.Op.ne]: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// 有效字段
|
||||||
|
active: {
|
||||||
|
where: {
|
||||||
|
status: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// 按业务类型
|
||||||
|
byBusiness(businessType) {
|
||||||
|
return {
|
||||||
|
where: {
|
||||||
|
business_type: businessType,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
// 按平台
|
||||||
|
byPlatform(platform) {
|
||||||
|
return {
|
||||||
|
where: {
|
||||||
|
platform,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 实例方法:获取分组配置
|
||||||
|
PrintItem.prototype.getGroupConfig = function() {
|
||||||
|
if (!this.group_field) return null;
|
||||||
|
return {
|
||||||
|
field: this.group_field,
|
||||||
|
label: this.group_label,
|
||||||
|
sort: this.group_sort,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:获取表格配置
|
||||||
|
PrintItem.prototype.getTableConfig = function() {
|
||||||
|
if (!this.is_table || !this.table_config) return null;
|
||||||
|
return this.table_config;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:获取指定业务类型的分组字段
|
||||||
|
PrintItem.getGroupFields = async function(businessType, platform) {
|
||||||
|
return await this.findAll({
|
||||||
|
where: {
|
||||||
|
business_type: businessType,
|
||||||
|
platform: platform || 'default',
|
||||||
|
group_field: {
|
||||||
|
[app.Sequelize.Op.ne]: null,
|
||||||
|
},
|
||||||
|
status: 1,
|
||||||
|
},
|
||||||
|
order: [
|
||||||
|
[ 'group_sort', 'ASC' ],
|
||||||
|
[ 'sort_order', 'ASC' ],
|
||||||
|
],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:获取指定业务类型的表格配置
|
||||||
|
PrintItem.getTableConfigs = async function(businessType, platform) {
|
||||||
|
return await this.findAll({
|
||||||
|
where: {
|
||||||
|
business_type: businessType,
|
||||||
|
platform: platform || 'default',
|
||||||
|
is_table: true,
|
||||||
|
status: 1,
|
||||||
|
},
|
||||||
|
order: [[ 'sort_order', 'ASC' ]],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 关联方法
|
||||||
|
PrintItem.associate = function() {
|
||||||
|
// 如果需要关联其他表,在这里添加
|
||||||
|
// 例如:PrintItem.belongsTo(app.model.OtherModel, { foreignKey: 'xxx' });
|
||||||
|
};
|
||||||
|
|
||||||
|
return PrintItem;
|
||||||
|
};
|
||||||
86
app/model/print_record.js
Normal file
86
app/model/print_record.js
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, STRING, JSON, ENUM, TEXT, DATE } = app.Sequelize;
|
||||||
|
const PrintRecord = app.model.define("PrintRecord", {
|
||||||
|
id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
autoIncrement: true,
|
||||||
|
primaryKey: true,
|
||||||
|
comment: "主键ID",
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: "仓库ID",
|
||||||
|
},
|
||||||
|
computer_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: "电脑ID",
|
||||||
|
},
|
||||||
|
printer: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: "打印机名称/标识",
|
||||||
|
},
|
||||||
|
type: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: "打印类型",
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
type: JSON,
|
||||||
|
allowNull: true,
|
||||||
|
comment: "打印数据(JSON格式)",
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: ENUM("pending", "sent", "success", "failed"),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: "pending",
|
||||||
|
comment: "打印状态:pending-待发送,sent-已发送,success-打印成功,failed-打印失败",
|
||||||
|
},
|
||||||
|
error_message: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: "错误信息",
|
||||||
|
},
|
||||||
|
sent_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: "发送时间",
|
||||||
|
},
|
||||||
|
print_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: "打印完成时间",
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: app.Sequelize.literal("CURRENT_TIMESTAMP"),
|
||||||
|
comment: "创建时间",
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: app.Sequelize.literal("CURRENT_TIMESTAMP"),
|
||||||
|
comment: "更新时间",
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: "wms_print_record",
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: false,
|
||||||
|
timestamps: false,
|
||||||
|
indexes: [
|
||||||
|
{ name: "idx_warehouse_id", fields: ["warehouse_id"] },
|
||||||
|
{ name: "idx_computer_id", fields: ["computer_id"] },
|
||||||
|
{ name: "idx_status", fields: ["status"] },
|
||||||
|
{ name: "idx_created_at", fields: ["created_at"] },
|
||||||
|
{ name: "idx_sent_time", fields: ["sent_time"] },
|
||||||
|
],
|
||||||
|
comment: "打印记录表",
|
||||||
|
});
|
||||||
|
|
||||||
|
return PrintRecord;
|
||||||
|
};
|
||||||
86
app/model/print_station_express.js
Normal file
86
app/model/print_station_express.js
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { INTEGER, BIGINT, STRING, DATE, TINYINT } = app.Sequelize;
|
||||||
|
const PrintStationExpress = app.model.define('print_station_express', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER.UNSIGNED,
|
||||||
|
autoIncrement: true,
|
||||||
|
primaryKey: true,
|
||||||
|
comment: '自增主键ID',
|
||||||
|
},
|
||||||
|
print_station_id: {
|
||||||
|
type: STRING(32),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '打印台ID,关联wms_print_stations表的print_station_id',
|
||||||
|
},
|
||||||
|
express_id: {
|
||||||
|
type: STRING(32),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '快递ID',
|
||||||
|
},
|
||||||
|
express_name: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '快递名称,冗余字段,便于查询',
|
||||||
|
},
|
||||||
|
printer_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '绑定的打印机名称',
|
||||||
|
},
|
||||||
|
creator_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建人工号ID',
|
||||||
|
},
|
||||||
|
creator_name: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建人名称',
|
||||||
|
},
|
||||||
|
create_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
update_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
deleted: {
|
||||||
|
type: TINYINT,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '软删除标记:0-未删除,1-已删除',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_print_station_express',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: false,
|
||||||
|
timestamps: false,
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
unique: true,
|
||||||
|
name: 'uk_print_station_express',
|
||||||
|
fields: ['print_station_id', 'express_id', 'deleted'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_print_station_id',
|
||||||
|
fields: ['print_station_id'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_express_id',
|
||||||
|
fields: ['express_id'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_creator_id',
|
||||||
|
fields: ['creator_id'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
comment: '打印台快递-打印机绑定关系表',
|
||||||
|
});
|
||||||
|
|
||||||
|
return PrintStationExpress;
|
||||||
|
};
|
||||||
103
app/model/print_stations.js
Normal file
103
app/model/print_stations.js
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
"use strict";
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { INTEGER, BIGINT, STRING, DATE, TINYINT } = app.Sequelize;
|
||||||
|
const PrintStations = app.model.define('print_stations', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER.UNSIGNED,
|
||||||
|
autoIncrement: true,
|
||||||
|
primaryKey: true,
|
||||||
|
comment: '自增主键ID',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库ID',
|
||||||
|
},
|
||||||
|
default_printer_name:{
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '默认打印机名称',
|
||||||
|
},
|
||||||
|
name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '打印台名称',
|
||||||
|
},
|
||||||
|
computer_id: {
|
||||||
|
type: INTEGER,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '打印电脑ID',
|
||||||
|
},
|
||||||
|
custom_barcode: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '自定义编码',
|
||||||
|
},
|
||||||
|
creator_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建人工号ID',
|
||||||
|
},
|
||||||
|
creator_name: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建人名称',
|
||||||
|
},
|
||||||
|
create_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
update_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
deleted: {
|
||||||
|
type: TINYINT,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '软删除标记:0-未删除,1-已删除',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_print_stations',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: false,
|
||||||
|
timestamps: false,
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
unique: true,
|
||||||
|
name: 'uk_print_station_id',
|
||||||
|
fields: ['print_station_id'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse_id',
|
||||||
|
fields: ['warehouse_id'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_computer_id',
|
||||||
|
fields: ['computer_id'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_name',
|
||||||
|
fields: ['name'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_custom_barcode',
|
||||||
|
fields: ['custom_barcode'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_creator_id',
|
||||||
|
fields: ['creator_id'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_create_at',
|
||||||
|
fields: ['create_at'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
comment: '打印台信息表',
|
||||||
|
});
|
||||||
|
|
||||||
|
return PrintStations;
|
||||||
|
};
|
||||||
90
app/model/print_template.js
Normal file
90
app/model/print_template.js
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
// app/model/print_template.js
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, STRING, INTEGER, BOOLEAN, JSON, DATE, DATEONLY } = app.Sequelize;
|
||||||
|
|
||||||
|
const PrintTemplate = app.model.define('print_template', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
template_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '模板名称',
|
||||||
|
},
|
||||||
|
platform: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '所属平台(抖音、拼多多、快手等)',
|
||||||
|
},
|
||||||
|
template_type: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '模板类型:STANDARD-标准模板,CUSTOM-自定义模板',
|
||||||
|
},
|
||||||
|
template_url: {
|
||||||
|
type: STRING(500),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '模板URL地址',
|
||||||
|
},
|
||||||
|
template_content: {
|
||||||
|
type: JSON,
|
||||||
|
comment: '模板内容(JSON格式)',
|
||||||
|
},
|
||||||
|
page_width: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
defaultValue: 76,
|
||||||
|
comment: '页面宽度(mm)',
|
||||||
|
},
|
||||||
|
page_height: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
defaultValue: 130,
|
||||||
|
comment: '页面高度(mm)',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
comment: '关联仓库ID',
|
||||||
|
},
|
||||||
|
is_default: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
defaultValue: false,
|
||||||
|
comment: '是否默认模板:0-否,1-是',
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: STRING(20),
|
||||||
|
defaultValue: 'ACTIVE',
|
||||||
|
comment: '状态:ACTIVE-启用,DISABLED-禁用',
|
||||||
|
},
|
||||||
|
create_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
update_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
business_type: {
|
||||||
|
type: STRING(10),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '类型',
|
||||||
|
},
|
||||||
|
delete_at: {
|
||||||
|
type: DATEONLY,
|
||||||
|
comment: '删除时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
timestamps: false,
|
||||||
|
tableName: 'wms_print_template',
|
||||||
|
comment: '打印模板配置表',
|
||||||
|
});
|
||||||
|
|
||||||
|
return PrintTemplate;
|
||||||
|
};
|
||||||
91
app/model/prohibited_type.js
Normal file
91
app/model/prohibited_type.js
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, BOOLEAN, DATE, BIGINT } = app.Sequelize;
|
||||||
|
|
||||||
|
const ProhibitedType = app.model.define('prohibitedType', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER.UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
type_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '类型名称',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '仓库ID(关联wms_store.id,NULL表示系统预设)',
|
||||||
|
},
|
||||||
|
is_system_preset: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: false,
|
||||||
|
comment: '是否系统预设',
|
||||||
|
},
|
||||||
|
sort_order: {
|
||||||
|
type: INTEGER,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '排序',
|
||||||
|
},
|
||||||
|
created_by: {
|
||||||
|
type: INTEGER.UNSIGNED,
|
||||||
|
comment: '创建人',
|
||||||
|
},
|
||||||
|
updated_by: {
|
||||||
|
type: INTEGER.UNSIGNED,
|
||||||
|
comment: '更新人',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_prohibited_type',
|
||||||
|
underscored: true,
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
paranoid: false,
|
||||||
|
comment: '违禁品类型表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'type_name', 'warehouse_id' ],
|
||||||
|
name: 'uk_type_warehouse',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'warehouse_id' ],
|
||||||
|
name: 'idx_warehouse_id',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'is_system_preset' ],
|
||||||
|
name: 'idx_is_system',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 定义关联关系
|
||||||
|
ProhibitedType.associate = function() {
|
||||||
|
// 关联仓库表
|
||||||
|
app.model.ProhibitedType.belongsTo(app.model.Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'warehouse',
|
||||||
|
});
|
||||||
|
app.model.ProhibitedType.hasMany(app.model.StockWarehouse, {
|
||||||
|
foreignKey: 'prohibited_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'stocks',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return ProhibitedType;
|
||||||
|
};
|
||||||
70
app/model/qimen_app.js
Normal file
70
app/model/qimen_app.js
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { INTEGER, STRING, DATE } = app.Sequelize;
|
||||||
|
|
||||||
|
const QimenApp = app.model.define('qimen_app', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '应用ID',
|
||||||
|
},
|
||||||
|
name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 100 ],
|
||||||
|
},
|
||||||
|
comment: '应用名称',
|
||||||
|
},
|
||||||
|
app_key: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
unique: 'uk_app_key',
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 50 ],
|
||||||
|
},
|
||||||
|
comment: '应用密钥',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_qimen_apps',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: true,
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
comment: '奇门应用配置表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_app_key',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'app_key' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_name',
|
||||||
|
fields: [ 'name' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 定义实例方法
|
||||||
|
QimenApp.prototype.toJSON = function() {
|
||||||
|
const values = { ...this.get() };
|
||||||
|
return values;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
return QimenApp;
|
||||||
|
};
|
||||||
81
app/model/qimen_log.js
Normal file
81
app/model/qimen_log.js
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
// app/model/qimen_log.js
|
||||||
|
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, BIGINT, TEXT, DATE, BOOLEAN } = app.Sequelize;
|
||||||
|
|
||||||
|
const QimenLog = app.model.define('qimen_log', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
},
|
||||||
|
from_key: {
|
||||||
|
type: INTEGER(10),
|
||||||
|
allowNull: true,
|
||||||
|
field: 'from_key',
|
||||||
|
},
|
||||||
|
method: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
},
|
||||||
|
sign: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
},
|
||||||
|
costomer_id: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
field: 'costomer_id',
|
||||||
|
},
|
||||||
|
v: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
},
|
||||||
|
url: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
},
|
||||||
|
body: {
|
||||||
|
type: TEXT('long'),
|
||||||
|
allowNull: true,
|
||||||
|
},
|
||||||
|
result: {
|
||||||
|
type: TEXT('long'),
|
||||||
|
allowNull: true,
|
||||||
|
},
|
||||||
|
use_time: {
|
||||||
|
type: INTEGER(12),
|
||||||
|
allowNull: true,
|
||||||
|
field: 'use_time',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
},
|
||||||
|
deleted_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
},
|
||||||
|
to_key: {
|
||||||
|
type: INTEGER(10),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 23535631,
|
||||||
|
field: 'to_key',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
// 模型配置
|
||||||
|
timestamps: false, // 禁用Sequelize的自动时间戳
|
||||||
|
freezeTableName: true, // 强制表名等于模型名
|
||||||
|
tableName: 'wms_qimen_log', // 数据库中的实际表名
|
||||||
|
underscored: false, // 保持字段名原样(不转换为下划线格式)
|
||||||
|
paranoid: false, // 不使用软删除
|
||||||
|
});
|
||||||
|
|
||||||
|
return QimenLog;
|
||||||
|
};
|
||||||
179
app/model/receiving.js
Normal file
179
app/model/receiving.js
Normal file
@ -0,0 +1,179 @@
|
|||||||
|
// app/model/receiving.js
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, DATE, DECIMAL, TEXT, BOOLEAN, ENUM } = app.Sequelize;
|
||||||
|
|
||||||
|
const Receiving = app.model.define('wms_receiving', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '收货单ID',
|
||||||
|
},
|
||||||
|
receiving_number: {
|
||||||
|
type: STRING(50),
|
||||||
|
unique: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '收货单号,如: RCV202312150001',
|
||||||
|
},
|
||||||
|
creator_id: {
|
||||||
|
type: INTEGER,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建人工号ID',
|
||||||
|
},
|
||||||
|
creator_snapshot: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建人信息快照(JSON格式)',
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: ENUM('receiving', 'completed', 'cancelled'),
|
||||||
|
defaultValue: 'receiving',
|
||||||
|
allowNull: false,
|
||||||
|
comment: '收货状态:receiving-收货中, completed-收货完成, cancelled-作废',
|
||||||
|
},
|
||||||
|
detail_status: {
|
||||||
|
type: ENUM('all_matched', 'partial_matched', 'unmatched'),
|
||||||
|
defaultValue: 'unmatched',
|
||||||
|
allowNull: false,
|
||||||
|
comment: '明细匹配状态:all_matched-全部匹配, partial_matched-部分匹配, unmatched-未匹配',
|
||||||
|
},
|
||||||
|
storage_status: {
|
||||||
|
type: ENUM('none', 'partial', 'all'),
|
||||||
|
defaultValue: 'none',
|
||||||
|
allowNull: false,
|
||||||
|
comment: '入库状态:none-未入库, partial-部分入库, all-全部入库',
|
||||||
|
},
|
||||||
|
delivery_method: {
|
||||||
|
type: ENUM('truck', 'express', 'air_freight', 'sea_freight', 'other'),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '来货方式:truck-货车, express-快递, air_freight-空运, sea_freight-海运, other-其他',
|
||||||
|
},
|
||||||
|
license_plate: {
|
||||||
|
type: STRING(20),
|
||||||
|
comment: '车牌号(货车运输时需要)',
|
||||||
|
},
|
||||||
|
tracking_number: {
|
||||||
|
type: STRING(100),
|
||||||
|
comment: '快递单号/物流单号',
|
||||||
|
},
|
||||||
|
loading_method: {
|
||||||
|
type: ENUM('with_pallet', 'without_pallet'),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '装卸方式:with_pallet-带托盘, without_pallet-不带托盘',
|
||||||
|
},
|
||||||
|
video_device_id: {
|
||||||
|
type: STRING(50),
|
||||||
|
comment: '录像设备ID(可选)',
|
||||||
|
},
|
||||||
|
total_items: {
|
||||||
|
type: INTEGER,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '总商品种类数',
|
||||||
|
},
|
||||||
|
total_quantity: {
|
||||||
|
type: INTEGER,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '商品总数量',
|
||||||
|
},
|
||||||
|
total_boxes: {
|
||||||
|
type: INTEGER,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '总箱数',
|
||||||
|
},
|
||||||
|
total_pallets: {
|
||||||
|
type: INTEGER,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '总托盘数',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: INTEGER,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '收货仓库ID',
|
||||||
|
},
|
||||||
|
remark: {
|
||||||
|
type: TEXT,
|
||||||
|
comment: '备注信息',
|
||||||
|
},
|
||||||
|
store_name: {
|
||||||
|
type: STRING(50),
|
||||||
|
},
|
||||||
|
store_id: {
|
||||||
|
type: INTEGER,
|
||||||
|
},
|
||||||
|
receiving_start_time: {
|
||||||
|
type: DATE,
|
||||||
|
comment: '收货开始时间',
|
||||||
|
},
|
||||||
|
receiving_end_time: {
|
||||||
|
type: DATE,
|
||||||
|
comment: '收货结束时间',
|
||||||
|
},
|
||||||
|
is_deleted: {
|
||||||
|
type: BOOLEAN,
|
||||||
|
defaultValue: false,
|
||||||
|
comment: '是否删除',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_receiving',
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
paranoid: false,
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'receiving_number' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'creator_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'status' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'delivery_method' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'created_at' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联定义
|
||||||
|
Receiving.associate = function() {
|
||||||
|
const { ReceivingDetail, Store, AccountStoreEmployee, Storage, StoreWarehouse } = app.model;
|
||||||
|
// 关联收货明细
|
||||||
|
Receiving.hasMany(ReceivingDetail, {
|
||||||
|
foreignKey: 'receiving_id',
|
||||||
|
as: 'details',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联仓库
|
||||||
|
Receiving.belongsTo(Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
as: 'warehouse',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联创建人(用户表)
|
||||||
|
Receiving.belongsTo(AccountStoreEmployee, {
|
||||||
|
foreignKey: 'creator_id',
|
||||||
|
as: 'creator',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联入库记录
|
||||||
|
Receiving.hasMany(Storage, {
|
||||||
|
foreignKey: 'receiving_id',
|
||||||
|
as: 'storage_records',
|
||||||
|
});
|
||||||
|
Receiving.belongsTo(StoreWarehouse, {
|
||||||
|
foreignKey: 'store_id', // 当前表的外键字段
|
||||||
|
targetKey: 'store_id', // 关联表的主键字段
|
||||||
|
as: 'store',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return Receiving;
|
||||||
|
};
|
||||||
173
app/model/receiving_detail.js
Normal file
173
app/model/receiving_detail.js
Normal file
@ -0,0 +1,173 @@
|
|||||||
|
// app/model/receiving_detail.js
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, DATE, DECIMAL, TEXT, ENUM, BOOLEAN, BIGINT } = app.Sequelize;
|
||||||
|
|
||||||
|
const ReceivingDetail = app.model.define('wms_receiving_detail', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '明细ID',
|
||||||
|
},
|
||||||
|
receiving_id: {
|
||||||
|
type: INTEGER,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '收货单ID',
|
||||||
|
},
|
||||||
|
product_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '商品名称',
|
||||||
|
},
|
||||||
|
barcode: {
|
||||||
|
type: STRING(100),
|
||||||
|
comment: '商品条码',
|
||||||
|
},
|
||||||
|
product_snapshot: {
|
||||||
|
type: TEXT,
|
||||||
|
comment: '商品信息快照(JSON格式)',
|
||||||
|
},
|
||||||
|
system_product_id: {
|
||||||
|
type: INTEGER,
|
||||||
|
comment: '关联的系统商品ID(可以为空)',
|
||||||
|
},
|
||||||
|
actual_quantity: {
|
||||||
|
type: INTEGER,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '实际收货数量',
|
||||||
|
},
|
||||||
|
box_quantity: {
|
||||||
|
type: INTEGER,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '箱数',
|
||||||
|
},
|
||||||
|
boxes_per_pallet: {
|
||||||
|
type: INTEGER,
|
||||||
|
defaultValue: 1,
|
||||||
|
comment: '每托盘箱数(箱规)',
|
||||||
|
},
|
||||||
|
pallet_quantity: {
|
||||||
|
type: INTEGER,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '托盘数',
|
||||||
|
},
|
||||||
|
receiving_time: {
|
||||||
|
type: DATE,
|
||||||
|
comment: '收货时间(该商品的收货时间)',
|
||||||
|
},
|
||||||
|
receiving_status: {
|
||||||
|
type: ENUM('pending', 'receiving', 'completed', 'cancelled'),
|
||||||
|
defaultValue: 'pending',
|
||||||
|
comment: '收货状态',
|
||||||
|
},
|
||||||
|
storage_status: {
|
||||||
|
type: ENUM('none', 'partial', 'all'),
|
||||||
|
defaultValue: 'none',
|
||||||
|
comment: '入库状态:none-未入库, partial-部分入库, all-全部入库',
|
||||||
|
},
|
||||||
|
stored_quantity: {
|
||||||
|
type: INTEGER,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '已入库数量',
|
||||||
|
},
|
||||||
|
batch_number: {
|
||||||
|
type: STRING(100),
|
||||||
|
comment: '批次号',
|
||||||
|
},
|
||||||
|
production_date: {
|
||||||
|
type: DATE,
|
||||||
|
comment: '生产日期',
|
||||||
|
},
|
||||||
|
expiry_date: {
|
||||||
|
type: DATE,
|
||||||
|
comment: '保质期/到期日期',
|
||||||
|
},
|
||||||
|
remark: {
|
||||||
|
type: TEXT,
|
||||||
|
comment: '备注',
|
||||||
|
},
|
||||||
|
space_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
defaultValue: 1,
|
||||||
|
comment: '存放库位',
|
||||||
|
},
|
||||||
|
creator_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
},
|
||||||
|
box_width: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
},
|
||||||
|
box_length: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
},
|
||||||
|
box_height: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
},
|
||||||
|
weight: {
|
||||||
|
type: INTEGER,
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_receiving_detail',
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
|
||||||
|
paranoid: false,
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
fields: [ 'receiving_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'barcode' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'system_product_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'receiving_status' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'storage_status' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'matched_status' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'batch_number' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
fields: [ 'receiving_id', 'barcode' ], // 添加这个复合索引
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
ReceivingDetail.associate = function() {
|
||||||
|
const { Receiving, StockWarehouse, Storage, LocationSpace } = app.model;
|
||||||
|
// 关联主表
|
||||||
|
ReceivingDetail.belongsTo(Receiving, {
|
||||||
|
foreignKey: 'receiving_id',
|
||||||
|
as: 'receiving',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联系统商品
|
||||||
|
ReceivingDetail.belongsTo(StockWarehouse, {
|
||||||
|
foreignKey: 'system_product_id',
|
||||||
|
as: 'system_product',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联入库记录
|
||||||
|
ReceivingDetail.hasMany(Storage, {
|
||||||
|
foreignKey: 'receiving_detail_id',
|
||||||
|
as: 'storage_details',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联系统商品
|
||||||
|
ReceivingDetail.belongsTo(LocationSpace, {
|
||||||
|
foreignKey: 'space_id',
|
||||||
|
as: 'receiving_space',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return ReceivingDetail;
|
||||||
|
};
|
||||||
269
app/model/role.js
Normal file
269
app/model/role.js
Normal file
@ -0,0 +1,269 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, STRING, DATE, TINYINT, TEXT } = app.Sequelize;
|
||||||
|
|
||||||
|
const Role = app.model.define('role', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '角色ID',
|
||||||
|
},
|
||||||
|
role_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
unique: true,
|
||||||
|
validate: {
|
||||||
|
notEmpty: {
|
||||||
|
msg: '角色代码不能为空',
|
||||||
|
},
|
||||||
|
len: {
|
||||||
|
args: [ 1, 50 ],
|
||||||
|
msg: '角色代码长度应在1-50个字符之间',
|
||||||
|
},
|
||||||
|
is: {
|
||||||
|
args: /^[a-zA-Z0-9_]+$/,
|
||||||
|
msg: '角色代码只能包含字母、数字和下划线',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '角色代码',
|
||||||
|
},
|
||||||
|
role_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: {
|
||||||
|
msg: '角色名称不能为空',
|
||||||
|
},
|
||||||
|
len: {
|
||||||
|
args: [ 1, 100 ],
|
||||||
|
msg: '角色名称长度应在1-100个字符之间',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '角色名称',
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: STRING(500),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '角色描述',
|
||||||
|
},
|
||||||
|
role_type: {
|
||||||
|
type: TINYINT(4),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
validate: {
|
||||||
|
isIn: {
|
||||||
|
args: [[ 1, 2 ]],
|
||||||
|
msg: '角色类型只能是1或2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '角色类型:1-系统角色,2-自定义角色',
|
||||||
|
},
|
||||||
|
scope: {
|
||||||
|
type: TINYINT(4),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
validate: {
|
||||||
|
isIn: {
|
||||||
|
args: [[ 1, 2 ]],
|
||||||
|
msg: '作用范围只能是1或2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '作用范围:1-全局,2-指定仓库',
|
||||||
|
},
|
||||||
|
is_system: {
|
||||||
|
type: TINYINT(4),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
validate: {
|
||||||
|
isIn: {
|
||||||
|
args: [[ 0, 1 ]],
|
||||||
|
msg: '是否系统预设只能是0或1',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '是否系统预设:0-否,1-是',
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: TINYINT(4),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
validate: {
|
||||||
|
isIn: {
|
||||||
|
args: [[ 0, 1 ]],
|
||||||
|
msg: '状态只能是0或1',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '状态:0-禁用,1-启用',
|
||||||
|
},
|
||||||
|
created_by: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建人',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
store_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '所属仓库ID',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_role',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: true,
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
comment: '平台角色表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_role_code',
|
||||||
|
fields: [ 'role_code' ],
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_role_type',
|
||||||
|
fields: [ 'role_type' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_scope',
|
||||||
|
fields: [ 'scope' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_status',
|
||||||
|
fields: [ 'status' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系
|
||||||
|
Role.associate = function(models) {
|
||||||
|
const { Account, Store, Permission, AccountStoreRole, RolePermission, EmployeeRole } = app.model;
|
||||||
|
// 创建人
|
||||||
|
Role.belongsTo(Account, {
|
||||||
|
foreignKey: 'created_by',
|
||||||
|
as: 'creator',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 所属仓库
|
||||||
|
Role.belongsTo(Store, {
|
||||||
|
foreignKey: 'store_id',
|
||||||
|
as: 'store',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 权限关联
|
||||||
|
Role.belongsToMany(Permission, {
|
||||||
|
through: RolePermission,
|
||||||
|
foreignKey: 'role_id',
|
||||||
|
otherKey: 'permission_id',
|
||||||
|
as: 'permissions',
|
||||||
|
});
|
||||||
|
Role.hasMany(EmployeeRole, {
|
||||||
|
foreignKey: 'role_id',
|
||||||
|
sourceKey: 'id',
|
||||||
|
as: 'employeeRole',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:检查角色是否启用
|
||||||
|
Role.prototype.isEnabled = function() {
|
||||||
|
return this.status === 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:检查是否是系统预设角色
|
||||||
|
Role.prototype.isSystemRole = function() {
|
||||||
|
return this.is_system === 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:获取角色类型名称
|
||||||
|
Role.prototype.getRoleTypeName = function() {
|
||||||
|
return this.role_type === 1 ? '系统角色' : '自定义角色';
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:获取作用范围名称
|
||||||
|
Role.prototype.getScopeName = function() {
|
||||||
|
return this.scope === 1 ? '全局' : '指定仓库';
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:为角色分配权限
|
||||||
|
Role.prototype.assignPermissions = async function(permissionIds) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
// 先清除现有权限
|
||||||
|
await ctx.model.RolePermission.destroy({
|
||||||
|
where: { role_id: this.id },
|
||||||
|
});
|
||||||
|
|
||||||
|
// 批量添加新权限
|
||||||
|
if (permissionIds && permissionIds.length > 0) {
|
||||||
|
const rolePermissions = permissionIds.map(permissionId => ({
|
||||||
|
role_id: this.id,
|
||||||
|
permission_id: permissionId,
|
||||||
|
}));
|
||||||
|
|
||||||
|
await ctx.model.RolePermission.bulkCreate(rolePermissions);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:获取角色的所有权限(树形结构)
|
||||||
|
Role.prototype.getPermissionTree = async function(permissionType = null) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const rolePermissions = await ctx.model.RolePermission.findAll({
|
||||||
|
where: { role_id: this.id },
|
||||||
|
include: [{
|
||||||
|
model: ctx.model.Permission,
|
||||||
|
as: 'permission',
|
||||||
|
where: { status: 1 },
|
||||||
|
required: true,
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 提取权限ID
|
||||||
|
const permissionIds = rolePermissions.map(rp => rp.permission.id);
|
||||||
|
|
||||||
|
// 获取权限详情
|
||||||
|
const where = {
|
||||||
|
id: permissionIds,
|
||||||
|
status: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (permissionType) {
|
||||||
|
where.type = permissionType;
|
||||||
|
}
|
||||||
|
|
||||||
|
const permissions = await ctx.model.Permission.findAll({
|
||||||
|
where,
|
||||||
|
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 构建树形结构
|
||||||
|
return ctx.model.Permission.buildPermissionTree(permissions);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:获取角色的权限ID列表
|
||||||
|
Role.prototype.getPermissionIds = async function() {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const rolePermissions = await ctx.model.RolePermission.findAll({
|
||||||
|
where: { role_id: this.id },
|
||||||
|
attributes: [ 'permission_id' ],
|
||||||
|
});
|
||||||
|
|
||||||
|
return rolePermissions.map(rp => rp.permission_id);
|
||||||
|
};
|
||||||
|
|
||||||
|
return Role;
|
||||||
|
};
|
||||||
145
app/model/role_permission.js
Normal file
145
app/model/role_permission.js
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, DATE } = app.Sequelize;
|
||||||
|
|
||||||
|
const RolePermission = app.model.define('role_permission', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '关联ID',
|
||||||
|
},
|
||||||
|
role_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '角色ID',
|
||||||
|
},
|
||||||
|
permission_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '权限ID',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_role_permission',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: true,
|
||||||
|
timestamps: true,
|
||||||
|
paranoid: false, // 明确禁用软删除
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: false,
|
||||||
|
comment: '角色权限关联表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_role_permission',
|
||||||
|
fields: [ 'role_id', 'permission_id' ],
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_role_id',
|
||||||
|
fields: [ 'role_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_permission_id',
|
||||||
|
fields: [ 'permission_id' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系
|
||||||
|
RolePermission.associate = function(models) {
|
||||||
|
const { Role, Permission } = app.model;
|
||||||
|
// 关联角色
|
||||||
|
RolePermission.belongsTo(Role, {
|
||||||
|
foreignKey: 'role_id',
|
||||||
|
as: 'role',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联权限
|
||||||
|
RolePermission.belongsTo(Permission, {
|
||||||
|
foreignKey: 'permission_id',
|
||||||
|
as: 'permission',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:检查关联是否有效
|
||||||
|
RolePermission.prototype.isValid = function() {
|
||||||
|
// 这里可以添加更多的有效性检查
|
||||||
|
return this.role_id && this.permission_id;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:批量创建角色权限关联
|
||||||
|
RolePermission.bulkAssign = async function(roleId, permissionIds) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
if (!permissionIds || permissionIds.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const rolePermissions = permissionIds.map(permissionId => ({
|
||||||
|
role_id: roleId,
|
||||||
|
permission_id: permissionId,
|
||||||
|
}));
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await ctx.model.RolePermission.bulkCreate(rolePermissions, {
|
||||||
|
ignoreDuplicates: true, // 忽略重复项
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// 处理批量创建中的错误
|
||||||
|
console.error('批量创建角色权限关联失败:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:删除角色的所有权限
|
||||||
|
RolePermission.clearRolePermissions = async function(roleId) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
return await ctx.model.RolePermission.destroy({
|
||||||
|
where: { role_id: roleId },
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:获取角色的权限列表
|
||||||
|
RolePermission.getRolePermissions = async function(roleId, includePermissionDetails = false) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
where: { role_id: roleId },
|
||||||
|
};
|
||||||
|
|
||||||
|
if (includePermissionDetails) {
|
||||||
|
options.include = [{
|
||||||
|
model: ctx.model.Permission,
|
||||||
|
as: 'permission',
|
||||||
|
where: { status: 1 },
|
||||||
|
required: false,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
|
||||||
|
return await ctx.model.RolePermission.findAll(options);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:检查角色是否拥有某个权限
|
||||||
|
RolePermission.hasPermission = async function(roleId, permissionId) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const rolePermission = await ctx.model.RolePermission.findOne({
|
||||||
|
where: {
|
||||||
|
role_id: roleId,
|
||||||
|
permission_id: permissionId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return !!rolePermission;
|
||||||
|
};
|
||||||
|
|
||||||
|
return RolePermission;
|
||||||
|
};
|
||||||
86
app/model/stock_barcode.js
Normal file
86
app/model/stock_barcode.js
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, BIGINT, DATE, TEXT } = app.Sequelize;
|
||||||
|
|
||||||
|
const StockBarcode = app.model.define('stock_barcodes', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
stock_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '主表ID',
|
||||||
|
references: {
|
||||||
|
model: 'wms_stock_warehouse',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
onDelete: 'CASCADE',
|
||||||
|
onUpdate: 'NO ACTION',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库id',
|
||||||
|
},
|
||||||
|
barcode: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '条码',
|
||||||
|
charset: 'utf8mb4',
|
||||||
|
collate: 'utf8mb4_unicode_ci',
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '条码描述',
|
||||||
|
charset: 'utf8mb4',
|
||||||
|
collate: 'utf8mb4_unicode_ci',
|
||||||
|
},
|
||||||
|
create_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_stock_barcodes',
|
||||||
|
timestamps: false, // 不使用Sequelize的自动时间戳
|
||||||
|
charset: 'utf8mb4',
|
||||||
|
collate: 'utf8mb4_unicode_ci',
|
||||||
|
paranoid: false,
|
||||||
|
// 明确指定不使用 deletedAt 字段
|
||||||
|
deletedAt: false,
|
||||||
|
comment: 'WMS商品条码表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'idx_stock_id',
|
||||||
|
fields: [ 'stock_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'uk_barcode',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'barcode' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 定义关联关系
|
||||||
|
StockBarcode.associate = function() {
|
||||||
|
const { StockWarehouse } = app.model;
|
||||||
|
console.log('StockWarehouse', StockWarehouse, StockBarcode);
|
||||||
|
StockBarcode.belongsTo(
|
||||||
|
app.model.StockWarehouse,
|
||||||
|
{
|
||||||
|
foreignKey: 'stock_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'stock',
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return StockBarcode;
|
||||||
|
};
|
||||||
426
app/model/stock_store.js
Normal file
426
app/model/stock_store.js
Normal file
@ -0,0 +1,426 @@
|
|||||||
|
// app/model/stock_store.js
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, STRING, DECIMAL, INTEGER, DATE, ENUM, CHAR } = app.Sequelize;
|
||||||
|
|
||||||
|
const StockStore = app.model.define('stock_store', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '库存商品ID',
|
||||||
|
},
|
||||||
|
warehouse_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
len: [ 1, 50 ],
|
||||||
|
},
|
||||||
|
comment: '仓库编码',
|
||||||
|
},
|
||||||
|
owner_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
len: [ 1, 50 ],
|
||||||
|
},
|
||||||
|
comment: '货主编码',
|
||||||
|
},
|
||||||
|
app_key: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 50 ],
|
||||||
|
},
|
||||||
|
comment: '应用',
|
||||||
|
},
|
||||||
|
is_area_sale: {
|
||||||
|
type: CHAR(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'N',
|
||||||
|
validate: {
|
||||||
|
isIn: [[ 'Y', 'N' ]],
|
||||||
|
},
|
||||||
|
comment: '是否区域销售',
|
||||||
|
},
|
||||||
|
brand_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 50 ],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
item_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
len: [ 1, 50 ],
|
||||||
|
},
|
||||||
|
comment: '商品编码',
|
||||||
|
},
|
||||||
|
goods_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货物编码',
|
||||||
|
},
|
||||||
|
item_name: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
len: [ 1, 255 ],
|
||||||
|
},
|
||||||
|
comment: '商品名称',
|
||||||
|
},
|
||||||
|
sku_property: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 100 ],
|
||||||
|
},
|
||||||
|
comment: 'SKU规格',
|
||||||
|
},
|
||||||
|
stock_unit: {
|
||||||
|
type: STRING(20),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 20 ],
|
||||||
|
},
|
||||||
|
comment: '库存单位',
|
||||||
|
},
|
||||||
|
length: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0.00,
|
||||||
|
validate: {
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
comment: '长度',
|
||||||
|
},
|
||||||
|
width: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0.00,
|
||||||
|
validate: {
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
comment: '宽度',
|
||||||
|
},
|
||||||
|
height: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0.00,
|
||||||
|
validate: {
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
comment: '高度',
|
||||||
|
},
|
||||||
|
volume: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0.00,
|
||||||
|
validate: {
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
comment: '体积',
|
||||||
|
},
|
||||||
|
gross_weight: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0.00,
|
||||||
|
validate: {
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
comment: '毛重',
|
||||||
|
},
|
||||||
|
net_weight: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0.00,
|
||||||
|
validate: {
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
comment: '净重',
|
||||||
|
},
|
||||||
|
category_id: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '分类ID',
|
||||||
|
},
|
||||||
|
category_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 100 ],
|
||||||
|
},
|
||||||
|
comment: '分类名称',
|
||||||
|
},
|
||||||
|
item_type: {
|
||||||
|
type: STRING(10),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
len: [ 1, 10 ],
|
||||||
|
},
|
||||||
|
comment: '商品类型',
|
||||||
|
},
|
||||||
|
tag_price: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0.00,
|
||||||
|
validate: {
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
comment: '标价',
|
||||||
|
},
|
||||||
|
retail_price: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 0.00,
|
||||||
|
validate: {
|
||||||
|
min: 0,
|
||||||
|
},
|
||||||
|
comment: '零售价',
|
||||||
|
},
|
||||||
|
is_sn_mgmt: {
|
||||||
|
type: CHAR(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'N',
|
||||||
|
validate: {
|
||||||
|
isIn: [[ 'Y', 'N' ]],
|
||||||
|
},
|
||||||
|
comment: '是否序列号管理',
|
||||||
|
},
|
||||||
|
is_shelf_life_mgmt: {
|
||||||
|
type: CHAR(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'N',
|
||||||
|
validate: {
|
||||||
|
isIn: [[ 'Y', 'N' ]],
|
||||||
|
},
|
||||||
|
comment: '是否保质期管理',
|
||||||
|
},
|
||||||
|
is_batch_mgmt: {
|
||||||
|
type: CHAR(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'N',
|
||||||
|
validate: {
|
||||||
|
isIn: [[ 'Y', 'N' ]],
|
||||||
|
},
|
||||||
|
comment: '是否批次管理',
|
||||||
|
},
|
||||||
|
create_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
update_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
is_valid: {
|
||||||
|
type: CHAR(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'Y',
|
||||||
|
validate: {
|
||||||
|
isIn: [[ 'Y', 'N' ]],
|
||||||
|
},
|
||||||
|
comment: '是否有效',
|
||||||
|
},
|
||||||
|
barcode: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 255 ],
|
||||||
|
},
|
||||||
|
comment: '条形码',
|
||||||
|
},
|
||||||
|
stock_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '库存ID',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库ID',
|
||||||
|
references: {
|
||||||
|
model: 'store',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
store_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '商家ID',
|
||||||
|
references: {
|
||||||
|
model: 'store',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
create_from: {
|
||||||
|
type: ENUM('qimen', 'api'),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '创建来源',
|
||||||
|
},
|
||||||
|
delete_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '删除时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_stock_store',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: true,
|
||||||
|
timestamps: false, // 使用自定义时间字段
|
||||||
|
comment: '库存商品信息表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_warehouse_owner_item',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'warehouse_code', 'owner_code', 'item_code', 'app_key', 'warehouse_id', 'store_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_owner_code',
|
||||||
|
fields: [ 'owner_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_goods_code',
|
||||||
|
fields: [ 'goods_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_category_id',
|
||||||
|
fields: [ 'category_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_create_time',
|
||||||
|
fields: [ 'create_time' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_is_valid',
|
||||||
|
fields: [ 'is_valid' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'uk_item_code',
|
||||||
|
fields: [ 'item_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse_id',
|
||||||
|
fields: [ 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_store_id',
|
||||||
|
fields: [ 'store_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_barcode',
|
||||||
|
fields: [ 'barcode' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse_valid',
|
||||||
|
fields: [ 'warehouse_id', 'is_valid' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_store_valid',
|
||||||
|
fields: [ 'store_id', 'is_valid' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_item_valid',
|
||||||
|
fields: [ 'item_code', 'is_valid' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 定义关联关系
|
||||||
|
StockStore.associate = function() {
|
||||||
|
const { Store, StockWarehouse } = app.model;
|
||||||
|
|
||||||
|
// 关联仓库
|
||||||
|
StockStore.belongsTo(Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'warehouse',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联商家
|
||||||
|
StockStore.belongsTo(Store, {
|
||||||
|
foreignKey: 'store_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'store',
|
||||||
|
});
|
||||||
|
|
||||||
|
StockStore.belongsTo(StockWarehouse, {
|
||||||
|
foreignKey: 'stock_id', // 当前表的外键字段
|
||||||
|
targetKey: 'id', // 关联表的主键字段
|
||||||
|
as: 'warehouse_stock',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法 - 根据商品编码查找
|
||||||
|
StockStore.findByItemCode = async function(itemCode, options = {}) {
|
||||||
|
const where = { item_code: itemCode, is_valid: 'Y' };
|
||||||
|
|
||||||
|
if (options.warehouse_id) {
|
||||||
|
where.warehouse_id = options.warehouse_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.store_id) {
|
||||||
|
where.store_id = options.store_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.findOne({
|
||||||
|
where,
|
||||||
|
include: options.include || [],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法 - 获取商家的商品列表
|
||||||
|
StockStore.findByStore = async function(storeId, options = {}) {
|
||||||
|
const where = { store_id: storeId, is_valid: 'Y' };
|
||||||
|
|
||||||
|
if (options.warehouse_id) {
|
||||||
|
where.warehouse_id = options.warehouse_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.owner_code) {
|
||||||
|
where.owner_code = options.owner_code;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.findAll({
|
||||||
|
where,
|
||||||
|
include: options.include || [],
|
||||||
|
order: options.order || [[ 'create_time', 'DESC' ]],
|
||||||
|
limit: options.limit,
|
||||||
|
offset: options.offset,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 检查商品是否有效
|
||||||
|
StockStore.prototype.isValid = function() {
|
||||||
|
return this.is_valid === 'Y' && !this.delete_at;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 软删除
|
||||||
|
StockStore.prototype.softDelete = function() {
|
||||||
|
return this.update({
|
||||||
|
is_valid: 'N',
|
||||||
|
delete_at: new Date(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 计算体积
|
||||||
|
StockStore.prototype.calculateVolume = function() {
|
||||||
|
if (this.length && this.width && this.height) {
|
||||||
|
return (this.length * this.width * this.height).toFixed(2);
|
||||||
|
}
|
||||||
|
return this.volume;
|
||||||
|
};
|
||||||
|
|
||||||
|
return StockStore;
|
||||||
|
};
|
||||||
49
app/model/stock_unit.js
Normal file
49
app/model/stock_unit.js
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
// app/model/stock_unit.js
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, DATE } = app.Sequelize;
|
||||||
|
|
||||||
|
const StockUnit = app.model.define('wms_stock_unit', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: INTEGER,
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: null,
|
||||||
|
comment: '仓库ID,NULL表示系统默认',
|
||||||
|
},
|
||||||
|
name: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '单位名称',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_stock_unit',
|
||||||
|
timestamps: false,
|
||||||
|
comment: '库存单位表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse_id',
|
||||||
|
fields: [ 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'uk_name_warehouse',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'name', 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
return StockUnit;
|
||||||
|
};
|
||||||
255
app/model/stock_warehouse.js
Normal file
255
app/model/stock_warehouse.js
Normal file
@ -0,0 +1,255 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, BIGINT, DECIMAL, TEXT, DATE, CHAR, INTEGER, ENUM, TINYINT } = app.Sequelize;
|
||||||
|
|
||||||
|
const StockWarehouse = app.model.define('stock_warehouse', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
item_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '商品编码',
|
||||||
|
},
|
||||||
|
goods_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货物编码',
|
||||||
|
},
|
||||||
|
store_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '货主ID',
|
||||||
|
},
|
||||||
|
item_name: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '商品名称',
|
||||||
|
},
|
||||||
|
sku_property: {
|
||||||
|
type: STRING(100),
|
||||||
|
comment: 'SKU规格',
|
||||||
|
},
|
||||||
|
stock_unit: {
|
||||||
|
type: STRING(20),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '库存单位',
|
||||||
|
},
|
||||||
|
packing_requirements: {
|
||||||
|
type: TEXT,
|
||||||
|
comment: '打包要求',
|
||||||
|
},
|
||||||
|
|
||||||
|
brand_name: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 50 ],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
length: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
defaultValue: 0.00,
|
||||||
|
comment: '长度',
|
||||||
|
},
|
||||||
|
width: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
defaultValue: 0.00,
|
||||||
|
comment: '宽度',
|
||||||
|
},
|
||||||
|
height: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
defaultValue: 0.00,
|
||||||
|
comment: '高度',
|
||||||
|
},
|
||||||
|
volume: {
|
||||||
|
type: INTEGER(11).UNSIGNED,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '体积',
|
||||||
|
},
|
||||||
|
gross_weight: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
defaultValue: 0.00,
|
||||||
|
comment: '毛重',
|
||||||
|
},
|
||||||
|
net_weight: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
defaultValue: 0.00,
|
||||||
|
comment: '净重',
|
||||||
|
},
|
||||||
|
item_type: {
|
||||||
|
type: STRING(10),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '商品类型',
|
||||||
|
},
|
||||||
|
tag_price: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
defaultValue: 0.00,
|
||||||
|
comment: '标价',
|
||||||
|
},
|
||||||
|
retail_price: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
defaultValue: 0.00,
|
||||||
|
comment: '零售价',
|
||||||
|
},
|
||||||
|
is_sn_mgmt: {
|
||||||
|
type: CHAR(1),
|
||||||
|
defaultValue: 'N',
|
||||||
|
comment: '是否序列号管理',
|
||||||
|
},
|
||||||
|
is_shelf_life_mgmt: {
|
||||||
|
type: CHAR(1),
|
||||||
|
defaultValue: 'N',
|
||||||
|
comment: '是否保质期管理',
|
||||||
|
},
|
||||||
|
is_batch_mgmt: {
|
||||||
|
type: CHAR(1),
|
||||||
|
defaultValue: 'N',
|
||||||
|
comment: '是否批次管理',
|
||||||
|
},
|
||||||
|
create_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
level: {
|
||||||
|
type: ENUM('A', 'B', 'C'),
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: 'N',
|
||||||
|
comment: '是否需要发票',
|
||||||
|
},
|
||||||
|
update_at: {
|
||||||
|
type: DATE,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
is_valid: {
|
||||||
|
type: CHAR(1),
|
||||||
|
defaultValue: 'Y',
|
||||||
|
comment: '是否有效',
|
||||||
|
},
|
||||||
|
is_images: {
|
||||||
|
type: CHAR(1),
|
||||||
|
defaultValue: 'Y',
|
||||||
|
comment: '是否有照片',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
comment: '仓库ID',
|
||||||
|
},
|
||||||
|
delete_at: {
|
||||||
|
type: DATE,
|
||||||
|
comment: '删除时间',
|
||||||
|
},
|
||||||
|
quantity: {
|
||||||
|
type: INTEGER(11).UNSIGNED,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '库存数量',
|
||||||
|
},
|
||||||
|
locked_quantity: {
|
||||||
|
type: INTEGER(11).UNSIGNED,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '锁定数量',
|
||||||
|
},
|
||||||
|
prohibited_id: {
|
||||||
|
type: INTEGER.UNSIGNED,
|
||||||
|
comment: '违禁品类型id',
|
||||||
|
},
|
||||||
|
enable_box_spec: {
|
||||||
|
type: TINYINT(1),
|
||||||
|
defaultValue: 0,
|
||||||
|
},
|
||||||
|
quantity_per_box: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
defaultValue: 0,
|
||||||
|
},
|
||||||
|
box_gross_weight: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
defaultValue: 0,
|
||||||
|
},
|
||||||
|
box_net_weight: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
defaultValue: 0,
|
||||||
|
},
|
||||||
|
box_height: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
defaultValue: 0.00,
|
||||||
|
},
|
||||||
|
box_length: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
defaultValue: 0.00,
|
||||||
|
},
|
||||||
|
box_width: {
|
||||||
|
type: DECIMAL(10, 2),
|
||||||
|
defaultValue: 0.00,
|
||||||
|
},
|
||||||
|
box_volume: {
|
||||||
|
type: INTEGER(11).UNSIGNED,
|
||||||
|
defaultValue: 0,
|
||||||
|
},
|
||||||
|
deleted_at: {
|
||||||
|
type: DATE,
|
||||||
|
defaultValue: null,
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_stock_warehouse',
|
||||||
|
freezeTableName: true,
|
||||||
|
timestamps: false,
|
||||||
|
paranoid: true,
|
||||||
|
comment: '仓库商品库存主表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_item_code',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'item_code', 'warehouse_id', 'store_id', 'deleted_at' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_create_time',
|
||||||
|
fields: [ 'create_at' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_is_valid',
|
||||||
|
fields: [ 'is_valid' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'warehouse_id',
|
||||||
|
fields: [ 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
StockWarehouse.associate = function(models) {
|
||||||
|
const { StoreWarehouse, StockBarcode, ProhibitedType, StockImage, StockStore, Storage } = app.model;
|
||||||
|
// 授权关系属于商家 - 修正:需要确认StoreWarehouse模型是否有store_id字段
|
||||||
|
StockWarehouse.belongsTo(StoreWarehouse, {
|
||||||
|
foreignKey: 'store_id', // 当前表的外键字段
|
||||||
|
targetKey: 'store_id', // 关联表的主键字段
|
||||||
|
as: 'store_stock',
|
||||||
|
});
|
||||||
|
StockWarehouse.hasMany(StockBarcode, {
|
||||||
|
foreignKey: 'stock_id', // StockBarcodes表中的外键字段
|
||||||
|
as: 'barcodes',
|
||||||
|
});
|
||||||
|
StockWarehouse.belongsTo(ProhibitedType, {
|
||||||
|
foreignKey: 'prohibited_id', // 当前表的外键字段
|
||||||
|
targetKey: 'id', // 关联表的主键字段
|
||||||
|
as: 'prohibited',
|
||||||
|
});
|
||||||
|
StockWarehouse.hasMany(StockStore, {
|
||||||
|
foreignKey: 'stock_id', // 当前表的外键字段
|
||||||
|
as: 'store_out_stock',
|
||||||
|
});
|
||||||
|
|
||||||
|
StockWarehouse.hasMany(Storage, {
|
||||||
|
foreignKey: 'stock_id', // 当前表的外键字段
|
||||||
|
as: 'storage',
|
||||||
|
});
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
return StockWarehouse;
|
||||||
|
};
|
||||||
468
app/model/storage.js
Normal file
468
app/model/storage.js
Normal file
@ -0,0 +1,468 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, BIGINT, ENUM, DATE, TINYINT } = app.Sequelize;
|
||||||
|
|
||||||
|
const Storage = app.model.define('wms_storage', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '库存ID',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库ID',
|
||||||
|
references: {
|
||||||
|
model: 'wms_store',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
store_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '货主ID',
|
||||||
|
references: {
|
||||||
|
model: 'wms_store',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
space_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '库位ID',
|
||||||
|
references: {
|
||||||
|
model: 'wms_location_space',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
stock_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '商品SKU ID',
|
||||||
|
references: {
|
||||||
|
model: 'wms_stock_warehouse',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
batch_no: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '批次号',
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
inventory_type: {
|
||||||
|
type: ENUM('ZP', 'CC', 'JS', 'XS', 'ZT', 'DJ', 'FP'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'ZP',
|
||||||
|
comment: '库存类型:ZP=正品, CC=残次, JS=机损, XS=箱损, ZT=在途库存, DJ=冻结, FP=废品',
|
||||||
|
},
|
||||||
|
quantity: {
|
||||||
|
type: INTEGER(12),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '库存数量',
|
||||||
|
},
|
||||||
|
locked_quantity: {
|
||||||
|
type: INTEGER(12),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '锁定数量',
|
||||||
|
},
|
||||||
|
available_quantity: {
|
||||||
|
type: INTEGER(12),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '可用数量',
|
||||||
|
},
|
||||||
|
production_date: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '生产日期',
|
||||||
|
},
|
||||||
|
expiry_date: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '过期日期',
|
||||||
|
},
|
||||||
|
inbound_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '入库时间',
|
||||||
|
},
|
||||||
|
inbound_order_no: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '入库单号',
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
supplier_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '供应商ID',
|
||||||
|
},
|
||||||
|
supplier_batch_no: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '供应商批次号',
|
||||||
|
},
|
||||||
|
is_enabled: {
|
||||||
|
type: TINYINT(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
comment: '是否启用',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
delete_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '删除时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_storage',
|
||||||
|
comment: '库存表',
|
||||||
|
timestamps: false,
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_location_sku_batch_type',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'space_id', 'stock_id', 'batch_no', 'inventory_type' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse_location',
|
||||||
|
fields: [ 'warehouse_id', 'space_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_sku_batch',
|
||||||
|
fields: [ 'stock_id', 'batch_no' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_inventory_type',
|
||||||
|
fields: [ 'inventory_type' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_expiry_date',
|
||||||
|
fields: [ 'expiry_date' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_inbound_order',
|
||||||
|
fields: [ 'inbound_order_no' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_store_id',
|
||||||
|
fields: [ 'store_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_is_enabled',
|
||||||
|
fields: [ 'is_enabled' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_delete_at',
|
||||||
|
fields: [ 'delete_at' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse_stock',
|
||||||
|
fields: [ 'warehouse_id', 'stock_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_available_quantity',
|
||||||
|
fields: [ 'available_quantity' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系
|
||||||
|
Storage.associate = function() {
|
||||||
|
const { Storage, Store, LocationSpace, StockWarehouse } = app.model;
|
||||||
|
|
||||||
|
// 关联仓库
|
||||||
|
Storage.belongsTo(Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
as: 'warehouse',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联货主
|
||||||
|
Storage.belongsTo(Store, {
|
||||||
|
foreignKey: 'store_id',
|
||||||
|
as: 'store',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联库位
|
||||||
|
Storage.belongsTo(LocationSpace, {
|
||||||
|
foreignKey: 'space_id',
|
||||||
|
as: 'space',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联商品SKU
|
||||||
|
Storage.belongsTo(StockWarehouse, {
|
||||||
|
foreignKey: 'stock_id',
|
||||||
|
as: 'stock',
|
||||||
|
});
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法
|
||||||
|
Storage.prototype.getAvailableQuantity = function() {
|
||||||
|
return this.quantity - this.locked_quantity;
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.prototype.isAvailable = function() {
|
||||||
|
return this.is_enabled === 1 && this.available_quantity > 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.prototype.isLocked = function() {
|
||||||
|
return this.locked_quantity > 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.prototype.canAllocate = function(quantity) {
|
||||||
|
return this.is_enabled === 1 && this.available_quantity >= quantity;
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.prototype.isNormalProduct = function() {
|
||||||
|
return this.inventory_type === 'ZP';
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.prototype.isDefective = function() {
|
||||||
|
return this.inventory_type === 'CC';
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.prototype.isExpired = function() {
|
||||||
|
if (!this.expiry_date) return false;
|
||||||
|
return new Date(this.expiry_date) < new Date();
|
||||||
|
};
|
||||||
|
|
||||||
|
// 静态方法
|
||||||
|
Storage.findByStockAndBatch = async function(app, stockId, batchNo, inventoryType = 'ZP') {
|
||||||
|
return await app.model.Storage.findOne({
|
||||||
|
where: {
|
||||||
|
stock_id: stockId,
|
||||||
|
batch_no: batchNo,
|
||||||
|
inventory_type: inventoryType,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: app.model.LocationSpace,
|
||||||
|
as: 'space',
|
||||||
|
attributes: [ 'space_code', 'custom_name' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: app.model.Store,
|
||||||
|
as: 'warehouse',
|
||||||
|
attributes: [ 'store_name' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.findBySpace = async function(app, spaceId) {
|
||||||
|
return await app.model.Storage.findAll({
|
||||||
|
where: {
|
||||||
|
space_id: spaceId,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: app.model.StockWarehouse,
|
||||||
|
as: 'stock',
|
||||||
|
attributes: [ 'product_code', 'product_name' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
order: [[ 'inbound_time', 'ASC' ]],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.findAvailableByWarehouse = async function(app, warehouseId, stockId = null) {
|
||||||
|
const where = {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
available_quantity: { [app.Sequelize.Op.gt]: 0 },
|
||||||
|
};
|
||||||
|
|
||||||
|
if (stockId) {
|
||||||
|
where.stock_id = stockId;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await app.model.Storage.findAll({
|
||||||
|
where,
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: app.model.LocationSpace,
|
||||||
|
as: 'space',
|
||||||
|
attributes: [ 'space_code', 'custom_name' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: app.model.StockWarehouse,
|
||||||
|
as: 'stock',
|
||||||
|
attributes: [ 'product_code', 'product_name' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
order: [
|
||||||
|
[ 'expiry_date', 'ASC' ],
|
||||||
|
[ 'inbound_time', 'ASC' ],
|
||||||
|
],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.findExpiringSoon = async function(app, days = 30) {
|
||||||
|
const expiryDate = new Date();
|
||||||
|
expiryDate.setDate(expiryDate.getDate() + days);
|
||||||
|
|
||||||
|
return await app.model.Storage.findAll({
|
||||||
|
where: {
|
||||||
|
expiry_date: {
|
||||||
|
[app.Sequelize.Op.between]: [ new Date(), expiryDate ],
|
||||||
|
},
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
quantity: { [app.Sequelize.Op.gt]: 0 },
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: app.model.Store,
|
||||||
|
as: 'warehouse',
|
||||||
|
attributes: [ 'store_name' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: app.model.StockWarehouse,
|
||||||
|
as: 'stock',
|
||||||
|
attributes: [ 'product_code', 'product_name' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
order: [[ 'expiry_date', 'ASC' ]],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.updateQuantity = async function(app, id, quantityChange, lockedChange = 0) {
|
||||||
|
const storage = await app.model.Storage.findByPk(id);
|
||||||
|
|
||||||
|
if (!storage) {
|
||||||
|
throw new Error('库存记录不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
const newQuantity = storage.quantity + quantityChange;
|
||||||
|
const newLocked = storage.locked_quantity + lockedChange;
|
||||||
|
|
||||||
|
if (newQuantity < 0) {
|
||||||
|
throw new Error('库存数量不能为负数');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newLocked < 0 || newLocked > newQuantity) {
|
||||||
|
throw new Error('锁定数量无效');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateData = {
|
||||||
|
quantity: newQuantity,
|
||||||
|
locked_quantity: newLocked,
|
||||||
|
available_quantity: newQuantity - newLocked,
|
||||||
|
updated_at: new Date(),
|
||||||
|
};
|
||||||
|
|
||||||
|
await storage.update(updateData);
|
||||||
|
return storage;
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.lockQuantity = async function(app, id, quantity) {
|
||||||
|
return await Storage.updateQuantity(app, id, 0, quantity);
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.unlockQuantity = async function(app, id, quantity) {
|
||||||
|
return await Storage.updateQuantity(app, id, 0, -quantity);
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.allocateQuantity = async function(app, id, quantity) {
|
||||||
|
const storage = await app.model.Storage.findByPk(id);
|
||||||
|
|
||||||
|
if (!storage) {
|
||||||
|
throw new Error('库存记录不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (storage.available_quantity < quantity) {
|
||||||
|
throw new Error('可用数量不足');
|
||||||
|
}
|
||||||
|
|
||||||
|
return await Storage.updateQuantity(app, id, 0, quantity);
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.getStockSummary = async function(app, warehouseId) {
|
||||||
|
return await app.model.Storage.findAll({
|
||||||
|
attributes: [
|
||||||
|
'stock_id',
|
||||||
|
'inventory_type',
|
||||||
|
[ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ],
|
||||||
|
[ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ],
|
||||||
|
[ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ],
|
||||||
|
],
|
||||||
|
where: {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
},
|
||||||
|
group: [ 'stock_id', 'inventory_type' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
Storage.getSpaceUsage = async function(app, spaceId) {
|
||||||
|
const result = await app.model.Storage.findAll({
|
||||||
|
attributes: [
|
||||||
|
'inventory_type',
|
||||||
|
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'record_count' ],
|
||||||
|
[ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ],
|
||||||
|
],
|
||||||
|
where: {
|
||||||
|
space_id: spaceId,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
},
|
||||||
|
group: [ 'inventory_type' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const usage = {
|
||||||
|
normal: 0,
|
||||||
|
defective: 0,
|
||||||
|
damaged: 0,
|
||||||
|
frozen: 0,
|
||||||
|
total: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
result.forEach(item => {
|
||||||
|
let type;
|
||||||
|
switch (item.inventory_type) {
|
||||||
|
case 'ZP': type = 'normal'; break;
|
||||||
|
case 'CC': type = 'defective'; break;
|
||||||
|
case 'JS':
|
||||||
|
case 'XS': type = 'damaged'; break;
|
||||||
|
case 'DJ': type = 'frozen'; break;
|
||||||
|
default: return;
|
||||||
|
}
|
||||||
|
|
||||||
|
usage[type] = parseInt(item.total_quantity) || 0;
|
||||||
|
usage.total += usage[type];
|
||||||
|
});
|
||||||
|
|
||||||
|
return usage;
|
||||||
|
};
|
||||||
|
|
||||||
|
return Storage;
|
||||||
|
};
|
||||||
325
app/model/store.js
Normal file
325
app/model/store.js
Normal file
@ -0,0 +1,325 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, STRING, DATE, TINYINT, INTEGER } = app.Sequelize;
|
||||||
|
|
||||||
|
const Store = app.model.define('store', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '商家ID',
|
||||||
|
},
|
||||||
|
company_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: false,
|
||||||
|
unique: true,
|
||||||
|
validate: {
|
||||||
|
notEmpty: {
|
||||||
|
msg: '公司全称不能为空',
|
||||||
|
},
|
||||||
|
len: {
|
||||||
|
args: [ 1, 200 ],
|
||||||
|
msg: '公司全称长度应在1-200个字符之间',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '公司全称',
|
||||||
|
},
|
||||||
|
business_license: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
unique: true,
|
||||||
|
comment: '营业执照号',
|
||||||
|
},
|
||||||
|
legal_person: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '法人代表',
|
||||||
|
},
|
||||||
|
contact_phone: {
|
||||||
|
type: STRING(20),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: {
|
||||||
|
msg: '联系电话不能为空',
|
||||||
|
},
|
||||||
|
is: {
|
||||||
|
args: /^[0-9+\-()\s]+$/,
|
||||||
|
msg: '请输入有效的联系电话',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '联系电话',
|
||||||
|
},
|
||||||
|
contact_email: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '联系邮箱',
|
||||||
|
},
|
||||||
|
contact_person: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
validate: {
|
||||||
|
notEmpty: {
|
||||||
|
msg: '联系人不能为空',
|
||||||
|
},
|
||||||
|
len: {
|
||||||
|
args: [ 1, 50 ],
|
||||||
|
msg: '联系人姓名长度应在1-50个字符之间',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '联系人',
|
||||||
|
},
|
||||||
|
address: {
|
||||||
|
type: STRING(500),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '公司地址',
|
||||||
|
},
|
||||||
|
industry: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '所属行业',
|
||||||
|
},
|
||||||
|
account_id: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '关联账号ID(商家管理员)',
|
||||||
|
},
|
||||||
|
status: {
|
||||||
|
type: TINYINT(4),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
validate: {
|
||||||
|
isIn: {
|
||||||
|
args: [[ 0, 1, 2 ]],
|
||||||
|
msg: '状态值不合法,0-禁用,1-启用,2-审核中',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comment: '状态:0-禁用,1-启用,2-审核中',
|
||||||
|
},
|
||||||
|
created_by: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建人',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
logo_url: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: 'logo链接',
|
||||||
|
},
|
||||||
|
project: {
|
||||||
|
type: STRING(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '应用',
|
||||||
|
},
|
||||||
|
domain: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '绑定域名',
|
||||||
|
},
|
||||||
|
auth_end: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '授权结束时间',
|
||||||
|
},
|
||||||
|
deleted_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '删除时间',
|
||||||
|
},
|
||||||
|
quota_bytes: {
|
||||||
|
type: BIGINT.UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 107374182400,
|
||||||
|
comment: '仓库文件存储配额',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_store',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: true,
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
paranoid: true,
|
||||||
|
deletedAt: 'deleted_at',
|
||||||
|
comment: '商家表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_company_name',
|
||||||
|
fields: [ 'company_name' ],
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'uk_business_license',
|
||||||
|
fields: [ 'business_license' ],
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_status',
|
||||||
|
fields: [ 'status' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_account_id',
|
||||||
|
fields: [ 'account_id' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联关系 - 使用您推荐的方式
|
||||||
|
Store.associate = function() {
|
||||||
|
const { Account, Role, AccountStoreEmployee, ProhibitedType } = app.model;
|
||||||
|
|
||||||
|
// 关联创建人
|
||||||
|
Store.belongsTo(Account, {
|
||||||
|
foreignKey: 'created_by',
|
||||||
|
as: 'creator',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联商家管理员账号
|
||||||
|
Store.belongsTo(Account, {
|
||||||
|
foreignKey: 'account_id',
|
||||||
|
as: 'adminAccount',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联商家拥有的角色
|
||||||
|
Store.hasMany(Role, {
|
||||||
|
foreignKey: 'store_id',
|
||||||
|
as: 'roles',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联商家拥有的账号角色关联
|
||||||
|
Store.hasMany(AccountStoreEmployee, {
|
||||||
|
foreignKey: 'store_id',
|
||||||
|
as: 'accountStoreEmployee',
|
||||||
|
});
|
||||||
|
|
||||||
|
Store.hasMany(ProhibitedType, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
as: 'prohibitedTypes',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:检查商家是否启用
|
||||||
|
Store.prototype.isEnabled = function() {
|
||||||
|
return this.status === 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:检查商家是否审核中
|
||||||
|
Store.prototype.isReviewing = function() {
|
||||||
|
return this.status === 2;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:检查是否是仓库
|
||||||
|
Store.prototype.isWarehouse = function() {
|
||||||
|
return this.project === 'warehouse';
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:检查授权是否有效
|
||||||
|
Store.prototype.isAuthValid = function() {
|
||||||
|
if (!this.auth_start || !this.auth_end) {
|
||||||
|
return true; // 如果没有设置授权时间,默认有效
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
return now >= new Date(this.auth_start) && now <= new Date(this.auth_end);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法:检查邮箱是否有效
|
||||||
|
Store.prototype.hasValidEmail = function() {
|
||||||
|
if (!this.contact_email) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
return emailRegex.test(this.contact_email);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:根据账号ID查找商家
|
||||||
|
Store.findByAccountId = async function(accountId) {
|
||||||
|
return await this.findOne({
|
||||||
|
where: {
|
||||||
|
account_id: accountId,
|
||||||
|
status: 1,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:获取所有启用的商家
|
||||||
|
Store.findAllEnabled = async function() {
|
||||||
|
return await this.findAll({
|
||||||
|
where: {
|
||||||
|
status: 1,
|
||||||
|
},
|
||||||
|
order: [[ 'company_name', 'ASC' ]],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:获取所有仓库类型的商家
|
||||||
|
Store.findAllWarehouses = async function() {
|
||||||
|
return await this.findAll({
|
||||||
|
where: {
|
||||||
|
status: 1,
|
||||||
|
project: 'warehouse',
|
||||||
|
},
|
||||||
|
order: [[ 'company_name', 'ASC' ]],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:检查公司名称是否存在
|
||||||
|
Store.checkCompanyNameExists = async function(companyName, excludeId = null) {
|
||||||
|
const where = {
|
||||||
|
company_name: companyName,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (excludeId) {
|
||||||
|
where.id = {
|
||||||
|
[app.Sequelize.Op.ne]: excludeId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const store = await this.findOne({ where });
|
||||||
|
return !!store;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 类方法:创建商家时的数据验证
|
||||||
|
Store.validateStoreData = function(data) {
|
||||||
|
const errors = [];
|
||||||
|
|
||||||
|
// 必填字段检查
|
||||||
|
const requiredFields = [ 'company_name', 'contact_person', 'contact_phone' ];
|
||||||
|
for (const field of requiredFields) {
|
||||||
|
if (!data[field]) {
|
||||||
|
errors.push(`${field} 不能为空`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 公司名称长度检查
|
||||||
|
if (data.company_name && (data.company_name.length < 1 || data.company_name.length > 200)) {
|
||||||
|
errors.push('公司名称长度应在1-200个字符之间');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 邮箱格式检查(如果提供了邮箱)
|
||||||
|
if (data.contact_email && data.contact_email.trim() !== '') {
|
||||||
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
if (!emailRegex.test(data.contact_email)) {
|
||||||
|
errors.push('联系邮箱格式不正确');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors;
|
||||||
|
};
|
||||||
|
|
||||||
|
return Store;
|
||||||
|
};
|
||||||
101
app/model/store_join.js
Normal file
101
app/model/store_join.js
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
// models/store_join.js
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, STRING, DATE, TINYINT, INTEGER, ENUM } = app.Sequelize;
|
||||||
|
const StoreJoin = app.model.define('StoreJoin', {
|
||||||
|
id: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '申请ID',
|
||||||
|
},
|
||||||
|
account_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '用户账户ID',
|
||||||
|
},
|
||||||
|
warehouse: {
|
||||||
|
type: TINYINT(1),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '是否为仓库',
|
||||||
|
},
|
||||||
|
real_name: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '真实姓名',
|
||||||
|
},
|
||||||
|
store_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '审批的门店/店铺ID',
|
||||||
|
},
|
||||||
|
apply_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '申请时间',
|
||||||
|
},
|
||||||
|
apply_username: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '申请人用户名',
|
||||||
|
},
|
||||||
|
audit_status: {
|
||||||
|
type: ENUM('pending', 'approved', 'rejected', 'processing'),
|
||||||
|
defaultValue: 'pending',
|
||||||
|
comment: '审核状态',
|
||||||
|
},
|
||||||
|
remark: {
|
||||||
|
type: STRING(500),
|
||||||
|
defaultValue: '',
|
||||||
|
comment: '备注',
|
||||||
|
},
|
||||||
|
join_token: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: false,
|
||||||
|
unique: true,
|
||||||
|
comment: '加入令牌/验证码',
|
||||||
|
},
|
||||||
|
token_expiry_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '令牌过期时间',
|
||||||
|
},
|
||||||
|
audit_real_name: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '审核人工号名字',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_store_join',
|
||||||
|
comment: '加入申请记录表',
|
||||||
|
paranoid: false, // 明确禁用软删除
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'idx_account_id',
|
||||||
|
fields: [ 'account_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_audit_status',
|
||||||
|
fields: [ 'audit_status' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_apply_time',
|
||||||
|
fields: [ 'apply_time' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_store_id',
|
||||||
|
fields: [ 'store_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'uk_account_warehouse_store',
|
||||||
|
fields: [ 'account_id', 'store_id' ],
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
return StoreJoin;
|
||||||
|
};
|
||||||
264
app/model/store_warehouse.js
Normal file
264
app/model/store_warehouse.js
Normal file
@ -0,0 +1,264 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
module.exports = app => {
|
||||||
|
const { BIGINT, TEXT, STRING, DATE, TINYINT, INTEGER } = app.Sequelize;
|
||||||
|
|
||||||
|
const StoreWarehouse = app.model.define('store_warehouse', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '授权ID',
|
||||||
|
},
|
||||||
|
store_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '商家ID',
|
||||||
|
references: {
|
||||||
|
model: 'store',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库ID',
|
||||||
|
references: {
|
||||||
|
model: 'store',
|
||||||
|
key: 'id',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
auth_status: {
|
||||||
|
type: TINYINT(4),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
validate: {
|
||||||
|
isIn: [[ 1, 2, 3, 4, 5 ]], // 1-申请中,2-已通过,3-已拒绝,4-已解除,5-已过期
|
||||||
|
},
|
||||||
|
comment: '授权状态:1-申请中,2-已通过,3-已拒绝,4-已解除,5-已过期',
|
||||||
|
},
|
||||||
|
apply_reason: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '申请理由',
|
||||||
|
},
|
||||||
|
review_comment: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '审核意见',
|
||||||
|
},
|
||||||
|
apply_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '申请时间',
|
||||||
|
},
|
||||||
|
print_quantity: {
|
||||||
|
type: BIGINT(12),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '面单余额',
|
||||||
|
},
|
||||||
|
review_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '审核时间',
|
||||||
|
},
|
||||||
|
auth_start: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '授权开始日期',
|
||||||
|
},
|
||||||
|
auth_end: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '授权结束日期',
|
||||||
|
},
|
||||||
|
actual_end: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '实际结束时间',
|
||||||
|
},
|
||||||
|
applied_by: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '申请人',
|
||||||
|
},
|
||||||
|
reviewed_by: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '审核人',
|
||||||
|
},
|
||||||
|
ended_by: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '解除人',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
store_remask: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 50 ],
|
||||||
|
},
|
||||||
|
comment: '商家备注',
|
||||||
|
},
|
||||||
|
warehouse_remask: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
validate: {
|
||||||
|
len: [ 0, 50 ],
|
||||||
|
},
|
||||||
|
comment: '仓库备注',
|
||||||
|
},
|
||||||
|
use_status: {
|
||||||
|
type: INTEGER(1),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '使用状态,0-不可用,1-可用(SKU可见,货主可见,即使解约了)',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_store_warehouse',
|
||||||
|
freezeTableName: true,
|
||||||
|
underscored: true,
|
||||||
|
timestamps: true,
|
||||||
|
createdAt: 'created_at',
|
||||||
|
updatedAt: 'updated_at',
|
||||||
|
comment: '商家仓库授权关系表',
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_store_warehouse',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'store_id', 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_store_id',
|
||||||
|
fields: [ 'store_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse_id',
|
||||||
|
fields: [ 'warehouse_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_auth_status',
|
||||||
|
fields: [ 'auth_status' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_apply_time',
|
||||||
|
fields: [ 'apply_time' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_auth_period',
|
||||||
|
fields: [ 'auth_start', 'auth_end' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_applied_by',
|
||||||
|
fields: [ 'applied_by' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_reviewed_by',
|
||||||
|
fields: [ 'reviewed_by' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_auth_end',
|
||||||
|
fields: [ 'auth_end' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_status_apply_time',
|
||||||
|
fields: [ 'auth_status', 'apply_time' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 定义关联关系
|
||||||
|
StoreWarehouse.associate = function() {
|
||||||
|
const { Store, Account, StockWarehouse, Receiving } = app.model;
|
||||||
|
|
||||||
|
// 授权关系属于商家
|
||||||
|
StoreWarehouse.belongsTo(Store, {
|
||||||
|
foreignKey: 'store_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'store',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 授权关系属于仓库
|
||||||
|
StoreWarehouse.belongsTo(Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'warehouse',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 申请人
|
||||||
|
StoreWarehouse.belongsTo(Account, {
|
||||||
|
foreignKey: 'applied_by',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'applicant',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 审核人
|
||||||
|
StoreWarehouse.belongsTo(Account, {
|
||||||
|
foreignKey: 'reviewed_by',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'reviewer',
|
||||||
|
});
|
||||||
|
|
||||||
|
StoreWarehouse.hasMany(StockWarehouse, {
|
||||||
|
foreignKey: 'store_id',
|
||||||
|
targetKey: 'store_id',
|
||||||
|
as: 'store_stock',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 解除人
|
||||||
|
StoreWarehouse.belongsTo(Account, {
|
||||||
|
foreignKey: 'ended_by',
|
||||||
|
targetKey: 'id',
|
||||||
|
as: 'end_user',
|
||||||
|
});
|
||||||
|
StoreWarehouse.hasMany(Receiving, {
|
||||||
|
foreignKey: 'store_id',
|
||||||
|
as: 'receiving',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 检查授权是否有效
|
||||||
|
StoreWarehouse.prototype.isAuthValid = function() {
|
||||||
|
if (this.auth_status !== 2) return false; // 只有已通过状态才有效
|
||||||
|
if (!this.auth_start || !this.auth_end) return false;
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const start = new Date(this.auth_start);
|
||||||
|
const end = new Date(this.auth_end);
|
||||||
|
|
||||||
|
return now >= start && now <= end;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 检查授权是否即将过期(30天内)
|
||||||
|
StoreWarehouse.prototype.isExpiringSoon = function() {
|
||||||
|
if (this.auth_status !== 2 || !this.auth_end) return false;
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const end = new Date(this.auth_end);
|
||||||
|
const daysUntilExpire = Math.ceil((end - now) / (1000 * 60 * 60 * 24));
|
||||||
|
|
||||||
|
return daysUntilExpire <= 30 && daysUntilExpire > 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实例方法 - 获取授权剩余天数
|
||||||
|
StoreWarehouse.prototype.getRemainingDays = function() {
|
||||||
|
if (!this.isAuthValid()) return 0;
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const end = new Date(this.auth_end);
|
||||||
|
const diffTime = end - now;
|
||||||
|
return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
|
||||||
|
};
|
||||||
|
|
||||||
|
return StoreWarehouse;
|
||||||
|
};
|
||||||
17
app/router.js
Normal file
17
app/router.js
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* @param {Egg.Application} app - egg application
|
||||||
|
*/
|
||||||
|
module.exports = app => {
|
||||||
|
const { router, controller } = app;
|
||||||
|
router.get('/', controller.home.index);
|
||||||
|
router.post('/qimen', controller.home.qimen);
|
||||||
|
router.post('/api/warehouse', controller.home.warehouse);
|
||||||
|
router.post('/api/store', controller.home.store);
|
||||||
|
router.post('/api/v1', controller.home.v1);
|
||||||
|
router.post('/system', controller.home.system);
|
||||||
|
router.post('/api/v2', controller.apiV2.index);
|
||||||
|
router.get('/template/xml/:id', controller.template.xml);
|
||||||
|
router.get('/auth/printSetting/:code', controller.auth.printerSetting);
|
||||||
|
router.get('/testSendData', controller.home.testSendData);
|
||||||
|
router.post('/auth/printSetting/', controller.auth.printerSetting);
|
||||||
|
};
|
||||||
48
app/service/api.js
Normal file
48
app/service/api.js
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
const { XMLParser } = require('fast-xml-parser');
|
||||||
|
|
||||||
|
class ApiService extends Service {
|
||||||
|
/**
|
||||||
|
* 调用业务方法
|
||||||
|
* @param className
|
||||||
|
* @param actionName
|
||||||
|
* @param jsonData
|
||||||
|
* @param format
|
||||||
|
*/
|
||||||
|
async callMethod(className, actionName, jsonData, format = 'json') {
|
||||||
|
try {
|
||||||
|
// 构建服务类路径
|
||||||
|
const servicePath = `${className}`;
|
||||||
|
const classs = servicePath.split('.');
|
||||||
|
let apiMethods = this.ctx.service.apiMethods;
|
||||||
|
for (let i = 0; i < classs.length; i++) {
|
||||||
|
const className = classs[i];
|
||||||
|
apiMethods = apiMethods[className];
|
||||||
|
}
|
||||||
|
// 检查服务是否存在
|
||||||
|
if (!apiMethods) {
|
||||||
|
throw new Error(`服务 ${servicePath} 不存在`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const serviceInstance = apiMethods;
|
||||||
|
|
||||||
|
// 检查方法是否存在
|
||||||
|
if (typeof serviceInstance[actionName] !== 'function') {
|
||||||
|
throw new Error(`方法 ${actionName} 不存在`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调用方法
|
||||||
|
const result = await serviceInstance[actionName](jsonData);
|
||||||
|
// 根据format参数返回相应格式
|
||||||
|
return result;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = ApiService;
|
||||||
150
app/service/apiMethods/test.js
Normal file
150
app/service/apiMethods/test.js
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class testServer extends Service {
|
||||||
|
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
const { app } = this;
|
||||||
|
try {
|
||||||
|
this.addon = require(app.appRoot + '/native/addons/subset_selector.node');
|
||||||
|
this.addonLoaded = true;
|
||||||
|
this.ctx.logger.info('[FibonacciService] C++插件加载成功');
|
||||||
|
console.log(this.addon);
|
||||||
|
} catch (error) {
|
||||||
|
|
||||||
|
|
||||||
|
this.addonLoaded = false;
|
||||||
|
this.ctx.logger.error('[FibonacciService] C++插件加载失败:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async entryorderConfirm(data) {
|
||||||
|
const { app, ctx } = this;
|
||||||
|
return await ctx.service.systems.entryOrder.entryorderConfirm(data.id, data.isCompleted);
|
||||||
|
}
|
||||||
|
async playbackRequest(data) {
|
||||||
|
const { app } = this;
|
||||||
|
try {
|
||||||
|
const entryOrder = await app.model.QimenLog.findOne({
|
||||||
|
where: {
|
||||||
|
id: data.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (entryOrder) {
|
||||||
|
console.log('entryOrder', entryOrder.body);
|
||||||
|
const body = await this.ctx.service.systems.qimenQuery.sendRequest(entryOrder.url, entryOrder.body);
|
||||||
|
return { body };
|
||||||
|
}
|
||||||
|
throw new Error('无历史请求数据');
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fibonacci(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { n, type = 'dynamic' } = data;
|
||||||
|
|
||||||
|
const DeliveryModel = await ctx.model.WmsOrderDeliveryFactory.getCurrentModel(100000);
|
||||||
|
const WmsOrderItemsModel = await ctx.model.WmsOrderItemsFactory.getCurrentModel(100000);
|
||||||
|
|
||||||
|
const order = [[ 'id', 'DESC' ]];
|
||||||
|
const pageSize = 20000;
|
||||||
|
const page = 1;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 先查询订单ID
|
||||||
|
const deliveryResult = await DeliveryModel.findAll({
|
||||||
|
attributes: [ 'id' ],
|
||||||
|
where: {},
|
||||||
|
order,
|
||||||
|
limit: parseInt(pageSize),
|
||||||
|
offset: (parseInt(page) - 1) * parseInt(pageSize),
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('查询到的订单ID数量:', deliveryResult.length);
|
||||||
|
|
||||||
|
if (deliveryResult.length === 0) {
|
||||||
|
return {
|
||||||
|
orderIds: [],
|
||||||
|
skus: [],
|
||||||
|
orderCount: 0,
|
||||||
|
skuCount: 0,
|
||||||
|
message: '没有找到订单数据',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 提取订单ID数组
|
||||||
|
const deliveryIds = deliveryResult.map(row => row.id);
|
||||||
|
|
||||||
|
// 3. 使用正确的语法查询去重的商品数据
|
||||||
|
const itemsResult = await WmsOrderItemsModel.findAll({
|
||||||
|
attributes: [
|
||||||
|
'order_id',
|
||||||
|
'item_id',
|
||||||
|
],
|
||||||
|
where: {
|
||||||
|
order_id: deliveryIds,
|
||||||
|
},
|
||||||
|
group: [ 'order_id', 'item_id' ], // ✅ 使用 GROUP BY 去重
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('查询到的商品记录数量:', itemsResult.length);
|
||||||
|
|
||||||
|
// 4. 按订单分组商品
|
||||||
|
const itemsByOrder = {};
|
||||||
|
itemsResult.forEach(item => {
|
||||||
|
if (!itemsByOrder[item.order_id]) {
|
||||||
|
itemsByOrder[item.order_id] = new Set(); // 使用 Set 自动去重
|
||||||
|
}
|
||||||
|
itemsByOrder[item.order_id].add(parseInt(item.item_id));
|
||||||
|
});
|
||||||
|
|
||||||
|
// 5. 构建订单数据结构
|
||||||
|
const orders = deliveryResult.map(row => {
|
||||||
|
const orderId = row.id.toString();
|
||||||
|
const skus = itemsByOrder[row.id] ? Array.from(itemsByOrder[row.id]) : [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: orderId,
|
||||||
|
skus,
|
||||||
|
size: skus.length,
|
||||||
|
};
|
||||||
|
}).filter(order => order.skus.length > 0); // 过滤掉没有商品的订单
|
||||||
|
|
||||||
|
console.log('有效订单数量:', orders.length);
|
||||||
|
|
||||||
|
if (orders.length === 0) {
|
||||||
|
return {
|
||||||
|
orderIds: [],
|
||||||
|
skus: [],
|
||||||
|
orderCount: 0,
|
||||||
|
skuCount: 0,
|
||||||
|
message: '没有找到包含商品的订单',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. 调用插件算法
|
||||||
|
const algorithmResult = this.addon.selectOrders(orders, n || 20, type);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...algorithmResult,
|
||||||
|
totalOrders: orders.length,
|
||||||
|
queryTime: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('执行订单选择算法失败:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fibonacciRecursive(n) {
|
||||||
|
if (n <= 1) return n;
|
||||||
|
return this.fibonacciRecursive(n - 1) + this.fibonacciRecursive(n - 2); // 大量重复计算
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = testServer;
|
||||||
82
app/service/dispatcher.js
Normal file
82
app/service/dispatcher.js
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class DispatcherService extends Service {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
// postpone building map until needed
|
||||||
|
this.methodMap = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// recursively walk through object to collect functions
|
||||||
|
buildMap(obj, prefix = '') {
|
||||||
|
// avoid expensive or dangerous walk when running tests
|
||||||
|
if (process.env.NODE_ENV === 'test') return {};
|
||||||
|
const map = {};
|
||||||
|
Object.keys(obj).forEach(key => {
|
||||||
|
let value;
|
||||||
|
try {
|
||||||
|
value = obj[key];
|
||||||
|
} catch (err) {
|
||||||
|
// skip getters that throw
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const path = prefix ? `${prefix}.${key}` : key;
|
||||||
|
if (typeof value === 'function') {
|
||||||
|
map[path] = value.bind(obj);
|
||||||
|
} else if (value && typeof value === 'object') {
|
||||||
|
Object.assign(map, this.buildMap(value, path));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
getMethodMap() {
|
||||||
|
if (!this.methodMap) {
|
||||||
|
this.methodMap = this.buildMap(this.ctx.service.systemMethods || {});
|
||||||
|
}
|
||||||
|
return this.methodMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
async invoke(method, data, authHeader, ctx) {
|
||||||
|
// debug output: show incoming request method and payload size
|
||||||
|
console.debug('[dispatcher] invoke method', method, 'data size',
|
||||||
|
data ? JSON.stringify(data).length : 0);
|
||||||
|
|
||||||
|
const fn = this.getMethodMap()[method];
|
||||||
|
if (!fn) {
|
||||||
|
console.error('[dispatcher] method not found in map:', method);
|
||||||
|
throw new Error(`方法 ${method} 不存在 (检查 systemMethods 目录或拼写)`);
|
||||||
|
}
|
||||||
|
// perform global auth/log check using original service API
|
||||||
|
// we rely on the service instance to provide checkAuth, so find owning service
|
||||||
|
const parts = method.split('.');
|
||||||
|
const action = parts.pop();
|
||||||
|
const servicePath = parts.join('.');
|
||||||
|
|
||||||
|
// resolve the service instance again (should be same as that bound earlier)
|
||||||
|
let svc = ctx.service.systemMethods;
|
||||||
|
parts.forEach(p => {
|
||||||
|
svc = svc && svc[p];
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!svc) {
|
||||||
|
console.error('[dispatcher] service instance not found for path', servicePath);
|
||||||
|
throw new Error(`服务 ${servicePath} 不存在`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const authPass = await svc.checkAuth(servicePath, action, authHeader);
|
||||||
|
const isLog = authPass.isLog;
|
||||||
|
if (authPass.status !== 200) {
|
||||||
|
console.debug('[dispatcher] auth failed', authPass);
|
||||||
|
return { isLog, result: { status: authPass.status, message: authPass.message } };
|
||||||
|
}
|
||||||
|
|
||||||
|
const resultData = await fn(data);
|
||||||
|
console.debug('[dispatcher] method executed successfully', method);
|
||||||
|
return { isLog, result: { status: 200, data: resultData } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = DispatcherService;
|
||||||
380
app/service/main.js
Normal file
380
app/service/main.js
Normal file
@ -0,0 +1,380 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class MainService extends Service {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
// 初始化公共变量
|
||||||
|
this.storeId = null;
|
||||||
|
this.warehouseId = null;
|
||||||
|
this.appKey = null;
|
||||||
|
this.customerId = null;
|
||||||
|
this.warehouseCode = null;
|
||||||
|
this.commonData = {}; // 额外的公共数据存储
|
||||||
|
this._noNeedLogin = null;
|
||||||
|
this._noNeedRight = null;
|
||||||
|
this._noNeedAuth = null;
|
||||||
|
this.user = null;
|
||||||
|
this.userId = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
success(message, data, code = 1) {
|
||||||
|
const result = {
|
||||||
|
flag: 'success',
|
||||||
|
code,
|
||||||
|
message,
|
||||||
|
...data,
|
||||||
|
};
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
fail(message, data, code = 0) {
|
||||||
|
console.log('fail', message, data);
|
||||||
|
const result = {
|
||||||
|
flag: 'failure',
|
||||||
|
code,
|
||||||
|
message,
|
||||||
|
...data,
|
||||||
|
};
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
normalizeDate(date, isEnd = false) {
|
||||||
|
if (!date) return null;
|
||||||
|
|
||||||
|
let d;
|
||||||
|
|
||||||
|
if (date instanceof Date) {
|
||||||
|
d = date;
|
||||||
|
} else {
|
||||||
|
// 尝试解析日期字符串
|
||||||
|
d = new Date(date);
|
||||||
|
if (isNaN(d.getTime())) {
|
||||||
|
return date;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取本地时间的年月日
|
||||||
|
const year = d.getFullYear();
|
||||||
|
const month = String(d.getMonth() + 1).padStart(2, '0');
|
||||||
|
const day = String(d.getDate()).padStart(2, '0');
|
||||||
|
|
||||||
|
// 根据 isEnd 参数添加时间部分
|
||||||
|
// 使用本地时间格式,避免时区转换
|
||||||
|
if (isEnd) {
|
||||||
|
return `${year}-${month}-${day} 23:59:59`;
|
||||||
|
}
|
||||||
|
return `${year}-${month}-${day} 00:00:00`;
|
||||||
|
|
||||||
|
}
|
||||||
|
setInfo(storeId, warehouseId, appKey, customerId, warehouseCode) {
|
||||||
|
this.storeId = storeId;
|
||||||
|
this.warehouseId = warehouseId;
|
||||||
|
this.appKey = appKey;
|
||||||
|
this.warehouseCode = warehouseCode;
|
||||||
|
this.customerId = customerId;
|
||||||
|
}
|
||||||
|
|
||||||
|
getInfo() {
|
||||||
|
return {
|
||||||
|
storeId: this.storeId,
|
||||||
|
warehouseId: this.warehouseId,
|
||||||
|
appKey: this.appKey,
|
||||||
|
warehouseCode: this.warehouseCode,
|
||||||
|
customerId: this.customerId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async findQimenAppWithContract(appkey, customerId, warehouseCode) {
|
||||||
|
const { app } = this;
|
||||||
|
const cacheKey = `contract:${appkey}:${customerId}:${warehouseCode}`;
|
||||||
|
try {
|
||||||
|
let cacheResult = null;
|
||||||
|
try {
|
||||||
|
cacheResult = await Promise.race([
|
||||||
|
this.app.getCacheAsync(cacheKey),
|
||||||
|
new Promise(resolve => setTimeout(() => {
|
||||||
|
app.logger.warn('[RedisTimeout] Redis get operation timeout');
|
||||||
|
resolve(null);
|
||||||
|
}, 100)),
|
||||||
|
]);
|
||||||
|
} catch (cacheError) {
|
||||||
|
app.logger.warn('[RedisGetError]', cacheError.message);
|
||||||
|
// Redis 错误时继续数据库查询
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cacheResult) {
|
||||||
|
try {
|
||||||
|
const parsedResult = cacheResult;
|
||||||
|
if (parsedResult) {
|
||||||
|
app.logger.info('[CacheHit] Found in cache', cacheKey);
|
||||||
|
return parsedResult;
|
||||||
|
}
|
||||||
|
} catch (parseError) {
|
||||||
|
app.logger.error('[RedisParseError]', parseError.message, cacheKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 数据库查询
|
||||||
|
app.logger.info('[CacheMiss] Querying from database', { appkey, customerId, warehouseCode });
|
||||||
|
const dbResult = await this.queryFromDatabase(appkey, customerId, warehouseCode);
|
||||||
|
|
||||||
|
// 4. 异步设置缓存(添加安全检查)
|
||||||
|
this.app.setCacheAsync(cacheKey, dbResult).catch(error => {
|
||||||
|
app.logger.error('[AsyncCacheError]', error.message);
|
||||||
|
});
|
||||||
|
|
||||||
|
return dbResult;
|
||||||
|
} catch (error) {
|
||||||
|
app.logger.error('[findQimenAppWithContract] Query failed', error.message, { appkey, customerId, warehouseCode });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取数据库查询逻辑
|
||||||
|
async queryFromDatabase(appkey, customerId, warehouseCode) {
|
||||||
|
const { app } = this;
|
||||||
|
|
||||||
|
// 检查模型是否存在
|
||||||
|
if (!app.model || !app.model.ApiApp) {
|
||||||
|
throw new Error('ApiApp model is not available');
|
||||||
|
}
|
||||||
|
|
||||||
|
return await app.model.ApiApp.findOne({
|
||||||
|
attributes: [
|
||||||
|
'id',
|
||||||
|
'app_name',
|
||||||
|
'qimen_app_key',
|
||||||
|
'qimen_customer_id',
|
||||||
|
'qimen_warehouse_code',
|
||||||
|
'api_version',
|
||||||
|
'sign_method',
|
||||||
|
'rate_limit',
|
||||||
|
'timeout_seconds',
|
||||||
|
[ app.Sequelize.col('contract.store_id'), 'store_id' ],
|
||||||
|
[ app.Sequelize.col('contract.warehouse_id'), 'warehouse_id' ],
|
||||||
|
[ app.Sequelize.col('contract.auth_end'), 'contract_auth_end' ],
|
||||||
|
[ app.Sequelize.col('contract.auth_status'), 'contract_auth_status' ],
|
||||||
|
[ app.Sequelize.col('contract.apply_reason'), 'apply_reason' ],
|
||||||
|
[ app.Sequelize.col('contract.review_comment'), 'review_comment' ],
|
||||||
|
[ app.Sequelize.col('contract.warehouse.status'), 'warehouse_status' ],
|
||||||
|
[ app.Sequelize.col('contract.warehouse.auth_end'), 'warehouse_auth_end' ],
|
||||||
|
],
|
||||||
|
where: {
|
||||||
|
qimen_app_key: appkey,
|
||||||
|
qimen_customer_id: customerId,
|
||||||
|
qimen_warehouse_code: warehouseCode,
|
||||||
|
is_enabled: 1,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: app.model.StoreWarehouse,
|
||||||
|
as: 'contract',
|
||||||
|
attributes: [],
|
||||||
|
required: false,
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: app.model.Store,
|
||||||
|
as: 'warehouse',
|
||||||
|
attributes: [],
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
raw: true,
|
||||||
|
timeout: 10000, // 10秒超时
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async checkAuth(servicePath, actionName, authHeader) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
|
||||||
|
// 配置免登录和免鉴权的接口
|
||||||
|
const _noNeedLogin = (this._noNeedLogin || '').split(',');
|
||||||
|
const _noNeedRight = (this._noNeedRight || '').split(',');
|
||||||
|
const _noNeedAuth = (this._noNeedAuth || '').split(',');
|
||||||
|
const _noNeedLog = (this._noNeedLog || '').split(',');
|
||||||
|
const api_path = `${servicePath}.${actionName}`;
|
||||||
|
console.log(api_path, '_noNeedLog', _noNeedLog);
|
||||||
|
const result = {
|
||||||
|
status: 401,
|
||||||
|
message: '',
|
||||||
|
user: null,
|
||||||
|
isLog: true,
|
||||||
|
};
|
||||||
|
if (_noNeedLog.indexOf('*') > -1 || _noNeedLog.indexOf(actionName) > -1) {
|
||||||
|
result.isLog = false;
|
||||||
|
}
|
||||||
|
// 1. 检查是否在免登录列表
|
||||||
|
if (_noNeedLogin.indexOf('*') > -1 || _noNeedLogin.indexOf(actionName) > -1) {
|
||||||
|
result.status = 200;
|
||||||
|
result.message = 'ok';
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 检查是否有认证令牌
|
||||||
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||||
|
result.status = 401;
|
||||||
|
result.message = '未提供有效的认证令牌';
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = authHeader.substring(7);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 3. 验证JWT令牌
|
||||||
|
const NewauthHeader = '';
|
||||||
|
const decoded = app.jwt.verify(token, app.config.jwt.secret);
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
const expiresIn = decoded.exp - now;
|
||||||
|
if (expiresIn < 1800 && expiresIn > 0) {
|
||||||
|
// 移除过期时间(exp)和签发时间(iat),保留其他payload
|
||||||
|
const { exp, iat, ...payload } = decoded;
|
||||||
|
|
||||||
|
// 生成新的 token,使用原来的有效时间配置
|
||||||
|
const newToken = app.jwt.sign(
|
||||||
|
payload,
|
||||||
|
app.config.jwt.secret,
|
||||||
|
{
|
||||||
|
expiresIn: app.config.jwt.expiresIn || '3600',
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// 设置新的 token 到响应头
|
||||||
|
ctx.set('Authorization', `Bearer ${newToken}`);
|
||||||
|
console.log('Token 已刷新,新 token:', newToken.substring(0, 50) + '...');
|
||||||
|
}
|
||||||
|
// 4. 获取用户信息
|
||||||
|
const user = await ctx.service.systems.auth.user.findById(decoded.id || decoded.userId);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
result.status = 401;
|
||||||
|
result.message = '用户不存在或已被删除';
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user.status !== 1) {
|
||||||
|
result.status = 403;
|
||||||
|
result.message = '账号已被禁用';
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1) {
|
||||||
|
} else {
|
||||||
|
if (user.auth_end && new Date(user.auth_end) < new Date()) {
|
||||||
|
result.status = 406;
|
||||||
|
result.message = '仓库有效期已过期';
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 检查是否在免权限列表
|
||||||
|
if (_noNeedRight.indexOf('*') > -1 || _noNeedRight.indexOf(actionName) > -1) {
|
||||||
|
// 免权限验证,只验证登录状态
|
||||||
|
this.setUserContext(ctx, user, decoded);
|
||||||
|
result.status = 200;
|
||||||
|
result.message = 'ok';
|
||||||
|
result.user = user;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. 验证API权限(只检查类型为api的权限)
|
||||||
|
console.log('检查权限开始');
|
||||||
|
|
||||||
|
const hasPermission = await this.checkApiPermission(user, api_path);
|
||||||
|
console.log('检查权限结束', hasPermission);
|
||||||
|
|
||||||
|
|
||||||
|
if (!hasPermission) {
|
||||||
|
result.status = 403;
|
||||||
|
result.message = '无权访问该接口';
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. 验证通过,设置用户上下文
|
||||||
|
this.setUserContext(ctx, user, decoded);
|
||||||
|
|
||||||
|
result.status = 200;
|
||||||
|
result.message = 'ok';
|
||||||
|
result.user = user;
|
||||||
|
return result;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('鉴权错误:', error);
|
||||||
|
|
||||||
|
if (error.name === 'TokenExpiredError') {
|
||||||
|
result.status = 401;
|
||||||
|
result.message = '令牌已过期';
|
||||||
|
} else if (error.name === 'JsonWebTokenError') {
|
||||||
|
result.status = 401;
|
||||||
|
result.message = '无效的令牌';
|
||||||
|
} else if (error.name === 'SequelizeDatabaseError') {
|
||||||
|
result.status = 500;
|
||||||
|
result.message = '数据库错误';
|
||||||
|
} else {
|
||||||
|
result.status = 500;
|
||||||
|
result.message = '服务器内部错误';
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查用户是否有API访问权限(只检查类型为api的权限)
|
||||||
|
* @param {Object} user - 用户信息
|
||||||
|
* @param {string} apiPath - API路径
|
||||||
|
* @return {Promise<boolean>}
|
||||||
|
*/
|
||||||
|
async checkApiPermission(user, apiPath) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
console.log(user);
|
||||||
|
try {
|
||||||
|
// 方法1: 从用户的权限列表中检查(如果已经加载了权限)
|
||||||
|
if (user.permissions && Array.isArray(user.permissions)) {
|
||||||
|
// 用户权限列表中可能包含所有权限,需要过滤出api权限
|
||||||
|
console.log('user.permissions', user.permissions);
|
||||||
|
return user.permissions.includes(apiPath);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('检查API权限失败:', error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 设置用户上下文信息
|
||||||
|
* @param {Object} ctx - 上下文对象
|
||||||
|
* @param {Object} user - 用户信息
|
||||||
|
* @param {Object} decoded - JWT解码信息
|
||||||
|
*/
|
||||||
|
setUserContext(ctx, user, decoded) {
|
||||||
|
// 设置用户基本信息
|
||||||
|
ctx.user = user;
|
||||||
|
ctx.userId = user.id;
|
||||||
|
ctx.username = user.username;
|
||||||
|
ctx.realName = user.real_name;
|
||||||
|
|
||||||
|
|
||||||
|
if (user.store_id) {
|
||||||
|
ctx.currentStoreId = user.store_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置平台信息
|
||||||
|
if (decoded.platform_code) {
|
||||||
|
ctx.platformCode = decoded.platform_code;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置JWT原始信息
|
||||||
|
ctx.jwtPayload = decoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
systemInit(_noNeedLogin, _noNeedRight, _noNeedLog = '*', _noNeedAuth = '*') {
|
||||||
|
this._noNeedLogin = _noNeedLogin;
|
||||||
|
this._noNeedRight = _noNeedRight;
|
||||||
|
this._noNeedLog = _noNeedLog;
|
||||||
|
this._noNeedAuth = _noNeedAuth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = MainService;
|
||||||
104
app/service/pda.js
Normal file
104
app/service/pda.js
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
const { XMLParser } = require('fast-xml-parser');
|
||||||
|
|
||||||
|
class pdaService extends Service {
|
||||||
|
async callMethod(className, actionName, requestData, authHeader) {
|
||||||
|
try {
|
||||||
|
// 构建服务类路径
|
||||||
|
const servicePath = `${className}`;
|
||||||
|
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];
|
||||||
|
}
|
||||||
|
// 检查服务是否存在
|
||||||
|
if (!systemMethods) {
|
||||||
|
throw new Error(`服务 ${servicePath} 不存在`);
|
||||||
|
}
|
||||||
|
const serviceInstance = systemMethods;
|
||||||
|
|
||||||
|
// 检查方法是否存在
|
||||||
|
if (typeof serviceInstance[actionName] !== 'function') {
|
||||||
|
throw new Error(`方法 ${actionName} 不存在`);
|
||||||
|
}
|
||||||
|
const result = {
|
||||||
|
message: '',
|
||||||
|
status: 401,
|
||||||
|
};
|
||||||
|
// 调用方法
|
||||||
|
const authPass = await serviceInstance.checkAuth(servicePath, actionName, authHeader);
|
||||||
|
const isLog = authPass.isLog;
|
||||||
|
if (authPass.status == 200) {
|
||||||
|
result.data = await serviceInstance[actionName](requestData);
|
||||||
|
console.log(result.data);
|
||||||
|
result.status = 200;
|
||||||
|
|
||||||
|
} else {
|
||||||
|
result.message = authPass.message;
|
||||||
|
result.status = authPass.status;
|
||||||
|
}
|
||||||
|
return { isLog, result };
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
validateParams(params) {
|
||||||
|
const required = [ 'method', 'v', 'timestamp' ];
|
||||||
|
|
||||||
|
for (const field of required) {
|
||||||
|
if (!params[field]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证method格式
|
||||||
|
if (typeof params.method !== 'string' || !params.method.includes('.')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
async saveLog(logData, startTime) {
|
||||||
|
const {
|
||||||
|
ctx,
|
||||||
|
} = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 限制日志内容长度
|
||||||
|
if (logData.body && logData.body.length > 65535) {
|
||||||
|
logData.body = logData.body.substring(0, 65535);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (logData.result && logData.result.length > 65535) {
|
||||||
|
logData.result = logData.result.substring(0, 65535);
|
||||||
|
}
|
||||||
|
|
||||||
|
logData.use_time = Date.now() - startTime;
|
||||||
|
|
||||||
|
// 使用 egg-mysql 保存日志到数据库
|
||||||
|
const result = await ctx.app.mysql.get('wms').insert('wms_system_log', {
|
||||||
|
method: logData.method || '',
|
||||||
|
v: logData.v || '',
|
||||||
|
url: logData.url || '',
|
||||||
|
headers: logData.headers || '',
|
||||||
|
auth: logData.auth || '',
|
||||||
|
created_at: ctx.app.mysql.get('wms').literals.now,
|
||||||
|
body: logData.body || '',
|
||||||
|
result: logData.result || '',
|
||||||
|
use_time: logData.use_time || 0,
|
||||||
|
store_id: logData.store_id || null,
|
||||||
|
device: 'pda',
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('保存日志失败: ' + error.message);
|
||||||
|
// 可以选择记录到文件日志作为备用
|
||||||
|
ctx.logger.info('日志数据: ', JSON.stringify(logData));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = pdaService;
|
||||||
283
app/service/qimen.js
Normal file
283
app/service/qimen.js
Normal file
@ -0,0 +1,283 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
const { XMLParser } = require('fast-xml-parser');
|
||||||
|
|
||||||
|
class QimenService extends Service {
|
||||||
|
/**
|
||||||
|
* 验证接口是否存在且启用
|
||||||
|
* @param appkey
|
||||||
|
* @param customerId
|
||||||
|
* @param warehouseCode
|
||||||
|
*/
|
||||||
|
async validateApi(appkey, customerId, warehouseCode) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { ctx } = this;
|
||||||
|
const result = await this.ctx.service.main.findQimenAppWithContract(appkey, customerId, warehouseCode);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
this.ctx.logger.error('验证接口配置失败: ' + error.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async getErpName(appkey) {
|
||||||
|
const { app } = this;
|
||||||
|
const result = await app.model.QimenApp.findOne({
|
||||||
|
attributes: [
|
||||||
|
'id',
|
||||||
|
'name',
|
||||||
|
],
|
||||||
|
where: {
|
||||||
|
app_key: appkey,
|
||||||
|
},
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
if (result) {
|
||||||
|
return result.name;
|
||||||
|
}
|
||||||
|
return '未知ERP';
|
||||||
|
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 解析XML到数组
|
||||||
|
* @param xmlString
|
||||||
|
*/
|
||||||
|
async parseXmlToArray(xmlString) {
|
||||||
|
const cleanedXml = this.cleanXmlString(xmlString);
|
||||||
|
|
||||||
|
if (!cleanedXml || cleanedXml.trim() === '') {
|
||||||
|
throw new Error('XML数据为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
const parser = new XMLParser({
|
||||||
|
ignoreAttributes: false,
|
||||||
|
attributeNamePrefix: '@_',
|
||||||
|
allowBooleanAttributes: true,
|
||||||
|
// 关闭值解析,保持原始字符串
|
||||||
|
parseTagValue: false,
|
||||||
|
parseAttributeValue: false,
|
||||||
|
trimValues: false, // 也关闭trim,保持原始格式
|
||||||
|
ignoreDeclaration: true,
|
||||||
|
// 添加标签值处理器,手动控制转换
|
||||||
|
tagValueProcessor: (tagName, tagValue, jPath, hasAttributes, isLeafNode) => {
|
||||||
|
// 如果是叶子节点且需要保持字符串格式的标签,可以在这里特殊处理
|
||||||
|
// 默认返回原始值
|
||||||
|
return tagValue;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = parser.parse(cleanedXml);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error('XML解析错误: ' + error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理XML字符串
|
||||||
|
* @param xmlString
|
||||||
|
*/
|
||||||
|
cleanXmlString(xmlString) {
|
||||||
|
if (!xmlString) return '';
|
||||||
|
|
||||||
|
// 移除UTF-8 BOM
|
||||||
|
let cleaned = xmlString.replace(/^\uFEFF/, '');
|
||||||
|
|
||||||
|
// 移除XML声明前面的空白字符
|
||||||
|
cleaned = cleaned.trim();
|
||||||
|
|
||||||
|
// 如果XML声明不在开头,尝试找到并移动到开头
|
||||||
|
const xmlDeclarationMatch = cleaned.match(/<\?xml[^?>]+\?>/);
|
||||||
|
if (xmlDeclarationMatch && cleaned.indexOf(xmlDeclarationMatch[0]) > 0) {
|
||||||
|
const xmlDeclaration = xmlDeclarationMatch[0];
|
||||||
|
// 移除原有的XML声明
|
||||||
|
cleaned = cleaned.replace(/<\?xml[^?>]+\?>/, '');
|
||||||
|
// 将XML声明放到开头
|
||||||
|
cleaned = xmlDeclaration + '\n' + cleaned.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
return cleaned.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调用业务方法
|
||||||
|
* @param className
|
||||||
|
* @param actionName
|
||||||
|
* @param xmlData
|
||||||
|
* @param storeId
|
||||||
|
* @param warehouseId
|
||||||
|
* @param appKey
|
||||||
|
* @param customerId
|
||||||
|
* @param warehouseCode
|
||||||
|
* @param format
|
||||||
|
*/
|
||||||
|
async callMethod(className, actionName, xmlData, storeId, warehouseId, appKey, customerId, warehouseCode, format = 'xml') {
|
||||||
|
try {
|
||||||
|
// 构建服务类路径
|
||||||
|
const servicePath = `${className}`;
|
||||||
|
const classs = servicePath.split('.');
|
||||||
|
let qimenMethods = this.ctx.service.qimenMethods;
|
||||||
|
for (let i = 0; i < classs.length; i++) {
|
||||||
|
const className = classs[i];
|
||||||
|
qimenMethods = qimenMethods[className];
|
||||||
|
}
|
||||||
|
// 检查服务是否存在
|
||||||
|
if (!qimenMethods) {
|
||||||
|
throw new Error(`服务 ${servicePath} 不存在`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const serviceInstance = qimenMethods;
|
||||||
|
|
||||||
|
// 检查方法是否存在
|
||||||
|
if (typeof serviceInstance[actionName] !== 'function') {
|
||||||
|
throw new Error(`方法 ${actionName} 不存在`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调用方法
|
||||||
|
await serviceInstance.setInfo(storeId, warehouseId, appKey, customerId, warehouseCode);
|
||||||
|
const result = await serviceInstance[actionName](xmlData);
|
||||||
|
// 根据format参数返回相应格式
|
||||||
|
return this.formatResponse(result);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化响应
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
formatResponse(data) {
|
||||||
|
return this.xmlResponse(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* XML响应
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
xmlResponse(data) {
|
||||||
|
let xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
|
||||||
|
xml += '<response>\n';
|
||||||
|
|
||||||
|
// 处理固定字段
|
||||||
|
xml += ` <flag>${data.flag || 'failure'}</flag>\n`;
|
||||||
|
xml += ` <code>${data.code || '0'}</code>\n`;
|
||||||
|
xml += ` <message>${this.escapeXml(data.message || '操作成功')}</message>\n`;
|
||||||
|
|
||||||
|
// 添加其他数据字段
|
||||||
|
for (const [ key, value ] of Object.entries(data)) {
|
||||||
|
if (![ 'flag', 'code', 'message' ].includes(key)) {
|
||||||
|
xml += this.buildXmlNode(key, value, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
xml += '</response>';
|
||||||
|
return xml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建XML节点 - 支持多层级
|
||||||
|
* @param key
|
||||||
|
* @param value
|
||||||
|
* @param level
|
||||||
|
*/
|
||||||
|
buildXmlNode(key, value, level = 0) {
|
||||||
|
const indent = ' '.repeat(level);
|
||||||
|
let xml = '';
|
||||||
|
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
// 数字索引数组
|
||||||
|
if (value.every((_, index) => index in value)) {
|
||||||
|
xml += `${indent}<${key}>\n`;
|
||||||
|
value.forEach(item => {
|
||||||
|
if (Array.isArray(item) || typeof item === 'object') {
|
||||||
|
xml += this.buildXmlNode('item', item, level + 1);
|
||||||
|
} else {
|
||||||
|
xml += `${indent} <item>${this.escapeXml(item)}</item>\n`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
xml += `${indent}</${key}>\n`;
|
||||||
|
}
|
||||||
|
} else if (typeof value === 'object' && value !== null) {
|
||||||
|
// 对象
|
||||||
|
xml += `${indent}<${key}>\n`;
|
||||||
|
for (const [ subKey, subValue ] of Object.entries(value)) {
|
||||||
|
xml += this.buildXmlNode(subKey, subValue, level + 1);
|
||||||
|
}
|
||||||
|
xml += `${indent}</${key}>\n`;
|
||||||
|
} else {
|
||||||
|
// 简单值
|
||||||
|
xml += `${indent}<${key}>${this.escapeXml(value)}</${key}>\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return xml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* XML转义
|
||||||
|
* @param unsafe
|
||||||
|
*/
|
||||||
|
escapeXml(unsafe) {
|
||||||
|
if (unsafe === null || unsafe === undefined) return '';
|
||||||
|
const str = String(unsafe);
|
||||||
|
return str.replace(/[<>&'"]/g, c => {
|
||||||
|
switch (c) {
|
||||||
|
case '<': return '<';
|
||||||
|
case '>': return '>';
|
||||||
|
case '&': return '&';
|
||||||
|
case '\'': return ''';
|
||||||
|
case '"': return '"';
|
||||||
|
default: return c;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async saveQimenLog(logData, startTime) {
|
||||||
|
const {
|
||||||
|
ctx,
|
||||||
|
} = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 限制日志内容长度
|
||||||
|
if (logData.body && logData.body.length > 65535) {
|
||||||
|
logData.body = logData.body.substring(0, 65535);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (logData.result && logData.result.length > 65535) {
|
||||||
|
logData.result = logData.result.substring(0, 65535);
|
||||||
|
}
|
||||||
|
|
||||||
|
logData.use_time = Date.now() - startTime;
|
||||||
|
|
||||||
|
// 使用 egg-mysql 保存日志到数据库
|
||||||
|
const result = await ctx.app.mysql.get('wms').insert('wms_qimen_log', {
|
||||||
|
from_key: logData.from_key || '',
|
||||||
|
to_key: logData.to_key || '',
|
||||||
|
method: logData.method || '',
|
||||||
|
sign: logData.sign || '',
|
||||||
|
costomer_id: logData.costomer_id || '',
|
||||||
|
v: logData.v || '',
|
||||||
|
url: logData.url || '',
|
||||||
|
created_at: ctx.app.mysql.get('wms').literals.now,
|
||||||
|
body: logData.body || '',
|
||||||
|
result: logData.result || '',
|
||||||
|
use_time: logData.use_time || 0,
|
||||||
|
});
|
||||||
|
return result.insertId;
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('保存奇门接口日志失败: ' + error.message);
|
||||||
|
// 可以选择记录到文件日志作为备用
|
||||||
|
ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async saveQimenLogResult(result) {
|
||||||
|
await this.ctx.app.mysql.get('wms').update('wms_qimen_log', { result, id: this.ctx.qimenLogId });
|
||||||
|
}
|
||||||
|
async saveQimenLogBody(body) {
|
||||||
|
await this.ctx.app.mysql.get('wms').update('wms_qimen_log', { body, id: this.ctx.qimenLogId });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = QimenService;
|
||||||
47
app/service/qimenMethods/deliveryorder.js
Normal file
47
app/service/qimenMethods/deliveryorder.js
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class deliveryorderServer extends MainService {
|
||||||
|
async query(data) {
|
||||||
|
const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(this.warehouseId);
|
||||||
|
const hisDeliveryModel = await this.ctx.model.OrderDeliveryFactory.getHistoryModel(this.warehouseId);
|
||||||
|
const order = await DeliveryModel.findOne({ where: { delivery_order_code: data.request.orderCode } });
|
||||||
|
const totalLines = 0;
|
||||||
|
if (order) {
|
||||||
|
return this.success('成功', {
|
||||||
|
totalLines,
|
||||||
|
deliveryOrder: {
|
||||||
|
deliveryOrderCode: order.delivery_order_code,
|
||||||
|
deliveryOrderId: order.delivery_order_code,
|
||||||
|
warehouseCode: order.warehouse_code,
|
||||||
|
orderType: order.order_type,
|
||||||
|
status: order.status,
|
||||||
|
orderConfirmTime: order.order_confirm_time,
|
||||||
|
operatorCode: 0,
|
||||||
|
operatorName: '',
|
||||||
|
operateTime: order.update_at,
|
||||||
|
},
|
||||||
|
packages: {
|
||||||
|
package: {},
|
||||||
|
},
|
||||||
|
orderLines: [],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return this.fail('未找到订单');
|
||||||
|
|
||||||
|
}
|
||||||
|
async create(data) {
|
||||||
|
const info = this.getInfo;
|
||||||
|
const res = await this.ctx.service.systems.deliveryOrder.addOrder(data, this.getInfo(), 'QM');
|
||||||
|
if (res.success) {
|
||||||
|
return this.success(res.message, { createTime: new Date().format(), deliveryOrderId: res.data.deliveryOrderId, warehouseCode: info.warehouseCode, logisticsCode: res.data.logisticsCode });
|
||||||
|
}
|
||||||
|
return this.fail(res.message, { createTime: new Date().format() });
|
||||||
|
|
||||||
|
}
|
||||||
|
async batchcreate() {
|
||||||
|
return this.fail('批量创建接口未完善');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = deliveryorderServer;
|
||||||
23
app/service/qimenMethods/entryorder.js
Normal file
23
app/service/qimenMethods/entryorder.js
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class entryorderServer extends MainService {
|
||||||
|
async create(data) {
|
||||||
|
const info = this.getInfo;
|
||||||
|
const res = await this.ctx.service.systems.entryOrder.addOrder(data, this.getInfo(), 'QM');
|
||||||
|
|
||||||
|
console.log('创建入库单返回', res);
|
||||||
|
if (res.success) {
|
||||||
|
return this.success(res.message, { createTime: new Date().format(), entryOrderId: res.data.entryOrderId });
|
||||||
|
}
|
||||||
|
return this.fail(res.message, { createTime: new Date().format() });
|
||||||
|
|
||||||
|
}
|
||||||
|
async query(data) {
|
||||||
|
console.log(data);
|
||||||
|
return this.fail('接口未完善');
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
module.exports = entryorderServer;
|
||||||
30
app/service/qimenMethods/inventory.js
Normal file
30
app/service/qimenMethods/inventory.js
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class inventoryServer extends MainService {
|
||||||
|
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
}
|
||||||
|
async query(data) {
|
||||||
|
const criteria = data.request.criteriaList.criteria;
|
||||||
|
const list = criteria.warehouseCode ? [ criteria ] : criteria;
|
||||||
|
const list2 = [];
|
||||||
|
for (let i = 0; i < list.length; i++) {
|
||||||
|
const info = await this.ctx.service.systems.stockStore.getItemStorages(list[i].itemId);
|
||||||
|
if (info.success) {
|
||||||
|
list2.push({
|
||||||
|
warehouseCode: info.data.stock.warehouse_code,
|
||||||
|
itemCode: info.data.stock.item_code,
|
||||||
|
itemId: info.data.stock.id,
|
||||||
|
quantity: info.data.storage.quantity - info.data.storage.lockedQuantity,
|
||||||
|
lockQuantity: info.data.storage.lockedQuantity,
|
||||||
|
inventoryType: 'ZP',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.success('库存信息抓取成功', { items: list2 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = inventoryServer;
|
||||||
153
app/service/qimenMethods/order.js
Normal file
153
app/service/qimenMethods/order.js
Normal file
@ -0,0 +1,153 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class orderServer extends MainService {
|
||||||
|
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
// 初始化公共变量
|
||||||
|
this.orderType = {
|
||||||
|
JYCK: {
|
||||||
|
method: 'ORDER',
|
||||||
|
name: '一般交易出库单',
|
||||||
|
},
|
||||||
|
HHCK: {
|
||||||
|
method: 'ORDER',
|
||||||
|
name: '换货出库',
|
||||||
|
},
|
||||||
|
BFCK: {
|
||||||
|
method: 'ORDER',
|
||||||
|
name: '补发出库',
|
||||||
|
},
|
||||||
|
PTCK: {
|
||||||
|
method: 'CK',
|
||||||
|
name: '普通出库单',
|
||||||
|
},
|
||||||
|
DBCK: {
|
||||||
|
method: 'CK',
|
||||||
|
name: '调拨出库',
|
||||||
|
},
|
||||||
|
B2BCK: {
|
||||||
|
method: 'CK',
|
||||||
|
name: 'B2B出库',
|
||||||
|
},
|
||||||
|
QTCK: {
|
||||||
|
method: 'CK',
|
||||||
|
name: '其他出库',
|
||||||
|
},
|
||||||
|
CGTH: {
|
||||||
|
method: 'CK',
|
||||||
|
name: '采购退货出库单',
|
||||||
|
},
|
||||||
|
B2BRK: {
|
||||||
|
method: 'RK',
|
||||||
|
name: 'B2B入库',
|
||||||
|
},
|
||||||
|
SCRK: {
|
||||||
|
method: 'RK',
|
||||||
|
name: '生产入库',
|
||||||
|
},
|
||||||
|
LYRK: {
|
||||||
|
method: 'RK',
|
||||||
|
name: '领用入库',
|
||||||
|
},
|
||||||
|
CCRK: {
|
||||||
|
method: 'RK',
|
||||||
|
name: '残次品入库',
|
||||||
|
},
|
||||||
|
CGRK: {
|
||||||
|
method: 'RK',
|
||||||
|
name: '采购入库',
|
||||||
|
},
|
||||||
|
DBRK: {
|
||||||
|
method: 'RK',
|
||||||
|
name: '调拨入库',
|
||||||
|
},
|
||||||
|
QTRK: {
|
||||||
|
method: 'RK',
|
||||||
|
name: '其他入库',
|
||||||
|
},
|
||||||
|
XTRK: {
|
||||||
|
method: 'BACKORDER',
|
||||||
|
name: '销退入库',
|
||||||
|
},
|
||||||
|
THRK: {
|
||||||
|
method: 'BACKORDER',
|
||||||
|
name: '退货入库',
|
||||||
|
},
|
||||||
|
HHRK: {
|
||||||
|
method: 'BACKORDER',
|
||||||
|
name: '换货入库',
|
||||||
|
},
|
||||||
|
CNJG: {
|
||||||
|
method: 'JG',
|
||||||
|
name: '仓内加工单',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async cancel(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const info = this.getInfo();
|
||||||
|
const orderType = this.orderType[data.request.orderType];
|
||||||
|
switch (orderType.method) {
|
||||||
|
case 'ORDER':
|
||||||
|
return this.success('取消订单成功');
|
||||||
|
break;
|
||||||
|
case 'RK' :
|
||||||
|
console.log(data, info);
|
||||||
|
const existingOrder = await ctx.model.EntryOrder.findOne({
|
||||||
|
where: {
|
||||||
|
entry_order_code: data.request.orderCode,
|
||||||
|
warehouse_id: info.warehouseId,
|
||||||
|
store_id: info.storeId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (existingOrder) {
|
||||||
|
await existingOrder.update({
|
||||||
|
order_status: 'CANCELLED',
|
||||||
|
updated_at: new Date(),
|
||||||
|
});
|
||||||
|
return this.success('取消入库单成功');
|
||||||
|
}
|
||||||
|
return this.fail('未找到对应的入库单');
|
||||||
|
break;
|
||||||
|
case 'CK' :
|
||||||
|
return this.fail('取消出库单未开发完成');
|
||||||
|
break;
|
||||||
|
case 'JG' :
|
||||||
|
return this.fail('取消加工单未开发完成');
|
||||||
|
break;
|
||||||
|
case 'BACKORDER':
|
||||||
|
return this.fail('取消退货单未开发完成');
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return this.fail(`未识别的作业类型${orderType.method}`, {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async pending(data) {
|
||||||
|
console.log(data);
|
||||||
|
const orderType = this.orderType[data.request.orderType];
|
||||||
|
switch (orderType.method) {
|
||||||
|
case 'ORDER':
|
||||||
|
return this.fail('锁定订单未开发完成');
|
||||||
|
break;
|
||||||
|
case 'RK' :
|
||||||
|
return this.fail('锁定入库单未开发完成');
|
||||||
|
break;
|
||||||
|
case 'CK' :
|
||||||
|
return this.fail('锁定出库单未开发完成');
|
||||||
|
break;
|
||||||
|
case 'JG' :
|
||||||
|
return this.fail('锁定加工单未开发完成');
|
||||||
|
break;
|
||||||
|
case 'BACKORDER':
|
||||||
|
return this.fail('锁定退货单未开发完成');
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return this.fail(`未识别的作业类型${orderType.method}`, {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = orderServer;
|
||||||
19
app/service/qimenMethods/returnorder.js
Normal file
19
app/service/qimenMethods/returnorder.js
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class returnorderServer extends MainService {
|
||||||
|
/*
|
||||||
|
退货入库创建接口
|
||||||
|
*/
|
||||||
|
async create(data) {
|
||||||
|
return this.fail('接口未完善', { result: 'singleitemServer', storeId: this.storeId });
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
退货入库查询接口
|
||||||
|
*/
|
||||||
|
async query(data) {
|
||||||
|
return this.fail('接口未完善', { result: 'singleitemServer', storeId: this.storeId });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = returnorderServer;
|
||||||
36
app/service/qimenMethods/singleitem.js
Normal file
36
app/service/qimenMethods/singleitem.js
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class singleitemServer extends MainService {
|
||||||
|
async synchronize(data) {
|
||||||
|
const { app } = this;
|
||||||
|
try {
|
||||||
|
console.log('data', data);
|
||||||
|
const stockData = await this.ctx.service.systems.stockStore.initQimenStockData(data.request, this.appKey, this.storeId, this.warehouseId);
|
||||||
|
console.log('stockData', stockData);
|
||||||
|
const result = await await this.ctx.service.systems.stockStore.create(stockData);
|
||||||
|
return this.success('同步完成', { itemId: result.id });
|
||||||
|
} catch (error) {
|
||||||
|
return this.fail('同步失败', { error: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async query(data) {
|
||||||
|
const { app } = this;
|
||||||
|
try {
|
||||||
|
if (!data.request.itemId) {
|
||||||
|
return this.fail('获取失败', { error: '参数错误itemId不存在' });
|
||||||
|
}
|
||||||
|
const Row = await app.model.StockStore.findByPk(data.request.itemId);
|
||||||
|
if (!Row) {
|
||||||
|
return this.fail('获取失败', { error: `wms的SKUID为${data.request.itemId}未找到` });
|
||||||
|
}
|
||||||
|
const result = await this.ctx.service.systems.stockStore.convertToQimenFormat(Row);
|
||||||
|
return this.success('获取成功', result);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取失败:', error);
|
||||||
|
return this.fail('获取失败', { error: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = singleitemServer;
|
||||||
72
app/service/qimenMethods/stockout.js
Normal file
72
app/service/qimenMethods/stockout.js
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class stockoutServer extends MainService {
|
||||||
|
|
||||||
|
async create(data) {
|
||||||
|
const { app } = this;
|
||||||
|
|
||||||
|
let totalOrderLines = data.request.deliveryOrder.totalOrderLines || 0;
|
||||||
|
|
||||||
|
let orderLine = data.request.orderLines.orderLine;
|
||||||
|
if (orderLine.orderLineNo) {
|
||||||
|
orderLine = [ orderLine ];
|
||||||
|
}
|
||||||
|
const isSingle = totalOrderLines ? 0 : 1;
|
||||||
|
totalOrderLines = totalOrderLines || orderLine.length;
|
||||||
|
const errors = [];
|
||||||
|
const items = [];
|
||||||
|
for (let i = 0; i < orderLine.length; i++) {
|
||||||
|
const wms_stock = await app.model.StockStore.findByPk(orderLine[i].itemId);
|
||||||
|
if (!wms_stock) {
|
||||||
|
errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》\n未同步推送到仓库`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!wms_stock.stock_id) {
|
||||||
|
errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》wms无对应关系\n请联系仓库关联创建商品`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
wms_stock.inventory_type = orderLine[i].inventoryType;
|
||||||
|
wms_stock.order_line_no = orderLine[i].orderLineNo;
|
||||||
|
wms_stock.count = orderLine[i].planQty;
|
||||||
|
wms_stock.item_id = orderLine[i].itemId;
|
||||||
|
items.push(wms_stock);
|
||||||
|
}
|
||||||
|
console.log('出库单参数:', data.request.deliveryOrder, this.appKey, this.storeId, this.warehouseId, totalOrderLines, 'QM', this.customerId, this.warehouseCode);
|
||||||
|
console.log('出库单明细:', items);
|
||||||
|
if (errors.length > 0) {
|
||||||
|
return this.fail('创建入库单失败,失败原因:\n' + errors.join('\n'));
|
||||||
|
}
|
||||||
|
/* const order = await this.ctx.service.systems.deliveryOrder.tryCreatedeliveryOrder(data.request.deliveryOrder,this.appKey, this.storeId, this.warehouseId,totalOrderLines,"QM",this.customerId,this.warehouseCode);
|
||||||
|
console.log("入库单参数",order);
|
||||||
|
if(!order.success){
|
||||||
|
return this.fail("创建入库单失败,失败原因:\n"+order.error);
|
||||||
|
}
|
||||||
|
const orderId = order.deliveryOrderId;
|
||||||
|
for (var i = 0; i < items.length; i++) {
|
||||||
|
const item = items[i];
|
||||||
|
let res = await this.ctx.service.systems.deliveryOrder.addItems(item,orderId);
|
||||||
|
console.log("“添加商品返回信息",res);
|
||||||
|
if(!res.success){
|
||||||
|
errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(errors.length>0){
|
||||||
|
await app.model.deliveryOrder.delete(orderId);//失败删除;
|
||||||
|
return this.fail("创建入库单失败,失败原因:\n"+errors.join("\n"));
|
||||||
|
}
|
||||||
|
const lineCount = await this.ctx.service.systems.deliveryOrder.getLineCount(orderId);//获取接收行数
|
||||||
|
if(lineCount==totalOrderLines){//所有行数接收完成
|
||||||
|
await this.ctx.service.systems.deliveryOrder.received(orderId,this.warehouseId,this.storeId);//接收完成
|
||||||
|
return this.success("入库单接收完毕",{deliveryOrderId:orderId});
|
||||||
|
}*/
|
||||||
|
return this.success('入库单接收中');
|
||||||
|
}
|
||||||
|
async query(data) {
|
||||||
|
console.log(data);
|
||||||
|
return this.fail('接口未完善');
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
module.exports = stockoutServer;
|
||||||
15
app/service/qimenMethods/taobao/qimen/service.js
Normal file
15
app/service/qimenMethods/taobao/qimen/service.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require(`${APP_ROOT}/app/service/main`);
|
||||||
|
|
||||||
|
class serviceServer extends MainService {
|
||||||
|
async heartbeat(data) {
|
||||||
|
console.log(data);
|
||||||
|
if (data?.request?.serialNumber) {
|
||||||
|
return this.success(new Date().format(), { code: data.request.serialNumber });
|
||||||
|
}
|
||||||
|
return this.fail(new Date().format(), { code: 0 });
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = serviceServer;
|
||||||
108
app/service/system.js
Normal file
108
app/service/system.js
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
const { XMLParser } = require('fast-xml-parser');
|
||||||
|
|
||||||
|
class systemService extends Service {
|
||||||
|
async callMethod(className, actionName, requestData, authHeader) {
|
||||||
|
try {
|
||||||
|
|
||||||
|
|
||||||
|
// 构建服务类路径
|
||||||
|
const servicePath = `${className}`;
|
||||||
|
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];
|
||||||
|
}
|
||||||
|
// 检查服务是否存在
|
||||||
|
if (!systemMethods) {
|
||||||
|
throw new Error(`服务 ${servicePath} 不存在`);
|
||||||
|
}else{
|
||||||
|
console.log(`调用服务: ${servicePath}, 方法: ${actionName}`);
|
||||||
|
}
|
||||||
|
const serviceInstance = systemMethods;
|
||||||
|
|
||||||
|
// 检查方法是否存在
|
||||||
|
if (typeof serviceInstance[actionName] !== 'function') {
|
||||||
|
throw new Error(`方法 ${actionName} 不存在`);
|
||||||
|
}
|
||||||
|
const result = {
|
||||||
|
message: '',
|
||||||
|
status: 401,
|
||||||
|
};
|
||||||
|
// 调用方法
|
||||||
|
const authPass = await serviceInstance.checkAuth(servicePath, actionName, authHeader);
|
||||||
|
const isLog = authPass.isLog;
|
||||||
|
if (authPass.status == 200) {
|
||||||
|
result.data = await serviceInstance[actionName](requestData);
|
||||||
|
console.log(result.data);
|
||||||
|
result.status = 200;
|
||||||
|
|
||||||
|
} else {
|
||||||
|
result.message = authPass.message;
|
||||||
|
result.status = authPass.status;
|
||||||
|
}
|
||||||
|
return { isLog, result };
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
validateParams(params) {
|
||||||
|
const required = [ 'method', 'v', 'timestamp' ];
|
||||||
|
|
||||||
|
for (const field of required) {
|
||||||
|
if (!params[field]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证method格式
|
||||||
|
if (typeof params.method !== 'string' || !params.method.includes('.')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
async saveLog(logData, startTime) {
|
||||||
|
const {
|
||||||
|
ctx,
|
||||||
|
} = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 限制日志内容长度
|
||||||
|
if (logData.body && logData.body.length > 65535) {
|
||||||
|
logData.body = logData.body.substring(0, 65535);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (logData.result && logData.result.length > 65535) {
|
||||||
|
logData.result = logData.result.substring(0, 65535);
|
||||||
|
}
|
||||||
|
|
||||||
|
logData.use_time = Date.now() - startTime;
|
||||||
|
|
||||||
|
// 使用 egg-mysql 保存日志到数据库
|
||||||
|
const result = await ctx.app.mysql.get('wms').insert('wms_system_log', {
|
||||||
|
method: logData.method || '',
|
||||||
|
v: logData.v || '',
|
||||||
|
url: logData.url || '',
|
||||||
|
headers: logData.headers || '',
|
||||||
|
auth: logData.auth || '',
|
||||||
|
created_at: ctx.app.mysql.get('wms').literals.now,
|
||||||
|
body: logData.body || '',
|
||||||
|
result: logData.result || '',
|
||||||
|
use_time: logData.use_time || 0,
|
||||||
|
store_id: logData.store_id || null,
|
||||||
|
device: ctx.header.platform,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('保存奇门接口日志失败: ' + error.message);
|
||||||
|
// 可以选择记录到文件日志作为备用
|
||||||
|
ctx.logger.info('奇门接口日志数据: ', JSON.stringify(logData));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = systemService;
|
||||||
25
app/service/systemMethods/config.js
Normal file
25
app/service/systemMethods/config.js
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class configService extends MainService {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
const _noNeedLogin = '';
|
||||||
|
const _noNeedRight = '*';
|
||||||
|
this.systemInit(_noNeedLogin, _noNeedRight);
|
||||||
|
}
|
||||||
|
async list() {
|
||||||
|
const {
|
||||||
|
ctx,
|
||||||
|
app,
|
||||||
|
} = this;
|
||||||
|
const user = ctx.user;
|
||||||
|
const result = {
|
||||||
|
data: user,
|
||||||
|
code: 200,
|
||||||
|
};
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = configService;
|
||||||
340
app/service/systemMethods/dashboard.js
Normal file
340
app/service/systemMethods/dashboard.js
Normal file
@ -0,0 +1,340 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class dashboardService extends MainService {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
const _noNeedLogin = '';
|
||||||
|
const _noNeedRight = '*';
|
||||||
|
const _noNeedLog = '*';
|
||||||
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog);
|
||||||
|
}
|
||||||
|
async storeStats() {
|
||||||
|
const data = {
|
||||||
|
code: 200,
|
||||||
|
message: '成功',
|
||||||
|
data: {
|
||||||
|
todayOrders: 13023,
|
||||||
|
orderTrend: 2,
|
||||||
|
|
||||||
|
// 处理状态
|
||||||
|
unassignedOrders: 15, // 未分配快递号
|
||||||
|
unprintedOrders: 32, // 未打印
|
||||||
|
unpickedOrders: 28, // 未拣货
|
||||||
|
|
||||||
|
// 发货相关
|
||||||
|
pendingShipments: 6542, // 待发货
|
||||||
|
shipmentProgress: 0, // 发货进度
|
||||||
|
|
||||||
|
// 出库相关
|
||||||
|
todayOutbound: 6480, // 今日出库
|
||||||
|
outboundRate: 49.77, // 出库完成率
|
||||||
|
|
||||||
|
// 异常订单
|
||||||
|
interceptedOrders: 8, // 拦截订单
|
||||||
|
exceptionOrders: 10, // 异常订单
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return this.success('ok', data);
|
||||||
|
}
|
||||||
|
async warehouseStats() {
|
||||||
|
const data = {
|
||||||
|
code: 200,
|
||||||
|
message: '成功',
|
||||||
|
data: {
|
||||||
|
todayOrders: 153023, // 今日订单数(基准)
|
||||||
|
orderTrend: 3, // 较昨日增长3%
|
||||||
|
|
||||||
|
// 处理状态(按百分比计算)
|
||||||
|
unassignedOrders: 3060, // 未分配快递号(占2%)
|
||||||
|
unprintedOrders: 4591, // 未打印(占3%)
|
||||||
|
unpickedOrders: 7651, // 未拣货(占5%)
|
||||||
|
|
||||||
|
// 发货相关
|
||||||
|
pendingShipments: 45907, // 待发货(占30%)
|
||||||
|
shipmentProgress: 70, // 发货进度70%
|
||||||
|
|
||||||
|
// 出库相关
|
||||||
|
todayOutbound: 107116, // 今日出库(占70%)
|
||||||
|
outboundRate: 70, // 出库完成率70%
|
||||||
|
|
||||||
|
// 异常订单(按比例)
|
||||||
|
interceptedOrders: 306, // 拦截订单(占0.2%)
|
||||||
|
exceptionOrders: 1530, // 异常订单(占1%)
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return this.success('ok', data);
|
||||||
|
}
|
||||||
|
async hot_order_rank() {
|
||||||
|
const data = {
|
||||||
|
code: 200,
|
||||||
|
message: '成功',
|
||||||
|
data: [{
|
||||||
|
id: 1,
|
||||||
|
name: '新***盒1',
|
||||||
|
sku: 'SKU202510081',
|
||||||
|
value: 51516,
|
||||||
|
trend: 18.5,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
name: '天***g',
|
||||||
|
sku: 'SKU202401002',
|
||||||
|
value: 43132,
|
||||||
|
trend: 12.3,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 3,
|
||||||
|
name: '定****l',
|
||||||
|
sku: 'SKU202401003',
|
||||||
|
value: 39098,
|
||||||
|
trend: -2.5,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 4,
|
||||||
|
name: '奥*****膜',
|
||||||
|
sku: 'SKU202401004',
|
||||||
|
value: 39087,
|
||||||
|
trend: 8.7,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 5,
|
||||||
|
name: '美*****液',
|
||||||
|
sku: 'SKU202401005',
|
||||||
|
value: 25776,
|
||||||
|
trend: 15.2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 6,
|
||||||
|
name: '荣耀Magic6 Pro 1TB',
|
||||||
|
sku: 'SKU202401006',
|
||||||
|
value: 65,
|
||||||
|
trend: 5.4,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 7,
|
||||||
|
name: '三星Galaxy S24 Ultra 512GB',
|
||||||
|
sku: 'SKU202401007',
|
||||||
|
value: 54,
|
||||||
|
trend: -3.8,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 8,
|
||||||
|
name: '一加12 512GB',
|
||||||
|
sku: 'SKU202401008',
|
||||||
|
value: 43,
|
||||||
|
trend: 22.1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 9,
|
||||||
|
name: '真我GT5 Pro 1TB',
|
||||||
|
sku: 'SKU202401009',
|
||||||
|
value: 38,
|
||||||
|
trend: 9.6,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 10,
|
||||||
|
name: '魅族21 Pro 512GB',
|
||||||
|
sku: 'SKU202401010',
|
||||||
|
value: 29,
|
||||||
|
trend: 4.2,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
return this.success('ok', data);
|
||||||
|
}
|
||||||
|
async express_ratio() {
|
||||||
|
const data = {
|
||||||
|
code: 200,
|
||||||
|
message: '成功',
|
||||||
|
data: [{
|
||||||
|
name: '顺丰速运',
|
||||||
|
value: 50250,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#409EFF',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '中通快递',
|
||||||
|
value: 34089,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#67C23A',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '圆通速递',
|
||||||
|
value: 10567,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#E6A23C',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '韵达快递',
|
||||||
|
value: 9023,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#909399',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '申通快递',
|
||||||
|
value: 8089,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#67023A',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '邮政EMS',
|
||||||
|
value: 4089,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#97293A',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '京东物流',
|
||||||
|
value: 3023,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#F56C6C',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '极兔速递',
|
||||||
|
value: 1089,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#67913A',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '德邦快递',
|
||||||
|
value: 357,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#9370DB',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '其他快递',
|
||||||
|
value: 5,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#67313A',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
return this.success('ok', data);
|
||||||
|
}
|
||||||
|
async platform_distribution() {
|
||||||
|
const data = {
|
||||||
|
code: 200,
|
||||||
|
message: '成功',
|
||||||
|
data: [{
|
||||||
|
name: '抖音',
|
||||||
|
value: 50250,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#409EFF',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '拼多多',
|
||||||
|
value: 34089,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#67C23A',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '小红书',
|
||||||
|
value: 8089,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#67023A',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '淘宝',
|
||||||
|
value: 10567,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#E6A23C',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '快手',
|
||||||
|
value: 9023,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#909399',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '天猫',
|
||||||
|
value: 4089,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#97293A',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '视频号',
|
||||||
|
value: 3023,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#606399',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '阿里巴巴',
|
||||||
|
value: 1089,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#67913A',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '其他',
|
||||||
|
value: 357,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#9370DB',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'TITOK',
|
||||||
|
value: 55,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#17313A',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '京东',
|
||||||
|
value: 45,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#F56C6C',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '德物',
|
||||||
|
value: 5,
|
||||||
|
itemStyle: {
|
||||||
|
color: '#67313A',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
return this.success('ok', data);
|
||||||
|
}
|
||||||
|
async order_trend() {
|
||||||
|
const data = {
|
||||||
|
code: 200,
|
||||||
|
message: '成功',
|
||||||
|
data: {
|
||||||
|
range: 'day',
|
||||||
|
date: '2024-01-15',
|
||||||
|
summary: {
|
||||||
|
total_orders: 1256,
|
||||||
|
total_shipments: 892,
|
||||||
|
shipment_rate: 71.0,
|
||||||
|
peak_hour: '15:00',
|
||||||
|
peak_orders: 178,
|
||||||
|
},
|
||||||
|
categories: [ '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00' ],
|
||||||
|
orders: [ 138, 84378, 102120, 129156, 153020, 153020, 153020, 153020, 153020, 153020 ],
|
||||||
|
shipments: [ 0, 30000, 60000, 70000, 86479, 86479, 86479, 86479, 86479, 86479 ],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return this.success('ok', data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = dashboardService;
|
||||||
426
app/service/systemMethods/index.js
Normal file
426
app/service/systemMethods/index.js
Normal file
@ -0,0 +1,426 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class indexService extends MainService {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
const _noNeedLogin = 'getI18nMessage,putI18nCollect';
|
||||||
|
const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace';
|
||||||
|
const _noNeedLog = '*';
|
||||||
|
const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace';
|
||||||
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
|
}
|
||||||
|
async fastWhereTree(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const { type } = data;
|
||||||
|
const result = await service.systems.fastWhere.getTreeByType(type);
|
||||||
|
return this.success('ok', { presetTree: result, code: 200 });
|
||||||
|
}
|
||||||
|
async loadStores(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.store.loadStores();
|
||||||
|
return this.success('ok', { stores: result, code: 200 });
|
||||||
|
}
|
||||||
|
async getCOSUploadConfig(datas) {
|
||||||
|
const { service } = this;
|
||||||
|
const { data } = datas;
|
||||||
|
const result = await service.systems.upload.getUploadParams(data);
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
}
|
||||||
|
async getImages(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.file.getImages(data);
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
}
|
||||||
|
async uploadSuccessNotify(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.upload.uploadSuccessNotify(data);
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
}
|
||||||
|
async ReferenceFile(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.file.ReferenceFile(data);
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
}
|
||||||
|
async getMessageDetail(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.operationLog.getMessageDetail(data);
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// app/controller/i18n.js 中
|
||||||
|
async getI18nMessage(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { language = 'zh-CN' } = data || ctx.query;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 直接查询表数据看看
|
||||||
|
const allTranslations = await ctx.model.I18nTranslation.findAll({
|
||||||
|
limit: 5,
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
console.log('📊 数据库翻译表数据(前5条):', allTranslations);
|
||||||
|
|
||||||
|
const allKeys = await ctx.model.I18nKey.findAll({
|
||||||
|
limit: 5,
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
console.log('📊 数据库键值表数据(前5条):', allKeys);
|
||||||
|
|
||||||
|
// 2. 检查关联查询
|
||||||
|
const testQuery = await ctx.model.I18nTranslation.findAll({
|
||||||
|
include: [{
|
||||||
|
model: ctx.model.I18nKey,
|
||||||
|
as: 'key',
|
||||||
|
required: false, // LEFT JOIN
|
||||||
|
}],
|
||||||
|
limit: 5,
|
||||||
|
raw: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('🔍 关联查询结果:', testQuery.length);
|
||||||
|
testQuery.forEach((item, index) => {
|
||||||
|
console.log(`结果${index + 1}:`, {
|
||||||
|
id: item.id,
|
||||||
|
language: item.language,
|
||||||
|
translation: item.translation,
|
||||||
|
hasKey: !!item.key,
|
||||||
|
keyName: item.key?.key_name,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 3. 按语言查询
|
||||||
|
const languageQuery = await ctx.model.I18nTranslation.findAll({
|
||||||
|
where: { language },
|
||||||
|
include: [{
|
||||||
|
model: ctx.model.I18nKey,
|
||||||
|
as: 'key',
|
||||||
|
}],
|
||||||
|
raw: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`🌍 语言 ${language} 的翻译数量:`, languageQuery.length);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ 数据库查询错误:', error);
|
||||||
|
ctx.logger.error('数据库查询错误:', error);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// 1. 查询当前项目的所有翻译(默认项目为 'wms')
|
||||||
|
const translations = await ctx.model.I18nTranslation.findAll({
|
||||||
|
include: [{
|
||||||
|
model: ctx.model.I18nKey,
|
||||||
|
as: 'key',
|
||||||
|
where: {
|
||||||
|
project: 'wms',
|
||||||
|
},
|
||||||
|
attributes: [ 'key_name' ],
|
||||||
|
}],
|
||||||
|
where: {
|
||||||
|
language,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. 构建嵌套结构的翻译对象
|
||||||
|
const result = {};
|
||||||
|
translations.forEach(item => {
|
||||||
|
if (item.key && item.key.key_name) {
|
||||||
|
const keys = item.key.key_name.split('.');
|
||||||
|
let current = result;
|
||||||
|
|
||||||
|
// 构建嵌套路径
|
||||||
|
for (let i = 0; i < keys.length - 1; i++) {
|
||||||
|
const key = keys[i];
|
||||||
|
if (!current[key]) {
|
||||||
|
current[key] = {};
|
||||||
|
}
|
||||||
|
current = current[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置翻译值
|
||||||
|
const lastKey = keys[keys.length - 1];
|
||||||
|
current[lastKey] = item.translation || item.key.key_name;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 3. 获取统计信息
|
||||||
|
const totalKeys = await ctx.model.I18nKey.count({
|
||||||
|
where: { project: 'wms' },
|
||||||
|
});
|
||||||
|
|
||||||
|
const translatedCount = await ctx.model.I18nTranslation.count({
|
||||||
|
include: [{
|
||||||
|
model: ctx.model.I18nKey,
|
||||||
|
as: 'key',
|
||||||
|
where: { project: 'wms' },
|
||||||
|
}],
|
||||||
|
where: {
|
||||||
|
language,
|
||||||
|
translation: { [ctx.app.Sequelize.Op.ne]: null }, // 非空
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.success('ok', {
|
||||||
|
data: {
|
||||||
|
success: true,
|
||||||
|
messages: result,
|
||||||
|
stats: {
|
||||||
|
language,
|
||||||
|
total: totalKeys,
|
||||||
|
translated: translatedCount,
|
||||||
|
untranslated: totalKeys - translatedCount,
|
||||||
|
progress: totalKeys > 0 ? Math.round((translatedCount / totalKeys) * 100) : 0,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
code: 200,
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('获取翻译失败:', error);
|
||||||
|
// 失败时返回空结果
|
||||||
|
return this.success('ok', {
|
||||||
|
data: {
|
||||||
|
success: true,
|
||||||
|
messages: {},
|
||||||
|
stats: {
|
||||||
|
language,
|
||||||
|
total: 0,
|
||||||
|
translated: 0,
|
||||||
|
untranslated: 0,
|
||||||
|
progress: 0,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
code: 200,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async putI18nCollect(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { keys = [], locale = 'zh-CN', project = 'wms', source = 'frontend-auto' } = data || ctx.request.body;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = {
|
||||||
|
processed: 0,
|
||||||
|
createdKeys: 0,
|
||||||
|
createdTranslations: 0,
|
||||||
|
updatedKeys: 0,
|
||||||
|
details: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const keyData of keys) {
|
||||||
|
const { key, value, context, timestamp } = keyData;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 查找或创建键值记录
|
||||||
|
let keyRecord = await ctx.model.I18nKey.findOne({
|
||||||
|
where: { key_name: key, project },
|
||||||
|
});
|
||||||
|
|
||||||
|
let keyAction = 'exists';
|
||||||
|
|
||||||
|
if (!keyRecord) {
|
||||||
|
// 创建新键值
|
||||||
|
keyRecord = await ctx.model.I18nKey.create({
|
||||||
|
key_name: key,
|
||||||
|
project,
|
||||||
|
module: this.extractModule(key),
|
||||||
|
description: context ? JSON.stringify(context) : null,
|
||||||
|
status: 1,
|
||||||
|
created_by: source,
|
||||||
|
});
|
||||||
|
keyAction = 'created';
|
||||||
|
result.createdKeys++;
|
||||||
|
} else {
|
||||||
|
// 更新使用次数(可以添加一个 usage_count 字段)
|
||||||
|
keyRecord.updated_at = new Date();
|
||||||
|
await keyRecord.save();
|
||||||
|
keyAction = 'updated';
|
||||||
|
result.updatedKeys++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 创建或更新翻译记录
|
||||||
|
let translation = await ctx.model.I18nTranslation.findOne({
|
||||||
|
where: { key_id: keyRecord.id, language: locale },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!translation) {
|
||||||
|
// 创建翻译记录(默认未翻译)
|
||||||
|
translation = await ctx.model.I18nTranslation.create({
|
||||||
|
key_id: keyRecord.id,
|
||||||
|
language: locale,
|
||||||
|
translation: value || null, // 如果有值就保存,否则null
|
||||||
|
translation_status: value ? 1 : 0, // 有值设为待审核,没有就是未翻译
|
||||||
|
auto_generated: source.includes('auto') ? 1 : 0,
|
||||||
|
translator: source,
|
||||||
|
created_at: new Date(timestamp || Date.now()),
|
||||||
|
});
|
||||||
|
result.createdTranslations++;
|
||||||
|
} else if (value && !translation.translation) {
|
||||||
|
// 如果已有记录但没有翻译,现在有值了就更新
|
||||||
|
translation.translation = value;
|
||||||
|
translation.translation_status = 1; // 设为待审核
|
||||||
|
translation.updated_at = new Date();
|
||||||
|
await translation.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
result.details.push({
|
||||||
|
key,
|
||||||
|
keyId: keyRecord.id,
|
||||||
|
keyAction,
|
||||||
|
translationExists: !!translation,
|
||||||
|
translationValue: translation?.translation || null,
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error(`处理键值 ${key} 失败:`, error);
|
||||||
|
result.details.push({
|
||||||
|
key,
|
||||||
|
error: error.message,
|
||||||
|
success: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result.processed = keys.length;
|
||||||
|
|
||||||
|
// 3. 尝试自动翻译(可选)
|
||||||
|
if (result.createdTranslations > 0) {
|
||||||
|
await this.tryAutoTranslateNewKeys(project, locale);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.success('ok', {
|
||||||
|
data: {
|
||||||
|
success: true,
|
||||||
|
processed: result.processed,
|
||||||
|
stats: {
|
||||||
|
totalKeys: await ctx.model.I18nKey.count({ where: { project } }),
|
||||||
|
totalTranslations: await ctx.model.I18nTranslation.count({
|
||||||
|
include: [{
|
||||||
|
model: ctx.model.I18nKey,
|
||||||
|
as: 'key',
|
||||||
|
where: { project },
|
||||||
|
}],
|
||||||
|
where: { language: locale },
|
||||||
|
}),
|
||||||
|
newKeys: result.createdKeys,
|
||||||
|
newTranslations: result.createdTranslations,
|
||||||
|
},
|
||||||
|
details: result.details,
|
||||||
|
},
|
||||||
|
code: 200,
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('批量处理键值失败:', error);
|
||||||
|
return this.success('ok', {
|
||||||
|
data: {
|
||||||
|
success: false,
|
||||||
|
error: error.message,
|
||||||
|
processed: 0,
|
||||||
|
},
|
||||||
|
code: 500,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从键名提取模块
|
||||||
|
* @param keyName
|
||||||
|
*/
|
||||||
|
extractModule(keyName) {
|
||||||
|
if (!keyName) return 'common';
|
||||||
|
|
||||||
|
const parts = keyName.split('.');
|
||||||
|
if (parts.length > 1) {
|
||||||
|
const possibleModules = [ 'warehouse', 'inventory', 'order', 'shipment', 'user', 'system', 'common' ];
|
||||||
|
if (possibleModules.includes(parts[0])) {
|
||||||
|
return parts[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'common';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 尝试自动翻译新键值(可选功能)
|
||||||
|
* @param project
|
||||||
|
* @param targetLanguage
|
||||||
|
*/
|
||||||
|
async tryAutoTranslateNewKeys(project, targetLanguage) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
// 只有目标语言不是中文时才需要翻译
|
||||||
|
if (targetLanguage === 'zh-CN') return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 查找需要翻译的记录(中文有翻译,但目标语言没有)
|
||||||
|
const needTranslate = await ctx.model.I18nTranslation.findAll({
|
||||||
|
include: [{
|
||||||
|
model: ctx.model.I18nKey,
|
||||||
|
as: 'key',
|
||||||
|
where: { project },
|
||||||
|
}],
|
||||||
|
where: {
|
||||||
|
language: 'zh-CN',
|
||||||
|
translation: { [ctx.app.Sequelize.Op.ne]: null },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const chineseTranslations = {};
|
||||||
|
needTranslate.forEach(item => {
|
||||||
|
if (item.key) {
|
||||||
|
chineseTranslations[item.key.id] = item.translation;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 检查目标语言是否已有翻译
|
||||||
|
const existingTranslations = await ctx.model.I18nTranslation.findAll({
|
||||||
|
where: {
|
||||||
|
key_id: Object.keys(chineseTranslations).map(id => parseInt(id)),
|
||||||
|
language: targetLanguage,
|
||||||
|
translation: { [ctx.app.Sequelize.Op.ne]: null },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const existingKeyIds = new Set(existingTranslations.map(t => t.key_id));
|
||||||
|
|
||||||
|
// 批量创建未翻译的记录
|
||||||
|
const createPromises = [];
|
||||||
|
for (const [ keyId, chineseText ] of Object.entries(chineseTranslations)) {
|
||||||
|
if (!existingKeyIds.has(parseInt(keyId))) {
|
||||||
|
createPromises.push(
|
||||||
|
ctx.model.I18nTranslation.create({
|
||||||
|
key_id: parseInt(keyId),
|
||||||
|
language: targetLanguage,
|
||||||
|
translation: null, // 这里可以调用翻译API自动填充
|
||||||
|
translation_status: 0,
|
||||||
|
auto_generated: 1,
|
||||||
|
translator: 'auto-translate',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (createPromises.length > 0) {
|
||||||
|
await Promise.all(createPromises);
|
||||||
|
ctx.logger.info(`为 ${createPromises.length} 个键值创建了 ${targetLanguage} 的翻译占位`);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('自动翻译处理失败:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async searchSpace(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.space.searchSpace(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async getExpressList(data){
|
||||||
|
|
||||||
|
return this.success('ok', { data: this.app.config.expressList, code: 200 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = indexService;
|
||||||
432
app/service/systemMethods/print.js
Normal file
432
app/service/systemMethods/print.js
Normal file
@ -0,0 +1,432 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { up } = require('../../../database/migrations/20251109160640-init-wms_account');
|
||||||
|
// 打印相关 Service
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打印 Service
|
||||||
|
* 参考 indexService 初始化方式,后续可扩展具体业务函数
|
||||||
|
*/
|
||||||
|
class PrintService extends MainService {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
// 初始化免登录、免权限、免日志、免认证等配置
|
||||||
|
const _noNeedLogin = '';
|
||||||
|
const _noNeedRight = '*';
|
||||||
|
const _noNeedLog = '';
|
||||||
|
const _noNeedAuth = '*';
|
||||||
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
|
this.defaultComponents = [
|
||||||
|
{ name: '抖音', port: '13888' },
|
||||||
|
{ name: '拼多多', port: '5000' },
|
||||||
|
{ name: '快手', port: '16888/ks/printer' },
|
||||||
|
{ name: '京东', port: '9113' },
|
||||||
|
{ name: '菜鸟', port: '13528' },
|
||||||
|
{ name: '视频号', port: '12705' },
|
||||||
|
{ name: '小红书', port: '10818' },
|
||||||
|
{ name: 'LODOP', port: '8000' }
|
||||||
|
];
|
||||||
|
|
||||||
|
}
|
||||||
|
async send(_data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const warehouseId = ctx.user.store_id;
|
||||||
|
const { printer, type, template, data, computerId, timestamp, count } = _data;
|
||||||
|
console.log('send to computer', warehouseId, printer, type, template, data, computerId, timestamp, count);
|
||||||
|
//生成打印编号并记录到数据库
|
||||||
|
const printRecord = await ctx.model.PrintRecord.create({
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
computer_id: computerId,
|
||||||
|
printer,
|
||||||
|
type,
|
||||||
|
data: { template, data },
|
||||||
|
status: 'pending'
|
||||||
|
});
|
||||||
|
//处理后的数据
|
||||||
|
let processedData = {};
|
||||||
|
switch (type) {
|
||||||
|
case "customize":
|
||||||
|
const { page_width, page_height, template_content } = template;
|
||||||
|
let htm = `<body style="position:relative; width:${page_width}mm; height:${page_height}mm;margin:0; padding:0;overflow:hidden;">`;
|
||||||
|
for (const item of template_content) {
|
||||||
|
let content = item.content;
|
||||||
|
|
||||||
|
for(const key in data) {
|
||||||
|
console.log("正在匹配字段:", key, "与", item.field_code);
|
||||||
|
if(item.field_code == key) {
|
||||||
|
content = data[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log("转后的内容:", content);
|
||||||
|
switch (item.type) {
|
||||||
|
case "text":
|
||||||
|
htm += `<div style="
|
||||||
|
position:absolute;
|
||||||
|
width:${item.width}mm;
|
||||||
|
height:${item.height}mm;
|
||||||
|
left:${item.left}mm;
|
||||||
|
top:${item.top}mm;
|
||||||
|
font-size:${item.fontSize}pt;
|
||||||
|
font-weight:${item.bold ? 'bold' : 'normal'};
|
||||||
|
font-style:${item.italic ? 'italic' : 'normal'};
|
||||||
|
text-decoration:${item.underline ? 'underline' : 'none'};
|
||||||
|
text-align:${item.textAlign};
|
||||||
|
transform: rotate(${item.rotate}deg);
|
||||||
|
line-height: ${item.lineHeight}mm;
|
||||||
|
};
|
||||||
|
">${content}</div>`;
|
||||||
|
break;
|
||||||
|
case "image":
|
||||||
|
htm += `<img src="${content}" style="position:absolute;
|
||||||
|
left:${item.left}mm;
|
||||||
|
top:${item.top}mm;
|
||||||
|
width:${item.width}mm;
|
||||||
|
height:${item.height}mm;" />`;
|
||||||
|
break;
|
||||||
|
case "barcode":
|
||||||
|
htm += `<div style="
|
||||||
|
position:absolute;
|
||||||
|
left:${item.left}mm;
|
||||||
|
top:${item.top}mm;
|
||||||
|
width:${item.width}mm;
|
||||||
|
height:${item.height}mm;
|
||||||
|
"><img style="width:100%; height:100%;" src="https://ye4s.wms.gztbyc.com/barcode/build?text=${content.slice(-13)}&type=C128&foreground=%23000000&width=2&height=${parseInt(item.height/25.4*96)}" /></div>`;
|
||||||
|
break;
|
||||||
|
case "qrcode":
|
||||||
|
let toUrl = `https://ye4s.wms.gztbyc.com/to/${content}`;
|
||||||
|
//转换成urlencode
|
||||||
|
toUrl = encodeURIComponent(toUrl);
|
||||||
|
let url = `https://ye4s.wms.gztbyc.com/qrcode/build?text=${toUrl}`;
|
||||||
|
|
||||||
|
|
||||||
|
htm += `<div style="
|
||||||
|
position:absolute;
|
||||||
|
left:${item.left}mm;
|
||||||
|
top:${item.top}mm;
|
||||||
|
width:${item.width}mm;
|
||||||
|
height:${item.height}mm;
|
||||||
|
"><img style="width:100%; height:100%;" src="${url}" /></div>`;
|
||||||
|
break;
|
||||||
|
case "line":
|
||||||
|
htm += `<div style="
|
||||||
|
position:absolute;
|
||||||
|
left:${item.left}mm;
|
||||||
|
top:${item.top}mm;
|
||||||
|
width:${item.width}mm;
|
||||||
|
height:${item.height}mm;
|
||||||
|
border-top: ${item.line_width}px ${item.line_style} ${item.line_color};
|
||||||
|
"></div>`;
|
||||||
|
break;
|
||||||
|
case "rectangle":
|
||||||
|
htm += `<div style="
|
||||||
|
position:absolute;
|
||||||
|
left:${item.left}mm;
|
||||||
|
top:${item.top}mm;
|
||||||
|
width:${item.width}mm;
|
||||||
|
height:${item.height}mm;
|
||||||
|
border: ${item.line_width}px ${item.line_style} ${item.line_color};
|
||||||
|
"></div>`;
|
||||||
|
break;
|
||||||
|
case "table":
|
||||||
|
let tableHtml = `<table style="position:absolute; left:${item.left}mm; top:${item.top}mm; border-collapse: collapse;">`;
|
||||||
|
for (let i = 0; i < item.rows; i++) {
|
||||||
|
tableHtml += `<tr>`;
|
||||||
|
for (let j = 0; j < item.columns; j++) {
|
||||||
|
let content = item.content[i] && item.content[i][j] ? item.content[i][j] : '';
|
||||||
|
tableHtml += `<td style="border: ${item.line_width}px ${item.line_style} ${item.line_color}; width:${item.width / item.columns}mm; height:${item.height / item.rows}mm;">${content}</td>`;
|
||||||
|
} tableHtml += `</tr>`;
|
||||||
|
} tableHtml += `</table>`;
|
||||||
|
htm += tableHtml;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
htm += `</body>`;
|
||||||
|
processedData = {
|
||||||
|
pageWidth: page_width,
|
||||||
|
pageHeight: page_height,
|
||||||
|
htm: htm,
|
||||||
|
lodopkey:["","13528A153BAEE3A0254B9507DCDE2839","EDE92F75B6A3D917F65910","D60BC84D7CF2DE18156A6F88987304CB6D8"]
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "express":
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return this.fail('不支持的打印类型', 1001);
|
||||||
|
}
|
||||||
|
|
||||||
|
const printData = {
|
||||||
|
printer,
|
||||||
|
type,
|
||||||
|
template,
|
||||||
|
data: processedData,
|
||||||
|
timestamp,
|
||||||
|
count,
|
||||||
|
printId: printRecord.id
|
||||||
|
};
|
||||||
|
const res = await this.service.systems.print.index.sendToComputer({warehouse:warehouseId, computerId: computerId, data:printData});
|
||||||
|
console.log('sendToComputer response', res);
|
||||||
|
//发送成功后更新打印记录状态
|
||||||
|
if (res.status=="success") {
|
||||||
|
await printRecord.update({ status: 'sent' });
|
||||||
|
return this.success('发送打印任务成功', { code: 200, printId: printRecord.id });
|
||||||
|
} else {
|
||||||
|
await printRecord.update({ status: 'failed', error_message: res.error });
|
||||||
|
return this.fail(res.error, { code: 504, printId: printRecord.id });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async getPrintResult(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const warehouseId = ctx.user.store_id;
|
||||||
|
const { printId } = data;
|
||||||
|
if (!printId) return this.fail('参数错误', 1001);
|
||||||
|
const record = await ctx.model.PrintRecord.findOne({ where: { id: printId, warehouse_id: warehouseId }, raw: true });
|
||||||
|
if (!record) return this.fail('打印记录不存在', 1002);
|
||||||
|
return this.success('success', { ...record, code: 0 });
|
||||||
|
}
|
||||||
|
async getPrintRecordItem(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const warehouseId = ctx.user.store_id;
|
||||||
|
const { id } = data;
|
||||||
|
if (!id) return this.fail('参数错误', 1001);
|
||||||
|
const item = await ctx.model.PrintRecord.findOne({ where: { id, warehouse_id: warehouseId }, raw: true });
|
||||||
|
if (!item) return this.fail('打印记录不存在', 1002);
|
||||||
|
return this.success('success', { ...item, code: 0 });
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 1. 查询打印台列表
|
||||||
|
* @param {Object} data { page, pageSize, where }
|
||||||
|
*/
|
||||||
|
async getList(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
console.log("ctx.user in PrintService constructor", ctx.user);
|
||||||
|
const warehouse_id = ctx.user.store_id;
|
||||||
|
// TODO: 需根据实际分页和条件查询调整
|
||||||
|
const { page = 1, pageSize = 20, where = {} } = data;
|
||||||
|
// 字段过滤
|
||||||
|
const filter = {};
|
||||||
|
['id', 'name', 'computer_id', 'custom_barcode'].forEach(key => {
|
||||||
|
if (where[key]) filter[key] = where[key];
|
||||||
|
});
|
||||||
|
filter.warehouse_id = warehouse_id;
|
||||||
|
filter.deleted = 0;
|
||||||
|
// 查询总数
|
||||||
|
console.log("ctx.model.PrintStations", ctx.model.PrintStations);
|
||||||
|
const total = await ctx.model.PrintStations.count({ where: filter });
|
||||||
|
// 查询分页数据
|
||||||
|
const list = await ctx.model.PrintStations.findAll({
|
||||||
|
where: filter,
|
||||||
|
offset: (page - 1) * pageSize,
|
||||||
|
limit: pageSize,
|
||||||
|
order: [['create_at', 'DESC']],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
let computers = list.map(item => {
|
||||||
|
const computer = {
|
||||||
|
id: item.computer_id,
|
||||||
|
is_online: 0,
|
||||||
|
components: this.defaultComponents.map(component => ({
|
||||||
|
name: component.name,
|
||||||
|
is_online: 0,
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
return computer;
|
||||||
|
});
|
||||||
|
// 动态属性处理(如 is_online、components)
|
||||||
|
for (let i = 0; i < computers.length; i++) {
|
||||||
|
let key = `warehouse:${warehouse_id}:printer:${computers[i].id}`;
|
||||||
|
const computerInfo = await this.app.redis.get("printer").get(key);
|
||||||
|
console.log("key and computerInfo", key, computerInfo);
|
||||||
|
if (computerInfo) {
|
||||||
|
computers[i].is_online = 1;
|
||||||
|
computers[i].components = await Promise.all(computers[i].components.map(async component => {
|
||||||
|
const componentKey = `printer:${computers[i].id}:name:${component.name}:status`;
|
||||||
|
const componentInfo = await this.app.redis.get("printer").get(componentKey);
|
||||||
|
console.log("componentKey and componentInfo", componentKey, componentInfo);
|
||||||
|
if (componentInfo && componentInfo == "connected") {
|
||||||
|
component.is_online = 1;
|
||||||
|
}
|
||||||
|
return component;
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const item of list) {
|
||||||
|
const computer = computers.find(c => c.id === item.computer_id);
|
||||||
|
item.is_online = computer ? computer.is_online : 0;
|
||||||
|
item.components = computer ? computer.components : this.defaultComponents.map(component => ({
|
||||||
|
name: component.name,
|
||||||
|
is_online: 0,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
const result = {
|
||||||
|
code: 200,
|
||||||
|
data: {
|
||||||
|
list: list,
|
||||||
|
pagination: {
|
||||||
|
hasNext: page * pageSize < total,
|
||||||
|
hasPrevious: page > 1,
|
||||||
|
page: page,
|
||||||
|
pageSize: pageSize,
|
||||||
|
total: total,
|
||||||
|
totalPages: Math.ceil(total / pageSize),
|
||||||
|
},
|
||||||
|
queryInfo: {
|
||||||
|
conditions: where,
|
||||||
|
hasBarcodeSearch: false,
|
||||||
|
sortField: 'id',
|
||||||
|
sortOrder: "DESC"
|
||||||
|
},
|
||||||
|
summary: {
|
||||||
|
total_available: total,
|
||||||
|
total_items: pageSize,
|
||||||
|
total_locked: 0,
|
||||||
|
total_quantity: 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.success('success', result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 2. 获取单个打印台
|
||||||
|
* @param {Object} data { id }
|
||||||
|
*/
|
||||||
|
async getItem(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { id } = data;
|
||||||
|
if (!id) return this.fail('参数错误', 1001);
|
||||||
|
const item = await ctx.model.PrintStations.findOne({ where: { id }, raw: true });
|
||||||
|
if (!item) return this.fail('打印台不存在', 1002);
|
||||||
|
return this.success('success', { ...item, code: 0 });
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 3. 添加打印台
|
||||||
|
* @param {Object} data { id, name, computer_id, custom_barcode }
|
||||||
|
*/
|
||||||
|
async add(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const warehouse_id = ctx.user.store_id;
|
||||||
|
const { name, computer_id, custom_barcode } = data;
|
||||||
|
if (!name || !computer_id) return this.fail('参数错误', 1001);
|
||||||
|
const newItem = await ctx.model.PrintStations.create({
|
||||||
|
warehouse_id,
|
||||||
|
name,
|
||||||
|
computer_id,
|
||||||
|
custom_barcode,
|
||||||
|
creator_id: ctx.user?.employees_id || '',
|
||||||
|
creator_name: ctx.user?.employees_name || '',
|
||||||
|
default_printer_name: data.default_printer_name || '',
|
||||||
|
create_at: new Date(),
|
||||||
|
update_at: new Date(),
|
||||||
|
deleted: 0,
|
||||||
|
});
|
||||||
|
return this.success('添加打印台成功', { data: newItem, code: 0 });
|
||||||
|
}
|
||||||
|
async hasName(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const warehouse_id = ctx.user.store_id;
|
||||||
|
const { name, id } = data;
|
||||||
|
if (!name) return this.fail('参数错误', 1001);
|
||||||
|
const item = await ctx.model.PrintStations.findOne({ where: { name, warehouse_id, id: { [ctx.model.Sequelize.Op.ne]: id } }, raw: true });
|
||||||
|
return this.success('success', { exists: !!item, code: 0 });
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 3. 修改打印台
|
||||||
|
* @param {Object} data { id, name, computer_id, custom_barcode }
|
||||||
|
*/
|
||||||
|
async updateItem(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { id, name, computer_id, custom_barcode } = data;
|
||||||
|
if (!id) return this.fail('参数错误', 1001);
|
||||||
|
const item = await ctx.model.PrintStations.findOne({ where: { id } });
|
||||||
|
if (!item) return this.fail('打印台不存在', 1002);
|
||||||
|
// 只更新允许字段
|
||||||
|
if (name !== undefined) item.name = name;
|
||||||
|
if (computer_id !== undefined) item.computer_id = computer_id;
|
||||||
|
if (custom_barcode !== undefined) item.custom_barcode = custom_barcode;
|
||||||
|
await item.save();
|
||||||
|
return this.success('success', { data: null, code: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 4. 删除打印台
|
||||||
|
* @param {Object} data { ids }
|
||||||
|
*/
|
||||||
|
async del(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { ids } = data;
|
||||||
|
if (!Array.isArray(ids) || ids.length === 0) return this.fail('参数错误', 1001);
|
||||||
|
// 软删除
|
||||||
|
const result = await ctx.model.PrintStations.update({ deleted: 1 }, { where: { id: ids } });
|
||||||
|
// TODO: 检查 result 是否成功
|
||||||
|
return this.success('success', { data: null, code: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 5. 获取打印电脑列表
|
||||||
|
* @param {Object} data {}
|
||||||
|
*/
|
||||||
|
async getComputer() {
|
||||||
|
const { ctx } = this;
|
||||||
|
// TODO: 打印电脑状态需根据实际业务实现
|
||||||
|
const warehouseId = ctx.user.store_id;
|
||||||
|
const list = await ctx.model.PrintComputer.findAll({ raw: true, where: { status: 1, warehouse_id: warehouseId } });
|
||||||
|
|
||||||
|
return this.success('success', { data: list, code: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 7. 获取打印电脑的所有打印机
|
||||||
|
* @param {Object} data { id }
|
||||||
|
*/
|
||||||
|
async getComputerPrinter(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { id } = data;
|
||||||
|
if (!id) return this.fail('参数错误', 1001);
|
||||||
|
const printerListResult = await this.app.redis.get("printer").get(`printer:${id}:printerList`);
|
||||||
|
console.log("getComputerPrinter printerListResult", printerListResult);
|
||||||
|
const printerList = JSON.parse(printerListResult);
|
||||||
|
let printers = [];
|
||||||
|
if(!printerList ||!printerList.data || printerList.data.length === 0){
|
||||||
|
printers = [];
|
||||||
|
} else {
|
||||||
|
printers = printerList.data;
|
||||||
|
}
|
||||||
|
return this.success('success', { data: printers, code: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 8. 保存打印台的快递-打印机绑定
|
||||||
|
* @param {Object} data { default, express }
|
||||||
|
*/
|
||||||
|
async savePrinters(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { defaultPrinter, express } = data;
|
||||||
|
// express: [{ express_id, name }]
|
||||||
|
if (!defaultPrinter || !Array.isArray(express)) return this.fail('参数错误', 1001);
|
||||||
|
// TODO: 需根据打印台ID、快递ID等实际业务调整
|
||||||
|
// 这里只做示例保存,实际应覆盖原有绑定
|
||||||
|
// 1. 保存默认打印机
|
||||||
|
// 2. 保存 express 打印机绑定
|
||||||
|
// 3. 需用 PrintStationExpress model
|
||||||
|
// 示例:批量保存
|
||||||
|
for (const item of express) {
|
||||||
|
await ctx.model.PrintStationExpress.upsert({
|
||||||
|
print_station_id: data.print_station_id, // 需传入
|
||||||
|
express_id: item.express_id,
|
||||||
|
express_name: item.name,
|
||||||
|
printer_name: item.name,
|
||||||
|
is_default: item.name === defaultPrinter ? 1 : 0,
|
||||||
|
creator_id: ctx.user?.id || '',
|
||||||
|
creator_name: ctx.user?.name || '',
|
||||||
|
create_at: new Date(),
|
||||||
|
update_at: new Date(),
|
||||||
|
deleted: 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return this.success('success', { data: null, code: 0 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = PrintService;
|
||||||
20
app/service/systemMethods/printer/station.js
Normal file
20
app/service/systemMethods/printer/station.js
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
const MainService = require('../../main');
|
||||||
|
|
||||||
|
class StationService extends MainService {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
const _noNeedLogin = '';
|
||||||
|
const _noNeedRight = 'list';
|
||||||
|
const _noNeedLog = '*';
|
||||||
|
const _noNeedAuth = 'list';
|
||||||
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
|
}
|
||||||
|
|
||||||
|
async list() {
|
||||||
|
// 返回结构与printTemplateService一致
|
||||||
|
const result = [];
|
||||||
|
return this.success('ok', { presetTree: result, code: 200 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = StationService;
|
||||||
36
app/service/systemMethods/setting/printTemplate.js
Normal file
36
app/service/systemMethods/setting/printTemplate.js
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../../main');
|
||||||
|
|
||||||
|
class printTemplateService extends MainService {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
const _noNeedLogin = '';
|
||||||
|
const _noNeedRight = 'list,save,listTemplatesByType';
|
||||||
|
const _noNeedLog = '*';
|
||||||
|
const _noNeedAuth = 'list,save,listTemplatesByType';
|
||||||
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
|
}
|
||||||
|
async list(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.setting.printTemplate.getTree();
|
||||||
|
return this.success('ok', { presetTree: result, code: 200 });
|
||||||
|
}
|
||||||
|
async save(data) {
|
||||||
|
console.log('接收到保存请求:', data);
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.setting.printTemplate.save(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async listTemplatesByType(data) {
|
||||||
|
const { service } = this;
|
||||||
|
console.log('接收到根据业务类型查询模板请求:', data);
|
||||||
|
const { businessType } = data;
|
||||||
|
if(!businessType){
|
||||||
|
throw new Error('缺少业务类型参数');
|
||||||
|
}
|
||||||
|
const list = await service.systems.setting.printTemplate.listTemplatesByType(businessType);
|
||||||
|
return this.success('ok', { data: list, code: 200 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = printTemplateService;
|
||||||
361
app/service/systemMethods/stock.js
Normal file
361
app/service/systemMethods/stock.js
Normal file
@ -0,0 +1,361 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class indexService extends MainService {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
const _noNeedLogin = '';
|
||||||
|
const _noNeedRight = 'fastWhereTree,stockWarehouse,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search';
|
||||||
|
const _noNeedLog = 'fastWhereTree,stockWarehouse,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search';
|
||||||
|
const _noNeedAuth = 'fastWhereTree,stockWarehouse,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search';
|
||||||
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
|
}
|
||||||
|
async stockWarehouse(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const { pagination, where } = data;
|
||||||
|
console.log('where', where);
|
||||||
|
const result = await service.systems.stockStore.getWarehouseStock(where, pagination);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async getProhibitedType() {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.stockStore.getProhibitedType();
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
}
|
||||||
|
async getInfo(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.stockStore.getInfo(data);
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
}
|
||||||
|
async saveWarehouseStock(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.stockStore.saveWarehouseStock(data);
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
|
async createWarehouseStock(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.stockStore.createWarehouseStock(data);
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
}
|
||||||
|
async getBarcodes(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.stockStore.getBarcodes(data);
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
}
|
||||||
|
async saveWarehouseStockBarcode(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.stockStore.saveWarehouseStockBarcode(data);
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
}
|
||||||
|
async getStoreStocks(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.stockStore.getStoreStocks(data);
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
}
|
||||||
|
async bindItem(data) {
|
||||||
|
const { service } = this;
|
||||||
|
try {
|
||||||
|
const result = await service.systems.stockStore.bindItem(data);
|
||||||
|
return this.success('绑定成功', { data: result, code: 200 });
|
||||||
|
} catch (e) {
|
||||||
|
return this.success(e.message, { code: 200 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async unbindItem(data) {
|
||||||
|
const { service } = this;
|
||||||
|
try {
|
||||||
|
const result = await service.systems.stockStore.unbindItem(data);
|
||||||
|
return this.success('解绑成功', { data: result, code: 200 });
|
||||||
|
} catch (e) {
|
||||||
|
return this.success(e.message, { code: 200 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async checkItemCodeUnique(data) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
const { id, item_code, store_id } = data;
|
||||||
|
console.log(data);
|
||||||
|
try {
|
||||||
|
if (!item_code || !store_id) {
|
||||||
|
return this.fail('参数错误');
|
||||||
|
}
|
||||||
|
const data = await service.systems.stockStore.checkItemCodeUnique(id, item_code, store_id, ctx.user.store_id);
|
||||||
|
return this.success('获取成功', { data, code: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
return this.fail(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async queryStockLogs(data) {
|
||||||
|
console.log('请求');
|
||||||
|
const { ctx } = this;
|
||||||
|
try {
|
||||||
|
const { service } = this;
|
||||||
|
data.warehouseId = ctx.user.store_id;
|
||||||
|
const result = await service.systems.operationLog.queryStockLogs(data);
|
||||||
|
return this.success('ok', { data: result, code: 200 });
|
||||||
|
} catch (e) {
|
||||||
|
console.log(e);
|
||||||
|
return this.success(e.message, { code: 200 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async handleBatchDelete(data) {
|
||||||
|
const { service } = this;
|
||||||
|
try {
|
||||||
|
const result = await service.systems.stockStore.handleBatchDelete(data);
|
||||||
|
return this.success(result.message, { data: result.data, code: result.code });
|
||||||
|
} catch (e) {
|
||||||
|
console.log(e);
|
||||||
|
return this.success(e.message, { code: 200 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteUnit(data) {
|
||||||
|
const { service } = this;
|
||||||
|
try {
|
||||||
|
const result = await service.systems.stockStore.deleteUnit(data);
|
||||||
|
return this.success(result.message, { data: result.data, code: result.code });
|
||||||
|
} catch (e) {
|
||||||
|
console.log(e);
|
||||||
|
return this.success(e.message, { code: 200 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteProhibited(data) {
|
||||||
|
const { service } = this;
|
||||||
|
try {
|
||||||
|
const result = await service.systems.stockStore.deleteProhibited(data);
|
||||||
|
return this.success(result.message, { data: result.data, code: result.code });
|
||||||
|
} catch (e) {
|
||||||
|
console.log(e);
|
||||||
|
return this.success(e.message, { code: 200 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async handleBatchChange(data) {
|
||||||
|
const { service } = this;
|
||||||
|
try {
|
||||||
|
const result = await service.systems.stockStore.handleBatchChange(data);
|
||||||
|
return this.success(result.message, { data: result.data, code: result.code });
|
||||||
|
} catch (e) {
|
||||||
|
console.log(e);
|
||||||
|
return this.success(e.message, { code: 405 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async getStockUnits() {
|
||||||
|
console.log('query_getStockUnits');
|
||||||
|
const { ctx } = this;
|
||||||
|
const warehouse_id = ctx.user.store_id;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 构建查询条件
|
||||||
|
const where = {
|
||||||
|
[ctx.app.Sequelize.Op.or]: [
|
||||||
|
{ warehouse_id: null }, // 系统预设单位
|
||||||
|
{ warehouse_id }, // 本仓库的单位
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const units = await ctx.model.StockUnit.findAll({
|
||||||
|
where,
|
||||||
|
order: [
|
||||||
|
[ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null)
|
||||||
|
[ 'created_at', 'DESC' ], // 按创建时间倒序
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return this.success('ok', { data: units, code: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
return this.fail(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async getUnitList() {
|
||||||
|
console.log('query_getUnitList');
|
||||||
|
const { ctx } = this;
|
||||||
|
const warehouse_id = ctx.user.store_id;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 构建查询条件
|
||||||
|
const where = {
|
||||||
|
warehouse_id,
|
||||||
|
};
|
||||||
|
|
||||||
|
const units = await ctx.model.StockUnit.findAll({
|
||||||
|
where,
|
||||||
|
order: [
|
||||||
|
[ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null)
|
||||||
|
[ 'created_at', 'DESC' ], // 按创建时间倒序
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return this.success('ok', { data: units, code: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
return this.fail(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async createProhibited(data) {
|
||||||
|
console.log('createProhibited', data);
|
||||||
|
const { ctx } = this;
|
||||||
|
const warehouse_id = ctx.user.store_id || null;
|
||||||
|
const { name } = data;
|
||||||
|
|
||||||
|
// 参数验证
|
||||||
|
if (!name || name.trim() === '') {
|
||||||
|
ctx.body = {
|
||||||
|
code: 400,
|
||||||
|
message: '违禁品类型名称不能为空',
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const trimmedName = name.trim();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 检查是否是系统预设单位(warehouse_id为null)
|
||||||
|
const systemUnit = await ctx.model.ProhibitedType.findOne({
|
||||||
|
where: {
|
||||||
|
type_name: trimmedName,
|
||||||
|
warehouse_id: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (systemUnit) {
|
||||||
|
ctx.body = {
|
||||||
|
code: 400,
|
||||||
|
message: '该违禁品类型是系统预设,不允许添加',
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 检查当前仓库是否已存在相同名称的单位
|
||||||
|
const existUnit = await ctx.model.ProhibitedType.findOne({
|
||||||
|
where: {
|
||||||
|
type_name: trimmedName,
|
||||||
|
warehouse_id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existUnit) {
|
||||||
|
ctx.body = {
|
||||||
|
code: 400,
|
||||||
|
message: '该违禁品类型名称已存在',
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 创建单位
|
||||||
|
const unit = await ctx.model.ProhibitedType.create({
|
||||||
|
type_name: trimmedName,
|
||||||
|
warehouse_id,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 4. 获取更新后的单位列表
|
||||||
|
const where = {};
|
||||||
|
if (warehouse_id) {
|
||||||
|
where[ctx.app.Sequelize.Op.or] = [
|
||||||
|
{ warehouse_id: null }, // 系统预设单位
|
||||||
|
{ warehouse_id }, // 当前仓库的单位
|
||||||
|
];
|
||||||
|
} else {
|
||||||
|
where.warehouse_id = null; // 只显示系统预设单位
|
||||||
|
}
|
||||||
|
|
||||||
|
const units = await ctx.model.ProhibitedType.findAll({
|
||||||
|
where,
|
||||||
|
order: [
|
||||||
|
[ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null)
|
||||||
|
[ 'created_at', 'DESC' ], // 按创建时间倒序
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return this.success('添加成功', { code: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
return this.success('创建违禁品类型失败', { code: 405 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async createUnit() {
|
||||||
|
const { ctx } = this;
|
||||||
|
const warehouse_id = ctx.user.store_id || null;
|
||||||
|
const { name } = ctx.request.body;
|
||||||
|
|
||||||
|
// 参数验证
|
||||||
|
if (!name || name.trim() === '') {
|
||||||
|
ctx.body = {
|
||||||
|
code: 400,
|
||||||
|
message: '单位名称不能为空',
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const trimmedName = name.trim();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 检查是否是系统预设单位(warehouse_id为null)
|
||||||
|
const systemUnit = await ctx.model.StockUnit.findOne({
|
||||||
|
where: {
|
||||||
|
name: trimmedName,
|
||||||
|
warehouse_id: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (systemUnit) {
|
||||||
|
ctx.body = {
|
||||||
|
code: 400,
|
||||||
|
message: '该单位是系统预设单位,不允许添加',
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 检查当前仓库是否已存在相同名称的单位
|
||||||
|
const existUnit = await ctx.model.StockUnit.findOne({
|
||||||
|
where: {
|
||||||
|
name: trimmedName,
|
||||||
|
warehouse_id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existUnit) {
|
||||||
|
ctx.body = {
|
||||||
|
code: 400,
|
||||||
|
message: '该单位名称已存在',
|
||||||
|
};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 创建单位
|
||||||
|
const unit = await ctx.model.StockUnit.create({
|
||||||
|
name: trimmedName,
|
||||||
|
warehouse_id,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 4. 获取更新后的单位列表
|
||||||
|
const where = {};
|
||||||
|
if (warehouse_id) {
|
||||||
|
where[ctx.app.Sequelize.Op.or] = [
|
||||||
|
{ warehouse_id: null }, // 系统预设单位
|
||||||
|
{ warehouse_id }, // 当前仓库的单位
|
||||||
|
];
|
||||||
|
} else {
|
||||||
|
where.warehouse_id = null; // 只显示系统预设单位
|
||||||
|
}
|
||||||
|
|
||||||
|
const units = await ctx.model.StockUnit.findAll({
|
||||||
|
where,
|
||||||
|
order: [
|
||||||
|
[ 'warehouse_id', 'ASC' ], // 先显示系统预设单位(warehouse_id为null)
|
||||||
|
[ 'created_at', 'DESC' ], // 按创建时间倒序
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return this.success('添加成功', { code: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
return this.success('创建库存单位失败', { code: 200 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async search(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.stockStore.search(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = indexService;
|
||||||
75
app/service/systemMethods/storage/receiving.js
Normal file
75
app/service/systemMethods/storage/receiving.js
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../../main');
|
||||||
|
|
||||||
|
class configService extends MainService {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
const _noNeedLogin = '';
|
||||||
|
const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving';
|
||||||
|
const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange';
|
||||||
|
const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving';
|
||||||
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
|
}
|
||||||
|
async getReceivingList(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const { pagination, where } = data;
|
||||||
|
console.log('where', where);
|
||||||
|
console.log('service.systems.storage.receiving', service.systems.storage.index.index);
|
||||||
|
const result = await service.systems.storage.receiving.getReceivingList(where, pagination);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async create(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.storage.receiving.create(data);
|
||||||
|
return this.success('创建失败', result);
|
||||||
|
}
|
||||||
|
async addItem(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const { id, item } = data;
|
||||||
|
const result = await service.systems.storage.receiving.addItem(id, item);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async removeItem(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const { id, item_id } = data;
|
||||||
|
const result = await service.systems.storage.receiving.removeItem(id, item_id);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async saveReceiving(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.storage.receiving.saveReceiving(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async get(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.storage.receiving.get(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async addDetail(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.storage.receiving.addDetail(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async deleteDetail(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.storage.receiving.deleteDetail(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async detailChange(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.storage.receiving.detailChange(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async cancel(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.storage.receiving.invalid(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async completeReceiving(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.storage.receiving.completeReceiving(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = configService;
|
||||||
50
app/service/systemMethods/store.js
Normal file
50
app/service/systemMethods/store.js
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class storeService extends MainService {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
const _noNeedLogin = '';
|
||||||
|
const _noNeedRight = 'createStore,createWarehouse,joinStore,joinWarehouse';
|
||||||
|
const _noNeedAuth = '*';
|
||||||
|
this.systemInit(_noNeedLogin, _noNeedRight, '', _noNeedAuth);
|
||||||
|
}
|
||||||
|
async createStore(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.store.createStore(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async createWarehouse(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.store.createWarehouse(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async joinStore(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.store.joinStore(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async joinWarehouse(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.store.joinWarehouse(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async getStoreRoles(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.store.getStoreRoles(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async getStoreRoles(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.store.getStoreRoles(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
async auditApply(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.store.auditApply(data);
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
module.exports = storeService;
|
||||||
45
app/service/systemMethods/user.js
Normal file
45
app/service/systemMethods/user.js
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class userService extends MainService {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
const _noNeedLogin = 'login,register';
|
||||||
|
const _noNeedRight = '*';
|
||||||
|
const _noNeedLog = 'info';
|
||||||
|
const _noNeedAuth = '*';
|
||||||
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
|
}
|
||||||
|
async login(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const { username, password } = data;
|
||||||
|
const result = await service.systems.auth.user.login(username, password);
|
||||||
|
console.log('result', result);
|
||||||
|
if (result.code) {
|
||||||
|
return this.success('登录成功', result);
|
||||||
|
}
|
||||||
|
return this.fail('登录失败:' + result.message, result);
|
||||||
|
|
||||||
|
}
|
||||||
|
async logout() {
|
||||||
|
return this.success('登出成功');
|
||||||
|
}
|
||||||
|
async info(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.auth.user.info(data);
|
||||||
|
return this.success('获取成功' + JSON.stringify(data), result);
|
||||||
|
}
|
||||||
|
async changeRole(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.auth.user.changeRole(data);
|
||||||
|
return this.success('获取成功', result, 200);
|
||||||
|
}
|
||||||
|
//注册
|
||||||
|
async register(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.auth.user.register(data);
|
||||||
|
return this.success(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = userService;
|
||||||
463
app/service/systemMethods/warehouse.js
Normal file
463
app/service/systemMethods/warehouse.js
Normal file
@ -0,0 +1,463 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
class warehouseService extends MainService {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
const _noNeedLogin = '';
|
||||||
|
const _noNeedRight = 'detail,getSpacesByRack,createRackWithSpaces,getSpaceInfo,checkBarcodeUnique';
|
||||||
|
const _noNeedLog = '*';
|
||||||
|
const _noNeedAuth = 'detail,getSpacesByRack,getSpaceInfo,checkBarcodeUnique,getWarehouseZones,getWarehouseTree,getChildren,toggleActive,getPath,getPickPath,getAreaRacks';
|
||||||
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
|
}
|
||||||
|
async getWarehouseZones() {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
console.log('获取仓库主体下所有实体仓库');
|
||||||
|
try {
|
||||||
|
const zones = await service.systems.locationZone.getWarehouseLevelZones(ctx.user.store_id);
|
||||||
|
return this.success('获取成功', { zones, code: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
return this.fail('获取失败' + error.message, { code: 0 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取仓库树状结构
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
async getWarehouseTree(data) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
const { warehouseId } = data;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!warehouseId) {
|
||||||
|
return this.fail('仓库ID不能为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
const tree = await service.systems.locationZone.getZoneTreeByWarehouse(parseInt(warehouseId));
|
||||||
|
return this.success('获取成功', tree);
|
||||||
|
} catch (error) {
|
||||||
|
return this.fail(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取子节点(懒加载)
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
async getChildren(data) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
const { zoneId } = data;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!zoneId) {
|
||||||
|
throw new Error('分区ID不能为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
const children = await service.systems.locationZone.getChildrenByZoneId(parseInt(zoneId));
|
||||||
|
ctx.success(children);
|
||||||
|
} catch (error) {
|
||||||
|
this.fail(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建分区
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
async create(data) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await service.systems.locationZone.createZone(data);
|
||||||
|
return this.success(result.message, { data: result.data, code: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
return this.fail(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新分区
|
||||||
|
* @param datas
|
||||||
|
*/
|
||||||
|
async update(datas) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
console.log('接收的数据', datas);
|
||||||
|
const { id } = datas;
|
||||||
|
const { length, width, height, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles } = datas;
|
||||||
|
try {
|
||||||
|
if (!id) {
|
||||||
|
return this.fail('分区ID不能为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await service.systems.locationZone.updateZone(parseInt(id), { length, width, height, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles });
|
||||||
|
return this.success(result.message, { data: result.data, code: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
return this.fail(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除分区
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
async delete(data) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
const { id } = data;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!id) {
|
||||||
|
return this.fail('分区ID不能为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await service.systems.locationZone.deleteZone(parseInt(id));
|
||||||
|
console.log('删除返回', result);
|
||||||
|
return this.success(result.message, { code: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
console.log('error', error);
|
||||||
|
return this.fail(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取分区详情
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
async detail(data) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
const { id } = data;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!id) {
|
||||||
|
return this.fail('分区ID不能为空');
|
||||||
|
}
|
||||||
|
const zone = await service.systems.locationZone.getZoneDetail(parseInt(id));
|
||||||
|
return this.success('获取成功', zone);
|
||||||
|
} catch (error) {
|
||||||
|
return this.fail(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async checkBarcodeUnique(data) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
const { id, barcode } = data;
|
||||||
|
console.log(data);
|
||||||
|
try {
|
||||||
|
if (!id) {
|
||||||
|
return this.fail('库位ID不能为空');
|
||||||
|
}
|
||||||
|
if (!barcode) {
|
||||||
|
return this.fail('条码不能为空');
|
||||||
|
}
|
||||||
|
const data = await service.systems.locationZone.checkBarcodeUnique(parseInt(id), barcode);
|
||||||
|
return this.success('获取成功', { data, code: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
return this.fail(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 切换分区状态
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
async toggleActive(data) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
const { id, isActive } = data;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!id) {
|
||||||
|
throw new Error('分区ID不能为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await service.systems.locationZone.toggleZoneActive(
|
||||||
|
parseInt(id),
|
||||||
|
isActive
|
||||||
|
);
|
||||||
|
ctx.success(null, result.message);
|
||||||
|
} catch (error) {
|
||||||
|
this.fail(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取分区路径
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
async getPath(data) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
const { id } = data;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!id) {
|
||||||
|
throw new Error('分区ID不能为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
const path = await service.systems.locationZone.getZonePath(parseInt(id));
|
||||||
|
ctx.success(path);
|
||||||
|
} catch (error) {
|
||||||
|
this.fail(error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async createRack() {
|
||||||
|
const { ctx } = this;
|
||||||
|
const params = ctx.request.body;
|
||||||
|
|
||||||
|
// 验证参数
|
||||||
|
ctx.validate({
|
||||||
|
warehouse_id: { type: 'int', required: true },
|
||||||
|
zone_code: { type: 'string', required: true },
|
||||||
|
zone_name: { type: 'string', required: true },
|
||||||
|
parent_id: { type: 'int', required: false },
|
||||||
|
x: { type: 'int', required: true },
|
||||||
|
y: { type: 'int', required: true },
|
||||||
|
z: { type: 'int', required: false, default: 0 },
|
||||||
|
length: { type: 'int', required: true },
|
||||||
|
width: { type: 'int', required: true },
|
||||||
|
height: { type: 'int', required: true },
|
||||||
|
rack_columns: { type: 'int', required: true },
|
||||||
|
rack_rows: { type: 'int', required: true },
|
||||||
|
rack_levels: { type: 'int', required: true },
|
||||||
|
direction: { type: 'enum', values: [ 'north', 'south', 'east', 'west' ], required: false },
|
||||||
|
color: { type: 'string', required: false },
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const rack = await ctx.service.location.createRackWithSpaces(params);
|
||||||
|
ctx.success(rack, '货架创建成功');
|
||||||
|
} catch (error) {
|
||||||
|
this.fail(error.message, 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取拣货路径
|
||||||
|
*/
|
||||||
|
async getPickPath() {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { warehouse_id } = ctx.query;
|
||||||
|
|
||||||
|
if (!warehouse_id) {
|
||||||
|
this.fail('仓库ID不能为空', 400);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const options = {
|
||||||
|
includeSpaces: ctx.query.include_spaces === 'true',
|
||||||
|
limit: parseInt(ctx.query.limit) || 50,
|
||||||
|
sortBy: ctx.query.sort_by || 'path_sequence',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await ctx.service.location.getPickPath(warehouse_id, options);
|
||||||
|
ctx.success(result);
|
||||||
|
} catch (error) {
|
||||||
|
this.fail(error.message, 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新货架位置
|
||||||
|
*/
|
||||||
|
async updateRackPosition() {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { rack_id } = ctx.params;
|
||||||
|
const { x, y, z } = ctx.request.body;
|
||||||
|
|
||||||
|
ctx.validate({
|
||||||
|
x: { type: 'int', required: true },
|
||||||
|
y: { type: 'int', required: true },
|
||||||
|
z: { type: 'int', required: false },
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const rack = await ctx.service.location.updateRackPosition(rack_id, { x, y, z });
|
||||||
|
ctx.success(rack, '货架位置更新成功');
|
||||||
|
} catch (error) {
|
||||||
|
this.fail(error.message, error.status || 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 重新计算拣货路径
|
||||||
|
*/
|
||||||
|
async recalculatePickPath() {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { warehouse_id } = ctx.request.body;
|
||||||
|
|
||||||
|
if (!warehouse_id) {
|
||||||
|
this.fail('仓库ID不能为空', 400);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await ctx.service.location._calculatePickPathForWarehouse(warehouse_id);
|
||||||
|
ctx.success(null, '拣货路径重新计算成功');
|
||||||
|
} catch (error) {
|
||||||
|
this.fail(error.message, 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新邻居关系
|
||||||
|
*/
|
||||||
|
async updateNeighbors() {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { warehouse_id } = ctx.request.body;
|
||||||
|
|
||||||
|
if (!warehouse_id) {
|
||||||
|
this.fail('仓库ID不能为空', 400);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await ctx.service.location.updateNeighborRelations(warehouse_id);
|
||||||
|
ctx.success(null, '邻居关系更新成功');
|
||||||
|
} catch (error) {
|
||||||
|
this.fail(error.message, 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取库区内的货架列表(按排序)
|
||||||
|
*/
|
||||||
|
async getAreaRacks() {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { area_id } = ctx.query;
|
||||||
|
|
||||||
|
if (!area_id) {
|
||||||
|
this.fail('库区ID不能为空', 400);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const racks = await ctx.model.LocationZone.findAll({
|
||||||
|
where: {
|
||||||
|
parent_id: area_id,
|
||||||
|
zone_type: 'rack',
|
||||||
|
is_active: true,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
order: [[ 'path_sequence', 'ASC' ]],
|
||||||
|
include: [{
|
||||||
|
model: ctx.model.LocationSpace,
|
||||||
|
as: 'spaces',
|
||||||
|
where: {
|
||||||
|
is_enabled: true,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
required: false,
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
ctx.success(racks);
|
||||||
|
} catch (error) {
|
||||||
|
this.fail(error.message, 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async getSpacesByRack(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { id } = data;
|
||||||
|
if (!id) {
|
||||||
|
return this.fail('货架ID不能为空');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
|
||||||
|
const spaces = await ctx.model.LocationSpace.findAll({
|
||||||
|
where: {
|
||||||
|
zone_id: id,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
order: [[ 'pick_sequence', 'ASC' ]],
|
||||||
|
});
|
||||||
|
return this.success('获取成功', { spaces, code: 200 });
|
||||||
|
} catch (e) {
|
||||||
|
return this.fail(e.message, 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async createRackWithSpaces(data) {
|
||||||
|
const { ctx, app, service } = this;
|
||||||
|
const { id } = data;
|
||||||
|
if (!id) {
|
||||||
|
return this.fail('货架ID不能为空');
|
||||||
|
}
|
||||||
|
const transaction = await ctx.model.transaction();
|
||||||
|
try {
|
||||||
|
const rack = await ctx.model.LocationZone.findOne({
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
if (!rack) {
|
||||||
|
throw new Error('货架不存在');
|
||||||
|
}
|
||||||
|
if (rack.zone_type != 'rack') {
|
||||||
|
throw new Error('仓库元素不为货架,拒绝生成仓位');
|
||||||
|
}
|
||||||
|
const message = await service.systems.locationZone.generateSpacesForRack(id, rack, transaction);
|
||||||
|
await transaction.commit();
|
||||||
|
return this.success(message, { code: 200 });
|
||||||
|
} catch (e) {
|
||||||
|
console.log('创建错误', e);
|
||||||
|
await transaction.rollback();
|
||||||
|
return this.fail(e.message, 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getSpaceInfo(data) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
const { id } = data;
|
||||||
|
try {
|
||||||
|
const data = await service.systems.locationZone.getSpaceInfo(id);
|
||||||
|
return this.success('获取成功', { data, code: 200 });
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
return this.fail('获取失败' + error.message, { code: 0 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateSpaceInfo(data) {
|
||||||
|
const { ctx, app, service } = this;
|
||||||
|
console.log('修改的数据', data);
|
||||||
|
const { id } = data;
|
||||||
|
if (!id) {
|
||||||
|
return this.fail('仓位ID不能为空');
|
||||||
|
}
|
||||||
|
const transaction = await ctx.model.transaction();
|
||||||
|
try {
|
||||||
|
const space = await ctx.model.LocationSpace.findOne({
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
warehouse_id: ctx.user.store_id,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
if (!space) {
|
||||||
|
throw new Error('仓位不存在');
|
||||||
|
}
|
||||||
|
if (data.custom_barcode) {
|
||||||
|
const { isUnique } = await service.systems.locationZone.checkBarcodeUnique(parseInt(id), data.custom_barcode);
|
||||||
|
if (!isUnique) {
|
||||||
|
throw new Error('自定义条码已存在');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const update_data = {
|
||||||
|
location_type_id: data.location_type_id || space.location_type_id,
|
||||||
|
custom_name: data.custom_name || null,
|
||||||
|
custom_barcode: data.custom_barcode || null,
|
||||||
|
space_status: data.space_status || space.space_status,
|
||||||
|
pick_sequence: data.pick_sequence || 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
await space.update(update_data);
|
||||||
|
await transaction.commit();
|
||||||
|
return this.success('保存成功', { code: 200 });
|
||||||
|
} catch (e) {
|
||||||
|
await transaction.rollback();
|
||||||
|
return this.fail('保存失败:' + e.message, { code: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = warehouseService;
|
||||||
383
app/service/systems/account_platform.js
Normal file
383
app/service/systems/account_platform.js
Normal file
@ -0,0 +1,383 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class AccountPlatformService extends Service {
|
||||||
|
/**
|
||||||
|
* 切换平台激活角色
|
||||||
|
* @param {number} accountId - 账号ID
|
||||||
|
* @param {number} accountStoreRoleId - 账号仓库角色关联ID
|
||||||
|
* @param {string} platformCode - 平台编码
|
||||||
|
* @return {Promise<Object>}
|
||||||
|
*/
|
||||||
|
async switchActiveRole(accountId, accountStoreRoleId, platformCode) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
|
||||||
|
// 使用事务确保数据一致性
|
||||||
|
const transaction = await ctx.model.transaction();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 验证角色关联的有效性
|
||||||
|
const accountStoreRole = await ctx.model.AccountStoreRole.findOne({
|
||||||
|
where: {
|
||||||
|
id: accountStoreRoleId,
|
||||||
|
account_id: accountId,
|
||||||
|
status: 1,
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!accountStoreRole) {
|
||||||
|
throw new Error('角色关联不存在或已失效');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 使用 upsert 切换激活角色
|
||||||
|
const [ platformActive, created ] = await ctx.model.AccountPlatformActive.upsert({
|
||||||
|
account_id: accountId,
|
||||||
|
account_store_role_id: accountStoreRoleId,
|
||||||
|
platform_code: platformCode,
|
||||||
|
}, {
|
||||||
|
transaction,
|
||||||
|
returning: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await transaction.commit();
|
||||||
|
|
||||||
|
// 3. 清理缓存
|
||||||
|
await this.clearPlatformCache(accountId, platformCode);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
created,
|
||||||
|
data: platformActive,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
await transaction.rollback();
|
||||||
|
|
||||||
|
// 处理唯一约束冲突
|
||||||
|
if (error.name === 'SequelizeUniqueConstraintError') {
|
||||||
|
// 如果是 account_store_role_id 和 platform_code 冲突,说明同一个平台不能关联到不同的账号
|
||||||
|
if (error.errors && error.errors.some(e => e.path === 'uk_account_store_role_platform')) {
|
||||||
|
throw new Error('该角色已被其他账号在同一平台激活');
|
||||||
|
}
|
||||||
|
throw new Error('平台激活状态更新失败,可能存在数据冲突');
|
||||||
|
}
|
||||||
|
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取平台当前激活角色
|
||||||
|
* @param {number} accountId - 账号ID
|
||||||
|
* @param {string} platformCode - 平台编码
|
||||||
|
* @param {boolean} useCache - 是否使用缓存
|
||||||
|
* @return {Promise<Object|null>}
|
||||||
|
*/
|
||||||
|
async getActiveRoleByPlatform(accountId, platformCode, useCache = true) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
|
||||||
|
const cacheKey = `platform_active:${accountId}:${platformCode}`;
|
||||||
|
|
||||||
|
// 尝试从缓存获取
|
||||||
|
if (useCache) {
|
||||||
|
try {
|
||||||
|
const cached = await app.getCacheAsync(cacheKey);
|
||||||
|
if (cached) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('获取平台激活缓存失败:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询数据库
|
||||||
|
const platformActive = await ctx.model.AccountPlatformActive.findOne({
|
||||||
|
where: {
|
||||||
|
account_id: accountId,
|
||||||
|
platform_code: platformCode,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.AccountStoreRole,
|
||||||
|
as: 'accountStoreRole',
|
||||||
|
where: { status: 1 },
|
||||||
|
required: true,
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.Role,
|
||||||
|
as: 'role',
|
||||||
|
attributes: [ 'id', 'name', 'code', 'permissions' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: ctx.model.Store,
|
||||||
|
as: 'store',
|
||||||
|
attributes: [ 'id', 'name', 'code' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!platformActive) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 整理返回数据
|
||||||
|
const result = {
|
||||||
|
account_id: accountId,
|
||||||
|
platform_code: platformCode,
|
||||||
|
role_id: platformActive.accountStoreRole.role_id,
|
||||||
|
role_name: platformActive.accountStoreRole.role.name,
|
||||||
|
role_code: platformActive.accountStoreRole.role.code,
|
||||||
|
role_permissions: platformActive.accountStoreRole.role.permissions,
|
||||||
|
store_id: platformActive.accountStoreRole.store_id,
|
||||||
|
store_name: platformActive.accountStoreRole.store.name,
|
||||||
|
store_code: platformActive.accountStoreRole.store.code,
|
||||||
|
created_at: platformActive.created_at,
|
||||||
|
updated_at: platformActive.updated_at,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 缓存结果
|
||||||
|
if (useCache) {
|
||||||
|
try {
|
||||||
|
await app.setCacheAsync(cacheKey, result, 1800); // 缓存30分钟
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('缓存平台激活状态失败:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量获取账号在多个平台的激活状态
|
||||||
|
* @param {number} accountId - 账号ID
|
||||||
|
* @param {Array<string>} platformCodes - 平台编码数组
|
||||||
|
* @return {Promise<Object>}
|
||||||
|
*/
|
||||||
|
async getMultiplePlatformActiveRoles(accountId, platformCodes) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const platformActives = await ctx.model.AccountPlatformActive.findAll({
|
||||||
|
where: {
|
||||||
|
account_id: accountId,
|
||||||
|
platform_code: platformCodes,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.AccountStoreRole,
|
||||||
|
as: 'accountStoreRole',
|
||||||
|
where: { status: 1 },
|
||||||
|
required: true,
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.Role,
|
||||||
|
as: 'role',
|
||||||
|
attributes: [ 'id', 'name', 'code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: ctx.model.Store,
|
||||||
|
as: 'store',
|
||||||
|
attributes: [ 'id', 'name', 'code' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 转换为平台编码为key的对象
|
||||||
|
const result = {};
|
||||||
|
platformActives.forEach(active => {
|
||||||
|
result[active.platform_code] = {
|
||||||
|
role_id: active.accountStoreRole.role_id,
|
||||||
|
role_name: active.accountStoreRole.role.name,
|
||||||
|
role_code: active.accountStoreRole.role.code,
|
||||||
|
store_id: active.accountStoreRole.store_id,
|
||||||
|
store_name: active.accountStoreRole.store.name,
|
||||||
|
store_code: active.accountStoreRole.store.code,
|
||||||
|
created_at: active.created_at,
|
||||||
|
updated_at: active.updated_at,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// 填充未设置的平台
|
||||||
|
platformCodes.forEach(code => {
|
||||||
|
if (!result[code]) {
|
||||||
|
result[code] = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取账号所有平台的激活状态
|
||||||
|
* @param {number} accountId - 账号ID
|
||||||
|
* @return {Promise<Array>}
|
||||||
|
*/
|
||||||
|
async getAllPlatformActives(accountId) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const platformActives = await ctx.model.AccountPlatformActive.findAll({
|
||||||
|
where: { account_id: accountId },
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.AccountStoreRole,
|
||||||
|
as: 'accountStoreRole',
|
||||||
|
where: { status: 1 },
|
||||||
|
required: true,
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.Role,
|
||||||
|
as: 'role',
|
||||||
|
attributes: [ 'id', 'name', 'code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: ctx.model.Store,
|
||||||
|
as: 'store',
|
||||||
|
attributes: [ 'id', 'name', 'code' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
order: [[ 'platform_code', 'ASC' ]],
|
||||||
|
});
|
||||||
|
|
||||||
|
return platformActives.map(active => ({
|
||||||
|
platform_code: active.platform_code,
|
||||||
|
role_id: active.accountStoreRole.role_id,
|
||||||
|
role_name: active.accountStoreRole.role.name,
|
||||||
|
role_code: active.accountStoreRole.role.code,
|
||||||
|
store_id: active.accountStoreRole.store_id,
|
||||||
|
store_name: active.accountStoreRole.store.name,
|
||||||
|
store_code: active.accountStoreRole.store.code,
|
||||||
|
created_at: active.created_at,
|
||||||
|
updated_at: active.updated_at,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除平台激活状态
|
||||||
|
* @param {number} accountId - 账号ID
|
||||||
|
* @param {string} platformCode - 平台编码
|
||||||
|
* @return {Promise<boolean>}
|
||||||
|
*/
|
||||||
|
async clearPlatformActive(accountId, platformCode) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await ctx.model.AccountPlatformActive.destroy({
|
||||||
|
where: {
|
||||||
|
account_id: accountId,
|
||||||
|
platform_code: platformCode,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 清理缓存
|
||||||
|
await this.clearPlatformCache(accountId, platformCode);
|
||||||
|
|
||||||
|
return result > 0;
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理平台缓存
|
||||||
|
* @param accountId
|
||||||
|
* @param platformCode
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
async clearPlatformCache(accountId, platformCode) {
|
||||||
|
const { app } = this;
|
||||||
|
const cacheKey = `platform_active:${accountId}:${platformCode}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await app.setCacheAsync(cacheKey, null, 0);
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('清理平台缓存失败:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取账号可用的角色列表
|
||||||
|
* @param {number} accountId - 账号ID
|
||||||
|
* @param {number} storeId - 仓库ID(可选)
|
||||||
|
* @return {Promise<Array>}
|
||||||
|
*/
|
||||||
|
async getAvailableRoles(accountId, storeId = null) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const where = {
|
||||||
|
account_id: accountId,
|
||||||
|
status: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (storeId) {
|
||||||
|
where.store_id = storeId;
|
||||||
|
}
|
||||||
|
|
||||||
|
const accountStoreRoles = await ctx.model.AccountStoreRole.findAll({
|
||||||
|
where,
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.Role,
|
||||||
|
as: 'role',
|
||||||
|
attributes: [ 'id', 'name', 'code', 'description' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: ctx.model.Store,
|
||||||
|
as: 'store',
|
||||||
|
attributes: [ 'id', 'name', 'code' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
order: [
|
||||||
|
[ 'store_id', 'ASC' ],
|
||||||
|
[ 'role_id', 'ASC' ],
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
return accountStoreRoles.map(item => ({
|
||||||
|
id: item.id,
|
||||||
|
account_id: item.account_id,
|
||||||
|
store_id: item.store_id,
|
||||||
|
store_name: item.store.name,
|
||||||
|
store_code: item.store.code,
|
||||||
|
role_id: item.role_id,
|
||||||
|
role_name: item.role.name,
|
||||||
|
role_code: item.role.code,
|
||||||
|
role_description: item.role.description,
|
||||||
|
real_name: item.real_name,
|
||||||
|
created_at: item.created_at,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据平台获取账号的当前仓库和角色
|
||||||
|
* @param {number} accountId - 账号ID
|
||||||
|
* @param {string} platformCode - 平台编码
|
||||||
|
* @return {Promise<Object|null>}
|
||||||
|
*/
|
||||||
|
async getCurrentContext(accountId, platformCode) {
|
||||||
|
const activeRole = await this.getActiveRoleByPlatform(accountId, platformCode);
|
||||||
|
|
||||||
|
if (!activeRole) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
account_id: accountId,
|
||||||
|
store_id: activeRole.store_id,
|
||||||
|
store_name: activeRole.store_name,
|
||||||
|
store_code: activeRole.store_code,
|
||||||
|
role_id: activeRole.role_id,
|
||||||
|
role_name: activeRole.role_name,
|
||||||
|
role_code: activeRole.role_code,
|
||||||
|
permissions: activeRole.role_permissions,
|
||||||
|
platform_code: platformCode,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = AccountPlatformService;
|
||||||
930
app/service/systems/auth/user.js
Normal file
930
app/service/systems/auth/user.js
Normal file
@ -0,0 +1,930 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class UserService extends Service {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户登录(重构版)
|
||||||
|
* @param {string} username - 用户名/手机号/邮箱
|
||||||
|
* @param {string} password - 密码
|
||||||
|
* @param {string} loginType - 登录类型: username, phone, email, auto
|
||||||
|
* @param {string} platformCode - 平台编码(web、pda、mini等)
|
||||||
|
* @return {Object} 登录结果
|
||||||
|
*/
|
||||||
|
async login(username, password, loginType = 'auto') {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 统一的认证错误信息
|
||||||
|
const authError = new Error('用户名或密码错误或账号状态异常');
|
||||||
|
authError.code = 'AUTH_FAILED';
|
||||||
|
|
||||||
|
// 1. 查找用户
|
||||||
|
const user = await this.findUserByIdentifier(username, loginType);
|
||||||
|
if (!user) {
|
||||||
|
app.coreLogger.warn(`登录失败: 用户不存在 [${username}]`);
|
||||||
|
throw authError;
|
||||||
|
}
|
||||||
|
console.log('登录获取用户信息', user);
|
||||||
|
// 2. 检查用户状态
|
||||||
|
try {
|
||||||
|
this.checkUserStatus(user);
|
||||||
|
} catch (statusError) {
|
||||||
|
app.coreLogger.warn(`登录失败: 用户状态异常 [${user.id}] - ${statusError.message}`);
|
||||||
|
throw authError;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 验证密码
|
||||||
|
const isPasswordValid = await user.verifyPassword(password);
|
||||||
|
if (!isPasswordValid) {
|
||||||
|
app.coreLogger.warn(`登录失败: 密码错误 [${user.id}]`);
|
||||||
|
throw authError;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 更新最后登录时间
|
||||||
|
await this.updateLastLoginTime(user.id);
|
||||||
|
|
||||||
|
// 5. 设置设备类型(用于菜单查询)
|
||||||
|
const platformCode = ctx.header.platform || 'web';
|
||||||
|
// 6. 获取用户完整信息
|
||||||
|
const userInfo = await this.findById(user.id);
|
||||||
|
console.log('用户信息', userInfo);
|
||||||
|
// 7. 如果用户有角色但当前平台没有激活角色,则自动设置一个
|
||||||
|
if (userInfo.roles && userInfo.roles.length > 0 && !userInfo.role_id) {
|
||||||
|
await this.ensurePlatformActiveRole(user.id, userInfo.roles[0].id, platformCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 8. 生成 JWT Token
|
||||||
|
const tokenPayload = {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
real_name: user.real_name,
|
||||||
|
platform_code: platformCode,
|
||||||
|
current_role_id: userInfo.employees_id,
|
||||||
|
current_store_id: userInfo.store_id || null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, {
|
||||||
|
expiresIn: app.config.jwt.expiresIn,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
real_name: user.real_name,
|
||||||
|
phone: user.phone,
|
||||||
|
email: user.email,
|
||||||
|
status: user.status,
|
||||||
|
last_login_at: user.last_login_at,
|
||||||
|
roles: userInfo.roles,
|
||||||
|
role_id: userInfo.role_id,
|
||||||
|
menus: userInfo.menus,
|
||||||
|
permissions: userInfo.permissions,
|
||||||
|
userRole: userInfo.userRole,
|
||||||
|
realName: userInfo.realName,
|
||||||
|
},
|
||||||
|
token,
|
||||||
|
},
|
||||||
|
code: 200,
|
||||||
|
message: '登录成功',
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
app.coreLogger.error(`登录异常: ${error.message}`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
data: null,
|
||||||
|
code: 0,
|
||||||
|
message: '用户名或密码错误或账号状态异常',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 切换角色(重构版)
|
||||||
|
* @param {Object} data - 切换角色数据
|
||||||
|
* @param {number} data.roleId - 角色关联ID (account_store_role.id)
|
||||||
|
* @param {string} data.platformCode - 平台编码(web、pda、mini等)
|
||||||
|
* @return {Object} 切换结果
|
||||||
|
*/
|
||||||
|
async changeRole(data) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
const user = ctx.state.user || ctx.user;
|
||||||
|
try {
|
||||||
|
// 验证角色关联是否存在且有效
|
||||||
|
const accountStoreRole = await ctx.model.AccountStoreEmployee.findOne({
|
||||||
|
where: {
|
||||||
|
id: data.roleId,
|
||||||
|
account_id: user.id,
|
||||||
|
status: 1,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.EmployeeRole,
|
||||||
|
as: 'employeeRole',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!accountStoreRole) {
|
||||||
|
throw new Error('角色不存在或未授权');
|
||||||
|
}
|
||||||
|
|
||||||
|
const platformCode = ctx.header.platform || 'web';
|
||||||
|
|
||||||
|
// 更新平台激活角色
|
||||||
|
await ctx.model.AccountPlatformActive.upsert({
|
||||||
|
account_id: user.id,
|
||||||
|
employee_id: data.roleId,
|
||||||
|
platform_code: platformCode,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 清理缓存
|
||||||
|
await this.clearUserCache(user.id);
|
||||||
|
|
||||||
|
// 获取更新后的用户信息
|
||||||
|
const userInfo = await this.findById(user.id);
|
||||||
|
|
||||||
|
const tokenPayload = {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
real_name: user.real_name,
|
||||||
|
platform_code: platformCode,
|
||||||
|
current_role_id: userInfo.employees_id,
|
||||||
|
current_store_id: accountStoreRole.store_id || null,
|
||||||
|
};
|
||||||
|
const newToken = app.jwt.sign(tokenPayload, app.config.jwt.secret, {
|
||||||
|
expiresIn: app.config.jwt.expiresIn,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
user: userInfo,
|
||||||
|
token: newToken,
|
||||||
|
},
|
||||||
|
code: 200,
|
||||||
|
message: '角色切换成功',
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
app.coreLogger.error(`切换角色失败: ${error.message}`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
data: null,
|
||||||
|
code: 0,
|
||||||
|
message: error.message || '角色切换失败',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取用户信息(重构版)
|
||||||
|
* @param {Object} data - 请求数据
|
||||||
|
* @return {Object} 用户信息
|
||||||
|
*/
|
||||||
|
async info(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
try {
|
||||||
|
const userId = ctx.userId || (ctx.user && ctx.user.id);
|
||||||
|
const user = await this.findById(userId);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: user,
|
||||||
|
code: 200,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
data: null,
|
||||||
|
code: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查找用户所有的角色以及对应的主体(重构版)
|
||||||
|
* @param {number} userId - 用户ID
|
||||||
|
* @param {string} platformCode - 平台编码
|
||||||
|
* @return {Promise<Array>}
|
||||||
|
*/
|
||||||
|
async getRoles(userId) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const platformCode = ctx.header.platform || 'web';
|
||||||
|
const project = ctx.header.project;
|
||||||
|
try {
|
||||||
|
// 获取用户的所有角色关联
|
||||||
|
const store_where = {
|
||||||
|
status: 1,
|
||||||
|
};
|
||||||
|
if (project != 'all') {
|
||||||
|
store_where.project = project;
|
||||||
|
}
|
||||||
|
console.log('store_where', store_where, project, platformCode, ctx.header);
|
||||||
|
const accountStoreEmployees = await ctx.model.AccountStoreEmployee.findAll({
|
||||||
|
where: {
|
||||||
|
account_id: userId,
|
||||||
|
status: 1,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.EmployeeRole,
|
||||||
|
as: 'employeeRole',
|
||||||
|
attributes: [ 'id', 'role_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: ctx.model.Store,
|
||||||
|
as: 'store',
|
||||||
|
attributes: [ 'id', 'company_name', 'project', 'auth_end' ],
|
||||||
|
where: store_where,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
order: [[ 'created_at', 'DESC' ]],
|
||||||
|
});
|
||||||
|
if (!accountStoreEmployees) {
|
||||||
|
throw ('没有符合的角色');
|
||||||
|
}
|
||||||
|
console.log('accountStoreEmployees>>>>>', accountStoreEmployees);
|
||||||
|
// 获取当前平台的激活角色
|
||||||
|
let activeEmployeeId = null;
|
||||||
|
let employee_id = null;
|
||||||
|
let realName = null;
|
||||||
|
let userRole = '';
|
||||||
|
|
||||||
|
const platformActive = await ctx.model.AccountPlatformActive.findOne({
|
||||||
|
where: {
|
||||||
|
account_id: userId,
|
||||||
|
platform_code: platformCode,
|
||||||
|
},
|
||||||
|
attributes: [ 'account_id', 'employee_id', 'platform_code' ],
|
||||||
|
});
|
||||||
|
if (platformActive) {
|
||||||
|
employee_id = platformActive.employee_id;
|
||||||
|
}
|
||||||
|
// 转换数据格式
|
||||||
|
const Employees = accountStoreEmployees.map(item => ({
|
||||||
|
id: item.id,
|
||||||
|
store_id: item.store_id,
|
||||||
|
store_name: item.store.company_name,
|
||||||
|
is_primary: platformActive && platformActive.employee_id === item.id ? 1 : 0,
|
||||||
|
real_name: item.real_name,
|
||||||
|
auth_end: item.store.auth_end,
|
||||||
|
role_type: item.store.project,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// 确定当前激活角色
|
||||||
|
for (const Employee of Employees) {
|
||||||
|
if (Employee.is_primary == 1) {
|
||||||
|
activeEmployeeId = Employee.id;
|
||||||
|
realName = Employee.real_name;
|
||||||
|
userRole = Employee.role_type == 1 ? 'warehouse' : 'customer';
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果没有激活角色,选择第一个
|
||||||
|
if (!activeEmployeeId && Employees.length > 0) {
|
||||||
|
activeEmployeeId = Employees[0].id;
|
||||||
|
realName = Employees[0].real_name;
|
||||||
|
userRole = Employees[0].role_type == 1 ? 'warehouse' : 'customer';
|
||||||
|
|
||||||
|
// 设置为激活角色
|
||||||
|
if (Employees[0].id) {
|
||||||
|
await this.ensurePlatformActiveRole(userId, Employees[0].id, platformCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取菜单和权限
|
||||||
|
const menus = await this.getMenus(activeEmployeeId);
|
||||||
|
|
||||||
|
console.log('获取菜单', activeEmployeeId, menus);
|
||||||
|
const permissions = await this.getPermissions(activeEmployeeId);
|
||||||
|
|
||||||
|
return { Employees, activeEmployeeId, menus, permissions, userRole, realName };
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取用户角色失败:', error);
|
||||||
|
return [[], null, [], [], '', null ];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据ID查找用户(重构版)
|
||||||
|
* @param {number} userId - 用户ID
|
||||||
|
* @param {string} platformCode - 平台编码
|
||||||
|
* @param useCache
|
||||||
|
* @return {Promise<Object>}
|
||||||
|
*/
|
||||||
|
async findById(userId, useCache = true) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const platformCode = ctx.header.platform || 'web';
|
||||||
|
const project = ctx.header.project;
|
||||||
|
console.log(`调用${ctx.query_count}次,平台为${platformCode}`);
|
||||||
|
ctx.query_count++;
|
||||||
|
try {
|
||||||
|
// 生成缓存key
|
||||||
|
const cacheKey = `user:info:${userId}:${platformCode}`;
|
||||||
|
|
||||||
|
// 1. 尝试从缓存获取
|
||||||
|
if (useCache) {
|
||||||
|
try {
|
||||||
|
const cachedUser = await this.app.getCacheAsync(cacheKey);
|
||||||
|
if (cachedUser) {
|
||||||
|
console.log('用户信息缓存命中:', userId);
|
||||||
|
return cachedUser;
|
||||||
|
}
|
||||||
|
} catch (cacheError) {
|
||||||
|
console.warn('获取用户缓存失败:', cacheError.message);
|
||||||
|
// 缓存失败不影响主流程,继续查询数据库
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 从数据库获取用户基本信息
|
||||||
|
const user = await this.ctx.model.Account.findOne({
|
||||||
|
where: { id: userId },
|
||||||
|
attributes: [ 'id', 'real_name', 'email', 'status', 'username', 'phone', 'last_login_at', 'last_login_ip' ],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
// 如果用户不存在,也缓存null值避免频繁查询
|
||||||
|
if (useCache) {
|
||||||
|
await this.setUserCache(cacheKey, null, 300); // 缓存5分钟
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 获取角色信息(这个方法内部也有缓存逻辑)
|
||||||
|
const { Employees, activeEmployeeId, menus, permissions, userRole, realName } = await this.getRoles(userId);
|
||||||
|
console.log('activeEmployeeId>>>>>>>>', activeEmployeeId);
|
||||||
|
// 4. 获取当前角色对应的仓库ID
|
||||||
|
let storeId = null;
|
||||||
|
let storeName = null;
|
||||||
|
let storeCode = null;
|
||||||
|
let roleName = null;
|
||||||
|
let auth_end = null;
|
||||||
|
let employees_name = null;
|
||||||
|
if (activeEmployeeId && Employees.length > 0) {
|
||||||
|
const currentRole = Employees.find(Employee => Employee.id === activeEmployeeId);
|
||||||
|
if (currentRole) {
|
||||||
|
storeId = currentRole.store_id;
|
||||||
|
storeName = currentRole.store_name;
|
||||||
|
storeCode = currentRole.store_code;
|
||||||
|
roleName = currentRole.role_name;
|
||||||
|
employees_name = currentRole.real_name;
|
||||||
|
auth_end = currentRole.auth_end;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const avatar = await this.getAvatarByEmployeeId(activeEmployeeId);
|
||||||
|
if (platformCode == 'pda' && !activeEmployeeId) {
|
||||||
|
throw ('无登录权限');
|
||||||
|
}
|
||||||
|
// 5. 组合用户信息
|
||||||
|
const userInfo = {
|
||||||
|
id: user.id,
|
||||||
|
status: user.status,
|
||||||
|
employees: Employees,
|
||||||
|
auth_end,
|
||||||
|
employees_id: activeEmployeeId,
|
||||||
|
employees_name: employees_name || '未命名',
|
||||||
|
loginIp: user.last_login_ip,
|
||||||
|
role_name: roleName,
|
||||||
|
store_id: storeId,
|
||||||
|
store_name: storeName,
|
||||||
|
store_code: storeCode,
|
||||||
|
menus,
|
||||||
|
permissions,
|
||||||
|
userRole,
|
||||||
|
platform_code: platformCode,
|
||||||
|
avatar,
|
||||||
|
cached_at: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
// 6. 设置缓存
|
||||||
|
if (useCache) {
|
||||||
|
console.log('设置用户缓存', userInfo);
|
||||||
|
await this.setUserCache(cacheKey, userInfo, 300); // 缓存5分钟
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('用户信息数据库查询:', userId);
|
||||||
|
return userInfo;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('根据ID查找用户失败:', error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 设置用户缓存
|
||||||
|
* @param cacheKey
|
||||||
|
* @param userInfo
|
||||||
|
* @param ttl
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
async setUserCache(cacheKey, userInfo, ttl = 300) {
|
||||||
|
try {
|
||||||
|
// 移除缓存标识字段
|
||||||
|
if (userInfo) {
|
||||||
|
const { cached_at, ...cacheData } = userInfo;
|
||||||
|
await this.app.setCacheAsync(cacheKey, cacheData, ttl);
|
||||||
|
} else {
|
||||||
|
await this.app.setCacheAsync(cacheKey, null, ttl);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('设置用户缓存失败:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async getAvatarByEmployeeId(employeeId) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
const { Op } = app.Sequelize;
|
||||||
|
let url = '';
|
||||||
|
const image = await ctx.model.FileReference.findOne({
|
||||||
|
where: {
|
||||||
|
business_type: 'avater',
|
||||||
|
business_id: employeeId,
|
||||||
|
},
|
||||||
|
include: [{
|
||||||
|
model: ctx.model.File,
|
||||||
|
as: 'file',
|
||||||
|
attributes: [ 'file_url' ],
|
||||||
|
required: true,
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
if (image) {
|
||||||
|
url = image.file.file_url;
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 清除用户缓存
|
||||||
|
* @param userId
|
||||||
|
* @param platformCode
|
||||||
|
*/
|
||||||
|
async clearUserCache(userId, platformCode = null) {
|
||||||
|
try {
|
||||||
|
if (platformCode) {
|
||||||
|
// 清除指定平台的缓存
|
||||||
|
const cacheKey = `user:info:${userId}:${platformCode}`;
|
||||||
|
await this.app.setCacheAsync(cacheKey, null, 1);
|
||||||
|
} else {
|
||||||
|
// 清除用户所有平台的缓存
|
||||||
|
const platforms = [ 'web', 'pda', 'mini', 'app' ];
|
||||||
|
for (const platform of platforms) {
|
||||||
|
const cacheKey = `user:info:${userId}:${platform}`;
|
||||||
|
await this.app.setCacheAsync(cacheKey, null, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 同时清除相关的缓存
|
||||||
|
await this.clearRelatedCache(userId);
|
||||||
|
|
||||||
|
console.log('用户缓存已清除:', userId);
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('清除用户缓存失败:', error.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 清除用户相关缓存
|
||||||
|
* @param userId
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
async clearRelatedCache(userId) {
|
||||||
|
try {
|
||||||
|
// 清除用户基本信息缓存
|
||||||
|
const basicCacheKeys = [
|
||||||
|
`user:basic:${userId}`,
|
||||||
|
`account:username:${userId}`,
|
||||||
|
`account:phone:${userId}`,
|
||||||
|
`account:email:${userId}`,
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const key of basicCacheKeys) {
|
||||||
|
await this.app.setCacheAsync(key, null, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清除用户角色缓存
|
||||||
|
const roleCacheKey = `user:roles:${userId}`;
|
||||||
|
await this.app.setCacheAsync(roleCacheKey, null, 1);
|
||||||
|
|
||||||
|
// 清除用户权限缓存
|
||||||
|
const permCacheKeys = [
|
||||||
|
`user:permissions:${userId}`,
|
||||||
|
`user:menus:${userId}`,
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const key of permCacheKeys) {
|
||||||
|
await this.app.setCacheAsync(key, null, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('清除相关缓存失败:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 获取权限列表(重构版)
|
||||||
|
* @param {number} roleId - 角色ID
|
||||||
|
* @param activeEmployeeId
|
||||||
|
* @return {Promise<Array>}
|
||||||
|
*/
|
||||||
|
async getPermissions(activeEmployeeId) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
const { Sequelize } = app;
|
||||||
|
const { Op } = Sequelize;
|
||||||
|
if (!activeEmployeeId) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 获取员工的角色
|
||||||
|
const roles = await ctx.model.EmployeeRole.findAll({
|
||||||
|
where: {
|
||||||
|
employee_id: activeEmployeeId,
|
||||||
|
},
|
||||||
|
raw: true, // 获取纯数据对象
|
||||||
|
});
|
||||||
|
console.log('员工绑定的角色', roles);
|
||||||
|
if (!roles || roles.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const roleIds = roles.map(item => item.role_id);
|
||||||
|
|
||||||
|
// 2. 获取角色的权限
|
||||||
|
const rolePermissions = await ctx.model.RolePermission.findAll({
|
||||||
|
where: {
|
||||||
|
role_id: {
|
||||||
|
[Op.in]: roleIds,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
if (!rolePermissions || rolePermissions.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const permissionIds = rolePermissions.map(item => item.permission_id);
|
||||||
|
|
||||||
|
const permissions = await ctx.model.Permission.findAll({
|
||||||
|
where: {
|
||||||
|
id: {
|
||||||
|
[Op.in]: permissionIds,
|
||||||
|
},
|
||||||
|
// 修正 like 查询
|
||||||
|
type: {
|
||||||
|
[ctx.app.Sequelize.Op.notLike]: '%_pages',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
attributes: [ 'id', 'path', 'type' ],
|
||||||
|
order: [
|
||||||
|
[ 'sort', 'ASC' ],
|
||||||
|
],
|
||||||
|
});
|
||||||
|
console.log('permissions列表', permissions);
|
||||||
|
if (!permissions) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return permissions.map(item => item.path);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取权限列表失败:', error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async getMenus(activeEmployeeId) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
const { Sequelize } = app;
|
||||||
|
const { Op } = Sequelize;
|
||||||
|
console.log('获取员工菜单员工id:', activeEmployeeId);
|
||||||
|
if (!ctx.header.platform || !activeEmployeeId) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 获取员工的角色
|
||||||
|
const roles = await ctx.model.EmployeeRole.findAll({
|
||||||
|
where: {
|
||||||
|
employee_id: activeEmployeeId,
|
||||||
|
},
|
||||||
|
raw: true, // 获取纯数据对象
|
||||||
|
});
|
||||||
|
console.log('员工绑定的角色', roles);
|
||||||
|
if (!roles || roles.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const roleIds = roles.map(item => item.role_id);
|
||||||
|
|
||||||
|
// 2. 获取角色的权限
|
||||||
|
const rolePermissions = await ctx.model.RolePermission.findAll({
|
||||||
|
where: {
|
||||||
|
role_id: {
|
||||||
|
[Op.in]: roleIds,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
if (!rolePermissions || rolePermissions.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const permissionIds = rolePermissions.map(item => item.permission_id);
|
||||||
|
|
||||||
|
// 3. 获取权限对应的菜单(根据设备筛选)
|
||||||
|
const permissions = await ctx.model.Permission.findAll({
|
||||||
|
where: {
|
||||||
|
id: {
|
||||||
|
[Op.in]: permissionIds,
|
||||||
|
},
|
||||||
|
// 修正 like 查询
|
||||||
|
type: {
|
||||||
|
[Op.like]: `${ctx.header.platform}_%`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
order: [
|
||||||
|
[ 'sort', 'ASC' ],
|
||||||
|
],
|
||||||
|
});
|
||||||
|
if (!permissions || permissions.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
return this.convertToRoutes(permissions);
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('获取菜单列表失败:', error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 转换权限为路由格式(保持不变)
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
async convertToRoutes(data) {
|
||||||
|
const map = new Map();
|
||||||
|
const roots = [];
|
||||||
|
|
||||||
|
// 创建所有节点的映射
|
||||||
|
data.forEach(item => {
|
||||||
|
map.set(item.id, {
|
||||||
|
id: item.id,
|
||||||
|
path: item.path,
|
||||||
|
component: item.component,
|
||||||
|
name: item.name,
|
||||||
|
redirect: item.redirect,
|
||||||
|
meta: {
|
||||||
|
title: item.meta_title,
|
||||||
|
icon: item.meta_icon,
|
||||||
|
},
|
||||||
|
hidden: item.hidden === 1,
|
||||||
|
alwaysShow: item.always_show === 1,
|
||||||
|
sort: item.sort,
|
||||||
|
children: [],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 构建树形结构
|
||||||
|
data.forEach(item => {
|
||||||
|
const node = map.get(item.id);
|
||||||
|
if (item.parent_id === 0) {
|
||||||
|
roots.push(node);
|
||||||
|
} else {
|
||||||
|
const parent = map.get(item.parent_id);
|
||||||
|
if (parent) {
|
||||||
|
parent.children.push(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 递归排序函数
|
||||||
|
const sortTree = nodes => {
|
||||||
|
if (!nodes || nodes.length === 0) return;
|
||||||
|
|
||||||
|
nodes.sort((a, b) => {
|
||||||
|
return a.sort - b.sort || a.id - b.id;
|
||||||
|
});
|
||||||
|
|
||||||
|
nodes.forEach(node => {
|
||||||
|
if (node.children && node.children.length > 0) {
|
||||||
|
sortTree(node.children);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// 从根节点开始排序
|
||||||
|
sortTree(roots);
|
||||||
|
|
||||||
|
// 移除辅助字段
|
||||||
|
const cleanNode = node => {
|
||||||
|
const { id, sort, ...rest } = node;
|
||||||
|
if (rest.children && rest.children.length > 0) {
|
||||||
|
rest.children = rest.children.map(child => cleanNode(child));
|
||||||
|
}
|
||||||
|
return rest;
|
||||||
|
};
|
||||||
|
|
||||||
|
return roots.map(root => cleanNode(root));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据标识符查找用户(已重构)
|
||||||
|
* @param identifier
|
||||||
|
* @param type
|
||||||
|
* @param useCache
|
||||||
|
*/
|
||||||
|
async findUserByIdentifier(identifier, type = 'auto', useCache = true) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
|
||||||
|
let user;
|
||||||
|
|
||||||
|
if (type === 'auto') {
|
||||||
|
// 自动判断类型
|
||||||
|
const Op = app.Sequelize.Op;
|
||||||
|
|
||||||
|
if (/^1[3-9]\d{9}$/.test(identifier)) {
|
||||||
|
// 手机号格式
|
||||||
|
user = await ctx.model.Account.findOne({
|
||||||
|
where: { phone: identifier },
|
||||||
|
});
|
||||||
|
} else if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(identifier)) {
|
||||||
|
// 邮箱格式
|
||||||
|
user = await ctx.model.Account.findOne({
|
||||||
|
where: { email: identifier },
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// 默认按用户名
|
||||||
|
user = await ctx.model.Account.findOne({
|
||||||
|
where: { username: identifier },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 指定类型
|
||||||
|
let whereCondition = {};
|
||||||
|
switch (type) {
|
||||||
|
case 'phone':
|
||||||
|
whereCondition = { phone: identifier };
|
||||||
|
break;
|
||||||
|
case 'email':
|
||||||
|
whereCondition = { email: identifier };
|
||||||
|
break;
|
||||||
|
case 'username':
|
||||||
|
default:
|
||||||
|
whereCondition = { username: identifier };
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
user = await ctx.model.Account.findOne({
|
||||||
|
where: whereCondition,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user) {
|
||||||
|
// 设置标志,表示不隐藏敏感字段
|
||||||
|
user._hideSensitive = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查用户状态(保持不变)
|
||||||
|
* @param user
|
||||||
|
*/
|
||||||
|
checkUserStatus(user) {
|
||||||
|
if (user.status === 0) {
|
||||||
|
throw new Error('账号已被禁用,请联系管理员');
|
||||||
|
}
|
||||||
|
if (user.status === 2) {
|
||||||
|
throw new Error('账号已离职,无法登录');
|
||||||
|
}
|
||||||
|
if (user.status !== 1) {
|
||||||
|
throw new Error('账号状态异常');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证密码(重构版)
|
||||||
|
* @param inputPassword
|
||||||
|
* @param storedHash
|
||||||
|
* @param salt
|
||||||
|
*/
|
||||||
|
async verifyPassword(inputPassword, storedHash, salt) {
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const hash = crypto.createHash('sha256');
|
||||||
|
hash.update(inputPassword + salt);
|
||||||
|
const encryptedPassword = hash.digest('hex');
|
||||||
|
|
||||||
|
if (encryptedPassword !== storedHash) {
|
||||||
|
throw new Error('密码错误');
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加密密码(保持不变)
|
||||||
|
* @param password
|
||||||
|
* @param salt
|
||||||
|
*/
|
||||||
|
async encryptPassword(password, salt) {
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const hash = crypto.createHash('sha256');
|
||||||
|
hash.update(password + salt);
|
||||||
|
return hash.digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成密码盐(保持不变)
|
||||||
|
*/
|
||||||
|
generateSalt() {
|
||||||
|
const crypto = require('crypto');
|
||||||
|
return crypto.randomBytes(10).toString('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新最后登录时间(重构版)
|
||||||
|
* @param userId
|
||||||
|
*/
|
||||||
|
async updateLastLoginTime(userId) {
|
||||||
|
const { ctx } = this;
|
||||||
|
console.log('登录上下文', ctx.request.header['x-real-ip']);
|
||||||
|
await ctx.model.Account.update({
|
||||||
|
last_login_at: new Date(),
|
||||||
|
last_login_ip: ctx.request.header['x-real-ip'],
|
||||||
|
}, {
|
||||||
|
where: { id: userId },
|
||||||
|
});
|
||||||
|
await this.clearUserCache(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 确保平台激活角色存在
|
||||||
|
* @param accountId
|
||||||
|
* @param accountStoreRoleId
|
||||||
|
* @param platformCode
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
async ensurePlatformActiveRole(accountId, accountStoreRoleId, platformCode) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await ctx.model.AccountPlatformActive.upsert({
|
||||||
|
account_id: accountId,
|
||||||
|
employee_id: accountStoreRoleId,
|
||||||
|
platform_code: platformCode,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('设置平台激活角色失败:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户注册(重构版)
|
||||||
|
* @param userInfo
|
||||||
|
*/
|
||||||
|
async register(userInfo) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
|
||||||
|
// 检查用户名是否已存在
|
||||||
|
const existingUser = await this.findUserByIdentifier(userInfo.username, 'username');
|
||||||
|
if (existingUser) {
|
||||||
|
throw new Error('用户名已存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成密码盐
|
||||||
|
const salt = this.generateSalt();
|
||||||
|
|
||||||
|
// 加密密码
|
||||||
|
const passwordHash = await this.encryptPassword(userInfo.password, salt);
|
||||||
|
|
||||||
|
// 创建用户
|
||||||
|
const user = await ctx.model.Account.create({
|
||||||
|
username: userInfo.username,
|
||||||
|
email: userInfo.email || '',
|
||||||
|
password_hash: passwordHash,
|
||||||
|
real_name: userInfo.real_name || '',
|
||||||
|
status: 1,
|
||||||
|
salt,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
userId: user.id,
|
||||||
|
username: user.username,
|
||||||
|
code: 200,
|
||||||
|
message: '注册成功',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = UserService;
|
||||||
534
app/service/systems/delivery_order.js
Normal file
534
app/service/systems/delivery_order.js
Normal file
@ -0,0 +1,534 @@
|
|||||||
|
'use strict';
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class DeliveryOrderService extends Service {
|
||||||
|
async addOrder(data, info) {
|
||||||
|
const { ctx } = this;
|
||||||
|
if (!info.warehouseId) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: '订单创建失败: 非法参数',
|
||||||
|
data: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId);
|
||||||
|
const { deliveryOrder, orderLines } = data.request;
|
||||||
|
|
||||||
|
// 开启事务
|
||||||
|
const transaction = await ctx.model.transaction();
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!info.storeId) {
|
||||||
|
throw new Error('非法参数');
|
||||||
|
}
|
||||||
|
if (!deliveryOrder || !deliveryOrder.deliveryOrderCode) {
|
||||||
|
throw new Error('订单信息不完整');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查订单是否已存在(根据唯一索引)
|
||||||
|
const existingOrder = await DeliveryModel.findOne({
|
||||||
|
where: {
|
||||||
|
delivery_order_code: deliveryOrder.deliveryOrderCode,
|
||||||
|
store_id: info.storeId,
|
||||||
|
warehouse_id: info.warehouseId,
|
||||||
|
},
|
||||||
|
attributes: [ 'id' ],
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
if (existingOrder) {
|
||||||
|
await transaction.rollback();
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: '订单已存在',
|
||||||
|
data: { deliveryOrderId: existingOrder.id },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 准备订单数据
|
||||||
|
const orderData = await this.prepareOrderData(deliveryOrder, info);
|
||||||
|
|
||||||
|
// 创建订单
|
||||||
|
const createdOrder = await DeliveryModel.create(orderData, { transaction });
|
||||||
|
const orderId = createdOrder.id;
|
||||||
|
|
||||||
|
let itemsInfo = null;
|
||||||
|
// 添加订单明细
|
||||||
|
if (orderLines && (orderLines.orderLine)) {
|
||||||
|
itemsInfo = await this.addOrderLines(
|
||||||
|
orderLines.orderLine,
|
||||||
|
orderId,
|
||||||
|
info,
|
||||||
|
transaction
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
throw new Error('[订单无明细]');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新订单统计信息 - 直接使用itemsInfo中的计算结果
|
||||||
|
if (itemsInfo) {
|
||||||
|
const stats = {
|
||||||
|
items: itemsInfo.items_str || '', // 原始结构字符串
|
||||||
|
items_count: itemsInfo.stock_count || 0, // 商品种类数
|
||||||
|
items_total: itemsInfo.item_total_count || 0, // 商品总数(直接使用计算结果)
|
||||||
|
items_weight: itemsInfo.total_weight || 0, // 总重量
|
||||||
|
items_hash: this.generateItemsHash(itemsInfo), // 哈希值
|
||||||
|
items_crc: this.calculateCRC32(itemsInfo.items_str || ''), // CRC校验
|
||||||
|
updated_at: new Date(),
|
||||||
|
};
|
||||||
|
|
||||||
|
await DeliveryModel.update(
|
||||||
|
stats,
|
||||||
|
{
|
||||||
|
where: { id: orderId },
|
||||||
|
transaction,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// 记录详细日志
|
||||||
|
ctx.logger.info('[订单统计信息已更新]', {
|
||||||
|
orderId,
|
||||||
|
orderCode: deliveryOrder.deliveryOrderCode,
|
||||||
|
stats: {
|
||||||
|
items_count: stats.items_count,
|
||||||
|
items_total: stats.items_total,
|
||||||
|
items_weight: stats.items_weight,
|
||||||
|
items_hash_preview: stats.items_hash?.substring(0, 8) + '...',
|
||||||
|
items_crc: stats.items_crc,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 异步处理:订单入队列
|
||||||
|
this.addOrderToQueue(orderId, info.warehouseId);
|
||||||
|
|
||||||
|
await transaction.commit();
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: '订单创建成功',
|
||||||
|
data: {
|
||||||
|
orderId,
|
||||||
|
stats: itemsInfo ? {
|
||||||
|
items_count: itemsInfo.stock_count,
|
||||||
|
items_total: itemsInfo.item_total_count,
|
||||||
|
items_weight: itemsInfo.total_weight,
|
||||||
|
} : null,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('创建订单失败:', error);
|
||||||
|
// 回滚事务
|
||||||
|
await transaction.rollback();
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: `订单创建失败: ${error.message}`,
|
||||||
|
data: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成订单结构哈希值
|
||||||
|
* 直接使用itemsInfo中的items_str
|
||||||
|
* @param itemsInfo
|
||||||
|
*/
|
||||||
|
generateItemsHash(itemsInfo) {
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
if (!itemsInfo || !itemsInfo.items_str) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成哈希
|
||||||
|
return crypto.createHash('md5')
|
||||||
|
.update(itemsInfo.items_str)
|
||||||
|
.digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算CRC32校验码
|
||||||
|
* @param str
|
||||||
|
*/
|
||||||
|
calculateCRC32(str) {
|
||||||
|
if (!str) return 0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const crc32 = require('crc-32');
|
||||||
|
return crc32.str(str) >>> 0; // 转为无符号整数
|
||||||
|
} catch (error) {
|
||||||
|
// 降级方案:简单校验和
|
||||||
|
let crc = 0;
|
||||||
|
for (let i = 0; i < str.length; i++) {
|
||||||
|
crc = (crc + str.charCodeAt(i)) & 0xFFFFFFFF;
|
||||||
|
}
|
||||||
|
return crc;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 准备订单数据
|
||||||
|
// 准备订单数据
|
||||||
|
async prepareOrderData(deliveryOrder, info) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
const {
|
||||||
|
deliveryOrderCode,
|
||||||
|
preDeliveryOrderCode,
|
||||||
|
preDeliveryOrderId,
|
||||||
|
orderType,
|
||||||
|
warehouseCode,
|
||||||
|
orderFlag,
|
||||||
|
sourcePlatformCode,
|
||||||
|
sourcePlatformName,
|
||||||
|
createTime,
|
||||||
|
placeOrderTime,
|
||||||
|
payTime,
|
||||||
|
payNo,
|
||||||
|
shopNick,
|
||||||
|
sellerNick,
|
||||||
|
buyerNick,
|
||||||
|
operatorName,
|
||||||
|
operateTime,
|
||||||
|
totalAmount,
|
||||||
|
itemAmount,
|
||||||
|
discountAmount,
|
||||||
|
freight,
|
||||||
|
arAmount,
|
||||||
|
gotAmount,
|
||||||
|
logisticsCode,
|
||||||
|
logisticsName,
|
||||||
|
expressCode,
|
||||||
|
logisticsAreaCode,
|
||||||
|
isUrgency,
|
||||||
|
invoiceFlag,
|
||||||
|
senderInfo,
|
||||||
|
receiverInfo,
|
||||||
|
} = deliveryOrder;
|
||||||
|
|
||||||
|
let platformCode = sourcePlatformCode;
|
||||||
|
let platformName = sourcePlatformName;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 验证平台代码是否存在
|
||||||
|
const platformInfo = await service.systems.platform.checkPlatformExists(
|
||||||
|
sourcePlatformCode,
|
||||||
|
info.warehouseId
|
||||||
|
);
|
||||||
|
|
||||||
|
if (platformInfo) {
|
||||||
|
// 平台存在,使用数据库中的平台信息
|
||||||
|
platformCode = platformInfo.code;
|
||||||
|
platformName = platformInfo.name;
|
||||||
|
|
||||||
|
ctx.logger.info(`平台验证通过: ${sourcePlatformCode} -> ${platformCode} (${platformName})`);
|
||||||
|
} else {
|
||||||
|
// 平台不存在,抛出错误
|
||||||
|
throw new Error(`平台代码 ${sourcePlatformCode} 在仓库 ${info.warehouseId} 中不存在`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error(`平台验证失败: ${error.message}`, {
|
||||||
|
platformCode: sourcePlatformCode,
|
||||||
|
warehouseId: info.warehouseId,
|
||||||
|
deliveryOrderCode,
|
||||||
|
});
|
||||||
|
throw error; // 抛出错误,让上层捕获
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
delivery_order_code: deliveryOrderCode,
|
||||||
|
pre_delivery_order_code: preDeliveryOrderCode || '',
|
||||||
|
pre_delivery_order_id: preDeliveryOrderId || '',
|
||||||
|
order_type: orderType,
|
||||||
|
warehouse_code: warehouseCode,
|
||||||
|
order_flag: orderFlag || '',
|
||||||
|
// 使用验证后的平台信息
|
||||||
|
source_platform_code: platformCode,
|
||||||
|
source_platform_name: platformName,
|
||||||
|
create_at: createTime ? new Date(createTime) : new Date(),
|
||||||
|
place_order_time: placeOrderTime ? new Date(placeOrderTime) : null,
|
||||||
|
pay_time: payTime ? new Date(payTime) : null,
|
||||||
|
pay_no: payNo || '',
|
||||||
|
shop_nick: shopNick,
|
||||||
|
seller_nick: sellerNick,
|
||||||
|
buyer_nick: buyerNick,
|
||||||
|
operator_name: operatorName,
|
||||||
|
operate_time: operateTime ? new Date(operateTime) : null,
|
||||||
|
total_amount: totalAmount ? parseFloat(totalAmount) : 0,
|
||||||
|
item_amount: itemAmount ? parseFloat(itemAmount) : 0,
|
||||||
|
discount_amount: discountAmount ? parseFloat(discountAmount) : 0,
|
||||||
|
freight: freight ? parseFloat(freight) : 0,
|
||||||
|
ar_amount: arAmount ? parseFloat(arAmount) : 0,
|
||||||
|
got_amount: gotAmount ? parseFloat(gotAmount) : 0,
|
||||||
|
logistics_code: logisticsCode,
|
||||||
|
logistics_name: logisticsName,
|
||||||
|
express_code: expressCode || '',
|
||||||
|
logistics_area_code: logisticsAreaCode || '',
|
||||||
|
is_urgency: isUrgency || 'N',
|
||||||
|
invoice_flag: invoiceFlag || 'N',
|
||||||
|
status: 'pedding',
|
||||||
|
// 收件人信息
|
||||||
|
name: receiverInfo?.name || '',
|
||||||
|
tel: receiverInfo?.tel || '',
|
||||||
|
mobile: receiverInfo?.mobile || '',
|
||||||
|
email: receiverInfo?.email || '',
|
||||||
|
country_code: receiverInfo?.countryCode || '',
|
||||||
|
province: receiverInfo?.province || '',
|
||||||
|
city: receiverInfo?.city || '',
|
||||||
|
area: receiverInfo?.area || '',
|
||||||
|
town: receiverInfo?.town || '',
|
||||||
|
detail_address: receiverInfo?.detailAddress || '',
|
||||||
|
zip_code: receiverInfo?.zipCode || '',
|
||||||
|
// 发件人信息(如果需要存储)
|
||||||
|
// 业务关联ID
|
||||||
|
store_id: info.storeId,
|
||||||
|
warehouse_id: info.warehouseId,
|
||||||
|
from_key: info.appKey,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加订单明细
|
||||||
|
async addOrderLines(orderLines, orderId, info, transaction) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
const { warehouseId, appKey, storeId } = info;
|
||||||
|
let order_items = [];
|
||||||
|
|
||||||
|
if (orderLines && typeof orderLines === 'object') {
|
||||||
|
if (orderLines.itemCode) {
|
||||||
|
order_items = [ orderLines ];
|
||||||
|
} else if (Array.isArray(orderLines)) {
|
||||||
|
order_items = orderLines;
|
||||||
|
} else if (orderLines.orderLine && Array.isArray(orderLines.orderLine)) {
|
||||||
|
order_items = orderLines.orderLine;
|
||||||
|
} else if (orderLines.orderLine && typeof orderLines.orderLine === 'object') {
|
||||||
|
order_items = [ orderLines.orderLine ];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!order_items || !Array.isArray(order_items) || order_items.length === 0) {
|
||||||
|
throw new Error('没有有效的订单明细数据');
|
||||||
|
}
|
||||||
|
|
||||||
|
const OrderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||||||
|
|
||||||
|
const lineData = [];
|
||||||
|
const errors = [];
|
||||||
|
const stockQuantityMap = new Map(); // stock_id -> 数量
|
||||||
|
const stockWeightMap = new Map(); // stock_id -> 单件重量(grossWeight)
|
||||||
|
const processedItemIds = new Set();
|
||||||
|
|
||||||
|
console.log('order_items', order_items);
|
||||||
|
|
||||||
|
for (let i = 0; i < order_items.length; i++) {
|
||||||
|
const line = order_items[i];
|
||||||
|
console.log('line', line);
|
||||||
|
|
||||||
|
// 跳过空值
|
||||||
|
if (!line || typeof line !== 'object') {
|
||||||
|
errors.push(`第${i + 1}行: 数据格式无效`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 数量验证
|
||||||
|
const planQty = line.planQty ? parseInt(line.planQty) : 0;
|
||||||
|
if (planQty <= 0) {
|
||||||
|
errors.push(`商品《${line.itemName}》数量必须大于0`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let wms_stock = null;
|
||||||
|
if (!line.itemId) {
|
||||||
|
console.log('ERP不处理WMS的外部商品编码');
|
||||||
|
// 查找唯一键
|
||||||
|
wms_stock = await app.model.StockStore.findOne({ where: {
|
||||||
|
item_code: line.itemCode,
|
||||||
|
app_key: appKey,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
store_id: storeId,
|
||||||
|
}, transaction });
|
||||||
|
} else {
|
||||||
|
wms_stock = await app.model.StockStore.findByPk(line.itemId, { transaction });
|
||||||
|
}
|
||||||
|
// 如果没有itemId,直接记录错误
|
||||||
|
if (!wms_stock) {
|
||||||
|
errors.push(`商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemId = parseInt(wms_stock.id);
|
||||||
|
// ========== 核心库存检查逻辑 ==========
|
||||||
|
const stockResult = await ctx.service.systems.stockStore.getItemStorages(wms_stock.id, transaction);
|
||||||
|
if (!stockResult.success) {
|
||||||
|
errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n${stockResult.error}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { stock, storage } = stockResult.data;
|
||||||
|
const stockId = storage.id;
|
||||||
|
|
||||||
|
if (!stockId) {
|
||||||
|
errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存记录不存在`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (processedItemIds.has(itemId)) {
|
||||||
|
errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》在同一订单中重复出现`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
processedItemIds.add(itemId);
|
||||||
|
|
||||||
|
const totalQtyForStock = (stockQuantityMap.get(stockId) || 0) + planQty;
|
||||||
|
stockQuantityMap.set(stockId, totalQtyForStock);
|
||||||
|
|
||||||
|
// 记录商品重量(如果storage中有grossWeight)
|
||||||
|
if (storage.grossWeight !== undefined && storage.grossWeight !== null) {
|
||||||
|
const weight = parseFloat(storage.grossWeight) || 0;
|
||||||
|
stockWeightMap.set(stockId, weight);
|
||||||
|
} else {
|
||||||
|
// 如果库存中没有重量信息,记录0
|
||||||
|
stockWeightMap.set(stockId, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (storage.canUse < totalQtyForStock) {
|
||||||
|
errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存不足,可用 ${storage.canUse},需求 ${totalQtyForStock}`);
|
||||||
|
stockQuantityMap.set(stockId, totalQtyForStock - planQty);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 锁定库存
|
||||||
|
const lockResult = await ctx.service.systems.stockStore.lockItemStorages(
|
||||||
|
storage.id,
|
||||||
|
planQty,
|
||||||
|
transaction
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!lockResult.success) {
|
||||||
|
errors.push(`SKU${wms_stock.id}商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》\n锁定失败: ${lockResult.error}`);
|
||||||
|
stockQuantityMap.set(stockId, totalQtyForStock - planQty);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// ========== 库存检查逻辑结束 ==========
|
||||||
|
|
||||||
|
// 所有检查通过,准备订单行数据
|
||||||
|
lineData.push({
|
||||||
|
order_id: orderId,
|
||||||
|
actual_price: this.safeParseFloat(line.actualPrice, 0),
|
||||||
|
retail_price: this.safeParseFloat(line.retailPrice, 0),
|
||||||
|
ext_code: line.extCode || '',
|
||||||
|
inventory_type: line.inventoryType || '',
|
||||||
|
item_code: line.itemCode || '',
|
||||||
|
item_id: line.itemId || null,
|
||||||
|
item_name: line.itemName || '',
|
||||||
|
order_line_no: line.orderLineNo || `${i + 1}`,
|
||||||
|
owner_code: line.ownerCode || '',
|
||||||
|
plan_qty: planQty,
|
||||||
|
source_order_code: line.sourceOrderCode || '',
|
||||||
|
sub_source_order_code: line.subSourceOrderCode || '',
|
||||||
|
extend_props: line.extendProps ?
|
||||||
|
(typeof line.extendProps === 'string' ? line.extendProps : JSON.stringify(line.extendProps))
|
||||||
|
: null,
|
||||||
|
// 可选:记录重量信息到明细
|
||||||
|
item_weight: stockWeightMap.get(stockId) || 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 计算订单统计信息 ==========
|
||||||
|
let items_str = '';
|
||||||
|
let total_weight = 0; // 总重量
|
||||||
|
let stock_count = 0; // stock种类数
|
||||||
|
let item_total_count = 0; // 商品总数
|
||||||
|
|
||||||
|
if (stockQuantityMap.size > 0) {
|
||||||
|
// 生成结构字符串
|
||||||
|
const sortedStocks = Array.from(stockQuantityMap.entries())
|
||||||
|
.sort(([ stockIdA ], [ stockIdB ]) => stockIdA - stockIdB)
|
||||||
|
.map(([ stockId, quantity ]) => {
|
||||||
|
// 可选:在字符串中包含重量信息
|
||||||
|
const weight = stockWeightMap.get(stockId) || 0;
|
||||||
|
return `${stockId}+${quantity}${weight > 0 ? `@${weight}` : ''}`;
|
||||||
|
});
|
||||||
|
items_str = sortedStocks.join('|');
|
||||||
|
|
||||||
|
// 计算统计信息
|
||||||
|
stock_count = stockQuantityMap.size; // stock种类数
|
||||||
|
|
||||||
|
// 计算商品总数
|
||||||
|
item_total_count = Array.from(stockQuantityMap.values())
|
||||||
|
.reduce((sum, quantity) => sum + (parseInt(quantity) || 0), 0);
|
||||||
|
|
||||||
|
// 计算总重量:重量 × 数量
|
||||||
|
total_weight = Array.from(stockQuantityMap.entries())
|
||||||
|
.reduce((sum, [ stockId, quantity ]) => {
|
||||||
|
const weight = stockWeightMap.get(stockId) || 0;
|
||||||
|
const qty = parseInt(quantity) || 0;
|
||||||
|
return sum + (weight * qty);
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
// 格式化重量(保留2位小数)
|
||||||
|
total_weight = parseFloat(total_weight.toFixed(2));
|
||||||
|
|
||||||
|
ctx.logger.debug('[订单统计信息]', {
|
||||||
|
orderId,
|
||||||
|
stock_count,
|
||||||
|
item_total_count,
|
||||||
|
total_weight,
|
||||||
|
items_str_length: items_str.length,
|
||||||
|
items_preview: items_str.substring(0, 100) + (items_str.length > 100 ? '...' : ''),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (errors.length > 0) {
|
||||||
|
throw new Error(`创建订单错误:\n${errors.join('\n')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lineData.length === 0) {
|
||||||
|
throw new Error('没有有效的商品明细可以创建');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批量创建订单明细
|
||||||
|
await OrderItemsModel.bulkCreate(lineData, { transaction });
|
||||||
|
ctx.logger.info(`成功添加 ${lineData.length} 个订单明细项,订单ID: ${orderId}`);
|
||||||
|
|
||||||
|
// 返回完整信息
|
||||||
|
return {
|
||||||
|
length: lineData.length, // 商品种类数(与stock_count相同)
|
||||||
|
items_str, // 结构字符串
|
||||||
|
stock_count, // stock种类数
|
||||||
|
item_total_count, // 商品总数
|
||||||
|
total_weight, // 总重量
|
||||||
|
stock_quantity_map: Object.fromEntries(stockQuantityMap), // stock_id -> 数量
|
||||||
|
stock_weight_map: Object.fromEntries(stockWeightMap), // stock_id -> 单件重量
|
||||||
|
line_data: lineData, // 创建的明细数据
|
||||||
|
stats: { // 统计信息汇总
|
||||||
|
unique_items: stock_count,
|
||||||
|
total_items: item_total_count,
|
||||||
|
total_weight,
|
||||||
|
avg_weight_per_item: stock_count > 0 ? (total_weight / item_total_count).toFixed(2) : 0,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加工具方法
|
||||||
|
safeParseFloat(value, defaultValue = 0) {
|
||||||
|
if (value === null || value === undefined) return defaultValue;
|
||||||
|
const num = parseFloat(value);
|
||||||
|
return isNaN(num) ? defaultValue : num;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 订单入队列(异步处理)
|
||||||
|
async addOrderToQueue(orderId, warehouseId) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const queueData = {
|
||||||
|
orderId,
|
||||||
|
warehouseId,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
action: 'order_created',
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = DeliveryOrderService;
|
||||||
751
app/service/systems/entry_order.js
Normal file
751
app/service/systems/entry_order.js
Normal file
@ -0,0 +1,751 @@
|
|||||||
|
'use strict';
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class entryOrderService extends Service {
|
||||||
|
async addOrder(data, info, fromCode) {
|
||||||
|
const { storeId, warehouseId, appKey, customerId, warehouseCode } = info;
|
||||||
|
const { app } = this;
|
||||||
|
const transaction = await app.model.transaction(); // 开启事务
|
||||||
|
|
||||||
|
try {
|
||||||
|
console.log('入库单开始接收处理');
|
||||||
|
let totalOrderLines = data.request.entryOrder.totalOrderLines || 0;
|
||||||
|
|
||||||
|
let orderLine = data.request.orderLines.orderLine;
|
||||||
|
if (orderLine.itemCode) {
|
||||||
|
orderLine = [ orderLine ];
|
||||||
|
}
|
||||||
|
console.log('orderLine', orderLine);
|
||||||
|
const isSingle = totalOrderLines ? 0 : 1;
|
||||||
|
totalOrderLines = totalOrderLines || orderLine.length;
|
||||||
|
let errors = [];
|
||||||
|
const items = [];
|
||||||
|
|
||||||
|
console.log('循环开始');
|
||||||
|
// 验证商品
|
||||||
|
for (var i = 0; i < orderLine.length; i++) {
|
||||||
|
let wms_stock = null;
|
||||||
|
// ERP不处理WMS的外部商品编码
|
||||||
|
if (!orderLine[i].itemId) {
|
||||||
|
console.log('ERP不处理WMS的外部商品编码');
|
||||||
|
// 查找唯一键
|
||||||
|
wms_stock = await app.model.StockStore.findOne({ where: {
|
||||||
|
item_code: orderLine[i].itemCode,
|
||||||
|
app_key: appKey,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
store_id: storeId,
|
||||||
|
}, transaction });
|
||||||
|
} else {
|
||||||
|
wms_stock = await app.model.StockStore.findByPk(orderLine[i].itemId, { transaction });
|
||||||
|
}
|
||||||
|
if (!wms_stock) {
|
||||||
|
errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》\n未同步推送到仓库`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!wms_stock.stock_id) {
|
||||||
|
errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》wms无对应关系\n请联系仓库关联创建商品`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
wms_stock.inventory_type = orderLine[i].inventoryType || 'ZP';
|
||||||
|
wms_stock.order_line_no = orderLine[i].orderLineNo || i + 1;
|
||||||
|
wms_stock.count = orderLine[i].planQty;
|
||||||
|
wms_stock.item_id = orderLine[i].itemId || wms_stock.id;
|
||||||
|
items.push(wms_stock);
|
||||||
|
}
|
||||||
|
console.log('items>>>>>', items);
|
||||||
|
if (errors.length > 0) {
|
||||||
|
await transaction.rollback(); // 验证失败,回滚事务
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: '创建入库单失败,失败原因:\n' + errors.join('\n'),
|
||||||
|
data: {
|
||||||
|
createTime: new Date(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建入库单(内部也使用事务)
|
||||||
|
const order = await this.tryCreateEntryOrder(
|
||||||
|
data.request.entryOrder,
|
||||||
|
appKey,
|
||||||
|
storeId,
|
||||||
|
warehouseId,
|
||||||
|
totalOrderLines,
|
||||||
|
fromCode,
|
||||||
|
customerId,
|
||||||
|
warehouseCode,
|
||||||
|
transaction // 传递事务
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log('入库单参数', order);
|
||||||
|
if (!order.success) {
|
||||||
|
await transaction.rollback();
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: '创建入库单失败,失败原因:\n' + order.error,
|
||||||
|
data: {
|
||||||
|
createTime: new Date(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const orderId = order.entryOrderId;
|
||||||
|
const orderCode = order.entryOrderCode || data.request.entryOrder.entryOrderCode;
|
||||||
|
errors = []; // 重置错误数组
|
||||||
|
|
||||||
|
// 添加商品明细
|
||||||
|
for (var i = 0; i < items.length; i++) {
|
||||||
|
const item = items[i];
|
||||||
|
const res = await this.addItems(item, orderId, transaction);
|
||||||
|
console.log('添加商品返回信息', res);
|
||||||
|
if (!res.success) {
|
||||||
|
errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (errors.length > 0) {
|
||||||
|
await transaction.rollback(); // 商品添加失败,回滚整个事务
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: '创建入库单失败,失败原因:\n' + errors.join('\n'),
|
||||||
|
data: {
|
||||||
|
createTime: new Date(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取接收行数并处理状态
|
||||||
|
const lineCount = await this.getLineCount(orderId, transaction);
|
||||||
|
|
||||||
|
if (lineCount == totalOrderLines) {
|
||||||
|
// 所有行数接收完成
|
||||||
|
await this.received(orderId, warehouseId, storeId, transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提交事务
|
||||||
|
await transaction.commit();
|
||||||
|
|
||||||
|
if (lineCount == totalOrderLines) {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: '入库单接收完毕',
|
||||||
|
data: {
|
||||||
|
entryOrderId: orderId,
|
||||||
|
entryOrderCode: orderCode,
|
||||||
|
createTime: new Date(),
|
||||||
|
warehouseCode,
|
||||||
|
status: 'COMPLETED',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 部分接收或等待接收
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: '入库单接收中',
|
||||||
|
data: {
|
||||||
|
entryOrderId: orderId,
|
||||||
|
entryOrderCode: orderCode,
|
||||||
|
createTime: new Date(),
|
||||||
|
warehouseCode,
|
||||||
|
status: 'PARTIAL_RECEIVED',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
// 发生异常,回滚事务
|
||||||
|
await transaction.rollback().catch(e => console.error('回滚事务失败:', e));
|
||||||
|
|
||||||
|
console.error('addOrder 事务异常:', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: `系统异常: ${error.message}`,
|
||||||
|
data: {
|
||||||
|
createTime: new Date(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 辅助函数:获取行数(支持事务)
|
||||||
|
async getLineCount(orderId, transaction = null) {
|
||||||
|
const { app } = this;
|
||||||
|
const options = {
|
||||||
|
where: { order_id: orderId },
|
||||||
|
};
|
||||||
|
|
||||||
|
if (transaction) {
|
||||||
|
options.transaction = transaction;
|
||||||
|
}
|
||||||
|
|
||||||
|
const count = await app.model.EntryItems.count(options);
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 辅助函数:标记为已接收(支持事务)
|
||||||
|
async received(orderId, warehouseId, storeId, transaction = null) {
|
||||||
|
const { app } = this;
|
||||||
|
|
||||||
|
const updateData = {
|
||||||
|
order_status: 'COMPLETED',
|
||||||
|
updated_at: new Date(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const where = {
|
||||||
|
id: orderId,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
store_id: storeId,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (transaction) {
|
||||||
|
await app.model.EntryOrder.update(updateData, {
|
||||||
|
where,
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await app.model.EntryOrder.update(updateData, { where });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 辅助函数:统一返回格式
|
||||||
|
success(message, data = {}) {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message,
|
||||||
|
data: {
|
||||||
|
...data,
|
||||||
|
createTime: new Date(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fail(message, data = {}) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message,
|
||||||
|
data: {
|
||||||
|
...data,
|
||||||
|
createTime: new Date(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async tryCreateEntryOrder(order, appKey, storeId, warehouseId, totalOrderLines, sourceType, qimenOwnerCode, qimenWarehouseCode, transaction = null) {
|
||||||
|
const { app } = this;
|
||||||
|
const { ctx } = this;
|
||||||
|
console.log('创建入库单信息', order, appKey, storeId, warehouseId);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const options = transaction ? { transaction } : {};
|
||||||
|
|
||||||
|
// 1. 检查入库单是否已存在
|
||||||
|
const existingOrder = await ctx.model.EntryOrder.findOne({
|
||||||
|
where: {
|
||||||
|
entry_order_code: order.entryOrderCode,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
store_id: storeId,
|
||||||
|
},
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. 如果入库单已存在
|
||||||
|
if (existingOrder) {
|
||||||
|
const allowedStatuses = [ 'CREATING' ];
|
||||||
|
|
||||||
|
if (allowedStatuses.includes(existingOrder.order_status)) {
|
||||||
|
// 状态在允许范围内,更新为接收中状态
|
||||||
|
await existingOrder.update({
|
||||||
|
order_status: 'CREATING',
|
||||||
|
updated_at: new Date(),
|
||||||
|
}, options);
|
||||||
|
|
||||||
|
console.log(`入库单 ${order.entryOrderCode} 已存在,状态更新为接收中`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
code: 1,
|
||||||
|
message: '入库单已存在,状态已更新为接收中',
|
||||||
|
entryOrderId: existingOrder.id,
|
||||||
|
entryOrderCode: existingOrder.entry_order_code,
|
||||||
|
orderStatus: 'CREATING',
|
||||||
|
items: existingOrder.items || [],
|
||||||
|
data: {
|
||||||
|
entryOrder: {
|
||||||
|
id: existingOrder.id,
|
||||||
|
entryOrderCode: existingOrder.entry_order_code,
|
||||||
|
orderType: existingOrder.order_type,
|
||||||
|
orderStatus: existingOrder.order_status,
|
||||||
|
totalOrderLines,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// 其他状态返回错误
|
||||||
|
const statusName = existingOrder.getOrderStatusName ? existingOrder.getOrderStatusName() : existingOrder.order_status;
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: 0,
|
||||||
|
message: `入库单已存在,当前状态为${statusName},无法重复创建`,
|
||||||
|
entryOrderId: existingOrder.id,
|
||||||
|
entryOrderCode: existingOrder.entry_order_code,
|
||||||
|
orderStatus: existingOrder.order_status,
|
||||||
|
error: `入库单已存在,状态: ${statusName}`,
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 入库单不存在,创建新的入库单
|
||||||
|
// 如果外部传入了事务,使用外部事务;否则创建新事务
|
||||||
|
const internalTransaction = transaction ? null : await ctx.model.transaction();
|
||||||
|
const currentTransaction = transaction || internalTransaction;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const warehouse_data = await this.ctx.service.systems.store.getStoreName(warehouseId);
|
||||||
|
let store_name = null;
|
||||||
|
let warehouse_name = null;
|
||||||
|
if (warehouse_data.code == 200) {
|
||||||
|
warehouse_name = warehouse_data.data.company_name;
|
||||||
|
}
|
||||||
|
const store_data = await this.ctx.service.systems.store.getStoreName(storeId);
|
||||||
|
|
||||||
|
if (store_data.code == 200) {
|
||||||
|
store_name = store_data.data.company_name;
|
||||||
|
}
|
||||||
|
|
||||||
|
const contract_data = await this.ctx.service.systems.store.getStoreRemaskName(storeId, warehouseId);
|
||||||
|
let contract = null;
|
||||||
|
if (contract_data.code == 200) {
|
||||||
|
contract = contract_data.data;
|
||||||
|
}
|
||||||
|
// 构建入库单数据
|
||||||
|
const entryOrderData = {
|
||||||
|
entry_order_code: order.entryOrderCode,
|
||||||
|
order_type: order.orderType,
|
||||||
|
purchase_order_code: order.relatedOrders?.relatedOrder?.orderCode || '',
|
||||||
|
total_order_lines: totalOrderLines,
|
||||||
|
order_create_time: order.orderCreateTime ? new Date(order.orderCreateTime) : new Date(),
|
||||||
|
expect_start_time: order.expectStartTime ? new Date(order.expectStartTime) : new Date(),
|
||||||
|
expect_end_time: order.expectStartTime ? new Date(order.expectStartTime) : new Date(),
|
||||||
|
logistics_code: order.logisticsCode || '',
|
||||||
|
logistics_name: order.logisticsName || '',
|
||||||
|
express_code: order.expressCode || '',
|
||||||
|
supplier_code: order.supplierCode || '',
|
||||||
|
supplier_name: order.supplierName || '',
|
||||||
|
source_type: sourceType,
|
||||||
|
order_status: 'CREATING',
|
||||||
|
sync_status: 'PENDING',
|
||||||
|
sync_message: '',
|
||||||
|
is_enabled: 1,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
store_id: storeId,
|
||||||
|
store_name: contract.store_remask || store_name,
|
||||||
|
warehouse_name: contract.warehouse_remask || warehouse_name,
|
||||||
|
remark: order.remark || '',
|
||||||
|
qimen_owner_code: qimenOwnerCode || '',
|
||||||
|
qimen_warehouse_code: qimenWarehouseCode || '',
|
||||||
|
};
|
||||||
|
|
||||||
|
// 创建入库单
|
||||||
|
const newEntryOrder = await ctx.model.EntryOrder.create(entryOrderData, {
|
||||||
|
transaction: currentTransaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 如果这是内部创建的事务,提交它
|
||||||
|
if (internalTransaction) {
|
||||||
|
await internalTransaction.commit();
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`成功创建入库单: ${order.entryOrderCode}, ID: ${newEntryOrder.id}`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
code: 1,
|
||||||
|
message: '入库单创建成功,状态设置为接收中',
|
||||||
|
entryOrderId: newEntryOrder.id,
|
||||||
|
entryOrderCode: newEntryOrder.entry_order_code,
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.log('创建入库单失败', error);
|
||||||
|
// 如果这是内部创建的事务,回滚它
|
||||||
|
if (internalTransaction) {
|
||||||
|
await internalTransaction.rollback();
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('创建入库单失败:', error);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: 0,
|
||||||
|
message: `创建入库单异常: ${error.message}`,
|
||||||
|
entryOrderId: null,
|
||||||
|
entryOrderCode: null,
|
||||||
|
orderStatus: null,
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async addItems(item, orderId, transaction = null) {
|
||||||
|
const { app } = this;
|
||||||
|
const { ctx } = this;
|
||||||
|
console.log('添加入库单商品');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const options = transaction ? { transaction } : {};
|
||||||
|
|
||||||
|
// 检查商品是否已存在
|
||||||
|
const existingOrderItem = await ctx.model.EntryItems.findOne({
|
||||||
|
where: {
|
||||||
|
order_id: orderId,
|
||||||
|
order_line_no: item.order_line_no,
|
||||||
|
},
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existingOrderItem) {
|
||||||
|
try {
|
||||||
|
// 构建入库明细数据
|
||||||
|
const entryItemsData = {
|
||||||
|
order_id: orderId,
|
||||||
|
out_biz_code: item.out_biz_code || '',
|
||||||
|
order_line_no: item.order_line_no || '',
|
||||||
|
owner_code: item.owner_code || '',
|
||||||
|
item_code: item.item_code || '',
|
||||||
|
item_id: item.item_id || 0,
|
||||||
|
count: item.count || 0,
|
||||||
|
inventory_type: item.inventory_type || '',
|
||||||
|
stock_id: item.stock_id || '',
|
||||||
|
};
|
||||||
|
|
||||||
|
// 创建入库明细
|
||||||
|
await ctx.model.EntryItems.create(entryItemsData, {
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
code: 1,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.log('添加商品明细出错', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
code: 1,
|
||||||
|
message: '商品已存在,跳过重复添加',
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('添加入库单商品失败:', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: 0,
|
||||||
|
message: `添加商品失败: ${error.message}`,
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async received(orderId, warehouseId, storeId, transaction = null) {
|
||||||
|
console.log('完结传参', orderId, warehouseId, storeId);
|
||||||
|
const { app } = this;
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const options = transaction ? { transaction } : {};
|
||||||
|
|
||||||
|
const existingOrder = await ctx.model.EntryOrder.findOne({
|
||||||
|
where: {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
store_id: storeId,
|
||||||
|
id: orderId,
|
||||||
|
},
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existingOrder) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: 0,
|
||||||
|
message: '入库单不存在',
|
||||||
|
entryOrderId: null,
|
||||||
|
orderStatus: null,
|
||||||
|
error: '入库单不存在',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const allowedStatuses = [ 'CREATING' ];
|
||||||
|
if (allowedStatuses.includes(existingOrder.order_status)) {
|
||||||
|
await existingOrder.update({
|
||||||
|
order_status: 'CREATED',
|
||||||
|
updated_at: new Date(),
|
||||||
|
}, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
code: 1,
|
||||||
|
message: '完成',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async qimenEntryorderConfirm(entryOrder, orderLines, isFin, outBizCode) {
|
||||||
|
if (orderLines.length < 1) {
|
||||||
|
throw new Error('行不能为空');
|
||||||
|
}
|
||||||
|
console.log('isFin:', isFin);
|
||||||
|
const queryData = {
|
||||||
|
request: {
|
||||||
|
entryOrder: {
|
||||||
|
entryOrderCode: entryOrder.entry_order_code,
|
||||||
|
ownerCode: entryOrder.qimen_owner_code,
|
||||||
|
warehouseCode: entryOrder.qimen_warehouse_code,
|
||||||
|
entryOrderId: entryOrder.id,
|
||||||
|
entryOrderType: entryOrder.order_type,
|
||||||
|
outBizCode,
|
||||||
|
confirmType: isFin ? 0 : 1,
|
||||||
|
status: isFin ? 'FULFILLED' : 'PARTFULFILLED',
|
||||||
|
freight: 0,
|
||||||
|
operateTime: new Date().format(),
|
||||||
|
remark: entryOrder.remark,
|
||||||
|
},
|
||||||
|
orderLines,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const Result = await this.ctx.service.systems.qimenQuery.send('taobao.qimen.entryorder.confirm', entryOrder.qimen_owner_code, queryData);
|
||||||
|
return Result;
|
||||||
|
}
|
||||||
|
async entryorderConfirm(orderId, isCompleted) {
|
||||||
|
const { app, ctx } = this;
|
||||||
|
const transaction = await app.model.transaction();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 锁定数据
|
||||||
|
const entryOrder = await app.model.EntryOrder.findOne({
|
||||||
|
where: {
|
||||||
|
id: orderId,
|
||||||
|
is_enabled: 1,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: app.model.EntryItems,
|
||||||
|
as: 'items',
|
||||||
|
lock: transaction.LOCK.UPDATE,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
lock: transaction.LOCK.UPDATE,
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!entryOrder) {
|
||||||
|
await transaction.rollback();
|
||||||
|
return { success: false, message: '入库单不存在' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 状态检查
|
||||||
|
const allowedStatuses = [ 'CREATED', 'PARTIAL_RECEIVED', 'CONFIRMED' ];
|
||||||
|
if (!allowedStatuses.includes(entryOrder.order_status)) {
|
||||||
|
await transaction.rollback();
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: 'INVALID_STATUS',
|
||||||
|
message: `入库单状态[${entryOrder.order_status}]不允许确认`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const orderLines = [];
|
||||||
|
let totalPlanQty = 0;
|
||||||
|
let totalReceivedQty = 0;
|
||||||
|
let totalConfirmIncrement = 0;
|
||||||
|
let hasItemsToConfirm = false;
|
||||||
|
|
||||||
|
// 第一阶段:计算和验证,不执行更新
|
||||||
|
const pendingUpdates = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < entryOrder.items.length; i++) {
|
||||||
|
const item = entryOrder.items[i];
|
||||||
|
const planQty = item.count || 0;
|
||||||
|
const receivedQty = item.received_quantity || 0;
|
||||||
|
const confirmedQty = item.confirm_quantity || 0;
|
||||||
|
|
||||||
|
// 计算本次确认的增量
|
||||||
|
const confirmIncrement = Math.max(0, receivedQty - confirmedQty);
|
||||||
|
|
||||||
|
if (confirmIncrement > 0) {
|
||||||
|
hasItemsToConfirm = true;
|
||||||
|
|
||||||
|
// 奇门需要的是本次确认的数量(actualQty)
|
||||||
|
const orderLine = {
|
||||||
|
orderLineNo: i + 1,
|
||||||
|
ownerCode: item.owner_code,
|
||||||
|
itemCode: item.item_code,
|
||||||
|
itemId: item.item_id,
|
||||||
|
inventoryType: item.inventory_type,
|
||||||
|
planQty,
|
||||||
|
actualQty: confirmIncrement, // 传本次增量
|
||||||
|
};
|
||||||
|
orderLines.push(orderLine);
|
||||||
|
|
||||||
|
totalConfirmIncrement += confirmIncrement;
|
||||||
|
|
||||||
|
// 记录待更新数据(不执行)
|
||||||
|
pendingUpdates.push({
|
||||||
|
id: item.id,
|
||||||
|
item_id: item.item_id,
|
||||||
|
new_confirm_quantity: confirmedQty + confirmIncrement,
|
||||||
|
old_confirm_quantity: confirmedQty,
|
||||||
|
received_quantity: receivedQty,
|
||||||
|
confirm_increment: confirmIncrement,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
totalPlanQty += planQty;
|
||||||
|
totalReceivedQty += receivedQty;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 没有需要确认的数量
|
||||||
|
if (!hasItemsToConfirm) {
|
||||||
|
await transaction.rollback();
|
||||||
|
return { success: false, message: '没有需要确认的收货数量' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 判断是否最终完成
|
||||||
|
const isFin = isCompleted ? true : (totalReceivedQty >= totalPlanQty);
|
||||||
|
let qimenResult = {};
|
||||||
|
let queryId = null;
|
||||||
|
// 奇门入库单,数据同步到奇门
|
||||||
|
if (entryOrder.source_type == 'QM') {
|
||||||
|
// 第二阶段:调用奇门接口
|
||||||
|
const Result = await this.qimenEntryorderConfirm(
|
||||||
|
entryOrder,
|
||||||
|
orderLines,
|
||||||
|
isFin,
|
||||||
|
Math.round(new Date() / 1000)
|
||||||
|
);
|
||||||
|
console.log(Result);
|
||||||
|
queryId = Result.queryId;
|
||||||
|
qimenResult = Result.xmlArray.response;
|
||||||
|
// 奇门调用失败,回滚事务
|
||||||
|
if (!qimenResult || qimenResult.flag != 'success') {
|
||||||
|
await transaction.rollback();
|
||||||
|
console.error('奇门接口调用失败:', qimenResult);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: 'QIMEN_FAILED',
|
||||||
|
message: '奇门接口调用失败',
|
||||||
|
detail: qimenResult?.message || '未知错误',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 第三阶段:奇门成功,执行数据库更新
|
||||||
|
|
||||||
|
// 1. 更新确认数量
|
||||||
|
for (const update of pendingUpdates) {
|
||||||
|
const result = await app.model.EntryItems.update({
|
||||||
|
confirm_quantity: update.new_confirm_quantity,
|
||||||
|
updated_at: new Date(),
|
||||||
|
}, {
|
||||||
|
where: {
|
||||||
|
id: update.id,
|
||||||
|
confirm_quantity: update.old_confirm_quantity, // 乐观锁,防止并发
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
const res = await ctx.service.systems.stockStore.inbound(update.item_id, update.confirm_increment, transaction);
|
||||||
|
console.log('增加库存返回', res);
|
||||||
|
if (result[0] === 0) {
|
||||||
|
// 更新失败,可能被并发修改了
|
||||||
|
console.warn(`更新入库明细失败,可能已被修改: id=${update.id}`);
|
||||||
|
// 可以选择重试或抛出异常
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 更新入库单状态
|
||||||
|
let newOrderStatus = entryOrder.order_status;
|
||||||
|
if (isFin) {
|
||||||
|
newOrderStatus = 'COMPLETED';
|
||||||
|
} else if (totalConfirmIncrement > 0) {
|
||||||
|
if (entryOrder.order_status === 'CREATED') {
|
||||||
|
newOrderStatus = 'CONFIRMED';
|
||||||
|
} else {
|
||||||
|
newOrderStatus = 'PARTIAL_RECEIVED';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateResult = await app.model.EntryOrder.update({
|
||||||
|
order_status: newOrderStatus,
|
||||||
|
sync_status: 'SUCCESS',
|
||||||
|
sync_message: JSON.stringify({
|
||||||
|
confirmTime: new Date(),
|
||||||
|
totalPlan: totalPlanQty,
|
||||||
|
totalReceived: totalReceivedQty,
|
||||||
|
totalConfirmIncrement,
|
||||||
|
isFin,
|
||||||
|
pendingUpdatesCount: pendingUpdates.length,
|
||||||
|
qimenResult: qimenResult?.data || {},
|
||||||
|
}),
|
||||||
|
updated_at: new Date(),
|
||||||
|
}, {
|
||||||
|
where: {
|
||||||
|
id: entryOrder.id,
|
||||||
|
order_status: entryOrder.order_status, // 乐观锁
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (updateResult[0] === 0) {
|
||||||
|
// 入库单状态已被修改,回滚
|
||||||
|
await transaction.rollback();
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: 'CONCURRENT_MODIFICATION',
|
||||||
|
message: '入库单已被修改,请刷新后重试',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// 4. 提交事务
|
||||||
|
await transaction.commit();
|
||||||
|
|
||||||
|
console.log(`入库单确认成功: id=${entryOrder.id}, 确认增量=${totalConfirmIncrement}, 状态=${newOrderStatus}`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: isFin ? '入库单完成确认' : '入库单增量确认成功',
|
||||||
|
data: {
|
||||||
|
entryOrderId: entryOrder.id,
|
||||||
|
entryOrderCode: entryOrder.entry_order_code,
|
||||||
|
orderStatus: newOrderStatus,
|
||||||
|
totalPlan: totalPlanQty,
|
||||||
|
totalReceived: totalReceivedQty,
|
||||||
|
totalConfirmIncrement,
|
||||||
|
isFin,
|
||||||
|
updatedItemsCount: pendingUpdates.length,
|
||||||
|
orderLinesCount: orderLines.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
// 发生异常,回滚事务
|
||||||
|
await transaction.rollback().catch(e => {
|
||||||
|
console.error('回滚事务失败:', e);
|
||||||
|
});
|
||||||
|
|
||||||
|
console.error('确认入库单失败:', error);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
code: 'SYSTEM_ERROR',
|
||||||
|
message: `系统异常: ${error.message}`,
|
||||||
|
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = entryOrderService;
|
||||||
264
app/service/systems/fast_where.js
Normal file
264
app/service/systems/fast_where.js
Normal file
@ -0,0 +1,264 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class FastWhereService extends Service {
|
||||||
|
// 构建树形结构
|
||||||
|
buildTree(data, pid = 0) {
|
||||||
|
const tree = [];
|
||||||
|
|
||||||
|
data.forEach(item => {
|
||||||
|
if (item.pid === pid) {
|
||||||
|
const children = this.buildTree(data, item.id);
|
||||||
|
if (children.length > 0) {
|
||||||
|
item.children = children;
|
||||||
|
}
|
||||||
|
tree.push(item);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return tree;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据type获取父节点及其所有子节点(树形结构)
|
||||||
|
async getTreeByType(type) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 首先找到所有指定type的父节点
|
||||||
|
const parentNodes = await ctx.model.FastWhere.findAll({
|
||||||
|
where: { type },
|
||||||
|
order: [[ 'id', 'ASC' ]],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. 获取所有数据用于构建树
|
||||||
|
const allData = await ctx.model.FastWhere.findAll({
|
||||||
|
order: [[ 'id', 'ASC' ]],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 3. 转换所有数据为普通对象(触发getter)
|
||||||
|
const plainAllData = allData.map(item => item.toJSON());
|
||||||
|
|
||||||
|
// 4. 为每个父节点构建子树
|
||||||
|
const result = [];
|
||||||
|
for (const parent of parentNodes) {
|
||||||
|
const parentPlain = parent.toJSON(); // 转换为普通对象
|
||||||
|
const tree = this.buildSubTree(parentPlain, plainAllData);
|
||||||
|
result.push(tree);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('[FastWhereService.getTreeByType] error:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建以某个节点为根的子树
|
||||||
|
buildSubTree(root, allData) {
|
||||||
|
const tree = {
|
||||||
|
...root,
|
||||||
|
children: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
// 递归查找子节点
|
||||||
|
const findChildren = (parentId, parentNode) => {
|
||||||
|
allData.forEach(item => {
|
||||||
|
if (item.pid === parentId) {
|
||||||
|
const childNode = {
|
||||||
|
...item,
|
||||||
|
children: [],
|
||||||
|
};
|
||||||
|
parentNode.children.push(childNode);
|
||||||
|
findChildren(item.id, childNode);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
findChildren(root.id, tree);
|
||||||
|
return tree;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据type获取父节点,并包含所有子节点(扁平结构)
|
||||||
|
async getWithChildrenByType(type) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 首先找到所有指定type的父节点
|
||||||
|
const parentNodes = await ctx.model.FastWhere.findAll({
|
||||||
|
where: { type },
|
||||||
|
order: [[ 'id', 'ASC' ]],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. 为每个父节点获取所有子节点
|
||||||
|
const result = [];
|
||||||
|
|
||||||
|
for (const parent of parentNodes) {
|
||||||
|
const parentPlain = parent.toJSON(); // 转换为普通对象
|
||||||
|
const allChildren = await this.getAllChildren(parent.id);
|
||||||
|
result.push({
|
||||||
|
...parentPlain,
|
||||||
|
children: allChildren,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('[FastWhereService.getWithChildrenByType] error:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 递归获取所有子节点(包括孙子节点等)
|
||||||
|
async getAllChildren(pid) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
// 获取直接子节点
|
||||||
|
const directChildren = await ctx.model.FastWhere.findAll({
|
||||||
|
where: { pid },
|
||||||
|
order: [[ 'id', 'ASC' ]],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 递归获取每个子节点的子节点
|
||||||
|
const childrenWithDescendants = [];
|
||||||
|
|
||||||
|
for (const child of directChildren) {
|
||||||
|
const childPlain = child.toJSON(); // 转换为普通对象
|
||||||
|
const grandchildren = await this.getAllChildren(child.id);
|
||||||
|
childrenWithDescendants.push({
|
||||||
|
...childPlain,
|
||||||
|
children: grandchildren,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return childrenWithDescendants;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据类型获取条件组(仅父节点)
|
||||||
|
async getByType(type) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const results = await ctx.model.FastWhere.findAll({
|
||||||
|
where: { type },
|
||||||
|
order: [[ 'id', 'ASC' ]],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 转换为普通对象
|
||||||
|
return results.map(item => item.toJSON());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取所有父级组
|
||||||
|
async getGroups() {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const results = await ctx.model.FastWhere.findAll({
|
||||||
|
where: { type: 'group' },
|
||||||
|
order: [[ 'id', 'ASC' ]],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 转换为普通对象
|
||||||
|
return results.map(item => item.toJSON());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据父级ID获取直接子条件(仅一层)
|
||||||
|
async getChildrenByPid(pid) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const results = await ctx.model.FastWhere.findAll({
|
||||||
|
where: { pid },
|
||||||
|
order: [[ 'id', 'ASC' ]],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 转换为普通对象
|
||||||
|
return results.map(item => item.toJSON());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据父级ID获取所有层级子条件(树形)
|
||||||
|
async getTreeChildrenByPid(pid) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 获取所有数据
|
||||||
|
const allData = await ctx.model.FastWhere.findAll({
|
||||||
|
order: [[ 'id', 'ASC' ]],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 转换为普通对象
|
||||||
|
const plainAllData = allData.map(item => item.toJSON());
|
||||||
|
|
||||||
|
// 找到父节点
|
||||||
|
const parentNode = plainAllData.find(item => item.id === pid);
|
||||||
|
if (!parentNode) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建子树
|
||||||
|
return this.buildSubTree(parentNode, plainAllData);
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('[FastWhereService.getTreeChildrenByPid] error:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加快速查询条件
|
||||||
|
async create(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const result = await ctx.model.FastWhere.create(data);
|
||||||
|
return result.toJSON(); // 转换为普通对象
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新快速查询条件
|
||||||
|
async update(id, data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const result = await ctx.model.FastWhere.update(data, {
|
||||||
|
where: { id },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result[0] === 0) {
|
||||||
|
ctx.throw(404, '记录不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await this.findById(id);
|
||||||
|
return updated.toJSON(); // 转换为普通对象
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据ID查找
|
||||||
|
async findById(id) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const result = await ctx.model.FastWhere.findByPk(id);
|
||||||
|
if (!result) {
|
||||||
|
ctx.throw(404, '记录不存在');
|
||||||
|
}
|
||||||
|
return result.toJSON(); // 转换为普通对象
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除快速查询条件
|
||||||
|
async delete(id) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
// 先检查是否有子节点
|
||||||
|
const children = await ctx.model.FastWhere.count({
|
||||||
|
where: { pid: id },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (children > 0) {
|
||||||
|
ctx.throw(400, '请先删除子节点');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await ctx.model.FastWhere.destroy({
|
||||||
|
where: { id },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result === 0) {
|
||||||
|
ctx.throw(404, '记录不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = FastWhereService;
|
||||||
121
app/service/systems/file.js
Normal file
121
app/service/systems/file.js
Normal file
@ -0,0 +1,121 @@
|
|||||||
|
'use strict';
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class FileService extends Service {
|
||||||
|
async getImages(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const result = await ctx.model.FileReference.findAll({ where: {
|
||||||
|
business_type: data.type,
|
||||||
|
business_id: data.id,
|
||||||
|
}, include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.File,
|
||||||
|
as: 'file',
|
||||||
|
attributes: [ 'file_url', 'file_name' ],
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
] });
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
async ReferenceFile(data) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
const { id, type, images } = data;
|
||||||
|
const warehouseId = ctx.user.store_id;
|
||||||
|
|
||||||
|
console.log('<<<type>>>>', type);
|
||||||
|
switch (type) {
|
||||||
|
case 'stock':
|
||||||
|
const stock = await ctx.model.StockWarehouse.findOne({
|
||||||
|
where: {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
delete_at: null,
|
||||||
|
id,
|
||||||
|
},
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
if (!stock) {
|
||||||
|
throw new Error('找不到商品');
|
||||||
|
}
|
||||||
|
console.log('<<<images>>>>', images.length);
|
||||||
|
|
||||||
|
if (images.length > 0) {
|
||||||
|
await ctx.model.StockWarehouse.update({ is_images: 'Y' }, {
|
||||||
|
where: {
|
||||||
|
id: stock.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await ctx.model.StockWarehouse.update({ is_images: 'N' }, {
|
||||||
|
where: {
|
||||||
|
id: stock.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await service.systems.operationLog.createOperationLog({
|
||||||
|
businessType: 'stock',
|
||||||
|
businessId: id,
|
||||||
|
operationCode: 'UPDATE_IMAGES',
|
||||||
|
operator: {
|
||||||
|
id: ctx.user.id,
|
||||||
|
name: ctx.user.employees_name,
|
||||||
|
},
|
||||||
|
extras: {
|
||||||
|
warehouseId,
|
||||||
|
},
|
||||||
|
beforeChanges: null,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
// code
|
||||||
|
}
|
||||||
|
// 获取现有的file_id
|
||||||
|
const existingRefs = await ctx.model.FileReference.findAll({
|
||||||
|
where: { business_type: type, business_id: id, warehouse_id: warehouseId },
|
||||||
|
});
|
||||||
|
const existingFileIds = existingRefs.map(item => item.file_id);
|
||||||
|
const newFileIds = images.map(item => item.file_id);
|
||||||
|
|
||||||
|
// 需要删除的ID
|
||||||
|
const toDeleteIds = existingFileIds.filter(id => !newFileIds.includes(id));
|
||||||
|
|
||||||
|
// 需要创建的记录
|
||||||
|
const toCreate = images.filter(item => !existingFileIds.includes(item.file_id));
|
||||||
|
|
||||||
|
// 批量操作
|
||||||
|
const promises = [];
|
||||||
|
|
||||||
|
if (toDeleteIds.length > 0) {
|
||||||
|
promises.push(
|
||||||
|
ctx.model.FileReference.destroy({
|
||||||
|
where: {
|
||||||
|
business_type: type,
|
||||||
|
business_id: id,
|
||||||
|
file_id: toDeleteIds,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (toCreate.length > 0) {
|
||||||
|
const refData = toCreate.map(item => ({
|
||||||
|
business_type: type,
|
||||||
|
business_id: id,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
file_id: item.file_id,
|
||||||
|
sort_order: item.sort_order || 0,
|
||||||
|
created_by: ctx.user.employees_name,
|
||||||
|
created_at: new Date(),
|
||||||
|
updated_at: new Date(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
promises.push(ctx.model.FileReference.bulkCreate(refData));
|
||||||
|
}
|
||||||
|
await Promise.all(promises);
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
module.exports = FileService;
|
||||||
420
app/service/systems/location.js
Normal file
420
app/service/systems/location.js
Normal file
@ -0,0 +1,420 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class LocationService extends Service {
|
||||||
|
/**
|
||||||
|
* 创建货架并自动生成仓位
|
||||||
|
* @param params
|
||||||
|
*/
|
||||||
|
async createRackWithSpaces(params) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { app } = ctx;
|
||||||
|
|
||||||
|
// 开启事务
|
||||||
|
return await app.model.transaction(async transaction => {
|
||||||
|
// 1. 创建货架
|
||||||
|
const rack = await app.model.LocationZone.create({
|
||||||
|
...params,
|
||||||
|
zone_type: 'rack',
|
||||||
|
is_active: true,
|
||||||
|
}, { transaction });
|
||||||
|
|
||||||
|
// 2. 自动生成仓位
|
||||||
|
await this._generateSpacesForRack(rack.id, rack, transaction);
|
||||||
|
|
||||||
|
// 3. 计算库区内的货架排序
|
||||||
|
if (rack.parent_id) {
|
||||||
|
await this._calculateAreaRackOrder(rack.warehouse_id, rack.parent_id, transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 计算拣货路径
|
||||||
|
await this._calculatePickPathForWarehouse(rack.warehouse_id, transaction);
|
||||||
|
|
||||||
|
return rack;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为货架生成仓位
|
||||||
|
* @param rackId
|
||||||
|
* @param rack
|
||||||
|
* @param transaction
|
||||||
|
*/
|
||||||
|
async _generateSpacesForRack(rackId, rack, transaction) {
|
||||||
|
const { app } = this;
|
||||||
|
const { rack_columns, rack_rows, rack_levels } = rack;
|
||||||
|
|
||||||
|
const spaces = [];
|
||||||
|
|
||||||
|
// 计算每个仓位的尺寸
|
||||||
|
const cellLength = rack.length / rack_columns / 10; // mm转cm
|
||||||
|
const cellWidth = rack.width / rack_levels / 10; // mm转cm
|
||||||
|
const cellHeight = rack.height / rack_rows / 10; // mm转cm
|
||||||
|
|
||||||
|
// 生成所有仓位
|
||||||
|
for (let row = 1; row <= rack_rows; row++) {
|
||||||
|
for (let column = 1; column <= rack_columns; column++) {
|
||||||
|
for (let level = 1; level <= rack_levels; level++) {
|
||||||
|
const spaceCode = `${rack.zone_code}-${row.toString().padStart(2, '0')}-${column.toString().padStart(2, '0')}-${level.toString().padStart(2, '0')}`;
|
||||||
|
|
||||||
|
// 计算相对坐标
|
||||||
|
const relativeX = (column - 1) * cellLength;
|
||||||
|
const relativeY = (row - 1) * cellHeight;
|
||||||
|
const relativeZ = (level - 1) * cellWidth;
|
||||||
|
|
||||||
|
spaces.push({
|
||||||
|
warehouse_id: rack.warehouse_id,
|
||||||
|
zone_id: rackId,
|
||||||
|
location_type_id: 1, // 默认仓位类型
|
||||||
|
space_code: spaceCode,
|
||||||
|
row_no: row.toString(),
|
||||||
|
column_no: column.toString(),
|
||||||
|
level_no: level.toString(),
|
||||||
|
cell_no: `${row}-${column}-${level}`,
|
||||||
|
length: cellLength,
|
||||||
|
width: cellWidth,
|
||||||
|
height: cellHeight,
|
||||||
|
volume: cellLength * cellWidth * cellHeight / 1000000, // cm³转m³
|
||||||
|
max_weight: 100, // 默认100kg
|
||||||
|
space_status: 'AVAILABLE',
|
||||||
|
is_enabled: true,
|
||||||
|
relative_x: relativeX,
|
||||||
|
relative_y: relativeY,
|
||||||
|
relative_z: relativeZ,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批量插入仓位
|
||||||
|
if (spaces.length > 0) {
|
||||||
|
await app.model.LocationSpace.bulkCreate(spaces, { transaction });
|
||||||
|
}
|
||||||
|
|
||||||
|
this.ctx.logger.info(`为货架 ${rack.zone_code} 生成了 ${spaces.length} 个仓位`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算库区内货架的排序(按X坐标排序)
|
||||||
|
* @param warehouseId
|
||||||
|
* @param areaId
|
||||||
|
* @param transaction
|
||||||
|
*/
|
||||||
|
async _calculateAreaRackOrder(warehouseId, areaId, transaction) {
|
||||||
|
const { app } = this;
|
||||||
|
|
||||||
|
// 获取库区内的所有货架,按X坐标排序
|
||||||
|
const racks = await app.model.LocationZone.findAll({
|
||||||
|
where: {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
parent_id: areaId,
|
||||||
|
zone_type: 'rack',
|
||||||
|
is_active: true,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
order: [[ 'x', 'ASC' ]],
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 更新排序序号
|
||||||
|
for (let i = 0; i < racks.length; i++) {
|
||||||
|
await racks[i].update({
|
||||||
|
path_sequence: i + 1,
|
||||||
|
}, { transaction });
|
||||||
|
}
|
||||||
|
|
||||||
|
this.ctx.logger.info(`更新库区 ${areaId} 内 ${racks.length} 个货架的排序`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算仓库的拣货路径
|
||||||
|
* @param warehouseId
|
||||||
|
* @param transaction
|
||||||
|
*/
|
||||||
|
async _calculatePickPathForWarehouse(warehouseId, transaction) {
|
||||||
|
const { app } = this;
|
||||||
|
|
||||||
|
// 1. 获取起始拣货点
|
||||||
|
const pickStart = await app.model.LocationZone.findOne({
|
||||||
|
where: {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
zone_type: 'pick_start',
|
||||||
|
is_active: true,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!pickStart) {
|
||||||
|
this.ctx.logger.warn(`仓库 ${warehouseId} 没有设置起始拣货点`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 获取所有货架,按距离排序
|
||||||
|
const racks = await app.model.LocationZone.findAll({
|
||||||
|
where: {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
zone_type: 'rack',
|
||||||
|
is_active: true,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 3. 计算距离并排序(曼哈顿距离)
|
||||||
|
const sortedRacks = racks.map(rack => {
|
||||||
|
const distance = Math.abs(rack.x - pickStart.x) + Math.abs(rack.y - pickStart.y);
|
||||||
|
return {
|
||||||
|
rack,
|
||||||
|
distance,
|
||||||
|
};
|
||||||
|
}).sort((a, b) => a.distance - b.distance);
|
||||||
|
|
||||||
|
// 4. 更新货架的拣货顺序和距离
|
||||||
|
for (let i = 0; i < sortedRacks.length; i++) {
|
||||||
|
const { rack, distance } = sortedRacks[i];
|
||||||
|
|
||||||
|
await rack.update({
|
||||||
|
path_sequence: i + 1,
|
||||||
|
pick_distance: distance,
|
||||||
|
}, { transaction });
|
||||||
|
|
||||||
|
// 5. 更新该货架下所有仓位的拣货顺序
|
||||||
|
await this._updateSpacePickSequence(rack.id, i + 1, distance, transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.ctx.logger.info(`为仓库 ${warehouseId} 计算了 ${sortedRacks.length} 个货架的拣货路径`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新货架下仓位的拣货顺序
|
||||||
|
* @param rackId
|
||||||
|
* @param rackSequence
|
||||||
|
* @param rackDistance
|
||||||
|
* @param transaction
|
||||||
|
*/
|
||||||
|
async _updateSpacePickSequence(rackId, rackSequence, rackDistance, transaction) {
|
||||||
|
const { app } = this;
|
||||||
|
|
||||||
|
// 获取货架信息
|
||||||
|
const rack = await app.model.LocationZone.findByPk(rackId, { transaction });
|
||||||
|
if (!rack) return;
|
||||||
|
|
||||||
|
// 获取货架的所有仓位
|
||||||
|
const spaces = await app.model.LocationSpace.findAll({
|
||||||
|
where: {
|
||||||
|
zone_id: rackId,
|
||||||
|
is_enabled: true,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
order: [
|
||||||
|
[ 'row_no', 'ASC' ], // 从下层开始
|
||||||
|
[ 'column_no', 'ASC' ], // 从左到右
|
||||||
|
[ 'level_no', 'ASC' ], // 从外到内
|
||||||
|
],
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 更新每个仓位的拣货顺序
|
||||||
|
for (let i = 0; i < spaces.length; i++) {
|
||||||
|
const space = spaces[i];
|
||||||
|
const spaceSequence = rackSequence * 1000 + i + 1; // 货架顺序 + 仓位顺序
|
||||||
|
|
||||||
|
// 计算预估拣货时间(基于层数)
|
||||||
|
const row = parseInt(space.row_no) || 1;
|
||||||
|
let pickTimeEstimate = 30; // 默认30秒
|
||||||
|
if (row <= 2) pickTimeEstimate = 25; // 下层快
|
||||||
|
else if (row <= 4) pickTimeEstimate = 40; // 中层需要梯子
|
||||||
|
else pickTimeEstimate = 60; // 上层需要设备
|
||||||
|
|
||||||
|
await space.update({
|
||||||
|
pick_sequence: spaceSequence,
|
||||||
|
distance_from_start: rackDistance,
|
||||||
|
pick_time_estimate: pickTimeEstimate,
|
||||||
|
pick_priority: this._calculatePickPriority(row, rackDistance),
|
||||||
|
}, { transaction });
|
||||||
|
}
|
||||||
|
|
||||||
|
this.ctx.logger.info(`更新货架 ${rack.zone_code} 下 ${spaces.length} 个仓位的拣货顺序`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算拣货优先级
|
||||||
|
* @param row
|
||||||
|
* @param distance
|
||||||
|
*/
|
||||||
|
_calculatePickPriority(row, distance) {
|
||||||
|
// 行数越小(下层)优先级越高
|
||||||
|
const rowPriority = Math.max(1, 10 - (row || 1));
|
||||||
|
|
||||||
|
// 距离越近优先级越高
|
||||||
|
const distancePriority = Math.max(1, 10 - Math.floor(distance / 1000));
|
||||||
|
|
||||||
|
// 综合优先级(1-100)
|
||||||
|
return Math.min(100, Math.max(1, rowPriority * 5 + distancePriority * 5));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新货架位置后重新计算路径
|
||||||
|
* @param rackId
|
||||||
|
* @param newPosition
|
||||||
|
*/
|
||||||
|
async updateRackPosition(rackId, newPosition) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
|
||||||
|
return await app.model.transaction(async transaction => {
|
||||||
|
// 1. 检查货架是否有占用仓位
|
||||||
|
const occupiedSpaces = await app.model.LocationSpace.count({
|
||||||
|
where: {
|
||||||
|
zone_id: rackId,
|
||||||
|
space_status: [ 'OCCUPIED', 'RESERVED' ],
|
||||||
|
is_enabled: true,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (occupiedSpaces > 0) {
|
||||||
|
ctx.throw(400, `货架有 ${occupiedSpaces} 个占用或预留仓位,不能修改位置`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 更新货架位置
|
||||||
|
const rack = await app.model.LocationZone.findByPk(rackId, { transaction });
|
||||||
|
if (!rack) {
|
||||||
|
ctx.throw(404, '货架不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
await rack.update({
|
||||||
|
x: newPosition.x,
|
||||||
|
y: newPosition.y,
|
||||||
|
z: newPosition.z || rack.z,
|
||||||
|
}, { transaction });
|
||||||
|
|
||||||
|
// 3. 重新计算库区内货架排序
|
||||||
|
if (rack.parent_id) {
|
||||||
|
await this._calculateAreaRackOrder(rack.warehouse_id, rack.parent_id, transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 重新计算拣货路径
|
||||||
|
await this._calculatePickPathForWarehouse(rack.warehouse_id, transaction);
|
||||||
|
|
||||||
|
return rack;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取拣货路径
|
||||||
|
* @param warehouseId
|
||||||
|
* @param options
|
||||||
|
*/
|
||||||
|
async getPickPath(warehouseId, options = {}) {
|
||||||
|
const { app } = this;
|
||||||
|
const {
|
||||||
|
includeSpaces = false,
|
||||||
|
limit = 50,
|
||||||
|
sortBy = 'path_sequence',
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
// 获取货架的拣货路径
|
||||||
|
const racks = await app.model.LocationZone.findAll({
|
||||||
|
where: {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
zone_type: 'rack',
|
||||||
|
is_active: true,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
order: [[ sortBy, 'ASC' ]],
|
||||||
|
limit,
|
||||||
|
include: includeSpaces ? [{
|
||||||
|
model: app.model.LocationSpace,
|
||||||
|
as: 'spaces',
|
||||||
|
where: {
|
||||||
|
is_enabled: true,
|
||||||
|
deleted_at: null,
|
||||||
|
space_status: [ 'AVAILABLE', 'OCCUPIED' ],
|
||||||
|
},
|
||||||
|
required: false,
|
||||||
|
order: [[ 'pick_sequence', 'ASC' ]],
|
||||||
|
}] : [],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 计算总距离和时间
|
||||||
|
let totalDistance = 0;
|
||||||
|
let totalTime = 0;
|
||||||
|
|
||||||
|
racks.forEach(rack => {
|
||||||
|
if (rack.pick_distance) totalDistance += rack.pick_distance;
|
||||||
|
if (rack.spaces) {
|
||||||
|
rack.spaces.forEach(space => {
|
||||||
|
if (space.pick_time_estimate) totalTime += space.pick_time_estimate;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
racks,
|
||||||
|
summary: {
|
||||||
|
totalRacks: racks.length,
|
||||||
|
totalDistance: `${(totalDistance / 1000).toFixed(2)}米`,
|
||||||
|
estimatedTotalTime: `${Math.ceil(totalTime / 60)}分钟`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量更新邻居关系
|
||||||
|
* @param warehouseId
|
||||||
|
*/
|
||||||
|
async updateNeighborRelations(warehouseId) {
|
||||||
|
const { app } = this;
|
||||||
|
|
||||||
|
// 获取所有货架
|
||||||
|
const racks = await app.model.LocationZone.findAll({
|
||||||
|
where: {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
zone_type: 'rack',
|
||||||
|
is_active: true,
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 为每个货架计算邻居
|
||||||
|
for (const rack of racks) {
|
||||||
|
const neighbors = await this._findNeighborRacks(rack, racks);
|
||||||
|
await rack.update({
|
||||||
|
neighbor_zone_ids: neighbors.map(n => n.id),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
this.ctx.logger.info(`为仓库 ${warehouseId} 更新了 ${racks.length} 个货架的邻居关系`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查找相邻货架
|
||||||
|
* @param currentRack
|
||||||
|
* @param allRacks
|
||||||
|
*/
|
||||||
|
async _findNeighborRacks(currentRack, allRacks) {
|
||||||
|
const NEIGHBOR_DISTANCE = 2000; // 2米内视为邻居
|
||||||
|
|
||||||
|
return allRacks.filter(rack => {
|
||||||
|
if (rack.id === currentRack.id) return false;
|
||||||
|
|
||||||
|
// 计算两个货架中心点的距离
|
||||||
|
const currentCenterX = currentRack.x + currentRack.length / 2;
|
||||||
|
const currentCenterY = currentRack.y + currentRack.width / 2;
|
||||||
|
const rackCenterX = rack.x + rack.length / 2;
|
||||||
|
const rackCenterY = rack.y + rack.width / 2;
|
||||||
|
|
||||||
|
const distance = Math.sqrt(
|
||||||
|
Math.pow(currentCenterX - rackCenterX, 2) +
|
||||||
|
Math.pow(currentCenterY - rackCenterY, 2)
|
||||||
|
);
|
||||||
|
|
||||||
|
return distance <= NEIGHBOR_DISTANCE;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = LocationService;
|
||||||
700
app/service/systems/location_space.js
Normal file
700
app/service/systems/location_space.js
Normal file
@ -0,0 +1,700 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class LocationSpaceService extends Service {
|
||||||
|
/**
|
||||||
|
* 创建仓位
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
async create(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
// 验证参数
|
||||||
|
const rules = {
|
||||||
|
warehouse_id: { type: 'int', required: true },
|
||||||
|
zone_id: { type: 'int', required: true },
|
||||||
|
location_type_id: { type: 'int', required: true },
|
||||||
|
space_code: { type: 'string', required: true, max: 50 },
|
||||||
|
custom_name: { type: 'string', required: false, max: 100 },
|
||||||
|
custom_barcode: { type: 'string', required: false, max: 100 },
|
||||||
|
row_no: { type: 'string', required: false, max: 10 },
|
||||||
|
column_no: { type: 'string', required: false, max: 10 },
|
||||||
|
level_no: { type: 'string', required: false, max: 10 },
|
||||||
|
cell_no: { type: 'string', required: false, max: 10 },
|
||||||
|
length: { type: 'number', required: false },
|
||||||
|
width: { type: 'number', required: false },
|
||||||
|
height: { type: 'number', required: false },
|
||||||
|
volume: { type: 'number', required: false },
|
||||||
|
max_weight: { type: 'number', required: false },
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
ctx.validate(rules, data);
|
||||||
|
} catch (error) {
|
||||||
|
ctx.throw(400, error.errors[0].message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查仓位编码唯一性
|
||||||
|
const exists = await ctx.model.LocationSpace.findOne({
|
||||||
|
where: {
|
||||||
|
warehouse_id: data.warehouse_id,
|
||||||
|
space_code: data.space_code,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (exists) {
|
||||||
|
ctx.throw(400, '仓位编码已存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查条码唯一性
|
||||||
|
if (data.custom_barcode) {
|
||||||
|
const barcodeExists = await ctx.model.LocationSpace.findOne({
|
||||||
|
where: { custom_barcode: data.custom_barcode },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (barcodeExists) {
|
||||||
|
ctx.throw(400, '条码已存在');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查关联数据存在性
|
||||||
|
await this._validateReferences(data);
|
||||||
|
|
||||||
|
// 设置创建人
|
||||||
|
const user = ctx.state.user;
|
||||||
|
if (user && user.id) {
|
||||||
|
data.created_by = user.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await ctx.model.LocationSpace.create(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量创建仓位
|
||||||
|
* @param dataList
|
||||||
|
*/
|
||||||
|
async batchCreate(dataList) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
if (!Array.isArray(dataList) || dataList.length === 0) {
|
||||||
|
ctx.throw(400, '仓位数据不能为空');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查批量数据中的唯一性
|
||||||
|
const warehouseId = dataList[0].warehouse_id;
|
||||||
|
const spaceCodes = dataList.map(item => item.space_code);
|
||||||
|
const barcodes = dataList.map(item => item.custom_barcode).filter(Boolean);
|
||||||
|
|
||||||
|
// 检查编码重复
|
||||||
|
const duplicateCodes = await ctx.model.LocationSpace.findAll({
|
||||||
|
where: {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
space_code: { [ctx.app.Sequelize.Op.in]: spaceCodes },
|
||||||
|
},
|
||||||
|
attributes: [ 'space_code' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (duplicateCodes.length > 0) {
|
||||||
|
const codes = duplicateCodes.map(item => item.space_code).join(',');
|
||||||
|
ctx.throw(400, `以下仓位编码已存在: ${codes}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查条码重复
|
||||||
|
if (barcodes.length > 0) {
|
||||||
|
const duplicateBarcodes = await ctx.model.LocationSpace.findAll({
|
||||||
|
where: {
|
||||||
|
custom_barcode: { [ctx.app.Sequelize.Op.in]: barcodes },
|
||||||
|
},
|
||||||
|
attributes: [ 'custom_barcode' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (duplicateBarcodes.length > 0) {
|
||||||
|
const codes = duplicateBarcodes.map(item => item.custom_barcode).join(',');
|
||||||
|
ctx.throw(400, `以下条码已存在: ${codes}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批量创建
|
||||||
|
const user = ctx.state.user;
|
||||||
|
const timestamp = new Date();
|
||||||
|
|
||||||
|
const locationSpaces = dataList.map(data => ({
|
||||||
|
...data,
|
||||||
|
created_by: user ? user.id : null,
|
||||||
|
created_at: timestamp,
|
||||||
|
updated_at: timestamp,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return await ctx.model.LocationSpace.bulkCreate(locationSpaces);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取仓位列表
|
||||||
|
* @param params
|
||||||
|
*/
|
||||||
|
async list(params = {}) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const {
|
||||||
|
warehouse_id,
|
||||||
|
zone_id,
|
||||||
|
location_type_id,
|
||||||
|
space_status,
|
||||||
|
is_enabled,
|
||||||
|
space_code,
|
||||||
|
custom_name,
|
||||||
|
page = 1,
|
||||||
|
pageSize = 20,
|
||||||
|
} = params;
|
||||||
|
|
||||||
|
const where = {};
|
||||||
|
|
||||||
|
if (warehouse_id) {
|
||||||
|
where.warehouse_id = warehouse_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (zone_id) {
|
||||||
|
where.zone_id = zone_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (location_type_id) {
|
||||||
|
where.location_type_id = location_type_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (space_status) {
|
||||||
|
where.space_status = space_status;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_enabled !== undefined) {
|
||||||
|
where.is_enabled = is_enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (space_code) {
|
||||||
|
where.space_code = { [ctx.app.Sequelize.Op.like]: `%${space_code}%` };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (custom_name) {
|
||||||
|
where.custom_name = { [ctx.app.Sequelize.Op.like]: `%${custom_name}%` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const { count, rows } = await ctx.model.LocationSpace.findAndCountAll({
|
||||||
|
where,
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.Store,
|
||||||
|
as: 'warehouse',
|
||||||
|
attributes: [ 'store_name', 'store_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: ctx.model.LocationZone,
|
||||||
|
as: 'zone',
|
||||||
|
attributes: [ 'zone_code', 'zone_name' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: ctx.model.LocationType,
|
||||||
|
as: 'locationType',
|
||||||
|
attributes: [ 'type_code', 'type_name', 'category' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
order: [
|
||||||
|
[ 'warehouse_id', 'ASC' ],
|
||||||
|
[ 'zone_id', 'ASC' ],
|
||||||
|
[ 'row_no', 'ASC' ],
|
||||||
|
[ 'column_no', 'ASC' ],
|
||||||
|
[ 'level_no', 'ASC' ],
|
||||||
|
[ 'cell_no', 'ASC' ],
|
||||||
|
],
|
||||||
|
offset: (page - 1) * pageSize,
|
||||||
|
limit: parseInt(pageSize),
|
||||||
|
distinct: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
list: rows,
|
||||||
|
pagination: {
|
||||||
|
page: parseInt(page),
|
||||||
|
pageSize: parseInt(pageSize),
|
||||||
|
total: count,
|
||||||
|
totalPages: Math.ceil(count / pageSize),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取仓位详情
|
||||||
|
* @param id
|
||||||
|
*/
|
||||||
|
async detail(id) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const locationSpace = await ctx.model.LocationSpace.findByPk(id, {
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.Store,
|
||||||
|
as: 'warehouse',
|
||||||
|
attributes: [ 'id', 'store_name', 'store_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: ctx.model.LocationZone,
|
||||||
|
as: 'zone',
|
||||||
|
attributes: [ 'id', 'zone_code', 'zone_name' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: ctx.model.LocationType,
|
||||||
|
as: 'locationType',
|
||||||
|
attributes: [ 'id', 'type_code', 'type_name', 'category',
|
||||||
|
'allow_allocation', 'allow_transfer_out' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!locationSpace) {
|
||||||
|
ctx.throw(404, '仓位不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
return locationSpace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新仓位
|
||||||
|
* @param id
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
async update(id, data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const locationSpace = await ctx.model.LocationSpace.findByPk(id);
|
||||||
|
if (!locationSpace) {
|
||||||
|
ctx.throw(404, '仓位不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 不能修改的字段
|
||||||
|
const protectedFields = [ 'id', 'warehouse_id', 'created_at', 'created_by' ];
|
||||||
|
protectedFields.forEach(field => delete data[field]);
|
||||||
|
|
||||||
|
// 如果修改编码,检查唯一性
|
||||||
|
if (data.space_code && data.space_code !== locationSpace.space_code) {
|
||||||
|
const exists = await ctx.model.LocationSpace.findOne({
|
||||||
|
where: {
|
||||||
|
warehouse_id: locationSpace.warehouse_id,
|
||||||
|
space_code: data.space_code,
|
||||||
|
id: { [ctx.app.Sequelize.Op.ne]: id },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (exists) {
|
||||||
|
ctx.throw(400, '仓位编码已存在');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果修改条码,检查唯一性
|
||||||
|
if (data.custom_barcode && data.custom_barcode !== locationSpace.custom_barcode) {
|
||||||
|
const exists = await ctx.model.LocationSpace.findOne({
|
||||||
|
where: {
|
||||||
|
custom_barcode: data.custom_barcode,
|
||||||
|
id: { [ctx.app.Sequelize.Op.ne]: id },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (exists) {
|
||||||
|
ctx.throw(400, '条码已存在');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查关联数据存在性
|
||||||
|
if (data.zone_id || data.location_type_id) {
|
||||||
|
await this._validateReferences({
|
||||||
|
zone_id: data.zone_id || locationSpace.zone_id,
|
||||||
|
location_type_id: data.location_type_id || locationSpace.location_type_id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置更新人
|
||||||
|
const user = ctx.state.user;
|
||||||
|
if (user && user.id) {
|
||||||
|
data.updated_by = user.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
await locationSpace.update(data);
|
||||||
|
return locationSpace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除仓位(软删除)
|
||||||
|
* @param id
|
||||||
|
*/
|
||||||
|
async delete(id) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const locationSpace = await ctx.model.LocationSpace.findByPk(id);
|
||||||
|
if (!locationSpace) {
|
||||||
|
ctx.throw(404, '仓位不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查仓位是否被使用
|
||||||
|
if (locationSpace.space_status === 'OCCUPIED') {
|
||||||
|
ctx.throw(400, '仓位已被占用,无法删除');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (locationSpace.current_quantity > 0) {
|
||||||
|
ctx.throw(400, '仓位内仍有库存,无法删除');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 软删除:设置为禁用
|
||||||
|
const user = ctx.state.user;
|
||||||
|
const updateData = {
|
||||||
|
is_enabled: 0,
|
||||||
|
space_status: 'DISABLED',
|
||||||
|
};
|
||||||
|
|
||||||
|
if (user && user.id) {
|
||||||
|
updateData.updated_by = user.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
await locationSpace.update(updateData);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启用/禁用仓位
|
||||||
|
* @param id
|
||||||
|
* @param enabled
|
||||||
|
*/
|
||||||
|
async toggleStatus(id, enabled) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const locationSpace = await ctx.model.LocationSpace.findByPk(id);
|
||||||
|
if (!locationSpace) {
|
||||||
|
ctx.throw(404, '仓位不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = ctx.state.user;
|
||||||
|
const updateData = {
|
||||||
|
is_enabled: enabled ? 1 : 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!enabled && locationSpace.space_status === 'AVAILABLE') {
|
||||||
|
updateData.space_status = 'DISABLED';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user && user.id) {
|
||||||
|
updateData.updated_by = user.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
await locationSpace.update(updateData);
|
||||||
|
return locationSpace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新仓位状态
|
||||||
|
* @param id
|
||||||
|
* @param status
|
||||||
|
*/
|
||||||
|
async updateStatus(id, status) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const validStatuses = [ 'AVAILABLE', 'OCCUPIED', 'RESERVED', 'MAINTENANCE', 'DISABLED' ];
|
||||||
|
if (!validStatuses.includes(status)) {
|
||||||
|
ctx.throw(400, '无效的仓位状态');
|
||||||
|
}
|
||||||
|
|
||||||
|
const locationSpace = await ctx.model.LocationSpace.findByPk(id);
|
||||||
|
if (!locationSpace) {
|
||||||
|
ctx.throw(404, '仓位不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 状态转换限制
|
||||||
|
const statusRules = {
|
||||||
|
OCCUPIED: () => {
|
||||||
|
if (locationSpace.space_status !== 'AVAILABLE' && locationSpace.space_status !== 'RESERVED') {
|
||||||
|
throw new Error('只有可用或预留仓位才能设置为占用');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
AVAILABLE: () => {
|
||||||
|
if (locationSpace.space_status === 'OCCUPIED' && locationSpace.current_quantity > 0) {
|
||||||
|
throw new Error('占用仓位有库存时不能设置为可用');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
if (statusRules[status]) {
|
||||||
|
try {
|
||||||
|
statusRules[status]();
|
||||||
|
} catch (error) {
|
||||||
|
ctx.throw(400, error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = ctx.state.user;
|
||||||
|
const updateData = { space_status: status };
|
||||||
|
|
||||||
|
if (user && user.id) {
|
||||||
|
updateData.updated_by = user.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
await locationSpace.update(updateData);
|
||||||
|
return locationSpace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询可用仓位
|
||||||
|
* @param params
|
||||||
|
*/
|
||||||
|
async findAvailableSpaces(params) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { warehouse_id, zone_id, location_type_id } = params;
|
||||||
|
|
||||||
|
const where = {
|
||||||
|
space_status: 'AVAILABLE',
|
||||||
|
is_enabled: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (warehouse_id) {
|
||||||
|
where.warehouse_id = warehouse_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (zone_id) {
|
||||||
|
where.zone_id = zone_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (location_type_id) {
|
||||||
|
where.location_type_id = location_type_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await ctx.model.LocationSpace.findAll({
|
||||||
|
where,
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.LocationZone,
|
||||||
|
as: 'zone',
|
||||||
|
attributes: [ 'zone_code', 'zone_name' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: ctx.model.LocationType,
|
||||||
|
as: 'locationType',
|
||||||
|
where: { allow_allocation: 1, is_active: 1 },
|
||||||
|
attributes: [ 'type_code', 'type_name' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
order: [
|
||||||
|
[ 'zone_id', 'ASC' ],
|
||||||
|
[ 'row_no', 'ASC' ],
|
||||||
|
[ 'column_no', 'ASC' ],
|
||||||
|
[ 'level_no', 'ASC' ],
|
||||||
|
[ 'cell_no', 'ASC' ],
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据编码查找仓位
|
||||||
|
* @param warehouseId
|
||||||
|
* @param spaceCode
|
||||||
|
*/
|
||||||
|
async findByCode(warehouseId, spaceCode) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const locationSpace = await ctx.model.LocationSpace.findOne({
|
||||||
|
where: {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
space_code: spaceCode,
|
||||||
|
is_enabled: 1,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.LocationZone,
|
||||||
|
as: 'zone',
|
||||||
|
attributes: [ 'zone_code', 'zone_name' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: ctx.model.LocationType,
|
||||||
|
as: 'locationType',
|
||||||
|
attributes: [ 'type_code', 'type_name', 'allow_allocation', 'allow_transfer_out' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!locationSpace) {
|
||||||
|
ctx.throw(404, '仓位不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
return locationSpace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据条码查找仓位
|
||||||
|
* @param barcode
|
||||||
|
*/
|
||||||
|
async findByBarcode(barcode) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const locationSpace = await ctx.model.LocationSpace.findOne({
|
||||||
|
where: {
|
||||||
|
custom_barcode: barcode,
|
||||||
|
is_enabled: 1,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: ctx.model.Store,
|
||||||
|
as: 'warehouse',
|
||||||
|
attributes: [ 'store_name', 'store_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: ctx.model.LocationZone,
|
||||||
|
as: 'zone',
|
||||||
|
attributes: [ 'zone_code', 'zone_name' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!locationSpace) {
|
||||||
|
ctx.throw(404, '仓位不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
return locationSpace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取仓库仓位统计
|
||||||
|
* @param warehouseId
|
||||||
|
*/
|
||||||
|
async getWarehouseStats(warehouseId) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const stats = await ctx.model.LocationSpace.getWarehouseStats(ctx.app, warehouseId);
|
||||||
|
|
||||||
|
// 汇总数据
|
||||||
|
const result = {
|
||||||
|
available: 0,
|
||||||
|
occupied: 0,
|
||||||
|
reserved: 0,
|
||||||
|
maintenance: 0,
|
||||||
|
disabled: 0,
|
||||||
|
total: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
stats.forEach(item => {
|
||||||
|
result[item.space_status.toLowerCase()] = parseInt(item.count);
|
||||||
|
result.total += parseInt(item.count);
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取分区的仓位统计
|
||||||
|
* @param warehouseId
|
||||||
|
* @param zoneId
|
||||||
|
*/
|
||||||
|
async getZoneStats(warehouseId, zoneId = null) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const stats = await ctx.model.LocationSpace.getZoneStats(ctx.app, warehouseId);
|
||||||
|
|
||||||
|
if (zoneId) {
|
||||||
|
return stats.find(item => item.zone_id === zoneId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证仓位是否可分配
|
||||||
|
* @param locationSpaceId
|
||||||
|
*/
|
||||||
|
async validateAllocation(locationSpaceId) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const locationSpace = await ctx.model.LocationSpace.findByPk(locationSpaceId, {
|
||||||
|
include: [{
|
||||||
|
model: ctx.model.LocationType,
|
||||||
|
as: 'locationType',
|
||||||
|
attributes: [ 'allow_allocation', 'is_active' ],
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!locationSpace) {
|
||||||
|
ctx.throw(404, '仓位不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!locationSpace.isAvailable()) {
|
||||||
|
ctx.throw(400, '仓位不可用');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!locationSpace.locationType ||
|
||||||
|
locationSpace.locationType.allow_allocation !== 1 ||
|
||||||
|
locationSpace.locationType.is_active !== 1) {
|
||||||
|
ctx.throw(400, '该仓位类型不允许分配');
|
||||||
|
}
|
||||||
|
|
||||||
|
return locationSpace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证仓位是否可移出
|
||||||
|
* @param locationSpaceId
|
||||||
|
*/
|
||||||
|
async validateTransferOut(locationSpaceId) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const locationSpace = await ctx.model.LocationSpace.findByPk(locationSpaceId, {
|
||||||
|
include: [{
|
||||||
|
model: ctx.model.LocationType,
|
||||||
|
as: 'locationType',
|
||||||
|
attributes: [ 'allow_transfer_out', 'is_active' ],
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!locationSpace) {
|
||||||
|
ctx.throw(404, '仓位不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (locationSpace.space_status !== 'OCCUPIED') {
|
||||||
|
ctx.throw(400, '仓位未被占用');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!locationSpace.locationType ||
|
||||||
|
locationSpace.locationType.allow_transfer_out !== 1 ||
|
||||||
|
locationSpace.locationType.is_active !== 1) {
|
||||||
|
ctx.throw(400, '该仓位类型不允许移出');
|
||||||
|
}
|
||||||
|
|
||||||
|
return locationSpace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 内部方法:验证关联数据
|
||||||
|
* @param data
|
||||||
|
*/
|
||||||
|
async _validateReferences(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
// 验证仓库存在
|
||||||
|
if (data.warehouse_id) {
|
||||||
|
const warehouse = await ctx.model.Store.findByPk(data.warehouse_id);
|
||||||
|
if (!warehouse) {
|
||||||
|
ctx.throw(400, '仓库不存在');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证分区存在
|
||||||
|
if (data.zone_id) {
|
||||||
|
const zone = await ctx.model.LocationZone.findByPk(data.zone_id);
|
||||||
|
if (!zone || !zone.is_active) {
|
||||||
|
ctx.throw(400, '分区不存在或已禁用');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证仓位类型存在
|
||||||
|
if (data.location_type_id) {
|
||||||
|
const locationType = await ctx.model.LocationType.findByPk(data.location_type_id);
|
||||||
|
if (!locationType || !locationType.is_active) {
|
||||||
|
ctx.throw(400, '仓位类型不存在或已禁用');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = LocationSpaceService;
|
||||||
1070
app/service/systems/location_zone.js
Normal file
1070
app/service/systems/location_zone.js
Normal file
File diff suppressed because it is too large
Load Diff
49
app/service/systems/notification.js
Normal file
49
app/service/systems/notification.js
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
const { Service } = require('egg');
|
||||||
|
|
||||||
|
class NotificationService extends Service {
|
||||||
|
constructor(ctx) {
|
||||||
|
super(ctx);
|
||||||
|
// 设置全局变量 oldAction
|
||||||
|
this.oldreceivingUrl = 'http://ye4s.wms.gztbyc.com/index/wms/wms/receiving_notic';
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送通知
|
||||||
|
* @param {Object} options - 通知参数
|
||||||
|
* @param {string} options.type - 通知类型,如 'email', 'sms', 'system'
|
||||||
|
* @param {string} options.title - 通知标题
|
||||||
|
* @param {string} options.content - 通知内容
|
||||||
|
* @param {string} options.bussinessType - 业务类型,如 'receiving'
|
||||||
|
* @param {string[]} [options.receivers] - 接收人列表
|
||||||
|
* @param {string} options.bussinessId - 业务ID
|
||||||
|
* @return {Promise<Object>} 发送结果
|
||||||
|
*/
|
||||||
|
async send(options) {
|
||||||
|
const { type, title, content, bussinessType, bussinessId, receivers = [] } = options;
|
||||||
|
switch (bussinessType) {
|
||||||
|
case 'receiving':
|
||||||
|
// 发送接收通知
|
||||||
|
await this.ctx.curl(this.oldreceivingUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
data: {
|
||||||
|
id: bussinessId,
|
||||||
|
},
|
||||||
|
dataType: 'json',
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: '通知已发送',
|
||||||
|
data: {
|
||||||
|
type,
|
||||||
|
title,
|
||||||
|
content,
|
||||||
|
receivers,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = NotificationService;
|
||||||
130
app/service/systems/operation_log.js
Normal file
130
app/service/systems/operation_log.js
Normal file
@ -0,0 +1,130 @@
|
|||||||
|
// app/service/operationLog.js
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class operationLogService extends Service {
|
||||||
|
/**
|
||||||
|
* 通用操作日志记录方法
|
||||||
|
* @param {Object} params 日志参数
|
||||||
|
* @param {string} params.businessType 业务类型: product, order, stock, wave, express, storage
|
||||||
|
* @param {string} params.businessId 业务ID
|
||||||
|
* @param {string} params.operationCode 操作编码
|
||||||
|
* @param {Object} params.operator 操作人信息
|
||||||
|
* @param {string} params.operator.id 操作人ID
|
||||||
|
* @param {string} params.operator.name 操作人名称
|
||||||
|
* @param {string} params.operationAction 操作动作: CREATE, UPDATE, DELETE, OTHER
|
||||||
|
* @param {string} params.changeSummary 变更描述
|
||||||
|
* @param {Object} params.keyChanges 关键变更字段
|
||||||
|
* @param {Object} params.extras 额外参数
|
||||||
|
* @param {string} params.extras.externalLogType 外部日志类型
|
||||||
|
* @param {number} params.extras.externalLogId 外部日志ID
|
||||||
|
* @param {number} params.extras.warehouseId 仓库ID
|
||||||
|
*/
|
||||||
|
async createOperationLog(params) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const {
|
||||||
|
businessType,
|
||||||
|
businessId,
|
||||||
|
operationCode,
|
||||||
|
operator = {},
|
||||||
|
beforeChanges = null,
|
||||||
|
extras = {},
|
||||||
|
} = params;
|
||||||
|
try {
|
||||||
|
const logData = {
|
||||||
|
business_type: businessType,
|
||||||
|
business_id: String(businessId),
|
||||||
|
operation_code: operationCode,
|
||||||
|
operator_id: operator?.id || null,
|
||||||
|
operator_name: operator?.name || null,
|
||||||
|
external_log_type: extras.externalLogType || 'NONE',
|
||||||
|
external_log_id: extras.externalLogId || null,
|
||||||
|
warehouse_id: extras.warehouseId || null,
|
||||||
|
before_changes: beforeChanges,
|
||||||
|
platform_code: ctx.user?.platform_code || 'SYSTEM',
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await ctx.model.OperationLog.create(logData);
|
||||||
|
ctx.logger.info(`[OperationLog] 记录操作日志成功,ID: ${result.id}, Business: ${businessType}/${businessId}`);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error(`[OperationLog] 记录操作日志失败: ${error.message}`, error);
|
||||||
|
// 生产环境建议添加降级处理,如写入文件或发送到监控系统
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async queryStockLogs(query) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
const {
|
||||||
|
id,
|
||||||
|
warehouseId,
|
||||||
|
page = 1,
|
||||||
|
pageSize = 20,
|
||||||
|
} = query;
|
||||||
|
const where = {};
|
||||||
|
where.business_type = 'stock';
|
||||||
|
if (!id) {
|
||||||
|
throw new Error('id不能为空');
|
||||||
|
} else {
|
||||||
|
where.business_id = id;
|
||||||
|
}
|
||||||
|
if (!warehouseId) {
|
||||||
|
throw new Error('仓库id不能为空');
|
||||||
|
} else {
|
||||||
|
where.warehouse_id = warehouseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
const offset = (page - 1) * pageSize;
|
||||||
|
|
||||||
|
const result = await ctx.model.OperationLog.findAndCountAll({
|
||||||
|
where,
|
||||||
|
order: [[ 'created_at', 'DESC' ]],
|
||||||
|
offset,
|
||||||
|
attributes: [ 'id', 'operation_code', 'operator_name', 'created_at', 'external_log_type', 'external_log_id', 'platform_code' ],
|
||||||
|
limit: pageSize,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
list: result.rows.map(item => {
|
||||||
|
const item_tmp = JSON.parse(JSON.stringify(item));
|
||||||
|
item_tmp.operation_name = app.getOperationCodeName(item.operation_code);
|
||||||
|
item_tmp.platform_name = app.getPlatformName(item.platform_code);
|
||||||
|
item_tmp.created_at = new Date(item_tmp.created_at).format();
|
||||||
|
return item_tmp;
|
||||||
|
}),
|
||||||
|
pagination: {
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
total: result.count,
|
||||||
|
totalPages: Math.ceil(result.count / pageSize),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
console.log(e);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async queryOrderLogs() {
|
||||||
|
|
||||||
|
}
|
||||||
|
async getMessageDetail(data) {
|
||||||
|
const { id, type } = data;
|
||||||
|
const { ctx } = this;
|
||||||
|
const warehouseId = ctx.user.store_id;
|
||||||
|
let LogModel = null;
|
||||||
|
switch (type) {
|
||||||
|
case 'QIMEN':
|
||||||
|
// code
|
||||||
|
LogModel = ctx.model.QimenLog;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const result = await LogModel.findOne({ where: { id } });
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = operationLogService;
|
||||||
276
app/service/systems/platform.js
Normal file
276
app/service/systems/platform.js
Normal file
@ -0,0 +1,276 @@
|
|||||||
|
// app/service/system/platform.js
|
||||||
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
|
class PlatformService extends Service {
|
||||||
|
/**
|
||||||
|
* 检查平台是否存在
|
||||||
|
* 逻辑:
|
||||||
|
* 1. 先查询设置表,有对应的平台代码+仓库ID组合,返回关联的基础表的代码和名称
|
||||||
|
* 2. 如果没有,尝试基础表中的code是否匹配,存在匹配则直接返回基础表的代码和名称
|
||||||
|
* 3. 使用缓存优化性能
|
||||||
|
* @param {string} platformCode 平台代码
|
||||||
|
* @param {number} warehouseId 仓库ID
|
||||||
|
* @return {Promise<Object|null>} 平台信息或null
|
||||||
|
*/
|
||||||
|
async checkPlatformExists(platformCode, warehouseId) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
|
||||||
|
// 生成缓存key
|
||||||
|
const cacheKey = `platform:${platformCode}:${warehouseId}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 先从缓存获取
|
||||||
|
const cachedData = await app.getCacheAsync(cacheKey);
|
||||||
|
if (cachedData) {
|
||||||
|
ctx.logger.info(`从缓存获取平台信息: ${cacheKey}`);
|
||||||
|
// 如果缓存中存的是"不存在"的特殊标记,返回null
|
||||||
|
if (cachedData === '__NOT_EXISTS__') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return cachedData;
|
||||||
|
}
|
||||||
|
ctx.logger.info(`${cacheKey}无缓存`);
|
||||||
|
|
||||||
|
|
||||||
|
let platformInfo = null;
|
||||||
|
// 2. 先查询平台设置表(关联基础平台表)
|
||||||
|
const platformSetting = await app.model.PlatformSetting.findOne({
|
||||||
|
where: {
|
||||||
|
code: platformCode,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: this.app.model.Platform,
|
||||||
|
as: 'platform',
|
||||||
|
attributes: [ 'code', 'name', 'default_express_interface' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
if (platformSetting && platformSetting.platform) {
|
||||||
|
// 从设置表中找到,并且有关联的平台信息
|
||||||
|
platformInfo = {
|
||||||
|
code: platformSetting.platform.code,
|
||||||
|
name: platformSetting.platform.name,
|
||||||
|
default_express_interface: platformSetting.platform.default_express_interface,
|
||||||
|
source: 'setting', // 标记来源
|
||||||
|
setting_id: platformSetting.id,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
// 3. 设置表中没有,直接查询基础平台表
|
||||||
|
const basePlatform = await app.model.Platform.findOne({
|
||||||
|
where: {
|
||||||
|
code: platformCode,
|
||||||
|
},
|
||||||
|
attributes: [ 'code', 'name', 'default_express_interface' ],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (basePlatform) {
|
||||||
|
platformInfo = {
|
||||||
|
code: basePlatform.code,
|
||||||
|
name: basePlatform.name,
|
||||||
|
default_express_interface: basePlatform.default_express_interface,
|
||||||
|
source: 'base', // 标记来源
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 设置缓存
|
||||||
|
if (platformInfo) {
|
||||||
|
// 平台存在,缓存5分钟
|
||||||
|
await app.setCacheAsync(cacheKey, platformInfo, 300);
|
||||||
|
ctx.logger.info(`平台信息已缓存: ${cacheKey}`);
|
||||||
|
} else {
|
||||||
|
// 平台不存在,缓存特殊标记,时间可以短一些(2分钟)
|
||||||
|
await app.setCacheAsync(cacheKey, '__NOT_EXISTS__', 120);
|
||||||
|
ctx.logger.info(`平台不存在标记已缓存: ${cacheKey}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return platformInfo;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error(`检查平台存在性失败: ${error.message}`, {
|
||||||
|
platformCode,
|
||||||
|
warehouseId,
|
||||||
|
error: error.stack,
|
||||||
|
});
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取平台信息(带异常处理)
|
||||||
|
* @param {string} platformCode 平台代码
|
||||||
|
* @param {number} warehouseId 仓库ID
|
||||||
|
* @return {Promise<Object>} 平台信息
|
||||||
|
* @throws {Error} 平台不存在时抛出异常
|
||||||
|
*/
|
||||||
|
async getPlatformInfo(platformCode, warehouseId) {
|
||||||
|
const platformInfo = await this.checkPlatformExists(platformCode, warehouseId);
|
||||||
|
|
||||||
|
if (!platformInfo) {
|
||||||
|
throw new Error(`平台 ${platformCode} 在仓库 ${warehouseId} 中不存在`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return platformInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除平台缓存
|
||||||
|
* @param {string} platformCode 平台代码
|
||||||
|
* @param {number} warehouseId 仓库ID
|
||||||
|
*/
|
||||||
|
async clearPlatformCache(platformCode, warehouseId) {
|
||||||
|
const { app } = this;
|
||||||
|
const cacheKey = `platform:${platformCode}:${warehouseId}`;
|
||||||
|
await app.setCacheAsync(cacheKey, null, 0); // 立即过期
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取平台设置详情(包括完整的设置信息)
|
||||||
|
* @param {string} platformCode 平台代码
|
||||||
|
* @param {number} warehouseId 仓库ID
|
||||||
|
* @return {Promise<Object|null>} 平台设置详情
|
||||||
|
*/
|
||||||
|
async getPlatformSettingDetail(platformCode, warehouseId) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const cacheKey = `platform_setting_detail:${platformCode}:${warehouseId}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 从缓存获取
|
||||||
|
const cachedData = await this.app.getCacheAsync(cacheKey);
|
||||||
|
if (cachedData) {
|
||||||
|
return cachedData === '__NOT_EXISTS__' ? null : cachedData;
|
||||||
|
}
|
||||||
|
|
||||||
|
const setting = await this.app.model.PlatformSetting.findOne({
|
||||||
|
where: {
|
||||||
|
code: platformCode,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
},
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: this.app.model.Platform,
|
||||||
|
as: 'platform',
|
||||||
|
attributes: [ 'code', 'name', 'default_express_interface' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (setting) {
|
||||||
|
const result = {
|
||||||
|
id: setting.id,
|
||||||
|
platform_code: setting.platform_code,
|
||||||
|
code: setting.code,
|
||||||
|
warehouse_id: setting.warehouse_id,
|
||||||
|
platform: setting.platform,
|
||||||
|
warehouse: setting.warehouse,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 缓存10分钟
|
||||||
|
await this.app.setCacheAsync(cacheKey, result, 600);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
// 缓存2分钟的不存在标记
|
||||||
|
await this.app.setCacheAsync(cacheKey, '__NOT_EXISTS__', 120);
|
||||||
|
return null;
|
||||||
|
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
this.ctx.logger.error(`获取平台设置详情失败: ${error.message}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量检查多个平台
|
||||||
|
* @param {Array} platformWarehouseList 平台和仓库列表 [{platformCode, warehouseId}, ...]
|
||||||
|
* @return {Promise<Array>} 存在的平台列表
|
||||||
|
*/
|
||||||
|
async batchCheckPlatforms(platformWarehouseList) {
|
||||||
|
const results = [];
|
||||||
|
|
||||||
|
for (const item of platformWarehouseList) {
|
||||||
|
const { platformCode, warehouseId } = item;
|
||||||
|
const exists = await this.checkPlatformExists(platformCode, warehouseId);
|
||||||
|
|
||||||
|
if (exists) {
|
||||||
|
results.push({
|
||||||
|
platformCode,
|
||||||
|
warehouseId,
|
||||||
|
exists: true,
|
||||||
|
info: exists,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
results.push({
|
||||||
|
platformCode,
|
||||||
|
warehouseId,
|
||||||
|
exists: false,
|
||||||
|
info: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建平台设置
|
||||||
|
* @param {Object} data 平台设置数据
|
||||||
|
* @param {string} data.platform_code 平台代码
|
||||||
|
* @param {string} data.code 设置代码
|
||||||
|
* @param {number} data.warehouse_id 仓库ID
|
||||||
|
* @return {Promise<Object>} 创建的设置
|
||||||
|
*/
|
||||||
|
async createPlatformSetting(data) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 验证平台是否存在
|
||||||
|
const platform = await this.app.model.Platform.findOne({
|
||||||
|
where: { code: data.platform_code },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!platform) {
|
||||||
|
throw new Error(`平台 ${data.platform_code} 不存在`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 验证仓库是否存在
|
||||||
|
const warehouse = await this.app.model.Store.findOne({
|
||||||
|
where: { id: data.warehouse_id },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!warehouse) {
|
||||||
|
throw new Error(`仓库 ${data.warehouse_id} 不存在`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 检查是否已存在相同的设置
|
||||||
|
const exists = await this.app.model.PlatformSetting.findOne({
|
||||||
|
where: {
|
||||||
|
platform_code: data.platform_code,
|
||||||
|
warehouse_id: data.warehouse_id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (exists) {
|
||||||
|
throw new Error(`平台 ${data.platform_code} 在仓库 ${data.warehouse_id} 中已存在设置`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 创建设置
|
||||||
|
const setting = await this.app.model.PlatformSetting.create(data);
|
||||||
|
|
||||||
|
// 5. 清除相关缓存
|
||||||
|
await this.clearPlatformCache(data.platform_code, data.warehouse_id);
|
||||||
|
|
||||||
|
return setting;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error(`创建平台设置失败: ${error.message}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = PlatformService;
|
||||||
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