From b8b18c4f595295fd3a70f2ff9aadb66ad720979c Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Sat, 21 Nov 2026 11:55:34 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=BC=80=E7=A5=A8=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E4=B8=8E=E5=93=81=E7=89=8C/=E6=94=B6=E6=AC=BE=E7=A0=81?= =?UTF-8?q?=E5=90=8C=E6=BA=90=E5=87=BA=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增发票申请/抬头/审批接入,并将品牌 Logo、收款码改为 API 同源文件地址,避免浏览器直连 COS 证书域名失败。 Co-authored-by: Cursor --- db.sql | 79 + sql/migrate_invoice_manage_20261121.sql | 112 ++ .../Dtos/Finance/InvoiceDtos.cs | 445 ++++++ .../Dtos/System/BrandLogoOutput.cs | 8 +- .../Dtos/System/PaymentReceiveQrOutput.cs | 4 +- src/Oms.Application/OmsApplicationModule.cs | 2 + .../Approval/ApprovalOperationCatalog.cs | 6 + .../Finance/InvoiceIssueApprovalHandler.cs | 150 ++ .../Services/Finance/InvoiceService.cs | 1315 +++++++++++++++++ .../System/SystemOtherConfigService.cs | 223 ++- .../ApprovalAggregate/Consts/ApprovalCodes.cs | 3 + .../FinanceAggregate/Consts/InvoiceCodes.cs | 111 ++ .../Entities/CustomerInvoiceProfile.cs | 31 + .../FinanceAggregate/Entities/InvoiceApply.cs | 82 + .../Entities/InvoiceApplyLine.cs | 31 + .../ICustomerInvoiceProfileRepository.cs | 8 + .../IInvoiceApplyLineRepository.cs | 11 + .../Repositories/IInvoiceApplyRepository.cs | 11 + .../CustomerInvoiceProfileRepository.cs | 11 + .../Finance/InvoiceApplyLineRepository.cs | 17 + .../Finance/InvoiceApplyRepository.cs | 20 + 21 files changed, 2654 insertions(+), 26 deletions(-) create mode 100644 sql/migrate_invoice_manage_20261121.sql create mode 100644 src/Oms.Application/Dtos/Finance/InvoiceDtos.cs create mode 100644 src/Oms.Application/Services/Finance/InvoiceIssueApprovalHandler.cs create mode 100644 src/Oms.Application/Services/Finance/InvoiceService.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Consts/InvoiceCodes.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Entities/CustomerInvoiceProfile.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Entities/InvoiceApply.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Entities/InvoiceApplyLine.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Repositories/ICustomerInvoiceProfileRepository.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Repositories/IInvoiceApplyLineRepository.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Repositories/IInvoiceApplyRepository.cs create mode 100644 src/Oms.SqlSugarCore/Finance/CustomerInvoiceProfileRepository.cs create mode 100644 src/Oms.SqlSugarCore/Finance/InvoiceApplyLineRepository.cs create mode 100644 src/Oms.SqlSugarCore/Finance/InvoiceApplyRepository.cs diff --git a/db.sql b/db.sql index 0ab1ce1..6abd3ef 100644 --- a/db.sql +++ b/db.sql @@ -75,6 +75,9 @@ DROP TABLE IF EXISTS `t_employee`; DROP TABLE IF EXISTS `t_dict_type`; DROP TABLE IF EXISTS `t_dict`; DROP TABLE IF EXISTS `t_country`; +DROP TABLE IF EXISTS `t_invoice_apply_line`; +DROP TABLE IF EXISTS `t_invoice_apply`; +DROP TABLE IF EXISTS `t_customer_invoice_profile`; DROP TABLE IF EXISTS `t_recharge_record`; DROP TABLE IF EXISTS `t_customer`; DROP TABLE IF EXISTS `t_label_print_record`; @@ -1141,6 +1144,82 @@ CREATE TABLE `t_recharge_record` ( KEY `idx_rr_audit_time` (`AuditTime`) ) COMMENT='充值记录表'; +CREATE TABLE `t_customer_invoice_profile` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键', + `CustomerId` INT NOT NULL COMMENT '客户 ID', + `TitleName` VARCHAR(128) NOT NULL COMMENT '发票抬头', + `TaxNo` VARCHAR(64) NOT NULL COMMENT '税号', + `AddressPhone` VARCHAR(256) NULL COMMENT '地址电话', + `BankNameAccount` VARCHAR(256) NULL COMMENT '开户行及账号', + `IsDefault` TINYINT NOT NULL DEFAULT 0 COMMENT '是否默认:0-否,1-是', + `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 `ix_inv_profile_customer` (`CustomerId`) +) COMMENT='客户发票抬头'; + +CREATE TABLE `t_invoice_apply` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键', + `ApplyNo` VARCHAR(32) NOT NULL COMMENT '申请单号 INV+yyyyMMdd+序号', + `CustomerId` INT NOT NULL COMMENT '客户 ID', + `InvoiceType` VARCHAR(16) NOT NULL DEFAULT 'normal' COMMENT '发票类型:normal 普票 / special 专票', + `Medium` VARCHAR(16) NOT NULL DEFAULT 'electronic' COMMENT '介质:electronic 电子 / paper 纸质', + `TitleName` VARCHAR(128) NOT NULL COMMENT '发票抬头快照', + `TaxNo` VARCHAR(64) NOT NULL COMMENT '税号快照', + `AddressPhone` VARCHAR(256) NULL COMMENT '地址电话快照', + `BankNameAccount` VARCHAR(256) NULL COMMENT '开户行及账号快照', + `AmountTotal` DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT '价税合计(含税)', + `TaxRate` DECIMAL(8,4) NOT NULL DEFAULT 0.0600 COMMENT '税率备注(含税金额不拆分)', + `Currency` VARCHAR(8) NOT NULL DEFAULT 'CNY' COMMENT '币种', + `Status` VARCHAR(32) NOT NULL DEFAULT 'draft' COMMENT 'draft/pendingApproval/approved/issued/rejected/voided/redFlushed', + `ApplicantSource` VARCHAR(16) NOT NULL DEFAULT 'admin' COMMENT '申请人来源:admin/customer', + `InvoiceCode` VARCHAR(64) NULL COMMENT '发票代码', + `InvoiceNumber` VARCHAR(64) NULL COMMENT '发票号码', + `InvoiceDate` DATETIME NULL COMMENT '开票日期', + `InvoicePdfUrl` VARCHAR(1024) NULL COMMENT '发票 PDF 地址', + `Remark` VARCHAR(512) NULL COMMENT '备注', + `ApprovalInstanceId` INT NULL COMMENT '审批实例 Id', + `ApprovalInstanceNo` VARCHAR(32) NULL COMMENT '审批单号', + `RejectReason` VARCHAR(512) NULL COMMENT '驳回原因', + `IssueTime` DATETIME NULL COMMENT '开票时间', + `IssueBy` VARCHAR(64) 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 `ix_inv_apply_customer` (`CustomerId`), + KEY `ix_inv_apply_no` (`ApplyNo`), + KEY `ix_inv_apply_status` (`Status`) +) COMMENT='发票申请'; + +CREATE TABLE `t_invoice_apply_line` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键', + `InvoiceApplyId` INT NOT NULL COMMENT '发票申请 Id', + `SourceType` VARCHAR(32) NOT NULL COMMENT '来源:parcelOrder/pickupOrder/storageRent', + `SourceId` INT NOT NULL COMMENT '来源单据 Id', + `SourceNo` VARCHAR(64) NOT NULL COMMENT '来源单号', + `Amount` DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT '本行开票金额(含税)', + `Currency` VARCHAR(8) NOT NULL DEFAULT 'CNY' 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`), + KEY `ix_inv_line_apply` (`InvoiceApplyId`), + KEY `ix_inv_line_source` (`SourceType`, `SourceId`) +) COMMENT='发票申请明细'; + CREATE TABLE `t_country` ( `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1', `ChineseName` VARCHAR(128) NOT NULL COMMENT '国家中文名', diff --git a/sql/migrate_invoice_manage_20261121.sql b/sql/migrate_invoice_manage_20261121.sql new file mode 100644 index 0000000..cd26f77 --- /dev/null +++ b/sql/migrate_invoice_manage_20261121.sql @@ -0,0 +1,112 @@ +# migrate_invoice_manage_20261121.sql +# 发票管理:客户抬头 + 开票申请头/行(可重复执行) +# no UNIQUE KEY;单号/占用唯一性在 Application 校验 + +SET NAMES utf8mb4; +SET @db := DATABASE(); + +# t_customer_invoice_profile +SET @tbl := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_customer_invoice_profile' +); +SET @sql := IF( + @tbl = 0, + 'CREATE TABLE `t_customer_invoice_profile` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键'', + `CustomerId` INT NOT NULL COMMENT ''客户 ID'', + `TitleName` VARCHAR(128) NOT NULL COMMENT ''发票抬头'', + `TaxNo` VARCHAR(64) NOT NULL COMMENT ''税号'', + `AddressPhone` VARCHAR(256) NULL COMMENT ''地址电话'', + `BankNameAccount` VARCHAR(256) NULL COMMENT ''开户行及账号'', + `IsDefault` TINYINT NOT NULL DEFAULT 0 COMMENT ''是否默认:0-否,1-是'', + `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 `ix_inv_profile_customer` (`CustomerId`) + ) COMMENT=''客户发票抬头''', + 'SELECT 1' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +# t_invoice_apply +SET @tbl := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_invoice_apply' +); +SET @sql := IF( + @tbl = 0, + 'CREATE TABLE `t_invoice_apply` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键'', + `ApplyNo` VARCHAR(32) NOT NULL COMMENT ''申请单号 INV+yyyyMMdd+序号'', + `CustomerId` INT NOT NULL COMMENT ''客户 ID'', + `InvoiceType` VARCHAR(16) NOT NULL DEFAULT ''normal'' COMMENT ''发票类型:normal 普票 / special 专票'', + `Medium` VARCHAR(16) NOT NULL DEFAULT ''electronic'' COMMENT ''介质:electronic 电子 / paper 纸质'', + `TitleName` VARCHAR(128) NOT NULL COMMENT ''发票抬头快照'', + `TaxNo` VARCHAR(64) NOT NULL COMMENT ''税号快照'', + `AddressPhone` VARCHAR(256) NULL COMMENT ''地址电话快照'', + `BankNameAccount` VARCHAR(256) NULL COMMENT ''开户行及账号快照'', + `AmountTotal` DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT ''价税合计(含税)'', + `TaxRate` DECIMAL(8,4) NOT NULL DEFAULT 0.0600 COMMENT ''税率备注(含税金额不拆分)'', + `Currency` VARCHAR(8) NOT NULL DEFAULT ''CNY'' COMMENT ''币种'', + `Status` VARCHAR(32) NOT NULL DEFAULT ''draft'' COMMENT ''draft/pendingApproval/approved/issued/rejected/voided/redFlushed'', + `ApplicantSource` VARCHAR(16) NOT NULL DEFAULT ''admin'' COMMENT ''申请人来源:admin/customer'', + `InvoiceCode` VARCHAR(64) NULL COMMENT ''发票代码'', + `InvoiceNumber` VARCHAR(64) NULL COMMENT ''发票号码'', + `InvoiceDate` DATETIME NULL COMMENT ''开票日期'', + `InvoicePdfUrl` VARCHAR(1024) NULL COMMENT ''发票 PDF 地址'', + `Remark` VARCHAR(512) NULL COMMENT ''备注'', + `ApprovalInstanceId` INT NULL COMMENT ''审批实例 Id'', + `ApprovalInstanceNo` VARCHAR(32) NULL COMMENT ''审批单号'', + `RejectReason` VARCHAR(512) NULL COMMENT ''驳回原因'', + `IssueTime` DATETIME NULL COMMENT ''开票时间'', + `IssueBy` VARCHAR(64) 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 `ix_inv_apply_customer` (`CustomerId`), + KEY `ix_inv_apply_no` (`ApplyNo`), + KEY `ix_inv_apply_status` (`Status`) + ) COMMENT=''发票申请''', + 'SELECT 1' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +# t_invoice_apply_line +SET @tbl := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_invoice_apply_line' +); +SET @sql := IF( + @tbl = 0, + 'CREATE TABLE `t_invoice_apply_line` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键'', + `InvoiceApplyId` INT NOT NULL COMMENT ''发票申请 Id'', + `SourceType` VARCHAR(32) NOT NULL COMMENT ''来源:parcelOrder/pickupOrder/storageRent'', + `SourceId` INT NOT NULL COMMENT ''来源单据 Id'', + `SourceNo` VARCHAR(64) NOT NULL COMMENT ''来源单号'', + `Amount` DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT ''本行开票金额(含税)'', + `Currency` VARCHAR(8) NOT NULL DEFAULT ''CNY'' 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`), + KEY `ix_inv_line_apply` (`InvoiceApplyId`), + KEY `ix_inv_line_source` (`SourceType`, `SourceId`) + ) COMMENT=''发票申请明细''', + 'SELECT 1' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/src/Oms.Application/Dtos/Finance/InvoiceDtos.cs b/src/Oms.Application/Dtos/Finance/InvoiceDtos.cs new file mode 100644 index 0000000..d1f4174 --- /dev/null +++ b/src/Oms.Application/Dtos/Finance/InvoiceDtos.cs @@ -0,0 +1,445 @@ +namespace Oms.Application.Dtos.Finance; + +/// +/// 发票抬头列表查询。 +/// +public class InvoiceProfileListInput +{ + /// 客户主键;客户登录忽略入参,强制本客户。 + public int? CustomerId { get; set; } +} + +/// +/// 保存发票抬头。 +/// +public class InvoiceProfileSaveInput +{ + /// 主键;空则新增。 + public int? Id { get; set; } + + /// 客户主键(管理端必填)。 + public int? CustomerId { get; set; } + + /// 发票抬头。 + public string TitleName { get; set; } = string.Empty; + + /// 税号。 + public string TaxNo { get; set; } = string.Empty; + + /// 地址电话。 + public string? AddressPhone { get; set; } + + /// 开户行及账号。 + public string? BankNameAccount { get; set; } + + /// 是否默认抬头。 + public bool IsDefault { get; set; } + + /// 备注。 + public string? Remark { get; set; } +} + +/// +/// 发票抬头输出。 +/// +public class InvoiceProfileOutput +{ + /// 主键。 + public int Id { get; set; } + + /// 客户主键。 + public int CustomerId { get; set; } + + /// 发票抬头。 + public string TitleName { get; set; } = string.Empty; + + /// 税号。 + public string TaxNo { get; set; } = string.Empty; + + /// 地址电话。 + public string? AddressPhone { get; set; } + + /// 开户行及账号。 + public string? BankNameAccount { get; set; } + + /// 是否默认抬头。 + public bool IsDefault { get; set; } + + /// 备注。 + public string? Remark { get; set; } + + /// 创建时间。 + public DateTime CreateTime { get; set; } + + /// 更新时间。 + public DateTime? UpdateTime { get; set; } +} + +/// +/// 可开票来源查询。 +/// +public class InvoiceSelectableInput +{ + /// 客户主键(管理端必填)。 + public int? CustomerId { get; set; } + + /// 来源类型:parcelOrder / pickupOrder / storageRent;空则合并三类。 + public string? SourceType { get; set; } + + /// 来源单号关键词。 + public string? Keyword { get; set; } + + /// 页码,从 1 开始。 + public int Page { get; set; } = 1; + + /// 每页条数。 + public int PageSize { get; set; } = 50; +} + +/// +/// 可开票来源行。 +/// +public class InvoiceSelectableItemOutput +{ + /// 来源类型。 + public string SourceType { get; set; } = string.Empty; + + /// 来源类型名称。 + public string SourceTypeName { get; set; } = string.Empty; + + /// 来源单据 Id。 + public int SourceId { get; set; } + + /// 来源单号。 + public string SourceNo { get; set; } = string.Empty; + + /// 来源含税金额。 + public decimal BaseAmount { get; set; } + + /// 已被占用金额(草稿/待审/已审/已开票)。 + public decimal OccupiedAmount { get; set; } + + /// 剩余可开票金额。 + public decimal RemainingAmount { get; set; } + + /// 币种,固定 CNY。 + public string Currency { get; set; } = "CNY"; + + /// 支付时间。 + public DateTime? PaidTime { get; set; } +} + +/// +/// 开票申请明细入参。 +/// +public class InvoiceApplyLineInput +{ + /// 来源类型:parcelOrder / pickupOrder / storageRent。 + public string SourceType { get; set; } = string.Empty; + + /// 来源单据 Id。 + public int SourceId { get; set; } + + /// 本行开票金额(含税,允许小于剩余)。 + public decimal Amount { get; set; } + + /// 行备注。 + public string? Remark { get; set; } +} + +/// +/// 新建开票申请。 +/// +public class InvoiceApplyCreateInput +{ + /// 客户主键(管理端必填)。 + public int? CustomerId { get; set; } + + /// 发票类型:normal / special。 + public string InvoiceType { get; set; } = "normal"; + + /// 介质:electronic / paper。 + public string Medium { get; set; } = "electronic"; + + /// 抬头 Id;有值则快照该抬头。 + public int? ProfileId { get; set; } + + /// 发票抬头(未传 ProfileId 时必填)。 + public string? TitleName { get; set; } + + /// 税号(未传 ProfileId 时必填)。 + public string? TaxNo { get; set; } + + /// 地址电话(专票必填)。 + public string? AddressPhone { get; set; } + + /// 开户行及账号(专票必填)。 + public string? BankNameAccount { get; set; } + + /// 税率备注,默认 0.06。 + public decimal? TaxRate { get; set; } + + /// 备注。 + public string? Remark { get; set; } + + /// 为 true 时创建后立即提交审批。 + public bool Submit { get; set; } + + /// 开票明细。 + public List Lines { get; set; } = []; +} + +/// +/// 更新开票申请(仅草稿)。 +/// +public class InvoiceApplyUpdateInput : InvoiceApplyCreateInput +{ + /// 申请主键。 + public int Id { get; set; } +} + +/// +/// 提交 / 作废等按 Id 操作。 +/// +public class InvoiceApplyIdInput +{ + /// 申请主键。 + public int Id { get; set; } +} + +/// +/// 开票入参(仅已审批)。 +/// +public class InvoiceApplyIssueInput +{ + /// 申请主键。 + public int Id { get; set; } + + /// 发票代码。 + public string? InvoiceCode { get; set; } + + /// 发票号码。 + public string InvoiceNumber { get; set; } = string.Empty; + + /// 开票日期;空则取当前时间。 + public DateTime? InvoiceDate { get; set; } + + /// 发票 PDF 地址。 + public string? InvoicePdfUrl { get; set; } + + /// 备注。 + public string? Remark { get; set; } +} + +/// +/// 作废入参。 +/// +public class InvoiceApplyVoidInput +{ + /// 申请主键。 + public int Id { get; set; } + + /// 作废原因。 + public string? Remark { get; set; } +} + +/// +/// 开票申请分页查询。 +/// +public class InvoiceApplyListInput +{ + /// 页码,从 1 开始。 + public int Page { get; set; } = 1; + + /// 每页条数。 + public int PageSize { get; set; } = 50; + + /// 客户主键。 + public int? CustomerId { get; set; } + + /// 状态。 + public string? Status { get; set; } + + /// 发票类型。 + public string? InvoiceType { get; set; } + + /// 申请单号 / 发票号 / 抬头关键词。 + public string? Keyword { get; set; } + + /// 创建时间起。 + public DateTime? StartTime { get; set; } + + /// 创建时间止。 + public DateTime? EndTime { get; set; } +} + +/// +/// 导出入参。 +/// +public class InvoiceExportInput +{ + /// 客户主键。 + public int? CustomerId { get; set; } + + /// 状态。 + public string? Status { get; set; } + + /// 发票类型。 + public string? InvoiceType { get; set; } + + /// 申请单号 / 发票号 / 抬头关键词。 + public string? Keyword { get; set; } + + /// 创建时间起。 + public DateTime? StartTime { get; set; } + + /// 创建时间止。 + public DateTime? EndTime { get; set; } +} + +/// +/// 开票申请明细输出。 +/// +public class InvoiceApplyLineOutput +{ + /// 明细主键。 + public int Id { get; set; } + + /// 来源类型。 + public string SourceType { get; set; } = string.Empty; + + /// 来源类型名称。 + public string SourceTypeName { get; set; } = string.Empty; + + /// 来源单据 Id。 + public int SourceId { get; set; } + + /// 来源单号。 + public string SourceNo { get; set; } = string.Empty; + + /// 本行含税金额。 + public decimal Amount { get; set; } + + /// 币种。 + public string Currency { get; set; } = "CNY"; + + /// 行备注。 + public string? Remark { get; set; } +} + +/// +/// 开票申请列表行。 +/// +public class InvoiceApplyListOutput +{ + /// 主键。 + public int Id { get; set; } + + /// 申请单号。 + public string ApplyNo { get; set; } = string.Empty; + + /// 客户主键。 + public int CustomerId { get; set; } + + /// 客户编码。 + public string? CustomerCode { get; set; } + + /// 客户名称。 + public string? CustomerName { get; set; } + + /// 发票类型。 + public string InvoiceType { get; set; } = string.Empty; + + /// 发票类型名称。 + public string InvoiceTypeName { get; set; } = string.Empty; + + /// 介质。 + public string Medium { get; set; } = string.Empty; + + /// 介质名称。 + public string MediumName { get; set; } = string.Empty; + + /// 发票抬头。 + public string TitleName { get; set; } = string.Empty; + + /// 税号。 + public string TaxNo { get; set; } = string.Empty; + + /// 价税合计(含税)。 + public decimal AmountTotal { get; set; } + + /// 税率备注。 + public decimal TaxRate { get; set; } + + /// 币种。 + public string Currency { get; set; } = "CNY"; + + /// 状态。 + public string Status { get; set; } = string.Empty; + + /// 状态名称。 + public string StatusName { get; set; } = string.Empty; + + /// 申请人来源。 + public string ApplicantSource { get; set; } = string.Empty; + + /// 发票代码。 + public string? InvoiceCode { get; set; } + + /// 发票号码。 + public string? InvoiceNumber { get; set; } + + /// 开票日期。 + public DateTime? InvoiceDate { get; set; } + + /// 发票 PDF。 + public string? InvoicePdfUrl { get; set; } + + /// 备注。 + public string? Remark { get; set; } + + /// 审批实例 Id。 + public int? ApprovalInstanceId { get; set; } + + /// 审批单号。 + public string? ApprovalInstanceNo { get; set; } + + /// 是否存在在途审批。 + public bool ApprovalPending { get; set; } + + /// 驳回原因。 + public string? RejectReason { get; set; } + + /// 开票时间。 + public DateTime? IssueTime { get; set; } + + /// 开票人。 + public string? IssueBy { get; set; } + + /// 创建时间。 + public DateTime CreateTime { get; set; } + + /// 更新时间。 + public DateTime? UpdateTime { get; set; } +} + +/// +/// 开票申请详情。 +/// +public class InvoiceApplyDetailOutput : InvoiceApplyListOutput +{ + /// 地址电话。 + public string? AddressPhone { get; set; } + + /// 开户行及账号。 + public string? BankNameAccount { get; set; } + + /// 审批门面判定:Bypass / PendingApproval。 + public string? Decision { get; set; } + + /// 提交结果说明。 + public string? Message { get; set; } + + /// 开票明细。 + public List Lines { get; set; } = []; +} diff --git a/src/Oms.Application/Dtos/System/BrandLogoOutput.cs b/src/Oms.Application/Dtos/System/BrandLogoOutput.cs index 6026054..e3fb7c6 100644 --- a/src/Oms.Application/Dtos/System/BrandLogoOutput.cs +++ b/src/Oms.Application/Dtos/System/BrandLogoOutput.cs @@ -6,22 +6,22 @@ namespace Oms.Application.Dtos.System; public class BrandLogoOutput { /// - /// 系统顶栏 Logo 可访问 URL;未配置时为空。 + /// 系统顶栏 Logo 同源 API 地址(/system/other-config/brand-logo/file?...);未配置时为空。 /// public string PortalUrl { get; set; } = string.Empty; /// - /// 官网 Logo 可访问 URL;未配置时为空。 + /// 官网 Logo 同源 API 地址;未配置时为空。 /// public string SiteUrl { get; set; } = string.Empty; /// - /// 网站标签(favicon)可访问 URL;未配置时为空。 + /// 网站标签(favicon)同源 API 地址;未配置时为空。 /// public string FaviconUrl { get; set; } = string.Empty; /// - /// 启动页 / 空态吉祥物可访问 URL;未配置时为空。 + /// 启动页 / 空态吉祥物同源 API 地址;未配置时为空。 /// public string MascotUrl { get; set; } = string.Empty; } diff --git a/src/Oms.Application/Dtos/System/PaymentReceiveQrOutput.cs b/src/Oms.Application/Dtos/System/PaymentReceiveQrOutput.cs index c88e44c..ebf02b4 100644 --- a/src/Oms.Application/Dtos/System/PaymentReceiveQrOutput.cs +++ b/src/Oms.Application/Dtos/System/PaymentReceiveQrOutput.cs @@ -6,12 +6,12 @@ namespace Oms.Application.Dtos.System; public class PaymentReceiveQrOutput { /// - /// 支付宝收款码可访问 URL;未配置时为空。 + /// 支付宝收款码同源 API 地址(/system/other-config/payment-qr/file?...);未配置时为空。 /// public string AlipayUrl { get; set; } = string.Empty; /// - /// 微信收款码可访问 URL;未配置时为空。 + /// 微信收款码同源 API 地址;未配置时为空。 /// public string WechatUrl { get; set; } = string.Empty; } diff --git a/src/Oms.Application/OmsApplicationModule.cs b/src/Oms.Application/OmsApplicationModule.cs index 09bd753..c4c913b 100644 --- a/src/Oms.Application/OmsApplicationModule.cs +++ b/src/Oms.Application/OmsApplicationModule.cs @@ -15,6 +15,7 @@ using Oms.Application.Labeling.Hiprint; using Oms.Application.Services.Approval; using Oms.Application.Services.Approval.Contracts; using Oms.Application.Services.Channels; +using Oms.Application.Services.Finance; using Oms.Application.Services.Recharge; using Oms.Application.Services.Storage; using Oms.Application.Shared; @@ -63,6 +64,7 @@ public class OmsApplicationModule : FakeModule // 否则 Approve 会空跑成 Executed、不落发布/入账。 context.Services.AddTransient(); context.Services.AddTransient(); + context.Services.AddTransient(); context.Services.AddTransient(); context.Services.AddHttpClient(FileStorageService.UrlFetchClientName, client => diff --git a/src/Oms.Application/Services/Approval/ApprovalOperationCatalog.cs b/src/Oms.Application/Services/Approval/ApprovalOperationCatalog.cs index d27b11a..47b63f5 100644 --- a/src/Oms.Application/Services/Approval/ApprovalOperationCatalog.cs +++ b/src/Oms.Application/Services/Approval/ApprovalOperationCatalog.cs @@ -31,6 +31,12 @@ public static class ApprovalOperationCatalog "Finance", SupportsCondition: false, ConditionHint: "已接入提交接口;未配置或未启用不拦截(直接入账),启用后提交审批"), + new( + ApprovalCodes.FinanceInvoiceIssue, + "发票开具", + "Finance", + SupportsCondition: false, + ConditionHint: "已接入提交接口;未配置或未启用不拦截(直接通过),启用后提交审批"), new( "Marketing.Commission.Withdraw", "佣金提现", diff --git a/src/Oms.Application/Services/Finance/InvoiceIssueApprovalHandler.cs b/src/Oms.Application/Services/Finance/InvoiceIssueApprovalHandler.cs new file mode 100644 index 0000000..817b087 --- /dev/null +++ b/src/Oms.Application/Services/Finance/InvoiceIssueApprovalHandler.cs @@ -0,0 +1,150 @@ +using System.Text.Json; +using Fake.Application; +using Fake.DependencyInjection; +using Oms.Application.Services.Approval.Contracts; +using Oms.Domain.ApprovalAggregate.Consts; +using Oms.Domain.FinanceAggregate.Consts; +using Oms.Domain.FinanceAggregate.Entities; +using Oms.Domain.FinanceAggregate.Repositories; + +namespace Oms.Application.Services.Finance; + +/// +/// 发票开具审批:通过后置为已审批待开票;驳回置 rejected;撤回置 draft。 +/// +[ExposeServices(typeof(IApprovalOperationHandler))] +public class InvoiceIssueApprovalHandler( + IInvoiceApplyRepository invoiceApplyRepository) : IApprovalOperationHandler, ITransientDependency +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + public string OperationCode => ApprovalCodes.FinanceInvoiceIssue; + + /// + public async Task ExecuteAsync(ApprovalExecutionContext context, CancellationToken cancellationToken = default) + { + var apply = await GetApplyOrThrowAsync(context, cancellationToken); + if (apply.Status == InvoiceStatusCodes.Approved || apply.Status == InvoiceStatusCodes.Issued) + { + return; + } + + if (apply.Status != InvoiceStatusCodes.PendingApproval) + { + throw new BusinessException("只有待审批的发票申请才能审批通过"); + } + + apply.Status = InvoiceStatusCodes.Approved; + apply.ApprovalInstanceId = context.InstanceId; + apply.ApprovalInstanceNo = context.InstanceNo; + apply.RejectReason = null; + await invoiceApplyRepository.UpdateAsync(apply, cancellationToken); + } + + /// + public async Task OnRejectedAsync( + ApprovalExecutionContext context, + string? comment, + CancellationToken cancellationToken = default) + { + var apply = await TryGetPendingApplyAsync(context, cancellationToken); + if (apply == null) + { + return; + } + + apply.Status = InvoiceStatusCodes.Rejected; + apply.RejectReason = string.IsNullOrWhiteSpace(comment) + ? $"审批驳回 {context.InstanceNo}".Trim() + : comment.Trim(); + apply.ApprovalInstanceId = context.InstanceId; + apply.ApprovalInstanceNo = context.InstanceNo; + await invoiceApplyRepository.UpdateAsync(apply, cancellationToken); + } + + /// + public async Task OnWithdrawnAsync( + ApprovalExecutionContext context, + string? comment, + CancellationToken cancellationToken = default) + { + var apply = await TryGetPendingApplyAsync(context, cancellationToken); + if (apply == null) + { + return; + } + + apply.Status = InvoiceStatusCodes.Draft; + apply.RejectReason = null; + apply.ApprovalInstanceId = context.InstanceId; + apply.ApprovalInstanceNo = context.InstanceNo; + if (!string.IsNullOrWhiteSpace(comment)) + { + apply.Remark = comment.Trim(); + } + + await invoiceApplyRepository.UpdateAsync(apply, cancellationToken); + } + + private async Task GetApplyOrThrowAsync( + ApprovalExecutionContext context, + CancellationToken cancellationToken) + { + var applyId = ResolveApplyId(context); + return await invoiceApplyRepository.FirstOrDefaultAsync(x => x.Id == applyId, cancellationToken) + ?? throw new BusinessException("发票申请不存在"); + } + + private async Task TryGetPendingApplyAsync( + ApprovalExecutionContext context, + CancellationToken cancellationToken) + { + var applyId = ResolveApplyId(context); + var apply = await invoiceApplyRepository.FirstOrDefaultAsync(x => x.Id == applyId, cancellationToken); + if (apply == null || apply.Status != InvoiceStatusCodes.PendingApproval) + { + return null; + } + + return apply; + } + + private static int ResolveApplyId(ApprovalExecutionContext context) + { + if (!string.IsNullOrWhiteSpace(context.PayloadJson)) + { + try + { + var payload = JsonSerializer.Deserialize(context.PayloadJson, JsonOptions); + if (payload is { InvoiceApplyId: > 0 }) + { + return payload.InvoiceApplyId; + } + } + catch + { + // fall through BizKey + } + } + + var bizKey = context.BizKey ?? string.Empty; + var prefix = $"{ApprovalCodes.FinanceInvoiceIssue}:"; + if (bizKey.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) + && int.TryParse(bizKey[prefix.Length..], out var id) + && id > 0) + { + return id; + } + + throw new BusinessException("发票审批载荷缺少申请 Id"); + } + + private sealed class InvoiceIssuePayload + { + public int InvoiceApplyId { get; set; } + } +} diff --git a/src/Oms.Application/Services/Finance/InvoiceService.cs b/src/Oms.Application/Services/Finance/InvoiceService.cs new file mode 100644 index 0000000..0137ff1 --- /dev/null +++ b/src/Oms.Application/Services/Finance/InvoiceService.cs @@ -0,0 +1,1315 @@ +using System.Linq.Expressions; +using Fake.Application; +using Fake.Domain.Exceptions; +using Microsoft.AspNetCore.Mvc; +using MiniExcelLibs; +using Oms.Application.Dtos.Finance; +using Oms.Application.Dtos.Shared; +using Oms.Application.Services.Approval.Contracts; +using Oms.Application.Shared; +using Oms.Domain.ApprovalAggregate.Consts; +using Oms.Domain.ApprovalAggregate.Enums; +using Oms.Domain.ApprovalAggregate.Repositories; +using Oms.Domain.CustomersAggregate.Entities; +using Oms.Domain.CustomersAggregate.Repositories; +using Oms.Domain.FinanceAggregate.Consts; +using Oms.Domain.FinanceAggregate.Entities; +using Oms.Domain.FinanceAggregate.Repositories; +using Oms.Domain.OrdersAggregate.Consts; +using Oms.Domain.OrdersAggregate.Repositories; +using Oms.Domain.WarehouseAggregate.Consts; +using Oms.Domain.WarehouseAggregate.Repositories; + +namespace Oms.Application.Services.Finance; + +/// +/// 发票管理 API(客户/管理端共用,按会话裁剪客户范围)。 +/// +[ApiExplorerSettings(GroupName = "OMS-Finance")] +public class InvoiceService : ApplicationService +{ + private static readonly byte PaidFlag = 1; + private static readonly byte NotRefundedFlag = 0; + + private ICustomerInvoiceProfileRepository ProfileRepository => + LazyServiceProvider.GetRequiredService(); + + private IInvoiceApplyRepository InvoiceApplyRepository => + LazyServiceProvider.GetRequiredService(); + + private IInvoiceApplyLineRepository InvoiceApplyLineRepository => + LazyServiceProvider.GetRequiredService(); + + private ICustomerRepository CustomerRepository => + LazyServiceProvider.GetRequiredService(); + + private IOrderRepository OrderRepository => + LazyServiceProvider.GetRequiredService(); + + private IPickupOrderRepository PickupOrderRepository => + LazyServiceProvider.GetRequiredService(); + + private ICWarehouseRentBillRepository RentBillRepository => + LazyServiceProvider.GetRequiredService(); + + private IApprovalGate ApprovalGate => + LazyServiceProvider.GetRequiredService(); + + private IApprovalInstanceRepository ApprovalInstanceRepository => + LazyServiceProvider.GetRequiredService(); + + /// + /// 查询客户发票抬头列表。 + /// + /// 入参:可选客户 Id。 + /// 抬头列表(默认抬头在前)。 + [HttpGet("/finance/invoice/profile/list")] + public async Task> GetProfileListAsync([FromQuery] InvoiceProfileListInput input) + { + var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( + CustomerRepository, + CurrentUser, + input.CustomerId); + var hasCustomer = customerId is > 0; + var customerIdValue = customerId.GetValueOrDefault(); + var entities = await ProfileRepository.GetListAsync(x => !hasCustomer || x.CustomerId == customerIdValue); + return entities + .OrderByDescending(x => x.IsDefault) + .ThenByDescending(x => x.Id) + .Select(MapProfile) + .ToList(); + } + + /// + /// 新增或更新发票抬头;设为默认时取消同客户其他默认。 + /// + /// 入参:抬头内容。 + /// 保存后的抬头。 + [HttpPost("/finance/invoice/profile/save")] + public async Task SaveProfileAsync(InvoiceProfileSaveInput input) + { + var customer = await OmsSessionHelper.ResolveSessionCustomerAsync( + CustomerRepository, + CurrentUser, + input.CustomerId); + var titleName = RequireText(input.TitleName, "发票抬头不能为空"); + var taxNo = RequireText(input.TaxNo, "税号不能为空"); + var addressPhone = NormalizeOptional(input.AddressPhone); + var bankNameAccount = NormalizeOptional(input.BankNameAccount); + var remark = NormalizeOptional(input.Remark); + + CustomerInvoiceProfile entity; + if (input.Id is > 0) + { + entity = await GetOwnedProfileOrThrowAsync(input.Id.Value, customer.Id); + entity.TitleName = titleName; + entity.TaxNo = taxNo; + entity.AddressPhone = addressPhone; + entity.BankNameAccount = bankNameAccount; + entity.IsDefault = input.IsDefault ? (byte)1 : (byte)0; + entity.Remark = remark; + await ProfileRepository.UpdateAsync(entity); + } + else + { + var existingCount = await ProfileRepository.CountAsync(x => x.CustomerId == customer.Id); + entity = new CustomerInvoiceProfile + { + CustomerId = customer.Id, + TitleName = titleName, + TaxNo = taxNo, + AddressPhone = addressPhone, + BankNameAccount = bankNameAccount, + IsDefault = input.IsDefault || existingCount == 0 ? (byte)1 : (byte)0, + Remark = remark + }; + entity = await ProfileRepository.InsertAsync(entity); + } + + if (entity.IsDefault == 1) + { + await ClearOtherDefaultProfilesAsync(customer.Id, entity.Id); + } + + return MapProfile(entity); + } + + /// + /// 删除发票抬头(软删除)。 + /// + /// 入参:抬头主键。 + [HttpPost("/finance/invoice/profile/delete")] + public async Task DeleteProfileAsync(IdInput input) + { + var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( + CustomerRepository, + CurrentUser, + null); + var entity = await ProfileRepository.FirstOrDefaultAsync(x => x.Id == input.Id) + ?? throw new BusinessException("发票抬头不存在"); + if (customerId is > 0 && entity.CustomerId != customerId.Value) + { + throw new BusinessException("发票抬头不存在"); + } + + var wasDefault = entity.IsDefault == 1; + var ownerId = entity.CustomerId; + await ProfileRepository.DeleteAsync(entity); + if (wasDefault) + { + var next = (await ProfileRepository.GetListAsync(x => x.CustomerId == ownerId)) + .OrderByDescending(x => x.Id) + .FirstOrDefault(); + if (next != null && next.IsDefault != 1) + { + next.IsDefault = 1; + await ProfileRepository.UpdateAsync(next); + } + } + } + + /// + /// 查询可开票来源(已支付运单/揽收/仓租,扣减占用后剩余大于 0,仅 CNY)。 + /// + /// 入参:客户、来源类型、关键词与分页。 + /// 剩余可开票来源分页。 + [HttpGet("/finance/invoice/selectable")] + public async Task> GetSelectableAsync( + [FromQuery] InvoiceSelectableInput input) + { + var customer = await OmsSessionHelper.ResolveSessionCustomerAsync( + CustomerRepository, + CurrentUser, + input.CustomerId); + var sourceType = input.SourceType?.Trim(); + if (!string.IsNullOrWhiteSpace(sourceType) && !InvoiceSourceTypeCodes.IsKnown(sourceType)) + { + throw new BusinessException("开票来源类型无效"); + } + + var keyword = input.Keyword?.Trim(); + var occupied = await LoadOccupiedAmountMapAsync(customer.Id, excludeApplyId: null); + var items = new List(); + if (string.IsNullOrWhiteSpace(sourceType) || sourceType == InvoiceSourceTypeCodes.ParcelOrder) + { + items.AddRange(await LoadParcelSelectableAsync(customer.Id, keyword, occupied)); + } + + if (string.IsNullOrWhiteSpace(sourceType) || sourceType == InvoiceSourceTypeCodes.PickupOrder) + { + items.AddRange(await LoadPickupSelectableAsync(customer.Id, keyword, occupied)); + } + + if (string.IsNullOrWhiteSpace(sourceType) || sourceType == InvoiceSourceTypeCodes.StorageRent) + { + items.AddRange(await LoadRentSelectableAsync(customer.Id, keyword, occupied)); + } + + items = items + .OrderByDescending(x => x.PaidTime ?? DateTime.MinValue) + .ThenByDescending(x => x.SourceId) + .ToList(); + + var pageIndex = OmsDocHelper.NormalizePage(input.Page); + var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); + var total = items.Count; + var pageItems = items + .Skip((pageIndex - 1) * pageSize) + .Take(pageSize) + .ToList(); + return new OmsPageResult + { + Items = pageItems, + Total = total + }; + } + + /// + /// 分页查询开票申请。 + /// + /// 入参:客户、状态、关键词与时间范围。 + /// 开票申请分页。 + [HttpGet("/finance/invoice/list")] + public async Task> GetListAsync([FromQuery] InvoiceApplyListInput input) + { + var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( + CustomerRepository, + CurrentUser, + input.CustomerId); + var predicate = BuildApplyPredicate(input.Status, input.InvoiceType, input.Keyword, input.StartTime, input.EndTime, customerId); + var pageIndex = OmsDocHelper.NormalizePage(input.Page); + var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); + var entities = await InvoiceApplyRepository.GetPagedListAsync( + predicate, + pageIndex, + pageSize, + new Dictionary + { + [nameof(InvoiceApply.CreateTime)] = false, + [nameof(InvoiceApply.Id)] = false + }); + var total = await InvoiceApplyRepository.CountAsync(predicate); + var items = await MapListAsync(entities); + return new OmsPageResult + { + Items = items, + Total = total + }; + } + + /// + /// 查询开票申请详情(含明细行)。 + /// + /// 申请主键。 + /// 开票申请详情。 + [HttpGet("/finance/invoice/detail")] + public async Task GetDetailAsync([FromQuery] int id) + { + var apply = await GetVisibleApplyOrThrowAsync(id); + var lines = await InvoiceApplyLineRepository.GetListByApplyIdAsync(apply.Id); + return await MapDetailAsync(apply, lines); + } + + /// + /// 创建开票申请草稿;Submit=true 时立即走审批门面。 + /// + /// 入参:抬头、明细与是否提交。 + /// 申请详情(含审批判定)。 + [HttpPost("/finance/invoice/apply")] + public async Task CreateAsync(InvoiceApplyCreateInput input) + { + var customer = await OmsSessionHelper.ResolveSessionCustomerAsync( + CustomerRepository, + CurrentUser, + input.CustomerId); + var header = await ResolveHeaderSnapshotAsync(customer.Id, input); + var builtLines = await BuildValidatedLinesAsync(customer.Id, input.Lines, excludeApplyId: null); + var amountTotal = RoundMoney(builtLines.Sum(x => x.Amount)); + if (amountTotal < 0.01m) + { + throw new BusinessException("开票金额必须大于 0"); + } + + var entity = new InvoiceApply + { + ApplyNo = await GenerateApplyNoAsync(), + CustomerId = customer.Id, + InvoiceType = header.InvoiceType, + Medium = header.Medium, + TitleName = header.TitleName, + TaxNo = header.TaxNo, + AddressPhone = header.AddressPhone, + BankNameAccount = header.BankNameAccount, + AmountTotal = amountTotal, + TaxRate = header.TaxRate, + Currency = InvoiceCurrencyCodes.Cny, + Status = InvoiceStatusCodes.Draft, + ApplicantSource = OmsSessionHelper.IsCustomerLogin(CurrentUser) + ? InvoiceApplicantSourceCodes.Customer + : InvoiceApplicantSourceCodes.Admin, + Remark = header.Remark + }; + entity = await InvoiceApplyRepository.InsertAsync(entity); + await ReplaceLinesAsync(entity.Id, builtLines, deleteExisting: false); + + if (input.Submit) + { + return await SubmitCoreAsync(entity, customer); + } + + var lines = await InvoiceApplyLineRepository.GetListByApplyIdAsync(entity.Id); + return await MapDetailAsync(entity, lines); + } + + /// + /// 更新开票申请(仅草稿)。 + /// + /// 入参:申请 Id 与抬头、明细。 + /// 更新后的详情。 + [HttpPost("/finance/invoice/update")] + public async Task UpdateAsync(InvoiceApplyUpdateInput input) + { + var apply = await GetVisibleApplyOrThrowAsync(input.Id); + if (apply.Status != InvoiceStatusCodes.Draft) + { + throw new BusinessException("只有草稿状态的发票申请才能修改"); + } + + var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == apply.CustomerId) + ?? throw new BusinessException("客户不存在"); + var header = await ResolveHeaderSnapshotAsync(customer.Id, input); + var builtLines = await BuildValidatedLinesAsync(customer.Id, input.Lines, excludeApplyId: apply.Id); + var amountTotal = RoundMoney(builtLines.Sum(x => x.Amount)); + if (amountTotal < 0.01m) + { + throw new BusinessException("开票金额必须大于 0"); + } + + apply.InvoiceType = header.InvoiceType; + apply.Medium = header.Medium; + apply.TitleName = header.TitleName; + apply.TaxNo = header.TaxNo; + apply.AddressPhone = header.AddressPhone; + apply.BankNameAccount = header.BankNameAccount; + apply.AmountTotal = amountTotal; + apply.TaxRate = header.TaxRate; + apply.Remark = header.Remark; + await InvoiceApplyRepository.UpdateAsync(apply); + await ReplaceLinesAsync(apply.Id, builtLines, deleteExisting: true); + + if (input.Submit) + { + return await SubmitCoreAsync(apply, customer); + } + + var lines = await InvoiceApplyLineRepository.GetListByApplyIdAsync(apply.Id); + return await MapDetailAsync(apply, lines); + } + + /// + /// 提交开票申请:未配置审批则直接通过,启用后进入待审批。 + /// + /// 入参:申请主键。 + /// 提交后的详情(含审批判定)。 + [HttpPost("/finance/invoice/submit")] + public async Task SubmitAsync(InvoiceApplyIdInput input) + { + var apply = await GetVisibleApplyOrThrowAsync(input.Id); + if (apply.Status != InvoiceStatusCodes.Draft) + { + throw new BusinessException("只有草稿状态的发票申请才能提交"); + } + + var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == apply.CustomerId) + ?? throw new BusinessException("客户不存在"); + return await SubmitCoreAsync(apply, customer); + } + + /// + /// 开具发票(仅已审批):写入发票代码/号码/日期/PDF 后置为已开票。 + /// + /// 入参:发票号码等。 + /// 开票后的详情。 + [HttpPost("/finance/invoice/issue")] + public async Task IssueAsync(InvoiceApplyIssueInput input) + { + var apply = await GetVisibleApplyOrThrowAsync(input.Id); + if (apply.Status != InvoiceStatusCodes.Approved) + { + throw new BusinessException("只有已审批的发票申请才能开具"); + } + + var invoiceNumber = RequireText(input.InvoiceNumber, "发票号码不能为空"); + apply.InvoiceCode = NormalizeOptional(input.InvoiceCode); + apply.InvoiceNumber = invoiceNumber; + apply.InvoiceDate = input.InvoiceDate ?? DateTime.Now; + apply.InvoicePdfUrl = NormalizeOptional(input.InvoicePdfUrl); + if (!string.IsNullOrWhiteSpace(input.Remark)) + { + apply.Remark = input.Remark.Trim(); + } + + apply.Status = InvoiceStatusCodes.Issued; + apply.IssueTime = DateTime.Now; + apply.IssueBy = CurrentUser.UserName; + await InvoiceApplyRepository.UpdateAsync(apply); + var lines = await InvoiceApplyLineRepository.GetListByApplyIdAsync(apply.Id); + return await MapDetailAsync(apply, lines); + } + + /// + /// 作废已开票申请(释放来源占用)。 + /// + /// 入参:申请主键与原因。 + /// 作废后的详情。 + [HttpPost("/finance/invoice/void")] + public async Task VoidAsync(InvoiceApplyVoidInput input) + { + var apply = await GetVisibleApplyOrThrowAsync(input.Id); + if (apply.Status != InvoiceStatusCodes.Issued) + { + throw new BusinessException("只有已开票的申请才能作废"); + } + + apply.Status = InvoiceStatusCodes.Voided; + if (!string.IsNullOrWhiteSpace(input.Remark)) + { + apply.Remark = input.Remark.Trim(); + } + + await InvoiceApplyRepository.UpdateAsync(apply); + var lines = await InvoiceApplyLineRepository.GetListByApplyIdAsync(apply.Id); + return await MapDetailAsync(apply, lines); + } + + /// + /// 导出开票申请 Excel。 + /// + /// 入参:与列表相同的筛选条件。 + /// xlsx 文件流。 + [HttpGet("/finance/invoice/export")] + public async Task ExportAsync([FromQuery] InvoiceExportInput input) + { + var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( + CustomerRepository, + CurrentUser, + input.CustomerId); + var predicate = BuildApplyPredicate( + input.Status, + input.InvoiceType, + input.Keyword, + input.StartTime, + input.EndTime, + customerId); + var records = (await InvoiceApplyRepository.GetListAsync(predicate)) + .OrderByDescending(x => x.CreateTime) + .ThenByDescending(x => x.Id) + .ToList(); + var mapped = await MapListAsync(records); + var exportRows = mapped.Select(record => new + { + record.ApplyNo, + record.CustomerId, + record.CustomerCode, + record.CustomerName, + record.InvoiceTypeName, + record.MediumName, + record.TitleName, + record.TaxNo, + record.AmountTotal, + record.TaxRate, + record.Currency, + record.StatusName, + record.InvoiceCode, + record.InvoiceNumber, + record.InvoiceDate, + record.InvoicePdfUrl, + record.ApprovalInstanceNo, + record.RejectReason, + record.IssueTime, + record.IssueBy, + record.Remark, + record.CreateTime, + record.UpdateTime + }).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 = $"invoice-applies-{DateTime.Now:yyyyMMddHHmmss}.xlsx" + }; + } + + private async Task SubmitCoreAsync(InvoiceApply apply, Customer customer) + { + var lines = await InvoiceApplyLineRepository.GetListByApplyIdAsync(apply.Id); + if (lines.Count == 0) + { + throw new BusinessException("请选择开票明细"); + } + + var occupied = await LoadOccupiedAmountMapAsync(apply.CustomerId, apply.Id); + foreach (var line in lines) + { + var snapshot = await LoadSourceSnapshotAsync(apply.CustomerId, line.SourceType, line.SourceId); + var remaining = RoundMoney( + snapshot.BaseAmount - occupied.GetValueOrDefault(OccupancyKey(line.SourceType, line.SourceId))); + if (line.Amount > remaining) + { + throw new BusinessException($"来源 {snapshot.SourceNo} 可开票余额不足,剩余 {remaining:0.00}"); + } + } + + var gateResult = await ApprovalGate.CheckAndSubmitOrBypassAsync(new ApprovalSubmitRequest + { + OperationCode = ApprovalCodes.FinanceInvoiceIssue, + BizKey = BuildInvoiceBizKey(apply.Id), + Title = $"发票开具 - {customer.CustomerCode} {customer.CustomerName} {apply.ApplyNo}".Trim(), + PayloadJson = OmsDocHelper.SerializeJson(new + { + invoiceApplyId = apply.Id, + customerId = customer.Id, + customerCode = customer.CustomerCode, + customerName = customer.CustomerName, + applyNo = apply.ApplyNo, + amountTotal = apply.AmountTotal, + taxRate = apply.TaxRate, + invoiceType = apply.InvoiceType, + medium = apply.Medium, + titleName = apply.TitleName, + taxNo = apply.TaxNo + }), + Summary = new + { + customer.CustomerCode, + customer.CustomerName, + apply.ApplyNo, + apply.AmountTotal, + apply.InvoiceType, + apply.TitleName + } + }); + + if (gateResult.Decision == ApprovalGateDecision.Bypass) + { + apply.Status = InvoiceStatusCodes.Approved; + apply.RejectReason = null; + apply.ApprovalInstanceId = gateResult.InstanceId; + apply.ApprovalInstanceNo = gateResult.InstanceNo; + await InvoiceApplyRepository.UpdateAsync(apply); + } + else + { + apply.Status = InvoiceStatusCodes.PendingApproval; + apply.RejectReason = null; + apply.ApprovalInstanceId = gateResult.InstanceId; + apply.ApprovalInstanceNo = gateResult.InstanceNo; + await InvoiceApplyRepository.UpdateAsync(apply); + } + + var output = await MapDetailAsync(apply, lines); + output.Decision = gateResult.Decision.ToString(); + output.ApprovalInstanceId = gateResult.InstanceId; + output.ApprovalInstanceNo = gateResult.InstanceNo; + output.Message = gateResult.Decision == ApprovalGateDecision.PendingApproval + ? $"已提交审批({gateResult.InstanceNo}),通过后可开具发票" + : (gateResult.Message ?? "未启用审批,已直接通过"); + return output; + } + + private async Task GetVisibleApplyOrThrowAsync(int id) + { + var apply = await InvoiceApplyRepository.FirstOrDefaultAsync(x => x.Id == id) + ?? throw new BusinessException("发票申请不存在"); + var customerId = await OmsSessionHelper.ResolveListCustomerIdAsync( + CustomerRepository, + CurrentUser, + null); + if (customerId is > 0 && apply.CustomerId != customerId.Value) + { + throw new BusinessException("发票申请不存在"); + } + + return apply; + } + + private async Task GetOwnedProfileOrThrowAsync(int id, int customerId) + { + var entity = await ProfileRepository.FirstOrDefaultAsync(x => x.Id == id && x.CustomerId == customerId) + ?? throw new BusinessException("发票抬头不存在"); + return entity; + } + + private async Task ClearOtherDefaultProfilesAsync(int customerId, int keepId) + { + var others = await ProfileRepository.GetListAsync(x => + x.CustomerId == customerId && x.IsDefault == 1 && x.Id != keepId); + foreach (var other in others) + { + other.IsDefault = 0; + await ProfileRepository.UpdateAsync(other); + } + } + + private async Task<( + string InvoiceType, + string Medium, + string TitleName, + string TaxNo, + string? AddressPhone, + string? BankNameAccount, + decimal TaxRate, + string? Remark)> ResolveHeaderSnapshotAsync(int customerId, InvoiceApplyCreateInput input) + { + var invoiceType = string.IsNullOrWhiteSpace(input.InvoiceType) + ? InvoiceTypeCodes.Normal + : input.InvoiceType.Trim(); + if (!InvoiceTypeCodes.IsKnown(invoiceType)) + { + throw new BusinessException("发票类型无效"); + } + + var medium = string.IsNullOrWhiteSpace(input.Medium) + ? InvoiceMediumCodes.Electronic + : input.Medium.Trim(); + if (!InvoiceMediumCodes.IsKnown(medium)) + { + throw new BusinessException("发票介质无效"); + } + + string titleName; + string taxNo; + string? addressPhone; + string? bankNameAccount; + if (input.ProfileId is > 0) + { + var profile = await GetOwnedProfileOrThrowAsync(input.ProfileId.Value, customerId); + titleName = profile.TitleName; + taxNo = profile.TaxNo; + addressPhone = profile.AddressPhone; + bankNameAccount = profile.BankNameAccount; + } + else + { + titleName = RequireText(input.TitleName, "发票抬头不能为空"); + taxNo = RequireText(input.TaxNo, "税号不能为空"); + addressPhone = NormalizeOptional(input.AddressPhone); + bankNameAccount = NormalizeOptional(input.BankNameAccount); + } + + if (invoiceType == InvoiceTypeCodes.Special) + { + if (string.IsNullOrWhiteSpace(addressPhone)) + { + throw new BusinessException("专票须填写地址电话"); + } + + if (string.IsNullOrWhiteSpace(bankNameAccount)) + { + throw new BusinessException("专票须填写开户行及账号"); + } + } + + var taxRate = input.TaxRate ?? InvoiceStatusCodes.DefaultTaxRate; + if (taxRate < 0 || taxRate > 1) + { + throw new BusinessException("税率须在 0~1 之间"); + } + + return ( + invoiceType, + medium, + titleName, + taxNo, + addressPhone, + bankNameAccount, + taxRate, + NormalizeOptional(input.Remark)); + } + + private async Task> BuildValidatedLinesAsync( + int customerId, + List? inputs, + int? excludeApplyId) + { + if (inputs == null || inputs.Count == 0) + { + throw new BusinessException("请选择开票明细"); + } + + var occupied = await LoadOccupiedAmountMapAsync(customerId, excludeApplyId); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + var result = new List(inputs.Count); + foreach (var line in inputs) + { + var sourceType = line.SourceType?.Trim() ?? string.Empty; + if (!InvoiceSourceTypeCodes.IsKnown(sourceType)) + { + throw new BusinessException("开票来源类型无效"); + } + + if (line.SourceId <= 0) + { + throw new BusinessException("开票来源不能为空"); + } + + var amount = RoundMoney(line.Amount); + if (amount < 0.01m) + { + throw new BusinessException("开票金额必须大于 0"); + } + + var key = OccupancyKey(sourceType, line.SourceId); + if (!seen.Add(key)) + { + throw new BusinessException("同一来源不能重复开票"); + } + + var snapshot = await LoadSourceSnapshotAsync(customerId, sourceType, line.SourceId); + var occupiedAmount = occupied.GetValueOrDefault(key); + var remaining = RoundMoney(snapshot.BaseAmount - occupiedAmount); + if (amount > remaining) + { + throw new BusinessException($"来源 {snapshot.SourceNo} 可开票余额不足,剩余 {remaining:0.00}"); + } + + result.Add(new InvoiceApplyLine + { + SourceType = sourceType, + SourceId = line.SourceId, + SourceNo = snapshot.SourceNo, + Amount = amount, + Currency = InvoiceCurrencyCodes.Cny, + Remark = NormalizeOptional(line.Remark) + }); + } + + return result; + } + + private async Task<(string SourceNo, decimal BaseAmount)> LoadSourceSnapshotAsync( + int customerId, + string sourceType, + int sourceId) + { + if (sourceType == InvoiceSourceTypeCodes.ParcelOrder) + { + var order = await OrderRepository.FirstOrDefaultAsync(x => + x.Id == sourceId && x.CustomerId == customerId) + ?? throw new BusinessException("运单不存在或无权开票"); + if (order.IsPaid != PaidFlag || order.IsRefunded != NotRefundedFlag) + { + throw new BusinessException($"运单 {order.ServiceNo} 未支付或已退款,不能开票"); + } + + var payable = order.PayableAmount ?? 0; + if (payable <= 0) + { + throw new BusinessException($"运单 {order.ServiceNo} 应付金额为 0,不能开票"); + } + + return (order.ServiceNo, payable); + } + + if (sourceType == InvoiceSourceTypeCodes.PickupOrder) + { + var pickup = await PickupOrderRepository.FirstOrDefaultAsync(x => + x.Id == sourceId && x.CustomerId == customerId) + ?? throw new BusinessException("揽收单不存在或无权开票"); + if (!string.Equals(pickup.PayStatus, PickupPayStatusCodes.Paid, StringComparison.OrdinalIgnoreCase)) + { + throw new BusinessException($"揽收单 {pickup.PickupNo} 未支付,不能开票"); + } + + if (!IsCny(pickup.Currency)) + { + throw new BusinessException($"揽收单 {pickup.PickupNo} 非人民币,不能开票"); + } + + var receivable = pickup.ReceivableAmount ?? 0; + if (receivable <= 0) + { + throw new BusinessException($"揽收单 {pickup.PickupNo} 应收金额为 0,不能开票"); + } + + return (pickup.PickupNo, receivable); + } + + if (sourceType == InvoiceSourceTypeCodes.StorageRent) + { + var bill = await RentBillRepository.FirstOrDefaultAsync(x => + x.Id == sourceId && x.CustomerId == customerId) + ?? throw new BusinessException("仓租账单不存在或无权开票"); + if (!string.Equals(bill.Status, WarehouseRentBillStatusCodes.Paid, StringComparison.OrdinalIgnoreCase)) + { + throw new BusinessException($"仓租账单 {bill.BillNo} 未支付,不能开票"); + } + + if (!IsCny(bill.Currency)) + { + throw new BusinessException($"仓租账单 {bill.BillNo} 非人民币,不能开票"); + } + + if (bill.Amount <= 0) + { + throw new BusinessException($"仓租账单 {bill.BillNo} 金额为 0,不能开票"); + } + + return (bill.BillNo, bill.Amount); + } + + throw new BusinessException("开票来源类型无效"); + } + + private async Task ReplaceLinesAsync(int applyId, List lines, bool deleteExisting) + { + if (deleteExisting) + { + var oldLines = await InvoiceApplyLineRepository.GetListByApplyIdAsync(applyId); + foreach (var old in oldLines) + { + await InvoiceApplyLineRepository.DeleteAsync(old); + } + } + + foreach (var line in lines) + { + line.InvoiceApplyId = applyId; + await InvoiceApplyLineRepository.InsertAsync(line); + } + } + + private async Task> LoadOccupiedAmountMapAsync(int customerId, int? excludeApplyId) + { + var occupying = InvoiceStatusCodes.OccupyingStatuses; + var applies = await InvoiceApplyRepository.GetListAsync(x => + x.CustomerId == customerId && occupying.Contains(x.Status)); + if (excludeApplyId is > 0) + { + applies = applies.Where(x => x.Id != excludeApplyId.Value).ToList(); + } + + if (applies.Count == 0) + { + return new Dictionary(StringComparer.OrdinalIgnoreCase); + } + + var applyIds = applies.Select(x => x.Id).ToList(); + var lines = await InvoiceApplyLineRepository.GetListAsync(x => applyIds.Contains(x.InvoiceApplyId)); + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var line in lines) + { + var key = OccupancyKey(line.SourceType, line.SourceId); + map[key] = map.TryGetValue(key, out var current) ? current + line.Amount : line.Amount; + } + + return map; + } + + private async Task> LoadParcelSelectableAsync( + int customerId, + string? keyword, + IReadOnlyDictionary occupied) + { + var paid = PaidFlag; + var notRefunded = NotRefundedFlag; + var hasKeyword = !string.IsNullOrWhiteSpace(keyword); + var orders = await OrderRepository.GetListAsync(x => + x.CustomerId == customerId + && x.IsPaid == paid + && x.IsRefunded == notRefunded + && x.PayableAmount != null + && x.PayableAmount > 0 + && (!hasKeyword || x.ServiceNo.Contains(keyword!))); + var items = new List(); + foreach (var order in orders) + { + var baseAmount = order.PayableAmount ?? 0; + var item = TryBuildSelectable( + InvoiceSourceTypeCodes.ParcelOrder, + order.Id, + order.ServiceNo, + baseAmount, + order.PayTime ?? order.CreateTime, + occupied); + if (item != null) + { + items.Add(item); + } + } + + return items; + } + + private async Task> LoadPickupSelectableAsync( + int customerId, + string? keyword, + IReadOnlyDictionary occupied) + { + var paid = PickupPayStatusCodes.Paid; + var hasKeyword = !string.IsNullOrWhiteSpace(keyword); + var pickups = await PickupOrderRepository.GetListAsync(x => + x.CustomerId == customerId + && x.PayStatus == paid + && x.ReceivableAmount != null + && x.ReceivableAmount > 0 + && (x.Currency == InvoiceCurrencyCodes.Cny || x.Currency == "") + && (!hasKeyword || x.PickupNo.Contains(keyword!))); + var items = new List(); + foreach (var pickup in pickups) + { + var item = TryBuildSelectable( + InvoiceSourceTypeCodes.PickupOrder, + pickup.Id, + pickup.PickupNo, + pickup.ReceivableAmount ?? 0, + pickup.PayTime ?? pickup.CreateTime, + occupied); + if (item != null) + { + items.Add(item); + } + } + + return items; + } + + private async Task> LoadRentSelectableAsync( + int customerId, + string? keyword, + IReadOnlyDictionary occupied) + { + var paid = WarehouseRentBillStatusCodes.Paid; + var hasKeyword = !string.IsNullOrWhiteSpace(keyword); + var bills = await RentBillRepository.GetListAsync(x => + x.CustomerId == customerId + && x.Status == paid + && x.Amount > 0 + && (x.Currency == InvoiceCurrencyCodes.Cny || x.Currency == "") + && (!hasKeyword || x.BillNo.Contains(keyword!))); + var items = new List(); + foreach (var bill in bills) + { + var item = TryBuildSelectable( + InvoiceSourceTypeCodes.StorageRent, + bill.Id, + bill.BillNo, + bill.Amount, + bill.PaidTime ?? bill.CreateTime, + occupied); + if (item != null) + { + items.Add(item); + } + } + + return items; + } + + private static InvoiceSelectableItemOutput? TryBuildSelectable( + string sourceType, + int sourceId, + string sourceNo, + decimal baseAmount, + DateTime? paidTime, + IReadOnlyDictionary occupied) + { + var remaining = RoundMoney(baseAmount - occupied.GetValueOrDefault(OccupancyKey(sourceType, sourceId))); + if (remaining < 0.01m) + { + return null; + } + + return new InvoiceSelectableItemOutput + { + SourceType = sourceType, + SourceTypeName = GetSourceTypeName(sourceType), + SourceId = sourceId, + SourceNo = sourceNo, + BaseAmount = RoundMoney(baseAmount), + OccupiedAmount = RoundMoney(baseAmount - remaining), + RemainingAmount = remaining, + Currency = InvoiceCurrencyCodes.Cny, + PaidTime = paidTime + }; + } + + private async Task> MapListAsync(IReadOnlyList entities) + { + var items = new List(entities.Count); + if (entities.Count == 0) + { + return items; + } + + var customerIds = entities.Select(x => x.CustomerId).Distinct().ToArray(); + var customers = await CustomerRepository.GetListAsync(x => customerIds.Contains(x.Id)); + var customerMap = customers.ToDictionary(x => x.Id); + var pendingBizKeys = entities + .Where(x => x.Status == InvoiceStatusCodes.PendingApproval) + .Select(x => BuildInvoiceBizKey(x.Id)) + .Distinct() + .ToList(); + var approvalMap = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (pendingBizKeys.Count > 0) + { + var approvals = await ApprovalInstanceRepository.GetListAsync(x => + x.OperationCode == ApprovalCodes.FinanceInvoiceIssue + && pendingBizKeys.Contains(x.BizKey) + && x.Status == ApprovalInstanceStatus.Pending); + foreach (var approval in approvals) + { + approvalMap[approval.BizKey] = (approval.Id, approval.InstanceNo); + } + } + + foreach (var entity in entities) + { + var output = MapListItem(entity); + if (customerMap.TryGetValue(entity.CustomerId, out var customer)) + { + output.CustomerCode = customer.CustomerCode; + output.CustomerName = customer.CustomerName; + } + + var bizKey = BuildInvoiceBizKey(entity.Id); + if (approvalMap.TryGetValue(bizKey, out var approvalInfo)) + { + output.ApprovalPending = true; + output.ApprovalInstanceId = approvalInfo.Id; + output.ApprovalInstanceNo = approvalInfo.InstanceNo; + } + + items.Add(output); + } + + return items; + } + + private async Task MapDetailAsync(InvoiceApply entity, List lines) + { + var listItem = (await MapListAsync([entity])).First(); + return new InvoiceApplyDetailOutput + { + Id = listItem.Id, + ApplyNo = listItem.ApplyNo, + CustomerId = listItem.CustomerId, + CustomerCode = listItem.CustomerCode, + CustomerName = listItem.CustomerName, + InvoiceType = listItem.InvoiceType, + InvoiceTypeName = listItem.InvoiceTypeName, + Medium = listItem.Medium, + MediumName = listItem.MediumName, + TitleName = listItem.TitleName, + TaxNo = listItem.TaxNo, + AddressPhone = entity.AddressPhone, + BankNameAccount = entity.BankNameAccount, + AmountTotal = listItem.AmountTotal, + TaxRate = listItem.TaxRate, + Currency = listItem.Currency, + Status = listItem.Status, + StatusName = listItem.StatusName, + ApplicantSource = listItem.ApplicantSource, + InvoiceCode = listItem.InvoiceCode, + InvoiceNumber = listItem.InvoiceNumber, + InvoiceDate = listItem.InvoiceDate, + InvoicePdfUrl = listItem.InvoicePdfUrl, + Remark = listItem.Remark, + ApprovalInstanceId = listItem.ApprovalInstanceId, + ApprovalInstanceNo = listItem.ApprovalInstanceNo, + ApprovalPending = listItem.ApprovalPending, + RejectReason = listItem.RejectReason, + IssueTime = listItem.IssueTime, + IssueBy = listItem.IssueBy, + CreateTime = listItem.CreateTime, + UpdateTime = listItem.UpdateTime, + Lines = lines + .OrderBy(x => x.Id) + .Select(x => new InvoiceApplyLineOutput + { + Id = x.Id, + SourceType = x.SourceType, + SourceTypeName = GetSourceTypeName(x.SourceType), + SourceId = x.SourceId, + SourceNo = x.SourceNo, + Amount = x.Amount, + Currency = x.Currency, + Remark = x.Remark + }) + .ToList() + }; + } + + private static InvoiceApplyListOutput MapListItem(InvoiceApply entity) => new() + { + Id = entity.Id, + ApplyNo = entity.ApplyNo, + CustomerId = entity.CustomerId, + InvoiceType = entity.InvoiceType, + InvoiceTypeName = GetInvoiceTypeName(entity.InvoiceType), + Medium = entity.Medium, + MediumName = GetMediumName(entity.Medium), + TitleName = entity.TitleName, + TaxNo = entity.TaxNo, + AmountTotal = entity.AmountTotal, + TaxRate = entity.TaxRate, + Currency = entity.Currency, + Status = entity.Status, + StatusName = GetStatusName(entity.Status), + ApplicantSource = entity.ApplicantSource, + InvoiceCode = entity.InvoiceCode, + InvoiceNumber = entity.InvoiceNumber, + InvoiceDate = entity.InvoiceDate, + InvoicePdfUrl = entity.InvoicePdfUrl, + Remark = entity.Remark, + ApprovalInstanceId = entity.ApprovalInstanceId, + ApprovalInstanceNo = entity.ApprovalInstanceNo, + RejectReason = entity.RejectReason, + IssueTime = entity.IssueTime, + IssueBy = entity.IssueBy, + CreateTime = entity.CreateTime, + UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime) + }; + + private static InvoiceProfileOutput MapProfile(CustomerInvoiceProfile entity) => new() + { + Id = entity.Id, + CustomerId = entity.CustomerId, + TitleName = entity.TitleName, + TaxNo = entity.TaxNo, + AddressPhone = entity.AddressPhone, + BankNameAccount = entity.BankNameAccount, + IsDefault = entity.IsDefault == 1, + Remark = entity.Remark, + CreateTime = entity.CreateTime, + UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime) + }; + + private static Expression> BuildApplyPredicate( + string? status, + string? invoiceType, + string? keyword, + DateTime? startTime, + DateTime? endTime, + int? customerId) + { + var hasCustomer = customerId is > 0; + var customerIdValue = customerId.GetValueOrDefault(); + var statusValue = status?.Trim(); + var hasStatus = !string.IsNullOrWhiteSpace(statusValue); + var typeValue = invoiceType?.Trim(); + var hasType = !string.IsNullOrWhiteSpace(typeValue); + var keywordValue = keyword?.Trim(); + var hasKeyword = !string.IsNullOrWhiteSpace(keywordValue); + + if (startTime.HasValue && endTime.HasValue) + { + var start = startTime.Value; + var end = endTime.Value; + return x => + (!hasCustomer || x.CustomerId == customerIdValue) && + (!hasStatus || x.Status == statusValue) && + (!hasType || x.InvoiceType == typeValue) && + (!hasKeyword + || x.ApplyNo.Contains(keywordValue!) + || x.TitleName.Contains(keywordValue!) + || (x.InvoiceNumber != null && x.InvoiceNumber.Contains(keywordValue!)) + || (x.InvoiceCode != null && x.InvoiceCode.Contains(keywordValue!))) && + x.CreateTime >= start && + x.CreateTime <= end; + } + + if (startTime.HasValue) + { + var start = startTime.Value; + return x => + (!hasCustomer || x.CustomerId == customerIdValue) && + (!hasStatus || x.Status == statusValue) && + (!hasType || x.InvoiceType == typeValue) && + (!hasKeyword + || x.ApplyNo.Contains(keywordValue!) + || x.TitleName.Contains(keywordValue!) + || (x.InvoiceNumber != null && x.InvoiceNumber.Contains(keywordValue!)) + || (x.InvoiceCode != null && x.InvoiceCode.Contains(keywordValue!))) && + x.CreateTime >= start; + } + + if (endTime.HasValue) + { + var end = endTime.Value; + return x => + (!hasCustomer || x.CustomerId == customerIdValue) && + (!hasStatus || x.Status == statusValue) && + (!hasType || x.InvoiceType == typeValue) && + (!hasKeyword + || x.ApplyNo.Contains(keywordValue!) + || x.TitleName.Contains(keywordValue!) + || (x.InvoiceNumber != null && x.InvoiceNumber.Contains(keywordValue!)) + || (x.InvoiceCode != null && x.InvoiceCode.Contains(keywordValue!))) && + x.CreateTime <= end; + } + + return x => + (!hasCustomer || x.CustomerId == customerIdValue) && + (!hasStatus || x.Status == statusValue) && + (!hasType || x.InvoiceType == typeValue) && + (!hasKeyword + || x.ApplyNo.Contains(keywordValue!) + || x.TitleName.Contains(keywordValue!) + || (x.InvoiceNumber != null && x.InvoiceNumber.Contains(keywordValue!)) + || (x.InvoiceCode != null && x.InvoiceCode.Contains(keywordValue!))); + } + + private async Task GenerateApplyNoAsync() + { + var prefix = $"INV{DateTime.Now:yyyyMMdd}"; + for (var i = 0; i < 10; i++) + { + var existing = await InvoiceApplyRepository.GetListAsync(x => x.ApplyNo.StartsWith(prefix)); + var maxSeq = 0; + foreach (var item in existing) + { + var suffix = item.ApplyNo.Length > prefix.Length ? item.ApplyNo[prefix.Length..] : string.Empty; + if (int.TryParse(suffix, out var seq) && seq > maxSeq) + { + maxSeq = seq; + } + } + + var applyNo = $"{prefix}{(maxSeq + 1):D4}"; + if (!await InvoiceApplyRepository.ExistsApplyNoAsync(applyNo)) + { + return applyNo; + } + } + + throw new BusinessException("发票申请单号生成失败"); + } + + private static string BuildInvoiceBizKey(int invoiceApplyId) => + $"{ApprovalCodes.FinanceInvoiceIssue}:{invoiceApplyId}"; + + private static string OccupancyKey(string sourceType, int sourceId) => + $"{sourceType}:{sourceId}"; + + private static decimal RoundMoney(decimal value) => + Math.Round(value, 2, MidpointRounding.AwayFromZero); + + private static bool IsCny(string? currency) => + string.IsNullOrWhiteSpace(currency) + || string.Equals(currency.Trim(), InvoiceCurrencyCodes.Cny, StringComparison.OrdinalIgnoreCase); + + private static string RequireText(string? value, string message) + { + var text = value?.Trim(); + if (string.IsNullOrWhiteSpace(text)) + { + throw new BusinessException(message); + } + + return text; + } + + private static string? NormalizeOptional(string? value) + { + var text = value?.Trim(); + return string.IsNullOrWhiteSpace(text) ? null : text; + } + + private static string GetStatusName(string? status) => status switch + { + InvoiceStatusCodes.Draft => "草稿", + InvoiceStatusCodes.PendingApproval => "待审批", + InvoiceStatusCodes.Approved => "已审批待开票", + InvoiceStatusCodes.Issued => "已开票", + InvoiceStatusCodes.Rejected => "已驳回", + InvoiceStatusCodes.Voided => "已作废", + InvoiceStatusCodes.RedFlushed => "已红冲", + _ => status ?? string.Empty + }; + + private static string GetSourceTypeName(string? sourceType) => sourceType switch + { + InvoiceSourceTypeCodes.ParcelOrder => "运单", + InvoiceSourceTypeCodes.PickupOrder => "揽收单", + InvoiceSourceTypeCodes.StorageRent => "仓租", + _ => sourceType ?? string.Empty + }; + + private static string GetInvoiceTypeName(string? invoiceType) => invoiceType switch + { + InvoiceTypeCodes.Normal => "普通发票", + InvoiceTypeCodes.Special => "专用发票", + _ => invoiceType ?? string.Empty + }; + + private static string GetMediumName(string? medium) => medium switch + { + InvoiceMediumCodes.Electronic => "电子", + InvoiceMediumCodes.Paper => "纸质", + _ => medium ?? string.Empty + }; +} diff --git a/src/Oms.Application/Services/System/SystemOtherConfigService.cs b/src/Oms.Application/Services/System/SystemOtherConfigService.cs index 036b02b..d126e96 100644 --- a/src/Oms.Application/Services/System/SystemOtherConfigService.cs +++ b/src/Oms.Application/Services/System/SystemOtherConfigService.cs @@ -1,4 +1,5 @@ using System.Linq.Expressions; +using System.Text.RegularExpressions; using Fake.Application; using Fake.ObjectStorage; using Microsoft.AspNetCore.Authorization; @@ -152,17 +153,40 @@ public class SystemOtherConfigService : ApplicationService } /// - /// 获取客户充值用支付宝/微信收款码图片地址。未配置时对应 URL 为空(前端可回退本地默认图)。 + /// 获取客户充值用支付宝/微信收款码图片地址。 + /// 返回同源 API 文件地址(非 COS 直链),未配置时对应 URL 为空(前端可回退本地默认图)。 /// [HttpGet("/system/other-config/payment-qr")] public async Task GetPaymentReceiveQrAsync() { var entity = await SystemOtherConfigRepository.GetByConfigCodeAsync(SystemOtherConfigCodes.PaymentReceiveQr); - return new PaymentReceiveQrOutput + return MapPaymentReceiveQrOutput(entity); + } + + /// + /// 按渠道输出收款码图片字节(同源,避免浏览器直连 COS 证书域名)。 + /// 收款码本身用于对客展示,允许匿名读取以便 <img src> 无需带 Authorization。 + /// + /// alipay / wechat。 + /// 缓存戳(来自 object key),可选。 + /// 取消令牌。 + [AllowAnonymous] + [HttpGet("/system/other-config/payment-qr/file")] + public async Task GetPaymentReceiveQrFileAsync( + [FromQuery] string channel, + [FromQuery] string? v = null, + CancellationToken cancellationToken = default) + { + _ = v; + var normalized = (channel ?? string.Empty).Trim().ToLowerInvariant(); + if (normalized is not (PaymentQrChannelAlipay or PaymentQrChannelWechat)) { - AlipayUrl = FileStorage.GetPublicUrl(entity?.AppKey), - WechatUrl = FileStorage.GetPublicUrl(entity?.Remark) - }; + throw new BusinessException("渠道仅支持 alipay 或 wechat"); + } + + var entity = await SystemOtherConfigRepository.GetByConfigCodeAsync(SystemOtherConfigCodes.PaymentReceiveQr); + var objectKey = normalized == PaymentQrChannelAlipay ? entity?.AppKey : entity?.Remark; + return await StreamManagedImageAsync(objectKey, cancellationToken); } /// @@ -191,11 +215,7 @@ public class SystemOtherConfigService : ApplicationService } await SystemOtherConfigRepository.UpdateAsync(entity); - return new PaymentReceiveQrOutput - { - AlipayUrl = FileStorage.GetPublicUrl(entity.AppKey), - WechatUrl = FileStorage.GetPublicUrl(entity.Remark) - }; + return MapPaymentReceiveQrOutput(entity); } /// @@ -222,15 +242,12 @@ public class SystemOtherConfigService : ApplicationService } await SystemOtherConfigRepository.UpdateAsync(entity); - return new PaymentReceiveQrOutput - { - AlipayUrl = FileStorage.GetPublicUrl(entity.AppKey), - WechatUrl = FileStorage.GetPublicUrl(entity.Remark) - }; + return MapPaymentReceiveQrOutput(entity); } /// - /// 获取品牌 Logo(系统顶栏 / 官网 / 网站标签 / 启动页吉祥物)。未配置时对应 URL 为空(前端回退本地默认图)。匿名可读。 + /// 获取品牌 Logo(系统顶栏 / 官网 / 网站标签 / 启动页吉祥物)。 + /// 返回同源 API 文件地址(非 COS 直链);未配置时对应 URL 为空。匿名可读。 /// [AllowAnonymous] [HttpGet("/system/other-config/brand-logo")] @@ -240,6 +257,41 @@ public class SystemOtherConfigService : ApplicationService return MapBrandLogoOutput(entity); } + /// + /// 按渠道输出品牌 Logo 图片字节(同源,避免浏览器直连 COS)。启动页/登录页匿名可读。 + /// + /// portal / site / favicon / mascot。 + /// 缓存戳(来自 object key),可选。 + /// 取消令牌。 + [AllowAnonymous] + [HttpGet("/system/other-config/brand-logo/file")] + public async Task GetBrandLogoFileAsync( + [FromQuery] string channel, + [FromQuery] string? v = null, + CancellationToken cancellationToken = default) + { + _ = v; + var normalized = (channel ?? string.Empty).Trim().ToLowerInvariant(); + if (normalized is not ( + BrandLogoChannelPortal + or BrandLogoChannelSite + or BrandLogoChannelFavicon + or BrandLogoChannelMascot)) + { + throw new BusinessException("渠道仅支持 portal、site、favicon 或 mascot"); + } + + var entity = await SystemOtherConfigRepository.GetByConfigCodeAsync(SystemOtherConfigCodes.BrandLogo); + var objectKey = normalized switch + { + BrandLogoChannelPortal => entity?.AppKey, + BrandLogoChannelSite => entity?.Remark, + BrandLogoChannelFavicon => entity?.BaseUrl, + _ => entity?.AppSecret + }; + return await StreamManagedImageAsync(objectKey, cancellationToken); + } + /// /// 上传并替换品牌 Logo。Channel=portal|site|favicon|mascot;返回最新可访问 URL。 /// @@ -325,12 +377,143 @@ public class SystemOtherConfigService : ApplicationService private BrandLogoOutput MapBrandLogoOutput(SystemOtherConfig? entity) => new() { - PortalUrl = FileStorage.GetPublicUrl(entity?.AppKey), - SiteUrl = FileStorage.GetPublicUrl(entity?.Remark), - FaviconUrl = FileStorage.GetPublicUrl(entity?.BaseUrl), - MascotUrl = FileStorage.GetPublicUrl(entity?.AppSecret) + PortalUrl = BuildSameOriginImageUrl("/system/other-config/brand-logo/file", BrandLogoChannelPortal, entity?.AppKey), + SiteUrl = BuildSameOriginImageUrl("/system/other-config/brand-logo/file", BrandLogoChannelSite, entity?.Remark), + FaviconUrl = BuildSameOriginImageUrl("/system/other-config/brand-logo/file", BrandLogoChannelFavicon, entity?.BaseUrl), + MascotUrl = BuildSameOriginImageUrl("/system/other-config/brand-logo/file", BrandLogoChannelMascot, entity?.AppSecret) }; + private PaymentReceiveQrOutput MapPaymentReceiveQrOutput(SystemOtherConfig? entity) => + new() + { + AlipayUrl = BuildSameOriginImageUrl("/system/other-config/payment-qr/file", PaymentQrChannelAlipay, entity?.AppKey), + WechatUrl = BuildSameOriginImageUrl("/system/other-config/payment-qr/file", PaymentQrChannelWechat, entity?.Remark) + }; + + /// + /// 生成浏览器可直开的同源相对路径;object key 仍存库,物理文件可在 COS/Local,但不把 cos.* 签发给前端。 + /// + private static string BuildSameOriginImageUrl(string path, string channel, string? objectKey) + { + if (string.IsNullOrWhiteSpace(objectKey) || objectKey == "0") + { + return string.Empty; + } + + string logicalKey; + try + { + logicalKey = FileStoragePath.NormalizeKey(objectKey); + } + catch + { + return string.Empty; + } + + if (string.IsNullOrWhiteSpace(logicalKey)) + { + return string.Empty; + } + + var stamp = Path.GetFileNameWithoutExtension(logicalKey.Replace('\\', '/')); + if (string.IsNullOrWhiteSpace(stamp)) + { + stamp = Math.Abs(logicalKey.GetHashCode(StringComparison.Ordinal)).ToString("x"); + } + + return $"{path}?channel={Uri.EscapeDataString(channel)}&v={Uri.EscapeDataString(stamp)}"; + } + + private async Task StreamManagedImageAsync( + string? objectKey, + CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(objectKey) || objectKey == "0") + { + throw new BusinessException("图片未配置"); + } + + string logicalKey; + try + { + logicalKey = FileStoragePath.NormalizeKey(objectKey); + } + catch + { + throw new BusinessException("图片路径无效"); + } + + foreach (var candidate in FileStoragePath.ExpandReadKeys(logicalKey)) + { + try + { + if (!await FileStorage.ExistsAsync(candidate, cancellationToken)) + { + continue; + } + + await using var stream = await FileStorage.GetAsync(candidate, cancellationToken); + using var ms = new MemoryStream(); + await stream.CopyToAsync(ms, cancellationToken); + var bytes = ms.ToArray(); + if (bytes.Length <= 0) + { + continue; + } + + return new FileContentResult(bytes, GuessImageMime(candidate)) + { + FileDownloadName = Path.GetFileName(candidate.Replace('\\', '/')) + }; + } + catch (UnauthorizedAccessException) + { + // try next key shape + } + catch (DirectoryNotFoundException) + { + } + catch (FileNotFoundException) + { + } + catch (IOException) + { + } + } + + throw new BusinessException("图片不存在或无法读取"); + } + + private static string GuessImageMime(string pathOrKey) + { + if (Regex.IsMatch(pathOrKey, @"\.png(\?|#|$)", RegexOptions.IgnoreCase)) + { + return "image/png"; + } + + if (Regex.IsMatch(pathOrKey, @"\.jpe?g(\?|#|$)", RegexOptions.IgnoreCase)) + { + return "image/jpeg"; + } + + if (Regex.IsMatch(pathOrKey, @"\.webp(\?|#|$)", RegexOptions.IgnoreCase)) + { + return "image/webp"; + } + + if (Regex.IsMatch(pathOrKey, @"\.gif(\?|#|$)", RegexOptions.IgnoreCase)) + { + return "image/gif"; + } + + if (Regex.IsMatch(pathOrKey, @"\.bmp(\?|#|$)", RegexOptions.IgnoreCase)) + { + return "image/bmp"; + } + + return "application/octet-stream"; + } + private async Task EnsurePaymentReceiveQrConfigAsync() { var entity = await SystemOtherConfigRepository.GetByConfigCodeAsync(SystemOtherConfigCodes.PaymentReceiveQr); diff --git a/src/Oms.Domain/ApprovalAggregate/Consts/ApprovalCodes.cs b/src/Oms.Domain/ApprovalAggregate/Consts/ApprovalCodes.cs index 51f43d6..7b7c071 100644 --- a/src/Oms.Domain/ApprovalAggregate/Consts/ApprovalCodes.cs +++ b/src/Oms.Domain/ApprovalAggregate/Consts/ApprovalCodes.cs @@ -40,6 +40,9 @@ public static class ApprovalCodes /// 客户充值入账。 public const string FinanceRechargeCredit = "Finance.Recharge.Credit"; + + /// 发票开具。 + public const string FinanceInvoiceIssue = "Finance.Invoice.Issue"; } /// diff --git a/src/Oms.Domain/FinanceAggregate/Consts/InvoiceCodes.cs b/src/Oms.Domain/FinanceAggregate/Consts/InvoiceCodes.cs new file mode 100644 index 0000000..f9964de --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Consts/InvoiceCodes.cs @@ -0,0 +1,111 @@ +namespace Oms.Domain.FinanceAggregate.Consts; + +/// +/// 发票申请状态。 +/// +public static class InvoiceStatusCodes +{ + /// 草稿。 + public const string Draft = "draft"; + + /// 待审批。 + public const string PendingApproval = "pendingApproval"; + + /// 已审批待开票。 + public const string Approved = "approved"; + + /// 已开票。 + public const string Issued = "issued"; + + /// 已驳回。 + public const string Rejected = "rejected"; + + /// 已作废(释放占用)。 + public const string Voided = "voided"; + + /// 已红冲。 + public const string RedFlushed = "redFlushed"; + + /// 占用可开票额度的状态(作废/驳回/红冲不占用)。 + public static readonly string[] OccupyingStatuses = + [ + Draft, + PendingApproval, + Approved, + Issued + ]; + + /// 默认税率备注(含税不拆分)。 + public const decimal DefaultTaxRate = 0.06m; + + public static bool OccupiesSource(string? status) => + status is Draft or PendingApproval or Approved or Issued; +} + +/// +/// 开票来源类型。 +/// +public static class InvoiceSourceTypeCodes +{ + /// 已支付运单(应付金额)。 + public const string ParcelOrder = "parcelOrder"; + + /// 已支付揽收单(应收金额)。 + public const string PickupOrder = "pickupOrder"; + + /// 已支付仓租账单。 + public const string StorageRent = "storageRent"; + + public static bool IsKnown(string? sourceType) => + sourceType is ParcelOrder or PickupOrder or StorageRent; +} + +/// +/// 发票类型。 +/// +public static class InvoiceTypeCodes +{ + /// 增值税普通发票。 + public const string Normal = "normal"; + + /// 增值税专用发票。 + public const string Special = "special"; + + public static bool IsKnown(string? invoiceType) => + invoiceType is Normal or Special; +} + +/// +/// 发票介质。 +/// +public static class InvoiceMediumCodes +{ + /// 电子发票。 + public const string Electronic = "electronic"; + + /// 纸质发票。 + public const string Paper = "paper"; + + public static bool IsKnown(string? medium) => + medium is Electronic or Paper; +} + +/// +/// 申请人来源。 +/// +public static class InvoiceApplicantSourceCodes +{ + /// 管理端。 + public const string Admin = "admin"; + + /// 客户门户。 + public const string Customer = "customer"; +} + +/// +/// 发票币种。 +/// +public static class InvoiceCurrencyCodes +{ + public const string Cny = "CNY"; +} diff --git a/src/Oms.Domain/FinanceAggregate/Entities/CustomerInvoiceProfile.cs b/src/Oms.Domain/FinanceAggregate/Entities/CustomerInvoiceProfile.cs new file mode 100644 index 0000000..53f339f --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Entities/CustomerInvoiceProfile.cs @@ -0,0 +1,31 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.FinanceAggregate.Entities; + +/// +/// 客户发票抬头。 +/// +[SugarTable("t_customer_invoice_profile")] +public class CustomerInvoiceProfile : OmsAuditedAggregateRoot +{ + public int CustomerId { get; set; } + + [SugarColumn(Length = 128)] + public string TitleName { get; set; } = string.Empty; + + [SugarColumn(Length = 64)] + public string TaxNo { get; set; } = string.Empty; + + [SugarColumn(Length = 256, IsNullable = true)] + public string? AddressPhone { get; set; } + + [SugarColumn(Length = 256, IsNullable = true)] + public string? BankNameAccount { get; set; } + + /// 是否默认:0-否,1-是。 + public byte IsDefault { get; set; } + + [SugarColumn(Length = 512, IsNullable = true)] + public string? Remark { get; set; } +} diff --git a/src/Oms.Domain/FinanceAggregate/Entities/InvoiceApply.cs b/src/Oms.Domain/FinanceAggregate/Entities/InvoiceApply.cs new file mode 100644 index 0000000..85d213a --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Entities/InvoiceApply.cs @@ -0,0 +1,82 @@ +using Oms.Domain.FinanceAggregate.Consts; +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.FinanceAggregate.Entities; + +/// +/// 发票申请头。金额为含税价税合计。 +/// +[SugarTable("t_invoice_apply")] +public class InvoiceApply : OmsAuditedAggregateRoot +{ + [SugarColumn(Length = 32)] + public string ApplyNo { get; set; } = string.Empty; + + public int CustomerId { get; set; } + + [SugarColumn(Length = 16)] + public string InvoiceType { get; set; } = InvoiceTypeCodes.Normal; + + [SugarColumn(Length = 16)] + public string Medium { get; set; } = InvoiceMediumCodes.Electronic; + + [SugarColumn(Length = 128)] + public string TitleName { get; set; } = string.Empty; + + [SugarColumn(Length = 64)] + public string TaxNo { get; set; } = string.Empty; + + [SugarColumn(Length = 256, IsNullable = true)] + public string? AddressPhone { get; set; } + + [SugarColumn(Length = 256, IsNullable = true)] + public string? BankNameAccount { get; set; } + + /// 价税合计(含税)。 + [SugarColumn(DecimalDigits = 2)] + public decimal AmountTotal { get; set; } + + /// 税率备注,默认 0.06;不拆分税额。 + [SugarColumn(DecimalDigits = 4)] + public decimal TaxRate { get; set; } = InvoiceStatusCodes.DefaultTaxRate; + + [SugarColumn(Length = 8)] + public string Currency { get; set; } = InvoiceCurrencyCodes.Cny; + + [SugarColumn(Length = 32)] + public string Status { get; set; } = InvoiceStatusCodes.Draft; + + [SugarColumn(Length = 16)] + public string ApplicantSource { get; set; } = InvoiceApplicantSourceCodes.Admin; + + [SugarColumn(Length = 64, IsNullable = true)] + public string? InvoiceCode { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? InvoiceNumber { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? InvoiceDate { get; set; } + + [SugarColumn(Length = 1024, IsNullable = true)] + public string? InvoicePdfUrl { get; set; } + + [SugarColumn(Length = 512, IsNullable = true)] + public string? Remark { get; set; } + + [SugarColumn(IsNullable = true)] + public int? ApprovalInstanceId { get; set; } + + [SugarColumn(Length = 32, IsNullable = true)] + public string? ApprovalInstanceNo { get; set; } + + [SugarColumn(Length = 512, IsNullable = true)] + public string? RejectReason { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? IssueTime { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? IssueBy { get; set; } +} diff --git a/src/Oms.Domain/FinanceAggregate/Entities/InvoiceApplyLine.cs b/src/Oms.Domain/FinanceAggregate/Entities/InvoiceApplyLine.cs new file mode 100644 index 0000000..f8a0f33 --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Entities/InvoiceApplyLine.cs @@ -0,0 +1,31 @@ +using Oms.Domain.FinanceAggregate.Consts; +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.FinanceAggregate.Entities; + +/// +/// 发票申请明细(来源占用行,金额含税)。 +/// +[SugarTable("t_invoice_apply_line")] +public class InvoiceApplyLine : OmsAuditedAggregateRoot +{ + public int InvoiceApplyId { get; set; } + + [SugarColumn(Length = 32)] + public string SourceType { get; set; } = string.Empty; + + public int SourceId { get; set; } + + [SugarColumn(Length = 64)] + public string SourceNo { get; set; } = string.Empty; + + [SugarColumn(DecimalDigits = 2)] + public decimal Amount { get; set; } + + [SugarColumn(Length = 8)] + public string Currency { get; set; } = InvoiceCurrencyCodes.Cny; + + [SugarColumn(Length = 512, IsNullable = true)] + public string? Remark { get; set; } +} diff --git a/src/Oms.Domain/FinanceAggregate/Repositories/ICustomerInvoiceProfileRepository.cs b/src/Oms.Domain/FinanceAggregate/Repositories/ICustomerInvoiceProfileRepository.cs new file mode 100644 index 0000000..447c22c --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Repositories/ICustomerInvoiceProfileRepository.cs @@ -0,0 +1,8 @@ +using Fake.Domain.Repositories; +using Oms.Domain.FinanceAggregate.Entities; + +namespace Oms.Domain.FinanceAggregate.Repositories; + +public interface ICustomerInvoiceProfileRepository : IRepository +{ +} diff --git a/src/Oms.Domain/FinanceAggregate/Repositories/IInvoiceApplyLineRepository.cs b/src/Oms.Domain/FinanceAggregate/Repositories/IInvoiceApplyLineRepository.cs new file mode 100644 index 0000000..154b875 --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Repositories/IInvoiceApplyLineRepository.cs @@ -0,0 +1,11 @@ +using Fake.Domain.Repositories; +using Oms.Domain.FinanceAggregate.Entities; + +namespace Oms.Domain.FinanceAggregate.Repositories; + +public interface IInvoiceApplyLineRepository : IRepository +{ + Task> GetListByApplyIdAsync( + int invoiceApplyId, + CancellationToken cancellationToken = default); +} diff --git a/src/Oms.Domain/FinanceAggregate/Repositories/IInvoiceApplyRepository.cs b/src/Oms.Domain/FinanceAggregate/Repositories/IInvoiceApplyRepository.cs new file mode 100644 index 0000000..dd6d688 --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Repositories/IInvoiceApplyRepository.cs @@ -0,0 +1,11 @@ +using Fake.Domain.Repositories; +using Oms.Domain.FinanceAggregate.Entities; + +namespace Oms.Domain.FinanceAggregate.Repositories; + +public interface IInvoiceApplyRepository : IRepository +{ + Task ExistsApplyNoAsync(string applyNo, CancellationToken cancellationToken = default); + + Task GetByApplyNoAsync(string applyNo, CancellationToken cancellationToken = default); +} diff --git a/src/Oms.SqlSugarCore/Finance/CustomerInvoiceProfileRepository.cs b/src/Oms.SqlSugarCore/Finance/CustomerInvoiceProfileRepository.cs new file mode 100644 index 0000000..fbdb53c --- /dev/null +++ b/src/Oms.SqlSugarCore/Finance/CustomerInvoiceProfileRepository.cs @@ -0,0 +1,11 @@ +using Fake.DependencyInjection; +using Oms.Domain.FinanceAggregate.Entities; +using Oms.Domain.FinanceAggregate.Repositories; +using Oms.SqlSugarCore.Repositories; + +namespace Oms.SqlSugarCore.Finance; + +public class CustomerInvoiceProfileRepository + : OmsSqlSugarRepository, ICustomerInvoiceProfileRepository, IScopedDependency +{ +} diff --git a/src/Oms.SqlSugarCore/Finance/InvoiceApplyLineRepository.cs b/src/Oms.SqlSugarCore/Finance/InvoiceApplyLineRepository.cs new file mode 100644 index 0000000..133a805 --- /dev/null +++ b/src/Oms.SqlSugarCore/Finance/InvoiceApplyLineRepository.cs @@ -0,0 +1,17 @@ +using Fake.DependencyInjection; +using Oms.Domain.FinanceAggregate.Entities; +using Oms.Domain.FinanceAggregate.Repositories; +using Oms.SqlSugarCore.Repositories; + +namespace Oms.SqlSugarCore.Finance; + +public class InvoiceApplyLineRepository + : OmsSqlSugarRepository, IInvoiceApplyLineRepository, IScopedDependency +{ + public Task> GetListByApplyIdAsync( + int invoiceApplyId, + CancellationToken cancellationToken = default) + { + return GetListAsync(x => x.InvoiceApplyId == invoiceApplyId, cancellationToken: cancellationToken); + } +} diff --git a/src/Oms.SqlSugarCore/Finance/InvoiceApplyRepository.cs b/src/Oms.SqlSugarCore/Finance/InvoiceApplyRepository.cs new file mode 100644 index 0000000..dccc946 --- /dev/null +++ b/src/Oms.SqlSugarCore/Finance/InvoiceApplyRepository.cs @@ -0,0 +1,20 @@ +using Fake.DependencyInjection; +using Oms.Domain.FinanceAggregate.Entities; +using Oms.Domain.FinanceAggregate.Repositories; +using Oms.SqlSugarCore.Repositories; + +namespace Oms.SqlSugarCore.Finance; + +public class InvoiceApplyRepository + : OmsSqlSugarRepository, IInvoiceApplyRepository, IScopedDependency +{ + public Task ExistsApplyNoAsync(string applyNo, CancellationToken cancellationToken = default) + { + return AnyAsync(x => x.ApplyNo == applyNo, cancellationToken); + } + + public Task GetByApplyNoAsync(string applyNo, CancellationToken cancellationToken = default) + { + return FirstOrDefaultAsync(x => x.ApplyNo == applyNo, cancellationToken); + } +}