chore: 更新接口文档路由与methods工作流
This commit is contained in:
parent
4faff36ccb
commit
279b292bae
226
AI_METHOD_ROUTING.md
Normal file
226
AI_METHOD_ROUTING.md
Normal file
@ -0,0 +1,226 @@
|
||||
# AI 方法路由速查(WMS)
|
||||
|
||||
本文用于让 AI/开发者快速理解入口路由与 method 到代码文件的映射关系。
|
||||
|
||||
## 1. 入口定义(router 风格)
|
||||
|
||||
当前路由定义见 `app/router.js`:
|
||||
- `POST /qimen` -> 奇门开发接口入口
|
||||
- `POST /system` -> Web 端与 PDA 端统一业务入口
|
||||
|
||||
注意:当前代码中 `/qimen` 与 `/system` 都是 `POST` 路由。
|
||||
|
||||
## 2. /system 入口说明(统一 Web + PDA)
|
||||
|
||||
调用链:
|
||||
1. `app/router.js` -> `controller.home.system`
|
||||
2. `app/controller/home.js` 的 `system()` 读取 `ctx.query.method`
|
||||
3. `app/service/system.js` 的 `callMethod(className, actionName, requestData, authHeader)`
|
||||
4. 从 `ctx.service.systemMethods` 中按 method 分段下钻并执行目标函数
|
||||
|
||||
参数规则(system):
|
||||
- 必填 query: `method`, `v`, `timestamp`
|
||||
- 认证头:可传 `Authorization`
|
||||
- 请求体:JSON(`system()` 中按 JSON 解析)
|
||||
|
||||
外部请求示例:
|
||||
|
||||
```text
|
||||
POST http://127.0.0.1:6060/system?method=print.getComputerPrinter&v=1.0×tamp=1773386721
|
||||
```
|
||||
|
||||
示例 body(按业务方法需要):
|
||||
|
||||
```json
|
||||
{
|
||||
"id": 10001
|
||||
}
|
||||
```
|
||||
|
||||
## 3. /qimen 入口说明(奇门开发接口)
|
||||
|
||||
调用链:
|
||||
1. `app/router.js` -> `controller.home.qimen`
|
||||
2. `app/controller/home.js` 的 `qimen()` 读取 `ctx.query.method`
|
||||
3. `app/service/qimen.js` 的 `callMethod(className, actionName, xmlData, ...)`
|
||||
4. 从 `ctx.service.qimenMethods` 中按 method 分段下钻并执行目标函数
|
||||
|
||||
参数规则(qimen):
|
||||
- 必填 query: `app_key`, `method`, `v`, `format`, `sign_method`, `sign`, `timestamp`
|
||||
- 请求体:XML(`qimen()` 中按 XML 解析)
|
||||
|
||||
## 4. method 指向规则(核心)
|
||||
|
||||
统一规则:
|
||||
- `method` 最后一段是函数名(actionName)
|
||||
- 前面部分是 service 路径(className)
|
||||
- service 路径按 `.` 拆分后,对应到 `app/service/systemMethods` 或 `app/service/qimenMethods` 的目录层级
|
||||
|
||||
### 4.1 /system 示例
|
||||
|
||||
1) `method=print.getComputerPrinter`
|
||||
- service 路径:`print`
|
||||
- 函数名:`getComputerPrinter`
|
||||
- 对应文件:`app/service/systemMethods/print.js`
|
||||
- 对应方法:`getComputerPrinter(data)`
|
||||
|
||||
2) `method=setting.printTemplate.list`
|
||||
- service 路径:`setting.printTemplate`
|
||||
- 函数名:`list`
|
||||
- 对应文件:`app/service/systemMethods/setting/printTemplate.js`
|
||||
- 对应方法:`list(data)`
|
||||
|
||||
3) `method=printer.station.list`
|
||||
- service 路径:`printer.station`
|
||||
- 函数名:`list`
|
||||
- 对应文件:`app/service/systemMethods/printer/station.js`
|
||||
- 对应方法:`list()`
|
||||
|
||||
### 4.2 /qimen 示例
|
||||
|
||||
1) `method=deliveryorder.xxx`
|
||||
- service 路径:`deliveryorder`
|
||||
- 对应文件:`app/service/qimenMethods/deliveryorder.js`
|
||||
|
||||
2) `method=taobao.qimen.service.xxx`
|
||||
- service 路径:`taobao.qimen.service`
|
||||
- 对应文件:`app/service/qimenMethods/taobao/qimen/service.js`
|
||||
|
||||
## 5. AI 快速定位建议
|
||||
|
||||
当收到 `method=aaa.bbb.ccc` 时,优先按以下步骤定位:
|
||||
1. 判定入口:`/system` 还是 `/qimen`
|
||||
2. 取最后一段 `ccc` 作为函数名
|
||||
3. 其余部分 `aaa.bbb` 作为 service 路径
|
||||
4. 在对应 methods 目录查找文件并确认类方法是否存在
|
||||
|
||||
可用检索命令示例:
|
||||
|
||||
```powershell
|
||||
rg "getComputerPrinter|class PrintService" app/service/systemMethods
|
||||
rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
```
|
||||
## 后续所有的method新增变更全部需要维护到下方
|
||||
|
||||
|
||||
## method结束
|
||||
|
||||
## 6. 全量 Service Method 能力清单(自动扫描)
|
||||
|
||||
维护说明:
|
||||
- 扫描范围:app/service/**/*.js
|
||||
- 本节内容由脚本生成,新增/修改 service 后请同步刷新。
|
||||
- 刷新命令:node .\script\tmp-gen-service-method-inventory.cjs
|
||||
|
||||
<!-- SERVICE_METHOD_INVENTORY:BEGIN -->
|
||||
自动生成时间: 2026-03-22T06:43:50.263Z
|
||||
|
||||
扫描范围: app/service/**/*.js
|
||||
文件数: 50
|
||||
|
||||
- app/service/api.js (1)
|
||||
- callMethod
|
||||
- app/service/apiMethods/test.js (4)
|
||||
- entryorderConfirm, playbackRequest, fibonacci, fibonacciRecursive
|
||||
- app/service/dispatcher.js (3)
|
||||
- buildMap, getMethodMap, invoke
|
||||
- app/service/main.js (11)
|
||||
- success, fail, normalizeDate, setInfo, getInfo, findQimenAppWithContract, queryFromDatabase, checkAuth, checkApiPermission, setUserContext, systemInit
|
||||
- app/service/pda.js (3)
|
||||
- callMethod, validateParams, saveLog
|
||||
- app/service/qimen.js (12)
|
||||
- validateApi, getErpName, parseXmlToArray, cleanXmlString, callMethod, formatResponse, xmlResponse, buildXmlNode, escapeXml, saveQimenLog, saveQimenLogResult, saveQimenLogBody
|
||||
- app/service/qimenMethods/deliveryorder.js (3)
|
||||
- query, create, batchcreate
|
||||
- app/service/qimenMethods/entryorder.js (2)
|
||||
- create, query
|
||||
- app/service/qimenMethods/inventory.js (1)
|
||||
- query
|
||||
- app/service/qimenMethods/order.js (2)
|
||||
- cancel, pending
|
||||
- app/service/qimenMethods/returnorder.js (2)
|
||||
- create, query
|
||||
- app/service/qimenMethods/singleitem.js (2)
|
||||
- synchronize, query
|
||||
- app/service/qimenMethods/stockout.js (2)
|
||||
- create, query
|
||||
- app/service/qimenMethods/taobao/qimen/service.js (1)
|
||||
- heartbeat
|
||||
- app/service/system.js (3)
|
||||
- callMethod, validateParams, saveLog
|
||||
- app/service/systemMethods/config.js (1)
|
||||
- list
|
||||
- app/service/systemMethods/dashboard.js (6)
|
||||
- storeStats, warehouseStats, hot_order_rank, express_ratio, platform_distribution, order_trend
|
||||
- app/service/systemMethods/index.js (13)
|
||||
- fastWhereTree, loadStores, getCOSUploadConfig, getImages, uploadSuccessNotify, ReferenceFile, getMessageDetail, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, getExpressList
|
||||
- app/service/systemMethods/order.js (11)
|
||||
- getWarehouseId, getOrderModels, applyDateRange, buildWhere, parseDateTime, list, detail, listItems, stats, updateStatus, updateDeliveryTime
|
||||
- app/service/systemMethods/print.js (3)
|
||||
- send, sendToComputer, log
|
||||
- app/service/systemMethods/printer/station.js (1)
|
||||
- list
|
||||
- app/service/systemMethods/setting/printTemplate.js (3)
|
||||
- list, save, listTemplatesByType
|
||||
- app/service/systemMethods/stock.js (21)
|
||||
- stockWarehouse, getProhibitedType, getInfo, saveWarehouseStock, createWarehouseStock, getBarcodes, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, checkItemCodeUnique, queryStockLogs, handleBatchDelete, deleteUnit, deleteProhibited, handleBatchChange, getStockUnits, getUnitList, createProhibited, createUnit, search
|
||||
- app/service/systemMethods/storage/receiving.js (13)
|
||||
- getReceivingList, getReceivingDetail, batchCancelReceiving, create, addItem, removeItem, saveReceiving, get, addDetail, deleteDetail, detailChange, cancel, completeReceiving
|
||||
- app/service/systemMethods/store.js (6)
|
||||
- createStore, createWarehouse, joinStore, joinWarehouse, getStoreRoles, auditApply
|
||||
- app/service/systemMethods/user.js (5)
|
||||
- login, logout, info, changeRole, register
|
||||
- app/service/systemMethods/warehouse.js (20)
|
||||
- getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, createRack, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo
|
||||
- app/service/systems/account_platform.js (8)
|
||||
- switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext
|
||||
- app/service/systems/auth/user.js (21)
|
||||
- login, ID, changeRole, info, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register
|
||||
- app/service/systems/delivery_order.js (7)
|
||||
- addOrder, generateItemsHash, calculateCRC32, prepareOrderData, addOrderLines, safeParseFloat, addOrderToQueue
|
||||
- app/service/systems/entry_order.js (9)
|
||||
- addOrder, getLineCount, received, success, fail, tryCreateEntryOrder, addItems, qimenEntryorderConfirm, entryorderConfirm
|
||||
- app/service/systems/fast_where.js (13)
|
||||
- buildTree, getTreeByType, buildSubTree, getWithChildrenByType, getAllChildren, getByType, getGroups, getChildrenByPid, getTreeChildrenByPid, create, update, findById, delete
|
||||
- app/service/systems/file.js (2)
|
||||
- getImages, ReferenceFile
|
||||
- app/service/systems/location_space.js (16)
|
||||
- create, batchCreate, list, detail, update, delete, toggleStatus, updateStatus, findAvailableSpaces, findByCode, findByBarcode, getWarehouseStats, getZoneStats, validateAllocation, validateTransferOut, _validateReferences
|
||||
- app/service/systems/location_zone.js (22)
|
||||
- getWarehouseLevelZones, getZoneTreeByWarehouse, getChildrenByZoneId, isLeafNode, createZone, validateBasicFields, validateByZoneType, validateParentElement, validateZoneOverlap, isOverlap, generateZoneCodeByType, getDefaultColorByType, getZoneTypeText, updateZone, deleteZone, checkZoneOverlap, getZoneDetail, toggleZoneActive, getZonePath, generateSpacesForRack, getSpaceInfo, checkBarcodeUnique
|
||||
- app/service/systems/location.js (10)
|
||||
- createRackWithSpaces, _generateSpacesForRack, _calculateAreaRackOrder, _calculatePickPathForWarehouse, _updateSpacePickSequence, _calculatePickPriority, updateRackPosition, getPickPath, updateNeighborRelations, _findNeighborRacks
|
||||
- app/service/systems/notification.js (1)
|
||||
- send
|
||||
- app/service/systems/operation_log.js (4)
|
||||
- createOperationLog, queryStockLogs, queryOrderLogs, getMessageDetail
|
||||
- app/service/systems/platform.js (6)
|
||||
- checkPlatformExists, getPlatformInfo, clearPlatformCache, getPlatformSettingDetail, batchCheckPlatforms, createPlatformSetting
|
||||
- app/service/systems/polo_api.js (6)
|
||||
- getJsonDatas, getJsonData, getSignText, md5Encrypt, _formatDate, _formatPickupDate
|
||||
- app/service/systems/print/index.js (2)
|
||||
- sendToComputer, test
|
||||
- app/service/systems/qimen_query.js (6)
|
||||
- send, replaceXmlTagsWithString, addSign, getQueryParams, generateUrlWithParams, sendRequest
|
||||
- app/service/systems/setting/print_template.js (14)
|
||||
- listTemplatesByType, getTree, getTemplatesByType, save, getBusinessTypesAndItem, getGroupedPrintItems, getTableConfigs, clearBusinessTypesCache, getXmlByTemplate, buildXmlFromElements, renderElement, computeItemStyle, computeTableItemStyle, renderTable
|
||||
- app/service/systems/sign.js (10)
|
||||
- Constants, toXml, signTopRequest, verifyTopRequest, verifyAndExtractParams, generateSignedParams, encryptHMAC, encryptHMACSHA256, encryptMD5, byte2hex
|
||||
- app/service/systems/space.js (1)
|
||||
- searchSpace
|
||||
- app/service/systems/stock_store.js (34)
|
||||
- create, initQimenStockData, convertToQimenFormat, getItemInfoWithCache, getItemStorages, _calculateCacheTTL, clearItemStorageCache, lockItemStorages, ID, inbound, outbound, checkAndCreateWarehouseStock, getWarehouseStock, buildSequelizeCondition, processConditionValue, formatDate, isEmptyValue, getProhibitedType, getBarcodes, handleBatchChange, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, getInfo, saveWarehouseStock, createWarehouseStock, validateSaveParams, stockLog, checkItemCodeUnique, handleBatchDelete, deleteUnit, deleteProhibited, search
|
||||
- app/service/systems/storage/index.js (1)
|
||||
- index
|
||||
- app/service/systems/storage/receiving.js (16)
|
||||
- getReceivingList, getReceivingDetail, batchCancelReceiving, isEmptyValue, buildSequelizeCondition, processConditionValue, create, get, addDetail, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, completeReceiving
|
||||
- app/service/systems/store.js (13)
|
||||
- getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores
|
||||
- app/service/systems/upload.js (14)
|
||||
- initCOS, getUploadParams, hash_hmac, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback
|
||||
<!-- SERVICE_METHOD_INVENTORY:END -->
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
170
AI_TOOLBOX.md
Normal file
170
AI_TOOLBOX.md
Normal file
@ -0,0 +1,170 @@
|
||||
# AI 工具箱(WMS)
|
||||
|
||||
本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。
|
||||
|
||||
## 1. 适用范围
|
||||
|
||||
- 项目根目录:D:\\wms
|
||||
- 主要用途:本地调试、数据库取数、问题定位
|
||||
- 默认环境:PowerShell + Node.js
|
||||
|
||||
## 2. 数据库调试脚本
|
||||
|
||||
项目已提供数据库查询脚本:`script/db-query.ps1`
|
||||
|
||||
脚本能力:
|
||||
- 自动读取 `config/config.local.js` 中的 `config.mysql.clients.<clientName>` 配置
|
||||
- 执行传入 SQL 并返回 JSON
|
||||
- 可选表格输出,便于命令行快速查看
|
||||
|
||||
### 2.1 基本用法
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT 1 AS ok"
|
||||
```
|
||||
|
||||
### 2.2 常用示例
|
||||
|
||||
```powershell
|
||||
# 查询最近 10 条账号
|
||||
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT * FROM account ORDER BY id DESC LIMIT 10"
|
||||
|
||||
# 表格输出
|
||||
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT id, name FROM store LIMIT 20" -AsTable
|
||||
|
||||
# 指定 mysql client(默认是 wms)
|
||||
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Query "SHOW TABLES"
|
||||
```
|
||||
|
||||
### 2.3 参数说明
|
||||
|
||||
- `-Query`:必填,SQL 语句
|
||||
- `-DbClient`:可选,MySQL 客户端名,默认 `wms`
|
||||
- `-ConfigPath`:可选,配置文件路径,默认 `.\config\config.local.js`(相对于项目根目录)
|
||||
- `-AsTable`:可选,按表格输出结果
|
||||
|
||||
### 2.4 返回结果说明
|
||||
|
||||
默认输出 JSON,结构如下:
|
||||
|
||||
```json
|
||||
{
|
||||
"client": "wms",
|
||||
"rowCount": 1,
|
||||
"rows": [
|
||||
{
|
||||
"ok": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## 3. AI 协助时建议使用的提问模板
|
||||
|
||||
### 3.1 只读查询(推荐)
|
||||
|
||||
```text
|
||||
请在项目根目录执行 script/db-query.ps1,查询 SQL:
|
||||
SELECT * FROM account LIMIT 20;
|
||||
并把结果按表格给我,同时解释关键字段含义。
|
||||
```
|
||||
|
||||
### 3.2 先分析再查询
|
||||
|
||||
```text
|
||||
请先阅读 app/model 下与 store 相关的模型,再使用 script/db-query.ps1 查询最近 50 条门店数据,
|
||||
最后输出:1) 字段映射说明 2) 异常数据判断规则 3) 建议补充索引。
|
||||
```
|
||||
|
||||
### 3.3 联合排障
|
||||
|
||||
```text
|
||||
请帮我排查某接口返回为空:
|
||||
1) 找到对应 controller 和 service
|
||||
2) 给出需要执行的 SQL
|
||||
3) 使用 script/db-query.ps1 验证每一步
|
||||
4) 输出最终根因和修复建议
|
||||
```
|
||||
|
||||
## 4. 常见问题
|
||||
|
||||
- 报错 `Cannot find module 'mysql2/promise'`
|
||||
- 先执行 `npm install`,确认依赖完整
|
||||
|
||||
- 报错 `MySQL client "xxx" not found in config.mysql.clients`
|
||||
- 检查 `config/config.local.js` 中 `config.mysql.clients` 是否包含对应 client
|
||||
|
||||
- 报错连接失败(超时/拒绝访问)
|
||||
- 检查数据库 IP、端口、用户名密码、网络白名单
|
||||
|
||||
- PowerShell 执行策略限制
|
||||
- 使用命令中的 `-ExecutionPolicy Bypass`(仅本次命令生效)
|
||||
|
||||
## 5. 安全约束
|
||||
|
||||
- 默认只执行 SELECT/SHOW 等只读 SQL
|
||||
- 执行 UPDATE/DELETE 前必须先让 AI 生成影响范围确认 SQL(COUNT + WHERE 条件)
|
||||
- 涉及生产数据时,优先在测试环境验证
|
||||
|
||||
## 6. 接口入口与 Method 指向
|
||||
|
||||
- 入口风格:
|
||||
- `/qimen`:奇门开发接口(POST)
|
||||
- `/system`:Web 端与 PDA 端统一接口(POST)
|
||||
|
||||
- 外部请求示例:
|
||||
- `http://127.0.0.1:6060/system?method=print.getComputerPrinter&v=1.0×tamp=1773386721`
|
||||
|
||||
- Method 指向说明文档:
|
||||
- 见 `AI_METHOD_ROUTING.md`
|
||||
- 文档记录了 method 到 `app/service/systemMethods`、`app/service/qimenMethods` 的映射规则与示例。
|
||||
|
||||
## 7. methods 目录地图
|
||||
|
||||
目录:`methods/`
|
||||
|
||||
- `methods/system.json`
|
||||
- 作用:维护 `/system`(及 system 风格 method)的接口说明。
|
||||
- 覆盖内容:公共请求头、method 分组、params、response、errors。
|
||||
|
||||
- `methods/qimen.json`
|
||||
- 作用:维护 `/qimen` 接口说明。
|
||||
- 覆盖内容:奇门 method、请求格式、响应格式、错误码。
|
||||
|
||||
建议将 `methods/*.json` 视为“接口文档单一事实来源(SSOT)”。
|
||||
|
||||
## 8. 接口变更联动工作流(强制)
|
||||
|
||||
当出现以下任一变更时,必须同步更新 `methods` 目录下对应 JSON:
|
||||
|
||||
1. 新增接口(新增 method)
|
||||
2. 修改接口入参(新增/删除/重命名/必填变化)
|
||||
3. 修改公共请求头(如 `platform`、`project`、`Authorization`)
|
||||
4. 修改响应结构或错误码
|
||||
|
||||
执行步骤:
|
||||
|
||||
1. 先改代码(controller/service/model)
|
||||
2. 更新对应文档文件:
|
||||
- system 入口改 `methods/system.json`
|
||||
- qimen 入口改 `methods/qimen.json`
|
||||
3. 若 system 入参有变化,执行参数结构化脚本刷新:
|
||||
|
||||
```powershell
|
||||
node .\script\tmp-struct-system-params.cjs
|
||||
```
|
||||
|
||||
4. 人工补充自动脚本无法推断的信息:
|
||||
- `description`
|
||||
- `response`
|
||||
- `errors`
|
||||
- 特殊枚举值与业务约束
|
||||
5. 提交前自检:
|
||||
- method 名称与代码一致
|
||||
- params 的 `name/type/required/source` 完整
|
||||
- 公共头部声明与实际鉴权逻辑一致
|
||||
|
||||
执行规则:接口代码与 `methods/*.json` 不一致时,以“必须补齐文档”为完成标准。
|
||||
|
||||
|
||||
|
||||
10
README.md
10
README.md
@ -93,3 +93,13 @@ npm stop
|
||||
如需二次开发或遇到问题,欢迎提 issue 或联系维护者。
|
||||
|
||||
[Egg.js 官方文档](https://eggjs.org)
|
||||
|
||||
## AI 协作工具箱
|
||||
|
||||
- 见 `AI_TOOLBOX.md`,内含数据库调试脚本 `script/db-query.ps1` 的完整使用方法与 AI 提问模板。
|
||||
- 见 `AI_METHOD_ROUTING.md`,内含入口路由与 method 到代码文件的映射关系。
|
||||
|
||||
## 日报维护
|
||||
|
||||
- 日报统一记录在 `day.log`。
|
||||
- 每次更新日报内容时,需同步更新 `day.log` 文件,确保项目内留痕一致。
|
||||
|
||||
965
app/controller/docs.js
Normal file
965
app/controller/docs.js
Normal file
@ -0,0 +1,965 @@
|
||||
const {
|
||||
Controller,
|
||||
} = require('egg');
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value || '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function toArray(value) {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
|
||||
function slugify(value) {
|
||||
return String(value || '')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
|
||||
.replace(/(^-|-$)/g, '');
|
||||
}
|
||||
|
||||
function normalizeGroups(docData) {
|
||||
if (docData && docData.methods && Array.isArray(docData.methods.groups)) {
|
||||
return docData.methods.groups.map(group => ({
|
||||
groupName: group.groupName || group.module || 'Default',
|
||||
module: group.module || '',
|
||||
list: toArray(group.list),
|
||||
}));
|
||||
}
|
||||
|
||||
if (docData && Array.isArray(docData.endpoints)) {
|
||||
return [{
|
||||
groupName: 'Endpoints',
|
||||
module: docData.module || '',
|
||||
list: docData.endpoints,
|
||||
}];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
function renderKeyValueRows(items, keyMap) {
|
||||
if (!items.length) {
|
||||
return '<tr><td colspan="4" class="muted">暂无数据</td></tr>';
|
||||
}
|
||||
|
||||
return items.map(item => {
|
||||
return `<tr>
|
||||
<td>${escapeHtml(item[keyMap.name] || '')}</td>
|
||||
<td>${escapeHtml(item[keyMap.type] || '')}</td>
|
||||
<td>${item[keyMap.required] ? '是' : '否'}</td>
|
||||
<td>${escapeHtml(item[keyMap.description] || '')}</td>
|
||||
</tr>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderGlobalHeadersControls(globalHeaders) {
|
||||
const headers = toArray(globalHeaders);
|
||||
if (!headers.length) {
|
||||
return '<p class="muted">当前文档未定义额外全局 Header</p>';
|
||||
}
|
||||
|
||||
return `<div class="global-headers-grid">${headers.map(item => {
|
||||
const name = item.name || '';
|
||||
const type = item.type || 'string';
|
||||
const required = !!item.required;
|
||||
const description = item.description || '';
|
||||
const options = toArray(item.list);
|
||||
|
||||
const field = options.length
|
||||
? `<select class="global-header-control" data-header-name="${escapeHtml(name)}" data-required="${required ? 'true' : 'false'}">
|
||||
<option value="">请选择</option>
|
||||
${options.map(option => `<option value="${escapeHtml(option.value || '')}">${escapeHtml(option.name || option.value || '')}</option>`).join('')}
|
||||
</select>`
|
||||
: `<input class="global-header-control" type="text" data-header-name="${escapeHtml(name)}" data-required="${required ? 'true' : 'false'}" placeholder="请输入 ${escapeHtml(name)}" />`;
|
||||
|
||||
return `<label class="global-header-item">
|
||||
<span>${escapeHtml(name)}${required ? ' *' : ''}</span>
|
||||
${field}
|
||||
<small class="muted">${escapeHtml(description)} (${escapeHtml(type)})</small>
|
||||
</label>`;
|
||||
}).join('')}</div>`;
|
||||
}
|
||||
|
||||
function renderMethodCard(item, entryPath, moduleName) {
|
||||
const headers = toArray(item.headers);
|
||||
const params = toArray(item.params);
|
||||
const response = toArray(item.response);
|
||||
const errors = toArray(item.errors);
|
||||
const methodName = item.method || item.name || 'unknown';
|
||||
const description = item.description || '';
|
||||
const isQimen = moduleName === 'qimen';
|
||||
const queryHint = isQimen
|
||||
? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx×tamp=1700000000'
|
||||
: `method=${methodName}&v=1.0×tamp=1700000000`;
|
||||
|
||||
return `<section class="method-card" id="${escapeHtml(methodName)}" data-method="${escapeHtml(methodName)}" data-desc="${escapeHtml(description)}" data-module="${escapeHtml(moduleName || '')}" data-endpoint="${escapeHtml(entryPath)}" data-login-required="${item.isNeedLogin ? 'true' : 'false'}">
|
||||
<div class="method-header">
|
||||
<div>
|
||||
<h3>${escapeHtml(methodName)}</h3>
|
||||
<p class="method-desc">${escapeHtml(description)}</p>
|
||||
</div>
|
||||
<div class="badges">
|
||||
<span class="badge">入口: ${escapeHtml(entryPath)}</span>
|
||||
<span class="badge">鉴权: ${item.isNeedAuth ? '是' : '否'}</span>
|
||||
<span class="badge">登录: ${item.isNeedLogin ? '是' : '否'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<details>
|
||||
<summary>Headers (${headers.length})</summary>
|
||||
<table>
|
||||
<thead><tr><th>名称</th><th>类型</th><th>必填</th><th>说明</th></tr></thead>
|
||||
<tbody>${renderKeyValueRows(headers, {
|
||||
name: 'name',
|
||||
type: 'type',
|
||||
required: 'required',
|
||||
description: 'description',
|
||||
})}</tbody>
|
||||
</table>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Params (${params.length})</summary>
|
||||
<table>
|
||||
<thead><tr><th>名称</th><th>类型</th><th>必填</th><th>说明</th></tr></thead>
|
||||
<tbody>${renderKeyValueRows(params, {
|
||||
name: 'name',
|
||||
type: 'type',
|
||||
required: 'required',
|
||||
description: 'description',
|
||||
})}</tbody>
|
||||
</table>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Response (${response.length})</summary>
|
||||
<table>
|
||||
<thead><tr><th>名称</th><th>类型</th><th>必填</th><th>说明</th></tr></thead>
|
||||
<tbody>${renderKeyValueRows(response, {
|
||||
name: 'name',
|
||||
type: 'type',
|
||||
required: 'required',
|
||||
description: 'description',
|
||||
})}</tbody>
|
||||
</table>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Errors (${errors.length})</summary>
|
||||
<table>
|
||||
<thead><tr><th>名称</th><th>类型</th><th>必填</th><th>说明</th></tr></thead>
|
||||
<tbody>${renderKeyValueRows(errors, {
|
||||
name: 'code',
|
||||
type: 'type',
|
||||
required: 'required',
|
||||
description: 'message',
|
||||
})}</tbody>
|
||||
</table>
|
||||
</details>
|
||||
|
||||
<details class="debug-panel">
|
||||
<summary>在线调试</summary>
|
||||
<div class="debug-form">
|
||||
<label>Query 参数</label>
|
||||
<input class="req-query" type="text" placeholder="${escapeHtml(queryHint)}" />
|
||||
|
||||
<label>Body (JSON)</label>
|
||||
<textarea class="req-body" rows="6" placeholder='{}'></textarea>
|
||||
|
||||
<div class="debug-actions">
|
||||
<button type="button" class="send-btn">发送 POST 请求</button>
|
||||
<span class="muted">${item.isNeedLogin ? '该接口需要登录,未设置 Token 将阻止请求' : '该接口无需登录,可不设置 Token 直接调试'}</span>
|
||||
</div>
|
||||
|
||||
<pre class="req-result muted">点击发送后显示响应</pre>
|
||||
</div>
|
||||
</details>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function renderHtmlPage({
|
||||
docName,
|
||||
docData,
|
||||
groups,
|
||||
docs,
|
||||
entryPath,
|
||||
}) {
|
||||
const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0);
|
||||
const globalHeaders = toArray(docData.headers);
|
||||
const globalHeadersControls = renderGlobalHeadersControls(globalHeaders);
|
||||
const navHtml = docs.map(name => {
|
||||
const activeClass = name === docName ? 'active' : '';
|
||||
return `<a class="tab ${activeClass}" href="/api/docs/${encodeURIComponent(name)}">${escapeHtml(name)}</a>`;
|
||||
}).join('');
|
||||
|
||||
const sidebarHtml = groups.map((group, index) => {
|
||||
const list = toArray(group.list);
|
||||
const groupKey = slugify(group.module || group.groupName || `group-${index}`) || `group-${index}`;
|
||||
const methodsHtml = list.map(item => {
|
||||
const methodName = item.method || item.name || 'unknown';
|
||||
const desc = item.description || '';
|
||||
return `<li class="nav-item" data-method="${escapeHtml(methodName)}" data-desc="${escapeHtml(desc)}">
|
||||
<a href="#${escapeHtml(methodName)}" title="${escapeHtml(desc)}">${escapeHtml(methodName)}</a>
|
||||
</li>`;
|
||||
}).join('');
|
||||
|
||||
return `<details class="nav-group" data-group-key="${escapeHtml(groupKey)}" ${index === 0 ? 'open' : ''}>
|
||||
<summary>${escapeHtml(group.groupName)} <span class="count">${list.length}</span></summary>
|
||||
<ul>${methodsHtml || '<li class="muted">暂无方法</li>'}</ul>
|
||||
</details>`;
|
||||
}).join('');
|
||||
|
||||
const groupHtml = groups.map(group => {
|
||||
const list = toArray(group.list);
|
||||
const groupKey = slugify(group.module || group.groupName) || 'group';
|
||||
const cards = list.map(item => renderMethodCard(item, entryPath, docData.module)).join('');
|
||||
return `<section class="group-block" data-group-key="${escapeHtml(groupKey)}">
|
||||
<h2>${escapeHtml(group.groupName)} <small>${escapeHtml(group.module || '')}</small></h2>
|
||||
${cards || '<p class="muted">该分组暂无方法定义</p>'}
|
||||
</section>`;
|
||||
}).join('');
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>${escapeHtml(docName)} API 文档</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #f4f6fb;
|
||||
--card: #ffffff;
|
||||
--line: #dbe1ee;
|
||||
--text: #1f2a44;
|
||||
--muted: #62708a;
|
||||
--accent: #1565c0;
|
||||
--accent-soft: #e8f1fc;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
color: var(--text);
|
||||
background: radial-gradient(circle at 20% 0%, #e9f2ff 0, var(--bg) 45%), var(--bg);
|
||||
}
|
||||
.container { max-width: 1180px; margin: 0 auto; padding: 24px; }
|
||||
.hero {
|
||||
background: var(--card);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
box-shadow: 0 6px 20px rgba(18, 48, 102, 0.08);
|
||||
}
|
||||
.hero h1 { margin: 0 0 8px; }
|
||||
.meta { color: var(--muted); display: flex; gap: 16px; flex-wrap: wrap; }
|
||||
.tabs { margin-top: 16px; display: flex; gap: 10px; flex-wrap: wrap; }
|
||||
.tab {
|
||||
text-decoration: none;
|
||||
color: var(--accent);
|
||||
border: 1px solid #b9d4f3;
|
||||
background: #f5faff;
|
||||
padding: 7px 12px;
|
||||
border-radius: 999px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.tab.active { background: var(--accent); color: white; border-color: var(--accent); }
|
||||
.global-auth {
|
||||
margin-top: 14px;
|
||||
border: 1px solid #c9dbf3;
|
||||
background: #f6faff;
|
||||
border-radius: 10px;
|
||||
padding: 12px;
|
||||
}
|
||||
.global-auth h3 { margin: 0 0 8px; font-size: 15px; }
|
||||
.global-auth .row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
.global-auth input {
|
||||
flex: 1;
|
||||
min-width: 300px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid #b5ccec;
|
||||
border-radius: 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.global-auth button {
|
||||
border: 1px solid #9fc2eb;
|
||||
background: #fff;
|
||||
color: #174c94;
|
||||
border-radius: 8px;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.global-headers-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
gap: 10px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.global-header-item {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: #21466f;
|
||||
}
|
||||
.global-header-item span {
|
||||
font-weight: 600;
|
||||
}
|
||||
.global-header-item input,
|
||||
.global-header-item select {
|
||||
border: 1px solid #b5ccec;
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
font-size: 13px;
|
||||
background: #fff;
|
||||
color: #1f2a44;
|
||||
}
|
||||
.global-header-item small {
|
||||
line-height: 1.2;
|
||||
}
|
||||
.group-block { margin-top: 18px; }
|
||||
.layout {
|
||||
margin-top: 16px;
|
||||
display: grid;
|
||||
grid-template-columns: 320px 1fr;
|
||||
gap: 16px;
|
||||
align-items: start;
|
||||
}
|
||||
.sidebar {
|
||||
position: sticky;
|
||||
top: 12px;
|
||||
background: var(--card);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
padding: 12px;
|
||||
max-height: calc(100vh - 24px);
|
||||
overflow: auto;
|
||||
box-shadow: 0 6px 20px rgba(18, 48, 102, 0.06);
|
||||
}
|
||||
.search-box {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.search-box input {
|
||||
width: 100%;
|
||||
border: 1px solid #b5ccec;
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.search-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.search-actions button {
|
||||
border: 1px solid #b5ccec;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
color: #174c94;
|
||||
padding: 6px 10px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
.nav-group {
|
||||
border: 1px solid #d7e4f7;
|
||||
border-radius: 8px;
|
||||
background: #fcfdff;
|
||||
padding: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.nav-group summary {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
color: #1a4c8f;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.nav-group .count {
|
||||
background: #e9f2ff;
|
||||
border: 1px solid #c7dbf5;
|
||||
border-radius: 999px;
|
||||
padding: 2px 8px;
|
||||
font-size: 11px;
|
||||
color: #174c94;
|
||||
}
|
||||
.nav-group ul {
|
||||
list-style: none;
|
||||
padding: 8px 0 0;
|
||||
margin: 0;
|
||||
}
|
||||
.nav-item {
|
||||
margin-bottom: 4px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.nav-item a {
|
||||
display: block;
|
||||
color: #32547f;
|
||||
text-decoration: none;
|
||||
font-size: 12px;
|
||||
padding: 6px 8px;
|
||||
border-radius: 6px;
|
||||
word-break: break-all;
|
||||
}
|
||||
.nav-item a:hover {
|
||||
background: #eef5ff;
|
||||
color: #123e79;
|
||||
}
|
||||
.doc-content {
|
||||
min-width: 0;
|
||||
}
|
||||
.group-block h2 { margin: 0 0 12px; }
|
||||
.group-block small { color: var(--muted); font-weight: normal; }
|
||||
.method-card {
|
||||
background: var(--card);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
padding: 16px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.method-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
}
|
||||
.method-header h3 { margin: 0 0 8px; }
|
||||
.method-header p { margin: 0; color: var(--muted); }
|
||||
.badges { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.badge {
|
||||
border-radius: 999px;
|
||||
padding: 5px 10px;
|
||||
background: var(--accent-soft);
|
||||
color: #174c94;
|
||||
font-size: 12px;
|
||||
border: 1px solid #c8def6;
|
||||
white-space: nowrap;
|
||||
}
|
||||
details { margin-top: 12px; }
|
||||
summary { cursor: pointer; color: #103f7a; font-weight: 600; }
|
||||
.debug-panel {
|
||||
border: 1px dashed #c6d9f2;
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
background: #fbfdff;
|
||||
}
|
||||
.debug-form {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.debug-form label {
|
||||
color: #254974;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.debug-form input,
|
||||
.debug-form textarea {
|
||||
width: 100%;
|
||||
border: 1px solid #b5ccec;
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
font-size: 13px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||||
background: #fff;
|
||||
}
|
||||
.debug-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.send-btn {
|
||||
border: 1px solid #0f5cb2;
|
||||
background: #1565c0;
|
||||
color: #fff;
|
||||
border-radius: 8px;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.send-btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.req-result {
|
||||
margin: 0;
|
||||
min-height: 80px;
|
||||
max-height: 260px;
|
||||
overflow: auto;
|
||||
background: #0d1d33;
|
||||
color: #d8e7ff;
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-top: 8px;
|
||||
background: #fff;
|
||||
}
|
||||
th, td {
|
||||
border: 1px solid var(--line);
|
||||
padding: 8px 10px;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
font-size: 13px;
|
||||
}
|
||||
th { background: #f6f9ff; }
|
||||
.muted { color: var(--muted); }
|
||||
@media (max-width: 768px) {
|
||||
.container { padding: 14px; }
|
||||
.method-card { padding: 12px; }
|
||||
.layout { grid-template-columns: 1fr; }
|
||||
.sidebar {
|
||||
position: static;
|
||||
max-height: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="container">
|
||||
<section class="hero">
|
||||
<h1>${escapeHtml(docData.module || docName)} API 文档</h1>
|
||||
<div class="meta">
|
||||
<span>说明: ${escapeHtml(docData.description || '无')}</span>
|
||||
<span>版本: ${escapeHtml(docData.version || 'N/A')}</span>
|
||||
<span>更新: ${escapeHtml(docData.updatedAt || 'N/A')}</span>
|
||||
<span>方法数: ${methodsCount}</span>
|
||||
<span>统一入口: <strong>${escapeHtml(entryPath)}</strong></span>
|
||||
</div>
|
||||
<div class="tabs">
|
||||
${navHtml}
|
||||
<a class="tab" href="/api/docs/${encodeURIComponent(docName)}/raw">查看 JSON</a>
|
||||
</div>
|
||||
<div class="global-auth">
|
||||
<h3>全局 Authorization</h3>
|
||||
<div class="row">
|
||||
<input id="globalAuth" type="text" placeholder="Bearer xxxxx" />
|
||||
<button type="button" id="clearAuthBtn">清空</button>
|
||||
</div>
|
||||
<p class="muted">设置后会自动注入所有“在线调试”请求头,保存在浏览器本地。</p>
|
||||
<h3>全局业务 Header</h3>
|
||||
${globalHeadersControls}
|
||||
<p class="muted">来自 JSON 的 headers 定义;带 * 的字段为必填,支持下拉 list 选择。</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="layout">
|
||||
<aside class="sidebar">
|
||||
<div class="search-box">
|
||||
<input id="methodSearch" type="text" placeholder="快速搜索: 方法名 / 描述" />
|
||||
<div class="search-actions">
|
||||
<button type="button" id="expandAllBtn">展开全部</button>
|
||||
<button type="button" id="collapseAllBtn">折叠全部</button>
|
||||
</div>
|
||||
<p id="searchStats" class="muted">共 ${methodsCount} 个方法</p>
|
||||
</div>
|
||||
${sidebarHtml || '<p class="muted">暂无导航数据</p>'}
|
||||
</aside>
|
||||
|
||||
<section class="doc-content">
|
||||
${groupHtml || '<p class="muted">暂无可展示的方法定义</p>'}
|
||||
</section>
|
||||
</section>
|
||||
</main>
|
||||
<script>
|
||||
(function() {
|
||||
var AUTH_KEY = 'wms_docs_global_auth';
|
||||
var HEADER_STORE_KEY = 'wms_docs_global_headers_' + ${JSON.stringify(docName)};
|
||||
var authInput = document.getElementById('globalAuth');
|
||||
var clearBtn = document.getElementById('clearAuthBtn');
|
||||
var searchInput = document.getElementById('methodSearch');
|
||||
var searchStats = document.getElementById('searchStats');
|
||||
var expandAllBtn = document.getElementById('expandAllBtn');
|
||||
var collapseAllBtn = document.getElementById('collapseAllBtn');
|
||||
|
||||
function nowTimestamp() {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
function formatPretty(text) {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(text), null, 2);
|
||||
} catch (e) {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
function buildDefaultQuery(card) {
|
||||
var moduleName = card.getAttribute('data-module') || '';
|
||||
var methodName = card.getAttribute('data-method') || '';
|
||||
if (moduleName === 'qimen') {
|
||||
return 'app_key=&method=' + encodeURIComponent(methodName)
|
||||
+ '&v=2.0&format=json&sign_method=md5&sign=×tamp=' + nowTimestamp();
|
||||
}
|
||||
return 'method=' + encodeURIComponent(methodName) + '&v=1.0×tamp=' + nowTimestamp();
|
||||
}
|
||||
|
||||
function initDefaultQueries() {
|
||||
var cards = document.querySelectorAll('.method-card');
|
||||
cards.forEach(function(card) {
|
||||
var queryInput = card.querySelector('.req-query');
|
||||
var bodyInput = card.querySelector('.req-body');
|
||||
if (queryInput && !queryInput.value.trim()) {
|
||||
queryInput.value = buildDefaultQuery(card);
|
||||
}
|
||||
if (bodyInput && !bodyInput.value.trim()) {
|
||||
bodyInput.value = '{}';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeText(text) {
|
||||
return String(text || '').toLowerCase();
|
||||
}
|
||||
|
||||
function getGlobalHeaderControls() {
|
||||
return document.querySelectorAll('.global-header-control');
|
||||
}
|
||||
|
||||
function saveGlobalHeaders() {
|
||||
var payload = {};
|
||||
getGlobalHeaderControls().forEach(function(control) {
|
||||
var name = control.getAttribute('data-header-name');
|
||||
if (!name) return;
|
||||
payload[name] = control.value || '';
|
||||
});
|
||||
localStorage.setItem(HEADER_STORE_KEY, JSON.stringify(payload));
|
||||
}
|
||||
|
||||
function loadGlobalHeaders() {
|
||||
var raw = localStorage.getItem(HEADER_STORE_KEY) || '{}';
|
||||
var data = {};
|
||||
try {
|
||||
data = JSON.parse(raw);
|
||||
} catch (e) {
|
||||
data = {};
|
||||
}
|
||||
|
||||
getGlobalHeaderControls().forEach(function(control) {
|
||||
var name = control.getAttribute('data-header-name');
|
||||
if (!name) return;
|
||||
if (Object.prototype.hasOwnProperty.call(data, name)) {
|
||||
control.value = data[name] || '';
|
||||
}
|
||||
control.addEventListener('change', saveGlobalHeaders);
|
||||
control.addEventListener('input', saveGlobalHeaders);
|
||||
});
|
||||
}
|
||||
|
||||
function collectGlobalHeaders() {
|
||||
var headers = {};
|
||||
var missingRequired = [];
|
||||
|
||||
getGlobalHeaderControls().forEach(function(control) {
|
||||
var name = control.getAttribute('data-header-name');
|
||||
var required = control.getAttribute('data-required') === 'true';
|
||||
var value = (control.value || '').trim();
|
||||
if (!name) return;
|
||||
|
||||
if (value) {
|
||||
headers[name] = value;
|
||||
} else if (required) {
|
||||
missingRequired.push(name);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
headers: headers,
|
||||
missingRequired: missingRequired,
|
||||
};
|
||||
}
|
||||
|
||||
function applySearch(keyword) {
|
||||
var key = normalizeText(keyword).trim();
|
||||
var cards = document.querySelectorAll('.method-card');
|
||||
var groups = document.querySelectorAll('.group-block');
|
||||
var navGroups = document.querySelectorAll('.nav-group');
|
||||
var navItems = document.querySelectorAll('.nav-item');
|
||||
var visibleCount = 0;
|
||||
|
||||
cards.forEach(function(card) {
|
||||
var method = normalizeText(card.getAttribute('data-method'));
|
||||
var desc = normalizeText(card.getAttribute('data-desc'));
|
||||
var matched = !key || method.indexOf(key) >= 0 || desc.indexOf(key) >= 0;
|
||||
card.style.display = matched ? '' : 'none';
|
||||
if (matched) {
|
||||
visibleCount += 1;
|
||||
}
|
||||
});
|
||||
|
||||
groups.forEach(function(group) {
|
||||
var visibleCards = group.querySelectorAll('.method-card:not([style*="display: none"])').length;
|
||||
group.style.display = visibleCards > 0 ? '' : 'none';
|
||||
});
|
||||
|
||||
navItems.forEach(function(item) {
|
||||
var method = normalizeText(item.getAttribute('data-method'));
|
||||
var desc = normalizeText(item.getAttribute('data-desc'));
|
||||
var matched = !key || method.indexOf(key) >= 0 || desc.indexOf(key) >= 0;
|
||||
item.style.display = matched ? '' : 'none';
|
||||
});
|
||||
|
||||
navGroups.forEach(function(group) {
|
||||
var visibleItems = group.querySelectorAll('.nav-item:not([style*="display: none"])').length;
|
||||
group.style.display = visibleItems > 0 ? '' : 'none';
|
||||
if (key && visibleItems > 0) {
|
||||
group.open = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (searchStats) {
|
||||
if (key) {
|
||||
searchStats.textContent = '匹配 ' + visibleCount + ' / ${methodsCount} 个方法';
|
||||
} else {
|
||||
searchStats.textContent = '共 ${methodsCount} 个方法';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (authInput) {
|
||||
authInput.value = localStorage.getItem(AUTH_KEY) || '';
|
||||
authInput.addEventListener('input', function() {
|
||||
localStorage.setItem(AUTH_KEY, authInput.value.trim());
|
||||
});
|
||||
}
|
||||
|
||||
if (clearBtn) {
|
||||
clearBtn.addEventListener('click', function() {
|
||||
localStorage.removeItem(AUTH_KEY);
|
||||
if (authInput) {
|
||||
authInput.value = '';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
loadGlobalHeaders();
|
||||
|
||||
if (searchInput) {
|
||||
searchInput.addEventListener('input', function() {
|
||||
applySearch(searchInput.value);
|
||||
});
|
||||
}
|
||||
|
||||
if (expandAllBtn) {
|
||||
expandAllBtn.addEventListener('click', function() {
|
||||
document.querySelectorAll('.nav-group').forEach(function(group) {
|
||||
if (group.style.display !== 'none') {
|
||||
group.open = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (collapseAllBtn) {
|
||||
collapseAllBtn.addEventListener('click', function() {
|
||||
document.querySelectorAll('.nav-group').forEach(function(group) {
|
||||
group.open = false;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('click', async function(event) {
|
||||
var btn = event.target.closest('.send-btn');
|
||||
if (!btn) return;
|
||||
|
||||
var card = btn.closest('.method-card');
|
||||
if (!card) return;
|
||||
|
||||
var queryInput = card.querySelector('.req-query');
|
||||
var bodyInput = card.querySelector('.req-body');
|
||||
var resultEl = card.querySelector('.req-result');
|
||||
var endpoint = card.getAttribute('data-endpoint') || '/system';
|
||||
var loginRequired = card.getAttribute('data-login-required') === 'true';
|
||||
|
||||
var query = (queryInput && queryInput.value.trim()) || '';
|
||||
var url = query ? (endpoint + '?' + query) : endpoint;
|
||||
var auth = (authInput && authInput.value.trim()) || localStorage.getItem(AUTH_KEY) || '';
|
||||
var rawBody = (bodyInput && bodyInput.value.trim()) || '{}';
|
||||
var globalHeaderData = collectGlobalHeaders();
|
||||
|
||||
var headers = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
Object.assign(headers, globalHeaderData.headers);
|
||||
if (auth) {
|
||||
headers.Authorization = auth;
|
||||
}
|
||||
|
||||
if (globalHeaderData.missingRequired.length) {
|
||||
if (resultEl) {
|
||||
resultEl.textContent = '请求已阻止: 全局 Header 缺少必填项 -> ' + globalHeaderData.missingRequired.join(', ');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var effectiveAuth = headers.Authorization || '';
|
||||
|
||||
if (loginRequired && !effectiveAuth) {
|
||||
if (resultEl) {
|
||||
resultEl.textContent = '请求已阻止: 当前接口 isNeedLogin=true,请先在页面顶部设置全局 Authorization。';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
btn.disabled = true;
|
||||
if (resultEl) {
|
||||
resultEl.textContent = '请求中...';
|
||||
}
|
||||
|
||||
try {
|
||||
var response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
body: rawBody,
|
||||
});
|
||||
var text = await response.text();
|
||||
var pretty = formatPretty(text);
|
||||
if (resultEl) {
|
||||
resultEl.textContent = 'HTTP ' + response.status + '\\n\\n' + pretty;
|
||||
}
|
||||
} catch (error) {
|
||||
if (resultEl) {
|
||||
resultEl.textContent = '请求失败: ' + error.message;
|
||||
}
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
initDefaultQueries();
|
||||
applySearch('');
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
class DocsController extends Controller {
|
||||
async list() {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const docs = await this.getDocNames();
|
||||
if (!docs.length) {
|
||||
ctx.status = 404;
|
||||
ctx.body = {
|
||||
code: 404,
|
||||
message: 'methods 目录下没有可用的 JSON 文档',
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const fallback = docs.includes('system') ? 'system' : docs[0];
|
||||
await this.renderDoc(fallback);
|
||||
} catch (error) {
|
||||
ctx.status = 500;
|
||||
ctx.body = {
|
||||
code: 500,
|
||||
message: '读取文档失败',
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async api() {
|
||||
await this.list();
|
||||
}
|
||||
|
||||
async detail() {
|
||||
const { ctx } = this;
|
||||
const docName = ctx.params.docName;
|
||||
await this.renderDoc(docName);
|
||||
}
|
||||
|
||||
async raw() {
|
||||
const { ctx } = this;
|
||||
const docName = ctx.params.docName;
|
||||
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(docName || '')) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '无效文档名' };
|
||||
return;
|
||||
}
|
||||
|
||||
const filePath = path.join(this.app.baseDir, 'methods', `${docName}.json`);
|
||||
|
||||
try {
|
||||
const content = await fs.readFile(filePath, 'utf8');
|
||||
ctx.type = 'application/json; charset=utf-8';
|
||||
ctx.body = content;
|
||||
} catch (error) {
|
||||
ctx.status = 404;
|
||||
ctx.body = {
|
||||
code: 404,
|
||||
message: `未找到文档: ${docName}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async getDocNames() {
|
||||
const docsDir = path.join(this.app.baseDir, 'methods');
|
||||
const entries = await fs.readdir(docsDir, { withFileTypes: true });
|
||||
|
||||
return entries
|
||||
.filter(entry => entry.isFile() && entry.name.endsWith('.json'))
|
||||
.map(entry => entry.name.replace(/\.json$/i, ''))
|
||||
.sort();
|
||||
}
|
||||
|
||||
async renderDoc(docName) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(docName || '')) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: '无效文档名' };
|
||||
return;
|
||||
}
|
||||
|
||||
const filePath = path.join(app.baseDir, 'methods', `${docName}.json`);
|
||||
|
||||
try {
|
||||
const [ content, docs ] = await Promise.all([
|
||||
fs.readFile(filePath, 'utf8'),
|
||||
this.getDocNames(),
|
||||
]);
|
||||
|
||||
const docData = JSON.parse(content);
|
||||
const groups = normalizeGroups(docData);
|
||||
const entryPath = docData.module === 'qimen' ? '/qimen' : '/system';
|
||||
const html = renderHtmlPage({
|
||||
docName,
|
||||
docData,
|
||||
groups,
|
||||
docs,
|
||||
entryPath,
|
||||
});
|
||||
|
||||
ctx.type = 'text/html; charset=utf-8';
|
||||
ctx.body = html;
|
||||
} catch (error) {
|
||||
ctx.status = 404;
|
||||
ctx.body = {
|
||||
code: 404,
|
||||
message: `未找到文档或 JSON 格式错误: ${docName}`,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DocsController;
|
||||
@ -119,6 +119,11 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: 'ERP审核时间',
|
||||
},
|
||||
delivery_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '发货时间',
|
||||
},
|
||||
shop_nick: {
|
||||
type: STRING(200),
|
||||
allowNull: true,
|
||||
|
||||
@ -294,6 +294,7 @@ module.exports = app => {
|
||||
\`service_code\` varchar(50) DEFAULT NULL COMMENT '集包服务编码',
|
||||
\`operator_name\` varchar(50) DEFAULT NULL COMMENT 'ERP审核人',
|
||||
\`operate_time\` datetime DEFAULT NULL COMMENT 'ERP审核时间',
|
||||
\`delivery_time\` datetime DEFAULT NULL COMMENT '发货时间',
|
||||
\`shop_nick\` varchar(200) DEFAULT NULL COMMENT '店铺名称',
|
||||
\`seller_nick\` varchar(200) DEFAULT NULL COMMENT '卖家名称',
|
||||
\`buyer_nick\` varchar(200) DEFAULT NULL COMMENT '买家名称',
|
||||
|
||||
@ -10,6 +10,9 @@ module.exports = app => {
|
||||
router.post('/api/v1', controller.home.v1);
|
||||
router.post('/system', controller.home.system);
|
||||
router.post('/api/v2', controller.apiV2.index);
|
||||
router.get('/api/docs', controller.docs.list);
|
||||
router.get('/api/docs/:docName', controller.docs.detail);
|
||||
router.get('/api/docs/:docName/raw', controller.docs.raw);
|
||||
router.get('/template/xml/:id', controller.template.xml);
|
||||
router.get('/auth/printSetting/:code', controller.auth.printerSetting);
|
||||
router.get('/testSendData', controller.home.testSendData);
|
||||
|
||||
351
app/service/systemMethods/order.js
Normal file
351
app/service/systemMethods/order.js
Normal file
@ -0,0 +1,351 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
class orderService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,detail,listItems,stats,updateStatus,updateDeliveryTime';
|
||||
const _noNeedLog = 'list,detail,listItems,stats';
|
||||
const _noNeedAuth = 'list,detail,listItems,stats,updateStatus,updateDeliveryTime';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
getWarehouseId(data = {}) {
|
||||
const fromParam = Number(data.warehouse_id || data.warehouseId || 0);
|
||||
const fromUser = Number(this.ctx.user?.store_id || 0);
|
||||
return fromParam || fromUser;
|
||||
}
|
||||
|
||||
async getOrderModels(warehouseId) {
|
||||
const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
const OrderItemsModel = await this.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||||
return { DeliveryModel, OrderItemsModel };
|
||||
}
|
||||
|
||||
applyDateRange(where, field, start, end) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const range = {};
|
||||
|
||||
if (start) {
|
||||
range[Op.gte] = this.normalizeDate(start, false);
|
||||
}
|
||||
if (end) {
|
||||
range[Op.lte] = this.normalizeDate(end, true);
|
||||
}
|
||||
|
||||
if (Object.keys(range).length > 0) {
|
||||
where[field] = range;
|
||||
}
|
||||
}
|
||||
|
||||
buildWhere(whereData = {}, warehouseId) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
const where = { warehouse_id: warehouseId };
|
||||
|
||||
const eqFields = [
|
||||
'id',
|
||||
'store_id',
|
||||
'status',
|
||||
'post_status',
|
||||
'storage_status',
|
||||
'pick_status',
|
||||
'pack_status',
|
||||
'inspection_status',
|
||||
'print_status',
|
||||
'claim_status',
|
||||
'outbound_status',
|
||||
'lock_status',
|
||||
'intercept_status',
|
||||
'source_platform_code',
|
||||
'logistics_code',
|
||||
'warehouse_code',
|
||||
'order_type',
|
||||
];
|
||||
|
||||
for (const key of eqFields) {
|
||||
if (whereData[key] !== undefined && whereData[key] !== null && whereData[key] !== '') {
|
||||
where[key] = whereData[key];
|
||||
}
|
||||
}
|
||||
|
||||
if (whereData.delivery_order_code) {
|
||||
where.delivery_order_code = { [Op.like]: `%${whereData.delivery_order_code}%` };
|
||||
}
|
||||
|
||||
if (Array.isArray(whereData.delivery_order_codes) && whereData.delivery_order_codes.length > 0) {
|
||||
where.delivery_order_code = { [Op.in]: whereData.delivery_order_codes };
|
||||
}
|
||||
|
||||
if (whereData.logistics_name) {
|
||||
where.logistics_name = { [Op.like]: `%${whereData.logistics_name}%` };
|
||||
}
|
||||
|
||||
if (whereData.buyer_nick) {
|
||||
where.buyer_nick = { [Op.like]: `%${whereData.buyer_nick}%` };
|
||||
}
|
||||
|
||||
if (whereData.mobile) {
|
||||
where.mobile = { [Op.like]: `%${whereData.mobile}%` };
|
||||
}
|
||||
|
||||
this.applyDateRange(where, 'create_at', whereData.create_at_start, whereData.create_at_end);
|
||||
this.applyDateRange(where, 'place_order_time', whereData.place_order_time_start, whereData.place_order_time_end);
|
||||
this.applyDateRange(where, 'pay_time', whereData.pay_time_start, whereData.pay_time_end);
|
||||
this.applyDateRange(where, 'delivery_time', whereData.delivery_time_start, whereData.delivery_time_end);
|
||||
|
||||
return where;
|
||||
}
|
||||
|
||||
parseDateTime(value, fieldName) {
|
||||
if (!value) return null;
|
||||
const d = value instanceof Date ? value : new Date(value);
|
||||
if (Number.isNaN(d.getTime())) {
|
||||
throw new Error(`${fieldName} 格式错误`);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
async list(data = {}) {
|
||||
try {
|
||||
const warehouseId = this.getWarehouseId(data);
|
||||
if (!warehouseId) {
|
||||
return this.fail('warehouse_id 不能为空', { code: 400 });
|
||||
}
|
||||
|
||||
const { DeliveryModel } = await this.getOrderModels(warehouseId);
|
||||
const where = this.buildWhere(data.where || {}, warehouseId);
|
||||
|
||||
const page = Math.max(Number(data.pagination?.page || 1), 1);
|
||||
const pageSize = Math.min(Math.max(Number(data.pagination?.pageSize || 20), 1), 200);
|
||||
const offset = (page - 1) * pageSize;
|
||||
|
||||
const result = await DeliveryModel.findAndCountAll({
|
||||
where,
|
||||
offset,
|
||||
limit: pageSize,
|
||||
order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
data: {
|
||||
list: result.rows,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total: result.count,
|
||||
totalPages: Math.ceil(result.count / pageSize),
|
||||
hasNext: page * pageSize < result.count,
|
||||
hasPrevious: page > 1,
|
||||
},
|
||||
},
|
||||
code: 200,
|
||||
});
|
||||
} catch (error) {
|
||||
return this.fail(error.message, { code: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async detail(data = {}) {
|
||||
try {
|
||||
const warehouseId = this.getWarehouseId(data);
|
||||
if (!warehouseId) {
|
||||
return this.fail('warehouse_id 不能为空', { code: 400 });
|
||||
}
|
||||
|
||||
const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId);
|
||||
const where = { warehouse_id: warehouseId };
|
||||
|
||||
if (data.id) {
|
||||
where.id = data.id;
|
||||
} else if (data.delivery_order_code) {
|
||||
where.delivery_order_code = data.delivery_order_code;
|
||||
} else {
|
||||
return this.fail('id 或 delivery_order_code 必填', { code: 400 });
|
||||
}
|
||||
|
||||
const order = await DeliveryModel.findOne({ where, raw: true });
|
||||
if (!order) {
|
||||
return this.fail('订单不存在', { code: 404 });
|
||||
}
|
||||
|
||||
const items = await OrderItemsModel.findAll({
|
||||
where: { order_id: order.id },
|
||||
order: [ [ 'id', 'ASC' ] ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
data: {
|
||||
order,
|
||||
items,
|
||||
},
|
||||
code: 200,
|
||||
});
|
||||
} catch (error) {
|
||||
return this.fail(error.message, { code: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async listItems(data = {}) {
|
||||
try {
|
||||
const warehouseId = this.getWarehouseId(data);
|
||||
if (!warehouseId) {
|
||||
return this.fail('warehouse_id 不能为空', { code: 400 });
|
||||
}
|
||||
|
||||
const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId);
|
||||
const where = { warehouse_id: warehouseId };
|
||||
|
||||
if (data.order_id) {
|
||||
where.id = data.order_id;
|
||||
} else if (data.delivery_order_code) {
|
||||
where.delivery_order_code = data.delivery_order_code;
|
||||
} else {
|
||||
return this.fail('order_id 或 delivery_order_code 必填', { code: 400 });
|
||||
}
|
||||
|
||||
const order = await DeliveryModel.findOne({ where, attributes: [ 'id', 'delivery_order_code' ], raw: true });
|
||||
if (!order) {
|
||||
return this.fail('订单不存在', { code: 404 });
|
||||
}
|
||||
|
||||
const items = await OrderItemsModel.findAll({
|
||||
where: { order_id: order.id },
|
||||
order: [ [ 'id', 'ASC' ] ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
data: {
|
||||
order,
|
||||
items,
|
||||
},
|
||||
code: 200,
|
||||
});
|
||||
} catch (error) {
|
||||
return this.fail(error.message, { code: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async stats(data = {}) {
|
||||
try {
|
||||
const warehouseId = this.getWarehouseId(data);
|
||||
if (!warehouseId) {
|
||||
return this.fail('warehouse_id 不能为空', { code: 400 });
|
||||
}
|
||||
|
||||
const { Sequelize } = this.app;
|
||||
const { DeliveryModel } = await this.getOrderModels(warehouseId);
|
||||
const where = this.buildWhere(data.where || {}, warehouseId);
|
||||
|
||||
const total = await DeliveryModel.count({ where });
|
||||
const byStatusRows = await DeliveryModel.findAll({
|
||||
where,
|
||||
attributes: [ 'status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ],
|
||||
group: [ 'status' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const byOutboundRows = await DeliveryModel.findAll({
|
||||
where,
|
||||
attributes: [ 'outbound_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ],
|
||||
group: [ 'outbound_status' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
data: {
|
||||
total,
|
||||
byStatus: byStatusRows,
|
||||
byOutboundStatus: byOutboundRows,
|
||||
},
|
||||
code: 200,
|
||||
});
|
||||
} catch (error) {
|
||||
return this.fail(error.message, { code: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async updateStatus(data = {}) {
|
||||
try {
|
||||
const warehouseId = this.getWarehouseId(data);
|
||||
if (!warehouseId) {
|
||||
return this.fail('warehouse_id 不能为空', { code: 400 });
|
||||
}
|
||||
|
||||
const { DeliveryModel } = await this.getOrderModels(warehouseId);
|
||||
const where = { warehouse_id: warehouseId };
|
||||
|
||||
if (data.id) {
|
||||
where.id = data.id;
|
||||
} else if (data.delivery_order_code) {
|
||||
where.delivery_order_code = data.delivery_order_code;
|
||||
} else {
|
||||
return this.fail('id 或 delivery_order_code 必填', { code: 400 });
|
||||
}
|
||||
|
||||
const allowedFields = [
|
||||
'status',
|
||||
'post_status',
|
||||
'storage_status',
|
||||
'pick_status',
|
||||
'pack_status',
|
||||
'inspection_status',
|
||||
'print_status',
|
||||
'claim_status',
|
||||
'outbound_status',
|
||||
'lock_status',
|
||||
'intercept_status',
|
||||
];
|
||||
|
||||
const updateData = {};
|
||||
for (const key of allowedFields) {
|
||||
if (data[key] !== undefined && data[key] !== null && data[key] !== '') {
|
||||
updateData[key] = data[key];
|
||||
}
|
||||
}
|
||||
|
||||
if (data.delivery_time) {
|
||||
updateData.delivery_time = this.parseDateTime(data.delivery_time, 'delivery_time');
|
||||
}
|
||||
|
||||
if (!updateData.delivery_time && updateData.outbound_status === 'fin') {
|
||||
updateData.delivery_time = new Date();
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length === 0) {
|
||||
return this.fail('没有可更新字段', { code: 400 });
|
||||
}
|
||||
|
||||
updateData.updated_at = new Date();
|
||||
|
||||
const [ affected ] = await DeliveryModel.update(updateData, { where });
|
||||
if (!affected) {
|
||||
return this.fail('订单不存在或未更新', { code: 404 });
|
||||
}
|
||||
|
||||
const order = await DeliveryModel.findOne({ where, raw: true });
|
||||
return this.success('更新成功', { data: order, code: 200 });
|
||||
} catch (error) {
|
||||
return this.fail(error.message, { code: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async updateDeliveryTime(data = {}) {
|
||||
if (!data.delivery_time) {
|
||||
return this.fail('delivery_time 必填', { code: 400 });
|
||||
}
|
||||
|
||||
const nextData = { ...data };
|
||||
if (nextData.syncOutboundStatus === true || nextData.syncOutboundStatus === 1 || nextData.syncOutboundStatus === '1') {
|
||||
nextData.outbound_status = 'fin';
|
||||
}
|
||||
|
||||
return await this.updateStatus(nextData);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = orderService;
|
||||
@ -0,0 +1,63 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const [ tables ] = await queryInterface.sequelize.query(`
|
||||
SELECT TABLE_NAME
|
||||
FROM INFORMATION_SCHEMA.TABLES
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND (TABLE_NAME = 'wms_order_delivery' OR TABLE_NAME LIKE 'wms_order_delivery\\_%')
|
||||
`);
|
||||
|
||||
for (const row of tables) {
|
||||
const tableName = row.TABLE_NAME;
|
||||
|
||||
const [ columns ] = await queryInterface.sequelize.query(
|
||||
`
|
||||
SELECT COLUMN_NAME
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = :tableName
|
||||
AND COLUMN_NAME = 'delivery_time'
|
||||
`,
|
||||
{ replacements: { tableName } }
|
||||
);
|
||||
|
||||
if (columns.length === 0) {
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${tableName}\` ADD COLUMN \`delivery_time\` datetime NULL DEFAULT NULL COMMENT '发货时间' AFTER \`operate_time\``
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const [ tables ] = await queryInterface.sequelize.query(`
|
||||
SELECT TABLE_NAME
|
||||
FROM INFORMATION_SCHEMA.TABLES
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND (TABLE_NAME = 'wms_order_delivery' OR TABLE_NAME LIKE 'wms_order_delivery\\_%')
|
||||
`);
|
||||
|
||||
for (const row of tables) {
|
||||
const tableName = row.TABLE_NAME;
|
||||
|
||||
const [ columns ] = await queryInterface.sequelize.query(
|
||||
`
|
||||
SELECT COLUMN_NAME
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = :tableName
|
||||
AND COLUMN_NAME = 'delivery_time'
|
||||
`,
|
||||
{ replacements: { tableName } }
|
||||
);
|
||||
|
||||
if (columns.length > 0) {
|
||||
await queryInterface.sequelize.query(
|
||||
`ALTER TABLE \`${tableName}\` DROP COLUMN \`delivery_time\``
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
7
methods/qimen.json
Normal file
7
methods/qimen.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"module": "qimen",
|
||||
"description": "Qimen API method catalog",
|
||||
"version": "0.1.0",
|
||||
"updatedAt": "2026-03-22",
|
||||
"endpoints": []
|
||||
}
|
||||
2896
methods/system.json
Normal file
2896
methods/system.json
Normal file
File diff suppressed because it is too large
Load Diff
104
script/db-query.ps1
Normal file
104
script/db-query.ps1
Normal file
@ -0,0 +1,104 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true, Position = 0)]
|
||||
[string]$Query,
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$DbClient = "wms",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$ConfigPath = ".\\config\\config.local.js",
|
||||
|
||||
[switch]$AsTable
|
||||
)
|
||||
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$projectRoot = Split-Path -Parent $scriptRoot
|
||||
$configFullPath = Join-Path $projectRoot $ConfigPath
|
||||
$configResolved = Resolve-Path -Path $configFullPath -ErrorAction Stop
|
||||
|
||||
$nodeScript = @'
|
||||
const path = require("path");
|
||||
const { createRequire } = require("module");
|
||||
|
||||
(async () => {
|
||||
const projectRoot = process.argv[2];
|
||||
const configPath = process.argv[3];
|
||||
const clientName = process.argv[4];
|
||||
const query = process.argv[5];
|
||||
|
||||
const projectRequire = createRequire(path.join(projectRoot, "package.json"));
|
||||
const mysql = projectRequire("mysql2/promise");
|
||||
|
||||
if (!query) {
|
||||
throw new Error("Query is required.");
|
||||
}
|
||||
|
||||
const configFactory = require(path.resolve(configPath));
|
||||
const config = typeof configFactory === "function"
|
||||
? configFactory({ name: "wms-debug" })
|
||||
: configFactory;
|
||||
|
||||
const client = config
|
||||
&& config.mysql
|
||||
&& config.mysql.clients
|
||||
&& config.mysql.clients[clientName];
|
||||
|
||||
if (!client) {
|
||||
throw new Error(`MySQL client "${clientName}" not found in config.mysql.clients.`);
|
||||
}
|
||||
|
||||
const connection = await mysql.createConnection({
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
charset: client.charset || "utf8mb4",
|
||||
});
|
||||
|
||||
try {
|
||||
const [rows] = await connection.query(query);
|
||||
process.stdout.write(JSON.stringify({
|
||||
client: clientName,
|
||||
rowCount: Array.isArray(rows) ? rows.length : 0,
|
||||
rows,
|
||||
}));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
})().catch((err) => {
|
||||
process.stderr.write(err && err.stack ? err.stack : String(err));
|
||||
process.exit(1);
|
||||
});
|
||||
'@
|
||||
|
||||
$tempFile = New-TemporaryFile
|
||||
$tempNodeFile = [System.IO.Path]::ChangeExtension($tempFile.FullName, ".cjs")
|
||||
Move-Item -Path $tempFile.FullName -Destination $tempNodeFile -Force
|
||||
Set-Content -Path $tempNodeFile -Value $nodeScript -Encoding UTF8
|
||||
|
||||
try {
|
||||
$json = & node $tempNodeFile $projectRoot $configResolved.Path $DbClient $Query
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Node query runner exited with code $LASTEXITCODE."
|
||||
}
|
||||
} finally {
|
||||
Remove-Item -Path $tempNodeFile -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
$result = $json | ConvertFrom-Json
|
||||
Write-Host "Client: $($result.client)"
|
||||
Write-Host "Rows: $($result.rowCount)"
|
||||
|
||||
if ($AsTable) {
|
||||
if (($result.rows -is [System.Array]) -and $result.rows.Count -gt 0) {
|
||||
$result.rows | Format-Table -AutoSize
|
||||
} else {
|
||||
Write-Host "No tabular rows to render."
|
||||
}
|
||||
} else {
|
||||
$result | ConvertTo-Json -Depth 50
|
||||
}
|
||||
171
script/tmp-compare-order-schema.cjs
Normal file
171
script/tmp-compare-order-schema.cjs
Normal file
@ -0,0 +1,171 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { createRequire } = require('module');
|
||||
|
||||
function extractTopLevelFieldsFromObjectBody(body) {
|
||||
const fields = [];
|
||||
let i = 0;
|
||||
let depth = 0;
|
||||
while (i < body.length) {
|
||||
const ch = body[i];
|
||||
if (ch === '{') {
|
||||
depth++;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === '}') {
|
||||
depth--;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (depth === 0) {
|
||||
const m = body.slice(i).match(/^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*\{/);
|
||||
if (m) {
|
||||
const key = m[1];
|
||||
fields.push(key);
|
||||
i += m[0].length;
|
||||
let inner = 1;
|
||||
while (i < body.length && inner > 0) {
|
||||
const c = body[i++];
|
||||
if (c === '{') inner++;
|
||||
if (c === '}') inner--;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return [...new Set(fields)];
|
||||
}
|
||||
|
||||
function getObjectBodyByMarker(text, marker) {
|
||||
const start = text.indexOf(marker);
|
||||
if (start < 0) return null;
|
||||
const braceStart = text.indexOf('{', start + marker.length);
|
||||
if (braceStart < 0) return null;
|
||||
let i = braceStart + 1;
|
||||
let depth = 1;
|
||||
let body = '';
|
||||
while (i < text.length && depth > 0) {
|
||||
const ch = text[i++];
|
||||
if (ch === '{') depth++;
|
||||
if (ch === '}') depth--;
|
||||
if (depth > 0) body += ch;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
function extractDefineFields(text) {
|
||||
const definePos = text.indexOf('define(');
|
||||
if (definePos < 0) return [];
|
||||
const firstBrace = text.indexOf('{', definePos);
|
||||
if (firstBrace < 0) return [];
|
||||
let i = firstBrace + 1;
|
||||
let depth = 1;
|
||||
let body = '';
|
||||
while (i < text.length && depth > 0) {
|
||||
const ch = text[i++];
|
||||
if (ch === '{') depth++;
|
||||
if (ch === '}') depth--;
|
||||
if (depth > 0) body += ch;
|
||||
}
|
||||
return extractTopLevelFieldsFromObjectBody(body);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const root = process.cwd();
|
||||
const projectRequire = createRequire(path.join(root, 'package.json'));
|
||||
const mysql = projectRequire('mysql2/promise');
|
||||
const cfgFactory = require(path.join(root, 'config', 'config.local.js'));
|
||||
const cfg = typeof cfgFactory === 'function' ? cfgFactory({ name: 'wms-debug' }) : cfgFactory;
|
||||
const client = cfg?.mysql?.clients?.wms;
|
||||
if (!client) throw new Error('mysql client wms not found');
|
||||
|
||||
const conn = await mysql.createConnection({
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
charset: client.charset || 'utf8mb4',
|
||||
});
|
||||
|
||||
const [tableRows] = await conn.query(
|
||||
"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND (TABLE_NAME IN ('wms_order_delivery','wms_order_items','wms_entry_order') OR TABLE_NAME LIKE 'wms_order_delivery_%' OR TABLE_NAME LIKE 'wms_order_items_%') ORDER BY TABLE_NAME"
|
||||
);
|
||||
|
||||
const tableSchemas = {};
|
||||
for (const t of tableRows.map(x => x.TABLE_NAME)) {
|
||||
const [cols] = await conn.query(
|
||||
"SELECT COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA,COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION",
|
||||
[t]
|
||||
);
|
||||
tableSchemas[t] = cols;
|
||||
}
|
||||
|
||||
const targets = [
|
||||
{ table: 'wms_order_delivery', modelFile: 'app/model/order_delivery.js', type: 'baseModel' },
|
||||
{ table: 'wms_order_items', modelFile: 'app/model/order_items.js', type: 'define' },
|
||||
{ table: 'wms_entry_order', modelFile: 'app/model/entry_order.js', type: 'define' },
|
||||
];
|
||||
|
||||
const compareWithModel = targets.map(t => {
|
||||
const txt = fs.readFileSync(path.join(root, t.modelFile), 'utf8');
|
||||
let modelFields = [];
|
||||
if (t.type === 'baseModel') {
|
||||
const body = getObjectBodyByMarker(txt, 'const baseModel =');
|
||||
modelFields = body ? extractTopLevelFieldsFromObjectBody(body) : [];
|
||||
} else {
|
||||
modelFields = extractDefineFields(txt);
|
||||
}
|
||||
|
||||
const dbColumns = (tableSchemas[t.table] || []).map(c => c.COLUMN_NAME);
|
||||
const modelOnly = modelFields.filter(f => !dbColumns.includes(f));
|
||||
const dbOnly = dbColumns.filter(c => !modelFields.includes(c));
|
||||
|
||||
return {
|
||||
table: t.table,
|
||||
modelFile: t.modelFile,
|
||||
modelFieldCount: modelFields.length,
|
||||
dbFieldCount: dbColumns.length,
|
||||
modelOnly,
|
||||
dbOnly,
|
||||
allMatched: modelOnly.length === 0 && dbOnly.length === 0,
|
||||
};
|
||||
});
|
||||
|
||||
const dynamicTableCheck = [];
|
||||
const dynamicTables = Object.keys(tableSchemas).filter(t => t.endsWith('_100000'));
|
||||
for (const dt of dynamicTables) {
|
||||
const baseTable = dt.startsWith('wms_order_delivery_') ? 'wms_order_delivery' : dt.startsWith('wms_order_items_') ? 'wms_order_items' : null;
|
||||
if (!baseTable) continue;
|
||||
const baseCols = (tableSchemas[baseTable] || []).map(c => c.COLUMN_NAME);
|
||||
const dynCols = (tableSchemas[dt] || []).map(c => c.COLUMN_NAME);
|
||||
dynamicTableCheck.push({
|
||||
table: dt,
|
||||
baseTable,
|
||||
missingFromDynamic: baseCols.filter(c => !dynCols.includes(c)),
|
||||
extraInDynamic: dynCols.filter(c => !baseCols.includes(c)),
|
||||
allMatched: baseCols.length === dynCols.length && baseCols.every(c => dynCols.includes(c)),
|
||||
});
|
||||
}
|
||||
|
||||
const out = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
dbName: client.database,
|
||||
tables: tableRows.map(x => x.TABLE_NAME),
|
||||
compareWithModel,
|
||||
dynamicTableCheck,
|
||||
schema: tableSchemas,
|
||||
};
|
||||
|
||||
fs.writeFileSync(path.join(root, 'tmp-order-schema-compare.json'), JSON.stringify(out, null, 2));
|
||||
await conn.end();
|
||||
console.log('WROTE tmp-order-schema-compare.json');
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error(err && err.stack ? err.stack : String(err));
|
||||
process.exit(1);
|
||||
});
|
||||
97
script/tmp-gen-service-method-inventory.cjs
Normal file
97
script/tmp-gen-service-method-inventory.cjs
Normal file
@ -0,0 +1,97 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const root = process.cwd();
|
||||
const serviceRoot = path.join(root, 'app', 'service');
|
||||
|
||||
function walk(dir) {
|
||||
const out = [];
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
const full = path.join(dir, name);
|
||||
const st = fs.statSync(full);
|
||||
if (st.isDirectory()) out.push(...walk(full));
|
||||
else if (name.endsWith('.js')) out.push(full);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractClassMethods(content) {
|
||||
const methods = [];
|
||||
const classIdx = content.indexOf('class ');
|
||||
if (classIdx < 0) return methods;
|
||||
const braceStart = content.indexOf('{', classIdx);
|
||||
if (braceStart < 0) return methods;
|
||||
|
||||
let i = braceStart + 1;
|
||||
let depth = 1;
|
||||
let body = '';
|
||||
while (i < content.length && depth > 0) {
|
||||
const ch = content[i++];
|
||||
if (ch === '{') depth++;
|
||||
if (ch === '}') depth--;
|
||||
if (depth > 0) body += ch;
|
||||
}
|
||||
|
||||
let p = 0;
|
||||
let nested = 0;
|
||||
while (p < body.length) {
|
||||
const ch = body[p];
|
||||
if (ch === '{') { nested++; p++; continue; }
|
||||
if (ch === '}') { nested--; p++; continue; }
|
||||
|
||||
if (nested === 0) {
|
||||
const slice = body.slice(p);
|
||||
const m = slice.match(/^\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*\(/);
|
||||
if (m) {
|
||||
const name = m[1];
|
||||
if (name !== 'constructor') methods.push(name);
|
||||
|
||||
// move to method body end
|
||||
p += m[0].length;
|
||||
while (p < body.length && body[p] !== '{') p++;
|
||||
if (body[p] === '{') {
|
||||
p++;
|
||||
let inMethod = 1;
|
||||
while (p < body.length && inMethod > 0) {
|
||||
if (body[p] === '{') inMethod++;
|
||||
else if (body[p] === '}') inMethod--;
|
||||
p++;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
p++;
|
||||
}
|
||||
|
||||
return [...new Set(methods)];
|
||||
}
|
||||
|
||||
const files = walk(serviceRoot)
|
||||
.map(full => path.relative(root, full).replace(/\\/g, '/'))
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
|
||||
const inventory = [];
|
||||
for (const rel of files) {
|
||||
const full = path.join(root, rel);
|
||||
const content = fs.readFileSync(full, 'utf8');
|
||||
const methods = extractClassMethods(content);
|
||||
inventory.push({ file: rel, methodCount: methods.length, methods });
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
let md = '';
|
||||
md += `自动生成时间: ${now}\n\n`;
|
||||
md += `扫描范围: app/service/**/*.js\n`;
|
||||
md += `文件数: ${inventory.length}\n\n`;
|
||||
for (const item of inventory) {
|
||||
md += `- ${item.file} (${item.methodCount})\n`;
|
||||
if (item.methods.length === 0) {
|
||||
md += ` - <no-class-method-found>\n`;
|
||||
} else {
|
||||
md += ` - ${item.methods.join(', ')}\n`;
|
||||
}
|
||||
}
|
||||
|
||||
fs.writeFileSync(path.join(root, 'tmp-service-method-inventory.md'), md, 'utf8');
|
||||
console.log('WROTE tmp-service-method-inventory.md');
|
||||
421
script/tmp-struct-system-params.cjs
Normal file
421
script/tmp-struct-system-params.cjs
Normal file
@ -0,0 +1,421 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const acorn = require('acorn');
|
||||
|
||||
const baseDir = process.cwd();
|
||||
const methodsDir = path.join(baseDir, 'app', 'service', 'systemMethods');
|
||||
const jsonPath = path.join(baseDir, 'methods', 'system.json');
|
||||
|
||||
function walk(node, visitor, parent = null) {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
visitor(node, parent);
|
||||
for (const key of Object.keys(node)) {
|
||||
const value = node[key];
|
||||
if (!value) continue;
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) walk(item, visitor, node);
|
||||
} else if (typeof value === 'object' && value.type) {
|
||||
walk(value, visitor, node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function walkFiles(dir) {
|
||||
const files = [];
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkFiles(full));
|
||||
if (entry.isFile() && entry.name.endsWith('.js')) files.push(full);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
function getPropName(node) {
|
||||
if (!node) return null;
|
||||
if (node.type === 'Identifier') return node.name;
|
||||
if (node.type === 'Literal') return String(node.value);
|
||||
return null;
|
||||
}
|
||||
|
||||
function memberPath(node) {
|
||||
if (!node) return null;
|
||||
if (node.type === 'ChainExpression') return memberPath(node.expression);
|
||||
if (node.type === 'Identifier') return node.name;
|
||||
if (node.type === 'ThisExpression') return 'this';
|
||||
if (node.type !== 'MemberExpression') return null;
|
||||
const left = memberPath(node.object);
|
||||
if (!left) return null;
|
||||
if (node.computed) {
|
||||
if (node.property.type === 'Literal') return `${left}.${String(node.property.value)}`;
|
||||
if (node.property.type === 'Identifier') return left;
|
||||
return left;
|
||||
}
|
||||
const right = getPropName(node.property);
|
||||
return right ? `${left}.${right}` : left;
|
||||
}
|
||||
|
||||
function classifySourceByExpr(expr, signatureSet) {
|
||||
const sources = new Set();
|
||||
const visit = node => {
|
||||
if (!node) return;
|
||||
if (node.type === 'Identifier' && signatureSet.has(node.name)) {
|
||||
sources.add('body');
|
||||
return;
|
||||
}
|
||||
if (node.type === 'MemberExpression' || node.type === 'ChainExpression') {
|
||||
const p = memberPath(node);
|
||||
if (p && p.startsWith('ctx.request.body')) sources.add('body');
|
||||
else if (p && p.startsWith('ctx.query')) sources.add('query');
|
||||
else if (p && p.startsWith('ctx.params')) sources.add('path');
|
||||
else if (p && p.startsWith('ctx.headers')) sources.add('header');
|
||||
return;
|
||||
}
|
||||
if (node.type === 'LogicalExpression' || node.type === 'BinaryExpression') {
|
||||
visit(node.left);
|
||||
visit(node.right);
|
||||
return;
|
||||
}
|
||||
if (node.type === 'ConditionalExpression') {
|
||||
visit(node.consequent);
|
||||
visit(node.alternate);
|
||||
return;
|
||||
}
|
||||
};
|
||||
visit(expr);
|
||||
if (!sources.size) return null;
|
||||
return Array.from(sources).sort().join('|');
|
||||
}
|
||||
|
||||
function inferTypeByName(name) {
|
||||
if (!name) return 'string';
|
||||
if (/ids$/i.test(name)) return 'array';
|
||||
if (/^(where|pagination|item|template|data|filters?)$/i.test(name)) return 'object';
|
||||
if (/^(is_|has_|need|sync)/i.test(name)) return 'boolean';
|
||||
if (/(^id$|_id$|^page$|^pageSize$|^limit$|^offset$|^count$|_count$|^x$|^y$|^z$|^rows$|^columns$|^levels$|^width$|^height$|^length$)/i.test(name)) return 'number';
|
||||
if (/(^date$|_date$|^time$|_time$|timestamp)/i.test(name)) return 'string';
|
||||
return 'string';
|
||||
}
|
||||
|
||||
function inferTypeByNode(node, fallbackName = '') {
|
||||
if (!node) return inferTypeByName(fallbackName);
|
||||
if (node.type === 'Literal') {
|
||||
if (typeof node.value === 'number') return 'number';
|
||||
if (typeof node.value === 'boolean') return 'boolean';
|
||||
return 'string';
|
||||
}
|
||||
if (node.type === 'ObjectExpression') return 'object';
|
||||
if (node.type === 'ArrayExpression') return 'array';
|
||||
return inferTypeByName(fallbackName);
|
||||
}
|
||||
|
||||
function mapValidateType(v) {
|
||||
if (!v) return 'string';
|
||||
const t = String(v).toLowerCase();
|
||||
if (t === 'int' || t === 'integer' || t === 'number') return 'number';
|
||||
if (t === 'boolean' || t === 'bool') return 'boolean';
|
||||
if (t === 'array') return 'array';
|
||||
if (t === 'object') return 'object';
|
||||
return 'string';
|
||||
}
|
||||
|
||||
function extractNoNeedLists(classNode) {
|
||||
const result = { noNeedLogin: [], noNeedAuth: ['*'] };
|
||||
const ctor = classNode.body.body.find(m => m.type === 'MethodDefinition' && m.kind === 'constructor');
|
||||
if (!ctor) return result;
|
||||
|
||||
for (const stmt of ctor.value.body.body || []) {
|
||||
if (stmt.type !== 'VariableDeclaration') continue;
|
||||
for (const decl of stmt.declarations || []) {
|
||||
if (decl.id.type !== 'Identifier' || !decl.init || decl.init.type !== 'Literal') continue;
|
||||
const name = decl.id.name;
|
||||
const value = String(decl.init.value || '');
|
||||
if (name === '_noNeedLogin') result.noNeedLogin = value.split(',').map(s => s.trim()).filter(Boolean);
|
||||
if (name === '_noNeedAuth') result.noNeedAuth = value.split(',').map(s => s.trim()).filter(Boolean);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function collectMethodParams(methodNode) {
|
||||
const signatureNames = [];
|
||||
for (const p of methodNode.value.params || []) {
|
||||
if (p.type === 'Identifier') signatureNames.push(p.name);
|
||||
else if (p.type === 'AssignmentPattern' && p.left.type === 'Identifier') signatureNames.push(p.left.name);
|
||||
}
|
||||
const signatureSet = new Set(signatureNames);
|
||||
const aliasMap = new Map();
|
||||
const entries = new Map();
|
||||
const listFields = [];
|
||||
|
||||
function resolveName(localName) {
|
||||
return aliasMap.get(localName) || localName;
|
||||
}
|
||||
|
||||
function ensure(name) {
|
||||
if (!entries.has(name)) {
|
||||
entries.set(name, {
|
||||
name,
|
||||
type: inferTypeByName(name),
|
||||
required: false,
|
||||
source: new Set(),
|
||||
});
|
||||
}
|
||||
return entries.get(name);
|
||||
}
|
||||
|
||||
function addParam(name, patch = {}) {
|
||||
if (!name) return;
|
||||
if ([ 'ctx', 'service', 'app', 'result', 'error', 'e' ].includes(name)) return;
|
||||
const item = ensure(name);
|
||||
if (patch.type) item.type = patch.type;
|
||||
if (patch.required === true) item.required = true;
|
||||
if (patch.source) item.source.add(patch.source);
|
||||
}
|
||||
|
||||
function addRequiredFromTest(testNode) {
|
||||
if (!testNode) return;
|
||||
if (testNode.type === 'UnaryExpression' && testNode.operator === '!') {
|
||||
if (testNode.argument.type === 'Identifier') {
|
||||
const local = testNode.argument.name;
|
||||
const resolved = resolveName(local);
|
||||
if (resolved !== local || entries.has(resolved)) {
|
||||
addParam(resolved, { required: true });
|
||||
}
|
||||
}
|
||||
if (testNode.argument.type === 'MemberExpression' || testNode.argument.type === 'ChainExpression') {
|
||||
const p = memberPath(testNode.argument);
|
||||
if (!p) return;
|
||||
const parts = p.split('.');
|
||||
if (parts.length === 2 && signatureSet.has(parts[0])) {
|
||||
addParam(parts[1], { required: true, source: 'body' });
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (testNode.type === 'LogicalExpression') {
|
||||
addRequiredFromTest(testNode.left);
|
||||
addRequiredFromTest(testNode.right);
|
||||
return;
|
||||
}
|
||||
if (testNode.type === 'CallExpression') {
|
||||
const callee = memberPath(testNode.callee);
|
||||
if (callee === 'Array.isArray' && testNode.arguments[0] && testNode.arguments[0].type === 'Identifier') {
|
||||
const local = testNode.arguments[0].name;
|
||||
const resolved = resolveName(local);
|
||||
if (resolved !== local || entries.has(resolved)) {
|
||||
addParam(resolved, { required: true, type: 'array' });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
walk(methodNode.value.body, (node, parent) => {
|
||||
if (node.type === 'VariableDeclarator') {
|
||||
if (node.id.type === 'ObjectPattern' && node.init) {
|
||||
const source = classifySourceByExpr(node.init, signatureSet);
|
||||
if (!source) return;
|
||||
for (const prop of node.id.properties || []) {
|
||||
if (prop.type !== 'Property') continue;
|
||||
const keyName = getPropName(prop.key);
|
||||
if (!keyName) continue;
|
||||
|
||||
let localName = keyName;
|
||||
let type = inferTypeByName(keyName);
|
||||
|
||||
if (prop.value.type === 'Identifier') {
|
||||
localName = prop.value.name;
|
||||
} else if (prop.value.type === 'AssignmentPattern') {
|
||||
if (prop.value.left.type === 'Identifier') localName = prop.value.left.name;
|
||||
type = inferTypeByNode(prop.value.right, keyName);
|
||||
}
|
||||
|
||||
aliasMap.set(localName, keyName);
|
||||
addParam(keyName, { source, type });
|
||||
}
|
||||
}
|
||||
|
||||
if (node.id.type === 'Identifier' && node.init) {
|
||||
const local = node.id.name;
|
||||
|
||||
if (node.init.type === 'MemberExpression' || node.init.type === 'ChainExpression') {
|
||||
const p = memberPath(node.init);
|
||||
if (p) {
|
||||
const parts = p.split('.');
|
||||
if (parts.length === 2 && signatureSet.has(parts[0])) {
|
||||
aliasMap.set(local, parts[1]);
|
||||
addParam(parts[1], { source: 'body' });
|
||||
}
|
||||
if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'query') {
|
||||
aliasMap.set(local, parts[2]);
|
||||
addParam(parts[2], { source: 'query' });
|
||||
}
|
||||
if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'params') {
|
||||
aliasMap.set(local, parts[2]);
|
||||
addParam(parts[2], { source: 'path' });
|
||||
}
|
||||
if (parts.length >= 4 && parts[0] === 'ctx' && parts[1] === 'request' && parts[2] === 'body') {
|
||||
aliasMap.set(local, parts[3]);
|
||||
addParam(parts[3], { source: 'body' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((/allowedFields|eqFields/i).test(local) && node.init.type === 'ArrayExpression') {
|
||||
const arr = [];
|
||||
for (const el of node.init.elements || []) {
|
||||
if (el && el.type === 'Literal' && typeof el.value === 'string') arr.push(el.value);
|
||||
}
|
||||
if (arr.length) listFields.push(...arr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (node.type === 'IfStatement') {
|
||||
addRequiredFromTest(node.test);
|
||||
}
|
||||
|
||||
if (node.type === 'CallExpression') {
|
||||
const callee = memberPath(node.callee);
|
||||
|
||||
if (callee === 'ctx.validate' && node.arguments[0] && node.arguments[0].type === 'ObjectExpression') {
|
||||
for (const p of node.arguments[0].properties || []) {
|
||||
if (p.type !== 'Property') continue;
|
||||
const field = getPropName(p.key);
|
||||
if (!field || p.value.type !== 'ObjectExpression') continue;
|
||||
let required = false;
|
||||
let type = null;
|
||||
for (const conf of p.value.properties || []) {
|
||||
if (conf.type !== 'Property') continue;
|
||||
const confKey = getPropName(conf.key);
|
||||
if (!confKey) continue;
|
||||
if (confKey === 'required' && conf.value.type === 'Literal') {
|
||||
required = Boolean(conf.value.value);
|
||||
}
|
||||
if (confKey === 'type' && conf.value.type === 'Literal') {
|
||||
type = mapValidateType(conf.value.value);
|
||||
}
|
||||
}
|
||||
addParam(field, { required, type: type || inferTypeByName(field), source: 'body' });
|
||||
}
|
||||
}
|
||||
|
||||
if (callee === 'Array.isArray' && node.arguments[0] && node.arguments[0].type === 'Identifier') {
|
||||
const local = node.arguments[0].name;
|
||||
const resolved = resolveName(local);
|
||||
if (resolved !== local || entries.has(resolved)) {
|
||||
addParam(resolved, { type: 'array' });
|
||||
}
|
||||
}
|
||||
|
||||
if ((callee === 'parseInt' || callee === 'Number') && node.arguments[0]) {
|
||||
const arg = node.arguments[0];
|
||||
if (arg.type === 'Identifier') {
|
||||
const resolved = resolveName(arg.name);
|
||||
if (resolved !== arg.name || entries.has(resolved)) {
|
||||
addParam(resolved, { type: 'number' });
|
||||
}
|
||||
}
|
||||
if (arg.type === 'MemberExpression' || arg.type === 'ChainExpression') {
|
||||
const p = memberPath(arg);
|
||||
if (p) {
|
||||
const parts = p.split('.');
|
||||
if (parts.length === 2 && signatureSet.has(parts[0])) addParam(parts[1], { type: 'number', source: 'body' });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (node.type === 'MemberExpression' || node.type === 'ChainExpression') {
|
||||
const p = memberPath(node);
|
||||
if (!p) return;
|
||||
const parts = p.split('.');
|
||||
if (parts.length === 2 && signatureSet.has(parts[0])) {
|
||||
addParam(parts[1], { source: 'body' });
|
||||
}
|
||||
if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'query') {
|
||||
addParam(parts[2], { source: 'query' });
|
||||
}
|
||||
if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'params') {
|
||||
addParam(parts[2], { source: 'path' });
|
||||
}
|
||||
if (parts.length >= 4 && parts[0] === 'ctx' && parts[1] === 'request' && parts[2] === 'body') {
|
||||
addParam(parts[3], { source: 'body' });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
for (const f of listFields) {
|
||||
addParam(f, { source: 'body' });
|
||||
}
|
||||
|
||||
const result = Array.from(entries.values()).map(item => ({
|
||||
name: item.name,
|
||||
type: item.type,
|
||||
required: item.required,
|
||||
source: item.source.size ? Array.from(item.source).sort().join('|') : 'body',
|
||||
description: `${item.name} 参数`,
|
||||
}));
|
||||
|
||||
result.sort((a, b) => {
|
||||
if (a.required !== b.required) return a.required ? -1 : 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function buildMethodParamMap() {
|
||||
const map = new Map();
|
||||
const files = walkFiles(methodsDir);
|
||||
|
||||
for (const file of files) {
|
||||
const source = fs.readFileSync(file, 'utf8');
|
||||
const ast = acorn.parse(source, { ecmaVersion: 'latest', sourceType: 'script' });
|
||||
const relative = path.relative(methodsDir, file).replace(/\\/g, '/').replace(/\.js$/, '');
|
||||
const moduleName = relative.replace(/\//g, '.');
|
||||
|
||||
for (const node of ast.body) {
|
||||
if (node.type !== 'ClassDeclaration') continue;
|
||||
const noNeed = extractNoNeedLists(node);
|
||||
for (const method of node.body.body) {
|
||||
if (method.type !== 'MethodDefinition') continue;
|
||||
if (method.kind !== 'method') continue;
|
||||
if (!method.value.async) continue;
|
||||
const methodName = method.key && method.key.name;
|
||||
if (!methodName) continue;
|
||||
|
||||
const fullMethod = `${moduleName}.${methodName}`;
|
||||
const params = collectMethodParams(method);
|
||||
|
||||
for (const p of params) {
|
||||
if (noNeed.noNeedLogin.includes('*') || noNeed.noNeedLogin.includes(methodName)) {
|
||||
if (p.name.toLowerCase().includes('authorization') || p.source === 'header') p.required = false;
|
||||
}
|
||||
}
|
||||
|
||||
map.set(fullMethod, params);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
const methodParamMap = buildMethodParamMap();
|
||||
const doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
|
||||
|
||||
let updated = 0;
|
||||
for (const group of doc.methods.groups || []) {
|
||||
for (const item of group.list || []) {
|
||||
const next = methodParamMap.get(item.method) || [];
|
||||
item.params = next;
|
||||
updated++;
|
||||
}
|
||||
}
|
||||
|
||||
doc.version = '0.3.0';
|
||||
doc.updatedAt = '2026-03-22';
|
||||
|
||||
fs.writeFileSync(jsonPath, JSON.stringify(doc, null, 2) + '\n', 'utf8');
|
||||
console.log(`updated methods: ${updated}`);
|
||||
console.log(`mapped methods: ${methodParamMap.size}`);
|
||||
30
script/tmp-update-ai-method-routing.cjs
Normal file
30
script/tmp-update-ai-method-routing.cjs
Normal file
@ -0,0 +1,30 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const root = process.cwd();
|
||||
const target = path.join(root, 'AI_METHOD_ROUTING.md');
|
||||
const inventoryPath = path.join(root, 'tmp-service-method-inventory.md');
|
||||
|
||||
const base = fs.readFileSync(target, 'utf8');
|
||||
const inventory = fs.readFileSync(inventoryPath, 'utf8').trim();
|
||||
|
||||
const section = `\n\n## 6. 全量 Service Method 能力清单(自动扫描)\n\n维护说明:\n- 扫描范围:app/service/**/*.js\n- 本节内容由脚本生成,新增/修改 service 后请同步刷新。\n- 刷新命令:node .\\script\\tmp-gen-service-method-inventory.cjs\n\n<!-- SERVICE_METHOD_INVENTORY:BEGIN -->\n${inventory}\n<!-- SERVICE_METHOD_INVENTORY:END -->\n`;
|
||||
|
||||
const begin = '<!-- SERVICE_METHOD_INVENTORY:BEGIN -->';
|
||||
const end = '<!-- SERVICE_METHOD_INVENTORY:END -->';
|
||||
|
||||
let next;
|
||||
if (base.includes(begin) && base.includes(end)) {
|
||||
const start = base.indexOf(begin);
|
||||
const finish = base.indexOf(end) + end.length;
|
||||
const head = base.slice(0, base.lastIndexOf('\n## 6. 全量 Service Method 能力清单(自动扫描)', start) >= 0
|
||||
? base.lastIndexOf('\n## 6. 全量 Service Method 能力清单(自动扫描)', start)
|
||||
: start);
|
||||
const tail = base.slice(finish);
|
||||
next = head.trimEnd() + section + tail;
|
||||
} else {
|
||||
next = base.trimEnd() + section;
|
||||
}
|
||||
|
||||
fs.writeFileSync(target, next + '\n', 'utf8');
|
||||
console.log('UPDATED AI_METHOD_ROUTING.md');
|
||||
1610
tmp-order-schema-compare.json
Normal file
1610
tmp-order-schema-compare.json
Normal file
File diff suppressed because it is too large
Load Diff
81
tmp-order-schema-workflow.md
Normal file
81
tmp-order-schema-workflow.md
Normal file
@ -0,0 +1,81 @@
|
||||
# 订单表结构与 Model 比对临时工作流
|
||||
|
||||
更新时间: 2026-03-22
|
||||
|
||||
## 1. 目标
|
||||
|
||||
用于后续排查订单相关问题时,快速复用以下能力:
|
||||
- 获取数据库订单表结构
|
||||
- 与当前 Model 做字段级比对
|
||||
- 识别主表/分仓动态表的结构漂移
|
||||
|
||||
## 2. 本次已确认的订单相关表
|
||||
|
||||
- wms_entry_order
|
||||
- wms_order_delivery
|
||||
- wms_order_delivery_100000
|
||||
- wms_order_items
|
||||
- wms_order_items_100000
|
||||
|
||||
## 3. 相关 Model
|
||||
|
||||
- app/model/entry_order.js
|
||||
- app/model/order_delivery.js
|
||||
- app/model/order_items.js
|
||||
- app/model/order_delivery_factory.js
|
||||
- app/model/order_items_factory.js
|
||||
|
||||
## 4. 已生成产物
|
||||
|
||||
- 结构与差异总结果: tmp-order-schema-compare.json
|
||||
- 比对脚本(可复跑): script/tmp-compare-order-schema.cjs
|
||||
|
||||
## 5. 关键比对结论
|
||||
|
||||
### 5.1 wms_entry_order vs entry_order model
|
||||
- 字段数: model 28 / db 28
|
||||
- 结论: 完全一致
|
||||
|
||||
### 5.2 wms_order_delivery vs order_delivery model
|
||||
- 字段数: model 72 / db 54
|
||||
- model 有但主表 db 没有的字段:
|
||||
from_key, items, items_count, items_total, items_weight, items_hash, items_crc, wave_id,
|
||||
post_status, storage_status, pick_status, pack_status, inspection_status, print_status,
|
||||
claim_status, outbound_status, lock_status, intercept_status
|
||||
- 结论: 主表结构落后于模型定义
|
||||
|
||||
补充:
|
||||
- delivery_time(发货时间) 已在主表与动态表补齐,并同步到 model 与动态建表 SQL。
|
||||
|
||||
### 5.3 wms_order_items vs order_items model
|
||||
- 字段数: model 18 / db 15
|
||||
- model 有但主表 db 没有的字段:
|
||||
stock_id, created_at, updated_at
|
||||
- 结论: 主表结构落后于模型定义
|
||||
|
||||
### 5.4 动态表 vs 主表
|
||||
- wms_order_delivery_100000 相比 wms_order_delivery 多出 18 个字段(与 modelOnly 一致)
|
||||
- wms_order_items_100000 相比 wms_order_items 多出 3 个字段(与 modelOnly 一致)
|
||||
- 结论: 动态表更接近当前模型,主表较旧
|
||||
|
||||
## 6. 复用命令
|
||||
|
||||
### 6.1 一键重跑比对
|
||||
PowerShell:
|
||||
|
||||
node .\script\tmp-compare-order-schema.cjs
|
||||
|
||||
### 6.2 快速查看结果摘要
|
||||
PowerShell:
|
||||
|
||||
Get-Content .\tmp-order-schema-compare.json -TotalCount 160
|
||||
|
||||
## 7. 后续建议
|
||||
|
||||
1. 若以主表为准,需回退 model 字段定义到主表现状,避免 ORM 读写异常。
|
||||
2. 若以模型为准,补充 migration,将主表补齐到动态表同等结构。
|
||||
3. 在服务中明确当前读写表策略(主表或动态表),避免混用导致字段可用性不一致。
|
||||
|
||||
## 8. 备注
|
||||
|
||||
本文件为临时工作流文件,可在结构收敛后删除或迁移到正式文档。
|
||||
105
tmp-service-method-inventory.md
Normal file
105
tmp-service-method-inventory.md
Normal file
@ -0,0 +1,105 @@
|
||||
自动生成时间: 2026-03-22T06:43:50.263Z
|
||||
|
||||
扫描范围: app/service/**/*.js
|
||||
文件数: 50
|
||||
|
||||
- app/service/api.js (1)
|
||||
- callMethod
|
||||
- app/service/apiMethods/test.js (4)
|
||||
- entryorderConfirm, playbackRequest, fibonacci, fibonacciRecursive
|
||||
- app/service/dispatcher.js (3)
|
||||
- buildMap, getMethodMap, invoke
|
||||
- app/service/main.js (11)
|
||||
- success, fail, normalizeDate, setInfo, getInfo, findQimenAppWithContract, queryFromDatabase, checkAuth, checkApiPermission, setUserContext, systemInit
|
||||
- app/service/pda.js (3)
|
||||
- callMethod, validateParams, saveLog
|
||||
- app/service/qimen.js (12)
|
||||
- validateApi, getErpName, parseXmlToArray, cleanXmlString, callMethod, formatResponse, xmlResponse, buildXmlNode, escapeXml, saveQimenLog, saveQimenLogResult, saveQimenLogBody
|
||||
- app/service/qimenMethods/deliveryorder.js (3)
|
||||
- query, create, batchcreate
|
||||
- app/service/qimenMethods/entryorder.js (2)
|
||||
- create, query
|
||||
- app/service/qimenMethods/inventory.js (1)
|
||||
- query
|
||||
- app/service/qimenMethods/order.js (2)
|
||||
- cancel, pending
|
||||
- app/service/qimenMethods/returnorder.js (2)
|
||||
- create, query
|
||||
- app/service/qimenMethods/singleitem.js (2)
|
||||
- synchronize, query
|
||||
- app/service/qimenMethods/stockout.js (2)
|
||||
- create, query
|
||||
- app/service/qimenMethods/taobao/qimen/service.js (1)
|
||||
- heartbeat
|
||||
- app/service/system.js (3)
|
||||
- callMethod, validateParams, saveLog
|
||||
- app/service/systemMethods/config.js (1)
|
||||
- list
|
||||
- app/service/systemMethods/dashboard.js (6)
|
||||
- storeStats, warehouseStats, hot_order_rank, express_ratio, platform_distribution, order_trend
|
||||
- app/service/systemMethods/index.js (13)
|
||||
- fastWhereTree, loadStores, getCOSUploadConfig, getImages, uploadSuccessNotify, ReferenceFile, getMessageDetail, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, getExpressList
|
||||
- app/service/systemMethods/order.js (11)
|
||||
- getWarehouseId, getOrderModels, applyDateRange, buildWhere, parseDateTime, list, detail, listItems, stats, updateStatus, updateDeliveryTime
|
||||
- app/service/systemMethods/print.js (3)
|
||||
- send, sendToComputer, log
|
||||
- app/service/systemMethods/printer/station.js (1)
|
||||
- list
|
||||
- app/service/systemMethods/setting/printTemplate.js (3)
|
||||
- list, save, listTemplatesByType
|
||||
- app/service/systemMethods/stock.js (21)
|
||||
- stockWarehouse, getProhibitedType, getInfo, saveWarehouseStock, createWarehouseStock, getBarcodes, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, checkItemCodeUnique, queryStockLogs, handleBatchDelete, deleteUnit, deleteProhibited, handleBatchChange, getStockUnits, getUnitList, createProhibited, createUnit, search
|
||||
- app/service/systemMethods/storage/receiving.js (13)
|
||||
- getReceivingList, getReceivingDetail, batchCancelReceiving, create, addItem, removeItem, saveReceiving, get, addDetail, deleteDetail, detailChange, cancel, completeReceiving
|
||||
- app/service/systemMethods/store.js (6)
|
||||
- createStore, createWarehouse, joinStore, joinWarehouse, getStoreRoles, auditApply
|
||||
- app/service/systemMethods/user.js (5)
|
||||
- login, logout, info, changeRole, register
|
||||
- app/service/systemMethods/warehouse.js (20)
|
||||
- getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, createRack, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo
|
||||
- app/service/systems/account_platform.js (8)
|
||||
- switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext
|
||||
- app/service/systems/auth/user.js (21)
|
||||
- login, ID, changeRole, info, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register
|
||||
- app/service/systems/delivery_order.js (7)
|
||||
- addOrder, generateItemsHash, calculateCRC32, prepareOrderData, addOrderLines, safeParseFloat, addOrderToQueue
|
||||
- app/service/systems/entry_order.js (9)
|
||||
- addOrder, getLineCount, received, success, fail, tryCreateEntryOrder, addItems, qimenEntryorderConfirm, entryorderConfirm
|
||||
- app/service/systems/fast_where.js (13)
|
||||
- buildTree, getTreeByType, buildSubTree, getWithChildrenByType, getAllChildren, getByType, getGroups, getChildrenByPid, getTreeChildrenByPid, create, update, findById, delete
|
||||
- app/service/systems/file.js (2)
|
||||
- getImages, ReferenceFile
|
||||
- app/service/systems/location_space.js (16)
|
||||
- create, batchCreate, list, detail, update, delete, toggleStatus, updateStatus, findAvailableSpaces, findByCode, findByBarcode, getWarehouseStats, getZoneStats, validateAllocation, validateTransferOut, _validateReferences
|
||||
- app/service/systems/location_zone.js (22)
|
||||
- getWarehouseLevelZones, getZoneTreeByWarehouse, getChildrenByZoneId, isLeafNode, createZone, validateBasicFields, validateByZoneType, validateParentElement, validateZoneOverlap, isOverlap, generateZoneCodeByType, getDefaultColorByType, getZoneTypeText, updateZone, deleteZone, checkZoneOverlap, getZoneDetail, toggleZoneActive, getZonePath, generateSpacesForRack, getSpaceInfo, checkBarcodeUnique
|
||||
- app/service/systems/location.js (10)
|
||||
- createRackWithSpaces, _generateSpacesForRack, _calculateAreaRackOrder, _calculatePickPathForWarehouse, _updateSpacePickSequence, _calculatePickPriority, updateRackPosition, getPickPath, updateNeighborRelations, _findNeighborRacks
|
||||
- app/service/systems/notification.js (1)
|
||||
- send
|
||||
- app/service/systems/operation_log.js (4)
|
||||
- createOperationLog, queryStockLogs, queryOrderLogs, getMessageDetail
|
||||
- app/service/systems/platform.js (6)
|
||||
- checkPlatformExists, getPlatformInfo, clearPlatformCache, getPlatformSettingDetail, batchCheckPlatforms, createPlatformSetting
|
||||
- app/service/systems/polo_api.js (6)
|
||||
- getJsonDatas, getJsonData, getSignText, md5Encrypt, _formatDate, _formatPickupDate
|
||||
- app/service/systems/print/index.js (2)
|
||||
- sendToComputer, test
|
||||
- app/service/systems/qimen_query.js (6)
|
||||
- send, replaceXmlTagsWithString, addSign, getQueryParams, generateUrlWithParams, sendRequest
|
||||
- app/service/systems/setting/print_template.js (14)
|
||||
- listTemplatesByType, getTree, getTemplatesByType, save, getBusinessTypesAndItem, getGroupedPrintItems, getTableConfigs, clearBusinessTypesCache, getXmlByTemplate, buildXmlFromElements, renderElement, computeItemStyle, computeTableItemStyle, renderTable
|
||||
- app/service/systems/sign.js (10)
|
||||
- Constants, toXml, signTopRequest, verifyTopRequest, verifyAndExtractParams, generateSignedParams, encryptHMAC, encryptHMACSHA256, encryptMD5, byte2hex
|
||||
- app/service/systems/space.js (1)
|
||||
- searchSpace
|
||||
- app/service/systems/stock_store.js (34)
|
||||
- create, initQimenStockData, convertToQimenFormat, getItemInfoWithCache, getItemStorages, _calculateCacheTTL, clearItemStorageCache, lockItemStorages, ID, inbound, outbound, checkAndCreateWarehouseStock, getWarehouseStock, buildSequelizeCondition, processConditionValue, formatDate, isEmptyValue, getProhibitedType, getBarcodes, handleBatchChange, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, getInfo, saveWarehouseStock, createWarehouseStock, validateSaveParams, stockLog, checkItemCodeUnique, handleBatchDelete, deleteUnit, deleteProhibited, search
|
||||
- app/service/systems/storage/index.js (1)
|
||||
- index
|
||||
- app/service/systems/storage/receiving.js (16)
|
||||
- getReceivingList, getReceivingDetail, batchCancelReceiving, isEmptyValue, buildSequelizeCondition, processConditionValue, create, get, addDetail, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, completeReceiving
|
||||
- app/service/systems/store.js (13)
|
||||
- getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores
|
||||
- app/service/systems/upload.js (14)
|
||||
- initCOS, getUploadParams, hash_hmac, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback
|
||||
Loading…
x
Reference in New Issue
Block a user