'use strict'; /** * @controller ExternalPrintAccountController 外部打单账号管理 * 账号归属主体,在前端「店铺管理 → 外部打单平台」维护(新增 / 修改 / 删除) */ 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; } /** 店铺类型:2 外部打单平台商家 */ const SHOP_TYPE_EXTERNAL = 2; /** 单品补拉时单次最多提交的商品数(订单明细一般远小于该值) */ const MAX_PULL_PRODUCT_ITEMS = 50; /** * 店铺商品唯一键(与店铺商品表的唯一索引对应) * @param {string} outerItemId 平台商品ID * @param {string|null} outerSkuId 平台规格ID * @return {string} 唯一键 */ function shopProductKey(outerItemId, outerSkuId) { return `${outerItemId || ''}|${outerSkuId || ''}`; } /** * 规划「平台规格ID 改键」 * * 平台规格ID 的口径变过(早期部分商品取了 `SpecId`,现在统一取 `SkuId`), * 重新拉取时这些老行的唯一键会对不上,如果按新键插入、老键又不在快照里, * 老行会被判成「平台已下架」而删除或下架(绑定关系、订单溯源都会丢)。 * 所以这里先按「商品ID + 规格名」认出是同一个 SKU,就地改掉老行的 `outer_sku_id`。 * * 只在两边都唯一命中时才改键(同名规格不猜),改键目标已被占用时也不动(交给常规 upsert)。 * @param {Array} rows 本次拉取并归一化的商品行(含 outer_item_id / outer_sku_id / spec) * @param {Array} existing 已有店铺商品行(含 id / outer_item_id / outer_sku_id / spec) * @return {Array<{id: number, outer_sku_id: string}>} 需要改键的行 */ function planShopProductRekey(rows, existing) { const existingKeys = new Set(existing.map(row => shopProductKey(row.outer_item_id, row.outer_sku_id))); const pending = rows.filter(row => !existingKeys.has(shopProductKey(row.outer_item_id, row.outer_sku_id))); if (!pending.length) return []; const groupBySpec = list => { const map = new Map(); for (const item of list) { const spec = String(item.spec == null ? '' : item.spec).trim(); if (!spec) continue; const key = `${item.outer_item_id || ''}|${spec}`; if (!map.has(key)) map.set(key, []); map.get(key).push(item); } return map; }; const existingBySpec = groupBySpec(existing); const pendingBySpec = groupBySpec(pending); const plan = []; for (const [ key, incoming ] of pendingBySpec) { const current = existingBySpec.get(key); if (!current || current.length !== 1 || incoming.length !== 1) continue; const target = current[0]; if (existingKeys.has(shopProductKey(target.outer_item_id, incoming[0].outer_sku_id))) continue; plan.push({ id: Number(target.id), outer_sku_id: String(incoming[0].outer_sku_id || '') }); } return plan; } /** 商品同步时允许更新的字段(新增行仍由 bulkCreate 写入) */ const SHOP_PRODUCT_UPSERT_FIELDS = [ 'subsidiary_id', 'title', 'outer_code', 'spec', 'image', 'price', 'stock', 'status', 'platform_type', 'external_shop_id', 'raw', 'synced_at', 'updated_at', ]; /** * 外部平台商家在 OMS 店铺表中的编码:平台标识-账号ID-商家ID(最多 50 字符) * @param {string} platformCode 平台标识 * @param {number} accountId 账号ID * @param {string} externalId 商家ID * @return {string} 店铺编码 */ function buildExternalShopCode(platformCode, accountId, externalId) { return `${platformCode}-${accountId}-${externalId}`.slice(0, 50); } 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); await ctx.service.cache.invalidateExternalPrintAccount(item.id); 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 }; } } /** * @summary 拉取账号在外部打单平台的店铺(商家)列表 * @description 实时向平台拉取并标记是否已创建到 OMS 店铺;不落库。前端按账号ID调用,不直连平台 * @router get /api/external-print-accounts/{id}/merchants * @apikey * @request path integer *id 账号主键ID * @request query integer page 页码,默认 1 * @request query integer pageSize 每页条数,默认 20 * @request query string keyword 关键词(商家名称/手机号) * @response 200 externalPrintMerchantListResponse success */ async merchants() { const { ctx } = this; const Op = this.app.Sequelize.Op; const account = await this.findAccount(ctx.params.id, { withPlatform: true }); if (!account) { ctx.status = 404; ctx.body = { code: 404, message: '打单账号不存在' }; return; } const { page, pageSize } = parsePagination(ctx.query); try { const service = this.createPlatformService(account); const result = await service.listShops({ pageIndex: page, pageSize, keyword: ctx.query.keyword || '', }); const platformCode = account.platform.code; const codes = result.list.map(item => buildExternalShopCode(platformCode, account.id, item.external_id)); const existing = codes.length ? await ctx.model.Shop.findAll({ where: { principal_id: ctx.state.principalId, code: { [Op.in]: codes } }, attributes: [ 'code' ], raw: true, }) : []; const added = new Set(existing.map(row => row.code)); const list = result.list.map(item => ({ ...item, added: added.has(buildExternalShopCode(platformCode, account.id, item.external_id)), })); ctx.body = { code: 0, message: 'success', data: buildPageResult(list, result.total, { page, pageSize }) }; } catch (err) { ctx.status = 400; ctx.body = { code: 400, message: err.message }; } } /** * @summary 刷新账号下店铺的「所在区」 * @description 一次拉取账号在平台的完整商家列表(同账号下多个店铺共享,只请求平台一次), * 把最新的商家结构(FxUserId、分区声明 DbAreas 等)写回店铺; * 商家已不在合作列表(解绑/停用)时把店铺自动禁用,之后不再参与自动拉单与一键拉单, * 需人工把店铺状态改回启用才会恢复 * @router post /api/external-print-accounts/{id}/refresh-shops-area * @apikey * @request path integer *id 账号主键ID * @response 200 shopAreaRefreshResponse success */ async refreshShopAreas() { 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 data = await ctx.service.shopAreaSync.refreshAccount(account); ctx.body = { code: 0, message: 'success', data }; } catch (err) { ctx.status = 400; ctx.body = { code: 400, message: err.message }; } } /** * @summary 把外部打单平台的店铺(商家)创建到 OMS 店铺 * @description merchants 为商家列表接口返回的项(含 raw),按 external_id 去重;已存在的跳过 * @router post /api/external-print-accounts/{id}/shops * @apikey * @request path integer *id 账号主键ID * @request body createShopsFromMerchantsRequest *body * @response 200 externalPrintShopCreateResponse success */ async createShops() { const { ctx } = this; const account = await this.findAccount(ctx.params.id, { withPlatform: true }); if (!account) { ctx.status = 404; ctx.body = { code: 404, message: '打单账号不存在' }; return; } const merchants = Array.isArray(ctx.request.body.merchants) ? ctx.request.body.merchants : []; if (!merchants.length) { ctx.status = 400; ctx.body = { code: 400, message: 'merchants 不能为空' }; return; } if (merchants.length > 200) { ctx.status = 400; ctx.body = { code: 400, message: '单次最多添加 200 个店铺' }; return; } const platformCode = account.platform.code; const principalId = ctx.state.principalId; // 添加店铺时必须选择货主(下属公司),货主权限据此判定店铺归属 const subsidiaryId = Number(ctx.request.body.subsidiary_id); if (!Number.isInteger(subsidiaryId) || subsidiaryId <= 0) { ctx.status = 400; ctx.body = { code: 400, message: '请选择所属货主(下属公司)' }; return; } const subsidiary = await ctx.model.PrincipalSubsidiary.findOne({ where: { id: subsidiaryId, principal_id: principalId }, attributes: [ 'id' ], }); if (!subsidiary) { ctx.status = 400; ctx.body = { code: 400, message: '所属货主不存在或不属于当前集团' }; return; } const created = []; const transaction = await ctx.model.transaction(); try { for (const item of merchants) { const externalId = String((item && item.external_id) || '').trim(); if (!externalId) continue; const code = buildExternalShopCode(platformCode, account.id, externalId); const exist = await ctx.model.Shop.findOne({ where: { principal_id: principalId, code }, transaction }); if (exist) continue; const shop = await ctx.model.Shop.create({ principal_id: principalId, subsidiary_id: subsidiaryId, code, name: String(item.name || '').trim() || code, platform: platformCode, contact_name: item.contact_name ? String(item.contact_name) : null, contact_phone: item.contact_phone ? String(item.contact_phone) : null, status: Number(item.status) === 0 ? 0 : 1, type: SHOP_TYPE_EXTERNAL, external_print_account_id: account.id, // 原样保存平台返回的商家完整结构(未带 raw 时退化为保存整条入参),后续按需取字段 external_data: item.raw || item, remark: item.remark ? String(item.remark).slice(0, 255) : null, }, { transaction }); created.push({ id: shop.id, code: shop.code, name: shop.name }); } await transaction.commit(); } catch (err) { await transaction.rollback(); ctx.status = 400; ctx.body = { code: 400, message: err.message }; return; } ctx.body = { code: 0, message: 'success', data: { created: created.length, skipped: merchants.length - created.length, shops: created }, }; } /** * @summary 同步外部打单平台商家的店铺商品 * @description 按商家的分区逐域名拉取全量商品快照,写入店铺商品表(shop_products); * 快照完整时把本次未出现的已采集商品直接移除(平台已下架/删除的商品无需在本地保留)。 * 前端按账号ID + 店铺ID调用,不直连平台 * @router post /api/external-print-accounts/{id}/shops/{shopId}/sync-products * @apikey * @request path integer *id 账号主键ID * @request path integer *shopId 店铺主键ID * @response 200 externalPrintShopProductSyncResponse success */ async syncShopProducts() { const { ctx } = this; const account = await this.findAccount(ctx.params.id, { withPlatform: true }); if (!account) { ctx.status = 404; ctx.body = { code: 404, message: '打单账号不存在' }; return; } const shop = await ctx.model.Shop.findOne({ where: { id: ctx.params.shopId, principal_id: ctx.state.principalId }, }); if (!shop) { ctx.status = 404; ctx.body = { code: 404, message: '店铺不存在' }; return; } if (Number(shop.type) !== SHOP_TYPE_EXTERNAL) { ctx.status = 400; ctx.body = { code: 400, message: '仅外部打单平台商家支持同步商品' }; return; } if (Number(shop.external_print_account_id) !== Number(account.id)) { ctx.status = 400; ctx.body = { code: 400, message: '该店铺不属于当前打单账号' }; return; } // 所在公司权限:仅可操作自己所属公司(货主)的店铺 const denied = await this.checkShopAccess(shop); if (denied) { ctx.status = denied.status; ctx.body = denied.body; return; } let snapshot; try { const service = this.createPlatformService(account); snapshot = await service.listProducts(shop.get({ plain: true })); } catch (err) { ctx.status = 400; ctx.body = { code: 400, message: err.message }; return; } try { const saved = await this.saveShopProducts(shop, snapshot); ctx.body = { code: 0, message: 'success', data: { total: snapshot.total, unique: saved.unique, created: saved.created, updated: saved.updated, rekeyed: saved.rekeyed || 0, removed: saved.removed, offline: saved.offline, verified: snapshot.verified, hosts: snapshot.hosts, }, }; } catch (err) { ctx.status = 500; ctx.body = { code: 500, message: `保存店铺商品失败:${err.message}` }; } } /** * @summary 按平台商品ID单独拉取店铺商品 * @description 订单明细匹配不到店铺商品时按需补拉:按平台商品ID(可选规格ID)在店铺所属分区及其它分区逐个查询, * 命中后写入店铺商品表并返回该商品;不会改动其它商品的下架状态 * @router post /api/external-print-accounts/{id}/shops/{shopId}/pull-products * @apikey * @request path integer *id 账号主键ID * @request path integer *shopId 店铺主键ID * @request body pullShopProductsRequest *body * @response 200 externalPrintShopProductPullResponse success */ async pullShopProducts() { const { ctx } = this; const account = await this.findAccount(ctx.params.id, { withPlatform: true }); if (!account) { ctx.status = 404; ctx.body = { code: 404, message: '打单账号不存在' }; return; } const shop = await ctx.model.Shop.findOne({ where: { id: ctx.params.shopId, principal_id: ctx.state.principalId }, }); if (!shop) { ctx.status = 404; ctx.body = { code: 404, message: '店铺不存在' }; return; } if (Number(shop.type) !== SHOP_TYPE_EXTERNAL) { ctx.status = 400; ctx.body = { code: 400, message: '仅外部打单平台商家支持拉取商品' }; return; } if (Number(shop.external_print_account_id) !== Number(account.id)) { ctx.status = 400; ctx.body = { code: 400, message: '该店铺不属于当前打单账号' }; return; } // 所在公司权限:仅可操作自己所属公司(货主)的店铺 const denied = await this.checkShopAccess(shop); if (denied) { ctx.status = denied.status; ctx.body = denied.body; return; } const body = ctx.request.body || {}; const items = (Array.isArray(body.items) ? body.items : []) .map(item => ({ outer_item_id: String((item && item.outer_item_id) || '').trim(), outer_sku_id: String((item && item.outer_sku_id) || '').trim(), })) .filter(item => item.outer_item_id); if (!items.length) { ctx.status = 400; ctx.body = { code: 400, message: 'items 不能为空(需传 outer_item_id)' }; return; } if (items.length > MAX_PULL_PRODUCT_ITEMS) { ctx.status = 400; ctx.body = { code: 400, message: `单次最多补拉 ${MAX_PULL_PRODUCT_ITEMS} 个商品` }; return; } let result; try { const service = this.createPlatformService(account); result = await service.listProductsByIds(shop.get({ plain: true }), items); } catch (err) { ctx.status = 400; ctx.body = { code: 400, message: err.message }; return; } let saved; try { // verified=false:单品补拉只做 upsert,不做移除处理,避免把其它商品误删 saved = await this.saveShopProducts(shop, { list: result.list, verified: false }); } catch (err) { ctx.status = 500; ctx.body = { code: 500, message: `保存店铺商品失败:${err.message}` }; return; } const savedRows = await this.findSavedShopProducts(shop.id, result.list); ctx.body = { code: 0, message: 'success', data: { requested: items.length, matched: result.list.length, created: saved.created, updated: saved.updated, rekeyed: saved.rekeyed || 0, hosts: result.hosts, missing: result.missing, products: savedRows, }, }; } /** * 回查刚写入的店铺商品(供前端直接拿到店铺商品ID去绑定) * @param {number} shopId 店铺ID * @param {Array} list 归一化后的商品行 * @return {Promise} 店铺商品关键字段 */ async findSavedShopProducts(shopId, list) { const { ctx } = this; const Op = this.app.Sequelize.Op; const outerIds = Array.from(new Set(list.map(item => item.outer_item_id).filter(Boolean))); if (!outerIds.length) return []; const keys = new Set(list.map(item => shopProductKey(item.outer_item_id, item.outer_sku_id))); const rows = await ctx.model.ShopProduct.findAll({ where: { shop_id: shopId, outer_item_id: { [Op.in]: outerIds } }, attributes: [ 'id', 'shop_id', 'outer_item_id', 'outer_sku_id', 'title', 'spec', 'platform_type', 'status', 'bind_type', 'product_id', 'combo_product_id' ], raw: true, }); return rows.filter(row => keys.has(shopProductKey(row.outer_item_id, row.outer_sku_id))); } /** * @summary 拉取外部打单平台商家的订单 * @description 按时间窗拉取平台订单(含明细)并写入 orders / order_items; * 明细按店铺商品匹配:店铺商品已绑定系统商品/组合商品的直接写入关联,未绑定的保留平台原样并标记为待处理 * @router post /api/external-print-accounts/{id}/shops/{shopId}/sync-orders * @apikey * @request path integer *id 账号主键ID * @request path integer *shopId 店铺主键ID * @request body syncShopOrdersRequest *body * @response 200 externalPrintShopOrderSyncResponse success */ async syncShopOrders() { const { ctx } = this; const account = await this.findAccount(ctx.params.id, { withPlatform: true }); if (!account) { ctx.status = 404; ctx.body = { code: 404, message: '打单账号不存在' }; return; } const shop = await ctx.model.Shop.findOne({ where: { id: ctx.params.shopId, principal_id: ctx.state.principalId }, }); if (!shop) { ctx.status = 404; ctx.body = { code: 404, message: '店铺不存在' }; return; } if (Number(shop.type) !== SHOP_TYPE_EXTERNAL) { ctx.status = 400; ctx.body = { code: 400, message: '仅外部打单平台商家支持拉取订单' }; return; } if (Number(shop.external_print_account_id) !== Number(account.id)) { ctx.status = 400; ctx.body = { code: 400, message: '该店铺不属于当前打单账号' }; return; } // 所在公司权限:仅可操作自己所属公司(货主)的店铺 const denied = await this.checkShopAccess(shop); if (denied) { ctx.status = denied.status; ctx.body = denied.body; return; } const body = ctx.request.body || {}; const days = Number(body.days); // days = 0(或 all=true)表示「全部待处理」:不限下单时间,由服务端按平台发货状态过滤, // 用于把店铺历史上积压的未发货订单一次性拉进来 const allPending = body.all === true || days === 0; const endTime = body.end_time ? new Date(body.end_time) : new Date(); // 「最近 N 天」按滚动时间窗计算(此刻往前 N×24 小时), // 不用「今天 00:00」对齐:凌晨拉单会只覆盖当天几小时,导致明明有待处理订单却提示 0 单 const startTime = body.start_time ? new Date(body.start_time) : allPending ? new Date('2018-01-01T00:00:00+08:00') : new Date(endTime.getTime() - Math.max(1, days || 1) * 86400000); if (Number.isNaN(startTime.getTime()) || Number.isNaN(endTime.getTime())) { ctx.status = 400; ctx.body = { code: 400, message: '时间格式不正确' }; return; } let saved; try { saved = await ctx.service.externalPrintOrder.syncOrders(shop, account, { startTime, endTime, }); } catch (err) { ctx.status = 400; ctx.body = { code: 400, message: err.message }; return; } await ctx.service.externalPrintOrder.markShopSynced( shop, new Date(), `手动拉取成功:${saved.orders} 单,跳过平台已发货 ${saved.skipped || 0} 单,自动作废 ${saved.voided || 0} 单` + (saved.voidedMissing ? `(其中平台已查不到 ${saved.voidedMissing} 单)` : '') ); ctx.body = { code: 0, message: 'success', data: { start_time: saved.startTime, end_time: saved.endTime, orders: saved.orders, skipped: saved.skipped || 0, voided: saved.voided || 0, voided_shipped: saved.voidedShipped || 0, voided_missing: saved.voidedMissing || 0, created: saved.created, updated: saved.updated, items: saved.items, items_bound: saved.itemsBound, items_unbound: saved.itemsUnbound, hosts: saved.hosts, }, }; } /** * 把商品快照写入店铺商品表:按唯一键 upsert,快照完整时把本次未出现的商品移除(下架)。 * 未绑定且未被订单引用的直接删除;已绑定或被订单引用的只标为下架,避免丢配置、断溯源。 * 快照不完整(平台分页前后数据不一致)时只更新,不做移除处理,避免误删。 * @param {Object} shop 店铺实例 * @param {Object} snapshot 平台商品快照 * @return {Promise<{unique: number, created: number, updated: number, rekeyed: number, removed: number, offline: number}>} 写入结果 */ async saveShopProducts(shop, snapshot) { const { ctx } = this; const Op = this.app.Sequelize.Op; const now = new Date(); const existing = await ctx.model.ShopProduct.findAll({ where: { shop_id: shop.id }, attributes: [ 'id', 'outer_item_id', 'outer_sku_id', 'spec', 'synced_at' ], raw: true, }); const rows = snapshot.list .filter(item => item.outer_item_id) .map(item => ({ principal_id: shop.principal_id, subsidiary_id: shop.subsidiary_id, shop_id: shop.id, outer_item_id: item.outer_item_id, outer_sku_id: item.outer_sku_id || '', title: item.title || null, outer_code: item.outer_code || null, spec: item.spec || null, image: item.image || null, price: item.price, stock: item.stock, status: item.status, platform_type: item.platform_type || null, external_shop_id: item.external_shop_id || null, raw: item.raw, synced_at: now, created_at: now, updated_at: now, })); // 平台规格ID 口径变更(SpecId → SkuId):同一个 SKU 就地改键,保住绑定关系与订单溯源 const rekey = planShopProductRekey(rows, existing); const rekeyMap = new Map(rekey.map(item => [ item.id, item.outer_sku_id ])); const effectiveExisting = rekeyMap.size ? existing.map(row => (rekeyMap.has(Number(row.id)) ? { ...row, outer_sku_id: rekeyMap.get(Number(row.id)) } : row)) : existing; const existingKeys = new Set(effectiveExisting.map(row => shopProductKey(row.outer_item_id, row.outer_sku_id))); let created = 0; let updated = 0; for (const row of rows) { if (existingKeys.has(shopProductKey(row.outer_item_id, row.outer_sku_id))) updated++; else created++; } let removed = 0; let offline = 0; const transaction = await ctx.model.transaction(); try { // 先改键,再 upsert:否则老键那行会被当成"平台已消失" for (const item of rekey) { await ctx.model.ShopProduct.update( { outer_sku_id: item.outer_sku_id, synced_at: now, updated_at: now }, { where: { id: item.id }, transaction } ); } if (rekey.length) { ctx.logger.info('[shop-product] 店铺 %d 按 SkuId 校正平台规格ID %d 行', shop.id, rekey.length); } if (rows.length) { await ctx.model.ShopProduct.bulkCreate(rows, { transaction, updateOnDuplicate: SHOP_PRODUCT_UPSERT_FIELDS, }); } // 操作记录:本次新采集进系统的商品(什么时候、从哪个店铺采集的) const existingIdSet = new Set(existing.map(row => Number(row.id))); const afterRows = await ctx.model.ShopProduct.findAll({ where: { shop_id: shop.id }, attributes: [ 'id', 'outer_item_id', 'outer_sku_id', 'title' ], raw: true, transaction, }); const createdRows = afterRows.filter(row => !existingIdSet.has(Number(row.id))); if (createdRows.length) { await ctx.service.operationLog.recordMany( createdRows.map(row => ({ targetType: 'shop_product', targetId: row.id, action: 'create', title: this.shopProductLogTitle('采集到系统', row), detail: { shop_id: shop.id, shop_name: shop.name, outer_item_id: row.outer_item_id, outer_sku_id: row.outer_sku_id, }, })), { transaction, source: 'sync' } ); } if (snapshot.verified) { const syncedKeys = new Set(rows.map(row => shopProductKey(row.outer_item_id, row.outer_sku_id))); const staleIds = effectiveExisting .filter(row => row.synced_at && !syncedKeys.has(shopProductKey(row.outer_item_id, row.outer_sku_id))) .map(row => row.id); if (staleIds.length) { // 平台已不存在该商品:未被使用的直接移除,避免本地留着无法再匹配订单的僵尸数据; // 已绑定系统商品/组合商品、或被订单明细引用的保留(删除会丢绑定配置、断掉订单溯源),只标为下架 const keepIds = new Set(); const boundRows = await ctx.model.ShopProduct.findAll({ where: { id: { [Op.in]: staleIds } }, attributes: [ 'id', 'bind_type' ], raw: true, transaction, }); for (const row of boundRows) { if (Number(row.bind_type) !== 0) keepIds.add(Number(row.id)); } const referenced = await ctx.model.OrderStatusItem.findAll({ where: { shop_product_id: { [Op.in]: staleIds } }, attributes: [ 'shop_product_id' ], group: [ 'shop_product_id' ], raw: true, transaction, }); for (const row of referenced) { if (row.shop_product_id != null) keepIds.add(Number(row.shop_product_id)); } const deleteIds = staleIds.filter(id => !keepIds.has(Number(id))); const offlineIds = staleIds.filter(id => keepIds.has(Number(id))); // 取被移除/下架行的标题,写清是哪件商品(删除后查不到,必须先取) const staleRows = await ctx.model.ShopProduct.findAll({ where: { id: { [Op.in]: staleIds } }, attributes: [ 'id', 'outer_item_id', 'outer_sku_id', 'title' ], raw: true, transaction, }); const staleMap = new Map(staleRows.map(row => [ Number(row.id), row ])); if (deleteIds.length) { await ctx.model.ShopProduct.destroy({ where: { id: deleteIds }, transaction }); removed = deleteIds.length; await ctx.service.operationLog.recordMany( deleteIds.map(id => ({ targetType: 'shop_product', targetId: id, action: 'remove', title: this.shopProductLogTitle('平台已无此商品,已移出系统', staleMap.get(Number(id))), detail: { shop_id: shop.id, shop_name: shop.name, reason: '平台快照中已不存在' }, })), { transaction, source: 'sync' } ); } if (offlineIds.length) { await ctx.model.ShopProduct.update( { status: 0, synced_at: now, updated_at: now }, { where: { id: offlineIds }, transaction } ); offline = offlineIds.length; await ctx.service.operationLog.recordMany( offlineIds.map(id => ({ targetType: 'shop_product', targetId: id, action: 'offline', title: this.shopProductLogTitle('平台已无此商品,因已绑定或被订单引用,已保留并置为下架', staleMap.get(Number(id))), detail: { shop_id: shop.id, shop_name: shop.name, reason: '平台快照中已不存在,保留记录' }, })), { transaction, source: 'sync' } ); } } } await transaction.commit(); } catch (err) { await transaction.rollback(); throw err; } return { unique: rows.length, created, updated, rekeyed: rekey.length, removed, offline }; } /** * 规划「平台规格ID 改键」:同一个 SKU 换了 outer_sku_id 口径(早期用 SpecId、统一后用 SkuId)时, * 就地改掉老行的 `outer_sku_id`,而不是插入新行再让老行被判成「平台已下架」。 * @param {Array} rows 本次拉取并归一化的商品行 * @param {Array} existing 已有店铺商品行 * @return {Array<{id: number, outer_sku_id: string}>} 需要改键的行 */ static planShopProductRekey(rows, existing) { return planShopProductRekey(rows, existing); } /** * 生成店铺商品日志标题(商品标题 + 平台商品ID/规格ID) * @param {string} prefix 动作说明 * @param {Object} row 店铺商品行(title / outer_item_id / outer_sku_id) * @return {string} 标题 */ shopProductLogTitle(prefix, row) { const data = row || {}; const name = data.title || data.outer_item_id || ''; const spec = data.outer_sku_id ? `,规格 ${data.outer_sku_id}` : ''; return `${prefix}:${name}(平台商品ID ${data.outer_item_id || '-'}${spec})`; } /** * 取当前主体下的账号。 * 资源不存在时 principalCheck 不会写入主体ID(交由控制器返回 404),此时直接返回 null, * 避免把 undefined 传给 Sequelize 导致 500。 * @param {number|string} id 账号ID * @param {Object} [options] withPlatform 为 true 时一并带出平台配置 * @return {Promise} 账号实例 */ /** * 所在公司权限:校验店铺是否属于自己所属公司(货主) * @param {Object} shop 店铺 model 实例 * @return {Promise<{status: number, body: Object}|null>} 无权限时返回错误响应 */ async checkShopAccess(shop) { const { ctx } = this; const access = await ctx.service.access.resolve(ctx.userId, shop.principal_id); if (access.isGroup) return null; const ownIds = access.ownCompanyIds.map(Number); if (shop.subsidiary_id == null || !ownIds.includes(Number(shop.subsidiary_id))) { return { status: 403, body: { code: 403, message: '仅可操作自己所属公司(货主)的店铺' } }; } return null; } 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(); await ctx.service.cache.invalidateExternalPrintAccount(item.id); ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } }; } } module.exports = ExternalPrintAccountController;