From 686bec2e5dedd84bfc1b7864257fffb3e1a5abb3 Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Sat, 21 Nov 2026 14:56:24 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=B4=A2=E5=8A=A1=E5=90=88=E5=90=8C?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E4=B8=8E=E4=BB=98=E6=AC=BE=E7=94=B3=E8=AF=B7?= =?UTF-8?q?=EF=BC=88=E5=90=AB=E4=BE=9B=E5=BA=94=E5=95=86/=E5=85=AC?= =?UTF-8?q?=E5=8F=B8=E8=B4=A6=E6=88=B7=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增合同与付款申请全链路 API、审批接入及迁移脚本;抬头列表附带客户信息便于管理端展示。 Co-authored-by: Cursor --- ...rate_finance_contract_payment_20261121.sql | 195 +++++ .../Dtos/Finance/FinanceContractDtos.cs | 164 ++++ .../Dtos/Finance/FinanceMasterDtos.cs | 145 ++++ .../Dtos/Finance/FinancePaymentDtos.cs | 200 +++++ .../Dtos/Finance/InvoiceDtos.cs | 6 + .../Approval/ApprovalOperationCatalog.cs | 6 + .../Services/Approval/README.md | 1 + .../Finance/FinanceContractService.cs | 558 ++++++++++++++ .../Services/Finance/FinanceMasterService.cs | 329 ++++++++ .../Finance/FinancePaymentApplyService.cs | 725 ++++++++++++++++++ .../Services/Finance/InvoiceService.cs | 24 +- .../Finance/PaymentApplyApprovalHandler.cs | 150 ++++ .../System/SystemOtherConfigService.cs | 2 +- .../ApprovalAggregate/Consts/ApprovalCodes.cs | 3 + .../Consts/FinanceContractCodes.cs | 168 ++++ .../Entities/FinanceCompanyAccount.cs | 31 + .../Entities/FinanceContract.cs | 85 ++ .../Entities/FinancePaymentApply.cs | 80 ++ .../Entities/FinancePaymentApplyLine.cs | 25 + .../Entities/FinanceSupplier.cs | 44 ++ .../IFinanceContractRepositories.cs | 38 + .../Finance/FinanceContractRepositories.cs | 91 +++ 22 files changed, 3066 insertions(+), 4 deletions(-) create mode 100644 sql/migrate_finance_contract_payment_20261121.sql create mode 100644 src/Oms.Application/Dtos/Finance/FinanceContractDtos.cs create mode 100644 src/Oms.Application/Dtos/Finance/FinanceMasterDtos.cs create mode 100644 src/Oms.Application/Dtos/Finance/FinancePaymentDtos.cs create mode 100644 src/Oms.Application/Services/Finance/FinanceContractService.cs create mode 100644 src/Oms.Application/Services/Finance/FinanceMasterService.cs create mode 100644 src/Oms.Application/Services/Finance/FinancePaymentApplyService.cs create mode 100644 src/Oms.Application/Services/Finance/PaymentApplyApprovalHandler.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Consts/FinanceContractCodes.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Entities/FinanceCompanyAccount.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Entities/FinanceContract.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Entities/FinancePaymentApply.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Entities/FinancePaymentApplyLine.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Entities/FinanceSupplier.cs create mode 100644 src/Oms.Domain/FinanceAggregate/Repositories/IFinanceContractRepositories.cs create mode 100644 src/Oms.SqlSugarCore/Finance/FinanceContractRepositories.cs diff --git a/sql/migrate_finance_contract_payment_20261121.sql b/sql/migrate_finance_contract_payment_20261121.sql new file mode 100644 index 0000000..9c02b8a --- /dev/null +++ b/sql/migrate_finance_contract_payment_20261121.sql @@ -0,0 +1,195 @@ +# migrate_finance_contract_payment_20261121.sql +# 财务:供应商、公司收付款账户、合同、付款申请(可重复执行) +# no UNIQUE KEY;编码/单号唯一性在 Application 校验 + +SET NAMES utf8mb4; +SET @db := DATABASE(); + +# t_finance_supplier +SET @tbl := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_finance_supplier' +); +SET @sql := IF( + @tbl = 0, + 'CREATE TABLE `t_finance_supplier` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键'', + `SupplierCode` VARCHAR(32) NOT NULL COMMENT ''供应商编码'', + `SupplierName` VARCHAR(128) NOT NULL COMMENT ''供应商名称'', + `ContactName` VARCHAR(64) NULL COMMENT ''联系人'', + `Phone` VARCHAR(32) NULL COMMENT ''电话'', + `Email` VARCHAR(128) NULL COMMENT ''邮箱'', + `BankAccountName` VARCHAR(128) NULL COMMENT ''收款户名'', + `BankName` VARCHAR(128) NULL COMMENT ''开户行'', + `BankAccountNo` VARCHAR(64) NULL COMMENT ''银行账号'', + `Currency` VARCHAR(8) NOT NULL DEFAULT ''CNY'' COMMENT ''默认币种'', + `Status` TINYINT NOT NULL DEFAULT 2 COMMENT ''1-停用 2-启用'', + `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_fin_supplier_code` (`SupplierCode`), + KEY `ix_fin_supplier_name` (`SupplierName`) + ) COMMENT=''财务供应商''', + 'SELECT 1' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +# t_finance_company_account +SET @tbl := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_finance_company_account' +); +SET @sql := IF( + @tbl = 0, + 'CREATE TABLE `t_finance_company_account` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键'', + `AccountName` VARCHAR(128) NOT NULL COMMENT ''账户名称/户名'', + `BankName` VARCHAR(128) NOT NULL COMMENT ''开户行'', + `AccountNo` VARCHAR(64) NOT NULL COMMENT ''银行账号'', + `Currency` VARCHAR(8) NOT NULL DEFAULT ''CNY'' COMMENT ''币种'', + `IsDefault` TINYINT NOT NULL DEFAULT 0 COMMENT ''是否默认:0-否,1-是'', + `Status` TINYINT NOT NULL DEFAULT 2 COMMENT ''1-停用 2-启用'', + `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_fin_co_account_no` (`AccountNo`) + ) COMMENT=''公司收付款账户''', + 'SELECT 1' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +# t_finance_contract +SET @tbl := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_finance_contract' +); +SET @sql := IF( + @tbl = 0, + 'CREATE TABLE `t_finance_contract` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键'', + `ContractNo` VARCHAR(32) NOT NULL COMMENT ''合同编号 CTR+yyyyMMdd+序号'', + `ContractName` VARCHAR(128) NOT NULL COMMENT ''合同名称'', + `PartyType` VARCHAR(16) NOT NULL COMMENT ''对方类型:customer/supplier/agent'', + `PartyId` INT NOT NULL COMMENT ''对方 Id'', + `OurEntityName` VARCHAR(128) NULL COMMENT ''我方签约主体'', + `SignDate` DATETIME NULL COMMENT ''签订日期'', + `EffectiveDate` DATETIME NOT NULL COMMENT ''生效日期'', + `ExpireDate` DATETIME NULL COMMENT ''到期日期'', + `AutoRenew` TINYINT NOT NULL DEFAULT 0 COMMENT ''是否自动续签:0-否,1-是'', + `SettlementMethod` VARCHAR(16) NOT NULL DEFAULT ''monthly'' COMMENT ''结算方式:prepaid/ticket/monthly/biweekly'', + `PaymentTermDays` INT NOT NULL DEFAULT 30 COMMENT ''账期天数'', + `BillingDay` INT NULL COMMENT ''账单日(1-28)'', + `PaymentDay` INT NULL COMMENT ''约定付款日(1-28)'', + `Currency` VARCHAR(8) NOT NULL DEFAULT ''CNY'' COMMENT ''币种'', + `CreditLimit` DECIMAL(18,2) NULL COMMENT ''客户信用额度(客户合同)'', + `CommissionBaseType` VARCHAR(32) NULL COMMENT ''代理佣金基数:freight/receivable'', + `CommissionRate` DECIMAL(10,4) NULL COMMENT ''代理佣金比例'', + `RequireVendorInvoice` TINYINT NOT NULL DEFAULT 0 COMMENT ''供应商须先有进项发票才付款'', + `OwnerUserId` INT NULL COMMENT ''负责人用户 Id'', + `OwnerName` VARCHAR(64) NULL COMMENT ''负责人姓名快照'', + `Status` VARCHAR(16) NOT NULL DEFAULT ''draft'' COMMENT ''draft/active/expired/terminated'', + `AttachmentUrls` VARCHAR(2048) NULL COMMENT ''附件 URL,逗号分隔'', + `Remark` VARCHAR(512) NULL COMMENT ''备注'', + `RenewedFromId` INT NULL COMMENT ''续签来源合同 Id'', + `TerminatedTime` DATETIME NULL COMMENT ''终止时间'', + `TerminateReason` 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_fin_contract_no` (`ContractNo`), + KEY `ix_fin_contract_party` (`PartyType`, `PartyId`), + KEY `ix_fin_contract_status` (`Status`), + KEY `ix_fin_contract_expire` (`ExpireDate`) + ) COMMENT=''财务合同''', + 'SELECT 1' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +# t_finance_payment_apply +SET @tbl := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_finance_payment_apply' +); +SET @sql := IF( + @tbl = 0, + 'CREATE TABLE `t_finance_payment_apply` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键'', + `ApplyNo` VARCHAR(32) NOT NULL COMMENT ''申请单号 PAY+yyyyMMdd+序号'', + `PaymentType` VARCHAR(32) NOT NULL COMMENT ''supplier/agentCommission/customerRefund/other'', + `PayeeType` VARCHAR(16) NOT NULL COMMENT ''收款方类型:customer/supplier/agent'', + `PayeeId` INT NOT NULL COMMENT ''收款方 Id'', + `ContractId` INT NULL COMMENT ''关联合同 Id'', + `Currency` VARCHAR(8) NOT NULL DEFAULT ''CNY'' COMMENT ''币种'', + `AmountTotal` DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT ''申请金额'', + `ExpectPayDate` DATETIME NULL COMMENT ''期望付款日'', + `PayeeAccountName` VARCHAR(128) NULL COMMENT ''收款户名'', + `PayeeBankName` VARCHAR(128) NULL COMMENT ''收款开户行'', + `PayeeAccountNo` VARCHAR(64) NULL COMMENT ''收款账号'', + `CompanyAccountId` INT NULL COMMENT ''付款公司账户 Id'', + `Status` VARCHAR(32) NOT NULL DEFAULT ''draft'' COMMENT ''draft/pendingApproval/pendingPay/paid/rejected'', + `ApplicantName` VARCHAR(64) NULL COMMENT ''申请人姓名快照'', + `AttachmentUrls` VARCHAR(2048) NULL COMMENT ''附件 URL,逗号分隔'', + `Remark` VARCHAR(512) NULL COMMENT ''备注'', + `ApprovalInstanceId` INT NULL COMMENT ''审批实例 Id'', + `ApprovalInstanceNo` VARCHAR(32) NULL COMMENT ''审批单号'', + `RejectReason` VARCHAR(512) NULL COMMENT ''驳回原因'', + `PaidTime` DATETIME NULL COMMENT ''实际付款时间'', + `BankTxnNo` VARCHAR(64) NULL COMMENT ''银行流水号'', + `PaidBy` VARCHAR(64) NULL COMMENT ''登记付款人'', + `PaidVoucherUrl` VARCHAR(1024) NULL COMMENT ''付款凭证 URL'', + `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_fin_pay_apply_no` (`ApplyNo`), + KEY `ix_fin_pay_payee` (`PayeeType`, `PayeeId`), + KEY `ix_fin_pay_status` (`Status`), + KEY `ix_fin_pay_contract` (`ContractId`) + ) COMMENT=''付款申请''', + 'SELECT 1' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +# t_finance_payment_apply_line +SET @tbl := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_finance_payment_apply_line' +); +SET @sql := IF( + @tbl = 0, + 'CREATE TABLE `t_finance_payment_apply_line` ( + `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键'', + `PaymentApplyId` INT NOT NULL COMMENT ''付款申请 Id'', + `Description` VARCHAR(256) NOT NULL COMMENT ''费用说明'', + `Amount` DECIMAL(18,2) NOT NULL DEFAULT 0.00 COMMENT ''金额'', + `RefNo` VARCHAR(64) 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`), + KEY `ix_fin_pay_line_apply` (`PaymentApplyId`) + ) COMMENT=''付款申请明细''', + 'SELECT 1' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/src/Oms.Application/Dtos/Finance/FinanceContractDtos.cs b/src/Oms.Application/Dtos/Finance/FinanceContractDtos.cs new file mode 100644 index 0000000..c30f5c4 --- /dev/null +++ b/src/Oms.Application/Dtos/Finance/FinanceContractDtos.cs @@ -0,0 +1,164 @@ +namespace Oms.Application.Dtos.Finance; + +/// 合同列表查询。 +public class FinanceContractListInput +{ + public int Page { get; set; } = 1; + + public int PageSize { get; set; } = 50; + + /// 对方类型。 + public string? PartyType { get; set; } + + public int? PartyId { get; set; } + + /// 状态;或 tab 值 expiringSoon。 + public string? Status { get; set; } + + public string? Keyword { get; set; } + + public DateTime? SignStartTime { get; set; } + + public DateTime? SignEndTime { get; set; } +} + +/// 合同保存。 +public class FinanceContractSaveInput +{ + public int? Id { get; set; } + + public string ContractName { get; set; } = string.Empty; + + public string PartyType { get; set; } = string.Empty; + + public int PartyId { get; set; } + + public string? OurEntityName { get; set; } + + public DateTime? SignDate { get; set; } + + public DateTime EffectiveDate { get; set; } + + public DateTime? ExpireDate { get; set; } + + public bool AutoRenew { get; set; } + + public string SettlementMethod { get; set; } = "monthly"; + + public int PaymentTermDays { get; set; } = 30; + + public int? BillingDay { get; set; } + + public int? PaymentDay { get; set; } + + public string? Currency { get; set; } + + public decimal? CreditLimit { get; set; } + + public string? CommissionBaseType { get; set; } + + public decimal? CommissionRate { get; set; } + + public bool RequireVendorInvoice { get; set; } + + public int? OwnerUserId { get; set; } + + public string? OwnerName { get; set; } + + public string? AttachmentUrls { get; set; } + + public string? Remark { get; set; } + + /// 保存后直接生效。 + public bool Activate { get; set; } +} + +/// 合同 Id 入参。 +public class FinanceContractIdInput +{ + public int Id { get; set; } +} + +/// 终止合同。 +public class FinanceContractTerminateInput +{ + public int Id { get; set; } + + public string? Reason { get; set; } +} + +/// 合同输出。 +public class FinanceContractOutput +{ + public int Id { get; set; } + + public string ContractNo { get; set; } = string.Empty; + + public string ContractName { get; set; } = string.Empty; + + public string PartyType { get; set; } = string.Empty; + + public string PartyTypeName { get; set; } = string.Empty; + + public int PartyId { get; set; } + + public string? PartyCode { get; set; } + + public string? PartyName { get; set; } + + public string? OurEntityName { get; set; } + + public DateTime? SignDate { get; set; } + + public DateTime EffectiveDate { get; set; } + + public DateTime? ExpireDate { get; set; } + + public bool AutoRenew { get; set; } + + public string SettlementMethod { get; set; } = string.Empty; + + public string SettlementMethodName { get; set; } = string.Empty; + + public int PaymentTermDays { get; set; } + + public int? BillingDay { get; set; } + + public int? PaymentDay { get; set; } + + public string Currency { get; set; } = "CNY"; + + public decimal? CreditLimit { get; set; } + + public string? CommissionBaseType { get; set; } + + public decimal? CommissionRate { get; set; } + + public bool RequireVendorInvoice { get; set; } + + public int? OwnerUserId { get; set; } + + public string? OwnerName { get; set; } + + public string Status { get; set; } = string.Empty; + + public string StatusName { get; set; } = string.Empty; + + public string? AttachmentUrls { get; set; } + + public int AttachmentCount { get; set; } + + public string? Remark { get; set; } + + public int? RenewedFromId { get; set; } + + public DateTime? TerminatedTime { get; set; } + + public string? TerminateReason { get; set; } + + public bool ExpiringSoon { get; set; } + + public DateTime CreateTime { get; set; } + + public DateTime? UpdateTime { get; set; } +} diff --git a/src/Oms.Application/Dtos/Finance/FinanceMasterDtos.cs b/src/Oms.Application/Dtos/Finance/FinanceMasterDtos.cs new file mode 100644 index 0000000..65828f1 --- /dev/null +++ b/src/Oms.Application/Dtos/Finance/FinanceMasterDtos.cs @@ -0,0 +1,145 @@ +namespace Oms.Application.Dtos.Finance; + +/// 供应商列表查询。 +public class FinanceSupplierListInput +{ + /// 关键词:编码/名称。 + public string? Keyword { get; set; } + + /// 状态:1 停用 / 2 启用;空=全部。 + public byte? Status { get; set; } + + public int Page { get; set; } = 1; + + public int PageSize { get; set; } = 50; +} + +/// 供应商保存。 +public class FinanceSupplierSaveInput +{ + public int? Id { get; set; } + + /// 编码;新建必填。 + public string SupplierCode { get; set; } = string.Empty; + + public string SupplierName { get; set; } = string.Empty; + + public string? ContactName { get; set; } + + public string? Phone { get; set; } + + public string? Email { get; set; } + + public string? BankAccountName { get; set; } + + public string? BankName { get; set; } + + public string? BankAccountNo { get; set; } + + public string? Currency { get; set; } + + /// 1 停用 / 2 启用。 + public byte? Status { get; set; } + + public string? Remark { get; set; } +} + +/// 供应商输出。 +public class FinanceSupplierOutput +{ + public int Id { get; set; } + + public string SupplierCode { get; set; } = string.Empty; + + public string SupplierName { get; set; } = string.Empty; + + public string? ContactName { get; set; } + + public string? Phone { get; set; } + + public string? Email { get; set; } + + public string? BankAccountName { get; set; } + + public string? BankName { get; set; } + + public string? BankAccountNo { get; set; } + + public string Currency { get; set; } = "CNY"; + + public byte Status { get; set; } + + public string? Remark { get; set; } + + public DateTime CreateTime { get; set; } + + public DateTime? UpdateTime { get; set; } +} + +/// 供应商删除。 +public class FinanceSupplierDeleteInput +{ + public int Id { get; set; } +} + +/// 公司账户列表查询。 +public class FinanceCompanyAccountListInput +{ + public string? Keyword { get; set; } + + public byte? Status { get; set; } + + public int Page { get; set; } = 1; + + public int PageSize { get; set; } = 50; +} + +/// 公司账户保存。 +public class FinanceCompanyAccountSaveInput +{ + public int? Id { get; set; } + + public string AccountName { get; set; } = string.Empty; + + public string BankName { get; set; } = string.Empty; + + public string AccountNo { get; set; } = string.Empty; + + public string? Currency { get; set; } + + public bool IsDefault { get; set; } + + public byte? Status { get; set; } + + public string? Remark { get; set; } +} + +/// 公司账户输出。 +public class FinanceCompanyAccountOutput +{ + public int Id { get; set; } + + public string AccountName { get; set; } = string.Empty; + + public string BankName { get; set; } = string.Empty; + + public string AccountNo { get; set; } = string.Empty; + + public string Currency { get; set; } = "CNY"; + + public bool IsDefault { get; set; } + + public byte Status { get; set; } + + public string? Remark { get; set; } + + public DateTime CreateTime { get; set; } + + public DateTime? UpdateTime { get; set; } +} + +/// 公司账户删除。 +public class FinanceCompanyAccountDeleteInput +{ + public int Id { get; set; } +} diff --git a/src/Oms.Application/Dtos/Finance/FinancePaymentDtos.cs b/src/Oms.Application/Dtos/Finance/FinancePaymentDtos.cs new file mode 100644 index 0000000..edadc1b --- /dev/null +++ b/src/Oms.Application/Dtos/Finance/FinancePaymentDtos.cs @@ -0,0 +1,200 @@ +namespace Oms.Application.Dtos.Finance; + +/// 付款申请列表查询。 +public class FinancePaymentApplyListInput +{ + public int Page { get; set; } = 1; + + public int PageSize { get; set; } = 50; + + public string? Status { get; set; } + + public string? PaymentType { get; set; } + + public string? PayeeType { get; set; } + + public int? PayeeId { get; set; } + + public string? Currency { get; set; } + + public string? Keyword { get; set; } + + public DateTime? StartTime { get; set; } + + public DateTime? EndTime { get; set; } +} + +/// 付款申请明细行入参。 +public class FinancePaymentApplyLineInput +{ + public string Description { get; set; } = string.Empty; + + public decimal Amount { get; set; } + + public string? RefNo { get; set; } + + public string? Remark { get; set; } +} + +/// 付款申请保存。 +public class FinancePaymentApplySaveInput +{ + public int? Id { get; set; } + + public string PaymentType { get; set; } = string.Empty; + + public int PayeeId { get; set; } + + public int? ContractId { get; set; } + + public string? Currency { get; set; } + + public DateTime? ExpectPayDate { get; set; } + + public string? PayeeAccountName { get; set; } + + public string? PayeeBankName { get; set; } + + public string? PayeeAccountNo { get; set; } + + public int? CompanyAccountId { get; set; } + + public string? AttachmentUrls { get; set; } + + public string? Remark { get; set; } + + /// 保存后提交审批。 + public bool Submit { get; set; } + + public List Lines { get; set; } = []; +} + +/// 付款申请 Id。 +public class FinancePaymentApplyIdInput +{ + public int Id { get; set; } +} + +/// 登记付款。 +public class FinancePaymentMarkPaidInput +{ + public int Id { get; set; } + + public DateTime? PaidTime { get; set; } + + public string? BankTxnNo { get; set; } + + public string? PaidVoucherUrl { get; set; } + + public string? Remark { get; set; } +} + +/// 付款申请明细输出。 +public class FinancePaymentApplyLineOutput +{ + public int Id { get; set; } + + public string Description { get; set; } = string.Empty; + + public decimal Amount { get; set; } + + public string? RefNo { get; set; } + + public string? Remark { get; set; } +} + +/// 付款申请输出。 +public class FinancePaymentApplyOutput +{ + public int Id { get; set; } + + public string ApplyNo { get; set; } = string.Empty; + + public string PaymentType { get; set; } = string.Empty; + + public string PaymentTypeName { get; set; } = string.Empty; + + public string PayeeType { get; set; } = string.Empty; + + public string PayeeTypeName { get; set; } = string.Empty; + + public int PayeeId { get; set; } + + public string? PayeeCode { get; set; } + + public string? PayeeName { get; set; } + + public int? ContractId { get; set; } + + public string? ContractNo { get; set; } + + public string Currency { get; set; } = "CNY"; + + public decimal AmountTotal { get; set; } + + public DateTime? ExpectPayDate { get; set; } + + public string? PayeeAccountName { get; set; } + + public string? PayeeBankName { get; set; } + + public string? PayeeAccountNo { get; set; } + + public int? CompanyAccountId { get; set; } + + public string? CompanyAccountName { get; set; } + + public string Status { get; set; } = string.Empty; + + public string StatusName { get; set; } = string.Empty; + + public string? ApplicantName { get; set; } + + public string? AttachmentUrls { get; set; } + + public string? Remark { get; set; } + + public int? ApprovalInstanceId { get; set; } + + public string? ApprovalInstanceNo { get; set; } + + public bool ApprovalPending { get; set; } + + public string? RejectReason { get; set; } + + public DateTime? PaidTime { get; set; } + + public string? BankTxnNo { get; set; } + + public string? PaidBy { get; set; } + + public string? PaidVoucherUrl { get; set; } + + public DateTime CreateTime { get; set; } + + public DateTime? UpdateTime { get; set; } + + public string? Decision { get; set; } + + public string? Message { get; set; } + + public List Lines { get; set; } = []; +} + +/// 付款申请汇总。 +public class FinancePaymentApplySummaryOutput +{ + public List Items { get; set; } = []; +} + +/// 付款申请汇总项(按币种)。 +public class FinancePaymentApplySummaryItemOutput +{ + public string Currency { get; set; } = "CNY"; + + public decimal PendingApprovalAmount { get; set; } + + public decimal PendingPayAmount { get; set; } + + public decimal PaidThisMonthAmount { get; set; } +} diff --git a/src/Oms.Application/Dtos/Finance/InvoiceDtos.cs b/src/Oms.Application/Dtos/Finance/InvoiceDtos.cs index d1f4174..66215c8 100644 --- a/src/Oms.Application/Dtos/Finance/InvoiceDtos.cs +++ b/src/Oms.Application/Dtos/Finance/InvoiceDtos.cs @@ -50,6 +50,12 @@ public class InvoiceProfileOutput /// 客户主键。 public int CustomerId { get; set; } + /// 客户编码(列表展示用)。 + public string? CustomerCode { get; set; } + + /// 客户名称(列表展示用)。 + public string? CustomerName { get; set; } + /// 发票抬头。 public string TitleName { get; set; } = string.Empty; diff --git a/src/Oms.Application/Services/Approval/ApprovalOperationCatalog.cs b/src/Oms.Application/Services/Approval/ApprovalOperationCatalog.cs index 47b63f5..4f23dcd 100644 --- a/src/Oms.Application/Services/Approval/ApprovalOperationCatalog.cs +++ b/src/Oms.Application/Services/Approval/ApprovalOperationCatalog.cs @@ -37,6 +37,12 @@ public static class ApprovalOperationCatalog "Finance", SupportsCondition: false, ConditionHint: "已接入提交接口;未配置或未启用不拦截(直接通过),启用后提交审批"), + new( + ApprovalCodes.FinancePaymentApply, + "付款申请", + "Finance", + SupportsCondition: false, + ConditionHint: "已接入提交接口;未配置或未启用不拦截(直接待付款),启用后提交审批"), new( "Marketing.Commission.Withdraw", "佣金提现", diff --git a/src/Oms.Application/Services/Approval/README.md b/src/Oms.Application/Services/Approval/README.md index b24c795..06918c8 100644 --- a/src/Oms.Application/Services/Approval/README.md +++ b/src/Oms.Application/Services/Approval/README.md @@ -12,5 +12,6 @@ 已接入: - `Channel.SalesProduct.PublishPrice`(`/channel/sales-product/publish`,operatorType=price)。未配置/未启用 Bypass 直接发布;启用后由 `SalesProductPricePublishApprovalHandler` 落发布记录。 - `Finance.Recharge.Credit`(`/recharge/recharge/submit`)。未配置/未启用 Bypass 直接入账;启用后建单,终审由 `RechargeCreditApprovalHandler` 入账,驳回/撤回同步充值记录为驳回。 +- `Finance.Payment.Apply`(`/finance/payment-apply/submit`)。未配置/未启用 Bypass 直接待付款;启用后建单,终审由 `PaymentApplyApprovalHandler` 置为待付款,驳回/撤回同步申请状态。 联调也可用「模拟提交」+ 操作码 `System.Approval.Simulate`。 diff --git a/src/Oms.Application/Services/Finance/FinanceContractService.cs b/src/Oms.Application/Services/Finance/FinanceContractService.cs new file mode 100644 index 0000000..9c5a756 --- /dev/null +++ b/src/Oms.Application/Services/Finance/FinanceContractService.cs @@ -0,0 +1,558 @@ +using System.Linq.Expressions; +using Fake.Application; +using Fake.Domain.Exceptions; +using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Finance; +using Oms.Application.Dtos.Shared; +using Oms.Application.Shared; +using Oms.Domain.AgentsAggregate.Repositories; +using Oms.Domain.CustomersAggregate.Repositories; +using Oms.Domain.FinanceAggregate.Consts; +using Oms.Domain.FinanceAggregate.Entities; +using Oms.Domain.FinanceAggregate.Repositories; + +namespace Oms.Application.Services.Finance; + +/// +/// 财务合同管理(客户 / 供应商 / 代理)。 +/// +[ApiExplorerSettings(GroupName = "OMS-Finance")] +public class FinanceContractService : ApplicationService +{ + private IFinanceContractRepository ContractRepository => + LazyServiceProvider.GetRequiredService(); + + private IFinanceSupplierRepository SupplierRepository => + LazyServiceProvider.GetRequiredService(); + + private ICustomerRepository CustomerRepository => + LazyServiceProvider.GetRequiredService(); + + private IAgentRepository AgentRepository => + LazyServiceProvider.GetRequiredService(); + + /// + /// 分页查询合同。 + /// + [HttpGet("/finance/contract/list")] + public async Task> GetListAsync([FromQuery] FinanceContractListInput input) + { + await RefreshExpiredContractsAsync(); + var predicate = BuildListPredicate(input); + var page = OmsDocHelper.NormalizePage(input.Page); + var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); + var entities = await ContractRepository.GetPagedListAsync( + predicate, + page, + pageSize, + new Dictionary + { + [nameof(FinanceContract.CreateTime)] = false, + [nameof(FinanceContract.Id)] = false + }); + var total = await ContractRepository.CountAsync(predicate); + var items = await MapListAsync(entities); + return new OmsPageResult + { + Items = items, + Total = total + }; + } + + /// + /// 合同详情。 + /// + [HttpGet("/finance/contract/detail")] + public async Task GetDetailAsync([FromQuery] int id) + { + await RefreshExpiredContractsAsync(); + var entity = await ContractRepository.FirstOrDefaultAsync(x => x.Id == id) + ?? throw new BusinessException("合同不存在"); + var list = await MapListAsync([entity]); + return list[0]; + } + + /// + /// 按对方查询当前生效合同(付款申请带出)。 + /// + [HttpGet("/finance/contract/active-by-party")] + public async Task GetActiveByPartyAsync( + [FromQuery] string partyType, + [FromQuery] int partyId) + { + await RefreshExpiredContractsAsync(); + if (!FinancePartyTypeCodes.IsKnown(partyType) || partyId <= 0) + { + return null; + } + + var entity = await ContractRepository.GetActiveByPartyAsync(partyType.Trim(), partyId); + if (entity == null) + { + return null; + } + + var list = await MapListAsync([entity]); + return list[0]; + } + + /// + /// 保存合同(草稿;可勾选 Activate 直接生效)。 + /// + [HttpPost("/finance/contract/save")] + public async Task SaveAsync(FinanceContractSaveInput input) + { + ValidateSaveInput(input); + await EnsurePartyExistsAsync(input.PartyType, input.PartyId); + + FinanceContract entity; + if (input.Id is > 0) + { + entity = await ContractRepository.FirstOrDefaultAsync(x => x.Id == input.Id.Value) + ?? throw new BusinessException("合同不存在"); + if (entity.Status is not (FinanceContractStatusCodes.Draft or FinanceContractStatusCodes.Active)) + { + throw new BusinessException("仅草稿或生效合同可编辑"); + } + + if (entity.Status == FinanceContractStatusCodes.Active + && (entity.PartyType != input.PartyType.Trim() || entity.PartyId != input.PartyId)) + { + throw new BusinessException("生效合同不可更换对方"); + } + } + else + { + entity = new FinanceContract + { + ContractNo = await GenerateContractNoAsync(), + Status = FinanceContractStatusCodes.Draft + }; + } + + ApplySaveFields(entity, input); + + if (input.Id is > 0) + { + await ContractRepository.UpdateAsync(entity); + } + else + { + entity = await ContractRepository.InsertAsync(entity); + } + + if (input.Activate) + { + await ActivateCoreAsync(entity); + } + + return (await MapListAsync([entity]))[0]; + } + + /// + /// 生效合同。同一对方同时仅允许一份生效合同。 + /// + [HttpPost("/finance/contract/activate")] + public async Task ActivateAsync(FinanceContractIdInput input) + { + var entity = await ContractRepository.FirstOrDefaultAsync(x => x.Id == input.Id) + ?? throw new BusinessException("合同不存在"); + if (entity.Status != FinanceContractStatusCodes.Draft) + { + throw new BusinessException("仅草稿合同可生效"); + } + + await ActivateCoreAsync(entity); + return (await MapListAsync([entity]))[0]; + } + + /// + /// 续签:复制条款生成新草稿。 + /// + [HttpPost("/finance/contract/renew")] + public async Task RenewAsync(FinanceContractIdInput input) + { + var source = await ContractRepository.FirstOrDefaultAsync(x => x.Id == input.Id) + ?? throw new BusinessException("合同不存在"); + if (source.Status is FinanceContractStatusCodes.Terminated) + { + throw new BusinessException("已终止合同不可续签"); + } + + var entity = new FinanceContract + { + ContractNo = await GenerateContractNoAsync(), + ContractName = source.ContractName, + PartyType = source.PartyType, + PartyId = source.PartyId, + OurEntityName = source.OurEntityName, + SignDate = DateTime.Now.Date, + EffectiveDate = source.ExpireDate?.Date.AddDays(1) ?? DateTime.Now.Date, + ExpireDate = source.ExpireDate.HasValue + ? source.ExpireDate.Value.AddYears(1) + : DateTime.Now.Date.AddYears(1), + AutoRenew = source.AutoRenew, + SettlementMethod = source.SettlementMethod, + PaymentTermDays = source.PaymentTermDays, + BillingDay = source.BillingDay, + PaymentDay = source.PaymentDay, + Currency = source.Currency, + CreditLimit = source.CreditLimit, + CommissionBaseType = source.CommissionBaseType, + CommissionRate = source.CommissionRate, + RequireVendorInvoice = source.RequireVendorInvoice, + OwnerUserId = source.OwnerUserId, + OwnerName = source.OwnerName, + Status = FinanceContractStatusCodes.Draft, + Remark = source.Remark, + RenewedFromId = source.Id + }; + entity = await ContractRepository.InsertAsync(entity); + return (await MapListAsync([entity]))[0]; + } + + /// + /// 终止合同。 + /// + [HttpPost("/finance/contract/terminate")] + public async Task TerminateAsync(FinanceContractTerminateInput input) + { + var entity = await ContractRepository.FirstOrDefaultAsync(x => x.Id == input.Id) + ?? throw new BusinessException("合同不存在"); + if (entity.Status is FinanceContractStatusCodes.Terminated or FinanceContractStatusCodes.Expired) + { + throw new BusinessException("合同已结束,无需终止"); + } + + entity.Status = FinanceContractStatusCodes.Terminated; + entity.TerminatedTime = DateTime.Now; + entity.TerminateReason = string.IsNullOrWhiteSpace(input.Reason) ? null : input.Reason.Trim(); + await ContractRepository.UpdateAsync(entity); + return (await MapListAsync([entity]))[0]; + } + + private async Task ActivateCoreAsync(FinanceContract entity) + { + var existing = await ContractRepository.GetActiveByPartyAsync( + entity.PartyType, + entity.PartyId, + entity.Id); + if (existing != null) + { + throw new BusinessException($"该对方已有生效合同 {existing.ContractNo},请先终止或到期后再生效"); + } + + if (entity.ExpireDate.HasValue && entity.ExpireDate.Value.Date < DateTime.Now.Date) + { + throw new BusinessException("到期日早于今天,无法生效"); + } + + entity.Status = FinanceContractStatusCodes.Active; + entity.TerminatedTime = null; + entity.TerminateReason = null; + await ContractRepository.UpdateAsync(entity); + + if (entity.PartyType == FinancePartyTypeCodes.Customer && entity.CreditLimit is >= 0) + { + var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == entity.PartyId); + if (customer != null) + { + customer.TotalQuota = entity.CreditLimit.Value; + await CustomerRepository.UpdateAsync(customer); + } + } + } + + private async Task RefreshExpiredContractsAsync() + { + var today = DateTime.Now.Date; + var actives = await ContractRepository.GetListAsync(x => + x.Status == FinanceContractStatusCodes.Active + && x.ExpireDate != null + && x.ExpireDate < today); + foreach (var item in actives) + { + item.Status = FinanceContractStatusCodes.Expired; + await ContractRepository.UpdateAsync(item); + } + } + + private static void ValidateSaveInput(FinanceContractSaveInput input) + { + if (string.IsNullOrWhiteSpace(input.ContractName)) + { + throw new BusinessException("合同名称不能为空"); + } + + if (!FinancePartyTypeCodes.IsKnown(input.PartyType)) + { + throw new BusinessException("对方类型无效"); + } + + if (input.PartyId <= 0) + { + throw new BusinessException("请选择对方"); + } + + if (!FinanceSettlementMethodCodes.IsKnown(input.SettlementMethod)) + { + throw new BusinessException("结算方式无效"); + } + + if (input.PaymentTermDays < 0) + { + throw new BusinessException("账期天数不能为负"); + } + + if (input.ExpireDate.HasValue && input.ExpireDate.Value.Date < input.EffectiveDate.Date) + { + throw new BusinessException("到期日不能早于生效日"); + } + } + + private async Task EnsurePartyExistsAsync(string partyType, int partyId) + { + var type = partyType.Trim(); + switch (type) + { + case FinancePartyTypeCodes.Customer: + _ = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == partyId) + ?? throw new BusinessException("客户不存在"); + break; + case FinancePartyTypeCodes.Supplier: + _ = await SupplierRepository.FirstOrDefaultAsync(x => x.Id == partyId) + ?? throw new BusinessException("供应商不存在"); + break; + case FinancePartyTypeCodes.Agent: + _ = await AgentRepository.FirstOrDefaultAsync(x => x.Id == partyId) + ?? throw new BusinessException("代理不存在"); + break; + default: + throw new BusinessException("对方类型无效"); + } + } + + private static void ApplySaveFields(FinanceContract entity, FinanceContractSaveInput input) + { + entity.ContractName = input.ContractName.Trim(); + entity.PartyType = input.PartyType.Trim(); + entity.PartyId = input.PartyId; + entity.OurEntityName = NormalizeOptional(input.OurEntityName); + entity.SignDate = input.SignDate?.Date; + entity.EffectiveDate = input.EffectiveDate.Date; + entity.ExpireDate = input.ExpireDate?.Date; + entity.AutoRenew = input.AutoRenew; + entity.SettlementMethod = input.SettlementMethod.Trim(); + entity.PaymentTermDays = input.PaymentTermDays; + entity.BillingDay = NormalizeDay(input.BillingDay); + entity.PaymentDay = NormalizeDay(input.PaymentDay); + entity.Currency = string.IsNullOrWhiteSpace(input.Currency) + ? FinanceCurrencyCodes.Cny + : input.Currency.Trim().ToUpperInvariant(); + entity.CreditLimit = input.PartyType == FinancePartyTypeCodes.Customer ? input.CreditLimit : null; + entity.CommissionBaseType = input.PartyType == FinancePartyTypeCodes.Agent + ? NormalizeOptional(input.CommissionBaseType) + : null; + entity.CommissionRate = input.PartyType == FinancePartyTypeCodes.Agent ? input.CommissionRate : null; + entity.RequireVendorInvoice = input.PartyType == FinancePartyTypeCodes.Supplier && input.RequireVendorInvoice; + entity.OwnerUserId = input.OwnerUserId is > 0 ? input.OwnerUserId : null; + entity.OwnerName = NormalizeOptional(input.OwnerName); + entity.AttachmentUrls = NormalizeOptional(input.AttachmentUrls); + entity.Remark = NormalizeOptional(input.Remark); + } + + private static int? NormalizeDay(int? day) => + day is >= 1 and <= 28 ? day : null; + + private static string? NormalizeOptional(string? value) => + string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static Expression> BuildListPredicate(FinanceContractListInput input) + { + var hasPartyType = !string.IsNullOrWhiteSpace(input.PartyType) + && input.PartyType != "all" + && input.PartyType != "expiringSoon"; + var partyType = input.PartyType?.Trim(); + var hasPartyId = input.PartyId is > 0; + var partyId = input.PartyId.GetValueOrDefault(); + var hasKeyword = !string.IsNullOrWhiteSpace(input.Keyword); + var keyword = input.Keyword?.Trim(); + var hasSignStart = input.SignStartTime.HasValue; + var signStart = input.SignStartTime; + var hasSignEnd = input.SignEndTime.HasValue; + var signEnd = input.SignEndTime; + var expiringSoon = string.Equals(input.Status, "expiringSoon", StringComparison.OrdinalIgnoreCase) + || string.Equals(input.PartyType, "expiringSoon", StringComparison.OrdinalIgnoreCase); + var endedTab = string.Equals(input.Status, "ended", StringComparison.OrdinalIgnoreCase); + var hasStatus = !string.IsNullOrWhiteSpace(input.Status) + && !expiringSoon + && !endedTab + && input.Status != "all"; + var status = input.Status?.Trim(); + var soonEnd = DateTime.Now.Date.AddDays(30); + + return x => + (!hasPartyType || x.PartyType == partyType) + && (!hasPartyId || x.PartyId == partyId) + && (!hasKeyword + || x.ContractNo.Contains(keyword!) + || x.ContractName.Contains(keyword!)) + && (!hasSignStart || (x.SignDate != null && x.SignDate >= signStart)) + && (!hasSignEnd || (x.SignDate != null && x.SignDate <= signEnd)) + && (!expiringSoon + || (x.Status == FinanceContractStatusCodes.Active + && x.ExpireDate != null + && x.ExpireDate <= soonEnd + && x.ExpireDate >= DateTime.Now.Date)) + && (!endedTab + || x.Status == FinanceContractStatusCodes.Expired + || x.Status == FinanceContractStatusCodes.Terminated) + && (!hasStatus || x.Status == status); + } + + private async Task> MapListAsync(List entities) + { + if (entities.Count == 0) + { + return []; + } + + var customerIds = entities + .Where(x => x.PartyType == FinancePartyTypeCodes.Customer) + .Select(x => x.PartyId) + .Distinct() + .ToList(); + var supplierIds = entities + .Where(x => x.PartyType == FinancePartyTypeCodes.Supplier) + .Select(x => x.PartyId) + .Distinct() + .ToList(); + var agentIds = entities + .Where(x => x.PartyType == FinancePartyTypeCodes.Agent) + .Select(x => x.PartyId) + .Distinct() + .ToList(); + + var customers = customerIds.Count == 0 + ? [] + : await CustomerRepository.GetListAsync(x => customerIds.Contains(x.Id)); + var suppliers = supplierIds.Count == 0 + ? [] + : await SupplierRepository.GetListAsync(x => supplierIds.Contains(x.Id)); + var agents = agentIds.Count == 0 + ? [] + : await AgentRepository.GetListAsync(x => agentIds.Contains(x.Id)); + + var customerMap = customers.ToDictionary(x => x.Id); + var supplierMap = suppliers.ToDictionary(x => x.Id); + var agentMap = agents.ToDictionary(x => x.Id); + var soonEnd = DateTime.Now.Date.AddDays(30); + + return entities.Select(entity => + { + string? partyCode = null; + string? partyName = null; + if (entity.PartyType == FinancePartyTypeCodes.Customer + && customerMap.TryGetValue(entity.PartyId, out var customer)) + { + partyCode = customer.CustomerCode; + partyName = customer.CustomerName; + } + else if (entity.PartyType == FinancePartyTypeCodes.Supplier + && supplierMap.TryGetValue(entity.PartyId, out var supplier)) + { + partyCode = supplier.SupplierCode; + partyName = supplier.SupplierName; + } + else if (entity.PartyType == FinancePartyTypeCodes.Agent + && agentMap.TryGetValue(entity.PartyId, out var agent)) + { + partyCode = agent.AgentCode; + partyName = agent.AgentName; + } + + var attachmentCount = CountAttachments(entity.AttachmentUrls); + return new FinanceContractOutput + { + Id = entity.Id, + ContractNo = entity.ContractNo, + ContractName = entity.ContractName, + PartyType = entity.PartyType, + PartyTypeName = FinancePartyTypeCodes.GetName(entity.PartyType), + PartyId = entity.PartyId, + PartyCode = partyCode, + PartyName = partyName, + OurEntityName = entity.OurEntityName, + SignDate = entity.SignDate, + EffectiveDate = entity.EffectiveDate, + ExpireDate = entity.ExpireDate, + AutoRenew = entity.AutoRenew, + SettlementMethod = entity.SettlementMethod, + SettlementMethodName = FinanceSettlementMethodCodes.GetName(entity.SettlementMethod), + PaymentTermDays = entity.PaymentTermDays, + BillingDay = entity.BillingDay, + PaymentDay = entity.PaymentDay, + Currency = entity.Currency, + CreditLimit = entity.CreditLimit, + CommissionBaseType = entity.CommissionBaseType, + CommissionRate = entity.CommissionRate, + RequireVendorInvoice = entity.RequireVendorInvoice, + OwnerUserId = entity.OwnerUserId, + OwnerName = entity.OwnerName, + Status = entity.Status, + StatusName = FinanceContractStatusCodes.GetName(entity.Status), + AttachmentUrls = entity.AttachmentUrls, + AttachmentCount = attachmentCount, + Remark = entity.Remark, + RenewedFromId = entity.RenewedFromId, + TerminatedTime = entity.TerminatedTime, + TerminateReason = entity.TerminateReason, + ExpiringSoon = entity.Status == FinanceContractStatusCodes.Active + && entity.ExpireDate.HasValue + && entity.ExpireDate.Value.Date <= soonEnd + && entity.ExpireDate.Value.Date >= DateTime.Now.Date, + CreateTime = entity.CreateTime, + UpdateTime = entity.UpdateTime == default ? null : entity.UpdateTime + }; + }).ToList(); + } + + private static int CountAttachments(string? urls) + { + if (string.IsNullOrWhiteSpace(urls)) + { + return 0; + } + + return urls.Split([',', ';', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Length; + } + + private async Task GenerateContractNoAsync() + { + var prefix = $"CTR{DateTime.Now:yyyyMMdd}"; + for (var i = 0; i < 10; i++) + { + var existing = await ContractRepository.GetListAsync(x => x.ContractNo.StartsWith(prefix)); + var maxSeq = 0; + foreach (var item in existing) + { + var suffix = item.ContractNo.Length > prefix.Length + ? item.ContractNo[prefix.Length..] + : string.Empty; + if (int.TryParse(suffix, out var seq) && seq > maxSeq) + { + maxSeq = seq; + } + } + + var contractNo = $"{prefix}{(maxSeq + 1):D4}"; + if (!await ContractRepository.ExistsContractNoAsync(contractNo)) + { + return contractNo; + } + } + + throw new BusinessException("合同编号生成失败"); + } +} diff --git a/src/Oms.Application/Services/Finance/FinanceMasterService.cs b/src/Oms.Application/Services/Finance/FinanceMasterService.cs new file mode 100644 index 0000000..0666350 --- /dev/null +++ b/src/Oms.Application/Services/Finance/FinanceMasterService.cs @@ -0,0 +1,329 @@ +using System.Linq.Expressions; +using Fake.Application; +using Fake.Domain.Exceptions; +using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Finance; +using Oms.Application.Dtos.Shared; +using Oms.Application.Shared; +using Oms.Domain.FinanceAggregate.Entities; +using Oms.Domain.FinanceAggregate.Repositories; +using Oms.Domain.Shared.Enums; + +namespace Oms.Application.Services.Finance; + +/// +/// 财务主数据:供应商、公司收付款账户。 +/// +[ApiExplorerSettings(GroupName = "OMS-Finance")] +public class FinanceMasterService : ApplicationService +{ + private IFinanceSupplierRepository SupplierRepository => + LazyServiceProvider.GetRequiredService(); + + private IFinanceCompanyAccountRepository CompanyAccountRepository => + LazyServiceProvider.GetRequiredService(); + + /// + /// 分页查询供应商。 + /// + [HttpGet("/finance/supplier/list")] + public async Task> GetSupplierListAsync( + [FromQuery] FinanceSupplierListInput input) + { + var predicate = BuildSupplierPredicate(input.Keyword, input.Status); + var page = OmsDocHelper.NormalizePage(input.Page); + var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); + var entities = await SupplierRepository.GetPagedListAsync( + predicate, + page, + pageSize, + new Dictionary + { + [nameof(FinanceSupplier.CreateTime)] = false, + [nameof(FinanceSupplier.Id)] = false + }); + var total = await SupplierRepository.CountAsync(predicate); + return new OmsPageResult + { + Items = entities.Select(MapSupplier).ToList(), + Total = total + }; + } + + /// + /// 供应商下拉(启用)。 + /// + [HttpGet("/finance/supplier/options")] + public async Task> GetSupplierOptionsAsync([FromQuery] string? keyword) + { + var hasKeyword = !string.IsNullOrWhiteSpace(keyword); + var kw = keyword?.Trim(); + var list = await SupplierRepository.GetListAsync(x => + x.Status == EnableStatus.Enabled + && (!hasKeyword + || x.SupplierCode.Contains(kw!) + || x.SupplierName.Contains(kw!))); + return list + .OrderBy(x => x.SupplierCode) + .Take(100) + .Select(MapSupplier) + .ToList(); + } + + /// + /// 保存供应商(新增/修改)。编码业务侧唯一校验。 + /// + [HttpPost("/finance/supplier/save")] + public async Task SaveSupplierAsync(FinanceSupplierSaveInput input) + { + if (string.IsNullOrWhiteSpace(input.SupplierName)) + { + throw new BusinessException("供应商名称不能为空"); + } + + var code = (input.SupplierCode ?? string.Empty).Trim(); + if (string.IsNullOrWhiteSpace(code)) + { + throw new BusinessException("供应商编码不能为空"); + } + + FinanceSupplier entity; + if (input.Id is > 0) + { + entity = await SupplierRepository.FirstOrDefaultAsync(x => x.Id == input.Id.Value) + ?? throw new BusinessException("供应商不存在"); + if (await SupplierRepository.ExistsCodeAsync(code, entity.Id)) + { + throw new BusinessException("供应商编码已存在"); + } + + entity.SupplierCode = code; + } + else + { + if (await SupplierRepository.ExistsCodeAsync(code)) + { + throw new BusinessException("供应商编码已存在"); + } + + entity = new FinanceSupplier { SupplierCode = code }; + } + + entity.SupplierName = input.SupplierName.Trim(); + entity.ContactName = NormalizeOptional(input.ContactName); + entity.Phone = NormalizeOptional(input.Phone); + entity.Email = NormalizeOptional(input.Email); + entity.BankAccountName = NormalizeOptional(input.BankAccountName); + entity.BankName = NormalizeOptional(input.BankName); + entity.BankAccountNo = NormalizeOptional(input.BankAccountNo); + entity.Currency = string.IsNullOrWhiteSpace(input.Currency) ? "CNY" : input.Currency.Trim().ToUpperInvariant(); + entity.Status = ResolveStatus(input.Status); + entity.Remark = NormalizeOptional(input.Remark); + + if (input.Id is > 0) + { + await SupplierRepository.UpdateAsync(entity); + } + else + { + entity = await SupplierRepository.InsertAsync(entity); + } + + return MapSupplier(entity); + } + + /// + /// 删除供应商(软删)。 + /// + [HttpPost("/finance/supplier/delete")] + public async Task DeleteSupplierAsync(FinanceSupplierDeleteInput input) + { + var entity = await SupplierRepository.FirstOrDefaultAsync(x => x.Id == input.Id) + ?? throw new BusinessException("供应商不存在"); + await SupplierRepository.DeleteAsync(entity); + } + + /// + /// 分页查询公司收付款账户。 + /// + [HttpGet("/finance/company-account/list")] + public async Task> GetCompanyAccountListAsync( + [FromQuery] FinanceCompanyAccountListInput input) + { + var predicate = BuildCompanyAccountPredicate(input.Keyword, input.Status); + var page = OmsDocHelper.NormalizePage(input.Page); + var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); + var entities = await CompanyAccountRepository.GetPagedListAsync( + predicate, + page, + pageSize, + new Dictionary + { + [nameof(FinanceCompanyAccount.IsDefault)] = false, + [nameof(FinanceCompanyAccount.Id)] = false + }); + var total = await CompanyAccountRepository.CountAsync(predicate); + return new OmsPageResult + { + Items = entities.Select(MapCompanyAccount).ToList(), + Total = total + }; + } + + /// + /// 公司账户下拉(启用)。 + /// + [HttpGet("/finance/company-account/options")] + public async Task> GetCompanyAccountOptionsAsync() + { + var list = await CompanyAccountRepository.GetListAsync(x => x.Status == EnableStatus.Enabled); + return list + .OrderByDescending(x => x.IsDefault) + .ThenBy(x => x.Id) + .Select(MapCompanyAccount) + .ToList(); + } + + /// + /// 保存公司收付款账户。 + /// + [HttpPost("/finance/company-account/save")] + public async Task SaveCompanyAccountAsync(FinanceCompanyAccountSaveInput input) + { + if (string.IsNullOrWhiteSpace(input.AccountName)) + { + throw new BusinessException("账户名称不能为空"); + } + + if (string.IsNullOrWhiteSpace(input.BankName)) + { + throw new BusinessException("开户行不能为空"); + } + + if (string.IsNullOrWhiteSpace(input.AccountNo)) + { + throw new BusinessException("银行账号不能为空"); + } + + FinanceCompanyAccount entity; + if (input.Id is > 0) + { + entity = await CompanyAccountRepository.FirstOrDefaultAsync(x => x.Id == input.Id.Value) + ?? throw new BusinessException("公司账户不存在"); + } + else + { + entity = new FinanceCompanyAccount(); + } + + entity.AccountName = input.AccountName.Trim(); + entity.BankName = input.BankName.Trim(); + entity.AccountNo = input.AccountNo.Trim(); + entity.Currency = string.IsNullOrWhiteSpace(input.Currency) ? "CNY" : input.Currency.Trim().ToUpperInvariant(); + entity.IsDefault = input.IsDefault; + entity.Status = ResolveStatus(input.Status); + entity.Remark = NormalizeOptional(input.Remark); + + if (input.Id is > 0) + { + await CompanyAccountRepository.UpdateAsync(entity); + } + else + { + entity = await CompanyAccountRepository.InsertAsync(entity); + } + + if (entity.IsDefault) + { + await ClearOtherDefaultsAsync(entity.Id); + } + + return MapCompanyAccount(entity); + } + + /// + /// 删除公司账户(软删)。 + /// + [HttpPost("/finance/company-account/delete")] + public async Task DeleteCompanyAccountAsync(FinanceCompanyAccountDeleteInput input) + { + var entity = await CompanyAccountRepository.FirstOrDefaultAsync(x => x.Id == input.Id) + ?? throw new BusinessException("公司账户不存在"); + await CompanyAccountRepository.DeleteAsync(entity); + } + + private async Task ClearOtherDefaultsAsync(int keepId) + { + var others = await CompanyAccountRepository.GetListAsync(x => x.IsDefault && x.Id != keepId); + foreach (var item in others) + { + item.IsDefault = false; + await CompanyAccountRepository.UpdateAsync(item); + } + } + + private static Expression> BuildSupplierPredicate(string? keyword, byte? status) + { + var hasKeyword = !string.IsNullOrWhiteSpace(keyword); + var kw = keyword?.Trim(); + var hasStatus = status is > 0; + var statusValue = (EnableStatus)(status ?? 0); + return x => + (!hasKeyword || x.SupplierCode.Contains(kw!) || x.SupplierName.Contains(kw!)) + && (!hasStatus || x.Status == statusValue); + } + + private static Expression> BuildCompanyAccountPredicate( + string? keyword, + byte? status) + { + var hasKeyword = !string.IsNullOrWhiteSpace(keyword); + var kw = keyword?.Trim(); + var hasStatus = status is > 0; + var statusValue = (EnableStatus)(status ?? 0); + return x => + (!hasKeyword + || x.AccountName.Contains(kw!) + || x.BankName.Contains(kw!) + || x.AccountNo.Contains(kw!)) + && (!hasStatus || x.Status == statusValue); + } + + private static EnableStatus ResolveStatus(byte? status) => + status is (byte)EnableStatus.Disabled ? EnableStatus.Disabled : EnableStatus.Enabled; + + private static string? NormalizeOptional(string? value) => + string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static FinanceSupplierOutput MapSupplier(FinanceSupplier entity) => new() + { + Id = entity.Id, + SupplierCode = entity.SupplierCode, + SupplierName = entity.SupplierName, + ContactName = entity.ContactName, + Phone = entity.Phone, + Email = entity.Email, + BankAccountName = entity.BankAccountName, + BankName = entity.BankName, + BankAccountNo = entity.BankAccountNo, + Currency = entity.Currency, + Status = (byte)entity.Status, + Remark = entity.Remark, + CreateTime = entity.CreateTime, + UpdateTime = entity.UpdateTime == default ? null : entity.UpdateTime + }; + + private static FinanceCompanyAccountOutput MapCompanyAccount(FinanceCompanyAccount entity) => new() + { + Id = entity.Id, + AccountName = entity.AccountName, + BankName = entity.BankName, + AccountNo = entity.AccountNo, + Currency = entity.Currency, + IsDefault = entity.IsDefault, + Status = (byte)entity.Status, + Remark = entity.Remark, + CreateTime = entity.CreateTime, + UpdateTime = entity.UpdateTime == default ? null : entity.UpdateTime + }; +} diff --git a/src/Oms.Application/Services/Finance/FinancePaymentApplyService.cs b/src/Oms.Application/Services/Finance/FinancePaymentApplyService.cs new file mode 100644 index 0000000..f05c0d1 --- /dev/null +++ b/src/Oms.Application/Services/Finance/FinancePaymentApplyService.cs @@ -0,0 +1,725 @@ +using System.Linq.Expressions; +using Fake.Application; +using Fake.Domain.Exceptions; +using Microsoft.AspNetCore.Mvc; +using Oms.Application.Dtos.Finance; +using Oms.Application.Dtos.Shared; +using Oms.Application.Services.Approval; +using Oms.Application.Services.Approval.Contracts; +using Oms.Application.Shared; +using Oms.Domain.AgentsAggregate.Repositories; +using Oms.Domain.ApprovalAggregate.Consts; +using Oms.Domain.ApprovalAggregate.Enums; +using Oms.Domain.CustomersAggregate.Repositories; +using Oms.Domain.FinanceAggregate.Consts; +using Oms.Domain.FinanceAggregate.Entities; +using Oms.Domain.FinanceAggregate.Repositories; + +namespace Oms.Application.Services.Finance; + +/// +/// 付款申请 API。 +/// +[ApiExplorerSettings(GroupName = "OMS-Finance")] +public class FinancePaymentApplyService : ApplicationService +{ + private IFinancePaymentApplyRepository PaymentApplyRepository => + LazyServiceProvider.GetRequiredService(); + + private IFinancePaymentApplyLineRepository PaymentApplyLineRepository => + LazyServiceProvider.GetRequiredService(); + + private IFinanceContractRepository ContractRepository => + LazyServiceProvider.GetRequiredService(); + + private IFinanceSupplierRepository SupplierRepository => + LazyServiceProvider.GetRequiredService(); + + private IFinanceCompanyAccountRepository CompanyAccountRepository => + LazyServiceProvider.GetRequiredService(); + + private ICustomerRepository CustomerRepository => + LazyServiceProvider.GetRequiredService(); + + private IAgentRepository AgentRepository => + LazyServiceProvider.GetRequiredService(); + + private IApprovalGate ApprovalGate => + LazyServiceProvider.GetRequiredService(); + + private ApprovalEngineCore ApprovalEngineCore => + LazyServiceProvider.GetRequiredService(); + + /// + /// 分页查询付款申请。 + /// + [HttpGet("/finance/payment-apply/list")] + public async Task> GetListAsync( + [FromQuery] FinancePaymentApplyListInput input) + { + var predicate = BuildListPredicate(input); + var page = OmsDocHelper.NormalizePage(input.Page); + var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize); + var entities = await PaymentApplyRepository.GetPagedListAsync( + predicate, + page, + pageSize, + new Dictionary + { + [nameof(FinancePaymentApply.CreateTime)] = false, + [nameof(FinancePaymentApply.Id)] = false + }); + var total = await PaymentApplyRepository.CountAsync(predicate); + var items = await MapListAsync(entities, includeLines: false); + return new OmsPageResult + { + Items = items, + Total = total + }; + } + + /// + /// 付款申请汇总(待审批 / 待付款 / 本月已付,按币种)。 + /// + [HttpGet("/finance/payment-apply/summary")] + public async Task GetSummaryAsync() + { + var monthStart = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1); + var entities = await PaymentApplyRepository.GetListAsync(x => + x.Status == FinancePaymentStatusCodes.PendingApproval + || x.Status == FinancePaymentStatusCodes.PendingPay + || (x.Status == FinancePaymentStatusCodes.Paid && x.PaidTime != null && x.PaidTime >= monthStart)); + + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var entity in entities) + { + var currency = string.IsNullOrWhiteSpace(entity.Currency) ? FinanceCurrencyCodes.Cny : entity.Currency; + if (!map.TryGetValue(currency, out var item)) + { + item = new FinancePaymentApplySummaryItemOutput { Currency = currency }; + map[currency] = item; + } + + if (entity.Status == FinancePaymentStatusCodes.PendingApproval) + { + item.PendingApprovalAmount += entity.AmountTotal; + } + else if (entity.Status == FinancePaymentStatusCodes.PendingPay) + { + item.PendingPayAmount += entity.AmountTotal; + } + else if (entity.Status == FinancePaymentStatusCodes.Paid) + { + item.PaidThisMonthAmount += entity.AmountTotal; + } + } + + return new FinancePaymentApplySummaryOutput + { + Items = map.Values.OrderBy(x => x.Currency).ToList() + }; + } + + /// + /// 付款申请详情。 + /// + [HttpGet("/finance/payment-apply/detail")] + public async Task GetDetailAsync([FromQuery] int id) + { + var entity = await PaymentApplyRepository.FirstOrDefaultAsync(x => x.Id == id) + ?? throw new BusinessException("付款申请不存在"); + var list = await MapListAsync([entity], includeLines: true); + return list[0]; + } + + /// + /// 保存付款申请(草稿;可勾选 Submit 提交审批)。 + /// + [HttpPost("/finance/payment-apply/save")] + public async Task SaveAsync(FinancePaymentApplySaveInput input) + { + ValidateSaveInput(input); + var payeeType = FinancePaymentTypeCodes.ResolvePayeeType(input.PaymentType); + await EnsurePayeeExistsAsync(payeeType, input.PayeeId); + var lines = BuildLines(input.Lines); + var amountTotal = RoundMoney(lines.Sum(x => x.Amount)); + + FinancePaymentApply entity; + if (input.Id is > 0) + { + entity = await PaymentApplyRepository.FirstOrDefaultAsync(x => x.Id == input.Id.Value) + ?? throw new BusinessException("付款申请不存在"); + if (entity.Status is not (FinancePaymentStatusCodes.Draft or FinancePaymentStatusCodes.Rejected)) + { + throw new BusinessException("仅草稿或已驳回单据可编辑"); + } + } + else + { + entity = new FinancePaymentApply + { + ApplyNo = await GenerateApplyNoAsync(), + Status = FinancePaymentStatusCodes.Draft, + ApplicantName = CurrentUser.UserName + }; + } + + await ApplyHeaderAsync(entity, input, payeeType, amountTotal); + + if (input.Id is > 0) + { + await PaymentApplyRepository.UpdateAsync(entity); + await ReplaceLinesAsync(entity.Id, lines, deleteExisting: true); + } + else + { + entity = await PaymentApplyRepository.InsertAsync(entity); + await ReplaceLinesAsync(entity.Id, lines, deleteExisting: false); + } + + if (input.Submit) + { + return await SubmitCoreAsync(entity); + } + + var output = (await MapListAsync([entity], includeLines: true))[0]; + return output; + } + + /// + /// 提交审批。未配置审批定义时 Bypass 直接进入待付款。 + /// + [HttpPost("/finance/payment-apply/submit")] + public async Task SubmitAsync(FinancePaymentApplyIdInput input) + { + var entity = await PaymentApplyRepository.FirstOrDefaultAsync(x => x.Id == input.Id) + ?? throw new BusinessException("付款申请不存在"); + if (entity.Status is not (FinancePaymentStatusCodes.Draft or FinancePaymentStatusCodes.Rejected)) + { + throw new BusinessException("仅草稿或已驳回单据可提交"); + } + + return await SubmitCoreAsync(entity); + } + + /// + /// 撤回审批中的申请(回到草稿)。 + /// + [HttpPost("/finance/payment-apply/withdraw")] + public async Task WithdrawAsync(FinancePaymentApplyIdInput input) + { + var entity = await PaymentApplyRepository.FirstOrDefaultAsync(x => x.Id == input.Id) + ?? throw new BusinessException("付款申请不存在"); + if (entity.Status != FinancePaymentStatusCodes.PendingApproval) + { + throw new BusinessException("仅审批中单据可撤回"); + } + + if (entity.ApprovalInstanceId is > 0) + { + try + { + await ApprovalEngineCore.WithdrawAsync(entity.ApprovalInstanceId.Value, "业务撤回", null); + } + catch + { + // 引擎撤回失败时仍回写业务态,避免卡死 + entity.Status = FinancePaymentStatusCodes.Draft; + entity.RejectReason = null; + await PaymentApplyRepository.UpdateAsync(entity); + } + } + else + { + entity.Status = FinancePaymentStatusCodes.Draft; + entity.RejectReason = null; + await PaymentApplyRepository.UpdateAsync(entity); + } + + entity = await PaymentApplyRepository.FirstOrDefaultAsync(x => x.Id == input.Id) ?? entity; + return (await MapListAsync([entity], includeLines: true))[0]; + } + + /// + /// 出纳登记付款。 + /// + [HttpPost("/finance/payment-apply/mark-paid")] + public async Task MarkPaidAsync(FinancePaymentMarkPaidInput input) + { + var entity = await PaymentApplyRepository.FirstOrDefaultAsync(x => x.Id == input.Id) + ?? throw new BusinessException("付款申请不存在"); + if (entity.Status != FinancePaymentStatusCodes.PendingPay) + { + throw new BusinessException("仅待付款单据可登记付款"); + } + + entity.Status = FinancePaymentStatusCodes.Paid; + entity.PaidTime = input.PaidTime ?? DateTime.Now; + entity.BankTxnNo = NormalizeOptional(input.BankTxnNo); + entity.PaidVoucherUrl = NormalizeOptional(input.PaidVoucherUrl); + entity.PaidBy = CurrentUser.UserName; + if (!string.IsNullOrWhiteSpace(input.Remark)) + { + entity.Remark = input.Remark.Trim(); + } + + await PaymentApplyRepository.UpdateAsync(entity); + return (await MapListAsync([entity], includeLines: true))[0]; + } + + private async Task SubmitCoreAsync(FinancePaymentApply entity) + { + var lines = await PaymentApplyLineRepository.GetListByApplyIdAsync(entity.Id); + if (lines.Count == 0) + { + throw new BusinessException("请填写付款明细"); + } + + if (entity.AmountTotal <= 0) + { + throw new BusinessException("付款金额必须大于 0"); + } + + var (payeeCode, payeeName) = await ResolvePayeeAsync(entity.PayeeType, entity.PayeeId); + var gateResult = await ApprovalGate.CheckAndSubmitOrBypassAsync(new ApprovalSubmitRequest + { + OperationCode = ApprovalCodes.FinancePaymentApply, + BizKey = BuildBizKey(entity.Id), + Title = $"付款申请 - {payeeCode} {payeeName} {entity.ApplyNo}".Trim(), + PayloadJson = OmsDocHelper.SerializeJson(new + { + paymentApplyId = entity.Id, + applyNo = entity.ApplyNo, + paymentType = entity.PaymentType, + payeeType = entity.PayeeType, + payeeId = entity.PayeeId, + payeeCode, + payeeName, + amountTotal = entity.AmountTotal, + currency = entity.Currency + }), + Summary = new + { + entity.ApplyNo, + entity.PaymentType, + payeeCode, + payeeName, + entity.AmountTotal, + entity.Currency + } + }); + + if (gateResult.Decision == ApprovalGateDecision.Bypass) + { + entity.Status = FinancePaymentStatusCodes.PendingPay; + entity.RejectReason = null; + entity.ApprovalInstanceId = gateResult.InstanceId; + entity.ApprovalInstanceNo = gateResult.InstanceNo; + await PaymentApplyRepository.UpdateAsync(entity); + } + else + { + entity.Status = FinancePaymentStatusCodes.PendingApproval; + entity.RejectReason = null; + entity.ApprovalInstanceId = gateResult.InstanceId; + entity.ApprovalInstanceNo = gateResult.InstanceNo; + await PaymentApplyRepository.UpdateAsync(entity); + } + + var output = (await MapListAsync([entity], includeLines: true))[0]; + 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 ApplyHeaderAsync( + FinancePaymentApply entity, + FinancePaymentApplySaveInput input, + string payeeType, + decimal amountTotal) + { + entity.PaymentType = input.PaymentType.Trim(); + entity.PayeeType = payeeType; + entity.PayeeId = input.PayeeId; + entity.Currency = string.IsNullOrWhiteSpace(input.Currency) + ? FinanceCurrencyCodes.Cny + : input.Currency.Trim().ToUpperInvariant(); + entity.AmountTotal = amountTotal; + entity.ExpectPayDate = input.ExpectPayDate?.Date; + entity.PayeeAccountName = NormalizeOptional(input.PayeeAccountName); + entity.PayeeBankName = NormalizeOptional(input.PayeeBankName); + entity.PayeeAccountNo = NormalizeOptional(input.PayeeAccountNo); + entity.AttachmentUrls = NormalizeOptional(input.AttachmentUrls); + entity.Remark = NormalizeOptional(input.Remark); + entity.Status = FinancePaymentStatusCodes.Draft; + entity.RejectReason = null; + entity.ApplicantName ??= CurrentUser.UserName; + + if (input.ContractId is > 0) + { + var contract = await ContractRepository.FirstOrDefaultAsync(x => x.Id == input.ContractId.Value) + ?? throw new BusinessException("关联合同不存在"); + if (contract.PartyType != payeeType || contract.PartyId != input.PayeeId) + { + throw new BusinessException("关联合同与收款方不匹配"); + } + + entity.ContractId = contract.Id; + if (string.IsNullOrWhiteSpace(input.Currency)) + { + entity.Currency = contract.Currency; + } + } + else + { + entity.ContractId = null; + } + + if (input.CompanyAccountId is > 0) + { + var account = await CompanyAccountRepository.FirstOrDefaultAsync(x => x.Id == input.CompanyAccountId.Value) + ?? throw new BusinessException("付款账户不存在"); + entity.CompanyAccountId = account.Id; + } + else + { + entity.CompanyAccountId = null; + } + + if (string.IsNullOrWhiteSpace(entity.PayeeAccountName) + || string.IsNullOrWhiteSpace(entity.PayeeAccountNo)) + { + await FillPayeeBankFromMasterAsync(entity); + } + } + + private async Task FillPayeeBankFromMasterAsync(FinancePaymentApply entity) + { + if (entity.PayeeType == FinancePartyTypeCodes.Supplier) + { + var supplier = await SupplierRepository.FirstOrDefaultAsync(x => x.Id == entity.PayeeId); + if (supplier == null) + { + return; + } + + entity.PayeeAccountName ??= supplier.BankAccountName; + entity.PayeeBankName ??= supplier.BankName; + entity.PayeeAccountNo ??= supplier.BankAccountNo; + if (string.IsNullOrWhiteSpace(entity.Currency)) + { + entity.Currency = supplier.Currency; + } + } + } + + private static void ValidateSaveInput(FinancePaymentApplySaveInput input) + { + if (!FinancePaymentTypeCodes.IsKnown(input.PaymentType)) + { + throw new BusinessException("付款类型无效"); + } + + if (input.PayeeId <= 0) + { + throw new BusinessException("请选择收款方"); + } + + if (input.Lines == null || input.Lines.Count == 0) + { + throw new BusinessException("请填写付款明细"); + } + } + + private async Task EnsurePayeeExistsAsync(string payeeType, int payeeId) + { + switch (payeeType) + { + case FinancePartyTypeCodes.Customer: + _ = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == payeeId) + ?? throw new BusinessException("客户不存在"); + break; + case FinancePartyTypeCodes.Supplier: + _ = await SupplierRepository.FirstOrDefaultAsync(x => x.Id == payeeId) + ?? throw new BusinessException("供应商不存在"); + break; + case FinancePartyTypeCodes.Agent: + _ = await AgentRepository.FirstOrDefaultAsync(x => x.Id == payeeId) + ?? throw new BusinessException("代理不存在"); + break; + default: + throw new BusinessException("收款方类型无效"); + } + } + + private static List BuildLines(List inputs) + { + var result = new List(inputs.Count); + foreach (var input in inputs) + { + if (string.IsNullOrWhiteSpace(input.Description)) + { + throw new BusinessException("明细说明不能为空"); + } + + var amount = RoundMoney(input.Amount); + if (amount <= 0) + { + throw new BusinessException("明细金额必须大于 0"); + } + + result.Add(new FinancePaymentApplyLine + { + Description = input.Description.Trim(), + Amount = amount, + RefNo = NormalizeOptional(input.RefNo), + Remark = NormalizeOptional(input.Remark) + }); + } + + return result; + } + + private async Task ReplaceLinesAsync(int applyId, List lines, bool deleteExisting) + { + if (deleteExisting) + { + await PaymentApplyLineRepository.DeleteByApplyIdAsync(applyId); + } + + foreach (var line in lines) + { + line.PaymentApplyId = applyId; + await PaymentApplyLineRepository.InsertAsync(line); + } + } + + private static Expression> BuildListPredicate( + FinancePaymentApplyListInput input) + { + var hasStatus = !string.IsNullOrWhiteSpace(input.Status) && input.Status != "all"; + var status = input.Status?.Trim(); + var hasPaymentType = !string.IsNullOrWhiteSpace(input.PaymentType); + var paymentType = input.PaymentType?.Trim(); + var hasPayeeType = !string.IsNullOrWhiteSpace(input.PayeeType); + var payeeType = input.PayeeType?.Trim(); + var hasPayeeId = input.PayeeId is > 0; + var payeeId = input.PayeeId.GetValueOrDefault(); + var hasCurrency = !string.IsNullOrWhiteSpace(input.Currency); + var currency = input.Currency?.Trim(); + var hasKeyword = !string.IsNullOrWhiteSpace(input.Keyword); + var keyword = input.Keyword?.Trim(); + var hasStart = input.StartTime.HasValue; + var start = input.StartTime; + var hasEnd = input.EndTime.HasValue; + var end = input.EndTime; + + return x => + (!hasStatus || x.Status == status) + && (!hasPaymentType || x.PaymentType == paymentType) + && (!hasPayeeType || x.PayeeType == payeeType) + && (!hasPayeeId || x.PayeeId == payeeId) + && (!hasCurrency || x.Currency == currency) + && (!hasKeyword || x.ApplyNo.Contains(keyword!)) + && (!hasStart || x.CreateTime >= start) + && (!hasEnd || x.CreateTime <= end); + } + + private async Task> MapListAsync( + List entities, + bool includeLines) + { + if (entities.Count == 0) + { + return []; + } + + var customerIds = entities.Where(x => x.PayeeType == FinancePartyTypeCodes.Customer) + .Select(x => x.PayeeId).Distinct().ToList(); + var supplierIds = entities.Where(x => x.PayeeType == FinancePartyTypeCodes.Supplier) + .Select(x => x.PayeeId).Distinct().ToList(); + var agentIds = entities.Where(x => x.PayeeType == FinancePartyTypeCodes.Agent) + .Select(x => x.PayeeId).Distinct().ToList(); + var contractIds = entities.Where(x => x.ContractId is > 0) + .Select(x => x.ContractId!.Value).Distinct().ToList(); + var accountIds = entities.Where(x => x.CompanyAccountId is > 0) + .Select(x => x.CompanyAccountId!.Value).Distinct().ToList(); + var applyIds = entities.Select(x => x.Id).ToList(); + + var customers = customerIds.Count == 0 + ? [] + : await CustomerRepository.GetListAsync(x => customerIds.Contains(x.Id)); + var suppliers = supplierIds.Count == 0 + ? [] + : await SupplierRepository.GetListAsync(x => supplierIds.Contains(x.Id)); + var agents = agentIds.Count == 0 + ? [] + : await AgentRepository.GetListAsync(x => agentIds.Contains(x.Id)); + var contracts = contractIds.Count == 0 + ? [] + : await ContractRepository.GetListAsync(x => contractIds.Contains(x.Id)); + var accounts = accountIds.Count == 0 + ? [] + : await CompanyAccountRepository.GetListAsync(x => accountIds.Contains(x.Id)); + var lines = !includeLines || applyIds.Count == 0 + ? [] + : await PaymentApplyLineRepository.GetListAsync(x => applyIds.Contains(x.PaymentApplyId)); + + var customerMap = customers.ToDictionary(x => x.Id); + var supplierMap = suppliers.ToDictionary(x => x.Id); + var agentMap = agents.ToDictionary(x => x.Id); + var contractMap = contracts.ToDictionary(x => x.Id); + var accountMap = accounts.ToDictionary(x => x.Id); + var lineGroups = lines.GroupBy(x => x.PaymentApplyId).ToDictionary(g => g.Key, g => g.ToList()); + + return entities.Select(entity => + { + string? payeeCode = null; + string? payeeName = null; + if (entity.PayeeType == FinancePartyTypeCodes.Customer + && customerMap.TryGetValue(entity.PayeeId, out var customer)) + { + payeeCode = customer.CustomerCode; + payeeName = customer.CustomerName; + } + else if (entity.PayeeType == FinancePartyTypeCodes.Supplier + && supplierMap.TryGetValue(entity.PayeeId, out var supplier)) + { + payeeCode = supplier.SupplierCode; + payeeName = supplier.SupplierName; + } + else if (entity.PayeeType == FinancePartyTypeCodes.Agent + && agentMap.TryGetValue(entity.PayeeId, out var agent)) + { + payeeCode = agent.AgentCode; + payeeName = agent.AgentName; + } + + string? contractNo = null; + if (entity.ContractId is > 0 && contractMap.TryGetValue(entity.ContractId.Value, out var contract)) + { + contractNo = contract.ContractNo; + } + + string? companyAccountName = null; + if (entity.CompanyAccountId is > 0 + && accountMap.TryGetValue(entity.CompanyAccountId.Value, out var account)) + { + companyAccountName = $"{account.AccountName} / {account.AccountNo}"; + } + + var output = new FinancePaymentApplyOutput + { + Id = entity.Id, + ApplyNo = entity.ApplyNo, + PaymentType = entity.PaymentType, + PaymentTypeName = FinancePaymentTypeCodes.GetName(entity.PaymentType), + PayeeType = entity.PayeeType, + PayeeTypeName = FinancePartyTypeCodes.GetName(entity.PayeeType), + PayeeId = entity.PayeeId, + PayeeCode = payeeCode, + PayeeName = payeeName, + ContractId = entity.ContractId, + ContractNo = contractNo, + Currency = entity.Currency, + AmountTotal = entity.AmountTotal, + ExpectPayDate = entity.ExpectPayDate, + PayeeAccountName = entity.PayeeAccountName, + PayeeBankName = entity.PayeeBankName, + PayeeAccountNo = entity.PayeeAccountNo, + CompanyAccountId = entity.CompanyAccountId, + CompanyAccountName = companyAccountName, + Status = entity.Status, + StatusName = FinancePaymentStatusCodes.GetName(entity.Status), + ApplicantName = entity.ApplicantName, + AttachmentUrls = entity.AttachmentUrls, + Remark = entity.Remark, + ApprovalInstanceId = entity.ApprovalInstanceId, + ApprovalInstanceNo = entity.ApprovalInstanceNo, + ApprovalPending = entity.Status == FinancePaymentStatusCodes.PendingApproval, + RejectReason = entity.RejectReason, + PaidTime = entity.PaidTime, + BankTxnNo = entity.BankTxnNo, + PaidBy = entity.PaidBy, + PaidVoucherUrl = entity.PaidVoucherUrl, + CreateTime = entity.CreateTime, + UpdateTime = entity.UpdateTime == default ? null : entity.UpdateTime + }; + + if (includeLines && lineGroups.TryGetValue(entity.Id, out var applyLines)) + { + output.Lines = applyLines.Select(x => new FinancePaymentApplyLineOutput + { + Id = x.Id, + Description = x.Description, + Amount = x.Amount, + RefNo = x.RefNo, + Remark = x.Remark + }).ToList(); + } + + return output; + }).ToList(); + } + + private async Task<(string? Code, string? Name)> ResolvePayeeAsync(string payeeType, int payeeId) + { + if (payeeType == FinancePartyTypeCodes.Customer) + { + var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == payeeId); + return customer == null ? (null, null) : (customer.CustomerCode, customer.CustomerName); + } + + if (payeeType == FinancePartyTypeCodes.Supplier) + { + var supplier = await SupplierRepository.FirstOrDefaultAsync(x => x.Id == payeeId); + return supplier == null ? (null, null) : (supplier.SupplierCode, supplier.SupplierName); + } + + if (payeeType == FinancePartyTypeCodes.Agent) + { + var agent = await AgentRepository.FirstOrDefaultAsync(x => x.Id == payeeId); + return agent == null ? (null, null) : (agent.AgentCode, agent.AgentName); + } + + return (null, null); + } + + private async Task GenerateApplyNoAsync() + { + var prefix = $"PAY{DateTime.Now:yyyyMMdd}"; + for (var i = 0; i < 10; i++) + { + var existing = await PaymentApplyRepository.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 PaymentApplyRepository.ExistsApplyNoAsync(applyNo)) + { + return applyNo; + } + } + + throw new BusinessException("付款申请单号生成失败"); + } + + private static string BuildBizKey(int paymentApplyId) => + $"{ApprovalCodes.FinancePaymentApply}:{paymentApplyId}"; + + private static decimal RoundMoney(decimal value) => Math.Round(value, 2, MidpointRounding.AwayFromZero); + + private static string? NormalizeOptional(string? value) => + string.IsNullOrWhiteSpace(value) ? null : value.Trim(); +} diff --git a/src/Oms.Application/Services/Finance/InvoiceService.cs b/src/Oms.Application/Services/Finance/InvoiceService.cs index 0137ff1..9e434f2 100644 --- a/src/Oms.Application/Services/Finance/InvoiceService.cs +++ b/src/Oms.Application/Services/Finance/InvoiceService.cs @@ -62,7 +62,7 @@ public class InvoiceService : ApplicationService /// 查询客户发票抬头列表。 /// /// 入参:可选客户 Id。 - /// 抬头列表(默认抬头在前)。 + /// 抬头列表(默认抬头在前;管理端附带客户编码/名称)。 [HttpGet("/finance/invoice/profile/list")] public async Task> GetProfileListAsync([FromQuery] InvoiceProfileListInput input) { @@ -73,11 +73,29 @@ public class InvoiceService : ApplicationService var hasCustomer = customerId is > 0; var customerIdValue = customerId.GetValueOrDefault(); var entities = await ProfileRepository.GetListAsync(x => !hasCustomer || x.CustomerId == customerIdValue); - return entities + var ordered = entities .OrderByDescending(x => x.IsDefault) .ThenByDescending(x => x.Id) - .Select(MapProfile) .ToList(); + if (ordered.Count == 0) + { + return []; + } + + var customerIds = ordered.Select(x => x.CustomerId).Distinct().ToList(); + var customers = await CustomerRepository.GetListAsync(x => customerIds.Contains(x.Id)); + var customerMap = customers.ToDictionary(x => x.Id); + return ordered.Select(entity => + { + var output = MapProfile(entity); + if (customerMap.TryGetValue(entity.CustomerId, out var customer)) + { + output.CustomerCode = customer.CustomerCode; + output.CustomerName = customer.CustomerName; + } + + return output; + }).ToList(); } /// diff --git a/src/Oms.Application/Services/Finance/PaymentApplyApprovalHandler.cs b/src/Oms.Application/Services/Finance/PaymentApplyApprovalHandler.cs new file mode 100644 index 0000000..e19e41b --- /dev/null +++ b/src/Oms.Application/Services/Finance/PaymentApplyApprovalHandler.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 PaymentApplyApprovalHandler( + IFinancePaymentApplyRepository paymentApplyRepository) : IApprovalOperationHandler, ITransientDependency +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + public string OperationCode => ApprovalCodes.FinancePaymentApply; + + /// + public async Task ExecuteAsync(ApprovalExecutionContext context, CancellationToken cancellationToken = default) + { + var apply = await GetApplyOrThrowAsync(context, cancellationToken); + if (apply.Status == FinancePaymentStatusCodes.PendingPay || apply.Status == FinancePaymentStatusCodes.Paid) + { + return; + } + + if (apply.Status != FinancePaymentStatusCodes.PendingApproval) + { + throw new BusinessException("只有审批中的付款申请才能审批通过"); + } + + apply.Status = FinancePaymentStatusCodes.PendingPay; + apply.ApprovalInstanceId = context.InstanceId; + apply.ApprovalInstanceNo = context.InstanceNo; + apply.RejectReason = null; + await paymentApplyRepository.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 = FinancePaymentStatusCodes.Rejected; + apply.RejectReason = string.IsNullOrWhiteSpace(comment) + ? $"审批驳回 {context.InstanceNo}".Trim() + : comment.Trim(); + apply.ApprovalInstanceId = context.InstanceId; + apply.ApprovalInstanceNo = context.InstanceNo; + await paymentApplyRepository.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 = FinancePaymentStatusCodes.Draft; + apply.RejectReason = null; + apply.ApprovalInstanceId = context.InstanceId; + apply.ApprovalInstanceNo = context.InstanceNo; + if (!string.IsNullOrWhiteSpace(comment)) + { + apply.Remark = comment.Trim(); + } + + await paymentApplyRepository.UpdateAsync(apply, cancellationToken); + } + + private async Task GetApplyOrThrowAsync( + ApprovalExecutionContext context, + CancellationToken cancellationToken) + { + var applyId = ResolveApplyId(context); + return await paymentApplyRepository.FirstOrDefaultAsync(x => x.Id == applyId, cancellationToken) + ?? throw new BusinessException("付款申请不存在"); + } + + private async Task TryGetPendingApplyAsync( + ApprovalExecutionContext context, + CancellationToken cancellationToken) + { + var applyId = ResolveApplyId(context); + var apply = await paymentApplyRepository.FirstOrDefaultAsync(x => x.Id == applyId, cancellationToken); + if (apply == null || apply.Status != FinancePaymentStatusCodes.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 { PaymentApplyId: > 0 }) + { + return payload.PaymentApplyId; + } + } + catch + { + // fall through BizKey + } + } + + var bizKey = context.BizKey ?? string.Empty; + var prefix = $"{ApprovalCodes.FinancePaymentApply}:"; + 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 PaymentApplyPayload + { + public int PaymentApplyId { get; set; } + } +} diff --git a/src/Oms.Application/Services/System/SystemOtherConfigService.cs b/src/Oms.Application/Services/System/SystemOtherConfigService.cs index 5bf996d..55ab664 100644 --- a/src/Oms.Application/Services/System/SystemOtherConfigService.cs +++ b/src/Oms.Application/Services/System/SystemOtherConfigService.cs @@ -166,7 +166,7 @@ public class SystemOtherConfigService : ApplicationService /// /// 获取客户充值用支付宝/微信收款码图片地址。 - /// 返回同源 API 文件地址(非 COS 直链),未配置时对应 URL 为空(前端可回退本地默认图)。 + /// 返回同源 API 文件地址(非 COS 直链),未配置时对应 URL 为空。 /// [HttpGet("/system/other-config/payment-qr")] public async Task GetPaymentReceiveQrAsync() diff --git a/src/Oms.Domain/ApprovalAggregate/Consts/ApprovalCodes.cs b/src/Oms.Domain/ApprovalAggregate/Consts/ApprovalCodes.cs index 7b7c071..1934393 100644 --- a/src/Oms.Domain/ApprovalAggregate/Consts/ApprovalCodes.cs +++ b/src/Oms.Domain/ApprovalAggregate/Consts/ApprovalCodes.cs @@ -43,6 +43,9 @@ public static class ApprovalCodes /// 发票开具。 public const string FinanceInvoiceIssue = "Finance.Invoice.Issue"; + + /// 付款申请。 + public const string FinancePaymentApply = "Finance.Payment.Apply"; } /// diff --git a/src/Oms.Domain/FinanceAggregate/Consts/FinanceContractCodes.cs b/src/Oms.Domain/FinanceAggregate/Consts/FinanceContractCodes.cs new file mode 100644 index 0000000..526f874 --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Consts/FinanceContractCodes.cs @@ -0,0 +1,168 @@ +namespace Oms.Domain.FinanceAggregate.Consts; + +/// +/// 合同对方类型。 +/// +public static class FinancePartyTypeCodes +{ + /// 客户。 + public const string Customer = "customer"; + + /// 供应商。 + public const string Supplier = "supplier"; + + /// 代理。 + public const string Agent = "agent"; + + public static bool IsKnown(string? partyType) => + partyType is Customer or Supplier or Agent; + + public static string GetName(string? partyType) => partyType switch + { + Customer => "客户", + Supplier => "供应商", + Agent => "代理", + _ => partyType ?? string.Empty + }; +} + +/// +/// 合同结算方式。 +/// +public static class FinanceSettlementMethodCodes +{ + /// 预付。 + public const string Prepaid = "prepaid"; + + /// 票结。 + public const string Ticket = "ticket"; + + /// 月结。 + public const string Monthly = "monthly"; + + /// 半月结。 + public const string Biweekly = "biweekly"; + + public static bool IsKnown(string? method) => + method is Prepaid or Ticket or Monthly or Biweekly; + + public static string GetName(string? method) => method switch + { + Prepaid => "预付", + Ticket => "票结", + Monthly => "月结", + Biweekly => "半月结", + _ => method ?? string.Empty + }; +} + +/// +/// 合同状态。 +/// +public static class FinanceContractStatusCodes +{ + /// 草稿。 + public const string Draft = "draft"; + + /// 生效。 + public const string Active = "active"; + + /// 已到期。 + public const string Expired = "expired"; + + /// 已终止。 + public const string Terminated = "terminated"; + + public static bool IsKnown(string? status) => + status is Draft or Active or Expired or Terminated; + + public static string GetName(string? status) => status switch + { + Draft => "草稿", + Active => "生效", + Expired => "已到期", + Terminated => "已终止", + _ => status ?? string.Empty + }; +} + +/// +/// 付款申请类型。 +/// +public static class FinancePaymentTypeCodes +{ + /// 供应商款项。 + public const string Supplier = "supplier"; + + /// 代理佣金。 + public const string AgentCommission = "agentCommission"; + + /// 客户退款。 + public const string CustomerRefund = "customerRefund"; + + /// 其他。 + public const string Other = "other"; + + public static bool IsKnown(string? paymentType) => + paymentType is Supplier or AgentCommission or CustomerRefund or Other; + + public static string GetName(string? paymentType) => paymentType switch + { + Supplier => "供应商款项", + AgentCommission => "代理佣金", + CustomerRefund => "客户退款", + Other => "其他", + _ => paymentType ?? string.Empty + }; + + /// 付款类型对应的收款方类型。 + public static string ResolvePayeeType(string paymentType) => paymentType switch + { + Supplier => FinancePartyTypeCodes.Supplier, + AgentCommission => FinancePartyTypeCodes.Agent, + CustomerRefund => FinancePartyTypeCodes.Customer, + _ => FinancePartyTypeCodes.Supplier + }; +} + +/// +/// 付款申请状态。 +/// +public static class FinancePaymentStatusCodes +{ + /// 草稿。 + public const string Draft = "draft"; + + /// 审批中。 + public const string PendingApproval = "pendingApproval"; + + /// 待付款。 + public const string PendingPay = "pendingPay"; + + /// 已付款。 + public const string Paid = "paid"; + + /// 已驳回。 + public const string Rejected = "rejected"; + + public static bool IsKnown(string? status) => + status is Draft or PendingApproval or PendingPay or Paid or Rejected; + + public static string GetName(string? status) => status switch + { + Draft => "草稿", + PendingApproval => "审批中", + PendingPay => "待付款", + Paid => "已付款", + Rejected => "已驳回", + _ => status ?? string.Empty + }; +} + +/// +/// 财务币种。 +/// +public static class FinanceCurrencyCodes +{ + public const string Cny = "CNY"; +} diff --git a/src/Oms.Domain/FinanceAggregate/Entities/FinanceCompanyAccount.cs b/src/Oms.Domain/FinanceAggregate/Entities/FinanceCompanyAccount.cs new file mode 100644 index 0000000..519efa7 --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Entities/FinanceCompanyAccount.cs @@ -0,0 +1,31 @@ +using Oms.Domain.Shared; +using Oms.Domain.Shared.Enums; +using SqlSugar; + +namespace Oms.Domain.FinanceAggregate.Entities; + +/// +/// 公司收付款账户。 +/// +[SugarTable("t_finance_company_account")] +public class FinanceCompanyAccount : OmsAuditedAggregateRoot +{ + [SugarColumn(Length = 128)] + public string AccountName { get; set; } = string.Empty; + + [SugarColumn(Length = 128)] + public string BankName { get; set; } = string.Empty; + + [SugarColumn(Length = 64)] + public string AccountNo { get; set; } = string.Empty; + + [SugarColumn(Length = 8)] + public string Currency { get; set; } = "CNY"; + + public bool IsDefault { get; set; } + + public EnableStatus Status { get; set; } = EnableStatus.Enabled; + + [SugarColumn(Length = 512, IsNullable = true)] + public string? Remark { get; set; } +} diff --git a/src/Oms.Domain/FinanceAggregate/Entities/FinanceContract.cs b/src/Oms.Domain/FinanceAggregate/Entities/FinanceContract.cs new file mode 100644 index 0000000..be165de --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Entities/FinanceContract.cs @@ -0,0 +1,85 @@ +using Oms.Domain.FinanceAggregate.Consts; +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.FinanceAggregate.Entities; + +/// +/// 财务合同(客户 / 供应商 / 代理)。 +/// +[SugarTable("t_finance_contract")] +public class FinanceContract : OmsAuditedAggregateRoot +{ + [SugarColumn(Length = 32)] + public string ContractNo { get; set; } = string.Empty; + + [SugarColumn(Length = 128)] + public string ContractName { get; set; } = string.Empty; + + [SugarColumn(Length = 16)] + public string PartyType { get; set; } = FinancePartyTypeCodes.Customer; + + public int PartyId { get; set; } + + [SugarColumn(Length = 128, IsNullable = true)] + public string? OurEntityName { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? SignDate { get; set; } + + public DateTime EffectiveDate { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? ExpireDate { get; set; } + + public bool AutoRenew { get; set; } + + [SugarColumn(Length = 16)] + public string SettlementMethod { get; set; } = FinanceSettlementMethodCodes.Monthly; + + public int PaymentTermDays { get; set; } = 30; + + [SugarColumn(IsNullable = true)] + public int? BillingDay { get; set; } + + [SugarColumn(IsNullable = true)] + public int? PaymentDay { get; set; } + + [SugarColumn(Length = 8)] + public string Currency { get; set; } = FinanceCurrencyCodes.Cny; + + [SugarColumn(DecimalDigits = 2, IsNullable = true)] + public decimal? CreditLimit { get; set; } + + [SugarColumn(Length = 32, IsNullable = true)] + public string? CommissionBaseType { get; set; } + + [SugarColumn(DecimalDigits = 4, IsNullable = true)] + public decimal? CommissionRate { get; set; } + + public bool RequireVendorInvoice { get; set; } + + [SugarColumn(IsNullable = true)] + public int? OwnerUserId { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? OwnerName { get; set; } + + [SugarColumn(Length = 16)] + public string Status { get; set; } = FinanceContractStatusCodes.Draft; + + [SugarColumn(Length = 2048, IsNullable = true)] + public string? AttachmentUrls { get; set; } + + [SugarColumn(Length = 512, IsNullable = true)] + public string? Remark { get; set; } + + [SugarColumn(IsNullable = true)] + public int? RenewedFromId { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? TerminatedTime { get; set; } + + [SugarColumn(Length = 512, IsNullable = true)] + public string? TerminateReason { get; set; } +} diff --git a/src/Oms.Domain/FinanceAggregate/Entities/FinancePaymentApply.cs b/src/Oms.Domain/FinanceAggregate/Entities/FinancePaymentApply.cs new file mode 100644 index 0000000..56ddf8d --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Entities/FinancePaymentApply.cs @@ -0,0 +1,80 @@ +using Oms.Domain.FinanceAggregate.Consts; +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.FinanceAggregate.Entities; + +/// +/// 付款申请头。 +/// +[SugarTable("t_finance_payment_apply")] +public class FinancePaymentApply : OmsAuditedAggregateRoot +{ + [SugarColumn(Length = 32)] + public string ApplyNo { get; set; } = string.Empty; + + [SugarColumn(Length = 32)] + public string PaymentType { get; set; } = FinancePaymentTypeCodes.Supplier; + + [SugarColumn(Length = 16)] + public string PayeeType { get; set; } = FinancePartyTypeCodes.Supplier; + + public int PayeeId { get; set; } + + [SugarColumn(IsNullable = true)] + public int? ContractId { get; set; } + + [SugarColumn(Length = 8)] + public string Currency { get; set; } = FinanceCurrencyCodes.Cny; + + [SugarColumn(DecimalDigits = 2)] + public decimal AmountTotal { get; set; } + + [SugarColumn(IsNullable = true)] + public DateTime? ExpectPayDate { get; set; } + + [SugarColumn(Length = 128, IsNullable = true)] + public string? PayeeAccountName { get; set; } + + [SugarColumn(Length = 128, IsNullable = true)] + public string? PayeeBankName { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? PayeeAccountNo { get; set; } + + [SugarColumn(IsNullable = true)] + public int? CompanyAccountId { get; set; } + + [SugarColumn(Length = 32)] + public string Status { get; set; } = FinancePaymentStatusCodes.Draft; + + [SugarColumn(Length = 64, IsNullable = true)] + public string? ApplicantName { get; set; } + + [SugarColumn(Length = 2048, IsNullable = true)] + public string? AttachmentUrls { 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? PaidTime { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? BankTxnNo { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? PaidBy { get; set; } + + [SugarColumn(Length = 1024, IsNullable = true)] + public string? PaidVoucherUrl { get; set; } +} diff --git a/src/Oms.Domain/FinanceAggregate/Entities/FinancePaymentApplyLine.cs b/src/Oms.Domain/FinanceAggregate/Entities/FinancePaymentApplyLine.cs new file mode 100644 index 0000000..82b29a7 --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Entities/FinancePaymentApplyLine.cs @@ -0,0 +1,25 @@ +using Oms.Domain.Shared; +using SqlSugar; + +namespace Oms.Domain.FinanceAggregate.Entities; + +/// +/// 付款申请明细。 +/// +[SugarTable("t_finance_payment_apply_line")] +public class FinancePaymentApplyLine : OmsAuditedAggregateRoot +{ + public int PaymentApplyId { get; set; } + + [SugarColumn(Length = 256)] + public string Description { get; set; } = string.Empty; + + [SugarColumn(DecimalDigits = 2)] + public decimal Amount { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? RefNo { get; set; } + + [SugarColumn(Length = 512, IsNullable = true)] + public string? Remark { get; set; } +} diff --git a/src/Oms.Domain/FinanceAggregate/Entities/FinanceSupplier.cs b/src/Oms.Domain/FinanceAggregate/Entities/FinanceSupplier.cs new file mode 100644 index 0000000..71b018e --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Entities/FinanceSupplier.cs @@ -0,0 +1,44 @@ +using Oms.Domain.Shared; +using Oms.Domain.Shared.Enums; +using SqlSugar; + +namespace Oms.Domain.FinanceAggregate.Entities; + +/// +/// 财务供应商主数据。 +/// +[SugarTable("t_finance_supplier")] +public class FinanceSupplier : OmsAuditedAggregateRoot +{ + [SugarColumn(Length = 32)] + public string SupplierCode { get; set; } = string.Empty; + + [SugarColumn(Length = 128)] + public string SupplierName { get; set; } = string.Empty; + + [SugarColumn(Length = 64, IsNullable = true)] + public string? ContactName { get; set; } + + [SugarColumn(Length = 32, IsNullable = true)] + public string? Phone { get; set; } + + [SugarColumn(Length = 128, IsNullable = true)] + public string? Email { get; set; } + + [SugarColumn(Length = 128, IsNullable = true)] + public string? BankAccountName { get; set; } + + [SugarColumn(Length = 128, IsNullable = true)] + public string? BankName { get; set; } + + [SugarColumn(Length = 64, IsNullable = true)] + public string? BankAccountNo { get; set; } + + [SugarColumn(Length = 8)] + public string Currency { get; set; } = "CNY"; + + public EnableStatus Status { get; set; } = EnableStatus.Enabled; + + [SugarColumn(Length = 512, IsNullable = true)] + public string? Remark { get; set; } +} diff --git a/src/Oms.Domain/FinanceAggregate/Repositories/IFinanceContractRepositories.cs b/src/Oms.Domain/FinanceAggregate/Repositories/IFinanceContractRepositories.cs new file mode 100644 index 0000000..48acdf1 --- /dev/null +++ b/src/Oms.Domain/FinanceAggregate/Repositories/IFinanceContractRepositories.cs @@ -0,0 +1,38 @@ +using Fake.Domain.Repositories; +using Oms.Domain.FinanceAggregate.Entities; + +namespace Oms.Domain.FinanceAggregate.Repositories; + +public interface IFinanceSupplierRepository : IRepository +{ + Task ExistsCodeAsync(string supplierCode, int? excludeId = null, CancellationToken cancellationToken = default); +} + +public interface IFinanceCompanyAccountRepository : IRepository +{ +} + +public interface IFinanceContractRepository : IRepository +{ + Task ExistsContractNoAsync(string contractNo, CancellationToken cancellationToken = default); + + Task GetActiveByPartyAsync( + string partyType, + int partyId, + int? excludeId = null, + CancellationToken cancellationToken = default); +} + +public interface IFinancePaymentApplyRepository : IRepository +{ + Task ExistsApplyNoAsync(string applyNo, CancellationToken cancellationToken = default); +} + +public interface IFinancePaymentApplyLineRepository : IRepository +{ + Task> GetListByApplyIdAsync( + int paymentApplyId, + CancellationToken cancellationToken = default); + + Task DeleteByApplyIdAsync(int paymentApplyId, CancellationToken cancellationToken = default); +} diff --git a/src/Oms.SqlSugarCore/Finance/FinanceContractRepositories.cs b/src/Oms.SqlSugarCore/Finance/FinanceContractRepositories.cs new file mode 100644 index 0000000..356858f --- /dev/null +++ b/src/Oms.SqlSugarCore/Finance/FinanceContractRepositories.cs @@ -0,0 +1,91 @@ +using Fake.DependencyInjection; +using Oms.Domain.FinanceAggregate.Consts; +using Oms.Domain.FinanceAggregate.Entities; +using Oms.Domain.FinanceAggregate.Repositories; +using Oms.SqlSugarCore.Repositories; + +namespace Oms.SqlSugarCore.Finance; + +public class FinanceSupplierRepository + : OmsSqlSugarRepository, IFinanceSupplierRepository, IScopedDependency +{ + public async Task ExistsCodeAsync( + string supplierCode, + int? excludeId = null, + CancellationToken cancellationToken = default) + { + var code = supplierCode.Trim(); + if (excludeId is > 0) + { + return await AnyAsync(x => x.SupplierCode == code && x.Id != excludeId.Value, cancellationToken); + } + + return await AnyAsync(x => x.SupplierCode == code, cancellationToken); + } +} + +public class FinanceCompanyAccountRepository + : OmsSqlSugarRepository, IFinanceCompanyAccountRepository, IScopedDependency +{ +} + +public class FinanceContractRepository + : OmsSqlSugarRepository, IFinanceContractRepository, IScopedDependency +{ + public Task ExistsContractNoAsync(string contractNo, CancellationToken cancellationToken = default) + { + return AnyAsync(x => x.ContractNo == contractNo, cancellationToken); + } + + public async Task GetActiveByPartyAsync( + string partyType, + int partyId, + int? excludeId = null, + CancellationToken cancellationToken = default) + { + if (excludeId is > 0) + { + return await FirstOrDefaultAsync( + x => x.PartyType == partyType + && x.PartyId == partyId + && x.Status == FinanceContractStatusCodes.Active + && x.Id != excludeId.Value, + cancellationToken); + } + + return await FirstOrDefaultAsync( + x => x.PartyType == partyType + && x.PartyId == partyId + && x.Status == FinanceContractStatusCodes.Active, + cancellationToken); + } +} + +public class FinancePaymentApplyRepository + : OmsSqlSugarRepository, IFinancePaymentApplyRepository, IScopedDependency +{ + public Task ExistsApplyNoAsync(string applyNo, CancellationToken cancellationToken = default) + { + return AnyAsync(x => x.ApplyNo == applyNo, cancellationToken); + } +} + +public class FinancePaymentApplyLineRepository + : OmsSqlSugarRepository, IFinancePaymentApplyLineRepository, IScopedDependency +{ + public Task> GetListByApplyIdAsync( + int paymentApplyId, + CancellationToken cancellationToken = default) + { + return GetListAsync(x => x.PaymentApplyId == paymentApplyId, cancellationToken: cancellationToken); + } + + public async Task DeleteByApplyIdAsync(int paymentApplyId, CancellationToken cancellationToken = default) + { + var lines = await GetListByApplyIdAsync(paymentApplyId, cancellationToken); + foreach (var line in lines) + { + await DeleteAsync(line, cancellationToken); + } + } +}