'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;