diff --git a/db.sql b/db.sql index b1afb07..7ca48f4 100644 --- a/db.sql +++ b/db.sql @@ -29,6 +29,15 @@ DROP TABLE IF EXISTS `role_data_scope`; DROP TABLE IF EXISTS `role_org_perm`; DROP TABLE IF EXISTS `user_org_perm`; DROP TABLE IF EXISTS `t_xhs_media`; +DROP TABLE IF EXISTS `t_kb_article`; +DROP TABLE IF EXISTS `t_kb_category`; +DROP TABLE IF EXISTS `t_mcp_tool`; +DROP TABLE IF EXISTS `t_pickup_order_line`; +DROP TABLE IF EXISTS `t_pickup_order`; +DROP TABLE IF EXISTS `t_9610_order_item`; +DROP TABLE IF EXISTS `t_9610_order`; +DROP TABLE IF EXISTS `t_ai_skill`; +DROP TABLE IF EXISTS `t_ai_provider`; DROP TABLE IF EXISTS `t_xhs_ai_provider`; DROP TABLE IF EXISTS `t_xhs_human_config`; DROP TABLE IF EXISTS `t_xhs_skill`; @@ -117,6 +126,9 @@ CREATE TABLE `t_order` ( `ExportCustomsMode` VARCHAR(32) NULL COMMENT '出口报关方式', `PredeclareFailReason` VARCHAR(512) NULL COMMENT '预报失败原因', `AllocationPendingReason` VARCHAR(512) NULL COMMENT '待排货原因(排货或渠道买价未匹配)', + `AllocationScheme` VARCHAR(32) NULL COMMENT '最近一次排货方案 costLowest/timeFastest/overallBest/designated', + `AllocationTraceJson` JSON NULL COMMENT '最近一次排货过程快照 JSON', + `AllocationTraceTime` DATETIME NULL COMMENT '排货快照写入时间', `SalesProductRulesVersion` VARCHAR(64) NULL COMMENT '销售产品规则快照版本', `SalesProductPriceVersion` VARCHAR(64) NULL COMMENT '销售产品价格快照版本', `OrderStatus` VARCHAR(32) NOT NULL COMMENT '订单状态', @@ -135,9 +147,20 @@ CREATE TABLE `t_order` ( `PreviousOrderStatus` VARCHAR(32) NULL COMMENT '进入异常状态前的订单状态', `WarehouseId` INT NULL COMMENT '仓库ID', `CustomerId` INT NULL COMMENT '客户ID', + `MemberLevelId` INT NULL COMMENT '下单时会员等级Id快照', + `PriceTierKey` VARCHAR(64) NULL COMMENT '下单时价区键快照', + `ReceivableSubtotal` DECIMAL(18,4) NULL COMMENT '应收小计(折扣前)', + `ForecastReceivableAmount` DECIMAL(18,4) NULL COMMENT '预报应收快照(创建预报后固化,入库不覆盖)', + `ForecastPayableAmount` DECIMAL(18,4) NULL COMMENT '预报应付快照(创建预报后固化,入库不覆盖)', + `LevelDiscountAmount` DECIMAL(18,4) NOT NULL DEFAULT 0 COMMENT '会员等级折扣金额', + `CouponInstanceId` INT NULL COMMENT '使用的优惠券实例Id', + `CouponDiscountAmount` DECIMAL(18,4) NOT NULL DEFAULT 0 COMMENT '优惠券抵扣金额', + `PayableAmount` DECIMAL(18,4) NULL COMMENT '应付金额(对客应收)', `OrderSource` VARCHAR(32) NULL COMMENT '订单来源:manual/pickup/upload/batch/platform', `PickupTime` DATETIME NULL COMMENT '预约揽收时间', `CustomerSenderAddressId` INT NULL COMMENT '发件地址簿 Id', + `InboundMethod` VARCHAR(16) NULL COMMENT '到仓方式 selfShip/doorPickup', + `PickupOrderId` INT NULL COMMENT '关联揽收单Id(冗余)', `OrganizationId` CHAR(36) NULL COMMENT '数据归属组织', `SecretLevel` TINYINT NOT NULL DEFAULT 2 COMMENT '数据密级 1-4', `SenderId` INT NULL COMMENT '发件人ID', @@ -156,6 +179,9 @@ CREATE TABLE `t_order` ( `Quantity` INT NULL COMMENT '包裹数量', `IsIntercept` TINYINT NOT NULL DEFAULT 0 COMMENT '是否拦截:0-否,1-是', `IsRemote` TINYINT NOT NULL DEFAULT 0 COMMENT '是否偏远:0-否,1-是', + `AdditionalServices` VARCHAR(512) NULL COMMENT '客户勾选附加服务字典code JSON数组', + `FulfillmentType` VARCHAR(16) NULL DEFAULT 'direct' COMMENT '履约类型 direct/warehouse', + `FulfillmentSource` VARCHAR(32) NULL COMMENT '代发来源 storeFulfill/postBind', `LabelTemplateId` INT NULL COMMENT '出单标签模板Id', `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', @@ -175,9 +201,14 @@ CREATE TABLE `t_order` ( KEY `idx_ord_recipient` (`RecipientId`), KEY `idx_ord_declaration` (`DeclarationId`), KEY `idx_ord_org_secret_ctime` (`OrganizationId`, `SecretLevel`, `CreateTime`), - KEY `idx_ord_source_ctime` (`OrderSource`, `CreateTime`) + KEY `idx_ord_source_ctime` (`OrderSource`, `CreateTime`), + KEY `idx_order_pickup` (`PickupOrderId`), + KEY `idx_order_inbound_method` (`InboundMethod`), + KEY `idx_ord_fulfillment_customer` (`FulfillmentType`, `CustomerId`, `OrderStatus`) ) COMMENT='订单表'; +-- 存量库升级脚本见:sql/migrate_t_order_fulfillment_type.sql(勿复制带 ... 的示例) + CREATE TABLE `t_order_file` ( `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增', `OrderId` INT NOT NULL COMMENT '订单Id', @@ -452,12 +483,16 @@ CREATE TABLE `t_order_exception_event` ( `Content` TEXT NULL COMMENT '内容快照', `IssueTemplateId` INT NULL COMMENT '模板Id', `NotifyMethod` VARCHAR(64) NULL COMMENT '通知方式快照', + `HandlerNames` VARCHAR(256) NULL COMMENT '处理人快照', + `HandlerType` VARCHAR(16) NULL COMMENT '处理人类型', + `HandlerUserId` INT NULL COMMENT '处理人用户Id(customer 时为订单客户账号)', `ClaimType` VARCHAR(32) NULL COMMENT '理赔类型', `ClaimAmount` DECIMAL(18,4) NULL COMMENT '索赔金额', `ClaimCurrency` VARCHAR(16) NULL COMMENT '索赔币种', `ClaimReason` VARCHAR(512) NULL COMMENT '理赔原因', `Remark` VARCHAR(512) NULL COMMENT '操作备注', `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', + `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '操作人', `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间', `UpdateUserId` INT NULL COMMENT '更新人', @@ -473,6 +508,9 @@ CREATE TABLE `t_sales_product` ( `ProductGroup` VARCHAR(32) NULL COMMENT '分组(专线/快递/邮政)', `MinTimeliness` INT NULL COMMENT '最小时效(天)', `MaxTimeliness` INT NULL COMMENT '最大时效(天)', + `TradeTerms` VARCHAR(16) NULL COMMENT '贸易条款:DDP/DDU', + `RouteSort` INT NOT NULL DEFAULT 0 COMMENT '官网线路排序,越小越靠前', + `AdditionalServices` VARCHAR(512) NULL COMMENT '可选附加服务字典code JSON数组', `CustomerWaybill` VARCHAR(32) NULL COMMENT '系统面单/客户面单', `BlacklistAreaId` INT NULL COMMENT '黑名单区ID', `RemoteAreaId` INT NULL COMMENT '偏远分区ID', @@ -493,6 +531,7 @@ CREATE TABLE `t_sales_product` ( PRIMARY KEY (`Id`), UNIQUE KEY `uk_sp_code` (`ProductCode`), KEY `idx_sp_group_active` (`ProductGroup`, `IsActive`), + KEY `idx_sp_route_sort` (`RouteSort`, `IsActive`), KEY `idx_sp_scheme` (`Scheme`), KEY `idx_sp_weight_rule` (`WeightRuleId`), KEY `idx_sp_weight_rounding` (`WeightRoundingId`) @@ -576,6 +615,7 @@ CREATE TABLE `t_sales_product_publish_record` ( `PublishUser` VARCHAR(64) NOT NULL COMMENT '发布人', `PublishTime` DATETIME NOT NULL COMMENT '发布时间', `Description` VARCHAR(512) NULL COMMENT '版本备注', + `AiAnalysisReport` MEDIUMTEXT NULL COMMENT '价格发布AI风险分析报告', `Content` JSON NULL COMMENT '发布内容JSON快照', `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', @@ -613,6 +653,7 @@ CREATE TABLE `t_service_channel` ( `ForecastType` VARCHAR(32) NULL COMMENT '预报单号类型(customer/waybill/tracking)', `ForecastCode` VARCHAR(128) NULL COMMENT '预报单号', `Description` TEXT COMMENT '描述', + `RemoteAreaId` INT NULL COMMENT '偏远分区KPI AreaId', `PreScript` TEXT COMMENT '入库前脚本', `IsActive` TINYINT NOT NULL DEFAULT 2 COMMENT 'EnableStatus:0=None未设置,1=Disabled禁用,2=Enabled启用', `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', @@ -823,6 +864,8 @@ CREATE TABLE `t_issue_template` ( `Title` VARCHAR(128) NOT NULL COMMENT '问题标题', `Content` TEXT NOT NULL COMMENT '问题内容', `NotifyMethod` VARCHAR(64) NOT NULL COMMENT '通知方式,逗号分隔', + `HandlerType` VARCHAR(16) NULL COMMENT '处理人类型:customer=订单所属客户 user=指定用户', + `HandlerUserId` INT NULL COMMENT '指定处理人用户Id(HandlerType=user 时必填)', `Status` TINYINT NOT NULL DEFAULT 2 COMMENT 'EnableStatus:0=None未设置,1=Disabled禁用,2=Enabled启用', `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', @@ -932,6 +975,8 @@ CREATE TABLE `t_customer` ( `WechatNickname` VARCHAR(64) NULL COMMENT '微信昵称', `Email` VARCHAR(64) NULL COMMENT '邮箱,用于登录/找回密码', `Phone` VARCHAR(16) NULL COMMENT '手机号,用于联系;可空,唯一(NULL 可多条)', + `MemberLevelId` INT NULL COMMENT '会员等级Id', + `PriceTierKey` VARCHAR(64) NULL COMMENT '价区键(卖价 CustomerGroupValues JSON 键)', `Balance` DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT '账户余额', `TotalQuota` DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT '总额度', `UsedQuota` DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT '已用额度', @@ -1300,7 +1345,11 @@ CREATE TABLE `c_sku` ( `CustomerId` INT NOT NULL COMMENT '客户ID → t_customer.Id', `SkuCode` VARCHAR(64) NOT NULL COMMENT '库内SKU编码', `SkuName` VARCHAR(256) NOT NULL COMMENT 'SKU名称', + `SkuNameEn` VARCHAR(256) NULL COMMENT 'SKU英文名称', `SkuImageUrl` VARCHAR(512) NULL COMMENT '图片URL', + `UnitPrice` DECIMAL(12,4) NULL COMMENT '单价', + `ExHsCode` VARCHAR(64) NULL COMMENT '出口HSCode', + `ImHsCode` VARCHAR(64) NULL COMMENT '进口HSCode', `WeightG` DECIMAL(10,2) NULL COMMENT '重量(g)', `LengthCm` DECIMAL(10,2) NULL COMMENT '长(cm)', `WidthCm` DECIMAL(10,2) NULL COMMENT '宽(cm)', @@ -1733,7 +1782,7 @@ CREATE TABLE `t_xhs_human_config` ( UNIQUE KEY `uk_xhs_human_customer` (`CustomerId`) ) COMMENT='小红书拟人行为与防封配置表'; -CREATE TABLE `t_xhs_ai_provider` ( +CREATE TABLE `t_ai_provider` ( `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键', `CustomerId` INT NOT NULL COMMENT '客户ID;0 表示全局', `ProviderKey` VARCHAR(32) NOT NULL COMMENT 'ai_chatgpt / ai_zhipu 等', @@ -1751,9 +1800,266 @@ CREATE TABLE `t_xhs_ai_provider` ( `UpdateUserId` INT NULL, `UpdateTime` DATETIME NULL, PRIMARY KEY (`Id`), - UNIQUE KEY `uk_xhs_ai_provider` (`CustomerId`, `ProviderKey`), - KEY `idx_xhs_ai_customer` (`CustomerId`, `Enabled`) -) COMMENT='小红书 AI 提供商配置表'; + UNIQUE KEY `uk_ai_provider` (`CustomerId`, `ProviderKey`), + KEY `idx_ai_customer` (`CustomerId`, `Enabled`) +) COMMENT='全局 AI 提供商配置表(CustomerId=0 表示平台级)'; + +CREATE TABLE `t_ai_skill` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键', + `SkillKey` VARCHAR(64) NOT NULL COMMENT '稳定键', + `Scene` VARCHAR(32) NOT NULL COMMENT '场景 pricePublish/autoTriggerFormula/receiverAddressParse/itfxPrefixScript', + `Name` VARCHAR(128) NOT NULL COMMENT '展示名', + `Description` VARCHAR(512) NULL COMMENT '简介', + `Content` LONGTEXT NOT NULL COMMENT '发给模型的正文', + `SortOrder` INT NOT NULL DEFAULT 0 COMMENT '排序', + `Enabled` TINYINT NOT NULL DEFAULT 1 COMMENT '是否启用:0-否,1-是', + `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', + `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', + `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', + `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `UpdateUserId` INT NULL COMMENT '更新人', + `UpdateTime` DATETIME NULL COMMENT '更新时间', + PRIMARY KEY (`Id`), + UNIQUE KEY `uk_ai_skill_key` (`SkillKey`), + KEY `idx_ai_skill_scene` (`Scene`, `Enabled`, `SortOrder`) +) COMMENT='平台级 AI Skill(提示词/规范)'; + +CREATE TABLE `t_mcp_tool` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增', + `ToolKey` VARCHAR(64) NOT NULL COMMENT '工具编码,如 oms.price_check', + `DisplayName` VARCHAR(128) NOT NULL COMMENT '显示名称', + `Description` VARCHAR(1000) NOT NULL COMMENT '给 AI 的工具描述', + `Enabled` TINYINT NOT NULL DEFAULT 1 COMMENT '是否启用:0-否,1-是', + `SortOrder` INT NOT NULL DEFAULT 0 COMMENT '排序,越小越靠前', + `Remark` VARCHAR(512) NULL COMMENT '备注', + `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', + `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', + `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', + `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `UpdateUserId` INT NULL COMMENT '更新人', + `UpdateTime` DATETIME NULL COMMENT '更新时间', + PRIMARY KEY (`Id`), + UNIQUE KEY `uk_mcp_tool_key` (`ToolKey`), + KEY `idx_mcp_tool_enabled` (`Enabled`, `SortOrder`, `Id`) +) COMMENT='MCP 工具配置表'; + +CREATE TABLE `t_pickup_order` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增', + `PickupNo` VARCHAR(32) NOT NULL COMMENT '揽收单号', + `RequestId` VARCHAR(64) NULL COMMENT '请求幂等ID', + `CustomerId` INT NOT NULL COMMENT '客户Id', + `OrganizationId` CHAR(36) NULL COMMENT '数据归属组织', + `SecretLevel` TINYINT NOT NULL DEFAULT 2 COMMENT '数据密级 1-4', + `SenderAddressId` INT NOT NULL COMMENT '发件地址簿Id', + `SenderName` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '取件联系人快照', + `SenderCompany` VARCHAR(255) NULL COMMENT '公司快照', + `SenderCountry` INT NULL COMMENT '国家 t_country.Id 快照', + `SenderCountryCode` VARCHAR(8) NULL COMMENT '国家码快照', + `SenderProvince` VARCHAR(50) NULL COMMENT '省快照', + `SenderCity` VARCHAR(50) NULL COMMENT '市快照', + `SenderZipCode` VARCHAR(50) NULL COMMENT '邮编快照', + `SenderStreetAddress1` VARCHAR(500) NOT NULL DEFAULT '' COMMENT '地址1快照', + `SenderStreetAddress2` VARCHAR(500) NULL COMMENT '地址2快照', + `SenderStreetAddress3` VARCHAR(500) NULL COMMENT '地址3快照', + `SenderHouseNumber` VARCHAR(50) NULL COMMENT '门牌号快照', + `SenderPhone` VARCHAR(50) NULL COMMENT '手机快照', + `SenderTelePhone` VARCHAR(50) NULL COMMENT '电话快照', + `SenderEmail` VARCHAR(60) NULL COMMENT '邮箱快照', + `WarehouseId` INT NOT NULL COMMENT '送到仓库Id', + `CarrierCode` VARCHAR(64) NULL COMMENT '承运商编码(draft可空)', + `CarrierService` VARCHAR(64) NULL COMMENT '承运服务(draft可空)', + `CarrierWaybillNo` VARCHAR(64) NULL COMMENT '承运商回执单号', + `ExpectPickupTime` DATETIME NOT NULL COMMENT '期望揽收时间', + `PickupWindowStart` DATETIME NULL COMMENT '时间窗起', + `PickupWindowEnd` DATETIME NULL COMMENT '时间窗止', + `ActualPickupTime` DATETIME NULL COMMENT '实际取件时间', + `Status` VARCHAR(32) NOT NULL DEFAULT 'draft' COMMENT 'draft/scheduled/dispatched/picked/inbound/cancelled/failed', + `ParcelCount` INT NOT NULL DEFAULT 0 COMMENT '关联票数', + `TotalActualWeight` DECIMAL(18,3) NULL COMMENT '汇总实重', + `ChargeableWeight` DECIMAL(18,3) NULL COMMENT '计费重', + `Currency` VARCHAR(8) NOT NULL DEFAULT 'CNY' COMMENT '币种', + `FreightAmount` DECIMAL(18,2) NULL COMMENT '对客揽收运费', + `OtherFeeAmount` DECIMAL(18,2) NULL COMMENT '对客其他费', + `ReceivableAmount` DECIMAL(18,2) NULL COMMENT '对客应收合计', + `PayStatus` VARCHAR(16) NOT NULL DEFAULT 'unpaid' COMMENT 'unpaid/paid', + `PayTime` DATETIME NULL COMMENT '支付时间', + `PayMode` VARCHAR(16) NOT NULL DEFAULT 'prepaid' COMMENT 'prepaid/collect', + `CarrierPayableAmount` DECIMAL(18,2) NULL COMMENT '应付承运商', + `SettlementStatus` VARCHAR(16) NOT NULL DEFAULT 'none' COMMENT 'none/pending/settled', + `SettlementBatchNo` VARCHAR(64) NULL COMMENT '结算批次号', + `SettledAt` DATETIME NULL COMMENT '结算时间', + `Remark` VARCHAR(512) NULL COMMENT '备注', + `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', + `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', + `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', + `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `UpdateUserId` INT NULL COMMENT '更新人', + `UpdateTime` DATETIME NULL COMMENT '更新时间', + PRIMARY KEY (`Id`), + UNIQUE KEY `uk_pickup_no` (`PickupNo`), + UNIQUE KEY `uk_pickup_request_id` (`RequestId`), + KEY `idx_pickup_customer_status` (`CustomerId`, `Status`, `CreateTime`), + KEY `idx_pickup_warehouse_time` (`WarehouseId`, `ExpectPickupTime`), + KEY `idx_pickup_pay` (`PayStatus`), + KEY `idx_pickup_settle` (`SettlementStatus`), + KEY `idx_pickup_org_secret_ctime` (`OrganizationId`, `SecretLevel`, `CreateTime`) +) COMMENT='揽收单(上门取件履约+对客收款+承运结算)'; + +CREATE TABLE `t_pickup_order_line` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增', + `PickupOrderId` INT NOT NULL COMMENT '揽收单Id', + `OrderId` INT NOT NULL COMMENT '物流订单Id', + `ServiceNo` VARCHAR(64) NULL COMMENT '运单号快照(便于列表)', + `ClientNo` VARCHAR(64) NULL COMMENT '客户单号快照', + `SortNo` INT NOT NULL DEFAULT 0 COMMENT '展示序', + `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', + `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', + `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', + `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `UpdateUserId` INT NULL COMMENT '更新人', + `UpdateTime` DATETIME NULL COMMENT '更新时间', + PRIMARY KEY (`Id`), + UNIQUE KEY `uk_pickup_line_order` (`OrderId`), + UNIQUE KEY `uk_pickup_line_pair` (`PickupOrderId`, `OrderId`), + KEY `idx_pickup_line_header` (`PickupOrderId`, `IsDeleted`) +) COMMENT='揽收单关联物流订单(1揽收:N物流)'; + +CREATE TABLE `t_9610_order` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键', + `OrderId` INT NOT NULL COMMENT '关联运单 t_order.Id', + `ServiceNo` VARCHAR(64) NULL COMMENT '运单号冗余', + `CustomerId` INT NOT NULL DEFAULT 0 COMMENT '客户Id', + `Status` VARCHAR(16) NOT NULL DEFAULT 'pending' COMMENT 'pending待申报 / declared已申报', + `PlatformCode` VARCHAR(16) NOT NULL DEFAULT '' COMMENT '电商平台', + `EcomCorpCode` VARCHAR(18) NULL COMMENT '电商企业代码', + `EcomCorpName` VARCHAR(100) NULL COMMENT '电商企业名称', + `ProducerCode` VARCHAR(18) NULL COMMENT '生产销售单位代码', + `ProducerName` VARCHAR(100) NULL COMMENT '生产销售单位', + `ClientNo` VARCHAR(48) NOT NULL DEFAULT '' COMMENT '客户单号(对齐 t_order.ClientNo)', + `BusinessType` CHAR(1) NOT NULL DEFAULT 'B' COMMENT '业务类型 A简化/B汇总', + `Region` VARCHAR(10) NULL COMMENT '区域 SZ/other', + `AgentDeclare` VARCHAR(2) NULL COMMENT '是否代理申报 是/否', + `ActualSellerCode` VARCHAR(18) NULL COMMENT '实际卖家信用代码', + `PreRecordFlag` CHAR(1) NULL COMMENT '汇总预录 0已预录 1未预录', + `IsSummarySimple` TINYINT NOT NULL DEFAULT 0 COMMENT '是否汇总简化申报', + `GrossWeight` DECIMAL(19,5) NOT NULL DEFAULT 0 COMMENT '毛重KG', + `Currency` VARCHAR(4) NOT NULL DEFAULT 'CNY' COMMENT '币制', + `DestCountry` VARCHAR(4) NOT NULL DEFAULT '' COMMENT '目的国', + `Freight` DECIMAL(19,5) NULL COMMENT '运费', + `FreightCurrency` VARCHAR(4) NULL COMMENT '运费币制', + `FreightMark` INT NULL COMMENT '运费标志 1率2单价3总价', + `PackageType` INT NULL COMMENT '包装种类代码', + `PackageQty` INT NULL COMMENT '件数', + `ShipmentNo` VARCHAR(32) NULL COMMENT '出货单号', + `CustomsOrderNo` VARCHAR(32) NULL COMMENT '海关订单号(申报回写)', + `DownstreamRefNo` VARCHAR(32) NULL COMMENT '申报回写的 referenceNo 快照', + `EnterpriseBizNo` VARCHAR(48) NULL COMMENT '企业唯一编号(上游 copNo)', + `ManifestNo` VARCHAR(48) NULL COMMENT '清单编号(上游 invtNo)', + `ClearanceTime` VARCHAR(48) NULL COMMENT '结关日期原文', + `CustomsInboundTime` VARCHAR(48) NULL COMMENT '海关入库时间原文', + `CustomsState` VARCHAR(4) NULL COMMENT '海关状态', + `DeclareCustomsCode` VARCHAR(4) NULL COMMENT '申报地海关代码', + `PlatformCorpCode` VARCHAR(18) NULL COMMENT '电商平台代码', + `PlatformName` VARCHAR(100) NULL COMMENT '电商平台名称', + `LogisticsCorpCode` VARCHAR(18) NULL COMMENT '物流企业代码', + `LogisticsCorpName` VARCHAR(100) NULL COMMENT '物流企业名称', + `IeMark` VARCHAR(4) NULL COMMENT '进出口标记 I/E', + `ExportPortCode` VARCHAR(4) NULL COMMENT '出口口岸代码', + `ExportDate` VARCHAR(32) NULL COMMENT '出口日期原文', + `DeclareAgentCode` VARCHAR(18) NULL COMMENT '申报企业代码', + `DeclareAgentName` VARCHAR(100) NULL COMMENT '申报企业名称', + `TradeModeCode` VARCHAR(4) NULL COMMENT '贸易方式代码', + `TransportMode` VARCHAR(4) NULL COMMENT '运输方式代码', + `DeclareTime` DATETIME NULL COMMENT '申报成功时间', + `ManifestSyncTime` DATETIME NULL COMMENT '清单数据最近同步时间', + `FailReason` VARCHAR(512) NULL COMMENT '最近失败原因', + `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除', + `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', + `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', + `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `UpdateUserId` INT NULL COMMENT '更新人', + `UpdateTime` DATETIME NULL COMMENT '更新时间', + PRIMARY KEY (`Id`), + UNIQUE KEY `uk_9610_order_id` (`OrderId`), + KEY `idx_9610_status_ctime` (`Status`, `CreateTime`), + KEY `idx_9610_service_no` (`ServiceNo`), + KEY `idx_9610_client_no` (`ClientNo`), + KEY `idx_9610_customer` (`CustomerId`, `CreateTime`), + KEY `idx_9610_manifest` (`ManifestNo`) +) COMMENT='9610汇总申报单'; + +CREATE TABLE `t_9610_order_item` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键', + `Customs9610OrderId` INT NOT NULL COMMENT 't_9610_order.Id', + `OrderDeclarationId` INT NULL COMMENT '溯源 t_order_declaration.Id', + `Sku` VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'SKU(对齐 t_order_declaration.Sku)', + `CnName` VARCHAR(250) NOT NULL DEFAULT '' COMMENT '中文品名(对齐 t_order_declaration.CnName)', + `ExHsCode` VARCHAR(10) NULL COMMENT '出口海关编码(对齐 t_order_declaration.ExHsCode)', + `DeclareElement` VARCHAR(255) NULL COMMENT '申报要素', + `Barcode` VARCHAR(255) NULL COMMENT '条形码', + `DestCountry` VARCHAR(255) NULL COMMENT '目的国(地区)代码', + `ItemCurrency` VARCHAR(3) NULL COMMENT '币制', + `UnitPrice` DECIMAL(19,5) NOT NULL DEFAULT 0 COMMENT '单价(对齐 t_order_declaration.UnitPrice)', + `Amount` DECIMAL(19,5) NULL COMMENT '总价(对齐 t_order_declaration.Amount)', + `Quantity` DECIMAL(19,5) NOT NULL DEFAULT 0 COMMENT '数量(对齐 t_order_declaration.Quantity)', + `LegalQty` DECIMAL(19,5) NULL COMMENT '法定数量', + `Unit` VARCHAR(3) NULL COMMENT '计量单位(对齐 t_order_declaration.Unit)', + `LegalUnit` VARCHAR(3) NULL COMMENT '法定计量单位', + `Freight` DECIMAL(12,4) NULL COMMENT '行运费', + `SortNo` INT NOT NULL DEFAULT 0 COMMENT '排序', + `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除', + `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', + `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `UpdateUserId` INT NULL COMMENT '更新人', + `UpdateTime` DATETIME NULL COMMENT '更新时间', + PRIMARY KEY (`Id`), + KEY `idx_9610_item_header` (`Customs9610OrderId`, `IsDeleted`) +) COMMENT='9610申报商品明细'; + +CREATE TABLE `t_kb_category` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键', + `Code` VARCHAR(64) NOT NULL COMMENT '稳定键,如 pricing', + `Name` VARCHAR(128) NOT NULL COMMENT '展示名(中文)', + `SortOrder` INT NOT NULL DEFAULT 0 COMMENT '排序,越小越前', + `Enabled` TINYINT NOT NULL DEFAULT 1 COMMENT '是否启用:0-否,1-是', + `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', + `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', + `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', + `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `UpdateUserId` INT NULL COMMENT '更新人', + `UpdateTime` DATETIME NULL COMMENT '更新时间', + PRIMARY KEY (`Id`), + UNIQUE KEY `uk_kb_category_code` (`Code`), + KEY `idx_kb_category_enabled_sort` (`Enabled`, `SortOrder`) +) COMMENT='知识库分类'; + +CREATE TABLE `t_kb_article` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键', + `CategoryId` INT NOT NULL COMMENT '分类 Id', + `Title` VARCHAR(200) NOT NULL COMMENT '标题(中文)', + `Summary` VARCHAR(500) NULL COMMENT '列表摘要', + `Content` LONGTEXT NOT NULL COMMENT 'Markdown 正文(中文)', + `Audience` VARCHAR(16) NOT NULL DEFAULT 'customer' COMMENT '受众 customer/internal', + `Status` VARCHAR(16) NOT NULL DEFAULT 'draft' COMMENT 'draft/published/offline', + `Tags` VARCHAR(256) NULL COMMENT '逗号分隔标签', + `RelatedPath` VARCHAR(256) NULL COMMENT '站内关联 path', + `RelatedLabel` VARCHAR(64) NULL COMMENT '关联按钮文案', + `IsPinned` TINYINT NOT NULL DEFAULT 0 COMMENT '置顶:0-否,1-是', + `SortOrder` INT NOT NULL DEFAULT 0 COMMENT '同类排序', + `PublishTime` DATETIME NULL COMMENT '发布时间', + `ExpireTime` DATETIME NULL COMMENT '过期时间', + `ViewCount` INT NOT NULL DEFAULT 0 COMMENT '浏览次数', + `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', + `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', + `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', + `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `UpdateUserId` INT NULL COMMENT '更新人', + `UpdateTime` DATETIME NULL COMMENT '更新时间', + PRIMARY KEY (`Id`), + KEY `idx_kb_article_list` (`Status`, `Audience`, `CategoryId`, `IsPinned`, `SortOrder`), + KEY `idx_kb_article_publish` (`Status`, `Audience`, `PublishTime`), + KEY `idx_kb_article_hot` (`Status`, `Audience`, `IsPinned`, `ViewCount`) +) COMMENT='知识库文章'; CREATE TABLE `t_xhs_media` ( `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键', @@ -2050,4 +2356,13 @@ CREATE TABLE `data_perm_access_log` ( KEY `idx_perm_access_resource` (`DataResourceCode`, `CreateTime`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='数据权限访问审计(可采样)'; +-- --------------------------------------------------------------------------- +-- 增量迁移(已有库执行;全新安装可忽略) +-- --------------------------------------------------------------------------- +-- ALTER TABLE `c_sku` +-- ADD COLUMN `SkuNameEn` VARCHAR(256) NULL COMMENT 'SKU英文名称' AFTER `SkuName`, +-- ADD COLUMN `UnitPrice` DECIMAL(12,4) NULL COMMENT '单价' AFTER `SkuImageUrl`, +-- ADD COLUMN `ExHsCode` VARCHAR(64) NULL COMMENT '出口HSCode' AFTER `UnitPrice`, +-- ADD COLUMN `ImHsCode` VARCHAR(64) NULL COMMENT '进口HSCode' AFTER `ExHsCode`; + SET FOREIGN_KEY_CHECKS = 1; diff --git a/sql/20260727_customer_phone_nullable.sql b/sql/20260727_customer_phone_nullable.sql deleted file mode 100644 index 1788f35..0000000 --- a/sql/20260727_customer_phone_nullable.sql +++ /dev/null @@ -1,5 +0,0 @@ --- 微信注册简化:客户手机号改为可空(空值请用 NULL,勿存空字符串) --- 执行环境:生产库先备份;与 docs/微信注册简化与联系方式补全方案.md 一致 - -ALTER TABLE `t_customer` - MODIFY COLUMN `Phone` VARCHAR(16) NULL COMMENT '手机号,用于联系;可空,唯一(NULL 可多条)'; diff --git a/sql/20260728_auto_trigger_merge_forecast_to_order_create.sql b/sql/20260728_auto_trigger_merge_forecast_to_order_create.sql deleted file mode 100644 index c3532bf..0000000 --- a/sql/20260728_auto_trigger_merge_forecast_to_order_create.sql +++ /dev/null @@ -1,6 +0,0 @@ --- 自动触发时机:预报 并入 下单 -UPDATE t_auto_trigger -SET TriggerTiming = N'下单' -WHERE TriggerTiming IN (N'预报', N'forecast', N'order_create', N'OrderCreate') - OR TriggerTiming LIKE N'%预报%' - OR LOWER(TriggerTiming) LIKE N'%forecast%'; diff --git a/sql/20260728_order_downstream_service_no.sql b/sql/20260728_order_downstream_service_no.sql deleted file mode 100644 index 691807f..0000000 --- a/sql/20260728_order_downstream_service_no.sql +++ /dev/null @@ -1,5 +0,0 @@ --- Add DownstreamServiceNo to t_order (provider service no from createOrderOne Data.serviceNo) --- Backup production DB before running. - -ALTER TABLE `t_order` - ADD COLUMN `DownstreamServiceNo` VARCHAR(64) NULL COMMENT 'Downstream provider service no' AFTER `TrackNo`; diff --git a/sql/20260728_order_file.sql b/sql/20260728_order_file.sql deleted file mode 100644 index 1e94b5f..0000000 --- a/sql/20260728_order_file.sql +++ /dev/null @@ -1,50 +0,0 @@ --- 订单附件表;将原 LabelUrl 迁移为 systemLabel 后删除订单旧面单字段。 --- 在 MySQL 执行前请先备份。 - -CREATE TABLE IF NOT EXISTS `t_order_file` ( - `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增', - `OrderId` INT NOT NULL COMMENT '订单Id', - `FileType` VARCHAR(32) NOT NULL COMMENT '附件类型:tradeProof交易证明/systemLabel系统面单/downstreamLabel下游面单/lastMileLabel末端面单/infraredImage红外图片', - `FileName` VARCHAR(255) NULL COMMENT '原始文件名', - `FileUrl` VARCHAR(512) NOT NULL COMMENT '文件地址(相对路径或外链)', - `ContentType` VARCHAR(128) NULL COMMENT '文件MIME类型', - `FileSize` BIGINT NULL COMMENT '文件大小(字节)', - `Sort` INT NOT NULL DEFAULT 0 COMMENT '同类型内排序', - `Source` VARCHAR(32) NOT NULL DEFAULT 'upload' COMMENT '来源:upload上传/systemGenerate系统生成/downstream下游回传/migrate迁移', - `Remark` VARCHAR(512) NULL COMMENT '备注', - `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', - `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', - `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', - `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `UpdateUserId` INT NULL COMMENT '更新人', - `UpdateTime` DATETIME NULL COMMENT '更新时间', - PRIMARY KEY (`Id`), - KEY `idx_ord_file_order_type` (`OrderId`, `FileType`, `IsDeleted`) -) COMMENT='订单附件表'; - --- 迁移已有系统面单地址(若 LabelUrl 列已删除可跳过本段) -INSERT INTO `t_order_file` (`OrderId`, `FileType`, `FileName`, `FileUrl`, `ContentType`, `Sort`, `Source`, `CreateUserId`, `CreateTime`) -SELECT - `Id`, - 'systemLabel', - SUBSTRING_INDEX(`LabelUrl`, '/', -1), - `LabelUrl`, - 'application/pdf', - 0, - 'migrate', - 0, - NOW() -FROM `t_order` -WHERE `LabelUrl` IS NOT NULL - AND TRIM(`LabelUrl`) <> '' - AND NOT EXISTS ( - SELECT 1 FROM `t_order_file` f - WHERE f.`OrderId` = `t_order`.`Id` - AND f.`FileType` = 'systemLabel' - AND f.`IsDeleted` = 0 - ); - -ALTER TABLE `t_order` - DROP COLUMN `LabelUrl`, - DROP COLUMN `LabelGenerateStatus`, - DROP COLUMN `LabelGenerateError`; diff --git a/sql/20260728_order_file_comments.sql b/sql/20260728_order_file_comments.sql deleted file mode 100644 index 1934c3c..0000000 --- a/sql/20260728_order_file_comments.sql +++ /dev/null @@ -1,20 +0,0 @@ --- 若 t_order_file 已按英文注释建表,执行本脚本改为中文注释(不改结构)。 - -ALTER TABLE `t_order_file` - MODIFY COLUMN `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增', - MODIFY COLUMN `OrderId` INT NOT NULL COMMENT '订单Id', - MODIFY COLUMN `FileType` VARCHAR(32) NOT NULL COMMENT '附件类型:tradeProof交易证明/systemLabel系统面单/downstreamLabel下游面单/lastMileLabel末端面单/infraredImage红外图片', - MODIFY COLUMN `FileName` VARCHAR(255) NULL COMMENT '原始文件名', - MODIFY COLUMN `FileUrl` VARCHAR(512) NOT NULL COMMENT '文件地址(相对路径或外链)', - MODIFY COLUMN `ContentType` VARCHAR(128) NULL COMMENT '文件MIME类型', - MODIFY COLUMN `FileSize` BIGINT NULL COMMENT '文件大小(字节)', - MODIFY COLUMN `Sort` INT NOT NULL DEFAULT 0 COMMENT '同类型内排序', - MODIFY COLUMN `Source` VARCHAR(32) NOT NULL DEFAULT 'upload' COMMENT '来源:upload上传/systemGenerate系统生成/downstream下游回传/migrate迁移', - MODIFY COLUMN `Remark` VARCHAR(512) NULL COMMENT '备注', - MODIFY COLUMN `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', - MODIFY COLUMN `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', - MODIFY COLUMN `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', - MODIFY COLUMN `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - MODIFY COLUMN `UpdateUserId` INT NULL COMMENT '更新人', - MODIFY COLUMN `UpdateTime` DATETIME NULL COMMENT '更新时间', - COMMENT='订单附件表'; diff --git a/sql/20260729_fix_user_empty_email.sql b/sql/20260729_fix_user_empty_email.sql deleted file mode 100644 index 3485f95..0000000 --- a/sql/20260729_fix_user_empty_email.sql +++ /dev/null @@ -1,12 +0,0 @@ --- 修复:微信注册无邮箱时曾写入 user.Email='',撞 uk_user_email 导致后续注册提示「邮箱已被占用」 --- 将空邮箱改为「客户编号@noemail.local」占位(与 CustomerContactHelper.ResolveRbacEmailOrPlaceholder 一致) - -UPDATE `user` u -INNER JOIN `t_customer` c ON c.`UserId` = u.`userid` -SET u.`Email` = CONCAT(LOWER(TRIM(c.`CustomerCode`)), '@noemail.local') -WHERE u.`Email` IS NULL OR TRIM(u.`Email`) = ''; - --- 无客户关联的残留空邮箱 -UPDATE `user` -SET `Email` = CONCAT('u', `userid`, '@noemail.local') -WHERE `Email` IS NULL OR TRIM(`Email`) = ''; diff --git a/sql/20260729_mcp_tool.sql b/sql/20260729_mcp_tool.sql deleted file mode 100644 index ebb0a69..0000000 --- a/sql/20260729_mcp_tool.sql +++ /dev/null @@ -1,32 +0,0 @@ --- MCP 工具配置(启用/描述覆盖),与代码内置目录合并 --- 对齐 t_system_other_config / t_order_file 等配置表结构习惯 - -CREATE TABLE IF NOT EXISTS `t_mcp_tool` ( - `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增', - `ToolKey` VARCHAR(64) NOT NULL COMMENT '工具编码,如 oms.price_check', - `DisplayName` VARCHAR(128) NOT NULL COMMENT '显示名称', - `Description` VARCHAR(1000) NOT NULL COMMENT '给 AI 的工具描述', - `Enabled` TINYINT NOT NULL DEFAULT 1 COMMENT '是否启用:0-否,1-是', - `SortOrder` INT NOT NULL DEFAULT 0 COMMENT '排序,越小越靠前', - `Remark` VARCHAR(512) NULL COMMENT '备注', - `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', - `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳', - `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', - `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `UpdateUserId` INT NULL COMMENT '更新人', - `UpdateTime` DATETIME NULL COMMENT '更新时间', - PRIMARY KEY (`Id`), - UNIQUE KEY `uk_mcp_tool_key` (`ToolKey`), - KEY `idx_mcp_tool_enabled` (`Enabled`, `SortOrder`, `Id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='MCP 工具配置表'; - -INSERT INTO `t_mcp_tool` (`ToolKey`, `DisplayName`, `Description`, `Enabled`, `SortOrder`, `Remark`) -VALUES - ('oms.price_check', '查价格', '根据目的国、重量等查询运费报价,返回可用渠道与价格摘要。', 1, 10, '内置:封装 /order/price-check'), - ('oms.channel_guide', '查渠道对客说明', '按销售产品代码/名称查询对客说明(禁运、可寄品名等),判断客户品名是否可承运。', 1, 20, '内置:读销售产品 CustomerGuideMarkdown'), - ('oms.track_query', '查轨迹', '根据运单号/客户单号查询物流轨迹时间轴摘要。', 1, 30, '内置:轨迹中心 GetDetailTimeline') -ON DUPLICATE KEY UPDATE - `DisplayName` = VALUES(`DisplayName`), - `Description` = VALUES(`Description`), - `SortOrder` = VALUES(`SortOrder`), - `Remark` = VALUES(`Remark`); diff --git a/sql/20260729_mcp_tool_alter_align.sql b/sql/20260729_mcp_tool_alter_align.sql deleted file mode 100644 index 501ee94..0000000 --- a/sql/20260729_mcp_tool_alter_align.sql +++ /dev/null @@ -1,38 +0,0 @@ --- 若已按旧版建过 t_mcp_tool,执行本脚本补齐字段(幂等) - -ALTER TABLE `t_mcp_tool` - ADD COLUMN IF NOT EXISTS `Remark` VARCHAR(512) NULL COMMENT '备注' AFTER `SortOrder`; - --- MySQL 8.0.12 前无 IF NOT EXISTS 时,可改用下面手工判断;8.0.29+ 支持 ADD COLUMN IF NOT EXISTS --- 并发戳:已存在则跳过 -SET @col_exists := ( - SELECT COUNT(*) FROM information_schema.COLUMNS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = 't_mcp_tool' - AND COLUMN_NAME = 'ConcurrencyStamp' -); -SET @sql := IF( - @col_exists = 0, - 'ALTER TABLE `t_mcp_tool` ADD COLUMN `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'' AFTER `IsDeleted`', - 'SELECT 1' -); -PREPARE stmt FROM @sql; -EXECUTE stmt; -DEALLOCATE PREPARE stmt; - -SET @idx_exists := ( - SELECT COUNT(*) FROM information_schema.STATISTICS - WHERE TABLE_SCHEMA = DATABASE() - AND TABLE_NAME = 't_mcp_tool' - AND INDEX_NAME = 'idx_mcp_tool_enabled' -); -SET @sql := IF( - @idx_exists = 0, - 'ALTER TABLE `t_mcp_tool` ADD KEY `idx_mcp_tool_enabled` (`Enabled`, `SortOrder`, `Id`)', - 'SELECT 1' -); -PREPARE stmt FROM @sql; -EXECUTE stmt; -DEALLOCATE PREPARE stmt; - -ALTER TABLE `t_mcp_tool` COMMENT = 'MCP 工具配置表'; diff --git a/sql/20260730_customer_price_tier_key.sql b/sql/20260730_customer_price_tier_key.sql deleted file mode 100644 index cbc9b9f..0000000 --- a/sql/20260730_customer_price_tier_key.sql +++ /dev/null @@ -1,46 +0,0 @@ --- 价区键迁到客户:与会员等级解耦 --- 新注册默认价区键/会员等级均为「普通会员」;计价时空键回落「普通客户」 - --- 1) 客户表增加价区键 -ALTER TABLE `t_customer` - ADD COLUMN `PriceTierKey` VARCHAR(64) NULL COMMENT '价区键(卖价 CustomerGroupValues JSON 键)' AFTER `MemberLevelId`; - --- 2) 从原会员等级价区键回填(依赖本脚本执行前 t_member_level 仍有 PriceTierKey) -UPDATE `t_customer` c -INNER JOIN `t_member_level` ml ON ml.`Id` = c.`MemberLevelId` AND ml.`IsDeleted` = 0 -SET c.`PriceTierKey` = NULLIF(TRIM(ml.`PriceTierKey`), '') -WHERE c.`IsDeleted` = 0 - AND (c.`PriceTierKey` IS NULL OR TRIM(c.`PriceTierKey`) = '') - AND ml.`PriceTierKey` IS NOT NULL - AND TRIM(ml.`PriceTierKey`) <> ''; - --- 3) 仍为空的主客户:默认「普通会员」(与新注册一致) -UPDATE `t_customer` -SET `PriceTierKey` = '普通会员' -WHERE `IsDeleted` = 0 - AND (`ParentCustomerId` IS NULL OR `ParentCustomerId` = 0) - AND (`PriceTierKey` IS NULL OR TRIM(`PriceTierKey`) = ''); - --- 4) 子客户跟随主客户价区 -UPDATE `t_customer` sub -INNER JOIN `t_customer` main ON main.`Id` = sub.`ParentCustomerId` AND main.`IsDeleted` = 0 -SET sub.`PriceTierKey` = main.`PriceTierKey` -WHERE sub.`IsDeleted` = 0 - AND sub.`ParentCustomerId` IS NOT NULL - AND sub.`ParentCustomerId` <> 0; - --- 5) 删除会员等级上的价区键列(须在插入默认等级前执行,避免 NOT NULL 约束) -ALTER TABLE `t_member_level` DROP COLUMN `PriceTierKey`; - --- 6) 确保存在启用的「普通会员」等级(供新注册默认挂靠) -INSERT INTO `t_member_level` ( - `LevelCode`, `LevelName`, `MinPoints`, `ExtraDiscountRate`, `Sort`, - `Status`, `IsDeleted`, `CreateTime` -) -SELECT '普通会员', '普通会员', 0, 0, 0, 2, 0, NOW() -FROM DUAL -WHERE NOT EXISTS ( - SELECT 1 FROM `t_member_level` - WHERE `IsDeleted` = 0 - AND (`LevelName` = '普通会员' OR `LevelCode` = '普通会员') -); diff --git a/sql/20260730_sales_product_trade_terms.sql b/sql/20260730_sales_product_trade_terms.sql deleted file mode 100644 index 9817317..0000000 --- a/sql/20260730_sales_product_trade_terms.sql +++ /dev/null @@ -1,3 +0,0 @@ --- 销售产品:贸易条款 DDP / DDU(查价线路返回并展示于价卡) -ALTER TABLE `t_sales_product` - ADD COLUMN `TradeTerms` VARCHAR(16) NULL COMMENT '贸易条款:DDP/DDU' AFTER `MaxTimeliness`; diff --git a/sql/migrate_dict_employee_position.sql b/sql/migrate_dict_employee_position.sql new file mode 100644 index 0000000..c0c2846 --- /dev/null +++ b/sql/migrate_dict_employee_position.sql @@ -0,0 +1,80 @@ +-- 员工档案「岗位 / 职级」字典初始数据(幂等:已存在同 DictType+DictCode 则跳过) +-- dictType: employee_position / employee_job_level +-- MySQL 5.7+ / 8.0 + +SET NAMES utf8mb4; + +-- ========== 岗位 employee_position ========== +INSERT INTO `t_dict_type` (`DictType`, `Remark`, `TypeSort`, `IsDeleted`, `CreateUserId`) +SELECT 'employee_position', '员工岗位', 0, 0, 0 +FROM DUAL +WHERE NOT EXISTS ( + SELECT 1 FROM `t_dict_type` WHERE `DictType` = 'employee_position' AND `IsDeleted` = 0 +); + +INSERT INTO `t_dict` (`DictType`, `DictSort`, `DictCode`, `DictName`, `IsDeleted`, `CreateUserId`) +SELECT v.`DictType`, v.`DictSort`, v.`DictCode`, v.`DictName`, 0, 0 +FROM ( + SELECT 'employee_position' AS DictType, 1 AS DictSort, 'generalManager' AS DictCode, '总经理' AS DictName + UNION ALL SELECT 'employee_position', 2, 'deputyGeneralManager', '副总经理' + UNION ALL SELECT 'employee_position', 3, 'logisticsAdvisor', '物流顾问' + UNION ALL SELECT 'employee_position', 4, 'csManager', '客服主管' + UNION ALL SELECT 'employee_position', 5, 'csSpecialist', '客服专员' + UNION ALL SELECT 'employee_position', 6, 'opsManager', '运营经理' + UNION ALL SELECT 'employee_position', 7, 'opsSpecialist', '运营专员' + UNION ALL SELECT 'employee_position', 8, 'financeManager', '财务经理' + UNION ALL SELECT 'employee_position', 9, 'financeSpecialist', '财务专员' + UNION ALL SELECT 'employee_position', 10, 'warehouseManager', '仓储主管' + UNION ALL SELECT 'employee_position', 11, 'warehouseClerk', '仓管员' + UNION ALL SELECT 'employee_position', 12, 'customsSpecialist', '关务专员' + UNION ALL SELECT 'employee_position', 13, 'productManager', '产品经理' + UNION ALL SELECT 'employee_position', 14, 'techEngineer', '技术工程师' + UNION ALL SELECT 'employee_position', 15, 'hrAdmin', '人事行政' + UNION ALL SELECT 'employee_position', 16, 'marketingSpecialist', '市场专员' + UNION ALL SELECT 'employee_position', 17, 'dispatcher', '调度员' +) AS v +WHERE NOT EXISTS ( + SELECT 1 + FROM `t_dict` d + WHERE d.`DictType` = v.`DictType` + AND d.`DictCode` = v.`DictCode` + AND d.`IsDeleted` = 0 +); + +UPDATE `t_dict` +SET `IsDeleted` = 1, + `UpdateTime` = NOW() +WHERE `DictType` = 'employee_position' + AND `DictCode` IN ( + 'salesDirector', + 'salesManager', + 'salesSpecialist', + 'logisticsAdvisorDirector', + 'logisticsAdvisorManager' + ) + AND `IsDeleted` = 0; + +-- ========== 职级 employee_job_level(一级~五级) ========== +INSERT INTO `t_dict_type` (`DictType`, `Remark`, `TypeSort`, `IsDeleted`, `CreateUserId`) +SELECT 'employee_job_level', '员工职级', 0, 0, 0 +FROM DUAL +WHERE NOT EXISTS ( + SELECT 1 FROM `t_dict_type` WHERE `DictType` = 'employee_job_level' AND `IsDeleted` = 0 +); + +INSERT INTO `t_dict` (`DictType`, `DictSort`, `DictCode`, `DictName`, `IsDeleted`, `CreateUserId`) +SELECT v.`DictType`, v.`DictSort`, v.`DictCode`, v.`DictName`, 0, 0 +FROM ( + SELECT 'employee_job_level' AS DictType, 1 AS DictSort, '1' AS DictCode, '一级' AS DictName + UNION ALL SELECT 'employee_job_level', 2, '2', '二级' + UNION ALL SELECT 'employee_job_level', 3, '3', '三级' + UNION ALL SELECT 'employee_job_level', 4, '4', '四级' + UNION ALL SELECT 'employee_job_level', 5, '5', '五级' +) AS v +WHERE NOT EXISTS ( + SELECT 1 + FROM `t_dict` d + WHERE d.`DictType` = v.`DictType` + AND d.`DictCode` = v.`DictCode` + AND d.`IsDeleted` = 0 +); diff --git a/sql/migrate_sales_product_route_sort.sql b/sql/migrate_sales_product_route_sort.sql new file mode 100644 index 0000000..54d6fd1 --- /dev/null +++ b/sql/migrate_sales_product_route_sort.sql @@ -0,0 +1,36 @@ +-- t_sales_product:官网线路展示排序(幂等;列已存在则跳过) +-- 数值越小越靠前;默认 0 + +SET @db := DATABASE(); + +SET @col := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_sales_product' + AND COLUMN_NAME = 'RouteSort' +); +SET @sql := IF( + @col = 0, + 'ALTER TABLE `t_sales_product` ADD COLUMN `RouteSort` INT NOT NULL DEFAULT 0 COMMENT ''官网线路排序,越小越靠前'' AFTER `TradeTerms`', + 'SELECT ''skip RouteSort'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +SET @idx := ( + SELECT COUNT(*) + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_sales_product' + AND INDEX_NAME = 'idx_sp_route_sort' +); +SET @sql_idx := IF( + @idx = 0, + 'ALTER TABLE `t_sales_product` ADD KEY `idx_sp_route_sort` (`RouteSort`, `IsActive`)', + 'SELECT ''skip idx_sp_route_sort'' AS msg' +); +PREPARE stmt_idx FROM @sql_idx; +EXECUTE stmt_idx; +DEALLOCATE PREPARE stmt_idx; diff --git a/sql/migrate_t_9610_align_item_fields.sql b/sql/migrate_t_9610_align_item_fields.sql new file mode 100644 index 0000000..255c769 --- /dev/null +++ b/sql/migrate_t_9610_align_item_fields.sql @@ -0,0 +1,81 @@ +-- 9610 商品明细命名对齐 t_order_declaration(幂等) +-- ItemNo→Sku, ItemName→CnName, Gcode→ExHsCode, Price→UnitPrice, Qty→Quantity, +-- TotalAmount→Amount, DeclareUnit→Unit +-- 海关专属保留:Gmodel / Barcode / DestCountry / ItemCurrency / LegalQty / LegalUnit / Freight / SortNo + +SET @db := DATABASE(); + +-- ItemNo → Sku +SET @hasOld := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='ItemNo'); +SET @hasNew := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Sku'); +SET @sql := IF(@hasOld>0 AND @hasNew=0, + 'ALTER TABLE `t_9610_order_item` CHANGE COLUMN `ItemNo` `Sku` VARCHAR(32) NOT NULL DEFAULT '''' COMMENT ''SKU(对齐 t_order_declaration.Sku / 上游 itemNo)''', + 'SELECT ''skip ItemNo->Sku'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ItemName → CnName +SET @hasOld := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='ItemName'); +SET @hasNew := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='CnName'); +SET @sql := IF(@hasOld>0 AND @hasNew=0, + 'ALTER TABLE `t_9610_order_item` CHANGE COLUMN `ItemName` `CnName` VARCHAR(250) NOT NULL DEFAULT '''' COMMENT ''中文品名(对齐 t_order_declaration.CnName / 上游 itemName)''', + 'SELECT ''skip ItemName->CnName'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- Gcode → ExHsCode +SET @hasOld := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Gcode'); +SET @hasNew := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='ExHsCode'); +SET @sql := IF(@hasOld>0 AND @hasNew=0, + 'ALTER TABLE `t_9610_order_item` CHANGE COLUMN `Gcode` `ExHsCode` VARCHAR(10) NULL COMMENT ''出口海关编码(对齐 t_order_declaration.ExHsCode / 上游 gcode)''', + 'SELECT ''skip Gcode->ExHsCode'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- Price → UnitPrice +SET @hasOld := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Price'); +SET @hasNew := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='UnitPrice'); +SET @sql := IF(@hasOld>0 AND @hasNew=0, + 'ALTER TABLE `t_9610_order_item` CHANGE COLUMN `Price` `UnitPrice` DECIMAL(19,5) NOT NULL DEFAULT 0 COMMENT ''单价(对齐 t_order_declaration.UnitPrice)''', + 'SELECT ''skip Price->UnitPrice'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- TotalAmount → Amount(可能尚未存在 TotalAmount) +SET @hasOld := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='TotalAmount'); +SET @hasNew := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Amount'); +SET @sql := IF(@hasOld>0 AND @hasNew=0, + 'ALTER TABLE `t_9610_order_item` CHANGE COLUMN `TotalAmount` `Amount` DECIMAL(19,5) NULL COMMENT ''总价(对齐 t_order_declaration.Amount / 上游 totalPrice)''', + 'SELECT ''skip TotalAmount->Amount'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +SET @hasNew := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Amount'); +SET @sql := IF(@hasNew=0, + 'ALTER TABLE `t_9610_order_item` ADD COLUMN `Amount` DECIMAL(19,5) NULL COMMENT ''总价(对齐 t_order_declaration.Amount)'' AFTER `UnitPrice`', + 'SELECT ''skip add Amount'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- Qty → Quantity +SET @hasOld := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Qty'); +SET @hasNew := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Quantity'); +SET @sql := IF(@hasOld>0 AND @hasNew=0, + 'ALTER TABLE `t_9610_order_item` CHANGE COLUMN `Qty` `Quantity` DECIMAL(19,5) NOT NULL DEFAULT 0 COMMENT ''数量(对齐 t_order_declaration.Quantity,精度保留海关小数)''', + 'SELECT ''skip Qty->Quantity'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- DeclareUnit → Unit +SET @hasOld := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='DeclareUnit'); +SET @hasNew := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Unit'); +SET @sql := IF(@hasOld>0 AND @hasNew=0, + 'ALTER TABLE `t_9610_order_item` CHANGE COLUMN `DeclareUnit` `Unit` VARCHAR(3) NULL COMMENT ''计量单位(对齐 t_order_declaration.Unit / 上游 unit)''', + 'SELECT ''skip DeclareUnit->Unit'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +SET @hasNew := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Unit'); +SET @sql := IF(@hasNew=0, + 'ALTER TABLE `t_9610_order_item` ADD COLUMN `Unit` VARCHAR(3) NULL COMMENT ''计量单位(对齐 t_order_declaration.Unit)'' AFTER `LegalQty`', + 'SELECT ''skip add Unit'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- Gmodel 注释:海关申报要素(由运单 Model/Specifications/Attributes/Material 拼接) +SET @has := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Gmodel'); +SET @sql := IF(@has>0, + 'ALTER TABLE `t_9610_order_item` MODIFY COLUMN `Gmodel` VARCHAR(255) NULL COMMENT ''申报要素(海关;由运单型号/规格等拼接,上游 gmodel)''', + 'SELECT ''skip Gmodel comment'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/sql/migrate_t_9610_align_order_nos.sql b/sql/migrate_t_9610_align_order_nos.sql new file mode 100644 index 0000000..1efd19a --- /dev/null +++ b/sql/migrate_t_9610_align_order_nos.sql @@ -0,0 +1,118 @@ +-- 9610 单号命名对齐运单 t_order(幂等) +-- ReferenceNo → ClientNo(客户单号) +-- LogisticsNo 并入 ServiceNo(运单号)后删除 LogisticsNo + +SET @db := DATABASE(); + +-- 1) ReferenceNo → ClientNo +SET @hasRef := ( + SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='ReferenceNo' +); +SET @hasClient := ( + SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='ClientNo' +); +SET @sql := IF( + @hasRef > 0 AND @hasClient = 0, + 'ALTER TABLE `t_9610_order` CHANGE COLUMN `ReferenceNo` `ClientNo` VARCHAR(48) NOT NULL DEFAULT '''' COMMENT ''客户单号(对齐 t_order.ClientNo / 上游 referenceNo)''', + 'SELECT ''skip ReferenceNo->ClientNo'' AS msg' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- 索引名顺带调整(旧 idx_9610_ref → idx_9610_client_no) +SET @idxRef := ( + SELECT COUNT(*) FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND INDEX_NAME='idx_9610_ref' +); +SET @idxClient := ( + SELECT COUNT(*) FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND INDEX_NAME='idx_9610_client_no' +); +SET @sql := IF( + @idxRef > 0 AND @idxClient = 0, + 'ALTER TABLE `t_9610_order` RENAME INDEX `idx_9610_ref` TO `idx_9610_client_no`', + 'SELECT ''skip rename idx_9610_ref'' AS msg' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +SET @idxClient := ( + SELECT COUNT(*) FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND INDEX_NAME='idx_9610_client_no' +); +SET @sql := IF( + @idxClient = 0, + 'ALTER TABLE `t_9610_order` ADD KEY `idx_9610_client_no` (`ClientNo`)', + 'SELECT ''skip add idx_9610_client_no'' AS msg' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- 2) LogisticsNo → 回填 ServiceNo,再删列 +SET @hasLog := ( + SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='LogisticsNo' +); +SET @sql := IF( + @hasLog > 0, + 'UPDATE `t_9610_order` SET `ServiceNo` = NULLIF(TRIM(`LogisticsNo`), '''') WHERE (`ServiceNo` IS NULL OR TRIM(`ServiceNo`) = '''') AND `LogisticsNo` IS NOT NULL AND TRIM(`LogisticsNo`) <> ''''', + 'SELECT ''skip backfill ServiceNo'' AS msg' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +SET @idxLog := ( + SELECT COUNT(*) FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND INDEX_NAME='idx_9610_logistics' +); +SET @sql := IF( + @idxLog > 0, + 'ALTER TABLE `t_9610_order` DROP INDEX `idx_9610_logistics`', + 'SELECT ''skip drop idx_9610_logistics'' AS msg' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +SET @hasLog := ( + SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='LogisticsNo' +); +SET @sql := IF( + @hasLog > 0, + 'ALTER TABLE `t_9610_order` DROP COLUMN `LogisticsNo`', + 'SELECT ''skip drop LogisticsNo'' AS msg' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ServiceNo 索引(检索) +SET @idxSvc := ( + SELECT COUNT(*) FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND INDEX_NAME='idx_9610_service_no' +); +SET @sql := IF( + @idxSvc = 0, + 'ALTER TABLE `t_9610_order` ADD KEY `idx_9610_service_no` (`ServiceNo`)', + 'SELECT ''skip idx_9610_service_no'' AS msg' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- OrderNo 注释对齐:海关下游订单编号(非运单 DownstreamServiceNo) +SET @hasOrderNo := ( + SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='OrderNo' +); +SET @sql := IF( + @hasOrderNo > 0, + 'ALTER TABLE `t_9610_order` MODIFY COLUMN `OrderNo` VARCHAR(32) NULL COMMENT ''海关下游订单编号(申报回写,非 t_order.DownstreamServiceNo)''', + 'SELECT ''skip OrderNo comment'' AS msg' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- DownstreamRefNo 注释 +SET @hasDr := ( + SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='DownstreamRefNo' +); +SET @sql := IF( + @hasDr > 0, + 'ALTER TABLE `t_9610_order` MODIFY COLUMN `DownstreamRefNo` VARCHAR(32) NULL COMMENT ''申报回写的 referenceNo 快照''', + 'SELECT ''skip DownstreamRefNo comment'' AS msg' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/sql/migrate_t_9610_manifest_fields.sql b/sql/migrate_t_9610_manifest_fields.sql new file mode 100644 index 0000000..59df813 --- /dev/null +++ b/sql/migrate_t_9610_manifest_fields.sql @@ -0,0 +1,170 @@ +-- 9610:补齐「获取清单数据」回写字段(幂等;列已存在则跳过) +-- 字段名为 OMS 自有命名,与上游 CEB 字段对照见注释 + +SET @db := DATABASE(); + +-- ========== t_9610_order ========== + +-- EnterpriseBizNo ← copNo 企业唯一编号 +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='EnterpriseBizNo'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `EnterpriseBizNo` VARCHAR(48) NULL COMMENT ''企业唯一编号(上游 copNo)'' AFTER `DownstreamRefNo`', 'SELECT ''skip EnterpriseBizNo'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ManifestNo ← invtNo 清单编号 +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='ManifestNo'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `ManifestNo` VARCHAR(48) NULL COMMENT ''清单编号(上游 invtNo)'' AFTER `EnterpriseBizNo`', 'SELECT ''skip ManifestNo'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ClearanceTime ← clearanceTime 结关日期(原文,格式不固定) +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='ClearanceTime'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `ClearanceTime` VARCHAR(48) NULL COMMENT ''结关日期原文'' AFTER `ManifestNo`', 'SELECT ''skip ClearanceTime'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- CustomsInboundTime ← warehouseTime 海关入库时间 +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='CustomsInboundTime'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `CustomsInboundTime` VARCHAR(48) NULL COMMENT ''海关入库时间原文'' AFTER `ClearanceTime`', 'SELECT ''skip CustomsInboundTime'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- CustomsState ← customsStatus 海关状态 +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='CustomsState'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `CustomsState` VARCHAR(4) NULL COMMENT ''海关状态'' AFTER `CustomsInboundTime`', 'SELECT ''skip CustomsState'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- DeclareCustomsCode ← customsCode 申报地海关 +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='DeclareCustomsCode'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `DeclareCustomsCode` VARCHAR(4) NULL COMMENT ''申报地海关代码'' AFTER `CustomsState`', 'SELECT ''skip DeclareCustomsCode'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- EbpCode ← ebpCode +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='EbpCode'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `EbpCode` VARCHAR(18) NULL COMMENT ''电商平台代码'' AFTER `DeclareCustomsCode`', 'SELECT ''skip EbpCode'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- EbpName ← ebpName +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='EbpName'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `EbpName` VARCHAR(100) NULL COMMENT ''电商平台名称'' AFTER `EbpCode`', 'SELECT ''skip EbpName'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- LogisticsCorpCode ← logisticsCode +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='LogisticsCorpCode'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `LogisticsCorpCode` VARCHAR(18) NULL COMMENT ''物流企业代码'' AFTER `EbpName`', 'SELECT ''skip LogisticsCorpCode'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- LogisticsCorpName ← logisticsName +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='LogisticsCorpName'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `LogisticsCorpName` VARCHAR(100) NULL COMMENT ''物流企业名称'' AFTER `LogisticsCorpCode`', 'SELECT ''skip LogisticsCorpName'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- IeMark ← ieFlag I/E +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='IeMark'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `IeMark` VARCHAR(4) NULL COMMENT ''进出口标记 I/E'' AFTER `LogisticsCorpName`', 'SELECT ''skip IeMark'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ExportPortCode ← portCode +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='ExportPortCode'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `ExportPortCode` VARCHAR(4) NULL COMMENT ''出口口岸代码'' AFTER `IeMark`', 'SELECT ''skip ExportPortCode'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ExportDate ← ieDate +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='ExportDate'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `ExportDate` VARCHAR(32) NULL COMMENT ''出口日期原文'' AFTER `ExportPortCode`', 'SELECT ''skip ExportDate'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- DeclareAgentCode ← agentCode +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='DeclareAgentCode'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `DeclareAgentCode` VARCHAR(18) NULL COMMENT ''申报企业代码'' AFTER `ExportDate`', 'SELECT ''skip DeclareAgentCode'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- DeclareAgentName ← agentName +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='DeclareAgentName'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `DeclareAgentName` VARCHAR(100) NULL COMMENT ''申报企业名称'' AFTER `DeclareAgentCode`', 'SELECT ''skip DeclareAgentName'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- TradeModeCode ← tradeMode +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='TradeModeCode'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `TradeModeCode` VARCHAR(4) NULL COMMENT ''贸易方式代码'' AFTER `DeclareAgentName`', 'SELECT ''skip TradeModeCode'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- TransportMode ← trafMode +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='TransportMode'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `TransportMode` VARCHAR(4) NULL COMMENT ''运输方式代码'' AFTER `TradeModeCode`', 'SELECT ''skip TransportMode'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- FreightCurrency ← fCurrency +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='FreightCurrency'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `FreightCurrency` VARCHAR(4) NULL COMMENT ''运费币制'' AFTER `Freight`', 'SELECT ''skip FreightCurrency'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- FreightMark ← fFlag 1率/2单价/3总价 +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='FreightMark'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `FreightMark` INT NULL COMMENT ''运费标志 1率2单价3总价'' AFTER `FreightCurrency`', 'SELECT ''skip FreightMark'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- PackageType ← wrapType +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='PackageType'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `PackageType` INT NULL COMMENT ''包装种类代码'' AFTER `FreightMark`', 'SELECT ''skip PackageType'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- PackageQty ← packNo +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='PackageQty'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `PackageQty` INT NULL COMMENT ''件数'' AFTER `PackageType`', 'SELECT ''skip PackageQty'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ManifestSyncTime 最近一次清单回写时间 +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='ManifestSyncTime'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order` ADD COLUMN `ManifestSyncTime` DATETIME NULL COMMENT ''清单数据最近同步时间'' AFTER `DeclareTime`', 'SELECT ''skip ManifestSyncTime'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- 运费精度对齐上游 DECIMAL(19,5) +SET @colType := ( + SELECT COLUMN_TYPE FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='Freight' +); +SET @sql := IF( + @colType IS NOT NULL AND @colType NOT LIKE 'decimal(19,5)%', + 'ALTER TABLE `t_9610_order` MODIFY COLUMN `Freight` DECIMAL(19,5) NULL COMMENT ''运费''', + 'SELECT ''skip Freight precision'' AS msg' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ManifestNo 索引(幂等) +SET @idx := (SELECT COUNT(*) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND INDEX_NAME='idx_9610_manifest'); +SET @sql := IF(@idx=0, 'ALTER TABLE `t_9610_order` ADD KEY `idx_9610_manifest` (`ManifestNo`)', 'SELECT ''skip idx_9610_manifest'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ========== t_9610_order_item ========== + +-- Barcode ← barCode +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Barcode'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order_item` ADD COLUMN `Barcode` VARCHAR(255) NULL COMMENT ''条形码'' AFTER `Gmodel`', 'SELECT ''skip Barcode'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- DestCountry ← country 目的国 +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='DestCountry'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order_item` ADD COLUMN `DestCountry` VARCHAR(255) NULL COMMENT ''目的国(地区)代码'' AFTER `Barcode`', 'SELECT ''skip DestCountry'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- ItemCurrency ← currency +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='ItemCurrency'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order_item` ADD COLUMN `ItemCurrency` VARCHAR(3) NULL COMMENT ''币制'' AFTER `DestCountry`', 'SELECT ''skip ItemCurrency'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- LegalQty ← qty1 法定数量 +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='LegalQty'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order_item` ADD COLUMN `LegalQty` DECIMAL(19,5) NULL COMMENT ''法定数量'' AFTER `Quantity`', 'SELECT ''skip LegalQty'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- Unit ← unit(对齐运单;旧名 DeclareUnit 由 align_item_fields 迁移) +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Unit'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order_item` ADD COLUMN `Unit` VARCHAR(3) NULL COMMENT ''计量单位'' AFTER `LegalQty`', 'SELECT ''skip Unit'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- LegalUnit ← unit1 +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='LegalUnit'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order_item` ADD COLUMN `LegalUnit` VARCHAR(3) NULL COMMENT ''法定计量单位'' AFTER `Unit`', 'SELECT ''skip LegalUnit'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- Amount ← totalPrice +SET @col := (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Amount'); +SET @sql := IF(@col=0, 'ALTER TABLE `t_9610_order_item` ADD COLUMN `Amount` DECIMAL(19,5) NULL COMMENT ''总价'' AFTER `UnitPrice`', 'SELECT ''skip Amount'' AS msg'); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/sql/migrate_t_9610_order.sql b/sql/migrate_t_9610_order.sql new file mode 100644 index 0000000..25c5f1c --- /dev/null +++ b/sql/migrate_t_9610_order.sql @@ -0,0 +1,122 @@ +-- 9610 汇总申报单(ExportCustomsMode=9610Summary) +-- 幂等:表已存在则跳过 + +SET @db := DATABASE(); + +-- t_9610_order +SET @exists := ( + SELECT COUNT(*) + FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_9610_order' +); +SET @sql := IF( + @exists = 0, + 'CREATE TABLE `t_9610_order` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键'', + `OrderId` INT NOT NULL COMMENT ''关联运单 t_order.Id'', + `ServiceNo` VARCHAR(64) NULL COMMENT ''运单号冗余'', + `CustomerId` INT NOT NULL DEFAULT 0 COMMENT ''客户Id'', + `Status` VARCHAR(16) NOT NULL DEFAULT ''pending'' COMMENT ''pending待申报 / declared已申报'', + `PlatformCode` VARCHAR(16) NOT NULL DEFAULT '''' COMMENT ''电商平台'', + `EcomCorpCode` VARCHAR(18) NULL COMMENT ''电商企业代码'', + `EcomCorpName` VARCHAR(100) NULL COMMENT ''电商企业名称'', + `ProducerCode` VARCHAR(18) NULL COMMENT ''生产销售单位代码'', + `ProducerName` VARCHAR(100) NULL COMMENT ''生产销售单位'', + `ClientNo` VARCHAR(48) NOT NULL DEFAULT '''' COMMENT ''客户单号(对齐 t_order.ClientNo)'', + `BusinessType` CHAR(1) NOT NULL DEFAULT ''B'' COMMENT ''业务类型 A简化/B汇总'', + `Region` VARCHAR(10) NULL COMMENT ''区域 SZ/other'', + `AgentDeclare` VARCHAR(2) NULL COMMENT ''是否代理申报 是/否'', + `ActualSellerCode` VARCHAR(18) NULL COMMENT ''实际卖家信用代码'', + `PreRecordFlag` CHAR(1) NULL COMMENT ''汇总预录 0已预录 1未预录'', + `IsSummarySimple` TINYINT NOT NULL DEFAULT 0 COMMENT ''是否汇总简化申报'', + `GrossWeight` DECIMAL(19,5) NOT NULL DEFAULT 0 COMMENT ''毛重KG'', + `Currency` VARCHAR(4) NOT NULL DEFAULT ''CNY'' COMMENT ''币制'', + `DestCountry` VARCHAR(4) NOT NULL DEFAULT '''' COMMENT ''目的国'', + `Freight` DECIMAL(19,5) NULL COMMENT ''运费'', + `FreightCurrency` VARCHAR(4) NULL COMMENT ''运费币制'', + `FreightMark` INT NULL COMMENT ''运费标志 1率2单价3总价'', + `PackageType` INT NULL COMMENT ''包装种类代码'', + `PackageQty` INT NULL COMMENT ''件数'', + `ShipmentNo` VARCHAR(32) NULL COMMENT ''出货单号'', + `CustomsOrderNo` VARCHAR(32) NULL COMMENT ''海关订单号(申报回写)'', + `DownstreamRefNo` VARCHAR(32) NULL COMMENT ''申报回写的 referenceNo 快照'', + `EnterpriseBizNo` VARCHAR(48) NULL COMMENT ''企业唯一编号(上游 copNo)'', + `ManifestNo` VARCHAR(48) NULL COMMENT ''清单编号(上游 invtNo)'', + `ClearanceTime` VARCHAR(48) NULL COMMENT ''结关日期原文'', + `CustomsInboundTime` VARCHAR(48) NULL COMMENT ''海关入库时间原文'', + `CustomsState` VARCHAR(4) NULL COMMENT ''海关状态'', + `DeclareCustomsCode` VARCHAR(4) NULL COMMENT ''申报地海关代码'', + `PlatformCorpCode` VARCHAR(18) NULL COMMENT ''电商平台代码'', + `PlatformName` VARCHAR(100) NULL COMMENT ''电商平台名称'', + `LogisticsCorpCode` VARCHAR(18) NULL COMMENT ''物流企业代码'', + `LogisticsCorpName` VARCHAR(100) NULL COMMENT ''物流企业名称'', + `IeMark` VARCHAR(4) NULL COMMENT ''进出口标记 I/E'', + `ExportPortCode` VARCHAR(4) NULL COMMENT ''出口口岸代码'', + `ExportDate` VARCHAR(32) NULL COMMENT ''出口日期原文'', + `DeclareAgentCode` VARCHAR(18) NULL COMMENT ''申报企业代码'', + `DeclareAgentName` VARCHAR(100) NULL COMMENT ''申报企业名称'', + `TradeModeCode` VARCHAR(4) NULL COMMENT ''贸易方式代码'', + `TransportMode` VARCHAR(4) NULL COMMENT ''运输方式代码'', + `DeclareTime` DATETIME NULL COMMENT ''申报成功时间'', + `ManifestSyncTime` DATETIME NULL COMMENT ''清单数据最近同步时间'', + `FailReason` VARCHAR(512) NULL COMMENT ''最近失败原因'', + `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除'', + `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'', + `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'', + `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'', + `UpdateUserId` INT NULL COMMENT ''更新人'', + `UpdateTime` DATETIME NULL COMMENT ''更新时间'', + PRIMARY KEY (`Id`), + UNIQUE KEY `uk_9610_order_id` (`OrderId`), + KEY `idx_9610_status_ctime` (`Status`, `CreateTime`), + KEY `idx_9610_service_no` (`ServiceNo`), + KEY `idx_9610_client_no` (`ClientNo`), + KEY `idx_9610_customer` (`CustomerId`, `CreateTime`), + KEY `idx_9610_manifest` (`ManifestNo`) +) COMMENT=''9610汇总申报单''', + 'SELECT ''skip t_9610_order'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +-- t_9610_order_item +SET @exists := ( + SELECT COUNT(*) + FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_9610_order_item' +); +SET @sql := IF( + @exists = 0, + 'CREATE TABLE `t_9610_order_item` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键'', + `Customs9610OrderId` INT NOT NULL COMMENT ''t_9610_order.Id'', + `OrderDeclarationId` INT NULL COMMENT ''溯源 t_order_declaration.Id'', + `Sku` VARCHAR(32) NOT NULL DEFAULT '''' COMMENT ''SKU(对齐 t_order_declaration.Sku)'', + `CnName` VARCHAR(250) NOT NULL DEFAULT '''' COMMENT ''中文品名(对齐 t_order_declaration.CnName)'', + `ExHsCode` VARCHAR(10) NULL COMMENT ''出口海关编码(对齐 t_order_declaration.ExHsCode)'', + `DeclareElement` VARCHAR(255) NULL COMMENT ''申报要素'', + `Barcode` VARCHAR(255) NULL COMMENT ''条形码'', + `DestCountry` VARCHAR(255) NULL COMMENT ''目的国(地区)代码'', + `ItemCurrency` VARCHAR(3) NULL COMMENT ''币制'', + `UnitPrice` DECIMAL(19,5) NOT NULL DEFAULT 0 COMMENT ''单价(对齐 t_order_declaration.UnitPrice)'', + `Amount` DECIMAL(19,5) NULL COMMENT ''总价(对齐 t_order_declaration.Amount)'', + `Quantity` DECIMAL(19,5) NOT NULL DEFAULT 0 COMMENT ''数量(对齐 t_order_declaration.Quantity)'', + `LegalQty` DECIMAL(19,5) NULL COMMENT ''法定数量'', + `Unit` VARCHAR(3) NULL COMMENT ''计量单位(对齐 t_order_declaration.Unit)'', + `LegalUnit` VARCHAR(3) NULL COMMENT ''法定计量单位'', + `Freight` DECIMAL(12,4) NULL COMMENT ''行运费'', + `SortNo` INT NOT NULL DEFAULT 0 COMMENT ''排序'', + `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除'', + `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'', + `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'', + `UpdateUserId` INT NULL COMMENT ''更新人'', + `UpdateTime` DATETIME NULL COMMENT ''更新时间'', + PRIMARY KEY (`Id`), + KEY `idx_9610_item_header` (`Customs9610OrderId`, `IsDeleted`) +) COMMENT=''9610申报商品明细''', + 'SELECT ''skip t_9610_order_item'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; diff --git a/sql/migrate_t_9610_rename_by_meaning.sql b/sql/migrate_t_9610_rename_by_meaning.sql new file mode 100644 index 0000000..0a3a452 --- /dev/null +++ b/sql/migrate_t_9610_rename_by_meaning.sql @@ -0,0 +1,90 @@ +-- 9610 其余字段按业务含义重命名(幂等 CHANGE) +-- 申报头:Ebp→PlatformCode, Ebc*→EcomCorp*, Owner*→Producer*, FormType→BusinessType, +-- IsAgent→AgentDeclare, ActBuyer→ActualSellerCode, SoLabelFlag→PreRecordFlag, +-- IsSimple→IsSummarySimple, Country→DestCountry, BlNo→ShipmentNo, +-- EbpCode/EbpName→PlatformCorpCode/PlatformName, OrderNo→CustomsOrderNo +-- 明细:Gmodel→DeclareElement + +SET @db := DATABASE(); + +-- helper pattern repeated + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='Ebp'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='PlatformCode'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `Ebp` `PlatformCode` VARCHAR(16) NOT NULL DEFAULT '''' COMMENT ''电商平台''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='EbcCode'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='EcomCorpCode'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `EbcCode` `EcomCorpCode` VARCHAR(18) NULL COMMENT ''电商企业代码''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='EbcName'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='EcomCorpName'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `EbcName` `EcomCorpName` VARCHAR(100) NULL COMMENT ''电商企业名称''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='OwnerCode'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='ProducerCode'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `OwnerCode` `ProducerCode` VARCHAR(18) NULL COMMENT ''生产销售单位代码''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='OwnerName'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='ProducerName'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `OwnerName` `ProducerName` VARCHAR(100) NULL COMMENT ''生产销售单位''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='FormType'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='BusinessType'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `FormType` `BusinessType` CHAR(1) NOT NULL DEFAULT ''B'' COMMENT ''业务类型 A简化/B汇总''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='IsAgent'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='AgentDeclare'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `IsAgent` `AgentDeclare` VARCHAR(2) NULL COMMENT ''是否代理申报 是/否''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='ActBuyer'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='ActualSellerCode'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `ActBuyer` `ActualSellerCode` VARCHAR(18) NULL COMMENT ''实际卖家信用代码''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='SoLabelFlag'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='PreRecordFlag'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `SoLabelFlag` `PreRecordFlag` CHAR(1) NULL COMMENT ''汇总预录 0已预录/1未预录''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='IsSimple'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='IsSummarySimple'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `IsSimple` `IsSummarySimple` TINYINT NOT NULL DEFAULT 0 COMMENT ''是否汇总简化申报''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='Country'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='DestCountry'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `Country` `DestCountry` VARCHAR(4) NOT NULL DEFAULT '''' COMMENT ''目的国''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='BlNo'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='ShipmentNo'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `BlNo` `ShipmentNo` VARCHAR(32) NULL COMMENT ''出货单号''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='OrderNo'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='CustomsOrderNo'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `OrderNo` `CustomsOrderNo` VARCHAR(32) NULL COMMENT ''海关订单号''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='EbpCode'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='PlatformCorpCode'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `EbpCode` `PlatformCorpCode` VARCHAR(18) NULL COMMENT ''电商平台代码''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='EbpName'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order' AND COLUMN_NAME='PlatformName'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order` CHANGE COLUMN `EbpName` `PlatformName` VARCHAR(100) NULL COMMENT ''电商平台名称''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; + +SET @o:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='Gmodel'); +SET @n:=(SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_9610_order_item' AND COLUMN_NAME='DeclareElement'); +SET @sql:=IF(@o>0 AND @n=0,'ALTER TABLE `t_9610_order_item` CHANGE COLUMN `Gmodel` `DeclareElement` VARCHAR(255) NULL COMMENT ''申报要素''','SELECT 1'); +PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s; diff --git a/sql/migrate_t_order_exception_event_handler.sql b/sql/migrate_t_order_exception_event_handler.sql new file mode 100644 index 0000000..96e6284 --- /dev/null +++ b/sql/migrate_t_order_exception_event_handler.sql @@ -0,0 +1,118 @@ +-- 订单异常事件表:补齐 Handler* / ConcurrencyStamp(幂等;列已存在则自动跳过) +-- 修复:Unknown column 'HandlerNames' / 'ConcurrencyStamp' in 'field list' +-- MySQL 5.7+ / 8.0 + +SET @db := DATABASE(); + +-- HandlerNames +SET @col := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_order_exception_event' + AND COLUMN_NAME = 'HandlerNames' +); +SET @sql := IF( + @col = 0, + 'ALTER TABLE `t_order_exception_event` ADD COLUMN `HandlerNames` VARCHAR(256) NULL COMMENT ''处理人快照''', + 'SELECT ''skip HandlerNames'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +-- HandlerType +SET @col := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_order_exception_event' + AND COLUMN_NAME = 'HandlerType' +); +SET @sql := IF( + @col = 0, + 'ALTER TABLE `t_order_exception_event` ADD COLUMN `HandlerType` VARCHAR(16) NULL COMMENT ''处理人类型''', + 'SELECT ''skip HandlerType'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +-- HandlerUserId +SET @col := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_order_exception_event' + AND COLUMN_NAME = 'HandlerUserId' +); +SET @sql := IF( + @col = 0, + 'ALTER TABLE `t_order_exception_event` ADD COLUMN `HandlerUserId` INT NULL COMMENT ''处理人用户Id(customer 时为订单客户账号)''', + 'SELECT ''skip HandlerUserId'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +-- ConcurrencyStamp(AggregateRoot 并发戳;避免 DEFAULT(UUID()) 触发 1674 复制不安全) +SET @col := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_order_exception_event' + AND COLUMN_NAME = 'ConcurrencyStamp' +); +SET @sql := IF( + @col = 0, + 'ALTER TABLE `t_order_exception_event` ADD COLUMN `ConcurrencyStamp` CHAR(36) NULL COMMENT ''并发戳''', + 'SELECT ''skip ConcurrencyStamp add'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +SET @col := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_order_exception_event' + AND COLUMN_NAME = 'ConcurrencyStamp' +); +SET @sql := IF( + @col > 0, + 'UPDATE `t_order_exception_event` + SET `ConcurrencyStamp` = LOWER(CONCAT( + LPAD(HEX(`Id`), 8, ''0''), + ''-0000-4000-8000-'', + LPAD(HEX(`Id` * 9973), 12, ''0'') + )) + WHERE `ConcurrencyStamp` IS NULL OR `ConcurrencyStamp` = ''''', + 'SELECT ''skip ConcurrencyStamp backfill'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +SET @col := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_order_exception_event' + AND COLUMN_NAME = 'ConcurrencyStamp' +); +SET @isNullable := ( + SELECT IFNULL(MAX(CASE WHEN IS_NULLABLE = 'YES' THEN 1 ELSE 0 END), 0) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_order_exception_event' + AND COLUMN_NAME = 'ConcurrencyStamp' +); +SET @sql := IF( + @col > 0 AND @isNullable = 1, + 'ALTER TABLE `t_order_exception_event` MODIFY COLUMN `ConcurrencyStamp` CHAR(36) NOT NULL COMMENT ''并发戳''', + 'SELECT ''skip ConcurrencyStamp not null'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; diff --git a/sql/migrate_t_order_fulfillment_type.sql b/sql/migrate_t_order_fulfillment_type.sql new file mode 100644 index 0000000..ff3cd2c --- /dev/null +++ b/sql/migrate_t_order_fulfillment_type.sql @@ -0,0 +1,70 @@ +-- 代发订单:t_order 履约类型字段(幂等;列/索引已存在则自动跳过) +-- MySQL 5.7+ / 8.0 + +SET @db := DATABASE(); + +-- FulfillmentType +SET @col := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_order' + AND COLUMN_NAME = 'FulfillmentType' +); +SET @sql := IF( + @col = 0, + 'ALTER TABLE `t_order` ADD COLUMN `FulfillmentType` VARCHAR(16) NULL DEFAULT ''direct'' COMMENT ''履约类型 direct/warehouse'' AFTER `AdditionalServices`', + 'SELECT ''skip FulfillmentType'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +-- FulfillmentSource +SET @col := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_order' + AND COLUMN_NAME = 'FulfillmentSource' +); +SET @sql := IF( + @col = 0, + 'ALTER TABLE `t_order` ADD COLUMN `FulfillmentSource` VARCHAR(32) NULL COMMENT ''代发来源 storeFulfill/postBind'' AFTER `FulfillmentType`', + 'SELECT ''skip FulfillmentSource'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +-- idx_ord_fulfillment_customer +SET @idx := ( + SELECT COUNT(*) + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_order' + AND INDEX_NAME = 'idx_ord_fulfillment_customer' +); +SET @sql := IF( + @idx = 0, + 'ALTER TABLE `t_order` ADD KEY `idx_ord_fulfillment_customer` (`FulfillmentType`, `CustomerId`, `OrderStatus`)', + 'SELECT ''skip idx_ord_fulfillment_customer'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +-- 历史:已有绑定行的订单标记为 warehouse +UPDATE `t_order` o +INNER JOIN ( + SELECT DISTINCT b.`OrderId` + FROM `t_order_stock_bind` b + WHERE b.`IsDeleted` = 0 + AND b.`Status` IN ('bound', 'deducted') +) x ON x.`OrderId` = o.`Id` +SET o.`FulfillmentType` = 'warehouse'; + +-- 其余空值兜底为 direct +UPDATE `t_order` +SET `FulfillmentType` = 'direct' +WHERE `FulfillmentType` IS NULL OR `FulfillmentType` = ''; diff --git a/sql/migrate_t_pickup_order_line_service_no.sql b/sql/migrate_t_pickup_order_line_service_no.sql new file mode 100644 index 0000000..db7d663 --- /dev/null +++ b/sql/migrate_t_pickup_order_line_service_no.sql @@ -0,0 +1,49 @@ +-- 揽收明细:补齐运单号/客户单号快照(幂等;列已存在则跳过) +-- 对应实体 PickupOrderLine.ServiceNo / ClientNo +-- 报错 Unknown column 'ServiceNo' in 'field list' 时执行本脚本 +-- MySQL 5.7+ / 8.0 + +SET @db := DATABASE(); + +-- ServiceNo +SET @col := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_pickup_order_line' + AND COLUMN_NAME = 'ServiceNo' +); +SET @sql := IF( + @col = 0, + 'ALTER TABLE `t_pickup_order_line` ADD COLUMN `ServiceNo` VARCHAR(64) NULL COMMENT ''运单号快照(便于列表)'' AFTER `OrderId`', + 'SELECT ''skip ServiceNo'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +-- ClientNo +SET @col := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_pickup_order_line' + AND COLUMN_NAME = 'ClientNo' +); +SET @sql := IF( + @col = 0, + 'ALTER TABLE `t_pickup_order_line` ADD COLUMN `ClientNo` VARCHAR(64) NULL COMMENT ''客户单号快照'' AFTER `ServiceNo`', + 'SELECT ''skip ClientNo'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +-- 存量行从订单表回填快照(仅空值) +UPDATE `t_pickup_order_line` pl +INNER JOIN `t_order` o ON o.`Id` = pl.`OrderId` +SET + pl.`ServiceNo` = IFNULL(NULLIF(pl.`ServiceNo`, ''), o.`ServiceNo`), + pl.`ClientNo` = IFNULL(NULLIF(pl.`ClientNo`, ''), o.`ClientNo`) +WHERE pl.`IsDeleted` = 0 + AND (pl.`ServiceNo` IS NULL OR pl.`ServiceNo` = '' OR pl.`ClientNo` IS NULL OR pl.`ClientNo` = ''); diff --git a/sql/migrate_user_wecom_kf_url.sql b/sql/migrate_user_wecom_kf_url.sql new file mode 100644 index 0000000..29d1e8a --- /dev/null +++ b/sql/migrate_user_wecom_kf_url.sql @@ -0,0 +1,20 @@ +-- user 表:企业微信客服接入链接(幂等;列已存在则跳过) +-- MySQL 5.7+ / 8.0 + +SET @db := DATABASE(); + +SET @col := ( + SELECT COUNT(*) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 'user' + AND COLUMN_NAME = 'WecomKfUrl' +); +SET @sql := IF( + @col = 0, + 'ALTER TABLE `user` ADD COLUMN `WecomKfUrl` VARCHAR(512) NULL COMMENT ''企业微信客服接入链接''', + 'SELECT ''skip WecomKfUrl'' AS msg' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; diff --git a/src/Oms.Application/Dtos/Ai/AiDtos.cs b/src/Oms.Application/Dtos/Ai/AiDtos.cs new file mode 100644 index 0000000..7cb0f98 --- /dev/null +++ b/src/Oms.Application/Dtos/Ai/AiDtos.cs @@ -0,0 +1,72 @@ +using System.ComponentModel.DataAnnotations; + +namespace Oms.Application.Dtos.Ai; + +public class AiProviderOutput +{ + public int Id { get; set; } + + public string ProviderKey { get; set; } = string.Empty; + + public string ProviderType { get; set; } = string.Empty; + + public string DisplayName { get; set; } = string.Empty; + + public string BaseUrl { get; set; } = string.Empty; + + public string? ApiKey { get; set; } + + public string? ApiSecret { get; set; } + + public bool IsDefault { get; set; } + + public bool Enabled { get; set; } +} + +public class AiProviderSaveInput +{ + [Required] + public string ProviderKey { get; set; } = string.Empty; + + [Required] + public string ProviderType { get; set; } = string.Empty; + + [Required] + public string DisplayName { get; set; } = string.Empty; + + [Required] + public string BaseUrl { get; set; } = string.Empty; + + public string? ApiKey { get; set; } + + public string? ApiSecret { get; set; } + + public bool IsDefault { get; set; } + + public bool Enabled { get; set; } = true; +} + +public class AiChatInput +{ + [Required] + public string ProviderKey { get; set; } = string.Empty; + + public string? Model { get; set; } + + [Required] + public List Messages { get; set; } = []; + + public string Scene { get; set; } = "assistant"; +} + +public class AiChatMessageInput +{ + public string Role { get; set; } = "user"; + + public string Content { get; set; } = string.Empty; +} + +public class AiChatOutput +{ + public string Content { get; set; } = string.Empty; +} diff --git a/src/Oms.Application/Dtos/Ai/AiSkillDtos.cs b/src/Oms.Application/Dtos/Ai/AiSkillDtos.cs new file mode 100644 index 0000000..62d364a --- /dev/null +++ b/src/Oms.Application/Dtos/Ai/AiSkillDtos.cs @@ -0,0 +1,70 @@ +using System.ComponentModel.DataAnnotations; + +namespace Oms.Application.Dtos.Ai; + +public class AiSkillOutput +{ + public int Id { get; set; } + + public string SkillKey { get; set; } = string.Empty; + + public string Scene { get; set; } = string.Empty; + + public string Name { get; set; } = string.Empty; + + public string? Description { get; set; } + + public string Content { get; set; } = string.Empty; + + public int SortOrder { get; set; } + + public bool Enabled { get; set; } +} + +public class AiSkillListInput +{ + /// 可选场景过滤 + public string? Scene { get; set; } + + /// 是否包含正文;调用方列表可 false,管理页 true + public bool IncludeContent { get; set; } = true; + + /// 是否仅启用 + public bool EnabledOnly { get; set; } +} + +public class AiSkillGetInput +{ + public int? Id { get; set; } + + public string? SkillKey { get; set; } +} + +public class AiSkillSaveInput +{ + public int? Id { get; set; } + + [Required] + public string SkillKey { get; set; } = string.Empty; + + [Required] + public string Scene { get; set; } = string.Empty; + + [Required] + public string Name { get; set; } = string.Empty; + + public string? Description { get; set; } + + [Required] + public string Content { get; set; } = string.Empty; + + public int SortOrder { get; set; } + + public bool Enabled { get; set; } = true; +} + +public class AiSkillDeleteInput +{ + [Required] + public int Id { get; set; } +} diff --git a/src/Oms.Application/Dtos/Channels/IssueTemplateOutput.cs b/src/Oms.Application/Dtos/Channels/IssueTemplateOutput.cs index aa30bb5..c9879a4 100644 --- a/src/Oms.Application/Dtos/Channels/IssueTemplateOutput.cs +++ b/src/Oms.Application/Dtos/Channels/IssueTemplateOutput.cs @@ -23,6 +23,14 @@ public class IssueTemplateOutput public List NotifyMethods { get; set; } = []; + public string? HandlerType { get; set; } + + public string? HandlerTypeName { get; set; } + + public int? HandlerUserId { get; set; } + + public string? HandlerUserName { get; set; } + public byte Status { get; set; } public DateTime CreateTime { get; set; } diff --git a/src/Oms.Application/Dtos/Channels/IssueTemplateSaveInput.cs b/src/Oms.Application/Dtos/Channels/IssueTemplateSaveInput.cs index 9ae17c6..49d5600 100644 --- a/src/Oms.Application/Dtos/Channels/IssueTemplateSaveInput.cs +++ b/src/Oms.Application/Dtos/Channels/IssueTemplateSaveInput.cs @@ -19,5 +19,9 @@ public class IssueTemplateSaveInput public string? NotifyMethod { get; set; } + public string? HandlerType { get; set; } + + public int? HandlerUserId { get; set; } + public EnableStatus Status { get; set; } = EnableStatus.Enabled; } diff --git a/src/Oms.Application/Dtos/Channels/SalesProductBillingSimulateDtos.cs b/src/Oms.Application/Dtos/Channels/SalesProductBillingSimulateDtos.cs new file mode 100644 index 0000000..fcda3e1 --- /dev/null +++ b/src/Oms.Application/Dtos/Channels/SalesProductBillingSimulateDtos.cs @@ -0,0 +1,95 @@ +using System.ComponentModel.DataAnnotations; + +namespace Oms.Application.Dtos.Channels; + +/// +/// 销售产品计费模拟入参(基于当前库内卖价,非必须已发布)。 +/// +public class SalesProductBillingSimulateInput +{ + [Required] + public int SalesProductId { get; set; } + + [Required] + [StringLength(8)] + public string CountryCode { get; set; } = string.Empty; + + [StringLength(64)] + public string? Province { get; set; } + + [StringLength(64)] + public string? City { get; set; } + + [StringLength(32)] + public string? ZipCode { get; set; } + + [Required] + public decimal Length { get; set; } + + [Required] + public decimal Width { get; set; } + + [Required] + public decimal Height { get; set; } + + [Required] + public decimal ActualWeight { get; set; } + + [StringLength(32)] + public string? CargoAttribute { get; set; } + + public int? WarehouseId { get; set; } + + public List? AdditionalServices { get; set; } + + public decimal? DeclaredSum { get; set; } + + [StringLength(16)] + public string? DeclaredCurrency { get; set; } + + /// + /// 可选覆盖是否偏远;未传时按产品偏远分区命中。 + /// + public bool? IsRemote { get; set; } + + [StringLength(64)] + public string? PriceTierKey { get; set; } +} + +/// +/// 销售产品计费模拟出参。 +/// +public class SalesProductBillingSimulateOutput +{ + public decimal ChargeableWeight { get; set; } + + public List ZoneKeys { get; set; } = []; + + public bool IsRemote { get; set; } + + public List ReceivableFees { get; set; } = []; + + public List PayableFees { get; set; } = []; + + public Dictionary ReceivableTotal { get; set; } = new(StringComparer.OrdinalIgnoreCase); + + public Dictionary PayableTotal { get; set; } = new(StringComparer.OrdinalIgnoreCase); + + /// + /// 同币种毛利(应收合计 - 应付合计);多币种时为 null。 + /// + public decimal? Margin { get; set; } + + public List Warnings { get; set; } = []; +} + +public class SalesProductBillingSimulateFeeOutput +{ + public string CostItem { get; set; } = string.Empty; + + public decimal Amount { get; set; } + + public string Currency { get; set; } = string.Empty; + + public string? Formula { get; set; } +} diff --git a/src/Oms.Application/Dtos/Channels/SalesProductDetailOutput.cs b/src/Oms.Application/Dtos/Channels/SalesProductDetailOutput.cs index 92eba36..2ddcfa8 100644 --- a/src/Oms.Application/Dtos/Channels/SalesProductDetailOutput.cs +++ b/src/Oms.Application/Dtos/Channels/SalesProductDetailOutput.cs @@ -40,6 +40,16 @@ public class SalesProductDetailOutput /// public string? TradeTerms { get; set; } + /// + /// 官网线路排序,数值越小越靠前。 + /// + public int RouteSort { get; set; } + + /// + /// 可选附加服务字典 code JSON 数组。 + /// + public string? AdditionalServices { get; set; } + /// /// 系统面单类型。 /// diff --git a/src/Oms.Application/Dtos/Channels/SalesProductListOutput.cs b/src/Oms.Application/Dtos/Channels/SalesProductListOutput.cs index 5a230e4..3743ba9 100644 --- a/src/Oms.Application/Dtos/Channels/SalesProductListOutput.cs +++ b/src/Oms.Application/Dtos/Channels/SalesProductListOutput.cs @@ -35,6 +35,16 @@ public class SalesProductListOutput /// public int? MaxTimeliness { get; set; } + /// + /// 官网线路排序,数值越小越靠前。 + /// + public int RouteSort { get; set; } + + /// + /// 可选附加服务字典 code JSON 数组。 + /// + public string? AdditionalServices { get; set; } + /// /// 系统面单类型。 /// diff --git a/src/Oms.Application/Dtos/Channels/SalesProductPortalCatalogOutput.cs b/src/Oms.Application/Dtos/Channels/SalesProductPortalCatalogOutput.cs new file mode 100644 index 0000000..fff802a --- /dev/null +++ b/src/Oms.Application/Dtos/Channels/SalesProductPortalCatalogOutput.cs @@ -0,0 +1,84 @@ +namespace Oms.Application.Dtos.Channels; + +/// +/// 官网线路目录出参(公开字段)。 +/// +public class SalesProductPortalCatalogOutput +{ + /// + /// 分组列表(已排除国内揽收,且仅含有产品的分组)。 + /// + public List Groups { get; set; } = []; + + /// + /// 启用中的销售产品(已排除国内揽收)。 + /// + public List Items { get; set; } = []; +} + +/// +/// 官网线路分组。 +/// +public class SalesProductPortalGroupOutput +{ + /// + /// 分组编码(字典 code)。 + /// + public string Code { get; set; } = string.Empty; + + /// + /// 分组名称。 + /// + public string Name { get; set; } = string.Empty; +} + +/// +/// 官网线路产品卡片字段。 +/// +public class SalesProductPortalItemOutput +{ + /// + /// 主键。 + /// + public int Id { get; set; } + + /// + /// 产品名称。 + /// + public string ProductName { get; set; } = string.Empty; + + /// + /// 产品分组编码。 + /// + public string? ProductGroup { get; set; } + + /// + /// 产品分组名称。 + /// + public string ProductGroupName { get; set; } = string.Empty; + + /// + /// 最小时效(天)。 + /// + public int? MinTimeliness { get; set; } + + /// + /// 最大时效(天)。 + /// + public int? MaxTimeliness { get; set; } + + /// + /// 贸易条款(DDP/DDU)。 + /// + public string? TradeTerms { get; set; } + + /// + /// 官网线路排序,数值越小越靠前。 + /// + public int RouteSort { get; set; } + + /// + /// 产品说明。 + /// + public string? ProductDescription { get; set; } +} diff --git a/src/Oms.Application/Dtos/Channels/SalesProductPriceSaveAllInput.cs b/src/Oms.Application/Dtos/Channels/SalesProductPriceSaveAllInput.cs index 7888c56..a68959a 100644 --- a/src/Oms.Application/Dtos/Channels/SalesProductPriceSaveAllInput.cs +++ b/src/Oms.Application/Dtos/Channels/SalesProductPriceSaveAllInput.cs @@ -15,6 +15,11 @@ public class SalesProductPriceSaveAllInput /// public bool Publish { get; set; } + /// + /// 价格发布 AI 风险分析报告(Publish=true 时必填)。 + /// + public string? AiAnalysisReport { get; set; } + /// /// 价格项集合。 /// diff --git a/src/Oms.Application/Dtos/Channels/SalesProductPublishInput.cs b/src/Oms.Application/Dtos/Channels/SalesProductPublishInput.cs index ca283c9..b75caa8 100644 --- a/src/Oms.Application/Dtos/Channels/SalesProductPublishInput.cs +++ b/src/Oms.Application/Dtos/Channels/SalesProductPublishInput.cs @@ -19,4 +19,9 @@ public class SalesProductPublishInput /// 描述。 /// public string? Description { get; set; } + + /// + /// 价格发布 AI 风险分析报告(operatorType=price 时必填)。 + /// + public string? AiAnalysisReport { get; set; } } diff --git a/src/Oms.Application/Dtos/Channels/SalesProductPublishRecordOutput.cs b/src/Oms.Application/Dtos/Channels/SalesProductPublishRecordOutput.cs index baca778..243de9d 100644 --- a/src/Oms.Application/Dtos/Channels/SalesProductPublishRecordOutput.cs +++ b/src/Oms.Application/Dtos/Channels/SalesProductPublishRecordOutput.cs @@ -45,6 +45,11 @@ public class SalesProductPublishRecordOutput /// public string? Description { get; set; } + /// + /// 价格发布 AI 风险分析报告。 + /// + public string? AiAnalysisReport { get; set; } + /// /// 内容。 /// diff --git a/src/Oms.Application/Dtos/Channels/SalesProductSaveInput.cs b/src/Oms.Application/Dtos/Channels/SalesProductSaveInput.cs index 73ef3a7..7cb0f1f 100644 --- a/src/Oms.Application/Dtos/Channels/SalesProductSaveInput.cs +++ b/src/Oms.Application/Dtos/Channels/SalesProductSaveInput.cs @@ -42,6 +42,16 @@ public class SalesProductSaveInput /// public string? TradeTerms { get; set; } + /// + /// 官网线路排序,数值越小越靠前。 + /// + public int RouteSort { get; set; } + + /// + /// 可选附加服务字典 code JSON 数组。 + /// + public string? AdditionalServices { get; set; } + /// /// 系统面单类型(旧枚举字段,兼容展示)。 /// diff --git a/src/Oms.Application/Dtos/Channels/ServiceChannelDetailOutput.cs b/src/Oms.Application/Dtos/Channels/ServiceChannelDetailOutput.cs index bf49d59..106135a 100644 --- a/src/Oms.Application/Dtos/Channels/ServiceChannelDetailOutput.cs +++ b/src/Oms.Application/Dtos/Channels/ServiceChannelDetailOutput.cs @@ -55,6 +55,11 @@ public class ServiceChannelDetailOutput /// public string? Description { get; set; } + /// + /// 偏远分区 KPI AreaId。 + /// + public int? RemoteAreaId { get; set; } + /// /// 预处理脚本。 /// diff --git a/src/Oms.Application/Dtos/Channels/ServiceChannelListOutput.cs b/src/Oms.Application/Dtos/Channels/ServiceChannelListOutput.cs index 0ba8f29..546f298 100644 --- a/src/Oms.Application/Dtos/Channels/ServiceChannelListOutput.cs +++ b/src/Oms.Application/Dtos/Channels/ServiceChannelListOutput.cs @@ -55,6 +55,11 @@ public class ServiceChannelListOutput /// public string? Description { get; set; } + /// + /// 偏远分区 KPI AreaId。 + /// + public int? RemoteAreaId { get; set; } + /// /// 是否启用。 /// diff --git a/src/Oms.Application/Dtos/Channels/ServiceChannelSaveInput.cs b/src/Oms.Application/Dtos/Channels/ServiceChannelSaveInput.cs index a532d58..c54b6c2 100644 --- a/src/Oms.Application/Dtos/Channels/ServiceChannelSaveInput.cs +++ b/src/Oms.Application/Dtos/Channels/ServiceChannelSaveInput.cs @@ -52,6 +52,11 @@ public class ServiceChannelSaveInput /// public string? Description { get; set; } + /// + /// 偏远分区 KPI AreaId。 + /// + public int? RemoteAreaId { get; set; } + /// /// 预处理脚本。 /// diff --git a/src/Oms.Application/Dtos/Customers/CreateCustomerInput.cs b/src/Oms.Application/Dtos/Customers/CreateCustomerInput.cs index cfbef33..1c1ac13 100644 --- a/src/Oms.Application/Dtos/Customers/CreateCustomerInput.cs +++ b/src/Oms.Application/Dtos/Customers/CreateCustomerInput.cs @@ -118,4 +118,10 @@ public class CreateCustomerInput [StringLength(16)] public string? InviteCode { get; set; } + /// + /// 顾问邀请码(所属顾问绑定,值为员工 Account;仅 CustomerService 为空时生效)。 + /// + [StringLength(64)] + public string? AdvisorCode { get; set; } + } diff --git a/src/Oms.Application/Dtos/Customers/CustomerServiceAdvisorOutput.cs b/src/Oms.Application/Dtos/Customers/CustomerServiceAdvisorOutput.cs index d73be89..752220e 100644 --- a/src/Oms.Application/Dtos/Customers/CustomerServiceAdvisorOutput.cs +++ b/src/Oms.Application/Dtos/Customers/CustomerServiceAdvisorOutput.cs @@ -19,4 +19,9 @@ public class CustomerServiceAdvisorOutput /// 微信二维码(URL 或 Base64)。 /// public string? WechatQrCode { get; set; } + + /// + /// 企业微信客服接入链接。 + /// + public string? WecomKfUrl { get; set; } } diff --git a/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedInput.cs b/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedInput.cs index bb51370..ce68e6b 100644 --- a/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedInput.cs +++ b/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedInput.cs @@ -32,12 +32,32 @@ public class ReceivablePayablePaginatedInput public int? CustomerId { get; set; } /// - /// 订单创建时间起。 + /// 客户编码关键词(模糊匹配)。 + /// + public string? CustomerCode { get; set; } + + /// + /// 仅保留各运单费用项的当前生效阶段。 + /// + public bool EffectiveStageOnly { get; set; } + + /// + /// 订单创建时间起(timeField=createTime 时生效,兼容旧参数)。 /// public DateTime? StartTime { get; set; } /// - /// 订单创建时间止。 + /// 订单创建时间止(timeField=createTime 时生效,兼容旧参数)。 /// public DateTime? EndTime { get; set; } + + /// + /// 时间筛选字段:createTime / receiveTime / shipTime / payTime。 + /// + public string? TimeField { get; set; } + + /// + /// 支付状态:0 未支付,1 已支付。 + /// + public int? IsPaid { get; set; } } diff --git a/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedOutput.cs b/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedOutput.cs index fa832c3..b39a291 100644 --- a/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedOutput.cs +++ b/src/Oms.Application/Dtos/Finance/ReceivablePayablePaginatedOutput.cs @@ -5,6 +5,8 @@ namespace Oms.Application.Dtos.Finance; /// public class ReceivablePayablePaginatedOutput { + public int OrderId { get; set; } + public string ServiceNo { get; set; } = string.Empty; public string? ClientNo { get; set; } @@ -37,6 +39,8 @@ public class ReceivablePayablePaginatedOutput public string CostItem { get; set; } = string.Empty; + public string? CostItemName { get; set; } + public decimal Amount { get; set; } public string Currency { get; set; } = string.Empty; diff --git a/src/Oms.Application/Dtos/Finance/ReceivablePayableSummaryOutput.cs b/src/Oms.Application/Dtos/Finance/ReceivablePayableSummaryOutput.cs new file mode 100644 index 0000000..4578aeb --- /dev/null +++ b/src/Oms.Application/Dtos/Finance/ReceivablePayableSummaryOutput.cs @@ -0,0 +1,30 @@ +namespace Oms.Application.Dtos.Finance; + +/// +/// 应收应付汇总出参。 +/// +public class ReceivablePayableSummaryOutput +{ + /// + /// 匹配筛选条件的费用明细总行数。 + /// + public int TotalLines { get; set; } + + /// + /// 按费用类型 + 币种汇总。 + /// + public List Items { get; set; } = []; +} + +public class ReceivablePayableSummaryItemOutput +{ + public string FeeType { get; set; } = string.Empty; + + public string? FeeTypeName { get; set; } + + public string Currency { get; set; } = string.Empty; + + public decimal TotalAmount { get; set; } + + public int LineCount { get; set; } +} diff --git a/src/Oms.Application/Dtos/Kb/KbDtos.cs b/src/Oms.Application/Dtos/Kb/KbDtos.cs new file mode 100644 index 0000000..3c801d6 --- /dev/null +++ b/src/Oms.Application/Dtos/Kb/KbDtos.cs @@ -0,0 +1,138 @@ +using System.ComponentModel.DataAnnotations; + +namespace Oms.Application.Dtos.Kb; + +public static class KbAudienceCodes +{ + public const string Customer = "customer"; + public const string Internal = "internal"; +} + +public static class KbArticleStatusCodes +{ + public const string Draft = "draft"; + public const string Published = "published"; + public const string Offline = "offline"; +} + +public class KbCategoryOutput +{ + public int Id { get; set; } + public string Code { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; + public int SortOrder { get; set; } + public bool Enabled { get; set; } +} + +public class KbCategorySaveInput +{ + public int? Id { get; set; } + + [Required] + public string Code { get; set; } = string.Empty; + + [Required] + public string Name { get; set; } = string.Empty; + + public int SortOrder { get; set; } + + public bool Enabled { get; set; } = true; +} + +public class KbCategoryDeleteInput +{ + [Required] + public int Id { get; set; } +} + +public class KbArticleOutput +{ + public int Id { get; set; } + public int CategoryId { get; set; } + public string? CategoryName { get; set; } + public string Title { get; set; } = string.Empty; + public string? Summary { get; set; } + public string? Content { get; set; } + public string Audience { get; set; } = KbAudienceCodes.Customer; + public string Status { get; set; } = KbArticleStatusCodes.Draft; + public string? Tags { get; set; } + public string? RelatedPath { get; set; } + public string? RelatedLabel { get; set; } + public bool IsPinned { get; set; } + public int SortOrder { get; set; } + public DateTime? PublishTime { get; set; } + public DateTime? ExpireTime { get; set; } + public int ViewCount { get; set; } + public DateTime? UpdateTime { get; set; } +} + +public class KbArticleListInput +{ + public int Page { get; set; } = 1; + public int PageSize { get; set; } = 30; + public string? Keyword { get; set; } + public int? CategoryId { get; set; } + public string? Status { get; set; } + public string? Audience { get; set; } + public bool? IsPinned { get; set; } + public bool IncludeContent { get; set; } +} + +public class KbArticleSaveInput +{ + public int? Id { get; set; } + + [Required] + public int CategoryId { get; set; } + + [Required] + public string Title { get; set; } = string.Empty; + + public string? Summary { get; set; } + + [Required] + public string Content { get; set; } = string.Empty; + + public string Audience { get; set; } = KbAudienceCodes.Customer; + + public string Status { get; set; } = KbArticleStatusCodes.Draft; + + public string? Tags { get; set; } + + public string? RelatedPath { get; set; } + + public string? RelatedLabel { get; set; } + + public bool IsPinned { get; set; } + + public int SortOrder { get; set; } + + public DateTime? ExpireTime { get; set; } +} + +public class KbArticleIdInput +{ + [Required] + public int Id { get; set; } +} + +public class KbArticlePinInput +{ + [Required] + public int Id { get; set; } + + public bool IsPinned { get; set; } +} + +public class KbPortalArticleListInput +{ + public int Page { get; set; } = 1; + public int PageSize { get; set; } = 20; + public string? Keyword { get; set; } + public int? CategoryId { get; set; } +} + +public class KbPortalHotInput +{ + public int Top { get; set; } = 10; +} diff --git a/src/Oms.Application/Dtos/Operations/InboundOrderLookupOutput.cs b/src/Oms.Application/Dtos/Operations/InboundOrderLookupOutput.cs index 9dfb3ca..e5db913 100644 --- a/src/Oms.Application/Dtos/Operations/InboundOrderLookupOutput.cs +++ b/src/Oms.Application/Dtos/Operations/InboundOrderLookupOutput.cs @@ -59,4 +59,9 @@ public class InboundOrderLookupOutput /// 订单状态名称。 /// public string? OrderStatusName { get; set; } + + /// + /// 待排货/计费失败原因。 + /// + public string? AllocationPendingReason { get; set; } } diff --git a/src/Oms.Application/Dtos/Operations/InboundRecordOutput.cs b/src/Oms.Application/Dtos/Operations/InboundRecordOutput.cs index 6671d2a..e5979b6 100644 --- a/src/Oms.Application/Dtos/Operations/InboundRecordOutput.cs +++ b/src/Oms.Application/Dtos/Operations/InboundRecordOutput.cs @@ -75,6 +75,26 @@ public class InboundRecordOutput /// public string? OperatorName { get; set; } + /// + /// 关联订单主键。 + /// + public int? OrderId { get; set; } + + /// + /// 订单状态码。 + /// + public string? OrderStatus { get; set; } + + /// + /// 订单状态名称。 + /// + public string? OrderStatusName { get; set; } + + /// + /// 待排货/计费失败原因(有则展示)。 + /// + public string? AllocationPendingReason { get; set; } + /// /// 创建时间。 /// diff --git a/src/Oms.Application/Dtos/Orders/Customs9610Dtos.cs b/src/Oms.Application/Dtos/Orders/Customs9610Dtos.cs new file mode 100644 index 0000000..c8bce36 --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/Customs9610Dtos.cs @@ -0,0 +1,313 @@ +using System.ComponentModel.DataAnnotations; + +namespace Oms.Application.Dtos.Orders; + +public class Customs9610ListInput +{ + public int Page { get; set; } = 1; + + public int PageSize { get; set; } = 30; + + public int? CustomerId { get; set; } + + /// + /// pending / declared;空=全部。 + /// + public string? Status { get; set; } + + public string? Keyword { get; set; } + + public DateTime? CreateTimeStart { get; set; } + + public DateTime? CreateTimeEnd { get; set; } +} + +public class Customs9610IdInput +{ + [Required] + public int Id { get; set; } +} + +public class Customs9610IdsInput +{ + [Required] + [MinLength(1)] + public List Ids { get; set; } = []; +} + +public class Customs9610StatusCountsOutput +{ + public int Total { get; set; } + + public int Pending { get; set; } + + public int Declared { get; set; } +} + +public class Customs9610ItemInput +{ + public int? Id { get; set; } + + public int? OrderDeclarationId { get; set; } + + [Required] + [StringLength(32)] + public string Sku { get; set; } = string.Empty; + + [Required] + [StringLength(250)] + public string CnName { get; set; } = string.Empty; + + [StringLength(10)] + public string? ExHsCode { get; set; } + + [StringLength(255)] + public string? DeclareElement { get; set; } + + [Required] + public decimal UnitPrice { get; set; } + + [Required] + public decimal Quantity { get; set; } + + public decimal? Freight { get; set; } + + public int SortNo { get; set; } +} + +public class Customs9610UpdateInput +{ + [Required] + public int Id { get; set; } + + [Required] + [StringLength(16)] + public string PlatformCode { get; set; } = string.Empty; + + [StringLength(18)] + public string? EcomCorpCode { get; set; } + + [StringLength(100)] + public string? EcomCorpName { get; set; } + + [StringLength(18)] + public string? ProducerCode { get; set; } + + [StringLength(100)] + public string? ProducerName { get; set; } + + [Required] + [StringLength(48)] + public string ClientNo { get; set; } = string.Empty; + + [Required] + [StringLength(48)] + public string ServiceNo { get; set; } = string.Empty; + + [Required] + [StringLength(1)] + public string BusinessType { get; set; } = "B"; + + [StringLength(10)] + public string? Region { get; set; } + + [StringLength(2)] + public string? AgentDeclare { get; set; } + + [StringLength(18)] + public string? ActualSellerCode { get; set; } + + [StringLength(1)] + public string? PreRecordFlag { get; set; } + + public bool IsSummarySimple { get; set; } + + [Required] + public decimal GrossWeight { get; set; } + + [Required] + [StringLength(4)] + public string Currency { get; set; } = "CNY"; + + [Required] + [StringLength(4)] + public string DestCountry { get; set; } = string.Empty; + + public decimal? Freight { get; set; } + + [StringLength(32)] + public string? ShipmentNo { get; set; } + + [MinLength(1)] + public List Items { get; set; } = []; +} + +public class Customs9610ItemOutput +{ + public int Id { get; set; } + + public int? OrderDeclarationId { get; set; } + + public string Sku { get; set; } = string.Empty; + + public string CnName { get; set; } = string.Empty; + + public string? ExHsCode { get; set; } + + public string? DeclareElement { get; set; } + + public string? Barcode { get; set; } + + public string? DestCountry { get; set; } + + public string? ItemCurrency { get; set; } + + public decimal UnitPrice { get; set; } + + public decimal? Amount { get; set; } + + public decimal Quantity { get; set; } + + public decimal? LegalQty { get; set; } + + public string? Unit { get; set; } + + public string? LegalUnit { get; set; } + + public decimal? Freight { get; set; } + + public int SortNo { get; set; } +} + +public class Customs9610OrderOutput +{ + public int Id { get; set; } + + public int OrderId { get; set; } + + public string? ServiceNo { get; set; } + + public int CustomerId { get; set; } + + public string? CustomerName { get; set; } + + public string Status { get; set; } = string.Empty; + + public string PlatformCode { get; set; } = string.Empty; + + public string? EcomCorpCode { get; set; } + + public string? EcomCorpName { get; set; } + + public string? ProducerCode { get; set; } + + public string? ProducerName { get; set; } + + public string ClientNo { get; set; } = string.Empty; + + public string BusinessType { get; set; } = "B"; + + public string? Region { get; set; } + + public string? AgentDeclare { get; set; } + + public string? ActualSellerCode { get; set; } + + public string? PreRecordFlag { get; set; } + + public bool IsSummarySimple { get; set; } + + public decimal GrossWeight { get; set; } + + public string Currency { get; set; } = "CNY"; + + public string DestCountry { get; set; } = string.Empty; + + public decimal? Freight { get; set; } + + public string? FreightCurrency { get; set; } + + public int? FreightMark { get; set; } + + public int? PackageType { get; set; } + + public int? PackageQty { get; set; } + + public string? ShipmentNo { get; set; } + + public string? CustomsOrderNo { get; set; } + + public string? DownstreamRefNo { get; set; } + + public string? EnterpriseBizNo { get; set; } + + public string? ManifestNo { get; set; } + + public string? ClearanceTime { get; set; } + + public string? CustomsInboundTime { get; set; } + + public string? CustomsState { get; set; } + + public string? DeclareCustomsCode { get; set; } + + public string? PlatformCorpCode { get; set; } + + public string? PlatformName { get; set; } + + public string? LogisticsCorpCode { get; set; } + + public string? LogisticsCorpName { get; set; } + + public string? IeMark { get; set; } + + public string? ExportPortCode { get; set; } + + public string? ExportDate { get; set; } + + public string? DeclareAgentCode { get; set; } + + public string? DeclareAgentName { get; set; } + + public string? TradeModeCode { get; set; } + + public string? TransportMode { get; set; } + + public DateTime? DeclareTime { get; set; } + + public DateTime? ManifestSyncTime { get; set; } + + public string? FailReason { get; set; } + + public DateTime CreateTime { get; set; } + + public DateTime? UpdateTime { get; set; } + + public List? Items { get; set; } +} + +public class Customs9610DeclareResult +{ + public int Id { get; set; } + + public bool Success { get; set; } + + public string Message { get; set; } = string.Empty; + + public string? CustomsOrderNo { get; set; } + + public string? Status { get; set; } + + public int? HttpStatusCode { get; set; } + + public string? ResponseBody { get; set; } +} + +public class Customs9610DeclareBatchOutput +{ + public int SuccessCount { get; set; } + + public int FailCount { get; set; } + + public List Items { get; set; } = []; +} diff --git a/src/Oms.Application/Dtos/Orders/FulfillWorkplaceStatsOutput.cs b/src/Oms.Application/Dtos/Orders/FulfillWorkplaceStatsOutput.cs new file mode 100644 index 0000000..e269cb6 --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/FulfillWorkplaceStatsOutput.cs @@ -0,0 +1,19 @@ +namespace Oms.Application.Dtos.Orders; + +/// +/// 工作台代发订单统计。 +/// +public class FulfillWorkplaceStatsOutput +{ + /// 待绑定包裹/库存。 + public int PendingBind { get; set; } + + /// 国内快递在途。 + public int DomesticInTransit { get; set; } + + /// 已到仓,待仓库拣货。 + public int ArrivedPendingPick { get; set; } + + /// 已出库(拣货扣减完成)。 + public int OutboundDone { get; set; } +} diff --git a/src/Oms.Application/Dtos/Orders/OrderAdditionalServicesUpdateInput.cs b/src/Oms.Application/Dtos/Orders/OrderAdditionalServicesUpdateInput.cs new file mode 100644 index 0000000..49dff75 --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/OrderAdditionalServicesUpdateInput.cs @@ -0,0 +1,20 @@ +using System.ComponentModel.DataAnnotations; + +namespace Oms.Application.Dtos.Orders; + +/// +/// 未付款订单更新附加服务入参。 +/// +public class OrderAdditionalServicesUpdateInput +{ + /// + /// 订单主键。 + /// + [Required] + public int Id { get; set; } + + /// + /// 附加服务字典 code 列表。 + /// + public List? AdditionalServices { get; set; } +} diff --git a/src/Oms.Application/Dtos/Orders/OrderAllocationTraceDtos.cs b/src/Oms.Application/Dtos/Orders/OrderAllocationTraceDtos.cs new file mode 100644 index 0000000..e431cc8 --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/OrderAllocationTraceDtos.cs @@ -0,0 +1,84 @@ +namespace Oms.Application.Dtos.Orders; + +/// +/// 订单排货过程(快照或现算)。 +/// +public class OrderAllocationTraceOutput +{ + public int OrderId { get; set; } + + /// true=历史快照;false=按当前规则现算。 + public bool FromSnapshot { get; set; } + + public string? Scheme { get; set; } + + public string? SchemeName { get; set; } + + /// productDefault / reallocate / designated + public string? SchemeSource { get; set; } + + public string? SchemeSourceName { get; set; } + + public decimal? ChargeableWeight { get; set; } + + /// 订单解析出的价格分区键(用于对照买价明细分区)。 + public List ZoneKeys { get; set; } = []; + + public string? ChargingStage { get; set; } + + public string? ChargingStageName { get; set; } + + public string? SelectedChannelCode { get; set; } + + public string? SelectedChannelName { get; set; } + + public string? FailReason { get; set; } + + public DateTime? TraceTime { get; set; } + + public List Candidates { get; set; } = []; + + public List Skipped { get; set; } = []; +} + +public class OrderAllocationCandidateOutput +{ + public int ServiceChannelId { get; set; } + + public string ChannelCode { get; set; } = string.Empty; + + public string? ChannelName { get; set; } + + /// 应付合计(价格优先主指标)。 + public decimal TotalPayableCost { get; set; } + + /// 时效天数(时效优先主指标)。 + public int? MinTime { get; set; } + + /// 综合权重(综合最优主指标)。 + public int Weight { get; set; } + + public bool Selected { get; set; } + + public List FeeLines { get; set; } = []; +} + +public class OrderAllocationSkippedOutput +{ + public int? ServiceChannelId { get; set; } + + public string? ChannelCode { get; set; } + + public string? ChannelName { get; set; } + + public string Reason { get; set; } = string.Empty; +} + +public class OrderAllocationFeeLineOutput +{ + public string? CostItem { get; set; } + + public decimal Amount { get; set; } + + public string? Currency { get; set; } +} diff --git a/src/Oms.Application/Dtos/Orders/OrderExceptionDtos.cs b/src/Oms.Application/Dtos/Orders/OrderExceptionDtos.cs index 2f442a5..eddc1be 100644 --- a/src/Oms.Application/Dtos/Orders/OrderExceptionDtos.cs +++ b/src/Oms.Application/Dtos/Orders/OrderExceptionDtos.cs @@ -29,6 +29,67 @@ public class OrderMarkProblematicInput public string? Content { get; set; } public string? Remark { get; set; } + + public string? HandlerNames { get; set; } +} + +public class OrderExceptionEventProcessInput +{ + public int Id { get; set; } + + public string? Remark { get; set; } +} + +public class OrderExceptionEventOutput +{ + public int Id { get; set; } + + public int OrderId { get; set; } + + public string EventType { get; set; } = string.Empty; + + public string? IssueType { get; set; } + + public string? IssueTypeName { get; set; } + + public string? Title { get; set; } + + public string? Content { get; set; } + + public string? NotifyMethod { get; set; } + + public string? NotifyMethodNames { get; set; } + + public string? HandlerNames { get; set; } + + public string? HandlerType { get; set; } + + public string? HandlerTypeName { get; set; } + + public int? HandlerUserId { get; set; } + + public string? HandleStatus { get; set; } + + public string? HandleStatusName { get; set; } + + public string? CreateBy { get; set; } + + public DateTime CreateTime { get; set; } + + public string? ProcessedBy { get; set; } + + public DateTime? ProcessedTime { get; set; } + + public string? Remark { get; set; } +} + +public class OrderExceptionEventListOutput +{ + public List Items { get; set; } = []; + + public int PendingCount { get; set; } + + public int ProcessedCount { get; set; } } public class OrderMarkClaimedInput diff --git a/src/Oms.Application/Dtos/Orders/OrderExportInput.cs b/src/Oms.Application/Dtos/Orders/OrderExportInput.cs index 1378635..cfb9101 100644 --- a/src/Oms.Application/Dtos/Orders/OrderExportInput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderExportInput.cs @@ -17,6 +17,19 @@ public class OrderExportInput [Newtonsoft.Json.JsonProperty("orderSource")] public string? OrderSource { get; set; } + /// + /// 履约类型:all / direct / warehouse。 + /// + [Newtonsoft.Json.JsonProperty("fulfillmentType")] + public string? FulfillmentType { get; set; } + + /// + /// 代发进度筛选(pendingBind / domesticInTransit / arrivedPendingPick / outboundDone)。 + /// + [Newtonsoft.Json.JsonProperty("fulfillProgress")] + [global::System.Text.Json.Serialization.JsonPropertyName("fulfillProgress")] + public string? FulfillProgress { get; set; } + /// /// 关键词。 /// diff --git a/src/Oms.Application/Dtos/Orders/OrderItemOutput.cs b/src/Oms.Application/Dtos/Orders/OrderItemOutput.cs index 6b4c374..c7dba00 100644 --- a/src/Oms.Application/Dtos/Orders/OrderItemOutput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderItemOutput.cs @@ -51,10 +51,20 @@ public class OrderItemOutput public decimal? Weight { get; set; } /// - /// HS 编码。 + /// HS 编码(兼容旧字段,优先出口编码)。 /// public string? HsCode { get; set; } + /// + /// 进口 HS 编码。 + /// + public string? ImHsCode { get; set; } + + /// + /// 出口 HS 编码。 + /// + public string? ExHsCode { get; set; } + /// /// SKU 图片。 /// diff --git a/src/Oms.Application/Dtos/Orders/OrderOutput.cs b/src/Oms.Application/Dtos/Orders/OrderOutput.cs index 7181b83..47b72f4 100644 --- a/src/Oms.Application/Dtos/Orders/OrderOutput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderOutput.cs @@ -40,6 +40,11 @@ public class OrderOutput /// public string? ProductName { get; set; } + /// + /// 销售产品最大时效(天)。 + /// + public int? MaxTimeliness { get; set; } + /// /// 渠道编码。 /// @@ -125,6 +130,71 @@ public class OrderOutput /// public int? CustomerSenderAddressId { get; set; } + /// + /// 到仓方式:selfShip / doorPickup。 + /// + public string? InboundMethod { get; set; } + + /// + /// 履约类型:direct / warehouse。 + /// + public string? FulfillmentType { get; set; } + + /// + /// 代发来源:storeFulfill / postBind。 + /// + public string? FulfillmentSource { get; set; } + + /// + /// 绑定状态聚合:none / bound / deducted。 + /// + public string? StockBindStatus { get; set; } + + /// + /// 绑定行数。 + /// + public int StockBindLineCount { get; set; } + + /// + /// 绑定件数合计。 + /// + public int StockBindQtyTotal { get; set; } + + /// + /// 国内快递单号(绑定行去重,逗号分隔)。 + /// + public string? DomesticTrackingNos { get; set; } + + /// + /// 代发进度:pendingBind / domesticInTransit / arrivedPendingPick / outboundDone。 + /// + public string? FulfillProgress { get; set; } + + /// + /// 主拣货库位(绑定行最小 BinCode,供拣货队列排序展示)。 + /// + public string? PrimaryBinCode { get; set; } + + /// + /// 绑定 SKU 编码汇总(逗号分隔,列表展示/拣货筛选用)。 + /// + public string? PrimarySkuCodes { get; set; } + + /// + /// 关联揽收单 Id。 + /// + public int? PickupOrderId { get; set; } + + /// + /// 关联揽收系统单号(OMS PickupNo)。 + /// + public string? PickupNo { get; set; } + + /// + /// 国内承运商回执单号(揽收承运商运单号)。 + /// + public string? CarrierWaybillNo { get; set; } + /// /// 幂等请求标识。 /// @@ -145,6 +215,16 @@ public class OrderOutput /// public string? AllocationPendingReason { get; set; } + /// + /// 最近一次排货方案。 + /// + public string? AllocationScheme { get; set; } + + /// + /// 是否已有排货过程快照。 + /// + public bool HasAllocationTrace { get; set; } + /// /// 申报币种。 /// @@ -258,6 +338,26 @@ public class OrderOutput /// public bool IsRemote { get; set; } + /// + /// 客户勾选附加服务字典 code 列表。 + /// + public List AdditionalServices { get; set; } = []; + + /// + /// 是否勾选保险附加服务。 + /// + public bool HasInsurance { get; set; } + + /// + /// 预报应收快照(入库不覆盖)。 + /// + public decimal? ForecastReceivableAmount { get; set; } + + /// + /// 预报应付快照(入库不覆盖)。 + /// + public decimal? ForecastPayableAmount { get; set; } + /// /// 创建时间。 /// diff --git a/src/Oms.Application/Dtos/Orders/OrderPaginatedInput.cs b/src/Oms.Application/Dtos/Orders/OrderPaginatedInput.cs index a33c92b..0be7777 100644 --- a/src/Oms.Application/Dtos/Orders/OrderPaginatedInput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderPaginatedInput.cs @@ -38,6 +38,27 @@ public class OrderPaginatedInput [global::System.Text.Json.Serialization.JsonPropertyName("orderSource")] public string? OrderSource { get; set; } + /// + /// 履约类型:all / direct / warehouse。 + /// + [Newtonsoft.Json.JsonProperty("fulfillmentType")] + [global::System.Text.Json.Serialization.JsonPropertyName("fulfillmentType")] + public string? FulfillmentType { get; set; } + + /// + /// 绑定状态聚合:all / none / bound / deducted。 + /// + [Newtonsoft.Json.JsonProperty("stockBindStatus")] + [global::System.Text.Json.Serialization.JsonPropertyName("stockBindStatus")] + public string? StockBindStatus { get; set; } + + /// + /// 代发进度:all / pendingBind / domesticInTransit / arrivedPendingPick / outboundDone。 + /// + [Newtonsoft.Json.JsonProperty("fulfillProgress")] + [global::System.Text.Json.Serialization.JsonPropertyName("fulfillProgress")] + public string? FulfillProgress { get; set; } + /// /// 客户 ID(管理端可选;不传则查全部)。 /// @@ -45,6 +66,13 @@ public class OrderPaginatedInput [global::System.Text.Json.Serialization.JsonPropertyName("customerId")] public int? CustomerId { get; set; } + /// + /// 发货仓 ID(拣货队列等按仓筛选)。 + /// + [Newtonsoft.Json.JsonProperty("warehouseId")] + [global::System.Text.Json.Serialization.JsonPropertyName("warehouseId")] + public int? WarehouseId { get; set; } + /// /// 关键词。 /// @@ -71,7 +99,7 @@ public class OrderPaginatedInput public List? Filters { get; set; } /// - /// 排序字段白名单:createTime / updateTime / serviceNo / clientNo / trackNo / payableAmount / payTime / shipTime / receiveTime / signTime。 + /// 排序字段白名单:createTime / updateTime / serviceNo / clientNo / trackNo / primaryBinCode / payableAmount / payTime / shipTime / receiveTime / signTime。 /// [Newtonsoft.Json.JsonProperty("sortField")] [global::System.Text.Json.Serialization.JsonPropertyName("sortField")] diff --git a/src/Oms.Application/Dtos/Orders/OrderParcelCreateInput.cs b/src/Oms.Application/Dtos/Orders/OrderParcelCreateInput.cs index f7038e5..700ec1d 100644 --- a/src/Oms.Application/Dtos/Orders/OrderParcelCreateInput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderParcelCreateInput.cs @@ -115,6 +115,16 @@ public class OrderParcelCreateInput /// public decimal? DeclaredSum { get; set; } + /// + /// 客户勾选附加服务字典 code 列表(落库序列化为 JSON 数组)。 + /// + public List? AdditionalServices { get; set; } + + /// + /// 是否偏远(预计算后可写入,供下单前公式/计费条件求值)。 + /// + public byte? IsRemote { get; set; } + /// /// 数量。 /// @@ -144,4 +154,29 @@ public class OrderParcelCreateInput /// 仅保存为草稿,不执行预报计费与状态推进。 /// public bool SaveAsDraft { get; set; } + + /// + /// 到仓方式:selfShip / doorPickup。 + /// + public string? InboundMethod { get; set; } + + /// + /// 上门揽收时发件地址簿 Id。 + /// + public int? SenderAddressId { get; set; } + + /// + /// 期望揽收时间(上门揽收)。 + /// + public DateTime? ExpectPickupTime { get; set; } + + /// + /// 承运商编码(可后补)。 + /// + public string? CarrierCode { get; set; } + + /// + /// 承运服务(可后补)。 + /// + public string? CarrierService { get; set; } } diff --git a/src/Oms.Application/Dtos/Orders/OrderParcelCreateOutput.cs b/src/Oms.Application/Dtos/Orders/OrderParcelCreateOutput.cs index 19a593c..0f7f1fe 100644 --- a/src/Oms.Application/Dtos/Orders/OrderParcelCreateOutput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderParcelCreateOutput.cs @@ -39,4 +39,24 @@ public class OrderParcelCreateOutput /// 收件国家/地区中文名称。 /// public string? ConsigneeCountryName { get; set; } + + /// + /// 同步创建的揽收单号(上门揽收成功时)。 + /// + public string? PickupNo { get; set; } + + /// + /// 同步创建的揽收单 Id。 + /// + public int? PickupOrderId { get; set; } + + /// + /// 国内承运运单号(上门揽收时可选)。 + /// + public string? CarrierWaybillNo { get; set; } + + /// + /// 揽收单创建失败原因(运单已成功时仅作提示)。 + /// + public string? PickupCreateError { get; set; } } diff --git a/src/Oms.Application/Dtos/Orders/OrderPriceCheckInput.cs b/src/Oms.Application/Dtos/Orders/OrderPriceCheckInput.cs index 77db7b6..c45bee6 100644 --- a/src/Oms.Application/Dtos/Orders/OrderPriceCheckInput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderPriceCheckInput.cs @@ -69,4 +69,19 @@ public class OrderPriceCheckInput /// 选用的优惠券实例 Id。 /// public int? CouponInstanceId { get; set; } + + /// + /// 勾选附加服务字典 code(用于计费条件求值)。 + /// + public List? AdditionalServices { get; set; } + + /// + /// 申报总金额(百分比申报类公式)。 + /// + public decimal? DeclaredSum { get; set; } + + /// + /// 申报币种。 + /// + public string? DeclaredCurrency { get; set; } } diff --git a/src/Oms.Application/Dtos/Orders/OrderPriceCheckOutput.cs b/src/Oms.Application/Dtos/Orders/OrderPriceCheckOutput.cs index dfad13e..3db4c4d 100644 --- a/src/Oms.Application/Dtos/Orders/OrderPriceCheckOutput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderPriceCheckOutput.cs @@ -57,6 +57,11 @@ public class OrderPriceCheckOutput /// public string? ProductGroupName { get; set; } + /// + /// 产品说明(线路简要说明,对客展示)。 + /// + public string? ProductDescription { get; set; } + /// /// 体积重量。 /// diff --git a/src/Oms.Application/Dtos/Orders/OrderReallocateDtos.cs b/src/Oms.Application/Dtos/Orders/OrderReallocateDtos.cs new file mode 100644 index 0000000..09c0e56 --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/OrderReallocateDtos.cs @@ -0,0 +1,59 @@ +using System.ComponentModel.DataAnnotations; + +namespace Oms.Application.Dtos.Orders; + +/// +/// 单票重新排货入参。 +/// +public class OrderReallocateInput +{ + [Required] + public int Id { get; set; } + + /// + /// 排货方案:costLowest / timeFastest / overallBest / designated。 + /// + [Required] + [StringLength(32)] + public string Scheme { get; set; } = string.Empty; + + /// + /// 指定渠道时必填。 + /// + public int? ServiceChannelId { get; set; } +} + +/// +/// 批量重新排货入参(同步兜底)。 +/// +public class OrderReallocateBatchInput +{ + [Required] + [MinLength(1)] + public List OrderIds { get; set; } = []; + + [Required] + [StringLength(32)] + public string Scheme { get; set; } = string.Empty; + + public int? ServiceChannelId { get; set; } +} + +/// +/// 查询指定渠道可选项(按订单排货池交集)。 +/// +public class OrderReallocateChannelOptionsInput +{ + [Required] + [MinLength(1)] + public List OrderIds { get; set; } = []; +} + +public class OrderReallocateChannelOptionOutput +{ + public int ServiceChannelId { get; set; } + + public string ChannelCode { get; set; } = string.Empty; + + public string? ChannelName { get; set; } +} diff --git a/src/Oms.Application/Dtos/Orders/OrderReceiverParseAddressDtos.cs b/src/Oms.Application/Dtos/Orders/OrderReceiverParseAddressDtos.cs index 58113ef..4408d29 100644 --- a/src/Oms.Application/Dtos/Orders/OrderReceiverParseAddressDtos.cs +++ b/src/Oms.Application/Dtos/Orders/OrderReceiverParseAddressDtos.cs @@ -17,6 +17,10 @@ public class OrderReceiverParseAddressInput /// 可选模型覆盖。 [MaxLength(128)] public string? Model { get; set; } + + /// 可选 Skill Key;为空时使用内置「oms-receiver-address-parse」。 + [MaxLength(128)] + public string? SkillKey { get; set; } } /// 地址解析结果 + 完整性校验。 diff --git a/src/Oms.Application/Dtos/Orders/OrderStatusCountsOutput.cs b/src/Oms.Application/Dtos/Orders/OrderStatusCountsOutput.cs index 9568dd2..60dfc49 100644 --- a/src/Oms.Application/Dtos/Orders/OrderStatusCountsOutput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderStatusCountsOutput.cs @@ -20,4 +20,10 @@ public class OrderStatusCountsOutput /// public Dictionary HandleCounts { get; set; } = new(StringComparer.OrdinalIgnoreCase); + + /// + /// 代发进度分组数量(fulfillmentType=warehouse 时返回)。 + /// + public Dictionary FulfillProgressCounts { get; set; } = + new(StringComparer.OrdinalIgnoreCase); } diff --git a/src/Oms.Application/Dtos/Orders/OrderUploadInput.cs b/src/Oms.Application/Dtos/Orders/OrderUploadInput.cs index ee4028b..fcf70ef 100644 --- a/src/Oms.Application/Dtos/Orders/OrderUploadInput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderUploadInput.cs @@ -21,4 +21,9 @@ public class OrderUploadInput /// 默认发件地址 ID(地址管理中的发件人地址)。 /// public int? SenderAddressId { get; set; } + + /// + /// 客户主键(管理端代客下单时必传)。 + /// + public int? CustomerId { get; set; } } diff --git a/src/Oms.Application/Dtos/Orders/OrderWorkplaceBusinessTrendOutput.cs b/src/Oms.Application/Dtos/Orders/OrderWorkplaceBusinessTrendOutput.cs new file mode 100644 index 0000000..6c05a99 --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/OrderWorkplaceBusinessTrendOutput.cs @@ -0,0 +1,43 @@ +namespace Oms.Application.Dtos.Orders; + +/// +/// 工作台业务线趋势(运单 / 代发 / 揽收新增量)。 +/// +public class OrderWorkplaceBusinessTrendOutput +{ + /// + /// 维度:day / week / month。 + /// + public string Dimension { get; set; } = "day"; + + /// + /// 趋势点(按时间正序)。 + /// + public List Points { get; set; } = []; +} + +/// +/// 单个时间桶的三类业务量。 +/// +public class OrderWorkplaceBusinessTrendPointOutput +{ + /// + /// 展示标签。 + /// + public string Label { get; set; } = string.Empty; + + /// + /// 运单新增(非仓内代发)。 + /// + public int WaybillCount { get; set; } + + /// + /// 代发订单新增(仓内履约)。 + /// + public int FulfillCount { get; set; } + + /// + /// 揽收单新增。 + /// + public int PickupCount { get; set; } +} diff --git a/src/Oms.Application/Dtos/Orders/OrderWorkplaceSpendTrendOutput.cs b/src/Oms.Application/Dtos/Orders/OrderWorkplaceSpendTrendOutput.cs new file mode 100644 index 0000000..e85de5b --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/OrderWorkplaceSpendTrendOutput.cs @@ -0,0 +1,58 @@ +namespace Oms.Application.Dtos.Orders; + +/// +/// 工作台费用趋势(按日/周/月)。 +/// +public class OrderWorkplaceSpendTrendOutput +{ + /// + /// 维度:day / week / month。 + /// + public string Dimension { get; set; } = "day"; + + /// + /// 区间合计:运费支出(客户应付)。 + /// + public decimal TotalSpend { get; set; } + + /// + /// 区间合计:订单数。 + /// + public int TotalOrders { get; set; } + + /// + /// 区间合计:单票均价。 + /// + public decimal AvgAmount { get; set; } + + /// + /// 趋势点(按时间正序)。 + /// + public List Points { get; set; } = []; +} + +/// +/// 单个时间桶的费用汇总。 +/// +public class OrderWorkplaceSpendTrendPointOutput +{ + /// + /// 展示标签。 + /// + public string Label { get; set; } = string.Empty; + + /// + /// 订单数(创建时间)。 + /// + public int OrderCount { get; set; } + + /// + /// 运费支出合计(Order.PayableAmount)。 + /// + public decimal SpendAmount { get; set; } + + /// + /// 单票均价。 + /// + public decimal AvgAmount { get; set; } +} diff --git a/src/Oms.Application/Dtos/Orders/OrderWorkplaceStatsOutput.cs b/src/Oms.Application/Dtos/Orders/OrderWorkplaceStatsOutput.cs index 1d345af..4e963fb 100644 --- a/src/Oms.Application/Dtos/Orders/OrderWorkplaceStatsOutput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderWorkplaceStatsOutput.cs @@ -41,15 +41,20 @@ public class OrderWorkplaceStatsOutput public int Shipped { get; set; } /// - /// 待上网数量。 + /// 待支付数量。 /// - public int PendingOnline { get; set; } + public int PendingPayment { get; set; } /// /// 问题件数量。 /// public int Problematic { get; set; } + /// + /// 理赔件数量。 + /// + public int Claimed { get; set; } + /// /// 店铺数量。 /// @@ -59,4 +64,14 @@ public class OrderWorkplaceStatsOutput /// 店铺订单待处理数量(履约状态 pending)。 /// public int StoreOrderPending { get; set; } + + /// + /// 代发订单统计(仓内履约)。 + /// + public FulfillWorkplaceStatsOutput Fulfill { get; set; } = new(); + + /// + /// 揽收订单统计。 + /// + public PickupWorkplaceStatsOutput Pickup { get; set; } = new(); } diff --git a/src/Oms.Application/Dtos/Orders/PickupOrderDtos.cs b/src/Oms.Application/Dtos/Orders/PickupOrderDtos.cs new file mode 100644 index 0000000..cebd222 --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/PickupOrderDtos.cs @@ -0,0 +1,290 @@ +using System.ComponentModel.DataAnnotations; + +namespace Oms.Application.Dtos.Orders; + +public class PickupOrderCreateInput +{ + public int? CustomerId { get; set; } + + /// + /// 请求幂等键(可选)。 + /// + public string? RequestId { get; set; } + + [Required] + public int SenderAddressId { get; set; } + + [Required] + public int WarehouseId { get; set; } + + public string? CarrierCode { get; set; } + + public string? CarrierService { get; set; } + + [Required] + public DateTime ExpectPickupTime { get; set; } + + [Required] + [MinLength(1)] + public List OrderIds { get; set; } = []; + + [StringLength(512)] + public string? Remark { get; set; } + + /// + /// 可选:创建时直接写入对客运费(未写则保持未确认)。 + /// + public decimal? FreightAmount { get; set; } +} + +public class PickupOrderIdInput +{ + [Required] + public int Id { get; set; } +} + +public class PickupOrderIdsInput +{ + [Required] + [MinLength(1)] + public List Ids { get; set; } = []; +} + +public class PickupOrderBatchPayItemOutput +{ + public int Id { get; set; } + + public string? PickupNo { get; set; } + + public bool Success { get; set; } + + public string Message { get; set; } = string.Empty; + + public decimal? Amount { get; set; } +} + +public class PickupOrderBatchPayOutput +{ + public int SuccessCount { get; set; } + + public int FailCount { get; set; } + + public decimal PaidAmount { get; set; } + + public string Message { get; set; } = string.Empty; + + public List Items { get; set; } = []; +} + +public class PickupOrderOrdersInput +{ + [Required] + public int Id { get; set; } + + [Required] + [MinLength(1)] + public List OrderIds { get; set; } = []; +} + +public class PickupOrderListInput +{ + public int Page { get; set; } = 1; + + public int PageSize { get; set; } = 30; + + public int? CustomerId { get; set; } + + public string? Status { get; set; } + + public string? PayStatus { get; set; } + + public string? Keyword { get; set; } + + public int? WarehouseId { get; set; } + + public DateTime? CreateTimeStart { get; set; } + + public DateTime? CreateTimeEnd { get; set; } + + public DateTime? ExpectPickupTimeStart { get; set; } + + public DateTime? ExpectPickupTimeEnd { get; set; } +} + +public class PickupOrderStatusCountsOutput +{ + public int Total { get; set; } + + public int PendingPayment { get; set; } + + public Dictionary Counts { get; set; } = new(StringComparer.OrdinalIgnoreCase); +} + +public class PickupOrderConfirmFreightInput +{ + [Required] + public int Id { get; set; } + + [Required] + public decimal FreightAmount { get; set; } + + public decimal? OtherFeeAmount { get; set; } + + public decimal? CarrierPayableAmount { get; set; } +} + +public class PickupOrderScheduleInput +{ + [Required] + public int Id { get; set; } + + /// + /// 兼容旧字段,已不再作为预约必填;承运服务改用销售产品编码。 + /// + public string? CarrierCode { get; set; } + + /// + /// 承运服务:国内揽收分组销售产品编码。 + /// + [Required] + public string CarrierService { get; set; } = string.Empty; + + /// + /// 国内承运商回执单号(手工录入或对接返回)。 + /// + public string? CarrierWaybillNo { get; set; } + + public DateTime? ExpectPickupTime { get; set; } +} + +public class PickupOrderRescheduleInput +{ + [Required] + public int Id { get; set; } + + [Required] + public DateTime ExpectPickupTime { get; set; } +} + +public class PickupOrderRejectItem +{ + public int OrderId { get; set; } + + public string? ServiceNo { get; set; } + + public string Reason { get; set; } = string.Empty; +} + +public class PickupOrderLineOutput +{ + public int OrderId { get; set; } + + public string? ServiceNo { get; set; } + + public string? ClientNo { get; set; } + + public string? OrderStatus { get; set; } + + public int? WarehouseId { get; set; } + + public decimal? ChargeableWeight { get; set; } +} + +public class PickupOrderOutput +{ + public int Id { get; set; } + + public string PickupNo { get; set; } = string.Empty; + + public string? RequestId { get; set; } + + public int CustomerId { get; set; } + + public string? CustomerName { get; set; } + + public string? OrganizationId { get; set; } + + public int SecretLevel { get; set; } + + public int SenderAddressId { get; set; } + + public string SenderName { get; set; } = string.Empty; + + public string? SenderPhone { get; set; } + + public string? SenderTelePhone { get; set; } + + public string? SenderEmail { get; set; } + + public string? SenderCompany { get; set; } + + public int? SenderCountry { get; set; } + + public string? SenderCountryCode { get; set; } + + public string? SenderProvince { get; set; } + + public string? SenderCity { get; set; } + + public string? SenderZipCode { get; set; } + + public string? SenderStreetAddress1 { get; set; } + + public string? SenderStreetAddress2 { get; set; } + + public string? SenderStreetAddress3 { get; set; } + + public string? SenderHouseNumber { get; set; } + + public int WarehouseId { get; set; } + + public string? WarehouseName { get; set; } + + public string? CarrierCode { get; set; } + + public string? CarrierService { get; set; } + + public string? CarrierWaybillNo { get; set; } + + public DateTime ExpectPickupTime { get; set; } + + public DateTime? ActualPickupTime { get; set; } + + public string Status { get; set; } = string.Empty; + + public int ParcelCount { get; set; } + + public decimal? TotalActualWeight { get; set; } + + public decimal? ChargeableWeight { get; set; } + + public string Currency { get; set; } = "CNY"; + + public decimal? FreightAmount { get; set; } + + public decimal? OtherFeeAmount { get; set; } + + public decimal? ReceivableAmount { get; set; } + + public string PayStatus { get; set; } = string.Empty; + + public DateTime? PayTime { get; set; } + + public string PayMode { get; set; } = string.Empty; + + public decimal? CarrierPayableAmount { get; set; } + + public string SettlementStatus { get; set; } = string.Empty; + + public string? SettlementBatchNo { get; set; } + + public string? Remark { get; set; } + + public DateTime? CreateTime { get; set; } + + public DateTime? UpdateTime { get; set; } + + public List Orders { get; set; } = []; + + public List Rejected { get; set; } = []; +} diff --git a/src/Oms.Application/Dtos/Orders/PickupWorkplaceStatsOutput.cs b/src/Oms.Application/Dtos/Orders/PickupWorkplaceStatsOutput.cs new file mode 100644 index 0000000..4145095 --- /dev/null +++ b/src/Oms.Application/Dtos/Orders/PickupWorkplaceStatsOutput.cs @@ -0,0 +1,19 @@ +namespace Oms.Application.Dtos.Orders; + +/// +/// 工作台揽收订单统计。 +/// +public class PickupWorkplaceStatsOutput +{ + /// 待支付(有应收且未支付,不含取消/失败)。 + public int PendingPayment { get; set; } + + /// 草稿,待确认下发。 + public int PendingSchedule { get; set; } + + /// 已预约/已派单,待取件。 + public int PendingPickup { get; set; } + + /// 已取件,待到仓。 + public int PendingInbound { get; set; } +} diff --git a/src/Oms.Application/Dtos/PlatformStore/PlatformStoreDtos.cs b/src/Oms.Application/Dtos/PlatformStore/PlatformStoreDtos.cs index 36baf5b..cdab609 100644 --- a/src/Oms.Application/Dtos/PlatformStore/PlatformStoreDtos.cs +++ b/src/Oms.Application/Dtos/PlatformStore/PlatformStoreDtos.cs @@ -147,6 +147,11 @@ public class PlatformStoreOrderListInput : PlatformStorePageInput { public int? StoreId { get; set; } + /// + /// 平台编码:tiktok / temu / shopee / lazada;空或 all 表示全部。 + /// + public string? PlatformCode { get; set; } + /// /// 履约状态:pending / toShip / shipped / canceled / suspended / completed;空或 all 表示全部。 /// @@ -254,6 +259,12 @@ public class PlatformStoreOrderOutput public string? LinkedServiceNo { get; set; } + /// 列表摘要:首个商品名称。 + public string? FirstProductName { get; set; } + + /// 列表摘要:首个商品图片。 + public string? FirstProductImageUrl { get; set; } + public DateTime? LastSyncTime { get; set; } public List Lines { get; set; } = []; diff --git a/src/Oms.Application/Dtos/Rbac/OmsUserProfileDtos.cs b/src/Oms.Application/Dtos/Rbac/OmsUserProfileDtos.cs index 9ea1153..903a8f2 100644 --- a/src/Oms.Application/Dtos/Rbac/OmsUserProfileDtos.cs +++ b/src/Oms.Application/Dtos/Rbac/OmsUserProfileDtos.cs @@ -11,6 +11,11 @@ public class UserProfileData public string? WechatId { get; set; } public string? WechatQrCode { get; set; } + + /// + /// 企业微信客服接入链接(微信外接入)。 + /// + public string? WecomKfUrl { get; set; } } public class OmsUserCreateInput : UserCreateDto @@ -22,6 +27,8 @@ public class OmsUserCreateInput : UserCreateDto public string? WechatId { get; set; } public string? WechatQrCode { get; set; } + + public string? WecomKfUrl { get; set; } } public class OmsUserUpdateInput : UserUpdateDto @@ -31,6 +38,8 @@ public class OmsUserUpdateInput : UserUpdateDto public string? WechatId { get; set; } public string? WechatQrCode { get; set; } + + public string? WecomKfUrl { get; set; } } public class OmsUserDetailDto : UserDto @@ -42,4 +51,6 @@ public class OmsUserDetailDto : UserDto public string? WechatId { get; set; } public string? WechatQrCode { get; set; } + + public string? WecomKfUrl { get; set; } } diff --git a/src/Oms.Application/Dtos/System/NoticeCreateInput.cs b/src/Oms.Application/Dtos/System/NoticeCreateInput.cs index c9742ac..e31841b 100644 --- a/src/Oms.Application/Dtos/System/NoticeCreateInput.cs +++ b/src/Oms.Application/Dtos/System/NoticeCreateInput.cs @@ -32,14 +32,13 @@ public class NoticeCreateInput public byte IsPopup { get; set; } /// - /// 接收对象类型:user/customer。 + /// 接收对象类型:user/customer。公告全体广播时可空(后端按 user 占位)。 /// - [Required] [StringLength(16)] public string ReceiverType { get; set; } = string.Empty; /// - /// 接收主体 ID 列表。 + /// 接收主体 ID 列表。公告传空表示全体生效;站内信必填。 /// public List ReceiverIds { get; set; } = []; } diff --git a/src/Oms.Application/Dtos/System/NoticeListInput.cs b/src/Oms.Application/Dtos/System/NoticeListInput.cs index 1ebc69a..4707ffa 100644 --- a/src/Oms.Application/Dtos/System/NoticeListInput.cs +++ b/src/Oms.Application/Dtos/System/NoticeListInput.cs @@ -29,4 +29,9 @@ public class NoticeListInput /// 关键词,匹配标题或内容。 /// public string? Keyword { get; set; } + + /// + /// 仅未读(相对当前登录主体)。 + /// + public bool? OnlyUnread { get; set; } } diff --git a/src/Oms.Application/Dtos/System/NoticeOutput.cs b/src/Oms.Application/Dtos/System/NoticeOutput.cs index 058f368..e142df5 100644 --- a/src/Oms.Application/Dtos/System/NoticeOutput.cs +++ b/src/Oms.Application/Dtos/System/NoticeOutput.cs @@ -60,6 +60,11 @@ public class NoticeOutput /// public int ReadCount { get; set; } + /// + /// 当前登录主体是否已读。 + /// + public bool IsRead { get; set; } + /// /// 接收总人数。 /// diff --git a/src/Oms.Application/Dtos/Warehouse/WarehouseDtos.cs b/src/Oms.Application/Dtos/Warehouse/WarehouseDtos.cs index 5b0e84f..85f3df5 100644 --- a/src/Oms.Application/Dtos/Warehouse/WarehouseDtos.cs +++ b/src/Oms.Application/Dtos/Warehouse/WarehouseDtos.cs @@ -32,8 +32,16 @@ public class WarehouseSkuOutput public string SkuName { get; set; } = string.Empty; + public string? SkuNameEn { get; set; } + public string? SkuImageUrl { get; set; } + public decimal? UnitPrice { get; set; } + + public string? ExHsCode { get; set; } + + public string? ImHsCode { get; set; } + public decimal? WeightG { get; set; } public decimal? LengthCm { get; set; } @@ -44,7 +52,7 @@ public class WarehouseSkuOutput public string? Remark { get; set; } - public int TotalQty { get; set; } + public int? TotalQty { get; set; } public DateTime CreateTime { get; set; } @@ -63,8 +71,16 @@ public class WarehouseSkuSaveInput [Required] public string SkuName { get; set; } = string.Empty; + public string? SkuNameEn { get; set; } + public string? SkuImageUrl { get; set; } + public decimal? UnitPrice { get; set; } + + public string? ExHsCode { get; set; } + + public string? ImHsCode { get; set; } + public decimal? WeightG { get; set; } public decimal? LengthCm { get; set; } @@ -563,6 +579,7 @@ public class WarehouseParcelArrivalListInput : WarehousePageInput public class WarehouseParcelArrivalCreateInput { + /// 已废弃:到仓按仓库+快递单号定位包裹,客户归属取自包裹。 public int? CustomerId { get; set; } [Required] @@ -591,4 +608,20 @@ public class WarehouseParcelArrivalOutput public int CreateUserId { get; set; } public string? CreateBy { get; set; } + + /// + /// 到仓包裹已绑定的代发物流单(bound 状态)。 + /// + public List LinkedOrders { get; set; } = []; +} + +public class WarehouseParcelArrivalLinkedOrderOutput +{ + public int OrderId { get; set; } + + public string ServiceNo { get; set; } = string.Empty; + + public string? ClientNo { get; set; } + + public string? FulfillProgress { get; set; } } diff --git a/src/Oms.Application/Dtos/Xhs/XhsDtos.cs b/src/Oms.Application/Dtos/Xhs/XhsDtos.cs index 7bd4919..100c7b2 100644 --- a/src/Oms.Application/Dtos/Xhs/XhsDtos.cs +++ b/src/Oms.Application/Dtos/Xhs/XhsDtos.cs @@ -320,75 +320,6 @@ public class XhsSkillSaveInput public object? Recipe { get; set; } } -public class XhsAiProviderOutput -{ - public int Id { get; set; } - - public string ProviderKey { get; set; } = string.Empty; - - public string ProviderType { get; set; } = string.Empty; - - public string DisplayName { get; set; } = string.Empty; - - public string BaseUrl { get; set; } = string.Empty; - - public string? ApiKey { get; set; } - - public string? ApiSecret { get; set; } - - public bool IsDefault { get; set; } - - public bool Enabled { get; set; } -} - -public class XhsAiProviderSaveInput -{ - [Required] - public string ProviderKey { get; set; } = string.Empty; - - [Required] - public string ProviderType { get; set; } = string.Empty; - - [Required] - public string DisplayName { get; set; } = string.Empty; - - [Required] - public string BaseUrl { get; set; } = string.Empty; - - public string? ApiKey { get; set; } - - public string? ApiSecret { get; set; } - - public bool IsDefault { get; set; } - - public bool Enabled { get; set; } = true; -} - -public class XhsAiChatInput -{ - [Required] - public string ProviderKey { get; set; } = string.Empty; - - public string? Model { get; set; } - - [Required] - public List Messages { get; set; } = []; - - public string Scene { get; set; } = "assistant"; -} - -public class XhsAiChatMessageInput -{ - public string Role { get; set; } = "user"; - - public string Content { get; set; } = string.Empty; -} - -public class XhsAiChatOutput -{ - public string Content { get; set; } = string.Empty; -} - public class XhsAnalysisStartInput { [Required] diff --git a/src/Oms.Application/Integrations/Itfx/IItfxForwardClient.cs b/src/Oms.Application/Integrations/Itfx/IItfxForwardClient.cs index c5a5ce8..cdeee86 100644 --- a/src/Oms.Application/Integrations/Itfx/IItfxForwardClient.cs +++ b/src/Oms.Application/Integrations/Itfx/IItfxForwardClient.cs @@ -21,4 +21,15 @@ public interface IItfxForwardClient string appSecret, object body, CancellationToken cancellationToken = default); + + /// + /// 通用 ForwardWithSubscribe(standardCode 可配,如 9610 申报暂定码)。 + /// + Task ForwardWithSubscribeAsync( + string standardCode, + string supplierCode, + string appKey, + string appSecret, + object body, + CancellationToken cancellationToken = default); } diff --git a/src/Oms.Application/Integrations/Itfx/ItfxForwardClient.cs b/src/Oms.Application/Integrations/Itfx/ItfxForwardClient.cs index e16f6ff..949bf88 100644 --- a/src/Oms.Application/Integrations/Itfx/ItfxForwardClient.cs +++ b/src/Oms.Application/Integrations/Itfx/ItfxForwardClient.cs @@ -21,7 +21,24 @@ internal sealed class ItfxForwardClient( WriteIndented = true }; - public async Task ForwardCreateOrderOneAsync( + public Task ForwardCreateOrderOneAsync( + string supplierCode, + string appKey, + string appSecret, + object body, + CancellationToken cancellationToken = default) + { + return ForwardWithSubscribeAsync( + CreateOrderOneStandardCode, + supplierCode, + appKey, + appSecret, + body, + cancellationToken); + } + + public async Task ForwardWithSubscribeAsync( + string standardCode, string supplierCode, string appKey, string appSecret, @@ -34,9 +51,19 @@ internal sealed class ItfxForwardClient( throw new InvalidOperationException("Itfx BaseUrl not configured"); } + if (string.IsNullOrWhiteSpace(standardCode)) + { + throw new InvalidOperationException("Itfx standardCode is empty"); + } + + if (string.IsNullOrWhiteSpace(supplierCode)) + { + throw new InvalidOperationException("Itfx supplierCode is empty"); + } + var root = $"{settings.BaseUrl.Trim().TrimEnd('/')}/InterfaceForward/ForwardWithSubscribe"; var url = - $"{root}?standardCode={CreateOrderOneStandardCode}&supplierCode={Uri.EscapeDataString(supplierCode)}"; + $"{root}?standardCode={Uri.EscapeDataString(standardCode.Trim())}&supplierCode={Uri.EscapeDataString(supplierCode.Trim())}"; var requestJson = JsonSerializer.Serialize(body, JsonOptions); using var request = new HttpRequestMessage(HttpMethod.Post, url); diff --git a/src/Oms.Application/Integrations/Itfx/ItfxGatewayOptions.cs b/src/Oms.Application/Integrations/Itfx/ItfxGatewayOptions.cs index 19366bd..1ba817e 100644 --- a/src/Oms.Application/Integrations/Itfx/ItfxGatewayOptions.cs +++ b/src/Oms.Application/Integrations/Itfx/ItfxGatewayOptions.cs @@ -13,4 +13,24 @@ public class ItfxGatewayOptions public string BaseUrl { get; set; } = "http://api.nanafa.com/itfx"; public int TimeoutSeconds { get; set; } = 30; + + /// + /// 9610 汇总申报上游标准码(暂定,可在配置覆盖)。 + /// + public string Customs9610StandardCode { get; set; } = "customs9610Declare"; + + /// + /// 9610 获取清单数据上游标准码(暂定)。 + /// + public string Customs9610ManifestStandardCode { get; set; } = "customs9610Manifest"; + + /// + /// 9610 获取报关单上游标准码(暂定)。 + /// + public string Customs9610DeclarationFormStandardCode { get; set; } = "customs9610DeclarationForm"; + + /// + /// 9610 申报默认 supplierCode;空则回退订单 DownstreamSupplierCode。 + /// + public string? Customs9610SupplierCode { get; set; } } diff --git a/src/Oms.Application/Oms.Application.csproj b/src/Oms.Application/Oms.Application.csproj index 352ddee..bea92ee 100644 --- a/src/Oms.Application/Oms.Application.csproj +++ b/src/Oms.Application/Oms.Application.csproj @@ -37,4 +37,8 @@ + + + + diff --git a/src/Oms.Application/OmsApplicationModule.cs b/src/Oms.Application/OmsApplicationModule.cs index ec7976d..f44ca86 100644 --- a/src/Oms.Application/OmsApplicationModule.cs +++ b/src/Oms.Application/OmsApplicationModule.cs @@ -55,7 +55,7 @@ public class OmsApplicationModule : FakeModule context.Services.AddOmsItfxIntegration(configuration); context.Services.AddOmsPlatformShopIntegration(configuration); context.Services.AddOmsOrderBatchMessaging(configuration); - context.Services.AddXhsLlmClient(); + context.Services.AddAiLlmClient(); context.Services.AddHostedService(); context.Services.AddHostedService(); } diff --git a/src/Oms.Application/Rbac/CustomerServiceAdvisorResolver.cs b/src/Oms.Application/Rbac/CustomerServiceAdvisorResolver.cs index 7d11d34..ea7f768 100644 --- a/src/Oms.Application/Rbac/CustomerServiceAdvisorResolver.cs +++ b/src/Oms.Application/Rbac/CustomerServiceAdvisorResolver.cs @@ -30,6 +30,7 @@ public class CustomerServiceAdvisorResolver(FakeRbacDbContext dbContext) : IScop Name = row.Name, WechatId = row.WechatId, WechatQrCode = row.WechatQrCode, + WecomKfUrl = row.WecomKfUrl, }; } @@ -44,7 +45,8 @@ public class CustomerServiceAdvisorResolver(FakeRbacDbContext dbContext) : IScop SELECT u.`Name` AS `Name`, u.`WechatId` AS `WechatId`, - u.`WechatQrCode` AS `WechatQrCode` + u.`WechatQrCode` AS `WechatQrCode`, + u.`WecomKfUrl` AS `WecomKfUrl` FROM `user` u WHERE u.`IsDeleted` = 0 AND u.`userid` = {0} @@ -62,7 +64,8 @@ public class CustomerServiceAdvisorResolver(FakeRbacDbContext dbContext) : IScop SELECT u.`Name` AS `Name`, u.`WechatId` AS `WechatId`, - u.`WechatQrCode` AS `WechatQrCode` + u.`WechatQrCode` AS `WechatQrCode`, + u.`WecomKfUrl` AS `WecomKfUrl` FROM `user` u WHERE u.`IsDeleted` = 0 AND (u.`Name` = {0} OR u.`Account` = {0}) @@ -82,5 +85,7 @@ public class CustomerServiceAdvisorResolver(FakeRbacDbContext dbContext) : IScop public string? WechatId { get; set; } public string? WechatQrCode { get; set; } + + public string? WecomKfUrl { get; set; } } } diff --git a/src/Oms.Application/Rbac/OmsUserProfileMapper.cs b/src/Oms.Application/Rbac/OmsUserProfileMapper.cs index 84d7761..463a194 100644 --- a/src/Oms.Application/Rbac/OmsUserProfileMapper.cs +++ b/src/Oms.Application/Rbac/OmsUserProfileMapper.cs @@ -32,6 +32,7 @@ internal static class OmsUserProfileMapper detail.EmployeeNo = profile.EmployeeNo; detail.WechatId = profile.WechatId; detail.WechatQrCode = profile.WechatQrCode; + detail.WecomKfUrl = profile.WecomKfUrl; return detail; } } diff --git a/src/Oms.Application/Rbac/UserProfileRepository.cs b/src/Oms.Application/Rbac/UserProfileRepository.cs index a90da01..73f75a3 100644 --- a/src/Oms.Application/Rbac/UserProfileRepository.cs +++ b/src/Oms.Application/Rbac/UserProfileRepository.cs @@ -20,7 +20,8 @@ public class UserProfileRepository(FakeRbacDbContext dbContext) : IScopedDepende u.`Phone` AS `Phone`, u.`EmployeeNo` AS `EmployeeNo`, u.`WechatId` AS `WechatId`, - u.`WechatQrCode` AS `WechatQrCode` + u.`WechatQrCode` AS `WechatQrCode`, + u.`WecomKfUrl` AS `WecomKfUrl` FROM `user` u WHERE u.`Id` = {0} AND u.`IsDeleted` = 0 LIMIT 1 @@ -41,6 +42,7 @@ public class UserProfileRepository(FakeRbacDbContext dbContext) : IScopedDepende EmployeeNo = row.EmployeeNo, WechatId = row.WechatId, WechatQrCode = row.WechatQrCode, + WecomKfUrl = row.WecomKfUrl, }; } @@ -60,7 +62,8 @@ public class UserProfileRepository(FakeRbacDbContext dbContext) : IScopedDepende u.`Phone` AS `Phone`, u.`EmployeeNo` AS `EmployeeNo`, u.`WechatId` AS `WechatId`, - u.`WechatQrCode` AS `WechatQrCode` + u.`WechatQrCode` AS `WechatQrCode`, + u.`WecomKfUrl` AS `WecomKfUrl` FROM `user` u WHERE u.`Id` IN ({inClause}) AND u.`IsDeleted` = 0 """; @@ -74,6 +77,7 @@ public class UserProfileRepository(FakeRbacDbContext dbContext) : IScopedDepende EmployeeNo = x.EmployeeNo, WechatId = x.WechatId, WechatQrCode = x.WechatQrCode, + WecomKfUrl = x.WecomKfUrl, }); } @@ -85,7 +89,8 @@ public class UserProfileRepository(FakeRbacDbContext dbContext) : IScopedDepende `Phone` = {1}, `EmployeeNo` = {2}, `WechatId` = {3}, - `WechatQrCode` = {4} + `WechatQrCode` = {4}, + `WecomKfUrl` = {5} WHERE `Id` = {0} AND `IsDeleted` = 0 """; @@ -98,6 +103,7 @@ public class UserProfileRepository(FakeRbacDbContext dbContext) : IScopedDepende (object?)NormalizeOptional(profile.EmployeeNo), (object?)NormalizeOptional(profile.WechatId), (object?)NormalizeOptional(profile.WechatQrCode), + (object?)NormalizeOptional(profile.WecomKfUrl), ], cancellationToken); } @@ -112,7 +118,8 @@ public class UserProfileRepository(FakeRbacDbContext dbContext) : IScopedDepende SET `Phone` = {1}, `WechatId` = {2}, - `WechatQrCode` = {3} + `WechatQrCode` = {3}, + `WecomKfUrl` = {4} WHERE `Id` = {0} AND `IsDeleted` = 0 """; @@ -123,6 +130,7 @@ public class UserProfileRepository(FakeRbacDbContext dbContext) : IScopedDepende (object?)NormalizeOptional(profile.Phone), (object?)NormalizeOptional(profile.WechatId), (object?)NormalizeOptional(profile.WechatQrCode), + (object?)NormalizeOptional(profile.WecomKfUrl), ], cancellationToken); } @@ -208,6 +216,8 @@ public class UserProfileRepository(FakeRbacDbContext dbContext) : IScopedDepende public string? WechatId { get; set; } public string? WechatQrCode { get; set; } + + public string? WecomKfUrl { get; set; } } private sealed class UserProfileListRow @@ -221,6 +231,8 @@ public class UserProfileRepository(FakeRbacDbContext dbContext) : IScopedDepende public string? WechatId { get; set; } public string? WechatQrCode { get; set; } + + public string? WecomKfUrl { get; set; } } private sealed class EmployeeNoRow diff --git a/src/Oms.Application/Services/Xhs/XhsAiService.cs b/src/Oms.Application/Services/Ai/AiService.cs similarity index 74% rename from src/Oms.Application/Services/Xhs/XhsAiService.cs rename to src/Oms.Application/Services/Ai/AiService.cs index 4ef37a6..cc9ecbd 100644 --- a/src/Oms.Application/Services/Xhs/XhsAiService.cs +++ b/src/Oms.Application/Services/Ai/AiService.cs @@ -1,48 +1,51 @@ using Fake.Application; using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Ai; using Oms.Application.Dtos.Shared; -using Oms.Application.Dtos.Xhs; using Oms.Application.Shared; +using Oms.Domain.AiAggregate.Entities; +using Oms.Domain.AiAggregate.Repositories; using Oms.Domain.CustomersAggregate.Repositories; -using Oms.Domain.XhsAggregate.Entities; -using Oms.Domain.XhsAggregate.Repositories; -namespace Oms.Application.Services.Xhs; +namespace Oms.Application.Services.Ai; -[ApiExplorerSettings(GroupName = "OMS-Xhs")] -public class XhsAiService : ApplicationService +/// +/// 全局 AI 提供商与对话服务(系统级,非业务域专属)。 +/// +[ApiExplorerSettings(GroupName = "OMS-Ai")] +public class AiService : ApplicationService { private const string SecretMask = "******"; - private IXhsAiProviderRepository AiProviderRepository => LazyServiceProvider.GetRequiredService(); + private IAiProviderRepository AiProviderRepository => LazyServiceProvider.GetRequiredService(); private ICustomerRepository CustomerRepository => LazyServiceProvider.GetRequiredService(); /// - /// 查询AI服务商列表 + /// 查询 AI 服务商列表。 /// - [HttpPost("/xhs/ai/provider/list")] - public async Task> ListProvidersAsync() + [HttpPost("/ai/provider/list")] + public async Task> ListProvidersAsync() { var customerId = await OmsSessionHelper.ResolveXhsCustomerIdAsync(CustomerRepository, CurrentUser); var items = await AiProviderRepository.GetListAsync(x => x.CustomerId == customerId || x.CustomerId == 0); - return new OmsItemsResult + return new OmsItemsResult { Items = items.Select(x => MapProvider(x, maskSecret: true)).ToList() }; } /// - /// 保存AI服务商配置 + /// 保存 AI 服务商配置。 /// - [HttpPost("/xhs/ai/provider/save")] - public async Task SaveProviderAsync(XhsAiProviderSaveInput input) + [HttpPost("/ai/provider/save")] + public async Task SaveProviderAsync(AiProviderSaveInput input) { var customerId = await OmsSessionHelper.ResolveXhsCustomerIdAsync(CustomerRepository, CurrentUser); var providerKey = input.ProviderKey.Trim(); var entity = await AiProviderRepository.GetByProviderKeyAsync(customerId, providerKey); if (entity == null) { - entity = new XhsAiProvider { CustomerId = customerId, ProviderKey = providerKey }; + entity = new AiProvider { CustomerId = customerId, ProviderKey = providerKey }; } entity.ProviderType = input.ProviderType.Trim(); @@ -85,22 +88,22 @@ public class XhsAiService : ApplicationService } /// - /// AI对话 + /// AI 对话。 /// - [HttpPost("/xhs/ai/chat")] - public async Task ChatAsync(XhsAiChatInput input) + [HttpPost("/ai/chat")] + public async Task ChatAsync(AiChatInput input) { var customerId = await OmsSessionHelper.ResolveXhsCustomerIdAsync(CustomerRepository, CurrentUser); var provider = await ResolveProviderAsync(customerId, input.ProviderKey.Trim()); - var llm = LazyServiceProvider.GetRequiredService(); + var llm = LazyServiceProvider.GetRequiredService(); var content = await llm.ChatCompletionAsync( provider, input.Messages.Select(x => (x.Role, x.Content)).ToList(), input.Model); - return new XhsAiChatOutput { Content = content }; + return new AiChatOutput { Content = content }; } - internal async Task ResolveProviderAsync(int customerId, string providerKey) + internal async Task ResolveProviderAsync(int customerId, string providerKey) { var provider = await AiProviderRepository.GetByProviderKeyAsync(customerId, providerKey); if (provider == null || !provider.Enabled) @@ -116,7 +119,7 @@ public class XhsAiService : ApplicationService return provider; } - private static XhsAiProviderOutput MapProvider(XhsAiProvider entity, bool maskSecret) => new() + private static AiProviderOutput MapProvider(AiProvider entity, bool maskSecret) => new() { Id = entity.Id, ProviderKey = entity.ProviderKey, diff --git a/src/Oms.Application/Services/Ai/AiSkillSeedContent.json b/src/Oms.Application/Services/Ai/AiSkillSeedContent.json new file mode 100644 index 0000000..d0c8738 --- /dev/null +++ b/src/Oms.Application/Services/Ai/AiSkillSeedContent.json @@ -0,0 +1 @@ +{"price":"你是 OMS「销售产品卖价发布」风险分析助手。对比「线上生效价」与「待发布价」,找出可能做错价、漏改、异常涨跌等问题,输出中文风险报告。\r\n\r\n## 产出格式(必须严格遵守)\r\n\r\n总评:高风险 | 中风险 | 低风险 | 无显著差异\r\n摘要:一句话说明本次变更整体风险\r\n风险点:\r\n1. [高|中|低] 字段/价格项:旧值 → 新值;原因:…\r\n2. …\r\n建议:发布前核对 … / 可发布 …\r\n\r\n- 若无实质差异:总评写「无显著差异」,风险点可写「无」\r\n- 不要编造上下文中不存在的字段或金额\r\n- 优先标出会导致客户错计费、少收/多收的变更\r\n- 本报告经用户「采用」后随价格发布版本落库(aiAnalysisReport),须严肃、可追溯\r\n\r\n## 风险检查清单(必查)\r\n\r\n1. 单价 / calculationFormula / calculatedValue 异常跳变(数量级、符号、空值、0 价)\r\n2. currency 币种误改\r\n3. 价格项新增 / 删除 / status 停用启用\r\n4. factors / factorValues / factorValuesJson 维度错位或漏维\r\n5. customerGroupValues 客户分组价漏改、串组、整组清空\r\n6. chargingCondition / costUnit / costItem 语义变化\r\n7. priceArea / priceAreaId / priceAreaInfos 分区错绑\r\n8. 首次发布(无线上快照)时,检查待发布是否像「未完成草稿」\r\n9. 相对生效版的「大面积替换」感(大量行删除+新增)\r\n\r\n## 输入说明\r\n\r\n用户消息会提供:\r\n- 产品信息、生效版本\r\n- Diff 摘要(仅变更行)\r\n- 精简后的线上/待发布快照片段(可能截断)\r\n","formula":"你是 OMS「自动触发」公式助手。根据用户中文描述,生成可粘贴的中文公式(ChineseFormulaEvaluator)。\r\n\r\n## 产出格式(必须)\r\n\r\n时机:下单 | 入库 | 出库\r\n操作:拦截 | 警告 | 问题件\r\n公式:单行可执行表达式\r\n说明:一句话\r\n验证样例:可选\r\n\r\n## 语法硬规则\r\n\r\n- 字段名必须是下方目录中的中文 label,禁止编造、禁止英文字段名\r\n- 字符串:字段包含('值');数值/聚合:字段() 再比较;布尔:字段()==1 / ==0\r\n- 字面量用单引号;逻辑用 && || !;比较用 == != > >= < <=\r\n- 禁止 and/or/not、中文「且」、双引号、字段() 用于字符串相等\r\n- 国家一般用二字码:国家包含('GB')\r\n- 公式单行、无注释夹杂、长度 ≤ 10000\r\n\r\n## 示例\r\n\r\n时机:下单\r\n操作:拦截\r\n公式:(单件最大长度()>60||单件最大宽度()>46)&&国家包含('GB')\r\n说明:英国且超尺寸时拦截\r\n验证样例:国家 GB,长 70,宽 40,高 40\r\n","itfx":"---\r\nname: itfx-prefix-script\r\ndescription: >-\r\n Generates InterfaceForward (接口通/itfx) PrefixScript C# for any signature/auth\r\n algorithm (MD5/SHA/HMAC/RSA/custom). Maps writes to Query/Header/Body field lists\r\n per downstream interface detail. Use for 前置脚本, PrefixScript, Natasha script.\r\n---\r\n\r\n# itfx 接口映射前置脚本生成(通用签名)\r\n\r\n为 **InterfaceMap → PrefixScript** 生成 Natasha 可执行的 C# 方法体,**按用户描述的任意签名规则**实现,不限于某一服务商。\r\n\r\n## 何时使用\r\n\r\n- 生成/修改 **前置脚本**(非 PostfixScript)\r\n- 第三方 API 需要签名、鉴权头、动态 token、时间戳参与计算等\r\n- OMS「上游接口 → 映射明细 → 前置脚本」\r\n\r\n## 执行时机\r\n\r\n```\r\nInParamRestructure → ReplacePlaceholder → PrefixScript ← 本 Skill\r\n → SerializationBody → HTTP 请求 → PostfixScript\r\n```\r\n\r\n| 可用 | 不可用 |\r\n|------|--------|\r\n| `obj.OriginalInterfaceMappedInput` | `obj.TargetInterfaceInput`(未序列化) |\r\n| `obj.QueryFieldList` / `HeaderFieldList` / `FormFieldList` | `obj.TargetInterfaceOutput` |\r\n| `obj.FixedFieldList` | 改 `InParamTreeList` / 映射树 |\r\n| `obj.GetAccountFieldValueOrNull(...)` | |\r\n\r\n## 下游接口明细 ↔ 运行时(写入位置必对齐)\r\n\r\n| 接口明细 Tab | 运行时列表 | 典型用途 |\r\n|--------------|------------|----------|\r\n| Query KV | `obj.QueryFieldList` | URL 参数、签名字段 |\r\n| Header KV | `obj.HeaderFieldList` | 请求头、Authorization |\r\n| Body KV(FormUrlEncoded) | `obj.FormFieldList` | 表单字段 |\r\n| Mapping Body 树 | → `OriginalInterfaceMappedInput` | 映射体(Form/None 类) |\r\n| Request Body 树(Json/Xml) | → `OriginalInterfaceMappedInput` | JSON/XML Body |\r\n\r\n**ContentType:** `None(0)` 无 Body;`FormUrlEncoded(1)` Body=FormFieldList;`Json(3)`/`Xml(4)` Body=序列化映射体。\r\n\r\n## 占位符(ReplacePlaceholder 早于 PrefixScript)\r\n\r\n| 占位符 | PrefixScript 阶段 |\r\n|--------|-------------------|\r\n| `$TimeStamp` / `$DateTime` / `$FromAccount` / `$Url` / `$token` | 通常已替换,直接读字段 Value |\r\n| `$FromMappingBody` | FormUrlEncoded:可能仍为字面量;None/Json Query:通常已替换为 JSON。**签名用最终 HTTP 参数值,不要用占位符字面量** |\r\n\r\n## 脚本技术约束\r\n\r\n- C#,Natasha 动态编译;参数名 **`obj`**(不是 `context`)\r\n- 仅方法体:无 `using` / `class` / `namespace` / `void Main`\r\n- 类型 **全限定名**:`System.Security.Cryptography.HMACSHA256`、`Newtonsoft.Json.JsonConvert`\r\n- 含 `await` 或首行 `//async` → 异步委托\r\n\r\n---\r\n\r\n## 通用签名生成流程(任何算法都走此流程)\r\n\r\n用户未给全规则时,**先向用户确认**缺失项;给全则直接生成。\r\n\r\n### 1. 从需求提取七要素\r\n\r\n| 要素 | 问什么 |\r\n|------|--------|\r\n| 算法 | MD5 / SHA1 / SHA256 / HMAC-SHA1 / HMAC-SHA256 / HMAC-MD5 / RSA / 自定义 |\r\n| 签名字符串 | 字段如何拼接、排序、分隔符、是否含 urlPath/body/secret 前缀后缀 |\r\n| 参与字段 | 哪些 Query/Header/Form/Body JSON 字段;**排除签名字段本身** |\r\n| 密钥 | 账户字段名(`GetAccountFieldValueOrNull`)或固定参数 |\r\n| 输出位置 | Query / Header / Form Body / JSON Body 字段名 |\r\n| 编码 | UTF-8;hex **大写/小写**、Base64、是否 URL 编码 |\r\n| 特殊 | 空值是否跳过、嵌套 JSON、时间戳单位、是否 double-MD5 等 |\r\n\r\n### 2. 对照下游接口明细\r\n\r\n- 签名字段在哪个 Tab → 写入 `QueryFieldList` / `HeaderFieldList` / `FormFieldList` 或改 `OriginalInterfaceMappedInput`\r\n- 参与签名的业务字段在哪个 Tab → 从**对应列表**读取 Value\r\n- 账户字段名与服务商配置一致\r\n\r\n### 3. 取参与签名的参数值(通用原则)\r\n\r\n**原则:签名字符串中的每个值 = 最终 HTTP 请求里该参数的值。**\r\n\r\n```csharp\r\n// 按名读 Query(通用 helper 思路,可内联)\r\nstring GetQueryValue(string name) {\r\n for (int i = 0; i < obj.QueryFieldList.Count; i++)\r\n if (obj.QueryFieldList[i].Name == name) return obj.QueryFieldList[i].Value ?? \"\";\r\n return \"\";\r\n}\r\n// Header / Form 同理遍历 HeaderFieldList / FormFieldList\r\n\r\n// JSON Body(ContentType.Json)\r\nstring bodyJson = Newtonsoft.Json.JsonConvert.SerializeObject(obj.OriginalInterfaceMappedInput);\r\n\r\n// 映射体 JSON:优先读已替换好的 Query/Form 字段;仍为 $FromMappingBody 时再 SerializeObject\r\n```\r\n\r\n**常见坑(任何服务商):**\r\n\r\n- 签名字段(`sign`、`_aop_signature` 等)**不参与**签名字符串\r\n- 不要读错列表(Query 参数却在 FormFieldList 里找)\r\n- 不要对已是最终值的字段再 `SerializeObject`(字段顺序/空格会变)\r\n- JSON 内 `\"CHINA SHENZHEN\"` 与 URL 编码的 `+` **不是同一字符**,签名用 JSON 原文\r\n- FormUrlEncoded 阶段 `$FromMappingBody` 可能尚未替换,需 `SerializeObject(OriginalInterfaceMappedInput)` 或读已替换 Value\r\n\r\n### 4. 常见算法 C# 片段(按文档选用,勿臆造)\r\n\r\n**MD5 / SHA → hex**\r\n\r\n```csharp\r\nvar md5 = System.Security.Cryptography.MD5.Create();\r\nbyte[] hash = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(signStr));\r\nstring sign = System.BitConverter.ToString(hash).Replace(\"-\", \"\").ToLowerInvariant();\r\n// 文档要求大写则 .ToUpperInvariant()\r\n```\r\n\r\n**HMAC-SHA1 / HMAC-SHA256 → hex**\r\n\r\n```csharp\r\nusing (var hmac = new System.Security.Cryptography.HMACSHA256(System.Text.Encoding.UTF8.GetBytes(secret))) {\r\n byte[] hash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(signStr));\r\n string sign = System.BitConverter.ToString(hash).Replace(\"-\", \"\").ToLowerInvariant();\r\n}\r\n// HMACSHA1 替换 HMACSHA256;文档要 Base64 则 Convert.ToBase64String(hash)\r\n```\r\n\r\n**按键排序后 key+value 拼接(多种开放平台通用)**\r\n\r\n```csharp\r\nvar parts = new System.Collections.Generic.List();\r\n// parts.Add(\"fieldA\" + valueA); 排除 sign 字段\r\nparts.Sort(System.StringComparer.Ordinal);\r\nvar sb = new System.Text.StringBuilder();\r\nfor (int i = 0; i < parts.Count; i++) sb.Append(parts[i]);\r\nstring signStr = sb.ToString(); // 或 prefix + sb + suffix,按文档\r\n```\r\n\r\n**secret 包裹式:`secret + params + secret`(1688 等)**\r\n\r\n```csharp\r\nstring signStr = secret + paramString + secret;\r\n```\r\n\r\n**写入 Query / Header / Form(字段名按接口明细)**\r\n\r\n```csharp\r\nfor (int i = 0; i < obj.QueryFieldList.Count; i++) {\r\n if (obj.QueryFieldList[i].Name == \"sign\") {\r\n obj.QueryFieldList[i].Value = sign;\r\n break;\r\n }\r\n}\r\n```\r\n\r\n### 5. 生成前自检\r\n\r\n- [ ] 算法、拼接规则、hex 大小写与**用户/文档**一致(不默认某一种)\r\n- [ ] 读写列表与接口明细 Tab 一致\r\n- [ ] 签名字段未参与计算\r\n- [ ] 仅用 `obj`、全限定名、无 `using`\r\n- [ ] 空密钥有抛错或明确处理\r\n\r\n---\r\n\r\n## 示例(仅参考,生成时以用户需求为准)\r\n\r\n### 示例 A:HMAC-SHA1 + urlPath + 排序 param(阿里国际站 AOP 一类)\r\n\r\n- 拼接:`urlPath + sort(key+value)`,不含签名字段\r\n- 输出:Query `_aop_signature`,小写 hex\r\n- 参数在 **QueryFieldList**;JSON 优先读 `notifyBizEventDTO` 的 Value\r\n\r\n### 示例 B:MD5 + secret 包裹 + 排序 keyvalue(1688 一类)\r\n\r\n- 拼接:`appSecret + key1val1key2val2... + appSecret`\r\n- 输出:Query/Form 的 `sign`,常为大写 hex\r\n\r\n### 示例 C:HMAC-SHA256 + Header\r\n\r\n- Body 用 `SerializeObject(OriginalInterfaceMappedInput)` 参与拼接\r\n- 输出:`HeaderFieldList` 的 `X-Sign` 或 `Authorization`\r\n\r\n### 示例 D:JSON Body 内写字段\r\n\r\n- `obj.OriginalInterfaceMappedInput[\"sign\"] = sign;`\r\n\r\n更多代码模式见 [examples.md](examples.md)。\r\n\r\n---\r\n\r\n## 输出要求\r\n\r\n只输出一个 ```csharp 代码块(Natasha 方法体),不要额外解释。\r\n\r\n## 禁止事项\r\n\r\n- 不要用 `HttpClient` 再发请求\r\n- 不要改 `InParamTreeList` / `OutParamTreeList`\r\n- 不要用 `TargetInterfaceInput`\r\n- 不要输出 Python/JavaScript\r\n- 不要写 `using`;不要用 `context`\r\n- 不要把 Query/Header 签名写到 `FormFieldList`\r\n- **不要**在未确认文档时硬编码某一服务商的算法(如默认阿里 HMAC-SHA1)\r\n- 不要把签名字段放进待签名字符串\r\n","address":"你是国际物流 OMS 的收件地址解析助手(跨境打单场景)。\n目标:把客户粘贴的整段中/英收件信息拆成结构化字段,并做「粗校验」提示——只关心下单/预报大概能不能用,不做地图精校、不验证门牌是否真实、不臆造邮编与城市匹配。\n\n只输出 JSON,不要 Markdown,不要解释。字段:\n{\n \"recipientsName\": \"\",\n \"companyName\": \"\",\n \"phone\": \"\",\n \"telePhone\": \"\",\n \"email\": \"\",\n \"countryCode\": \"\",\n \"province\": \"\",\n \"city\": \"\",\n \"streetNumber\": \"\",\n \"streetAddress1\": \"\",\n \"streetAddress2\": \"\",\n \"streetAddress3\": \"\",\n \"zipCode\": \"\",\n \"warnings\": []\n}\n\n规则:\n1) countryCode 必须是 ISO 二字码大写(中国→CN,美国→US,英国→GB 不要用 UK,香港→HK,台湾→TW,澳门→MO)。无法判断则留空并在 warnings 说明。\n2) phone 优先填手机;固定电话放 telePhone;保留 + 国家码。\n3) 街道门牌放入 streetAddress1;过长拆到 streetAddress2/3;单独门牌号可放 streetNumber。\n4) 中国地址:省→province,市→city,区县街道合并进 streetAddress1(不要把省市区塞进姓名)。\n5) 英文地址:State→province,City→city,Street→streetAddress*,ZIP/Postcode→zipCode。\n6) 粗风险才写 warnings(短中文):缺国家/邮编/电话不像号码/街道与姓名粘连拆不清等。禁止写「地图不存在」「邮编与城市不匹配」这类无依据结论。\n7) 不确定的字段留空;不要编造原文没有的省市区邮编。\n8) 税号/EORI/VAT 不是本任务重点,原文没有就忽略。","billingCondition":"你是 OMS「计费条件」公式助手。根据用户中文描述,生成可粘贴到价格项 ChargingCondition 的中文公式(ChineseFormulaEvaluator)。\n\n## 产出格式(必须)\n\n公式:单行可执行表达式\n说明:一句话\n\n## 语法硬规则\n\n- 字段名必须是下方目录中的中文 label,禁止编造、禁止英文字段名\n- 字符串:字段包含('值');数值/聚合:字段() 再比较;布尔:字段()==1 / ==0\n- 字面量用单引号;逻辑用 && || !;比较用 == != > >= < <=\n- 禁止 and/or/not、中文「且」、双引号、字段() 用于字符串相等\n- 附加服务用:附加服务包含('insurance');偏远:是否偏远()==1\n- 空/「无」表示无条件(始终计费),不要输出空公式除非用户明确说无条件\n- 公式单行、无注释夹杂、长度 ≤ 10000\n- 不需要时机/操作(本场景仅计费条件)\n\n## 示例\n\n公式:附加服务包含('insurance')\n说明:客户勾选保险时计费\n\n公式:是否偏远()==1\n说明:偏远地址时计偏远费","parameterMap":"---\r\nname: itfx-create-order-map\r\ndescription: >-\r\n 根据上下游接口参数,按创建物流订单四模块(订单基本信息、收件人、发件人、申报信息)\r\n 做初步字段映射。用于 OMS 上游接口映射明细「AI映射」。\r\n---\r\n\r\n# 创建订单自动映射\r\n\r\n为 **接口通 InterfaceMap 入参映射** 做字段初匹配:把上游(来源)参数映射到下游(目标)参数。\r\n\r\n## 何时使用\r\n\r\n- 创建物流订单 / 下单类接口的入参映射\r\n- 用户点击「AI映射」,希望按业务模块自动填映射关系\r\n\r\n## 业务模块(仅此四类)\r\n\r\n创建物流订单字段通常落在以下模块,匹配时优先按模块归类再比字段名/中文名:\r\n\r\n| 模块 | 常见字段语义 |\r\n|------|----------------|\r\n| 订单基本信息 | 客户单号、参考号、销售产品、重量、尺寸、件数、包裹、币种、COD、备注、下单时间等 |\r\n| 收件人信息 | 收件人姓名、公司、电话、手机、邮箱、国家/省/市、邮编、街道、门牌、税号、证件等 |\r\n| 发件人信息 | 发件人姓名、公司、电话、国家/省/市、邮编、地址、仓库、退件地址等 |\r\n| 申报信息 | 品名中英文、SKU、HSCode、申报数量、单价、总价、材质、用途、品牌、原产地等 |\r\n\r\n## 匹配原则\r\n\r\n1. **语义优先**:alias / cnName / description 同义即可(如 `ConsigneeName` ↔ `recipientsName` / 收件人姓名)。\r\n2. **模块一致**:收件人字段不要映到发件人;申报品名不要映到订单备注。\r\n3. **层级**:数组行(如 `Items[]` / `Parcels[]`)内的叶子字段,优先与同源数组路径匹配。\r\n4. **只映叶子**:跳过纯对象/数组容器节点;无法确定时不要猜,放入 `unmapped`。\r\n5. **一对一**:同一 `sourceId` 尽量只映射一次;目标已有更合适来源时以语义更近者为准。\r\n6. **大小写/分隔符不敏感**:`shipper_name`、`ShipperName`、`shipperName` 视为同名候选。\r\n\r\n## 输入\r\n\r\n用户消息会提供:\r\n\r\n- `targets`:下游待填映射行(含 `id` / `alias` / `cnName` / `description` / `type`)\r\n- `sources`:可选上来源参数扁平列表(含 `id` / `alias` / `cnName` / `description` / `path`)\r\n- 可选用户补充说明\r\n\r\n**约束**:`sourceId` / `targetId` 必须来自输入列表中的 `id`,禁止编造。\r\n\r\n## 输出格式(只输出 JSON,不要 Markdown)\r\n\r\n```json\r\n{\r\n \"mappings\": [\r\n {\r\n \"targetId\": 1001,\r\n \"sourceId\": 2001,\r\n \"module\": \"收件人信息\",\r\n \"reason\": \"收件人姓名\"\r\n }\r\n ],\r\n \"unmapped\": [\r\n {\r\n \"targetId\": 1002,\r\n \"reason\": \"来源无对应税号字段\"\r\n }\r\n ]\r\n}\r\n```\r\n\r\n- `module` 只能是:`订单基本信息` | `收件人信息` | `发件人信息` | `申报信息` | `其他`\r\n- `mappings` 只含有把握的匹配;不确定的进 `unmapped`\r\n- 不要输出除上述 JSON 以外的文字\r\n"} \ No newline at end of file diff --git a/src/Oms.Application/Services/Ai/AiSkillService.cs b/src/Oms.Application/Services/Ai/AiSkillService.cs new file mode 100644 index 0000000..775d83f --- /dev/null +++ b/src/Oms.Application/Services/Ai/AiSkillService.cs @@ -0,0 +1,251 @@ +using System.Text.Json; +using Fake.Application; +using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Ai; +using Oms.Application.Dtos.Shared; +using Oms.Domain.AiAggregate.Entities; +using Oms.Domain.AiAggregate.Repositories; + +namespace Oms.Application.Services.Ai; + +/// +/// 平台级 AI Skill 管理(提示词/规范正文)。 +/// +[ApiExplorerSettings(GroupName = "OMS-Ai")] +public class AiSkillService : ApplicationService +{ + public const string ScenePricePublish = "pricePublish"; + public const string SceneAutoTriggerFormula = "autoTriggerFormula"; + public const string SceneBillingConditionFormula = "billingConditionFormula"; + public const string SceneReceiverAddressParse = "receiverAddressParse"; + public const string SceneItfxPrefixScript = "itfxPrefixScript"; + public const string SceneItfxParameterMap = "itfxParameterMap"; + + public const string KeyPricePublish = "oms-sales-price-publish-risk"; + public const string KeyAutoTriggerFormula = "oms-auto-trigger-formula"; + public const string KeyBillingConditionFormula = "oms-billing-condition-formula"; + public const string KeyReceiverAddressParse = "oms-receiver-address-parse"; + public const string KeyItfxPrefixScript = "itfx-prefix-script"; + public const string KeyItfxCreateOrderMap = "itfx-create-order-map"; + + private IAiSkillRepository AiSkillRepository => LazyServiceProvider.GetRequiredService(); + + /// + /// Skill 列表(可按场景过滤)。 + /// + [HttpPost("/ai/skill/list")] + public async Task> ListAsync(AiSkillListInput input) + { + await EnsureBuiltinSkillsAsync(); + var scene = NormalizeOptional(input.Scene); + var items = await AiSkillRepository.GetListAsync(x => + (scene == null || x.Scene == scene) && + (!input.EnabledOnly || x.Enabled)); + var ordered = items.OrderBy(x => x.SortOrder).ThenBy(x => x.Id).ToList(); + return new OmsItemsResult + { + Items = ordered.Select(x => Map(x, input.IncludeContent)).ToList() + }; + } + + /// + /// 按 Id 或 SkillKey 获取 Skill(含正文)。 + /// + [HttpPost("/ai/skill/get")] + public async Task GetAsync(AiSkillGetInput input) + { + await EnsureBuiltinSkillsAsync(); + AiSkill? entity = null; + if (input.Id is > 0) + { + entity = await AiSkillRepository.FirstOrDefaultAsync(x => x.Id == input.Id.Value); + } + else if (!string.IsNullOrWhiteSpace(input.SkillKey)) + { + entity = await AiSkillRepository.GetBySkillKeyAsync(input.SkillKey.Trim()); + } + + if (entity == null) + { + throw new BusinessException("Skill 不存在"); + } + + return Map(entity, includeContent: true); + } + + /// + /// 新增或更新 Skill。 + /// + [HttpPost("/ai/skill/save")] + public async Task SaveAsync(AiSkillSaveInput input) + { + var skillKey = input.SkillKey.Trim(); + var scene = input.Scene.Trim(); + if (string.IsNullOrWhiteSpace(skillKey) || string.IsNullOrWhiteSpace(scene)) + { + throw new BusinessException("SkillKey / Scene 不能为空"); + } + + AiSkill? entity = null; + if (input.Id is > 0) + { + entity = await AiSkillRepository.FirstOrDefaultAsync(x => x.Id == input.Id.Value); + } + + entity ??= await AiSkillRepository.GetBySkillKeyAsync(skillKey); + + if (entity == null) + { + entity = new AiSkill { SkillKey = skillKey }; + } + else if (!string.Equals(entity.SkillKey, skillKey, StringComparison.OrdinalIgnoreCase)) + { + var conflict = await AiSkillRepository.GetBySkillKeyAsync(skillKey); + if (conflict != null && conflict.Id != entity.Id) + { + throw new BusinessException($"SkillKey 已存在:{skillKey}"); + } + + entity.SkillKey = skillKey; + } + + entity.Scene = scene; + entity.Name = input.Name.Trim(); + entity.Description = NormalizeOptional(input.Description); + entity.Content = input.Content ?? string.Empty; + entity.SortOrder = input.SortOrder; + entity.Enabled = input.Enabled; + + if (entity.Id > 0) + { + await AiSkillRepository.UpdateAsync(entity); + } + else + { + await AiSkillRepository.InsertAsync(entity); + } + + return Map(entity, includeContent: true); + } + + /// + /// 软删除 Skill。 + /// + [HttpPost("/ai/skill/delete")] + public async Task DeleteAsync(AiSkillDeleteInput input) + { + var entity = await AiSkillRepository.FirstOrDefaultAsync(x => x.Id == input.Id); + if (entity == null) + { + throw new BusinessException("Skill 不存在"); + } + + await AiSkillRepository.DeleteAsync(entity); + } + + /// + /// 供内部调用:按 key 取正文,不存在返回 null。 + /// + public async Task TryGetContentByKeyAsync(string skillKey) + { + if (string.IsNullOrWhiteSpace(skillKey)) return null; + await EnsureBuiltinSkillsAsync(); + var entity = await AiSkillRepository.GetBySkillKeyAsync(skillKey.Trim()); + if (entity == null || !entity.Enabled || string.IsNullOrWhiteSpace(entity.Content)) + { + return null; + } + + return entity.Content; + } + + private async Task EnsureBuiltinSkillsAsync() + { + var seeds = LoadSeedDefinitions(); + foreach (var seed in seeds) + { + var existing = await AiSkillRepository.GetBySkillKeyAsync(seed.SkillKey); + if (existing != null) continue; + + await AiSkillRepository.InsertAsync(new AiSkill + { + SkillKey = seed.SkillKey, + Scene = seed.Scene, + Name = seed.Name, + Description = seed.Description, + Content = seed.Content, + SortOrder = seed.SortOrder, + Enabled = true + }); + } + } + + private static List LoadSeedDefinitions() + { + var asm = typeof(AiSkillService).Assembly; + var resourceName = asm.GetManifestResourceNames() + .FirstOrDefault(n => n.EndsWith("AiSkillSeedContent.json", StringComparison.OrdinalIgnoreCase)); + if (resourceName == null) + { + throw new InvalidOperationException("未找到嵌入资源 AiSkillSeedContent.json"); + } + + using var stream = asm.GetManifestResourceStream(resourceName)!; + using var reader = new StreamReader(stream); + var json = reader.ReadToEnd(); + var payload = JsonSerializer.Deserialize(json, new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true + }) + ?? throw new InvalidOperationException("AiSkillSeedContent.json 解析失败"); + + return + [ + new SeedDef(KeyPricePublish, ScenePricePublish, "销售产品价格发布风险", + "对比线上生效价与待发布价,输出中文风险报告", payload.Price, 10), + new SeedDef(KeyAutoTriggerFormula, SceneAutoTriggerFormula, "自动触发公式助手", + "根据中文描述生成可粘贴的自动触发公式(字段目录由前端追加)", payload.Formula, 20), + new SeedDef(KeyBillingConditionFormula, SceneBillingConditionFormula, "计费条件公式助手", + "根据中文描述生成价格项计费条件公式(字段目录由前端追加)", payload.BillingCondition, 25), + new SeedDef(KeyReceiverAddressParse, SceneReceiverAddressParse, "收件地址 AI 解析", + "解析粘贴的收件地址为结构化字段并做粗校验", payload.Address, 30), + new SeedDef(KeyItfxPrefixScript, SceneItfxPrefixScript, "接口通前置脚本", + "按用户需求生成 Natasha C# 前置签名脚本", payload.Itfx, 40), + new SeedDef(KeyItfxCreateOrderMap, SceneItfxParameterMap, "创建订单自动映射", + "按订单基本信息/收件人/发件人/申报信息四模块初步匹配上下游参数", payload.ParameterMap, 50), + ]; + } + + private static AiSkillOutput Map(AiSkill entity, bool includeContent) => new() + { + Id = entity.Id, + SkillKey = entity.SkillKey, + Scene = entity.Scene, + Name = entity.Name, + Description = entity.Description, + Content = includeContent ? entity.Content : string.Empty, + SortOrder = entity.SortOrder, + Enabled = entity.Enabled + }; + + private static string? NormalizeOptional(string? value) => + string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private sealed record SeedDef( + string SkillKey, + string Scene, + string Name, + string Description, + string Content, + int SortOrder); + + private sealed class SeedPayload + { + public string Price { get; set; } = string.Empty; + public string Formula { get; set; } = string.Empty; + public string BillingCondition { get; set; } = string.Empty; + public string Itfx { get; set; } = string.Empty; + public string Address { get; set; } = string.Empty; + public string ParameterMap { get; set; } = string.Empty; + } +} diff --git a/src/Oms.Application/Services/Channels/IssueTemplateService.cs b/src/Oms.Application/Services/Channels/IssueTemplateService.cs index 07d4d57..8e4da90 100644 --- a/src/Oms.Application/Services/Channels/IssueTemplateService.cs +++ b/src/Oms.Application/Services/Channels/IssueTemplateService.cs @@ -24,6 +24,9 @@ public class IssueTemplateService : ApplicationService private DataPermRepository DataPermRepository => LazyServiceProvider.GetRequiredService(); + private OmsRbacUserDisplayNameResolver UserDisplayNameResolver => + LazyServiceProvider.GetRequiredService(); + /// /// 分页查询问题模板列表。 /// @@ -40,7 +43,8 @@ public class IssueTemplateService : ApplicationService new Dictionary { [nameof(IssueTemplate.UpdateTime)] = false, [nameof(IssueTemplate.Id)] = false }); var total = await IssueTemplateRepository.CountAsync(predicate); var orgNameMap = await ResolveOrganizationNameMapAsync(entities); - var items = entities.Select(x => MapOutput(x, orgNameMap)).ToList(); + var handlerUserNameMap = await ResolveHandlerUserNameMapAsync(entities); + var items = entities.Select(x => MapOutput(x, orgNameMap, handlerUserNameMap)).ToList(); return new OmsPageResult { Items = items, Total = total }; } @@ -52,7 +56,8 @@ public class IssueTemplateService : ApplicationService { var entity = await GetEntityOrThrowAsync(id); var orgNameMap = await ResolveOrganizationNameMapAsync([entity]); - return MapOutput(entity, orgNameMap); + var handlerUserNameMap = await ResolveHandlerUserNameMapAsync([entity]); + return MapOutput(entity, orgNameMap, handlerUserNameMap); } /// @@ -69,6 +74,8 @@ public class IssueTemplateService : ApplicationService Title = normalized.Title, Content = normalized.Content, NotifyMethod = normalized.NotifyMethod, + HandlerType = normalized.HandlerType, + HandlerUserId = normalized.HandlerUserId, Status = normalized.Status }; await IssueTemplateRepository.InsertAsync(entity); @@ -87,6 +94,8 @@ public class IssueTemplateService : ApplicationService entity.Title = normalized.Title; entity.Content = normalized.Content; entity.NotifyMethod = normalized.NotifyMethod; + entity.HandlerType = normalized.HandlerType; + entity.HandlerUserId = normalized.HandlerUserId; entity.Status = normalized.Status; await IssueTemplateRepository.UpdateAsync(entity); } @@ -212,6 +221,38 @@ public class IssueTemplateService : ApplicationService throw new BusinessException("请至少选择一种通知方式"); } + var handlerType = input.HandlerType?.Trim().ToLowerInvariant(); + if (string.IsNullOrWhiteSpace(handlerType)) + { + handlerType = IssueHandlerTypeCodes.User; + } + + if (!IssueHandlerTypeCodes.All.Contains(handlerType)) + { + throw new BusinessException("处理人类型不合法"); + } + + int? handlerUserId = null; + if (IssueHandlerTypeCodes.IsUser(handlerType)) + { + if (input.HandlerUserId is not int userId || userId <= 0) + { + throw new BusinessException("请选择指定处理人"); + } + + handlerUserId = userId; + } + else if (IssueHandlerTypeCodes.IsCustomer(handlerType)) + { + var methods = IssueNotifyMethodCodes.ParseList(notifyMethod); + if (methods.Any(x => !string.Equals(x, IssueNotifyMethodCodes.InApp, StringComparison.OrdinalIgnoreCase))) + { + throw new BusinessException("处理人为客户时,目前仅支持站内信通知"); + } + + notifyMethod = IssueNotifyMethodCodes.InApp; + } + var organizationId = NormalizeOrganizationId(input.OrganizationId); if (!string.IsNullOrWhiteSpace(organizationId)) { @@ -238,6 +279,8 @@ public class IssueTemplateService : ApplicationService Title = title, Content = content, NotifyMethod = notifyMethod, + HandlerType = handlerType, + HandlerUserId = handlerUserId, Status = input.Status }; } @@ -280,9 +323,20 @@ public class IssueTemplateService : ApplicationService : await DataPermRepository.GetOrganizationNamesAsync(orgIds); } + private async Task> ResolveHandlerUserNameMapAsync( + IReadOnlyCollection entities) + { + var userIds = entities + .Where(x => IssueHandlerTypeCodes.IsUser(x.HandlerType) && x.HandlerUserId is > 0) + .Select(x => x.HandlerUserId!.Value) + .Distinct(); + return await UserDisplayNameResolver.ResolveManyAsync(userIds); + } + private static IssueTemplateOutput MapOutput( IssueTemplate entity, - IReadOnlyDictionary orgNameMap) + IReadOnlyDictionary orgNameMap, + IReadOnlyDictionary handlerUserNameMap) { string? organizationName = null; if (!string.IsNullOrWhiteSpace(entity.OrganizationId) @@ -307,6 +361,12 @@ public class IssueTemplateService : ApplicationService Content = entity.Content, NotifyMethod = entity.NotifyMethod, NotifyMethods = IssueNotifyMethodCodes.ParseList(entity.NotifyMethod), + HandlerType = entity.HandlerType, + HandlerTypeName = IssueHandlerTypeCodes.GetDisplayName(entity.HandlerType), + HandlerUserId = entity.HandlerUserId, + HandlerUserName = entity.HandlerUserId is int handlerUserId && handlerUserId > 0 + ? OmsRbacUserDisplayNameResolver.FormatUserId(handlerUserId, handlerUserNameMap) + : null, Status = (byte)entity.Status, CreateTime = entity.CreateTime, UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime) @@ -325,6 +385,10 @@ public class IssueTemplateService : ApplicationService public string NotifyMethod { get; set; } = string.Empty; + public string HandlerType { get; set; } = IssueHandlerTypeCodes.User; + + public int? HandlerUserId { get; set; } + public EnableStatus Status { get; set; } } } diff --git a/src/Oms.Application/Services/Channels/SalesProductService.BillingSimulate.cs b/src/Oms.Application/Services/Channels/SalesProductService.BillingSimulate.cs new file mode 100644 index 0000000..e8ff699 --- /dev/null +++ b/src/Oms.Application/Services/Channels/SalesProductService.BillingSimulate.cs @@ -0,0 +1,448 @@ +using Fake.Application; +using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Channels; +using Oms.Application.Dtos.Orders; +using Oms.Application.Services.Orders; +using Oms.Application.Services.Orders.Issues; +using Oms.Application.Shared; +using Oms.Domain.ChannelsAggregate.Entities; +using Oms.Domain.OrdersAggregate.Consts; +using Oms.Domain.OrdersAggregate.Entities; +using Oms.Domain.SystemAggregate.Repositories; + +namespace Oms.Application.Services.Channels; + +public partial class SalesProductService +{ + private IWarehouseAddressRepository WarehouseAddressRepository => + LazyServiceProvider.GetRequiredService(); + + /// + /// 基于当前库内卖价(非必须已发布)模拟计费,用于运营核对附加服务/偏远/申报比例等。 + /// + [HttpPost("/channel/sales-product/billing/simulate")] + public async Task SimulateBillingAsync( + [FromBody] SalesProductBillingSimulateInput input) + { + if (input.Length <= 0 || input.Width <= 0 || input.Height <= 0 || input.ActualWeight <= 0) + { + throw new BusinessException("长宽高与实重必须大于0"); + } + + var product = await GetProductOrThrowAsync(input.SalesProductId); + var countryCode = input.CountryCode?.Trim().ToUpperInvariant() + ?? throw new BusinessException("目的国家不能为空"); + if (string.IsNullOrWhiteSpace(countryCode)) + { + throw new BusinessException("目的国家不能为空"); + } + + var warnings = new List(); + var priceSnapshot = await BuildPricePublishSnapshotAsync(product.Id); + var rulesSnapshot = await BuildRulesPublishSnapshotAsync(product.Id); + + var weight = new OrderWeight + { + Type = OrderWeightTypeCodes.Forecast, + Length = input.Length, + Width = input.Width, + Height = input.Height, + ActualWeight = input.ActualWeight, + Cubic = ParcelBillingCalculator.CalculateCubic(input.Length, input.Width, input.Height) + }; + + decimal chargeableWeight; + try + { + chargeableWeight = await ResolveSimulateChargeableWeightAsync(product, rulesSnapshot, weight); + } + catch (BusinessException) + { + throw; + } + catch (InvalidOperationException ex) + { + throw new BusinessException($"计费重计算失败:{ex.Message}"); + } + + var zoneKeys = ParcelBillingCalculator.TryResolveZoneKeysFromPriceSnapshot( + priceSnapshot, + countryCode, + input.Province, + input.City, + input.ZipCode); + if (zoneKeys == null || zoneKeys.Count == 0) + { + throw new BusinessException("价格分区未匹配"); + } + + var isRemote = input.IsRemote + ?? await IsSimulateRemoteHitAsync(product, rulesSnapshot, countryCode, input.Province, input.City, input.ZipCode); + + var additionalServices = (input.AdditionalServices ?? []) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Select(x => x.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + var allowed = OmsDocHelper.DeserializeJson>(product.AdditionalServices) ?? []; + var allowedSet = allowed + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Select(x => x.Trim()) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + var invalidServices = additionalServices.Where(x => !allowedSet.Contains(x)).ToList(); + if (invalidServices.Count > 0) + { + warnings.Add($"附加服务不在产品可选范围:{string.Join(", ", invalidServices)}"); + additionalServices = additionalServices.Where(allowedSet.Contains).ToList(); + } + + var cargoAttribute = string.IsNullOrWhiteSpace(input.CargoAttribute) + ? CargoAttributeCodes.General + : input.CargoAttribute.Trim(); + var warehouseName = await ResolveSimulateWarehouseNameAsync(input.WarehouseId); + var priceTierKey = string.IsNullOrWhiteSpace(input.PriceTierKey) ? null : input.PriceTierKey.Trim(); + var priceVersion = DateTime.Now.ToString("yyyyMMddHHmmss"); + var priceEffectiveTime = DateTime.Now; + + var conditionContext = OrderRuleEvaluationContext.FromOrderOnly(new Order + { + ProductCode = product.ProductCode, + ConsigneeCountry = countryCode, + CargoAttribute = cargoAttribute, + WarehouseId = input.WarehouseId, + DeclaredSum = input.DeclaredSum, + DeclaredCurrency = input.DeclaredCurrency, + IsRemote = isRemote ? (byte)1 : (byte)0, + AdditionalServices = additionalServices.Count == 0 + ? null + : OmsDocHelper.SerializeJson(additionalServices) + }); + + var remoteAreaId = product.RemoteAreaId is > 0 ? product.RemoteAreaId : rulesSnapshot.RemoteAreaId; + var remoteZoneKeys = isRemote + ? ParcelBillingCalculator.BuildRemoteZoneKeys(remoteAreaId, rulesSnapshot.RemoteAreaName) + : Array.Empty(); + + var receivableLines = ParcelBillingCalculator.CalculateQuoteReceivableFeeLines( + priceSnapshot, + priceVersion, + priceEffectiveTime, + chargeableWeight, + zoneKeys, + cargoAttribute, + priceTierKey, + input.WarehouseId, + warehouseName, + conditionContext, + input.DeclaredSum, + input.DeclaredCurrency, + remoteZoneKeys); + + if (receivableLines.Count == 0 && ParcelBillingCalculator.HasEnabledReceivablePriceItems(priceSnapshot)) + { + var detail = ParcelBillingCalculator.ExplainQuotePriceMiss( + priceSnapshot, + chargeableWeight, + zoneKeys, + cargoAttribute, + priceTierKey, + input.WarehouseId, + warehouseName); + warnings.Add($"卖价未匹配到有效价格:{detail}"); + } + + var receivableFees = receivableLines.Select(x => new SalesProductBillingSimulateFeeOutput + { + CostItem = x.Fee.CostItem, + Amount = x.Fee.Amount, + Currency = x.Fee.Currency ?? string.Empty, + Formula = x.FormulaPart + }).ToList(); + + var payableFees = new List(); + try + { + payableFees = await TrySimulatePayableFeesAsync( + product, + rulesSnapshot, + zoneKeys, + chargeableWeight, + cargoAttribute, + input.WarehouseId, + warehouseName, + isRemote, + remoteZoneKeys, + input.DeclaredSum, + input.DeclaredCurrency, + priceVersion, + priceEffectiveTime, + warnings); + } + catch (Exception ex) + { + warnings.Add($"应付估算失败:{ex.Message}"); + } + + var receivableTotal = SumByCurrency(receivableFees); + var payableTotal = SumByCurrency(payableFees); + decimal? margin = null; + if (receivableTotal.Count == 1 + && payableTotal.Count == 1 + && string.Equals(receivableTotal.Keys.First(), payableTotal.Keys.First(), StringComparison.OrdinalIgnoreCase)) + { + margin = receivableTotal.Values.First() - payableTotal.Values.First(); + } + else if (receivableTotal.Count > 1 || payableTotal.Count > 1) + { + warnings.Add("多币种费用无法直接计算毛利"); + } + else if (receivableTotal.Count == 1 && payableTotal.Count == 0) + { + warnings.Add("仅返回应收估算,无应付费用"); + } + + return new SalesProductBillingSimulateOutput + { + ChargeableWeight = chargeableWeight, + ZoneKeys = zoneKeys.ToList(), + IsRemote = isRemote, + ReceivableFees = receivableFees, + PayableFees = payableFees, + ReceivableTotal = receivableTotal, + PayableTotal = payableTotal, + Margin = margin, + Warnings = warnings + }; + } + + private async Task ResolveSimulateChargeableWeightAsync( + SalesProduct product, + SalesProductRulesPublishSnapshotDto rulesSnapshot, + OrderWeight weight) + { + var weightRuleId = product.WeightRuleId is > 0 + ? product.WeightRuleId + : rulesSnapshot.WeightRuleId; + if (weightRuleId is not > 0) + { + throw new BusinessException("未配置计重规则"); + } + + IReadOnlyList ruleInfos; + if (rulesSnapshot.WeightRuleInfos is { Count: > 0 }) + { + ruleInfos = RulesSnapshotHelper.ToWeightRuleEntities(rulesSnapshot.WeightRuleInfos); + } + else + { + ruleInfos = await WeightRuleRepository.GetAllInfosByRuleIdAsync(weightRuleId.Value); + } + + var (_, rawWeight) = ParcelBillingCalculator.CalculateRawBillableWeight(weight, ruleInfos); + + var weightRoundingId = product.WeightRoundingId is > 0 + ? product.WeightRoundingId + : rulesSnapshot.WeightRoundingId; + if (weightRoundingId is not > 0) + { + throw new BusinessException("未配置计重进位"); + } + + IReadOnlyList ranges; + if (rulesSnapshot.WeightRoundingInfos is { Count: > 0 }) + { + ranges = RulesSnapshotHelper.ToWeightRoundingEntities(rulesSnapshot.WeightRoundingInfos); + } + else + { + ranges = await WeightRoundingRepository.GetAllInfosByRoundingIdAsync(weightRoundingId.Value); + } + + return ParcelBillingCalculator.ApplyRounding(rawWeight, ranges); + } + + private async Task IsSimulateRemoteHitAsync( + SalesProduct product, + SalesProductRulesPublishSnapshotDto rulesSnapshot, + string countryCode, + string? province, + string? city, + string? zipCode) + { + var areaId = product.RemoteAreaId is > 0 ? product.RemoteAreaId : rulesSnapshot.RemoteAreaId; + if (areaId is not > 0) + { + return false; + } + + if (rulesSnapshot.RemoteAreaInfos is { Count: > 0 }) + { + return RulesSnapshotHelper.IsAreaHitFromSnapshot( + rulesSnapshot.RemoteAreaInfos, + countryCode, + province, + city, + zipCode); + } + + var rules = await KpiAreaRepository.GetAllInfosByAreaIdAsync(areaId.Value); + return rules.Any(rule => ParcelBillingCalculator.IsAreaMatched( + rule, + countryCode, + province, + city, + zipCode)); + } + + private async Task ResolveSimulateWarehouseNameAsync(int? warehouseId) + { + if (warehouseId is not > 0) + { + return null; + } + + var warehouse = await WarehouseAddressRepository.FirstOrDefaultAsync(x => x.Id == warehouseId.Value); + return warehouse?.WarehouseName; + } + + private async Task> TrySimulatePayableFeesAsync( + SalesProduct product, + SalesProductRulesPublishSnapshotDto rulesSnapshot, + IReadOnlyList zoneKeys, + decimal chargeableWeight, + string cargoAttribute, + int? warehouseId, + string? warehouseName, + bool isRemote, + IReadOnlyList remoteZoneKeys, + decimal? declaredSum, + string? declaredCurrency, + string priceVersion, + DateTime priceEffectiveTime, + List warnings) + { + var providers = rulesSnapshot.Providers.Count > 0 + ? rulesSnapshot.Providers + : (await GetAllocationCoreAsync(product.Id)).Providers + .Select(PublishSnapshotSlimmer.SlimAllocationProvider) + .ToList(); + var filtered = AllocationResolver.FilterProviders(providers, customerId: null); + var provider = filtered.OrderBy(x => x.SerialNumber).FirstOrDefault(x => x.ServiceChannelId is > 0); + if (provider?.ServiceChannelId is not > 0) + { + warnings.Add("未配置可用排货服务渠道,跳过应付估算"); + return []; + } + + var channelPrices = await BuildChannelPriceOutputsAsync(provider.ServiceChannelId.Value); + if (channelPrices.Count == 0) + { + warnings.Add($"服务渠道 {provider.ServiceChannelId} 无买价,跳过应付估算"); + return []; + } + + var channel = await ServiceChannelRepository.FirstOrDefaultAsync(x => x.Id == provider.ServiceChannelId.Value); + var payableRemoteZoneKeys = isRemote + ? ParcelBillingCalculator.BuildRemoteZoneKeys( + channel?.RemoteAreaId is > 0 ? channel.RemoteAreaId : null) + : Array.Empty(); + // 渠道未配偏远分区时回落产品偏远键,便于模拟偏远费行 + if (isRemote && payableRemoteZoneKeys.Count == 0) + { + payableRemoteZoneKeys = remoteZoneKeys; + } + + var payableContext = OrderRuleEvaluationContext.FromOrderOnly(new Order + { + ProductCode = product.ProductCode, + ConsigneeCountry = null, + CargoAttribute = cargoAttribute, + WarehouseId = warehouseId, + DeclaredSum = declaredSum, + DeclaredCurrency = declaredCurrency, + IsRemote = isRemote ? (byte)1 : (byte)0 + }); + + var payable = ParcelBillingCalculator.CalculatePayableFees( + channelPrices, + priceVersion, + priceEffectiveTime, + chargeableWeight, + zoneKeys, + cargoAttribute, + OrderFeeChargingStageCodes.Forecast, + warehouseId, + warehouseName, + payableContext, + declaredSum, + declaredCurrency, + payableRemoteZoneKeys); + + if (payable.Count == 0) + { + warnings.Add($"服务渠道 {provider.ServiceChannelId} 买价未匹配,跳过应付估算"); + return []; + } + + warnings.Add($"应付按排货服务渠道 {provider.ServiceChannelId} 估算(首个可用渠道)"); + return payable.Select(x => new SalesProductBillingSimulateFeeOutput + { + CostItem = x.CostItem, + Amount = x.Amount, + Currency = x.Currency ?? string.Empty + }).ToList(); + } + + private async Task> BuildChannelPriceOutputsAsync(int serviceChannelId) + { + var prices = await ServiceChannelRepository.GetPricesAsync(serviceChannelId); + var priceIds = prices.Select(x => x.Id).ToArray(); + var factorMap = (await ServiceChannelRepository.GetPriceFactorsAsync(priceIds)) + .GroupBy(x => x.PriceId) + .ToDictionary(x => x.Key, x => x.OrderBy(item => item.SerialNumber).ToList()); + var detailMap = (await ServiceChannelRepository.GetPriceDetailsAsync(priceIds)) + .GroupBy(x => x.PriceId) + .ToDictionary(x => x.Key, x => x.OrderBy(item => item.Id).ToList()); + + return prices.Select(price => new ServiceChannelPriceListOutput + { + Id = price.Id, + ServiceChannelId = price.ServiceChannelId, + SerialNumber = price.SerialNumber, + Status = (byte)price.Status, + PriceName = price.PriceName, + CostItem = price.CostItem, + CostUnit = price.CostUnit, + Currency = price.Currency, + ChargingCondition = price.ChargingCondition, + Factors = factorMap.TryGetValue(price.Id, out var factors) + ? factors.Select(f => new ChannelPriceFactorOutput + { + Id = f.Id, + PriceId = f.PriceId, + SerialNumber = f.SerialNumber, + Factor = f.Factor, + FactorValues = OmsDocHelper.DeserializeJson>(f.FactorValues) ?? [] + }).ToList() + : [], + Details = detailMap.TryGetValue(price.Id, out var details) + ? details.Select(d => new ChannelPriceDetailOutput + { + Id = d.Id, + PriceId = d.PriceId, + FactorValuesJson = OmsDocHelper.DeserializeJsonObject(d.FactorValuesJson), + CalculationFormula = d.CalculationFormula, + CalculatedValue = d.CalculatedValue, + CustomerGroupValues = OmsDocHelper.DeserializeJsonObject(d.CustomerGroupValues) + }).ToList() + : [] + }).ToList(); + } + + private static Dictionary SumByCurrency(IEnumerable fees) + { + return fees + .GroupBy(x => string.IsNullOrWhiteSpace(x.Currency) ? "UNK" : x.Currency.Trim(), StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.Sum(x => x.Amount), StringComparer.OrdinalIgnoreCase); + } +} diff --git a/src/Oms.Application/Services/Channels/SalesProductService.Helpers.cs b/src/Oms.Application/Services/Channels/SalesProductService.Helpers.cs index 859d4ee..ecf7284 100644 --- a/src/Oms.Application/Services/Channels/SalesProductService.Helpers.cs +++ b/src/Oms.Application/Services/Channels/SalesProductService.Helpers.cs @@ -153,6 +153,7 @@ public partial class SalesProductService PublishUser = entity.PublishUser, PublishTime = entity.PublishTime, Description = entity.Description, + AiAnalysisReport = entity.AiAnalysisReport, Content = operatorType == PriceOperatorType ? OmsDocHelper.ParseSalesProductPricePublishContentForApi(entity.Content) : OmsDocHelper.ToSnapshotApiContent(OmsDocHelper.DeserializeRulesSnapshot(entity.Content)), @@ -210,6 +211,8 @@ public partial class SalesProductService MinTimeliness = product.MinTimeliness, MaxTimeliness = product.MaxTimeliness, TradeTerms = product.TradeTerms, + RouteSort = product.RouteSort, + AdditionalServices = product.AdditionalServices, CustomerWaybill = product.CustomerWaybill, LabelTemplateId = product.LabelTemplateId, BlacklistAreaId = product.BlacklistAreaId, @@ -219,7 +222,8 @@ public partial class SalesProductService WeightRoundingId = product.WeightRoundingId, ProductDescription = product.ProductDescription, PreStorageScript = product.PreStorageScript, - CustomerGuideMarkdown = product.CustomerGuideMarkdown, + // 对客说明不常变动,且有独立保存入口;规则发布快照跳过,避免配置发布被其 diff 干扰 + CustomerGuideMarkdown = null, IsActive = product.IsActive, Scheme = product.Scheme }; @@ -227,11 +231,25 @@ public partial class SalesProductService /// /// 为当前配置生成发布快照。 /// - private async Task CreatePublishRecordAsync(int salesProductId, string operatorType, string? description) + private async Task CreatePublishRecordAsync( + int salesProductId, + string operatorType, + string? description, + string? aiAnalysisReport = null) { - object snapshot = operatorType == PriceOperatorType - ? await BuildPricePublishSnapshotAsync(salesProductId) - : await BuildRulesPublishSnapshotAsync(salesProductId); + object snapshot; + if (operatorType == PriceOperatorType) + { + var priceSnapshot = await BuildPricePublishSnapshotAsync(salesProductId); + ValidateBillingPriceItemRules( + priceSnapshot.Prices.Select(p => MapPriceSaveInput(p, salesProductId)).ToList()); + await PriceAreaSnapshotHelper.EnsureSingleResolvedPriceAreaAsync(priceSnapshot, KpiAreaRepository); + snapshot = priceSnapshot; + } + else + { + snapshot = await BuildRulesPublishSnapshotAsync(salesProductId); + } // Content 中保存完整快照,回滚时直接从快照恢复,避免依赖当前库内状态。 await SalesProductRepository.InsertPublishRecordAsync(new SalesProductPublishRecord @@ -243,6 +261,7 @@ public partial class SalesProductService PublishUser = string.IsNullOrWhiteSpace(CurrentUser.UserName) ? CurrentUser.GetId().ToString() : CurrentUser.UserName!, PublishTime = DateTime.Now, Description = description, + AiAnalysisReport = string.IsNullOrWhiteSpace(aiAnalysisReport) ? null : aiAnalysisReport.Trim(), Content = OmsDocHelper.SerializeSnapshotJson(snapshot) }); } @@ -316,16 +335,19 @@ public partial class SalesProductService entity.MinTimeliness = input.MinTimeliness; entity.MaxTimeliness = input.MaxTimeliness; entity.TradeTerms = NormalizeTradeTerms(input.TradeTerms); + entity.RouteSort = input.RouteSort < 0 ? 0 : input.RouteSort; + entity.AdditionalServices = NormalizeAdditionalServices(input.AdditionalServices); entity.CustomerWaybill = input.CustomerWaybill; entity.LabelTemplateId = input.LabelTemplateId; entity.BlacklistAreaId = input.BlacklistAreaId; entity.RemoteAreaId = input.RemoteAreaId; - entity.PriceAreaId = input.PriceAreaId; + // 价格分区改由卖价明细分区推断并固化进发布快照,产品表不再持久化 PriceAreaId。 + entity.PriceAreaId = null; entity.WeightRuleId = input.WeightRuleId; entity.WeightRoundingId = input.WeightRoundingId; entity.ProductDescription = input.ProductDescription; entity.PreStorageScript = input.PreStorageScript; - entity.CustomerGuideMarkdown = input.CustomerGuideMarkdown; + // 对客说明仅通过 /customer-guide/save 维护,产品配置保存/发布不覆盖 entity.IsActive = input.IsActive; entity.Scheme = string.IsNullOrWhiteSpace(input.Scheme) ? AllocationSchemeCodes.CostLowest : input.Scheme; } @@ -336,6 +358,85 @@ public partial class SalesProductService return value is "DDP" or "DDU" ? value : null; } + private static SalesProductPricePublishSnapshotDto BuildPriceSnapshotFromSaveInputs( + int salesProductId, + IReadOnlyList prices) => + new() + { + SalesProductId = salesProductId, + Prices = prices.Select(price => new SalesProductPriceSnapshotItemDto + { + Id = price.Id ?? 0, + SerialNumber = price.SerialNumber, + Status = (byte)price.Status, + PriceName = price.PriceName, + CostItem = price.CostItem, + CostUnit = price.CostUnit, + Currency = price.Currency, + ChargingCondition = price.ChargingCondition, + Details = price.Details.Select(detail => new ChannelPriceDetailOutput + { + Id = detail.Id ?? 0, + FactorValuesJson = detail.FactorValuesJson, + CalculationFormula = detail.CalculationFormula, + CalculatedValue = detail.CalculatedValue, + CustomerGroupValues = detail.CustomerGroupValues + }).ToList() + }).ToList() + }; + + /// + /// 保险/偏远费等附加费用项的计费条件校验。 + /// + private static void ValidateBillingPriceItemRules(IReadOnlyList prices) + { + foreach (var price in prices) + { + var costItem = price.CostItem?.Trim() ?? string.Empty; + var condition = price.ChargingCondition?.Trim() ?? string.Empty; + if (costItem.Equals("insurance", StringComparison.OrdinalIgnoreCase)) + { + if (string.IsNullOrWhiteSpace(condition) + || string.Equals(condition, "无", StringComparison.OrdinalIgnoreCase)) + { + throw new Fake.Application.BusinessException("保险费用项必须配置非空计费条件(不能为「无」)"); + } + } + + if (costItem.Equals("remoteFee", StringComparison.OrdinalIgnoreCase) + || costItem.Equals("remote_fee", StringComparison.OrdinalIgnoreCase) + || costItem.Contains("偏远", StringComparison.OrdinalIgnoreCase)) + { + if (!condition.Contains("是否偏远", StringComparison.Ordinal)) + { + throw new Fake.Application.BusinessException("偏远费用项的计费条件必须包含「是否偏远」"); + } + } + } + } + + private static string? NormalizeAdditionalServices(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) + { + return null; + } + + var trimmed = raw.Trim(); + var codes = OmsDocHelper.DeserializeJson>(trimmed); + if (codes == null) + { + return trimmed; + } + + var normalized = codes + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Select(x => x.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + return normalized.Count == 0 ? null : OmsDocHelper.SerializeJson(normalized); + } + private static SalesProductListOutput MapListOutput(SalesProduct entity) { return new SalesProductListOutput @@ -346,6 +447,8 @@ public partial class SalesProductService ProductGroup = entity.ProductGroup, MinTimeliness = entity.MinTimeliness, MaxTimeliness = entity.MaxTimeliness, + RouteSort = entity.RouteSort, + AdditionalServices = entity.AdditionalServices, CustomerWaybill = entity.CustomerWaybill, LabelTemplateId = entity.LabelTemplateId, BlacklistAreaId = entity.BlacklistAreaId, @@ -374,6 +477,8 @@ public partial class SalesProductService MinTimeliness = entity.MinTimeliness, MaxTimeliness = entity.MaxTimeliness, TradeTerms = entity.TradeTerms, + RouteSort = entity.RouteSort, + AdditionalServices = entity.AdditionalServices, CustomerWaybill = entity.CustomerWaybill, LabelTemplateId = entity.LabelTemplateId, BlacklistAreaId = entity.BlacklistAreaId, diff --git a/src/Oms.Application/Services/Channels/SalesProductService.Portal.cs b/src/Oms.Application/Services/Channels/SalesProductService.Portal.cs new file mode 100644 index 0000000..12c0ed9 --- /dev/null +++ b/src/Oms.Application/Services/Channels/SalesProductService.Portal.cs @@ -0,0 +1,130 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Channels; +using Oms.Domain.Shared.Enums; +using Oms.Domain.SystemAggregate.Repositories; + +namespace Oms.Application.Services.Channels; + +public partial class SalesProductService +{ + private const string SalesProductGroupDictType = "sales_product_group"; + private const string UngroupedProductGroupCode = "_ungrouped"; + private const string DomesticPickupGroupNameKeyword = "国内揽收"; + + private IDictRepository DictRepository => + LazyServiceProvider.GetRequiredService(); + + /// + /// 官网线路目录(匿名):仅启用产品,排除「国内揽收」分组。 + /// + [AllowAnonymous] + [HttpGet("/channel/sales-product/portal/catalog")] + public async Task GetPortalCatalogAsync() + { + var products = await SalesProductRepository.GetListAsync(x => x.IsActive == EnableStatus.Enabled); + var dictRows = await DictRepository.GetListAsync(x => x.DictType == SalesProductGroupDictType); + + var domesticPickupGroupCodes = dictRows + .Where(x => !string.IsNullOrWhiteSpace(x.DictName) + && x.DictName.Trim().Contains(DomesticPickupGroupNameKeyword)) + .Select(x => (x.DictCode ?? string.Empty).Trim()) + .Where(code => !string.IsNullOrWhiteSpace(code)) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + var groupNameMap = dictRows + .Where(x => !string.IsNullOrWhiteSpace(x.DictCode)) + .GroupBy(x => x.DictCode!.Trim(), StringComparer.OrdinalIgnoreCase) + .ToDictionary( + g => g.Key, + g => + { + var name = g.First().DictName?.Trim(); + return string.IsNullOrWhiteSpace(name) ? g.Key : name; + }, + StringComparer.OrdinalIgnoreCase); + groupNameMap[UngroupedProductGroupCode] = "未分组"; + + var filtered = products + .Where(p => + { + var groupCode = string.IsNullOrWhiteSpace(p.ProductGroup) + ? UngroupedProductGroupCode + : p.ProductGroup.Trim(); + return !domesticPickupGroupCodes.Contains(groupCode); + }) + .OrderBy(p => p.RouteSort) + .ThenBy(p => p.MinTimeliness ?? int.MaxValue) + .ThenBy(p => p.ProductName, StringComparer.OrdinalIgnoreCase) + .ThenBy(p => p.Id) + .ToList(); + + var usedGroupCodes = new HashSet(StringComparer.OrdinalIgnoreCase); + var items = filtered.Select(p => + { + var groupCode = string.IsNullOrWhiteSpace(p.ProductGroup) + ? UngroupedProductGroupCode + : p.ProductGroup.Trim(); + usedGroupCodes.Add(groupCode); + groupNameMap.TryGetValue(groupCode, out var groupName); + return new SalesProductPortalItemOutput + { + Id = p.Id, + ProductName = p.ProductName, + ProductGroup = groupCode == UngroupedProductGroupCode ? null : groupCode, + ProductGroupName = string.IsNullOrWhiteSpace(groupName) ? groupCode : groupName, + MinTimeliness = p.MinTimeliness, + MaxTimeliness = p.MaxTimeliness, + TradeTerms = string.IsNullOrWhiteSpace(p.TradeTerms) ? null : p.TradeTerms.Trim().ToUpperInvariant(), + RouteSort = p.RouteSort, + ProductDescription = p.ProductDescription + }; + }).ToList(); + + var groups = new List(); + var consumed = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var dict in dictRows.OrderBy(x => x.DictSort).ThenBy(x => x.DictCode)) + { + var code = dict.DictCode?.Trim(); + if (string.IsNullOrWhiteSpace(code) + || domesticPickupGroupCodes.Contains(code) + || !usedGroupCodes.Contains(code) + || !consumed.Add(code)) + { + continue; + } + + groups.Add(new SalesProductPortalGroupOutput + { + Code = code, + Name = string.IsNullOrWhiteSpace(dict.DictName) ? code : dict.DictName.Trim() + }); + } + + if (usedGroupCodes.Contains(UngroupedProductGroupCode) && consumed.Add(UngroupedProductGroupCode)) + { + groups.Add(new SalesProductPortalGroupOutput + { + Code = UngroupedProductGroupCode, + Name = groupNameMap[UngroupedProductGroupCode] + }); + } + + foreach (var code in usedGroupCodes.OrderBy(x => x, StringComparer.OrdinalIgnoreCase)) + { + if (!consumed.Add(code)) continue; + groupNameMap.TryGetValue(code, out var name); + groups.Add(new SalesProductPortalGroupOutput + { + Code = code, + Name = string.IsNullOrWhiteSpace(name) ? code : name + }); + } + + return new SalesProductPortalCatalogOutput + { + Groups = groups, + Items = items + }; + } +} diff --git a/src/Oms.Application/Services/Channels/SalesProductService.cs b/src/Oms.Application/Services/Channels/SalesProductService.cs index 5d4c535..ff28367 100644 --- a/src/Oms.Application/Services/Channels/SalesProductService.cs +++ b/src/Oms.Application/Services/Channels/SalesProductService.cs @@ -158,6 +158,7 @@ public partial class SalesProductService : ApplicationService public async Task CreatePriceAsync(SalesProductPriceSaveInput input) { await GetProductOrThrowAsync(input.SalesProductId); + ValidateBillingPriceItemRules([input]); await SalesProductRepository.InsertPriceAsync( new SalesProductPrice { @@ -188,6 +189,7 @@ public partial class SalesProductService : ApplicationService throw new BusinessException("价格项归属不匹配"); } + ValidateBillingPriceItemRules([input]); price.SerialNumber = input.SerialNumber; price.Status = input.Status; price.PriceName = input.PriceName; @@ -234,6 +236,10 @@ public partial class SalesProductService : ApplicationService public async Task SavePriceAsync(SalesProductPriceSaveAllInput input) { await GetProductOrThrowAsync(input.SalesProductId); + ValidateBillingPriceItemRules(input.Prices); + await PriceAreaSnapshotHelper.EnsureSingleResolvedPriceAreaAsync( + BuildPriceSnapshotFromSaveInputs(input.SalesProductId, input.Prices), + KpiAreaRepository); var prices = new List(); var factors = new List(); var details = new List(); @@ -262,7 +268,16 @@ public partial class SalesProductService : ApplicationService await SalesProductRepository.ReplacePricesAsync(input.SalesProductId, prices, factors, details); if (input.Publish) { - await CreatePublishRecordAsync(input.SalesProductId, PriceOperatorType, "保存并发布价格"); + if (string.IsNullOrWhiteSpace(input.AiAnalysisReport)) + { + throw new Fake.Application.BusinessException("价格发布前须完成 AI 风险分析并保存报告"); + } + + await CreatePublishRecordAsync( + input.SalesProductId, + PriceOperatorType, + "保存并发布价格", + input.AiAnalysisReport); } } @@ -349,7 +364,17 @@ public partial class SalesProductService : ApplicationService [HttpPost("/channel/sales-product/publish")] public async Task PublishAsync(SalesProductPublishInput input) { - await CreatePublishRecordAsync(input.SalesProductId, NormalizeOperatorType(input.OperatorType), input.Description); + var operatorType = NormalizeOperatorType(input.OperatorType); + if (operatorType == PriceOperatorType && string.IsNullOrWhiteSpace(input.AiAnalysisReport)) + { + throw new Fake.Application.BusinessException("价格发布前须完成 AI 风险分析并保存报告"); + } + + await CreatePublishRecordAsync( + input.SalesProductId, + operatorType, + input.Description, + input.AiAnalysisReport); } /// diff --git a/src/Oms.Application/Services/Channels/ServiceChannelService.Helpers.cs b/src/Oms.Application/Services/Channels/ServiceChannelService.Helpers.cs index 69eabf1..af3ea5f 100644 --- a/src/Oms.Application/Services/Channels/ServiceChannelService.Helpers.cs +++ b/src/Oms.Application/Services/Channels/ServiceChannelService.Helpers.cs @@ -226,6 +226,7 @@ public partial class ServiceChannelService ForecastType = entity.ForecastType, ForecastCode = entity.ForecastCode, Description = entity.Description, + RemoteAreaId = entity.RemoteAreaId, PreScript = entity.PreScript, IsActive = entity.IsActive }; @@ -307,10 +308,32 @@ public partial class ServiceChannelService entity.ForecastType = input.ForecastType; entity.ForecastCode = input.ForecastCode; entity.Description = input.Description; + entity.RemoteAreaId = input.RemoteAreaId; entity.PreScript = input.PreScript; entity.IsActive = input.IsActive; } + /// + /// 买价偏远费等附加费用项的计费条件校验。 + /// + private static void ValidateBillingPriceItemRules(IReadOnlyList prices) + { + foreach (var price in prices) + { + var costItem = price.CostItem?.Trim() ?? string.Empty; + var condition = price.ChargingCondition?.Trim() ?? string.Empty; + if (costItem.Equals("remoteFee", StringComparison.OrdinalIgnoreCase) + || costItem.Equals("remote_fee", StringComparison.OrdinalIgnoreCase) + || costItem.Contains("偏远", StringComparison.OrdinalIgnoreCase)) + { + if (!condition.Contains("是否偏远", StringComparison.Ordinal)) + { + throw new Fake.Application.BusinessException("偏远费用项的计费条件必须包含「是否偏远」"); + } + } + } + } + private static ServiceChannelGroupListOutput MapGroupListOutput(ServiceChannelGroup entity) { return new ServiceChannelGroupListOutput @@ -338,6 +361,7 @@ public partial class ServiceChannelService ForecastType = entity.ForecastType, ForecastCode = entity.ForecastCode, Description = entity.Description, + RemoteAreaId = entity.RemoteAreaId, IsActive = (byte)entity.IsActive, CreateTime = entity.CreateTime, UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime) @@ -361,6 +385,7 @@ public partial class ServiceChannelService ForecastType = entity.ForecastType, ForecastCode = entity.ForecastCode, Description = entity.Description, + RemoteAreaId = entity.RemoteAreaId, PreScript = entity.PreScript, IsActive = (byte)entity.IsActive, CreateTime = entity.CreateTime, diff --git a/src/Oms.Application/Services/Channels/ServiceChannelService.cs b/src/Oms.Application/Services/Channels/ServiceChannelService.cs index 389c859..dea8476 100644 --- a/src/Oms.Application/Services/Channels/ServiceChannelService.cs +++ b/src/Oms.Application/Services/Channels/ServiceChannelService.cs @@ -208,6 +208,7 @@ public partial class ServiceChannelService : ApplicationService public async Task CreatePriceAsync(ServiceChannelPriceSaveInput input) { await GetEntityOrThrowAsync(input.ServiceChannelId); + ValidateBillingPriceItemRules([input]); await ServiceChannelRepository.InsertPriceAsync( new ServiceChannelPrice { @@ -238,6 +239,7 @@ public partial class ServiceChannelService : ApplicationService throw new BusinessException("买价项归属不匹配"); } + ValidateBillingPriceItemRules([input]); price.SerialNumber = input.SerialNumber; price.Status = input.Status; price.PriceName = input.PriceName; @@ -284,6 +286,7 @@ public partial class ServiceChannelService : ApplicationService public async Task SavePriceAsync(ServiceChannelPriceSaveAllInput input) { await GetEntityOrThrowAsync(input.ServiceChannelId); + ValidateBillingPriceItemRules(input.Prices); var prices = new List(); var factors = new List(); var details = new List(); diff --git a/src/Oms.Application/Services/Customers/CustomerAccountFlowService.cs b/src/Oms.Application/Services/Customers/CustomerAccountFlowService.cs index 319b263..c1124f4 100644 --- a/src/Oms.Application/Services/Customers/CustomerAccountFlowService.cs +++ b/src/Oms.Application/Services/Customers/CustomerAccountFlowService.cs @@ -140,6 +140,7 @@ public class CustomerAccountFlowService : ApplicationService { CustomerAccountFlowBizTypes.Recharge => "充值入账", CustomerAccountFlowBizTypes.OrderPay => "订单支付", + CustomerAccountFlowBizTypes.PickupPay => "揽收支付", _ => bizType }; } diff --git a/src/Oms.Application/Services/Customers/CustomerService.cs b/src/Oms.Application/Services/Customers/CustomerService.cs index 07ddc94..21550cd 100644 --- a/src/Oms.Application/Services/Customers/CustomerService.cs +++ b/src/Oms.Application/Services/Customers/CustomerService.cs @@ -233,6 +233,10 @@ public class CustomerService : ApplicationService input.InviteCode, ReferralCodeRepository, CustomerRepository); + await StaffAdvisorBinder.BindAdvisorOnCreateAsync( + entity, + input.AdvisorCode, + RbacDbContext); await CustomerRepository.InsertAsync(entity); try { diff --git a/src/Oms.Application/Services/Finance/FinanceService.cs b/src/Oms.Application/Services/Finance/FinanceService.cs index 5cce6f0..6a3021d 100644 --- a/src/Oms.Application/Services/Finance/FinanceService.cs +++ b/src/Oms.Application/Services/Finance/FinanceService.cs @@ -1,46 +1,49 @@ using Fake.Application; using Fake.Users; using Microsoft.AspNetCore.Mvc; +using MiniExcelLibs; using Oms.Application.DataPerm; using Oms.Application.Dtos.Finance; using Oms.Application.Dtos.Shared; +using Oms.Application.Services.Orders; using Oms.Application.Shared; using Oms.Domain.CustomersAggregate.Repositories; using Oms.Domain.OrdersAggregate; using Oms.Domain.OrdersAggregate.Consts; using Oms.Domain.OrdersAggregate.Repositories; +using Oms.Domain.SystemAggregate.Repositories; namespace Oms.Application.Services.Finance; /// -/// 财务相关 API�。 - /// +/// 财务相关 API。 +/// [ApiExplorerSettings(GroupName = "OMS-Finance")] public class FinanceService : ApplicationService { + private const string FeeItemDictType = "fee_item"; + private const int ExportMaxRows = 50000; + private IOrderRepository OrderRepository => LazyServiceProvider.GetRequiredService(); private ICustomerRepository CustomerRepository => LazyServiceProvider.GetRequiredService(); + private IDictRepository DictRepository => + LazyServiceProvider.GetRequiredService(); + private EffectiveScopeBuilder DataScopeBuilder => LazyServiceProvider.GetRequiredService(); /// - /// 分页查询应收应付(订单费用联查订单)�。 + /// 分页查询应收应付(订单费用联查订单)。 /// [HttpGet("/finance/receivable-payable/list")] public async Task> GetReceivablePayableListAsync( [FromQuery] ReceivablePayablePaginatedInput input) { - var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( - CustomerRepository, - CurrentUser, - input.CustomerId); - var filter = BuildFilter(input, customerId); - await ApplyInternalOrderDataScopeAsync(filter); - + var filter = await BuildScopedFilterAsync(input); var pageIndex = OmsDocHelper.NormalizePage(input.Page); var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); var (rows, total) = await OrderRepository.GetReceivablePayablePagedListAsync( @@ -48,6 +51,102 @@ public class FinanceService : ApplicationService pageSize, filter); + var items = await MapReceivablePayableRowsAsync(rows); + return new OmsPageResult + { + Items = items, + Total = total + }; + } + + /// + /// 应收应付汇总(当前筛选条件下全量费用明细)。 + /// + [HttpGet("/finance/receivable-payable/summary")] + public async Task GetReceivablePayableSummaryAsync( + [FromQuery] ReceivablePayablePaginatedInput input) + { + var filter = await BuildScopedFilterAsync(input); + var rows = await OrderRepository.GetReceivablePayableSummaryAsync(filter); + var items = rows + .Select(row => new ReceivablePayableSummaryItemOutput + { + FeeType = row.FeeType, + FeeTypeName = GetFeeTypeName(row.FeeType), + Currency = row.Currency, + TotalAmount = row.TotalAmount, + LineCount = row.LineCount + }) + .OrderBy(x => x.FeeType) + .ThenBy(x => x.Currency) + .ToList(); + + return new ReceivablePayableSummaryOutput + { + TotalLines = items.Sum(x => x.LineCount), + Items = items + }; + } + + /// + /// 导出应收应付 Excel。 + /// + [HttpGet("/finance/receivable-payable/export")] + public async Task ExportReceivablePayableAsync( + [FromQuery] ReceivablePayablePaginatedInput input) + { + var filter = await BuildScopedFilterAsync(input); + var rows = await OrderRepository.GetReceivablePayableExportListAsync(filter, ExportMaxRows); + var items = await MapReceivablePayableRowsAsync(rows); + var exportRows = items.Select(item => new + { + 运单号 = item.ServiceNo, + 客户单号 = item.ClientNo, + 跟踪号 = item.TrackNo, + 客户编码 = item.CustomerCode, + 费用类型 = item.FeeTypeName, + 费用项 = item.CostItemName ?? item.CostItem, + 金额 = item.Amount, + 币种 = item.Currency, + 计费阶段 = item.ChargingStageName, + 订单状态 = item.OrderStatusName, + 支付状态 = item.IsPaid == 1 ? "已支付" : "未支付", + 产品编码 = item.ProductCode, + 渠道编码 = item.ChannelCode, + 目的国 = item.ConsigneeCountryName, + 下游服务商 = item.DownstreamProvider, + 价格编号 = item.PriceNo, + 价格生效时间 = item.PriceEffectiveTime, + 支付时间 = item.PayTime, + 收货时间 = item.ReceiveTime, + 发货时间 = item.ShipTime + }).ToList(); + + await using var stream = new MemoryStream(); + await MiniExcel.SaveAsAsync(stream, exportRows); + stream.Position = 0; + return new FileContentResult(stream.ToArray(), + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") + { + FileDownloadName = $"receivable-payable-{DateTime.Now:yyyyMMddHHmmss}.xlsx" + }; + } + + private async Task BuildScopedFilterAsync( + ReceivablePayablePaginatedInput input) + { + var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( + CustomerRepository, + CurrentUser, + input.CustomerId); + var filter = BuildFilter(input, customerId); + await ApplyInternalOrderDataScopeAsync(filter); + return filter; + } + + private async Task> MapReceivablePayableRowsAsync( + List rows) + { var customerIds = rows .Select(x => x.Order.CustomerId) .Where(x => x.HasValue) @@ -58,8 +157,9 @@ public class FinanceService : ApplicationService ? [] : await CustomerRepository.GetListAsync(x => customerIds.Contains(x.Id)); var customerMap = customers.ToDictionary(x => x.Id); + var feeItemNameMap = await BuildFeeItemNameMapAsync(); - var items = rows.Select(row => + return rows.Select(row => { string? customerCode = null; if (row.Order.CustomerId.HasValue @@ -68,8 +168,12 @@ public class FinanceService : ApplicationService customerCode = customer.CustomerCode; } + var costItem = row.Fee.CostItem; + feeItemNameMap.TryGetValue(costItem, out var costItemName); + return new ReceivablePayablePaginatedOutput { + OrderId = row.Order.Id, ServiceNo = row.Order.ServiceNo, ClientNo = row.Order.ClientNo, TrackNo = row.Order.TrackNo, @@ -85,7 +189,8 @@ public class FinanceService : ApplicationService ConsigneeCountryName = row.Order.ConsigneeCountryName, FeeType = row.Fee.Type, FeeTypeName = GetFeeTypeName(row.Fee.Type), - CostItem = row.Fee.CostItem, + CostItem = costItem, + CostItemName = costItemName ?? ParcelBillingCalculator.ResolveFeeDisplayName(costItem, null), Amount = row.Fee.Amount, Currency = row.Fee.Currency, DownstreamProvider = row.Fee.DownstreamProvider, @@ -95,27 +200,59 @@ public class FinanceService : ApplicationService ChargingStageName = GetChargingStageName(row.Fee.ChargingStage) }; }).ToList(); + } - return new OmsPageResult - { - Items = items, - Total = total - }; + private async Task> BuildFeeItemNameMapAsync() + { + var dictRows = await DictRepository.GetListAsync(x => x.DictType == FeeItemDictType); + return dictRows + .Where(x => !string.IsNullOrWhiteSpace(x.DictCode)) + .GroupBy(x => x.DictCode.Trim(), StringComparer.OrdinalIgnoreCase) + .ToDictionary( + g => g.Key, + g => g.First().DictName?.Trim() ?? g.Key, + StringComparer.OrdinalIgnoreCase); } private static OrderReceivablePayableFilter BuildFilter( ReceivablePayablePaginatedInput input, - int? customerId) => - new() + int? customerId) + { + var timeField = NormalizeTimeField(input.TimeField); + var useCreateTime = timeField == "createTime"; + return new() { Keyword = input.Keyword, CustomerId = customerId, - CreateTimeStart = input.StartTime, - CreateTimeEnd = input.EndTime, + CustomerCode = input.CustomerCode, + CreateTimeStart = useCreateTime ? input.StartTime : null, + CreateTimeEnd = useCreateTime ? input.EndTime : null, + TimeField = timeField, + TimeStart = input.StartTime, + TimeEnd = input.EndTime, FeeType = input.FeeType, CostItem = input.CostItem, - ChargingStage = input.ChargingStage + ChargingStage = input.ChargingStage, + EffectiveStageOnly = input.EffectiveStageOnly, + IsPaid = NormalizeIsPaid(input.IsPaid) }; + } + + private static int? NormalizeIsPaid(int? isPaid) + { + if (!isPaid.HasValue) return null; + return isPaid.Value == 1 ? 1 : isPaid.Value == 0 ? 0 : null; + } + + private static string NormalizeTimeField(string? timeField) + { + var raw = timeField?.Trim(); + return raw switch + { + "receiveTime" or "shipTime" or "payTime" => raw, + _ => "createTime" + }; + } private async Task ApplyInternalOrderDataScopeAsync(OrderReceivablePayableFilter filter) { diff --git a/src/Oms.Application/Services/Kb/KbArticleService.cs b/src/Oms.Application/Services/Kb/KbArticleService.cs new file mode 100644 index 0000000..003bbb9 --- /dev/null +++ b/src/Oms.Application/Services/Kb/KbArticleService.cs @@ -0,0 +1,394 @@ +using System.Linq.Expressions; +using Fake.Application; +using Fake.Domain.Exceptions; +using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Kb; +using Oms.Application.Dtos.Shared; +using Oms.Application.Shared; +using Oms.Domain.KbAggregate.Entities; +using Oms.Domain.KbAggregate.Repositories; + +namespace Oms.Application.Services.Kb; + +/// +/// 知识库文章:管理端 + 客户门户。 +/// +[ApiExplorerSettings(GroupName = "OMS-Kb")] +public class KbArticleService : ApplicationService +{ + private IKbArticleRepository ArticleRepository => + LazyServiceProvider.GetRequiredService(); + + private IKbCategoryRepository CategoryRepository => + LazyServiceProvider.GetRequiredService(); + + [HttpPost("/kb/admin/article/page")] + public async Task> AdminPageAsync(KbArticleListInput input) + { + var predicate = BuildAdminPredicate(input); + var pageIndex = OmsDocHelper.NormalizePage(input.Page); + var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); + var entities = await ArticleRepository.GetPagedListAsync( + predicate, + pageIndex, + pageSize, + new Dictionary + { + [nameof(KbArticle.IsPinned)] = false, + [nameof(KbArticle.SortOrder)] = true, + [nameof(KbArticle.Id)] = false + }); + var total = await ArticleRepository.CountAsync(predicate); + var categoryMap = await LoadCategoryNameMapAsync(entities.Select(x => x.CategoryId).Distinct()); + return new OmsPageResult + { + Total = total, + Items = entities.Select(x => Map(x, categoryMap, input.IncludeContent)).ToList() + }; + } + + [HttpGet("/kb/admin/article/{id:int}")] + public async Task AdminGetAsync(int id) + { + var entity = await GetArticleOrThrowAsync(id); + var categoryMap = await LoadCategoryNameMapAsync([entity.CategoryId]); + return Map(entity, categoryMap, includeContent: true); + } + + [HttpPost("/kb/admin/article/save")] + public async Task SaveAsync(KbArticleSaveInput input) + { + ValidateSave(input); + await EnsureCategoryExistsAsync(input.CategoryId); + + KbArticle? entity = null; + if (input.Id is > 0) + { + entity = await GetArticleOrThrowAsync(input.Id.Value); + } + + entity ??= new KbArticle(); + ApplySave(input, entity); + + if (string.Equals(entity.Status, KbArticleStatusCodes.Published, StringComparison.OrdinalIgnoreCase) + && entity.PublishTime == null) + { + entity.PublishTime = DateTime.Now; + } + + if (entity.Id > 0) + { + await ArticleRepository.UpdateAsync(entity); + } + else + { + await ArticleRepository.InsertAsync(entity); + } + + var categoryMap = await LoadCategoryNameMapAsync([entity.CategoryId]); + return Map(entity, categoryMap, includeContent: true); + } + + [HttpPost("/kb/admin/article/publish")] + public async Task PublishAsync(KbArticleIdInput input) + { + var entity = await GetArticleOrThrowAsync(input.Id); + entity.Status = KbArticleStatusCodes.Published; + entity.PublishTime ??= DateTime.Now; + await ArticleRepository.UpdateAsync(entity); + } + + [HttpPost("/kb/admin/article/offline")] + public async Task OfflineAsync(KbArticleIdInput input) + { + var entity = await GetArticleOrThrowAsync(input.Id); + entity.Status = KbArticleStatusCodes.Offline; + await ArticleRepository.UpdateAsync(entity); + } + + [HttpPost("/kb/admin/article/pin")] + public async Task PinAsync(KbArticlePinInput input) + { + var entity = await GetArticleOrThrowAsync(input.Id); + entity.IsPinned = input.IsPinned; + await ArticleRepository.UpdateAsync(entity); + } + + [HttpPost("/kb/admin/article/delete")] + public async Task DeleteAsync(KbArticleIdInput input) + { + var entity = await GetArticleOrThrowAsync(input.Id); + await ArticleRepository.DeleteAsync(entity); + } + + /// 门户:启用分类列表(需客户登录)。 + [HttpGet("/kb/portal/category/list")] + public async Task> PortalCategoryListAsync() + { + MarketingPortalSessionHelper.EnsureCustomerLogin(CurrentUser); + var items = await CategoryRepository.GetListAsync(x => x.Enabled); + var ordered = items.OrderBy(x => x.SortOrder).ThenBy(x => x.Id).ToList(); + return new OmsItemsResult + { + Items = ordered.Select(x => new KbCategoryOutput + { + Id = x.Id, + Code = x.Code, + Name = x.Name, + SortOrder = x.SortOrder, + Enabled = x.Enabled + }).ToList() + }; + } + + /// 门户:文章分页(需客户登录)。 + [HttpPost("/kb/portal/article/page")] + public async Task> PortalPageAsync(KbPortalArticleListInput input) + { + MarketingPortalSessionHelper.EnsureCustomerLogin(CurrentUser); + var predicate = BuildPortalPredicate(input.Keyword, input.CategoryId); + var pageIndex = OmsDocHelper.NormalizePage(input.Page); + var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); + var entities = await ArticleRepository.GetPagedListAsync( + predicate, + pageIndex, + pageSize, + new Dictionary + { + [nameof(KbArticle.IsPinned)] = false, + [nameof(KbArticle.SortOrder)] = true, + [nameof(KbArticle.PublishTime)] = false, + [nameof(KbArticle.Id)] = false + }); + var total = await ArticleRepository.CountAsync(predicate); + var categoryMap = await LoadCategoryNameMapAsync(entities.Select(x => x.CategoryId).Distinct()); + return new OmsPageResult + { + Total = total, + Items = entities.Select(x => Map(x, categoryMap, includeContent: false)).ToList() + }; + } + + /// 门户:热门(需客户登录)。 + [HttpGet("/kb/portal/article/hot")] + public async Task> PortalHotAsync([FromQuery] int top = 10) + { + MarketingPortalSessionHelper.EnsureCustomerLogin(CurrentUser); + top = Math.Clamp(top <= 0 ? 10 : top, 1, 50); + var now = DateTime.Now; + var all = await ArticleRepository.GetListAsync(x => + x.Status == KbArticleStatusCodes.Published + && x.Audience == KbAudienceCodes.Customer + && (x.ExpireTime == null || x.ExpireTime > now)); + var ordered = all + .OrderByDescending(x => x.IsPinned) + .ThenByDescending(x => x.ViewCount) + .ThenByDescending(x => x.PublishTime) + .ThenByDescending(x => x.Id) + .Take(top) + .ToList(); + var categoryMap = await LoadCategoryNameMapAsync(ordered.Select(x => x.CategoryId).Distinct()); + return new OmsItemsResult + { + Items = ordered.Select(x => Map(x, categoryMap, includeContent: false)).ToList() + }; + } + + /// 门户:详情(需客户登录;浏览量 +1)。 + [HttpGet("/kb/portal/article/{id:int}")] + public async Task PortalGetAsync(int id) + { + MarketingPortalSessionHelper.EnsureCustomerLogin(CurrentUser); + var entity = await GetArticleOrThrowAsync(id); + EnsurePortalVisible(entity); + entity.ViewCount += 1; + await ArticleRepository.UpdateAsync(entity); + var categoryMap = await LoadCategoryNameMapAsync([entity.CategoryId]); + return Map(entity, categoryMap, includeContent: true); + } + + private static Expression> BuildAdminPredicate(KbArticleListInput input) + { + var keyword = NormalizeOptional(input.Keyword); + var status = NormalizeOptional(input.Status); + var audience = NormalizeOptional(input.Audience); + var predicate = ExpressionPredicate.True(); + + if (input.CategoryId is int categoryId) + { + predicate = ExpressionPredicate.AndAlso(predicate, x => x.CategoryId == categoryId); + } + + if (status != null) + { + predicate = ExpressionPredicate.AndAlso(predicate, x => x.Status == status); + } + + if (audience != null) + { + predicate = ExpressionPredicate.AndAlso(predicate, x => x.Audience == audience); + } + + if (input.IsPinned is bool isPinned) + { + predicate = ExpressionPredicate.AndAlso(predicate, x => x.IsPinned == isPinned); + } + + if (keyword != null) + { + predicate = ExpressionPredicate.AndAlso( + predicate, + x => x.Title.Contains(keyword) + || (x.Summary != null && x.Summary.Contains(keyword)) + || (x.Tags != null && x.Tags.Contains(keyword))); + } + + return predicate; + } + + private static Expression> BuildPortalPredicate(string? keyword, int? categoryId) + { + var kw = NormalizeOptional(keyword); + var now = DateTime.Now; + var predicate = ExpressionPredicate.AndAlso( + ExpressionPredicate.True(), + x => x.Status == KbArticleStatusCodes.Published + && x.Audience == KbAudienceCodes.Customer + && (x.ExpireTime == null || x.ExpireTime > now)); + + if (categoryId is int cid) + { + predicate = ExpressionPredicate.AndAlso(predicate, x => x.CategoryId == cid); + } + + if (kw != null) + { + predicate = ExpressionPredicate.AndAlso( + predicate, + x => x.Title.Contains(kw) + || (x.Summary != null && x.Summary.Contains(kw)) + || (x.Tags != null && x.Tags.Contains(kw))); + } + + return predicate; + } + + private static void EnsurePortalVisible(KbArticle entity) + { + if (!string.Equals(entity.Audience, KbAudienceCodes.Customer, StringComparison.OrdinalIgnoreCase) + || !string.Equals(entity.Status, KbArticleStatusCodes.Published, StringComparison.OrdinalIgnoreCase) + || (entity.ExpireTime != null && entity.ExpireTime <= DateTime.Now)) + { + throw new BusinessException("文章不存在或未发布"); + } + } + + private async Task EnsureCategoryExistsAsync(int categoryId) + { + var exists = await CategoryRepository.AnyAsync(x => x.Id == categoryId && x.Enabled); + if (!exists) + { + throw new BusinessException("分类不存在或已停用"); + } + } + + private async Task GetArticleOrThrowAsync(int id) + { + var entity = await ArticleRepository.FirstOrDefaultAsync(x => x.Id == id); + if (entity == null) + { + throw new BusinessException("文章不存在"); + } + + return entity; + } + + private async Task> LoadCategoryNameMapAsync(IEnumerable ids) + { + var idList = ids.Where(x => x > 0).Distinct().ToList(); + if (idList.Count == 0) + { + return new Dictionary(); + } + + var categories = await CategoryRepository.GetListAsync(x => idList.Contains(x.Id)); + return categories.ToDictionary(x => x.Id, x => x.Name); + } + + private static void ValidateSave(KbArticleSaveInput input) + { + if (input.CategoryId <= 0) + { + throw new BusinessException("请选择分类"); + } + + if (string.IsNullOrWhiteSpace(input.Title)) + { + throw new BusinessException("标题不能为空"); + } + + if (string.IsNullOrWhiteSpace(input.Content)) + { + throw new BusinessException("正文不能为空"); + } + + var audience = (input.Audience ?? string.Empty).Trim().ToLowerInvariant(); + if (audience is not (KbAudienceCodes.Customer or KbAudienceCodes.Internal)) + { + throw new BusinessException("受众仅支持 customer / internal"); + } + + var status = (input.Status ?? string.Empty).Trim().ToLowerInvariant(); + if (status is not (KbArticleStatusCodes.Draft or KbArticleStatusCodes.Published or KbArticleStatusCodes.Offline)) + { + throw new BusinessException("状态仅支持 draft / published / offline"); + } + } + + private static void ApplySave(KbArticleSaveInput input, KbArticle entity) + { + entity.CategoryId = input.CategoryId; + entity.Title = input.Title.Trim(); + entity.Summary = NormalizeOptional(input.Summary); + entity.Content = input.Content ?? string.Empty; + entity.Audience = input.Audience.Trim().ToLowerInvariant(); + entity.Status = input.Status.Trim().ToLowerInvariant(); + entity.Tags = NormalizeOptional(input.Tags); + entity.RelatedPath = NormalizeOptional(input.RelatedPath); + entity.RelatedLabel = NormalizeOptional(input.RelatedLabel); + entity.IsPinned = input.IsPinned; + entity.SortOrder = input.SortOrder; + entity.ExpireTime = input.ExpireTime; + } + + private static KbArticleOutput Map( + KbArticle x, + IReadOnlyDictionary categoryMap, + bool includeContent) => + new() + { + Id = x.Id, + CategoryId = x.CategoryId, + CategoryName = categoryMap.TryGetValue(x.CategoryId, out var name) ? name : null, + Title = x.Title, + Summary = x.Summary, + Content = includeContent ? x.Content : null, + Audience = x.Audience, + Status = x.Status, + Tags = x.Tags, + RelatedPath = x.RelatedPath, + RelatedLabel = x.RelatedLabel, + IsPinned = x.IsPinned, + SortOrder = x.SortOrder, + PublishTime = x.PublishTime, + ExpireTime = x.ExpireTime, + ViewCount = x.ViewCount, + UpdateTime = x.UpdateTime + }; + + private static string? NormalizeOptional(string? value) + { + var trimmed = value?.Trim(); + return string.IsNullOrWhiteSpace(trimmed) ? null : trimmed; + } +} diff --git a/src/Oms.Application/Services/Kb/KbCategoryService.cs b/src/Oms.Application/Services/Kb/KbCategoryService.cs new file mode 100644 index 0000000..a42186e --- /dev/null +++ b/src/Oms.Application/Services/Kb/KbCategoryService.cs @@ -0,0 +1,111 @@ +using System.Linq.Expressions; +using Fake.Application; +using Fake.Domain.Exceptions; +using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Kb; +using Oms.Application.Dtos.Shared; +using Oms.Application.Shared; +using Oms.Domain.KbAggregate.Entities; +using Oms.Domain.KbAggregate.Repositories; + +namespace Oms.Application.Services.Kb; + +/// +/// 知识库分类管理。 +/// +[ApiExplorerSettings(GroupName = "OMS-Kb")] +public class KbCategoryService : ApplicationService +{ + private IKbCategoryRepository CategoryRepository => + LazyServiceProvider.GetRequiredService(); + + private IKbArticleRepository ArticleRepository => + LazyServiceProvider.GetRequiredService(); + + [HttpGet("/kb/admin/category/list")] + public async Task> AdminListAsync([FromQuery] bool? enabledOnly = null) + { + Expression> predicate = ExpressionPredicate.True(); + if (enabledOnly is bool enabled) + { + predicate = ExpressionPredicate.AndAlso(predicate, x => x.Enabled == enabled); + } + + var items = await CategoryRepository.GetListAsync(predicate); + var ordered = items.OrderBy(x => x.SortOrder).ThenBy(x => x.Id).ToList(); + return new OmsItemsResult + { + Items = ordered.Select(Map).ToList() + }; + } + + [HttpPost("/kb/admin/category/save")] + public async Task SaveAsync(KbCategorySaveInput input) + { + var code = input.Code.Trim(); + var name = input.Name.Trim(); + if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(name)) + { + throw new BusinessException("分类编码 / 名称不能为空"); + } + + KbCategory? entity = null; + if (input.Id is > 0) + { + entity = await CategoryRepository.FirstOrDefaultAsync(x => x.Id == input.Id.Value); + if (entity == null) + { + throw new BusinessException("分类不存在"); + } + } + + if (await CategoryRepository.ExistsCodeAsync(code, entity?.Id)) + { + throw new BusinessException($"分类编码已存在:{code}"); + } + + entity ??= new KbCategory(); + entity.Code = code; + entity.Name = name; + entity.SortOrder = input.SortOrder; + entity.Enabled = input.Enabled; + + if (entity.Id > 0) + { + await CategoryRepository.UpdateAsync(entity); + } + else + { + await CategoryRepository.InsertAsync(entity); + } + + return Map(entity); + } + + [HttpPost("/kb/admin/category/delete")] + public async Task DeleteAsync(KbCategoryDeleteInput input) + { + var entity = await CategoryRepository.FirstOrDefaultAsync(x => x.Id == input.Id); + if (entity == null) + { + throw new BusinessException("分类不存在"); + } + + var articleCount = await ArticleRepository.CountByCategoryIdAsync(entity.Id); + if (articleCount > 0) + { + throw new BusinessException($"该分类下仍有 {articleCount} 篇文章,无法删除"); + } + + await CategoryRepository.DeleteAsync(entity); + } + + private static KbCategoryOutput Map(KbCategory x) => new() + { + Id = x.Id, + Code = x.Code, + Name = x.Name, + SortOrder = x.SortOrder, + Enabled = x.Enabled + }; +} diff --git a/src/Oms.Application/Services/Mcp/McpToolService.cs b/src/Oms.Application/Services/Mcp/McpToolService.cs index c404907..2985f1c 100644 --- a/src/Oms.Application/Services/Mcp/McpToolService.cs +++ b/src/Oms.Application/Services/Mcp/McpToolService.cs @@ -7,10 +7,10 @@ using Oms.Application.Dtos.Mcp; using Oms.Application.Dtos.Shared; using Oms.Application.Mcp; using Oms.Application.Shared; +using Oms.Domain.AiAggregate.Repositories; using Oms.Domain.CustomersAggregate.Repositories; using Oms.Domain.McpAggregate.Entities; using Oms.Domain.McpAggregate.Repositories; -using Oms.Domain.XhsAggregate.Repositories; namespace Oms.Application.Services.Mcp; @@ -19,9 +19,9 @@ public class McpToolService : ApplicationService { private IMcpToolRepository McpToolRepository => LazyServiceProvider.GetRequiredService(); private IMcpToolExecutor ToolExecutor => LazyServiceProvider.GetRequiredService(); - private IXhsAiProviderRepository AiProviderRepository => LazyServiceProvider.GetRequiredService(); + private IAiProviderRepository AiProviderRepository => LazyServiceProvider.GetRequiredService(); private ICustomerRepository CustomerRepository => LazyServiceProvider.GetRequiredService(); - private XhsLlmClient LlmClient => LazyServiceProvider.GetRequiredService(); + private AiLlmClient LlmClient => LazyServiceProvider.GetRequiredService(); /// 列出 MCP 工具(内置目录 + 库表覆盖) [HttpPost("/mcp/tool/list")] @@ -307,7 +307,7 @@ public class McpToolService : ApplicationService return enabled; } - private async Task ResolveProviderAsync( + private async Task ResolveProviderAsync( int customerId, string providerKey) { diff --git a/src/Oms.Application/Services/Operations/InboundRecordService.cs b/src/Oms.Application/Services/Operations/InboundRecordService.cs index 2dda5d6..5d6a56d 100644 --- a/src/Oms.Application/Services/Operations/InboundRecordService.cs +++ b/src/Oms.Application/Services/Operations/InboundRecordService.cs @@ -8,6 +8,8 @@ using Oms.Application.Shared; using Oms.Domain.ChannelsAggregate.Repositories; using Oms.Domain.OperationsAggregate.Entities; using Oms.Domain.OperationsAggregate.Repositories; +using Oms.Domain.OrdersAggregate.Consts; +using Oms.Domain.OrdersAggregate.Entities; using Oms.Domain.OrdersAggregate.Repositories; using Oms.Domain.SystemAggregate.Repositories; @@ -54,7 +56,8 @@ public class InboundRecordService : ApplicationService ProductCode = order.ProductCode, DestinationCountry = order.ConsigneeCountry, OrderStatus = order.OrderStatus, - OrderStatusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus) + OrderStatusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus), + AllocationPendingReason = order.AllocationPendingReason }; if (!string.IsNullOrWhiteSpace(order.ProductCode)) @@ -103,6 +106,7 @@ public class InboundRecordService : ApplicationService "收货"); ParcelBillingValidators.EnsureInboundOrderStatus(order.OrderStatus); + await EnsureInboundNotInFlightAsync(order, input.WaybillNo.Trim()); int? salesProductId = null; string? destinationCountry = order.ConsigneeCountry; @@ -137,20 +141,13 @@ public class InboundRecordService : ApplicationService var savedEntity = await InboundRecordRepository.InsertAsync(entity); - try - { - var refreshed = await OrderRepository.GetByWaybillNoAsync(input.WaybillNo.Trim()); - if (refreshed != null) - { - await AutoTriggerRuntimeService.FireAsync(refreshed, AutoTriggerTiming.Inbound, operatorId); - } - } - catch - { - // 自动触发失败不影响入库主流程 - } + // 自动触发改异步,避免拉长扫码 RT + AutoTriggerRuntimeService.EnqueueFire(order.Id, AutoTriggerTiming.Inbound, operatorId); - return ObjectMapper.Map(savedEntity); + var refreshed = await OrderRepository.GetByWaybillNoAsync(input.WaybillNo.Trim()); + var output = ObjectMapper.Map(savedEntity); + ApplyOrderStatusToInboundOutput(output, refreshed); + return output; } /// @@ -181,6 +178,14 @@ public class InboundRecordService : ApplicationService var productMap = products.ToDictionary(x => x.Id); var warehouseMap = warehouses.ToDictionary(x => x.Id); + var waybillNos = entities + .Select(x => x.WaybillNo?.Trim()) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Cast() + .ToArray(); + var orderMap = await BuildOrderMapByWaybillNosAsync(waybillNos); + var items = entities.Select(entity => { var output = ObjectMapper.Map(entity); @@ -191,9 +196,88 @@ public class InboundRecordService : ApplicationService ? warehouse.WarehouseName : null; output.OperatorName = entity.OperatorId?.ToString(); + var key = entity.WaybillNo?.Trim() ?? string.Empty; + if (orderMap.TryGetValue(key, out var order)) + { + ApplyOrderStatusToInboundOutput(output, order); + } + return output; }).ToList(); return new OmsItemsResult { Items = items }; } + + private async Task> BuildOrderMapByWaybillNosAsync(string[] waybillNos) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (waybillNos.Length == 0) + { + return map; + } + + var orders = await OrderRepository.GetListAsync(x => + waybillNos.Contains(x.ServiceNo) + || (x.TrackNo != null && waybillNos.Contains(x.TrackNo)) + || (x.DownstreamServiceNo != null && waybillNos.Contains(x.DownstreamServiceNo)) + || (x.ClientNo != null && waybillNos.Contains(x.ClientNo))); + + foreach (var order in orders) + { + void Put(string? key) + { + if (string.IsNullOrWhiteSpace(key)) + { + return; + } + + map[key.Trim()] = order; + } + + Put(order.ServiceNo); + Put(order.TrackNo); + Put(order.DownstreamServiceNo); + Put(order.ClientNo); + } + + return map; + } + + private static void ApplyOrderStatusToInboundOutput(InboundRecordOutput output, Order? order) + { + if (order == null) + { + return; + } + + output.OrderId = order.Id; + output.OrderStatus = order.OrderStatus; + output.OrderStatusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus); + output.AllocationPendingReason = order.AllocationPendingReason; + } + + /// + /// 短时幂等:处理中重复扫码直接拒绝,避免双写入库记录与双投计费任务。 + /// + private async Task EnsureInboundNotInFlightAsync(Order order, string waybillNo) + { + const int windowSeconds = 15; + var now = DateTime.Now; + + if (string.Equals(order.OrderStatus, OrderStatusCodes.PendingAllocation, StringComparison.OrdinalIgnoreCase) + && string.Equals(order.AllocationPendingReason?.Trim(), "入库后计费/排货处理中", StringComparison.Ordinal) + && order.ReceiveTime.HasValue + && (now - order.ReceiveTime.Value).TotalSeconds < windowSeconds) + { + throw new BusinessException("订单入库处理中,请勿重复扫描"); + } + + var latest = await InboundRecordRepository.GetLatestByWaybillNoAsync(waybillNo); + if (latest != null + && (now - latest.OperateTime).TotalSeconds < windowSeconds + && string.Equals(order.OrderStatus, OrderStatusCodes.PendingAllocation, StringComparison.OrdinalIgnoreCase)) + { + throw new BusinessException("订单入库处理中,请勿重复扫描"); + } + } } diff --git a/src/Oms.Application/Services/Orders/Batch/OrderBatchActionExecutor.cs b/src/Oms.Application/Services/Orders/Batch/OrderBatchActionExecutor.cs index 3d95a99..ab02c47 100644 --- a/src/Oms.Application/Services/Orders/Batch/OrderBatchActionExecutor.cs +++ b/src/Oms.Application/Services/Orders/Batch/OrderBatchActionExecutor.cs @@ -43,6 +43,8 @@ public sealed class OrderBatchActionExecutor( OrderBatchActionCodes.Delete => await orderActionHandler.ExecuteAsync(message, cancellationToken), OrderBatchActionCodes.Print => await orderActionHandler.ExecuteAsync(message, cancellationToken), OrderBatchActionCodes.GenerateLabelPdf => await orderActionHandler.ExecuteAsync(message, cancellationToken), + OrderBatchActionCodes.InboundBilling => await orderActionHandler.ExecuteAsync(message, cancellationToken), + OrderBatchActionCodes.Reallocate => await orderActionHandler.ExecuteAsync(message, cancellationToken), OrderBatchActionCodes.MarkProblematic => await orderActionHandler.ExecuteAsync(message, cancellationToken), OrderBatchActionCodes.MarkClaimed => await orderActionHandler.ExecuteAsync(message, cancellationToken), OrderBatchActionCodes.HandleStatusUpdate => await orderActionHandler.ExecuteAsync(message, cancellationToken), diff --git a/src/Oms.Application/Services/Orders/Batch/OrderBatchJobItemFeedback.cs b/src/Oms.Application/Services/Orders/Batch/OrderBatchJobItemFeedback.cs index f54422f..b8f75fd 100644 --- a/src/Oms.Application/Services/Orders/Batch/OrderBatchJobItemFeedback.cs +++ b/src/Oms.Application/Services/Orders/Batch/OrderBatchJobItemFeedback.cs @@ -268,6 +268,8 @@ public static class OrderBatchJobItemFeedback OrderBatchActionCodes.Delete => "删除成功", OrderBatchActionCodes.Print => "打印成功", OrderBatchActionCodes.GenerateLabelPdf => "面单生成成功", + OrderBatchActionCodes.InboundBilling => "入库计费/排货完成", + OrderBatchActionCodes.Reallocate => "重新排货成功", OrderBatchActionCodes.MarkProblematic => "问题件创建成功", OrderBatchActionCodes.MarkClaimed => "理赔件创建成功", OrderBatchActionCodes.HandleStatusUpdate => "处理状态更新成功", diff --git a/src/Oms.Application/Services/Orders/Batch/OrderBatchOrderActionHandler.cs b/src/Oms.Application/Services/Orders/Batch/OrderBatchOrderActionHandler.cs index 4e48e98..f578a60 100644 --- a/src/Oms.Application/Services/Orders/Batch/OrderBatchOrderActionHandler.cs +++ b/src/Oms.Application/Services/Orders/Batch/OrderBatchOrderActionHandler.cs @@ -63,6 +63,17 @@ public sealed class OrderBatchOrderActionHandler(IServiceScopeFactory scopeFacto resultJson: JsonConvert.SerializeObject(new { labelUrl = result.LabelUrl })); } + case OrderBatchActionCodes.InboundBilling: + await orderService.ProcessInboundBillingForBatchAsync(message.OrderId, cancellationToken); + return OrderBatchActionExecuteResult.Ok(); + + case OrderBatchActionCodes.Reallocate: + await orderService.ReallocateForBatchAsync( + message.OrderId, + message.PayloadJson, + cancellationToken); + return OrderBatchActionExecuteResult.Ok(); + case OrderBatchActionCodes.MarkProblematic: await orderService.MarkProblematicForBatchAsync( message.OrderId, diff --git a/src/Oms.Application/Services/Orders/Customs9610OrderService.cs b/src/Oms.Application/Services/Orders/Customs9610OrderService.cs new file mode 100644 index 0000000..9feb3bc --- /dev/null +++ b/src/Oms.Application/Services/Orders/Customs9610OrderService.cs @@ -0,0 +1,1116 @@ +using System.Text.Json; +using Fake.Application; +using Fake.Domain.Exceptions; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; +using Oms.Application.Dtos.Orders; +using Oms.Application.Dtos.Shared; +using Oms.Application.Integrations.Itfx; +using Oms.Application.Shared; +using Oms.Domain.CustomersAggregate.Repositories; +using Oms.Domain.OrdersAggregate.Consts; +using Oms.Domain.OrdersAggregate.Entities; +using Oms.Domain.OrdersAggregate.Repositories; + +namespace Oms.Application.Services.Orders; + +/// +/// 9610 汇总申报单管理。 +/// +[ApiExplorerSettings(GroupName = "OMS-Order")] +public class Customs9610OrderService : ApplicationService +{ + private ICustoms9610OrderRepository HeaderRepository => + LazyServiceProvider.GetRequiredService(); + + private ICustoms9610OrderItemRepository ItemRepository => + LazyServiceProvider.GetRequiredService(); + + private IOrderRepository OrderRepository => + LazyServiceProvider.GetRequiredService(); + + private ICustomerRepository CustomerRepository => + LazyServiceProvider.GetRequiredService(); + + private IItfxForwardClient ItfxForwardClient => + LazyServiceProvider.GetRequiredService(); + + private OrderDownstreamCredentialResolver CredentialResolver => + LazyServiceProvider.GetRequiredService(); + + private IOptions ItfxOptions => + LazyServiceProvider.GetRequiredService>(); + + [HttpPost("/order/customs-9610/list")] + public async Task> ListAsync([FromBody] Customs9610ListInput input) + { + var page = input.Page <= 0 ? 1 : input.Page; + var pageSize = input.PageSize <= 0 ? 30 : Math.Min(input.PageSize, 200); + var customerId = await WarehouseCustomerHelper.ResolveListCustomerIdAsync( + CustomerRepository, + CurrentUser, + input.CustomerId); + + var keyword = Normalize(input.Keyword); + var status = Normalize(input.Status); + + var all = await HeaderRepository.GetListAsync(x => + (customerId == null || x.CustomerId == customerId.Value) && + (status == null || x.Status == status) && + (input.CreateTimeStart == null || x.CreateTime >= input.CreateTimeStart) && + (input.CreateTimeEnd == null || x.CreateTime <= input.CreateTimeEnd) && + (keyword == null || + (x.ServiceNo != null && x.ServiceNo.Contains(keyword)) || + (x.ClientNo != null && x.ClientNo.Contains(keyword)) || + (x.CustomsOrderNo != null && x.CustomsOrderNo.Contains(keyword)))); + + var ordered = all.OrderByDescending(x => x.CreateTime).ThenByDescending(x => x.Id).ToList(); + var total = ordered.Count; + var pageItems = ordered.Skip((page - 1) * pageSize).Take(pageSize).ToList(); + var customerNames = await LoadCustomerNamesAsync(pageItems.Select(x => x.CustomerId)); + + return new OmsPageResult + { + Total = total, + Items = pageItems.Select(x => MapOutput(x, customerNames, includeItems: false)).ToList() + }; + } + + [HttpGet("/order/customs-9610/status-counts")] + public async Task GetStatusCountsAsync([FromQuery] int? customerId) + { + var resolvedCustomerId = await WarehouseCustomerHelper.ResolveListCustomerIdAsync( + CustomerRepository, + CurrentUser, + customerId); + + var all = await HeaderRepository.GetListAsync(x => + resolvedCustomerId == null || x.CustomerId == resolvedCustomerId.Value); + + return new Customs9610StatusCountsOutput + { + Total = all.Count, + Pending = all.Count(x => + string.Equals(x.Status, Customs9610StatusCodes.Pending, StringComparison.OrdinalIgnoreCase)), + Declared = all.Count(x => + string.Equals(x.Status, Customs9610StatusCodes.Declared, StringComparison.OrdinalIgnoreCase)), + }; + } + + [HttpGet("/order/customs-9610/detail")] + public async Task GetDetailAsync([FromQuery] int id) + { + var header = await GetOwnedOrThrowAsync(id); + var items = await ItemRepository.GetByHeaderIdAsync(header.Id); + var customerNames = await LoadCustomerNamesAsync([header.CustomerId]); + var output = MapOutput(header, customerNames, includeItems: true); + output.Items = items + .OrderBy(x => x.SortNo) + .ThenBy(x => x.Id) + .Select(MapItem) + .ToList(); + return output; + } + + [HttpPost("/order/customs-9610/update")] + public async Task UpdateAsync([FromBody] Customs9610UpdateInput input) + { + var header = await GetOwnedOrThrowAsync(input.Id); + if (!string.Equals(header.Status, Customs9610StatusCodes.Pending, StringComparison.OrdinalIgnoreCase)) + { + throw new BusinessException("仅待申报单据可编辑"); + } + + ValidateFormFields(input); + + header.PlatformCode = input.PlatformCode.Trim(); + header.EcomCorpCode = Normalize(input.EcomCorpCode); + header.EcomCorpName = Normalize(input.EcomCorpName); + header.ProducerCode = Normalize(input.ProducerCode); + header.ProducerName = Normalize(input.ProducerName); + header.ClientNo = input.ClientNo.Trim(); + header.ServiceNo = input.ServiceNo.Trim(); + header.BusinessType = input.BusinessType.Trim().ToUpperInvariant(); + header.Region = Normalize(input.Region); + header.AgentDeclare = Normalize(input.AgentDeclare); + header.ActualSellerCode = Normalize(input.ActualSellerCode); + header.PreRecordFlag = Normalize(input.PreRecordFlag); + header.IsSummarySimple = input.IsSummarySimple ? (byte)1 : (byte)0; + header.GrossWeight = input.GrossWeight; + header.Currency = input.Currency.Trim().ToUpperInvariant(); + header.DestCountry = input.DestCountry.Trim().ToUpperInvariant(); + header.Freight = input.Freight; + header.ShipmentNo = Normalize(input.ShipmentNo); + header.FailReason = null; + header.UpdateTime = DateTime.Now; + await HeaderRepository.UpdateAsync(header); + + await HeaderRepository.HardDeleteItemsByHeaderIdAsync(header.Id); + var sort = 0; + foreach (var row in input.Items) + { + if (string.IsNullOrWhiteSpace(row.Sku) || string.IsNullOrWhiteSpace(row.CnName)) + { + throw new BusinessException("商品货号与品名不能为空"); + } + + await ItemRepository.InsertAsync(new Customs9610OrderItem + { + Customs9610OrderId = header.Id, + OrderDeclarationId = row.OrderDeclarationId, + Sku = row.Sku.Trim(), + CnName = row.CnName.Trim(), + ExHsCode = Normalize(row.ExHsCode), + DeclareElement = Normalize(row.DeclareElement), + UnitPrice = row.UnitPrice, + Quantity = row.Quantity, + Freight = row.Freight, + SortNo = row.SortNo > 0 ? row.SortNo : sort, + CreateTime = DateTime.Now, + }); + sort++; + } + + return await GetDetailAsync(header.Id); + } + + [HttpPost("/order/customs-9610/declare")] + public async Task DeclareAsync([FromBody] Customs9610IdInput input) + { + return await DeclareOneAsync(input.Id); + } + + [HttpPost("/order/customs-9610/declare-batch")] + public async Task DeclareBatchAsync([FromBody] Customs9610IdsInput input) + { + var results = new List(); + foreach (var id in input.Ids.Where(x => x > 0).Distinct()) + { + try + { + results.Add(await DeclareOneAsync(id)); + } + catch (Exception ex) + { + results.Add(new Customs9610DeclareResult + { + Id = id, + Success = false, + Message = string.IsNullOrWhiteSpace(ex.Message) ? "申报失败" : ex.Message, + }); + } + } + + return new Customs9610DeclareBatchOutput + { + SuccessCount = results.Count(x => x.Success), + FailCount = results.Count(x => !x.Success), + Items = results, + }; + } + + /// + /// 批量获取清单数据(调 API 中心上游,标准码暂定),成功后回写本地字段。 + /// + [HttpPost("/order/customs-9610/fetch-manifest-batch")] + public async Task FetchManifestBatchAsync([FromBody] Customs9610IdsInput input) + { + var results = new List(); + foreach (var id in input.Ids.Where(x => x > 0).Distinct()) + { + try + { + results.Add(await FetchManifestOneAsync(id)); + } + catch (Exception ex) + { + results.Add(new Customs9610DeclareResult + { + Id = id, + Success = false, + Message = string.IsNullOrWhiteSpace(ex.Message) ? "获取清单数据失败" : ex.Message, + }); + } + } + + return new Customs9610DeclareBatchOutput + { + SuccessCount = results.Count(x => x.Success), + FailCount = results.Count(x => !x.Success), + Items = results, + }; + } + + /// + /// 批量获取报关单(调 API 中心上游,标准码暂定)。 + /// + [HttpPost("/order/customs-9610/fetch-declaration-form-batch")] + public async Task FetchDeclarationFormBatchAsync([FromBody] Customs9610IdsInput input) + { + return await FetchDocumentBatchAsync( + input, + settings => string.IsNullOrWhiteSpace(settings.Customs9610DeclarationFormStandardCode) + ? "customs9610DeclarationForm" + : settings.Customs9610DeclarationFormStandardCode.Trim(), + "获取报关单"); + } + + private async Task FetchManifestOneAsync(int id) + { + var forwardResult = await FetchDocumentOneAsync( + id, + settings => string.IsNullOrWhiteSpace(settings.Customs9610ManifestStandardCode) + ? "customs9610Manifest" + : settings.Customs9610ManifestStandardCode.Trim(), + "获取清单数据"); + + if (!forwardResult.Success) + { + return forwardResult; + } + + try + { + await ApplyManifestFromResponseAsync(id, forwardResult.ResponseBody); + } + catch (Exception ex) + { + return new Customs9610DeclareResult + { + Id = id, + Success = false, + Message = Truncate(ex.Message, 512) ?? "清单数据解析/回写失败", + Status = forwardResult.Status, + CustomsOrderNo = forwardResult.CustomsOrderNo, + HttpStatusCode = forwardResult.HttpStatusCode, + ResponseBody = forwardResult.ResponseBody, + }; + } + + return forwardResult; + } + + private async Task ApplyManifestFromResponseAsync(int headerId, string? responseBody) + { + if (string.IsNullOrWhiteSpace(responseBody)) + { + throw new BusinessException("清单响应为空"); + } + + using var doc = JsonDocument.Parse(responseBody); + var payload = ResolveManifestPayload(doc.RootElement); + if (payload.ValueKind is JsonValueKind.Undefined or JsonValueKind.Null) + { + throw new BusinessException("清单响应缺少有效数据节点"); + } + + var header = await GetOwnedOrThrowAsync(headerId); + ApplyManifestHeader(header, payload); + header.ManifestSyncTime = DateTime.Now; + header.UpdateTime = DateTime.Now; + await HeaderRepository.UpdateAsync(header); + + var itemArray = ResolveManifestItems(payload); + if (itemArray is null || itemArray.Value.ValueKind != JsonValueKind.Array) + { + return; + } + + var existing = await ItemRepository.GetByHeaderIdAsync(header.Id); + foreach (var el in itemArray.Value.EnumerateArray()) + { + if (el.ValueKind != JsonValueKind.Object) + { + continue; + } + + var sortNo = ReadInt(el, "gNo", "GNo", "gno") ?? 0; + var itemNo = Truncate(ReadString(el, "itemNo", "ItemNo", "sku", "Sku") ?? string.Empty, 32) ?? string.Empty; + var matched = existing.FirstOrDefault(x => sortNo > 0 && x.SortNo == sortNo) + ?? existing.FirstOrDefault(x => + !string.IsNullOrWhiteSpace(itemNo) + && string.Equals(x.Sku, itemNo, StringComparison.OrdinalIgnoreCase)); + + if (matched is null) + { + matched = new Customs9610OrderItem + { + Customs9610OrderId = header.Id, + SortNo = sortNo, + Sku = itemNo, + CreateTime = DateTime.Now, + }; + ApplyManifestItem(matched, el); + await ItemRepository.InsertAsync(matched); + existing.Add(matched); + } + else + { + ApplyManifestItem(matched, el); + matched.UpdateTime = DateTime.Now; + await ItemRepository.UpdateAsync(matched); + } + } + } + + private static JsonElement ResolveManifestPayload(JsonElement root) + { + if (TryGetObject(root, out var data, "data", "Data")) + { + if (TryGetObject(data, out var nested, "cebItems", "CebItems")) + { + // 部分上游把头字段放 data,商品放 cebItems;头字段仍用 data + return data; + } + + return data; + } + + if (TryGetObject(root, out var ceb, "cebItems", "CebItems")) + { + return ceb; + } + + return root; + } + + private static JsonElement? ResolveManifestItems(JsonElement payload) + { + if (TryGetPropertyIgnoreCase(payload, out var items, "items", "Items") + && items.ValueKind == JsonValueKind.Array) + { + return items; + } + + if (TryGetObject(payload, out var ceb, "cebItems", "CebItems") + && TryGetPropertyIgnoreCase(ceb, out var nested, "items", "Items") + && nested.ValueKind == JsonValueKind.Array) + { + return nested; + } + + return null; + } + + private static void ApplyManifestHeader(Customs9610Order header, JsonElement payload) + { + var customsOrderNo = Truncate(ReadString(payload, "customsOrderNo", "CustomsOrderNo"), 32); + if (!string.IsNullOrWhiteSpace(customsOrderNo)) + { + header.CustomsOrderNo = customsOrderNo; + } + + var logisticsNo = Truncate(ReadString(payload, "logisticsNo", "LogisticsNo", "serviceNo", "ServiceNo"), 48); + if (!string.IsNullOrWhiteSpace(logisticsNo)) + { + header.ServiceNo = logisticsNo!; + } + + var clientNo = Truncate(ReadString(payload, "referenceNo", "ReferenceNo", "clientNo", "ClientNo"), 48); + if (!string.IsNullOrWhiteSpace(clientNo)) + { + header.ClientNo = clientNo!; + } + + header.EnterpriseBizNo = Truncate(ReadString(payload, "copNo", "CopNo"), 48) ?? header.EnterpriseBizNo; + header.ManifestNo = Truncate(ReadString(payload, "invtNo", "InvtNo"), 48) ?? header.ManifestNo; + header.ClearanceTime = Truncate(ReadString(payload, "clearanceTime", "ClearanceTime"), 48) ?? header.ClearanceTime; + header.CustomsInboundTime = + Truncate(ReadString(payload, "warehouseTime", "WarehouseTime"), 48) ?? header.CustomsInboundTime; + header.CustomsState = Truncate(ReadString(payload, "customsStatus", "CustomsStatus"), 4) ?? header.CustomsState; + header.DeclareCustomsCode = + Truncate(ReadString(payload, "customsCode", "CustomsCode"), 4) ?? header.DeclareCustomsCode; + header.PlatformCorpCode = Truncate(ReadString(payload, "ebpCode", "EbpCode", "platformCorpCode", "PlatformCorpCode"), 18) ?? header.PlatformCorpCode; + header.PlatformName = Truncate(ReadString(payload, "ebpName", "EbpName", "platformName", "PlatformName"), 100) ?? header.PlatformName; + header.LogisticsCorpCode = + Truncate(ReadString(payload, "logisticsCode", "LogisticsCode"), 18) ?? header.LogisticsCorpCode; + header.LogisticsCorpName = + Truncate(ReadString(payload, "logisticsName", "LogisticsName"), 100) ?? header.LogisticsCorpName; + header.IeMark = Truncate(ReadString(payload, "ieFlag", "IeFlag"), 4) ?? header.IeMark; + header.ExportPortCode = Truncate(ReadString(payload, "portCode", "PortCode"), 4) ?? header.ExportPortCode; + header.ExportDate = Truncate(ReadString(payload, "ieDate", "IeDate"), 32) ?? header.ExportDate; + + var businessType = Truncate(ReadString(payload, "statisticsFlag", "StatisticsFlag", "formType", "FormType", "businessType", "BusinessType"), 1); + if (businessType is "A" or "B" or "a" or "b") + { + header.BusinessType = businessType.ToUpperInvariant(); + } + + header.DeclareAgentCode = Truncate(ReadString(payload, "agentCode", "AgentCode"), 18) ?? header.DeclareAgentCode; + header.DeclareAgentName = Truncate(ReadString(payload, "agentName", "AgentName"), 100) ?? header.DeclareAgentName; + header.EcomCorpCode = Truncate(ReadString(payload, "ebcCode", "EbcCode", "ecomCorpCode", "EcomCorpCode"), 18) ?? header.EcomCorpCode; + header.EcomCorpName = Truncate(ReadString(payload, "ebcName", "EbcName", "ecomCorpName", "EcomCorpName"), 100) ?? header.EcomCorpName; + header.ProducerCode = Truncate(ReadString(payload, "ownerCode", "OwnerCode", "producerCode", "ProducerCode"), 18) ?? header.ProducerCode; + header.ProducerName = Truncate(ReadString(payload, "ownerName", "OwnerName", "producerName", "ProducerName"), 100) ?? header.ProducerName; + header.TradeModeCode = Truncate(ReadString(payload, "tradeMode", "TradeMode"), 4) ?? header.TradeModeCode; + header.TransportMode = Truncate(ReadString(payload, "trafMode", "TrafMode"), 4) ?? header.TransportMode; + + var destCountry = Truncate(ReadString(payload, "countryCode", "CountryCode", "destCountry", "DestCountry"), 4); + if (!string.IsNullOrWhiteSpace(destCountry)) + { + header.DestCountry = destCountry!; + } + + var freight = ReadDecimal(payload, "freight", "Freight"); + if (freight.HasValue) + { + header.Freight = freight; + } + + header.FreightCurrency = Truncate(ReadString(payload, "fCurrency", "FCurrency"), 4) ?? header.FreightCurrency; + header.FreightMark = ReadInt(payload, "fFlag", "FFlag") ?? header.FreightMark; + header.PackageType = ReadInt(payload, "wrapType", "WrapType") ?? header.PackageType; + header.PackageQty = ReadInt(payload, "packNo", "PackNo") ?? header.PackageQty; + + // 兼容:若平台短码仍空,用 platformCorpCode 回填 PlatformCode + if (string.IsNullOrWhiteSpace(header.PlatformCode) && !string.IsNullOrWhiteSpace(header.PlatformCorpCode)) + { + header.PlatformCode = Truncate(header.PlatformCorpCode, 16)!; + } + } + + private static void ApplyManifestItem(Customs9610OrderItem item, JsonElement el) + { + var sortNo = ReadInt(el, "gNo", "GNo", "gno"); + if (sortNo.HasValue) + { + item.SortNo = sortNo.Value; + } + + var itemNo = Truncate(ReadString(el, "itemNo", "ItemNo", "sku", "Sku"), 32); + if (!string.IsNullOrWhiteSpace(itemNo)) + { + item.Sku = itemNo!; + } + + var itemName = Truncate(ReadString(el, "itemName", "ItemName", "cnName", "CnName"), 250); + if (!string.IsNullOrWhiteSpace(itemName)) + { + item.CnName = itemName!; + } + + item.ExHsCode = Truncate(ReadString(el, "gcode", "Gcode", "gCode", "exHsCode", "ExHsCode"), 10) ?? item.ExHsCode; + item.DeclareElement = Truncate(ReadString(el, "gmodel", "Gmodel", "gModel", "declareElement", "DeclareElement"), 255) ?? item.DeclareElement; + item.Barcode = Truncate(ReadString(el, "barCode", "BarCode", "barcode"), 255) ?? item.Barcode; + item.DestCountry = Truncate(ReadString(el, "country", "Country", "destCountry", "DestCountry"), 255) ?? item.DestCountry; + item.ItemCurrency = Truncate(ReadString(el, "currency", "Currency"), 3) ?? item.ItemCurrency; + + var qty = ReadDecimal(el, "qty", "Qty"); + if (qty.HasValue) + { + item.Quantity = qty.Value; + } + + item.LegalQty = ReadDecimal(el, "qty1", "Qty1") ?? item.LegalQty; + item.Unit = Truncate(ReadString(el, "unit", "Unit"), 3) ?? item.Unit; + item.LegalUnit = Truncate(ReadString(el, "unit1", "Unit1"), 3) ?? item.LegalUnit; + + var price = ReadDecimal(el, "price", "Price"); + if (price.HasValue) + { + item.UnitPrice = price.Value; + } + + item.Amount = ReadDecimal(el, "totalPrice", "TotalPrice", "amount", "Amount") ?? item.Amount; + } + + private static bool TryGetObject(JsonElement parent, out JsonElement child, params string[] names) + { + if (TryGetPropertyIgnoreCase(parent, out child, names) && child.ValueKind == JsonValueKind.Object) + { + return true; + } + + child = default; + return false; + } + + private static bool TryGetPropertyIgnoreCase(JsonElement parent, out JsonElement child, params string[] names) + { + foreach (var name in names) + { + if (parent.TryGetProperty(name, out child)) + { + return true; + } + } + + child = default; + return false; + } + + private static int? ReadInt(JsonElement el, params string[] names) + { + foreach (var name in names) + { + if (!el.TryGetProperty(name, out var p)) + { + continue; + } + + if (p.ValueKind == JsonValueKind.Number && p.TryGetInt32(out var n)) + { + return n; + } + + if (p.ValueKind == JsonValueKind.String + && int.TryParse(p.GetString(), out var parsed)) + { + return parsed; + } + } + + return null; + } + + private static decimal? ReadDecimal(JsonElement el, params string[] names) + { + foreach (var name in names) + { + if (!el.TryGetProperty(name, out var p)) + { + continue; + } + + if (p.ValueKind == JsonValueKind.Number && p.TryGetDecimal(out var d)) + { + return d; + } + + if (p.ValueKind == JsonValueKind.String + && decimal.TryParse(p.GetString(), out var parsed)) + { + return parsed; + } + } + + return null; + } + + private async Task FetchDocumentBatchAsync( + Customs9610IdsInput input, + Func resolveStandardCode, + string actionLabel) + { + var results = new List(); + foreach (var id in input.Ids.Where(x => x > 0).Distinct()) + { + try + { + results.Add(await FetchDocumentOneAsync(id, resolveStandardCode, actionLabel)); + } + catch (Exception ex) + { + results.Add(new Customs9610DeclareResult + { + Id = id, + Success = false, + Message = string.IsNullOrWhiteSpace(ex.Message) ? $"{actionLabel}失败" : ex.Message, + }); + } + } + + return new Customs9610DeclareBatchOutput + { + SuccessCount = results.Count(x => x.Success), + FailCount = results.Count(x => !x.Success), + Items = results, + }; + } + + private async Task FetchDocumentOneAsync( + int id, + Func resolveStandardCode, + string actionLabel) + { + var header = await GetOwnedOrThrowAsync(id); + if (!string.Equals(header.Status, Customs9610StatusCodes.Declared, StringComparison.OrdinalIgnoreCase)) + { + throw new BusinessException($"仅已申报单据可{actionLabel}"); + } + + if (string.IsNullOrWhiteSpace(header.CustomsOrderNo) + && string.IsNullOrWhiteSpace(header.ClientNo) + && string.IsNullOrWhiteSpace(header.ServiceNo)) + { + throw new BusinessException("缺少海关订单号/客户单号/运单号,无法获取"); + } + + var order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == header.OrderId) + ?? throw new BusinessException("关联运单不存在"); + + var settings = ItfxOptions.Value; + var standardCode = resolveStandardCode(settings); + var creds = await CredentialResolver.ResolveAsync(order); + var supplierCode = !string.IsNullOrWhiteSpace(settings.Customs9610SupplierCode) + ? settings.Customs9610SupplierCode.Trim() + : creds.SupplierCode; + + var body = new + { + customsOrderNo = header.CustomsOrderNo, + clientNo = header.ClientNo, + serviceNo = header.ServiceNo, + businessType = header.BusinessType, + platformCode = header.PlatformCode, + }; + + ItfxForwardResult forward; + try + { + forward = await ItfxForwardClient.ForwardWithSubscribeAsync( + standardCode, + supplierCode, + creds.AppKey, + creds.AppSecret, + body); + } + catch (Exception ex) + { + return new Customs9610DeclareResult + { + Id = header.Id, + Success = false, + Message = Truncate(ex.Message, 512) ?? $"调用 API 中心失败({actionLabel})", + Status = header.Status, + CustomsOrderNo = header.CustomsOrderNo, + }; + } + + if (!forward.Success) + { + var reason = ItfxForwardResultEvaluator.BuildFailReason( + forward.StatusCode, + forward.ResponseBody, + null, + null); + return new Customs9610DeclareResult + { + Id = header.Id, + Success = false, + Message = Truncate(reason, 512) ?? $"{actionLabel}失败", + Status = header.Status, + CustomsOrderNo = header.CustomsOrderNo, + HttpStatusCode = forward.StatusCode, + ResponseBody = forward.ResponseBody, + }; + } + + return new Customs9610DeclareResult + { + Id = header.Id, + Success = true, + Message = $"{actionLabel}成功", + Status = header.Status, + CustomsOrderNo = header.CustomsOrderNo, + HttpStatusCode = forward.StatusCode, + ResponseBody = forward.ResponseBody, + }; + } + + private async Task DeclareOneAsync(int id) + { + var header = await GetOwnedOrThrowAsync(id); + if (!string.Equals(header.Status, Customs9610StatusCodes.Pending, StringComparison.OrdinalIgnoreCase)) + { + throw new BusinessException("仅待申报单据可申报"); + } + + var items = await ItemRepository.GetByHeaderIdAsync(header.Id); + if (items.Count == 0) + { + throw new BusinessException("申报商品不能为空"); + } + + ValidateHeaderForDeclare(header); + + var order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == header.OrderId) + ?? throw new BusinessException("关联运单不存在"); + + var settings = ItfxOptions.Value; + var standardCode = string.IsNullOrWhiteSpace(settings.Customs9610StandardCode) + ? "customs9610Declare" + : settings.Customs9610StandardCode.Trim(); + + var creds = await CredentialResolver.ResolveAsync(order); + var supplierCode = !string.IsNullOrWhiteSpace(settings.Customs9610SupplierCode) + ? settings.Customs9610SupplierCode.Trim() + : creds.SupplierCode; + + var body = BuildDeclareBody(header, items); + ItfxForwardResult forward; + try + { + forward = await ItfxForwardClient.ForwardWithSubscribeAsync( + standardCode, + supplierCode, + creds.AppKey, + creds.AppSecret, + body); + } + catch (Exception ex) + { + header.FailReason = Truncate(ex.Message, 512); + header.UpdateTime = DateTime.Now; + await HeaderRepository.UpdateAsync(header); + return new Customs9610DeclareResult + { + Id = header.Id, + Success = false, + Message = header.FailReason ?? "调用 API 中心失败", + Status = header.Status, + }; + } + + if (!forward.Success) + { + var reason = ItfxForwardResultEvaluator.BuildFailReason( + forward.StatusCode, + forward.ResponseBody, + null, + null); + header.FailReason = Truncate(reason, 512); + header.UpdateTime = DateTime.Now; + await HeaderRepository.UpdateAsync(header); + return new Customs9610DeclareResult + { + Id = header.Id, + Success = false, + Message = header.FailReason ?? "申报失败", + Status = header.Status, + HttpStatusCode = forward.StatusCode, + ResponseBody = forward.ResponseBody, + }; + } + + TryParseDeclareResponse(forward.ResponseBody, out var customsOrderNo, out var downstreamRef); + header.Status = Customs9610StatusCodes.Declared; + header.CustomsOrderNo = Truncate(customsOrderNo, 32) ?? header.CustomsOrderNo; + header.DownstreamRefNo = Truncate(downstreamRef, 32) ?? header.DownstreamRefNo; + header.DeclareTime = DateTime.Now; + header.FailReason = null; + header.UpdateTime = DateTime.Now; + await HeaderRepository.UpdateAsync(header); + + return new Customs9610DeclareResult + { + Id = header.Id, + Success = true, + Message = "申报成功", + CustomsOrderNo = header.CustomsOrderNo, + Status = header.Status, + HttpStatusCode = forward.StatusCode, + ResponseBody = forward.ResponseBody, + }; + } + + private static object BuildDeclareBody(Customs9610Order header, List items) + { + return new + { + platformCode = header.PlatformCode, + ecomCorpCode = header.EcomCorpCode, + ecomCorpName = header.EcomCorpName, + producerCode = header.ProducerCode, + producerName = header.ProducerName, + clientNo = header.ClientNo, + serviceNo = header.ServiceNo, + businessType = header.BusinessType, + region = header.Region, + agentDeclare = header.AgentDeclare, + actualSellerCode = header.ActualSellerCode, + preRecordFlag = header.PreRecordFlag, + isSummarySimple = header.IsSummarySimple == 1, + grossWeight = header.GrossWeight, + currency = header.Currency, + destCountry = header.DestCountry, + freight = header.Freight, + shipmentNo = header.ShipmentNo, + items = items + .OrderBy(x => x.SortNo) + .ThenBy(x => x.Id) + .Select(x => new + { + sku = x.Sku, + cnName = x.CnName, + exHsCode = x.ExHsCode, + declareElement = x.DeclareElement, + unitPrice = x.UnitPrice, + quantity = x.Quantity, + freight = x.Freight, + sortNo = x.SortNo, + }) + .ToList() + }; + } + + private static void TryParseDeclareResponse(string? responseBody, out string? customsOrderNo, out string? referenceNo) + { + customsOrderNo = null; + referenceNo = null; + if (string.IsNullOrWhiteSpace(responseBody)) + { + return; + } + + try + { + using var doc = JsonDocument.Parse(responseBody); + var root = doc.RootElement; + if (root.TryGetProperty("data", out var data) || root.TryGetProperty("Data", out data)) + { + customsOrderNo = ReadString(data, "orderNo", "OrderNo", "customsOrderNo", "CustomsOrderNo"); + referenceNo = ReadString(data, "referenceNo", "ReferenceNo"); + } + else + { + customsOrderNo = ReadString(root, "orderNo", "OrderNo", "customsOrderNo", "CustomsOrderNo"); + referenceNo = ReadString(root, "referenceNo", "ReferenceNo"); + } + } + catch + { + // ignore parse errors + } + } + + private static string? ReadString(JsonElement el, params string[] names) + { + foreach (var name in names) + { + if (!el.TryGetProperty(name, out var p)) + { + continue; + } + + if (p.ValueKind == JsonValueKind.String) + { + var s = p.GetString(); + if (!string.IsNullOrWhiteSpace(s)) + { + return s.Trim(); + } + } + else if (p.ValueKind == JsonValueKind.Number) + { + return p.ToString(); + } + } + + return null; + } + + private static void ValidateFormFields(Customs9610UpdateInput input) + { + if (string.IsNullOrWhiteSpace(input.PlatformCode)) + { + throw new BusinessException("电商平台 platformCode 不能为空"); + } + + var businessType = (input.BusinessType ?? string.Empty).Trim().ToUpperInvariant(); + if (businessType is not (Customs9610FormTypeCodes.SimpleA or Customs9610FormTypeCodes.SummaryB)) + { + throw new BusinessException("businessType 仅支持 A 或 B"); + } + + if (input.GrossWeight <= 0) + { + throw new BusinessException("毛重必须大于 0"); + } + + if (string.IsNullOrWhiteSpace(input.Currency)) + { + throw new BusinessException("币制不能为空"); + } + + if (string.IsNullOrWhiteSpace(input.DestCountry)) + { + throw new BusinessException("目的国不能为空"); + } + + if (businessType == Customs9610FormTypeCodes.SimpleA) + { + if (string.IsNullOrWhiteSpace(input.Region)) + { + throw new BusinessException("A 简化申报必须填写 region"); + } + + if (string.IsNullOrWhiteSpace(input.AgentDeclare)) + { + throw new BusinessException("A 简化申报必须填写 agentDeclare"); + } + } + + if (businessType == Customs9610FormTypeCodes.SummaryB + && string.IsNullOrWhiteSpace(input.PreRecordFlag)) + { + throw new BusinessException("B 汇总申报必须填写 preRecordFlag"); + } + } + + private static void ValidateHeaderForDeclare(Customs9610Order header) + { + if (string.IsNullOrWhiteSpace(header.PlatformCode)) + { + throw new BusinessException("请先填写电商平台 platformCode"); + } + + if (string.IsNullOrWhiteSpace(header.ClientNo)) + { + throw new BusinessException("客户单号不能为空"); + } + + if (string.IsNullOrWhiteSpace(header.ServiceNo)) + { + throw new BusinessException("运单号不能为空"); + } + + if (header.GrossWeight <= 0) + { + throw new BusinessException("毛重必须大于 0"); + } + + if (string.Equals(header.BusinessType, Customs9610FormTypeCodes.SummaryB, StringComparison.OrdinalIgnoreCase) + && string.IsNullOrWhiteSpace(header.PreRecordFlag)) + { + throw new BusinessException("B 汇总申报必须填写 preRecordFlag"); + } + + if (string.Equals(header.BusinessType, Customs9610FormTypeCodes.SimpleA, StringComparison.OrdinalIgnoreCase)) + { + if (string.IsNullOrWhiteSpace(header.Region) || string.IsNullOrWhiteSpace(header.AgentDeclare)) + { + throw new BusinessException("A 简化申报必须填写 region / agentDeclare"); + } + } + } + + private async Task GetOwnedOrThrowAsync(int id) + { + var header = await HeaderRepository.FirstOrDefaultAsync(x => x.Id == id) + ?? throw new BusinessException("9610 订单不存在"); + + var customerId = await WarehouseCustomerHelper.ResolveListCustomerIdAsync( + CustomerRepository, + CurrentUser, + null); + if (customerId is > 0 && header.CustomerId != customerId.Value) + { + throw new BusinessException("无权访问该 9610 订单"); + } + + return header; + } + + private async Task> LoadCustomerNamesAsync(IEnumerable customerIds) + { + var ids = customerIds.Where(x => x > 0).Distinct().ToList(); + if (ids.Count == 0) + { + return new Dictionary(); + } + + var customers = await CustomerRepository.GetListAsync(x => ids.Contains(x.Id)); + return customers.ToDictionary(x => x.Id, x => x.CustomerName); + } + + private static Customs9610OrderOutput MapOutput( + Customs9610Order header, + IReadOnlyDictionary customerNames, + bool includeItems) + { + customerNames.TryGetValue(header.CustomerId, out var customerName); + return new Customs9610OrderOutput + { + Id = header.Id, + OrderId = header.OrderId, + ServiceNo = header.ServiceNo, + CustomerId = header.CustomerId, + CustomerName = customerName, + Status = header.Status, + PlatformCode = header.PlatformCode, + EcomCorpCode = header.EcomCorpCode, + EcomCorpName = header.EcomCorpName, + ProducerCode = header.ProducerCode, + ProducerName = header.ProducerName, + ClientNo = header.ClientNo, + BusinessType = header.BusinessType, + Region = header.Region, + AgentDeclare = header.AgentDeclare, + ActualSellerCode = header.ActualSellerCode, + PreRecordFlag = header.PreRecordFlag, + IsSummarySimple = header.IsSummarySimple == 1, + GrossWeight = header.GrossWeight, + Currency = header.Currency, + DestCountry = header.DestCountry, + Freight = header.Freight, + FreightCurrency = header.FreightCurrency, + FreightMark = header.FreightMark, + PackageType = header.PackageType, + PackageQty = header.PackageQty, + ShipmentNo = header.ShipmentNo, + CustomsOrderNo = header.CustomsOrderNo, + DownstreamRefNo = header.DownstreamRefNo, + EnterpriseBizNo = header.EnterpriseBizNo, + ManifestNo = header.ManifestNo, + ClearanceTime = header.ClearanceTime, + CustomsInboundTime = header.CustomsInboundTime, + CustomsState = header.CustomsState, + DeclareCustomsCode = header.DeclareCustomsCode, + PlatformCorpCode = header.PlatformCorpCode, + PlatformName = header.PlatformName, + LogisticsCorpCode = header.LogisticsCorpCode, + LogisticsCorpName = header.LogisticsCorpName, + IeMark = header.IeMark, + ExportPortCode = header.ExportPortCode, + ExportDate = header.ExportDate, + DeclareAgentCode = header.DeclareAgentCode, + DeclareAgentName = header.DeclareAgentName, + TradeModeCode = header.TradeModeCode, + TransportMode = header.TransportMode, + DeclareTime = header.DeclareTime, + ManifestSyncTime = header.ManifestSyncTime, + FailReason = header.FailReason, + CreateTime = header.CreateTime, + UpdateTime = header.UpdateTime == default ? null : header.UpdateTime, + Items = includeItems ? [] : null, + }; + } + + private static Customs9610ItemOutput MapItem(Customs9610OrderItem item) => new() + { + Id = item.Id, + OrderDeclarationId = item.OrderDeclarationId, + Sku = item.Sku, + CnName = item.CnName, + ExHsCode = item.ExHsCode, + DeclareElement = item.DeclareElement, + Barcode = item.Barcode, + DestCountry = item.DestCountry, + ItemCurrency = item.ItemCurrency, + UnitPrice = item.UnitPrice, + Amount = item.Amount, + Quantity = item.Quantity, + LegalQty = item.LegalQty, + Unit = item.Unit, + LegalUnit = item.LegalUnit, + Freight = item.Freight, + SortNo = item.SortNo, + }; + + private static string? Normalize(string? value) + { + var t = value?.Trim(); + return string.IsNullOrEmpty(t) ? null : t; + } + + private static string? Truncate(string? value, int max) + { + if (string.IsNullOrEmpty(value)) + { + return value; + } + + return value.Length <= max ? value : value[..max]; + } +} diff --git a/src/Oms.Application/Services/Orders/Customs9610OrderWriter.cs b/src/Oms.Application/Services/Orders/Customs9610OrderWriter.cs new file mode 100644 index 0000000..0fc0a5b --- /dev/null +++ b/src/Oms.Application/Services/Orders/Customs9610OrderWriter.cs @@ -0,0 +1,184 @@ +using Fake.DependencyInjection; +using Oms.Domain.OrdersAggregate.Consts; +using Oms.Domain.OrdersAggregate.Entities; +using Oms.Domain.OrdersAggregate.Repositories; + +namespace Oms.Application.Services.Orders; + +/// +/// 运单创建时按 ExportCustomsMode=9610Summary 写入/刷新 t_9610_order。 +/// +public class Customs9610OrderWriter : IScopedDependency +{ + private readonly ICustoms9610OrderRepository _headerRepository; + private readonly ICustoms9610OrderItemRepository _itemRepository; + private readonly IOrderRepository _orderRepository; + + public Customs9610OrderWriter( + ICustoms9610OrderRepository headerRepository, + ICustoms9610OrderItemRepository itemRepository, + IOrderRepository orderRepository) + { + _headerRepository = headerRepository; + _itemRepository = itemRepository; + _orderRepository = orderRepository; + } + + public async Task UpsertFromOrderAsync(Order order, CancellationToken cancellationToken = default) + { + if (order.Id <= 0) + { + return; + } + + var isSummary = string.Equals( + order.ExportCustomsMode, + ExportCustomsModeCodes.Mode9610Summary, + StringComparison.OrdinalIgnoreCase); + + var existing = await _headerRepository.GetByOrderIdAsync(order.Id, cancellationToken); + + if (!isSummary) + { + if (existing != null + && string.Equals(existing.Status, Customs9610StatusCodes.Pending, StringComparison.OrdinalIgnoreCase)) + { + await _headerRepository.HardDeleteItemsByHeaderIdAsync(existing.Id, cancellationToken); + await _headerRepository.HardDeleteAsync(existing, cancellationToken); + } + + return; + } + + var declarations = await _orderRepository.GetDeclarationsByOrderIdsAsync([order.Id], cancellationToken); + var weights = await _orderRepository.GetWeightsByOrderIdsAsync([order.Id], cancellationToken); + var grossWeight = ResolveGrossWeight(weights); + var serviceNo = order.ServiceNo?.Trim() ?? string.Empty; + var clientNo = FirstNonEmpty(order.ClientNo, order.ServiceNo) ?? string.Empty; + + if (existing != null + && string.Equals(existing.Status, Customs9610StatusCodes.Declared, StringComparison.OrdinalIgnoreCase)) + { + // 已申报:仅同步冗余检索字段,不覆盖申报内容 + existing.ServiceNo = string.IsNullOrWhiteSpace(existing.ServiceNo) ? serviceNo : existing.ServiceNo; + existing.UpdateTime = DateTime.Now; + await _headerRepository.UpdateAsync(existing); + return; + } + + Customs9610Order header; + if (existing == null) + { + header = new Customs9610Order + { + OrderId = order.Id, + CustomerId = order.CustomerId ?? 0, + Status = Customs9610StatusCodes.Pending, + BusinessType = Customs9610FormTypeCodes.SummaryB, + PreRecordFlag = "1", + IsSummarySimple = 0, + CreateTime = DateTime.Now, + }; + } + else + { + header = existing; + header.IsDeleted = false; + } + + header.ServiceNo = serviceNo; + header.CustomerId = order.CustomerId ?? header.CustomerId; + header.ClientNo = clientNo; + header.BusinessType = string.IsNullOrWhiteSpace(header.BusinessType) + ? Customs9610FormTypeCodes.SummaryB + : header.BusinessType; + if (string.IsNullOrWhiteSpace(header.PreRecordFlag) + && string.Equals(header.BusinessType, Customs9610FormTypeCodes.SummaryB, StringComparison.OrdinalIgnoreCase)) + { + header.PreRecordFlag = "1"; + } + + header.GrossWeight = grossWeight; + header.Currency = FirstNonEmpty(order.DeclaredCurrency, header.Currency, "CNY")!; + header.DestCountry = FirstNonEmpty(order.ConsigneeCountry, header.DestCountry) ?? string.Empty; + header.UpdateTime = DateTime.Now; + + if (existing == null) + { + header = await _headerRepository.InsertAsync(header); + } + else + { + await _headerRepository.UpdateAsync(header); + } + + await _headerRepository.HardDeleteItemsByHeaderIdAsync(header.Id, cancellationToken); + + var sort = 0; + foreach (var d in declarations.OrderBy(x => x.Id)) + { + var itemName = FirstNonEmpty(d.CnName, d.EnName) ?? string.Empty; + var sku = FirstNonEmpty(d.Sku, $"ITEM{sort + 1}")!; + var declareElement = JoinNonEmpty(" ", d.Model, d.Specifications, d.Attributes, d.Material); + await _itemRepository.InsertAsync(new Customs9610OrderItem + { + Customs9610OrderId = header.Id, + OrderDeclarationId = d.Id, + Sku = Truncate(sku, 32) ?? string.Empty, + CnName = Truncate(itemName, 250) ?? string.Empty, + ExHsCode = Truncate(FirstNonEmpty(d.ExHsCode, d.HsCode, d.ImHsCode), 10), + DeclareElement = Truncate(declareElement, 255), + UnitPrice = d.UnitPrice ?? 0, + Quantity = d.Quantity ?? 0, + Amount = d.Amount, + Unit = Truncate(d.Unit, 3), + Freight = null, + SortNo = sort++, + CreateTime = DateTime.Now, + }); + } + } + + private static decimal ResolveGrossWeight(IReadOnlyList weights) + { + var forecast = weights.FirstOrDefault(x => + string.Equals(x.Type, OrderWeightTypeCodes.Forecast, StringComparison.OrdinalIgnoreCase)); + var row = forecast ?? weights.FirstOrDefault(); + if (row == null) + { + return 0; + } + + var w = row.ActualWeight ?? row.ChargeableWeight ?? 0; + return w > 0 ? w : 0; + } + + private static string? FirstNonEmpty(params string?[] values) + { + foreach (var v in values) + { + if (!string.IsNullOrWhiteSpace(v)) + { + return v.Trim(); + } + } + + return null; + } + + private static string? JoinNonEmpty(string sep, params string?[] values) + { + var parts = values.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x!.Trim()).ToList(); + return parts.Count == 0 ? null : string.Join(sep, parts); + } + + private static string? Truncate(string? value, int max) + { + if (string.IsNullOrEmpty(value)) + { + return value; + } + + return value.Length <= max ? value : value[..max]; + } +} diff --git a/src/Oms.Application/Services/Orders/Issues/AutoTriggerFormulaMeta.cs b/src/Oms.Application/Services/Orders/Issues/AutoTriggerFormulaMeta.cs index 50ae08e..0e9e8ce 100644 --- a/src/Oms.Application/Services/Orders/Issues/AutoTriggerFormulaMeta.cs +++ b/src/Oms.Application/Services/Orders/Issues/AutoTriggerFormulaMeta.cs @@ -146,6 +146,7 @@ public static class AutoTriggerFormulaMeta yield return ("订单件数", "t_order", "Quantity", FormulaValueType.Number, false); yield return ("是否拦截", "t_order", "IsIntercept", FormulaValueType.Boolean, false); yield return ("是否偏远", "t_order", "IsRemote", FormulaValueType.Boolean, false); + yield return ("附加服务", "t_order", "AdditionalServices", FormulaValueType.String, false); // t_order_recipient yield return ("收件人姓名", "t_order_recipient", "RecipientsName", FormulaValueType.String, false); diff --git a/src/Oms.Application/Services/Orders/Issues/AutoTriggerRuntimeService.cs b/src/Oms.Application/Services/Orders/Issues/AutoTriggerRuntimeService.cs index 8d06daa..e8276d1 100644 --- a/src/Oms.Application/Services/Orders/Issues/AutoTriggerRuntimeService.cs +++ b/src/Oms.Application/Services/Orders/Issues/AutoTriggerRuntimeService.cs @@ -1,4 +1,5 @@ using Fake.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Oms.Domain.ChannelsAggregate.Consts; using Oms.Domain.ChannelsAggregate.Entities; @@ -15,10 +16,40 @@ public class AutoTriggerRuntimeService( OrderAutoTriggerService orderAutoTriggerService, OrderExceptionWorkflowService exceptionWorkflowService, OrderIssueNotificationService issueNotificationService, + IServiceScopeFactory scopeFactory, ILogger logger) : IScopedDependency { private const string InterceptOperation = "拦截"; + /// + /// 后台异步触发,避免拉长入库/出库扫码请求。 + /// + public void EnqueueFire(int orderId, AutoTriggerTiming timing, int operatorUserId) + { + if (orderId <= 0) + { + return; + } + + _ = Task.Run(async () => + { + try + { + using var scope = scopeFactory.CreateScope(); + var runtime = scope.ServiceProvider.GetRequiredService(); + await runtime.FireByOrderIdAsync(orderId, timing, operatorUserId); + } + catch (Exception ex) + { + logger.LogWarning( + ex, + "异步自动触发失败 OrderId={OrderId} Timing={Timing}", + orderId, + timing); + } + }); + } + public async Task FireAsync(Order order, AutoTriggerTiming timing, int operatorUserId) { if (order.Id <= 0) @@ -103,6 +134,7 @@ public class AutoTriggerRuntimeService( IssuePlaceholderRenderer.Render(content, context), IssueNotifyMethodCodes.InApp, operatorUserId, + null, AutoTriggerConditionMatcher.ParseNotifierUserIds(trigger.Notifier)); return; } diff --git a/src/Oms.Application/Services/Orders/Issues/IssueHandlerResolver.cs b/src/Oms.Application/Services/Orders/Issues/IssueHandlerResolver.cs new file mode 100644 index 0000000..32575a5 --- /dev/null +++ b/src/Oms.Application/Services/Orders/Issues/IssueHandlerResolver.cs @@ -0,0 +1,101 @@ +using Fake.Application; +using Fake.DependencyInjection; +using Oms.Application.Shared; +using Oms.Domain.ChannelsAggregate.Consts; +using Oms.Domain.ChannelsAggregate.Entities; +using Oms.Domain.CustomersAggregate.Repositories; +using Oms.Domain.OrdersAggregate.Entities; + +namespace Oms.Application.Services.Orders.Issues; + +public sealed class IssueHandlerResolution +{ + public string? HandlerType { get; set; } + + public int? HandlerUserId { get; set; } + + public string? HandlerNames { get; set; } + + public IReadOnlyList NotifyUserIds { get; set; } = []; +} + +public class IssueHandlerResolver( + ICustomerRepository customerRepository, + OmsRbacUserDisplayNameResolver userDisplayNameResolver) : IScopedDependency +{ + public async Task ResolveAsync( + Order order, + IssueTemplate? template, + string? manualHandlerNames = null) + { + if (template != null && !string.IsNullOrWhiteSpace(template.HandlerType)) + { + if (IssueHandlerTypeCodes.IsCustomer(template.HandlerType)) + { + return await ResolveCustomerHandlerAsync(order); + } + + if (IssueHandlerTypeCodes.IsUser(template.HandlerType)) + { + return await ResolveUserHandlerAsync(template.HandlerUserId); + } + } + + var names = manualHandlerNames?.Trim(); + return new IssueHandlerResolution + { + HandlerNames = string.IsNullOrWhiteSpace(names) ? null : names, + NotifyUserIds = [] + }; + } + + private async Task ResolveCustomerHandlerAsync(Order order) + { + if (order.CustomerId is not int customerId || customerId <= 0) + { + throw new BusinessException("订单未关联客户,无法指定客户为处理人"); + } + + var customer = await customerRepository.FirstOrDefaultAsync(x => x.Id == customerId); + if (customer == null) + { + throw new BusinessException("订单客户不存在,无法指定客户为处理人"); + } + + if (customer.UserId <= 0) + { + throw new BusinessException("客户未绑定登录账号,无法通知客户处理"); + } + + var displayName = string.IsNullOrWhiteSpace(customer.CustomerName) + ? $"客户#{customer.Id}" + : customer.CustomerName.Trim(); + + return new IssueHandlerResolution + { + HandlerType = IssueHandlerTypeCodes.Customer, + HandlerUserId = customer.UserId, + HandlerNames = displayName, + NotifyUserIds = [customer.UserId] + }; + } + + private async Task ResolveUserHandlerAsync(int? handlerUserId) + { + if (handlerUserId is not int userId || userId <= 0) + { + throw new BusinessException("问题模板未配置指定处理人"); + } + + var nameMap = await userDisplayNameResolver.ResolveManyAsync([userId]); + var displayName = OmsRbacUserDisplayNameResolver.FormatUserId(userId, nameMap); + + return new IssueHandlerResolution + { + HandlerType = IssueHandlerTypeCodes.User, + HandlerUserId = userId, + HandlerNames = displayName, + NotifyUserIds = [userId] + }; + } +} diff --git a/src/Oms.Application/Services/Orders/Issues/OrderExceptionWorkflowService.cs b/src/Oms.Application/Services/Orders/Issues/OrderExceptionWorkflowService.cs index d8b41ac..374b18a 100644 --- a/src/Oms.Application/Services/Orders/Issues/OrderExceptionWorkflowService.cs +++ b/src/Oms.Application/Services/Orders/Issues/OrderExceptionWorkflowService.cs @@ -1,3 +1,4 @@ +using Fake.Application; using Fake.DependencyInjection; using Oms.Domain.ChannelsAggregate.Consts; using Oms.Domain.ChannelsAggregate.Entities; @@ -21,6 +22,8 @@ public sealed class ProblematicMarkRequest public string? NotifyMethod { get; set; } + public string? HandlerNames { get; set; } + public string? Remark { get; set; } public IEnumerable? ExtraReceiverUserIds { get; set; } @@ -30,6 +33,7 @@ public class OrderExceptionWorkflowService( IOrderRepository orderRepository, IOrderExceptionEventRepository orderExceptionEventRepository, IIssueTemplateRepository issueTemplateRepository, + IssueHandlerResolver issueHandlerResolver, OrderIssueNotificationService issueNotificationService) : IScopedDependency { public async Task TryMarkProblematicAsync( @@ -43,13 +47,40 @@ public class OrderExceptionWorkflowService( return OrderExceptionStatusRules.GetForbiddenReason(order.OrderStatus); } + IssueTemplate? template = null; + if (request.IssueTemplateId is int templateId && templateId > 0) + { + template = await issueTemplateRepository.FirstOrDefaultAsync(x => x.Id == templateId); + } + + IssueHandlerResolution handlerResolution; + try + { + handlerResolution = await issueHandlerResolver.ResolveAsync(order, template, request.HandlerNames); + } + catch (BusinessException ex) + { + return ex.Message; + } + var context = IssuePlaceholderContext.FromOrder(order, request.IssueType, request.Title); var renderedTitle = IssuePlaceholderRenderer.Render(request.Title, context); var renderedContent = IssuePlaceholderRenderer.Render(request.Content, context); + var notifyMethod = request.NotifyMethod; + if (IssueHandlerTypeCodes.IsCustomer(handlerResolution.HandlerType)) + { + notifyMethod = IssueNotifyMethodCodes.InApp; + } + var fromStatus = order.OrderStatus; - order.PreviousOrderStatus = fromStatus; - order.OrderStatus = OrderStatusCodes.Problematic; + var isAppend = string.Equals(fromStatus, OrderStatusCodes.Problematic, StringComparison.OrdinalIgnoreCase); + if (!isAppend) + { + order.PreviousOrderStatus = fromStatus; + order.OrderStatus = OrderStatusCodes.Problematic; + } + order.HandleStatus = OrderHandleStatusCodes.Pending; order.IssueType = request.IssueType; order.IssueTitle = renderedTitle; @@ -76,18 +107,25 @@ public class OrderExceptionWorkflowService( Title = renderedTitle, Content = renderedContent, IssueTemplateId = request.IssueTemplateId, - NotifyMethod = request.NotifyMethod, + NotifyMethod = notifyMethod, + HandlerNames = handlerResolution.HandlerNames, + HandlerType = handlerResolution.HandlerType, + HandlerUserId = handlerResolution.HandlerUserId, Remark = request.Remark }); - if (sendNotification) + if (sendNotification && !string.IsNullOrWhiteSpace(notifyMethod)) { + var notifyUserIds = handlerResolution.NotifyUserIds.Count > 0 + ? handlerResolution.NotifyUserIds + : null; await issueNotificationService.DispatchAsync( order, renderedTitle, renderedContent, - request.NotifyMethod, + notifyMethod, operatorUserId, + notifyUserIds, request.ExtraReceiverUserIds); } diff --git a/src/Oms.Application/Services/Orders/Issues/OrderFormulaFieldResolver.cs b/src/Oms.Application/Services/Orders/Issues/OrderFormulaFieldResolver.cs index c62bc0b..077a4bf 100644 --- a/src/Oms.Application/Services/Orders/Issues/OrderFormulaFieldResolver.cs +++ b/src/Oms.Application/Services/Orders/Issues/OrderFormulaFieldResolver.cs @@ -123,10 +123,29 @@ public static class OrderFormulaFieldResolver "DeclaredCurrency" => input.DeclaredCurrency, "DeclaredSum" => input.DeclaredSum, "Quantity" => input.Quantity, + "IsRemote" => input.IsRemote, + "AdditionalServices" => SerializeAdditionalServices(input.AdditionalServices), _ => null }; } + private static string? SerializeAdditionalServices(List? codes) + { + if (codes == null || codes.Count == 0) + { + return null; + } + + var normalized = codes + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Select(x => x.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + return normalized.Count == 0 + ? null + : global::System.Text.Json.JsonSerializer.Serialize(normalized); + } + private static object? ResolveRecipientField(string field, OrderRuleEvaluationContext context) { if (context.Recipient != null) diff --git a/src/Oms.Application/Services/Orders/Issues/OrderIssueNotificationService.cs b/src/Oms.Application/Services/Orders/Issues/OrderIssueNotificationService.cs index e7730d0..7732dcd 100644 --- a/src/Oms.Application/Services/Orders/Issues/OrderIssueNotificationService.cs +++ b/src/Oms.Application/Services/Orders/Issues/OrderIssueNotificationService.cs @@ -29,6 +29,7 @@ public class OrderIssueNotificationService( string content, string? notifyMethodCsv, int operatorUserId, + IEnumerable? primaryReceiverUserIds = null, IEnumerable? extraReceiverUserIds = null) { var methods = IssueNotifyMethodCodes.ParseList(notifyMethodCsv); @@ -50,7 +51,7 @@ public class OrderIssueNotificationService( switch (method) { case IssueNotifyMethodCodes.InApp: - await SendInAppAsync(order, customer, title, content, extraReceiverUserIds); + await SendInAppAsync(order, customer, title, content, primaryReceiverUserIds, extraReceiverUserIds); break; case IssueNotifyMethodCodes.Email: await SendEmailAsync(order, customer, title, content, operatorUserId); @@ -81,19 +82,44 @@ public class OrderIssueNotificationService( Customer? customer, string title, string content, + IEnumerable? primaryReceiverUserIds, IEnumerable? extraReceiverUserIds) { var receiverIds = new HashSet(); - if (customer is { UserId: > 0 }) + if (primaryReceiverUserIds != null) { - receiverIds.Add(customer.UserId); + foreach (var userId in primaryReceiverUserIds) + { + if (userId > 0) + { + receiverIds.Add(userId); + } + } } - foreach (var userId in extraReceiverUserIds ?? []) + if (receiverIds.Count == 0) { - if (userId > 0) + if (customer is { UserId: > 0 }) { - receiverIds.Add(userId); + receiverIds.Add(customer.UserId); + } + + foreach (var userId in extraReceiverUserIds ?? []) + { + if (userId > 0) + { + receiverIds.Add(userId); + } + } + } + else + { + foreach (var userId in extraReceiverUserIds ?? []) + { + if (userId > 0) + { + receiverIds.Add(userId); + } } } diff --git a/src/Oms.Application/Services/Orders/OrderService.BatchJob.cs b/src/Oms.Application/Services/Orders/OrderService.BatchJob.cs index a82e40e..61120b2 100644 --- a/src/Oms.Application/Services/Orders/OrderService.BatchJob.cs +++ b/src/Oms.Application/Services/Orders/OrderService.BatchJob.cs @@ -166,6 +166,13 @@ public partial class OrderService public Task BatchMarkProblematicAsync([FromBody] OrderBatchJobCreateInput input) => EnqueueOrderBatchAsync(OrderBatchActionCodes.MarkProblematic, input); + /// + /// 异步批量重新排货。 + /// + [HttpPost("/order/batch/reallocate")] + public Task BatchReallocateAsync([FromBody] OrderBatchJobCreateInput input) => + EnqueueOrderBatchAsync(OrderBatchActionCodes.Reallocate, input); + /// /// 异步批量标记已认领。 /// diff --git a/src/Oms.Application/Services/Orders/OrderService.BatchWorker.cs b/src/Oms.Application/Services/Orders/OrderService.BatchWorker.cs index 97b5db7..d15d384 100644 --- a/src/Oms.Application/Services/Orders/OrderService.BatchWorker.cs +++ b/src/Oms.Application/Services/Orders/OrderService.BatchWorker.cs @@ -86,27 +86,12 @@ public partial class OrderService ?? throw new BusinessException("理赔件参数无效"); var payload = NormalizeClaimedPayload(input); var order = await GetOrderOrThrowAsync(orderId); - - if (!OrderExceptionStatusRules.CanMarkException(order.OrderStatus)) - { - throw new BusinessException(OrderExceptionStatusRules.GetForbiddenReason(order.OrderStatus)); - } - var fromStatus = order.OrderStatus; - order.PreviousOrderStatus = fromStatus; - order.OrderStatus = OrderStatusCodes.Claimed; - order.HandleStatus = OrderHandleStatusCodes.Pending; - order.ClaimType = payload.ClaimType; - order.ClaimAmount = payload.ClaimAmount; - order.ClaimCurrency = payload.ClaimCurrency; - order.ClaimReason = payload.ClaimReason; - order.ClaimTime = DateTime.Now; - order.IssueType = null; - order.IssueTitle = null; - order.IssueContent = null; - order.IssueTemplateId = null; - order.IssueRemark = null; - order.IssueTime = null; + var reason = TryApplyClaimed(order, payload); + if (!string.IsNullOrWhiteSpace(reason)) + { + throw new BusinessException(reason); + } await OrderRepository.UpdateAsync(order); await OrderExceptionEventRepository.InsertAsync(new OrderExceptionEvent @@ -117,14 +102,26 @@ public partial class OrderService ToStatus = OrderStatusCodes.Claimed, FromHandleStatus = null, ToHandleStatus = OrderHandleStatusCodes.Pending, - ClaimType = payload.ClaimType, - ClaimAmount = payload.ClaimAmount, - ClaimCurrency = payload.ClaimCurrency, - ClaimReason = payload.ClaimReason, + ClaimType = order.ClaimType, + ClaimAmount = order.ClaimAmount, + ClaimCurrency = order.ClaimCurrency, + ClaimReason = order.ClaimReason, Remark = payload.Remark, }); } + internal async Task ReallocateForBatchAsync( + int orderId, + string? payloadJson, + CancellationToken cancellationToken = default) + { + _ = cancellationToken; + var input = DeserializeBatchPayload(payloadJson) + ?? throw new BusinessException("重新排货参数无效"); + var order = await GetOrderOrThrowAsync(orderId); + await ReallocateCoreAsync(order, input.Scheme, input.ServiceChannelId); + } + internal async Task UpdateHandleStatusForBatchAsync( int orderId, string? payloadJson, diff --git a/src/Oms.Application/Services/Orders/OrderService.Exception.cs b/src/Oms.Application/Services/Orders/OrderService.Exception.cs index 502ea6f..bb48203 100644 --- a/src/Oms.Application/Services/Orders/OrderService.Exception.cs +++ b/src/Oms.Application/Services/Orders/OrderService.Exception.cs @@ -3,6 +3,7 @@ using Fake.Domain.Exceptions; using Microsoft.AspNetCore.Mvc; using Oms.Application.Dtos.Orders; using Oms.Application.Services.Orders.Issues; +using Oms.Application.Shared; using Oms.Domain.ChannelsAggregate.Consts; using Oms.Domain.ChannelsAggregate.Entities; using Oms.Domain.ChannelsAggregate.Repositories; @@ -40,6 +41,7 @@ public partial class OrderService Content = payload.Content, IssueTemplateId = payload.IssueTemplateId, NotifyMethod = payload.NotifyMethod, + HandlerNames = payload.HandlerNames, Remark = payload.Remark }; @@ -55,30 +57,7 @@ public partial class OrderService var payload = NormalizeClaimedPayload(input); return await ExecuteExceptionBatchAsync( input.OrderIds, - order => - { - if (!OrderExceptionStatusRules.CanMarkException(order.OrderStatus)) - { - return OrderExceptionStatusRules.GetForbiddenReason(order.OrderStatus); - } - - var fromStatus = order.OrderStatus; - order.PreviousOrderStatus = fromStatus; - order.OrderStatus = OrderStatusCodes.Claimed; - order.HandleStatus = OrderHandleStatusCodes.Pending; - order.ClaimType = payload.ClaimType; - order.ClaimAmount = payload.ClaimAmount; - order.ClaimCurrency = payload.ClaimCurrency; - order.ClaimReason = payload.ClaimReason; - order.ClaimTime = DateTime.Now; - order.IssueType = null; - order.IssueTitle = null; - order.IssueContent = null; - order.IssueTemplateId = null; - order.IssueRemark = null; - order.IssueTime = null; - return null; - }, + order => TryApplyClaimed(order, payload), (order, remark) => new OrderExceptionEvent { OrderId = order.Id, @@ -87,10 +66,10 @@ public partial class OrderService ToStatus = OrderStatusCodes.Claimed, FromHandleStatus = null, ToHandleStatus = OrderHandleStatusCodes.Pending, - ClaimType = payload.ClaimType, - ClaimAmount = payload.ClaimAmount, - ClaimCurrency = payload.ClaimCurrency, - ClaimReason = payload.ClaimReason, + ClaimType = order.ClaimType, + ClaimAmount = order.ClaimAmount, + ClaimCurrency = order.ClaimCurrency, + ClaimReason = order.ClaimReason, Remark = remark }, payload.Remark); @@ -138,6 +117,154 @@ public partial class OrderService input.Remark?.Trim()); } + /// + /// 订单问题处理记录列表(mark_problematic 事件,支持一单多条)。 + /// + [HttpGet("/order/exception-events/list")] + public async Task GetExceptionEventListAsync([FromQuery] int orderId) + { + if (orderId <= 0) + { + throw new BusinessException("订单Id无效"); + } + + await GetOrderOrThrowAsync(orderId); + var events = await OrderExceptionEventRepository.GetListAsync(x => + x.OrderId == orderId && x.EventType == OrderExceptionEventTypeCodes.MarkProblematic); + events = events.OrderByDescending(x => x.CreateTime).ThenByDescending(x => x.Id).ToList(); + + var userIds = events + .SelectMany(x => new int?[] { x.CreateUserId, x.UpdateUserId, x.HandlerUserId }) + .Where(x => x is > 0) + .Select(x => x!.Value) + .Distinct(); + var auditUserNameMap = await UserDisplayNameResolver.ResolveManyAsync(userIds); + + var items = events.Select(evt => MapExceptionEventOutput(evt, auditUserNameMap)).ToList(); + return new OrderExceptionEventListOutput + { + Items = items, + PendingCount = items.Count(x => OrderHandleStatusCodes.IsPending(x.HandleStatus)), + ProcessedCount = items.Count(x => OrderHandleStatusCodes.IsProcessed(x.HandleStatus)) + }; + } + + /// + /// 单条问题标记已处理。 + /// + [HttpPost("/order/exception-event/process")] + public async Task ProcessExceptionEventAsync([FromBody] OrderExceptionEventProcessInput input) + { + if (input.Id <= 0) + { + throw new BusinessException("问题记录Id无效"); + } + + var evt = await OrderExceptionEventRepository.FirstOrDefaultAsync(x => x.Id == input.Id); + if (evt == null || !string.Equals(evt.EventType, OrderExceptionEventTypeCodes.MarkProblematic, StringComparison.OrdinalIgnoreCase)) + { + throw new BusinessException("问题记录不存在"); + } + + await GetOrderOrThrowAsync(evt.OrderId); + if (OrderHandleStatusCodes.IsProcessed(evt.ToHandleStatus)) + { + throw new BusinessException("该问题已处理"); + } + + var remark = input.Remark?.Trim(); + if (!string.IsNullOrWhiteSpace(remark) && remark.Length > 512) + { + throw new BusinessException("备注长度不能超过512"); + } + + var operatorUserId = CurrentUser.GetId(); + evt.ToHandleStatus = OrderHandleStatusCodes.Processed; + evt.UpdateUserId = operatorUserId; + evt.UpdateTime = DateTime.Now; + if (!string.IsNullOrWhiteSpace(remark)) + { + evt.Remark = remark; + } + + await OrderExceptionEventRepository.UpdateAsync(evt); + await OrderExceptionEventRepository.InsertAsync(new OrderExceptionEvent + { + OrderId = evt.OrderId, + EventType = OrderExceptionEventTypeCodes.HandleProcessed, + FromStatus = OrderStatusCodes.Problematic, + ToStatus = OrderStatusCodes.Problematic, + FromHandleStatus = OrderHandleStatusCodes.Pending, + ToHandleStatus = OrderHandleStatusCodes.Processed, + IssueType = evt.IssueType, + Title = evt.Title, + Content = evt.Content, + Remark = remark + }); + + await SyncOrderHandleStatusFromEventsAsync(evt.OrderId); + } + + private async Task SyncOrderHandleStatusFromEventsAsync(int orderId) + { + var order = await GetOrderOrThrowAsync(orderId); + if (order.OrderStatus is not (OrderStatusCodes.Problematic or OrderStatusCodes.Claimed)) + { + return; + } + + var issues = await OrderExceptionEventRepository.GetListAsync(x => + x.OrderId == orderId && x.EventType == OrderExceptionEventTypeCodes.MarkProblematic); + if (issues.Count == 0) + { + return; + } + + var anyPending = issues.Any(x => OrderHandleStatusCodes.IsPending(x.ToHandleStatus)); + order.HandleStatus = anyPending ? OrderHandleStatusCodes.Pending : OrderHandleStatusCodes.Processed; + order.UpdateTime = DateTime.Now; + await OrderRepository.UpdateAsync(order); + } + + private static OrderExceptionEventOutput MapExceptionEventOutput( + OrderExceptionEvent evt, + IReadOnlyDictionary auditUserNameMap) + { + var notifyCodes = IssueNotifyMethodCodes.ParseList(evt.NotifyMethod); + var notifyNames = notifyCodes.Count == 0 + ? string.Empty + : string.Join('、', notifyCodes.Select(IssueNotifyMethodCodes.GetDisplayName)); + + return new OrderExceptionEventOutput + { + Id = evt.Id, + OrderId = evt.OrderId, + EventType = evt.EventType, + IssueType = evt.IssueType, + IssueTypeName = IssueTypeCodes.GetDisplayName(evt.IssueType), + Title = evt.Title, + Content = evt.Content, + NotifyMethod = evt.NotifyMethod, + NotifyMethodNames = notifyNames, + HandlerNames = evt.HandlerNames + ?? (evt.HandlerUserId is int handlerUserId && handlerUserId > 0 + ? OmsRbacUserDisplayNameResolver.FormatUserId(handlerUserId, auditUserNameMap) + : null), + HandlerType = evt.HandlerType, + HandlerTypeName = IssueHandlerTypeCodes.GetDisplayName(evt.HandlerType), + HandlerUserId = evt.HandlerUserId, + HandleStatus = evt.ToHandleStatus, + HandleStatusName = OrderHandleStatusCodes.GetDisplayName(evt.ToHandleStatus), + CreateBy = OmsRbacUserDisplayNameResolver.FormatUserId(evt.CreateUserId, auditUserNameMap), + CreateTime = evt.CreateTime, + ProcessedBy = OrderHandleStatusCodes.IsProcessed(evt.ToHandleStatus) + ? OmsRbacUserDisplayNameResolver.FormatUserId(evt.UpdateUserId, auditUserNameMap) + : null, + ProcessedTime = OrderHandleStatusCodes.IsProcessed(evt.ToHandleStatus) ? evt.UpdateTime : null, + Remark = evt.Remark + }; + } + private async Task ExecuteProblematicBatchAsync( IReadOnlyCollection orderIds, ProblematicMarkRequest request) @@ -294,6 +421,12 @@ public partial class OrderService throw new BusinessException("备注长度不能超过512"); } + var handlerNames = input.HandlerNames?.Trim(); + if (!string.IsNullOrWhiteSpace(handlerNames) && handlerNames.Length > 256) + { + throw new BusinessException("处理人长度不能超过256"); + } + return new ResolvedProblematicPayload { IssueType = issueType, @@ -301,6 +434,7 @@ public partial class OrderService Content = content, IssueTemplateId = template?.Id, NotifyMethod = template == null ? null : IssueNotifyMethodCodes.Normalize(template.NotifyMethod), + HandlerNames = string.IsNullOrWhiteSpace(handlerNames) ? null : handlerNames, Remark = remark }; } @@ -319,12 +453,7 @@ public partial class OrderService } var currency = input.ClaimCurrency?.Trim().ToUpperInvariant(); - if (string.IsNullOrWhiteSpace(currency)) - { - throw new BusinessException("索赔币种不能为空"); - } - - if (currency.Length > 16) + if (!string.IsNullOrWhiteSpace(currency) && currency.Length > 16) { throw new BusinessException("索赔币种长度不能超过16"); } @@ -350,12 +479,71 @@ public partial class OrderService { ClaimType = claimType, ClaimAmount = input.ClaimAmount.Value, - ClaimCurrency = currency, + ClaimCurrency = string.IsNullOrWhiteSpace(currency) ? null : currency, ClaimReason = reason, Remark = remark }; } + /// + /// 按订单附加服务/申报金额校验并写入理赔字段。 + /// + private static string? TryApplyClaimed(Order order, ResolvedClaimedPayload payload) + { + if (!OrderExceptionStatusRules.CanMarkException(order.OrderStatus)) + { + return OrderExceptionStatusRules.GetForbiddenReason(order.OrderStatus); + } + + if (order.DeclaredSum is > 0 && payload.ClaimAmount > order.DeclaredSum.Value) + { + return "索赔金额不能超过申报金额"; + } + + var hasInsurance = ParseAdditionalServiceCodes(order.AdditionalServices) + .Contains("insurance"); + var currency = payload.ClaimCurrency; + if (string.IsNullOrWhiteSpace(currency)) + { + if (hasInsurance && !string.IsNullOrWhiteSpace(order.DeclaredCurrency)) + { + currency = order.DeclaredCurrency.Trim().ToUpperInvariant(); + } + else + { + return "索赔币种不能为空"; + } + } + + var fromStatus = order.OrderStatus; + order.PreviousOrderStatus = fromStatus; + order.OrderStatus = OrderStatusCodes.Claimed; + order.HandleStatus = OrderHandleStatusCodes.Pending; + order.ClaimType = payload.ClaimType; + order.ClaimAmount = payload.ClaimAmount; + order.ClaimCurrency = currency; + order.ClaimReason = payload.ClaimReason; + order.ClaimTime = DateTime.Now; + order.IssueType = null; + order.IssueTitle = null; + order.IssueContent = null; + order.IssueTemplateId = null; + order.IssueTime = null; + if (!hasInsurance) + { + const string uninsuredPrefix = "[未购保险]"; + order.IssueRemark = string.IsNullOrWhiteSpace(payload.Remark) + ? uninsuredPrefix + : $"{uninsuredPrefix}{payload.Remark}"; + } + else + { + order.IssueRemark = null; + } + + return null; + } + private sealed class ResolvedProblematicPayload { public string IssueType { get; set; } = string.Empty; @@ -368,6 +556,8 @@ public partial class OrderService public string? NotifyMethod { get; set; } + public string? HandlerNames { get; set; } + public string? Remark { get; set; } } @@ -377,7 +567,7 @@ public partial class OrderService public decimal ClaimAmount { get; set; } - public string ClaimCurrency { get; set; } = string.Empty; + public string? ClaimCurrency { get; set; } public string ClaimReason { get; set; } = string.Empty; diff --git a/src/Oms.Application/Services/Orders/OrderService.Helpers.cs b/src/Oms.Application/Services/Orders/OrderService.Helpers.cs index f40183d..8b14ed7 100644 --- a/src/Oms.Application/Services/Orders/OrderService.Helpers.cs +++ b/src/Oms.Application/Services/Orders/OrderService.Helpers.cs @@ -14,9 +14,11 @@ using Oms.Application.Services.Orders.Templates; using Oms.Application.Shared; using Oms.Domain.OrdersAggregate; using Oms.Domain.ChannelsAggregate.Consts; +using Oms.Domain.ChannelsAggregate.Entities; using Oms.Domain.OrdersAggregate.Consts; using Oms.Domain.OrdersAggregate.Entities; using Oms.Domain.SystemAggregate.Entities; +using Oms.Domain.WarehouseAggregate.Consts; namespace Oms.Application.Services.Orders; @@ -89,6 +91,21 @@ public partial class OrderService : await CustomerRepository.GetListAsync(x => customerIds.Contains(x.Id)); var customerMap = customers.ToDictionary(x => x.Id); + var pickupOrderIds = orders + .Where(x => x.PickupOrderId is > 0) + .Select(x => x.PickupOrderId!.Value) + .Distinct() + .ToArray(); + var pickupOrders = pickupOrderIds.Length == 0 + ? [] + : await PickupOrderRepository.GetListAsync(x => pickupOrderIds.Contains(x.Id)); + var pickupNoMap = pickupOrders.ToDictionary(x => x.Id, x => x.PickupNo); + var carrierWaybillNoMap = pickupOrders + .Where(x => !string.IsNullOrWhiteSpace(x.CarrierWaybillNo)) + .ToDictionary(x => x.Id, x => x.CarrierWaybillNo!); + + var bindSummaryMap = await LoadStockBindListSummariesAsync(orderIds); + var outputs = orders.Select(order => { senderMap.TryGetValue(order.Id, out var sender); @@ -101,6 +118,10 @@ public partial class OrderService var receivableAmount = feeOutputs .Where(x => x.Type == OrderFeeTypeCodes.Receivable) .Sum(x => x.Amount); + var additionalServices = NormalizeAdditionalServiceCodes( + OmsDocHelper.DeserializeJson>(order.AdditionalServices)); + var hasInsurance = additionalServices.Any(x => + string.Equals(x, "insurance", StringComparison.OrdinalIgnoreCase)); string? customerName = null; string? customerCode = null; if (order.CustomerId is > 0 && customerMap.TryGetValue(order.CustomerId.Value, out var customer)) @@ -109,6 +130,14 @@ public partial class OrderService customerCode = customer.CustomerCode; } + SalesProduct? product = null; + if (!string.IsNullOrWhiteSpace(order.ProductCode)) + { + productMap.TryGetValue(order.ProductCode.Trim(), out product); + } + + bindSummaryMap.TryGetValue(order.Id, out var bindSummary); + return new OrderOutput { Id = order.Id, @@ -117,10 +146,8 @@ public partial class OrderService DownstreamServiceNo = order.DownstreamServiceNo, ServiceNo = order.ServiceNo, ProductCode = order.ProductCode, - ProductName = !string.IsNullOrWhiteSpace(order.ProductCode) - && productMap.TryGetValue(order.ProductCode.Trim(), out var product) - ? product.ProductName - : null, + ProductName = product?.ProductName, + MaxTimeliness = product?.MaxTimeliness, ChannelCode = order.ChannelCode, DownstreamSupplierCode = order.DownstreamSupplierCode, DownstreamAppKey = order.DownstreamAppKey, @@ -145,6 +172,31 @@ public partial class OrderService : order.OrderSource, PickupTime = order.PickupTime, CustomerSenderAddressId = order.CustomerSenderAddressId, + InboundMethod = order.InboundMethod, + FulfillmentType = string.IsNullOrWhiteSpace(order.FulfillmentType) + ? FulfillmentTypeCodes.Direct + : order.FulfillmentType, + FulfillmentSource = order.FulfillmentSource, + StockBindStatus = bindSummary?.BindStatus ?? "none", + StockBindLineCount = bindSummary?.LineCount ?? 0, + StockBindQtyTotal = bindSummary?.QtyTotal ?? 0, + DomesticTrackingNos = bindSummary?.TrackingNosText, + FulfillProgress = FulfillmentProgressCodes.Resolve( + FulfillmentTypeCodes.IsWarehouse(order.FulfillmentType), + bindSummary?.BindStatus ?? "none", + bindSummary?.LineCount ?? 0, + bindSummary?.HasInTransitParcel ?? false), + PrimaryBinCode = bindSummary?.PrimaryBinCode, + PrimarySkuCodes = bindSummary?.PrimarySkuCodes, + PickupOrderId = order.PickupOrderId, + PickupNo = order.PickupOrderId is > 0 + && pickupNoMap.TryGetValue(order.PickupOrderId.Value, out var pickupNo) + ? pickupNo + : null, + CarrierWaybillNo = order.PickupOrderId is > 0 + && carrierWaybillNoMap.TryGetValue(order.PickupOrderId.Value, out var carrierWaybillNo) + ? carrierWaybillNo + : null, RequestId = order.RequestId, ExportCustomsMode = order.ExportCustomsMode, PredeclareFailReason = string.IsNullOrWhiteSpace(order.PredeclareFailReason) @@ -153,6 +205,10 @@ public partial class OrderService AllocationPendingReason = string.IsNullOrWhiteSpace(order.AllocationPendingReason) ? null : order.AllocationPendingReason.Trim(), + AllocationScheme = string.IsNullOrWhiteSpace(order.AllocationScheme) + ? null + : order.AllocationScheme.Trim(), + HasAllocationTrace = !string.IsNullOrWhiteSpace(order.AllocationTraceJson), DeclaredCurrency = order.DeclaredCurrency, DeclaredSum = order.DeclaredSum, Quantity = order.Quantity, @@ -186,6 +242,10 @@ public partial class OrderService SignTime = order.SignTime, IsIntercept = order.IsIntercept > 0, IsRemote = order.IsRemote > 0, + AdditionalServices = additionalServices, + HasInsurance = hasInsurance, + ForecastReceivableAmount = order.ForecastReceivableAmount, + ForecastPayableAmount = order.ForecastPayableAmount, CreateTime = order.CreateTime, CreateBy = OmsRbacUserDisplayNameResolver.FormatUserId(order.CreateUserId, auditUserNameMap), UpdateTime = OmsDocHelper.NullIfDefault(order.UpdateTime), @@ -208,6 +268,102 @@ public partial class OrderService return outputs; } + private sealed class StockBindListSummary + { + public string BindStatus { get; init; } = "none"; + + public int LineCount { get; init; } + + public int QtyTotal { get; init; } + + public string? TrackingNosText { get; init; } + + public bool HasInTransitParcel { get; init; } + + public string? PrimaryBinCode { get; init; } + + public string? PrimarySkuCodes { get; init; } + } + + private async Task> LoadStockBindListSummariesAsync(int[] orderIds) + { + if (orderIds.Length == 0) + { + return new Dictionary(); + } + + var binds = await OrderStockBindRepository.GetListAsync(x => + orderIds.Contains(x.OrderId) + && (x.Status == OrderStockBindStatusCodes.Bound || x.Status == OrderStockBindStatusCodes.Deducted)); + + var parcelIds = binds + .Where(x => x.ParcelId is > 0) + .Select(x => x.ParcelId!.Value) + .Distinct() + .ToArray(); + var parcels = parcelIds.Length == 0 + ? [] + : await StockBindParcelRepository.GetListAsync(x => parcelIds.Contains(x.Id)); + var parcelLifecycleMap = parcels.ToDictionary(x => x.Id, x => x.LifecycleStatus); + + var binIds = binds + .Where(x => x.BinLocationId is > 0) + .Select(x => x.BinLocationId!.Value) + .Distinct() + .ToArray(); + var bins = binIds.Length == 0 + ? [] + : await StockBindBinLocationRepository.GetListAsync(x => binIds.Contains(x.Id)); + var binCodeMap = bins.ToDictionary(x => x.Id, x => x.BinCode); + + return binds + .GroupBy(x => x.OrderId) + .ToDictionary( + g => g.Key, + g => + { + var rows = g.ToList(); + var bindStatus = rows.Any(x => x.Status == OrderStockBindStatusCodes.Deducted) + ? OrderStockBindStatusCodes.Deducted + : OrderStockBindStatusCodes.Bound; + var trackingNos = rows + .Select(x => x.TrackingNo?.Trim()) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + var hasInTransitParcel = rows.Any(row => + row.ParcelId is > 0 + && parcelLifecycleMap.TryGetValue(row.ParcelId.Value, out var lifecycle) + && string.Equals( + lifecycle, + WarehouseParcelLifecycleCodes.InTransit, + StringComparison.OrdinalIgnoreCase)); + var primaryBinCode = rows + .Where(row => row.BinLocationId is > 0 + && binCodeMap.TryGetValue(row.BinLocationId.Value, out _)) + .Select(row => binCodeMap[row.BinLocationId!.Value]) + .Where(code => !string.IsNullOrWhiteSpace(code)) + .OrderBy(code => code, StringComparer.OrdinalIgnoreCase) + .FirstOrDefault(); + var skuCodes = rows + .Select(row => row.SkuCode?.Trim()) + .Where(code => !string.IsNullOrWhiteSpace(code)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(code => code, StringComparer.OrdinalIgnoreCase) + .ToArray(); + return new StockBindListSummary + { + BindStatus = bindStatus, + LineCount = rows.Count, + QtyTotal = rows.Sum(x => x.BindQty), + TrackingNosText = trackingNos.Length == 0 ? null : string.Join(", ", trackingNos), + HasInTransitParcel = hasInTransitParcel, + PrimaryBinCode = primaryBinCode, + PrimarySkuCodes = skuCodes.Length == 0 ? null : string.Join(", ", skuCodes), + }; + }); + } + private static void RedactChannelFieldsForCustomer(IEnumerable outputs) { foreach (var output in outputs) @@ -387,7 +543,7 @@ public partial class OrderService var template = await OrderTemplateRepository.FirstOrDefaultAsync(x => x.Id == input.TemplateId) ?? throw new BusinessException("模板不存在"); - var effectiveCustomer = await ResolveEffectiveCustomerAsync(); + var effectiveCustomer = await ResolveEffectiveCustomerAsync(input.CustomerId); EnsureTemplateAccessible(template, effectiveCustomer.Id); OrderTemplateImportMapping.EnsureTemplateReadyForImport(template); @@ -586,6 +742,8 @@ public partial class OrderService Amount = x.Amount, Weight = x.Weight, HsCode = x.ExHsCode ?? x.ImHsCode ?? x.HsCode, + ImHsCode = x.ImHsCode ?? x.HsCode, + ExHsCode = x.ExHsCode ?? x.HsCode, SkuImage = x.SkuImage, Category = x.Category, Brand = x.Brand, diff --git a/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs b/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs index 63b583e..61c9183 100644 --- a/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs +++ b/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs @@ -1,8 +1,11 @@ using Fake.Application; using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; using Oms.Application.Dtos.Channels; using Oms.Application.Dtos.Orders; +using Oms.Application.Dtos.Shared; using Oms.Application.Shared; +using Oms.Domain.ChannelsAggregate.Consts; using Oms.Domain.ChannelsAggregate.Entities; using Oms.Domain.ChannelsAggregate.Repositories; using Oms.Domain.CustomersAggregate.Enums; @@ -230,6 +233,7 @@ public partial class OrderService public async Task RecalculateReceivableFeesAsync(OrderActionInput input) { var order = await GetOrderOrThrowAsync(input.Id); + EnsureReceivableMutable(order); await RecalculateReceivableCoreAsync(order); return (await MapOrderOutputsAsync([order])).First(); } @@ -245,6 +249,349 @@ public partial class OrderService return (await MapOrderOutputsAsync([order])).First(); } + /// + /// 重跑入库计费(应收 wipe+upsert + 排货应付)。用于队列投递失败或待排货补救。 + /// + [HttpPost("/order/fee/rerun-inbound-billing")] + public async Task RerunInboundBillingAsync(OrderActionInput input) + { + var order = await GetOrderOrThrowAsync(input.Id); + await ProcessInboundBillingForBatchAsync(order.Id); + order = await GetOrderOrThrowAsync(input.Id); + return (await MapOrderOutputsAsync([order])).First(); + } + + /// + /// 查询排货过程:优先返回快照;无快照或 live=true 时按当前规则现算(不落库)。 + /// + [HttpGet("/order/allocation-trace")] + public async Task GetAllocationTraceAsync( + [FromQuery] int id, + [FromQuery] bool live = false) + { + var order = await GetOrderOrThrowAsync(id); + if (!live && !string.IsNullOrWhiteSpace(order.AllocationTraceJson)) + { + try + { + var snapshot = JsonConvert.DeserializeObject(order.AllocationTraceJson); + if (snapshot != null) + { + snapshot.OrderId = order.Id; + snapshot.FromSnapshot = true; + snapshot.TraceTime = order.AllocationTraceTime ?? snapshot.TraceTime; + if (string.IsNullOrWhiteSpace(snapshot.Scheme)) + { + snapshot.Scheme = order.AllocationScheme; + snapshot.SchemeName = ResolveAllocationSchemeName(order.AllocationScheme); + } + + snapshot.Candidates = SortAllocationCandidates(snapshot.Scheme, snapshot.Candidates ?? []); + return snapshot; + } + } + catch + { + // 快照损坏则走现算 + } + } + + return await BuildLiveAllocationTraceAsync(order); + } + + private async Task BuildLiveAllocationTraceAsync(Order order) + { + if (string.IsNullOrWhiteSpace(order.ProductCode)) + { + return new OrderAllocationTraceOutput + { + OrderId = order.Id, + FromSnapshot = false, + FailReason = "订单未绑定销售产品", + TraceTime = DateTime.Now + }; + } + + var product = await SalesProductRepository.GetByProductCodeAsync(order.ProductCode.Trim()); + if (product == null) + { + return new OrderAllocationTraceOutput + { + OrderId = order.Id, + FromSnapshot = false, + FailReason = "销售产品不存在", + TraceTime = DateTime.Now + }; + } + + try + { + var weights = await OrderRepository.GetWeightsByOrderIdsAsync([order.Id]); + var weightRow = ResolvePayableWeightRow(order, weights); + var chargeable = weightRow.ChargeableWeight ?? 0; + // 现算与重新排货一致:规则分区 + 渠道买价均取当前有效发布。 + var snapshotBinding = await ResolveSnapshotBindingAsync(product, DateTime.Now); + var billing = await ResolveOrderBillingContextAsync( + order, + product, + chargeable, + snapshotBinding); + var (_, chargingStage) = ResolveReceivableBillingStage(order); + + string? schemeOverride = null; + int? forceChannelId = null; + if (AllocationSchemeCodes.IsDesignated(order.AllocationScheme) + && !string.IsNullOrWhiteSpace(order.ChannelCode)) + { + var channel = await ServiceChannelRepository.FirstOrDefaultAsync(x => + x.ChannelCode == order.ChannelCode.Trim()); + if (channel != null) + { + schemeOverride = AllocationSchemeCodes.Designated; + forceChannelId = channel.Id; + } + } + else if (AllocationSchemeCodes.IsAutoScheme(order.AllocationScheme)) + { + schemeOverride = order.AllocationScheme; + } + + var evaluation = await EvaluateAllocationAsync( + order, + product, + billing.SnapshotBinding, + billing.ZoneKeys, + chargeable, + chargingStage, + schemeOverride, + forceChannelId); + + var output = BuildAllocationTraceOutput( + order.Id, + evaluation, + fromSnapshot: false, + selectedChannelCode: evaluation.Selected?.Channel.ChannelCode ?? order.ChannelCode); + output.FromSnapshot = false; + if (string.IsNullOrWhiteSpace(output.FailReason) + && !string.IsNullOrWhiteSpace(order.AllocationPendingReason) + && evaluation.Selected == null) + { + output.FailReason = order.AllocationPendingReason; + } + + return output; + } + catch (Exception ex) + { + return new OrderAllocationTraceOutput + { + OrderId = order.Id, + FromSnapshot = false, + Scheme = order.AllocationScheme, + SchemeName = ResolveAllocationSchemeName(order.AllocationScheme), + FailReason = ex is BusinessException be ? be.Message : ex.Message, + TraceTime = DateTime.Now + }; + } + } + + /// + /// 指定渠道可选项:取选中订单销售产品排货池(含客户过滤)的交集。 + /// + [HttpPost("/order/fee/reallocate-channel-options")] + public async Task> GetReallocateChannelOptionsAsync( + [FromBody] OrderReallocateChannelOptionsInput input) + { + var orderIds = (input.OrderIds ?? []).Where(x => x > 0).Distinct().ToList(); + if (orderIds.Count == 0) + { + return new OmsItemsResult { Items = [] }; + } + + var orders = await OrderRepository.GetListAsync(x => orderIds.Contains(x.Id)); + if (orders.Count == 0) + { + return new OmsItemsResult { Items = [] }; + } + + HashSet? intersection = null; + var channelMeta = new Dictionary(); + + foreach (var order in orders) + { + if (string.IsNullOrWhiteSpace(order.ProductCode)) + { + return new OmsItemsResult { Items = [] }; + } + + var product = await SalesProductRepository.GetByProductCodeAsync(order.ProductCode.Trim()); + if (product == null) + { + return new OmsItemsResult { Items = [] }; + } + + var binding = await ResolveSnapshotBindingAsync(product, DateTime.Now); + var providers = await ResolveAllocationProvidersAsync(product, binding.Rules); + var filtered = AllocationResolver.FilterProviders(providers, order.CustomerId); + var channelIds = new HashSet(); + foreach (var provider in filtered) + { + if (provider.ServiceChannelId is not > 0) + { + continue; + } + + var channelId = provider.ServiceChannelId.Value; + if (!channelMeta.TryGetValue(channelId, out _)) + { + var channel = await ServiceChannelRepository.FirstOrDefaultAsync(x => x.Id == channelId); + if (channel == null || channel.IsActive != EnableStatus.Enabled) + { + continue; + } + + channelMeta[channelId] = (channel.ChannelCode, channel.ChannelName); + } + + channelIds.Add(channelId); + } + + intersection = intersection == null + ? channelIds + : intersection.Intersect(channelIds).ToHashSet(); + + if (intersection.Count == 0) + { + break; + } + } + + var items = (intersection ?? []) + .Where(id => channelMeta.ContainsKey(id)) + .Select(id => new OrderReallocateChannelOptionOutput + { + ServiceChannelId = id, + ChannelCode = channelMeta[id].Code, + ChannelName = channelMeta[id].Name + }) + .OrderBy(x => x.ChannelCode, StringComparer.OrdinalIgnoreCase) + .ToList(); + + return new OmsItemsResult { Items = items }; + } + + /// + /// 单票重新排货:仅重写应付与服务渠道,不动应收。 + /// + [HttpPost("/order/fee/reallocate")] + public async Task ReallocateAsync([FromBody] OrderReallocateInput input) + { + var order = await GetOrderOrThrowAsync(input.Id); + await ReallocateCoreAsync(order, input.Scheme, input.ServiceChannelId); + order = await GetOrderOrThrowAsync(input.Id); + return (await MapOrderOutputsAsync([order])).First(); + } + + /// + /// 批量重新排货(同步兜底,队列关闭时使用)。 + /// + [HttpPost("/order/fee/reallocate-batch")] + public async Task ReallocateBatchAsync([FromBody] OrderReallocateBatchInput input) + { + NormalizeReallocateOptions(input.Scheme, input.ServiceChannelId, out var scheme, out var channelId); + var result = new OrderBatchActionResultOutput(); + var orderIds = (input.OrderIds ?? []).Where(x => x > 0).Distinct().ToList(); + foreach (var orderId in orderIds) + { + try + { + var order = await GetOrderOrThrowAsync(orderId); + await ReallocateCoreAsync(order, scheme, channelId); + result.SuccessCount++; + } + catch (Exception ex) + { + result.Failures.Add(new OrderBatchActionFailureOutput + { + OrderId = orderId, + Reason = ex is BusinessException be ? be.Message : ex.Message + }); + } + } + + return result; + } + + /// + /// 未付款订单更新附加服务并重算当前阶段应收(可选尝试重算应付)。 + /// + [HttpPost("/order/additional-services/update")] + public async Task UpdateAdditionalServicesAsync(OrderAdditionalServicesUpdateInput input) + { + var order = await GetOrderOrThrowAsync(input.Id); + EnsureReceivableMutable(order); + + if (string.IsNullOrWhiteSpace(order.ProductCode)) + { + throw new BusinessException("订单未绑定销售产品,无法更新附加服务"); + } + + var product = await SalesProductRepository.GetByProductCodeAsync(order.ProductCode.Trim()); + if (product == null) + { + throw new BusinessException("销售产品不存在"); + } + + EnsureAdditionalServicesAllowed(product, input.AdditionalServices); + order.AdditionalServices = SerializeAdditionalServices(input.AdditionalServices); + await RebillReceivableAfterAdditionalServicesChangeAsync(order, product); + + order.UpdateTime = DateTime.Now; + await OrderRepository.UpdateAsync(order); + return (await MapOrderOutputsAsync([order])).First(); + } + + /// + /// 附加服务变更后重算当前阶段应收(订单须未付款)。 + /// + private async Task RebillReceivableAfterAdditionalServicesChangeAsync(Order order, SalesProduct product) + { + EnsureReceivableMutable(order); + + var weights = await OrderRepository.GetWeightsByOrderIdsAsync([order.Id]); + var (weightType, chargingStage) = ResolveReceivableBillingStage(order); + var weightRow = weights.FirstOrDefault(x => x.Type == weightType) + ?? throw new BusinessException($"缺少件重尺类型 {weightType}"); + if (!weightRow.ChargeableWeight.HasValue || weightRow.ChargeableWeight <= 0) + { + throw new BusinessException("计费重无效,请先完善件重尺"); + } + + var snapshotBinding = await ResolveSnapshotBindingFromOrderAsync(product, order); + var billing = await ResolveOrderBillingContextAsync( + order, + product, + weightRow.ChargeableWeight ?? 0, + snapshotBinding); + + if (chargingStage == OrderFeeChargingStageCodes.Inbound) + { + await OrderRepository.DeleteReceivableFeesAsync(order.Id); + await UpsertReceivableFeesAsync(order, billing, chargingStage); + } + else + { + await UpsertReceivableFeesAsync( + order, + billing, + chargingStage, + replaceExistingReceivable: true); + } + + await RefreshMarketingPayableAmountAsync(order); + await TryConfirmServiceChannelAndPayableAsync(order, product, billing, chargingStage); + } + /// /// 手动添加订单费用(应收或应付)。 /// @@ -259,6 +606,11 @@ public partial class OrderService throw new BusinessException("费用类型无效"); } + if (type == OrderFeeTypeCodes.Receivable) + { + EnsureReceivableMutable(order); + } + var costItem = input.CostItem?.Trim() ?? string.Empty; if (string.IsNullOrWhiteSpace(costItem)) { @@ -349,6 +701,29 @@ public partial class OrderService private async Task RecalculatePayableCoreAsync(Order order) { + await ReallocateCoreAsync(order, scheme: null, serviceChannelId: null, enforceReallocateGate: false); + } + + /// + /// 重新排货核心:按方案/指定渠道确认服务渠道并重写应付。 + /// + private async Task ReallocateCoreAsync( + Order order, + string? scheme, + int? serviceChannelId, + bool enforceReallocateGate = true) + { + string? schemeOverride = null; + int? forceChannelId = null; + if (enforceReallocateGate) + { + EnsureReallocateAllowed(order); + NormalizeReallocateOptions(scheme, serviceChannelId, out var normalizedScheme, out forceChannelId); + schemeOverride = AllocationSchemeCodes.IsDesignated(normalizedScheme) + ? AllocationSchemeCodes.Designated + : normalizedScheme; + } + if (string.IsNullOrWhiteSpace(order.ProductCode)) { throw new BusinessException("订单未绑定销售产品,无法重算应付"); @@ -367,7 +742,10 @@ public partial class OrderService throw new BusinessException("计费重无效,请先完善件重尺"); } - var snapshotBinding = await ResolveSnapshotBindingFromOrderAsync(product, order); + // 重新排货:产品规则/分区与渠道买价均取当前有效发布,避免沿用下单时旧快照。 + var snapshotBinding = enforceReallocateGate + ? await ResolveSnapshotBindingAsync(product, DateTime.Now) + : await ResolveSnapshotBindingFromOrderAsync(product, order); var billing = await ResolveOrderBillingContextAsync( order, product, @@ -380,7 +758,9 @@ public partial class OrderService order, product, billing, - chargingStage); + chargingStage, + schemeOverride, + forceChannelId); if (string.Equals(order.OrderStatus, OrderStatusCodes.PendingAllocation, StringComparison.OrdinalIgnoreCase)) { @@ -391,6 +771,52 @@ public partial class OrderService await OrderRepository.UpdateAsync(order); } + private static void EnsureReallocateAllowed(Order order) + { + if (order.IsPaid != 0) + { + throw new BusinessException("订单已付款,不允许重新排货"); + } + + if (order.OrderStatus is not (OrderStatusCodes.PendingAllocation or OrderStatusCodes.PendingPayment)) + { + throw new BusinessException( + $"订单状态为「{OmsDocHelper.GetOrderStatusName(order.OrderStatus ?? string.Empty)}」,仅待排货/待支付可重新排货"); + } + } + + private static void NormalizeReallocateOptions( + string? scheme, + int? serviceChannelId, + out string normalizedScheme, + out int? forceServiceChannelId) + { + normalizedScheme = (scheme ?? string.Empty).Trim(); + forceServiceChannelId = null; + + if (AllocationSchemeCodes.IsDesignated(normalizedScheme)) + { + if (serviceChannelId is not > 0) + { + throw new BusinessException("指定渠道时请选择服务渠道"); + } + + forceServiceChannelId = serviceChannelId; + return; + } + + if (!AllocationSchemeCodes.IsAutoScheme(normalizedScheme)) + { + throw new BusinessException("排货方案无效,请选择价格优先/时效优先/综合最优/指定渠道"); + } + + if (serviceChannelId is > 0) + { + // 自动方案忽略渠道入参,避免误传 + forceServiceChannelId = null; + } + } + private static OrderWeight ResolvePayableWeightRow(Order order, IReadOnlyList weights) { var (_, chargingStage) = ResolveReceivableBillingStage(order); @@ -460,7 +886,7 @@ public partial class OrderService private static (string WeightType, string ChargingStage) ResolveReceivableBillingStage(Order order) => order.OrderStatus switch { - OrderStatusCodes.Received or OrderStatusCodes.PendingAllocation or OrderStatusCodes.PendingPayment or OrderStatusCodes.PendingShip + OrderStatusCodes.PendingAllocation or OrderStatusCodes.PendingPayment or OrderStatusCodes.PendingShip => (OrderWeightTypeCodes.Receive, OrderFeeChargingStageCodes.Inbound), OrderStatusCodes.PendingOnline or OrderStatusCodes.Shipping or OrderStatusCodes.DeliverySuccess or OrderStatusCodes.DeliveryFailed diff --git a/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs b/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs index 26e1309..5d22cdc 100644 --- a/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs +++ b/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs @@ -1,12 +1,16 @@ +using System.Collections.Concurrent; using Fake.Application; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; using Oms.Application.Dtos.Channels; using Oms.Application.Dtos.Orders; using Oms.Application.Integrations.SmallBagTrack; using Oms.Application.Labeling; using Oms.Application.Messaging; using Oms.Application.Shared; +using Oms.Application.Services.Orders.Batch; using Oms.Application.Services.Orders.Issues; using Oms.Domain.ChannelsAggregate.Consts; using Oms.Domain.ChannelsAggregate.Entities; @@ -17,6 +21,7 @@ using Oms.Domain.CustomersAggregate.Repositories; using Oms.Domain.MarketingAggregate.Repositories; using Oms.Domain.OrdersAggregate.Consts; using Oms.Domain.OrdersAggregate.Entities; +using Oms.Domain.OrdersAggregate.Repositories; using Oms.Domain.Shared.Enums; using Oms.Domain.SystemAggregate.Entities; using Oms.Domain.SystemAggregate.Repositories; @@ -28,6 +33,10 @@ public partial class OrderService private const string PriceOperatorType = "price"; private const string RulesOperatorType = "rules"; private const int ParcelBatchMaxCount = 2000; + private const string InboundBillingProcessingReason = "入库后计费/排货处理中"; + private const string InboundBillingEnqueueFailReason = "入库计费任务投递失败,请重跑入库计费"; + + private static readonly ConcurrentDictionary InboundBillingInFlight = new(); private ICustomerRepository CustomerRepository => LazyServiceProvider.GetRequiredService(); @@ -55,6 +64,8 @@ public partial class OrderService public DateTime? PickupTime { get; init; } public int? CustomerSenderAddressId { get; init; } + + public string? InboundMethod { get; init; } } private async Task CreateParcelCoreAsync( @@ -85,6 +96,8 @@ public partial class OrderService throw new BusinessException("销售产品不存在或未启用"); } + EnsureAdditionalServicesAllowed(product, input.AdditionalServices); + var snapshotBinding = await ResolveSnapshotBindingAsync(product, bindTime); var country = await GetCountryOrThrowAsync(input.Receiver!.CountryCode); @@ -126,6 +139,7 @@ public partial class OrderService // 客户主动「先保存为草稿」:落库草稿后直接返回,不跑预报计费。 if (input.SaveAsDraft) { + await TryUpsertCustoms9610Async(order); return await BuildParcelCreateOutputAsync(order); } @@ -141,6 +155,7 @@ public partial class OrderService await ApplyChargeableWeightAsync(product, snapshotBinding.Rules, forecast); SyncWeightRows(weights, forecast); await OrderRepository.ReplaceWeightsAsync(order.Id, weights); + await TryUpsertCustoms9610Async(order); var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == order.CustomerId); var priceTierKey = await ResolvePriceTierKeyAsync(order.CustomerId); @@ -162,13 +177,18 @@ public partial class OrderService billing, OrderFeeChargingStageCodes.Forecast); - await ApplyMarketingSnapshotOnCreateAsync(order, input.CouponInstanceId); + // 预报阶段尝试排货写应付;失败不阻断创建(仅记录 AllocationPendingReason)。 + await TryConfirmServiceChannelAndPayableAsync( + order, + product, + billing, + OrderFeeChargingStageCodes.Forecast); + + await ApplyMarketingSnapshotOnCreateAsync(order, input.CouponInstanceId); + await CaptureForecastBillingSnapshotAsync(order); - // 创建订单不对客户暴露排货/买价:渠道与应付在入库等环节由运营侧处理。 order.OrderStatus = OrderStatusCodes.Predeclared; order.PredeclareFailReason = string.Empty; - order.AllocationPendingReason = string.Empty; - order.IsRemote = order.IsRemote; order.UpdateTime = DateTime.Now; await OrderRepository.UpdateAsync(order); @@ -217,6 +237,20 @@ public partial class OrderService /// private async Task RollbackFailedParcelCreateAsync(Order order) { + try + { + var writer = LazyServiceProvider.GetRequiredService(); + // 强制清掉可能已写入的 pending 9610(ExportCustomsMode 临时置空触发删除逻辑) + var mode = order.ExportCustomsMode; + order.ExportCustomsMode = null; + await writer.UpsertFromOrderAsync(order); + order.ExportCustomsMode = mode; + } + catch + { + // ignore + } + order.OrderStatus = OrderStatusCodes.Deleted; order.PredeclareFailReason = string.Empty; order.UpdateTime = DateTime.Now; @@ -224,6 +258,19 @@ public partial class OrderService await OrderRepository.DeleteAsync(order); } + private async Task TryUpsertCustoms9610Async(Order order) + { + try + { + await LazyServiceProvider.GetRequiredService() + .UpsertFromOrderAsync(order); + } + catch + { + // 9610 同步失败不阻断运单创建 + } + } + /// /// 已有草稿重新预报失败时,在业务文案末尾附加机器可读标记,供前端区分。 /// 格式:原因 [[omsDraft:{"draftSaved":true,"orderId":1,"serviceNo":"IDE..."}]] @@ -681,11 +728,14 @@ public partial class OrderService int? warehouseId = null, string? warehouseName = null) { - if (chargeableWeight <= 0) - { - throw new BusinessException("计费重无效,无法计算应收费用"); - } - + var conditionContext = BuildBillingConditionContext(order); + var remoteAreaId = order.IsRemote > 0 + ? (snapshotBinding.Rules?.RemoteAreaId + ?? snapshotBinding.Rules?.Product?.RemoteAreaId) + : null; + var remoteZoneKeys = ParcelBillingCalculator.BuildRemoteZoneKeys( + remoteAreaId is > 0 ? remoteAreaId : null, + snapshotBinding.Rules?.RemoteAreaName); var fees = ParcelBillingCalculator.CalculateReceivableFees( snapshotBinding.Price, snapshotBinding.PriceVersion, @@ -696,10 +746,19 @@ public partial class OrderService priceTierKey, chargingStage, warehouseId ?? order.WarehouseId, - warehouseName); + warehouseName, + conditionContext, + order.DeclaredSum, + order.DeclaredCurrency, + remoteZoneKeys); if (fees.Count == 0 && ParcelBillingCalculator.HasEnabledReceivablePriceItems(snapshotBinding.Price)) { + if (chargeableWeight <= 0) + { + throw new BusinessException("计费重无效,无法计算应收费用"); + } + var detail = ParcelBillingCalculator.ExplainQuotePriceMiss( snapshotBinding.Price, chargeableWeight, @@ -733,48 +792,234 @@ public partial class OrderService IReadOnlyList zoneKeys, decimal chargeableWeight, string chargingStage, - string? _) + string? _, + string? schemeOverride = null, + int? forceServiceChannelId = null) { - if (chargeableWeight <= 0) + var evaluation = await EvaluateAllocationAsync( + order, + product, + snapshotBinding, + zoneKeys, + chargeableWeight, + chargingStage, + schemeOverride, + forceServiceChannelId); + + ApplyAllocationTraceToOrder(order, evaluation); + + if (!string.IsNullOrWhiteSpace(evaluation.FailReason) || evaluation.Selected == null) { - throw new BusinessException("计费重无效,无法计算应付费用"); + throw new BusinessException(evaluation.FailReason ?? "排货规则未匹配到可用服务渠道"); } + var selectedCandidate = evaluation.Selected; + var payableFees = selectedCandidate.PayableFees.ToList(); + if (payableFees.Count == 0) + { + evaluation.FailReason = "渠道买价未配置或未匹配到有效价格"; + ApplyAllocationTraceToOrder(order, evaluation); + throw new BusinessException(evaluation.FailReason); + } + + var previousChannelCode = order.ChannelCode?.Trim(); + var newChannelCode = selectedCandidate.Channel.ChannelCode?.Trim() ?? string.Empty; + var channelChanged = !string.Equals( + previousChannelCode, + newChannelCode, + StringComparison.OrdinalIgnoreCase); + + order.ChannelCode = selectedCandidate.Channel.ChannelCode; + AllocationProviderSnapshotEnricher.ApplyDownstreamFieldsToOrder( + order, + selectedCandidate.Provider, + selectedCandidate.Channel); + + // 换渠道后旧下游单号/跟踪号失效,清空以免「新渠道+旧服务商单号」。 + if (channelChanged + && (!string.IsNullOrWhiteSpace(order.DownstreamServiceNo) + || !string.IsNullOrWhiteSpace(order.TrackNo))) + { + order.DownstreamServiceNo = null; + order.TrackNo = null; + } + + // 有效应付只保留本阶段一套,避免 forecast+inbound 叠行虚增成本。 + await OrderRepository.DeletePayableFeesAsync(order.Id); + await OrderRepository.UpsertFeesAsync(order.Id, payableFees); + order.AllocationPendingReason = string.Empty; + } + + private sealed class AllocationEvaluation + { + public string StoredScheme { get; init; } = AllocationSchemeCodes.CostLowest; + public string SelectScheme { get; init; } = AllocationSchemeCodes.CostLowest; + public string SchemeSource { get; init; } = "productDefault"; + public decimal ChargeableWeight { get; init; } + public string ChargingStage { get; init; } = string.Empty; + public IReadOnlyList ZoneKeys { get; init; } = []; + public List Candidates { get; init; } = []; + public List Skipped { get; init; } = []; + public AllocationResolver.ChannelCandidate? Selected { get; set; } + public string? FailReason { get; set; } + } + + private async Task EvaluateAllocationAsync( + Order order, + SalesProduct product, + ProductSnapshotBinding snapshotBinding, + IReadOnlyList zoneKeys, + decimal chargeableWeight, + string chargingStage, + string? schemeOverride, + int? forceServiceChannelId) + { + var skipped = new List(); var warehouseName = await ResolveWarehouseNameAsync(order.WarehouseId); var providers = await ResolveAllocationProvidersAsync(product, snapshotBinding.Rules); var filtered = AllocationResolver.FilterProviders(providers, order.CustomerId); - if (filtered.Count == 0) + + var productScheme = snapshotBinding.Rules.Product?.Scheme + ?? product.Scheme + ?? AllocationSchemeCodes.CostLowest; + var hasOverride = !string.IsNullOrWhiteSpace(schemeOverride); + var isDesignated = forceServiceChannelId is > 0 + || AllocationSchemeCodes.IsDesignated(schemeOverride); + var storedScheme = isDesignated + ? AllocationSchemeCodes.Designated + : hasOverride + ? schemeOverride!.Trim() + : productScheme; + var schemeSource = isDesignated + ? "designated" + : hasOverride + ? "reallocate" + : "productDefault"; + var selectScheme = AllocationSchemeCodes.IsDesignated(storedScheme) + ? AllocationSchemeCodes.CostLowest + : storedScheme; + + if (forceServiceChannelId is > 0) { - throw new BusinessException("排货规则未匹配到可用服务渠道"); + var before = filtered; + filtered = filtered + .Where(x => x.ServiceChannelId == forceServiceChannelId.Value) + .ToList(); + if (filtered.Count == 0) + { + foreach (var p in before.Where(x => x.ServiceChannelId != forceServiceChannelId)) + { + // 非指定渠道不记跳过;指定不在池内单独失败 + } + + return new AllocationEvaluation + { + StoredScheme = storedScheme, + SelectScheme = selectScheme, + SchemeSource = schemeSource, + ChargeableWeight = chargeableWeight, + ChargingStage = chargingStage, + ZoneKeys = zoneKeys, + Skipped = skipped, + FailReason = "指定渠道不在该销售产品排货池或当前客户不可用" + }; + } } - var bindTime = order.CreateTime == default ? DateTime.Now : order.CreateTime; - var scheme = snapshotBinding.Rules.Product?.Scheme - ?? product.Scheme - ?? AllocationSchemeCodes.CostLowest; + if (filtered.Count == 0) + { + return new AllocationEvaluation + { + StoredScheme = storedScheme, + SelectScheme = selectScheme, + SchemeSource = schemeSource, + ChargeableWeight = chargeableWeight, + ChargingStage = chargingStage, + ZoneKeys = zoneKeys, + Skipped = skipped, + FailReason = "排货规则未匹配到可用服务渠道" + }; + } + + // 应付买价取「当前」有效发布(PublishTime<=Now),不用下单时间,避免重新排货/入库漏掉后续发布的买价。 + var bindTime = DateTime.Now; var candidates = new List(); + var recipient = (await OrderRepository.GetRecipientsByOrderIdsAsync([order.Id])).FirstOrDefault(); + var cargoAttribute = order.CargoAttribute ?? CargoAttributeCodes.General; foreach (var provider in filtered) { - var channel = await ServiceChannelRepository.FirstOrDefaultAsync(x => x.Id == provider.ServiceChannelId!.Value); - if (channel == null || channel.IsActive != EnableStatus.Enabled) + var channelId = provider.ServiceChannelId!.Value; + var channel = await ServiceChannelRepository.FirstOrDefaultAsync(x => x.Id == channelId); + if (channel == null) { + skipped.Add(new OrderAllocationSkippedOutput + { + ServiceChannelId = channelId, + Reason = "服务渠道不存在" + }); continue; } + if (channel.IsActive != EnableStatus.Enabled) + { + skipped.Add(new OrderAllocationSkippedOutput + { + ServiceChannelId = channel.Id, + ChannelCode = channel.ChannelCode, + ChannelName = channel.ChannelName, + Reason = "服务渠道未启用" + }); + continue; + } + + var channelIsRemote = await IsChannelRemoteHitAsync( + channel, + order.ConsigneeCountry ?? string.Empty, + recipient?.Province, + recipient?.City, + recipient?.ZipCode); + var payableContext = BuildBillingConditionContext( + order, + channelIsRemote ? (byte)1 : (byte)0); + var channelPriceBinding = await ResolveChannelPriceBindingAsync(channel.Id, bindTime); + var channelRemoteZoneKeys = channelIsRemote + ? ParcelBillingCalculator.BuildRemoteZoneKeys(channel.RemoteAreaId) + : Array.Empty(); var previewFees = ParcelBillingCalculator.CalculatePayableFees( channelPriceBinding.Prices, channelPriceBinding.PriceVersion, channelPriceBinding.PriceEffectiveTime, chargeableWeight, zoneKeys, - order.CargoAttribute ?? CargoAttributeCodes.General, + cargoAttribute, chargingStage, order.WarehouseId, - warehouseName); + warehouseName, + payableContext, + order.DeclaredSum, + order.DeclaredCurrency, + channelRemoteZoneKeys); if (previewFees.Count == 0) { + var miss = ParcelBillingCalculator.ExplainPayablePriceMiss( + channelPriceBinding.Prices, + chargeableWeight, + zoneKeys, + cargoAttribute, + order.WarehouseId, + warehouseName, + channelRemoteZoneKeys); + skipped.Add(new OrderAllocationSkippedOutput + { + ServiceChannelId = channel.Id, + ChannelCode = channel.ChannelCode, + ChannelName = channel.ChannelName, + Reason = string.IsNullOrWhiteSpace(miss) + ? $"未匹配到有效渠道买价(版本 {channelPriceBinding.PriceVersion})" + : $"未匹配到有效渠道买价(版本 {channelPriceBinding.PriceVersion}):{miss}" + }); continue; } @@ -789,31 +1034,154 @@ public partial class OrderService if (candidates.Count == 0) { - throw new BusinessException("排货规则未匹配到有效渠道买价"); + var detail = skipped.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x.Reason))?.Reason; + return new AllocationEvaluation + { + StoredScheme = storedScheme, + SelectScheme = selectScheme, + SchemeSource = schemeSource, + ChargeableWeight = chargeableWeight, + ChargingStage = chargingStage, + ZoneKeys = zoneKeys, + Candidates = candidates, + Skipped = skipped, + FailReason = chargeableWeight <= 0 + ? "计费重无效,无法计算应付费用" + : string.IsNullOrWhiteSpace(detail) + ? "排货规则未匹配到有效渠道买价" + : $"排货规则未匹配到有效渠道买价;{detail}" + }; } - var selectedCandidate = AllocationResolver.SelectCandidate(scheme, candidates); - var payableFees = selectedCandidate.PayableFees.ToList(); - if (payableFees.Count == 0) + var selected = AllocationResolver.SelectCandidate(selectScheme, candidates); + return new AllocationEvaluation { - throw new BusinessException("渠道买价未配置或未匹配到有效价格"); - } - - order.ChannelCode = selectedCandidate.Channel.ChannelCode; - AllocationProviderSnapshotEnricher.ApplyDownstreamFieldsToOrder( - order, - selectedCandidate.Provider, - selectedCandidate.Channel); - await OrderRepository.DeletePayableFeesByStageAsync(order.Id, chargingStage); - await OrderRepository.UpsertFeesAsync(order.Id, payableFees); - order.AllocationPendingReason = string.Empty; + StoredScheme = storedScheme, + SelectScheme = selectScheme, + SchemeSource = schemeSource, + ChargeableWeight = chargeableWeight, + ChargingStage = chargingStage, + ZoneKeys = zoneKeys, + Candidates = candidates, + Skipped = skipped, + Selected = selected + }; } + private static void ApplyAllocationTraceToOrder(Order order, AllocationEvaluation evaluation) + { + var selectedCode = evaluation.Selected?.Channel.ChannelCode; + var output = BuildAllocationTraceOutput( + order.Id, + evaluation, + fromSnapshot: true, + selectedChannelCode: selectedCode); + order.AllocationScheme = evaluation.StoredScheme; + order.AllocationTraceJson = JsonConvert.SerializeObject(output); + order.AllocationTraceTime = DateTime.Now; + } + + private static OrderAllocationTraceOutput BuildAllocationTraceOutput( + int orderId, + AllocationEvaluation evaluation, + bool fromSnapshot, + string? selectedChannelCode) + { + var selectedId = evaluation.Selected?.Channel.Id; + var candidates = evaluation.Candidates + .Select(c => new OrderAllocationCandidateOutput + { + ServiceChannelId = c.Channel.Id, + ChannelCode = c.Channel.ChannelCode, + ChannelName = c.Channel.ChannelName, + TotalPayableCost = c.TotalPayableCost, + MinTime = c.Channel.MinTime, + Weight = c.Provider.Weight, + Selected = selectedId.HasValue && c.Channel.Id == selectedId.Value, + FeeLines = c.PayableFees.Select(f => new OrderAllocationFeeLineOutput + { + CostItem = f.CostItem, + Amount = f.Amount, + Currency = f.Currency + }).ToList() + }) + .ToList(); + + // 按方案主指标排序,选中置顶 + candidates = SortAllocationCandidates(evaluation.StoredScheme, candidates); + + return new OrderAllocationTraceOutput + { + OrderId = orderId, + FromSnapshot = fromSnapshot, + Scheme = evaluation.StoredScheme, + SchemeName = ResolveAllocationSchemeName(evaluation.StoredScheme), + SchemeSource = evaluation.SchemeSource, + SchemeSourceName = ResolveAllocationSchemeSourceName(evaluation.SchemeSource), + ChargeableWeight = evaluation.ChargeableWeight, + ZoneKeys = evaluation.ZoneKeys?.ToList() ?? [], + ChargingStage = evaluation.ChargingStage, + ChargingStageName = ResolveChargingStageName(evaluation.ChargingStage), + SelectedChannelCode = selectedChannelCode ?? evaluation.Selected?.Channel.ChannelCode, + SelectedChannelName = evaluation.Selected?.Channel.ChannelName, + FailReason = evaluation.FailReason, + TraceTime = DateTime.Now, + Candidates = candidates, + Skipped = evaluation.Skipped + }; + } + + private static List SortAllocationCandidates( + string? scheme, + List candidates) + { + Func metric = scheme switch + { + AllocationSchemeCodes.TimeFastest => x => x.MinTime ?? int.MaxValue, + AllocationSchemeCodes.OverallBest => x => -x.Weight, + _ => x => x.TotalPayableCost + }; + + return candidates + .OrderByDescending(x => x.Selected) + .ThenBy(metric) + .ThenBy(x => x.ChannelCode, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + private static string ResolveAllocationSchemeName(string? scheme) => + scheme switch + { + AllocationSchemeCodes.TimeFastest => "时效优先", + AllocationSchemeCodes.OverallBest => "综合最优", + AllocationSchemeCodes.Designated => "指定渠道", + _ => "价格优先" + }; + + private static string ResolveAllocationSchemeSourceName(string? source) => + source switch + { + "reallocate" => "运营重新排货", + "designated" => "指定渠道", + _ => "产品默认" + }; + + private static string ResolveChargingStageName(string? stage) => + stage switch + { + OrderFeeChargingStageCodes.Inbound => "入库", + OrderFeeChargingStageCodes.Outbound => "出库", + OrderFeeChargingStageCodes.Forecast => "预报", + _ => stage ?? string.Empty + }; + private Task ConfirmServiceChannelAndPayableAsync( Order order, SalesProduct product, OrderBillingContext billing, - string chargingStage) => + string chargingStage, + string? schemeOverride = null, + int? forceServiceChannelId = null) => ConfirmServiceChannelAndPayableAsync( order, product, @@ -821,7 +1189,9 @@ public partial class OrderService billing.ZoneKeys, billing.ChargeableWeight, chargingStage, - billing.PriceTierKey); + billing.PriceTierKey, + schemeOverride, + forceServiceChannelId); /// /// 尝试排货并写入应付;失败时不抛异常,写入 供运营补配置。 @@ -830,11 +1200,19 @@ public partial class OrderService Order order, SalesProduct product, OrderBillingContext billing, - string chargingStage) + string chargingStage, + string? schemeOverride = null, + int? forceServiceChannelId = null) { try { - await ConfirmServiceChannelAndPayableAsync(order, product, billing, chargingStage); + await ConfirmServiceChannelAndPayableAsync( + order, + product, + billing, + chargingStage, + schemeOverride, + forceServiceChannelId); return true; } catch (BusinessException ex) @@ -1358,26 +1736,6 @@ public partial class OrderService weightRow.Cubic = ParcelBillingCalculator.CalculateCubic(length, width, height); } - private async Task ApplyStageReceivableBillingAsync( - Order order, - SalesProduct product, - OrderWeight weightRow, - ProductSnapshotBinding snapshotBinding, - string chargingStage) - { - var billing = await ResolveOrderBillingContextAsync( - order, - product, - weightRow.ChargeableWeight ?? 0, - snapshotBinding); - - await UpsertReceivableFeesAsync( - order, - billing, - chargingStage, - replaceExistingReceivable: true); - } - private static int? ResolveEffectiveWeightRuleId( SalesProduct product, SalesProductRulesPublishSnapshotDto? rulesSnapshot) @@ -1505,6 +1863,9 @@ public partial class OrderService OrderSource = orderSource, PickupTime = createContext?.PickupTime, CustomerSenderAddressId = createContext?.CustomerSenderAddressId, + InboundMethod = string.IsNullOrWhiteSpace(createContext?.InboundMethod) + ? null + : createContext!.InboundMethod!.Trim(), IsCod = input.IsCod ? (byte)1 : (byte)0, CodCurrency = input.CodCurrency, CodSum = input.CodSum, @@ -1513,6 +1874,8 @@ public partial class OrderService Quantity = input.Quantity, IsIntercept = 0, IsRemote = 0, + AdditionalServices = SerializeAdditionalServices(input.AdditionalServices), + FulfillmentType = FulfillmentTypeCodes.Direct, PredeclareFailReason = string.Empty, AllocationPendingReason = string.Empty, SalesProductRulesVersion = snapshotBinding.RulesVersion, @@ -1747,7 +2110,8 @@ public partial class OrderService } /// - /// 入库收货后:仅覆盖 receive 件重尺、重算计费重,写入 inbound 阶段应收,并更新订单状态。 + /// 入库收货:同步只写入 receive 件重尺与收货时间,状态先置待排货; + /// 应收/应付/排货走异步任务,失败不回滚入库。 /// internal async Task ApplyReceiveBillingByWaybillAsync( string waybillNo, @@ -1769,20 +2133,101 @@ public partial class OrderService throw new BusinessException("未找到对应订单,请检查单号"); } - if (string.IsNullOrWhiteSpace(order.ProductCode)) + ParcelBillingValidators.EnsureInboundOrderStatus(order.OrderStatus); + + if (!InboundBillingInFlight.TryAdd(order.Id, 0)) { - throw new BusinessException("订单未绑定销售产品,无法入库计费"); + throw new BusinessException("订单入库处理中,请勿重复扫描"); } - ParcelBillingValidators.EnsureInboundOrderStatus(order.OrderStatus); + try + { + var weights = (await OrderRepository.GetWeightsByOrderIdsAsync([order.Id])) + .OrderBy(x => x.Id) + .ToList(); + var receive = weights.FirstOrDefault(x => x.Type == OrderWeightTypeCodes.Receive); + if (receive == null) + { + throw new BusinessException("订单缺少收货件重尺记录"); + } + + ApplyMeasuredDimensions(receive, length!.Value, width!.Value, height!.Value, actualWeight!.Value); + + // 尽力算计费重,失败留给异步计费重试,不阻断入库扫码。 + try + { + if (!string.IsNullOrWhiteSpace(order.ProductCode)) + { + var product = await SalesProductRepository.GetByProductCodeAsync(order.ProductCode.Trim()); + if (product != null) + { + var snapshotBinding = await ResolveSnapshotBindingFromOrderAsync(product, order); + await ApplyChargeableWeightAsync(product, snapshotBinding.Rules, receive); + } + } + } + catch + { + // ignore + } + + await OrderRepository.ReplaceWeightsAsync(order.Id, weights); + + order.OrderStatus = OrderStatusCodes.PendingAllocation; + order.AllocationPendingReason = InboundBillingProcessingReason; + order.ReceiveTime = DateTime.Now; + order.UpdateTime = DateTime.Now; + await OrderRepository.UpdateAsync(order); + + EnqueueLifecycleTrackAppend(order, SmallBagTrackLifecycleEvents.InboundTrackCode); + await EnqueueInboundBillingAsync(order); + } + finally + { + InboundBillingInFlight.TryRemove(order.Id, out _); + } + } + + /// + /// 入库异步计费:重算 inbound 应收 + 尝试排货写应付;失败仅落待排货原因。 + /// + internal async Task ProcessInboundBillingForBatchAsync( + int orderId, + CancellationToken cancellationToken = default) + { + _ = cancellationToken; + var order = await GetOrderOrThrowAsync(orderId); + if (string.IsNullOrWhiteSpace(order.ProductCode)) + { + order.OrderStatus = OrderStatusCodes.PendingAllocation; + order.AllocationPendingReason = "订单未绑定销售产品,无法入库计费"; + order.UpdateTime = DateTime.Now; + await OrderRepository.UpdateAsync(order); + return; + } var product = await SalesProductRepository.GetByProductCodeAsync(order.ProductCode.Trim()); if (product == null) { - throw new BusinessException("订单关联的销售产品不存在"); + order.OrderStatus = OrderStatusCodes.PendingAllocation; + order.AllocationPendingReason = "订单关联的销售产品不存在"; + order.UpdateTime = DateTime.Now; + await OrderRepository.UpdateAsync(order); + return; } - EnsureBillingProductActive(product); + try + { + EnsureBillingProductActive(product); + } + catch (BusinessException ex) + { + order.OrderStatus = OrderStatusCodes.PendingAllocation; + order.AllocationPendingReason = TrimPendingReason(ex.Message); + order.UpdateTime = DateTime.Now; + await OrderRepository.UpdateAsync(order); + return; + } var weights = (await OrderRepository.GetWeightsByOrderIdsAsync([order.Id])) .OrderBy(x => x.Id) @@ -1790,42 +2235,89 @@ public partial class OrderService var receive = weights.FirstOrDefault(x => x.Type == OrderWeightTypeCodes.Receive); if (receive == null) { - throw new BusinessException("订单缺少收货件重尺记录"); + order.OrderStatus = OrderStatusCodes.PendingAllocation; + order.AllocationPendingReason = "订单缺少收货件重尺记录"; + order.UpdateTime = DateTime.Now; + await OrderRepository.UpdateAsync(order); + return; } - ApplyMeasuredDimensions(receive, length!.Value, width!.Value, height!.Value, actualWeight!.Value); + ProductSnapshotBinding snapshotBinding; + try + { + snapshotBinding = await ResolveSnapshotBindingFromOrderAsync(product, order); + await ApplyChargeableWeightAsync(product, snapshotBinding.Rules, receive); + await OrderRepository.ReplaceWeightsAsync(order.Id, weights); + } + catch (Exception ex) + { + order.OrderStatus = OrderStatusCodes.PendingAllocation; + order.AllocationPendingReason = TrimPendingReason( + ex is BusinessException be ? be.Message : $"计费重计算失败:{ex.Message}"); + order.UpdateTime = DateTime.Now; + await OrderRepository.UpdateAsync(order); + return; + } - var snapshotBinding = await ResolveSnapshotBindingFromOrderAsync(product, order); - await ApplyChargeableWeightAsync(product, snapshotBinding.Rules, receive); - await OrderRepository.ReplaceWeightsAsync(order.Id, weights); - - var billing = await ResolveOrderBillingContextAsync( - order, - product, - receive.ChargeableWeight ?? 0, - snapshotBinding); - - await UpsertReceivableFeesAsync( - order, - billing, - OrderFeeChargingStageCodes.Inbound, - replaceExistingReceivable: true); + OrderBillingContext billing; + try + { + billing = await ResolveOrderBillingContextAsync( + order, + product, + receive.ChargeableWeight ?? 0, + snapshotBinding); + } + catch (Exception ex) + { + order.OrderStatus = OrderStatusCodes.PendingAllocation; + order.AllocationPendingReason = TrimPendingReason( + ex is BusinessException be ? be.Message : $"计费上下文解析失败:{ex.Message}"); + order.UpdateTime = DateTime.Now; + await OrderRepository.UpdateAsync(order); + return; + } + var (receivableOk, receivableFailReason) = await TryUpsertInboundReceivableFeesAsync(order, billing); var allocated = await TryConfirmServiceChannelAndPayableAsync( order, product, billing, OrderFeeChargingStageCodes.Inbound); - order.OrderStatus = allocated - ? OrderStatusCodes.PendingPayment - : OrderStatusCodes.PendingAllocation; - order.ReceiveTime = DateTime.Now; + try + { + await RefreshMarketingPayableAmountAsync(order); + } + catch + { + // 营销金额刷新失败不影响入库结果 + } + + if (allocated && receivableOk) + { + order.OrderStatus = OrderStatusCodes.PendingPayment; + order.AllocationPendingReason = string.Empty; + } + else + { + order.OrderStatus = OrderStatusCodes.PendingAllocation; + // 排货成功会清空 AllocationPendingReason,需用应收失败原因回填 + if (!receivableOk && !string.IsNullOrWhiteSpace(receivableFailReason)) + { + order.AllocationPendingReason = receivableFailReason; + } + else if (string.IsNullOrWhiteSpace(order.AllocationPendingReason)) + { + order.AllocationPendingReason = allocated + ? "入库应收未匹配到有效卖价" + : "排货未匹配到可用服务渠道或买价"; + } + } + order.UpdateTime = DateTime.Now; await OrderRepository.UpdateAsync(order); - EnqueueLifecycleTrackAppend(order, SmallBagTrackLifecycleEvents.InboundTrackCode); - if (allocated) { var customer = order.CustomerId.HasValue @@ -1835,8 +2327,141 @@ public partial class OrderService } } + private async Task<(bool Ok, string? FailReason)> TryUpsertInboundReceivableFeesAsync( + Order order, + OrderBillingContext billing) + { + try + { + await OrderRepository.DeleteReceivableFeesAsync(order.Id); + await UpsertReceivableFeesAsync( + order, + billing, + OrderFeeChargingStageCodes.Inbound); + return (true, null); + } + catch (BusinessException ex) + { + return (false, TrimPendingReason(ex.Message)); + } + catch (Exception ex) + { + return (false, TrimPendingReason($"入库应收计费失败:{ex.Message}")); + } + } + + private static string TrimPendingReason(string? message) + { + var text = (message ?? string.Empty).Trim(); + if (text.Length <= 512) + { + return text; + } + + return text[..512]; + } + + private async Task EnqueueInboundBillingAsync(Order order) + { + var logger = LazyServiceProvider.GetRequiredService() + .CreateLogger("Oms.InboundBilling"); + try + { + var publisher = LazyServiceProvider.GetRequiredService(); + if (!publisher.IsEnabled) + { + // 本地未开队列:同步跑异步计费逻辑,仍不向外抛(入库主流程已完成) + try + { + await ProcessInboundBillingForBatchAsync(order.Id); + } + catch (Exception ex) + { + logger.LogError(ex, "入库计费同步执行失败 OrderId={OrderId} ServiceNo={ServiceNo}", order.Id, order.ServiceNo); + order.OrderStatus = OrderStatusCodes.PendingAllocation; + order.AllocationPendingReason = TrimPendingReason($"入库计费失败:{ex.Message}"); + order.UpdateTime = DateTime.Now; + await OrderRepository.UpdateAsync(order); + } + + return; + } + + var requestId = await ResolveInboundBillingRequestIdAsync(order.Id); + if (requestId == null) + { + logger.LogInformation( + "入库计费任务已在队列中,跳过重复投递 OrderId={OrderId} ServiceNo={ServiceNo}", + order.Id, + order.ServiceNo); + return; + } + + await BatchJobCoordinator.CreateAndEnqueueAsync( + new OrderBatchJobCreateInput + { + Action = OrderBatchActionCodes.InboundBilling, + OrderIds = [order.Id], + RequestId = requestId + }, + CurrentUser.IsAuthenticated ? CurrentUser.GetId() : 0); + } + catch (Exception ex) + { + // 投递失败不回滚入库;落待排货并记错误日志,供运营重跑入库计费 + logger.LogError( + ex, + "入库计费任务投递失败 OrderId={OrderId} ServiceNo={ServiceNo}", + order.Id, + order.ServiceNo); + try + { + order.OrderStatus = OrderStatusCodes.PendingAllocation; + if (string.IsNullOrWhiteSpace(order.AllocationPendingReason) + || order.AllocationPendingReason == InboundBillingProcessingReason) + { + order.AllocationPendingReason = InboundBillingEnqueueFailReason; + } + + order.UpdateTime = DateTime.Now; + await OrderRepository.UpdateAsync(order); + } + catch + { + // ignore + } + } + } + /// - /// 出库发货后:仅覆盖 ship 件重尺、重算计费重,写入 outbound 阶段应收,并更新订单状态。 + /// 幂等 RequestId:进行中任务复用并跳过;已结束任务换新 ID 允许重跑。 + /// 返回 null 表示已有进行中任务,无需再投递。 + /// + private async Task ResolveInboundBillingRequestIdAsync(int orderId) + { + var batchJobRepository = LazyServiceProvider.GetRequiredService(); + var stableId = $"inbound-billing:{orderId}"; + var existing = await batchJobRepository.GetByRequestIdAsync(stableId); + if (existing != null) + { + if (IsActiveBatchJob(existing.Status)) + { + return null; + } + + // 旧稳定 ID 已结束,后续用带时间戳 ID,避免被已完成任务挡住重跑 + return $"inbound-billing:{orderId}:{DateTime.UtcNow:yyyyMMddHHmmssfff}"; + } + + return stableId; + } + + private static bool IsActiveBatchJob(string? status) => + string.Equals(status, OrderBatchJobStatusCodes.Pending, StringComparison.OrdinalIgnoreCase) + || string.Equals(status, OrderBatchJobStatusCodes.Running, StringComparison.OrdinalIgnoreCase); + + /// + /// 出库发货后:仅覆盖 ship 件重尺、重算计费重并更新状态;不再重算应收。 /// internal async Task ApplyShipBillingByWaybillAsync( string waybillNo, @@ -1902,13 +2527,7 @@ public partial class OrderService await ApplyChargeableWeightAsync(product, snapshotBinding.Rules, ship); await OrderRepository.ReplaceWeightsAsync(order.Id, weights); - await ApplyStageReceivableBillingAsync( - order, - product, - ship, - snapshotBinding, - OrderFeeChargingStageCodes.Outbound); - + // 出库仅更新件重尺与状态,不再重算/覆盖应收。 var now = DateTime.Now; order.OrderStatus = OrderStatusCodes.PendingOnline; order.ShipTime = now; @@ -2118,4 +2737,136 @@ public partial class OrderService await couponManager.LockForOrderAsync(breakdown.CouponInstanceId.Value, mainCustomerId, order.Id); } } + + /// + /// 预报计费完成后固化应收/应付快照;入库重算不得覆盖。 + /// + private async Task CaptureForecastBillingSnapshotAsync(Order order) + { + var fees = await OrderRepository.GetFeesByOrderIdsAsync([order.Id]); + order.ForecastReceivableAmount = order.ReceivableSubtotal + ?? fees.Where(x => x.Type == OrderFeeTypeCodes.Receivable).Sum(x => x.Amount); + order.ForecastPayableAmount = fees + .Where(x => x.Type == OrderFeeTypeCodes.Payable) + .Sum(x => x.Amount); + } + + /// + /// 入库等场景重算应收后,按当前应收小计刷新营销应付金额(不重新锁定优惠券)。 + /// + private async Task RefreshMarketingPayableAmountAsync(Order order) + { + var fees = await OrderRepository.GetFeesByOrderIdsAsync([order.Id]); + var receivableSubtotal = fees + .Where(x => x.Type == OrderFeeTypeCodes.Receivable) + .Sum(x => x.Amount); + var marketingHelper = LazyServiceProvider.GetRequiredService(); + var breakdown = await marketingHelper.BuildBreakdownAsync( + order.CustomerId, + receivableSubtotal, + order.CouponInstanceId); + marketingHelper.ApplySnapshotToOrder(order, breakdown, order.CouponInstanceId); + } + + private static void EnsureReceivableMutable(Order order) + { + if (order.IsPaid != 0) + { + throw new BusinessException("订单已付款,不能修改应收费用"); + } + } + + private static void EnsureAdditionalServicesAllowed(SalesProduct product, List? selected) + { + var selectedCodes = NormalizeAdditionalServiceCodes(selected); + if (selectedCodes.Count == 0) + { + return; + } + + var allowed = ParseAdditionalServiceCodes(product.AdditionalServices); + if (allowed.Count == 0) + { + throw new BusinessException("销售产品未配置附加服务,不能勾选附加服务"); + } + + var invalid = selectedCodes + .Where(code => !allowed.Contains(code)) + .ToList(); + if (invalid.Count > 0) + { + throw new BusinessException($"附加服务不在产品可选范围:{string.Join(", ", invalid)}"); + } + } + + private static string? SerializeAdditionalServices(List? codes) + { + var normalized = NormalizeAdditionalServiceCodes(codes); + return normalized.Count == 0 ? null : OmsDocHelper.SerializeJson(normalized); + } + + private static List NormalizeAdditionalServiceCodes(IEnumerable? codes) => + (codes ?? []) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Select(x => x.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + private static HashSet ParseAdditionalServiceCodes(string? json) + { + var codes = OmsDocHelper.DeserializeJson>(json) ?? []; + return NormalizeAdditionalServiceCodes(codes) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + } + + private static OrderRuleEvaluationContext BuildBillingConditionContext( + Order order, + byte? overrideIsRemote = null) + { + var evalOrder = overrideIsRemote.HasValue + ? new Order + { + Id = order.Id, + ProductCode = order.ProductCode, + ChannelCode = order.ChannelCode, + ConsigneeCountry = order.ConsigneeCountry, + ConsigneeCountryName = order.ConsigneeCountryName, + CargoAttribute = order.CargoAttribute, + WarehouseId = order.WarehouseId, + CustomerId = order.CustomerId, + DeclaredCurrency = order.DeclaredCurrency, + DeclaredSum = order.DeclaredSum, + Quantity = order.Quantity, + IsRemote = overrideIsRemote.Value, + AdditionalServices = order.AdditionalServices, + IsPaid = order.IsPaid, + IsCod = order.IsCod, + CodCurrency = order.CodCurrency, + CodSum = order.CodSum + } + : order; + + return OrderRuleEvaluationContext.FromOrderOnly(evalOrder); + } + + private async Task IsChannelRemoteHitAsync( + ServiceChannel channel, + string countryCode, + string? province, + string? city, + string? zipCode) + { + if (channel.RemoteAreaId is not > 0) + { + return false; + } + + var rules = await KpiAreaRepository.GetAllInfosByAreaIdAsync(channel.RemoteAreaId.Value); + return rules.Any(rule => ParcelBillingCalculator.IsAreaMatched( + rule, + countryCode, + province, + city, + zipCode)); + } } diff --git a/src/Oms.Application/Services/Orders/OrderService.ParcelQuote.cs b/src/Oms.Application/Services/Orders/OrderService.ParcelQuote.cs index fb2a1a8..a2b290a 100644 --- a/src/Oms.Application/Services/Orders/OrderService.ParcelQuote.cs +++ b/src/Oms.Application/Services/Orders/OrderService.ParcelQuote.cs @@ -1,6 +1,7 @@ using Fake.Application; using Oms.Application.Dtos.Marketing; using Oms.Application.Dtos.Orders; +using Oms.Application.Services.Orders.Issues; using Oms.Application.Shared; using Oms.Domain.ChannelsAggregate.Entities; using Oms.Domain.OrdersAggregate.Consts; @@ -138,7 +139,10 @@ public partial class OrderService Length = dimensionLength, Width = dimensionWidth, Height = dimensionHeight, - ActualWeight = input.CargoWeight!.Value + ActualWeight = input.CargoWeight!.Value, + AdditionalServices = input.AdditionalServices, + DeclaredSum = input.DeclaredSum, + DeclaredCurrency = input.DeclaredCurrency }; var priceTierKey = await ResolveCurrentPriceTierKeyAsync(); @@ -233,7 +237,10 @@ public partial class OrderService Length = baseContext.Length, Width = baseContext.Width, Height = baseContext.Height, - ActualWeight = baseContext.ActualWeight + ActualWeight = baseContext.ActualWeight, + AdditionalServices = baseContext.AdditionalServices, + DeclaredSum = baseContext.DeclaredSum, + DeclaredCurrency = baseContext.DeclaredCurrency }; var attempt = await TryComputePriceCheckQuoteAsync( @@ -269,6 +276,9 @@ public partial class OrderService TradeTerms = string.IsNullOrWhiteSpace(product.TradeTerms) ? null : product.TradeTerms.Trim().ToUpperInvariant(), ProductGroup = groupCode, ProductGroupName = groupName, + ProductDescription = string.IsNullOrWhiteSpace(product.ProductDescription) + ? null + : product.ProductDescription.Trim(), VolumetricWeight = quote.VolumetricWeight, ChargeableWeight = quote.ChargeableWeight, CostFormula = summary.CostFormula, @@ -578,6 +588,22 @@ public partial class OrderService ParcelQuoteResult? bestQuote = null; decimal bestTotal = decimal.MaxValue; + var isRemote = profile.HasPostalCode + && await IsRemoteHitAsync( + product, + snapshotBinding.Rules, + context.CountryCode, + context.Province, + context.City, + context.PostalCode); + var conditionContext = BuildQuoteBillingConditionContext(context, isRemote); + + var remoteZoneKeys = isRemote + ? ParcelBillingCalculator.BuildRemoteZoneKeys( + ResolveEffectiveRemoteAreaId(product, snapshotBinding.Rules), + snapshotBinding.Rules?.RemoteAreaName) + : Array.Empty(); + foreach (var zoneAttempt in zoneAttempts) { var feeLines = ParcelBillingCalculator.CalculateQuoteReceivableFeeLines( @@ -589,7 +615,11 @@ public partial class OrderService context.CargoAttribute, priceTierKey, context.WarehouseId, - context.WarehouseName); + context.WarehouseName, + conditionContext, + context.DeclaredSum, + context.DeclaredCurrency, + remoteZoneKeys); if (feeLines.Count == 0) { continue; @@ -601,15 +631,6 @@ public partial class OrderService continue; } - var isRemote = profile.HasPostalCode - && await IsRemoteHitAsync( - product, - snapshotBinding.Rules, - context.CountryCode, - context.Province, - context.City, - context.PostalCode); - bestTotal = total; bestQuote = new ParcelQuoteResult { @@ -762,6 +783,28 @@ public partial class OrderService return attempts; } + private static OrderRuleEvaluationContext BuildQuoteBillingConditionContext( + ParcelQuoteContext context, + bool isRemote) + { + var services = (context.AdditionalServices ?? []) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Select(x => x.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + return OrderRuleEvaluationContext.FromOrderOnly(new Order + { + ConsigneeCountry = context.CountryCode, + CargoAttribute = context.CargoAttribute, + WarehouseId = context.WarehouseId, + DeclaredSum = context.DeclaredSum, + DeclaredCurrency = context.DeclaredCurrency, + IsRemote = isRemote ? (byte)1 : (byte)0, + AdditionalServices = services.Count == 0 ? null : OmsDocHelper.SerializeJson(services) + }); + } + private static PriceCheckAttemptResult PriceCheckFailure( SalesProduct product, string step, diff --git a/src/Oms.Application/Services/Orders/OrderService.ReceiverAddressParse.cs b/src/Oms.Application/Services/Orders/OrderService.ReceiverAddressParse.cs index 8bf89d1..855da0c 100644 --- a/src/Oms.Application/Services/Orders/OrderService.ReceiverAddressParse.cs +++ b/src/Oms.Application/Services/Orders/OrderService.ReceiverAddressParse.cs @@ -3,9 +3,10 @@ using System.Text.RegularExpressions; using Fake.Application; using Microsoft.AspNetCore.Mvc; using Oms.Application.Dtos.Orders; +using Oms.Application.Services.Ai; using Oms.Application.Shared; -using Oms.Domain.XhsAggregate.Entities; -using Oms.Domain.XhsAggregate.Repositories; +using Oms.Domain.AiAggregate.Entities; +using Oms.Domain.AiAggregate.Repositories; namespace Oms.Application.Services.Orders; @@ -20,10 +21,44 @@ public partial class OrderService "地址1", ]; - private IXhsAiProviderRepository AiProviderRepository => - LazyServiceProvider.GetRequiredService(); + private const string DefaultReceiverAddressParseSkill = + """ + 你是国际物流 OMS 的收件地址解析助手(跨境打单场景)。 + 目标:把客户粘贴的整段中/英收件信息拆成结构化字段,并做「粗校验」提示——只关心下单/预报大概能不能用,不做地图精校、不验证门牌是否真实、不臆造邮编与城市匹配。 - private XhsLlmClient LlmClient => LazyServiceProvider.GetRequiredService(); + 只输出 JSON,不要 Markdown,不要解释。字段: + { + "recipientsName": "", + "companyName": "", + "phone": "", + "telePhone": "", + "email": "", + "countryCode": "", + "province": "", + "city": "", + "streetNumber": "", + "streetAddress1": "", + "streetAddress2": "", + "streetAddress3": "", + "zipCode": "", + "warnings": [] + } + + 规则: + 1) countryCode 必须是 ISO 二字码大写(中国→CN,美国→US,英国→GB 不要用 UK,香港→HK,台湾→TW,澳门→MO)。无法判断则留空并在 warnings 说明。 + 2) phone 优先填手机;固定电话放 telePhone;保留 + 国家码。 + 3) 街道门牌放入 streetAddress1;过长拆到 streetAddress2/3;单独门牌号可放 streetNumber。 + 4) 中国地址:省→province,市→city,区县街道合并进 streetAddress1(不要把省市区塞进姓名)。 + 5) 英文地址:State→province,City→city,Street→streetAddress*,ZIP/Postcode→zipCode。 + 6) 粗风险才写 warnings(短中文):缺国家/邮编/电话不像号码/街道与姓名粘连拆不清等。禁止写「地图不存在」「邮编与城市不匹配」这类无依据结论。 + 7) 不确定的字段留空;不要编造原文没有的省市区邮编。 + 8) 税号/EORI/VAT 不是本任务重点,原文没有就忽略。 + """; + + private IAiProviderRepository AiProviderRepository => + LazyServiceProvider.GetRequiredService(); + + private AiLlmClient LlmClient => LazyServiceProvider.GetRequiredService(); /// /// AI 解析粘贴的收件地址文本,并校验是否完整。 @@ -47,39 +82,22 @@ public partial class OrderService var customerId = await OmsSessionHelper.ResolveXhsCustomerIdAsync(CustomerRepository, CurrentUser); var provider = await ResolveAiProviderAsync(customerId, input.ProviderKey); - var systemPrompt = - """ - 你是国际物流 OMS 的收件地址解析助手(跨境打单场景)。 - 目标:把客户粘贴的整段中/英收件信息拆成结构化字段,并做「粗校验」提示——只关心下单/预报大概能不能用,不做地图精校、不验证门牌是否真实、不臆造邮编与城市匹配。 - - 只输出 JSON,不要 Markdown,不要解释。字段: + var skillService = LazyServiceProvider.GetRequiredService(); + var skillKey = string.IsNullOrWhiteSpace(input.SkillKey) + ? AiSkillService.KeyReceiverAddressParse + : input.SkillKey.Trim(); + var systemPrompt = await skillService.TryGetContentByKeyAsync(skillKey); + if (string.IsNullOrWhiteSpace(systemPrompt)) + { + if (skillKey == AiSkillService.KeyReceiverAddressParse) { - "recipientsName": "", - "companyName": "", - "phone": "", - "telePhone": "", - "email": "", - "countryCode": "", - "province": "", - "city": "", - "streetNumber": "", - "streetAddress1": "", - "streetAddress2": "", - "streetAddress3": "", - "zipCode": "", - "warnings": [] + systemPrompt = DefaultReceiverAddressParseSkill; } - - 规则: - 1) countryCode 必须是 ISO 二字码大写(中国→CN,美国→US,英国→GB 不要用 UK,香港→HK,台湾→TW,澳门→MO)。无法判断则留空并在 warnings 说明。 - 2) phone 优先填手机;固定电话放 telePhone;保留 + 国家码。 - 3) 街道门牌放入 streetAddress1;过长拆到 streetAddress2/3;单独门牌号可放 streetNumber。 - 4) 中国地址:省→province,市→city,区县街道合并进 streetAddress1(不要把省市区塞进姓名)。 - 5) 英文地址:State→province,City→city,Street→streetAddress*,ZIP/Postcode→zipCode。 - 6) 粗风险才写 warnings(短中文):缺国家/邮编/电话不像号码/街道与姓名粘连拆不清等。禁止写「地图不存在」「邮编与城市不匹配」这类无依据结论。 - 7) 不确定的字段留空;不要编造原文没有的省市区邮编。 - 8) 税号/EORI/VAT 不是本任务重点,原文没有就忽略。 - """; + else + { + throw new BusinessException($"Skill「{skillKey}」未配置或未启用"); + } + } var userPrompt = "请解析以下收件信息:\n" + raw; string modelText; @@ -122,7 +140,7 @@ public partial class OrderService }; } - private async Task ResolveAiProviderAsync(int customerId, string? providerKey) + private async Task ResolveAiProviderAsync(int customerId, string? providerKey) { var key = (providerKey ?? string.Empty).Trim(); if (!string.IsNullOrWhiteSpace(key)) diff --git a/src/Oms.Application/Services/Orders/OrderService.StockBind.cs b/src/Oms.Application/Services/Orders/OrderService.StockBind.cs index 50e475c..d8f5150 100644 --- a/src/Oms.Application/Services/Orders/OrderService.StockBind.cs +++ b/src/Oms.Application/Services/Orders/OrderService.StockBind.cs @@ -7,6 +7,8 @@ using Oms.Application.Shared; using Oms.Domain.OrdersAggregate.Consts; using Oms.Domain.OrdersAggregate.Entities; using Oms.Domain.OrdersAggregate.Repositories; +using Oms.Domain.ChannelsAggregate.Entities; +using Oms.Domain.WarehouseAggregate.Consts; using Oms.Domain.WarehouseAggregate.Entities; using Oms.Domain.WarehouseAggregate.Repositories; @@ -192,6 +194,11 @@ public partial class OrderService var warehouseId = ResolveBindWarehouseId(order, null); var items = input.Items ?? []; + if (items.Count > 0) + { + await EnsureProxyPackingConfiguredForOrderAsync(order); + } + await ReleaseBoundBindsAsync(order.Id); foreach (var item in items) @@ -216,12 +223,36 @@ public partial class OrderService } } + var needOrderUpdate = false; if (!order.WarehouseId.HasValue || order.WarehouseId.Value <= 0) { order.WarehouseId = warehouseId; + needOrderUpdate = true; + } + + if (items.Count > 0) + { + if (!FulfillmentTypeCodes.IsWarehouse(order.FulfillmentType)) + { + order.FulfillmentType = FulfillmentTypeCodes.Warehouse; + needOrderUpdate = true; + } + + if (string.IsNullOrWhiteSpace(order.FulfillmentSource)) + { + order.FulfillmentSource = FulfillmentSourceCodes.PostBind; + needOrderUpdate = true; + } + } + + if (needOrderUpdate) + { await UpdateOrderAsync(order); } + order = await GetOrderOrThrowAsync(order.Id); + await SyncProxyPackingFeeByStockBindAsync(order); + return await BuildStockBindDetailAsync(order); } @@ -235,6 +266,8 @@ public partial class OrderService EnsureOrderCanBindStock(order); await EnsureNoDeductedBindsAsync(order.Id); await ReleaseBoundBindsAsync(order.Id); + order = await GetOrderOrThrowAsync(order.Id); + await SyncProxyPackingFeeByStockBindAsync(order); return await BuildStockBindDetailAsync(order); } @@ -247,6 +280,12 @@ public partial class OrderService var order = await GetOrderOrThrowAsync(input.OrderId); var binds = await OrderStockBindRepository.GetListAsync(x => x.OrderId == order.Id && x.Status == OrderStockBindStatusCodes.Bound); + if (binds.Count == 0) + { + throw new BusinessException("当前订单无已绑定明细,无法确认扣减"); + } + + await EnsureStockBindReadyForDeductAsync(binds); foreach (var bind in binds) { await DeductBoundLineAsync(bind); @@ -793,4 +832,118 @@ public partial class OrderService private static void SyncParcelItemAvailable(CParcelItem item) => item.AvailableQty = Math.Max(0, item.Quantity - item.FrozenQty); + + /// + /// 绑定前校验:销售产品须配置代打包附加服务,否则无法绑定。 + /// + private async Task EnsureProxyPackingConfiguredForOrderAsync(Order order) + { + if (string.IsNullOrWhiteSpace(order.ProductCode)) + { + throw new BusinessException("订单未绑定销售产品,无法绑定库存/包裹"); + } + + var product = await SalesProductRepository.GetByProductCodeAsync(order.ProductCode.Trim()) + ?? throw new BusinessException("销售产品不存在"); + + var allowed = ParseAdditionalServiceCodes(product.AdditionalServices); + if (!allowed.Contains(OrderAdditionalServiceCodes.ProxyPacking)) + { + throw new BusinessException( + "当前销售产品未配置「代打包」附加服务,无法绑定库存/包裹。请在销售产品中勾选代打包并配置对应卖价计费条件。"); + } + } + + /// + /// 有绑定则自动勾选代打包附加服务并重算应收;无绑定则移除代打包并重算。 + /// + private async Task SyncProxyPackingFeeByStockBindAsync(Order order) + { + if (string.IsNullOrWhiteSpace(order.ProductCode)) + { + return; + } + + if (order.IsPaid != 0) + { + return; + } + + var hasActiveBinds = await OrderStockBindRepository.CountAsync(x => + x.OrderId == order.Id + && (x.Status == OrderStockBindStatusCodes.Bound || x.Status == OrderStockBindStatusCodes.Deducted)) > 0; + + var services = ParseAdditionalServiceCodes(order.AdditionalServices).ToList(); + var hasProxyPacking = services.Any(x => + string.Equals(x, OrderAdditionalServiceCodes.ProxyPacking, StringComparison.OrdinalIgnoreCase)); + + if (hasActiveBinds) + { + if (!hasProxyPacking) + { + services.Add(OrderAdditionalServiceCodes.ProxyPacking); + } + } + else if (hasProxyPacking) + { + services.RemoveAll(x => + string.Equals(x, OrderAdditionalServiceCodes.ProxyPacking, StringComparison.OrdinalIgnoreCase)); + } + else + { + return; + } + + var normalized = NormalizeAdditionalServiceCodes(services); + var serialized = SerializeAdditionalServices(normalized); + if (string.Equals(order.AdditionalServices ?? string.Empty, serialized ?? string.Empty, StringComparison.Ordinal)) + { + return; + } + + var product = await SalesProductRepository.GetByProductCodeAsync(order.ProductCode.Trim()); + if (product == null) + { + return; + } + + EnsureAdditionalServicesAllowed(product, normalized); + order.AdditionalServices = serialized; + await RebillReceivableAfterAdditionalServicesChangeAsync(order, product); + order.UpdateTime = DateTime.Now; + await OrderRepository.UpdateAsync(order); + } + + private async Task EnsureStockBindReadyForDeductAsync(IReadOnlyList binds) + { + var parcelIds = binds + .Where(x => x.ParcelId is > 0) + .Select(x => x.ParcelId!.Value) + .Distinct() + .ToArray(); + if (parcelIds.Length == 0) + { + return; + } + + var parcels = await StockBindParcelRepository.GetListAsync(x => parcelIds.Contains(x.Id)); + var inTransitNos = parcels + .Where(x => string.Equals( + x.LifecycleStatus, + WarehouseParcelLifecycleCodes.InTransit, + StringComparison.OrdinalIgnoreCase)) + .Select(x => x.TrackingNo?.Trim()) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + if (inTransitNos.Length == 0) + { + return; + } + + var sample = inTransitNos[0]; + throw new BusinessException(inTransitNos.Length == 1 + ? $"包裹国内在途({sample}),请先到仓确认后再标记已打包" + : $"存在 {inTransitNos.Length} 个国内在途包裹,请先到仓确认后再标记已打包"); + } } diff --git a/src/Oms.Application/Services/Orders/OrderService.Workplace.cs b/src/Oms.Application/Services/Orders/OrderService.Workplace.cs index dbfa3b8..2bc46b5 100644 --- a/src/Oms.Application/Services/Orders/OrderService.Workplace.cs +++ b/src/Oms.Application/Services/Orders/OrderService.Workplace.cs @@ -65,6 +65,25 @@ public partial class OrderService : await SalesStoreOrderRepository.CountAsync(x => x.FulfillStatus == SalesStoreFulfillStatusCodes.Pending); + var fulfillFilter = new OrderListFilter + { + CustomerId = filter.CustomerId, + FulfillmentType = FulfillmentTypeCodes.Warehouse, + ScopeOrganizationIds = filter.ScopeOrganizationIds, + ScopeSecretLevels = filter.ScopeSecretLevels, + ScopeDataScope = filter.ScopeDataScope, + ScopePersonalOwnerMapId = filter.ScopePersonalOwnerMapId, + ScopePersonalOwnerAccount = filter.ScopePersonalOwnerAccount, + ScopeOwnerMapIds = filter.ScopeOwnerMapIds, + ScopeBizFilters = filter.ScopeBizFilters, + ScopeCustomFilters = filter.ScopeCustomFilters, + }; + var fulfillCounts = await OrderRepository.GetFulfillProgressCountsByFilterAsync(fulfillFilter); + int FulfillCount(string key) => + fulfillCounts.TryGetValue(key, out var value) ? value : 0; + + var pickupCounts = await PickupOrderRepository.GetWorkplaceCountsAsync(filter.CustomerId); + return new OrderWorkplaceStatsOutput { Total = counts.Values.Sum(), @@ -74,10 +93,25 @@ public partial class OrderService DayOverDayGrowthPercent = growth, PendingShip = GetCount(OrderStatusCodes.PendingShip), Shipped = shipped, - PendingOnline = GetCount(OrderStatusCodes.PendingOnline), + PendingPayment = GetCount(OrderStatusCodes.PendingPayment), Problematic = GetCount(OrderStatusCodes.Problematic), + Claimed = GetCount(OrderStatusCodes.Claimed), StoreCount = storeCount, StoreOrderPending = storeOrderPending, + Fulfill = new FulfillWorkplaceStatsOutput + { + PendingBind = FulfillCount(FulfillmentProgressCodes.PendingBind), + DomesticInTransit = FulfillCount(FulfillmentProgressCodes.DomesticInTransit), + ArrivedPendingPick = FulfillCount(FulfillmentProgressCodes.ArrivedPendingPick), + OutboundDone = FulfillCount(FulfillmentProgressCodes.OutboundDone), + }, + Pickup = new PickupWorkplaceStatsOutput + { + PendingPayment = pickupCounts.PendingPayment, + PendingSchedule = pickupCounts.PendingSchedule, + PendingPickup = pickupCounts.PendingPickup, + PendingInbound = pickupCounts.PendingInbound, + }, }; } @@ -132,6 +166,144 @@ public partial class OrderService }; } + /// + /// 工作台费用趋势(运费支出 vs 单票均价)。 + /// + [HttpGet("/order/workplace-spend-trend")] + public async Task GetWorkplaceSpendTrendAsync( + [FromQuery] string? dimension = "day", + [FromQuery] int count = 7) + { + var dim = (dimension ?? "day").Trim().ToLowerInvariant(); + if (dim is not ("day" or "week" or "month")) + { + dim = "day"; + } + + count = dim switch + { + "week" => Math.Clamp(count, 1, 12), + "month" => Math.Clamp(count, 1, 12), + _ => Math.Clamp(count, 1, 31), + }; + + var filter = await BuildScopedListFilterAsync(); + var buckets = BuildTrendBuckets(dim, count); + var points = new List(buckets.Count); + + foreach (var bucket in buckets) + { + var orderCount = await OrderRepository.CountByFilterAndCreateTimeRangeAsync( + filter, + bucket.Start, + bucket.EndExclusive); + var spendAmount = await OrderRepository.SumPayableAmountByCreateTimeRangeAsync( + filter, + bucket.Start, + bucket.EndExclusive); + spendAmount = Math.Round(spendAmount, 2); + var avg = orderCount > 0 + ? Math.Round(spendAmount / orderCount, 2) + : 0m; + + points.Add(new OrderWorkplaceSpendTrendPointOutput + { + Label = bucket.Label, + OrderCount = orderCount, + SpendAmount = spendAmount, + AvgAmount = avg, + }); + } + + var totalOrders = points.Sum(x => x.OrderCount); + var totalSpend = Math.Round(points.Sum(x => x.SpendAmount), 2); + var totalAvg = totalOrders > 0 + ? Math.Round(totalSpend / totalOrders, 2) + : 0m; + + return new OrderWorkplaceSpendTrendOutput + { + Dimension = dim, + TotalSpend = totalSpend, + TotalOrders = totalOrders, + AvgAmount = totalAvg, + Points = points, + }; + } + + /// + /// 工作台业务线趋势(运单 / 代发 / 揽收新增量)。 + /// + [HttpGet("/order/workplace-business-trend")] + public async Task GetWorkplaceBusinessTrendAsync( + [FromQuery] string? dimension = "day", + [FromQuery] int count = 7) + { + var dim = (dimension ?? "day").Trim().ToLowerInvariant(); + if (dim is not ("day" or "week" or "month")) + { + dim = "day"; + } + + count = dim switch + { + "week" => Math.Clamp(count, 1, 12), + "month" => Math.Clamp(count, 1, 12), + _ => Math.Clamp(count, 1, 31), + }; + + var filter = await BuildScopedListFilterAsync(); + var fulfillFilter = CloneScopedFilter(filter); + fulfillFilter.FulfillmentType = FulfillmentTypeCodes.Warehouse; + + var buckets = BuildTrendBuckets(dim, count); + var points = new List(buckets.Count); + + foreach (var bucket in buckets) + { + var totalOrders = await OrderRepository.CountByFilterAndCreateTimeRangeAsync( + filter, + bucket.Start, + bucket.EndExclusive); + var fulfillOrders = await OrderRepository.CountByFilterAndCreateTimeRangeAsync( + fulfillFilter, + bucket.Start, + bucket.EndExclusive); + var pickupOrders = await PickupOrderRepository.CountByCreateTimeRangeAsync( + filter.CustomerId, + bucket.Start, + bucket.EndExclusive); + + points.Add(new OrderWorkplaceBusinessTrendPointOutput + { + Label = bucket.Label, + WaybillCount = Math.Max(0, totalOrders - fulfillOrders), + FulfillCount = fulfillOrders, + PickupCount = pickupOrders, + }); + } + + return new OrderWorkplaceBusinessTrendOutput + { + Dimension = dim, + Points = points, + }; + } + + private static OrderListFilter CloneScopedFilter(OrderListFilter filter) => + new() + { + CustomerId = filter.CustomerId, + ScopeOrganizationIds = filter.ScopeOrganizationIds, + ScopeSecretLevels = filter.ScopeSecretLevels, + ScopeDataScope = filter.ScopeDataScope, + ScopePersonalOwnerMapId = filter.ScopePersonalOwnerMapId, + ScopePersonalOwnerAccount = filter.ScopePersonalOwnerAccount, + ScopeOwnerMapIds = filter.ScopeOwnerMapIds, + ScopeBizFilters = filter.ScopeBizFilters, + ScopeCustomFilters = filter.ScopeCustomFilters, + }; + private async Task BuildScopedListFilterAsync() { var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( diff --git a/src/Oms.Application/Services/Orders/OrderService.cs b/src/Oms.Application/Services/Orders/OrderService.cs index 01e3fb2..2929197 100644 --- a/src/Oms.Application/Services/Orders/OrderService.cs +++ b/src/Oms.Application/Services/Orders/OrderService.cs @@ -32,6 +32,7 @@ public partial class OrderService : ApplicationService private IWarehouseAddressRepository WarehouseAddressRepository => LazyServiceProvider.GetRequiredService(); private ISalesProductRepository SalesProductRepository => LazyServiceProvider.GetRequiredService(); private IDictRepository DictRepository => LazyServiceProvider.GetRequiredService(); + private IPickupOrderRepository PickupOrderRepository => LazyServiceProvider.GetRequiredService(); private IWebHostEnvironment WebHostEnvironment => LazyServiceProvider.GetRequiredService(); private LabelPdfGenerationService LabelPdfGenerationService => LazyServiceProvider.GetRequiredService(); @@ -70,11 +71,13 @@ public partial class OrderService : ApplicationService [HttpGet("/order/status-counts")] public async Task GetStatusCountsAsync( [FromQuery] DateTime? createTimeStart = null, - [FromQuery] DateTime? createTimeEnd = null) + [FromQuery] DateTime? createTimeEnd = null, + [FromQuery] string? fulfillmentType = null) { var filter = await BuildScopedListFilterAsync(); filter.CreateTimeStart = createTimeStart; filter.CreateTimeEnd = createTimeEnd; + filter.FulfillmentType = NormalizeFulfillmentTypeFilter(fulfillmentType); EnsureOrderListTimeWindow(filter); var rows = await OrderRepository.GetStatusCountsByFilterAsync(filter); var counts = rows.ToDictionary( @@ -90,12 +93,18 @@ public partial class OrderService : ApplicationService Processed = x.Value.Processed }, StringComparer.OrdinalIgnoreCase); - return new OrderStatusCountsOutput + var output = new OrderStatusCountsOutput { Total = rows.Sum(x => x.Count), Counts = counts, HandleCounts = handleCounts }; + if (string.Equals(filter.FulfillmentType, FulfillmentTypeCodes.Warehouse, StringComparison.OrdinalIgnoreCase)) + { + output.FulfillProgressCounts = await OrderRepository.GetFulfillProgressCountsByFilterAsync(filter); + } + + return output; } /// @@ -124,7 +133,7 @@ public partial class OrderService : ApplicationService throw new BusinessException("订单已支付"); } - if (order.OrderStatus is not (OrderStatusCodes.PendingPayment or OrderStatusCodes.Received)) + if (order.OrderStatus is not OrderStatusCodes.PendingPayment) { throw new BusinessException("当前订单状态不可支付"); } @@ -405,7 +414,81 @@ public partial class OrderService : ApplicationService [HttpPost("/order/parcel/create")] public async Task CreateParcelAsync(OrderParcelCreateInput input) { - return await CreateParcelCoreAsync(input); + var inbound = string.IsNullOrWhiteSpace(input.InboundMethod) + ? null + : input.InboundMethod.Trim(); + var createContext = inbound == null + ? null + : new ParcelCreateContext + { + InboundMethod = inbound, + PickupTime = string.Equals(inbound, OrderInboundMethodCodes.DoorPickup, StringComparison.OrdinalIgnoreCase) + ? input.ExpectPickupTime + : null, + CustomerSenderAddressId = string.Equals(inbound, OrderInboundMethodCodes.DoorPickup, StringComparison.OrdinalIgnoreCase) + ? input.SenderAddressId + : null + }; + + var output = await CreateParcelCoreAsync(input, createContext: createContext); + + if (string.Equals(inbound, OrderInboundMethodCodes.DoorPickup, StringComparison.OrdinalIgnoreCase)) + { + await TryAttachPickupAfterParcelCreateAsync(input, output); + } + + return output; + } + + private async Task TryAttachPickupAfterParcelCreateAsync( + OrderParcelCreateInput input, + OrderParcelCreateOutput output) + { + if (output.OrderId <= 0) + { + return; + } + + if (input.SenderAddressId is not > 0) + { + output.PickupCreateError = "上门揽收需选择发件地址"; + return; + } + + if (input.ExpectPickupTime is null || input.ExpectPickupTime == default) + { + output.PickupCreateError = "上门揽收需填写期望揽收时间"; + return; + } + + if (input.WarehouseId is not > 0) + { + output.PickupCreateError = "上门揽收需选择仓库"; + return; + } + + try + { + var pickupService = LazyServiceProvider.GetRequiredService(); + var pickup = await pickupService.CreateForParcelInternalAsync(new PickupOrderCreateInput + { + CustomerId = input.CustomerId, + SenderAddressId = input.SenderAddressId.Value, + WarehouseId = input.WarehouseId.Value, + CarrierCode = input.CarrierCode, + CarrierService = input.CarrierService, + ExpectPickupTime = input.ExpectPickupTime.Value, + OrderIds = [output.OrderId], + Remark = null + }); + output.PickupNo = pickup.PickupNo; + output.PickupOrderId = pickup.Id; + output.CarrierWaybillNo = pickup.CarrierWaybillNo; + } + catch (Exception ex) + { + output.PickupCreateError = ex.Message; + } } /// @@ -526,10 +609,14 @@ public partial class OrderService : ApplicationService Status = input.Status, HandleStatus = input.HandleStatus, OrderSource = input.OrderSource, + FulfillmentType = NormalizeFulfillmentTypeFilter(input.FulfillmentType), + StockBindStatus = NormalizeStockBindStatusFilter(input.StockBindStatus), + FulfillProgress = NormalizeFulfillProgressFilter(input.FulfillProgress), Keyword = NormalizeOrderKeyword(input.Keyword), CreateTimeStart = input.CreateTimeStart, CreateTimeEnd = input.CreateTimeEnd, CustomerId = customerId, + WarehouseId = NormalizeOrderWarehouseId(input.WarehouseId), FieldFilters = NormalizeOrderFieldFilters(input.Filters), SortField = NormalizeOrderSortField(input.SortField), SortOrder = NormalizeOrderSortOrder(input.SortOrder) @@ -544,6 +631,8 @@ public partial class OrderService : ApplicationService { Status = input.Status, OrderSource = input.OrderSource, + FulfillmentType = NormalizeFulfillmentTypeFilter(input.FulfillmentType), + FulfillProgress = NormalizeFulfillProgressFilter(input.FulfillProgress), Keyword = NormalizeOrderKeyword(input.Keyword), CreateTimeStart = input.CreateTimeStart, CreateTimeEnd = input.CreateTimeEnd, @@ -611,6 +700,7 @@ public partial class OrderService : ApplicationService "productCode", "channelCode", "orderSource", + "fulfillmentType", "payableAmount", "isPaid", "predeclareFailReason", @@ -634,6 +724,7 @@ public partial class OrderService : ApplicationService "serviceNo", "clientNo", "trackNo", + "primaryBinCode", "payableAmount", "payTime", "shipTime", @@ -711,6 +802,72 @@ public partial class OrderService : ApplicationService return null; } + private static string? NormalizeFulfillmentTypeFilter(string? fulfillmentType) + { + var code = fulfillmentType?.Trim(); + if (string.IsNullOrWhiteSpace(code) + || string.Equals(code, "all", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + if (!FulfillmentTypeCodes.All.Contains(code)) + { + throw new BusinessException($"不支持的履约类型:{fulfillmentType}"); + } + + return code; + } + + private static string? NormalizeStockBindStatusFilter(string? stockBindStatus) + { + var code = stockBindStatus?.Trim(); + if (string.IsNullOrWhiteSpace(code) + || string.Equals(code, "all", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + if (string.Equals(code, "none", StringComparison.OrdinalIgnoreCase) + || string.Equals(code, OrderStockBindStatusCodes.Bound, StringComparison.OrdinalIgnoreCase) + || string.Equals(code, OrderStockBindStatusCodes.Deducted, StringComparison.OrdinalIgnoreCase)) + { + if (string.Equals(code, "none", StringComparison.OrdinalIgnoreCase)) + { + return "none"; + } + + if (string.Equals(code, OrderStockBindStatusCodes.Bound, StringComparison.OrdinalIgnoreCase)) + { + return OrderStockBindStatusCodes.Bound; + } + + return OrderStockBindStatusCodes.Deducted; + } + + throw new BusinessException($"不支持的绑定状态筛选:{stockBindStatus}"); + } + + private static int? NormalizeOrderWarehouseId(int? warehouseId) => + warehouseId is > 0 ? warehouseId : null; + + private static string? NormalizeFulfillProgressFilter(string? fulfillProgress) + { + var code = fulfillProgress?.Trim(); + if (string.IsNullOrWhiteSpace(code) + || string.Equals(code, "all", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + if (FulfillmentProgressCodes.All.Contains(code)) + { + return code; + } + + throw new BusinessException($"不支持的代发进度筛选:{fulfillProgress}"); + } + private static List? NormalizeOrderFieldFilters( List? filters) { diff --git a/src/Oms.Application/Services/Orders/ParcelBillingCalculator.cs b/src/Oms.Application/Services/Orders/ParcelBillingCalculator.cs index c7a010d..331c327 100644 --- a/src/Oms.Application/Services/Orders/ParcelBillingCalculator.cs +++ b/src/Oms.Application/Services/Orders/ParcelBillingCalculator.cs @@ -3,6 +3,7 @@ using System.Text.Json; using System.Text.RegularExpressions; using Oms.Application.Dtos.Channels; using Oms.Application.Dtos.Orders; +using Oms.Application.Services.Orders.Issues; using Oms.Application.Shared; using Oms.Domain.ChannelsAggregate.Entities; using Oms.Domain.OrdersAggregate.Consts; @@ -373,14 +374,34 @@ internal static class ParcelBillingCalculator }; /// - /// 卖价/买价明细匹配共用上下文(分区、货物属性、计费重、仓库)。 + /// 卖价/买价明细匹配共用上下文(价格分区、偏远分区、货物属性、计费重、仓库)。 /// internal readonly record struct PriceDetailMatchContext( IReadOnlyList ZoneKeys, string CargoAttribute, decimal ChargeableWeight, int? WarehouseId = null, - string? WarehouseName = null); + string? WarehouseName = null, + IReadOnlyList? RemoteZoneKeys = null); + + /// + /// 偏远命中时用生效 RemoteAreaId(及可选名称)作为偏远分区匹配键;非偏远返回空。 + /// + public static IReadOnlyList BuildRemoteZoneKeys(int? remoteAreaId, string? remoteAreaName = null) + { + if (remoteAreaId is not > 0) + { + return Array.Empty(); + } + + var keys = new List { remoteAreaId.Value.ToString(CultureInfo.InvariantCulture) }; + if (!string.IsNullOrWhiteSpace(remoteAreaName)) + { + keys.Add(remoteAreaName.Trim()); + } + + return keys; + } public static List CalculateQuoteReceivableFees( SalesProductPricePublishSnapshotDto priceSnapshot, @@ -391,7 +412,11 @@ internal static class ParcelBillingCalculator string cargoAttribute, string? priceTierKey, int? warehouseId = null, - string? warehouseName = null) => + string? warehouseName = null, + OrderRuleEvaluationContext? conditionContext = null, + decimal? declaredSum = null, + string? declaredCurrency = null, + IReadOnlyList? remoteZoneKeys = null) => CalculateQuoteReceivableFeeLines( priceSnapshot, priceVersion, @@ -401,7 +426,11 @@ internal static class ParcelBillingCalculator cargoAttribute, priceTierKey, warehouseId, - warehouseName).Select(x => x.Fee).ToList(); + warehouseName, + conditionContext, + declaredSum, + declaredCurrency, + remoteZoneKeys).Select(x => x.Fee).ToList(); public static List CalculateQuoteReceivableFeeLines( SalesProductPricePublishSnapshotDto priceSnapshot, @@ -412,10 +441,15 @@ internal static class ParcelBillingCalculator string cargoAttribute, string? priceTierKey, int? warehouseId = null, - string? warehouseName = null) + string? warehouseName = null, + OrderRuleEvaluationContext? conditionContext = null, + decimal? declaredSum = null, + string? declaredCurrency = null, + IReadOnlyList? remoteZoneKeys = null) { var items = priceSnapshot.Prices.Select(p => new ReceivableBillingPriceItem( - p.Status, p.CostItem, p.PriceName, p.Currency, p.Details)); + p.Status, p.CostItem, p.PriceName, p.Currency, p.Details, + p.SerialNumber, p.ChargingCondition, p.CostUnit)); return CalculateReceivableFeeLines( items, priceVersion, @@ -426,7 +460,11 @@ internal static class ParcelBillingCalculator priceTierKey, OrderFeeChargingStageCodes.Forecast, warehouseId, - warehouseName); + warehouseName, + conditionContext, + declaredSum, + declaredCurrency, + remoteZoneKeys); } public static bool HasEnabledQuotePriceItems(SalesProductPricePublishSnapshotDto priceSnapshot) => @@ -590,6 +628,128 @@ internal static class ParcelBillingCalculator return string.Join(";", reasons); } + /// + /// 买价未命中时,按价格项输出具体原因(分区/货物类型/重量区间等)。 + /// + public static string ExplainPayablePriceMiss( + IReadOnlyList prices, + decimal chargeableWeight, + IReadOnlyList zoneKeys, + string cargoAttribute, + int? warehouseId = null, + string? warehouseName = null, + IReadOnlyList? remoteZoneKeys = null) + { + var cargoLabel = GetCargoAttributeLabel(cargoAttribute); + var warehouseLabel = FormatWarehouseLabel(warehouseId, warehouseName); + var enabledPrices = prices.Where(x => EnableStatusRules.IsEnabled(x.Status)).ToList(); + if (enabledPrices.Count == 0) + { + return "买价中无启用的价格项"; + } + + var reasons = new List(); + foreach (var price in enabledPrices) + { + var label = !string.IsNullOrWhiteSpace(price.PriceName) ? price.PriceName! : price.CostItem; + var details = price.Details ?? []; + if (details.Count == 0) + { + reasons.Add($"【{label}】价格项Id={price.Id}:无明细行"); + continue; + } + + var zoneMatchedDetails = details.Where(detail => + { + var factors = ParseFactorDictionary(detail.FactorValuesJson); + return ZoneMatches(factors, zoneKeys); + }).ToList(); + + if (zoneMatchedDetails.Count == 0) + { + var detailZones = details + .Select(detail => + { + var factors = ParseFactorDictionary(detail.FactorValuesJson); + return TryGetZoneFactorText(factors, out var zone) ? zone.Trim() : null; + }) + .Where(zone => !string.IsNullOrWhiteSpace(zone)) + .Distinct(StringComparer.OrdinalIgnoreCase); + reasons.Add( + $"【{label}】分区不匹配,明细分区=[{string.Join(", ", detailZones)}]," + + $"订单分区键=[{string.Join(", ", zoneKeys)}]"); + continue; + } + + var cargoMatchedDetails = zoneMatchedDetails.Where(detail => + { + var factors = ParseFactorDictionary(detail.FactorValuesJson); + return MatchCargoTypeFactor(factors, cargoAttribute); + }).ToList(); + + if (cargoMatchedDetails.Count == 0) + { + reasons.Add($"【{label}】货物类型不匹配,当前={cargoLabel}"); + continue; + } + + var warehouseMatchedDetails = cargoMatchedDetails.Where(detail => + { + var factors = ParseFactorDictionary(detail.FactorValuesJson); + return MatchWarehouseFactor(factors, warehouseId, warehouseName); + }).ToList(); + + if (warehouseMatchedDetails.Count == 0) + { + reasons.Add($"【{label}】仓库不匹配,当前={warehouseLabel}"); + continue; + } + + var remoteMatchedDetails = warehouseMatchedDetails.Where(detail => + { + var factors = ParseFactorDictionary(detail.FactorValuesJson); + return RemoteZoneMatches(factors, remoteZoneKeys); + }).ToList(); + + if (remoteMatchedDetails.Count == 0) + { + reasons.Add($"【{label}】偏远分区不匹配"); + continue; + } + + var weightMatched = false; + var intervals = new List(); + foreach (var detail in remoteMatchedDetails) + { + var factors = ParseFactorDictionary(detail.FactorValuesJson); + if (!TryGetWeightFactorText(factors, out var weightText)) + { + weightMatched = true; + break; + } + + intervals.Add(weightText); + if (TryParseWeightInterval(weightText, out var rangeStart, out var rangeEnd) + && WeightInLeftOpenRightClosedInterval(chargeableWeight, rangeStart, rangeEnd)) + { + weightMatched = true; + break; + } + } + + if (!weightMatched) + { + var intervalText = intervals.Count > 0 + ? string.Join(", ", intervals.Distinct(StringComparer.OrdinalIgnoreCase)) + : "无有效重量区间"; + reasons.Add( + $"【{label}】计费重 {chargeableWeight}kg 未落入重量区间 [{intervalText}]"); + } + } + + return string.Join(";", reasons); + } + public static List CalculateForecastReceivableFees( SalesProductPricePublishSnapshotDto priceSnapshot, string priceVersion, @@ -639,10 +799,15 @@ internal static class ParcelBillingCalculator string? priceTierKey, string chargingStage, int? warehouseId = null, - string? warehouseName = null) + string? warehouseName = null, + OrderRuleEvaluationContext? conditionContext = null, + decimal? declaredSum = null, + string? declaredCurrency = null, + IReadOnlyList? remoteZoneKeys = null) { var items = priceSnapshot.Prices.Select(p => new ReceivableBillingPriceItem( - p.Status, p.CostItem, p.PriceName, p.Currency, p.Details)); + p.Status, p.CostItem, p.PriceName, p.Currency, p.Details, + p.SerialNumber, p.ChargingCondition, p.CostUnit)); return CalculateReceivableFeesFromItems( items, priceVersion, @@ -653,7 +818,11 @@ internal static class ParcelBillingCalculator priceTierKey, chargingStage, warehouseId, - warehouseName); + warehouseName, + conditionContext, + declaredSum, + declaredCurrency, + remoteZoneKeys); } /// @@ -668,16 +837,30 @@ internal static class ParcelBillingCalculator string cargoAttribute, string chargingStage, int? warehouseId = null, - string? warehouseName = null) + string? warehouseName = null, + OrderRuleEvaluationContext? conditionContext = null, + decimal? declaredSum = null, + string? declaredCurrency = null, + IReadOnlyList? remoteZoneKeys = null) { var items = prices.Select(p => new PayableBillingPriceItem( - p.Status, p.CostItem, p.Currency, p.Details)); + p.Status, p.CostItem, p.Currency, p.Details, + p.SerialNumber, p.ChargingCondition)); return CalculatePayableFeesFromItems( items, priceVersion, priceEffectiveTime, - new PriceDetailMatchContext(zoneKeys, cargoAttribute, chargeableWeight, warehouseId, warehouseName), - chargingStage); + new PriceDetailMatchContext( + zoneKeys, + cargoAttribute, + chargeableWeight, + warehouseId, + warehouseName, + remoteZoneKeys), + chargingStage, + conditionContext, + declaredSum, + declaredCurrency); } /// @@ -691,7 +874,10 @@ internal static class ParcelBillingCalculator string zoneName, string cargoAttribute, int? warehouseId = null, - string? warehouseName = null) => + string? warehouseName = null, + OrderRuleEvaluationContext? conditionContext = null, + decimal? declaredSum = null, + string? declaredCurrency = null) => CalculatePayableFees( prices, priceVersion, @@ -701,7 +887,34 @@ internal static class ParcelBillingCalculator cargoAttribute, OrderFeeChargingStageCodes.Forecast, warehouseId, - warehouseName); + warehouseName, + conditionContext, + declaredSum, + declaredCurrency); + + /// + /// 计费条件:空/null/「无」视为命中;否则按中文公式求值,求值失败视为未命中。 + /// + public static bool IsBillingConditionMet(string? condition, OrderRuleEvaluationContext? context) + { + if (string.IsNullOrWhiteSpace(condition)) + { + return true; + } + + var trimmed = condition.Trim(); + if (string.Equals(trimmed, "无", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (context == null) + { + return false; + } + + return ChineseFormulaEvaluator.TryEvaluate(trimmed, context, out var hit) && hit; + } public static bool HasEnabledForecastPriceItems(SalesProductPricePublishSnapshotDto priceSnapshot) => HasEnabledReceivablePriceItems(priceSnapshot); @@ -810,6 +1023,8 @@ internal static class ParcelBillingCalculator { "freight" => "运费", "handling" => "操作费", + "proxyPacking" => "代打包费", + "insurance" => "保险费", _ => costItem }; } @@ -838,14 +1053,12 @@ internal static class ParcelBillingCalculator string? priceTierKey, string chargingStage, int? warehouseId = null, - string? warehouseName = null) - { - if (chargeableWeight <= 0) - { - return []; - } - - return CalculateReceivableFeeLines( + string? warehouseName = null, + OrderRuleEvaluationContext? conditionContext = null, + decimal? declaredSum = null, + string? declaredCurrency = null, + IReadOnlyList? remoteZoneKeys = null) => + CalculateReceivableFeeLines( priceItems, priceVersion, priceEffectiveTime, @@ -855,8 +1068,11 @@ internal static class ParcelBillingCalculator priceTierKey, chargingStage, warehouseId, - warehouseName).Select(x => x.Fee).ToList(); - } + warehouseName, + conditionContext, + declaredSum, + declaredCurrency, + remoteZoneKeys).Select(x => x.Fee).ToList(); private static List CalculateReceivableFeeLines( IEnumerable priceItems, @@ -868,23 +1084,55 @@ internal static class ParcelBillingCalculator string? priceTierKey, string chargingStage, int? warehouseId = null, - string? warehouseName = null) + string? warehouseName = null, + OrderRuleEvaluationContext? conditionContext = null, + decimal? declaredSum = null, + string? declaredCurrency = null, + IReadOnlyList? remoteZoneKeys = null) { - var fees = new List(); + var pass1 = new List<(int SerialNumber, BillingFeeLine Line)>(); + var percentFreightPending = new List<(int SerialNumber, ReceivableBillingPriceItem PriceItem, ChannelPriceDetailOutput Detail)>(); + foreach (var priceItem in priceItems.Where(x => EnableStatusRules.IsEnabled(x.Status))) { + if (!IsBillingConditionMet(priceItem.ChargingCondition, conditionContext)) + { + continue; + } + + if (chargeableWeight <= 0 && !CanBillWithoutChargeableWeight(priceItem.Details)) + { + continue; + } + var detail = MatchPriceDetail( priceItem.Details, zoneKeys, cargoAttribute, chargeableWeight, warehouseId, - warehouseName); + warehouseName, + remoteZoneKeys); if (detail == null) { continue; } + var formula = NormalizeCalculationFormula(detail.CalculationFormula); + if (formula == "percent_freight") + { + percentFreightPending.Add((priceItem.SerialNumber, priceItem, detail)); + continue; + } + + if (formula == "percent_declared" + && !string.IsNullOrWhiteSpace(declaredCurrency) + && !string.IsNullOrWhiteSpace(priceItem.Currency) + && !string.Equals(declaredCurrency.Trim(), priceItem.Currency.Trim(), StringComparison.OrdinalIgnoreCase)) + { + continue; + } + var amount = CalculateDetailAmount( priceItem.Details, detail, @@ -893,7 +1141,13 @@ internal static class ParcelBillingCalculator chargeableWeight, priceTierKey, warehouseId, - warehouseName); + warehouseName, + declaredSum); + if (amount <= 0) + { + continue; + } + var formulaPart = BuildDetailFormulaExpression( priceItem.Details, detail, @@ -902,8 +1156,9 @@ internal static class ParcelBillingCalculator chargeableWeight, priceTierKey, warehouseId, - warehouseName); - fees.Add(new BillingFeeLine + warehouseName, + declaredSum); + pass1.Add((priceItem.SerialNumber, new BillingFeeLine { Fee = new OrderFee { @@ -917,10 +1172,46 @@ internal static class ParcelBillingCalculator }, PriceName = priceItem.PriceName, FormulaPart = formulaPart - }); + })); } - return fees; + var pass1Deduped = DedupeFeeLinesByCostItem(pass1); + var candidates = new List<(int SerialNumber, BillingFeeLine Line)>(pass1); + foreach (var pending in percentFreightPending) + { + var freightBase = SumFreightBaseAmount( + pass1Deduped.Select(x => x.Fee), + pending.PriceItem.Currency); + if (freightBase <= 0) + { + continue; + } + + var rate = ResolvePriceTierKeyPrice(pending.Detail, priceTierKey) ?? pending.Detail.CalculatedValue ?? 0; + var amount = CalculatePercentFreightAmount(rate, freightBase); + if (amount <= 0) + { + continue; + } + + candidates.Add((pending.SerialNumber, new BillingFeeLine + { + Fee = new OrderFee + { + Type = OrderFeeTypeCodes.Receivable, + CostItem = pending.PriceItem.CostItem, + Amount = amount, + Currency = pending.PriceItem.Currency, + PriceNo = priceVersion, + PriceEffectiveTime = priceEffectiveTime, + ChargingStage = chargingStage + }, + PriceName = pending.PriceItem.PriceName, + FormulaPart = BuildPercentFreightFormulaExpression(rate, freightBase) + })); + } + + return DedupeFeeLinesByCostItem(candidates); } private static List CalculatePayableFeesFromItems( @@ -928,35 +1219,61 @@ internal static class ParcelBillingCalculator string priceVersion, DateTime priceEffectiveTime, PriceDetailMatchContext match, - string chargingStage) + string chargingStage, + OrderRuleEvaluationContext? conditionContext = null, + decimal? declaredSum = null, + string? declaredCurrency = null) { - if (match.ChargeableWeight <= 0) - { - return []; - } + var pass1 = new List<(int SerialNumber, OrderFee Fee)>(); + var percentFreightPending = new List<(int SerialNumber, PayableBillingPriceItem PriceItem, ChannelPriceDetailOutput Detail)>(); - var fees = new List(); foreach (var priceItem in priceItems.Where(x => EnableStatusRules.IsEnabled(x.Status))) { + if (!IsBillingConditionMet(priceItem.ChargingCondition, conditionContext)) + { + continue; + } + + if (match.ChargeableWeight <= 0 && !CanBillWithoutChargeableWeight(priceItem.Details)) + { + continue; + } + var detail = MatchPriceDetail( priceItem.Details, match.ZoneKeys, match.CargoAttribute, match.ChargeableWeight, match.WarehouseId, - match.WarehouseName); + match.WarehouseName, + match.RemoteZoneKeys); if (detail == null) { continue; } - var amount = CalculatePayableDetailAmount(priceItem.Details, detail, match); + var formula = NormalizeCalculationFormula(detail.CalculationFormula); + if (formula == "percent_freight") + { + percentFreightPending.Add((priceItem.SerialNumber, priceItem, detail)); + continue; + } + + if (formula == "percent_declared" + && !string.IsNullOrWhiteSpace(declaredCurrency) + && !string.IsNullOrWhiteSpace(priceItem.Currency) + && !string.Equals(declaredCurrency.Trim(), priceItem.Currency.Trim(), StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + var amount = CalculatePayableDetailAmount(priceItem.Details, detail, match, declaredSum); if (amount <= 0) { continue; } - fees.Add(new OrderFee + pass1.Add((priceItem.SerialNumber, new OrderFee { Type = OrderFeeTypeCodes.Payable, CostItem = priceItem.CostItem, @@ -965,10 +1282,87 @@ internal static class ParcelBillingCalculator PriceNo = priceVersion, PriceEffectiveTime = priceEffectiveTime, ChargingStage = chargingStage - }); + })); } - return fees; + var pass1Deduped = DedupeFeesByCostItem(pass1); + var candidates = new List<(int SerialNumber, OrderFee Fee)>(pass1); + foreach (var pending in percentFreightPending) + { + var freightBase = SumFreightBaseAmount(pass1Deduped, pending.PriceItem.Currency); + if (freightBase <= 0) + { + continue; + } + + var rate = ResolveBuyPrice(pending.Detail); + var amount = CalculatePercentFreightAmount(rate, freightBase); + if (amount <= 0) + { + continue; + } + + candidates.Add((pending.SerialNumber, new OrderFee + { + Type = OrderFeeTypeCodes.Payable, + CostItem = pending.PriceItem.CostItem, + Amount = amount, + Currency = pending.PriceItem.Currency, + PriceNo = priceVersion, + PriceEffectiveTime = priceEffectiveTime, + ChargingStage = chargingStage + })); + } + + return DedupeFeesByCostItem(candidates); + } + + private static decimal SumFreightBaseAmount(IEnumerable fees, string? currency) + { + var query = fees.Where(x => IsFreightCostItem(x.CostItem)); + if (!string.IsNullOrWhiteSpace(currency)) + { + query = query.Where(x => + string.IsNullOrWhiteSpace(x.Currency) + || string.Equals(x.Currency.Trim(), currency.Trim(), StringComparison.OrdinalIgnoreCase)); + } + + return query.Sum(x => x.Amount); + } + + private static List DedupeFeeLinesByCostItem( + IReadOnlyList<(int SerialNumber, BillingFeeLine Line)> candidates) => + candidates + .GroupBy(x => x.Line.Fee.CostItem, StringComparer.OrdinalIgnoreCase) + .Select(g => g.OrderBy(x => x.SerialNumber).First().Line) + .ToList(); + + private static List DedupeFeesByCostItem( + IReadOnlyList<(int SerialNumber, OrderFee Fee)> candidates) => + candidates + .GroupBy(x => x.Fee.CostItem, StringComparer.OrdinalIgnoreCase) + .Select(g => g.OrderBy(x => x.SerialNumber).First().Fee) + .ToList(); + + private static bool CanBillWithoutChargeableWeight(IReadOnlyList details) + { + foreach (var detail in details) + { + var formula = NormalizeCalculationFormula(detail.CalculationFormula); + // percent_freight 依赖同批次运费;无计费重时先放行,pass-2 若无运费则跳过。 + if (formula is not ("percent_declared" or "percent_freight" or "total")) + { + continue; + } + + var factors = ParseFactorDictionary(detail.FactorValuesJson); + if (!TryGetWeightFactorText(factors, out _)) + { + return true; + } + } + + return false; } /// @@ -977,13 +1371,17 @@ internal static class ParcelBillingCalculator private static decimal CalculatePayableDetailAmount( IReadOnlyList allDetails, ChannelPriceDetailOutput detail, - PriceDetailMatchContext match) + PriceDetailMatchContext match, + decimal? declaredSum = null) { return NormalizeCalculationFormula(detail.CalculationFormula) switch { "unit" => CalculateBuyUnitPrice(detail, match.ChargeableWeight), "total" => ResolveBuyPrice(detail), "continue" => CalculateBuyContinueAmount(allDetails, detail, match), + "percent_declared" => CalculatePercentDeclaredAmount(ResolveBuyPrice(detail), declaredSum), + // percent_freight 在两趟计算的第二趟处理 + "percent_freight" => 0, _ => ResolveBuyPrice(detail) }; } @@ -1033,6 +1431,7 @@ internal static class ParcelBillingCalculator { var factors = ParseFactorDictionary(candidate.FactorValuesJson); if (!ZoneMatches(factors, match.ZoneKeys) + || !RemoteZoneMatches(factors, match.RemoteZoneKeys) || !MatchCargoTypeFactor(factors, match.CargoAttribute) || !MatchWarehouseFactor(factors, match.WarehouseId, match.WarehouseName)) { @@ -1088,13 +1487,18 @@ internal static class ParcelBillingCalculator string CostItem, string PriceName, string Currency, - List Details); + List Details, + int SerialNumber = 0, + string? ChargingCondition = null, + string? CostUnit = null); private readonly record struct PayableBillingPriceItem( byte Status, string CostItem, string Currency, - List Details); + List Details, + int SerialNumber = 0, + string? ChargingCondition = null); private static ChannelPriceDetailOutput? MatchPriceDetail( IReadOnlyList details, @@ -1102,7 +1506,8 @@ internal static class ParcelBillingCalculator string cargoAttribute, decimal chargeableWeight, int? warehouseId = null, - string? warehouseName = null) + string? warehouseName = null, + IReadOnlyList? remoteZoneKeys = null) { ChannelPriceDetailOutput? bestMatch = null; var bestIntervalWidth = decimal.MaxValue; @@ -1115,6 +1520,11 @@ internal static class ParcelBillingCalculator continue; } + if (!RemoteZoneMatches(factors, remoteZoneKeys)) + { + continue; + } + if (!MatchCargoTypeFactor(factors, cargoAttribute)) { continue; @@ -1205,6 +1615,24 @@ internal static class ParcelBillingCalculator return zoneKeys.Any(key => string.Equals(key.Trim(), expected, StringComparison.OrdinalIgnoreCase)); } + private static bool RemoteZoneMatches(Dictionary factors, IReadOnlyList? remoteZoneKeys) + { + if (!TryGetRemoteZoneFactorText(factors, out var remoteZoneValue)) + { + return true; + } + + if (remoteZoneKeys == null || remoteZoneKeys.Count == 0) + { + return false; + } + + var expected = remoteZoneValue.Trim(); + return remoteZoneKeys.Any(key => + !string.IsNullOrWhiteSpace(key) + && string.Equals(key.Trim(), expected, StringComparison.OrdinalIgnoreCase)); + } + private static bool TryGetZoneFactorText(Dictionary factors, out string zoneValue) { if (TryGetFactorValue(factors, out zoneValue, "分区", "价格分区", "zone")) @@ -1216,6 +1644,17 @@ internal static class ParcelBillingCalculator return false; } + private static bool TryGetRemoteZoneFactorText(Dictionary factors, out string remoteZoneValue) + { + if (TryGetFactorValue(factors, out remoteZoneValue, "偏远分区", "remoteZone")) + { + return !string.IsNullOrWhiteSpace(remoteZoneValue); + } + + remoteZoneValue = string.Empty; + return false; + } + private static bool TryGetWeightFactorText(Dictionary factors, out string weightText) => TryGetFactorValue(factors, out weightText, "重量", "weight") && !string.IsNullOrWhiteSpace(weightText); @@ -1334,7 +1773,8 @@ internal static class ParcelBillingCalculator decimal chargeableWeight, string? priceTierKey, int? warehouseId = null, - string? warehouseName = null) + string? warehouseName = null, + decimal? declaredSum = null) { return NormalizeCalculationFormula(detail.CalculationFormula) switch { @@ -1349,6 +1789,11 @@ internal static class ParcelBillingCalculator priceTierKey, warehouseId, warehouseName), + "percent_declared" => CalculatePercentDeclaredAmount( + ResolvePriceTierKeyPrice(detail, priceTierKey) ?? detail.CalculatedValue ?? 0, + declaredSum), + // percent_freight 在两趟计算的第二趟处理 + "percent_freight" => 0, _ => detail.CalculatedValue ?? 0 }; } @@ -1361,7 +1806,9 @@ internal static class ParcelBillingCalculator decimal chargeableWeight, string? priceTierKey, int? warehouseId = null, - string? warehouseName = null) + string? warehouseName = null, + decimal? declaredSum = null, + decimal? freightBase = null) { return NormalizeCalculationFormula(detail.CalculationFormula) switch { @@ -1377,10 +1824,45 @@ internal static class ParcelBillingCalculator priceTierKey, warehouseId, warehouseName), + "percent_declared" => BuildPercentDeclaredFormulaExpression( + ResolvePriceTierKeyPrice(detail, priceTierKey) ?? detail.CalculatedValue ?? 0, + declaredSum), + "percent_freight" => BuildPercentFreightFormulaExpression( + ResolvePriceTierKeyPrice(detail, priceTierKey) ?? detail.CalculatedValue ?? 0, + freightBase ?? 0M), _ => FormatDecimal(detail.CalculatedValue ?? 0) }; } + private static decimal CalculatePercentDeclaredAmount(decimal rate, decimal? declaredSum) + { + if (!declaredSum.HasValue || declaredSum.Value <= 0 || rate <= 0) + { + return 0; + } + + return Math.Round(declaredSum.Value * rate / 100M, 2, MidpointRounding.AwayFromZero); + } + + private static string BuildPercentDeclaredFormulaExpression(decimal rate, decimal? declaredSum) + { + var sum = declaredSum is > 0 ? declaredSum.Value : 0M; + return $"{FormatDecimal(sum)}*{FormatDecimal(rate)}/100"; + } + + private static decimal CalculatePercentFreightAmount(decimal rate, decimal freightBase) + { + if (freightBase <= 0 || rate <= 0) + { + return 0; + } + + return Math.Round(freightBase * rate / 100M, 2, MidpointRounding.AwayFromZero); + } + + private static string BuildPercentFreightFormulaExpression(decimal rate, decimal freightBase) => + $"{FormatDecimal(freightBase)}*{FormatDecimal(rate)}/100"; + private static string BuildUnitFormulaExpression( ChannelPriceDetailOutput detail, decimal chargeableWeight, @@ -1526,6 +2008,7 @@ internal static class ParcelBillingCalculator continue; } + // 续重邻档总价查找不按偏远分区过滤:邻档通常与运费同组,偏远费单独成项。 if (NormalizeCalculationFormula(candidate.CalculationFormula) != "total") { continue; @@ -1565,6 +2048,8 @@ internal static class ParcelBillingCalculator "unit" or "单价" => "unit", "total" or "总价" or "固定价" => "total", "continueunit" or "continue_unit" or "continueprice" or "continue_price" or "续单价" or "续重价" => "continue", + "percent_declared" or "percentdeclared" or "申报比例" or "申报金额比例" or "货值比例" => "percent_declared", + "percent_freight" or "percentfreight" or "运费比例" or "运费百分比" => "percent_freight", _ => value.ToLowerInvariant() }; } @@ -1647,6 +2132,12 @@ internal static class ParcelBillingCalculator return null; } + // 「全部客户」优先:任意价区键共用这一列 + if (TryGetMapPrice(map, out var allPrice, "全部客户", "all")) + { + return allPrice; + } + if (!string.IsNullOrWhiteSpace(priceTierKey) && map.TryGetValue(priceTierKey.Trim(), out var tierPrice)) { @@ -1661,6 +2152,32 @@ internal static class ParcelBillingCalculator return null; } + private static bool TryGetMapPrice( + Dictionary map, + out decimal price, + params string[] keys) + { + foreach (var key in keys) + { + if (map.TryGetValue(key, out price)) + { + return true; + } + + foreach (var pair in map) + { + if (string.Equals(pair.Key, key, StringComparison.OrdinalIgnoreCase)) + { + price = pair.Value; + return true; + } + } + } + + price = 0; + return false; + } + private static bool EvaluateCondition(string condition, decimal gw, decimal vw) { if (string.IsNullOrWhiteSpace(condition)) diff --git a/src/Oms.Application/Services/Orders/ParcelQuoteContext.cs b/src/Oms.Application/Services/Orders/ParcelQuoteContext.cs index 357469a..8b00eb0 100644 --- a/src/Oms.Application/Services/Orders/ParcelQuoteContext.cs +++ b/src/Oms.Application/Services/Orders/ParcelQuoteContext.cs @@ -29,4 +29,19 @@ internal sealed class ParcelQuoteContext public decimal Height { get; init; } public decimal ActualWeight { get; init; } + + /// + /// 勾选附加服务字典 code。 + /// + public List? AdditionalServices { get; init; } + + /// + /// 申报总金额。 + /// + public decimal? DeclaredSum { get; init; } + + /// + /// 申报币种。 + /// + public string? DeclaredCurrency { get; init; } } diff --git a/src/Oms.Application/Services/Orders/PickupOrderService.cs b/src/Oms.Application/Services/Orders/PickupOrderService.cs new file mode 100644 index 0000000..e00debf --- /dev/null +++ b/src/Oms.Application/Services/Orders/PickupOrderService.cs @@ -0,0 +1,1021 @@ +using Fake.Application; +using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Orders; +using Oms.Application.Dtos.Shared; +using Oms.Application.Shared; +using Oms.Domain.CustomersAggregate.Repositories; +using Oms.Domain.OrdersAggregate.Consts; +using Oms.Domain.OrdersAggregate.Entities; +using Oms.Domain.OrdersAggregate.Repositories; +using Oms.Domain.SystemAggregate.Repositories; + +namespace Oms.Application.Services.Orders; + +/// +/// 揽收单(1 揽收 : N 物流)管理。 +/// +[ApiExplorerSettings(GroupName = "OMS-Order")] +public class PickupOrderService : ApplicationService +{ + private static readonly HashSet BindableOrderStatuses = new(StringComparer.OrdinalIgnoreCase) + { + OrderStatusCodes.Draft, + OrderStatusCodes.Predeclared, + OrderStatusCodes.PendingAllocation, + OrderStatusCodes.PendingPayment, + OrderStatusCodes.PendingShip, + OrderStatusCodes.PendingOnline, + }; + + private IPickupOrderRepository PickupOrderRepository => + LazyServiceProvider.GetRequiredService(); + + private IPickupOrderLineRepository PickupOrderLineRepository => + LazyServiceProvider.GetRequiredService(); + + private IOrderRepository OrderRepository => + LazyServiceProvider.GetRequiredService(); + + private ICustomerRepository CustomerRepository => + LazyServiceProvider.GetRequiredService(); + + private ICustomerSenderAddressRepository CustomerSenderAddressRepository => + LazyServiceProvider.GetRequiredService(); + + private IWarehouseAddressRepository WarehouseAddressRepository => + LazyServiceProvider.GetRequiredService(); + + private ICountryRepository CountryRepository => + LazyServiceProvider.GetRequiredService(); + + /// + /// 创建揽收单并挂载物流单(原子:全部校验通过才落库)。 + /// + [HttpPost("/order/pickup-order/create")] + public async Task CreateAsync([FromBody] PickupOrderCreateInput input) + { + var customerId = await WarehouseCustomerHelper.ResolveRequiredCustomerIdAsync( + CustomerRepository, + CurrentUser, + input.CustomerId); + var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == customerId); + CustomerContactHelper.EnsureContactComplete(customer); + + if (input.SenderAddressId <= 0) + { + throw new BusinessException("发件地址不能为空"); + } + + if (input.WarehouseId <= 0) + { + throw new BusinessException("仓库不能为空"); + } + + if (input.ExpectPickupTime == default) + { + throw new BusinessException("期望揽收时间不能为空"); + } + + var orderIds = (input.OrderIds ?? []).Where(x => x > 0).Distinct().ToList(); + if (orderIds.Count == 0) + { + throw new BusinessException("请至少选择一票物流订单"); + } + + var senderAddress = await CustomerSenderAddressRepository.GetOwnedAsync(input.SenderAddressId, customerId); + if (senderAddress == null) + { + throw new BusinessException("发件地址不存在"); + } + + var addressType = string.IsNullOrWhiteSpace(senderAddress.AddressType) + ? CustomerAddressTypeCodes.Sender + : senderAddress.AddressType; + if (!string.Equals(addressType, CustomerAddressTypeCodes.Sender, StringComparison.OrdinalIgnoreCase)) + { + throw new BusinessException("揽收单仅可选择发件地址"); + } + + var warehouse = await WarehouseAddressRepository.FirstOrDefaultAsync(x => x.Id == input.WarehouseId); + if (warehouse == null) + { + throw new BusinessException("仓库不存在"); + } + + var orders = await OrderRepository.GetListAsync(x => orderIds.Contains(x.Id)); + var orderMap = orders.ToDictionary(x => x.Id); + var existingLines = await PickupOrderLineRepository.GetActiveByOrderIdsAsync(orderIds); + var existingByOrderId = existingLines.ToDictionary(x => x.OrderId); + + var rejected = new List(); + var accepted = new List(); + foreach (var orderId in orderIds) + { + if (!orderMap.TryGetValue(orderId, out var order)) + { + rejected.Add(new PickupOrderRejectItem { OrderId = orderId, Reason = "订单不存在" }); + continue; + } + + var reason = ValidateOrderForBind( + order, + customerId, + input.WarehouseId, + input.SenderAddressId, + existingByOrderId.GetValueOrDefault(orderId)); + if (reason != null) + { + rejected.Add(new PickupOrderRejectItem + { + OrderId = orderId, + ServiceNo = order.ServiceNo, + Reason = reason + }); + continue; + } + + accepted.Add(order); + } + + if (rejected.Count > 0) + { + throw new BusinessException( + "部分运单不能合并揽收:" + + string.Join(";", rejected.Select(x => $"{x.ServiceNo ?? x.OrderId.ToString()} — {x.Reason}"))); + } + + if (accepted.Count == 0) + { + throw new BusinessException("没有可挂载的物流订单"); + } + + string? senderCountryCode = null; + if (senderAddress.Country.HasValue) + { + var country = await CountryRepository.FirstOrDefaultAsync(x => x.Id == senderAddress.Country.Value); + senderCountryCode = country?.CountryCode; + } + + if (!string.IsNullOrWhiteSpace(input.RequestId)) + { + var existedByRequest = await PickupOrderRepository.FirstOrDefaultAsync(x => x.RequestId == input.RequestId.Trim()); + if (existedByRequest != null) + { + if (existedByRequest.CustomerId != customerId) + { + throw new BusinessException("幂等请求已存在"); + } + + return await MapOutputAsync(existedByRequest, includeOrders: true); + } + } + + var weights = await OrderRepository.GetWeightsByOrderIdsAsync(accepted.Select(x => x.Id)); + var weightSum = weights + .GroupBy(x => x.OrderId) + .Select(g => g.OrderByDescending(w => w.Type == OrderWeightTypeCodes.Receive ? 2 : 1).FirstOrDefault()) + .Where(x => x != null) + .Sum(x => x!.ActualWeight ?? 0); + + var freight = input.FreightAmount; + var receivable = freight; + var orgId = accepted + .Select(x => x.OrganizationId) + .FirstOrDefault(x => !string.IsNullOrWhiteSpace(x)); + var secretLevel = accepted + .Select(x => x.SecretLevel) + .FirstOrDefault(x => x > 0); + if (secretLevel <= 0) + { + secretLevel = 2; + } + + var entity = new PickupOrder + { + PickupNo = await GeneratePickupNoAsync(), + RequestId = NormalizeOptional(input.RequestId), + CustomerId = customerId, + OrganizationId = orgId, + SecretLevel = secretLevel, + SenderAddressId = senderAddress.Id, + SenderName = senderAddress.SenderName ?? string.Empty, + SenderCompany = senderAddress.Company, + SenderCountry = senderAddress.Country, + SenderCountryCode = senderCountryCode, + SenderProvince = senderAddress.Province, + SenderCity = senderAddress.City, + SenderZipCode = senderAddress.ZipCode, + SenderStreetAddress1 = senderAddress.StreetAddress1 ?? string.Empty, + SenderStreetAddress2 = senderAddress.StreetAddress2, + SenderStreetAddress3 = senderAddress.StreetAddress3, + SenderHouseNumber = senderAddress.HouseNumber, + SenderPhone = senderAddress.Phone, + SenderTelePhone = senderAddress.TelePhone, + SenderEmail = senderAddress.Email, + WarehouseId = input.WarehouseId, + CarrierCode = NormalizeOptional(input.CarrierCode), + CarrierService = NormalizeOptional(input.CarrierService), + ExpectPickupTime = input.ExpectPickupTime, + Status = PickupOrderStatusCodes.Draft, + ParcelCount = accepted.Count, + TotalActualWeight = weightSum > 0 ? weightSum : null, + Currency = "CNY", + FreightAmount = freight, + OtherFeeAmount = null, + ReceivableAmount = receivable, + PayStatus = PickupPayStatusCodes.Unpaid, + PayMode = PickupPayModeCodes.Prepaid, + SettlementStatus = PickupSettlementStatusCodes.None, + Remark = NormalizeOptional(input.Remark) + }; + + await PickupOrderRepository.InsertAsync(entity); + + var sort = 0; + foreach (var order in accepted) + { + await PickupOrderLineRepository.InsertAsync(new PickupOrderLine + { + PickupOrderId = entity.Id, + OrderId = order.Id, + ServiceNo = order.ServiceNo, + ClientNo = order.ClientNo, + SortNo = sort++ + }); + + order.PickupOrderId = entity.Id; + order.InboundMethod = OrderInboundMethodCodes.DoorPickup; + order.PickupTime = entity.ExpectPickupTime; + order.CustomerSenderAddressId = entity.SenderAddressId; + await OrderRepository.UpdateAsync(order); + } + + return await MapOutputAsync(entity, includeOrders: true); + } + + /// + /// 追加物流单到已有揽收单。 + /// + [HttpPost("/order/pickup-order/add-orders")] + public async Task AddOrdersAsync([FromBody] PickupOrderOrdersInput input) + { + var pickup = await GetOwnedPickupOrThrowAsync(input.Id); + if (!PickupOrderStatusCodes.IsMutableBinding(pickup.Status)) + { + throw new BusinessException("当前揽收单状态不可追加运单"); + } + + var orderIds = (input.OrderIds ?? []).Where(x => x > 0).Distinct().ToList(); + if (orderIds.Count == 0) + { + throw new BusinessException("请至少选择一票物流订单"); + } + + var orders = await OrderRepository.GetListAsync(x => orderIds.Contains(x.Id)); + var orderMap = orders.ToDictionary(x => x.Id); + var existingLines = await PickupOrderLineRepository.GetActiveByOrderIdsAsync(orderIds); + var existingByOrderId = existingLines.ToDictionary(x => x.OrderId); + var currentLines = await PickupOrderLineRepository.GetByPickupOrderIdAsync(pickup.Id); + var sort = currentLines.Count == 0 ? 0 : currentLines.Max(x => x.SortNo) + 1; + + var rejected = new List(); + var accepted = new List(); + foreach (var orderId in orderIds) + { + if (!orderMap.TryGetValue(orderId, out var order)) + { + rejected.Add(new PickupOrderRejectItem { OrderId = orderId, Reason = "订单不存在" }); + continue; + } + + var reason = ValidateOrderForBind( + order, + pickup.CustomerId, + pickup.WarehouseId, + pickup.SenderAddressId, + existingByOrderId.GetValueOrDefault(orderId)); + if (reason != null) + { + rejected.Add(new PickupOrderRejectItem + { + OrderId = orderId, + ServiceNo = order.ServiceNo, + Reason = reason + }); + continue; + } + + accepted.Add(order); + } + + if (rejected.Count > 0) + { + throw new BusinessException( + "部分运单不能追加:" + + string.Join(";", rejected.Select(x => $"{x.ServiceNo ?? x.OrderId.ToString()} — {x.Reason}"))); + } + + foreach (var order in accepted) + { + await PickupOrderLineRepository.InsertAsync(new PickupOrderLine + { + PickupOrderId = pickup.Id, + OrderId = order.Id, + ServiceNo = order.ServiceNo, + ClientNo = order.ClientNo, + SortNo = sort++ + }); + order.PickupOrderId = pickup.Id; + order.InboundMethod = OrderInboundMethodCodes.DoorPickup; + order.PickupTime = pickup.ExpectPickupTime; + order.CustomerSenderAddressId = pickup.SenderAddressId; + await OrderRepository.UpdateAsync(order); + } + + await RefreshParcelCountAsync(pickup); + return await MapOutputAsync(pickup, includeOrders: true); + } + + /// + /// 从揽收单移除物流单;移除后若无关联则自动取消揽收单。 + /// + [HttpPost("/order/pickup-order/remove-orders")] + public async Task RemoveOrdersAsync([FromBody] PickupOrderOrdersInput input) + { + var pickup = await GetOwnedPickupOrThrowAsync(input.Id); + if (!PickupOrderStatusCodes.IsMutableBinding(pickup.Status)) + { + throw new BusinessException("当前揽收单状态不可移除运单"); + } + + var orderIds = (input.OrderIds ?? []).Where(x => x > 0).Distinct().ToHashSet(); + if (orderIds.Count == 0) + { + throw new BusinessException("请至少选择一票物流订单"); + } + + var lines = await PickupOrderLineRepository.GetByPickupOrderIdAsync(pickup.Id); + var toRemove = lines.Where(x => orderIds.Contains(x.OrderId)).ToList(); + if (toRemove.Count == 0) + { + throw new BusinessException("所选运单不在该揽收单中"); + } + + foreach (var line in toRemove) + { + await PickupOrderLineRepository.HardDeleteAsync(line); + var order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == line.OrderId); + if (order != null && order.PickupOrderId == pickup.Id) + { + order.PickupOrderId = null; + await OrderRepository.UpdateAsync(order); + } + } + + var remain = await PickupOrderLineRepository.GetByPickupOrderIdAsync(pickup.Id); + if (remain.Count == 0) + { + if (pickup.PayStatus == PickupPayStatusCodes.Paid) + { + throw new BusinessException("揽收单已支付且将无关联运单,请先处理退款后再取消(P1 请联系客服)"); + } + + pickup.Status = PickupOrderStatusCodes.Cancelled; + pickup.ParcelCount = 0; + await PickupOrderRepository.UpdateAsync(pickup); + } + else + { + await RefreshParcelCountAsync(pickup); + } + + return await MapOutputAsync(pickup, includeOrders: true); + } + + /// + /// 揽收单分页列表。 + /// + [HttpPost("/order/pickup-order/list")] + public async Task> ListAsync([FromBody] PickupOrderListInput input) + { + var page = input.Page <= 0 ? 1 : input.Page; + var pageSize = input.PageSize <= 0 ? 30 : Math.Min(input.PageSize, 200); + var customerId = await WarehouseCustomerHelper.ResolveListCustomerIdAsync( + CustomerRepository, + CurrentUser, + input.CustomerId); + + var keyword = NormalizeOptional(input.Keyword); + var status = NormalizeOptional(input.Status); + var payStatus = NormalizeOptional(input.PayStatus); + + var all = await PickupOrderRepository.GetListAsync(x => + (customerId == null || x.CustomerId == customerId.Value) && + (status == null || x.Status == status) && + (payStatus == null || x.PayStatus == payStatus) && + (input.WarehouseId == null || input.WarehouseId <= 0 || x.WarehouseId == input.WarehouseId.Value) && + (input.CreateTimeStart == null || x.CreateTime >= input.CreateTimeStart) && + (input.CreateTimeEnd == null || x.CreateTime <= input.CreateTimeEnd) && + (input.ExpectPickupTimeStart == null || x.ExpectPickupTime >= input.ExpectPickupTimeStart) && + (input.ExpectPickupTimeEnd == null || x.ExpectPickupTime <= input.ExpectPickupTimeEnd) && + (keyword == null || x.PickupNo.Contains(keyword) || + (x.CarrierWaybillNo != null && x.CarrierWaybillNo.Contains(keyword)) || + (x.SenderName != null && x.SenderName.Contains(keyword)))); + + var ordered = all.OrderByDescending(x => x.CreateTime).ThenByDescending(x => x.Id).ToList(); + var total = ordered.Count; + var pageItems = ordered.Skip((page - 1) * pageSize).Take(pageSize).ToList(); + var outputs = new List(); + foreach (var item in pageItems) + { + outputs.Add(await MapOutputAsync(item, includeOrders: false)); + } + + return new OmsPageResult { Items = outputs, Total = total }; + } + + /// + /// 揽收单状态计数(Tab 徽章)。 + /// + [HttpGet("/order/pickup-order/status-counts")] + public async Task GetStatusCountsAsync([FromQuery] int? customerId) + { + var resolvedCustomerId = await WarehouseCustomerHelper.ResolveListCustomerIdAsync( + CustomerRepository, + CurrentUser, + customerId); + + var all = await PickupOrderRepository.GetListAsync(x => + resolvedCustomerId == null || x.CustomerId == resolvedCustomerId.Value); + + var terminal = new[] { PickupOrderStatusCodes.Cancelled, PickupOrderStatusCodes.Failed }; + var pendingPayment = all.Count(x => + !terminal.Contains(x.Status) && + x.PayStatus != PickupPayStatusCodes.Paid && + x.ReceivableAmount is > 0); + + var counts = all + .GroupBy(x => x.Status ?? string.Empty, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.Count(), StringComparer.OrdinalIgnoreCase); + + return new PickupOrderStatusCountsOutput + { + Total = all.Count, + PendingPayment = pendingPayment, + Counts = counts + }; + } + + /// + /// 揽收单详情。 + /// + [HttpGet("/order/pickup-order/detail")] + public async Task GetDetailAsync([FromQuery] int id) + { + var pickup = await GetOwnedPickupOrThrowAsync(id); + return await MapOutputAsync(pickup, includeOrders: true); + } + + /// + /// 确认对客揽收运费。 + /// + [HttpPost("/order/pickup-order/confirm-freight")] + public async Task ConfirmFreightAsync([FromBody] PickupOrderConfirmFreightInput input) + { + var pickup = await GetOwnedPickupOrThrowAsync(input.Id); + if (pickup.Status is PickupOrderStatusCodes.Cancelled or PickupOrderStatusCodes.Failed) + { + throw new BusinessException("已取消/失败的揽收单不可确认运费"); + } + + if (pickup.PayStatus == PickupPayStatusCodes.Paid) + { + throw new BusinessException("已支付不可修改运费"); + } + + if (input.FreightAmount < 0) + { + throw new BusinessException("运费不能为负数"); + } + + var other = input.OtherFeeAmount ?? 0; + if (other < 0) + { + throw new BusinessException("其他费用不能为负数"); + } + + pickup.FreightAmount = input.FreightAmount; + pickup.OtherFeeAmount = other; + pickup.ReceivableAmount = input.FreightAmount + other; + if (input.CarrierPayableAmount.HasValue) + { + pickup.CarrierPayableAmount = input.CarrierPayableAmount; + } + + await PickupOrderRepository.UpdateAsync(pickup); + return await MapOutputAsync(pickup, includeOrders: true); + } + + /// + /// 客户支付揽收运费(余额)。 + /// + [HttpPost("/order/pickup-order/pay")] + public async Task PayAsync([FromBody] PickupOrderIdInput input) + { + var pickup = await PayCoreAsync(input.Id); + return await MapOutputAsync(pickup, includeOrders: true); + } + + /// + /// 批量支付揽收运费(逐单扣余额,部分失败不回滚已成功项)。 + /// + [HttpPost("/order/pickup-order/pay-batch")] + public async Task PayBatchAsync([FromBody] PickupOrderIdsInput input) + { + var ids = (input.Ids ?? []).Where(x => x > 0).Distinct().ToList(); + if (ids.Count == 0) + { + throw new BusinessException("请至少选择一张揽收单"); + } + + if (ids.Count > 100) + { + throw new BusinessException("单次最多支付 100 张揽收单"); + } + + var output = new PickupOrderBatchPayOutput(); + foreach (var id in ids) + { + try + { + var pickup = await PayCoreAsync(id); + var amount = pickup.ReceivableAmount ?? pickup.FreightAmount ?? 0; + output.SuccessCount++; + output.PaidAmount += amount; + output.Items.Add(new PickupOrderBatchPayItemOutput + { + Id = pickup.Id, + PickupNo = pickup.PickupNo, + Success = true, + Message = "支付成功", + Amount = amount + }); + } + catch (Exception ex) + { + output.FailCount++; + var pickupNo = await TryGetPickupNoAsync(id); + output.Items.Add(new PickupOrderBatchPayItemOutput + { + Id = id, + PickupNo = pickupNo, + Success = false, + Message = ex.Message + }); + } + } + + output.Message = $"支付完成:成功 {output.SuccessCount},失败 {output.FailCount}"; + return output; + } + + private async Task PayCoreAsync(int id) + { + var pickup = await GetOwnedPickupOrThrowAsync(id); + if (pickup.PayStatus == PickupPayStatusCodes.Paid) + { + throw new BusinessException("揽收单已支付"); + } + + if (pickup.Status is PickupOrderStatusCodes.Cancelled or PickupOrderStatusCodes.Failed) + { + throw new BusinessException("当前状态不可支付"); + } + + var amount = pickup.ReceivableAmount ?? pickup.FreightAmount ?? 0; + if (amount <= 0) + { + throw new BusinessException("请先确认揽收运费"); + } + + var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == pickup.CustomerId); + if (customer == null) + { + throw new BusinessException("客户不存在"); + } + + var balanceMutator = LazyServiceProvider.GetRequiredService(); + await balanceMutator.DebitPickupPayAsync( + customer, + amount, + pickup.Id, + pickup.PickupNo, + $"揽收支付 {pickup.PickupNo}"); + + pickup.PayStatus = PickupPayStatusCodes.Paid; + pickup.PayTime = DateTime.Now; + await PickupOrderRepository.UpdateAsync(pickup); + return pickup; + } + + private async Task TryGetPickupNoAsync(int id) + { + var pickup = await PickupOrderRepository.FirstOrDefaultAsync(x => x.Id == id); + return pickup?.PickupNo; + } + + /// + /// 补承运商并预约(draft → scheduled)。 + /// + [HttpPost("/order/pickup-order/schedule")] + public async Task ScheduleAsync([FromBody] PickupOrderScheduleInput input) + { + var pickup = await GetOwnedPickupOrThrowAsync(input.Id); + if (pickup.Status is not (PickupOrderStatusCodes.Draft or PickupOrderStatusCodes.Scheduled)) + { + throw new BusinessException("当前状态不可预约下发"); + } + + var carrierService = NormalizeOptional(input.CarrierService); + if (carrierService == null) + { + throw new BusinessException("承运服务不能为空"); + } + + if (string.Equals(pickup.PayMode, PickupPayModeCodes.Prepaid, StringComparison.OrdinalIgnoreCase) + && pickup.PayStatus != PickupPayStatusCodes.Paid) + { + throw new BusinessException("请先支付揽收运费"); + } + + var amount = pickup.ReceivableAmount ?? pickup.FreightAmount ?? 0; + if (amount <= 0) + { + throw new BusinessException("请先确认揽收运费"); + } + + pickup.CarrierService = carrierService; + pickup.CarrierCode = NormalizeOptional(input.CarrierCode); + var carrierWaybillNo = NormalizeOptional(input.CarrierWaybillNo); + if (carrierWaybillNo != null) + { + pickup.CarrierWaybillNo = carrierWaybillNo; + } + + if (input.ExpectPickupTime.HasValue && input.ExpectPickupTime.Value != default) + { + pickup.ExpectPickupTime = input.ExpectPickupTime.Value; + } + + pickup.Status = PickupOrderStatusCodes.Scheduled; + await PickupOrderRepository.UpdateAsync(pickup); + + var lines = await PickupOrderLineRepository.GetByPickupOrderIdAsync(pickup.Id); + foreach (var line in lines) + { + var order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == line.OrderId); + if (order == null) + { + continue; + } + + order.PickupTime = pickup.ExpectPickupTime; + await OrderRepository.UpdateAsync(order); + } + + return await MapOutputAsync(pickup, includeOrders: true); + } + + /// + /// 改约(未取件)。 + /// + [HttpPost("/order/pickup-order/reschedule")] + public async Task RescheduleAsync([FromBody] PickupOrderRescheduleInput input) + { + var pickup = await GetOwnedPickupOrThrowAsync(input.Id); + if (!PickupOrderStatusCodes.IsMutableBinding(pickup.Status)) + { + throw new BusinessException("当前状态不可改约"); + } + + if (input.ExpectPickupTime == default) + { + throw new BusinessException("期望揽收时间不能为空"); + } + + pickup.ExpectPickupTime = input.ExpectPickupTime; + await PickupOrderRepository.UpdateAsync(pickup); + + var lines = await PickupOrderLineRepository.GetByPickupOrderIdAsync(pickup.Id); + foreach (var line in lines) + { + var order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == line.OrderId); + if (order == null) + { + continue; + } + + order.PickupTime = pickup.ExpectPickupTime; + await OrderRepository.UpdateAsync(order); + } + + return await MapOutputAsync(pickup, includeOrders: true); + } + + /// + /// 取消揽收单。 + /// + [HttpPost("/order/pickup-order/cancel")] + public async Task CancelAsync([FromBody] PickupOrderIdInput input) + { + var pickup = await GetOwnedPickupOrThrowAsync(input.Id); + if (!PickupOrderStatusCodes.IsMutableBinding(pickup.Status)) + { + throw new BusinessException("当前状态不可取消"); + } + + if (pickup.PayStatus == PickupPayStatusCodes.Paid) + { + throw new BusinessException("已支付揽收单取消请先处理退款(P1 人工)"); + } + + var lines = await PickupOrderLineRepository.GetByPickupOrderIdAsync(pickup.Id); + foreach (var line in lines) + { + await PickupOrderLineRepository.HardDeleteAsync(line); + var order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == line.OrderId); + if (order != null && order.PickupOrderId == pickup.Id) + { + order.PickupOrderId = null; + await OrderRepository.UpdateAsync(order); + } + } + + pickup.Status = PickupOrderStatusCodes.Cancelled; + pickup.ParcelCount = 0; + await PickupOrderRepository.UpdateAsync(pickup); + return await MapOutputAsync(pickup, includeOrders: true); + } + + /// + /// 标记已取件。 + /// + [HttpPost("/order/pickup-order/mark-picked")] + public async Task MarkPickedAsync([FromBody] PickupOrderIdInput input) + { + var pickup = await GetOwnedPickupOrThrowAsync(input.Id); + if (pickup.Status is not (PickupOrderStatusCodes.Scheduled or PickupOrderStatusCodes.Dispatched)) + { + throw new BusinessException("仅已预约/已派车状态可标记取件"); + } + + pickup.Status = PickupOrderStatusCodes.Picked; + pickup.ActualPickupTime = DateTime.Now; + if (pickup.SettlementStatus == PickupSettlementStatusCodes.None) + { + pickup.SettlementStatus = PickupSettlementStatusCodes.Pending; + } + + await PickupOrderRepository.UpdateAsync(pickup); + return await MapOutputAsync(pickup, includeOrders: true); + } + + /// + /// 标记已到仓。 + /// + [HttpPost("/order/pickup-order/mark-inbound")] + public async Task MarkInboundAsync([FromBody] PickupOrderIdInput input) + { + var pickup = await GetOwnedPickupOrThrowAsync(input.Id); + if (pickup.Status != PickupOrderStatusCodes.Picked) + { + throw new BusinessException("仅已取件状态可确认到仓"); + } + + pickup.Status = PickupOrderStatusCodes.Inbound; + await PickupOrderRepository.UpdateAsync(pickup); + return await MapOutputAsync(pickup, includeOrders: true); + } + + /// + /// 供小包创建成功后内部挂载(失败由调用方吞掉并回显)。 + /// + public async Task CreateForParcelInternalAsync(PickupOrderCreateInput input) + { + return await CreateAsync(input); + } + + private async Task GetOwnedPickupOrThrowAsync(int id) + { + if (id <= 0) + { + throw new BusinessException("揽收单Id无效"); + } + + var pickup = await PickupOrderRepository.FirstOrDefaultAsync(x => x.Id == id); + if (pickup == null) + { + throw new BusinessException("揽收单不存在"); + } + + if (OmsSessionHelper.IsCustomerLogin(CurrentUser)) + { + var customerId = await WarehouseCustomerHelper.ResolveRequiredCustomerIdAsync( + CustomerRepository, + CurrentUser, + null); + if (pickup.CustomerId != customerId) + { + throw new BusinessException("揽收单不存在"); + } + } + + return pickup; + } + + private static string? ValidateOrderForBind( + Order order, + int customerId, + int warehouseId, + int senderAddressId, + PickupOrderLine? existingLine) + { + if (order.CustomerId != customerId) + { + return "不属于当前客户"; + } + + if (string.Equals(order.OrderStatus, OrderStatusCodes.Deleted, StringComparison.OrdinalIgnoreCase)) + { + return "订单已删除"; + } + + if (!BindableOrderStatuses.Contains(order.OrderStatus ?? string.Empty)) + { + return $"订单状态不可挂载揽收({order.OrderStatus})"; + } + + if (order.WarehouseId != warehouseId) + { + return "仓库不一致"; + } + + if (existingLine != null) + { + return existingLine.PickupOrderId == order.PickupOrderId + ? "已在当前揽收单中" + : $"已绑定其他揽收单(Id={existingLine.PickupOrderId})"; + } + + if (order.PickupOrderId is > 0) + { + return $"已绑定其他揽收单(Id={order.PickupOrderId})"; + } + + // 已有发件地址快照时要求与揽收同址;尚未绑定时以本次选择为准 + if (order.CustomerSenderAddressId is > 0 && order.CustomerSenderAddressId != senderAddressId) + { + return "取件地址不一致"; + } + + return null; + } + + private async Task RefreshParcelCountAsync(PickupOrder pickup) + { + var lines = await PickupOrderLineRepository.GetByPickupOrderIdAsync(pickup.Id); + pickup.ParcelCount = lines.Count; + await PickupOrderRepository.UpdateAsync(pickup); + } + + private async Task GeneratePickupNoAsync() + { + for (var i = 0; i < 8; i++) + { + var no = $"PK{DateTime.Now:yyyyMMddHHmmss}{Random.Shared.Next(1000, 9999)}"; + var existed = await PickupOrderRepository.GetByPickupNoAsync(no); + if (existed == null) + { + return no; + } + } + + throw new BusinessException("揽收单号生成失败"); + } + + private async Task MapOutputAsync(PickupOrder entity, bool includeOrders) + { + string? warehouseName = null; + var warehouse = await WarehouseAddressRepository.FirstOrDefaultAsync(x => x.Id == entity.WarehouseId); + if (warehouse != null) + { + warehouseName = warehouse.WarehouseName; + } + + string? customerName = null; + var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == entity.CustomerId); + if (customer != null) + { + customerName = customer.CustomerName; + } + + var output = new PickupOrderOutput + { + Id = entity.Id, + PickupNo = entity.PickupNo, + RequestId = entity.RequestId, + CustomerId = entity.CustomerId, + CustomerName = customerName, + OrganizationId = entity.OrganizationId, + SecretLevel = entity.SecretLevel, + SenderAddressId = entity.SenderAddressId, + SenderName = entity.SenderName, + SenderPhone = entity.SenderPhone, + SenderTelePhone = entity.SenderTelePhone, + SenderEmail = entity.SenderEmail, + SenderCompany = entity.SenderCompany, + SenderCountry = entity.SenderCountry, + SenderCountryCode = entity.SenderCountryCode, + SenderProvince = entity.SenderProvince, + SenderCity = entity.SenderCity, + SenderZipCode = entity.SenderZipCode, + SenderStreetAddress1 = entity.SenderStreetAddress1, + SenderStreetAddress2 = entity.SenderStreetAddress2, + SenderStreetAddress3 = entity.SenderStreetAddress3, + SenderHouseNumber = entity.SenderHouseNumber, + WarehouseId = entity.WarehouseId, + WarehouseName = warehouseName, + CarrierCode = entity.CarrierCode, + CarrierService = entity.CarrierService, + CarrierWaybillNo = entity.CarrierWaybillNo, + ExpectPickupTime = entity.ExpectPickupTime, + ActualPickupTime = entity.ActualPickupTime, + Status = entity.Status, + ParcelCount = entity.ParcelCount, + TotalActualWeight = entity.TotalActualWeight, + ChargeableWeight = entity.ChargeableWeight, + Currency = entity.Currency, + FreightAmount = entity.FreightAmount, + OtherFeeAmount = entity.OtherFeeAmount, + ReceivableAmount = entity.ReceivableAmount, + PayStatus = entity.PayStatus, + PayTime = entity.PayTime, + PayMode = entity.PayMode, + CarrierPayableAmount = entity.CarrierPayableAmount, + SettlementStatus = entity.SettlementStatus, + SettlementBatchNo = entity.SettlementBatchNo, + Remark = entity.Remark, + CreateTime = entity.CreateTime, + UpdateTime = entity.UpdateTime + }; + + if (!includeOrders) + { + return output; + } + + var lines = await PickupOrderLineRepository.GetByPickupOrderIdAsync(entity.Id); + if (lines.Count == 0) + { + return output; + } + + var orderIds = lines.Select(x => x.OrderId).ToList(); + var orders = await OrderRepository.GetListAsync(x => orderIds.Contains(x.Id)); + var orderMap = orders.ToDictionary(x => x.Id); + var weights = await OrderRepository.GetWeightsByOrderIdsAsync(orderIds); + var weightMap = weights + .GroupBy(x => x.OrderId) + .ToDictionary( + g => g.Key, + g => g.OrderByDescending(w => w.Type == OrderWeightTypeCodes.Receive ? 2 : 1) + .Select(w => w.ChargeableWeight ?? w.ActualWeight) + .FirstOrDefault()); + + output.Orders = lines + .OrderBy(x => x.SortNo) + .Select(line => + { + orderMap.TryGetValue(line.OrderId, out var order); + weightMap.TryGetValue(line.OrderId, out var cw); + return new PickupOrderLineOutput + { + OrderId = line.OrderId, + ServiceNo = order?.ServiceNo, + ClientNo = order?.ClientNo, + OrderStatus = order?.OrderStatus, + WarehouseId = order?.WarehouseId, + ChargeableWeight = cw + }; + }) + .ToList(); + + return output; + } + + private static string? NormalizeOptional(string? value) + { + var v = value?.Trim(); + return string.IsNullOrEmpty(v) ? null : v; + } +} diff --git a/src/Oms.Application/Services/Orders/PlatformStoreOrderService.cs b/src/Oms.Application/Services/Orders/PlatformStoreOrderService.cs index 446ab57..d812708 100644 --- a/src/Oms.Application/Services/Orders/PlatformStoreOrderService.cs +++ b/src/Oms.Application/Services/Orders/PlatformStoreOrderService.cs @@ -78,6 +78,16 @@ public class PlatformStoreOrderService : ApplicationService : await CustomerRepository.GetListAsync(x => customerIds.Contains(x.Id)); var customerMap = customers.ToDictionary(x => x.Id); + var orderIds = entities.Select(x => x.Id).ToArray(); + var pageLines = orderIds.Length == 0 + ? [] + : await StoreOrderLineRepository.GetListAsync(x => orderIds.Contains(x.StoreOrderId)); + var firstLineMap = pageLines + .GroupBy(x => x.StoreOrderId) + .ToDictionary( + g => g.Key, + g => g.OrderBy(x => x.Id).First()); + return new OmsPageResult { Items = entities.Select(x => @@ -90,13 +100,20 @@ public class PlatformStoreOrderService : ApplicationService } customerMap.TryGetValue(x.CustomerId, out var customer); - return MapOrderOutput( + var output = MapOrderOutput( x, store?.StoreNickname ?? string.Empty, [], linkedServiceNo: linkedServiceNo, customerName: customer?.CustomerName, customerCode: customer?.CustomerCode); + if (firstLineMap.TryGetValue(x.Id, out var firstLine)) + { + output.FirstProductName = firstLine.ProductName; + output.FirstProductImageUrl = firstLine.ProductImageUrl; + } + + return output; }).ToList(), Total = total }; @@ -141,9 +158,13 @@ public class PlatformStoreOrderService : ApplicationService /// /// 客户 ID(可选)。 /// 店铺 ID(可选)。 + /// 平台编码(可选)。 /// 各履约状态数量汇总。 [HttpGet("/order/platform-store-order/summary")] - public async Task GetSummaryAsync([FromQuery] int? customerId = null, [FromQuery] int? storeId = null) + public async Task GetSummaryAsync( + [FromQuery] int? customerId = null, + [FromQuery] int? storeId = null, + [FromQuery] string? platformCode = null) { var resolvedCustomerId = await WarehouseCustomerHelper.ResolveListCustomerIdAsync( CustomerRepository, @@ -152,9 +173,12 @@ public class PlatformStoreOrderService : ApplicationService var (hasCustomerFilter, customerIdValue) = WarehouseCustomerHelper.ToCustomerFilter(resolvedCustomerId); var hasStoreFilter = storeId.HasValue; var storeIdValue = storeId.GetValueOrDefault(); + var normalizedPlatform = NormalizePlatformCodeFilter(platformCode); + var hasPlatformFilter = !string.IsNullOrWhiteSpace(normalizedPlatform); var orders = await StoreOrderRepository.GetListAsync(x => (!hasCustomerFilter || x.CustomerId == customerIdValue) - && (!hasStoreFilter || x.StoreId == storeIdValue)); + && (!hasStoreFilter || x.StoreId == storeIdValue) + && (!hasPlatformFilter || x.PlatformCode == normalizedPlatform)); return new PlatformStoreOrderSummaryOutput { @@ -557,9 +581,15 @@ public class PlatformStoreOrderService : ApplicationService if (resolvedWarehouseId is > 0) { var logisticsOrder = await OrderRepository.FirstOrDefaultAsync(x => x.Id == parcelOutput.OrderId); - if (logisticsOrder != null && logisticsOrder.WarehouseId is not > 0) + if (logisticsOrder != null) { - logisticsOrder.WarehouseId = resolvedWarehouseId; + if (logisticsOrder.WarehouseId is not > 0) + { + logisticsOrder.WarehouseId = resolvedWarehouseId; + } + + logisticsOrder.FulfillmentType = FulfillmentTypeCodes.Warehouse; + logisticsOrder.FulfillmentSource = FulfillmentSourceCodes.StoreFulfill; await OrderRepository.UpdateAsync(logisticsOrder); } } @@ -891,6 +921,8 @@ public class PlatformStoreOrderService : ApplicationService // 前端 Tab「全部」会传 all / 空;需忽略,不能按字面 FulfillStatus == "all" 过滤 var fulfillStatus = NormalizeFulfillStatusFilter(input.FulfillStatus); var hasFulfillStatusFilter = !string.IsNullOrWhiteSpace(fulfillStatus); + var platformCode = NormalizePlatformCodeFilter(input.PlatformCode); + var hasPlatformFilter = !string.IsNullOrWhiteSpace(platformCode); var platformOrderNo = input.PlatformOrderNo?.Trim(); var hasStoreFilter = input.StoreId.HasValue; var storeIdValue = input.StoreId.GetValueOrDefault(); @@ -902,16 +934,33 @@ public class PlatformStoreOrderService : ApplicationService ? x => (!hasCustomerFilter || x.CustomerId == customerIdValue) && (!hasStoreFilter || x.StoreId == storeIdValue) + && (!hasPlatformFilter || x.PlatformCode == platformCode) && x.FulfillStatus == fulfillStatus && (!hasSuspendedFilter || x.IsSuspended == isSuspendedValue) && (!hasPlatformOrderNoFilter || x.PlatformOrderNo.Contains(platformOrderNo!)) : x => (!hasCustomerFilter || x.CustomerId == customerIdValue) && (!hasStoreFilter || x.StoreId == storeIdValue) + && (!hasPlatformFilter || x.PlatformCode == platformCode) && (!hasSuspendedFilter || x.IsSuspended == isSuspendedValue) && (!hasPlatformOrderNoFilter || x.PlatformOrderNo.Contains(platformOrderNo!)); } + /// + /// 规范化平台筛选:空 / all 表示不按平台过滤。 + /// + private static string? NormalizePlatformCodeFilter(string? platformCode) + { + var value = platformCode?.Trim(); + if (string.IsNullOrEmpty(value) + || value.Equals("all", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + return value.ToLowerInvariant(); + } + /// /// 规范化履约状态筛选:空 / all 表示不按状态过滤;已知编码统一为规范值。 /// diff --git a/src/Oms.Application/Services/Rbac/OmsUserService.cs b/src/Oms.Application/Services/Rbac/OmsUserService.cs index 106a20e..27f8eb6 100644 --- a/src/Oms.Application/Services/Rbac/OmsUserService.cs +++ b/src/Oms.Application/Services/Rbac/OmsUserService.cs @@ -109,6 +109,7 @@ public class OmsUserService( EmployeeNo = employeeNo, WechatId = input.WechatId, WechatQrCode = input.WechatQrCode, + WecomKfUrl = input.WecomKfUrl, }, cancellationToken); @@ -145,6 +146,7 @@ public class OmsUserService( Phone = input.Phone, WechatId = input.WechatId, WechatQrCode = input.WechatQrCode, + WecomKfUrl = input.WecomKfUrl, }, cancellationToken); diff --git a/src/Oms.Application/Services/System/NoticeService.cs b/src/Oms.Application/Services/System/NoticeService.cs index 5b50b99..d804de4 100644 --- a/src/Oms.Application/Services/System/NoticeService.cs +++ b/src/Oms.Application/Services/System/NoticeService.cs @@ -59,7 +59,17 @@ public class NoticeService : ApplicationService ? ReceiverTypeCustomer : ReceiverTypeUser; - var predicate = BuildListPredicate(input, receiverUserId, expectedReceiverType); + var myReadNoticeIds = (await NoticeReadRepository.GetListAsync(x => + x.ReceiverType == expectedReceiverType && x.ReceiverId == receiverUserId)) + .Select(x => x.NoticeId) + .Distinct() + .ToList(); + + var predicate = BuildListPredicate( + input, + receiverUserId, + expectedReceiverType, + input.OnlyUnread == true ? myReadNoticeIds : null); var pageIndex = OmsDocHelper.NormalizePage(input.Page); var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); var notices = await NoticeRepository.GetPagedListAsync( @@ -78,6 +88,7 @@ public class NoticeService : ApplicationService .ToDictionary( x => x.Key, x => (int)x.Select(item => $"{item.ReceiverType}:{item.ReceiverId}").Distinct(StringComparer.Ordinal).Count()); + var myReadIdSet = myReadNoticeIds.ToHashSet(); var selectionIdMap = await BuildReceiverSelectionIdMapAsync(notices); @@ -86,6 +97,7 @@ public class NoticeService : ApplicationService Items = notices.Select(x => MapNoticeOutput( x, readCountMap.TryGetValue(x.Id, out var readCount) ? readCount : 0, + myReadIdSet.Contains(x.Id), selectionIdMap.TryGetValue(x.Id, out var selectionIds) ? selectionIds : [])).ToList(), Total = total }; @@ -118,14 +130,15 @@ public class NoticeService : ApplicationService { var noticeType = NormalizeNoticeType(input.NoticeType); ValidateNoticeText(noticeType, input.Title, input.Content); - var receiverIds = await NormalizeAndValidateReceiverIdsAsync(input.ReceiverType, input.ReceiverIds); + var receiverType = ResolveReceiverType(noticeType, input.ReceiverType); + var receiverIds = await NormalizeAndValidateReceiverIdsAsync(noticeType, receiverType, input.ReceiverIds); await NoticeRepository.InsertAsync(new Notice { NoticeType = noticeType, Title = NormalizeTitle(input.Title), Content = input.Content.Trim(), - IsPopup = NormalizePopupValue(input.IsPopup), - ReceiverType = NormalizeReceiverType(input.ReceiverType), + IsPopup = noticeType == NoticeTypeMessage ? (byte)0 : NormalizePopupValue(input.IsPopup), + ReceiverType = receiverType, ReceiverIds = OmsDocHelper.SerializeJson(receiverIds) ?? "[]" }); } @@ -139,20 +152,27 @@ public class NoticeService : ApplicationService var entity = await GetNoticeOrThrowAsync(input.Id); var noticeType = NormalizeNoticeType(input.NoticeType); ValidateNoticeText(noticeType, input.Title, input.Content); - var receiverIds = await NormalizeAndValidateReceiverIdsAsync(input.ReceiverType, input.ReceiverIds); + var receiverType = ResolveReceiverType(noticeType, input.ReceiverType); + var receiverIds = await NormalizeAndValidateReceiverIdsAsync(noticeType, receiverType, input.ReceiverIds); entity.NoticeType = noticeType; entity.Title = NormalizeTitle(input.Title); entity.Content = input.Content.Trim(); - entity.IsPopup = NormalizePopupValue(input.IsPopup); - entity.ReceiverType = NormalizeReceiverType(input.ReceiverType); + entity.IsPopup = noticeType == NoticeTypeMessage ? (byte)0 : NormalizePopupValue(input.IsPopup); + entity.ReceiverType = receiverType; entity.ReceiverIds = OmsDocHelper.SerializeJson(receiverIds) ?? "[]"; await NoticeRepository.UpdateAsync(entity); - var existsReads = await NoticeReadRepository.GetListAsync(x => x.NoticeId == entity.Id); - var receiverIdSet = receiverIds.ToHashSet(); - foreach (var read in existsReads.Where(x => x.ReceiverType != ReceiverTypeUser || !receiverIdSet.Contains(x.ReceiverId))) + // 全体广播不清理已读;定向接收时移除已不在名单内的已读记录 + if (receiverIds.Count > 0) { - await NoticeReadRepository.DeleteAsync(read); + var existsReads = await NoticeReadRepository.GetListAsync(x => x.NoticeId == entity.Id); + var receiverIdSet = receiverIds.ToHashSet(); + foreach (var read in existsReads.Where(x => + !string.Equals(x.ReceiverType, receiverType, StringComparison.OrdinalIgnoreCase) || + !receiverIdSet.Contains(x.ReceiverId))) + { + await NoticeReadRepository.DeleteAsync(read); + } } } @@ -174,14 +194,17 @@ public class NoticeService : ApplicationService { var notice = await GetNoticeOrThrowAsync(input.Id); var receiverIds = OmsDocHelper.DeserializeJson>(notice.ReceiverIds) ?? []; - var currentReceiverType = NormalizeReceiverType(notice.ReceiverType); + var currentReceiverType = OmsSessionHelper.IsCustomerLogin(CurrentUser) + ? ReceiverTypeCustomer + : ReceiverTypeUser; var currentReceiverId = CurrentUser.GetId(); if (currentReceiverId <= 0) { throw new BusinessException("当前登录主体无效"); } - if (!receiverIds.Contains(currentReceiverId)) + // 空接收人 = 全体广播;否则校验当前主体在定向名单内 + if (receiverIds.Count > 0 && !receiverIds.Contains(currentReceiverId)) { throw new BusinessException("当前主体不在通知接收范围内"); } @@ -329,23 +352,30 @@ public class NoticeService : ApplicationService private static Expression> BuildListPredicate( NoticeListInput input, int receiverUserId, - string expectedReceiverType) + string expectedReceiverType, + IReadOnlyCollection? excludeNoticeIds) { var noticeType = input.NoticeType?.Trim(); var receiverType = input.ReceiverType?.Trim(); var keyword = input.Keyword?.Trim(); var receiverIdToken = receiverUserId.ToString(); + var excluded = excludeNoticeIds?.Where(x => x > 0).Distinct().ToList() ?? []; return x => (string.IsNullOrWhiteSpace(noticeType) || x.NoticeType == noticeType) && (string.IsNullOrWhiteSpace(receiverType) || x.ReceiverType == receiverType) && (string.IsNullOrWhiteSpace(keyword) || x.Title.Contains(keyword) || x.Content.Contains(keyword)) && - x.ReceiverType == expectedReceiverType && - (x.ReceiverIds == $"[{receiverIdToken}]" || - x.ReceiverIds.StartsWith($"[{receiverIdToken},") || - x.ReceiverIds.Contains($",{receiverIdToken},") || - x.ReceiverIds.EndsWith($",{receiverIdToken}]")); + ( + // 空接收人列表 = 全体广播(员工/客户均可见) + x.ReceiverIds == "[]" || + (x.ReceiverType == expectedReceiverType && + (x.ReceiverIds == $"[{receiverIdToken}]" || + x.ReceiverIds.StartsWith($"[{receiverIdToken},") || + x.ReceiverIds.Contains($",{receiverIdToken},") || + x.ReceiverIds.EndsWith($",{receiverIdToken}]"))) + ) && + (excluded.Count == 0 || !excluded.Contains(x.Id)); } private async Task GetNoticeOrThrowAsync(int id) @@ -359,19 +389,29 @@ public class NoticeService : ApplicationService return entity; } - private async Task> NormalizeAndValidateReceiverIdsAsync(string receiverType, IEnumerable? receiverIds) + private async Task> NormalizeAndValidateReceiverIdsAsync( + string noticeType, + string receiverType, + IEnumerable? receiverIds) { - var normalizedReceiverType = NormalizeReceiverType(receiverType); var selectionIds = (receiverIds ?? []) .Where(x => x > 0) .Distinct() .ToList(); + // 公告默认全体生效,允许空接收人;站内信必须指定接收人 if (selectionIds.Count == 0) { + if (noticeType == NoticeTypeNotice) + { + return []; + } + throw new BusinessException("接收人不能为空"); } + var normalizedReceiverType = NormalizeReceiverType(receiverType); + if (normalizedReceiverType == ReceiverTypeCustomer) { var customers = await CustomerRepository.GetListAsync(x => @@ -405,6 +445,19 @@ public class NoticeService : ApplicationService return selectionIds; } + /// + /// 公告全体广播时接收类型仅作占位;站内信必须明确 user/customer。 + /// + private static string ResolveReceiverType(string noticeType, string? receiverType) + { + if (noticeType == NoticeTypeNotice && string.IsNullOrWhiteSpace(receiverType)) + { + return ReceiverTypeUser; + } + + return NormalizeReceiverType(receiverType ?? string.Empty); + } + private async Task> QueryValidUserIdsAsync(IReadOnlyCollection userIds) { if (userIds.Count == 0) @@ -434,9 +487,14 @@ public class NoticeService : ApplicationService private static string NormalizeTitle(string? title) => string.IsNullOrWhiteSpace(title) ? string.Empty : title.Trim(); - private static NoticeOutput MapNoticeOutput(Notice entity, int readCount, List receiverSelectionIds) + private static NoticeOutput MapNoticeOutput( + Notice entity, + int readCount, + bool isRead, + List receiverSelectionIds) { var receiverIds = OmsDocHelper.DeserializeJson>(entity.ReceiverIds) ?? []; + var isBroadcast = receiverIds.Count == 0; return new NoticeOutput { Id = entity.Id, @@ -446,11 +504,14 @@ public class NoticeService : ApplicationService Content = entity.Content, IsPopup = entity.IsPopup, ReceiverType = entity.ReceiverType, - ReceiverTypeName = entity.ReceiverType == ReceiverTypeCustomer ? "客户" : "用户", + ReceiverTypeName = isBroadcast + ? "全部" + : entity.ReceiverType == ReceiverTypeCustomer ? "客户" : "用户", ReceiverIds = receiverIds, ReceiverSelectionIds = receiverSelectionIds, ReadCount = readCount, - ReceiverCount = receiverIds.Distinct().Count(), + IsRead = isRead, + ReceiverCount = isBroadcast ? 0 : receiverIds.Distinct().Count(), CreateTime = entity.CreateTime, UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime) }; diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.ParcelArrival.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.ParcelArrival.cs index a19a8fb..91d24be 100644 --- a/src/Oms.Application/Services/Warehouse/WarehouseService.ParcelArrival.cs +++ b/src/Oms.Application/Services/Warehouse/WarehouseService.ParcelArrival.cs @@ -4,6 +4,9 @@ using Microsoft.AspNetCore.Mvc; using Oms.Application.Dtos.Shared; using Oms.Application.Dtos.Warehouse; using Oms.Application.Shared; +using Oms.Domain.OrdersAggregate.Consts; +using Oms.Domain.OrdersAggregate.Entities; +using Oms.Domain.OrdersAggregate.Repositories; using Oms.Domain.SystemAggregate.Repositories; using Oms.Domain.WarehouseAggregate.Consts; using Oms.Domain.WarehouseAggregate.Entities; @@ -22,6 +25,12 @@ public partial class WarehouseService private OmsRbacUserDisplayNameResolver UserDisplayNameResolver => LazyServiceProvider.GetRequiredService(); + private IOrderStockBindRepository ParcelArrivalStockBindRepository => + LazyServiceProvider.GetRequiredService(); + + private IOrderRepository ParcelArrivalOrderRepository => + LazyServiceProvider.GetRequiredService(); + /// /// 快递到仓记录列表。 /// @@ -87,7 +96,10 @@ public partial class WarehouseService [HttpPost("/warehouse/parcel-arrival/create")] public async Task CreateParcelArrivalAsync(WarehouseParcelArrivalCreateInput input) { - var customerId = await ResolveMutationCustomerIdAsync(input.CustomerId); + // 到仓按仓库 + 快递单号定位包裹;客户归属取自包裹本身,管理端无需先选客户。 + // 客户门户会话仍会限制只能到自己的包裹。 + var sessionCustomerId = await ResolveListCustomerIdAsync(null); + var (hasCustomerFilter, customerIdValue) = CustomerFilter(sessionCustomerId); if (input.WarehouseId <= 0) { throw new BusinessException("仓库ID不能为空"); @@ -102,15 +114,21 @@ public partial class WarehouseService var warehouse = await WarehouseAddressRepository.FirstOrDefaultAsync(x => x.Id == input.WarehouseId) ?? throw new BusinessException("仓库不存在"); - var parcel = await ParcelRepository.FirstOrDefaultAsync(x => - x.CustomerId == customerId - && x.WarehouseId == input.WarehouseId - && x.TrackingNo == trackingNo); - if (parcel == null) + var parcels = await ParcelRepository.GetListAsync(x => + x.WarehouseId == input.WarehouseId + && x.TrackingNo == trackingNo + && (!hasCustomerFilter || x.CustomerId == customerIdValue)); + if (parcels.Count == 0) { throw new BusinessException("未找到对应包裹,请确认快递单号与仓库"); } + if (parcels.Count > 1) + { + throw new BusinessException("同一仓库下存在多条相同快递单号的包裹,请先在「我的包裹」核对后再到仓"); + } + + var parcel = parcels[0]; if (parcel.LifecycleStatus == WarehouseParcelLifecycleCodes.Stored) { throw new BusinessException("包裹已上架,无法再到仓"); @@ -122,13 +140,15 @@ public partial class WarehouseService var entity = new CParcelArrival { - CustomerId = customerId, + CustomerId = parcel.CustomerId, WarehouseId = input.WarehouseId, ParcelId = parcel.Id, TrackingNo = trackingNo }; await ParcelArrivalRepository.InsertAsync(entity); + var linkedOrders = await LoadParcelArrivalLinkedOrdersAsync(parcel.Id); + var userNameMap = await UserDisplayNameResolver.ResolveManyAsync([entity.CreateUserId]); return new WarehouseParcelArrivalOutput { @@ -140,10 +160,46 @@ public partial class WarehouseService TrackingNo = entity.TrackingNo, CreateTime = entity.CreateTime, CreateUserId = entity.CreateUserId, - CreateBy = OmsRbacUserDisplayNameResolver.FormatUserId(entity.CreateUserId, userNameMap) + CreateBy = OmsRbacUserDisplayNameResolver.FormatUserId(entity.CreateUserId, userNameMap), + LinkedOrders = linkedOrders }; } + private async Task> LoadParcelArrivalLinkedOrdersAsync(int parcelId) + { + var binds = await ParcelArrivalStockBindRepository.GetListAsync(x => + x.ParcelId == parcelId + && !x.IsDeleted + && x.Status == OrderStockBindStatusCodes.Bound); + if (binds.Count == 0) + { + return []; + } + + var orderIds = binds.Select(x => x.OrderId).Distinct().ToArray(); + var orders = await ParcelArrivalOrderRepository.GetListAsync(x => orderIds.Contains(x.Id)); + var orderMap = orders.ToDictionary(x => x.Id); + + return orderIds + .Where(orderMap.ContainsKey) + .Select(orderId => + { + var order = orderMap[orderId]; + var isWarehouse = FulfillmentTypeCodes.IsWarehouse(order.FulfillmentType); + return new WarehouseParcelArrivalLinkedOrderOutput + { + OrderId = orderId, + ServiceNo = order.ServiceNo, + ClientNo = order.ClientNo, + FulfillProgress = isWarehouse + ? FulfillmentProgressCodes.ArrivedPendingPick + : null + }; + }) + .OrderBy(x => x.ServiceNo, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + /// /// 删除快递到仓记录(不回退包裹状态)。 /// diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.Sku.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.Sku.cs index ecd753e..3bb855f 100644 --- a/src/Oms.Application/Services/Warehouse/WarehouseService.Sku.cs +++ b/src/Oms.Application/Services/Warehouse/WarehouseService.Sku.cs @@ -40,15 +40,6 @@ public partial class WarehouseService new Dictionary { [nameof(Domain.WarehouseAggregate.Entities.CSku.UpdateTime)] = false, [nameof(Domain.WarehouseAggregate.Entities.CSku.Id)] = false }); var total = await SkuRepository.CountAsync(predicate); - var skuIds = entities.Select(x => x.Id).ToArray(); - var inventories = skuIds.Length == 0 - ? [] - : await InventoryRepository.GetListAsync(x => - (!hasCustomerFilter || x.CustomerId == customerIdValue) && skuIds.Contains(x.SkuId)); - var qtyMap = inventories - .GroupBy(x => x.SkuId) - .ToDictionary(g => g.Key, g => g.Sum(x => x.Qty)); - var customerIds = entities.Select(x => x.CustomerId).Distinct().ToArray(); var customers = customerIds.Length == 0 ? [] @@ -59,7 +50,7 @@ public partial class WarehouseService { Items = entities.Select(x => { - var output = MapSkuOutput(x, qtyMap.GetValueOrDefault(x.Id)); + var output = MapSkuListOutput(x); if (customerMap.TryGetValue(x.CustomerId, out var customer)) { output.CustomerName = customer.CustomerName; @@ -125,7 +116,11 @@ public partial class WarehouseService entity.SkuCode = skuCode; entity.SkuName = skuName; + entity.SkuNameEn = string.IsNullOrWhiteSpace(input.SkuNameEn) ? null : input.SkuNameEn.Trim(); entity.SkuImageUrl = string.IsNullOrWhiteSpace(input.SkuImageUrl) ? null : input.SkuImageUrl.Trim(); + entity.UnitPrice = input.UnitPrice; + entity.ExHsCode = string.IsNullOrWhiteSpace(input.ExHsCode) ? null : input.ExHsCode.Trim(); + entity.ImHsCode = string.IsNullOrWhiteSpace(input.ImHsCode) ? null : input.ImHsCode.Trim(); entity.WeightG = input.WeightG; entity.LengthCm = input.LengthCm; entity.WidthCm = input.WidthCm; @@ -141,7 +136,7 @@ public partial class WarehouseService await SkuRepository.InsertAsync(entity); } - return MapSkuOutput(entity, 0); + return MapSkuOutput(entity, null); } /// @@ -222,14 +217,39 @@ public partial class WarehouseService }; } - private static WarehouseSkuOutput MapSkuOutput(Domain.WarehouseAggregate.Entities.CSku entity, int totalQty) => + private static WarehouseSkuOutput MapSkuListOutput(Domain.WarehouseAggregate.Entities.CSku entity) => new() { Id = entity.Id, CustomerId = entity.CustomerId, SkuCode = entity.SkuCode, SkuName = entity.SkuName, + SkuNameEn = entity.SkuNameEn, SkuImageUrl = entity.SkuImageUrl, + UnitPrice = entity.UnitPrice, + ExHsCode = entity.ExHsCode, + ImHsCode = entity.ImHsCode, + WeightG = entity.WeightG, + LengthCm = entity.LengthCm, + WidthCm = entity.WidthCm, + HeightCm = entity.HeightCm, + Remark = entity.Remark, + CreateTime = entity.CreateTime, + UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime) + }; + + private static WarehouseSkuOutput MapSkuOutput(Domain.WarehouseAggregate.Entities.CSku entity, int? totalQty) => + new() + { + Id = entity.Id, + CustomerId = entity.CustomerId, + SkuCode = entity.SkuCode, + SkuName = entity.SkuName, + SkuNameEn = entity.SkuNameEn, + SkuImageUrl = entity.SkuImageUrl, + UnitPrice = entity.UnitPrice, + ExHsCode = entity.ExHsCode, + ImHsCode = entity.ImHsCode, WeightG = entity.WeightG, LengthCm = entity.LengthCm, WidthCm = entity.WidthCm, diff --git a/src/Oms.Application/Services/Xhs/XhsAnalysisService.cs b/src/Oms.Application/Services/Xhs/XhsAnalysisService.cs index 2d34d44..7445b82 100644 --- a/src/Oms.Application/Services/Xhs/XhsAnalysisService.cs +++ b/src/Oms.Application/Services/Xhs/XhsAnalysisService.cs @@ -2,6 +2,7 @@ using Fake.Application; using Microsoft.AspNetCore.Mvc; using Oms.Application.Dtos.Shared; using Oms.Application.Dtos.Xhs; +using Oms.Application.Services.Ai; using Oms.Application.Shared; using Oms.Domain.CustomersAggregate.Repositories; using Oms.Domain.XhsAggregate.Consts; @@ -110,9 +111,9 @@ public class XhsAnalysisService : ApplicationService throw new BusinessException("请先完成笔记采集"); } - var aiService = LazyServiceProvider.GetRequiredService(); + var aiService = LazyServiceProvider.GetRequiredService(); var provider = await aiService.ResolveProviderAsync(customerId, input.ProviderKey.Trim()); - var llm = LazyServiceProvider.GetRequiredService(); + var llm = LazyServiceProvider.GetRequiredService(); var skillHint = string.Empty; if (input.SkillId is > 0) diff --git a/src/Oms.Application/Services/Xhs/XhsCreationService.cs b/src/Oms.Application/Services/Xhs/XhsCreationService.cs index a556482..e518103 100644 --- a/src/Oms.Application/Services/Xhs/XhsCreationService.cs +++ b/src/Oms.Application/Services/Xhs/XhsCreationService.cs @@ -1,6 +1,7 @@ using Fake.Application; using Microsoft.AspNetCore.Mvc; using Oms.Application.Dtos.Xhs; +using Oms.Application.Services.Ai; using Oms.Application.Shared; using Oms.Domain.CustomersAggregate.Repositories; using Oms.Domain.XhsAggregate.Consts; @@ -66,9 +67,9 @@ public class XhsCreationService : ApplicationService public async Task GenerateAsync(XhsCreationGenerateInput input) { var customerId = await OmsSessionHelper.ResolveXhsCustomerIdAsync(CustomerRepository, CurrentUser); - var aiService = LazyServiceProvider.GetRequiredService(); + var aiService = LazyServiceProvider.GetRequiredService(); var provider = await aiService.ResolveProviderAsync(customerId, input.ProviderKey.Trim()); - var llm = LazyServiceProvider.GetRequiredService(); + var llm = LazyServiceProvider.GetRequiredService(); var skillHint = string.Empty; if (input.SkillId is > 0) diff --git a/src/Oms.Application/Shared/XhsLlmClient.cs b/src/Oms.Application/Shared/AiLlmClient.cs similarity index 93% rename from src/Oms.Application/Shared/XhsLlmClient.cs rename to src/Oms.Application/Shared/AiLlmClient.cs index c76d48f..6f9f825 100644 --- a/src/Oms.Application/Shared/XhsLlmClient.cs +++ b/src/Oms.Application/Shared/AiLlmClient.cs @@ -1,11 +1,11 @@ -using System.Net.Http.Headers; +using System.Net.Http.Headers; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using Fake.Application; using Microsoft.Extensions.DependencyInjection; using Oms.Application.Mcp; -using Oms.Domain.XhsAggregate.Entities; +using Oms.Domain.AiAggregate.Entities; namespace Oms.Application.Shared; @@ -40,21 +40,21 @@ public class LlmChatResult } /// -/// OpenAI 兼容 Chat Completions 客户端(智谱 / DeepSeek / 豆包等)。 +/// OpenAI 兼容 Chat Completions 客户端(通义 / DeepSeek / 豆包等)。 /// -public class XhsLlmClient +public class AiLlmClient { - public const string HttpClientName = nameof(XhsLlmClient); + public const string HttpClientName = nameof(AiLlmClient); private readonly IHttpClientFactory _httpClientFactory; - public XhsLlmClient(IHttpClientFactory httpClientFactory) + public AiLlmClient(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } public async Task ChatCompletionAsync( - XhsAiProvider provider, + AiProvider provider, IReadOnlyList<(string Role, string Content)> messages, string? modelOverride = null, CancellationToken cancellationToken = default) @@ -69,7 +69,7 @@ public class XhsLlmClient } public async Task ChatCompletionDetailedAsync( - XhsAiProvider provider, + AiProvider provider, IReadOnlyList messages, IReadOnlyList? tools = null, string? modelOverride = null, @@ -258,11 +258,11 @@ public class XhsLlmClient } } -public static class XhsLlmServiceExtensions +public static class AiLlmServiceExtensions { - public static IServiceCollection AddXhsLlmClient(this IServiceCollection services) + public static IServiceCollection AddAiLlmClient(this IServiceCollection services) { - services.AddHttpClient(XhsLlmClient.HttpClientName, client => + services.AddHttpClient(AiLlmClient.HttpClientName, client => { client.Timeout = TimeSpan.FromMinutes(3); }); @@ -270,7 +270,8 @@ public static class XhsLlmServiceExtensions { client.Timeout = TimeSpan.FromSeconds(45); }); - services.AddTransient(); + services.AddTransient(); return services; } } + diff --git a/src/Oms.Application/Shared/CustomerBalanceMutator.cs b/src/Oms.Application/Shared/CustomerBalanceMutator.cs index 0e7c839..a2ded58 100644 --- a/src/Oms.Application/Shared/CustomerBalanceMutator.cs +++ b/src/Oms.Application/Shared/CustomerBalanceMutator.cs @@ -63,6 +63,29 @@ public class CustomerBalanceMutator : IScopedDependency cancellationToken); } + public Task DebitPickupPayAsync( + Customer customer, + decimal amount, + int pickupOrderId, + string pickupNo, + string? remark, + CancellationToken cancellationToken = default) + { + if (amount <= 0) + { + throw new BusinessException("支付金额必须大于 0"); + } + + return ApplyAsync( + customer, + -amount, + CustomerAccountFlowBizTypes.PickupPay, + pickupOrderId, + pickupNo, + remark, + cancellationToken); + } + private async Task ApplyAsync( Customer customer, decimal signedAmount, diff --git a/src/Oms.Application/Shared/ExpressionPredicate.cs b/src/Oms.Application/Shared/ExpressionPredicate.cs new file mode 100644 index 0000000..1a8810a --- /dev/null +++ b/src/Oms.Application/Shared/ExpressionPredicate.cs @@ -0,0 +1,38 @@ +using System.Linq.Expressions; + +namespace Oms.Application.Shared; + +/// +/// 组合 LINQ 谓词,避免把 `HasValue` / `== null` 写进表达式导致 SqlSugar 生成非法 SQL。 +/// +public static class ExpressionPredicate +{ + public static Expression> True() => static _ => true; + + public static Expression> AndAlso( + Expression> left, + Expression> right) + { + var parameter = Expression.Parameter(typeof(T), "x"); + var leftBody = new ReplaceParameterVisitor(left.Parameters[0], parameter).Visit(left.Body) + ?? throw new InvalidOperationException("left predicate body is null"); + var rightBody = new ReplaceParameterVisitor(right.Parameters[0], parameter).Visit(right.Body) + ?? throw new InvalidOperationException("right predicate body is null"); + return Expression.Lambda>(Expression.AndAlso(leftBody, rightBody), parameter); + } + + private sealed class ReplaceParameterVisitor : ExpressionVisitor + { + private readonly ParameterExpression _from; + private readonly ParameterExpression _to; + + public ReplaceParameterVisitor(ParameterExpression from, ParameterExpression to) + { + _from = from; + _to = to; + } + + protected override Expression VisitParameter(ParameterExpression node) => + ReferenceEquals(node, _from) ? _to : base.VisitParameter(node); + } +} diff --git a/src/Oms.Application/Shared/OmsDocHelper.cs b/src/Oms.Application/Shared/OmsDocHelper.cs index e7a6315..ddcd2a3 100644 --- a/src/Oms.Application/Shared/OmsDocHelper.cs +++ b/src/Oms.Application/Shared/OmsDocHelper.cs @@ -199,7 +199,6 @@ public static class OmsDocHelper { OrderStatusCodes.Draft => "草稿", OrderStatusCodes.Predeclared => "已预报", - OrderStatusCodes.Received => "已收货", OrderStatusCodes.PendingAllocation => "待排货", OrderStatusCodes.PendingPayment => "待支付", OrderStatusCodes.PendingShip => "待发货", diff --git a/src/Oms.Application/Shared/PriceAreaSnapshotHelper.cs b/src/Oms.Application/Shared/PriceAreaSnapshotHelper.cs index 6a4b7e2..3cd3f06 100644 --- a/src/Oms.Application/Shared/PriceAreaSnapshotHelper.cs +++ b/src/Oms.Application/Shared/PriceAreaSnapshotHelper.cs @@ -1,3 +1,4 @@ +using Fake.Application; using Oms.Application.Dtos.Channels; using Oms.Application.Dtos.Orders; using Oms.Application.Services.Orders; @@ -20,6 +21,8 @@ public static class PriceAreaSnapshotHelper IKpiAreaRepository kpiAreaRepository, CancellationToken cancellationToken = default) { + await EnsureSingleResolvedPriceAreaAsync(snapshot, kpiAreaRepository, cancellationToken); + var priceAreaId = await ResolvePriceAreaIdAsync( product, snapshot, @@ -74,4 +77,62 @@ public static class PriceAreaSnapshotHelper return null; } + + /// + /// 校验卖价明细中可解析的分区因子键均指向同一 AreaId;混用多个分区表时抛业务异常。 + /// 非数字/无法解析的分区名(如「美西」)跳过,与 ResolvePriceAreaIdAsync 一致。 + /// + public static async Task EnsureSingleResolvedPriceAreaAsync( + SalesProductPricePublishSnapshotDto snapshot, + IKpiAreaRepository kpiAreaRepository, + CancellationToken cancellationToken = default) + { + var zoneKeys = ParcelBillingCalculator.CollectDistinctDetailZoneKeys(snapshot); + if (zoneKeys.Count == 0) + { + return; + } + + int? resolvedAreaId = null; + foreach (var zoneKey in zoneKeys) + { + var areaId = await TryResolveZoneKeyToAreaIdAsync(zoneKey, kpiAreaRepository, cancellationToken); + if (!areaId.HasValue) + { + continue; + } + + if (resolvedAreaId == null) + { + resolvedAreaId = areaId; + continue; + } + + if (resolvedAreaId.Value != areaId.Value) + { + throw new BusinessException( + $"卖价明细分区混用了多个价格分区(AreaId={resolvedAreaId} 与 {areaId}),请统一分区后再发布"); + } + } + } + + private static async Task TryResolveZoneKeyToAreaIdAsync( + string zoneKey, + IKpiAreaRepository kpiAreaRepository, + CancellationToken cancellationToken) + { + if (!int.TryParse(zoneKey.Trim(), out var zoneId) || zoneId <= 0) + { + return null; + } + + var area = await kpiAreaRepository.FirstOrDefaultAsync(x => x.Id == zoneId, cancellationToken); + if (area != null) + { + return zoneId; + } + + var info = await kpiAreaRepository.GetInfoByIdAsync(zoneId, cancellationToken); + return info?.AreaId; + } } diff --git a/src/Oms.Application/Shared/StaffAdvisorBinder.cs b/src/Oms.Application/Shared/StaffAdvisorBinder.cs new file mode 100644 index 0000000..48c9719 --- /dev/null +++ b/src/Oms.Application/Shared/StaffAdvisorBinder.cs @@ -0,0 +1,67 @@ +using Fake.Rbac.Infrastructure; +using Microsoft.EntityFrameworkCore; +using Oms.Domain.CustomersAggregate.Entities; + +namespace Oms.Application.Shared; + +/// +/// 顾问邀请绑定:注册时把所属顾问(CustomerService)写成员工登录账号。 +/// +public static class StaffAdvisorBinder +{ + /// + /// 仅在 CustomerService 为空时绑定;advisorCode 为员工 Account(来自 ?advisor=)。 + /// 无效账号静默跳过,不阻断注册。 + /// + public static async Task BindAdvisorOnCreateAsync( + Customer entity, + string? advisorCode, + FakeRbacDbContext rbacDbContext, + CancellationToken cancellationToken = default) + { + if (!string.IsNullOrWhiteSpace(entity.CustomerService)) + { + return; + } + + var key = advisorCode?.Trim(); + if (string.IsNullOrWhiteSpace(key)) + { + return; + } + + var account = await ResolveStaffAccountAsync(rbacDbContext, key, cancellationToken); + if (string.IsNullOrWhiteSpace(account)) + { + return; + } + + entity.CustomerService = account; + } + + private static async Task ResolveStaffAccountAsync( + FakeRbacDbContext rbacDbContext, + string key, + CancellationToken cancellationToken) + { + const string sql = """ + SELECT u.`Account` AS `Account` + FROM `user` u + WHERE u.`IsDeleted` = 0 + AND u.`Account` = {0} + ORDER BY u.`CreateTime` ASC + LIMIT 1 + """; + + var row = await rbacDbContext.Database + .SqlQueryRaw(sql, key) + .FirstOrDefaultAsync(cancellationToken); + + return string.IsNullOrWhiteSpace(row?.Account) ? null : row.Account.Trim(); + } + + private sealed class AccountRow + { + public string? Account { get; set; } + } +} diff --git a/src/Oms.Domain/XhsAggregate/Entities/XhsAiProvider.cs b/src/Oms.Domain/AiAggregate/Entities/AiProvider.cs similarity index 72% rename from src/Oms.Domain/XhsAggregate/Entities/XhsAiProvider.cs rename to src/Oms.Domain/AiAggregate/Entities/AiProvider.cs index 0504237..18c9360 100644 --- a/src/Oms.Domain/XhsAggregate/Entities/XhsAiProvider.cs +++ b/src/Oms.Domain/AiAggregate/Entities/AiProvider.cs @@ -1,10 +1,13 @@ using Oms.Domain.Shared; using SqlSugar; -namespace Oms.Domain.XhsAggregate.Entities; +namespace Oms.Domain.AiAggregate.Entities; -[SugarTable("t_xhs_ai_provider")] -public class XhsAiProvider : OmsAuditedAggregateRoot +/// +/// 全局 AI 提供商配置(CustomerId=0 表示平台级)。 +/// +[SugarTable("t_ai_provider")] +public class AiProvider : OmsAuditedAggregateRoot { public int CustomerId { get; set; } diff --git a/src/Oms.Domain/AiAggregate/Entities/AiSkill.cs b/src/Oms.Domain/AiAggregate/Entities/AiSkill.cs new file mode 100644 index 0000000..d4253f7 --- /dev/null +++ b/src/Oms.Domain/AiAggregate/Entities/AiSkill.cs @@ -0,0 +1,30 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.AiAggregate.Entities; + +/// +/// 平台级 AI Skill(提示词/规范正文,全局一份)。 +/// +[SugarTable("t_ai_skill")] +public class AiSkill : OmsAuditedAggregateRoot +{ + /// 稳定键,如 oms-sales-price-publish-risk + public string SkillKey { get; set; } = string.Empty; + + /// 场景:pricePublish / autoTriggerFormula / receiverAddressParse / itfxPrefixScript + public string Scene { get; set; } = string.Empty; + + public string Name { get; set; } = string.Empty; + + [SugarColumn(IsNullable = true, Length = 512)] + public string? Description { get; set; } + + /// 发给模型的正文 + [SugarColumn(ColumnDataType = "longtext")] + public string Content { get; set; } = string.Empty; + + public int SortOrder { get; set; } + + public bool Enabled { get; set; } = true; +} diff --git a/src/Oms.Domain/AiAggregate/Repositories/IAiProviderRepository.cs b/src/Oms.Domain/AiAggregate/Repositories/IAiProviderRepository.cs new file mode 100644 index 0000000..f36c2dd --- /dev/null +++ b/src/Oms.Domain/AiAggregate/Repositories/IAiProviderRepository.cs @@ -0,0 +1,9 @@ +using Fake.Domain.Repositories; +using Oms.Domain.AiAggregate.Entities; + +namespace Oms.Domain.AiAggregate.Repositories; + +public interface IAiProviderRepository : IRepository +{ + Task GetByProviderKeyAsync(int customerId, string providerKey, CancellationToken cancellationToken = default); +} diff --git a/src/Oms.Domain/AiAggregate/Repositories/IAiSkillRepository.cs b/src/Oms.Domain/AiAggregate/Repositories/IAiSkillRepository.cs new file mode 100644 index 0000000..8dfae78 --- /dev/null +++ b/src/Oms.Domain/AiAggregate/Repositories/IAiSkillRepository.cs @@ -0,0 +1,9 @@ +using Fake.Domain.Repositories; +using Oms.Domain.AiAggregate.Entities; + +namespace Oms.Domain.AiAggregate.Repositories; + +public interface IAiSkillRepository : IRepository +{ + Task GetBySkillKeyAsync(string skillKey, CancellationToken cancellationToken = default); +} diff --git a/src/Oms.Domain/ChannelsAggregate/Consts/AllocationSchemeCodes.cs b/src/Oms.Domain/ChannelsAggregate/Consts/AllocationSchemeCodes.cs index d149a97..c61c4cd 100644 --- a/src/Oms.Domain/ChannelsAggregate/Consts/AllocationSchemeCodes.cs +++ b/src/Oms.Domain/ChannelsAggregate/Consts/AllocationSchemeCodes.cs @@ -5,4 +5,15 @@ public static class AllocationSchemeCodes public const string CostLowest = "costLowest"; public const string TimeFastest = "timeFastest"; public const string OverallBest = "overallBest"; + + /// 运营指定渠道(仅重新排货场景,不写入销售产品默认方案)。 + public const string Designated = "designated"; + + public static bool IsAutoScheme(string? scheme) => + string.Equals(scheme, CostLowest, StringComparison.OrdinalIgnoreCase) + || string.Equals(scheme, TimeFastest, StringComparison.OrdinalIgnoreCase) + || string.Equals(scheme, OverallBest, StringComparison.OrdinalIgnoreCase); + + public static bool IsDesignated(string? scheme) => + string.Equals(scheme, Designated, StringComparison.OrdinalIgnoreCase); } diff --git a/src/Oms.Domain/ChannelsAggregate/Consts/IssueHandlerTypeCodes.cs b/src/Oms.Domain/ChannelsAggregate/Consts/IssueHandlerTypeCodes.cs new file mode 100644 index 0000000..17c97b8 --- /dev/null +++ b/src/Oms.Domain/ChannelsAggregate/Consts/IssueHandlerTypeCodes.cs @@ -0,0 +1,27 @@ +namespace Oms.Domain.ChannelsAggregate.Consts; + +public static class IssueHandlerTypeCodes +{ + public const string Customer = "customer"; + + public const string User = "user"; + + public static readonly HashSet All = new(StringComparer.OrdinalIgnoreCase) + { + Customer, + User + }; + + public static string GetDisplayName(string? code) => code?.Trim().ToLowerInvariant() switch + { + Customer => "客户", + User => "指定用户", + _ => "—" + }; + + public static bool IsCustomer(string? code) => + string.Equals(code?.Trim(), Customer, StringComparison.OrdinalIgnoreCase); + + public static bool IsUser(string? code) => + string.Equals(code?.Trim(), User, StringComparison.OrdinalIgnoreCase); +} diff --git a/src/Oms.Domain/ChannelsAggregate/Entities/IssueTemplate.cs b/src/Oms.Domain/ChannelsAggregate/Entities/IssueTemplate.cs index 4a07876..8890c17 100644 --- a/src/Oms.Domain/ChannelsAggregate/Entities/IssueTemplate.cs +++ b/src/Oms.Domain/ChannelsAggregate/Entities/IssueTemplate.cs @@ -17,5 +17,11 @@ public class IssueTemplate : OmsAuditedAggregateRoot public string NotifyMethod { get; set; } = string.Empty; + /// 处理人类型:customer=订单所属客户,user=指定用户。 + public string? HandlerType { get; set; } + + /// 指定处理人用户 Id(HandlerType=user 时)。 + public int? HandlerUserId { get; set; } + public EnableStatus Status { get; set; } = EnableStatus.Enabled; } diff --git a/src/Oms.Domain/ChannelsAggregate/Entities/SalesProduct.cs b/src/Oms.Domain/ChannelsAggregate/Entities/SalesProduct.cs index c1f95e8..a6a65ec 100644 --- a/src/Oms.Domain/ChannelsAggregate/Entities/SalesProduct.cs +++ b/src/Oms.Domain/ChannelsAggregate/Entities/SalesProduct.cs @@ -22,6 +22,16 @@ public class SalesProduct : OmsAuditedAggregateRoot /// public string? TradeTerms { get; set; } + /// + /// 官网线路排序,数值越小越靠前。 + /// + public int RouteSort { get; set; } + + /// + /// 可选附加服务字典 code JSON 数组,如 ["insurance","remoteFee"]。 + /// + public string? AdditionalServices { get; set; } + public string? CustomerWaybill { get; set; } /// diff --git a/src/Oms.Domain/ChannelsAggregate/Entities/SalesProductPublishRecord.cs b/src/Oms.Domain/ChannelsAggregate/Entities/SalesProductPublishRecord.cs index a0c42a4..aedd8c3 100644 --- a/src/Oms.Domain/ChannelsAggregate/Entities/SalesProductPublishRecord.cs +++ b/src/Oms.Domain/ChannelsAggregate/Entities/SalesProductPublishRecord.cs @@ -21,6 +21,12 @@ public class SalesProductPublishRecord : OmsAuditedEntity public string? Description { get; set; } + /// + /// 价格发布 AI 风险分析报告(operatorType=price 时必填)。 + /// + [SugarColumn(ColumnDataType = "mediumtext", IsNullable = true)] + public string? AiAnalysisReport { get; set; } + [SugarColumn(ColumnDataType = "json", IsNullable = true)] public string? Content { get; set; } } diff --git a/src/Oms.Domain/ChannelsAggregate/Entities/ServiceChannel.cs b/src/Oms.Domain/ChannelsAggregate/Entities/ServiceChannel.cs index 3b61b85..109a891 100644 --- a/src/Oms.Domain/ChannelsAggregate/Entities/ServiceChannel.cs +++ b/src/Oms.Domain/ChannelsAggregate/Entities/ServiceChannel.cs @@ -23,6 +23,11 @@ public class ServiceChannel : OmsAuditedAggregateRoot public string? Description { get; set; } + /// + /// 偏远分区 KPI AreaId(渠道侧判定是否偏远)。 + /// + public int? RemoteAreaId { get; set; } + public string? PreScript { get; set; } public EnableStatus IsActive { get; set; } diff --git a/src/Oms.Domain/CustomersAggregate/Consts/CustomerAccountFlowBizTypes.cs b/src/Oms.Domain/CustomersAggregate/Consts/CustomerAccountFlowBizTypes.cs index 0c62c14..e77fc24 100644 --- a/src/Oms.Domain/CustomersAggregate/Consts/CustomerAccountFlowBizTypes.cs +++ b/src/Oms.Domain/CustomersAggregate/Consts/CustomerAccountFlowBizTypes.cs @@ -9,6 +9,8 @@ public static class CustomerAccountFlowBizTypes public const string OrderPay = "orderPay"; + public const string PickupPay = "pickupPay"; + public const string ReferralCommission = "referralCommission"; public const string CommissionToBalance = "commissionToBalance"; diff --git a/src/Oms.Domain/KbAggregate/Entities/KbArticle.cs b/src/Oms.Domain/KbAggregate/Entities/KbArticle.cs new file mode 100644 index 0000000..db35c04 --- /dev/null +++ b/src/Oms.Domain/KbAggregate/Entities/KbArticle.cs @@ -0,0 +1,51 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.KbAggregate.Entities; + +/// +/// 知识库文章。 +/// +[SugarTable("t_kb_article")] +public class KbArticle : OmsAuditedAggregateRoot +{ + public int CategoryId { get; set; } + + [SugarColumn(Length = 200)] + public string Title { get; set; } = string.Empty; + + [SugarColumn(IsNullable = true, Length = 500)] + public string? Summary { get; set; } + + [SugarColumn(ColumnDataType = "longtext")] + public string Content { get; set; } = string.Empty; + + /// customer / internal + [SugarColumn(Length = 16)] + public string Audience { get; set; } = "customer"; + + /// draft / published / offline + [SugarColumn(Length = 16)] + public string Status { get; set; } = "draft"; + + [SugarColumn(IsNullable = true, Length = 256)] + public string? Tags { get; set; } + + [SugarColumn(IsNullable = true, Length = 256)] + public string? RelatedPath { get; set; } + + [SugarColumn(IsNullable = true, Length = 64)] + public string? RelatedLabel { get; set; } + + public bool IsPinned { get; set; } + + public int SortOrder { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? PublishTime { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? ExpireTime { get; set; } + + public int ViewCount { get; set; } +} diff --git a/src/Oms.Domain/KbAggregate/Entities/KbCategory.cs b/src/Oms.Domain/KbAggregate/Entities/KbCategory.cs new file mode 100644 index 0000000..d3b70cf --- /dev/null +++ b/src/Oms.Domain/KbAggregate/Entities/KbCategory.cs @@ -0,0 +1,21 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.KbAggregate.Entities; + +/// +/// 知识库分类。 +/// +[SugarTable("t_kb_category")] +public class KbCategory : OmsAuditedAggregateRoot +{ + [SugarColumn(Length = 64)] + public string Code { get; set; } = string.Empty; + + [SugarColumn(Length = 128)] + public string Name { get; set; } = string.Empty; + + public int SortOrder { get; set; } + + public bool Enabled { get; set; } = true; +} diff --git a/src/Oms.Domain/KbAggregate/Repositories/IKbArticleRepository.cs b/src/Oms.Domain/KbAggregate/Repositories/IKbArticleRepository.cs new file mode 100644 index 0000000..e579079 --- /dev/null +++ b/src/Oms.Domain/KbAggregate/Repositories/IKbArticleRepository.cs @@ -0,0 +1,9 @@ +using Fake.Domain.Repositories; +using Oms.Domain.KbAggregate.Entities; + +namespace Oms.Domain.KbAggregate.Repositories; + +public interface IKbArticleRepository : IRepository +{ + Task CountByCategoryIdAsync(int categoryId, CancellationToken cancellationToken = default); +} diff --git a/src/Oms.Domain/KbAggregate/Repositories/IKbCategoryRepository.cs b/src/Oms.Domain/KbAggregate/Repositories/IKbCategoryRepository.cs new file mode 100644 index 0000000..4fe86d9 --- /dev/null +++ b/src/Oms.Domain/KbAggregate/Repositories/IKbCategoryRepository.cs @@ -0,0 +1,11 @@ +using Fake.Domain.Repositories; +using Oms.Domain.KbAggregate.Entities; + +namespace Oms.Domain.KbAggregate.Repositories; + +public interface IKbCategoryRepository : IRepository +{ + Task GetByCodeAsync(string code, CancellationToken cancellationToken = default); + + Task ExistsCodeAsync(string code, int? excludeId = null, CancellationToken cancellationToken = default); +} diff --git a/src/Oms.Domain/OrdersAggregate/Consts/Customs9610StatusCodes.cs b/src/Oms.Domain/OrdersAggregate/Consts/Customs9610StatusCodes.cs new file mode 100644 index 0000000..0b4b4ff --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Consts/Customs9610StatusCodes.cs @@ -0,0 +1,15 @@ +namespace Oms.Domain.OrdersAggregate.Consts; + +public static class Customs9610StatusCodes +{ + public const string Pending = "pending"; + public const string Declared = "declared"; + + public static readonly string[] All = [Pending, Declared]; +} + +public static class Customs9610FormTypeCodes +{ + public const string SimpleA = "A"; + public const string SummaryB = "B"; +} diff --git a/src/Oms.Domain/OrdersAggregate/Consts/FulfillmentProgressCodes.cs b/src/Oms.Domain/OrdersAggregate/Consts/FulfillmentProgressCodes.cs new file mode 100644 index 0000000..6bc3904 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Consts/FulfillmentProgressCodes.cs @@ -0,0 +1,56 @@ +namespace Oms.Domain.OrdersAggregate.Consts; + +/// +/// 代发订单客户可见进度(由绑定状态 + 包裹生命周期聚合)。 +/// +public static class FulfillmentProgressCodes +{ + /// 待绑定包裹/库存。 + public const string PendingBind = "pendingBind"; + + /// 国内快递在途,未到仓。 + public const string DomesticInTransit = "domesticInTransit"; + + /// 已到仓(或库存已就绪),待仓库拣货。 + public const string ArrivedPendingPick = "arrivedPendingPick"; + + /// 已确认拣货扣减(出库完成)。 + public const string OutboundDone = "outboundDone"; + + public static readonly HashSet All = new(StringComparer.OrdinalIgnoreCase) + { + PendingBind, + DomesticInTransit, + ArrivedPendingPick, + OutboundDone + }; + + /// + /// 非仓内代发返回 null;否则按绑定与包裹状态合成进度码。 + /// + public static string? Resolve(bool isWarehouseFulfill, string? bindStatus, int lineCount, bool hasInTransitParcel) + { + if (!isWarehouseFulfill) + { + return null; + } + + var status = bindStatus?.Trim() ?? "none"; + if (lineCount <= 0 || string.Equals(status, "none", StringComparison.OrdinalIgnoreCase)) + { + return PendingBind; + } + + if (string.Equals(status, OrderStockBindStatusCodes.Deducted, StringComparison.OrdinalIgnoreCase)) + { + return OutboundDone; + } + + if (hasInTransitParcel) + { + return DomesticInTransit; + } + + return ArrivedPendingPick; + } +} diff --git a/src/Oms.Domain/OrdersAggregate/Consts/FulfillmentSourceCodes.cs b/src/Oms.Domain/OrdersAggregate/Consts/FulfillmentSourceCodes.cs new file mode 100644 index 0000000..28025e7 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Consts/FulfillmentSourceCodes.cs @@ -0,0 +1,19 @@ +namespace Oms.Domain.OrdersAggregate.Consts; + +/// +/// 代发订单来源(仅 FulfillmentType=warehouse 时有意义)。 +/// +public static class FulfillmentSourceCodes +{ + /// 店铺订单创建代发运单。 + public const string StoreFulfill = "storeFulfill"; + + /// 普通物流单事后绑定包裹/库存转代发。 + public const string PostBind = "postBind"; + + public static readonly HashSet All = new(StringComparer.OrdinalIgnoreCase) + { + StoreFulfill, + PostBind + }; +} diff --git a/src/Oms.Domain/OrdersAggregate/Consts/FulfillmentTypeCodes.cs b/src/Oms.Domain/OrdersAggregate/Consts/FulfillmentTypeCodes.cs new file mode 100644 index 0000000..d048581 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Consts/FulfillmentTypeCodes.cs @@ -0,0 +1,22 @@ +namespace Oms.Domain.OrdersAggregate.Consts; + +/// +/// 订单履约类型:直发物流 / 仓内代发。 +/// +public static class FulfillmentTypeCodes +{ + /// 直发物流(默认,无需绑定仓内货物)。 + public const string Direct = "direct"; + + /// 仓内代发(需绑定包裹/库存,仓库拣货打包)。 + public const string Warehouse = "warehouse"; + + public static readonly HashSet All = new(StringComparer.OrdinalIgnoreCase) + { + Direct, + Warehouse + }; + + public static bool IsWarehouse(string? code) => + string.Equals(code?.Trim(), Warehouse, StringComparison.OrdinalIgnoreCase); +} diff --git a/src/Oms.Domain/OrdersAggregate/Consts/OrderAdditionalServiceCodes.cs b/src/Oms.Domain/OrdersAggregate/Consts/OrderAdditionalServiceCodes.cs new file mode 100644 index 0000000..1393826 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Consts/OrderAdditionalServiceCodes.cs @@ -0,0 +1,14 @@ +namespace Oms.Domain.OrdersAggregate.Consts; + +/// +/// 附加服务字典 code(dictType = additional_service)。 +/// +public static class OrderAdditionalServiceCodes +{ + public const string Insurance = "insurance"; + + public const string Repackage = "repackage"; + + /// 代打包:绑定库存/包裹时系统自动勾选并触发卖价计费条件。 + public const string ProxyPacking = "proxyPacking"; +} diff --git a/src/Oms.Domain/OrdersAggregate/Consts/OrderBatchJobStatusCodes.cs b/src/Oms.Domain/OrdersAggregate/Consts/OrderBatchJobStatusCodes.cs index ec1ac4c..da96b64 100644 --- a/src/Oms.Domain/OrdersAggregate/Consts/OrderBatchJobStatusCodes.cs +++ b/src/Oms.Domain/OrdersAggregate/Consts/OrderBatchJobStatusCodes.cs @@ -32,6 +32,8 @@ public static class OrderBatchActionCodes public const string HandleStatusUpdate = "handle-status-update"; public const string Print = "print"; public const string GenerateLabelPdf = "generate-label-pdf"; + public const string InboundBilling = "inbound-billing"; + public const string Reallocate = "reallocate"; public const string Export = "export"; public const string ParcelCreate = "parcel-create"; public const string ImportRow = "import-row"; diff --git a/src/Oms.Domain/OrdersAggregate/Consts/OrderExceptionStatusRules.cs b/src/Oms.Domain/OrdersAggregate/Consts/OrderExceptionStatusRules.cs index b188712..b866189 100644 --- a/src/Oms.Domain/OrdersAggregate/Consts/OrderExceptionStatusRules.cs +++ b/src/Oms.Domain/OrdersAggregate/Consts/OrderExceptionStatusRules.cs @@ -6,7 +6,6 @@ public static class OrderExceptionStatusRules { OrderStatusCodes.Draft, OrderStatusCodes.Deleted, - OrderStatusCodes.Problematic, OrderStatusCodes.Claimed }; @@ -18,7 +17,6 @@ public static class OrderExceptionStatusRules { OrderStatusCodes.Draft => "草稿订单不可标记", OrderStatusCodes.Deleted => "已删除订单不可标记", - OrderStatusCodes.Problematic => "已是问题件", OrderStatusCodes.Claimed => "已是理赔件", _ => "订单状态不允许标记" }; diff --git a/src/Oms.Domain/OrdersAggregate/Consts/OrderStatusCodes.cs b/src/Oms.Domain/OrdersAggregate/Consts/OrderStatusCodes.cs index 6debda2..070a647 100644 --- a/src/Oms.Domain/OrdersAggregate/Consts/OrderStatusCodes.cs +++ b/src/Oms.Domain/OrdersAggregate/Consts/OrderStatusCodes.cs @@ -4,7 +4,6 @@ public static class OrderStatusCodes { public const string Draft = "draft"; public const string Predeclared = "predeclared"; - public const string Received = "received"; public const string PendingAllocation = "pendingAllocation"; public const string PendingPayment = "pendingPayment"; public const string PendingShip = "pendingShip"; diff --git a/src/Oms.Domain/OrdersAggregate/Consts/PickupOrderStatusCodes.cs b/src/Oms.Domain/OrdersAggregate/Consts/PickupOrderStatusCodes.cs new file mode 100644 index 0000000..7bf5b67 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Consts/PickupOrderStatusCodes.cs @@ -0,0 +1,43 @@ +namespace Oms.Domain.OrdersAggregate.Consts; + +public static class PickupOrderStatusCodes +{ + public const string Draft = "draft"; + public const string Scheduled = "scheduled"; + public const string Dispatched = "dispatched"; + public const string Picked = "picked"; + public const string Inbound = "inbound"; + public const string Cancelled = "cancelled"; + public const string Failed = "failed"; + + public static bool IsMutableBinding(string? status) => + status is Draft or Scheduled; + + public static bool IsTerminal(string? status) => + status is Cancelled or Failed or Inbound; +} + +public static class PickupPayStatusCodes +{ + public const string Unpaid = "unpaid"; + public const string Paid = "paid"; +} + +public static class PickupSettlementStatusCodes +{ + public const string None = "none"; + public const string Pending = "pending"; + public const string Settled = "settled"; +} + +public static class PickupPayModeCodes +{ + public const string Prepaid = "prepaid"; + public const string Collect = "collect"; +} + +public static class OrderInboundMethodCodes +{ + public const string SelfShip = "selfShip"; + public const string DoorPickup = "doorPickup"; +} diff --git a/src/Oms.Domain/OrdersAggregate/Entities/Customs9610Order.cs b/src/Oms.Domain/OrdersAggregate/Entities/Customs9610Order.cs new file mode 100644 index 0000000..12be076 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Entities/Customs9610Order.cs @@ -0,0 +1,164 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.OrdersAggregate.Entities; + +/// +/// 9610 汇总申报单(1 运单 : 0..1)。 +/// +[SugarTable("t_9610_order")] +public class Customs9610Order : OmsAuditedAggregateRoot +{ + public int OrderId { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? ServiceNo { get; set; } + + public int CustomerId { get; set; } + + [SugarColumn(Length = 16)] + public string Status { get; set; } = "pending"; + + /// 电商平台。 + [SugarColumn(Length = 16)] + public string PlatformCode { get; set; } = string.Empty; + + /// 电商企业代码。 + [SugarColumn(Length = 18, IsNullable = true)] + public string? EcomCorpCode { get; set; } + + /// 电商企业名称。 + [SugarColumn(Length = 100, IsNullable = true)] + public string? EcomCorpName { get; set; } + + /// 生产销售单位代码。 + [SugarColumn(Length = 18, IsNullable = true)] + public string? ProducerCode { get; set; } + + /// 生产销售单位。 + [SugarColumn(Length = 100, IsNullable = true)] + public string? ProducerName { get; set; } + + [SugarColumn(Length = 48)] + public string ClientNo { get; set; } = string.Empty; + + /// 业务类型:A 简化 / B 汇总。 + [SugarColumn(Length = 1)] + public string BusinessType { get; set; } = "B"; + + /// 区域 SZ/other(A 必填)。 + [SugarColumn(Length = 10, IsNullable = true)] + public string? Region { get; set; } + + /// 是否代理申报:是/否(A 必填)。 + [SugarColumn(Length = 2, IsNullable = true)] + public string? AgentDeclare { get; set; } + + /// 实际卖家信用代码(A 可填)。 + [SugarColumn(Length = 18, IsNullable = true)] + public string? ActualSellerCode { get; set; } + + /// 汇总预录:0 已预录 / 1 未预录(B 必填)。 + [SugarColumn(Length = 1, IsNullable = true)] + public string? PreRecordFlag { get; set; } + + /// 是否汇总简化申报。 + public byte IsSummarySimple { get; set; } + + public decimal GrossWeight { get; set; } + + [SugarColumn(Length = 4)] + public string Currency { get; set; } = "CNY"; + + /// 目的国。 + [SugarColumn(Length = 4)] + public string DestCountry { get; set; } = string.Empty; + + [SugarColumn(DecimalDigits = 5, IsNullable = true)] + public decimal? Freight { get; set; } + + [SugarColumn(Length = 4, IsNullable = true)] + public string? FreightCurrency { get; set; } + + [SugarColumn(IsNullable = true)] + public int? FreightMark { get; set; } + + [SugarColumn(IsNullable = true)] + public int? PackageType { get; set; } + + [SugarColumn(IsNullable = true)] + public int? PackageQty { get; set; } + + /// 出货单号。 + [SugarColumn(Length = 32, IsNullable = true)] + public string? ShipmentNo { get; set; } + + /// 海关订单号(申报回写)。 + [SugarColumn(Length = 32, IsNullable = true)] + public string? CustomsOrderNo { get; set; } + + [SugarColumn(Length = 32, IsNullable = true)] + public string? DownstreamRefNo { get; set; } + + [SugarColumn(Length = 48, IsNullable = true)] + public string? EnterpriseBizNo { get; set; } + + [SugarColumn(Length = 48, IsNullable = true)] + public string? ManifestNo { get; set; } + + [SugarColumn(Length = 48, IsNullable = true)] + public string? ClearanceTime { get; set; } + + [SugarColumn(Length = 48, IsNullable = true)] + public string? CustomsInboundTime { get; set; } + + [SugarColumn(Length = 4, IsNullable = true)] + public string? CustomsState { get; set; } + + [SugarColumn(Length = 4, IsNullable = true)] + public string? DeclareCustomsCode { get; set; } + + /// 电商平台代码(清单回写)。 + [SugarColumn(Length = 18, IsNullable = true)] + public string? PlatformCorpCode { get; set; } + + /// 电商平台名称(清单回写)。 + [SugarColumn(Length = 100, IsNullable = true)] + public string? PlatformName { get; set; } + + [SugarColumn(Length = 18, IsNullable = true)] + public string? LogisticsCorpCode { get; set; } + + [SugarColumn(Length = 100, IsNullable = true)] + public string? LogisticsCorpName { get; set; } + + [SugarColumn(Length = 4, IsNullable = true)] + public string? IeMark { get; set; } + + [SugarColumn(Length = 4, IsNullable = true)] + public string? ExportPortCode { get; set; } + + [SugarColumn(Length = 32, IsNullable = true)] + public string? ExportDate { get; set; } + + [SugarColumn(Length = 18, IsNullable = true)] + public string? DeclareAgentCode { get; set; } + + [SugarColumn(Length = 100, IsNullable = true)] + public string? DeclareAgentName { get; set; } + + [SugarColumn(Length = 4, IsNullable = true)] + public string? TradeModeCode { get; set; } + + [SugarColumn(Length = 4, IsNullable = true)] + public string? TransportMode { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? DeclareTime { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? ManifestSyncTime { get; set; } + + [SugarColumn(Length = 512, IsNullable = true)] + public string? FailReason { get; set; } +} diff --git a/src/Oms.Domain/OrdersAggregate/Entities/Customs9610OrderItem.cs b/src/Oms.Domain/OrdersAggregate/Entities/Customs9610OrderItem.cs new file mode 100644 index 0000000..271ced4 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Entities/Customs9610OrderItem.cs @@ -0,0 +1,59 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.OrdersAggregate.Entities; + +/// +/// 9610 申报商品明细(字段名对齐 t_order_declaration;海关专属另列)。 +/// +[SugarTable("t_9610_order_item")] +public class Customs9610OrderItem : OmsAuditedAggregateRoot +{ + public int Customs9610OrderId { get; set; } + + [SugarColumn(IsNullable = true)] + public int? OrderDeclarationId { get; set; } + + [SugarColumn(Length = 32)] + public string Sku { get; set; } = string.Empty; + + [SugarColumn(Length = 250)] + public string CnName { get; set; } = string.Empty; + + [SugarColumn(Length = 10, IsNullable = true)] + public string? ExHsCode { get; set; } + + /// 申报要素。 + [SugarColumn(Length = 255, IsNullable = true)] + public string? DeclareElement { get; set; } + + [SugarColumn(Length = 255, IsNullable = true)] + public string? Barcode { get; set; } + + [SugarColumn(Length = 255, IsNullable = true)] + public string? DestCountry { get; set; } + + [SugarColumn(Length = 3, IsNullable = true)] + public string? ItemCurrency { get; set; } + + public decimal UnitPrice { get; set; } + + [SugarColumn(DecimalDigits = 5, IsNullable = true)] + public decimal? Amount { get; set; } + + public decimal Quantity { get; set; } + + [SugarColumn(DecimalDigits = 5, IsNullable = true)] + public decimal? LegalQty { get; set; } + + [SugarColumn(Length = 3, IsNullable = true)] + public string? Unit { get; set; } + + [SugarColumn(Length = 3, IsNullable = true)] + public string? LegalUnit { get; set; } + + [SugarColumn(DecimalDigits = 4, IsNullable = true)] + public decimal? Freight { get; set; } + + public int SortNo { get; set; } +} diff --git a/src/Oms.Domain/OrdersAggregate/Entities/Order.cs b/src/Oms.Domain/OrdersAggregate/Entities/Order.cs index f096c77..f58d638 100644 --- a/src/Oms.Domain/OrdersAggregate/Entities/Order.cs +++ b/src/Oms.Domain/OrdersAggregate/Entities/Order.cs @@ -60,6 +60,24 @@ public class Order : OmsAuditedAggregateRoot [SugarColumn(Length = 512, IsNullable = true)] public string? AllocationPendingReason { get; set; } + /// + /// 最近一次排货方案:costLowest / timeFastest / overallBest / designated。 + /// + [SugarColumn(Length = 32, IsNullable = true)] + public string? AllocationScheme { get; set; } + + /// + /// 最近一次排货过程快照 JSON。 + /// + [SugarColumn(ColumnDataType = "json", IsNullable = true)] + public string? AllocationTraceJson { get; set; } + + /// + /// 排货快照写入时间。 + /// + [SugarColumn(IsNullable = true)] + public DateTime? AllocationTraceTime { get; set; } + public string? SalesProductRulesVersion { get; set; } public string? SalesProductPriceVersion { get; set; } @@ -105,6 +123,16 @@ public class Order : OmsAuditedAggregateRoot public decimal? ReceivableSubtotal { get; set; } + /// + /// 预报应收快照(创建预报计费后固化;入库重算不覆盖,用于预报→入库差额)。 + /// + public decimal? ForecastReceivableAmount { get; set; } + + /// + /// 预报应付快照(创建预报计费后固化;入库重算不覆盖,用于预报→入库差额)。 + /// + public decimal? ForecastPayableAmount { get; set; } + public decimal LevelDiscountAmount { get; set; } public int? CouponInstanceId { get; set; } @@ -128,6 +156,18 @@ public class Order : OmsAuditedAggregateRoot /// public int? CustomerSenderAddressId { get; set; } + /// + /// 到仓方式:selfShip / doorPickup。 + /// + [SugarColumn(Length = 16, IsNullable = true)] + public string? InboundMethod { get; set; } + + /// + /// 关联揽收单 Id(冗余,真源为 t_pickup_order_line)。 + /// + [SugarColumn(IsNullable = true)] + public int? PickupOrderId { get; set; } + public string? OrganizationId { get; set; } public int SecretLevel { get; set; } = 2; @@ -167,6 +207,23 @@ public class Order : OmsAuditedAggregateRoot public byte IsRemote { get; set; } + /// + /// 客户勾选附加服务字典 code JSON 数组,如 ["insurance"]。 + /// + public string? AdditionalServices { get; set; } + + /// + /// 履约类型:direct 直发物流 / warehouse 仓内代发。 + /// + [SugarColumn(Length = 16, IsNullable = true)] + public string? FulfillmentType { get; set; } + + /// + /// 代发来源:storeFulfill 店铺代发 / postBind 事后绑定转代发。 + /// + [SugarColumn(Length = 32, IsNullable = true)] + public string? FulfillmentSource { get; set; } + /// /// 出单时实际使用的标签模板 Id(面单文件见 t_order_file.systemLabel)。 /// diff --git a/src/Oms.Domain/OrdersAggregate/Entities/OrderExceptionEvent.cs b/src/Oms.Domain/OrdersAggregate/Entities/OrderExceptionEvent.cs index 8f368ba..be4a1e0 100644 --- a/src/Oms.Domain/OrdersAggregate/Entities/OrderExceptionEvent.cs +++ b/src/Oms.Domain/OrdersAggregate/Entities/OrderExceptionEvent.cs @@ -28,6 +28,12 @@ public class OrderExceptionEvent : OmsAuditedAggregateRoot public string? NotifyMethod { get; set; } + public string? HandlerNames { get; set; } + + public string? HandlerType { get; set; } + + public int? HandlerUserId { get; set; } + public string? ClaimType { get; set; } public decimal? ClaimAmount { get; set; } diff --git a/src/Oms.Domain/OrdersAggregate/Entities/PickupOrder.cs b/src/Oms.Domain/OrdersAggregate/Entities/PickupOrder.cs new file mode 100644 index 0000000..f758144 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Entities/PickupOrder.cs @@ -0,0 +1,137 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.OrdersAggregate.Entities; + +/// +/// 揽收单(上门取件履约 + 对客收款 + 承运结算)。 +/// +[SugarTable("t_pickup_order")] +public class PickupOrder : OmsAuditedAggregateRoot +{ + [SugarColumn(Length = 32)] + public string PickupNo { get; set; } = string.Empty; + + [SugarColumn(Length = 64, IsNullable = true)] + public string? RequestId { get; set; } + + public int CustomerId { get; set; } + + [SugarColumn(Length = 36, IsNullable = true)] + public string? OrganizationId { get; set; } + + public int SecretLevel { get; set; } = 2; + + public int SenderAddressId { get; set; } + + [SugarColumn(Length = 50)] + public string SenderName { get; set; } = string.Empty; + + [SugarColumn(Length = 255, IsNullable = true)] + public string? SenderCompany { get; set; } + + [SugarColumn(IsNullable = true)] + public int? SenderCountry { get; set; } + + [SugarColumn(Length = 8, IsNullable = true)] + public string? SenderCountryCode { get; set; } + + [SugarColumn(Length = 50, IsNullable = true)] + public string? SenderProvince { get; set; } + + [SugarColumn(Length = 50, IsNullable = true)] + public string? SenderCity { get; set; } + + [SugarColumn(Length = 50, IsNullable = true)] + public string? SenderZipCode { get; set; } + + [SugarColumn(Length = 500)] + public string SenderStreetAddress1 { get; set; } = string.Empty; + + [SugarColumn(Length = 500, IsNullable = true)] + public string? SenderStreetAddress2 { get; set; } + + [SugarColumn(Length = 500, IsNullable = true)] + public string? SenderStreetAddress3 { get; set; } + + [SugarColumn(Length = 50, IsNullable = true)] + public string? SenderHouseNumber { get; set; } + + [SugarColumn(Length = 50, IsNullable = true)] + public string? SenderPhone { get; set; } + + [SugarColumn(Length = 50, IsNullable = true)] + public string? SenderTelePhone { get; set; } + + [SugarColumn(Length = 60, IsNullable = true)] + public string? SenderEmail { get; set; } + + public int WarehouseId { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? CarrierCode { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? CarrierService { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? CarrierWaybillNo { get; set; } + + public DateTime ExpectPickupTime { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? PickupWindowStart { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? PickupWindowEnd { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? ActualPickupTime { get; set; } + + [SugarColumn(Length = 32)] + public string Status { get; set; } = "draft"; + + public int ParcelCount { get; set; } + + [SugarColumn(DecimalDigits = 3, IsNullable = true)] + public decimal? TotalActualWeight { get; set; } + + [SugarColumn(DecimalDigits = 3, IsNullable = true)] + public decimal? ChargeableWeight { get; set; } + + [SugarColumn(Length = 8)] + public string Currency { get; set; } = "CNY"; + + [SugarColumn(DecimalDigits = 2, IsNullable = true)] + public decimal? FreightAmount { get; set; } + + [SugarColumn(DecimalDigits = 2, IsNullable = true)] + public decimal? OtherFeeAmount { get; set; } + + [SugarColumn(DecimalDigits = 2, IsNullable = true)] + public decimal? ReceivableAmount { get; set; } + + [SugarColumn(Length = 16)] + public string PayStatus { get; set; } = "unpaid"; + + [SugarColumn(IsNullable = true)] + public DateTime? PayTime { get; set; } + + [SugarColumn(Length = 16)] + public string PayMode { get; set; } = "prepaid"; + + [SugarColumn(DecimalDigits = 2, IsNullable = true)] + public decimal? CarrierPayableAmount { get; set; } + + [SugarColumn(Length = 16)] + public string SettlementStatus { get; set; } = "none"; + + [SugarColumn(Length = 64, IsNullable = true)] + public string? SettlementBatchNo { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? SettledAt { get; set; } + + [SugarColumn(Length = 512, IsNullable = true)] + public string? Remark { get; set; } +} diff --git a/src/Oms.Domain/OrdersAggregate/Entities/PickupOrderLine.cs b/src/Oms.Domain/OrdersAggregate/Entities/PickupOrderLine.cs new file mode 100644 index 0000000..f19450d --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Entities/PickupOrderLine.cs @@ -0,0 +1,23 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.OrdersAggregate.Entities; + +/// +/// 揽收单关联物流订单。 +/// +[SugarTable("t_pickup_order_line")] +public class PickupOrderLine : OmsAuditedAggregateRoot +{ + public int PickupOrderId { get; set; } + + public int OrderId { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? ServiceNo { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? ClientNo { get; set; } + + public int SortNo { get; set; } +} diff --git a/src/Oms.Domain/OrdersAggregate/OrderListFilter.cs b/src/Oms.Domain/OrdersAggregate/OrderListFilter.cs index df7e5c2..0cbfc0e 100644 --- a/src/Oms.Domain/OrdersAggregate/OrderListFilter.cs +++ b/src/Oms.Domain/OrdersAggregate/OrderListFilter.cs @@ -11,6 +11,21 @@ public class OrderListFilter public string? OrderSource { get; set; } + /// + /// 履约类型:all / direct / warehouse。 + /// + public string? FulfillmentType { get; set; } + + /// + /// 绑定状态聚合:all / none / bound / deducted。 + /// + public string? StockBindStatus { get; set; } + + /// + /// 代发进度:pendingBind / domesticInTransit / arrivedPendingPick / outboundDone。 + /// + public string? FulfillProgress { get; set; } + public string? Keyword { get; set; } public DateTime? CreateTimeStart { get; set; } @@ -19,6 +34,11 @@ public class OrderListFilter public int? CustomerId { get; set; } + /// + /// 发货仓 ID(订单或绑定行所属仓)。 + /// + public int? WarehouseId { get; set; } + /// /// 表头字段级筛选(已规范化的白名单条件)。 /// diff --git a/src/Oms.Domain/OrdersAggregate/OrderReceivablePayableFilter.cs b/src/Oms.Domain/OrdersAggregate/OrderReceivablePayableFilter.cs index 9d72a6f..41c494e 100644 --- a/src/Oms.Domain/OrdersAggregate/OrderReceivablePayableFilter.cs +++ b/src/Oms.Domain/OrdersAggregate/OrderReceivablePayableFilter.cs @@ -19,4 +19,34 @@ public class OrderReceivablePayableFilter : OrderListFilter /// 计费阶段:forecast / inbound / outbound。 /// public string? ChargingStage { get; set; } + + /// + /// 客户编码关键词(模糊匹配)。 + /// + public string? CustomerCode { get; set; } + + /// + /// 仅保留各运单费用项的当前生效阶段(出库 > 入库 > 预报)。 + /// + public bool EffectiveStageOnly { get; set; } + + /// + /// 时间筛选字段:createTime / receiveTime / shipTime / payTime。 + /// + public string? TimeField { get; set; } + + /// + /// 时间区间起(与 TimeField 对应字段)。 + /// + public DateTime? TimeStart { get; set; } + + /// + /// 时间区间止(与 TimeField 对应字段)。 + /// + public DateTime? TimeEnd { get; set; } + + /// + /// 支付状态:0 未支付,1 已支付;null 表示全部。 + /// + public int? IsPaid { get; set; } } diff --git a/src/Oms.Domain/OrdersAggregate/OrderReceivablePayableSummaryRow.cs b/src/Oms.Domain/OrdersAggregate/OrderReceivablePayableSummaryRow.cs new file mode 100644 index 0000000..64afd60 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/OrderReceivablePayableSummaryRow.cs @@ -0,0 +1,15 @@ +namespace Oms.Domain.OrdersAggregate; + +/// +/// 应收应付汇总行(按费用类型 + 币种)。 +/// +public class OrderReceivablePayableSummaryRow +{ + public string FeeType { get; set; } = string.Empty; + + public string Currency { get; set; } = string.Empty; + + public decimal TotalAmount { get; set; } + + public int LineCount { get; set; } +} diff --git a/src/Oms.Domain/OrdersAggregate/Repositories/ICustoms9610OrderRepository.cs b/src/Oms.Domain/OrdersAggregate/Repositories/ICustoms9610OrderRepository.cs new file mode 100644 index 0000000..0956b90 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Repositories/ICustoms9610OrderRepository.cs @@ -0,0 +1,24 @@ +using Fake.Domain.Repositories; +using Oms.Domain.OrdersAggregate.Entities; + +namespace Oms.Domain.OrdersAggregate.Repositories; + +public interface ICustoms9610OrderRepository : IRepository +{ + Task GetByOrderIdAsync(int orderId, CancellationToken cancellationToken = default); + + Task HardDeleteItemsByHeaderIdAsync(int customs9610OrderId, CancellationToken cancellationToken = default); + + Task HardDeleteAsync(Customs9610Order entity, CancellationToken cancellationToken = default); +} + +public interface ICustoms9610OrderItemRepository : IRepository +{ + Task> GetByHeaderIdAsync( + int customs9610OrderId, + CancellationToken cancellationToken = default); + + Task> GetByHeaderIdsAsync( + IReadOnlyCollection headerIds, + CancellationToken cancellationToken = default); +} diff --git a/src/Oms.Domain/OrdersAggregate/Repositories/IOrderRepository.cs b/src/Oms.Domain/OrdersAggregate/Repositories/IOrderRepository.cs index f720371..1cd7722 100644 --- a/src/Oms.Domain/OrdersAggregate/Repositories/IOrderRepository.cs +++ b/src/Oms.Domain/OrdersAggregate/Repositories/IOrderRepository.cs @@ -76,6 +76,15 @@ public interface IOrderRepository : IRepository OrderReceivablePayableFilter filter, CancellationToken cancellationToken = default); + Task> GetReceivablePayableSummaryAsync( + OrderReceivablePayableFilter filter, + CancellationToken cancellationToken = default); + + Task> GetReceivablePayableExportListAsync( + OrderReceivablePayableFilter filter, + int maxRows, + CancellationToken cancellationToken = default); + Task> GetStatusCountsAsync(int? customerId, CancellationToken cancellationToken = default); Task> GetStatusCountsByFilterAsync( @@ -86,6 +95,10 @@ public interface IOrderRepository : IRepository OrderListFilter filter, CancellationToken cancellationToken = default); + Task> GetFulfillProgressCountsByFilterAsync( + OrderListFilter filter, + CancellationToken cancellationToken = default); + Task CountByFilterAndCreateTimeRangeAsync( OrderListFilter filter, DateTime startInclusive, @@ -98,6 +111,15 @@ public interface IOrderRepository : IRepository DateTime endExclusive, CancellationToken cancellationToken = default); + /// + /// 按创建时间汇总客户应付金额(Order.PayableAmount,营销后净额)。 + /// + Task SumPayableAmountByCreateTimeRangeAsync( + OrderListFilter filter, + DateTime startInclusive, + DateTime endExclusive, + CancellationToken cancellationToken = default); + Task SumFeeAmountByPayTimeRangeAsync( OrderListFilter filter, string feeType, diff --git a/src/Oms.Domain/OrdersAggregate/Repositories/IPickupOrderRepository.cs b/src/Oms.Domain/OrdersAggregate/Repositories/IPickupOrderRepository.cs new file mode 100644 index 0000000..55b9cc8 --- /dev/null +++ b/src/Oms.Domain/OrdersAggregate/Repositories/IPickupOrderRepository.cs @@ -0,0 +1,45 @@ +using Fake.Domain.Repositories; +using Oms.Domain.OrdersAggregate.Entities; + +namespace Oms.Domain.OrdersAggregate.Repositories; + +public interface IPickupOrderRepository : IRepository +{ + Task GetByPickupNoAsync(string pickupNo, CancellationToken cancellationToken = default); + + Task GetOwnedAsync(int id, int customerId, CancellationToken cancellationToken = default); + + Task GetWorkplaceCountsAsync( + int? customerId, + CancellationToken cancellationToken = default); + + Task CountByCreateTimeRangeAsync( + int? customerId, + DateTime startInclusive, + DateTime endExclusive, + CancellationToken cancellationToken = default); +} + +public sealed class PickupWorkplaceCountRow +{ + public int PendingPayment { get; set; } + + public int PendingSchedule { get; set; } + + public int PendingPickup { get; set; } + + public int PendingInbound { get; set; } +} + +public interface IPickupOrderLineRepository : IRepository +{ + Task> GetByPickupOrderIdAsync(int pickupOrderId, CancellationToken cancellationToken = default); + + Task GetActiveByOrderIdAsync(int orderId, CancellationToken cancellationToken = default); + + Task> GetActiveByOrderIdsAsync(IReadOnlyCollection orderIds, CancellationToken cancellationToken = default); + + Task HardDeleteByPickupOrderIdAsync(int pickupOrderId, CancellationToken cancellationToken = default); + + Task HardDeleteAsync(PickupOrderLine line, CancellationToken cancellationToken = default); +} diff --git a/src/Oms.Domain/WarehouseAggregate/Entities/CSku.cs b/src/Oms.Domain/WarehouseAggregate/Entities/CSku.cs index 058a91b..cbb6855 100644 --- a/src/Oms.Domain/WarehouseAggregate/Entities/CSku.cs +++ b/src/Oms.Domain/WarehouseAggregate/Entities/CSku.cs @@ -12,8 +12,16 @@ public class CSku : OmsAuditedAggregateRoot public string SkuName { get; set; } = string.Empty; + public string? SkuNameEn { get; set; } + public string? SkuImageUrl { get; set; } + public decimal? UnitPrice { get; set; } + + public string? ExHsCode { get; set; } + + public string? ImHsCode { get; set; } + public decimal? WeightG { get; set; } public decimal? LengthCm { get; set; } diff --git a/src/Oms.Domain/XhsAggregate/Repositories/IXhsRepositories.cs b/src/Oms.Domain/XhsAggregate/Repositories/IXhsRepositories.cs index c37a36e..a59230d 100644 --- a/src/Oms.Domain/XhsAggregate/Repositories/IXhsRepositories.cs +++ b/src/Oms.Domain/XhsAggregate/Repositories/IXhsRepositories.cs @@ -51,9 +51,4 @@ public interface IXhsHumanConfigRepository : IRepository Task GetByCustomerIdAsync(int customerId, CancellationToken cancellationToken = default); } -public interface IXhsAiProviderRepository : IRepository -{ - Task GetByProviderKeyAsync(int customerId, string providerKey, CancellationToken cancellationToken = default); -} - public interface IXhsMediaRepository : IRepository; diff --git a/src/Oms.SqlSugarCore/Ai/AiProviderRepository.cs b/src/Oms.SqlSugarCore/Ai/AiProviderRepository.cs new file mode 100644 index 0000000..ad1f961 --- /dev/null +++ b/src/Oms.SqlSugarCore/Ai/AiProviderRepository.cs @@ -0,0 +1,16 @@ +using Fake.DependencyInjection; +using Oms.Domain.AiAggregate.Entities; +using Oms.Domain.AiAggregate.Repositories; +using Oms.SqlSugarCore.Repositories; + +namespace Oms.SqlSugarCore.Ai; + +public class AiProviderRepository + : OmsSqlSugarRepository, IAiProviderRepository, IScopedDependency +{ + public Task GetByProviderKeyAsync( + int customerId, + string providerKey, + CancellationToken cancellationToken = default) => + FirstOrDefaultAsync(x => x.CustomerId == customerId && x.ProviderKey == providerKey, cancellationToken); +} diff --git a/src/Oms.SqlSugarCore/Ai/AiSkillRepository.cs b/src/Oms.SqlSugarCore/Ai/AiSkillRepository.cs new file mode 100644 index 0000000..cac80c7 --- /dev/null +++ b/src/Oms.SqlSugarCore/Ai/AiSkillRepository.cs @@ -0,0 +1,15 @@ +using Fake.DependencyInjection; +using Oms.Domain.AiAggregate.Entities; +using Oms.Domain.AiAggregate.Repositories; +using Oms.SqlSugarCore.Repositories; + +namespace Oms.SqlSugarCore.Ai; + +public class AiSkillRepository + : OmsSqlSugarRepository, IAiSkillRepository, IScopedDependency +{ + public Task GetBySkillKeyAsync( + string skillKey, + CancellationToken cancellationToken = default) => + FirstOrDefaultAsync(x => x.SkillKey == skillKey, cancellationToken); +} diff --git a/src/Oms.SqlSugarCore/Kb/KbArticleRepository.cs b/src/Oms.SqlSugarCore/Kb/KbArticleRepository.cs new file mode 100644 index 0000000..3cd9697 --- /dev/null +++ b/src/Oms.SqlSugarCore/Kb/KbArticleRepository.cs @@ -0,0 +1,13 @@ +using Fake.DependencyInjection; +using Oms.Domain.KbAggregate.Entities; +using Oms.Domain.KbAggregate.Repositories; +using Oms.SqlSugarCore.Repositories; + +namespace Oms.SqlSugarCore.Kb; + +public class KbArticleRepository + : OmsSqlSugarRepository, IKbArticleRepository, IScopedDependency +{ + public Task CountByCategoryIdAsync(int categoryId, CancellationToken cancellationToken = default) => + CountAsync(x => x.CategoryId == categoryId, cancellationToken); +} diff --git a/src/Oms.SqlSugarCore/Kb/KbCategoryRepository.cs b/src/Oms.SqlSugarCore/Kb/KbCategoryRepository.cs new file mode 100644 index 0000000..f6fdc90 --- /dev/null +++ b/src/Oms.SqlSugarCore/Kb/KbCategoryRepository.cs @@ -0,0 +1,26 @@ +using Fake.DependencyInjection; +using Oms.Domain.KbAggregate.Entities; +using Oms.Domain.KbAggregate.Repositories; +using Oms.SqlSugarCore.Repositories; + +namespace Oms.SqlSugarCore.Kb; + +public class KbCategoryRepository + : OmsSqlSugarRepository, IKbCategoryRepository, IScopedDependency +{ + public Task GetByCodeAsync(string code, CancellationToken cancellationToken = default) => + FirstOrDefaultAsync(x => x.Code == code, cancellationToken); + + public async Task ExistsCodeAsync( + string code, + int? excludeId = null, + CancellationToken cancellationToken = default) + { + if (excludeId is > 0) + { + return await AnyAsync(x => x.Code == code && x.Id != excludeId.Value, cancellationToken); + } + + return await AnyAsync(x => x.Code == code, cancellationToken); + } +} diff --git a/src/Oms.SqlSugarCore/Orders/Customs9610OrderRepository.cs b/src/Oms.SqlSugarCore/Orders/Customs9610OrderRepository.cs new file mode 100644 index 0000000..9e1445a --- /dev/null +++ b/src/Oms.SqlSugarCore/Orders/Customs9610OrderRepository.cs @@ -0,0 +1,56 @@ +using Fake.DependencyInjection; +using Oms.Domain.OrdersAggregate.Entities; +using Oms.Domain.OrdersAggregate.Repositories; +using Oms.SqlSugarCore.Repositories; + +namespace Oms.SqlSugarCore.Orders; + +public class Customs9610OrderRepository : OmsSqlSugarRepository, ICustoms9610OrderRepository, IScopedDependency +{ + public Task GetByOrderIdAsync(int orderId, CancellationToken cancellationToken = default) + { + return FirstOrDefaultAsync(x => x.OrderId == orderId, cancellationToken); + } + + public async Task HardDeleteItemsByHeaderIdAsync(int customs9610OrderId, CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + await db.Deleteable() + .Where(x => x.Customs9610OrderId == customs9610OrderId) + .ExecuteCommandAsync(cancellationToken); + } + + public async Task HardDeleteAsync(Customs9610Order entity, CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + await db.Deleteable() + .Where(x => x.Id == entity.Id) + .ExecuteCommandAsync(cancellationToken); + } +} + +public class Customs9610OrderItemRepository + : OmsSqlSugarRepository, + ICustoms9610OrderItemRepository, + IScopedDependency +{ + public Task> GetByHeaderIdAsync( + int customs9610OrderId, + CancellationToken cancellationToken = default) + { + return GetListAsync(x => x.Customs9610OrderId == customs9610OrderId, cancellationToken: cancellationToken); + } + + public async Task> GetByHeaderIdsAsync( + IReadOnlyCollection headerIds, + CancellationToken cancellationToken = default) + { + if (headerIds == null || headerIds.Count == 0) + { + return []; + } + + var ids = headerIds.Distinct().ToList(); + return await GetListAsync(x => ids.Contains(x.Customs9610OrderId), cancellationToken: cancellationToken); + } +} diff --git a/src/Oms.SqlSugarCore/Orders/OrderRepository.cs b/src/Oms.SqlSugarCore/Orders/OrderRepository.cs index d0279ae..c50a52f 100644 --- a/src/Oms.SqlSugarCore/Orders/OrderRepository.cs +++ b/src/Oms.SqlSugarCore/Orders/OrderRepository.cs @@ -1,8 +1,11 @@ using Fake.DependencyInjection; +using Oms.Domain.CustomersAggregate.Entities; using Oms.Domain.OrdersAggregate; using Oms.Domain.OrdersAggregate.Consts; using Oms.Domain.OrdersAggregate.Entities; using Oms.Domain.OrdersAggregate.Repositories; +using Oms.Domain.WarehouseAggregate.Consts; +using Oms.Domain.WarehouseAggregate.Entities; using Oms.SqlSugarCore.Repositories; using SqlSugar; @@ -52,11 +55,33 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I var keyword = filter.Keyword?.Trim(); if (!string.IsNullOrWhiteSpace(keyword)) { - query = query.Where(x => - x.ServiceNo.Contains(keyword) - || (x.ClientNo ?? string.Empty).Contains(keyword) - || (x.TrackNo ?? string.Empty).Contains(keyword) - || (x.DownstreamServiceNo ?? string.Empty).Contains(keyword)); + query = query.Where(o => + o.ServiceNo.Contains(keyword) + || (o.ClientNo ?? string.Empty).Contains(keyword) + || (o.TrackNo ?? string.Empty).Contains(keyword) + || (o.DownstreamServiceNo ?? string.Empty).Contains(keyword) + || SqlFunc.Subqueryable() + .Where(b => b.OrderId == o.Id + && !b.IsDeleted + && (b.Status == OrderStockBindStatusCodes.Bound + || b.Status == OrderStockBindStatusCodes.Deducted) + && b.TrackingNo != null + && b.TrackingNo.Contains(keyword)) + .Any()); + } + + if (filter.WarehouseId is > 0) + { + var warehouseId = filter.WarehouseId.Value; + query = query.Where(o => + o.WarehouseId == warehouseId + || SqlFunc.Subqueryable() + .Where(b => b.OrderId == o.Id + && !b.IsDeleted + && b.WarehouseId == warehouseId + && (b.Status == OrderStockBindStatusCodes.Bound + || b.Status == OrderStockBindStatusCodes.Deducted)) + .Any()); } if (filter.CreateTimeStart.HasValue) @@ -95,6 +120,27 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I query = query.Where(x => x.OrderSource == orderSource); } + var fulfillmentType = filter.FulfillmentType?.Trim(); + if (!string.IsNullOrWhiteSpace(fulfillmentType) + && !string.Equals(fulfillmentType, "all", StringComparison.OrdinalIgnoreCase)) + { + query = query.Where(x => x.FulfillmentType == fulfillmentType); + } + + var stockBindStatus = filter.StockBindStatus?.Trim(); + if (!string.IsNullOrWhiteSpace(stockBindStatus) + && !string.Equals(stockBindStatus, "all", StringComparison.OrdinalIgnoreCase)) + { + query = ApplyStockBindStatusFilter(query, stockBindStatus); + } + + var fulfillProgress = filter.FulfillProgress?.Trim(); + if (!string.IsNullOrWhiteSpace(fulfillProgress) + && !string.Equals(fulfillProgress, "all", StringComparison.OrdinalIgnoreCase)) + { + query = ApplyFulfillProgressFilter(query, fulfillProgress); + } + query = ApplyFieldFilters(query, filter.FieldFilters); query = OrderListScopeFilterApplier.Apply(query, filter); @@ -102,6 +148,96 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I return query; } + private static ISugarQueryable ApplyStockBindStatusFilter( + ISugarQueryable query, + string stockBindStatus) + { + if (string.Equals(stockBindStatus, OrderStockBindStatusCodes.Bound, StringComparison.OrdinalIgnoreCase)) + { + return query.Where(o => + SqlFunc.Subqueryable() + .Where(b => b.OrderId == o.Id && !b.IsDeleted && b.Status == OrderStockBindStatusCodes.Bound) + .Any() + && !SqlFunc.Subqueryable() + .Where(b => b.OrderId == o.Id && !b.IsDeleted && b.Status == OrderStockBindStatusCodes.Deducted) + .Any()); + } + + if (string.Equals(stockBindStatus, OrderStockBindStatusCodes.Deducted, StringComparison.OrdinalIgnoreCase)) + { + return query.Where(o => + SqlFunc.Subqueryable() + .Where(b => b.OrderId == o.Id && !b.IsDeleted && b.Status == OrderStockBindStatusCodes.Deducted) + .Any()); + } + + if (string.Equals(stockBindStatus, "none", StringComparison.OrdinalIgnoreCase)) + { + return query.Where(o => + !SqlFunc.Subqueryable() + .Where(b => b.OrderId == o.Id && !b.IsDeleted + && (b.Status == OrderStockBindStatusCodes.Bound || b.Status == OrderStockBindStatusCodes.Deducted)) + .Any()); + } + + return query; + } + + private static ISugarQueryable ApplyFulfillProgressFilter( + ISugarQueryable query, + string fulfillProgress) + { + if (string.Equals(fulfillProgress, FulfillmentProgressCodes.PendingBind, StringComparison.OrdinalIgnoreCase)) + { + return query.Where(o => + (o.FulfillmentType ?? FulfillmentTypeCodes.Direct) == FulfillmentTypeCodes.Warehouse + && !SqlFunc.Subqueryable() + .Where(b => b.OrderId == o.Id + && !b.IsDeleted + && (b.Status == OrderStockBindStatusCodes.Bound + || b.Status == OrderStockBindStatusCodes.Deducted)) + .Any()); + } + + if (string.Equals(fulfillProgress, FulfillmentProgressCodes.OutboundDone, StringComparison.OrdinalIgnoreCase)) + { + return query.Where(o => + SqlFunc.Subqueryable() + .Where(b => b.OrderId == o.Id + && !b.IsDeleted + && b.Status == OrderStockBindStatusCodes.Deducted) + .Any()); + } + + if (string.Equals(fulfillProgress, FulfillmentProgressCodes.DomesticInTransit, StringComparison.OrdinalIgnoreCase)) + { + return ApplyStockBindStatusFilter(query, OrderStockBindStatusCodes.Bound).Where(o => + (o.FulfillmentType ?? FulfillmentTypeCodes.Direct) == FulfillmentTypeCodes.Warehouse + && SqlFunc.Subqueryable() + .InnerJoin((b, p) => b.ParcelId == p.Id) + .Where((b, p) => b.OrderId == o.Id + && !b.IsDeleted + && b.Status == OrderStockBindStatusCodes.Bound + && p.LifecycleStatus == WarehouseParcelLifecycleCodes.InTransit) + .Any()); + } + + if (string.Equals(fulfillProgress, FulfillmentProgressCodes.ArrivedPendingPick, StringComparison.OrdinalIgnoreCase)) + { + return ApplyStockBindStatusFilter(query, OrderStockBindStatusCodes.Bound).Where(o => + (o.FulfillmentType ?? FulfillmentTypeCodes.Direct) == FulfillmentTypeCodes.Warehouse + && !SqlFunc.Subqueryable() + .InnerJoin((b, p) => b.ParcelId == p.Id) + .Where((b, p) => b.OrderId == o.Id + && !b.IsDeleted + && b.Status == OrderStockBindStatusCodes.Bound + && p.LifecycleStatus == WarehouseParcelLifecycleCodes.InTransit) + .Any()); + } + + return query; + } + private static ISugarQueryable ApplyListSort( ISugarQueryable query, OrderListFilter filter) @@ -157,6 +293,26 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I { query = query.OrderBy(x => x.SignTime, orderType); } + else if (string.Equals(field, "primaryBinCode", StringComparison.OrdinalIgnoreCase)) + { + query = query.OrderBy(o => + SqlFunc.Subqueryable() + .InnerJoin((b, bin) => b.BinLocationId == bin.Id) + .Where((b, bin) => b.OrderId == o.Id + && !b.IsDeleted + && b.Status == OrderStockBindStatusCodes.Bound) + .Min((b, bin) => bin.BinCode), + orderType); + query = query.OrderBy(o => + SqlFunc.Subqueryable() + .Where(b => b.OrderId == o.Id + && !b.IsDeleted + && b.Status == OrderStockBindStatusCodes.Bound + && b.TrackingNo != null + && b.TrackingNo != string.Empty) + .Min(b => b.TrackingNo), + orderType); + } else { query = query.OrderBy(x => x.UpdateTime, OrderByType.Desc); @@ -269,6 +425,17 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I q => q.Where(x => x.OrderSource == null || x.OrderSource == string.Empty), q => q.Where(x => x.OrderSource != null && x.OrderSource != string.Empty)); } + else if (string.Equals(field, "fulfillmentType", StringComparison.OrdinalIgnoreCase)) + { + query = ApplyStringField(query, op, value, values, + (q, v) => q.Where(x => (x.FulfillmentType ?? FulfillmentTypeCodes.Direct).Contains(v)), + (q, v) => q.Where(x => x.FulfillmentType == v), + (q, v) => q.Where(x => x.FulfillmentType != v), + (q, list) => q.Where(x => x.FulfillmentType != null && list.Contains(x.FulfillmentType)), + (q, list) => q.Where(x => x.FulfillmentType == null || !list.Contains(x.FulfillmentType)), + q => q.Where(x => x.FulfillmentType == null || x.FulfillmentType == string.Empty), + q => q.Where(x => x.FulfillmentType != null && x.FulfillmentType != string.Empty)); + } else if (string.Equals(field, "predeclareFailReason", StringComparison.OrdinalIgnoreCase)) { query = ApplyStringField(query, op, value, values, @@ -922,8 +1089,81 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I CancellationToken cancellationToken = default) { var db = await GetDbContextAsync(cancellationToken); - var orderIdsQuery = ApplyListFilter(db.Queryable(), filter).Select(x => x.Id); + var feeQuery = await BuildReceivablePayableFeeQueryAsync(db, filter, cancellationToken); + var total = await feeQuery.CountAsync(cancellationToken); + var fees = await feeQuery + .OrderBy(fee => fee.CreateTime, OrderByType.Desc) + .OrderBy(fee => fee.Id, OrderByType.Desc) + .ToPageListAsync(pageIndex, pageSize, cancellationToken); + + return (await MapReceivablePayableRowsAsync(db, fees, cancellationToken), total); + } + + public async Task> GetReceivablePayableSummaryAsync( + OrderReceivablePayableFilter filter, + CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + var feeQuery = await BuildReceivablePayableFeeQueryAsync(db, filter, cancellationToken); + + return await feeQuery + .GroupBy(fee => new { fee.Type, fee.Currency }) + .Select(g => new OrderReceivablePayableSummaryRow + { + FeeType = g.Type, + Currency = g.Currency, + TotalAmount = SqlFunc.AggregateSum(g.Amount), + LineCount = SqlFunc.AggregateCount(g.Id) + }) + .ToListAsync(cancellationToken); + } + + public async Task> GetReceivablePayableExportListAsync( + OrderReceivablePayableFilter filter, + int maxRows, + CancellationToken cancellationToken = default) + { + if (maxRows <= 0) + { + return []; + } + + var db = await GetDbContextAsync(cancellationToken); + var feeQuery = await BuildReceivablePayableFeeQueryAsync(db, filter, cancellationToken); + var fees = await feeQuery + .OrderBy(fee => fee.CreateTime, OrderByType.Desc) + .OrderBy(fee => fee.Id, OrderByType.Desc) + .Take(maxRows) + .ToListAsync(cancellationToken); + + return await MapReceivablePayableRowsAsync(db, fees, cancellationToken); + } + + private static async Task> BuildReceivablePayableFeeQueryAsync( + ISqlSugarClient db, + OrderReceivablePayableFilter filter, + CancellationToken cancellationToken = default) + { + var orderQuery = ApplyListFilter(db.Queryable(), filter); + var customerCode = filter.CustomerCode?.Trim(); + if (!string.IsNullOrWhiteSpace(customerCode)) + { + orderQuery = orderQuery.Where(o => + SqlFunc.Subqueryable() + .Where(c => c.Id == o.CustomerId && c.CustomerCode.Contains(customerCode)) + .Any()); + } + + orderQuery = ApplyReceivablePayableTimeFilter(orderQuery, filter); + + if (filter.IsPaid is 0 or 1) + { + var paidFlag = (byte)filter.IsPaid.Value; + orderQuery = orderQuery.Where(o => o.IsPaid == paidFlag); + } + + var orderIdsQuery = orderQuery.Select(x => x.Id); var feeQuery = db.Queryable() .Where(fee => !fee.IsDeleted) .In(fee => fee.OrderId, orderIdsQuery); @@ -938,7 +1178,7 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I var costItem = filter.CostItem?.Trim(); if (!string.IsNullOrWhiteSpace(costItem)) { - feeQuery = feeQuery.Where(fee => fee.CostItem.Contains(costItem)); + feeQuery = feeQuery.Where(fee => fee.CostItem == costItem || fee.CostItem.Contains(costItem)); } var chargingStage = filter.ChargingStage?.Trim(); @@ -948,15 +1188,85 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I feeQuery = feeQuery.Where(fee => fee.ChargingStage == chargingStage); } - var total = await feeQuery.CountAsync(cancellationToken); - var fees = await feeQuery - .OrderBy(fee => fee.CreateTime, OrderByType.Desc) - .OrderBy(fee => fee.Id, OrderByType.Desc) - .ToPageListAsync(pageIndex, pageSize, cancellationToken); + if (!filter.EffectiveStageOnly) + { + return feeQuery; + } + var candidates = await feeQuery + .Select(f => new { f.Id, f.OrderId, f.Type, f.CostItem, f.ChargingStage }) + .ToListAsync(cancellationToken); + if (candidates.Count == 0) + { + return feeQuery.Where(_ => false); + } + + var winningIds = candidates + .GroupBy(f => (f.OrderId, f.Type, f.CostItem)) + .Select(g => g + .OrderByDescending(f => GetChargingStageRank(f.ChargingStage)) + .ThenByDescending(f => f.Id) + .First() + .Id) + .ToArray(); + + return feeQuery.Where(f => winningIds.Contains(f.Id)); + } + + private static int GetChargingStageRank(string? stage) => + stage switch + { + OrderFeeChargingStageCodes.Outbound => 3, + OrderFeeChargingStageCodes.Inbound => 2, + OrderFeeChargingStageCodes.Forecast => 1, + _ => 0 + }; + + private static ISugarQueryable ApplyReceivablePayableTimeFilter( + ISugarQueryable query, + OrderReceivablePayableFilter filter) + { + var timeField = filter.TimeField?.Trim(); + if (string.IsNullOrWhiteSpace(timeField) || string.Equals(timeField, "createTime", StringComparison.OrdinalIgnoreCase)) + { + return query; + } + + if (filter.TimeStart.HasValue) + { + var start = filter.TimeStart.Value; + query = timeField switch + { + "receiveTime" => query.Where(o => o.ReceiveTime != null && o.ReceiveTime >= start), + "shipTime" => query.Where(o => o.ShipTime != null && o.ShipTime >= start), + "payTime" => query.Where(o => o.PayTime != null && o.PayTime >= start), + _ => query + }; + } + + if (filter.TimeEnd.HasValue) + { + var end = filter.TimeEnd.Value; + query = timeField switch + { + "receiveTime" => query.Where(o => o.ReceiveTime != null && o.ReceiveTime <= end), + "shipTime" => query.Where(o => o.ShipTime != null && o.ShipTime <= end), + "payTime" => query.Where(o => o.PayTime != null && o.PayTime <= end), + _ => query + }; + } + + return query; + } + + private static async Task> MapReceivablePayableRowsAsync( + ISqlSugarClient db, + List fees, + CancellationToken cancellationToken) + { if (fees.Count == 0) { - return ([], total); + return []; } var orderIds = fees.Select(x => x.OrderId).Distinct().ToArray(); @@ -965,7 +1275,7 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I .ToListAsync(cancellationToken); var orderMap = orders.ToDictionary(x => x.Id); - var items = fees + return fees .Where(fee => orderMap.ContainsKey(fee.OrderId)) .Select(fee => new OrderReceivablePayableRow { @@ -973,8 +1283,6 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I Order = orderMap[fee.OrderId] }) .ToList(); - - return (items, total); } public async Task> GetStatusCountsAsync(int? customerId, CancellationToken cancellationToken = default) @@ -1046,6 +1354,56 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I return result; } + public async Task> GetFulfillProgressCountsByFilterAsync( + OrderListFilter filter, + CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + var baseFilter = new OrderListFilter + { + Keyword = filter.Keyword, + CreateTimeStart = filter.CreateTimeStart, + CreateTimeEnd = filter.CreateTimeEnd, + CustomerId = filter.CustomerId, + WarehouseId = filter.WarehouseId, + FulfillmentType = filter.FulfillmentType, + StockBindStatus = filter.StockBindStatus, + OrderSource = filter.OrderSource, + FieldFilters = filter.FieldFilters, + SortField = filter.SortField, + SortOrder = filter.SortOrder, + ScopeOrganizationIds = filter.ScopeOrganizationIds, + ScopeSecretLevels = filter.ScopeSecretLevels, + ScopeDataScope = filter.ScopeDataScope, + ScopePersonalOwnerMapId = filter.ScopePersonalOwnerMapId, + ScopePersonalOwnerAccount = filter.ScopePersonalOwnerAccount, + ScopeOwnerMapIds = filter.ScopeOwnerMapIds, + ScopeBizFilters = filter.ScopeBizFilters, + ScopeCustomFilters = filter.ScopeCustomFilters, + }; + + async Task CountAsync(string? fulfillProgress) + { + var query = ApplyListFilter(db.Queryable(), baseFilter); + if (!string.IsNullOrWhiteSpace(fulfillProgress)) + { + query = ApplyFulfillProgressFilter(query, fulfillProgress); + } + + return await query.CountAsync(cancellationToken); + } + + var result = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["all"] = await CountAsync(null), + [FulfillmentProgressCodes.PendingBind] = await CountAsync(FulfillmentProgressCodes.PendingBind), + [FulfillmentProgressCodes.DomesticInTransit] = await CountAsync(FulfillmentProgressCodes.DomesticInTransit), + [FulfillmentProgressCodes.ArrivedPendingPick] = await CountAsync(FulfillmentProgressCodes.ArrivedPendingPick), + [FulfillmentProgressCodes.OutboundDone] = await CountAsync(FulfillmentProgressCodes.OutboundDone), + }; + return result; + } + public async Task CountByFilterAndCreateTimeRangeAsync( OrderListFilter filter, DateTime startInclusive, @@ -1074,6 +1432,21 @@ public class OrderRepository : OmsSqlSugarRepository, IOrderRepository, I return await query.CountAsync(cancellationToken); } + public async Task SumPayableAmountByCreateTimeRangeAsync( + OrderListFilter filter, + DateTime startInclusive, + DateTime endExclusive, + CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + var query = ApplyListFilter(db.Queryable(), filter) + .Where(x => x.CreateTime >= startInclusive && x.CreateTime < endExclusive) + .Where(x => x.OrderStatus != OrderStatusCodes.Deleted) + .Where(x => x.PayableAmount != null); + + return await query.SumAsync(x => x.PayableAmount!.Value); + } + public async Task SumFeeAmountByPayTimeRangeAsync( OrderListFilter filter, string feeType, diff --git a/src/Oms.SqlSugarCore/Orders/PickupOrderRepository.cs b/src/Oms.SqlSugarCore/Orders/PickupOrderRepository.cs new file mode 100644 index 0000000..a898e0b --- /dev/null +++ b/src/Oms.SqlSugarCore/Orders/PickupOrderRepository.cs @@ -0,0 +1,120 @@ +using Fake.DependencyInjection; +using Oms.Domain.OrdersAggregate.Consts; +using Oms.Domain.OrdersAggregate.Entities; +using Oms.Domain.OrdersAggregate.Repositories; +using Oms.SqlSugarCore.Repositories; + +namespace Oms.SqlSugarCore.Orders; + +public class PickupOrderRepository : OmsSqlSugarRepository, IPickupOrderRepository, IScopedDependency +{ + public Task GetByPickupNoAsync(string pickupNo, CancellationToken cancellationToken = default) + { + var no = pickupNo.Trim(); + return FirstOrDefaultAsync(x => x.PickupNo == no, cancellationToken); + } + + public Task GetOwnedAsync(int id, int customerId, CancellationToken cancellationToken = default) + { + return FirstOrDefaultAsync(x => x.Id == id && x.CustomerId == customerId, cancellationToken); + } + + public async Task GetWorkplaceCountsAsync( + int? customerId, + CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + var query = db.Queryable(); + if (customerId is > 0) + { + query = query.Where(x => x.CustomerId == customerId.Value); + } + + var terminal = new[] { PickupOrderStatusCodes.Cancelled, PickupOrderStatusCodes.Failed }; + + var pendingPayment = await query + .Where(x => !terminal.Contains(x.Status)) + .Where(x => x.PayStatus != PickupPayStatusCodes.Paid) + .Where(x => x.ReceivableAmount != null && x.ReceivableAmount > 0) + .CountAsync(cancellationToken); + + var pendingSchedule = await query + .Where(x => x.Status == PickupOrderStatusCodes.Draft) + .CountAsync(cancellationToken); + + var pendingPickup = await query + .Where(x => x.Status == PickupOrderStatusCodes.Scheduled || x.Status == PickupOrderStatusCodes.Dispatched) + .CountAsync(cancellationToken); + + var pendingInbound = await query + .Where(x => x.Status == PickupOrderStatusCodes.Picked) + .CountAsync(cancellationToken); + + return new PickupWorkplaceCountRow + { + PendingPayment = pendingPayment, + PendingSchedule = pendingSchedule, + PendingPickup = pendingPickup, + PendingInbound = pendingInbound, + }; + } + + public async Task CountByCreateTimeRangeAsync( + int? customerId, + DateTime startInclusive, + DateTime endExclusive, + CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + var query = db.Queryable() + .Where(x => x.CreateTime >= startInclusive && x.CreateTime < endExclusive); + if (customerId is > 0) + { + query = query.Where(x => x.CustomerId == customerId.Value); + } + + return await query.CountAsync(cancellationToken); + } +} + +public class PickupOrderLineRepository : OmsSqlSugarRepository, IPickupOrderLineRepository, IScopedDependency +{ + public Task> GetByPickupOrderIdAsync(int pickupOrderId, CancellationToken cancellationToken = default) + { + return GetListAsync(x => x.PickupOrderId == pickupOrderId, cancellationToken: cancellationToken); + } + + public Task GetActiveByOrderIdAsync(int orderId, CancellationToken cancellationToken = default) + { + return FirstOrDefaultAsync(x => x.OrderId == orderId, cancellationToken); + } + + public async Task> GetActiveByOrderIdsAsync( + IReadOnlyCollection orderIds, + CancellationToken cancellationToken = default) + { + if (orderIds == null || orderIds.Count == 0) + { + return []; + } + + var ids = orderIds.Distinct().ToList(); + return await GetListAsync(x => ids.Contains(x.OrderId), cancellationToken: cancellationToken); + } + + public async Task HardDeleteByPickupOrderIdAsync(int pickupOrderId, CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + await db.Deleteable() + .Where(x => x.PickupOrderId == pickupOrderId) + .ExecuteCommandAsync(cancellationToken); + } + + public async Task HardDeleteAsync(PickupOrderLine line, CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + await db.Deleteable() + .Where(x => x.Id == line.Id) + .ExecuteCommandAsync(cancellationToken); + } +} diff --git a/src/Oms.SqlSugarCore/Xhs/XhsRepositories.cs b/src/Oms.SqlSugarCore/Xhs/XhsRepositories.cs index ab355c9..d833163 100644 --- a/src/Oms.SqlSugarCore/Xhs/XhsRepositories.cs +++ b/src/Oms.SqlSugarCore/Xhs/XhsRepositories.cs @@ -162,14 +162,4 @@ public class XhsHumanConfigRepository FirstOrDefaultAsync(x => x.CustomerId == customerId, cancellationToken); } -public class XhsAiProviderRepository - : OmsSqlSugarRepository, IXhsAiProviderRepository, IScopedDependency -{ - public Task GetByProviderKeyAsync( - int customerId, - string providerKey, - CancellationToken cancellationToken = default) => - FirstOrDefaultAsync(x => x.CustomerId == customerId && x.ProviderKey == providerKey, cancellationToken); -} - public class XhsMediaRepository : OmsSqlSugarRepository, IXhsMediaRepository, IScopedDependency; diff --git a/src/Oms.Tests/ParcelBillingCalculatorTests.cs b/src/Oms.Tests/ParcelBillingCalculatorTests.cs index 66add3a..91b621d 100644 --- a/src/Oms.Tests/ParcelBillingCalculatorTests.cs +++ b/src/Oms.Tests/ParcelBillingCalculatorTests.cs @@ -2,6 +2,7 @@ using FluentAssertions; using Oms.Application.Dtos.Channels; using Oms.Application.Dtos.Orders; using Oms.Application.Services.Orders; +using Oms.Application.Services.Orders.Issues; using Oms.Domain.CustomersAggregate.Enums; using Oms.Domain.OrdersAggregate.Consts; using Oms.Domain.OrdersAggregate.Entities; @@ -351,4 +352,268 @@ public class ParcelBillingCalculatorTests } #endregion + + #region 计费条件 / 申报比例 / 去重 + + [Fact] + public void CalculateReceivableFees_BillingCondition_ShouldSkipWhenAdditionalServiceMissing() + { + var snapshot = ParcelBillingTestData.BuildReceivableSnapshot( + ParcelBillingTestData.ReceivablePriceItem( + 1, + "insurance", + serialNumber: 1, + chargingCondition: "附加服务包含('insurance')", + ParcelBillingTestData.FixedPriceDetail(20M))); + + var context = OrderRuleEvaluationContext.FromOrderOnly(new Order + { + AdditionalServices = """["remoteFee"]""" + }); + + var fees = ParcelBillingCalculator.CalculateReceivableFees( + snapshot, + _meta.PriceVersion, + _meta.EffectiveTime, + 1.2M, + new[] { Zone }, + "general", + null, + OrderFeeChargingStageCodes.Forecast, + conditionContext: context); + + fees.Should().BeEmpty(); + } + + [Fact] + public void CalculateReceivableFees_BillingCondition_ShouldHitWhenAdditionalServiceSelected() + { + var snapshot = ParcelBillingTestData.BuildReceivableSnapshot( + ParcelBillingTestData.ReceivablePriceItem( + 1, + "insurance", + serialNumber: 1, + chargingCondition: "附加服务包含('insurance')", + ParcelBillingTestData.FixedPriceDetail(20M))); + + var context = OrderRuleEvaluationContext.FromOrderOnly(new Order + { + AdditionalServices = """["insurance"]""" + }); + + var fees = ParcelBillingCalculator.CalculateReceivableFees( + snapshot, + _meta.PriceVersion, + _meta.EffectiveTime, + 1.2M, + new[] { Zone }, + "general", + null, + OrderFeeChargingStageCodes.Forecast, + conditionContext: context); + + fees.Should().ContainSingle(); + fees[0].CostItem.Should().Be("insurance"); + fees[0].Amount.Should().Be(20M); + } + + [Fact] + public void CalculateReceivableFees_PercentDeclared_ShouldRoundToTwoDecimals() + { + var snapshot = ParcelBillingTestData.BuildReceivableSnapshot( + ParcelBillingTestData.ReceivablePriceItem( + 1, + "insurance", + ParcelBillingTestData.PercentDeclaredDetail(1.5M))); + + var fees = ParcelBillingCalculator.CalculateReceivableFees( + snapshot, + _meta.PriceVersion, + _meta.EffectiveTime, + 0M, + new[] { Zone }, + "general", + null, + OrderFeeChargingStageCodes.Forecast, + declaredSum: 1000M, + declaredCurrency: "CNY"); + + fees.Should().ContainSingle(); + fees[0].Amount.Should().Be(15M); + } + + [Fact] + public void CalculateReceivableFees_PercentFreight_ShouldUseSameBatchFreightBase() + { + var snapshot = ParcelBillingTestData.BuildReceivableSnapshot( + ParcelBillingTestData.ReceivablePriceItem( + 1, + "freight", + ParcelBillingTestData.FixedPriceDetail(100M)), + ParcelBillingTestData.ReceivablePriceItem( + 1, + "fuel", + ParcelBillingTestData.PercentFreightDetail(10M))); + + var fees = ParcelBillingCalculator.CalculateReceivableFees( + snapshot, + _meta.PriceVersion, + _meta.EffectiveTime, + 1.2M, + new[] { Zone }, + "general", + null, + OrderFeeChargingStageCodes.Forecast); + + fees.Should().HaveCount(2); + fees.Should().Contain(x => x.CostItem == "freight" && x.Amount == 100M); + fees.Should().Contain(x => x.CostItem == "fuel" && x.Amount == 10M); + } + + [Fact] + public void CalculateReceivableFees_PercentFreight_ShouldSkipWhenNoFreightInBatch() + { + var snapshot = ParcelBillingTestData.BuildReceivableSnapshot( + ParcelBillingTestData.ReceivablePriceItem( + 1, + "fuel", + ParcelBillingTestData.PercentFreightDetail(10M))); + + var fees = ParcelBillingCalculator.CalculateReceivableFees( + snapshot, + _meta.PriceVersion, + _meta.EffectiveTime, + 1.2M, + new[] { Zone }, + "general", + null, + OrderFeeChargingStageCodes.Forecast); + + fees.Should().BeEmpty(); + } + + [Fact] + public void CalculatePayableFees_PercentFreight_ShouldUseSameBatchFreightBase() + { + var payablePrices = ParcelBillingTestData.BuildPayablePrices( + ParcelBillingTestData.PayablePriceItem( + 1, + "freight", + ParcelBillingTestData.FixedPriceDetail(80M)), + ParcelBillingTestData.PayablePriceItem( + 1, + "fuel", + ParcelBillingTestData.PercentFreightDetail(5M))); + + var fees = ParcelBillingCalculator.CalculatePayableFees( + payablePrices, + _meta.PriceVersion, + _meta.EffectiveTime, + 1.2M, + new[] { Zone }, + "general", + OrderFeeChargingStageCodes.Forecast); + + fees.Should().HaveCount(2); + fees.Should().Contain(x => x.CostItem == "freight" && x.Amount == 80M); + fees.Should().Contain(x => x.CostItem == "fuel" && x.Amount == 4M); + } + + [Fact] + public void NormalizeCalculationFormula_ShouldAliasPercentFreight() + { + ParcelBillingCalculator.NormalizeCalculationFormula("运费比例").Should().Be("percent_freight"); + ParcelBillingCalculator.NormalizeCalculationFormula("percentFreight").Should().Be("percent_freight"); + } + + [Fact] + public void CalculateReceivableFees_ShouldDedupeCostItemBySmallestSerialNumber() + { + var snapshot = ParcelBillingTestData.BuildReceivableSnapshot( + ParcelBillingTestData.ReceivablePriceItem( + 1, + "freight", + serialNumber: 20, + chargingCondition: null, + ParcelBillingTestData.FixedPriceDetail(99M)), + ParcelBillingTestData.ReceivablePriceItem( + 1, + "freight", + serialNumber: 5, + chargingCondition: null, + ParcelBillingTestData.FixedPriceDetail(12M))); + + var fees = ParcelBillingCalculator.CalculateReceivableFees( + snapshot, + _meta.PriceVersion, + _meta.EffectiveTime, + 1.2M, + new[] { Zone }, + "general", + null, + OrderFeeChargingStageCodes.Forecast); + + fees.Should().ContainSingle(); + fees[0].Amount.Should().Be(12M); + } + + [Fact] + public void CalculateReceivableFees_AllCustomerColumn_ShouldApplyToAnyPriceTierKey() + { + var snapshot = ParcelBillingTestData.BuildReceivableSnapshot( + ParcelBillingTestData.ReceivablePriceItem( + 1, + "freight", + ParcelBillingTestData.AllCustomerTierDetail(Zone, 33M))); + + var fees = ParcelBillingCalculator.CalculateReceivableFees( + snapshot, + _meta.PriceVersion, + _meta.EffectiveTime, + 1.2M, + new[] { Zone }, + "general", + "VIP5", + OrderFeeChargingStageCodes.Forecast); + + fees.Should().ContainSingle(); + fees[0].Amount.Should().Be(33M); + } + + [Fact] + public void CalculateReceivableFees_RemoteZoneFactor_ShouldRequireMatchingRemoteKeys() + { + var snapshot = ParcelBillingTestData.BuildReceivableSnapshot( + ParcelBillingTestData.ReceivablePriceItem( + 1, + "remoteFee", + ParcelBillingTestData.RemoteZoneFixedDetail(15M, Zone, "88"))); + + var miss = ParcelBillingCalculator.CalculateReceivableFees( + snapshot, + _meta.PriceVersion, + _meta.EffectiveTime, + 1.2M, + new[] { Zone }, + "general", + null, + OrderFeeChargingStageCodes.Forecast, + remoteZoneKeys: Array.Empty()); + miss.Should().BeEmpty(); + + var hit = ParcelBillingCalculator.CalculateReceivableFees( + snapshot, + _meta.PriceVersion, + _meta.EffectiveTime, + 1.2M, + new[] { Zone }, + "general", + null, + OrderFeeChargingStageCodes.Forecast, + remoteZoneKeys: ParcelBillingCalculator.BuildRemoteZoneKeys(88)); + hit.Should().ContainSingle(); + hit[0].Amount.Should().Be(15M); + } + + #endregion } diff --git a/src/Oms.Tests/Support/ParcelBillingTestData.cs b/src/Oms.Tests/Support/ParcelBillingTestData.cs index 78ea605..e970796 100644 --- a/src/Oms.Tests/Support/ParcelBillingTestData.cs +++ b/src/Oms.Tests/Support/ParcelBillingTestData.cs @@ -27,11 +27,21 @@ internal static class ParcelBillingTestData byte status, string costItem, params ChannelPriceDetailOutput[] details) => + ReceivablePriceItem(status, costItem, serialNumber: 1, chargingCondition: null, details); + + public static SalesProductPriceListOutput ReceivablePriceItem( + byte status, + string costItem, + int serialNumber, + string? chargingCondition, + params ChannelPriceDetailOutput[] details) => new() { Status = status == 0 ? (byte)0 : (byte)2, + SerialNumber = serialNumber, CostItem = costItem, Currency = "CNY", + ChargingCondition = chargingCondition, Details = details.ToList() }; @@ -47,6 +57,36 @@ internal static class ParcelBillingTestData Details = details.ToList() }; + public static ChannelPriceDetailOutput PercentDeclaredDetail( + decimal rate, + string zone = Zone, + string cargoType = "普货") => + new() + { + CalculationFormula = "percent_declared", + CalculatedValue = rate, + FactorValuesJson = new Dictionary + { + ["分区"] = zone, + ["货物类型"] = cargoType + } + }; + + public static ChannelPriceDetailOutput PercentFreightDetail( + decimal rate, + string zone = Zone, + string cargoType = "普货") => + new() + { + CalculationFormula = "percent_freight", + CalculatedValue = rate, + FactorValuesJson = new Dictionary + { + ["分区"] = zone, + ["货物类型"] = cargoType + } + }; + public static ChannelPriceDetailOutput ContinueFreightDetail( decimal firstWeight = 1M, decimal firstPrice = 18M, @@ -110,6 +150,37 @@ internal static class ParcelBillingTestData CustomerGroupValues = new Dictionary { ["普通客户"] = normalCustomerPrice } }; + public static ChannelPriceDetailOutput AllCustomerTierDetail( + string zone, + decimal allCustomerPrice, + string? weightInterval = null) => + new() + { + CalculationFormula = "total", + CalculatedValue = 0, + FactorValuesJson = new Dictionary + { + ["价格分区"] = zone, + ["重量"] = weightInterval ?? "999" + }, + CustomerGroupValues = new Dictionary { ["全部客户"] = allCustomerPrice } + }; + + public static ChannelPriceDetailOutput RemoteZoneFixedDetail( + decimal amount, + string priceZone, + string remoteZoneId) => + new() + { + CalculationFormula = "固定价", + CalculatedValue = amount, + FactorValuesJson = new Dictionary + { + ["价格分区"] = priceZone, + ["偏远分区"] = remoteZoneId + } + }; + public static WeightRuleInfo GwRule(string condition = "gw>=vw", string factor = "6000") => new() { diff --git a/src/SimpleAdmin.Api/Auth/AuthService.cs b/src/SimpleAdmin.Api/Auth/AuthService.cs index c9bda03..c380ff1 100644 --- a/src/SimpleAdmin.Api/Auth/AuthService.cs +++ b/src/SimpleAdmin.Api/Auth/AuthService.cs @@ -531,12 +531,32 @@ public partial class AuthService( .FirstOrDefaultAsync(cancellationToken); } - var permissions = roles - .SelectMany(x => x.Permissions.Select(p => p.PermissionCode)) - .Where(x => !string.IsNullOrWhiteSpace(x)) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToList(); - var menus = await BuildMenusByPermissionsAsync(permissions, cancellationToken); + var isAdminRole = roles.Any(x => + string.Equals(x.Code, "Admin", StringComparison.OrdinalIgnoreCase)); + + List permissions; + List menus; + if (isAdminRole) + { + // Admin:默认全菜单/全权限码,无需在角色管理里逐项勾选 + var allMenus = await GetAllActiveMenusCachedAsync(cancellationToken); + permissions = allMenus + .Select(x => x.PermissionCode) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(x => x!) + .ToList(); + menus = BuildMenuTree(allMenus); + } + else + { + permissions = roles + .SelectMany(x => x.Permissions.Select(p => p.PermissionCode)) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + menus = await BuildMenusByPermissionsAsync(permissions, cancellationToken); + } var dto = new UserInfoDto { @@ -784,8 +804,12 @@ public partial class AuthService( } } - var menuDtos = allMenus - .Where(x => selectedMenuIds.Contains(x.Id)) + return BuildMenuTree(allMenus.Where(x => selectedMenuIds.Contains(x.Id))); + } + + private static List BuildMenuTree(IEnumerable menus) + { + var menuDtos = menus .OrderBy(x => x.Order) .ThenBy(x => x.CreateTime) .Select(x => new MenuTreeDto diff --git a/src/SimpleAdmin.Api/Auth/XhsRolePermissionSeedContributor.cs b/src/SimpleAdmin.Api/Auth/XhsRolePermissionSeedContributor.cs index 86a4f85..10abc06 100644 --- a/src/SimpleAdmin.Api/Auth/XhsRolePermissionSeedContributor.cs +++ b/src/SimpleAdmin.Api/Auth/XhsRolePermissionSeedContributor.cs @@ -22,8 +22,19 @@ public class XhsRolePermissionSeedContributor(RoleService roleService) : IDataSe "Xhs.Skills.Save", "Xhs.Skills.Run", "Xhs.HumanSettings.Save", - "Xhs.Ai.Use", - "Xhs.Ai.Save" + "System.Ai.Use", + "System.Ai.Save", + "System.AiSkill.Use", + "System.AiSkill.Save" + ]; + + public static readonly string[] AdminKbPermissions = + [ + "Knowledge.Category.Query", + "Knowledge.Category.Edit", + "Knowledge.Article.Query", + "Knowledge.Article.Edit", + "Knowledge.Article.Publish" ]; public async Task SeedAsync() @@ -40,7 +51,7 @@ public class XhsRolePermissionSeedContributor(RoleService roleService) : IDataSe string.Equals(x.Code, AdminRoleCode, StringComparison.OrdinalIgnoreCase)); if (admin != null) { - await MergePermissionsAsync(admin.Id, CustomerPermissions); + await MergePermissionsAsync(admin.Id, CustomerPermissions.Concat(AdminKbPermissions)); } } diff --git a/src/SimpleAdmin.Api/WeChat/Dtos/WeChatDtos.cs b/src/SimpleAdmin.Api/WeChat/Dtos/WeChatDtos.cs index ea4808c..f5c09ba 100644 --- a/src/SimpleAdmin.Api/WeChat/Dtos/WeChatDtos.cs +++ b/src/SimpleAdmin.Api/WeChat/Dtos/WeChatDtos.cs @@ -96,6 +96,11 @@ public class WeChatCustomerRegisterInput /// public string? InviteCode { get; set; } + /// + /// 顾问邀请码(可选)。来自 ?advisor=,值为员工登录账号;注册时写入所属顾问 CustomerService。 + /// + public string? AdvisorCode { get; set; } + [Required] public WeChatProfileInput Wechat { get; set; } = new(); } diff --git a/src/SimpleAdmin.Api/WeChat/WeChatCustomerService.cs b/src/SimpleAdmin.Api/WeChat/WeChatCustomerService.cs index 21f239a..36b5ce9 100644 --- a/src/SimpleAdmin.Api/WeChat/WeChatCustomerService.cs +++ b/src/SimpleAdmin.Api/WeChat/WeChatCustomerService.cs @@ -164,6 +164,11 @@ public class WeChatCustomerService( { entity.ReferralChannel = "wechat"; } + await StaffAdvisorBinder.BindAdvisorOnCreateAsync( + entity, + input.AdvisorCode, + rbacDbContext, + cancellationToken); await customerRepository.InsertAsync(entity); try diff --git a/src/SimpleAdmin.Api/appsettings.Development.json b/src/SimpleAdmin.Api/appsettings.Development.json index a53b3df..f9647a9 100644 --- a/src/SimpleAdmin.Api/appsettings.Development.json +++ b/src/SimpleAdmin.Api/appsettings.Development.json @@ -64,7 +64,10 @@ }, "Itfx": { "BaseUrl": "http://api.nanafa.com/itfx", - "TimeoutSeconds": 30 + "TimeoutSeconds": 30, + "Customs9610StandardCode": "customs9610Declare", + "Customs9610ManifestStandardCode": "customs9610Manifest", + "Customs9610DeclarationFormStandardCode": "customs9610DeclarationForm" }, "PlatformShop": { "FrontendBaseUrl": "http://localhost:5173", diff --git a/tools/SwaggerDiag/Program.cs b/tools/SwaggerDiag/Program.cs new file mode 100644 index 0000000..539c73d --- /dev/null +++ b/tools/SwaggerDiag/Program.cs @@ -0,0 +1,47 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.OpenApi.Models; +using Oms.Application.Dtos.Orders; +using Swashbuckle.AspNetCore.SwaggerGen; +using System.Reflection; + +var services = new ServiceCollection(); +services.AddSwaggerGen(c => +{ + c.SwaggerDoc("OMS-Order", new OpenApiInfo { Title = "OMS-Order", Version = "v1" }); + c.CustomSchemaIds(t => t.FullName?.Replace("+", ".") ?? t.Name); +}); +var sp = services.BuildServiceProvider(); +var gen = sp.GetRequiredService(); +var repo = new SchemaRepository("OMS-Order"); + +void Try(string name, Type t) +{ + try + { + gen.GenerateSchema(t, repo); + Console.WriteLine($"OK {name}"); + } + catch (Exception ex) + { + Console.WriteLine($"FAIL {name}: {ex.GetType().Name}: {ex.Message}"); + if (ex.InnerException != null) Console.WriteLine($" inner: {ex.InnerException.Message}"); + } +} + +Try(nameof(OrderParcelBatchCreateInput), typeof(OrderParcelBatchCreateInput)); +Try(nameof(OrderParcelCreateInput), typeof(OrderParcelCreateInput)); +Try(nameof(OrderPriceCheckResultOutput), typeof(OrderPriceCheckResultOutput)); +Try(nameof(OrderPriceCheckOutput), typeof(OrderPriceCheckOutput)); +Try(nameof(OrderUploadInput), typeof(OrderUploadInput)); +Try(nameof(OrderTemplateCustomDetailOutput), typeof(OrderTemplateCustomDetailOutput)); +Try(nameof(OrderOutput), typeof(OrderOutput)); +Try(nameof(OrderPaginatedOutput), typeof(OrderPaginatedOutput)); + +// Also generate for all public types in Orders Dtos +var asm = typeof(OrderOutput).Assembly; +foreach (var t in asm.GetTypes().Where(x => x.IsPublic && x.Namespace == "Oms.Application.Dtos.Orders").OrderBy(x => x.Name)) +{ + Try(t.Name, t); +} + +Console.WriteLine($"Schemas generated: {repo.Schemas.Count}"); diff --git a/tools/SwaggerDiag/SwaggerDiag.csproj b/tools/SwaggerDiag/SwaggerDiag.csproj new file mode 100644 index 0000000..6617412 --- /dev/null +++ b/tools/SwaggerDiag/SwaggerDiag.csproj @@ -0,0 +1,13 @@ + + + Exe + net8.0 + enable + enable + + + + + + + diff --git a/tools/_chk.py b/tools/_chk.py new file mode 100644 index 0000000..18c6313 --- /dev/null +++ b/tools/_chk.py @@ -0,0 +1,10 @@ +from pathlib import Path +db = Path(r"c:\Users\wilso\Desktop\oms0414-back\db.sql").read_text(encoding="utf-8") +names = [ + "t_member_level", "t_mcp_tool", "t_pickup_order", "t_coupon_template", + "MemberLevelId", "PriceTierKey", "PayableAmount", "ReceivableSubtotal", + "TradeTerms", "AdditionalServices", "AiAnalysisReport", "HandlerNames", +] +for n in names: + needle = f"`{n}`" if not n.startswith("t_") else f"CREATE TABLE `{n}`" + print(n, needle in db or f"`{n}`" in db) diff --git a/tools/_cmp_sql_db.ps1 b/tools/_cmp_sql_db.ps1 new file mode 100644 index 0000000..8066c15 --- /dev/null +++ b/tools/_cmp_sql_db.ps1 @@ -0,0 +1,79 @@ +# Compare sql/*.sql migrations against db.sql +$dbPath = "c:\Users\wilso\Desktop\oms0414-back\db.sql" +$sqlDir = "c:\Users\wilso\Desktop\oms0414-back\sql" +$db = [IO.File]::ReadAllText($dbPath) + +function HasCol([string]$name) { + return $db.Contains("`$name`".Replace('$name', $name)) -or $db.Contains("``$name``") +} + +# simpler: look for `ColName` +function ColInDb([string]$name) { + return $db.IndexOf("`" + $name + "`" ) -ge 0 -or $db.IndexOf("``$name``") -ge 0 +} + +function ColInDb2([string]$name) { + $needle = [char]96 + $name + [char]96 # backtick Col backtick + return $db.Contains($needle) +} + +function TableInDb([string]$name) { + $needle = "CREATE TABLE " + [char]96 + $name + [char]96 + return $db.Contains($needle) +} + +$files = Get-ChildItem "$sqlDir\*.sql" | Where-Object { $_.Name -notmatch 'menu_notes' } | Sort-Object Name +$missing = @() + +foreach ($f in $files) { + $content = [IO.File]::ReadAllText($f.FullName) + $createMatches = [regex]::Matches($content, 'CREATE TABLE(?: IF NOT EXISTS)?\s+`([^`]+)`', 'IgnoreCase') + $addMatches = [regex]::Matches($content, 'ADD COLUMN(?: IF NOT EXISTS)?\s+`([^`]+)`', 'IgnoreCase') + $dropMatches = [regex]::Matches($content, 'DROP COLUMN\s+`([^`]+)`', 'IgnoreCase') + $modMatches = [regex]::Matches($content, 'MODIFY COLUMN\s+`([^`]+)`', 'IgnoreCase') + + $section = @() + foreach ($m in $createMatches) { + $t = $m.Groups[1].Value + if (-not (TableInDb $t)) { + $section += "MISSING TABLE: $t" + $missing += "$($f.Name) -> TABLE $t" + } else { + $section += "OK TABLE: $t" + } + } + foreach ($m in $addMatches) { + $c = $m.Groups[1].Value + if (-not (ColInDb2 $c)) { + $section += "MISSING COL (ADD): $c" + $missing += "$($f.Name) -> ADD $c" + } else { + $section += "OK COL (ADD): $c" + } + } + foreach ($m in $dropMatches) { + $c = $m.Groups[1].Value + if (ColInDb2 $c) { + $section += "STILL IN db (DROP intended): $c" + $missing += "$($f.Name) -> DROP not applied in db.sql: $c" + } else { + $section += "OK DROPPED: $c" + } + } + foreach ($m in $modMatches) { + $c = $m.Groups[1].Value + if (-not (ColInDb2 $c)) { + $section += "MISSING COL (MODIFY): $c" + $missing += "$($f.Name) -> MODIFY $c (col absent)" + } + } + + if ($section.Count -gt 0) { + Write-Output "==== $($f.Name) ====" + $section | ForEach-Object { Write-Output " $_" } + } +} + +Write-Output "" +Write-Output "==== SUMMARY MISSING ====" +if ($missing.Count -eq 0) { Write-Output "(none)" } else { $missing | ForEach-Object { Write-Output $_ } } diff --git a/tools/_cmp_sql_db.py b/tools/_cmp_sql_db.py new file mode 100644 index 0000000..a2beae0 --- /dev/null +++ b/tools/_cmp_sql_db.py @@ -0,0 +1,75 @@ +import re +from pathlib import Path + +db = Path(r"c:\Users\wilso\Desktop\oms0414-back\db.sql").read_text(encoding="utf-8") +sql_dir = Path(r"c:\Users\wilso\Desktop\oms0414-back\sql") +missing = [] + +# Extract CREATE TABLE blocks from db.sql for per-table column checks +table_cols = {} +for m in re.finditer(r"CREATE TABLE `([^`]+)`\s*\((.*?)\)\s*(?:ENGINE|COMMENT|=|;)", db, re.S | re.I): + name = m.group(1) + body = m.group(2) + cols = re.findall(r"`([^`]+)`", body) + # filter index-only mentions roughly: keep all backtick names in body + table_cols[name] = set(cols) + +for f in sorted(sql_dir.glob("*.sql")): + if "menu_notes" in f.name: + continue + text = f.read_text(encoding="utf-8") + creates = re.findall(r"CREATE TABLE(?: IF NOT EXISTS)?\s+`([^`]+)`", text, re.I) + # ALTER TABLE `x` ... ADD COLUMN `c` + alter_adds = re.findall( + r"ALTER TABLE\s+`([^`]+)`[\s\S]*?(?=ALTER TABLE|CREATE TABLE|\Z)", + text, + re.I, + ) + # Better: find each ADD COLUMN with preceding table via scanning + lines_out = [] + for t in creates: + ok = f"CREATE TABLE `{t}`" in db + lines_out.append(("OK" if ok else "MISS", "TABLE", t, None)) + if not ok: + missing.append(f"{f.name}: TABLE `{t}`") + + # Parse ADD COLUMN with associated table + pos = 0 + current_table = None + for m in re.finditer( + r"ALTER TABLE\s+`([^`]+)`|ADD COLUMN(?: IF NOT EXISTS)?\s+`([^`]+)`|DROP COLUMN\s+`([^`]+)`|MODIFY COLUMN\s+`([^`]+)`", + text, + re.I, + ): + if m.group(1): + current_table = m.group(1) + elif m.group(2): + col = m.group(2) + in_db = f"`{col}`" in db + in_table = current_table and col in table_cols.get(current_table, set()) + ok = bool(in_table) if current_table in table_cols else in_db + lines_out.append(("OK" if ok else "MISS", "ADD", col, current_table)) + if not ok: + missing.append(f"{f.name}: ADD `{current_table}`.`{col}`") + elif m.group(3): + col = m.group(3) + still = current_table and col in table_cols.get(current_table, set()) + lines_out.append(("STILL" if still else "OK", "DROP", col, current_table)) + if still: + missing.append(f"{f.name}: DROP `{current_table}`.`{col}` still in db.sql") + elif m.group(4): + col = m.group(4) + ok = current_table and col in table_cols.get(current_table, set()) + # For MODIFY we just check presence; nullability needs manual review + lines_out.append(("OK" if ok else "MISS", "MODIFY", col, current_table)) + if not ok: + missing.append(f"{f.name}: MODIFY `{current_table}`.`{col}` absent") + + if lines_out: + print(f"==== {f.name} ====") + for st, kind, name, tbl in lines_out: + loc = f"{tbl}." if tbl else "" + print(f" [{st}] {kind} {loc}{name}") + +print("\n==== SUMMARY (needs db.sql sync) ====") +print("\n".join(missing) if missing else "(none)")