'use strict'; const { Service } = require('egg'); /** * 店铺默认发货仓库服务 * * 店铺可配置「默认发货仓库」(shops.default_warehouse_id,取自店铺所属货主的仓库): * - 拉取订单(打单平台 / 数据库店铺)写入待审核时自动带上该仓库; * - 旧配置修改后,把该店铺尚未审核的订单回填为新仓库。 */ class ShopWarehouseService extends Service { /** * 读取店铺的默认发货仓库 * * 仓库必须仍然存在、启用,且与店铺同货主;否则视为未配置(返回 null), * 避免店铺货主变更或仓库停用后写入越权/无效的仓库。 * @param {Object} shop 店铺实例或纯对象(需含 principal_id / subsidiary_id / default_warehouse_id) * @return {Promise<{id: number, code: string, name: string}|null>} 默认仓库,未配置或失效时为 null */ async resolveDefault(shop) { const { ctx } = this; const warehouseId = Number(shop && shop.default_warehouse_id); if (!Number.isInteger(warehouseId) || warehouseId <= 0) return null; const where = { id: warehouseId, principal_id: Number(shop.principal_id), status: 1 }; if (shop.subsidiary_id != null) where.subsidiary_id = Number(shop.subsidiary_id); const warehouse = await ctx.model.Warehouse.findOne({ where, attributes: [ 'id', 'code', 'name' ], }); return warehouse ? { id: Number(warehouse.id), code: warehouse.code, name: warehouse.name } : null; } /** * 待审核订单的仓库回填条件:仓库为空,或仍是旧默认仓库(用户没手工改过) * @param {Object} Op Sequelize 操作符 * @param {number|null} previousWarehouseId 变更前的默认仓库ID * @return {Object} where 片段 */ pendingWarehouseScope(Op, previousWarehouseId) { const previous = Number(previousWarehouseId); if (!Number.isInteger(previous) || previous <= 0) return { warehouse_id: null }; return { [Op.or]: [{ warehouse_id: null }, { warehouse_id: previous }] }; } /** * 把店铺的默认发货仓库回填到该店铺「未审核(待审核)」的订单 * @param {Object} shop 店铺实例或纯对象 * @param {Object} [options] 参数 * @param {number|null} [options.previousWarehouseId] 变更前的默认仓库ID(这些订单也会被改成新仓库) * @return {Promise<{updated: number, warehouse: Object|null}>} 更新条数与生效仓库 */ async applyToPendingOrders(shop, { previousWarehouseId = null } = {}) { const { ctx } = this; const Op = this.app.Sequelize.Op; const warehouse = await this.resolveDefault(shop); if (!warehouse) return { updated: 0, warehouse: null }; const where = { principal_id: Number(shop.principal_id), shop_id: Number(shop.id), ...this.pendingWarehouseScope(Op, previousWarehouseId), }; const [ updated ] = await ctx.model.OrderStatusPending.update( { warehouse_id: warehouse.id, warehouse_code: warehouse.code }, { where } ); return { updated: Number(updated) || 0, warehouse }; } } module.exports = ShopWarehouseService;