feat(shop): 店铺支持设置默认发货仓库,拉单与未审核订单自动带仓库

- shops 新增 default_warehouse_id(迁移 + 模型 + 契约),仓库须存在、启用且属于店铺货主

- 新增 PUT /api/shops/:id/default-warehouse 单独维护该字段,外部打单平台店铺的货主权限也可配置

- 新增 shopWarehouse 服务:保存后把该店铺待审核订单中仓库为空或是旧默认值的订单回填为新仓库(手工改过的不覆盖)

- 打单平台与数据库店铺拉单落待审核时自动带上默认仓库(含 warehouse_code 快照);一键拉单店铺查询补 default_warehouse_id

- 前端:店铺列表新增「默认仓库」列与配置弹窗,新增/编辑表单增加默认发货仓库下拉(按货主过滤),详情面板展示

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-06 22:23:23 +08:00
parent fe97be2893
commit 74ddeca3c0
11 changed files with 437 additions and 10 deletions

View File

@ -48,6 +48,8 @@ const shopItem = {
principal_id: { type: 'integer', description: '所属主体ID' },
subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID)' },
subsidiary_name: { type: 'string', description: '所属货主名称' },
default_warehouse_id: { type: 'integer', description: '默认发货仓库ID(须属于店铺货主;拉单与未审核订单默认用该仓库)' },
default_warehouse_name: { type: 'string', description: '默认发货仓库名称(编码 + 名称)' },
code: { type: 'string', description: '店铺编码(平台店铺ID / 自定义编码 / OMS 前缀自动生成)' },
name: { type: 'string', description: '店铺名称' },
platform: { type: 'string', description: '所属平台:taobao/pdd/douyin/jd/other' },
@ -1175,6 +1177,7 @@ module.exports = {
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
auto_fetch_order: { type: 'integer', description: '是否自动拉取订单:1是 0否,默认0' },
auto_fetch_interval: { type: 'integer', description: '自动拉取订单间隔(分钟,最小 3),默认3' },
default_warehouse_id: { type: 'integer', description: '默认发货仓库ID,须属于店铺货主且启用;不传或 null 表示不设置' },
extra: { type: 'string', description: '扩展配置 JSON' },
remark: { type: 'string', description: '备注' },
},
@ -1188,11 +1191,15 @@ module.exports = {
status: { type: 'integer', description: '状态:1启用 0禁用' },
auto_fetch_order: { type: 'integer', description: '是否自动拉取订单:1是 0否' },
auto_fetch_interval: { type: 'integer', description: '自动拉取订单间隔(分钟,最小 3)' },
default_warehouse_id: { type: 'integer', description: '默认发货仓库ID,须属于店铺货主且启用;null 表示清除' },
last_order_sync_at: { type: 'string', description: '最近一次拉取订单时间(系统写入)' },
last_order_sync_msg: { type: 'string', description: '最近一次拉取订单结果/失败原因(系统写入)' },
extra: { type: 'string', description: '扩展配置 JSON' },
remark: { type: 'string', description: '备注' },
},
setShopDefaultWarehouseRequest: {
default_warehouse_id: { type: 'integer', description: '默认发货仓库ID,须属于店铺货主且启用;传 null 清除设置' },
},
// ---------- 数据库店铺配置 shop_database_configs ----------
/** 数据库店铺字段映射:OMS 字段 key → 源表列名 */

View File

@ -119,6 +119,7 @@ class ShopController extends Controller {
order: [[ 'id', 'DESC' ]],
include: [
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
{ model: ctx.model.Warehouse, as: 'defaultWarehouse', attributes: [ 'id', 'code', 'name' ], required: false },
],
});
@ -127,6 +128,10 @@ class ShopController extends Controller {
const plain = row.get({ plain: true });
plain.has_db_password = !!plain.db_password;
plain.subsidiary_name = plain.subsidiary ? plain.subsidiary.name : '';
plain.default_warehouse_name = plain.defaultWarehouse
? (plain.defaultWarehouse.code ? `${plain.defaultWarehouse.code} ${plain.defaultWarehouse.name}` : plain.defaultWarehouse.name)
: '';
delete plain.defaultWarehouse;
delete plain.db_password;
return plain;
});
@ -148,6 +153,7 @@ class ShopController extends Controller {
const shop = await ctx.model.Shop.findByPk(ctx.params.id, {
include: [
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
{ model: ctx.model.Warehouse, as: 'defaultWarehouse', attributes: [ 'id', 'code', 'name' ], required: false },
],
});
@ -181,6 +187,10 @@ class ShopController extends Controller {
const data = shop.get({ plain: true });
data.has_db_password = !!data.db_password;
data.subsidiary_name = data.subsidiary ? data.subsidiary.name : '';
data.default_warehouse_name = data.defaultWarehouse
? (data.defaultWarehouse.code ? `${data.defaultWarehouse.code} ${data.defaultWarehouse.name}` : data.defaultWarehouse.name)
: '';
delete data.defaultWarehouse;
delete data.db_password;
ctx.body = {
@ -269,6 +279,15 @@ class ShopController extends Controller {
delete body.db_username;
delete body.db_password;
// 默认发货仓库:必须是店铺货主(下属公司)下启用的仓库
const defaultWarehouse = await this.resolveDefaultWarehouseId(body.default_warehouse_id, subsidiary.value, principalId);
if (!defaultWarehouse.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: defaultWarehouse.message };
return;
}
body.default_warehouse_id = defaultWarehouse.value == null ? null : defaultWarehouse.value;
// 店铺类型:不传默认平台店铺;数据库店铺的连接信息在「配置」弹窗单独维护
let shopType = SHOP_TYPE_PLATFORM;
if (body.type !== undefined && body.type !== null && body.type !== '') {
@ -342,6 +361,32 @@ class ShopController extends Controller {
return (access.ownCompanyIds || []).map(Number).includes(Number(subsidiaryId));
}
/**
* 校验「默认发货仓库」:必须存在、启用,且属于店铺所属货主
* @param {number|string|null|undefined} value 前端传入的 default_warehouse_id
* @param {number|null} subsidiaryId 店铺所属货主
* @param {number} principalId 当前主体ID
* @return {Promise<{ok: boolean, value?: number|null, message?: string}>} 校验结果(value 为 null 表示清空)
*/
async resolveDefaultWarehouseId(value, subsidiaryId, principalId) {
if (value === null || value === '') return { ok: true, value: null };
if (value === undefined) return { ok: true, value: undefined };
const id = Number(value);
if (!Number.isInteger(id) || id <= 0) return { ok: false, message: '默认发货仓库不合法' };
const warehouse = await this.ctx.model.Warehouse.findOne({
where: { id, principal_id: principalId, status: 1 },
attributes: [ 'id', 'subsidiary_id' ],
});
if (!warehouse) return { ok: false, message: '默认发货仓库不存在或已停用' };
if (subsidiaryId != null && warehouse.subsidiary_id != null
&& Number(warehouse.subsidiary_id) !== Number(subsidiaryId)) {
return { ok: false, message: '默认发货仓库不属于该店铺的货主,请选择同货主的仓库' };
}
return { ok: true, value: id };
}
/**
* 判断店铺是否为外部打单平台导入的店铺
* @param {Object} shop 店铺 model 实例
@ -453,6 +498,25 @@ class ShopController extends Controller {
delete ctx.request.body.last_order_sync_at;
delete ctx.request.body.last_order_sync_msg;
// 默认发货仓库:必须是(变更后的)店铺货主下启用的仓库;显式传空表示清除
const previousWarehouseId = shop.default_warehouse_id == null ? null : Number(shop.default_warehouse_id);
let warehouseChanged = false;
if (ctx.request.body.default_warehouse_id !== undefined) {
const effectiveSubsidiary = ctx.request.body.subsidiary_id ?? shop.subsidiary_id;
const resolvedWarehouse = await this.resolveDefaultWarehouseId(
ctx.request.body.default_warehouse_id,
effectiveSubsidiary == null ? null : Number(effectiveSubsidiary),
shop.principal_id
);
if (!resolvedWarehouse.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: resolvedWarehouse.message };
return;
}
ctx.request.body.default_warehouse_id = resolvedWarehouse.value;
warehouseChanged = Number(resolvedWarehouse.value || 0) !== Number(previousWarehouseId || 0);
}
const autoFetch = parseAutoFetchConfig(ctx.request.body);
if (autoFetch.error) {
ctx.status = 400;
@ -506,7 +570,75 @@ class ShopController extends Controller {
}
// 店铺资料变更:清掉推送/取号用的店铺基础缓存
await ctx.service.cache.invalidateShop(shop.id);
ctx.body = { code: 0, message: 'success', data: { id: shop.id, code: shop.code } };
// 默认发货仓库变更:把尚未审核的订单回填为新仓库(未手工改过仓库的)
let pendingUpdated = 0;
if (warehouseChanged) {
const applied = await ctx.service.shopWarehouse.applyToPendingOrders(shop, { previousWarehouseId });
pendingUpdated = applied.updated;
}
ctx.body = {
code: 0,
message: 'success',
data: { id: shop.id, code: shop.code, pending_orders_updated: pendingUpdated },
};
}
/**
* @summary 设置店铺默认发货仓库
* @description 单独维护「默认发货仓库」(外部打单平台店铺所在的公司在只读模式下也可配置):
* 仓库必须属于店铺货主且启用;保存后同时回填该店铺尚未审核订单的发货仓库
* @router put /api/shops/{id}/default-warehouse
* @apikey
* @request path integer *id 店铺主键ID
* @request body setShopDefaultWarehouseRequest *body
* @response 200 baseResponse success
*/
async setDefaultWarehouse() {
const { ctx } = this;
const shop = await ctx.model.Shop.findByPk(ctx.params.id);
if (!shop) {
ctx.status = 404;
ctx.body = { code: 404, message: '店铺不存在' };
return;
}
// 所在公司权限:仅可维护自己所属公司(货主)的店铺;集团权限不限
if (!(await this.canAccess(ctx, shop))) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可维护自己所属公司(货主)的店铺' };
return;
}
const body = ctx.request.body || {};
const resolved = await this.resolveDefaultWarehouseId(
body.default_warehouse_id,
shop.subsidiary_id == null ? null : Number(shop.subsidiary_id),
shop.principal_id
);
if (!resolved.ok) {
ctx.status = 400;
ctx.body = { code: 400, message: resolved.message };
return;
}
if (resolved.value === undefined) {
ctx.status = 400;
ctx.body = { code: 400, message: 'default_warehouse_id 不能为空(清除请传 null)' };
return;
}
const previousWarehouseId = shop.default_warehouse_id == null ? null : Number(shop.default_warehouse_id);
await shop.update({ default_warehouse_id: resolved.value });
await ctx.service.cache.invalidateShop(shop.id);
// 未审核订单跟随新的默认仓库(未手工改过仓库的)
const applied = await ctx.service.shopWarehouse.applyToPendingOrders(shop, { previousWarehouseId });
ctx.body = {
code: 0,
message: 'success',
data: {
id: Number(shop.id),
default_warehouse_id: shop.default_warehouse_id == null ? null : Number(shop.default_warehouse_id),
pending_orders_updated: applied.updated,
},
};
}
/**

View File

@ -12,6 +12,7 @@ module.exports = app => {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
subsidiary_id: { type: BIGINT.UNSIGNED, comment: '所属货主(下属公司ID)' },
default_warehouse_id: { type: BIGINT.UNSIGNED, comment: '默认发货仓库ID(须属于店铺货主,拉单/未审核订单默认用该仓库)' },
code: { type: STRING(50), allowNull: false, comment: '店铺编码(平台店铺ID或自定义编码,OMS 内新建时按 OMS 前缀自动生成)' },
name: { type: STRING(100), allowNull: false, comment: '店铺名称' },
platform: { type: STRING(50), comment: '所属平台:taobao/pdd/douyin/jd/other' },
@ -40,6 +41,7 @@ module.exports = app => {
app.model.Shop.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
app.model.Shop.belongsTo(app.model.PrincipalSubsidiary, { foreignKey: 'subsidiary_id', as: 'subsidiary' });
app.model.Shop.belongsTo(app.model.ExternalPrintAccount, { foreignKey: 'external_print_account_id', as: 'externalPrintAccount' });
app.model.Shop.belongsTo(app.model.Warehouse, { foreignKey: 'default_warehouse_id', as: 'defaultWarehouse' });
app.model.Shop.hasMany(app.model.ShopProduct, { foreignKey: 'shop_id', as: 'shopProducts' });
app.model.Shop.hasMany(app.model.Order, { foreignKey: 'shop_id', as: 'orders' });
app.model.Shop.hasMany(app.model.OrderItem, { foreignKey: 'shop_id', as: 'orderItems' });

View File

@ -160,6 +160,8 @@ module.exports = app => {
// 数据库店铺拉取(服务端连客户库):店铺商品 / 订单
router.post('/api/shops/:id/database-config/pull-products', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.pullProducts);
router.post('/api/shops/:id/database-config/pull-orders', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.pullOrders);
// 店铺默认发货仓库:单独维护(外部打单平台店铺的所在公司权限也可配置),需在 resources('shops') 之前注册
router.put('/api/shops/:id/default-warehouse', jwtAuth, principalCheck({ model: 'Shop' }), controller.shop.setDefaultWarehouse);
router.resources('shops', '/api/shops', jwtAuth, principalCheck({ model: 'Shop' }), controller.shop);
// 店铺商品完全来自平台采集:不提供手工新增 / 编辑 / 删除,只保留查询与绑定;
// 同步商品时平台已不存在的商品会自动移除

View File

@ -391,6 +391,8 @@ class ExternalPrintOrderService extends Service {
async saveOrders(shop, account, list) {
const { ctx } = this;
const now = new Date();
// 店铺配置了默认发货仓库时,新拉进来的待审核订单直接落到该仓库
const defaultWarehouse = await ctx.service.shopWarehouse.resolveDefault(shop);
let created = 0;
let updated = 0;
let items = 0;
@ -501,7 +503,7 @@ class ExternalPrintOrderService extends Service {
}
// 同步写入「待审核」状态表:订单页(待审核/待推送…)读取的是状态分表,不写这里列表看不到
await this.saveOrderToPending(shop, account, item, resolvedLines, transaction);
await this.saveOrderToPending(shop, account, item, resolvedLines, transaction, defaultWarehouse);
}
await transaction.commit();
@ -522,9 +524,10 @@ class ExternalPrintOrderService extends Service {
* @param {Object} item 平台订单
* @param {Array} resolvedLines 已解析的明细(line / externalItemId / matched / bound)
* @param {Object} transaction 事务
* @param {Object|null} [defaultWarehouse] 店铺默认发货仓库(id / code),未配置为 null
* @return {Promise<void>} 无返回值
*/
async saveOrderToPending(shop, account, item, resolvedLines, transaction) {
async saveOrderToPending(shop, account, item, resolvedLines, transaction, defaultWarehouse = null) {
const { ctx } = this;
const externalOrderId = String(item.external_order_id || '').trim();
const lines = resolvedLines || [];
@ -578,6 +581,11 @@ class ExternalPrintOrderService extends Service {
},
};
// 店铺配置了默认发货仓库时带入(已有仓库的订单不覆盖,避免打乱用户手工设置)
const defaultWarehouseFields = defaultWarehouse
? { warehouse_id: defaultWarehouse.id, warehouse_code: defaultWarehouse.code }
: {};
let index = await ctx.model.OrderIndex.findOne({
where: { principal_id: shop.principal_id, parent_order_no: externalOrderId },
transaction,
@ -589,7 +597,8 @@ class ExternalPrintOrderService extends Service {
// 已流转出待审核(待推送/异常/委外中/配送…)时保持现状
if (!pending) return;
orderId = index.id;
await pending.update(fields, { transaction });
const keepWarehouse = pending.warehouse_id != null && Number(pending.warehouse_id) > 0;
await pending.update({ ...fields, ...(keepWarehouse ? {} : defaultWarehouseFields) }, { transaction });
} else {
const orderNo = truncateText(`${account.platform.code}-${externalOrderId}`, 50);
index = await ctx.model.OrderIndex.create({
@ -603,6 +612,7 @@ class ExternalPrintOrderService extends Service {
orderId = index.id;
await ctx.model.OrderStatusPending.create({
...fields,
...defaultWarehouseFields,
id: orderId,
order_no: orderNo,
parent_order_no: externalOrderId,

View File

@ -91,7 +91,7 @@ class OrderSyncTaskService extends Service {
// 少查会让 syncOrders 收到缺字段的店铺实例,直接报「店铺缺少商家 FxUserId」
attributes: [
'id', 'code', 'name', 'principal_id', 'type', 'subsidiary_id',
'external_print_account_id', 'external_data',
'external_print_account_id', 'external_data', 'default_warehouse_id',
],
order: [[ 'id', 'ASC' ]],
limit: MAX_SHOPS,

View File

@ -369,6 +369,11 @@ class ShopDatabaseSyncService extends Service {
const totalAmount = orderRow.total_amount == null || orderRow.total_amount === ''
? Number(itemAmount.toFixed(2))
: Number(orderRow.total_amount);
// 店铺配置了默认发货仓库时,新拉进来的待审核订单直接落到该仓库
const defaultWarehouse = await ctx.service.shopWarehouse.resolveDefault(shop);
const defaultWarehouseFields = defaultWarehouse
? { warehouse_id: defaultWarehouse.id, warehouse_code: defaultWarehouse.code }
: {};
const transaction = await ctx.model.transaction();
try {
@ -444,7 +449,13 @@ class ShopDatabaseSyncService extends Service {
}
if (indexRow) {
orderId = indexRow.id;
await ctx.model.OrderStatusPending.update(headFields, { where: { id: orderId }, transaction });
const pending = await ctx.model.OrderStatusPending.findByPk(orderId, { transaction });
// 已有发货仓库的订单不覆盖,保留用户手工设置
const keepWarehouse = !!pending && pending.warehouse_id != null && Number(pending.warehouse_id) > 0;
await ctx.model.OrderStatusPending.update(
{ ...headFields, ...(keepWarehouse ? {} : defaultWarehouseFields) },
{ where: { id: orderId }, transaction }
);
} else {
const index = await ctx.model.OrderIndex.create({
order_no: orderNo,
@ -457,6 +468,7 @@ class ShopDatabaseSyncService extends Service {
orderId = index.id;
await ctx.model.OrderStatusPending.create({
...headFields,
...defaultWarehouseFields,
id: orderId,
order_no: orderNo,
parent_order_no: sourceOrderNo,

View File

@ -0,0 +1,73 @@
'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;

View File

@ -0,0 +1,27 @@
'use strict';
/**
* 店铺增加「默认发货仓库」。
*
* 取值来自店铺所属货主(下属公司)的仓库;设置后:
* - 拉取订单(打单平台 / 数据库店铺)落待审核时自动带上该仓库;
* - 该店铺尚未审核的订单也会回填为该仓库(已有仓库且不是旧默认值的保持不动)。
*/
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn('shops', 'default_warehouse_id', {
type: Sequelize.BIGINT.UNSIGNED,
allowNull: true,
comment: '默认发货仓库ID(关联 warehouses,须属于店铺货主)',
after: 'subsidiary_id',
});
await queryInterface.addIndex('shops', [ 'default_warehouse_id' ], {
name: 'idx_shops_default_warehouse',
});
},
async down(queryInterface) {
await queryInterface.removeIndex('shops', 'idx_shops_default_warehouse');
await queryInterface.removeColumn('shops', 'default_warehouse_id');
},
};

View File

@ -7,6 +7,10 @@ export interface ShopItem {
subsidiary_id?: number | null
/** 所属货主名称(列表返回) */
subsidiary_name?: string
/** 默认发货仓库ID(须属于店铺货主) */
default_warehouse_id?: number | null
/** 默认发货仓库名称(列表/详情返回,编码 + 名称) */
default_warehouse_name?: string
code: string
name: string
platform: string | null
@ -48,6 +52,8 @@ export interface ShopPayload {
code?: string
/** 所属货主(下属公司ID),新增必填 */
subsidiary_id?: number | null
/** 默认发货仓库ID(须属于店铺货主),传 null 清除 */
default_warehouse_id?: number | null
name: string
platform?: string
/** 店铺类型:1 平台店铺(默认)/ 3 数据库店铺 */
@ -96,7 +102,15 @@ export function createShop(data: ShopPayload) {
/** 更新店铺 */
export function updateShop(id: number, data: Partial<ShopPayload>) {
return put<{ id: number }>(`/shops/${id}`, data)
return put<{ id: number; pending_orders_updated?: number }>(`/shops/${id}`, data)
}
/** 设置店铺默认发货仓库(外部打单平台店铺的所在公司权限也可维护;null 表示清除) */
export function setShopDefaultWarehouse(id: number, defaultWarehouseId: number | null) {
return put<{ id: number; default_warehouse_id: number | null; pending_orders_updated: number }>(
`/shops/${id}/default-warehouse`,
{ default_warehouse_id: defaultWarehouseId },
)
}
/** 删除店铺(存在订单引用时不可删除) */

View File

@ -7,11 +7,13 @@ import {
createShop,
updateShop,
deleteShop,
setShopDefaultWarehouse,
type ShopItem,
type ShopDetail,
} from '@/api/shop'
import { syncExternalPrintShopProducts, syncExternalPrintShopOrders } from '@/api/externalPrintAccount'
import { getPrincipalSubsidiaryOptions, type PrincipalSubsidiaryOption } from '@/api/principalSubsidiary'
import { getWarehouseOptions, type WarehouseOption } from '@/api/warehouse'
import { getAccessContext } from '@/api/access'
import {
getShopDatabaseConfig,
@ -92,6 +94,39 @@ async function loadAccessInfo() {
}
}
/* -------------------- 默认发货仓库 -------------------- */
/** 仓库下拉(仅启用仓库;按店铺货主过滤) */
const warehouseOptions = ref<WarehouseOption[]>([])
async function loadWarehouseOptions() {
try {
warehouseOptions.value = await getWarehouseOptions()
} catch {
warehouseOptions.value = []
}
}
/**
* 指定货主下的仓库选项
* @param subsidiaryId 货主ID
* @return 仓库选项(含编码与名称)
*/
function warehousesOf(subsidiaryId: number | null | undefined) {
const id = Number(subsidiaryId)
const list = warehouseOptions.value.filter((w) => (id ? Number(w.subsidiary_id) === id : true))
return list.map((w) => ({ id: w.id, label: `${w.code} ${w.name}` }))
}
/** 表单里的默认仓库选项:跟随所选货主 */
const formWarehouseOptions = computed(() => warehousesOf(form.subsidiary_id))
/** 切换货主时清掉不属于该货主的默认仓库 */
function onFormSubsidiaryChange() {
if (form.default_warehouse_id == null) return
const allowed = formWarehouseOptions.value.some((w) => w.id === form.default_warehouse_id)
if (!allowed) form.default_warehouse_id = null
}
const { loading, list, total, elapsed, fetchList, search, handlePageChange, handleSizeChange } = useListPage({
query,
fetcher: () => {
@ -149,6 +184,7 @@ const editId = ref<number | null>(null)
const form = reactive({
code: '',
subsidiary_id: null as number | null,
default_warehouse_id: null as number | null,
name: '',
type: SHOP_TYPE_PLATFORM,
platform: '',
@ -198,6 +234,7 @@ function openCreate() {
form.subsidiary_id = isCompanyScope.value && subsidiaryOptions.value.length === 1
? subsidiaryOptions.value[0].id
: null
form.default_warehouse_id = null
form.name = ''
form.type = SHOP_TYPE_PLATFORM
form.platform = ''
@ -214,6 +251,7 @@ function openEdit(row: ShopItem) {
editId.value = row.id
form.code = row.code
form.subsidiary_id = row.subsidiary_id ?? null
form.default_warehouse_id = row.default_warehouse_id ?? null
form.name = row.name
form.type = Number(row.type) || SHOP_TYPE_PLATFORM
form.platform = row.platform || ''
@ -237,6 +275,7 @@ async function submitForm() {
const payload = {
...form,
subsidiary_id: form.subsidiary_id == null ? null : Number(form.subsidiary_id),
default_warehouse_id: form.default_warehouse_id == null ? null : Number(form.default_warehouse_id),
...(isOffline ? { auto_fetch_order: 0, platform: '' } : {}),
// 店铺类型只在新增时提交,编辑接口不接受改类型
...(editId.value == null ? {} : { type: undefined }),
@ -249,8 +288,9 @@ async function submitForm() {
pendingConfigShop.value = { id: created.id, name: form.name }
}
} else {
await updateShop(editId.value, payload)
ElMessage.success('保存成功')
const saved = await updateShop(editId.value, payload)
const filled = Number(saved?.pending_orders_updated) || 0
ElMessage.success(filled ? `保存成功,已同步 ${filled} 个未审核订单的发货仓库` : '保存成功')
// 详情面板正展示该店铺时同步刷新
if (currentShop.value && currentShop.value.id === editId.value) {
await fetchDetail(editId.value)
@ -791,9 +831,46 @@ async function handleDelete(row: ShopItem) {
}
}
/* -------------------- 默认发货仓库配置 -------------------- */
const warehouseDialogVisible = ref(false)
const warehouseSaving = ref(false)
const warehouseShop = ref<{ id: number; name: string; subsidiary_id: number | null } | null>(null)
const warehouseForm = reactive({ default_warehouse_id: null as number | null })
/** 弹窗里的仓库选项:按店铺货主过滤 */
const warehouseDialogOptions = computed(() => warehousesOf(warehouseShop.value?.subsidiary_id))
function openWarehouseConfig(row: ShopItem) {
warehouseShop.value = { id: row.id, name: row.name, subsidiary_id: row.subsidiary_id ?? null }
warehouseForm.default_warehouse_id = row.default_warehouse_id ?? null
warehouseDialogVisible.value = true
}
async function submitWarehouseConfig() {
const shop = warehouseShop.value
if (!shop) return
warehouseSaving.value = true
try {
const res = await setShopDefaultWarehouse(
shop.id,
warehouseForm.default_warehouse_id == null ? null : Number(warehouseForm.default_warehouse_id),
)
const filled = Number(res?.pending_orders_updated) || 0
ElMessage.success(filled ? `已保存,并同步 ${filled} 个未审核订单的发货仓库` : '已保存')
warehouseDialogVisible.value = false
await fetchList()
if (currentShop.value && currentShop.value.id === shop.id) await fetchDetail(shop.id)
} catch {
// 拦截器已提示
} finally {
warehouseSaving.value = false
}
}
onMounted(() => {
fetchList()
loadAccessInfo()
loadWarehouseOptions()
})
</script>
@ -868,6 +945,13 @@ onMounted(() => {
<el-table-column label="类型" width="110">
<template #default="{ row }">{{ TYPE_LABELS[row.type] || '-' }}</template>
</el-table-column>
<el-table-column label="默认仓库" width="150" show-overflow-tooltip>
<template #default="{ row }">
<span :class="{ 'last-sync': !row.default_warehouse_name }">
{{ row.default_warehouse_name || '未设置' }}
</span>
</template>
</el-table-column>
<el-table-column label="自动拉取" width="150">
<template #default="{ row }">
<span v-if="row.type === SHOP_TYPE_OFFLINE" class="last-sync">-</span>
@ -895,7 +979,7 @@ onMounted(() => {
</el-tag>
</template>
</el-table-column>
<el-table-column label="操作" width="290" fixed="right">
<el-table-column label="操作" width="340" fixed="right">
<template #default="{ row }">
<el-button
v-if="!(isCompanyScope && row.type === 2)"
@ -903,6 +987,12 @@ onMounted(() => {
type="primary"
@click.stop="openEdit(row)"
>编辑</el-button>
<el-button
v-if="row.type === 2"
link
type="primary"
@click.stop="openWarehouseConfig(row)"
>默认仓库</el-button>
<el-button
v-if="row.type === 3"
link
@ -1005,6 +1095,9 @@ onMounted(() => {
{{ currentShop.auto_fetch_order === 1 ? `是(每 ${currentShop.auto_fetch_interval} 分钟)` : '否' }}
</span>
</el-descriptions-item>
<el-descriptions-item label="默认发货仓库">
{{ currentShop.default_warehouse_name || '未设置' }}
</el-descriptions-item>
<el-descriptions-item label="最近拉单">
<span v-if="currentShop.last_order_sync_at">
{{ formatDateTime(currentShop.last_order_sync_at) }}
@ -1078,11 +1171,30 @@ onMounted(() => {
filterable
:disabled="editId != null"
style="width: 100%"
@change="onFormSubsidiaryChange"
>
<el-option v-for="s in subsidiaryOptions" :key="s.id" :label="s.name" :value="s.id" />
</el-select>
<div v-if="editId != null" class="owner-tip">店铺创建后不可更改所属货主</div>
</el-form-item>
<el-form-item label="默认发货仓库">
<el-select
v-model="form.default_warehouse_id"
placeholder="不设置为空;拉单与未审核订单默认用该仓库"
filterable
clearable
:disabled="!form.subsidiary_id"
style="width: 100%"
>
<el-option
v-for="w in formWarehouseOptions"
:key="w.id"
:label="w.label"
:value="w.id"
/>
</el-select>
<div class="owner-tip">仅可选所属货主下的启用仓库;设置后拉取的订单与未审核订单自动使用该仓库</div>
</el-form-item>
<el-form-item label="店铺名称" prop="name">
<el-input v-model="form.name" placeholder="请输入店铺名称" />
</el-form-item>
@ -1134,6 +1246,42 @@ onMounted(() => {
</template>
</el-dialog>
<el-dialog v-model="warehouseDialogVisible" title="默认发货仓库" width="460px" append-to-body>
<el-alert
type="info"
:closable="false"
show-icon
title="设置后:拉取该店铺订单时自动带此仓库;该店铺尚未审核的订单也会回填为该仓库(已手工改过仓库的不动)。"
class="code-tip"
/>
<el-form label-width="110px">
<el-form-item label="店铺">
<span>{{ warehouseShop?.name || '-' }}</span>
</el-form-item>
<el-form-item label="默认发货仓库">
<el-select
v-model="warehouseForm.default_warehouse_id"
placeholder="不设置为空"
filterable
clearable
style="width: 100%"
>
<el-option
v-for="w in warehouseDialogOptions"
:key="w.id"
:label="w.label"
:value="w.id"
/>
</el-select>
<div class="owner-tip">仅可选该店铺货主下的启用仓库</div>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="warehouseDialogVisible = false">取消</el-button>
<el-button type="primary" :loading="warehouseSaving" @click="submitWarehouseConfig">保存</el-button>
</template>
</el-dialog>
<el-dialog v-model="dbPullOrdersVisible" title="拉取订单(数据库店铺)" width="480px">
<el-alert
type="info"