From 969c68f5f97e56ec5ff773a15036a97bdac616c6 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 2 Nov 2026 18:02:34 +0800 Subject: [PATCH] =?UTF-8?q?feat(external-print):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=A4=96=E9=83=A8=E6=89=93=E5=8D=95=E5=B9=B3=E5=8F=B0=E4=B8=8E?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E7=AE=A1=E7=90=86=EF=BC=88=E6=8E=A5=E5=85=A5?= =?UTF-8?q?=E5=BA=97=E7=AE=A1=E5=AE=B6=E7=99=BB=E5=BD=95=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 external_print_platforms(平台基础资料,开发者维护)与 external_print_accounts(账号/密码/cookie/token/登录状态) - 新增平台账号 CRUD、登录态检查、登录接口;店铺管理下新增「外部打单平台」菜单 - 平台服务按 code 独立存放于 app/lib/printPlatform(dgj.js 实现店管家登录与 GetUserInfo 登录态检查) - 平台接口 401 自动记录账号登录状态,前端展示状态并支持检查/登录 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- backend/app/contract/index.js | 68 +++ .../app/controller/externalPrintAccount.js | 353 ++++++++++++++++ .../app/controller/externalPrintPlatform.js | 34 ++ backend/app/lib/printPlatform/base.js | 164 ++++++++ backend/app/lib/printPlatform/dgj.js | 392 ++++++++++++++++++ backend/app/lib/printPlatform/index.js | 96 +++++ backend/app/model/externalPrintAccount.js | 32 ++ backend/app/model/externalPrintPlatform.js | 30 ++ backend/app/router.js | 6 + ...2000000-create-external-print-platforms.js | 124 ++++++ ...00100-seed-external-print-platform-menu.js | 64 +++ ...0-add-cookie-to-external-print-accounts.js | 22 + ...00-add-token-to-external-print-accounts.js | 22 + ...login-status-to-external-print-accounts.js | 23 + frontend/src/api/externalPrintAccount.ts | 76 ++++ frontend/src/api/externalPrintPlatform.ts | 20 + frontend/src/store/menu.ts | 1 + .../src/views/ExternalPrintPlatform/Index.vue | 351 ++++++++++++++++ 18 files changed, 1878 insertions(+) create mode 100644 backend/app/controller/externalPrintAccount.js create mode 100644 backend/app/controller/externalPrintPlatform.js create mode 100644 backend/app/lib/printPlatform/base.js create mode 100644 backend/app/lib/printPlatform/dgj.js create mode 100644 backend/app/lib/printPlatform/index.js create mode 100644 backend/app/model/externalPrintAccount.js create mode 100644 backend/app/model/externalPrintPlatform.js create mode 100644 backend/database/migrations/20261102000000-create-external-print-platforms.js create mode 100644 backend/database/migrations/20261102000100-seed-external-print-platform-menu.js create mode 100644 backend/database/migrations/20261102000200-add-cookie-to-external-print-accounts.js create mode 100644 backend/database/migrations/20261102000300-add-token-to-external-print-accounts.js create mode 100644 backend/database/migrations/20261102000400-add-login-status-to-external-print-accounts.js create mode 100644 frontend/src/api/externalPrintAccount.ts create mode 100644 frontend/src/api/externalPrintPlatform.ts create mode 100644 frontend/src/views/ExternalPrintPlatform/Index.vue diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index 6f37275..f4c91a2 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -1003,6 +1003,74 @@ module.exports = { remark: { type: 'string', description: '备注' }, }, + // ---------- 外部打单平台 external_print_platforms ---------- + externalPrintPlatformItem: { + id: { type: 'integer', description: '主键' }, + code: { type: 'string', description: '平台标识,程序按此选择打单/取号适配逻辑' }, + name: { type: 'string', description: '平台名称' }, + url: { type: 'string', description: '平台链接地址' }, + fetch_waybill_no: { type: 'integer', description: '是否回打单平台取号:1是 0否' }, + sort: { type: 'integer', description: '排序,越小越靠前' }, + status: { type: 'integer', description: '状态:1启用 0禁用' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + externalPrintPlatformListResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'array', itemType: 'externalPrintPlatformItem', description: '外部打单平台列表(开发者维护,前端只读)' }, + }, + + // ---------- 外部打单账号 external_print_accounts ---------- + externalPrintAccountItem: { + id: { type: 'integer', description: '主键' }, + principal_id: { type: 'integer', description: '所属主体ID' }, + platform_id: { type: 'integer', description: '所属外部打单平台ID' }, + account: { type: 'string', description: '外部打单平台登录账号' }, + has_password: { type: 'boolean', description: '是否已设置密码(密码本身不回显)' }, + has_cookie: { type: 'boolean', description: '是否已保存会话 cookie(cookie 本身不回显)' }, + has_token: { type: 'boolean', description: '是否已保存登录 token(token 本身不回显)' }, + login_status: { type: 'integer', description: '登录状态:1已登录 0未登录/已失效(最近一次平台交互结果)' }, + platform: { type: 'externalPrintPlatformItem', description: '所属外部打单平台' }, + created_at: { type: 'string', description: '创建时间' }, + updated_at: { type: 'string', description: '更新时间' }, + }, + externalPrintAccountPage: buildPage('externalPrintAccountItem', '外部打单账号列表'), + externalPrintAccountListResponse: buildListResponse('externalPrintAccountPage'), + createExternalPrintAccountRequest: { + principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, + platform_id: { type: 'integer', required: true, description: '外部打单平台ID' }, + account: { type: 'string', required: true, description: '外部打单平台登录账号' }, + password: { type: 'string', required: true, description: '外部打单平台登录密码(明文,HTTPS 传输)' }, + }, + updateExternalPrintAccountRequest: { + platform_id: { type: 'integer', description: '外部打单平台ID' }, + account: { type: 'string', description: '外部打单平台登录账号' }, + password: { type: 'string', description: '外部打单平台登录密码,留空表示不修改' }, + }, + externalPrintAccountCheckResult: { + logged_in: { type: 'boolean', description: '是否仍处于登录态' }, + message: { type: 'string', description: '检查结果说明' }, + url: { type: 'string', description: '检查时访问的接口地址' }, + nickname: { type: 'string', description: '平台账号昵称(登录态有效时返回)' }, + shop_name: { type: 'string', description: '平台当前店铺名称(登录态有效时返回)' }, + }, + externalPrintAccountCheckResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'externalPrintAccountCheckResult', description: '登录态检查结果' }, + }, + externalPrintAccountLoginResult: { + logged_in: { type: 'boolean', description: '是否已登录' }, + reused: { type: 'boolean', description: '是否复用已有 cookie(未重新登录)' }, + shop_name: { type: 'string', description: '平台当前店铺名称(登录成功时返回)' }, + }, + externalPrintAccountLoginResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'externalPrintAccountLoginResult', description: '登录结果' }, + }, + // ---------- 店铺商品 shop_products ---------- shopProductItem: { id: { type: 'integer', description: '主键' }, diff --git a/backend/app/controller/externalPrintAccount.js b/backend/app/controller/externalPrintAccount.js new file mode 100644 index 0000000..c59a512 --- /dev/null +++ b/backend/app/controller/externalPrintAccount.js @@ -0,0 +1,353 @@ +'use strict'; + +const { Controller } = require('egg'); +const { parsePagination, buildPageResult } = require('../lib/pagination'); +const { createPrintPlatformService, hasPrintPlatformService } = require('../lib/printPlatform'); + +/** + * 列表/详情不回显密码与 cookie,仅返回是否已设置 + * @param {object} row 账号记录(Sequelize 实例或普通对象) + * @return {object} 去掉凭据后的账号数据 + */ +function toSafeAccount(row) { + const plain = typeof row.get === 'function' ? row.get({ plain: true }) : { ...row }; + plain.has_password = !!plain.password; + plain.has_cookie = !!plain.cookie; + plain.has_token = !!plain.token; + delete plain.password; + delete plain.cookie; + delete plain.token; + return plain; +} + +/** + * @controller ExternalPrintAccountController 外部打单账号管理 + * 账号归属主体,在前端「店铺管理 → 外部打单平台」维护(新增 / 修改 / 删除) + */ +class ExternalPrintAccountController extends Controller { + /** + * @summary 外部打单账号列表 + * @description 分页查询当前主体下的打单账号,支持按平台过滤与账号模糊搜索;响应不含密码 + * @router get /api/external-print-accounts + * @apikey + * @request query integer page 页码,默认 1 + * @request query integer pageSize 每页条数,默认 20 + * @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体) + * @request query integer platform_id 外部打单平台ID,不传则返回全部平台 + * @request query string keyword 关键词,匹配账号 + * @response 200 externalPrintAccountListResponse success + */ + async index() { + const { ctx } = this; + const Op = this.app.Sequelize.Op; + const { page, pageSize, offset, limit } = parsePagination(ctx.query); + const { platform_id: platformId, keyword } = ctx.query; + + const where = { principal_id: ctx.state.principalId }; + if (platformId) where.platform_id = Number(platformId); + if (keyword) where.account = { [Op.like]: `%${String(keyword).trim()}%` }; + + const { count, rows } = await ctx.model.ExternalPrintAccount.findAndCountAll({ + where, + offset, + limit, + order: [[ 'id', 'DESC' ]], + include: [ + { + model: ctx.model.ExternalPrintPlatform, + as: 'platform', + attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ], + }, + ], + }); + + const list = rows.map(toSafeAccount); + ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; + } + + /** + * @summary 外部打单账号详情 + * @description 按主键查询账号信息(不含密码) + * @router get /api/external-print-accounts/{id} + * @apikey + * @request path integer *id 账号主键ID + * @response 200 baseResponse success + */ + async show() { + const { ctx } = this; + const item = await this.findAccount(ctx.params.id, { withPlatform: true }); + + if (!item) { + ctx.status = 404; + ctx.body = { code: 404, message: '打单账号不存在' }; + return; + } + + ctx.body = { code: 0, message: 'success', data: toSafeAccount(item) }; + } + + /** + * @summary 新增外部打单账号 + * @description platform_id、account、password 必填;同一主体在同一平台下账号不能重复 + * @router post /api/external-print-accounts + * @apikey + * @request body createExternalPrintAccountRequest *body + * @response 200 baseResponse success + */ + async create() { + const { ctx } = this; + const principalId = ctx.state.principalId; + const body = ctx.request.body || {}; + const platformId = Number(body.platform_id); + const account = String(body.account || '').trim(); + const password = String(body.password || ''); + + if (!platformId || !account || !password) { + ctx.status = 400; + ctx.body = { code: 400, message: 'platform_id(外部打单平台)、account(账号)、password(密码)为必填项' }; + return; + } + + const platform = await ctx.model.ExternalPrintPlatform.findByPk(platformId); + if (!platform) { + ctx.status = 400; + ctx.body = { code: 400, message: '外部打单平台不存在' }; + return; + } + + const exist = await ctx.model.ExternalPrintAccount.findOne({ + where: { principal_id: principalId, platform_id: platformId, account }, + }); + if (exist) { + ctx.status = 400; + ctx.body = { code: 400, message: `该平台下账号 ${account} 已存在` }; + return; + } + + const item = await ctx.model.ExternalPrintAccount.create({ + principal_id: principalId, + platform_id: platformId, + account, + password, + }); + ctx.body = { code: 0, message: 'success', data: { id: item.id } }; + } + + /** + * @summary 更新外部打单账号 + * @description 未传入的字段保持原值;password 留空表示不修改密码(接口不回显密码) + * @router put /api/external-print-accounts/{id} + * @apikey + * @request path integer *id 账号主键ID + * @request body updateExternalPrintAccountRequest *body + * @response 200 baseResponse success + */ + async update() { + const { ctx } = this; + const Op = this.app.Sequelize.Op; + const item = await this.findAccount(ctx.params.id); + + if (!item) { + ctx.status = 404; + ctx.body = { code: 404, message: '打单账号不存在' }; + return; + } + + const body = ctx.request.body || {}; + const patch = {}; + + if (body.platform_id !== undefined && body.platform_id !== '' && body.platform_id !== null) { + const platformId = Number(body.platform_id); + const platform = await ctx.model.ExternalPrintPlatform.findByPk(platformId); + if (!platform) { + ctx.status = 400; + ctx.body = { code: 400, message: '外部打单平台不存在' }; + return; + } + patch.platform_id = platformId; + } + + if (body.account !== undefined) { + const account = String(body.account).trim(); + if (!account) { + ctx.status = 400; + ctx.body = { code: 400, message: 'account(账号)不能为空' }; + return; + } + patch.account = account; + } + + if (body.password !== undefined && body.password !== null && String(body.password) !== '') { + patch.password = String(body.password); + } + + const platformId = patch.platform_id === undefined ? item.platform_id : patch.platform_id; + const account = patch.account === undefined ? item.account : patch.account; + if (patch.platform_id !== undefined || patch.account !== undefined) { + const exist = await ctx.model.ExternalPrintAccount.findOne({ + where: { + principal_id: item.principal_id, + platform_id: platformId, + account, + id: { [Op.ne]: item.id }, + }, + }); + if (exist) { + ctx.status = 400; + ctx.body = { code: 400, message: `该平台下账号 ${account} 已存在` }; + return; + } + } + + await item.update(patch); + ctx.body = { code: 0, message: 'success', data: { id: item.id } }; + } + + /** + * @summary 检查外部打单账号登录状态 + * @description 用账号已保存的 cookie 访问平台门户,返回是否仍处于登录态;不会触发重新登录 + * @router post /api/external-print-accounts/{id}/check + * @apikey + * @request path integer *id 账号主键ID + * @response 200 externalPrintAccountCheckResponse success + */ + async check() { + const { ctx } = this; + const account = await this.findAccount(ctx.params.id, { withPlatform: true }); + + if (!account) { + ctx.status = 404; + ctx.body = { code: 404, message: '打单账号不存在' }; + return; + } + + try { + const service = this.createPlatformService(account); + const result = await service.checkSession(); + ctx.body = { + code: 0, + message: 'success', + data: { + logged_in: !!result.loggedIn, + message: result.message || '', + url: result.url || '', + nickname: result.nickname || '', + shop_name: result.shopName || '', + }, + }; + } catch (err) { + ctx.status = 400; + ctx.body = { code: 400, message: err.message }; + } + } + + /** + * @summary 登录外部打单账号 + * @description cookie 有效时直接复用;否则用账号密码登录,成功后把会话 cookie 写回账号表 + * @router post /api/external-print-accounts/{id}/login + * @apikey + * @request path integer *id 账号主键ID + * @response 200 externalPrintAccountLoginResponse success + */ + async login() { + const { ctx } = this; + const account = await this.findAccount(ctx.params.id, { withPlatform: true }); + + if (!account) { + ctx.status = 404; + ctx.body = { code: 404, message: '打单账号不存在' }; + return; + } + + try { + const service = this.createPlatformService(account); + const result = await service.login(); + ctx.body = { + code: 0, + message: 'success', + data: { logged_in: true, reused: !!result.reused, shop_name: result.shopName || '' }, + }; + } catch (err) { + ctx.status = 400; + ctx.body = { code: 400, message: err.message }; + } + } + + /** + * 取当前主体下的账号。 + * 资源不存在时 principalCheck 不会写入主体ID(交由控制器返回 404),此时直接返回 null, + * 避免把 undefined 传给 Sequelize 导致 500。 + * @param {number|string} id 账号ID + * @param {Object} [options] withPlatform 为 true 时一并带出平台配置 + * @return {Promise} 账号实例 + */ + async findAccount(id, options = {}) { + const { ctx } = this; + const principalId = ctx.state.principalId; + if (principalId == null) return null; + + const query = { where: { id, principal_id: principalId } }; + if (options.withPlatform) { + query.include = [ + { + model: ctx.model.ExternalPrintPlatform, + as: 'platform', + attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ], + }, + ]; + } + return ctx.model.ExternalPrintAccount.findOne(query); + } + + /** + * 按账号所属平台创建服务实例;cookie 变更时写回账号表 + * @param {Object} account 账号实例(需 include platform) + * @return {Object} 平台服务实例 + */ + createPlatformService(account) { + const platform = account.platform; + if (!platform) throw new Error('打单账号未关联外部打单平台'); + if (!hasPrintPlatformService(platform.code)) { + throw new Error(`外部打单平台 ${platform.name}(${platform.code})暂未接入`); + } + return createPrintPlatformService(platform.code, { + platform: platform.get({ plain: true }), + account: account.get({ plain: true }), + saveCookie: async cookie => { + await account.update({ cookie }); + }, + saveToken: async token => { + await account.update({ token }); + }, + saveLoginStatus: async status => { + if (Number(account.login_status) !== Number(status)) { + await account.update({ login_status: status }); + } + }, + }); + } + + /** + * @summary 删除外部打单账号 + * @description 物理删除账号 + * @router delete /api/external-print-accounts/{id} + * @apikey + * @request path integer *id 账号主键ID + * @response 200 baseResponse success + */ + async destroy() { + const { ctx } = this; + const item = await this.findAccount(ctx.params.id); + + if (!item) { + ctx.status = 404; + ctx.body = { code: 404, message: '打单账号不存在' }; + return; + } + + await item.destroy(); + ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } }; + } +} + +module.exports = ExternalPrintAccountController; diff --git a/backend/app/controller/externalPrintPlatform.js b/backend/app/controller/externalPrintPlatform.js new file mode 100644 index 0000000..b2c95ff --- /dev/null +++ b/backend/app/controller/externalPrintPlatform.js @@ -0,0 +1,34 @@ +'use strict'; + +const { Controller } = require('egg'); + +/** + * @controller ExternalPrintPlatformController 外部打单平台(平台字典) + * 平台基础资料由开发者维护,前端只读展示;是否回平台取号由 fetch_waybill_no 固化 + */ +class ExternalPrintPlatformController extends Controller { + /** + * @summary 外部打单平台列表 + * @description 返回全部外部打单平台(按 sort 升序),供「店铺管理 → 外部打单平台」页面展示与账号表单选择 + * @router get /api/external-print-platforms + * @apikey + * @request query integer status 状态:1启用 0禁用,不传则返回全部 + * @response 200 externalPrintPlatformListResponse success + */ + async index() { + const { ctx } = this; + const { status } = ctx.query; + + const where = {}; + if (status !== undefined && status !== '') where.status = Number(status); + + const rows = await ctx.model.ExternalPrintPlatform.findAll({ + where, + order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], + }); + + ctx.body = { code: 0, message: 'success', data: rows }; + } +} + +module.exports = ExternalPrintPlatformController; diff --git a/backend/app/lib/printPlatform/base.js b/backend/app/lib/printPlatform/base.js new file mode 100644 index 0000000..ee48ce3 --- /dev/null +++ b/backend/app/lib/printPlatform/base.js @@ -0,0 +1,164 @@ +'use strict'; + +/** + * 外部打单平台服务基类。 + * + * 约定:一个平台一个 service 类,放在 app/lib/printPlatform/ 目录下,文件名与平台标识(code)保持一致; + * 类上声明 static code(须与 external_print_platforms.code 相同),由 ./index.js 统一注册与实例化。 + * + * 平台基础资料(链接地址、是否回平台取号)来自 external_print_platforms,由开发者维护; + * 账号密码来自 external_print_accounts,仅供服务端调用平台使用,切勿写入日志或返回给前端。 + */ +class PrintPlatformService { + /** + * @param {Object} options 构造参数 + * @param {Object} options.platform 平台配置(external_print_platforms 记录) + * @param {Object} [options.account] 打单账号(external_print_accounts 记录,含 account / password / cookie / token) + * @param {Function} [options.saveCookie] 会话 cookie 落库回调,签名 (cookie) => Promise + * @param {Function} [options.saveToken] 登录 token 落库回调,签名 (token) => Promise + * @param {Function} [options.saveLoginStatus] 登录状态落库回调,签名 (status) => Promise,1已登录 0未登录/失效 + */ + constructor({ platform, account, saveCookie, saveToken, saveLoginStatus } = {}) { + if (!platform || !platform.code) { + throw new Error('创建外部打单平台服务需要平台配置(platform.code)'); + } + this.platform = platform; + this.account = account || null; + this._saveCookie = typeof saveCookie === 'function' ? saveCookie : null; + this._saveToken = typeof saveToken === 'function' ? saveToken : null; + this._saveLoginStatus = typeof saveLoginStatus === 'function' ? saveLoginStatus : null; + } + + /** + * 平台标识,必须与 external_print_platforms.code 一致 + * @return {string|null} 平台标识,基类未声明时为 null(注册时会因缺少 code 报错) + */ + static get code() { + return null; + } + + /** 平台标识(与平台配置的 code 对应) */ + get platformCode() { + return this.constructor.code; + } + + /** 平台名称 */ + get platformName() { + return this.platform.name; + } + + /** 平台链接地址:仅服务端请求使用,前端不展示 */ + get baseUrl() { + return this.platform.url; + } + + /** 是否回打单平台取号:1 是 0 否(固化在平台基础资料中) */ + get needFetchWaybillNo() { + return Number(this.platform.fetch_waybill_no) === 1; + } + + /** + * 读取打单账号密码,未配置时抛错,避免各实现重复判空 + * @return {{account: string, password: string}} 平台登录凭据 + */ + getCredentials() { + const account = this.account || {}; + if (!account.account || !account.password) { + throw new Error(`外部打单平台 ${this.platformName} 未配置账号密码`); + } + return { account: account.account, password: account.password }; + } + + /** + * 该账号已保存的会话 cookie(未登录过时为空字符串) + * @return {string} 会话 cookie + */ + get cookie() { + return (this.account && this.account.cookie) || ''; + } + + /** + * 保存会话 cookie:更新内存中的账号记录,并通过构造时传入的 saveCookie 回调落库, + * 避免登录态散落在临时变量、文件或缓存里 + * @param {string} cookie 平台返回的会话 cookie + * @return {Promise} 无返回值 + */ + async saveCookie(cookie) { + const value = String(cookie || ''); + if (this.account) this.account.cookie = value; + if (!this._saveCookie) { + throw new Error(`外部打单平台 ${this.platformName} 未提供 cookie 保存回调,无法持久化会话`); + } + await this._saveCookie(value); + } + + /** + * 该账号已保存的登录 token(未登录过时为空字符串) + * @return {string} 登录 token + */ + get token() { + return (this.account && this.account.token) || ''; + } + + /** + * 保存登录 token:更新内存中的账号记录,并通过构造时传入的 saveToken 回调落库 + * @param {string} token 平台返回的登录 token + * @return {Promise} 无返回值 + */ + async saveToken(token) { + const value = String(token || ''); + if (this.account) this.account.token = value; + if (!this._saveToken) { + throw new Error(`外部打单平台 ${this.platformName} 未提供 token 保存回调,无法持久化登录态`); + } + await this._saveToken(value); + } + + /** + * 记录登录状态(1 已登录 / 0 未登录或已失效)。 + * 状态是辅助信息,未提供落库回调时只更新内存,不抛错。 + * @param {number|boolean} status 登录状态 + * @return {Promise} 无返回值 + */ + async saveLoginStatus(status) { + const value = status === true || Number(status) === 1 ? 1 : 0; + if (this.account) this.account.login_status = value; + if (this._saveLoginStatus) await this._saveLoginStatus(value); + } + + /** + * 登录外部打单平台(获取会话/令牌),由各平台实现 + * @return {Promise} 登录结果(会话、令牌等,由各实现定义) + */ + async login() { + throw new Error(`外部打单平台 ${this.platformName} 未实现 login()`); + } + + /** + * 检查当前账号的登录态(不触发登录),由各平台实现 + * @return {Promise<{loggedIn: boolean, message?: string, url?: string}>} 登录态检查结果 + */ + async checkSession() { + throw new Error(`外部打单平台 ${this.platformName} 未实现 checkSession()`); + } + + /** + * 把订单推送到打单平台打印,由各平台实现 + * @param {Object} order 订单数据(字段口径由平台协议决定) + * @return {Promise} 平台响应 + */ + async print(order) { // eslint-disable-line no-unused-vars + throw new Error(`外部打单平台 ${this.platformName} 未实现 print()`); + } + + /** + * 回打单平台取运单号(fetch_waybill_no=1 的平台必须实现),由各平台实现 + * @param {Object} order 订单数据(字段口径由平台协议决定) + * @return {Promise} 运单号列表 + */ + async fetchWaybillNo(order) { // eslint-disable-line no-unused-vars + throw new Error(`外部打单平台 ${this.platformName} 未实现 fetchWaybillNo()`); + } +} + +module.exports = PrintPlatformService; diff --git a/backend/app/lib/printPlatform/dgj.js b/backend/app/lib/printPlatform/dgj.js new file mode 100644 index 0000000..5c5d4a5 --- /dev/null +++ b/backend/app/lib/printPlatform/dgj.js @@ -0,0 +1,392 @@ +'use strict'; + +const PrintPlatformService = require('./base'); + +/** 店管家商家门户站点 */ +const PORTAL_ORIGIN = 'https://tfxportal.dgjapp.com'; +/** 门户登录页入口(用于登录前建立会话 cookie;未登录时访问会停在登录页) */ +const PORTAL_URL = `${PORTAL_ORIGIN}/ffaccount`; +/** 登录前置接口:判断是否需要提示绑定微信 */ +const BIND_WECHAT_PROMPT_URL = `${PORTAL_ORIGIN}/FFAccount/BindWeChatPrompt`; +/** 登录接口:返回 Token 与跳转地址,并通过 set-cookie 下发登录态 */ +const LOGIN_URL = `${PORTAL_ORIGIN}/FFAccount/LoginPortal`; + +/** 登录后的工作台域名(需同时带 token 与 cookie 才能打开) */ +const WORKBENCH_HOST = 'fxali.dgjapp.com'; +/** 工作台入口:?token=<登录接口返回的 Token> */ +const WORKBENCH_URL = `https://${WORKBENCH_HOST}/GeneralizeIndex/`; +/** 工作台用户信息接口:返回当前登录账号的店铺/昵称等信息(需 token + cookie) */ +const USER_INFO_URL = `https://${WORKBENCH_HOST}/api/user/GetUserInfo`; + +/** 单次请求超时(毫秒) */ +const REQUEST_TIMEOUT_MS = 15000; + +/** + * 模拟 Chrome 访问 html 页面的请求头(取自真实抓包)。 + * 说明:HTTP/2 伪头(:authority / :method / :path / :scheme)由客户端按 URL 自动生成,不能手动设置; + * accept-encoding 交给 fetch 自动协商并解压,手动声明会导致响应不解压。 + */ +const BROWSER_HEADERS = { + accept: + 'text/html,application/xhtml+xml,application/xml;q=0.9,image/jxl,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', + 'accept-language': 'zh-CN,zh;q=0.9', + 'cache-control': 'max-age=0', + priority: 'u=0, i', + 'sec-ch-ua': '"Not:A-Brand";v="8", "Chromium";v="156", "Google Chrome";v="156"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'document', + 'sec-fetch-mode': 'navigate', + 'sec-fetch-site': 'none', + 'sec-fetch-user': '?1', + 'upgrade-insecure-requests': '1', + 'user-agent': + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36', +}; + +/** 模拟浏览器 ajax 表单提交的请求头(登录接口为同源 XHR) */ +const AJAX_HEADERS = { + accept: 'application/json, text/javascript, */*; q=0.01', + 'accept-language': 'zh-CN,zh;q=0.9', + 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', + origin: PORTAL_ORIGIN, + referer: PORTAL_URL, + 'sec-ch-ua': '"Not:A-Brand";v="8", "Chromium";v="156", "Google Chrome";v="156"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'sec-fetch-dest': 'empty', + 'sec-fetch-mode': 'cors', + 'sec-fetch-site': 'same-origin', + 'user-agent': + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36', + 'x-requested-with': 'XMLHttpRequest', +}; + +/** 模拟工作台 ajax(GET 接口)的请求头,Referer 指向工作台 */ +const WORKBENCH_AJAX_HEADERS = { + accept: 'application/json, text/javascript, */*; q=0.01', + 'accept-language': 'zh-CN,zh;q=0.9', + referer: WORKBENCH_URL, + 'sec-ch-ua': '"Not:A-Brand";v="8", "Chromium";v="156", "Google Chrome";v="156"', + 'sec-ch-ua-mobile': '?0', + 'sec-ch-ua-platform': '"Windows"', + 'user-agent': + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36', + 'x-requested-with': 'XMLHttpRequest', +}; + +/** + * 登录表单字段加密:店管家要求 IsEnc=1 时字段值做 base64(URLSearchParams 会再对 = 等字符做 URL 编码) + * @param {string} value 原始值 + * @return {string} base64 值 + */ +function encodeField(value) { + return Buffer.from(String(value), 'utf8').toString('base64'); +} + +/** + * 读取响应里的 set-cookie(兼容没有 getSetCookie 的运行时) + * @param {Response} res fetch 响应 + * @return {string[]} set-cookie 列表 + */ +function getSetCookies(res) { + if (typeof res.headers.getSetCookie === 'function') return res.headers.getSetCookie(); + const raw = res.headers.get('set-cookie'); + return raw ? [ raw ] : []; +} + +/** + * 合并 set-cookie 到已有 cookie:同名覆盖,其余保留 + * @param {string} cookie 已有 cookie + * @param {string[]} setCookies 响应头 set-cookie + * @return {string} 合并后的 cookie + */ +function mergeCookie(cookie, setCookies) { + const jar = new Map(); + for (const item of String(cookie || '').split(';')) { + const kv = item.trim(); + const idx = kv.indexOf('='); + if (idx > 0) jar.set(kv.slice(0, idx), kv.slice(idx + 1)); + } + for (const raw of setCookies) { + const kv = String(raw).split(';')[0].trim(); + const idx = kv.indexOf('='); + if (idx > 0) jar.set(kv.slice(0, idx), kv.slice(idx + 1)); + } + return Array.from(jar, ([ key, value ]) => `${key}=${value}`).join('; '); +} + +/** + * 组装登录失败提示 + * @param {{status: number, json: Object|null}} res 接口响应 + * @return {string} 失败原因 + */ +function describeFailure(res) { + const json = (res && res.json) || {}; + const message = json.Message || json.ErrorCode || '未知错误'; + return `${message}(HTTP ${res ? res.status : '-'})`; +} + +/** + * 店管家(dgj)外部打单平台服务。 + * + * 平台记录:external_print_platforms.code = 'dgj'(名称「店管家」,fetch_waybill_no = 0 即不回平台取号)。 + * 该平台的全部处理逻辑(登录、打单、取号等)都写在本文件里,不要散落到别处; + * 新增平台时同样新建 `<平台 code>.js`,并把 static code 改成对应平台标识。 + * + * 登录流程(与浏览器一致): + * 1. GET /ffaccount 建立会话(拿到 WAF/ASP.NET 基础 cookie) + * 2. POST /FFAccount/BindWeChatPrompt(是否需要提示绑定微信) + * 3. POST /FFAccount/LoginPortal(返回 Token / RedirectUrl,并通过 set-cookie 下发登录态) + * 4. GET /api/user/GetUserInfo?token=(需同时带 cookie)确认登录态并拿账号信息 + * 成功后把 token 与 cookie 一并写回账号表,后续检查/调用复用。 + * + * 注意:店管家工作台同时依赖 token 与 cookie,仅保存 cookie 无法获取账号信息(返回 401)。 + * 登录态检查走 GetUserInfo(轻量 JSON,避免每次拉取 500KB 的工作台页面)。 + */ +class DgjService extends PrintPlatformService { + static get code() { + return 'dgj'; + } + + /** + * 店管家站点根地址(平台配置的链接未带协议时补 https://) + * @return {string} 站点根地址 + */ + get siteUrl() { + const url = String(this.platform.url || '').trim(); + if (!url) throw new Error('店管家平台未配置链接地址(external_print_platforms.url)'); + return /^https?:\/\//i.test(url) ? url : `https://${url}`; + } + + /** + * 统一平台请求入口(请求拦截器)。 + * 平台接口返回 401 表示登录已失效,这里统一把账号登录状态记为 0; + * 其余状态交由调用方按业务判断。 + * @param {string} url 完整请求地址 + * @param {Object} [options] fetch 选项(method / headers / body 等) + * @return {Promise<{status: number, json: Object|null, text: string, setCookies: string[]}>} 响应 + */ + async request(url, options = {}) { + const res = await fetch(url, { + redirect: 'follow', + ...options, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + const text = await res.text(); + let json = null; + try { + json = JSON.parse(text); + } catch { + json = null; + } + + if (res.status === 401) { + await this.saveLoginStatus(0); + } + + return { status: res.status, json, text, setCookies: getSetCookies(res) }; + } + + /** + * 拉取工作台当前登录账号信息(需 token + cookie,缺一不可) + * @param {string} [token] 登录 token,默认取账号已保存的 token + * @param {string} [cookie] 会话 cookie,默认取账号已保存的 cookie + * @return {Promise<{success: boolean, status: number, message: string, data: Object|null, setCookies: string[]}>} 账号信息 + */ + async getUserInfo(token = this.token, cookie = this.cookie) { + const tk = String(token || '').trim(); + if (!tk) throw new Error('店管家账号未保存登录 token,无法获取账号信息'); + + const query = new URLSearchParams({ + traceId: '', + dbname: '', + dataFlag: '', + IsCustomerOrder: 'false', + FxPageType: '1', + _: String(Date.now()), + token: tk, + }); + + const headers = { ...WORKBENCH_AJAX_HEADERS }; + if (cookie) headers.cookie = cookie; + + const res = await this.request(`${USER_INFO_URL}?${query.toString()}`, { method: 'GET', headers }); + + const success = res.status === 200 && !!res.json && res.json.Success === true; + if (success) await this.saveLoginStatus(1); + + return { + success, + status: res.status, + message: (res.json && res.json.Message) || '', + data: success && res.json.Data ? res.json.Data : null, + setCookies: res.setCookies, + }; + } + + /** + * 登录:token + cookie 有效时直接复用;否则用账号密码登录, + * 成功后把 token 与 cookie 写回账号表,避免上下文丢失 + * @return {Promise<{cookie: string, token: string|null, redirectUrl: string|null, reused: boolean}>} 登录结果 + */ + async login() { + if (this.cookie && this.token) { + const status = await this.checkSession(); + if (status.loggedIn) { + return { cookie: this.cookie, token: this.token, redirectUrl: null, reused: true, shopName: status.shopName || '' }; + } + } + return this.loginByPassword(); + } + + /** + * 检查当前账号登录态:token/cookie 缺失视为未登录; + * 都有则打开工作台校验(未登录会被重定向回门户登录页) + * @return {Promise<{loggedIn: boolean, message: string, url: string}>} 登录态检查结果 + */ + async checkSession() { + if (!this.token) { + await this.saveLoginStatus(0); + return { loggedIn: false, message: '账号未保存登录 token,尚未登录', url: USER_INFO_URL }; + } + if (!this.cookie) { + await this.saveLoginStatus(0); + return { loggedIn: false, message: '账号未保存会话 cookie,尚未登录', url: USER_INFO_URL }; + } + + const info = await this.getUserInfo(this.token, this.cookie); + const loggedIn = info.success; + if (!loggedIn) await this.saveLoginStatus(0); + + return { + loggedIn, + message: loggedIn ? '登录态有效' : `登录态已失效${info.message ? `(${info.message})` : ''}`, + url: USER_INFO_URL, + nickname: info.data ? info.data.FxUserNickName || info.data.NickName || '' : '', + shopName: info.data ? info.data.ShopName || '' : '', + }; + } + + /** + * 账号密码登录(两次 POST:BindWeChatPrompt → LoginPortal) + * @return {Promise<{cookie: string, token: string|null, redirectUrl: string|null, reused: boolean}>} 登录结果 + */ + async loginByPassword() { + const { account, password } = this.getCredentials(); + let cookie = await this.bootstrapSession(); + + const prompt = await this.postForm(BIND_WECHAT_PROMPT_URL, this.buildLoginForm(account, password, false), cookie); + cookie = mergeCookie(cookie, prompt.setCookies); + if (!this.isSuccess(prompt)) { + throw new Error(`店管家登录前置校验失败:${describeFailure(prompt)}`); + } + + const result = await this.postForm(LOGIN_URL, this.buildLoginForm(account, password, true), cookie); + cookie = mergeCookie(cookie, result.setCookies); + const data = result.json && result.json.Data; + if (!this.isSuccess(result) || !data || !data.Token) { + throw new Error(`店管家登录失败:${describeFailure(result)}`); + } + + // 用登录返回的 token + cookie 拉取账号信息,确认登录态真正可用后再落库 + const info = await this.getUserInfo(data.Token, cookie); + if (!info.success) { + throw new Error(`店管家登录后校验失败:${info.message || '获取账号信息失败'}`); + } + + await this.saveCookie(cookie); + await this.saveToken(data.Token); + return { + cookie, + token: data.Token, + redirectUrl: data.RedirectUrl || null, + reused: false, + shopName: info.data ? info.data.ShopName || '' : '', + }; + } + + /** + * 访问门户建立会话,拿到 WAF / ASP.NET 基础 cookie + * @return {Promise} 新建的 cookie + */ + async bootstrapSession() { + const res = await fetch(PORTAL_URL, { + method: 'GET', + headers: BROWSER_HEADERS, + redirect: 'follow', + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + // 只需要响应头里的 set-cookie,正文丢弃 + await res.arrayBuffer().catch(() => {}); + return mergeCookie('', getSetCookies(res)); + } + + /** + * 组装登录表单(IsEnc=1:Mobile/Password 做 base64;LoginPortal 额外带空参数) + * @param {string} account 登录账号 + * @param {string} password 登录密码 + * @param {boolean} forPortal 是否为 LoginPortal 接口 + * @return {URLSearchParams} 表单 + */ + buildLoginForm(account, password, forPortal) { + const form = new URLSearchParams(); + form.set('Mobile', encodeField(account)); + form.set('Password', encodeField(password)); + form.set('ValidCode', ''); + form.set('IsEnc', '1'); + form.set('NotUseAliyunCaptcha', 'true'); + if (forPortal) { + form.set('ShopId', ''); + form.set('From', ''); + form.set('PlatformType', ''); + } + return form; + } + + /** + * 以浏览器 ajax 方式提交登录表单 + * @param {string} url 接口地址 + * @param {URLSearchParams} form 表单 + * @param {string} cookie 会话 cookie + * @return {Promise<{status: number, json: Object|null, text: string, setCookies: string[]}>} 接口响应 + */ + async postForm(url, form, cookie) { + const headers = { ...AJAX_HEADERS }; + if (cookie) headers.cookie = cookie; + + return this.request(url, { + method: 'POST', + headers, + body: form.toString(), + }); + } + + /** + * 接口是否返回 Success = true + * @param {{json: Object|null}} res 接口响应 + * @return {boolean} 是否成功 + */ + isSuccess(res) { + return !!(res && res.json && res.json.Success === true); + } + + /** + * 把订单推送到店管家打印 + * @param {Object} order 订单数据(字段口径由店管家协议决定) + * @return {Promise} 平台响应 + */ + async print(order) { + throw new Error(`店管家未实现 print(),订单:${order && order.id}`); + } + + /** + * 店管家不回平台取号(平台配置 fetch_waybill_no = 0),调用即视为错误 + * @return {Promise} 固定抛错 + */ + async fetchWaybillNo() { + throw new Error('店管家不回平台取号(fetch_waybill_no=0),不应调用 fetchWaybillNo()'); + } +} + +module.exports = DgjService; diff --git a/backend/app/lib/printPlatform/index.js b/backend/app/lib/printPlatform/index.js new file mode 100644 index 0000000..367442b --- /dev/null +++ b/backend/app/lib/printPlatform/index.js @@ -0,0 +1,96 @@ +'use strict'; + +/** + * 外部打单平台服务注册入口。 + * + * 约定:一个平台一个文件,文件名 = 平台标识(external_print_platforms.code), + * 例如 code 为 dgj 的平台对应本目录下的 dgj.js;文件内的类声明 static code = 'dgj', + * 必须与表里的 code 完全一致。以 `_` 开头的文件不参与注册(草稿/临时文件)。 + */ + +const fs = require('fs'); +const path = require('path'); +const PrintPlatformService = require('./base'); + +/** 平台实现目录 */ +const SERVICE_DIR = __dirname; + +/** + * 是否作为平台实现加载:`_` 开头的为模板/草稿,base.js 与 index.js 为基础设施 + * @param {string} file 文件名 + * @return {boolean} 是否加载 + */ +function isServiceFile(file) { + return file.endsWith('.js') && !file.startsWith('_') && file !== 'base.js' && file !== 'index.js'; +} + +/** code -> 平台服务类,首次使用时扫描目录建立索引 */ +let registry = null; + +/** + * 扫描目录加载全部平台实现,按 static code 建立索引 + * @return {Map} 平台标识 -> 服务类 + */ +function loadRegistry() { + if (registry) return registry; + + const map = new Map(); + for (const file of fs.readdirSync(SERVICE_DIR).filter(isServiceFile)) { + const Service = require(path.join(SERVICE_DIR, file)); + const code = Service && Service.code; + if (!code) throw new Error(`外部打单平台服务 ${file} 缺少 static code`); + if (map.has(code)) throw new Error(`外部打单平台服务 code 重复:${code}(${file})`); + map.set(code, Service); + } + + registry = map; + return registry; +} + +/** + * 按平台标识取服务类 + * @param {string} code 平台标识(external_print_platforms.code) + * @return {Function|null} 服务类,未实现时返回 null + */ +function getPrintPlatformServiceClass(code) { + return loadRegistry().get(String(code)) || null; +} + +/** + * 平台是否已有服务实现 + * @param {string} code 平台标识(external_print_platforms.code) + * @return {boolean} 是否已实现 + */ +function hasPrintPlatformService(code) { + return !!getPrintPlatformServiceClass(code); +} + +/** + * 创建平台服务实例 + * @param {string} code 平台标识(external_print_platforms.code) + * @param {Object} options 构造参数:{ platform, account } + * @return {PrintPlatformService} 平台服务实例 + */ +function createPrintPlatformService(code, options = {}) { + const Service = getPrintPlatformServiceClass(code); + if (!Service) { + throw new Error(`外部打单平台 ${code} 暂无服务实现,请先在 app/lib/printPlatform 下新增对应 service 类`); + } + return new Service(options); +} + +/** + * 已实现服务的平台标识列表 + * @return {string[]} 平台标识列表 + */ +function listPrintPlatformServiceCodes() { + return Array.from(loadRegistry().keys()); +} + +module.exports = { + PrintPlatformService, + getPrintPlatformServiceClass, + hasPrintPlatformService, + createPrintPlatformService, + listPrintPlatformServiceCodes, +}; diff --git a/backend/app/model/externalPrintAccount.js b/backend/app/model/externalPrintAccount.js new file mode 100644 index 0000000..927574c --- /dev/null +++ b/backend/app/model/externalPrintAccount.js @@ -0,0 +1,32 @@ +'use strict'; + +/** + * 外部打单账号模型,对应 external_print_accounts 表。 + * 一个主体在同一平台上可配置多个账号,账号密码供服务端调用外部打单平台使用; + * 密码不通过接口下发(列表/详情只返回 has_password),避免泄露。 + * @param {Egg.Application} app egg application + * @return {object} externalPrintAccount model + */ +module.exports = app => { + const { BIGINT, STRING, TEXT, TINYINT, DATE } = app.Sequelize; + + const ExternalPrintAccount = app.model.define('external_print_account', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, + platform_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属外部打单平台ID' }, + account: { type: STRING(100), allowNull: false, comment: '外部打单平台登录账号' }, + password: { type: STRING(255), allowNull: false, comment: '外部打单平台登录密码(服务端调用平台时使用,接口不回显)' }, + cookie: { type: TEXT, comment: '外部打单平台会话 cookie(服务端登录后写回,接口不回显)' }, + token: { type: STRING(255), comment: '外部打单平台登录 Token(服务端登录后写回,接口不回显)' }, + login_status: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '登录状态:1已登录 0未登录/已失效' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + }); + + ExternalPrintAccount.associate = () => { + app.model.ExternalPrintAccount.belongsTo(app.model.ExternalPrintPlatform, { foreignKey: 'platform_id', as: 'platform' }); + app.model.ExternalPrintAccount.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); + }; + + return ExternalPrintAccount; +}; diff --git a/backend/app/model/externalPrintPlatform.js b/backend/app/model/externalPrintPlatform.js new file mode 100644 index 0000000..cb646c2 --- /dev/null +++ b/backend/app/model/externalPrintPlatform.js @@ -0,0 +1,30 @@ +'use strict'; + +/** + * 外部打单平台模型,对应 external_print_platforms 表。 + * 平台字典由开发者维护(随打单/取号适配逻辑一起通过迁移写入),前端只读; + * fetch_waybill_no 固化「是否回打单平台取号」,程序按 code 选择对应适配实现。 + * @param {Egg.Application} app egg application + * @return {object} externalPrintPlatform model + */ +module.exports = app => { + const { BIGINT, STRING, TINYINT, INTEGER, DATE } = app.Sequelize; + + const ExternalPrintPlatform = app.model.define('external_print_platform', { + id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, + code: { type: STRING(50), allowNull: false, comment: '平台标识,程序按此选择打单/取号适配逻辑' }, + name: { type: STRING(100), allowNull: false, comment: '平台名称' }, + url: { type: STRING(255), comment: '平台链接地址' }, + fetch_waybill_no: { type: TINYINT, allowNull: false, defaultValue: 0, comment: '是否回打单平台取号:1是 0否' }, + sort: { type: INTEGER, allowNull: false, defaultValue: 0, comment: '排序,越小越靠前' }, + status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, + created_at: { type: DATE, comment: '创建时间' }, + updated_at: { type: DATE, comment: '更新时间' }, + }); + + ExternalPrintPlatform.associate = () => { + app.model.ExternalPrintPlatform.hasMany(app.model.ExternalPrintAccount, { foreignKey: 'platform_id', as: 'accounts' }); + }; + + return ExternalPrintPlatform; +}; diff --git a/backend/app/router.js b/backend/app/router.js index 7e96d4a..9226ea1 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -124,6 +124,12 @@ module.exports = app => { router.resources('shops', '/api/shops', jwtAuth, principalCheck({ model: 'Shop' }), controller.shop); router.resources('shopProducts', '/api/shop-products', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct); router.post('/api/shop-products/:id/bind', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct.bind); + // 外部打单平台:平台基础资料由开发者维护(只读查询);打单账号归属主体,在「店铺管理」下维护 + router.get('/api/external-print-platforms', jwtAuth, controller.externalPrintPlatform.index); + // 账号登录态检查 / 登录(需在 resources 之前注册,避免被 /:id 误匹配) + router.post('/api/external-print-accounts/:id/check', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.check); + router.post('/api/external-print-accounts/:id/login', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.login); + router.resources('externalPrintAccounts', '/api/external-print-accounts', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount); // 出入库单与明细(明细共用 stock_items 表,以 bill_type 区分:1入库 2出库) // 单据状态由业务事务推动(审核/推送/完成/驳回/作废/取消/恢复),不提供直接修改状态的接口 // 状态流转(按序校验):审核 / 推送 / 完成 / 取消 / 恢复 / 作废,需在 resources 之前注册避免被 :id 误匹配 diff --git a/backend/database/migrations/20261102000000-create-external-print-platforms.js b/backend/database/migrations/20261102000000-create-external-print-platforms.js new file mode 100644 index 0000000..c91a472 --- /dev/null +++ b/backend/database/migrations/20261102000000-create-external-print-platforms.js @@ -0,0 +1,124 @@ +'use strict'; + +/** + * 外部打单平台基础表 + 外部打单账号表。 + * + * - external_print_platforms:平台字典,由开发者维护(新增平台时随适配逻辑一起通过迁移写入), + * 前端只读展示。fetch_waybill_no 固化「是否回打单平台取号」,取号逻辑在程序内按平台 code 选择。 + * - external_print_accounts:各主体在外部打单平台上的登录账号,在前端「店铺管理 → 外部打单平台」维护, + * 密码仅供服务端调用平台使用,接口不回显。 + * + * 平台数据由开发者按对接情况写入(示例): + * INSERT INTO external_print_platforms (code, name, url, fetch_waybill_no, sort, status) + * VALUES ('example', '示例平台', 'https://example.com', 1, 10, 1); + * + * 平台接入实现见 app/lib/printPlatform/:一个平台一个文件,文件名 = 平台 code(如 dgj.js), + * 文件内的服务类 static code 需与本表 code 列一致。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable( + 'external_print_platforms', + { + id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + autoIncrement: true, + primaryKey: true, + }, + code: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '平台标识,程序按此选择打单/取号适配逻辑', + }, + name: { type: Sequelize.STRING(100), allowNull: false, comment: '平台名称' }, + url: { type: Sequelize.STRING(255), allowNull: true, comment: '平台链接地址' }, + fetch_waybill_no: { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '是否回打单平台取号:1是 0否', + }, + sort: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0, comment: '排序,越小越靠前' }, + status: { type: Sequelize.TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + }, + }, + { charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '外部打单平台表(开发者维护)' } + ); + + await queryInterface.addIndex('external_print_platforms', { + fields: [ 'code' ], + unique: true, + name: 'uk_external_print_platforms_code', + }); + + await queryInterface.createTable( + 'external_print_accounts', + { + id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + autoIncrement: true, + primaryKey: true, + }, + principal_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '所属主体ID', + references: { model: 'principals', key: 'id' }, + }, + platform_id: { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: false, + comment: '所属外部打单平台ID', + references: { model: 'external_print_platforms', key: 'id' }, + }, + account: { type: Sequelize.STRING(100), allowNull: false, comment: '外部打单平台登录账号' }, + password: { + type: Sequelize.STRING(255), + allowNull: false, + comment: '外部打单平台登录密码(服务端调用平台时使用,接口不回显)', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + }, + }, + { charset: 'utf8mb4', collate: 'utf8mb4_unicode_ci', comment: '外部打单账号表' } + ); + + await queryInterface.addIndex('external_print_accounts', { + fields: [ 'principal_id', 'platform_id', 'account' ], + unique: true, + name: 'uk_external_print_accounts_principal_platform_account', + }); + await queryInterface.addIndex('external_print_accounts', { + fields: [ 'principal_id' ], + name: 'idx_external_print_accounts_principal', + }); + await queryInterface.addIndex('external_print_accounts', { + fields: [ 'platform_id' ], + name: 'idx_external_print_accounts_platform', + }); + }, + + async down(queryInterface) { + await queryInterface.dropTable('external_print_accounts'); + await queryInterface.dropTable('external_print_platforms'); + }, +}; diff --git a/backend/database/migrations/20261102000100-seed-external-print-platform-menu.js b/backend/database/migrations/20261102000100-seed-external-print-platform-menu.js new file mode 100644 index 0000000..257aa93 --- /dev/null +++ b/backend/database/migrations/20261102000100-seed-external-print-platform-menu.js @@ -0,0 +1,64 @@ +'use strict'; + +/** + * 新增「外部打单平台」菜单:挂在「店铺管理」目录下,指向 views/ExternalPrintPlatform/Index.vue。 + * 平台基础资料由开发者维护,本菜单主要用于维护外部打单账号。 + * 按 name + parent_id 判重,可重复执行。 + */ +const PARENT_NAME = '店铺管理'; +const MENU = { + name: '外部打单平台', + type: 2, + path: '/external-print-platform', + icon: 'Printer', + permission: 'externalPrintAccount:list', + component: 'views/ExternalPrintPlatform/Index.vue', + sort: 70, +}; + +module.exports = { + async up(queryInterface) { + const sequelize = queryInterface.sequelize; + + const [ parent ] = await sequelize.query( + 'SELECT id FROM menus WHERE name = ? AND parent_id = 0 LIMIT 1', + { replacements: [ PARENT_NAME ], type: sequelize.QueryTypes.SELECT } + ); + if (!parent) { + // 父菜单不存在(异常数据)时跳过,避免挂错层级 + return; + } + const parentId = Number(parent.id); + + const [ exist ] = await sequelize.query( + 'SELECT id FROM menus WHERE name = ? AND parent_id = ? LIMIT 1', + { replacements: [ MENU.name, parentId ], type: sequelize.QueryTypes.SELECT } + ); + if (exist) return; + + await sequelize.query( + `INSERT INTO menus + (parent_id, name, type, path, icon, permission, component, sort, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, NOW(), NOW())`, + { + replacements: [ + parentId, + MENU.name, + MENU.type, + MENU.path, + MENU.icon, + MENU.permission, + MENU.component, + MENU.sort, + ], + } + ); + }, + + async down(queryInterface) { + const sequelize = queryInterface.sequelize; + await sequelize.query('DELETE FROM menus WHERE name = ? AND path = ?', { + replacements: [ MENU.name, MENU.path ], + }); + }, +}; diff --git a/backend/database/migrations/20261102000200-add-cookie-to-external-print-accounts.js b/backend/database/migrations/20261102000200-add-cookie-to-external-print-accounts.js new file mode 100644 index 0000000..72360cb --- /dev/null +++ b/backend/database/migrations/20261102000200-add-cookie-to-external-print-accounts.js @@ -0,0 +1,22 @@ +'use strict'; + +/** + * 外部打单账号增加 cookie 字段。 + * + * 用于存放该账号登录外部打单平台后的会话 cookie:由服务端登录成功后写回, + * 后续请求直接复用,避免会话上下文丢失或凭据散落在临时位置。 + * cookie 等同于登录态,接口不回显,仅服务端使用。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('external_print_accounts', 'cookie', { + type: Sequelize.TEXT, + allowNull: true, + comment: '外部打单平台会话 cookie(服务端登录后写回,接口不回显)', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('external_print_accounts', 'cookie'); + }, +}; diff --git a/backend/database/migrations/20261102000300-add-token-to-external-print-accounts.js b/backend/database/migrations/20261102000300-add-token-to-external-print-accounts.js new file mode 100644 index 0000000..2045ec1 --- /dev/null +++ b/backend/database/migrations/20261102000300-add-token-to-external-print-accounts.js @@ -0,0 +1,22 @@ +'use strict'; + +/** + * 外部打单账号增加 token 字段。 + * + * 店管家登录接口(/FFAccount/LoginPortal)返回的 Token 是访问工作台(fxali.dgjapp.com) + * 的必需凭据:仅有 cookie 无法打开登录后的页面,必须带上 token。 + * token 与 cookie 一样只由服务端保存和使用,接口不回显。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('external_print_accounts', 'token', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '外部打单平台登录 Token(服务端登录后写回,接口不回显)', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('external_print_accounts', 'token'); + }, +}; diff --git a/backend/database/migrations/20261102000400-add-login-status-to-external-print-accounts.js b/backend/database/migrations/20261102000400-add-login-status-to-external-print-accounts.js new file mode 100644 index 0000000..c7567b0 --- /dev/null +++ b/backend/database/migrations/20261102000400-add-login-status-to-external-print-accounts.js @@ -0,0 +1,23 @@ +'use strict'; + +/** + * 外部打单账号增加 login_status 字段。 + * + * 记录最近一次与平台交互的登录状态:1 已登录 / 0 未登录或已失效。 + * 由平台服务的统一请求入口维护:平台接口返回 401 时置 0,GetUserInfo 成功时置 1, + * 前端列表直接展示该状态,无需每次手动检查。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('external_print_accounts', 'login_status', { + type: Sequelize.TINYINT, + allowNull: false, + defaultValue: 0, + comment: '登录状态:1已登录 0未登录/已失效', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('external_print_accounts', 'login_status'); + }, +}; diff --git a/frontend/src/api/externalPrintAccount.ts b/frontend/src/api/externalPrintAccount.ts new file mode 100644 index 0000000..5d9c931 --- /dev/null +++ b/frontend/src/api/externalPrintAccount.ts @@ -0,0 +1,76 @@ +import { get, post, put, del } from '@/utils/request' +import type { ExternalPrintPlatformItem } from '@/api/externalPrintPlatform' + +export interface ExternalPrintAccountItem { + id: number + principal_id: number + platform_id: number + account: string + /** 后端不回显密码,仅标识是否已设置 */ + has_password: boolean + /** 后端不回显会话 cookie,仅标识是否已保存 */ + has_cookie?: boolean + /** 后端不回显登录 token,仅标识是否已保存 */ + has_token?: boolean + /** 登录状态:1 已登录 0 未登录/已失效(最近一次平台交互结果) */ + login_status: number + platform?: Pick | null + created_at?: string + updated_at?: string +} + +export interface ExternalPrintAccountPayload { + platform_id: number + account: string + /** 修改时留空表示不修改密码 */ + password?: string +} + +/** 当前主体下的外部打单账号列表 */ +export function getExternalPrintAccounts(params?: object) { + return get<{ list: ExternalPrintAccountItem[]; total: number; page: number; pageSize: number }>( + '/external-print-accounts', + params, + ) +} + +/** 新增外部打单账号 */ +export function createExternalPrintAccount(data: ExternalPrintAccountPayload & { password: string }) { + return post<{ id: number }>('/external-print-accounts', data) +} + +/** 修改外部打单账号(password 留空表示不修改) */ +export function updateExternalPrintAccount(id: number, data: ExternalPrintAccountPayload) { + return put<{ id: number }>(`/external-print-accounts/${id}`, data) +} + +/** 删除外部打单账号 */ +export function deleteExternalPrintAccount(id: number) { + return del<{ id: number }>(`/external-print-accounts/${id}`) +} + +export interface ExternalPrintAccountCheckResult { + logged_in: boolean + message: string + url?: string + /** 平台账号昵称(登录态有效时返回) */ + nickname?: string + /** 平台当前店铺名称(登录态有效时返回) */ + shop_name?: string +} + +/** 检查账号登录态:用已保存的 cookie 访问平台门户 */ +export function checkExternalPrintAccount(id: number) { + return post(`/external-print-accounts/${id}/check`, undefined, { + timeout: 60000, + }) +} + +/** 登录账号:cookie 有效时复用,否则用账号密码登录并把 cookie 写回 */ +export function loginExternalPrintAccount(id: number) { + return post<{ logged_in: boolean; reused: boolean; shop_name?: string }>( + `/external-print-accounts/${id}/login`, + undefined, + { timeout: 60000 }, + ) +} diff --git a/frontend/src/api/externalPrintPlatform.ts b/frontend/src/api/externalPrintPlatform.ts new file mode 100644 index 0000000..eac106f --- /dev/null +++ b/frontend/src/api/externalPrintPlatform.ts @@ -0,0 +1,20 @@ +import { get } from '@/utils/request' + +export interface ExternalPrintPlatformItem { + id: number + /** 平台标识,程序按此选择打单/取号适配逻辑 */ + code: string + name: string + url: string | null + /** 是否回打单平台取号:1 是 0 否 */ + fetch_waybill_no: number + sort: number + status: number + created_at?: string + updated_at?: string +} + +/** 外部打单平台字典(开发者维护,前端只读) */ +export function getExternalPrintPlatforms() { + return get('/external-print-platforms') +} diff --git a/frontend/src/store/menu.ts b/frontend/src/store/menu.ts index 7037ebf..bc8ff6d 100644 --- a/frontend/src/store/menu.ts +++ b/frontend/src/store/menu.ts @@ -51,6 +51,7 @@ const defaultMenus: MenuItem[] = [ id: 5, parent_id: 0, name: '店铺管理', type: 1, icon: 'Shop', sort: 85, status: 1, children: [ { id: 51, parent_id: 5, name: '店铺', type: 2, path: '/shop', icon: 'Shop', permission: 'shop:list', component: 'views/Shop/Index.vue', sort: 80, status: 1 }, + { id: 53, parent_id: 5, name: '外部打单平台', type: 2, path: '/external-print-platform', icon: 'Printer', permission: 'externalPrintAccount:list', component: 'views/ExternalPrintPlatform/Index.vue', sort: 70, status: 1 }, ], }, { id: 25, parent_id: 0, name: '外部仓库', type: 2, path: '/system/external-api', icon: 'Link', permission: 'principalExternalApi:list', component: 'views/ExternalApi/Index.vue', sort: 75, status: 1 }, diff --git a/frontend/src/views/ExternalPrintPlatform/Index.vue b/frontend/src/views/ExternalPrintPlatform/Index.vue new file mode 100644 index 0000000..474e568 --- /dev/null +++ b/frontend/src/views/ExternalPrintPlatform/Index.vue @@ -0,0 +1,351 @@ + + + + +