From c7264cc50d9d77f5534bfc0e7802cc4999cde52a Mon Sep 17 00:00:00 2001 From: GEEKi Date: Mon, 16 Nov 2026 18:25:21 +0800 Subject: [PATCH] Initial commit --- .gitignore | 28 + Leiren.Erp.slnx | 12 + .../appsettings.Production.example.json | 28 + deploy/windows/backup.example.json | 18 + docs/01-总体业务流程设计.md | 359 ++++ docs/02-产品与样品库设计.md | 374 ++++ docs/03-数据库迁移与导入设计.md | 418 ++++ docs/04-系统架构与技术设计.md | 810 +++++++ docs/05-部署与备份运维.md | 105 + docs/启动文档.md | 484 +++++ migration/README.md | 73 + src/Leiren.Erp.Api/AuthorizationEndpoints.cs | 95 + src/Leiren.Erp.Api/BearerAuthorization.cs | 127 ++ src/Leiren.Erp.Api/BillingEndpoints.cs | 122 ++ src/Leiren.Erp.Api/CatalogEndpoints.cs | 141 ++ src/Leiren.Erp.Api/CiPlDocumentEndpoints.cs | 52 + src/Leiren.Erp.Api/CustomsEndpoints.cs | 94 + src/Leiren.Erp.Api/DashboardEndpoints.cs | 14 + .../DocumentTemplateEndpoints.cs | 115 + .../DocumentTemplateMappingEndpoints.cs | 104 + src/Leiren.Erp.Api/FileEndpoints.cs | 129 ++ src/Leiren.Erp.Api/FinanceEndpoints.cs | 40 + src/Leiren.Erp.Api/HealthEndpoints.cs | 129 ++ src/Leiren.Erp.Api/Leiren.Erp.Api.csproj | 28 + src/Leiren.Erp.Api/Leiren.Erp.Api.http | 54 + src/Leiren.Erp.Api/MasterDataEndpoints.cs | 64 + src/Leiren.Erp.Api/Program.cs | 398 ++++ .../Properties/launchSettings.json | 14 + src/Leiren.Erp.Api/PurchasingEndpoints.cs | 128 ++ src/Leiren.Erp.Api/SalesOrderEndpoints.cs | 85 + .../SalesOrderImportEndpoints.cs | 119 ++ src/Leiren.Erp.Api/ShippingEndpoints.cs | 87 + .../appsettings.Development.json | 14 + src/Leiren.Erp.Api/appsettings.json | 27 + .../templates/billing/开票购销合同.xlsx | Bin 0 -> 8498 bytes .../templates/billing/开票通知.xlsx | Bin 0 -> 6825 bytes .../templates/customs/报关单.xlsx | Bin 0 -> 15736 bytes .../templates/customs/报关发票.xlsx | Bin 0 -> 35705 bytes .../templates/customs/报关外销合同.xlsx | Bin 0 -> 40453 bytes .../templates/customs/报关装箱单.xlsx | Bin 0 -> 35927 bytes .../templates/purchase-contract.xlsx | Bin 0 -> 10946 bytes .../Billing/BillingDocumentExportService.cs | 77 + .../Billing/BillingDocumentRenderer.cs | 192 ++ .../Billing/BillingExceptions.cs | 16 + .../Billing/BillingService.cs | 843 ++++++++ .../Billing/IBillingDbContext.cs | 26 + .../Catalog/CatalogExceptions.cs | 16 + .../Catalog/ICatalogDbContext.cs | 16 + .../Catalog/ProductService.cs | 727 +++++++ src/Leiren.Erp.Application/Class1.cs | 6 + .../Customs/CiPlDocumentGenerationService.cs | 204 ++ .../Customs/CiPlTemplateRenderer.cs | 412 ++++ .../Customs/CustomsExceptions.cs | 16 + .../Customs/CustomsService.cs | 527 +++++ .../Customs/DocumentRenderSource.cs | 34 + .../Customs/DocumentTemplateCatalogService.cs | 168 ++ .../Customs/DocumentTemplateFields.cs | 104 + .../Customs/DocumentTemplateMappingService.cs | 432 ++++ .../Customs/ICustomsDbContext.cs | 23 + .../IDocumentTemplateMappingDbContext.cs | 19 + .../Dashboard/DashboardService.cs | 46 + .../Dashboard/IDashboardDbContext.cs | 16 + .../Documents/DocumentTemplateKinds.cs | 40 + .../Documents/DocumentTemplateService.cs | 172 ++ .../Documents/TemplatePlaceholderScanner.cs | 249 +++ .../Documents/TokenWorkbookRenderer.cs | 214 ++ .../Files/FileService.cs | 356 ++++ .../Files/FilesExceptions.cs | 16 + .../Files/IFileStorage.cs | 53 + .../Files/IFilesDbContext.cs | 12 + .../Finance/PayableService.cs | 83 + .../Identity/IIdentityDbContext.cs | 17 + .../Identity/IdentityExceptions.cs | 16 + .../Identity/IdentityService.cs | 364 ++++ .../Leiren.Erp.Application.csproj | 19 + .../MasterData/IMasterDataDbContext.cs | 22 + .../MasterData/MasterDataExceptions.cs | 16 + .../MasterData/SupplierService.cs | 131 ++ .../Purchasing/IPurchasingDbContext.cs | 25 + .../PurchaseContractExportService.cs | 114 + .../PurchaseContractTemplateRenderer.cs | 104 + .../Purchasing/PurchaseService.cs | 723 +++++++ .../Purchasing/PurchasingExceptions.cs | 16 + .../Sales/ISalesDbContext.cs | 25 + .../Sales/PoExcelImportService.cs | 727 +++++++ .../Sales/SalesExceptions.cs | 16 + .../Sales/SalesOrderService.cs | 587 +++++ .../Shipping/IShippingDbContext.cs | 23 + .../Shipping/ShippingExceptions.cs | 16 + .../Shipping/ShippingService.cs | 630 ++++++ .../Leiren.Erp.Backup.csproj | 14 + src/Leiren.Erp.Backup/Program.cs | 262 +++ src/Leiren.Erp.Client/ApiClient.cs | 259 +++ src/Leiren.Erp.Client/App.xaml | 220 ++ src/Leiren.Erp.Client/App.xaml.cs | 70 + src/Leiren.Erp.Client/AssemblyInfo.cs | 10 + src/Leiren.Erp.Client/ClientSettings.cs | 120 ++ src/Leiren.Erp.Client/Controls/DialogKit.cs | 84 + .../Controls/DisplayTextConverter.cs | 20 + src/Leiren.Erp.Client/Controls/FluentIcons.cs | 43 + src/Leiren.Erp.Client/Controls/PageFrame.cs | 35 + .../Controls/XlsxPreviewView.cs | 233 ++ .../Documents/BillingAllocationWindow.cs | 223 ++ .../Documents/BillingNoticeEditWindow.cs | 146 ++ .../Documents/BillingNoticeWindow.cs | 138 ++ .../Documents/ContainerNumbersWindow.cs | 119 ++ .../Documents/CustomsDeclarationWindow.cs | 299 +++ .../Documents/PayableConfirmWindow.cs | 82 + .../SupplierInvoiceRegisterWindow.cs | 104 + .../Documents/TemplateImportWindow.cs | 147 ++ .../Documents/TemplateMappingWindow.cs | 191 ++ .../Documents/TemplatePreviewWindow.cs | 163 ++ .../Leiren.Erp.Client.csproj | 18 + src/Leiren.Erp.Client/LoginWindow.xaml | 24 + src/Leiren.Erp.Client/LoginWindow.xaml.cs | 75 + src/Leiren.Erp.Client/MainWindow.xaml | 108 + src/Leiren.Erp.Client/MainWindow.xaml.cs | 176 ++ src/Leiren.Erp.Client/Pages/CustomerPage.xaml | 87 + .../Pages/CustomerPage.xaml.cs | 143 ++ src/Leiren.Erp.Client/Pages/FlowWorkspace.cs | 1894 +++++++++++++++++ src/Leiren.Erp.Client/Pages/ILoadablePage.cs | 6 + src/Leiren.Erp.Client/Pages/ProductPage.xaml | 99 + .../Pages/ProductPage.xaml.cs | 392 ++++ src/Leiren.Erp.Client/Pages/SettingsPage.xaml | 137 ++ .../Pages/SettingsPage.xaml.cs | 333 +++ src/Leiren.Erp.Client/Pages/SupplierPage.xaml | 91 + .../Pages/SupplierPage.xaml.cs | 237 +++ .../ProductCatalog/ProductEditWindow.xaml | 143 ++ .../ProductCatalog/ProductEditWindow.xaml.cs | 264 +++ .../ProductCatalog/ProductPartEditWindow.xaml | 61 + .../ProductPartEditWindow.xaml.cs | 92 + .../SupplierQuoteEditWindow.xaml | 85 + .../SupplierQuoteEditWindow.xaml.cs | 189 ++ .../Shipping/ContainerLoadCalculator.cs | 54 + .../Wizards/ContractEditWindow.xaml | 36 + .../Wizards/ContractEditWindow.xaml.cs | 72 + .../Wizards/ContractPreviewWindow.xaml | 30 + .../Wizards/ContractPreviewWindow.xaml.cs | 61 + .../Wizards/CreateCustomerWizardWindow.xaml | 97 + .../CreateCustomerWizardWindow.xaml.cs | 168 ++ .../Wizards/CreateRoleWizardWindow.xaml | 66 + .../Wizards/CreateRoleWizardWindow.xaml.cs | 155 ++ .../Wizards/CreateSupplierWizardWindow.xaml | 97 + .../CreateSupplierWizardWindow.xaml.cs | 191 ++ .../Wizards/CreateUserWizardWindow.xaml | 68 + .../Wizards/CreateUserWizardWindow.xaml.cs | 163 ++ .../Wizards/FlowWizardWindow.Documents.cs | 195 ++ .../Wizards/FlowWizardWindow.Order.cs | 322 +++ .../Wizards/FlowWizardWindow.Shipping.cs | 396 ++++ .../Wizards/FlowWizardWindow.cs | 1294 +++++++++++ src/Leiren.Erp.Contracts/AuthContracts.cs | 6 + .../AuthorizationContracts.cs | 63 + src/Leiren.Erp.Contracts/BillingContracts.cs | 344 +++ src/Leiren.Erp.Contracts/CatalogContracts.cs | 189 ++ .../CiPlGenerationContracts.cs | 20 + src/Leiren.Erp.Contracts/Class1.cs | 6 + src/Leiren.Erp.Contracts/CustomsContracts.cs | 199 ++ .../DashboardContracts.cs | 17 + .../DocumentTemplateContracts.cs | 90 + .../DocumentTemplateMappingContracts.cs | 75 + src/Leiren.Erp.Contracts/FileContracts.cs | 40 + src/Leiren.Erp.Contracts/FinanceContracts.cs | 31 + .../Leiren.Erp.Contracts.csproj | 9 + .../MasterDataContracts.cs | 34 + src/Leiren.Erp.Contracts/PoImportContracts.cs | 61 + .../PurchasingContracts.cs | 264 +++ src/Leiren.Erp.Contracts/SalesContracts.cs | 206 ++ src/Leiren.Erp.Contracts/ShippingContracts.cs | 220 ++ .../Authorization/AuthorizationCatalog.cs | 86 + src/Leiren.Erp.Domain/Class1.cs | 6 + .../Entities/AppPermission.cs | 13 + src/Leiren.Erp.Domain/Entities/AppRole.cs | 15 + src/Leiren.Erp.Domain/Entities/AppUser.cs | 14 + .../Entities/AuthorizationAssignments.cs | 27 + src/Leiren.Erp.Domain/Entities/Customer.cs | 25 + .../Entities/CustomsDeclaration.cs | 103 + .../Entities/CustomsDeclarationLine.cs | 52 + .../Entities/DocumentPackage.cs | 89 + .../Entities/DocumentTemplateFieldMapping.cs | 36 + .../DocumentTemplateMappingProfile.cs | 58 + .../Entities/FileAttachment.cs | 56 + src/Leiren.Erp.Domain/Entities/Product.cs | 95 + .../Entities/ProductChangeLog.cs | 29 + src/Leiren.Erp.Domain/Entities/ProductPart.cs | 24 + .../Entities/ProductSupplierQuote.cs | 39 + .../Entities/PurchaseArrival.cs | 35 + .../Entities/PurchaseContract.cs | 99 + .../Entities/PurchaseTask.cs | 102 + .../Entities/RefreshSession.cs | 17 + src/Leiren.Erp.Domain/Entities/SalesOrder.cs | 74 + .../Entities/SalesOrderLine.cs | 40 + .../Entities/ShipmentLine.cs | 67 + .../Entities/ShippingBatch.cs | 87 + .../Entities/ShippingContainer.cs | 22 + src/Leiren.Erp.Domain/Entities/Supplier.cs | 30 + .../Entities/SupplierBillingContract.cs | 65 + .../Entities/SupplierInvoice.cs | 78 + .../Entities/SupplierInvoiceNotice.cs | 174 ++ .../Entities/SupplierInvoiceNoticeLine.cs | 56 + .../Entities/SupplierPayable.cs | 71 + src/Leiren.Erp.Domain/Enums/BillingEnums.cs | 30 + src/Leiren.Erp.Domain/Enums/CatalogEnums.cs | 50 + src/Leiren.Erp.Domain/Enums/CustomsEnums.cs | 28 + .../Enums/DocumentTemplateEnums.cs | 14 + src/Leiren.Erp.Domain/Enums/FinanceEnums.cs | 8 + .../Enums/PurchasingEnums.cs | 19 + .../Enums/SalesOrderEnums.cs | 9 + src/Leiren.Erp.Domain/Enums/ShippingEnums.cs | 8 + .../Leiren.Erp.Domain.csproj | 9 + .../Backup/BackupModels.cs | 93 + .../Backup/FileBackupService.cs | 609 ++++++ src/Leiren.Erp.Infrastructure/Class1.cs | 6 + .../Files/LocalFileStorage.cs | 114 + .../Leiren.Erp.Infrastructure.csproj | 18 + .../Persistence/CustomsSchemaInitializer.cs | 57 + .../Persistence/DatabaseOptions.cs | 159 ++ .../Persistence/ErpDbContext.cs | 661 ++++++ .../Persistence/IdentitySchemaInitializer.cs | 78 + .../RefreshSessionSchemaInitializer.cs | 68 + .../SupplierPayableSchemaInitializer.cs | 62 + .../Legacy/LegacyFormalImporter.cs | 550 +++++ .../Legacy/LegacyMapping.cs | 188 ++ .../Legacy/LegacyProductImageExtractor.cs | 215 ++ .../Legacy/LegacyStagingModels.cs | 61 + .../Legacy/LegacyStagingStore.cs | 284 +++ src/Leiren.Erp.Migration/LegacySqlParser.cs | 967 +++++++++ .../Leiren.Erp.Migration.csproj | 20 + src/Leiren.Erp.Migration/MigrationModels.cs | 303 +++ src/Leiren.Erp.Migration/Program.cs | 501 +++++ 229 files changed, 33543 insertions(+) create mode 100644 .gitignore create mode 100644 Leiren.Erp.slnx create mode 100644 deploy/windows/appsettings.Production.example.json create mode 100644 deploy/windows/backup.example.json create mode 100644 docs/01-总体业务流程设计.md create mode 100644 docs/02-产品与样品库设计.md create mode 100644 docs/03-数据库迁移与导入设计.md create mode 100644 docs/04-系统架构与技术设计.md create mode 100644 docs/05-部署与备份运维.md create mode 100644 docs/启动文档.md create mode 100644 migration/README.md create mode 100644 src/Leiren.Erp.Api/AuthorizationEndpoints.cs create mode 100644 src/Leiren.Erp.Api/BearerAuthorization.cs create mode 100644 src/Leiren.Erp.Api/BillingEndpoints.cs create mode 100644 src/Leiren.Erp.Api/CatalogEndpoints.cs create mode 100644 src/Leiren.Erp.Api/CiPlDocumentEndpoints.cs create mode 100644 src/Leiren.Erp.Api/CustomsEndpoints.cs create mode 100644 src/Leiren.Erp.Api/DashboardEndpoints.cs create mode 100644 src/Leiren.Erp.Api/DocumentTemplateEndpoints.cs create mode 100644 src/Leiren.Erp.Api/DocumentTemplateMappingEndpoints.cs create mode 100644 src/Leiren.Erp.Api/FileEndpoints.cs create mode 100644 src/Leiren.Erp.Api/FinanceEndpoints.cs create mode 100644 src/Leiren.Erp.Api/HealthEndpoints.cs create mode 100644 src/Leiren.Erp.Api/Leiren.Erp.Api.csproj create mode 100644 src/Leiren.Erp.Api/Leiren.Erp.Api.http create mode 100644 src/Leiren.Erp.Api/MasterDataEndpoints.cs create mode 100644 src/Leiren.Erp.Api/Program.cs create mode 100644 src/Leiren.Erp.Api/Properties/launchSettings.json create mode 100644 src/Leiren.Erp.Api/PurchasingEndpoints.cs create mode 100644 src/Leiren.Erp.Api/SalesOrderEndpoints.cs create mode 100644 src/Leiren.Erp.Api/SalesOrderImportEndpoints.cs create mode 100644 src/Leiren.Erp.Api/ShippingEndpoints.cs create mode 100644 src/Leiren.Erp.Api/appsettings.Development.json create mode 100644 src/Leiren.Erp.Api/appsettings.json create mode 100644 src/Leiren.Erp.Api/templates/billing/开票购销合同.xlsx create mode 100644 src/Leiren.Erp.Api/templates/billing/开票通知.xlsx create mode 100644 src/Leiren.Erp.Api/templates/customs/报关单.xlsx create mode 100644 src/Leiren.Erp.Api/templates/customs/报关发票.xlsx create mode 100644 src/Leiren.Erp.Api/templates/customs/报关外销合同.xlsx create mode 100644 src/Leiren.Erp.Api/templates/customs/报关装箱单.xlsx create mode 100644 src/Leiren.Erp.Api/templates/purchase-contract.xlsx create mode 100644 src/Leiren.Erp.Application/Billing/BillingDocumentExportService.cs create mode 100644 src/Leiren.Erp.Application/Billing/BillingDocumentRenderer.cs create mode 100644 src/Leiren.Erp.Application/Billing/BillingExceptions.cs create mode 100644 src/Leiren.Erp.Application/Billing/BillingService.cs create mode 100644 src/Leiren.Erp.Application/Billing/IBillingDbContext.cs create mode 100644 src/Leiren.Erp.Application/Catalog/CatalogExceptions.cs create mode 100644 src/Leiren.Erp.Application/Catalog/ICatalogDbContext.cs create mode 100644 src/Leiren.Erp.Application/Catalog/ProductService.cs create mode 100644 src/Leiren.Erp.Application/Class1.cs create mode 100644 src/Leiren.Erp.Application/Customs/CiPlDocumentGenerationService.cs create mode 100644 src/Leiren.Erp.Application/Customs/CiPlTemplateRenderer.cs create mode 100644 src/Leiren.Erp.Application/Customs/CustomsExceptions.cs create mode 100644 src/Leiren.Erp.Application/Customs/CustomsService.cs create mode 100644 src/Leiren.Erp.Application/Customs/DocumentRenderSource.cs create mode 100644 src/Leiren.Erp.Application/Customs/DocumentTemplateCatalogService.cs create mode 100644 src/Leiren.Erp.Application/Customs/DocumentTemplateFields.cs create mode 100644 src/Leiren.Erp.Application/Customs/DocumentTemplateMappingService.cs create mode 100644 src/Leiren.Erp.Application/Customs/ICustomsDbContext.cs create mode 100644 src/Leiren.Erp.Application/Customs/IDocumentTemplateMappingDbContext.cs create mode 100644 src/Leiren.Erp.Application/Dashboard/DashboardService.cs create mode 100644 src/Leiren.Erp.Application/Dashboard/IDashboardDbContext.cs create mode 100644 src/Leiren.Erp.Application/Documents/DocumentTemplateKinds.cs create mode 100644 src/Leiren.Erp.Application/Documents/DocumentTemplateService.cs create mode 100644 src/Leiren.Erp.Application/Documents/TemplatePlaceholderScanner.cs create mode 100644 src/Leiren.Erp.Application/Documents/TokenWorkbookRenderer.cs create mode 100644 src/Leiren.Erp.Application/Files/FileService.cs create mode 100644 src/Leiren.Erp.Application/Files/FilesExceptions.cs create mode 100644 src/Leiren.Erp.Application/Files/IFileStorage.cs create mode 100644 src/Leiren.Erp.Application/Files/IFilesDbContext.cs create mode 100644 src/Leiren.Erp.Application/Finance/PayableService.cs create mode 100644 src/Leiren.Erp.Application/Identity/IIdentityDbContext.cs create mode 100644 src/Leiren.Erp.Application/Identity/IdentityExceptions.cs create mode 100644 src/Leiren.Erp.Application/Identity/IdentityService.cs create mode 100644 src/Leiren.Erp.Application/Leiren.Erp.Application.csproj create mode 100644 src/Leiren.Erp.Application/MasterData/IMasterDataDbContext.cs create mode 100644 src/Leiren.Erp.Application/MasterData/MasterDataExceptions.cs create mode 100644 src/Leiren.Erp.Application/MasterData/SupplierService.cs create mode 100644 src/Leiren.Erp.Application/Purchasing/IPurchasingDbContext.cs create mode 100644 src/Leiren.Erp.Application/Purchasing/PurchaseContractExportService.cs create mode 100644 src/Leiren.Erp.Application/Purchasing/PurchaseContractTemplateRenderer.cs create mode 100644 src/Leiren.Erp.Application/Purchasing/PurchaseService.cs create mode 100644 src/Leiren.Erp.Application/Purchasing/PurchasingExceptions.cs create mode 100644 src/Leiren.Erp.Application/Sales/ISalesDbContext.cs create mode 100644 src/Leiren.Erp.Application/Sales/PoExcelImportService.cs create mode 100644 src/Leiren.Erp.Application/Sales/SalesExceptions.cs create mode 100644 src/Leiren.Erp.Application/Sales/SalesOrderService.cs create mode 100644 src/Leiren.Erp.Application/Shipping/IShippingDbContext.cs create mode 100644 src/Leiren.Erp.Application/Shipping/ShippingExceptions.cs create mode 100644 src/Leiren.Erp.Application/Shipping/ShippingService.cs create mode 100644 src/Leiren.Erp.Backup/Leiren.Erp.Backup.csproj create mode 100644 src/Leiren.Erp.Backup/Program.cs create mode 100644 src/Leiren.Erp.Client/ApiClient.cs create mode 100644 src/Leiren.Erp.Client/App.xaml create mode 100644 src/Leiren.Erp.Client/App.xaml.cs create mode 100644 src/Leiren.Erp.Client/AssemblyInfo.cs create mode 100644 src/Leiren.Erp.Client/ClientSettings.cs create mode 100644 src/Leiren.Erp.Client/Controls/DialogKit.cs create mode 100644 src/Leiren.Erp.Client/Controls/DisplayTextConverter.cs create mode 100644 src/Leiren.Erp.Client/Controls/FluentIcons.cs create mode 100644 src/Leiren.Erp.Client/Controls/PageFrame.cs create mode 100644 src/Leiren.Erp.Client/Controls/XlsxPreviewView.cs create mode 100644 src/Leiren.Erp.Client/Documents/BillingAllocationWindow.cs create mode 100644 src/Leiren.Erp.Client/Documents/BillingNoticeEditWindow.cs create mode 100644 src/Leiren.Erp.Client/Documents/BillingNoticeWindow.cs create mode 100644 src/Leiren.Erp.Client/Documents/ContainerNumbersWindow.cs create mode 100644 src/Leiren.Erp.Client/Documents/CustomsDeclarationWindow.cs create mode 100644 src/Leiren.Erp.Client/Documents/PayableConfirmWindow.cs create mode 100644 src/Leiren.Erp.Client/Documents/SupplierInvoiceRegisterWindow.cs create mode 100644 src/Leiren.Erp.Client/Documents/TemplateImportWindow.cs create mode 100644 src/Leiren.Erp.Client/Documents/TemplateMappingWindow.cs create mode 100644 src/Leiren.Erp.Client/Documents/TemplatePreviewWindow.cs create mode 100644 src/Leiren.Erp.Client/Leiren.Erp.Client.csproj create mode 100644 src/Leiren.Erp.Client/LoginWindow.xaml create mode 100644 src/Leiren.Erp.Client/LoginWindow.xaml.cs create mode 100644 src/Leiren.Erp.Client/MainWindow.xaml create mode 100644 src/Leiren.Erp.Client/MainWindow.xaml.cs create mode 100644 src/Leiren.Erp.Client/Pages/CustomerPage.xaml create mode 100644 src/Leiren.Erp.Client/Pages/CustomerPage.xaml.cs create mode 100644 src/Leiren.Erp.Client/Pages/FlowWorkspace.cs create mode 100644 src/Leiren.Erp.Client/Pages/ILoadablePage.cs create mode 100644 src/Leiren.Erp.Client/Pages/ProductPage.xaml create mode 100644 src/Leiren.Erp.Client/Pages/ProductPage.xaml.cs create mode 100644 src/Leiren.Erp.Client/Pages/SettingsPage.xaml create mode 100644 src/Leiren.Erp.Client/Pages/SettingsPage.xaml.cs create mode 100644 src/Leiren.Erp.Client/Pages/SupplierPage.xaml create mode 100644 src/Leiren.Erp.Client/Pages/SupplierPage.xaml.cs create mode 100644 src/Leiren.Erp.Client/ProductCatalog/ProductEditWindow.xaml create mode 100644 src/Leiren.Erp.Client/ProductCatalog/ProductEditWindow.xaml.cs create mode 100644 src/Leiren.Erp.Client/ProductCatalog/ProductPartEditWindow.xaml create mode 100644 src/Leiren.Erp.Client/ProductCatalog/ProductPartEditWindow.xaml.cs create mode 100644 src/Leiren.Erp.Client/ProductCatalog/SupplierQuoteEditWindow.xaml create mode 100644 src/Leiren.Erp.Client/ProductCatalog/SupplierQuoteEditWindow.xaml.cs create mode 100644 src/Leiren.Erp.Client/Shipping/ContainerLoadCalculator.cs create mode 100644 src/Leiren.Erp.Client/Wizards/ContractEditWindow.xaml create mode 100644 src/Leiren.Erp.Client/Wizards/ContractEditWindow.xaml.cs create mode 100644 src/Leiren.Erp.Client/Wizards/ContractPreviewWindow.xaml create mode 100644 src/Leiren.Erp.Client/Wizards/ContractPreviewWindow.xaml.cs create mode 100644 src/Leiren.Erp.Client/Wizards/CreateCustomerWizardWindow.xaml create mode 100644 src/Leiren.Erp.Client/Wizards/CreateCustomerWizardWindow.xaml.cs create mode 100644 src/Leiren.Erp.Client/Wizards/CreateRoleWizardWindow.xaml create mode 100644 src/Leiren.Erp.Client/Wizards/CreateRoleWizardWindow.xaml.cs create mode 100644 src/Leiren.Erp.Client/Wizards/CreateSupplierWizardWindow.xaml create mode 100644 src/Leiren.Erp.Client/Wizards/CreateSupplierWizardWindow.xaml.cs create mode 100644 src/Leiren.Erp.Client/Wizards/CreateUserWizardWindow.xaml create mode 100644 src/Leiren.Erp.Client/Wizards/CreateUserWizardWindow.xaml.cs create mode 100644 src/Leiren.Erp.Client/Wizards/FlowWizardWindow.Documents.cs create mode 100644 src/Leiren.Erp.Client/Wizards/FlowWizardWindow.Order.cs create mode 100644 src/Leiren.Erp.Client/Wizards/FlowWizardWindow.Shipping.cs create mode 100644 src/Leiren.Erp.Client/Wizards/FlowWizardWindow.cs create mode 100644 src/Leiren.Erp.Contracts/AuthContracts.cs create mode 100644 src/Leiren.Erp.Contracts/AuthorizationContracts.cs create mode 100644 src/Leiren.Erp.Contracts/BillingContracts.cs create mode 100644 src/Leiren.Erp.Contracts/CatalogContracts.cs create mode 100644 src/Leiren.Erp.Contracts/CiPlGenerationContracts.cs create mode 100644 src/Leiren.Erp.Contracts/Class1.cs create mode 100644 src/Leiren.Erp.Contracts/CustomsContracts.cs create mode 100644 src/Leiren.Erp.Contracts/DashboardContracts.cs create mode 100644 src/Leiren.Erp.Contracts/DocumentTemplateContracts.cs create mode 100644 src/Leiren.Erp.Contracts/DocumentTemplateMappingContracts.cs create mode 100644 src/Leiren.Erp.Contracts/FileContracts.cs create mode 100644 src/Leiren.Erp.Contracts/FinanceContracts.cs create mode 100644 src/Leiren.Erp.Contracts/Leiren.Erp.Contracts.csproj create mode 100644 src/Leiren.Erp.Contracts/MasterDataContracts.cs create mode 100644 src/Leiren.Erp.Contracts/PoImportContracts.cs create mode 100644 src/Leiren.Erp.Contracts/PurchasingContracts.cs create mode 100644 src/Leiren.Erp.Contracts/SalesContracts.cs create mode 100644 src/Leiren.Erp.Contracts/ShippingContracts.cs create mode 100644 src/Leiren.Erp.Domain/Authorization/AuthorizationCatalog.cs create mode 100644 src/Leiren.Erp.Domain/Class1.cs create mode 100644 src/Leiren.Erp.Domain/Entities/AppPermission.cs create mode 100644 src/Leiren.Erp.Domain/Entities/AppRole.cs create mode 100644 src/Leiren.Erp.Domain/Entities/AppUser.cs create mode 100644 src/Leiren.Erp.Domain/Entities/AuthorizationAssignments.cs create mode 100644 src/Leiren.Erp.Domain/Entities/Customer.cs create mode 100644 src/Leiren.Erp.Domain/Entities/CustomsDeclaration.cs create mode 100644 src/Leiren.Erp.Domain/Entities/CustomsDeclarationLine.cs create mode 100644 src/Leiren.Erp.Domain/Entities/DocumentPackage.cs create mode 100644 src/Leiren.Erp.Domain/Entities/DocumentTemplateFieldMapping.cs create mode 100644 src/Leiren.Erp.Domain/Entities/DocumentTemplateMappingProfile.cs create mode 100644 src/Leiren.Erp.Domain/Entities/FileAttachment.cs create mode 100644 src/Leiren.Erp.Domain/Entities/Product.cs create mode 100644 src/Leiren.Erp.Domain/Entities/ProductChangeLog.cs create mode 100644 src/Leiren.Erp.Domain/Entities/ProductPart.cs create mode 100644 src/Leiren.Erp.Domain/Entities/ProductSupplierQuote.cs create mode 100644 src/Leiren.Erp.Domain/Entities/PurchaseArrival.cs create mode 100644 src/Leiren.Erp.Domain/Entities/PurchaseContract.cs create mode 100644 src/Leiren.Erp.Domain/Entities/PurchaseTask.cs create mode 100644 src/Leiren.Erp.Domain/Entities/RefreshSession.cs create mode 100644 src/Leiren.Erp.Domain/Entities/SalesOrder.cs create mode 100644 src/Leiren.Erp.Domain/Entities/SalesOrderLine.cs create mode 100644 src/Leiren.Erp.Domain/Entities/ShipmentLine.cs create mode 100644 src/Leiren.Erp.Domain/Entities/ShippingBatch.cs create mode 100644 src/Leiren.Erp.Domain/Entities/ShippingContainer.cs create mode 100644 src/Leiren.Erp.Domain/Entities/Supplier.cs create mode 100644 src/Leiren.Erp.Domain/Entities/SupplierBillingContract.cs create mode 100644 src/Leiren.Erp.Domain/Entities/SupplierInvoice.cs create mode 100644 src/Leiren.Erp.Domain/Entities/SupplierInvoiceNotice.cs create mode 100644 src/Leiren.Erp.Domain/Entities/SupplierInvoiceNoticeLine.cs create mode 100644 src/Leiren.Erp.Domain/Entities/SupplierPayable.cs create mode 100644 src/Leiren.Erp.Domain/Enums/BillingEnums.cs create mode 100644 src/Leiren.Erp.Domain/Enums/CatalogEnums.cs create mode 100644 src/Leiren.Erp.Domain/Enums/CustomsEnums.cs create mode 100644 src/Leiren.Erp.Domain/Enums/DocumentTemplateEnums.cs create mode 100644 src/Leiren.Erp.Domain/Enums/FinanceEnums.cs create mode 100644 src/Leiren.Erp.Domain/Enums/PurchasingEnums.cs create mode 100644 src/Leiren.Erp.Domain/Enums/SalesOrderEnums.cs create mode 100644 src/Leiren.Erp.Domain/Enums/ShippingEnums.cs create mode 100644 src/Leiren.Erp.Domain/Leiren.Erp.Domain.csproj create mode 100644 src/Leiren.Erp.Infrastructure/Backup/BackupModels.cs create mode 100644 src/Leiren.Erp.Infrastructure/Backup/FileBackupService.cs create mode 100644 src/Leiren.Erp.Infrastructure/Class1.cs create mode 100644 src/Leiren.Erp.Infrastructure/Files/LocalFileStorage.cs create mode 100644 src/Leiren.Erp.Infrastructure/Leiren.Erp.Infrastructure.csproj create mode 100644 src/Leiren.Erp.Infrastructure/Persistence/CustomsSchemaInitializer.cs create mode 100644 src/Leiren.Erp.Infrastructure/Persistence/DatabaseOptions.cs create mode 100644 src/Leiren.Erp.Infrastructure/Persistence/ErpDbContext.cs create mode 100644 src/Leiren.Erp.Infrastructure/Persistence/IdentitySchemaInitializer.cs create mode 100644 src/Leiren.Erp.Infrastructure/Persistence/RefreshSessionSchemaInitializer.cs create mode 100644 src/Leiren.Erp.Infrastructure/Persistence/SupplierPayableSchemaInitializer.cs create mode 100644 src/Leiren.Erp.Migration/Legacy/LegacyFormalImporter.cs create mode 100644 src/Leiren.Erp.Migration/Legacy/LegacyMapping.cs create mode 100644 src/Leiren.Erp.Migration/Legacy/LegacyProductImageExtractor.cs create mode 100644 src/Leiren.Erp.Migration/Legacy/LegacyStagingModels.cs create mode 100644 src/Leiren.Erp.Migration/Legacy/LegacyStagingStore.cs create mode 100644 src/Leiren.Erp.Migration/LegacySqlParser.cs create mode 100644 src/Leiren.Erp.Migration/Leiren.Erp.Migration.csproj create mode 100644 src/Leiren.Erp.Migration/MigrationModels.cs create mode 100644 src/Leiren.Erp.Migration/Program.cs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7656b67 --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +# Whitelist: the repository holds only source code and what the build needs. +# Everything at the root is ignored unless re-included below (logs, backups, +# legacy SQL dumps, extracted images, sample documents, temp output, .vs). +/* +!/.gitignore +!/Leiren.Erp.slnx +!/src/ +!/deploy/ +!/docs/ +!/migration/ + +# Build output and IDE state +bin/ +obj/ +.vs/ +*.user + +# Local runtime data: SQLite databases, uploaded files, scratch output +src/**/data/ +src/**/temp/ +*.db +*.db-shm +*.db-wal +*.log + +# Docs: keep the markdown, not prototype pages +/docs/* +!/docs/*.md diff --git a/Leiren.Erp.slnx b/Leiren.Erp.slnx new file mode 100644 index 0000000..32c6bd9 --- /dev/null +++ b/Leiren.Erp.slnx @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/deploy/windows/appsettings.Production.example.json b/deploy/windows/appsettings.Production.example.json new file mode 100644 index 0000000..8cc7d4b --- /dev/null +++ b/deploy/windows/appsettings.Production.example.json @@ -0,0 +1,28 @@ +{ + "Urls": "http://*:5118", + "AllowedHosts": "*", + "Database": { + "Provider": "PostgreSql" + }, + "ConnectionStrings": { + "Default": "Host=127.0.0.1;Port=5432;Database=leiren_erp;Username=leiren_erp;Password=CHANGE_ME_VIA_ENVIRONMENT" + }, + "HealthChecks": { + "DatabaseTimeout": "00:00:05" + }, + "FileStorage": { + "RootPath": "D:\\LeirenErpData\\storage", + "MaxFileSizeBytes": 52428800, + "AllowedExtensions": [ + ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", + ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", + ".txt", ".csv", ".zip", ".rar", ".7z" + ] + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/deploy/windows/backup.example.json b/deploy/windows/backup.example.json new file mode 100644 index 0000000..867fc3a --- /dev/null +++ b/deploy/windows/backup.example.json @@ -0,0 +1,18 @@ +{ + "Sources": [ + { + "Name": "FileStorage", + "Path": "D:\\LeirenErpData\\storage" + }, + { + "Name": "Templates", + "Path": "D:\\LeirenErpData\\templates" + } + ], + "DestinationPath": "E:\\LeirenErpBackups", + "IncludeDatabase": true, + "DatabaseProvider": "PostgreSql", + "DatabaseConnectionString": "", + "PgDumpPath": "C:\\Program Files\\PostgreSQL\\17\\bin\\pg_dump.exe", + "AllowEmpty": false +} diff --git a/docs/01-总体业务流程设计.md b/docs/01-总体业务流程设计.md new file mode 100644 index 0000000..f1e1430 --- /dev/null +++ b/docs/01-总体业务流程设计.md @@ -0,0 +1,359 @@ +# 简化 ERP 总体业务流程设计 + +## 1. 目标 + +系统服务于小企业内部订单、采购、出货、报关和供应商开票流程。核心原则: + +- 以客户销售订单为主线。 +- 产品资料只维护一次,后续流程自动带出。 +- 每次实际出货形成一个独立的出货批次和单证包。 +- 客户 SKU、客户产品名只属于订单明细,不建立长期客户产品映射。 +- 无独立审核人员,资料采用 `Draft -> Publish` 发布机制。 +- 已生成业务单据保存数据快照,不受后续主档修改影响。 + +## 2. 主流程 + +```text +客户 PO 原文件 + -> 客户订单录入/导入 + -> 订单明细匹配内部货号 + -> 订单确认 + -> 采购拆解 + -> 按供应商生成采购合同 + -> 采购完货并确认实际包装数据 + -> 建立出货批次 + -> 从订单选择本次出货数量 + -> 确认箱数、毛净重、尺寸、CBM、集装箱 + -> 确认报关资料 + -> 生成报关单证包 + -> 按客户模板生成 CI/PL + -> 生成供应商开票通知及购销合同 + -> 登记供应商发票 + -> 转财务 +``` + +## 3. 核心业务对象 + +```text +客户 +供应商 +产品 +销售订单 +销售订单明细 +采购任务 +采购合同 +到货/完货确认 +出货批次 +出货明细 +集装箱 +报关资料 +客户 CI +客户 PL +供应商开票通知 +供应商购销合同 +文件模板 +附件 +操作日志 +``` + +关键关系: + +```text +销售订单明细 + ├── 多个采购任务 + ├── 多个出货批次 + └── 多套生成单据 +``` + +## 4. 客户订单 + +客户提供的文件可能包含客户 PO、客户 SKU、客户英文描述、数量、箱数、价格、交期、装运方式、港口、HS 编码、箱规等信息。 + +订单明细必须同时保存: + +| 字段 | 用途 | +|---|---| +| 内部货号 | 内部采购、订单跟踪和产品识别 | +| 客户 SKU | 原样显示在客户单证中,仅属于当前订单 | +| 客户产品名 Override | 覆盖产品默认英文名,仅属于当前订单 | +| 产品主档英文品名 | 无 Override 时的默认值 | +| 订单数量 | 客户订购数量 | +| 客户单价 | 客户订单/CI 使用 | +| 客户装箱率 | 客户提供的订单数据 | +| 客户备注 | 原始要求 | +| 原始 PO 文件 | 用于核对和追溯 | + +客户单证名称规则: + +```text +订单明细.客户产品名 Override 非空 -> 使用 Override +否则 -> 使用产品主档英文品名 +``` + +客户 SKU 不进入产品主档,不建立客户 SKU 与内部货号的长期映射。 + +## 5. 采购拆解 + +一个销售产品可以整体采购,也可以拆成主体、配件、包装和加工项目,由不同供应商分别完成。 + +采购任务至少保存: + +- 销售订单及订单明细 +- 采购内容 +- 部件或产品 +- 供应商 +- 数量和单位 +- 单价、币种、含税标志、税率 +- 交期 +- 采购要求 +- 包装/质量要求 + +系统可以根据产品 BOM 自动生成采购任务,采购人员可以修改供应商、数量、价格、税率、采购内容,或临时增加采购项目。 + +生成采购任务/采购合同后,价格和关键资料复制为单据快照。 + +## 6. 采购合同 + +采购合同样本中的主要内容: + +- 甲乙方信息 +- 客户订单号 +- 合同编号、签约时间、完货时间 +- 付款条件 +- 客户 SKU、产品描述、材料要求 +- 数量、含税单价、装箱数、金额 +- 合同条款 +- 盖章及签字位置 + +合同生成后不随产品或供应商主档变化。修改合同应生成新版本或作废后重新生成。 + +## 7. 到货与实际包装 + +产品主档中的包装信息只是默认/预计数据。采购完货或出货前必须记录本次实际数据: + +- 已采购数量、已到货数量 +- 实际装箱率、箱数 +- 实际外箱长宽高 +- 实际单箱毛重、净重 +- 实际总毛重、净重、CBM +- 包装照片和异常说明 + +报关单证和客户 PL 应使用本次出货的实际数据。 + +## 8. 出货批次 + +一个销售订单可以拆成多个出货批次。每个批次保存: + +- 批次编号 +- 关联订单和客户 +- 船期、截关日期、ETD、ETA +- 起运港、目的港 +- 货代 +- 集装箱号、柜型、封条号 +- 提单号、船名航次 +- 出货明细 + +出货明细保存: + +- 订单明细和内部货号 +- 客户 SKU、客户产品名 +- 出货数量和单位 +- 箱数 +- 实际外箱尺寸 +- 毛重、净重、CBM +- 客户单价和金额 +- 报关单价和金额 +- HS 编码、报关品名、申报要素 +- 原产国、目的国、境内货源地、征免信息 + +出货批次确认后,关键数据应锁定;如果修改,必须提示会影响哪些已生成单据。 + +## 9. 报关资料 + +报关资料由产品默认资料、订单数据和本次出货数据组成,并在生成前提供确认页面。 + +产品默认资料: + +- HS 编码 +- 中文/英文报关品名 +- 报关单位 +- 申报要素 +- 原产国 +- 境内货源地 +- 包装种类 + +本次出货资料: + +- 报关数量、单位 +- 报关单价、金额、币制 +- 贸易方式、征免性质 +- 箱数、毛净重、CBM +- 集装箱、提单、船名航次 +- 出口日期、申报日期 + +输出: + +- 报关发票 +- 报关装箱单 +- 报关外销合同 +- 报关单录入数据 + +系统生成文件时自行计算合计,不依赖模板中的 Excel 公式,避免 `#REF!` 等错误。 + +## 10. 客户 CI/PL 与占位符模板 + +客户可以自行设计 XLSX 模板,不要求系统预先固定版式。 + +模板中使用双大括号包围占位符,例如: + +```text +{{InvoiceNo}} +{{CustomerName}} +{{CustomerAddress}} +{{CustomerPO}} +{{ProductDescription}} +{{Quantity}} +{{CartonCount}} +{{GrossWeight}} +{{NetWeight}} +{{TotalCBM}} +``` + +模板导入系统后,系统扫描所有工作表和单元格,提取全部 `{{...}}` 内容,显示占位符清单。用户逐项选择该占位符对应的业务字段。 + +系统保存: + +- 模板文件 +- 模板版本 +- 占位符原文 +- 对应业务字段 +- 格式化方式:日期、数字、小数位、币种 +- 是否为明细行字段 + +建议占位符名称由用户自行决定;名称只用于模板显示,真正的数据来源由用户在导入模板后选择。 + +### 模板生成规则 + +- 普通占位符替换为单值,例如 `{{InvoiceNo}}`。 +- 同一个占位符可以在多个单元格重复使用。 +- 一个单元格中可以包含多个占位符。 +- 未配置的占位符禁止生成文件,并显示缺失映射。 +- 明细行占位符放在同一行,系统按出货明细复制该行。 +- 合计字段由系统重新计算,不依赖 Excel 公式。 +- 模板版本和字段映射固定后,历史生成文件不受模板后续修改影响。 + +CI 可能包含: + +- 买卖双方及地址 +- Invoice No.、日期、运输方式 +- 起运地、目的地 +- PO、Item、描述、数量、单价、金额 +- 制造商、材料、付款条款 +- 佣金、货代费用、银行资料 + +PL 可能包含: + +- PO、Item、描述 +- PCS、Cartons +- 毛重、净重 +- 长宽高、CBM +- 集装箱/封条号 +- 总箱数、总毛重、总净重、总 CBM + +## 11. 供应商开票 + +出货确认后,按供应商生成开票资料。一个出货批次可以对应多个供应商开票通知。 + +开票通知包含: + +- 外销发票号 +- 采购合同号 +- 供应商和开票抬头 +- 地址、电话、开户银行、账号、税号、海关代码 +- 品名、数量、规范中文单位 +- 含税单价、含税金额 +- 开票要求、合同/出库单盖章要求 +- 联系人及寄送地址 + +供应商购销合同还包括不含税金额、增值税额、含税金额、质量/技术要求、交货、包装、结算、税务和知识产权条款。 + +发票状态: + +```text +未生成 -> 已通知供应商 -> 等待发票 -> 已收到发票 -> 已交财务 -> 已完成 +``` + +## 12. 单证版本与数据快照 + +单据状态: + +```text +Draft -> Generated -> Confirmed -> Exported + └-> Voided +``` + +以下业务单据生成时必须保存快照: + +- 销售订单 +- 采购任务 +- 采购合同 +- 出货明细 +- 报关资料 +- 客户 CI/PL +- 供应商开票资料 + +修改关键出货数据时,系统提示会影响的文件,并要求重新生成新版本;不直接覆盖已导出的文件。 + +## 13. 多账户与组合权限 + +系统采用“用户 + 权限项”的组合授权模型,不把用户限制为单一角色。 + +每个用户可以独立勾选或分配多个模块和操作权限,例如: + +| 用户 | 可访问模块 | 可执行操作 | +|---|---|---| +| 张三 | 订单、采购 | 查看、新增、修改、确认、导出 | +| 李四 | 订单、出货、客户单证 | 查看、修改、生成、导出 | +| 王五 | 报关 | 查看、修改、确认、生成、导出 | +| 赵六 | 开票、财务 | 查看、修改、登记、导出 | + +权限至少包括: + +- 模块访问:客户、供应商、产品、订单、采购、出货、报关、客户 CI/PL、开票、财务、附件、查询报表、系统设置 +- 操作权限:查看、新增、修改、发布、停用、确认、生成、导出、作废、删除草稿 + +角色或权限组可以作为可选的权限打包工具,例如“采购常用权限”,但角色不是用户授权的唯一来源。用户可以: + +- 直接拥有单项权限 +- 同时加入多个权限组 +- 在权限组基础上追加个人权限 +- 不加入任何权限组而单独配置权限 + +最终有效权限为用户直接权限与所属权限组权限的并集。没有明确授权的模块和操作默认拒绝。管理员也必须通过权限项访问管理模块,不能用代码内置“万能角色”绕过授权。 + +所有关键操作记录操作人、时间、对象、权限来源和前后变化。停用用户后立即禁止登录;权限变化在下一次请求鉴权时生效。 + +## 14. 技术部署 + +- 服务端:ASP.NET Core Web API,.NET 11,Windows Server +- 客户端:WPF,.NET 11,MVVM +- 开发和验收数据库:SQLite,通过 EF Core 访问 +- 生产数据库:PostgreSQL,通过 EF Core 访问 +- 附件和模板:服务器集中存储 +- 客户端通过 API 访问服务端,不直接连接数据库 + +## 15. 第一阶段范围 + +- 用户、角色和权限 +- 客户、供应商、产品资料 +- 产品 BOM、供应商报价 +- 客户订单手工录入和 Excel 导入 +- 采购拆解和采购合同 +- 到货及实际包装确认 +- 出货批次和集装箱装箱 +- 报关资料和报关单证 +- 客户 CI/PL 两类以上模板 +- 供应商开票通知和购销合同 +- 附件、版本、操作日志 + +第一阶段暂不实现复杂总账、供应商门户、自动海关接口、自由报表设计器和完整库存管理。 diff --git a/docs/02-产品与样品库设计.md b/docs/02-产品与样品库设计.md new file mode 100644 index 0000000..8c0bad1 --- /dev/null +++ b/docs/02-产品与样品库设计.md @@ -0,0 +1,374 @@ +# 产品库详细设计 + +## 1. 设计原则 + +- 产品是内部长期主档;客户 SKU 和客户产品名不进入产品主档。 +- 产品资料采用 `Draft -> Publish -> Disabled`,不设置独立审核人。 +- 保存草稿和发布是两个不同操作。 +- 已发布产品编辑时生成新的 Draft 版本,不直接改写历史版本。 +- 产品包装、报关、供应商价格和 BOM 分区维护。 +- 订单、采购合同、出货和报关单据保存产品数据快照。 +- 已使用的资料不能删除,只能停用;未引用的草稿才允许删除。 + +产品和零件统一在产品库维护。本系统不包含产品实物/样品管理:不维护样品编号、版本、类型、来源、数量、存放位置、保管人、借出归还或样品确认等信息,也不建立样品实体、接口或页面。产品图片和确认文件等资料通过产品附件功能管理,与样品无关。 + +## 2. 产品状态 + +```text +Draft + -> Publish +Published + -> Disable +Disabled +``` + +| 状态 | 规则 | +|---|---| +| Draft | 可继续编辑;默认不能进入正式订单、采购和报关流程 | +| Published | 可用于订单、采购、出货和单证 | +| Disabled | 禁止新业务使用,历史业务可查看 | + +### 操作 + +草稿:保存、发布、删除草稿。 + +已发布:编辑新版本、停用、查看历史版本。 + +已停用:查看历史版本;如需恢复,建立新 Draft 后重新 Publish。 + +## 3. 发布检查 + +发布不需要其他人审核,但系统自动检查资料。 + +### 基础发布条件 + +- 内部货号 +- 中文品名 +- 英文品名 +- 产品分类 +- 产品类型 +- 计量单位 + +### 采购使用检查 + +- 至少一个有效供应商,或明确允许采购时临时指定 +- 采购要求已填写,或明确无要求 + +### 出货使用检查 + +- 装箱率 +- 默认外箱长宽高 +- 单箱毛重 +- 单箱净重 + +### 报关使用检查 + +- HS 编码 +- 中文报关品名 +- 英文报关品名 +- 报关单位 +- 申报要素 + +发布失败时显示缺失字段。不同业务阶段按用途检查,不要求创建产品时一次填写全部资料。 + +## 4. 产品主档 + +### 基本资料 + +| 字段 | 说明 | +|---|---| +| 内部货号 | 公司内部唯一编号;支持手工输入,必须唯一 | +| 中文品名 | 内部中文名称 | +| 英文品名 | 默认英文名称;客户单证可被订单 Override 覆盖 | +| 产品分类 | 玩具、包装、配件等 | +| 产品类型 | 成品、部件、包装材料、其他 | +| 计量单位 | PCS、SET、BOX、KG 等 | +| 产品尺寸 | 长、宽、高和单位 | +| 产品描述 | 内部综合说明 | +| 采购要求 | 给采购和工厂看的要求 | +| 质量要求 | 验货和质量控制要求 | +| 默认产地 | 默认中国或具体地区 | +| 备注 | 其他说明 | + +产品不保存客户 SKU、客户产品名或客户长期映射关系。 + +## 5. 产品包装资料 + +产品包装资料是默认/预估资料,实际订单和出货可以覆盖。 + +### 单品包装 + +- 单品长、宽、高及单位 +- 单品净重、毛重 +- 单品包装方式 + +### 外箱包装 + +- 装箱率 +- 外箱长、宽、高及单位 +- 单箱净重、毛重 +- 外箱材质 +- 外箱包装说明 +- 默认箱数计算方式 + +默认计算: + +```text +预计箱数 = 向上取整(订单数量 / 装箱率) +单箱 CBM = 长 × 宽 × 高 / 1,000,000 +预计总 CBM = 预计箱数 × 单箱 CBM +预计总毛重 = 预计箱数 × 单箱毛重 +预计总净重 = 预计箱数 × 单箱净重 +``` + +### 包装方案 + +一个产品允许多个包装方案,例如普通出口箱、半托包装、客户指定包装。产品设置默认方案;订单选择方案时复制为订单包装快照。 + +## 6. 报关资料 + +报关资料独立于基本资料维护: + +- HS 编码 +- 中文报关品名 +- 英文报关品名 +- 报关单位 +- 申报要素 +- 原产国 +- 境内货源地 +- 征免性质默认值 +- 包装种类 +- 监管条件 +- 检验检疫类别 +- 报关备注 + +第一版的申报要素可以保存为多行文本,同时保留原始文本。后续如需要标准化,再拆为材质、用途、品牌、型号等字段。 + +HS 编码、报关品名和申报要素应保留修改历史。已用于历史报关的版本不能被当前资料覆盖。 + +## 7. 产品、零件、供应商与价格 + +产品库必须保存产品与供应商的完整关系,不把供应商只放在采购单中。 + +关系模型: + +```text +产品 + ├── 供应商 A ── 多个历史报价 + ├── 供应商 B ── 多个历史报价 + └── BOM 零件 + ├── 零件 1 ── 供应商 C、供应商 D ── 各自报价 + └── 零件 2 ── 供应商 E ── 多个历史报价 +``` + +一个产品可以: + +- 由一个供应商整体供货 +- 由多个供应商分别供货 +- 由主体、配件、包装和加工项目组成 +- 某个零件由一个或多个供应商供货 +- 每个供应商使用不同的产品/零件货号、要求、交期和报价 + +### 产品或零件供应商关系 + +每条关系至少保存: + +- 产品或零件 +- 供应商 +- 供应商产品名称 +- 供应商产品货号 +- 采购内容类型:成品、主体、配件、包装、加工 +- 是否默认供应商 +- 供应商要求 +- 最小采购量 +- 交期 +- 启用状态 + +独立管理的零件应建立独立产品主档。这样该零件可以被多个成品复用,并且在零件自身的产品页面维护多个供应商和报价。 + +### 供应商价格 + +同一产品/零件与同一供应商允许存在多个价格版本: + +- 单价 +- 币种 +- 计价单位 +- 含税/未税 +- 税率:0%、3%、6%、9%、13% 等 +- 最小起订量 +- 生效日期 +- 失效日期 +- 价格备注 + +价格必须保留历史。生成采购任务或采购合同时,复制当时生效的供应商关系和价格快照,后续价格变化不影响已生成单据。 + +## 8. 产品 BOM/配件 + +一个产品可以没有 BOM,也可以包含主体、配件、包装和加工项目。 + +BOM 明细字段: + +- 主产品 +- 部件名称 +- 部件类型:主体、配件、包装、加工 +- 部件内部货号,可为空 +- 每套用量 +- 计量单位 +- 默认供应商,可为空 +- 采购要求 +- 是否必须 +- 显示/合同排序 +- 启用状态 + +需要独立采购、报价、复用或独立管理的部件建立独立产品,例如说明书、彩盒、外箱、桌垫。只属于单个产品的简单要求可直接写在 BOM 明细中。 + +BOM 可以自动生成采购任务,但采购人员必须能够修改、删除某一拆解项或临时新增采购项目。 + +## 9. 产品图片和附件 + +一个产品支持多个附件: + +- 产品正面图 +- 包装图、彩盒图、外箱图 +- 结构图、设计稿、规格书 +- 检验报告 +- 客户确认文件 +- 供应商报价文件 + +附件元数据: + +- 文件名、类型、用途 +- 上传人、上传时间 +- 当前版本标记 +- 备注 + +产品详情页显示第一张图片作为封面,所有附件集中管理。 + +## 10. 产品版本 + +已发布产品编辑时,不直接修改当前版本,而是建立新的 Draft: + +```text +产品 P-001 + ├── V1 Published + └── V2 Draft +``` + +V2 发布前: + +- 新订单继续使用 V1 +- V2 可继续编辑 + +V2 发布后: + +- 新订单使用 V2 +- 已有订单继续使用订单创建/确认时的快照 +- V1 保留为历史版本 + +界面不要求用户理解复杂版本模型,只显示当前版本、状态、编辑新版本和历史版本。 + +## 11. 修改日志 + +记录: + +- 修改字段 +- 修改前值 +- 修改后值 +- 修改人 +- 修改时间 +- 修改原因 + +以下关键字段修改建议要求填写原因: + +- HS 编码 +- 报关品名 +- 报关单位 +- 装箱率 +- 外箱尺寸 +- 毛重、净重 +- 默认供应商 + +## 12. 页面设计 + +### 产品列表 + +显示:状态、内部货号、中文品名、英文品名、分类、默认供应商、HS 编码。 + +筛选:货号、名称、分类、状态、供应商、HS 编码、资料完整度。 + +操作:新增产品、批量导入、导出、查看停用产品、资料完整性检查。 + +### 产品详情 + +标签页: + +```text +基本资料 +包装资料 +采购供应商 +配件/BOM +报关资料 +图片/附件 +修改记录 +``` + +产品详情不包含产品实物/样品管理;本系统不提供样品登记、借出、归还或确认功能。 + +## 13. 建议数据结构 + +```text +Product + ProductId, InternalCode, ChineseName, EnglishName, + CategoryId, ProductType, UnitId, Status, + CurrentVersionId, PurchaseRequirement, QualityRequirement, Remark + +ProductVersion + ProductId, VersionNo, Status, PublishedAt, PublishedBy, + EffectiveFrom, EffectiveTo + +ProductPackaging + ProductVersionId, SchemeName, PackingRate, + CartonLength, CartonWidth, CartonHeight, DimensionUnit, + CartonGrossWeight, CartonNetWeight, IsDefault + +ProductCustoms + ProductVersionId, HsCode, CustomsChineseName, + CustomsEnglishName, CustomsUnit, DeclarationElements, + Origin, SourceArea, PackagingType + +ProductSupplier + ProductVersionId, SupplierId, SupplierProductCode, + SupplierProductName, PurchaseType, IsDefault, + Requirement, MinimumQuantity, LeadDays, Status + +ProductSupplierPrice + ProductSupplierId, Currency, UnitPrice, PricingUnit, + TaxIncluded, TaxRate, EffectiveFrom, EffectiveTo, Remark + +ProductBomItem + ProductVersionId, ComponentProductId, ComponentName, + ComponentType, QuantityPerProduct, UnitId, + Requirement, IsRequired, SortOrder, Status + +``` + +产品零件如果建立为独立产品,则通过该零件自己的 `ProductSupplier` 和 `ProductSupplierPrice` 维护多个供应商及报价。BOM 只保存零件组成关系,不把供应商限制为一个。 + +图片、附件、操作日志使用统一附件和审计表。 + +## 14. 第一版范围 + +第一版实现: + +1. 产品基本资料 +2. 产品包装方案 +3. 报关资料 +4. 供应商和历史价格 +5. 产品 BOM/配件及零件供应商 +6. 产品图片和附件 +7. 产品 Draft/Publish/Disabled +8. 产品版本和修改日志 +9. 资料完整性检查 +10. 产品批量导入/导出 + +第一版暂不实现完整仓库库存、条码扫描、供应商门户、自动图片识别和复杂审批流。 diff --git a/docs/03-数据库迁移与导入设计.md b/docs/03-数据库迁移与导入设计.md new file mode 100644 index 0000000..8f9ce3a --- /dev/null +++ b/docs/03-数据库迁移与导入设计.md @@ -0,0 +1,418 @@ +# 数据库迁移与导入设计 + +## 1. 数据源范围 + +旧 ERP 数据提取只使用仓库中的 UTF-16 SQL 导出文件: + +```text +bak/ps_tr.sql +bak/ps_tr_mail.sql +bak/ps_tr_pic.sql +``` + +这些文件包含 `CREATE TABLE`、字段定义和 `INSERT` 数据。迁移程序直接解析 SQL 文件,不恢复 `.bak`,不连接旧 SQL Server,也不把 `.bak` 作为后续步骤。 + +`.bak` 文件不属于本次数据提取路径。它们只作为原始备份文件保留,不在开发、迁移、验收或上线流程中使用。 + +从 SQL 文件已经识别出与本 ERP 流程直接相关的旧表: + +| 旧表 | 初步业务含义 | 已观察到的字段/关系 | +|---|---|---| +| `yp_hh` | 产品货号主档 | `ypid`、`hh`、中文/英文品名、单位、产品尺寸、装箱率、外箱尺寸、毛净重、报关字段 | +| `khxx` | 客户 | 客户编号、中文/英文名称、附件/图片字段 | +| `gysxx` | 供应商 | 供应商编号、名称、地址、联系人、银行/税务及附件字段 | +| `order_main` | 客户订单主表 | 订单 ID、客户、合同号、PO、订单日期、交期、币种、装运信息 | +| `order_hh` | 客户订单明细 | 订单 ID、产品 ID、数量、单价、金额、箱规、装箱数、尺寸及交期字段 | +| `maker_order_main/detail` | 供应商采购合同及明细 | 供应商、合同号、交期、币种、数量、单价、金额、包装和要求字段 | +| `invoice/invoice_detail` | 出货/报关发票及明细 | 客户、发票号、箱数、毛重、CBM、产品、数量、报关数量和金额字段 | +| `yp_zj`、`yp_jg`、`yp_glgx` | 产品部件/加工/关联关系候选表 | 产品与部件、加工项目、关系数量及要求字段 | +| `Documents`、`relate_files_data` | 文件元数据/附件候选表 | 文件编号、名称、业务对象、类型、哈希/内容关联字段 | + +历史产品图片核查结论(`ps_tr_pic.sql` 实测):该文件 95 张表只有 7 张有 INSERT;业务图片表自身的图片列无真实字节(`yp_pic_hh.pic`/`clzb_pic.pic` 为 `NULL`,`html_attach_data.filedata`/`relate_files_data.file_image` 为空 `0x`)。真实字节在 `blob_hash.hash_blob`(17 行、1,830,748 字节、6 PNG + 11 JPEG,`file_type` 全为 `NULL`,已验证 `hash_value` = `hash_blob` 的 SHA-1)。产品图片经 `yp_pic_hh.ypid -> yp_hh.ypid`、`yp_pic_hh.hash_value -> blob_hash.hash_value` 关联,5 行全部命中(4 个不同哈希),可真实导入;`execute` 已按此导入为 `product` 的 `product-photo` 附件(文件写入服务器文件存储、数据库只存 `FileAttachment` 元数据),无法恢复的行逐行进入迁移错误报告,不臆造图片。详见 `migration/README.md`「历史产品图片」。 + +## 2. SQL 文件解析范围 + +解析器必须支持: + +1. UTF-16 SQL 文件读取。 +2. `CREATE TABLE` 字段定义解析。 +3. `INSERT [dbo].[table] ([column...]) VALUES (...)` 解析。 +4. `N'中文字符串'`、普通字符串、`NULL`、数字和 `CAST(...)`。 +5. SQL 字符串中的换行、逗号和单引号转义。 +6. `GO` 批次分隔。 +7. `SET IDENTITY_INSERT`,但不依赖其执行。 +8. 大文件逐行或分块解析,不把全部文件复制成多个内存副本。 + +解析结果必须保留: + +- 源文件 +- 源表 +- 源列 +- 源主键或候选主键 +- 原始值 +- 转换后的标准值 +- 解析错误位置 + +静态脚本中已经能看到真实业务字段,例如产品的 `ypid/hh/pm/pm_e/dw/box_i/box_m/box_o`,订单的 `ddid/khid/po`,订单明细的 `ypid/sl/dj/je`,采购合同明细的 `gysid/sl/dj/je`,以及发票明细的 `invoice_id/qty/ctns/cbm`。 + +## 3. 数据库选型 + +新 ERP 使用 EF Core: + +- 开发和实际交互验收使用 SQLite。 +- 生产使用 PostgreSQL。 +- 业务代码只依赖 EF Core 和通用关系模型。 +- 迁移解析器先写入 SQLite 做验证,再写入生产 PostgreSQL。 +- 不使用 PostgreSQL 专用 SQL。 +- 申报要素、模板参数和旧字段使用文本或 EF Core 可兼容的 JSON 字符串。 +- 附件不放数据库大字段,使用服务器文件存储,数据库保存元数据。 + +MongoDB 不作为主业务库。 + +## 4. 新系统数据库边界 + +新数据库只承载新 ERP 的有效业务模型,旧 SQL 文件先进入 `legacy` 导入区,再经过映射写入正式表: + +```text +legacy_* 原始导入区,保留源文件、源表、源主键、原始值 +core_* 客户、供应商、产品、用户等主数据 +sales_* 客户订单及明细 +purchase_* 采购拆解、采购合同、到货 +shipping_* 出货批次、集装箱、出货明细 +customs_* 报关数据 +billing_* 供应商开票通知和发票状态 +document_* 文件、模板和生成版本 +audit_* 操作日志和迁移日志 +``` + +导入程序不得直接把旧表写入正式业务表。所有数据必须通过 `source_file + source_table + source_key` 追溯回来源。 + + +## 5. 建议正式表 + +### 5.1 基础资料 + +```text +core_company +core_user +core_role +core_user_role +core_customer +core_supplier +core_product +core_product_version +core_product_packaging +core_product_customs +core_product_supplier +core_product_supplier_price +core_product_bom_item +core_category +core_unit +``` + +### 5.2 订单与采购 + +```text +sales_order +sales_order_line +sales_order_line_packaging_snapshot +purchase_task +purchase_task_line +purchase_contract +purchase_contract_version +purchase_receipt +purchase_receipt_line +``` + +### 5.3 出货与报关 + +```text +shipping_batch +shipping_container +shipping_line +shipping_line_packaging_snapshot +customs_declaration +customs_declaration_line +``` + +### 5.4 单证与开票 + +```text +document_template +document_template_version +document_file +document_generation +document_generation_item +billing_notice +billing_notice_line +supplier_invoice +``` + +### 5.5 附件和迁移 + +```text +file_attachment +audit_log +legacy_source_record +legacy_id_map +migration_run +migration_error +``` + +## 6. 核心表关键字段 + +以下字段定义使用逻辑类型,实际由 EF Core provider 映射:`uuid` 映射为 `Guid`,`datetime` 映射为 UTC 时间,`json_text` 映射为字符串。为保证 SQLite 开发环境可运行,正式表不依赖 PostgreSQL 专用类型。 + +### `core_product` + +```text +id uuid primary key +internal_code varchar(100) unique not null +status varchar(20) not null -- draft/published/disabled +current_version_id uuid null +created_at timestamptz not null +created_by uuid not null +``` + +### `core_product_version` + +```text +id uuid primary key +product_id uuid not null +version_no integer not null +status varchar(20) not null -- draft/published/disabled +chinese_name varchar(300) not null +english_name varchar(500) not null +category_id uuid null +product_type varchar(30) not null +unit_code varchar(30) not null +product_size jsonb null +purchase_requirement text null +quality_requirement text null +remark text null +published_at timestamptz null +published_by uuid null +unique(product_id, version_no) +``` + +### `core_product_packaging` + +```text +id uuid primary key +product_version_id uuid not null +scheme_name varchar(100) not null +is_default boolean not null default false +packing_rate numeric(18,6) null +carton_length numeric(18,6) null +carton_width numeric(18,6) null +carton_height numeric(18,6) null +dimension_unit varchar(20) null +carton_gross_weight numeric(18,6) null +carton_net_weight numeric(18,6) null +weight_unit varchar(20) null +packaging_note text null +``` + +### `core_product_customs` + +```text +id uuid primary key +product_version_id uuid not null +hs_code varchar(30) null +customs_chinese_name varchar(300) null +customs_english_name varchar(500) null +customs_unit varchar(30) null +declaration_elements text null +origin_country varchar(100) null +source_area varchar(200) null +packaging_type varchar(100) null +extra jsonb null +``` + +### `sales_order` 和 `sales_order_line` + +订单明细中保留客户字段,不建立客户 SKU 主数据: + +```text +sales_order +------------ +id uuid primary key +order_no varchar(100) unique not null +customer_id uuid not null +customer_po_no varchar(200) null +order_date date null +delivery_date date null +currency_code varchar(10) null +status varchar(30) not null +original_file_id uuid null + +sales_order_line +---------------- +id uuid primary key +sales_order_id uuid not null +line_no integer not null +product_id uuid not null +product_version_id uuid not null +customer_sku varchar(200) null +customer_product_name_override varchar(500) null +quantity numeric(18,6) not null +unit_code varchar(30) not null +customer_unit_price numeric(18,6) null +customer_amount numeric(18,6) null +customer_packing_rate numeric(18,6) null +customer_requirement text null +product_snapshot jsonb not null +unique(sales_order_id, line_no) +``` + +`product_snapshot` 保存订单生成时的产品名称、包装和报关默认值;客户 SKU 和 Override 直接保存在订单明细。 + +### `shipping_line` + +```text +id uuid primary key +shipping_batch_id uuid not null +sales_order_line_id uuid not null +quantity numeric(18,6) not null +unit_code varchar(30) not null +carton_count numeric(18,6) null +gross_weight numeric(18,6) null +net_weight numeric(18,6) null +carton_length numeric(18,6) null +carton_width numeric(18,6) null +carton_height numeric(18,6) null +cbm numeric(18,6) null +customer_unit_price numeric(18,6) null +customer_amount numeric(18,6) null +customs_unit_price numeric(18,6) null +customs_amount numeric(18,6) null +customs_snapshot jsonb not null +``` + +### `legacy_source_record` 和 `legacy_id_map` + +```text +legacy_source_record +-------------------- +id bigserial primary key +migration_run_id uuid not null +source_database varchar(128) not null +source_schema varchar(128) not null +source_table varchar(128) not null +source_key varchar(500) not null +source_payload jsonb not null +source_hash char(64) not null +unique(source_database, source_schema, source_table, source_key) + +legacy_id_map +------------- +id bigserial primary key +source_record_id bigint not null +source_entity varchar(100) not null +target_id uuid not null +unique(source_record_id, source_entity) +``` + +## 7. 导入程序设计 + +建立独立的 `.NET 11` 控制台工具: + +```text +src/ + Erp.Migration.Cli/ + Erp.Migration.SqlFile/ + Erp.Migration.Mapping/ + Erp.Migration.EfCore/ + Erp.Migration.Reporting/ +``` + +职责: + +- `SqlFile`:流式读取 UTF-16 SQL 文件,解析表结构和 INSERT 数据。 +- `Mapping`:把旧表行映射到标准中间模型。 +- `EfCore`:使用 EF Core 写入 SQLite 或 PostgreSQL。 +- `Reporting`:生成读取数、成功数、跳过数、错误数和未映射报告。 +- `Cli`:控制源文件、批次、目标数据库和 dry-run。 + +建议使用: + +- `System.IO` 流式读取大文件。 +- `System.Text.Json` 保存原始行和扩展字段。 +- EF Core SQLite provider 写入开发/验收数据库。 +- EF Core PostgreSQL provider 写入生产数据库。 +- `CsvHelper` 或 JSON 输出报告。 + +## 8. 导入阶段 + +```text +0. 检查源 SQL 文件和目标数据库 +1. 解析 CREATE TABLE 和 INSERT +2. 保存原始行到 legacy_source_record +3. 清洗字符串、日期、金额、单位和空值 +4. 建立源文件/表/主键到新 UUID 的映射 +5. 导入客户、供应商、分类、单位 +6. 导入产品和产品版本 +7. 导入供应商价格及 BOM +8. 导入订单和订单明细 +9. 导入采购、出货、报关、附件 +10. 运行一致性检查 +11. 输出迁移报告 +12. 使用 SQLite 完成真实交互抽样 +13. 生产切换时使用同一批次导入 PostgreSQL +``` + +## 9. 映射规则 + +实际旧表结构确认前,不写死字段名。映射采用配置文件: + +```yaml +source: + database: ps_tr + table: legacy_table_name + key: old_id +mapping: + internal_code: [product_code, item_no, art_no] + chinese_name: [cn_name, product_name_cn] + english_name: [en_name, product_name_en, description] + quantity: [qty, quantity, amount] +transform: + trim_strings: true + empty_to_null: true + date_system: excel_serial_if_numeric +``` + +一个旧字段映射多个候选列时,按优先级读取第一个非空值,并在报告中记录来源列。 + +## 10. 幂等、错误和数据安全 + +- 每次导入有 `migration_run` 编号。 +- 原始行使用源库、表、主键唯一约束,重复执行不重复导入。 +- 清洗失败的行写入 `migration_error`,不静默跳过。 +- 金额使用 `numeric`,不使用浮点类型。 +- 日期明确记录时区和来源格式。 +- 导入程序不删除目标数据,修正采用新批次或显式回滚。 +- 默认 dry-run,只生成报告,不写正式业务表。 +- 数据库密码只从环境变量或 Windows Credential Manager 读取。 +- 原始附件和敏感客户数据不进入 Git。 + +## 11. 必须验证的业务规则 + +导入完成后检查: + +- 订单号是否唯一。 +- 订单明细数量是否非负。 +- 采购数量、到货数量、出货数量关系是否合理。 +- 供应商、客户和产品引用是否存在。 +- 产品货号、客户订单号、采购合同号是否有重复。 +- 金额是否满足数量 × 单价,允许记录原始金额和差异。 +- 出货总箱数、毛重、净重、CBM 是否与单证原数据一致。 +- 图片和邮件是否能关联到原业务记录。 +- 无法映射的旧表和字段是否有报告。 + +## 12. 当前结论 + +旧 ERP 数据提取路径已经确定为三个 UTF-16 SQL 文件。迁移程序直接解析 `CREATE TABLE` 和 `INSERT`,不恢复 `.bak`,不连接旧 SQL Server。 + +SQL 文件中的 `INSERT` 语句计数为:`yp_hh` 110、`khxx` 5、`gysxx` 25、`order_main` 3、`order_hh` 1、`maker_order_main` 5、`maker_order_hh` 5、`invoice` 1、`invoice_detail` 1。该数字是 INSERT 语句数,不等于最终可靠行数;解析器必须以实际解析结果和错误报告为准。 + +SQLite 用于开发和真实交互抽样,生产数据导入使用 PostgreSQL。`.bak` 不属于本项目的数据提取、迁移、验收或上线流程。 diff --git a/docs/04-系统架构与技术设计.md b/docs/04-系统架构与技术设计.md new file mode 100644 index 0000000..756b1d6 --- /dev/null +++ b/docs/04-系统架构与技术设计.md @@ -0,0 +1,810 @@ +# ERP 系统架构与技术设计 + +## 1. 设计目标 + +系统面向小企业内部 Windows 局域网使用,核心目标: + +- 客户端简单、页面少、按待办推动流程。 +- 所有业务数据集中在服务器,客户端不直接连接数据库。 +- 订单、采购、出货、报关和开票共享同一套数据。 +- 单证从统一业务数据生成,避免手工复制造成不一致。 +- 支持多账户和按用户组合配置的模块/操作权限、操作日志和附件。 +- 开发和验收默认使用 SQLite;生产部署使用 PostgreSQL,业务代码通过 EF Core 保持两者兼容。 +- 先做模块化单体,不提前拆分微服务。 + +## 2. 总体架构 + +```text ++-------------------+ HTTPS/HTTP +-------------------------+ +| WPF 客户端 | <--------------------> | ASP.NET Core API | +| 业务/采购/报关/财务 | | .NET 11 | ++-------------------+ +-----------+-------------+ + | + +------------------------------+------------------+ + | | + +-------v--------+ +-------v--------+ + | EF Core 数据访问 | | 文件存储 | + | SQLite 开发/验收 | | 附件/模板/导出 | + | PostgreSQL 生产 | | | +``` + +服务端操作系统不作为业务代码依赖。初始部署可以使用 Windows Server,后续可以迁移到 Linux: + +- ERP API:Windows Service 或 Linux `systemd` 服务 +- PostgreSQL:生产环境 Windows 服务或独立数据库服务器 +- SQLite:开发、实际交互验收和迁移 dry-run +- 文件目录:服务器本地磁盘、NAS 或兼容对象存储 +- WPF 客户端:Windows 客户端电脑 + +客户端只访问 API,不允许直接访问数据库。 + +## 3. 采用模块化单体 + +第一版采用一个 API 进程和一个数据库,不拆分微服务。 + +原因: + +- 团队规模小,部署简单。 +- 订单到单证的事务边界集中。 +- 不需要消息队列、服务发现和分布式事务。 +- 后续可以按模块拆分,但现在不为未来复杂度付成本。 + +模块边界: + +```text +Identity 用户、角色、权限、登录 +- Catalog 产品、包装、报关、供应商价格和 BOM +Sales 客户订单、订单明细、客户 PO 附件 +Purchase 采购拆解、采购合同、到货/完货 +Shipping 出货批次、集装箱、装箱明细 +Customs 报关资料和报关单证 +Documents 模板、字段映射、文件生成、版本 +Billing 供应商开票通知、发票登记 +Files 附件、文件版本、下载权限 +Audit 操作日志、数据变更、迁移记录 +``` + +模块之间通过应用服务调用,不直接互相修改数据库表。跨模块操作使用明确的命令,例如: + +```text +ConfirmSalesOrder +CreatePurchaseTasks +ConfirmPurchaseCompletion +CreateShippingBatch +ConfirmShippingBatch +GenerateCustomsDocuments +GenerateCustomerDocuments +CreateBillingNotices +``` + +## 4. 后端项目结构 + +建议解决方案: + +```text +src/ + Leiren.Erp.Api/ + Controllers/ + Middleware/ + Program.cs + + Leiren.Erp.Application/ + Identity/ + MasterData/ + Catalog/ + Sales/ + Purchase/ + Shipping/ + Customs/ + Documents/ + Billing/ + Files/ + Audit/ + Common/ + + Leiren.Erp.Domain/ + Entities/ + ValueObjects/ + Enums/ + Rules/ + + Leiren.Erp.Infrastructure/ + Persistence/ + Authentication/ + FileStorage/ + DocumentGeneration/ + BackgroundJobs/ + Logging/ + + Leiren.Erp.Contracts/ + Requests/ + Responses/ + Enums/ + + Leiren.Erp.Migration/ + SqlServer/ + Mapping/ + Postgres/ + Reporting/ +``` + +### 各层职责 + +#### `Domain` + +保存实体、状态、值对象和业务不变量。不得依赖数据库、HTTP 或 WPF。 + +#### `Application` + +实现用例和事务边界。负责权限检查、状态迁移、快照生成和领域规则调用。 + +#### `Infrastructure` +实现 EF Core 数据访问、文件系统、模板生成、日志和后台任务。 + +#### `Contracts` + +保存 API 请求/响应模型。禁止直接把 EF Core 实体作为 API 返回值。 + +#### `Api` + +只负责 HTTP、认证、异常转换、参数验证和 OpenAPI。 + +#### `Migration` +独立命令行程序,不加载 WPF 和业务 UI。流式读取 UTF-16 SQL 文件,使用 EF Core 写入 SQLite 或 PostgreSQL。 + +## 5. 客户端项目结构 + +```text +src/ + Leiren.Erp.Client/ + App.xaml + Shell/ + Login/ + Dashboard/ + Sales/ + Purchase/ + Shipping/ + Customs/ + Billing/ + Catalog/ + Settings/ + Shared/ + + Leiren.Erp.Client.Infrastructure/ + ApiClient/ + Authentication/ + LocalSettings/ + FileDownload/ +``` + +客户端技术: + +- WPF +- MVVM +- `CommunityToolkit.Mvvm` +- `HttpClientFactory` +- `System.Text.Json` +- 本地不保存业务数据库 + +页面设计: + +- 左侧模块导航。 +- 首页显示当前用户待办和异常。 +- 列表页统一筛选、分页、导出。 +- 详情页使用标签页减少一次性字段数量。 +- 保存和发布按钮明确分开。 +- 生成文件后显示文件版本、生成时间和生成者。 + +### 客户端壳原型 + +快速原型位于 `docs/client-shell.html`,用于锁定 WPF 的页面结构、导航名称和信息层级,不作为生产前端代码。 + +WPF 必须按原型实现以下固定结构: + +```text +主窗口 +├── 左侧导航 +│ ├── 首页 +│ ├── 客户订单 +│ ├── 采购 +│ ├── 出货 +│ ├── 报关与单证 +│ ├── 供应商开票 +│ ├── 产品库 +│ ├── 客户 +│ ├── 供应商 +│ ├── 附件 +│ └── 系统设置 +├── 顶部用户区 +└── 内容区 + ├── 页面标题 + ├── 操作按钮 + ├── 数据卡片或筛选栏 + └── 列表/详情 +``` + +前端实现规则: + +- 只显示当前用户有权限的导航项和按钮。 +- 页面标题直接说明当前功能,不写欢迎语、解释性长句或营销文案。 +- 数据卡片只展示可操作的数量,不放装饰性插图。 +- 列表优先显示业务编号、客户/供应商、日期、状态和负责人。 +- 详情页使用固定标签页;字段按业务录入顺序排列。 +- 所有保存、确认、生成、导出按钮放在页面右上角或表格上方。 +- 危险操作使用“作废”“停用”等明确文字,不使用仅靠颜色表达的图标。 +- 无数据时显示“暂无数据”和下一步操作,不显示无意义说明。 +- 禁止在生产界面保留原型占位数据、演示数字和无实际用途的提示条。 + +前端验收: + +1. 登录一个只有采购权限的用户,导航中不出现报关、财务和系统管理入口。 +2. 打开订单列表,能完成搜索、筛选、打开详情和返回列表。 +3. 在详情页完成保存、确认和生成文件,按钮状态与服务端结果一致。 +4. 列表、详情、错误提示和确认对话框不包含欢迎语、营销文案或装饰性说明。 + +## 6. API 设计 + +采用 REST API,写操作使用命令式端点,避免客户端直接修改状态字段。 + +示例: + +```text +POST /api/auth/login +POST /api/auth/refresh +POST /api/auth/logout + +GET /api/products +POST /api/products/drafts +PUT /api/products/{id}/draft +POST /api/products/{id}/publish +POST /api/products/{id}/disable + +GET /api/sales-orders +POST /api/sales-orders +POST /api/sales-orders/{id}/confirm + +POST /api/sales-orders/{id}/purchase-tasks +POST /api/shipping-batches +POST /api/shipping-batches/{id}/confirm +POST /api/shipping-batches/{id}/documents/generate + +GET /api/files/{id}/download +POST /api/files +``` + +写操作返回: + +```json +{ + "id": "uuid", + "status": "published", + "version": 3, + "updatedAt": "2026-11-13T10:00:00Z" +} +``` + +错误统一使用 RFC 7807 Problem Details,包含: + +- `type` +- `title` +- `status` +- `code` +- `detail` +- `traceId` +- 字段级验证错误 + +列表接口统一支持: + +```text +page +pageSize +sort +search +filters +``` + +禁止返回无限制全表数据。 + +## 7. 认证与授权 + +### 登录 + +- 用户名 + 密码。 +- 密码只保存不可逆哈希,不保存明文。 +- 默认使用 ASP.NET Core 的安全密码哈希器;生产环境可升级为 Argon2id。 +- 连续失败次数和锁定时间写入登录审计。 + +### Token + +推荐: + +- 短期 access token,约 30 分钟。 +- 长期 refresh token,服务端保存哈希,支持撤销。 +- 客户端只保存在 Windows Credential Manager,不写普通配置文件。 + +局域网部署也建议使用 HTTPS。服务器使用内部证书,客户端安装企业根证书或指定可信证书。 + +### 权限模型 + +权限采用 `module:action`,并以用户为最终授权主体: + +```text +catalog:product:view +catalog:product:edit +catalog:product:publish +sales:order:confirm +purchase:contract:generate +shipping:batch:confirm +customs:document:generate +billing:invoice:receive +file:download +admin:user:manage +``` + +系统支持三种授权来源: + +1. 用户直接权限。 +2. 可复用的权限组权限。 +3. 多个权限组叠加后的权限。 + +角色/权限组只是权限集合,不是互斥身份,也不是用户必须选择的唯一角色。最终有效权限为用户直接权限与所有所属权限组权限的并集;未明确授予的权限默认拒绝。用户可以只访问一个模块,也可以跨多个模块组合权限,例如“订单查看 + 采购编辑 + 出货导出”。 + +权限组可预置“采购权限”“报关权限”等常用组合,但管理员可以对每个用户追加或移除单项权限。权限判断必须在 API 和应用服务执行,客户端隐藏菜单不能代替服务端授权。 + +### 身份与授权数据 + +`identity` schema 至少包含: + +```text +identity_user +identity_permission +identity_user_permission +identity_permission_group +identity_permission_group_item +identity_user_permission_group +identity_refresh_token +``` + +权限变更记录审计日志,并在下一次请求鉴权时生效。停用用户立即禁止登录。权限检查同时覆盖模块访问、具体操作和文件下载。 + +## 8. 状态与发布规则 + +产品、模板和业务单据: + +```text +Draft -> Published -> Disabled +``` + +订单、采购、出货和开票使用各自有限状态机。状态修改必须由应用服务执行,禁止 API 直接接受任意状态值。 + +重要规则: + +- 已发布主档编辑产生新的 Draft 版本。 +- 已确认出货批次不能静默修改。 +- 已导出文件不覆盖,重新生成产生新文件版本。 +- 已被业务引用的数据不能删除,只能停用或作废。 +- 每个状态转换记录操作者、时间和原因。 + +数据库访问统一使用 EF Core。 + +- 开发和交互验收:SQLite 文件数据库。 +- 生产部署:PostgreSQL。 +- API、应用服务和业务实体不直接依赖具体数据库提供程序。 +- 只使用 SQLite 与 PostgreSQL 都支持的字段和约束;生产专用能力必须有明确替代方案。 + +### Schema 分区 + +```text +identity +master +catalog +sales +purchase +shipping +customs +documents +billing +files +audit +legacy +``` + +### 通用字段 + +业务表按需要使用: + +```text +id uuid primary key +created_at datetime not null +created_by uuid not null +updated_at datetime not null +updated_by uuid not null +row_version integer not null +``` + +`row_version` 用于乐观并发控制。客户端提交修改时携带读取时版本,版本不一致返回冲突,不覆盖他人修改。 + +### 约束 + +- 业务编号唯一。 +- 数量、价格、重量和税率使用 EF Core `decimal`,由数据库映射为适合提供程序的精确数值类型;不使用浮点计算金额。 +- 外键默认不级联删除业务数据。 +- 关键金额字段不依赖客户端计算,服务端重新计算并校验。 +- 时间统一存 UTC,界面按公司时区显示。 + +## 10. 文件与模板 + +文件内容不放数据库大字段,保存到服务器文件存储;数据库只保存文件元数据。 + +文件路径由 `IFileStorage` 抽象管理,不在业务代码中拼接 Windows 路径。默认文件系统实现的逻辑目录: + +```text +{root}/files/{year}/{entity}/{id}/{file-id}-{safe-name} +{root}/templates/{template-id}/{version}/... +{root}/generated/{year}/{document-id}/... +``` + +Windows 示例根目录: + +```text +D:\LeirenErpData +``` + +Linux 示例根目录: + +```text +/var/lib/leiren-erp +``` + +数据库保存: + +- 文件 ID +- 原始文件名 +- 存储路径或对象键 +- MIME 类型 +- 文件大小 +- SHA-256 +- 关联业务对象 +- 上传人和时间 +- 是否当前版本 + +客户端下载文件必须经过 API 权限检查,不能直接暴露共享目录。 + +### 文件安全 + +- 文件名不直接拼接用户输入路径。 +- 限制允许的文件扩展名和大小。 +- 上传后计算 SHA-256。 +- Office/PDF 文件保存原始文件,不执行宏。 +- 生成文件和上传文件分开目录。 +- 定期备份数据库和文件目录,备份必须可恢复验证。 + +## 11. 单证生成 + +模板生成采用简单的 XLSX 占位符替换,不制作自由报表设计器。 + +```text +业务数据快照 + -> 模板版本 + -> 扫描 {{...}} 占位符 + -> 读取已保存的字段映射 + -> 计算合计 + -> 替换单元格文字 + -> 按明细行复制模板行 + -> 生成 XLSX + -> 可选转换 PDF + -> 保存 document_generation 和 document_file +``` + +模板规则: + +- 用户自行设计 XLSX 文件并导入系统。 +- 系统扫描所有工作表和单元格中的 `{{...}}` 占位符。 +- 用户在导入页面把每个占位符选择为一个业务字段。 +- 占位符名称不要求使用固定英文名称,例如 `{{客户名称}}`、`{{InvoiceNo}}` 都可以。 +- 普通占位符替换单值;同一占位符可以在多个单元格使用;一个单元格可以有多个占位符。 +- 明细行中的占位符使用统一的明细字段,系统复制该行生成所有明细。 +- 未映射占位符禁止生成文件,并显示占位符名称。 +- 日期、金额、数量和币种格式在映射中配置。 +- 生成时固定模板版本、字段映射和业务数据快照。 + +模板版本至少保存: + +```text +template_id +customer_id +document_type +version_no +source_file_id +placeholder_mapping +status +``` + +实现优先使用 ClosedXML 或 Open XML SDK。只替换单元格文字,不调用 Excel COM;复杂公式不作为数据来源,合计由服务端计算。 + +## 12. 后台任务 + +第一版不引入 RabbitMQ、Kafka 等消息系统。 + +使用 EF Core 兼容的数据库任务表和 ASP.NET Core `BackgroundService`;开发/验收使用 SQLite,生产使用 PostgreSQL。 + +```text +document_job +---------------- +id +job_type +payload +status +attempt_count +available_at +started_at +finished_at +error +``` + +适合后台执行: + +- 大文件生成 +- 批量单证生成 +- PDF 转换 +- 数据导入 +- 附件校验 +- 迁移报告 + +任务必须可重试且幂等。用户界面显示任务状态,不长时间阻塞 HTTP 请求。 + +## 13. 日志与审计 + +### 技术日志 + +记录: + +- API 请求耗时 +- traceId +- 异常堆栈 +- 后台任务失败 +- 数据库连接异常 + +技术日志使用结构化日志,按日期滚动,保留期限可配置。 + +### 业务审计 + +记录: + +- 用户 +- 操作类型 +- 实体类型和 ID +- 操作前值/后值或差异 +- IP/客户端信息 +- 时间 +- 原因 + +密码、token 和敏感凭据不得进入日志。客户文件内容不写入普通日志。 + +## 14. 部署与备份 + +### 服务安装 + +服务端采用可跨平台部署的 ASP.NET Core 发布方式: + +```text +Windows: + LeirenErp.Api -> Windows Service + PostgreSQL -> Windows Service + +Linux: + LeirenErp.Api -> systemd service + PostgreSQL -> systemd service +``` + +业务代码不得依赖: + +- Windows 注册表 +- Windows 专用路径格式 +- IIS 专用 API +- Windows 用户登录状态 +- 仅 Windows 可用的 Office COM 自动化 + +配置通过环境变量或外部配置文件注入。敏感配置不写入客户端安装包。 + +开发和交互验收使用 SQLite;生产环境使用 PostgreSQL。生产 PostgreSQL 是否使用 Docker 由部署环境决定,不作为应用依赖。 + +### Linux 迁移要求 + +- 使用 `Path.Combine` 或 `IFileStorage`,禁止手写反斜杠路径。 +- 文件名进行平台无关清理,禁止依赖大小写不敏感。 +- 连接字符串、时区和文件根目录均配置化。 +- PDF 转换使用服务器安装的 LibreOffice headless 或跨平台商业组件。 +- 不调用 Excel COM;XLSX 生成必须使用 Open XML/ClosedXML 等库。 +- 日志输出 stdout/结构化文件,由 Windows Event Log 或 Linux journald 收集。 +- 安装脚本分别提供 PowerShell 和 shell/systemd 版本。 + +### 网络 + +- API 仅开放局域网端口。 +- PostgreSQL 只允许 API 服务器访问。 +- Windows 使用 Windows Firewall;Linux 使用 `firewalld` 或 `ufw`。 +- 管理员接口不暴露到公网。 + +### 备份 + +至少包括: + +- PostgreSQL 定时逻辑/物理备份 +- 文件目录增量备份 +- 模板目录备份 +- 配置和证书备份 + +备份策略不能只保存备份文件,必须定期在隔离环境执行恢复演练。 + +## 15. 开发里程碑与验收规则 + +每个里程碑都必须先完成可运行的实际交互,再进入下一个里程碑。验收使用 SQLite、真实文件和真实 WPF 客户端操作,不使用 Mock API、Mock 数据库或只验证函数返回值的测试。生产发布前再使用 PostgreSQL 做一次同样的关键场景验收。 + +### M0:可运行骨架 + +实现: + +- API、WPF 客户端和 SQLite 可以启动。 +- EF Core 迁移可以创建必要表。 +- 客户端可以配置 API 地址。 +- 统一异常提示和日志目录可用。 + +验收: + +1. 在一台 Windows 机器启动 API、SQLite 和客户端。 +2. 客户端能连接 API;API 无法连接数据库时显示明确错误。 +3. 创建一个空数据库后执行 EF Core 迁移,迁移可重复执行且不破坏已有数据。 +4. API 返回错误时,客户端显示业务错误,不显示未处理异常窗口。 + +### M1:账户、组合权限和基础资料 + +实现: + +- 用户登录、停用和密码修改。 +- 用户直接权限。 +- 权限组权限。 +- 用户加入多个权限组。 +- 客户、供应商和基础单位。 +- 产品草稿、发布、停用。 +- 产品供应商、零件/BOM 和供应商历史报价。 +- 本系统不包含产品实物/样品管理,不提供样品实体、接口或页面。 + +验收: + +1. 建立三个用户,分别只授权订单、采购、报关模块。 +2. 一个用户同时拥有“订单查看 + 采购修改 + 出货导出”,客户端只显示允许的菜单和按钮。 +3. 使用无权限用户直接调用 API,API 返回 403;仅隐藏菜单不算通过。 +4. 产品可以包含多个 BOM 零件;同一个零件可以关联多个供应商;每个供应商可以保存不同币种、税率、含税状态和历史价格。 +5. 发布产品时缺少业务必需字段,界面显示缺失字段;发布成功后订单可以选择该产品。 +6. 已被业务引用的产品不能删除,只能停用。 + +### M2:客户订单和采购 + +实现: + +- 客户订单手工录入。 +- PO Excel 导入和原始 PO 附件。 +- 订单明细保存客户 SKU、客户描述覆盖值、数量、装箱率和备注。 +- 订单确认。 +- 根据 BOM 生成采购任务。 +- 采购人员调整供应商、数量、价格、税率和采购内容。 +- 采购合同生成和导出。 +- 到货/完货确认及实际包装数据。 + +验收: + +1. 新建一个包含至少两个产品的订单,并上传真实 PO 文件。 +2. 导入一份真实 Excel,导入失败行必须显示行号和原因,不能静默跳过。 +3. 一个产品拆成主体和两个零件,系统生成不同供应商的采购任务。 +4. 修改一个采购任务的供应商和价格后生成采购合同,合同显示修改后的值。 +5. 修改产品主档供应商价格后,已生成采购合同内容不变。 +6. 录入实际箱数、外箱尺寸、毛重和净重后,订单页面显示采购完成/待出货状态。 + +### M3:出货、报关和客户单证 + +实现: + +- 出货批次和集装箱。 +- 从订单选择本次出货数量,允许一个订单分批出货。 +- 实际箱数、尺寸、CBM、毛重和净重。 +- 报关资料确认。 +- 报关发票、装箱单、外销合同。 +- 客户 CI/PL 占位符模板导入、占位符扫描和字段映射。 + +验收: + +1. 一个订单拆成两个出货批次,两个批次数量之和不得超过订单数量。 +2. 出货明细使用本次实际包装数据,不直接重新读取当前产品默认值。 +3. 确认出货批次后,普通编辑不能覆盖关键数据。 +4. 导入用户自制 XLSX,系统列出所有 `{{...}}` 占位符。 +5. 用户为每个占位符选择业务字段后,生成可打开的 XLSX;产品明细、箱数、重量和合计与页面一致。 +6. 未映射占位符禁止生成,并显示缺失的占位符名称。 + +### M4:供应商开票与财务交接 + +实现: + +- 按供应商生成开票通知。 +- 生成开票用购销合同。 +- 登记供应商发票。 +- 发票状态流转。 +- 订单工作台显示开票完成情况。 + +验收: + +1. 一个出货批次关联两个供应商时,生成两份独立开票通知。 +2. 开票通知中的供应商、采购合同、数量、单价、税率和金额与采购/出货数据一致。 +3. 发票状态只能按规定顺序流转,非法操作显示原因。 +4. 供应商发票登记后,订单工作台能看到待处理和已完成状态。 + +### M5:迁移、备份和上线 + +实现: + +- 解析 `bak/ps_tr*.sql` 的表结构和 INSERT 数据。 +- 原始旧数据进入 `legacy` 区。 +- 客户、供应商、产品、订单、采购合同和出货数据映射到正式表。 +- 导入报告、错误报告和重复执行保护。 +- PostgreSQL、附件和模板备份。 +- Windows 服务部署。 + +验收: + +1. 对复制的 SQL 文件执行 dry-run,不修改正式业务表。 +2. 报告显示每张源表的读取数、成功数、跳过数和错误数。 +3. 同一批次重复执行不会产生重复客户、产品、订单或合同。 +4. 无法关联的产品、客户、供应商和订单明细进入错误报告,不能静默丢失。 +5. 从 SQL 文件导入后的 SQLite 数据库中,能启动系统并打开一个迁移后的订单及其附件。 +6. 新用户能登录,权限、订单、产品和生成文件均可实际操作。 + +### 里程碑完成规则 + +- 验收清单全部通过才算完成。 +- 发现阻塞问题时只修复当前里程碑,不顺手加入未验收功能。 +- 每个里程碑保留一份真实操作记录和生成文件。 +- 任何未完成项进入下一里程碑清单,不用空实现、假数据或 TODO 冒充完成。 + +## 16. 简化工程规则 + +- 先完成业务闭环,再增加抽象。 +- 允许模块之间直接调用;不要为了“解耦”创建大量接口、工厂、事件和通用基类。 +- 优先使用简单函数和清晰的数据结构;只有确实需要共享状态或生命周期时才定义类。 +- API、应用服务和数据库查询可以适度耦合,避免仿照 Java 的多层包装。 +- 一个功能只保留一个实现,不建立兼容层、空实现或未来扩展占位。 +- 业务规则在服务端集中实现;客户端只负责展示、输入和调用命令。 +- 不做完整库存、复杂审批、自由报表、供应商门户和公网访问。 +- 只有发现真实问题并且需要防止回归时才新增单元测试。 +- 单元测试必须针对真实缺陷或明确边界;禁止测试 Mock、代码结构、简单属性访问、按钮转发或“只是不抛异常”。 +- 默认使用真实 SQLite、真实 API、真实 WPF 客户端和真实文件进行交互验收。 +- 每个里程碑只运行覆盖当前验收场景的最窄检查,不运行无关的大型测试套件。 +- 注释只在解释“为什么必须这样做”时编写;不要注释代码正在执行的动作。没有必要时不写注释。 +- 可以使用 subagent 完成边界清晰的实现任务,但 subagent 不负责最终验收。 +- 主 agent 必须检查 subagent 的修改,启动真实环境并按里程碑清单完成实际交互验收;未经过主 agent 验收只能标记为待验收。 +## 17. 关键技术决策 + +| 项目 | 决策 | +|---|---| +| 主数据库 | 开发/验收使用 SQLite;生产使用 PostgreSQL | +| 后端 | ASP.NET Core Web API,.NET 11 | +| 客户端 | WPF,.NET 11,MVVM | +| 部署 | Windows Server 或 Linux;API 使用 Windows Service 或 systemd | +| 数据访问 | EF Core;不引入 Dapper | +| 文件 | 服务器文件系统 + 数据库文件元数据 | +| 认证 | access token + refresh token,HTTPS | +| 任务 | 数据库任务表 + BackgroundService;开发和验收使用 SQLite | +| 单证 | Excel 模板渲染,XLSX 优先,PDF 后处理 | +| 架构 | 模块化单体,不做微服务 | +| 旧数据 | SQL Server 只读读取,PostgreSQL 分层导入 | +| 删除策略 | 业务数据不物理删除,使用停用/作废 | +| 并发 | `row_version` 乐观并发控制 | + +## 18. 暂不实现 + +- 微服务和消息队列。 +- 移动端和网页端。 +- 复杂工作流引擎。 +- 完整财务总账。 +- 复杂库存和仓库条码系统。 +- 公网访问。 +- 自由报表设计器。 diff --git a/docs/05-部署与备份运维.md b/docs/05-部署与备份运维.md new file mode 100644 index 0000000..abb72a5 --- /dev/null +++ b/docs/05-部署与备份运维.md @@ -0,0 +1,105 @@ +# 部署与备份运维 + +本文覆盖 M5 基础:数据库选择、健康检查、NSSM 进程托管,以及文件/模板/数据库备份。开发和本地验收继续使用 SQLite,生产使用 PostgreSQL;业务代码不依赖具体数据库。 + +## 1. 数据库选择 + +配置项(`appsettings.json`、环境专属配置或环境变量三选一注入,优先级由 ASP.NET Core 配置系统决定): + +| 配置 | 说明 | +|---|---| +| `Database:Provider` | `Sqlite`(默认,未配置时也是 SQLite)或 `PostgreSql`(接受 `Postgres`/`Npgsql` 别名)。其他值直接使启动失败,不会静默回退 SQLite。 | +| `ConnectionStrings:Default` | 当前提供程序的连接字符串。SQLite 缺省时使用内容根目录下 `data/leiren-dev.db`,相对路径按内容根目录解析。PostgreSQL 缺失、格式错误或缺少 `Host`/`Database` 时启动失败,且错误信息不回显连接字符串(避免泄露密码)。 | +| `FileStorage:RootPath` | 服务器文件根目录。附件、上传的单证模板和生成文件都在此目录下,数据库只存元数据。 | +| `HealthChecks:DatabaseTimeout` | 就绪检查的数据库连接超时,默认 5 秒。 | + +生产连接字符串优先通过服务账户的环境变量注入,不要把真实密码写进发布包或版本控制: + +```powershell +# 仅示例变量名;实际由服务运行账户的环境提供 +ConnectionStrings__Default = Host=127.0.0.1;Port=5432;Database=leiren_erp;Username=leiren_erp;Password=... +Database__Provider = PostgreSql +``` + +PostgreSQL 侧准备(管理员在数据库服务器上执行,应用不自动建库/建用户): + +```sql +CREATE USER leiren_erp WITH PASSWORD '...'; +CREATE DATABASE leiren_erp OWNER leiren_erp; +``` + +当前仓库尚无 EF Core 迁移,API 首次启动会用 `EnsureCreated` 建表;一旦引入首个迁移,启动自动切换为 `Migrate`。PostgreSQL 只允许 API 服务器访问(防火墙/安全组与 `pg_hba.conf` 同时限制)。 + +## 2. 健康与就绪检查 + +| 端点 | 含义 | 失败表现 | +|---|---|---| +| `GET /health/live` | 进程存活探针,只证明进程能响应。 | 进程挂死时无响应。 | +| `GET /health`、`GET /health/ready` | 就绪探针:打开真实数据库连接(带超时),并验证文件存储根目录存在且可写(写入后立即删除探针文件)。 | 任一项不健康返回 HTTP 503,逐项给出 `name/status/durationMs/description`; healthy 返回 200。响应不包含连接字符串、密码或服务器路径。 | + +两个端点都无需登录,负载均衡和服务监控应使用 `/health/ready`,不要用 `/health/live` 代替业务就绪判断。 + +## 3. NSSM 进程托管 + +生产环境不使用 Windows Service Host。使用 NSSM 将 ASP.NET Core API 作为普通进程托管。 + +```powershell +dotnet publish src/Leiren.Erp.Api -c Release -o C:\LeirenErp\Api +nssm install LeirenErpApi C:\Program Files\dotnet\dotnet.exe +nssm set LeirenErpApi AppParameters "C:\LeirenErp\Api\Leiren.Erp.Api.dll --urls http://0.0.0.0:5118" +nssm set LeirenErpApi AppDirectory C:\LeirenErp\Api +nssm set LeirenErpApi AppEnvironmentExtra "ASPNETCORE_ENVIRONMENT=Production" "Database__Provider=PostgreSql" +nssm set LeirenErpApi AppExit Default Restart +nssm set LeirenErpApi AppStdout C:\LeirenErp\Logs\api.out.log +nssm set LeirenErpApi AppStderr C:\LeirenErp\Logs\api.err.log +nssm start LeirenErpApi +``` + +NSSM 配置完成后必须检查 `GET /health/ready` 返回 `200`。停止或删除进程不会删除数据库、附件和备份目录。 + +网络:API 只开放局域网端口,管理接口不对公网暴露。 +## 4. 备份(文件、模板与数据库) + +备份工具 `Leiren.Erp.Backup` 把配置的每个源目录(含文件存储、独立模板目录)连同可选数据库备份复制到带时间戳的备份目录,逐文件计算 SHA-256 写入 `manifest.json`,并在宣布完成前把已写文件重新哈希自校验。任何失败(源目录缺失、目录互相包含、空备份、pg_dump 失败、校验不一致)都以非零退出码结束并删除该次未完成目录,不会冒充成功。 + +```powershell +dotnet publish src/Leiren.Erp.Backup -c Release -o C:\LeirenErp\Tools + +# 先 dry-run:只枚举并哈希源文件,不写任何东西 +C:\LeirenErp\Tools\Leiren.Erp.Backup.exe backup --config C:\LeirenErp\Config\backup.json --dry-run + +# 正式备份 +C:\LeirenErp\Tools\Leiren.Erp.Backup.exe backup --config C:\LeirenErp\Config\backup.json + +# 校验已有备份(逐文件比对大小与 SHA-256) +C:\LeirenErp\Tools\Leiren.Erp.Backup.exe verify --backup E:\LeirenErpBackups\20261113T020000Z-xxxxxxxx +``` + +配置示例见 `deploy/windows/backup.example.json`: + +- `Sources[]`:`Name`(仅字母/数字/`-`/`_`/`.`,用作备份内文件夹名)+ `Path`。源目录不存在会直接失败,不跳过。经 API 上传的单证模板保存在文件存储根目录下,已随 `FileStorage` 源覆盖;只有模板另行存放时才保留 `Templates` 源(目录需真实存在)。 +- `DestinationPath`:备份根目录,不能位于任何源目录之内、也不能包含源目录。 +- `IncludeDatabase` + `DatabaseProvider` + `DatabaseConnectionString`:SQLite 使用在线备份 API 做一致性副本;PostgreSQL 调用 `pg_dump --format=custom`,密码只通过 `PGPASSWORD` 环境传递,不进进程参数。`pg_dump` 不存在或退出码非零即失败。连接字符串也可改用环境变量 `LEIREN_ERP_CONNECTION_STRING` 注入(参数/配置文件优先)。 +- `AllowEmpty`:默认 `false`,源为空且无数据库时拒绝生成空备份。 + +每次备份目录结构: + +```text +// + manifest.json # 备份编号、时间、每个文件的源/相对路径/大小/SHA-256、数据库条目 + files/<源名>/... # 按原相对路径保存的文件与模板 + database/leiren-erp.dump | leiren-erp.sqlite # 仅 IncludeDatabase 时 +``` + +定时备份使用任务计划程序或现有运维平台调用 `Leiren.Erp.Backup`,必须保留工具退出码;失败不得打印成功。 + +## 5. 恢复与演练 + +备份“生成成功”不等于可恢复,至少每季度在隔离环境演练一次: + +1. 对备份目录先跑 `verify`,失败则该备份不可用,换更早的备份并记录。 +2. PostgreSQL:在隔离实例上用 `pg_restore` 恢复 `database/leiren-erp.dump`;SQLite:停 API 后用备份的 `leiren-erp.sqlite` 替换数据文件。 +3. 把 `files/<源名>/` 内容按原相对路径还原到文件存储/模板根目录,不要改名。 +4. 用隔离配置启动 API,确认 `/health/ready` 为 200,并登录抽查一个订单及其附件、一个模板和一份生成文件。 + +演练结果(日期、备份编号、校验结论、恢复耗时)记录在运维日志中。 diff --git a/docs/启动文档.md b/docs/启动文档.md new file mode 100644 index 0000000..a785fe8 --- /dev/null +++ b/docs/启动文档.md @@ -0,0 +1,484 @@ +# Leiren ERP 启动文档 + +## 1. 当前仓库状态 + +当前仓库处于设计和原型阶段,包含: + +- `docs/01-总体业务流程设计.md`:总体业务流程 +- `docs/02-产品与样品库设计.md`:产品、零件、供应商和报价设计 +- `docs/03-数据库迁移与导入设计.md`:旧 ERP 数据迁移设计 +- `docs/04-系统架构与技术设计.md`:后端、WPF 客户端、数据库和里程碑 +- `docs/client-shell.html`:WPF 客户端壳的 HTML 参考原型 +- `migration/README.md`:迁移工具约定 +- `订单流程涉及单据文件/`:真实业务单据样本 +- `bak/`:旧 ERP SQL Server 备份和 SQL 导出文件 + +目前没有可直接运行的 API、WPF 客户端或数据库工程。 + +## 2. 查看客户端壳原型 + +### 方式 A:直接打开 + +在 Windows 文件管理器中双击: + +```text +docs/client-shell.html +``` + +### 方式 B:使用本地静态服务器 + +在仓库根目录打开 PowerShell: + +```powershell +python -m http.server 8080 --directory docs +``` + +浏览器打开: + +```text +http://127.0.0.1:8080/client-shell.html +``` + +停止服务: + +```text +Ctrl+C +``` + +HTML 原型只用于确认页面结构、导航名称和信息层级,不连接数据库,也不实现真实业务操作。 + +## 3. 目标开发环境 + +### 必需 + +- Windows +- .NET 11 SDK +- Visual Studio 2022 或 JetBrains Rider +- Git + +### 开发数据库 + +- SQLite +- 通过 EF Core 访问 +- 数据库文件放在本地开发目录,不提交到 Git + +### 生产数据库 + +- PostgreSQL +- 通过 EF Core PostgreSQL provider 访问 +- WPF 客户端不直接连接数据库 + +### 文件和单证 + +- 开发阶段使用本地文件目录 +- 生产阶段使用服务器文件目录 +- Excel 使用 Open XML SDK 或 ClosedXML +- 不使用 Excel COM 自动化 + +## 4. 目标解决方案 + +建议解决方案结构: + +```text +src/ + Leiren.Erp.Api/ + Leiren.Erp.Client/ + Leiren.Erp.Domain/ + Leiren.Erp.Application/ + Leiren.Erp.Infrastructure/ + Leiren.Erp.Migration/ +``` + +第一版不要拆分微服务,也不要增加独立消息队列服务。 + +如果项目尚未创建,先创建最小可运行结构: + +```powershell +dotnet new sln -n Leiren.Erp +dotnet new webapi -n Leiren.Erp.Api -f net11.0 +dotnet new wpf -n Leiren.Erp.Client -f net11.0 +dotnet sln Leiren.Erp.sln add .\src\Leiren.Erp.Api\Leiren.Erp.Api.csproj +dotnet sln Leiren.Erp.sln add .\src\Leiren.Erp.Client\Leiren.Erp.Client.csproj +``` + +实际创建项目时,以已安装 SDK 支持的目标框架为准。 + +## 5. EF Core 数据库配置 + +开发环境使用 SQLite: + +```text +Database: .\data\leiren-dev.db +Provider: Microsoft.EntityFrameworkCore.Sqlite +``` + +生产环境使用 PostgreSQL: + +```text +Provider: Npgsql.EntityFrameworkCore.PostgreSQL +``` + +业务代码必须使用 EF Core 的通用关系模型。不得在业务逻辑中直接写 PostgreSQL 专用 SQL,避免开发环境和生产环境行为不一致。 + +典型配置分离: + +```text +appsettings.Development.json -> SQLite +appsettings.Production.json -> PostgreSQL +``` + +数据库密码不得写入 Git,不得写入 WPF 客户端安装包。 + +## 6. Subagent 使用规则 + +开发任务可以分配给 subagent,但 subagent 只负责一个边界清晰的实现任务,例如一个 API 模块、一个 WPF 页面或一个迁移解析步骤。 + +主 agent 必须负责最终验收: + +1. 检查 subagent 修改的文件和实际差异。 +2. 阅读关键代码,确认实现没有超出任务范围。 +3. 启动真实 API、SQLite 和 WPF 客户端。 +4. 按当前里程碑验收规则执行真实交互。 +5. 发现问题后由主 agent 决定修复方式,不能把 subagent 自己的“已完成”当作验收结果。 + +subagent 不得自行宣布功能验收通过。没有主 agent 的实际验收,任务只能标记为“待验收”。 + +## 7. 启动顺序 + +### 开发阶段 + +1. 启动 API。 +2. API 使用 SQLite 数据库。 +3. 执行 EF Core 数据库迁移。 +4. 启动 WPF 客户端。 +5. 使用真实客户端操作验证功能。 + +推荐启动检查: + +```powershell +dotnet restore +dotnet build +``` + +启动 API: + +```powershell +dotnet run --project .\src\Leiren.Erp.Api +``` + +启动 WPF: + +```powershell +dotnet run --project .\src\Leiren.Erp.Client +``` + +如果解决方案尚未包含数据库迁移命令,不要创建假的迁移脚本;先完成 EF Core `DbContext` 和第一条真实迁移。 + +## 8. 第一阶段启动验收 + +### M0 验收 + +以下操作必须使用真实 SQLite、真实 API 和真实 WPF 客户端完成: + +1. 创建空 SQLite 数据库。 +2. 执行 EF Core 迁移。 +3. 启动 API。 +4. 启动 WPF 客户端。 +5. 登录一个真实创建的用户。 +6. API 连接失败时,客户端显示明确错误。 +7. API 返回业务错误时,客户端显示错误信息,不弹出未处理异常窗口。 +8. 关闭并重新启动 API 后,SQLite 中的数据仍然存在。 + +### M1 验收 + +1. 创建三个用户。 +2. 分别授权订单、采购和报关模块。 +3. 验证用户只能看到自己的模块。 +4. 直接调用无权限 API,确认返回 `403`。 +5. 创建一个产品。 +6. 为产品添加两个零件。 +7. 为同一个零件添加两个供应商。 +8. 为两个供应商分别保存不同报价和税率。 +9. 发布产品。 +10. 在订单页面选择已发布产品。 + +## 9. 真实交互测试规则 + +默认不写单元测试。 + +只有发现真实缺陷,并且需要防止回归时,才新增测试。新增测试必须说明: + +- 真实问题是什么 +- 用户如何遇到问题 +- 测试防止哪一次回归 +- 为什么实际交互验收不足以覆盖该问题 + +禁止编写以下测试: + +- Mock API 测试 +- Mock 数据库测试 +- 只测试属性读写 +- 只测试按钮转发 +- 只测试方法不抛异常 +- 只验证代码行被执行 +- 只验证控件数量或 XAML 文本 + +## 10. 编码规则 + +- 优先使用简单函数和直接数据结构。 +- 不为每个方法创建接口。 +- 不为了“解耦”增加大量工厂、事件、适配器和通用基类。 +- 允许模块之间适度耦合。 +- 业务规则集中在 API,WPF 只负责输入、显示和调用。 +- 注释只写“为什么必须这样做”,不写“代码正在做什么”。 +- 没有必要时不写注释。 +- 不写空实现、假数据、无效 fallback 或 TODO 占位。 +- 一个功能只保留一个实现。 + +## 11. 注意事项 + +- WPF 客户端不直接访问 SQLite 或 PostgreSQL。 +- 生产环境不使用开发 SQLite 数据库。 +- 真实单据模板先用仓库中的文件验证;新模板使用 `{{占位符}}`,导入后由用户完成字段映射,不要先写死模板单元格坐标。 +- 旧 ERP 数据只从 `bak/ps_tr.sql`、`bak/ps_tr_mail.sql` 和 `bak/ps_tr_pic.sql` 提取;不恢复、不解析、不使用 `.bak`。 + +## 12. 当前开发状态 + +已完成: + +- .NET 11 分层解决方案、API、WPF 客户端和迁移 CLI 骨架 +- SQLite EF Core 开发数据库 +- 用户初始化、登录、Bearer Session、角色和模块权限 +- 产品、零件、供应商报价和产品发布 +- 客户、销售订单和订单确认 +- 采购任务、采购合同、到货和实际包装 +- 出货批次、集装箱和出货实际数据快照 +- 报关资料和单证包元数据版本 +- 供应商开票通知、发票登记和开票合同快照 +- 附件元数据、版本、服务器文件存储和下载 +- 旧 ERP UTF-16 SQL 文件检查/快照 CLI +- WPF 登录、产品库、客户、订单和采购页面 + +当前开发验收命令: + +```powershell +dotnet build .\Leiren.Erp.slnx +dotnet run --project .\src\Leiren.Erp.Api --urls http://127.0.0.1:5118 +dotnet run --project .\src\Leiren.Erp.Migration -- inspect --source-file .\bak\ps_tr.sql +dotnet run --project .\src\Leiren.Erp.Client +``` + +开发数据库位置: + +```text +src/Leiren.Erp.Api/data/leiren-dev.db +``` + +该目录不应提交到 Git。生产环境必须配置 PostgreSQL 连接字符串和服务器文件存储目录。 + +## 13. M2 开发状态 + +已完成 M2 客户订单和采购功能: + +- PO Excel 通过表头识别导入,不依赖固定单元格坐标。 +- 导入预览返回工作表行号、错误原因、缺失表头和无效数据。 +- 失败行不会静默跳过,也不会创建草稿订单。 +- 有效 PO 可以创建草稿订单,并将原始 PO 保存到附件版本系统。 +- 采购合同可导出为真实 XLSX 文件。 +- 合同导出使用采购合同自身快照,不重新读取产品或供应商当前报价。 +- 合同重新导出产生新的附件版本。 +- 销售订单详情和采购页面显示采购完成、待出货、部分出货和已完成状态。 +- 工作台状态从订单、采购任务、到货和出货数据实时计算,不保存重复状态字段。 + +M2 验收使用临时 SQLite 数据库完成: + +```text +创建完整业务表结构 +创建管理员 +登录 API +访问销售订单列表 +访问采购任务列表 +``` + +已有开发数据库如果创建于 M1 之前,需要先执行正式 EF Core migration 或重新创建开发数据库;不得在生产数据库上删除旧数据代替迁移。 + +## 14. M3 开发状态 + +已完成客户 CI/PL 单证基础能力: + +- XLSX 模板上传和真实文件保存。 +- 遍历所有工作表扫描 `{{占位符}}`。 +- 返回占位符名称、工作表、单元格位置和明细行信息。 +- 支持模板版本和模板附件版本。 +- 支持业务字段映射配置。 +- 映射字段使用受限业务字段目录,不接受任意表达式。 +- 生成前校验所有占位符,未映射字段全部返回并禁止生成。 +- 生成后的模板映射自动锁定,修改必须上传新版本模板。 +- 基于确认后的出货批次快照生成 CI/PL XLSX。 +- 明细行按出货明细复制。 +- 合计由系统重新计算,不依赖模板公式。 +- 生成文件保存到附件版本系统。 +- 未确认出货批次禁止生成客户单证。 + +M3 模板接口: + +```text +POST /api/document-templates/upload +POST /api/document-templates/{fileId}/versions +GET /api/document-templates/{fileId}/scan +GET /api/document-templates/fields +POST /api/document-templates/mapping-profiles +POST /api/shipping-batches/{id}/documents/ci-pl +``` + +使用仓库中的旧 Excel 模板进行扫描时,如果模板没有 `{{...}}` 占位符,接口会明确返回 400,不会创建无效模板记录。 + +## 15. M4/M5 开发状态 + +M4 财务交接已完成: + +- 一个出货批次按供应商拆分独立开票通知。 +- 开票通知保存供应商、采购合同、数量、单价、税率和金额快照。 +- 发票状态必须按 `Received -> HandedToFinance -> Completed` 顺序流转。 +- 非法状态变更返回业务错误原因。 +- 订单工作台显示每个供应商的开票状态、通知数、发票数、已开票金额和待开票金额。 + +M5 迁移和上线基础已完成: + +- `ps_tr.sql`、`ps_tr_mail.sql`、`ps_tr_pic.sql` 的 UTF-16 解析。 +- `legacy_*` 暂存表和批次哈希。 +- dry-run 不修改正式业务表。 +- 已知客户、产品、订单和采购合同的正式表映射。 +- 无法映射数据进入错误表,不静默丢失。 +- 重复批次拒绝再次导入。 +- SQLite/PostgreSQL 显式数据库提供者选择。 +- 文件和模板目录备份。 +- SHA-256 备份清单和备份校验。 +- PostgreSQL 使用 `pg_dump`。 +- `/health/live`、`/health`、`/health/ready`。 +- NSSM 进程托管和 `/health/ready` 就绪检查。 + +备份 dry-run 示例: + +```powershell +dotnet run --project .\src\Leiren.Erp.Backup -- backup --dry-run ` + --source docs=docs ` + --destination temp/m5-backups +``` + +## 16. 产品库补充能力 + +- 本系统不包含产品实物/样品管理,不提供样品登记、借出、归还、确认、库存或样品附件引用功能,产品库不维护样品记录。 +- 产品详情提供资料完整度检查。 +- 产品发布只阻塞必要基础字段,采购、出货、报关字段作为待补齐提示。 +- 产品变更记录按产品版本追加保存,不能修改或删除。 +- 产品详情提供历史记录和变更字段。 +- 产品库主界面是列表优先布局:左侧显示可搜索、可筛选和可键盘操作的产品列表,右侧显示当前产品快速预览,不在列表区域嵌入编辑器。 +- 产品列表按 `product-photo` 附件类别加载当前版本图片缩略图;没有图片时保持空缩略图,不生成假图片。 +- 产品、部件和部件供应商报价分别使用独立编辑窗口,列表双击或回车只打开对应编辑窗口。 +- 产品详情右侧预览提供部件和部件供应商报价列表,新增、编辑、删除操作均通过真实 API 完成。 +- WPF 客户端配置保存在 `%LOCALAPPDATA%\LeirenErp\settings.ini`,不再读取 `LEIREN_API_BASE_URL` 环境变量;`ApiBaseUrl` 可直接在 `[Client]` 段修改。 +- “保持登录”使用服务端持久化 refresh token,客户端只在 INI 中保存 Windows 当前用户 DPAPI 保护后的令牌。登录成功后 refresh token 会轮换保存,退出登录会撤销服务端令牌。 + +## 17. 主数据与权限客户端 + +- 供应商主数据支持编码、名称、联系人、税号、默认币种、税率和停用。 +- 供应商被报价、采购或开票引用后禁止硬删除。 +- 采购合同和采购任务保存供应商快照,不因主数据后续修改而改变历史。 +- 系统设置提供用户、角色、模块权限和直接权限管理。 +- 非管理员访问系统设置显示服务器返回的 403 权限错误。 +- 管理员可以创建用户、启用/停用用户、分配角色、模块和直接权限。 +- 客户端不显示密码哈希。 + +## 18. 首页工作台 + +- 首页通过 `/api/dashboard` 加载真实业务汇总。 +- 展示客户订单、采购任务、采购合同、出货批次、报关单、供应商开票通知和产品状态数量。 +- 汇总按服务端状态枚举返回,即使数量为零也保留状态项。 +- 首页需要 `dashboard:view` 权限,客户端支持刷新和错误显示。 + +## 19. 功能验证记录 + +- 使用全新 SQLite 数据库完成 97 次真实 HTTP 调用的端到端验证。 +- 验证链路覆盖:客户、供应商、产品、报价、销售订单、采购任务、采购合同、到货、出货、报关、CI/PL、供应商开票、发票、附件、权限和首页汇总。 +- 验证结果:成功响应 200/201;预期的权限、状态和数据校验错误返回 400/401/403/404/409。 +- 真实 XLSX 采购合同导出、CI/PL 模板扫描映射生成、PO 导入和附件下载均已验证。 +- 复杂总账、完整仓库库存、供应商门户、自动海关接口和自由报表设计器仍属于第一阶段明确排除范围。 + +## 20. 真实生产数据测试实例 + +测试实例可以与开发数据库完全隔离: + +```powershell +$env:ConnectionStrings__Default = "Data Source=D:\repo\leiren-erp\temp\production-rerun-20261114\data\test.db" +$env:FileStorage__RootPath = "D:\repo\leiren-erp\temp\production-rerun-20261114\storage" +dotnet run --project src/Leiren.Erp.Api --urls http://127.0.0.1:5128 +``` + +本次真实迁移使用 `bak/ps_tr.sql`、`bak/ps_tr_mail.sql` 和 `bak/ps_tr_pic.sql`,共读取 271828 行,正式映射 146 行,未映射 2 行。已导入客户 3 条、供应商 25 条、产品 110 条、销售订单 1 条、采购任务 3 条、采购合同 3 条。未映射的 1 条出口发票及 1 条出口发票明细因当前系统没有对应的正式出口发票实体,仍保存在 `legacy_*` 暂存表和迁移报告中。 + +测试账号:`erp-tester` / `ErpTest2026!`。 + +产品库采用资源管理器式列表,支持搜索、状态/分类/类型筛选、排序、分组、键盘选择和右侧详情。 + +产品、客户、供应商、销售订单、用户和角色的新建操作均打开各自业务向导,取消不会写入数据,只有向导成功提交后才创建记录。 + +## 21. 采购订单向导 + +- 从“新建采购订单”进入时,第一步是采购订单(销售订单)列表;选择订单后才进入创建模式。 +- 从订单卡片(“进入采购”)或采购任务卡片(“查看拆解”)进入时直接打开创建模式页,步骤条不显示第一步。 +- 创建模式页标题为“选择采购方式”,只读显示当前订单,再选择“新建采购方案”或“复用历史方案”。 +- 新建方案第二步按订单产品列出全部启用配件;每个配件只列出已报价的供应商,组合框旁的“编辑”直接维护该配件的供应商报价。 +- 复用历史方案第二步只列出同一产品在其他订单中的历史采购任务,选中后沿用当时的供应商、单价和税率。 +- 生成采购任务时提交每个配件的供应商与价格;同一订单明细已有任务时跳过,不重复生成。 +- 采购页(左侧栏“采购”,其下缩进子项“采购合同”)是一个按客户订单分组的列表:订单号、客户 PO 和采购状态在订单行,下面按产品 → 部件列出供应商和数量;产品只有一个采购项时合并成一行;未生成方案时供应商显示 TBD。 +- 列表上方提供搜索(订单号、PO、客户、产品、部件、供应商)、状态筛选(待生成采购方案 / 待导出采购合同 / 待到货确认 / 已完成)和排序(订单日期、订单号、客户 PO、采购状态)。 +- 采购状态由订单的未取消采购任务推导:无任务=待生成采购方案;有任务但未全部进入已确认合同=待导出采购合同;任务都在已确认合同内=待到货确认;任务全部完成=已完成。 +- 订单行的“处理”按采购状态跳转:待生成→采购订单向导,待导出→采购合同页面(搜索框自动填入该订单的客户 PO),待到货确认→到货确认向导;已完成不显示处理按钮。 +- 待导出采购合同且全部任务都还没进合同时,订单行显示“修改采购单”:重新打开采购订单向导,不显示创建模式步骤,直接按原方案预填供应商与报价,保存后覆盖原采购任务。 +- 客户订单、采购、采购合同、出货与报关、供应商开票页面使用同一布局:顶部筛选卡(搜索 / 状态 / 排序),下方一个列表卡,不再在列表卡内重复页面标题;分组下的明细行统一向右缩进,状态标签垂直居中。页头只显示页面标题,不再显示英文眉题和说明文字。搜索在停止输入 400ms 后自动执行,回车立即执行。 +- 客户订单列表中草稿订单显示“确认订单”,二次确认后调用 `POST /api/sales-orders/{id}/confirm`;服务端校验失败(例如产品未发布)时在左侧栏提示原因。 +- 左侧“采购合同”页面按客户订单分组:已有采购方案但仍有任务未生成合同的订单立即显示一行“尚未生成合同”和“生成合同”按钮;草稿合同显示“修改 / 确认”,修改只改合同头信息并使版本号 +1;“确认”先打开预览窗口,预览中确认后再弹出二次确认,确认后合同锁定并保存导出文件,按钮变为“导出”(即下载)。页面顶部不提供“生成采购合同”按钮。 +- 合同预览使用 `GET /api/purchase-contracts/{id}/export/preview` 取回与导出相同的 XLSX,客户端用 ExcelRenderer(NuGet `ExcelRenderer`,SkiaSharp 渲染,不依赖 Excel/LibreOffice/WebView2)把工作表渲染成一张完整图片;字体使用 Windows 自带等线(`Deng.ttf` / `Dengb.ttf`)。默认缩放到适应窗口,单击放大到 100% 并保持点击位置,按住拖动平移,再次单击恢复适应窗口。 +- 生成采购合同向导只列出尚未进入合同的采购任务:按供应商新建合同并确认履约条件;不生成下载文件。 +- 采购合同导出在采购合同页面按合同执行,使用 `src/Leiren.Erp.Api/templates/purchase-contract.xlsx`(由 `订单流程涉及单据文件/采购合同样本.xlsx` 改造,配置项 `PurchaseContract:TemplatePath`)。模板占位符写在单元格内,明细行按 `{{...}}` 所在行复制并填充,合并单元格与行高随之复制;表头、合计、签约日期同步替换。 +- 到货登记按最终成品(订单明细)进行,不选择零件:每个成品填写本次到货数量(默认待到数量,可部分到货,填 0 表示本次未到)、到货日期,并确认外箱尺寸(长宽高 cm,必填)、装箱率或箱数、单箱毛重 / 净重(必填),已按产品包装资料预填。提交时该成品的每个采购任务按比例登记到货,外箱数据只记在成品 / 主体任务(没有时取第一项)的到货记录上,箱数按成品数量计算。 +- 成品已到货数量 = 订单数量 × 各采购任务到货比例的最小值(最慢的零件决定成品数量);出货数量累计不能超过该数量。 +- 主窗口不显示顶部工具栏;左侧栏底部显示当前用户的显示名称和账号,点击后弹出菜单,“退出登录”在菜单内;操作结果提示也显示在该区域。 +- 登录是独立窗口,启动时在主窗口之前弹出;勾选“保持登录”且 refresh token 仍有效时自动登录,不弹出登录窗口。退出登录会隐藏主窗口并重新弹出登录窗口(保留用户名和“保持登录”选择),关闭登录窗口即退出程序。 +- 向导窗口只显示标题和步骤,不再显示副标题、提示文字和右上角重复的关闭按钮(使用窗口自带关闭)。 +- 图标统一使用系统已安装的 Segoe Fluent Icons 字体(Windows 10 回退到 Segoe MDL2 Assets,码位相同),字体不随程序分发;代码中的图标常量在 `Controls/FluentIcons.cs`。 +- 全局控件样式在 `App.xaml`(按钮、输入框、表格、主操作按钮 `PrimaryAction`);产品与供应商、客户资料、供应商资料、系统设置页面套用与业务页面相同的深色页头(`Controls/PageFrame.cs`),同样只显示页面标题。 +- 客户订单页的草稿订单可“修改”(打开订单向导并带入全部订单信息和明细,保存走 `PUT /api/sales-orders/{id}`)或“删除”(二次确认后 `DELETE /api/sales-orders/{id}`,只允许草稿)。 +- 修改采购单时点“编辑”打开该供应商针对此部件的报价并带出全部已存内容;该供应商还没有报价时以采购单中的价格、币种、单位、税率预填一份新报价。内容类型、产品类型、部件类型在界面上显示中文。 + +## 22. 出货与报关 + +- 出货与报关页面只显示真实数据:已确认订单中成品已到货但未装箱的产品(待装箱),以及出货批次(待确认出货 / 已出货 / 已取消),按客户订单分组,顶部提供搜索、出货状态筛选和排序。 +- `GET /api/shipping-batches/ready-orders` 返回可装箱订单:每个订单明细的订单数量、成品已到数量、已装箱数量、可出货数量,以及最近一次到货登记的外箱数据(没有时取产品包装资料)。 +- “装箱”向导:选择订单(同一客户、同一币种的多个订单可一起勾选拼柜;从订单行或今日概览待办进入时跳过此步,直接装箱该订单)→ 选择标准集装箱(20GP / 40GP / 40HQ / 45HQ,按内径和最大载重)并填写各订单产品的本次出货数量(不出货填 0)→ 出货信息(起运港、目的港必填,默认取第一个出货订单)→ 确认装箱。每柜可装箱数取 6 种统一摆放方向中能装最多的一种,再按单箱毛重受载重上限约束;系统按订单号顺序逐柜装货,每箱占 1/(该产品每柜可装箱数)个柜,柜内剩余空间由下一个产品 / 订单继续填满,放不下的部分进入下一柜,并显示每个柜装了哪些订单的哪些产品及箱数。 +- 完成后创建草稿出货批次:集装箱按分配结果生成(柜号暂为 `40HQ-01` 形式,备注“柜号待补”),每条出货明细按 `ContainerNo` 归属到对应集装箱,一个产品跨柜时按整箱拆成多条明细。出货明细可以来自同一客户、同一币种的任意已确认订单(服务端校验),批次的订单号 / PO 显示为全部订单(如 `SC-TEST-02 / SC-TEST-03`),按订单筛选批次时包含拼柜批次。草稿批次行可“柜号”(补录集装箱号和封条号,留空则保持待补)、“确认出货”(锁定报关快照;仍有待补柜号时二次提醒)或“取消”(产品回到待装箱);已出货批次显示“报关资料”和“生成单证”。 +- “报关资料”:没有有效报关资料时自动按出货批次生成草稿;报关品名、HS 编码、申报要素、原产国、境内货源地、征免、报关单位按同一产品(内部货号)最近一次已确认报关单预填,没有历史时取产品资料;监管方式、征免性质沿用该客户最近一次报关单。草稿可修改表头(报关单号、发票编号、出口 / 申报日期、监管方式、征免性质、备注)和每项明细(含数量、单价)并保存;“确认报关单”二次确认后锁定。已确认的报关资料只能作废,作废后重新打开生成新版本。 +- 报关单证(报关发票、报关装箱单、报关外销合同、报关单数据)从已确认的报关资料取数:数量、单位、单价、金额、HS 编码和报关品名等以报关资料为准;未确认报关资料时拒绝生成。客户 CI / PL 仍按出货明细生成。 +- “生成单证”向导:选择已确认出货的批次(从批次行进入时跳过)→ 多选单证模板(按类型分组,只有字段全部映射的报关 / 客户单证模板可勾选;其他客户的专用模板不显示)→ 确认生成。进入时按批次客户自动勾选:每种单证优先勾选该客户专用的最新模板,没有时勾选最新的通用模板,可再调整。每份单证调用 `POST /api/shipping-batches/{id}/documents/generate` 生成并存入附件版本,生成后选择文件夹一次保存全部文件。 +- “开票通知”(已出货批次):填写发票抬头、地址、电话、开户银行、帐号、税号、海关代码、寄件地址、联系人、签订地点(按上一份开票通知预填),调用 `POST /api/billing/notices/generate-from-shipping-batch`,每个供应商生成一份开票通知和开票用购销合同。开票内容取自已确认的报关资料:品名、单位与报关单一致;一个产品由多个供应商供货(主体、配件、包装)时,报关数量按各供应商本次出货部分的含税采购金额比例拆分(整数数量按最大余数法分配,且每家至少 1),各供应商数量合计等于报关数量,金额为各自的含税采购金额,单价 = 金额 / 数量。未确认报关资料时拒绝生成;外销发票号为空时取报关资料的发票编号。 + +## 23. 供应商开票单据 + +- “供应商开票”页按出货批次分组,顶部显示待确认、待收票和已收票金额。流程:草稿开票通知可“编辑”(发票抬头、联系人、寄件地址等表头资料)→ 批次“分配数量”(每个报关品名由一个或多个供应商开票,数量合计必须等于报关数量,金额为各供应商含税金额,单价自动计算;“全部给它”把该品名全部数量和金额分给一个供应商;某供应商所有品名都为 0 时其开票通知作废;`PUT /api/billing/notices/shipping-batches/{batchId}/allocation`)→ 批次“确认开票”(两次确认后锁定并发给供应商,`POST /api/billing/notices/shipping-batches/{batchId}/confirm`)→ 每个供应商“登记发票”(发票号码、开票日期、含税金额和税率,自动拆分不含税金额和税额)→ “完成”。每份开票通知都可“导出单据”:选择文件夹后保存开票通知书和开票用产品购销合同两份 xlsx(`GET /api/billing/notices/{id}/documents/SupplierInvoiceNotice|SupplierBillingContract`)。 +- 付款管理页在统计卡片下方显示两张图表:近 6 个月应付(按应付日期)与已付(按付款日期)的月度柱状图,以及各供应商待付款金额排行;图表随搜索、供应商和日期筛选变化,按金额最大的币种统计。 +- 两种单据走模板系统:模板类型“开票通知”“开票购销合同”(数据来自开票通知,使用内置占位符,无需映射),优先使用“单证模板”中最近导入的该类型模板,没有时使用 `src/Leiren.Erp.Api/templates/billing/` 下的内置模板(按 `订单流程涉及单据文件/出货后给供应商的开票通知和开票用购销合同.pdf` 的版式制作,开发库已导入)。预览测试选择一份开票通知作为测试数据。 +- 内置占位符:表头 `NoticeNo`、`NoticeDate`、`ExportInvoiceNo`、`ContractNo`、`SignedPlace`、`SignedDate`、`SupplierName/Contact/Phone/Fax/Address`、`InvoiceTitle*`、`MailingAddress`、`ContactName`、`Buyer*`、`Seller*`、合计 `TotalQuantity`、`TotalAmountIncludingTax`、`TotalAmountExcludingTax`、`TotalTaxAmount`、`TotalAmountInWords`(大写金额,如“陆万陆仟贰佰壹拾壹元贰角”)、`TotalAmountText`(千分位金额);明细 `LineNumber`、`ProductName`、`Specification`、`Quantity`、`Unit`、`TaxIncludedUnitPrice`、`TaxExcludingUnitPrice`、`AmountIncludingTax`、`AmountExcludingTax`、`TaxAmount`、`TaxRate`。表头占位符也可以放在明细行中(如每行重复的外销发票号)。 + +## 24. 单证模板编辑器 + +- 左侧“单证模板”页面列出全部已导入模板(每个模板的当前版本),顶部提供搜索、模板类型筛选和排序;按类型分组显示文件、版本、导入人、占位符数量和状态(已可用 / 待映射 N 项 / 待识别 N 项 / 已锁定)。 +- 模板类型(`GET /api/document-templates/kinds`):报关发票、报关装箱单、报关外销合同、报关单数据、客户 CI、客户 PL(数据来自出货批次,需要字段映射),采购合同(数据来自采购合同),开票通知、开票购销合同(数据来自开票通知);后三种使用内置占位符名,无需映射。导入时类型必选,服务端拒绝其他类型和没有 `{{...}}` 占位符的文件。 +- 导入出货批次类模板时可选“适用客户”(默认通用),客户专用模板在列表中显示客户名,生成单证时按批次客户自动勾选;新版本沿用原模板的客户。 +- “导入模板”上传 .xlsx;“新版本”为同一模板上传新文件,类型不变。出货批次类模板导入后直接打开字段映射。 +- “字段映射”为每个占位符选择业务字段(表头 / 明细 / 合计)。选了明细字段的占位符所在行按出货明细逐行复制;新版本自动带入上一版本同名占位符的映射,再按同名业务字段补全。已用于生成单证的版本映射锁定,只能上传新版本调整。 +- “预览测试”选择测试数据(出货批次或采购合同)后调用 `POST /api/document-templates/{versionId}/preview`,服务端按当前映射渲染(未映射的占位符保持原样),客户端用 ExcelRenderer 真实渲染显示,可另存为 xlsx;不保存任何数据。 +- 采购合同导出优先使用最近导入的采购合同模板,没有导入时才使用 `PurchaseContract:TemplatePath` 配置的模板文件。 +- 报关单证模板源自 `订单流程涉及单据文件/报关资料输入.xlsx` 的 4 个工作表,已拆成 4 个模板文件放在 `src/Leiren.Erp.Api/templates/customs/`:`报关装箱单.xlsx`、`报关发票.xlsx`、`报关单.xlsx`(每项 3 行:品名 / 申报要素 / 币制)、`报关外销合同.xlsx`。原表中的示例数据和跨表公式已替换为占位符,占位符名与业务字段同名,导入时选对应类型即可一一映射。开发库已导入这 4 个模板。 +- 报关相关业务字段:表头 `InvoiceNo`(发票编号,空则用出货批次号)、`CustomerAddress`、`OrderDate`、`ExportDate`、`DeclarationDate`、`TradeMode`、`ExemptionNature`、`CurrencyNameZh`;明细 `CustomsNameZh`、`CustomsNameEn`、`DeclarationElements`、`OriginCountry`、`DomesticSourcePlace`、`ExemptionInfo`、`LineCurrencyZh`。 + diff --git a/migration/README.md b/migration/README.md new file mode 100644 index 0000000..cf67968 --- /dev/null +++ b/migration/README.md @@ -0,0 +1,73 @@ +# ERP 数据迁移程序 + +## 当前状态 + +迁移程序只读取仓库中的 UTF-16 SQL 文件: + +```text +bak/ps_tr.sql +bak/ps_tr_mail.sql +bak/ps_tr_pic.sql +``` + +迁移程序直接解析 `CREATE TABLE` 和 `INSERT`。不恢复 `.bak`,不连接旧 SQL Server,也不把 `.bak` 作为迁移步骤。 + +## 目标运行方式 + +```text +UTF-16 SQL 文件 + | + v +.NET 11 Migration CLI + | + +--> SQLite 开发/验收数据库 + +--> PostgreSQL 生产数据库 + +--> legacy 原始区和正式业务表 + +--> migration_run / migration_error + +--> 脱敏迁移报告 +``` + +迁移程序和业务 API 使用 EF Core;SQL 文件使用流式解析。目标数据库使用 EF Core SQLite provider 或 PostgreSQL provider。 + +## 已实现命令(`src/Leiren.Erp.Migration`) + +```text +Leiren.Erp.Migration inspect --source-file bak/ps_tr.sql --output report.json [--staging-output staging.jsonl] +Leiren.Erp.Migration import --source-file bak/ps_tr.sql --dry-run --output report.json [--staging-output staging.jsonl] +Leiren.Erp.Migration import --source-dir bak --dry-run --output combined-report.json +Leiren.Erp.Migration inspect-all [--source-dir bak] [--output combined-report.json] [--staging-output staging.jsonl] +Leiren.Erp.Migration execute --source-dir bak --target-db erp.db [--batch-id ] [--output report.json] [--file-storage ] +Leiren.Erp.Migration execute --source-file bak/ps_tr.sql --target-db erp.db [--batch-id ] [--output report.json] [--file-storage ] +``` + +- 只接受 `ps_tr.sql`、`ps_tr_mail.sql`、`ps_tr_pic.sql` 三个文件名;`.bak` 明确拒绝。 +- 流式解析安全子集:`CREATE TABLE` 字段定义、`ALTER TABLE ... PRIMARY KEY`、`INSERT ... VALUES`(`NULL`、`N'...'`/普通字符串、数字、`0x...` 二进制、`CAST`/`CONVERT`)、`GO`、`SET`/`USE`。 +- 不在子集内的语句计入报告的 `unsupportedStatements`,解析失败的行计入 `parseErrors`(含源文件、表、行、列),都不静默丢弃或导入。 +- 二进制字面量不保留内容,只记录字节数和 SHA-256。 +- 每张源表在报告中均有 `readRows`(读取)、`successRows`(成功暂存)、`skippedRows`(同表同源主键重复而跳过)、`errorRows`(解析失败 + 未映射)、`mappedRows`、`unmappedRows`、`stagingOnlyRows` 和 `mappingStatus`。 +- dry-run(`inspect` / `import --dry-run`)从不打开目标数据库、不修改正式业务表;`--staging-output` 仅在显式指定时写 JSONL 暂存文件(源文件/表/主键或显式 `__row:<序号>` 回退键、源列、原始值、标准值)。 +- `execute` 是唯一写库命令:先把全部解析行写入 `legacy_source_row`(批次 `legacy_import_batch`、错误 `legacy_import_error`、映射 `legacy_id_map`,均为迁移专用暂存表),再按依赖顺序将已知表映射到正式表:`khxx -> Customer`、`yp_hh -> Product`、`order_main -> SalesOrder`、`order_hh -> SalesOrderLine`、`maker_order_main -> PurchaseContract`。 +- 无正式供应商主档实体,`gysxx` 供应商行只保留在 legacy 暂存区并逐行写入未映射报告(其名称仍会被解析到采购合同上);`maker_order_hh` 无正式合同明细实体、`invoice/invoice_detail` 无正式映射,同样逐行报告未映射,不静默丢弃。未文档化表只进 legacy 暂存区(`stagingOnlyRows`)。 +- 重复保护:批次键为显式 `--batch-id` 或三个源文件内容 SHA-256;同批次重复 `execute` 直接返回退出码 4 且不写任何数据。`legacy_source_row` 对 `(source_file, source_schema, source_table, source_key)` 全局唯一,跨批次重复行跳过;正式表按客户编码/产品货号/订单号/合同号及 `legacy_id_map` 查重,不重复创建。 +- 退出码:0 成功,1 I/O 失败,2 用法/源文件校验失败,3 有行解析失败,4 重复批次(未写入),5 有未映射行(详见报告与 `legacy_import_error`)。 + +## 历史产品图片(ps_tr_pic.sql,已核查并实现) + +核查证据(2026-11-14 实测 `bak/ps_tr_pic.sql`,UTF-16,约 7.5 MB): + +- 共定义 95 张表,但只有 7 张表有 INSERT:`DDLEvents`(66)、`DDLEvents_detail`(262)、`blob_hash`(17)、`clzb_pic`(8)、`html_attach_data`(11)、`relate_files_data`(13)、`yp_pic_hh`(5);其余 `*_pic` 表只有表结构、无数据行。 +- 各业务图片表自身的图片列在导出中均无真实字节:`yp_pic_hh.pic`、`clzb_pic.pic` 全部为 `NULL`,`html_attach_data.filedata`、`relate_files_data.file_image` 全部为 `0x`(空)。 +- 真实图片字节集中在 `blob_hash.hash_blob`:17 行、合计 1,830,748 字节,其中 6 行为 PNG(魔数 `89 50 4E 47`)、11 行为 JPEG(魔数 `FF D8 FF`);`blob_hash.file_type` 全为 `NULL`,格式只能按魔数识别。已逐行验证 `hash_value` 等于该行 `hash_blob` 的 SHA-1(大写十六进制),17/17 一致。 +- 产品图片关联:`yp_pic_hh.ypid` 对应产品主档 `yp_hh.ypid`(5 行的 ypid 均能在 `ps_tr.sql` 的 `yp_hh` 中找到);每行 `pic=NULL`,但 `hash_value` 全部能在 `blob_hash` 中命中(4 个不同哈希,其中 1 个被 2 个产品共用),均为 JPEG。因此产品图片**可以**从 SQL 导入,不是只有元数据。 + +`execute` 正式流程(批次内包含 `ps_tr_pic.sql` 时)在普通正式映射之后执行产品图片导入:按 `yp_pic_hh.ypid -> 已映射 Product`、`hash_value -> blob_hash.hash_blob` 恢复真实字节,经 `LocalFileStorage` 写入文件存储(`--file-storage` 指定根目录,未指定时为目标数据库同目录的 `storage/`),并创建 `FileAttachment(OwnerType=product, OwnerId=产品Id, Category=product-photo, UploadedBy=legacy-migration)`;同时在 `legacy_id_map` 记录 `ProductPhoto` 映射。暂存解析器仍只保留二进制长度/SHA-256,图片字节由导入阶段对 `ps_tr_pic.sql` 做第二遍定向提取,不进入暂存 JSON。 + +不静默丢失:报告顶层 `productImages{status,ypPicHhRows,blobHashRows,imported,skippedDuplicate,unmapped,evidence}` 与 `formalImport.byTable.yp_pic_hh` 给出计数;无法导入的行逐行写入 `legacy_import_error` 并进入未映射计数(退出码 5),错误码为 `PRODUCT_IMAGE_MISSING_YPID`、`PRODUCT_IMAGE_PRODUCT_UNMAPPED`、`PRODUCT_IMAGE_BLOB_NOT_FOUND`、`PRODUCT_IMAGE_EMPTY`、`PRODUCT_IMAGE_FORMAT_UNRECOGNIZED`(含前 12 字节十六进制证据)、`PRODUCT_IMAGE_WRITE_FAILED`。批次未包含 `ps_tr_pic.sql` 时 `productImages.status=source-file-not-in-batch`,不读取批次外文件。同一图片(同产品 + 同 SHA-256)重复执行不会重复建附件。其余图片表(如 `clzb_pic`)无正式业务主档映射,仍只进 legacy 暂存并计数,不臆造归属。 + +## 实现边界 + +- 使用流式读取解析 UTF-16 SQL 文件,不把全文件复制成多个内存副本(映射评估仅保留已知业务表的键集合与轻量行摘要)。 +- `execute` 目标库为 SQLite 文件(开发/验收);PostgreSQL 生产导入不在本命令内臆造连接方式。 +- 使用 `System.Text.Json` 保存旧表原始行(`payload_json`)及行内容 SHA-256(`source_hash`)。 +- 金额、重量、尺寸和数量使用 `decimal` 精确数值;超过正式表长度上限或引用缺失的行进入未映射报告,不截断、不臆造。 +- 附件/图片/邮件表只做 legacy 暂存与计数;产品图片例外,按上文在 `execute` 中经 `blob_hash` 恢复并导入为 `product-photo` 附件,其他图片/附件二进制内容不迁移(解析器只保留字节数与 SHA-256)。 diff --git a/src/Leiren.Erp.Api/AuthorizationEndpoints.cs b/src/Leiren.Erp.Api/AuthorizationEndpoints.cs new file mode 100644 index 0000000..66e533d --- /dev/null +++ b/src/Leiren.Erp.Api/AuthorizationEndpoints.cs @@ -0,0 +1,95 @@ +using System.Collections.Concurrent; +using Leiren.Erp.Application.Identity; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Microsoft.AspNetCore.Identity; + +namespace Leiren.Erp.Api; + +public static class AuthorizationEndpoints +{ + public static IEndpointRouteBuilder MapAuthorizationEndpoints( + this IEndpointRouteBuilder app, + ConcurrentDictionary sessions, + PasswordHasher passwordHasher) + { + var group = app.MapGroup("/api/admin"); + + // Every admin route requires admin:manage, checked against the database per request. + group.AddEndpointFilter(async (context, next) => + { + var denied = await BearerAuthorization.AuthorizeAsync( + context.HttpContext, sessions, "admin:manage", context.HttpContext.RequestAborted); + return denied ?? await next(context); + }); + + group.MapGet("/modules", (IdentityService service) => Results.Ok(service.ListModules())); + + group.MapGet("/permissions", (IdentityService service) => Results.Ok(service.ListPermissions())); + + group.MapGet("/roles", (IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListRolesAsync(ct)))); + + group.MapPost("/roles", (CreateRoleRequest request, IdentityService service, CancellationToken ct) => + Handle(async () => + { + var role = await service.CreateRoleAsync(request, ct); + return Results.Created($"/api/admin/roles/{role.Id}", role); + })); + + group.MapPut("/roles/{id:guid}/permissions", (Guid id, UpdateRolePermissionsRequest request, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateRolePermissionsAsync(id, request, ct)))); + + group.MapGet("/users", (int? page, int? pageSize, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListUsersAsync(page ?? 1, pageSize ?? 100, ct)))); + + group.MapPost("/users", (CreateUserRequest? request, IdentityService service, CancellationToken ct) => + Handle(async () => + { + if (request is null || string.IsNullOrWhiteSpace(request.Password)) + return Results.ValidationProblem(new Dictionary { ["password"] = ["密码不能为空。"] }); + // Hash here with the same hasher login uses; the service persists only the hash. + var placeholder = new AppUser { UserName = request.UserName?.Trim() ?? string.Empty, DisplayName = request.DisplayName?.Trim() ?? string.Empty, PasswordHash = string.Empty }; + var hash = passwordHasher.HashPassword(placeholder, request.Password); + var user = await service.CreateUserAsync(request, hash, ct); + return Results.Created($"/api/admin/users/{user.Id}", user); + })); + + group.MapGet("/users/{id:guid}", (Guid id, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetUserAsync(id, ct)))); + + group.MapPut("/users/{id:guid}/roles", (Guid id, AssignRolesRequest request, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AssignRolesAsync(id, request, ct)))); + + group.MapPut("/users/{id:guid}/modules", (Guid id, AssignModulesRequest request, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AssignModulesAsync(id, request, ct)))); + + group.MapPut("/users/{id:guid}/permissions", (Guid id, AssignPermissionsRequest request, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AssignPermissionsAsync(id, request, ct)))); + + group.MapPut("/users/{id:guid}/active", (Guid id, SetUserActiveRequest request, IdentityService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.SetUserActiveAsync(id, request.IsActive, ct)))); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (IdentityValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (IdentityNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (IdentityConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/BearerAuthorization.cs b/src/Leiren.Erp.Api/BearerAuthorization.cs new file mode 100644 index 0000000..9c3ba09 --- /dev/null +++ b/src/Leiren.Erp.Api/BearerAuthorization.cs @@ -0,0 +1,127 @@ +using System.Collections.Concurrent; +using Leiren.Erp.Application.Identity; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Api; + +/// +/// Server-side bearer authorization. Every protected request re-reads the user and +/// effective permissions from the database, so role/permission changes and user +/// deactivation take effect on the next request. +/// +public static class BearerAuthorization +{ + public static bool TryGetUserId(HttpContext context, ConcurrentDictionary sessions, out Guid userId) + { + userId = Guid.Empty; + if (!context.Request.Headers.TryGetValue("Authorization", out var authorization) || + !authorization.ToString().StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + var token = authorization.ToString()["Bearer ".Length..].Trim(); + return token.Length > 0 && sessions.TryGetValue(token, out userId); + } + + /// Returns null when authorized; otherwise the 401/403 result to return. + public static async Task AuthorizeAsync( + HttpContext context, + ConcurrentDictionary sessions, + string requiredPermission, + CancellationToken cancellationToken = default) + { + if (!TryGetUserId(context, sessions, out var userId)) + { + return Unauthorized(); + } + + var database = context.RequestServices.GetRequiredService(); + var user = await database.Users.AsNoTracking() + .SingleOrDefaultAsync(x => x.Id == userId, cancellationToken); + if (user is null) return Unauthorized(); + if (!user.IsActive) return Forbidden("用户已停用。"); + + var identity = context.RequestServices.GetRequiredService(); + return await identity.HasPermissionAsync(user.Id, requiredPermission, cancellationToken) + ? null + : Forbidden($"缺少权限:{requiredPermission}"); + } + + public static async Task GetCurrentUserAsync( + HttpContext context, + ConcurrentDictionary sessions, + CancellationToken cancellationToken = default) + { + if (!TryGetUserId(context, sessions, out var userId)) return null; + var database = context.RequestServices.GetRequiredService(); + var user = await database.Users.AsNoTracking() + .SingleOrDefaultAsync(x => x.Id == userId, cancellationToken); + return user is { IsActive: true } ? user : null; + } + + public static IResult Unauthorized() => Results.Problem( + title: "未登录", + detail: "缺少或无效的登录凭据。", + statusCode: StatusCodes.Status401Unauthorized); + + public static IResult Forbidden(string detail) => Results.Problem( + title: "无权限", + detail: detail, + statusCode: StatusCodes.Status403Forbidden); + + /// Permission required for a business route, or null when the route is not authorization-protected here. + public static string? RequiredPermissionFor(HttpRequest request) + { + var path = request.Path.Value ?? string.Empty; + var method = request.Method; + + string ActionFor(string module, params (string Suffix, string Action)[] special) + { + foreach (var (suffix, action) in special) + { + if (path.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) return $"{module}:{action}"; + } + return method switch + { + "GET" => $"{module}:view", + "DELETE" => $"{module}:delete", + _ => $"{module}:edit", + }; + } + + if (path.StartsWith("/api/dashboard", StringComparison.OrdinalIgnoreCase)) return "dashboard:view"; + if (path.StartsWith("/api/admin", StringComparison.OrdinalIgnoreCase)) return "admin:manage"; + if (path.StartsWith("/api/products", StringComparison.OrdinalIgnoreCase)) + return ActionFor("catalog", ("/publish", "publish"), ("/disable", "disable")); + if (path.StartsWith("/api/customers", StringComparison.OrdinalIgnoreCase)) return ActionFor("customers"); + if (path.StartsWith("/api/suppliers", StringComparison.OrdinalIgnoreCase)) return ActionFor("suppliers"); + if (path.StartsWith("/api/sales-orders", StringComparison.OrdinalIgnoreCase)) + return ActionFor("sales", ("/confirm", "confirm"), ("/cancel", "void")); + if (path.StartsWith("/api/purchase-tasks", StringComparison.OrdinalIgnoreCase) || + path.StartsWith("/api/purchase-contracts", StringComparison.OrdinalIgnoreCase) || + path.StartsWith("/api/purchases", StringComparison.OrdinalIgnoreCase)) + return ActionFor("purchase", ("/confirm", "confirm"), ("/void", "void"), ("/generate-from-sales-order", "generate"), ("/export", "export")); + if (path.StartsWith("/api/shipping", StringComparison.OrdinalIgnoreCase)) + return ActionFor("shipping", ("/confirm", "confirm"), ("/void", "void")); + if (path.StartsWith("/api/customs", StringComparison.OrdinalIgnoreCase)) + return ActionFor("customs", ("/confirm", "confirm")); + if (path.StartsWith("/api/billing", StringComparison.OrdinalIgnoreCase) || + path.StartsWith("/api/invoices", StringComparison.OrdinalIgnoreCase)) + return ActionFor("billing", ("/confirm", "confirm"), ("/generate-from-shipping-batch", "generate"), ("/hand-to-finance", "confirm"), ("/complete", "confirm"), ("/void", "delete")); + // Supplier payables belong to the billing/finance permission group; paying needs confirm rights. + if (path.StartsWith("/api/payables", StringComparison.OrdinalIgnoreCase)) + return ActionFor("billing", ("/pay", "confirm")); + if (path.StartsWith("/api/document-templates", StringComparison.OrdinalIgnoreCase)) + return path.Contains("/mapping", StringComparison.OrdinalIgnoreCase) || + path.EndsWith("/fields", StringComparison.OrdinalIgnoreCase) || + path.EndsWith("/validate", StringComparison.OrdinalIgnoreCase) + ? ActionFor("customs") + : ActionFor("files"); + if (path.StartsWith("/api/files", StringComparison.OrdinalIgnoreCase)) + return ActionFor("files", ("/download", "download")); + return null; + } +} diff --git a/src/Leiren.Erp.Api/BillingEndpoints.cs b/src/Leiren.Erp.Api/BillingEndpoints.cs new file mode 100644 index 0000000..33f9ae5 --- /dev/null +++ b/src/Leiren.Erp.Api/BillingEndpoints.cs @@ -0,0 +1,122 @@ +using Leiren.Erp.Application.Billing; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class BillingEndpoints +{ + public static IEndpointRouteBuilder MapBillingEndpoints(this IEndpointRouteBuilder app) + { + var notices = app.MapGroup("/api/billing/notices"); + + notices.MapGet("/", (Guid? shippingBatchId, Guid? purchaseContractId, Guid? supplierId, string? status, + string? search, int? page, int? pageSize, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListNoticesAsync( + shippingBatchId, purchaseContractId, supplierId, status, search, page ?? 1, pageSize ?? 50, ct)))); + + notices.MapGet("/{id:guid}", (Guid id, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetNoticeAsync(id, ct)))); + + notices.MapPost("/", (CreateSupplierInvoiceNoticeRequest request, BillingService service, CancellationToken ct) => + Handle(async () => + { + var created = await service.CreateNoticeAsync(request, ct); + return Results.Created($"/api/billing/notices/{created.Id}", created); + })); + + // One notice per supplier from a confirmed shipping batch. + notices.MapPost("/generate-from-shipping-batch", (GenerateBillingNoticesRequest request, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GenerateFromShippingBatchAsync(request, ct)))); + + notices.MapPut("/{id:guid}", (Guid id, UpdateSupplierInvoiceNoticeRequest request, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateNoticeAsync(id, request, ct)))); + + notices.MapPost("/{id:guid}/notify", (Guid id, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.NotifyAsync(id, ct)))); + + notices.MapPost("/{id:guid}/await-invoice", (Guid id, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AwaitInvoiceAsync(id, ct)))); + + notices.MapPost("/{id:guid}/void", (Guid id, VoidBillingRequest? request, BillingService service, CancellationToken ct) => + Handle(async () => + { + await service.VoidNoticeAsync(id, request, ct); + return Results.NoContent(); + })); + + notices.MapGet("/{id:guid}/contract", (Guid id, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetBillingContractAsync(id, ct)))); + + notices.MapPut("/{id:guid}/contract", (Guid id, UpdateSupplierBillingContractRequest request, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateBillingContractAsync(id, request, ct)))); + + // documentKind: SupplierInvoiceNotice (开票通知) or SupplierBillingContract (开票购销合同). + notices.MapGet("/{id:guid}/documents/{documentKind}", (Guid id, string documentKind, BillingDocumentExportService service, CancellationToken ct) => + Handle(async () => + { + var (bytes, fileName) = await service.RenderAsync(id, documentKind, ct); + return Results.File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); + })); + + // Batch level: split quantities between the batch's suppliers, then confirm all notices at once. + notices.MapPut("/shipping-batches/{batchId:guid}/allocation", (Guid batchId, ReallocateBillingRequest request, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ReallocateBatchAsync(batchId, request, ct)))); + notices.MapPost("/shipping-batches/{batchId:guid}/confirm", (Guid batchId, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ConfirmBatchAsync(batchId, ct)))); + + notices.MapPost("/{id:guid}/invoices", (Guid id, RegisterSupplierInvoiceRequest request, BillingService service, CancellationToken ct) => + Handle(async () => + { + var created = await service.RegisterInvoiceAsync(id, request, ct); + return Results.Created($"/api/billing/invoices/{created.Id}", created); + })); + + var invoices = app.MapGroup("/api/billing/invoices"); + + invoices.MapGet("/", (Guid? noticeId, string? status, string? search, int? page, int? pageSize, + BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListInvoicesAsync(noticeId, status, search, page ?? 1, pageSize ?? 50, ct)))); + + invoices.MapGet("/{id:guid}", (Guid id, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetInvoiceAsync(id, ct)))); + + invoices.MapPost("/{id:guid}/hand-to-finance", (Guid id, HandSupplierInvoiceToFinanceRequest? request, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.HandInvoiceToFinanceAsync(id, request, ct)))); + + invoices.MapPost("/{id:guid}/complete", (Guid id, BillingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.CompleteInvoiceAsync(id, ct)))); + + invoices.MapPost("/{id:guid}/void", (Guid id, VoidBillingRequest? request, BillingService service, CancellationToken ct) => + Handle(async () => + { + await service.VoidInvoiceAsync(id, request, ct); + return Results.NoContent(); + })); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (BillingValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (BillingNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (BillingConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/CatalogEndpoints.cs b/src/Leiren.Erp.Api/CatalogEndpoints.cs new file mode 100644 index 0000000..7b3a0a3 --- /dev/null +++ b/src/Leiren.Erp.Api/CatalogEndpoints.cs @@ -0,0 +1,141 @@ +using System.Collections.Concurrent; +using Leiren.Erp.Application.Catalog; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class CatalogEndpoints +{ + public static IEndpointRouteBuilder MapCatalogEndpoints( + this IEndpointRouteBuilder app, ConcurrentDictionary sessions) + { + var group = app.MapGroup("/api/products"); + + group.MapGet("/", (string? search, string? status, int? page, int? pageSize, ProductService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync(search, status, page ?? 1, pageSize ?? 50, ct)))); + + group.MapGet("/{id:guid}", (Guid id, ProductService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetAsync(id, ct)))); + + group.MapGet("/{id:guid}/history", (Guid id, ProductService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListHistoryAsync(id, ct)))); + + group.MapGet("/{id:guid}/completeness", (Guid id, ProductService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetCompletenessAsync(id, ct)))); + + group.MapPost("/drafts", (SaveProductDraftRequest request, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + var product = await service.CreateDraftAsync(request, ct, actor.UserId, actor.UserName); + return Results.Created($"/api/products/{product.Id}", product); + })); + + group.MapPut("/{id:guid}/draft", (Guid id, SaveProductDraftRequest request, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + return Results.Ok(await service.UpdateDraftAsync(id, request, ct, actor.UserId, actor.UserName)); + })); + + group.MapPost("/{id:guid}/publish", (Guid id, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + return Results.Ok(await service.PublishAsync(id, ct, actor.UserId, actor.UserName)); + })); + + group.MapPost("/{id:guid}/disable", (Guid id, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + return Results.Ok(await service.DisableAsync(id, ct, actor.UserId, actor.UserName)); + })); + + group.MapDelete("/{id:guid}", (Guid id, ProductService service, CancellationToken ct) => + Handle(async () => + { + await service.DeleteDraftAsync(id, ct); + return Results.NoContent(); + })); + + group.MapPost("/{id:guid}/parts", (Guid id, SaveProductPartRequest request, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + var part = await service.AddPartAsync(id, request, ct, actor.UserId, actor.UserName); + return Results.Created($"/api/products/{id}/parts/{part.Id}", part); + })); + + group.MapPut("/{id:guid}/parts/{partId:guid}", (Guid id, Guid partId, SaveProductPartRequest request, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + return Results.Ok(await service.UpdatePartAsync(id, partId, request, ct, actor.UserId, actor.UserName)); + })); + + group.MapDelete("/{id:guid}/parts/{partId:guid}", (Guid id, Guid partId, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + await service.DeletePartAsync(id, partId, ct, actor.UserId, actor.UserName); + return Results.NoContent(); + })); + + group.MapPost("/{id:guid}/quotes", (Guid id, CreateSupplierQuoteRequest request, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + var quote = await service.AddQuoteAsync(id, request, ct, actor.UserId, actor.UserName); + return Results.Created($"/api/products/{id}/quotes/{quote.Id}", quote); + })); + + group.MapPut("/{id:guid}/quotes/{quoteId:guid}", (Guid id, Guid quoteId, CreateSupplierQuoteRequest request, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + return Results.Ok(await service.UpdateQuoteAsync(id, quoteId, request, ct, actor.UserId, actor.UserName)); + })); + + group.MapDelete("/{id:guid}/quotes/{quoteId:guid}", (Guid id, Guid quoteId, ProductService service, HttpContext http, CancellationToken ct) => + Handle(async () => + { + var actor = await ActorAsync(http, sessions, ct); + await service.DeleteQuoteAsync(id, quoteId, ct, actor.UserId, actor.UserName); + return Results.NoContent(); + })); + + return app; + } + + private static async Task<(Guid? UserId, string? UserName)> ActorAsync( + HttpContext http, ConcurrentDictionary sessions, CancellationToken ct) + { + var user = await BearerAuthorization.GetCurrentUserAsync(http, sessions, ct); + return user is null ? (null, null) : (user.Id, $"{user.DisplayName} ({user.UserName})"); + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (CatalogValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (CatalogNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (CatalogConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/CiPlDocumentEndpoints.cs b/src/Leiren.Erp.Api/CiPlDocumentEndpoints.cs new file mode 100644 index 0000000..21a4c9b --- /dev/null +++ b/src/Leiren.Erp.Api/CiPlDocumentEndpoints.cs @@ -0,0 +1,52 @@ +using Leiren.Erp.Application.Customs; +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class CiPlDocumentEndpoints +{ + public static IEndpointRouteBuilder MapCiPlDocumentEndpoints(this IEndpointRouteBuilder app) + { + var documents = app.MapGroup("/api/shipping-batches/{shippingBatchId:guid}/documents"); + + // Generates one customs or customer document from a mapped template version. + documents.MapPost("/generate", (Guid shippingBatchId, GenerateCiPlDocumentRequest request, CiPlDocumentGenerationService service, CancellationToken ct) => + Handle(async () => + { + var result = await service.GenerateAsync(shippingBatchId, request, ct); + return Results.Created( + $"/api/shipping-batches/{shippingBatchId}/documents/{result.Document.Id}", result); + })); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (CustomsValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (DocumentTemplateValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (CustomsNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (CustomsConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/CustomsEndpoints.cs b/src/Leiren.Erp.Api/CustomsEndpoints.cs new file mode 100644 index 0000000..df2441b --- /dev/null +++ b/src/Leiren.Erp.Api/CustomsEndpoints.cs @@ -0,0 +1,94 @@ +using Leiren.Erp.Application.Customs; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class CustomsEndpoints +{ + public static IEndpointRouteBuilder MapCustomsEndpoints(this IEndpointRouteBuilder app) + { + var customs = app.MapGroup("/api/customs"); + + customs.MapGet("/", (string? search, string? status, Guid? shippingBatchId, int? page, int? pageSize, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync(search, status, shippingBatchId, page ?? 1, pageSize ?? 50, ct)))); + + customs.MapGet("/{id:guid}", (Guid id, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetAsync(id, ct)))); + + customs.MapPost("/", (CreateCustomsDeclarationRequest request, CustomsService service, CancellationToken ct) => + Handle(async () => + { + var declaration = await service.CreateFromShippingBatchAsync(request, ct); + return Results.Created($"/api/customs/{declaration.Id}", declaration); + })); + + customs.MapPut("/{id:guid}", (Guid id, UpdateCustomsDeclarationRequest request, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateAsync(id, request, ct)))); + + customs.MapPost("/{id:guid}/confirm", (Guid id, ConfirmCustomsDeclarationRequest? request, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ConfirmAsync(id, request, ct)))); + + customs.MapPost("/{id:guid}/void", (Guid id, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.VoidAsync(id, ct)))); + + customs.MapGet("/{id:guid}/documents", (Guid id, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListDocumentsForCustomsAsync(id, ct)))); + + customs.MapPost("/{id:guid}/documents", (Guid id, GenerateCustomsDocumentPackageRequest request, CustomsService service, CancellationToken ct) => + Handle(async () => + { + var package = await service.GenerateForCustomsAsync(id, request, ct); + return Results.Created($"/api/shipping-batches/{package.ShippingBatchId}/documents/{package.Id}", package); + })); + + var documents = app.MapGroup("/api/shipping-batches/{shippingBatchId:guid}/documents"); + + documents.MapGet("/", (Guid shippingBatchId, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListDocumentsAsync(shippingBatchId, ct)))); + + documents.MapGet("/{documentId:guid}", (Guid shippingBatchId, Guid documentId, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetDocumentAsync(shippingBatchId, documentId, ct)))); + + documents.MapPost("/", (Guid shippingBatchId, GenerateDocumentPackageRequest request, CustomsService service, CancellationToken ct) => + Handle(async () => + { + var package = await service.GenerateDocumentAsync(shippingBatchId, request, ct); + return Results.Created($"/api/shipping-batches/{shippingBatchId}/documents/{package.Id}", package); + })); + + documents.MapPost("/{documentId:guid}/confirm", (Guid shippingBatchId, Guid documentId, DocumentPackageActionRequest? request, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ConfirmDocumentAsync(shippingBatchId, documentId, request, ct)))); + + documents.MapPost("/{documentId:guid}/export", (Guid shippingBatchId, Guid documentId, DocumentPackageActionRequest? request, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ExportDocumentAsync(shippingBatchId, documentId, request, ct)))); + + documents.MapPost("/{documentId:guid}/void", (Guid shippingBatchId, Guid documentId, CustomsService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.VoidDocumentAsync(shippingBatchId, documentId, ct)))); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (CustomsValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (CustomsNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (CustomsConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/DashboardEndpoints.cs b/src/Leiren.Erp.Api/DashboardEndpoints.cs new file mode 100644 index 0000000..27cb691 --- /dev/null +++ b/src/Leiren.Erp.Api/DashboardEndpoints.cs @@ -0,0 +1,14 @@ +using Leiren.Erp.Application.Dashboard; + +namespace Leiren.Erp.Api; + +public static class DashboardEndpoints +{ + public static IEndpointRouteBuilder MapDashboardEndpoints(this IEndpointRouteBuilder app) + { + app.MapGet("/api/dashboard", async (DashboardService service, CancellationToken ct) => + Results.Ok(await service.GetSummaryAsync(ct))); + + return app; + } +} diff --git a/src/Leiren.Erp.Api/DocumentTemplateEndpoints.cs b/src/Leiren.Erp.Api/DocumentTemplateEndpoints.cs new file mode 100644 index 0000000..4d778ad --- /dev/null +++ b/src/Leiren.Erp.Api/DocumentTemplateEndpoints.cs @@ -0,0 +1,115 @@ +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Application.Files; + +namespace Leiren.Erp.Api; + +public static class DocumentTemplateEndpoints +{ + public static IEndpointRouteBuilder MapDocumentTemplateEndpoints(this IEndpointRouteBuilder app) + { + var templates = app.MapGroup("/api/document-templates"); + + // multipart/form-data: file (required, real .xlsx), name, documentKind, + // customerId, uploadedBy, uploadedByUserId. The workbook is scanned + // before it is stored through Files; a template without placeholders + // is rejected and nothing is persisted. + templates.MapPost("/upload", (HttpRequest request, DocumentTemplateService service, CancellationToken ct) => + Handle(async () => + { + var form = await ReadFormAsync(request, ct); + var file = RequireFile(form); + await using var content = file.OpenReadStream(); + var created = await service.UploadAsync( + content, file.FileName, file.ContentType, + new DocumentTemplateUploadOptions( + FormValue(form, "name"), + FormValue(form, "documentKind"), + ParseGuid(FormValue(form, "customerId"), "customerId"), + FormValue(form, "uploadedBy"), + ParseGuid(FormValue(form, "uploadedByUserId"), "uploadedByUserId")), ct); + return Results.Created($"/api/document-templates/{created.SourceFileId}/scan", created); + })).DisableAntiforgery(); + + templates.MapPost("/{fileId:guid}/versions", (Guid fileId, HttpRequest request, DocumentTemplateService service, CancellationToken ct) => + Handle(async () => + { + var form = await ReadFormAsync(request, ct); + var file = RequireFile(form); + await using var content = file.OpenReadStream(); + var created = await service.UploadNewVersionAsync( + fileId, content, file.FileName, file.ContentType, + new DocumentTemplateUploadOptions( + FormValue(form, "name"), + FormValue(form, "documentKind"), + ParseGuid(FormValue(form, "customerId"), "customerId"), + FormValue(form, "uploadedBy"), + ParseGuid(FormValue(form, "uploadedByUserId"), "uploadedByUserId")), ct); + return Results.Created($"/api/document-templates/{created.SourceFileId}/scan", created); + })).DisableAntiforgery(); + + templates.MapGet("/{fileId:guid}/scan", (Guid fileId, DocumentTemplateService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ScanStoredAsync(fileId, ct)))); + + return app; + } + + private static async Task ReadFormAsync(HttpRequest request, CancellationToken ct) + { + if (!request.HasFormContentType) + throw new DocumentTemplateValidationException("file", "上传必须使用 multipart/form-data。"); + return await request.ReadFormAsync(ct); + } + + private static IFormFile RequireFile(IFormCollection form) + { + var file = form.Files.GetFile("file") ?? form.Files.FirstOrDefault(); + if (file is null || file.Length == 0 && string.IsNullOrWhiteSpace(file.FileName)) + throw new DocumentTemplateValidationException("file", "请选择要上传的 .xlsx 模板文件。"); + return file; + } + + private static string? FormValue(IFormCollection form, string key) + => form.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value.ToString()) + ? value.ToString().Trim() + : null; + + private static Guid? ParseGuid(string? value, string field) + { + if (string.IsNullOrWhiteSpace(value)) return null; + if (!Guid.TryParse(value, out var parsed) || parsed == Guid.Empty) + throw new DocumentTemplateValidationException(field, "标识无效。"); + return parsed; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (DocumentTemplateValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (FilesValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (FilesNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (FilesConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidDataException ex) + { + return Results.Problem(title: "文件无效", detail: ex.Message, statusCode: StatusCodes.Status413PayloadTooLarge); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/DocumentTemplateMappingEndpoints.cs b/src/Leiren.Erp.Api/DocumentTemplateMappingEndpoints.cs new file mode 100644 index 0000000..907f259 --- /dev/null +++ b/src/Leiren.Erp.Api/DocumentTemplateMappingEndpoints.cs @@ -0,0 +1,104 @@ +using Leiren.Erp.Application.Customs; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +/// +/// Versioned placeholder-to-business-field mapping CRUD for scanned XLSX +/// document templates. {templateVersionId} is the immutable template +/// version id (scanned template file version) from the template upload/scan +/// endpoints. Once a document package is generated from a version, every +/// mutation of its mappings is refused (409); upload a new template version +/// to change mappings. +/// +public static class DocumentTemplateMappingEndpoints +{ + public static IEndpointRouteBuilder MapDocumentTemplateMappingEndpoints(this IEndpointRouteBuilder app) + { + var templates = app.MapGroup("/api/document-templates"); + + templates.MapGet("/", (DocumentTemplateCatalogService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync(ct)))); + + templates.MapGet("/kinds", (DocumentTemplateCatalogService service) => + Handle(() => Task.FromResult(Results.Ok(service.ListKinds())))); + + // Renders the template against chosen test data; nothing is stored. + templates.MapPost("/{templateVersionId:guid}/preview", (Guid templateVersionId, PreviewDocumentTemplateRequest request, DocumentTemplateCatalogService service, CancellationToken ct) => + Handle(async () => + { + var (bytes, fileName) = await service.PreviewAsync(templateVersionId, request, ct); + return Results.File(bytes, CiPlDocumentGenerationService.ContentType, fileName); + })); + + templates.MapGet("/fields", (DocumentTemplateMappingService service) => + Handle(() => Task.FromResult(Results.Ok(service.ListFields())))); + + templates.MapGet("/mapping-profiles", (Guid? templateId, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListProfilesAsync(templateId, ct)))); + + templates.MapPost("/{templateVersionId:guid}/mapping-profile", (Guid templateVersionId, CreateDocumentTemplateMappingProfileRequest request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => + { + var profile = await service.CreateProfileAsync(templateVersionId, request, ct); + return Results.Created($"/api/document-templates/{templateVersionId}/mapping-profile", profile); + })); + + templates.MapGet("/{templateVersionId:guid}/mapping-profile", (Guid templateVersionId, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetProfileAsync(templateVersionId, ct)))); + + templates.MapPut("/{templateVersionId:guid}/mapping-profile", (Guid templateVersionId, UpdateDocumentTemplateMappingProfileRequest request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateProfileAsync(templateVersionId, request, ct)))); + + templates.MapDelete("/{templateVersionId:guid}/mapping-profile", (Guid templateVersionId, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => + { + await service.DeleteProfileAsync(templateVersionId, ct); + return Results.NoContent(); + })); + + templates.MapPost("/{templateVersionId:guid}/mappings", (Guid templateVersionId, SaveDocumentTemplateFieldMappingRequest request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AddMappingAsync(templateVersionId, request, ct)))); + + templates.MapPut("/{templateVersionId:guid}/mappings", (Guid templateVersionId, ReplaceDocumentTemplateFieldMappingsRequest request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ReplaceMappingsAsync(templateVersionId, request, ct)))); + + templates.MapPost("/{templateVersionId:guid}/mappings/copy-from", (Guid templateVersionId, CopyDocumentTemplateMappingsRequest request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.CopyMappingsAsync(templateVersionId, request, ct)))); + + templates.MapPut("/{templateVersionId:guid}/mappings/{mappingId:guid}", (Guid templateVersionId, Guid mappingId, SaveDocumentTemplateFieldMappingRequest request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateMappingAsync(templateVersionId, mappingId, request, ct)))); + + templates.MapDelete("/{templateVersionId:guid}/mappings/{mappingId:guid}", (Guid templateVersionId, Guid mappingId, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.DeleteMappingAsync(templateVersionId, mappingId, ct)))); + + templates.MapPost("/{templateVersionId:guid}/validate", (Guid templateVersionId, ValidateDocumentTemplateRequest? request, DocumentTemplateMappingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ValidateAsync(templateVersionId, request?.Placeholders, ct)))); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (CustomsValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (CustomsNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (CustomsConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/FileEndpoints.cs b/src/Leiren.Erp.Api/FileEndpoints.cs new file mode 100644 index 0000000..6ed3e03 --- /dev/null +++ b/src/Leiren.Erp.Api/FileEndpoints.cs @@ -0,0 +1,129 @@ +using Leiren.Erp.Application.Files; + +namespace Leiren.Erp.Api; + +public static class FileEndpoints +{ + public static IEndpointRouteBuilder MapFileEndpoints(this IEndpointRouteBuilder app) + { + var group = app.MapGroup("/api/files"); + + group.MapGet("/", (string? ownerType, Guid? ownerId, string? category, string? search, + bool? currentOnly, int? page, int? pageSize, FileService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync( + ownerType, ownerId, category, search, currentOnly ?? false, page ?? 1, pageSize ?? 50, ct)))); + + group.MapGet("/{id:guid}", (Guid id, FileService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetAsync(id, ct)))); + + group.MapGet("/{id:guid}/versions", (Guid id, FileService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListVersionsAsync(id, ct)))); + + group.MapGet("/{id:guid}/download", (Guid id, FileService service, CancellationToken ct) => + Handle(async () => + { + var download = await service.OpenDownloadAsync(id, ct); + // Results.File owns and disposes the stream. + return Results.File(download.Content, download.File.ContentType, + download.File.OriginalFileName, enableRangeProcessing: true); + })); + + group.MapPost("/", (HttpRequest request, FileService service, CancellationToken ct) => + Handle(async () => + { + var form = await ReadFormAsync(request, ct); + var file = RequireFile(form); + Guid? uploadedByUserId = Guid.TryParse(FormValue(form, "uploadedByUserId"), out var parsed) ? parsed : null; + await using var content = file.OpenReadStream(); + var created = await service.UploadAsync(new UploadFileCommand( + FormValue(form, "ownerType"), + ParseGuid(FormValue(form, "ownerId"), "ownerId"), + FormValue(form, "category"), + FormValue(form, "description"), + file.FileName, + file.ContentType, + content, + uploadedByUserId, + FormValue(form, "uploadedBy")), ct); + return Results.Created($"/api/files/{created.Id}", created); + })).DisableAntiforgery(); + + group.MapPost("/{id:guid}/versions", (Guid id, HttpRequest request, FileService service, CancellationToken ct) => + Handle(async () => + { + var form = await ReadFormAsync(request, ct); + var file = RequireFile(form); + Guid? uploadedByUserId = Guid.TryParse(FormValue(form, "uploadedByUserId"), out var parsed) ? parsed : null; + await using var content = file.OpenReadStream(); + var created = await service.UploadNewVersionAsync( + id, content, file.FileName, file.ContentType, + FormValue(form, "category"), FormValue(form, "description"), + uploadedByUserId, FormValue(form, "uploadedBy"), ct); + return Results.Created($"/api/files/{created.Id}", created); + })).DisableAntiforgery(); + + group.MapDelete("/{id:guid}", (Guid id, FileService service, CancellationToken ct) => + Handle(async () => + { + await service.DeleteAsync(id, ct); + return Results.NoContent(); + })); + + return app; + } + + private static async Task ReadFormAsync(HttpRequest request, CancellationToken ct) + { + if (!request.HasFormContentType) + throw new FilesValidationException("file", "上传必须使用 multipart/form-data。"); + return await request.ReadFormAsync(ct); + } + + private static IFormFile RequireFile(IFormCollection form) + { + var file = form.Files.GetFile("file") ?? form.Files.FirstOrDefault(); + if (file is null || file.Length == 0 && string.IsNullOrWhiteSpace(file.FileName)) + throw new FilesValidationException("file", "请选择要上传的文件。"); + return file; + } + + private static string? FormValue(IFormCollection form, string key) + => form.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value.ToString()) + ? value.ToString() + : null; + + private static Guid ParseGuid(string? value, string field) + { + if (!Guid.TryParse(value, out var parsed) || parsed == Guid.Empty) + throw new FilesValidationException(field, "所属业务对象标识无效。"); + return parsed; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (FilesValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (FilesNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (FilesConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidDataException ex) + { + return Results.Problem(title: "文件无效", detail: ex.Message, statusCode: StatusCodes.Status413PayloadTooLarge); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/FinanceEndpoints.cs b/src/Leiren.Erp.Api/FinanceEndpoints.cs new file mode 100644 index 0000000..338e6c3 --- /dev/null +++ b/src/Leiren.Erp.Api/FinanceEndpoints.cs @@ -0,0 +1,40 @@ +using Leiren.Erp.Application.Finance; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class FinanceEndpoints +{ + public static IEndpointRouteBuilder MapFinanceEndpoints(this IEndpointRouteBuilder app) + { + var payables = app.MapGroup("/api/payables"); + + payables.MapGet("/", (PayableService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync(ct)))); + + payables.MapPost("/{id:guid}/pay", (Guid id, PaySupplierPayableRequest request, PayableService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.PayAsync(id, request, ct)))); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (FinanceValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (FinanceNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (FinanceConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/HealthEndpoints.cs b/src/Leiren.Erp.Api/HealthEndpoints.cs new file mode 100644 index 0000000..76d0221 --- /dev/null +++ b/src/Leiren.Erp.Api/HealthEndpoints.cs @@ -0,0 +1,129 @@ +using System.Diagnostics; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Api; + +public sealed record HealthCheckResult(string Name, string Status, long DurationMs, string? Description); + +public sealed record HealthReport(string Status, string Provider, DateTimeOffset CheckedAtUtc, IReadOnlyList Checks); + +/// +/// Real liveness/readiness probes. +/// /health/live only proves the process responds. +/// /health and /health/ready open a database connection and probe that the +/// configured file-storage root exists and is writable; any failed check +/// yields 503 with per-check detail (no connection strings, passwords or +/// server paths are exposed). +/// +public static class HealthEndpoints +{ + private static readonly TimeSpan DefaultDatabaseTimeout = TimeSpan.FromSeconds(5); + + public static IEndpointRouteBuilder MapErpHealthEndpoints(this IEndpointRouteBuilder app) + { + app.MapGet("/health/live", () => Results.Ok(new + { + status = "ok", + checkedAtUtc = DateTimeOffset.UtcNow, + })); + + app.MapGet("/health", RunReadinessAsync); + app.MapGet("/health/ready", RunReadinessAsync); + return app; + } + + private static async Task RunReadinessAsync(HttpContext context, ErpDbContext database) + { + var configuration = context.RequestServices.GetRequiredService(); + var timeout = DefaultDatabaseTimeout; + if (TimeSpan.TryParse(configuration["HealthChecks:DatabaseTimeout"], out var configured) && configured > TimeSpan.Zero) + { + timeout = configured; + } + + var checks = new List + { + await CheckDatabaseAsync(database, timeout, context.RequestAborted), + CheckFileStorage(context.RequestServices.GetRequiredService()), + }; + + var healthy = checks.All(x => x.Status == "healthy"); + var provider = database.Database.ProviderName ?? "unknown"; + var report = new HealthReport( + healthy ? "ok" : "unhealthy", + provider, + DateTimeOffset.UtcNow, + checks); + return Results.Json(report, statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable); + } + + private static async Task CheckDatabaseAsync( + ErpDbContext database, TimeSpan timeout, CancellationToken requestAborted) + { + var stopwatch = Stopwatch.StartNew(); + try + { + using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(requestAborted); + timeoutSource.CancelAfter(timeout); + var canConnect = await database.Database.CanConnectAsync(timeoutSource.Token); + stopwatch.Stop(); + return canConnect + ? new HealthCheckResult("database", "healthy", stopwatch.ElapsedMilliseconds, "数据库连接可用。") + : new HealthCheckResult("database", "unhealthy", stopwatch.ElapsedMilliseconds, "数据库连接不可用。"); + } + catch (OperationCanceledException) when (!requestAborted.IsCancellationRequested) + { + stopwatch.Stop(); + return new HealthCheckResult("database", "unhealthy", stopwatch.ElapsedMilliseconds, + $"数据库连接在 {timeout.TotalSeconds:0} 秒内未完成。"); + } + catch (Exception ex) + { + stopwatch.Stop(); + // Exception type only: messages may contain hosts or credentials. + return new HealthCheckResult("database", "unhealthy", stopwatch.ElapsedMilliseconds, + $"数据库连接失败({ex.GetType().Name})。"); + } + } + + private static HealthCheckResult CheckFileStorage(FileStorageOptions options) + { + var stopwatch = Stopwatch.StartNew(); + string? probePath = null; + try + { + if (string.IsNullOrWhiteSpace(options.RootPath) || !Directory.Exists(options.RootPath)) + { + stopwatch.Stop(); + return new HealthCheckResult("fileStorage", "unhealthy", stopwatch.ElapsedMilliseconds, "文件存储根目录不存在。"); + } + + probePath = Path.Combine(options.RootPath, ".health-probe-" + Guid.NewGuid().ToString("N")); + using (var stream = new FileStream(probePath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + stream.WriteByte(0); + stream.Flush(); + } + + File.Delete(probePath); + probePath = null; + stopwatch.Stop(); + return new HealthCheckResult("fileStorage", "healthy", stopwatch.ElapsedMilliseconds, "文件存储根目录可写。"); + } + catch (Exception ex) + { + stopwatch.Stop(); + return new HealthCheckResult("fileStorage", "unhealthy", stopwatch.ElapsedMilliseconds, + $"文件存储根目录不可写({ex.GetType().Name})。"); + } + finally + { + if (probePath is not null) + { + try { File.Delete(probePath); } catch { /* probe cleanup is best effort */ } + } + } + } +} diff --git a/src/Leiren.Erp.Api/Leiren.Erp.Api.csproj b/src/Leiren.Erp.Api/Leiren.Erp.Api.csproj new file mode 100644 index 0000000..fd2bcce --- /dev/null +++ b/src/Leiren.Erp.Api/Leiren.Erp.Api.csproj @@ -0,0 +1,28 @@ + + + + net11.0 + enable + enable + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + + + + + diff --git a/src/Leiren.Erp.Api/Leiren.Erp.Api.http b/src/Leiren.Erp.Api/Leiren.Erp.Api.http new file mode 100644 index 0000000..5c3931c --- /dev/null +++ b/src/Leiren.Erp.Api/Leiren.Erp.Api.http @@ -0,0 +1,54 @@ +@Leiren.Erp.Api_HostAddress = http://localhost:5118 + +GET {{Leiren.Erp.Api_HostAddress}}/health +Accept: application/json + +### + +# Only succeeds while no user exists. +POST {{Leiren.Erp.Api_HostAddress}}/api/auth/bootstrap +Content-Type: application/json + +{ + "userName": "admin", + "displayName": "管理员", + "password": "change-me" +} + +### + +POST {{Leiren.Erp.Api_HostAddress}}/api/auth/login +Content-Type: application/json + +{ + "userName": "admin", + "password": "change-me" +} + +### + +# Replace with the accessToken returned by login. +GET {{Leiren.Erp.Api_HostAddress}}/api/auth/me +Authorization: Bearer +Accept: application/json + +### + +POST {{Leiren.Erp.Api_HostAddress}}/api/products/drafts +Content-Type: application/json + +{ + "internalSku": "P-001", + "nameZh": "示例产品", + "nameEn": "Example Product", + "category": "玩具", + "productType": "Finished", + "unit": "PCS", + "packingRate": 12, + "hsCode": "950300" +} + +### + +GET {{Leiren.Erp.Api_HostAddress}}/api/products?status=Draft +Accept: application/json diff --git a/src/Leiren.Erp.Api/MasterDataEndpoints.cs b/src/Leiren.Erp.Api/MasterDataEndpoints.cs new file mode 100644 index 0000000..8787392 --- /dev/null +++ b/src/Leiren.Erp.Api/MasterDataEndpoints.cs @@ -0,0 +1,64 @@ +using Leiren.Erp.Application.MasterData; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class MasterDataEndpoints +{ + public static IEndpointRouteBuilder MapMasterDataEndpoints(this IEndpointRouteBuilder app) + { + var suppliers = app.MapGroup("/api/suppliers"); + + suppliers.MapGet("/", (string? search, bool? isActive, int? page, int? pageSize, SupplierService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync(search, isActive, page ?? 1, pageSize ?? 50, ct)))); + + suppliers.MapGet("/{id:guid}", (Guid id, SupplierService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetAsync(id, ct)))); + + suppliers.MapPost("/", (SaveSupplierRequest request, SupplierService service, CancellationToken ct) => + Handle(async () => + { + var supplier = await service.CreateAsync(request, ct); + return Results.Created($"/api/suppliers/{supplier.Id}", supplier); + })); + + suppliers.MapPut("/{id:guid}", (Guid id, SaveSupplierRequest request, SupplierService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateAsync(id, request, ct)))); + + suppliers.MapPost("/{id:guid}/deactivate", (Guid id, SupplierService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.DeactivateAsync(id, ct)))); + + suppliers.MapDelete("/{id:guid}", (Guid id, SupplierService service, CancellationToken ct) => + Handle(async () => + { + await service.DeleteAsync(id, ct); + return Results.NoContent(); + })); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (MasterDataValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (MasterDataNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (MasterDataConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/Program.cs b/src/Leiren.Erp.Api/Program.cs new file mode 100644 index 0000000..0bc4275 --- /dev/null +++ b/src/Leiren.Erp.Api/Program.cs @@ -0,0 +1,398 @@ +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text; +using Leiren.Erp.Api; +using Leiren.Erp.Application.Billing; +using Leiren.Erp.Application.Catalog; +using Leiren.Erp.Application.Customs; +using Leiren.Erp.Application.Dashboard; +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Application.Finance; +using Leiren.Erp.Application.Identity; +using Leiren.Erp.Application.MasterData; +using Leiren.Erp.Application.Purchasing; +using Leiren.Erp.Application.Sales; +using Leiren.Erp.Application.Shipping; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Infrastructure.Files; +using Leiren.Erp.Infrastructure.Persistence; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; + +var builder = WebApplication.CreateBuilder(args); + + +// Database provider is selected by configuration: Sqlite (development/local +// acceptance, the default) or PostgreSql (production). Unknown providers and +// malformed PostgreSQL connection strings fail startup explicitly. +var database = ErpDatabaseConfiguration.Resolve( + builder.Configuration["Database:Provider"], + builder.Configuration.GetConnectionString("Default"), + builder.Environment.ContentRootPath); + +builder.Services.AddProblemDetails(); +builder.Services.AddErpDbContext(database); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(sp => sp.GetRequiredService()); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +// File content lives on the server filesystem under FileStorage:RootPath +// (relative to the content root); the database stores only metadata. +var fileStorageOptions = new FileStorageOptions(); +builder.Configuration.GetSection("FileStorage").Bind(fileStorageOptions); +if (!Path.IsPathFullyQualified(fileStorageOptions.RootPath)) +{ + fileStorageOptions.RootPath = Path.GetFullPath( + Path.Combine(builder.Environment.ContentRootPath, fileStorageOptions.RootPath)); +} +Directory.CreateDirectory(fileStorageOptions.RootPath); +builder.Services.AddSingleton(fileStorageOptions); + +// Purchase-contract exports render the contract snapshot into this XLSX +// template. A missing file fails the export with an explicit message. +var contractTemplatePath = builder.Configuration["PurchaseContract:TemplatePath"]; +if (string.IsNullOrWhiteSpace(contractTemplatePath)) + contractTemplatePath = Path.Combine("templates", "purchase-contract.xlsx"); +if (!Path.IsPathFullyQualified(contractTemplatePath)) +{ + contractTemplatePath = Path.GetFullPath( + Path.Combine(builder.Environment.ContentRootPath, contractTemplatePath)); +} +builder.Services.AddSingleton(new PurchaseContractTemplateOptions(contractTemplatePath)); +// Built-in 开票通知 / 开票购销合同 templates; an imported template of the same type wins. +string ContentPath(string relative) => Path.GetFullPath(Path.Combine(builder.Environment.ContentRootPath, relative)); +builder.Services.AddSingleton(new BillingTemplateOptions( + ContentPath(Path.Combine("templates", "billing", "开票通知.xlsx")), + ContentPath(Path.Combine("templates", "billing", "开票购销合同.xlsx")))); +builder.Services.AddScoped(); +builder.Services.AddSingleton(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddOpenApi(); + +var app = builder.Build(); + +app.UseExceptionHandler(); +app.UseStatusCodePages(); + +using (var scope = app.Services.CreateScope()) +{ + var dbContext = scope.ServiceProvider.GetRequiredService(); + // This repository has no EF Core migrations yet, so EnsureCreated creates the + // development schema. Once a first migration is added, Migrate takes over. + if (dbContext.Database.GetMigrations().Any()) + { + await dbContext.Database.MigrateAsync(); + } + else + { + await dbContext.Database.EnsureCreatedAsync(); + } + await IdentitySchemaInitializer.EnsureCreatedAsync(dbContext); + await RefreshSessionSchemaInitializer.EnsureCreatedAsync(dbContext); + await SupplierPayableSchemaInitializer.EnsureCreatedAsync(dbContext); + await CustomsSchemaInitializer.EnsureCreatedAsync(dbContext); + // Contracts confirmed before payables existed still owe their suppliers. + await scope.ServiceProvider.GetRequiredService().BackfillAsync(); + var identityService = scope.ServiceProvider.GetRequiredService(); + var firstUser = await dbContext.Users.OrderBy(x => x.Id).FirstOrDefaultAsync(); + var adminRole = await dbContext.Roles.SingleOrDefaultAsync(x => x.Code == "admin"); + if (firstUser is not null && adminRole is not null && + !await dbContext.UserRoles.AnyAsync(x => x.UserId == firstUser.Id)) + { + dbContext.UserRoles.Add(new UserRole { UserId = firstUser.Id, RoleId = adminRole.Id }); + await dbContext.SaveChangesAsync(); + } +} + +app.Logger.LogInformation("Database ready: {DatabaseTarget}", database.DisplayTarget); + +if (app.Environment.IsDevelopment()) +{ + app.MapOpenApi(); +} + +var passwordHasher = new PasswordHasher(); +var sessions = new ConcurrentDictionary(StringComparer.Ordinal); + +// Access tokens stay in the in-memory session dictionary (existing behavior). +// Refresh tokens are random, persisted only as SHA-256 hashes, and rotated on +// every refresh so a used refresh token can never be replayed. +Func createAccessToken = userId => +{ + var accessToken = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); + sessions[accessToken] = userId; + return accessToken; +}; +Func hashRefreshToken = static token => + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token))); +Func createRefreshSession = userId => +{ + var refreshToken = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); + var now = DateTimeOffset.UtcNow; + var session = new RefreshSession + { + UserId = userId, + TokenHash = hashRefreshToken(refreshToken), + CreatedAt = now, + ExpiresAt = now.AddDays(30) + }; + return (refreshToken, session); +}; + +app.MapErpHealthEndpoints(); + +// Server-side authorization for business routes: 401 without a valid bearer +// token, 403 when the user's effective permissions do not include the route's +// required permission. Permissions are re-read from the database per request. +app.Use(async (context, next) => +{ + var required = BearerAuthorization.RequiredPermissionFor(context.Request); + if (required is null) + { + await next(); + return; + } + + var denied = await BearerAuthorization.AuthorizeAsync(context, sessions, required, context.RequestAborted); + if (denied is not null) + { + await denied.ExecuteAsync(context); + return; + } + + await next(); +}); +app.MapAuthorizationEndpoints(sessions, passwordHasher); +app.MapCatalogEndpoints(sessions); +app.MapSalesOrderEndpoints(); +app.MapSalesOrderImportEndpoints(); +app.MapPurchasingEndpoints(); +app.MapShippingEndpoints(); +app.MapFinanceEndpoints(); +app.MapBillingEndpoints(); +app.MapFileEndpoints(); +app.MapCustomsEndpoints(); +app.MapDocumentTemplateEndpoints(); +app.MapDocumentTemplateMappingEndpoints(); +app.MapCiPlDocumentEndpoints(); +app.MapMasterDataEndpoints(); +app.MapDashboardEndpoints(); + +app.MapPost("/api/auth/bootstrap", async (BootstrapRequest? request, ErpDbContext database, IdentityService identity, CancellationToken cancellationToken) => +{ + if (request is null || + string.IsNullOrWhiteSpace(request.UserName) || + string.IsNullOrWhiteSpace(request.DisplayName) || + string.IsNullOrWhiteSpace(request.Password)) + { + return Results.ValidationProblem(new Dictionary + { + ["user"] = ["用户名、显示名称和密码均不能为空。"] + }); + } + + if (await database.Users.AnyAsync(cancellationToken)) + { + return Results.Problem( + title: "初始化已完成", + detail: "系统已经存在用户,不能重复初始化。", + statusCode: StatusCodes.Status409Conflict); + } + + var user = new AppUser + { + UserName = request.UserName.Trim(), + DisplayName = request.DisplayName.Trim(), + PasswordHash = string.Empty + }; + user.PasswordHash = passwordHasher.HashPassword(user, request.Password); + + database.Users.Add(user); + try + { + await database.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + return Results.Problem( + title: "初始化已完成", + detail: "系统已经存在用户,不能重复初始化。", + statusCode: StatusCodes.Status409Conflict); + } + + await identity.EnsureAuthorizationCatalogAsync(cancellationToken); + await identity.AssignRoleToUserAsync(user.Id, "admin", cancellationToken); + return Results.Created($"/api/auth/users/{user.Id}", new { user.Id, user.UserName, user.DisplayName, Roles = new[] { "admin" } }); +}); + +app.MapPost("/api/auth/login", async (LoginRequest? request, ErpDbContext database, CancellationToken cancellationToken) => +{ + if (request is null || + string.IsNullOrWhiteSpace(request.UserName) || + string.IsNullOrWhiteSpace(request.Password)) + { + return Results.ValidationProblem(new Dictionary + { + ["credentials"] = ["用户名和密码均不能为空。"] + }); + } + + var user = await database.Users.SingleOrDefaultAsync( + x => x.UserName == request.UserName.Trim(), cancellationToken); + + var passwordValid = false; + if (user is not null) + { + try + { + passwordValid = passwordHasher.VerifyHashedPassword(user, user.PasswordHash, request.Password) + is PasswordVerificationResult.Success or PasswordVerificationResult.SuccessRehashNeeded; + } + catch (FormatException) + { + passwordValid = false; + } + } + + if (user is null || !passwordValid) + { + return Results.Problem( + title: "登录失败", + detail: "用户名或密码不正确。", + statusCode: StatusCodes.Status401Unauthorized); + } + + + if (!user.IsActive) + { + return Results.Problem( + title: "用户已停用", + detail: "该用户已被停用,不能登录。", + statusCode: StatusCodes.Status403Forbidden); + } + var accessToken = createAccessToken(user.Id); + var (refreshToken, refreshSession) = createRefreshSession(user.Id); + database.RefreshSessions.Add(refreshSession); + await database.SaveChangesAsync(cancellationToken); + return Results.Ok(new AuthResponse(user.Id, user.UserName, user.DisplayName, accessToken, refreshToken)); +}); + +app.MapPost("/api/auth/refresh", async (RefreshTokenRequest? request, ErpDbContext database, CancellationToken cancellationToken) => +{ + if (request is null || string.IsNullOrWhiteSpace(request.RefreshToken)) + { + return Results.ValidationProblem(new Dictionary + { + ["refreshToken"] = ["刷新凭据不能为空。"] + }); + } + + static IResult InvalidRefresh() => Results.Problem( + title: "刷新失败", + detail: "刷新凭据无效或已过期,请重新登录。", + statusCode: StatusCodes.Status401Unauthorized); + + var tokenHash = hashRefreshToken(request.RefreshToken.Trim()); + var session = await database.RefreshSessions.SingleOrDefaultAsync( + x => x.TokenHash == tokenHash, cancellationToken); + if (session is null || session.RevokedAt is not null || session.ExpiresAt <= DateTimeOffset.UtcNow) + { + return InvalidRefresh(); + } + + var user = await database.Users.SingleOrDefaultAsync(x => x.Id == session.UserId, cancellationToken); + if (user is null || !user.IsActive) + { + session.RevokedAt = DateTimeOffset.UtcNow; + await database.SaveChangesAsync(cancellationToken); + return InvalidRefresh(); + } + + // Rotation: the presented token is revoked and replaced in the same save. + session.RevokedAt = DateTimeOffset.UtcNow; + var (newRefreshToken, newSession) = createRefreshSession(user.Id); + database.RefreshSessions.Add(newSession); + var newAccessToken = createAccessToken(user.Id); + await database.SaveChangesAsync(cancellationToken); + return Results.Ok(new AuthResponse(user.Id, user.UserName, user.DisplayName, newAccessToken, newRefreshToken)); +}); + +app.MapPost("/api/auth/logout", async (RefreshTokenRequest? request, ErpDbContext database, CancellationToken cancellationToken) => +{ + if (request is null || string.IsNullOrWhiteSpace(request.RefreshToken)) + { + return Results.ValidationProblem(new Dictionary + { + ["refreshToken"] = ["刷新凭据不能为空。"] + }); + } + + var tokenHash = hashRefreshToken(request.RefreshToken.Trim()); + var session = await database.RefreshSessions.SingleOrDefaultAsync( + x => x.TokenHash == tokenHash, cancellationToken); + if (session is not null && session.RevokedAt is null) + { + session.RevokedAt = DateTimeOffset.UtcNow; + await database.SaveChangesAsync(cancellationToken); + } + + return Results.NoContent(); +}); + +app.MapGet("/api/auth/me", async (HttpRequest request, ErpDbContext database, IdentityService identity, CancellationToken cancellationToken) => +{ + static IResult Unauthorized() => Results.Problem( + title: "未登录", + detail: "缺少或无效的登录凭据。", + statusCode: StatusCodes.Status401Unauthorized); + + if (!request.Headers.TryGetValue("Authorization", out var authorization) || + !authorization.ToString().StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) + { + return Unauthorized(); + } + + var token = authorization.ToString()["Bearer ".Length..].Trim(); + if (token.Length == 0 || !sessions.TryGetValue(token, out var userId)) + { + return Unauthorized(); + } + + var user = await database.Users.SingleOrDefaultAsync(x => x.Id == userId, cancellationToken); + if (user is null || !user.IsActive) + { + return Unauthorized(); + } + + var profile = await identity.GetUserAsync(user.Id, cancellationToken); + return Results.Ok(new { user.Id, user.UserName, user.DisplayName, profile.IsActive, profile.Roles, profile.Modules, profile.Permissions }); +}); + +app.Run(); diff --git a/src/Leiren.Erp.Api/Properties/launchSettings.json b/src/Leiren.Erp.Api/Properties/launchSettings.json new file mode 100644 index 0000000..d00ec73 --- /dev/null +++ b/src/Leiren.Erp.Api/Properties/launchSettings.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5118", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/src/Leiren.Erp.Api/PurchasingEndpoints.cs b/src/Leiren.Erp.Api/PurchasingEndpoints.cs new file mode 100644 index 0000000..58fb43f --- /dev/null +++ b/src/Leiren.Erp.Api/PurchasingEndpoints.cs @@ -0,0 +1,128 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Application.Purchasing; + +namespace Leiren.Erp.Api; + +public static class PurchasingEndpoints +{ + public static IEndpointRouteBuilder MapPurchasingEndpoints(this IEndpointRouteBuilder app) + { + var tasks = app.MapGroup("/api/purchase-tasks"); + + tasks.MapGet("/", (Guid? salesOrderId, Guid? purchaseContractId, string? status, string? search, + int? page, int? pageSize, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListTasksAsync( + salesOrderId, purchaseContractId, status, search, page ?? 1, pageSize ?? 50, ct)))); + + tasks.MapGet("/{id:guid}", (Guid id, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetTaskAsync(id, ct)))); + + tasks.MapGet("/overview", (PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetOverviewAsync(ct)))); + + tasks.MapPost("/", (CreatePurchaseTaskRequest request, PurchaseService service, CancellationToken ct) => + Handle(async () => + { + var task = await service.CreateTaskAsync(request, ct); + return Results.Created($"/api/purchase-tasks/{task.Id}", task); + })); + + // Explicit cross-module command: derive tasks from a confirmed sales order. + tasks.MapPost("/generate-from-sales-order", (GeneratePurchaseTasksRequest request, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GenerateFromSalesOrderAsync(request, ct)))); + + tasks.MapPut("/{id:guid}", (Guid id, UpdatePurchaseTaskRequest request, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateTaskAsync(id, request, ct)))); + + tasks.MapPost("/{id:guid}/cancel", (Guid id, PurchaseService service, CancellationToken ct) => + Handle(async () => + { + await service.CancelTaskAsync(id, ct); + return Results.NoContent(); + })); + + tasks.MapPost("/{id:guid}/arrivals", (Guid id, RecordPurchaseArrivalRequest request, PurchaseService service, CancellationToken ct) => + Handle(async () => + { + var arrival = await service.RecordArrivalAsync(id, request, ct); + return Results.Created($"/api/purchase-tasks/{id}/arrivals/{arrival.Id}", arrival); + })); + + var contracts = app.MapGroup("/api/purchase-contracts"); + + contracts.MapGet("/", (string? status, string? search, int? page, int? pageSize, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListContractsAsync(status, search, page ?? 1, pageSize ?? 50, ct)))); + + contracts.MapGet("/{id:guid}", (Guid id, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetContractAsync(id, ct)))); + + contracts.MapPost("/", (CreatePurchaseContractRequest request, PurchaseService service, CancellationToken ct) => + Handle(async () => + { + var contract = await service.CreateContractAsync(request, ct); + return Results.Created($"/api/purchase-contracts/{contract.Id}", contract); + })); + + contracts.MapPut("/{id:guid}", (Guid id, UpdatePurchaseContractRequest request, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateContractAsync(id, request, ct)))); + + contracts.MapPost("/{id:guid}/confirm", (Guid id, PurchaseService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ConfirmContractAsync(id, ct)))); + + contracts.MapPost("/{id:guid}/export", (Guid id, PurchaseContractExportService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ExportAsync(id, ct)))); + + contracts.MapGet("/{id:guid}/export/preview", (Guid id, PurchaseContractExportService service, CancellationToken ct) => + Handle(async () => + { + var (bytes, fileName) = await service.PreviewAsync(id, ct); + return Results.File(bytes, PurchaseContractExportService.ContentType, fileName); + })); + + contracts.MapPost("/{id:guid}/void", (Guid id, PurchaseService service, CancellationToken ct) => + Handle(async () => + { + await service.VoidContractAsync(id, ct); + return Results.NoContent(); + })); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (PurchasingValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (PurchasingNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (PurchasingConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (FilesValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (FilesNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (FilesConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/SalesOrderEndpoints.cs b/src/Leiren.Erp.Api/SalesOrderEndpoints.cs new file mode 100644 index 0000000..d28b911 --- /dev/null +++ b/src/Leiren.Erp.Api/SalesOrderEndpoints.cs @@ -0,0 +1,85 @@ +using Leiren.Erp.Application.Sales; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class SalesOrderEndpoints +{ + public static IEndpointRouteBuilder MapSalesOrderEndpoints(this IEndpointRouteBuilder app) + { + var customers = app.MapGroup("/api/customers"); + + customers.MapGet("/", (string? search, bool? isActive, int? page, int? pageSize, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListCustomersAsync(search, isActive, page ?? 1, pageSize ?? 50, ct)))); + + customers.MapGet("/{id:guid}", (Guid id, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetCustomerAsync(id, ct)))); + + customers.MapPost("/", (SaveCustomerRequest request, SalesOrderService service, CancellationToken ct) => + Handle(async () => + { + var customer = await service.CreateCustomerAsync(request, ct); + return Results.Created($"/api/customers/{customer.Id}", customer); + })); + + customers.MapPut("/{id:guid}", (Guid id, SaveCustomerRequest request, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateCustomerAsync(id, request, ct)))); + + var orders = app.MapGroup("/api/sales-orders"); + + orders.MapGet("/", (string? search, string? status, Guid? customerId, int? page, int? pageSize, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListAsync(search, status, customerId, page ?? 1, pageSize ?? 50, ct)))); + + orders.MapGet("/{id:guid}", (Guid id, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetAsync(id, ct)))); + + orders.MapPost("/", (SaveSalesOrderRequest request, SalesOrderService service, CancellationToken ct) => + Handle(async () => + { + var order = await service.CreateAsync(request, ct); + return Results.Created($"/api/sales-orders/{order.Id}", order); + })); + + orders.MapPut("/{id:guid}", (Guid id, SaveSalesOrderRequest request, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateAsync(id, request, ct)))); + + orders.MapPost("/{id:guid}/confirm", (Guid id, ConfirmSalesOrderRequest? request, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ConfirmAsync(id, request, ct)))); + + orders.MapPost("/{id:guid}/cancel", (Guid id, CancelSalesOrderRequest? request, SalesOrderService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.CancelAsync(id, request, ct)))); + + orders.MapDelete("/{id:guid}", (Guid id, SalesOrderService service, CancellationToken ct) => + Handle(async () => + { + await service.DeleteAsync(id, ct); + return Results.NoContent(); + })); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (SalesValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (SalesNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (SalesConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/SalesOrderImportEndpoints.cs b/src/Leiren.Erp.Api/SalesOrderImportEndpoints.cs new file mode 100644 index 0000000..8f6e15f --- /dev/null +++ b/src/Leiren.Erp.Api/SalesOrderImportEndpoints.cs @@ -0,0 +1,119 @@ +using System.Globalization; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Application.Sales; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class SalesOrderImportEndpoints +{ + public static IEndpointRouteBuilder MapSalesOrderImportEndpoints(this IEndpointRouteBuilder app) + { + var orders = app.MapGroup("/api/sales-orders"); + + // multipart/form-data: + // file (required, real .xlsx), customerId, customerPoNumber, orderNumber, + // orderDate, requiredDeliveryDate, currency, transportMode, loadingPort, + // destinationPort, destinationCountry, tradeTerm, paymentTerms, + // shippingNote, remark, sheetName, createDraft, attachOriginal, uploadedBy + // Without createDraft this is a pure preview: nothing is persisted and + // every bad row is reported with its worksheet row number. With + // createDraft a Draft order is created only when all rows are valid; + // attachOriginal additionally stores the uploaded file as the order's + // original PO through FileService. + orders.MapPost("/import-po", (HttpRequest request, PoExcelImportService service, CancellationToken ct) => + Handle(async () => + { + if (!request.HasFormContentType) + throw new SalesValidationException("file", "PO 导入必须使用 multipart/form-data 上传 .xlsx 文件。"); + + var form = await request.ReadFormAsync(ct); + var file = form.Files.GetFile("file") ?? form.Files.FirstOrDefault(); + if (file is null || file.Length == 0) + throw new SalesValidationException("file", "请选择要导入的 PO Excel 文件。"); + + await using var content = file.OpenReadStream(); + var result = await service.ImportAsync(content, file.FileName, file.ContentType, new PoExcelImportOptions( + CustomerId: ParseGuid(FormValue(form, "customerId")), + CustomerPoNumber: FormValue(form, "customerPoNumber"), + OrderNumber: FormValue(form, "orderNumber"), + OrderDate: ParseDate(FormValue(form, "orderDate"), "orderDate"), + RequiredDeliveryDate: ParseDate(FormValue(form, "requiredDeliveryDate"), "requiredDeliveryDate"), + Currency: FormValue(form, "currency"), + TransportMode: FormValue(form, "transportMode"), + LoadingPort: FormValue(form, "loadingPort"), + DestinationPort: FormValue(form, "destinationPort"), + DestinationCountry: FormValue(form, "destinationCountry"), + TradeTerm: FormValue(form, "tradeTerm"), + PaymentTerms: FormValue(form, "paymentTerms"), + ShippingNote: FormValue(form, "shippingNote"), + Remark: FormValue(form, "remark"), + SheetName: FormValue(form, "sheetName"), + CreateDraft: ParseBool(FormValue(form, "createDraft")), + AttachOriginal: ParseBool(FormValue(form, "attachOriginal") ?? FormValue(form, "saveOriginalPo")), + UploadedBy: FormValue(form, "uploadedBy")), ct); + + return result.CreatedOrder is { } order + ? Results.Created($"/api/sales-orders/{order.Id}", result) + : Results.Ok(result); + })).DisableAntiforgery(); + + return app; + } + + private static string? FormValue(IFormCollection form, string key) + => form.TryGetValue(key, out var value) && !string.IsNullOrWhiteSpace(value.ToString()) + ? value.ToString().Trim() + : null; + + private static Guid? ParseGuid(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return null; + if (!Guid.TryParse(value, out var parsed)) + throw new SalesValidationException("customerId", "customerId 不是有效的标识。"); + return parsed; + } + + private static bool ParseBool(string? value) + => bool.TryParse(value, out var parsed) && parsed; + + private static DateOnly? ParseDate(string? value, string field) + { + if (string.IsNullOrWhiteSpace(value)) return null; + if (DateOnly.TryParseExact(value.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) + return date; + throw new SalesValidationException(field, $"{field} 必须为 yyyy-MM-dd 格式。"); + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (SalesValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (FilesValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (SalesNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (SalesConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidDataException ex) + { + return Results.Problem(title: "文件无效", detail: ex.Message, statusCode: StatusCodes.Status400BadRequest); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/ShippingEndpoints.cs b/src/Leiren.Erp.Api/ShippingEndpoints.cs new file mode 100644 index 0000000..7da052f --- /dev/null +++ b/src/Leiren.Erp.Api/ShippingEndpoints.cs @@ -0,0 +1,87 @@ +using Leiren.Erp.Application.Shipping; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Api; + +public static class ShippingEndpoints +{ + public static IEndpointRouteBuilder MapShippingEndpoints(this IEndpointRouteBuilder app) + { + var batches = app.MapGroup("/api/shipping-batches"); + + batches.MapGet("/", (Guid? salesOrderId, string? status, string? search, + int? page, int? pageSize, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListBatchesAsync( + salesOrderId, status, search, page ?? 1, pageSize ?? 50, ct)))); + + batches.MapGet("/ready-orders", (ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ListReadyOrdersAsync(ct)))); + + batches.MapGet("/{id:guid}", (Guid id, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.GetBatchAsync(id, ct)))); + + batches.MapPost("/", (CreateShippingBatchRequest request, ShippingService service, CancellationToken ct) => + Handle(async () => + { + var batch = await service.CreateBatchAsync(request, ct); + return Results.Created($"/api/shipping-batches/{batch.Id}", batch); + })); + + batches.MapPut("/{id:guid}", (Guid id, UpdateShippingBatchRequest request, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateBatchAsync(id, request, ct)))); + + batches.MapPost("/{id:guid}/confirm", (Guid id, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.ConfirmBatchAsync(id, confirmedBy: null, ct)))); + + batches.MapPost("/{id:guid}/cancel", (Guid id, CancelShippingBatchRequest? request, ShippingService service, CancellationToken ct) => + Handle(async () => + { + await service.CancelBatchAsync(id, request?.Reason, ct); + return Results.NoContent(); + })); + + batches.MapPost("/{id:guid}/containers", (Guid id, SaveShippingContainerRequest request, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AddContainerAsync(id, request, ct)))); + + batches.MapPut("/{id:guid}/containers/{containerId:guid}", (Guid id, Guid containerId, SaveShippingContainerRequest request, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateContainerAsync(id, containerId, request, ct)))); + + batches.MapDelete("/{id:guid}/containers/{containerId:guid}", (Guid id, Guid containerId, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.RemoveContainerAsync(id, containerId, ct)))); + + batches.MapPost("/{id:guid}/lines", (Guid id, SaveShipmentLineRequest request, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.AddLineAsync(id, request, ct)))); + + batches.MapPut("/{id:guid}/lines/{lineId:guid}", (Guid id, Guid lineId, SaveShipmentLineRequest request, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.UpdateLineAsync(id, lineId, request, ct)))); + + batches.MapDelete("/{id:guid}/lines/{lineId:guid}", (Guid id, Guid lineId, ShippingService service, CancellationToken ct) => + Handle(async () => Results.Ok(await service.RemoveLineAsync(id, lineId, ct)))); + + return app; + } + + private static async Task Handle(Func> action) + { + try + { + return await action(); + } + catch (ShippingValidationException ex) + { + return Results.ValidationProblem(ex.Errors); + } + catch (ShippingNotFoundException ex) + { + return Results.Problem(title: "资源不存在", detail: ex.Message, statusCode: StatusCodes.Status404NotFound); + } + catch (ShippingConflictException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "操作冲突", detail: ex.Message, statusCode: StatusCodes.Status409Conflict); + } + } +} diff --git a/src/Leiren.Erp.Api/appsettings.Development.json b/src/Leiren.Erp.Api/appsettings.Development.json new file mode 100644 index 0000000..c5d74a5 --- /dev/null +++ b/src/Leiren.Erp.Api/appsettings.Development.json @@ -0,0 +1,14 @@ +{ + "ConnectionStrings": { + "Default": "Data Source=data/leiren-dev.db" + }, + "Database": { + "Provider": "Sqlite" + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/src/Leiren.Erp.Api/appsettings.json b/src/Leiren.Erp.Api/appsettings.json new file mode 100644 index 0000000..d57caa6 --- /dev/null +++ b/src/Leiren.Erp.Api/appsettings.json @@ -0,0 +1,27 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "Database": { + "Provider": "Sqlite" + }, + "HealthChecks": { + "DatabaseTimeout": "00:00:05" + }, + "PurchaseContract": { + "TemplatePath": "templates/purchase-contract.xlsx" + }, + "FileStorage": { + "RootPath": "data/storage", + "MaxFileSizeBytes": 52428800, + "AllowedExtensions": [ + ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", + ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", + ".txt", ".csv", ".zip", ".rar", ".7z" + ] + } +} diff --git a/src/Leiren.Erp.Api/templates/billing/开票购销合同.xlsx b/src/Leiren.Erp.Api/templates/billing/开票购销合同.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..2d1213632e4457a640a1d0f1e731ce749287f670 GIT binary patch literal 8498 zcmZ`;WmH|svOc)GySux)y9RfM;2b%O^@d+*+> zyI24CYIoJ{s_L#!RRIDL6953f0-7S64W);bWYgYe6K@UmtywsktGYTlyRn!$J2QJZ z*ek^=A@s4LO1{b;Z4@>giJ6Jb7aWcHD)MkASfp8m-hqmONLuj1ZcVPJD8#H#q~>we zSGX}a9Fplhf^4EBgEY;Z(+hUU*|xCw519z3g~=(k#+wZpN)c^CT*Qn`IgW_b&KGNk zIkUb_=uFq~Y9WaIWJ@#+Kp;)##h~+>c004YB^EKP*!s8wrTPyg z5E6*7L2rv^00#ij{#^-kCs)fqw3tZTkna~ol{PN=>Brtt25m6APHRL5i;W3N-LUNd zzAh8VJ=`QN7e@#Ows4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9W! literal 0 HcmV?d00001 diff --git a/src/Leiren.Erp.Api/templates/billing/开票通知.xlsx b/src/Leiren.Erp.Api/templates/billing/开票通知.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..63431a6e4bcc42638aa9f8cf79d51402f3690e55 GIT binary patch literal 6825 zcmZ`;by$>3``$$m>28qjh9!iR4(SGIfu*}k&LS)!?UEuZvXn>)2oeH{l7e)@BDu75 z!w=87zU!RB@B7~OnwjhU<9=qI`<>^RnR|3K?qHGw0Dyad53ydBDxF%7GH<^6ZVK^D zfq2^K`gnTz3fg#i2?V*jX(emneGwv7x>iTe7JNX<+scpRqq{>jCB#!8nUJWHox%vl zdYb6tCkO1T@(x7GBh>nn;$))kX*>ZDPH{>RhIU?A`9E2NQ4~_E{PY7dENsTTb(Xwu z@ttAb^42z@Xa>DsV^y7?oaVmA1Mek`@#Hs!;Wkh_rZh=1wvaKVkjd_J%z@2k*1Qn z7DF>!R^0a}$#*hlotylwCm7Vuj^GnTu`=QHqKvE3cZS#4{J)>T?Y?MI_PQJhke3Wc zGsMC%xz56^(xo`?^8=f*J|Xoxn_~(N^tMQ7`^|qn>fzEC0+!Yio1$p={Z*8Ob9Yq) zPYzzr;)~J_Ukg0C@sb!9%_dK9?hpjbTqOWu5tbK=P zGylExd2*s)L>PAK74jP6-|W1!$YI5~3jpMB0sv$;>;$<9`Z?LV+y7My|K?}Q3}rAa zN&LrZ1y#?>3#M<(ackP=MRE>9AX+A4o>CB2v=coTqvFV*<5n`;*N0DcISt4pks9 zRI!@?1lQ~niHJuZ+l=1*;lUV>xQ&J!Vwpd=B`N@%0Bq2 znmb6o!NmP!Efbcmhi=n;BCjh>XS|D{l4T*ob| z)SESrVj9MyCWKkG7@9hXROPfUfHd{Ps8S76rx%E7v+QNzs-$)${8GFpp)7MYgt;GU zT-w+c*E)(GuY!LAAGG{PP*fx)7BdL2W~d)@z?7@}22|+7uRmQ$Q=byY*5?;~-4nhz zG=qXRF(yy9*PjmV&mkA$?e2m(H^K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c*SoJd&ZzPsi9 zPL<8I8a%hbZ3-4GN{(IH3`zN4fm^<4jw~G=u_S-HyU#ZxBgb@S_!LR(_@fMR+OufU z0=u`>%nj9IBX6S+R!hr70^x;ikVmW);T@G?o?YEuetzBmfOs5;gZSy!XWYWeW&b#Z z4Ie(Ax2MNT{w45D8CFg6aeFiq&3q*m-85i_T^7ZB$QyZHH-WcxAJ3X~IZj~yjV$mf zWld@9=wwH&tXE<#cV_PNp9}Gb@yTN(yxQsl=|)Es*x} zLSZ@TmNO6rn^W_s7tt&5)6Iy}B0*@D6-lYv>4wE_c}je45*|=w6kqTXm03e@f!J{> z^ZFs3=OnnCe` zs|5bdk#TJkMc{+qwkT(qCE->44No|GIIa^lpIg@;{llJB;!tXAKu9g{hKPN zys|&A*MW7=v{Vs@G5t5y$_in=$pc1_T=Pr5or2ivqzlE7$i35i<4cpNWOpzb_j?X9 z3iZ@6qza`tc#qn<=Rg)-q%f$a$=pFOkK>H-0WFa*T?pN(7kI^NG@Rs$JK$Pv9~)xv zd}5uk;p`dV)bI(I?M`r-D&xt=-ZB;#wz5djN$?;jWfjow35J|^LRw0ZnjBj=yifA&oNZ3_hC2R!gUt^d1&@=x^EcrCCxQQo z@Mn?y9|UmnzfS3&lKG#ef9C6dOdHw$mA(Ho{4?SGV_3=lpJDj#^!KOnpF#H@V>8ab ojQ@`i{3p(zf$bk0X|De@%qhx%L;U^{!pE}|6bPu5`}fxW124kfZ~y=R literal 0 HcmV?d00001 diff --git a/src/Leiren.Erp.Api/templates/customs/报关发票.xlsx b/src/Leiren.Erp.Api/templates/customs/报关发票.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..481410020adc8ff6ddd0163a7a510f64abf9870a GIT binary patch literal 35705 zcmZ5`W3VVev*fXLk8RtwZQHhO+qP}nwteogZSQ^iHs0>HKdO7Ge@skPR8(eXjJy;u z2r>Ww00h8Jh`o;Jn2dPZzij4TAp8qsJ0p2VJ9{TO1ABW~cN=S&I2q_cdIaHL$+Ml} z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X9WTfV%LP+p+y6E=5Tftl+4YdC?P&ujrPuY=NpIlm8lAnvs z1uOo%Ztevty(bH~#~0>;ZHRjWD337;FGy5F1@9dX0E^K)8aLfnj$$hz9^RFX^8E literal 0 HcmV?d00001 diff --git a/src/Leiren.Erp.Api/templates/customs/报关外销合同.xlsx b/src/Leiren.Erp.Api/templates/customs/报关外销合同.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..69723656ef59cf685cee23aeaac3a9858d54fb13 GIT binary patch literal 40453 zcma&N19W6t*997@qmIpv?R0G0wr#7!j&0lO*y_Ulao4o z)tPI~HTT+8wJS2>z#vEf000mG>j5^JLj95=iSLg_-VgZq!@yc!#?IQto<`TkhT6r_ zLNZeFQ#UQVz?<0qN?zSQuO9Do?*4$g1PgPNL83vx{aL;*ZUcJYoz688A+Hgf;53@t z0y83mWgNMauStl2uY$f!Qtk!;-5N669u?L&7r_^$p?Xb<4Z*6Dz7mMDQAu(V&q(JR_1MXOZ62%_Ibx>s#5O5@C{I8aN zv7ba83fMjI=eVNUgCr~pkyctb-X5-YKIJ83h@!4Dv%=wW^=mD9 z!IwZ3=y@bMDl(yG4RlLK30+pzElxu`VhG|_kSrk!sW*c?7@;L2+?)Bs=8EHjCgsn3 z7d@N1)E!OZ%*47xS)#a1;+SyuwJi@`Zmu&Lgj%27G~m_7YXT933d5rMyKXwIX)Mwv z#b3tyX3DZ^vuXm8f^<{OuPH?4-DW`4ffx;c6&@9SXU|JoTEv8XC#ua9-* za6fd<^1G&}tn5Zfpa1|b7ytl>@0z+;&^VYFS{nZ6H{D;Vo~TM%W3s@vq3(O*xmYXx zsEsi+z*f-~#bl?mAQ6nn)ig__OVo&pvs?+;R>|U-sNK)!vF1dw1pdN9b5LoUnj`t` zIY7_(hF2^Okp*fzCmN2p$vQBSp-0%v@n%tVa2zr^1PW*UFdjURiXUJbGa-mLRd1$^OKFJKoD!`m0L7X$T@Och-8l8^cX`62aS=p;_5@% zU@0Ha`?yPyG@NLL@Xx^c>=I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;Q%^zlYtwd*JsFOlhKz(qWChxKvMz8qFdd z^$pr1GkgHRiQV5Mz<)HTjgX`JC$|0KO7)XJqD&=MgPcnE4@x+N9*InrWXC^Tvi~L) zCPyLXpglr?Oa6`Wd(!_K>(`_w2PEf#JpvSxA~)_g2?pZ+@xq_i+;Zyq>ZE literal 0 HcmV?d00001 diff --git a/src/Leiren.Erp.Api/templates/customs/报关装箱单.xlsx b/src/Leiren.Erp.Api/templates/customs/报关装箱单.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..c86a9cb2f524b4b4077f92c66d2dbe6f3b5945e6 GIT binary patch literal 35927 zcmZ6SbC4%NknhK~ZQHhO+qP}b?AY9~ZF_!Wn>#zUt+#jg;@;i+BfGk)D?0j{QIYwn zjA|uWP%tzgARs89op2|834pv*#=qXoKSTOwW{##xE{;yFjK)q*3|{tj@(J>=Lrh3w zKQgB~C9S8zCc?|brxU(%oE(W}8D`Dwj?bs17MvvsA!WM|)%UCKK9H^}JsWcuT zRxx5BYNk$^#rq`8d+0nT^my|EBxD*>ZThqoaMoeY!iL7Ir})aZs|^6Q+@2Y&`9>}c zSm8_NWaB_sqEs$aGM`l%YjSP>dKB53mD0e+?jQsg@wX$sJ&!y$zF!>AXn-PSwf=lDjg}M!K{)e6hYw26Kj9VygX4%%RqAp@o*yQXxlvG<#4oA;z;LmUq&nID- zR8&rw`JyC5icZIf1lD0m8~3M8?a6uQq!<{2Kj&#M5@C@fMSKXidBxw5Iat*2d>|BD z(6^aXe)b<!RXrn^WP#<%FwgMaB%s_EYb< z%y%V97jIR5+qvn@{8TocGes)|fxo8S zOXU(IvHn5^E#;Mi=uq)%X!l>q!Dj9qT5Y(%EQsD2A>!Gkx-{d<#9qA!=xt;rOEFhryNU^JM6p zfeA=@OSq>!>(y7aqFuvoVCrE`fXj0)9>l>BlL21?6@yAIF#JNzQv}roi#s_|sz{Hx z$4-JFpK%KkoD4Dry}#c;WGvtp{$~P#w~wELb0>&|`GT(##$KRab~t^n*AM-DZ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(b`&wb-o}3AI_6Yj1ZUxOyO>i#$Pn)eIcFfMa6|0$czBxe%PuUIb5X4JS{})tTo-gC(74hk>5gft(<|0R^r> zVCH7DGro5IguCxkkt$~I*YCV literal 0 HcmV?d00001 diff --git a/src/Leiren.Erp.Api/templates/purchase-contract.xlsx b/src/Leiren.Erp.Api/templates/purchase-contract.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..fc918d20f022463aa6fd013e0ab580cedf0039f2 GIT binary patch literal 10946 zcmZ{K1ymi&vi8Q^-3jh)0fM`4++BmaLvRlScMTBS-QC^Y-Glqjx#!(?@5y@q-fO03 z*34JaRWtQfcULJ$gMp(1003yf^H)0^u>o0$q>r<)j}7@_GqyESaIm#=WHhj|V{o&! zl8u&y>t;e0d6zm|`&oA=Xecb3?6EYIp!&XP)g;8=cy4k}$gfkf;kN~$@DC*- z8hLGKK>&a#Pyhhszm+hubujr$i@sP{xgI8Du?j`^tVMeX6xCD+Vlwaq8X&l#+0x8B z$=eU>cqb?Acp&DpkbT?BUEpWBK7))52Wr1^1NS8p$pgoSVDbthV+zM_2W=Tk%aq}6 zH~M$Rx$q_=yUfSKw>#Y^)f2j_QbV}bAP-KCuXk=wUdwtrC|iDy($1WDx+VDUnWdGy zP~CQ2O_a2Q{L`{1QFff25CA|d9sq#$VOcjTMkjLkC%zxSTOheulO&q;L?bsE2 zj9~tR|5Ml^@#*5E5U~_I#=yba)p*QO%G@Ydm@NiAtxB;JEki=FuE(!s62Dog{49$2 zaK*3+g|YMH^}2x=0R=5Tq^r@>i?)qt)(dx2$G2{S?kPTCsw9g3yA=W{i4YDm3e^DAIB@#q5zIYmt zya_1`&maC^6x)HGx0=>{(%)br!O6%v7ea(FQEzq^HZr|kiEL$RT|Y~PGA%O%YM*JY z{UnJs$osP4b5wP17j)+b_3$lBg79W2rzjxm=lw zrRo*=YZSzbX3LsQnaU*&6%hy4Wl3GaexC;iN%ybL$PqdFvk7V zI6@MjtA57W*y^C_lnNfPj6og-Lk^z^XcA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Z+l;{JiL=Z5p2 zenLi=mRtJa9}gdiUfjR^TOQW zp=#dy0xd_40?Ezp`-I37jxQ(w=t01@`LX zk=vuUAyvIk%-g!(+RF%tVtM_PVjDfupk_e;mqkVEWq81KoRmSm zmLs>m^ME?GZ}L)vBo*F`^+c%Bwa%U|JJ_x>3f*N=B?+Jewnm11DM95Xzlbyq0TSfC zic-sir*t8Go^2F~U~tPRM}5lb04Z#~2irZRL)Xf9l!f{gc-%_D=Ry3L-acQv)Y7ao z*8)r=F`mU-8UX;sC_dH4mVyV()Q(j17%+-HnY&~v^Ap~*k;t|FX9a^&KX}U8O(<5b zoW-5jWQ%pz`UnR-bMVpwa9_;rU=C~lwG#ekFw@3n7M#meM^3bS@2l^HE0M`0L+0aG zE|Qavj5Y`;I^h3bF8J~B{OkAa!_xm%Ebu?YgMXs`tke4&3jllr>HBZ=zpM8Cg#THL z_8&OW2kHMGrD=Z(__Mg-KLU`U|Eu@^DRuZ$z@I7oe+#Jh(}MX|5B|>t|DRI+T=@C7 zly4xOSbr=7{R#auvi}D<_vs&T{!ieaq47V!F_Qo7`M+KNPw=07@gMLl`M<#bANKfD j&YwQ{A2~}D0Kos@p$gIvkbm6-`|Absolute paths of the built-in 开票通知 / 开票购销合同 templates. +public sealed record BillingTemplateOptions(string NoticeTemplatePath, string ContractTemplatePath); + +///

+/// Renders a supplier notice's 开票通知书 or 开票用产品购销合同 as XLSX. +/// The most recently imported template of that type (template editor) wins; +/// without one the configured built-in template is used. Nothing is stored. +/// +public sealed class BillingDocumentExportService(IBillingDbContext db, FileService files, BillingTemplateOptions options) +{ + public async Task<(byte[] Bytes, string FileName)> RenderAsync(Guid noticeId, string kind, CancellationToken ct = default) + { + var (label, fallbackPath) = kind switch + { + DocumentTemplateKinds.SupplierInvoiceNoticeKind => ("开票通知", options.NoticeTemplatePath), + DocumentTemplateKinds.SupplierBillingContractKind => ("开票购销合同", options.ContractTemplatePath), + _ => throw new BillingValidationException(nameof(kind), "单据类型只能是开票通知或开票购销合同。"), + }; + + var notice = await db.SupplierInvoiceNotices.AsNoTracking() + .Include(x => x.Lines) + .Include(x => x.BillingContract) + .SingleOrDefaultAsync(x => x.Id == noticeId, ct) + ?? throw new BillingNotFoundException("开票通知不存在。"); + + var template = await LoadTemplateAsync(kind, fallbackPath, label, ct); + var bytes = BillingDocumentRenderer.Render(template, notice, label); + return (bytes, $"{Sanitize(notice.NoticeNo)}-{Sanitize(notice.SupplierName)}-{label}.xlsx"); + } + + /// Renders a template file against a notice for the template editor preview. + public async Task PreviewAsync(byte[] template, Guid noticeId, string label, CancellationToken ct = default) + { + var notice = await db.SupplierInvoiceNotices.AsNoTracking() + .Include(x => x.Lines) + .Include(x => x.BillingContract) + .SingleOrDefaultAsync(x => x.Id == noticeId, ct) + ?? throw new BillingNotFoundException("开票通知不存在。"); + return BillingDocumentRenderer.Render(template, notice, label); + } + + private async Task LoadTemplateAsync(string kind, string fallbackPath, string label, CancellationToken ct) + { + var imported = (await files.ListAsync( + DocumentTemplateService.TemplateOwnerType, null, kind, null, currentOnly: true, 1, 200, ct)) + .MaxBy(x => x.CreatedAt); + if (imported is not null) + { + await using var content = (await files.OpenDownloadAsync(imported.Id, ct)).Content; + using var buffer = new MemoryStream(); + await content.CopyToAsync(buffer, ct); + return buffer.ToArray(); + } + + try + { + return await File.ReadAllBytesAsync(fallbackPath, ct); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + throw new BillingValidationException("Template", $"{label}模板读取失败:{ex.Message}"); + } + } + + private static string Sanitize(string value) + { + var invalid = Path.GetInvalidFileNameChars(); + var stem = new string(value.Select(ch => invalid.Contains(ch) || ch < 32 ? '_' : ch).ToArray()).Trim(); + return stem.Length == 0 ? "billing" : stem; + } +} diff --git a/src/Leiren.Erp.Application/Billing/BillingDocumentRenderer.cs b/src/Leiren.Erp.Application/Billing/BillingDocumentRenderer.cs new file mode 100644 index 0000000..0996b18 --- /dev/null +++ b/src/Leiren.Erp.Application/Billing/BillingDocumentRenderer.cs @@ -0,0 +1,192 @@ +using System.Globalization; +using System.Text; +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Domain.Entities; + +namespace Leiren.Erp.Application.Billing; + +/// +/// Renders the supplier 开票通知书 and 开票用产品购销合同 from a notice +/// snapshot (whose lines were taken from the customs declaration) through +/// . Both document types share one +/// built-in placeholder catalog. +/// +public static class BillingDocumentRenderer +{ + private static readonly string[] HeaderFields = + [ + "NoticeNo", "NoticeDate", "ExportInvoiceNo", "ShipmentNo", "SalesOrderNo", "CustomerPoNo", "ShipmentDate", + "PurchaseContractNo", "ContractNo", "SignedPlace", "SignedDate", + "SupplierName", "SupplierContact", "SupplierPhone", "SupplierFax", "SupplierAddress", + "InvoiceTitle", "InvoiceTitleAddress", "InvoiceTitlePhone", "InvoiceTitleBankName", "InvoiceTitleBankAccount", + "InvoiceTitleTaxNo", "InvoiceTitleCustomsCode", "InvoicingRequirement", "StampRequirement", "ContactName", + "MailingAddress", "Remark", "Currency", + "BuyerName", "BuyerAddress", "BuyerPhone", "BuyerFax", "BuyerBankName", "BuyerBankAccount", "BuyerTaxNo", + "SellerName", "SellerAddress", "SellerContact", "SellerPhone", "SellerFax", + "QualityTechnicalTerms", "DeliveryTerms", "PackagingTerms", "SettlementTerms", "TaxTerms", "IntellectualPropertyTerms", + "LineCount", "TotalQuantity", "TotalAmountIncludingTax", "TotalAmountExcludingTax", "TotalTaxAmount", "TotalAmountInWords", + "TotalAmountText", + ]; + + private static readonly TokenTemplateFields Fields = new( + new HashSet(StringComparer.OrdinalIgnoreCase) + { + "LineNumber", "ProductName", "ProductNameEn", "InternalSku", "CustomerSku", "Specification", "Quantity", "Unit", + "TaxIncludedUnitPrice", "TaxExcludingUnitPrice", "AmountIncludingTax", "AmountExcludingTax", "TaxAmount", "TaxRate", + "LinePurchaseContractNo", + }, + new HashSet(StringComparer.OrdinalIgnoreCase) + { + "LineNumber", "Quantity", "TaxIncludedUnitPrice", "TaxExcludingUnitPrice", "AmountIncludingTax", "AmountExcludingTax", + "TaxAmount", "TaxRate", "LineCount", "TotalQuantity", "TotalAmountIncludingTax", "TotalAmountExcludingTax", "TotalTaxAmount", + }, + new HashSet(StringComparer.OrdinalIgnoreCase) { "NoticeDate", "ShipmentDate", "SignedDate" }); + + /// Every placeholder name a 开票通知 / 开票购销合同 template may use. + public static IReadOnlyList FieldNames { get; } = [.. HeaderFields, .. Fields.LineFields]; + + public static byte[] Render(byte[] templateBytes, SupplierInvoiceNotice notice, string documentLabel) + { + ArgumentNullException.ThrowIfNull(notice); + var lines = notice.Lines.OrderBy(x => x.InternalSku, StringComparer.Ordinal).ThenBy(x => x.ContentDescription, StringComparer.Ordinal).ToList(); + return TokenWorkbookRenderer.Render( + templateBytes, BuildHeaderValues(notice), lines.Select((l, i) => (IReadOnlyDictionary)BuildLineValues(l, i)).ToList(), + Fields, documentLabel, message => new BillingValidationException("Template", message)); + } + + private static string N(decimal value) => value.ToString("0.####", CultureInfo.InvariantCulture); + private static string? D(DateOnly? value) => value?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + + private static Dictionary BuildHeaderValues(SupplierInvoiceNotice n) + { + var c = n.BillingContract; + return new(StringComparer.OrdinalIgnoreCase) + { + ["NoticeNo"] = n.NoticeNo, + ["NoticeDate"] = D(n.NoticeDate), + ["ExportInvoiceNo"] = n.ExportInvoiceNo, + ["ShipmentNo"] = n.ShipmentNo, + ["SalesOrderNo"] = n.SalesOrderNo, + ["CustomerPoNo"] = n.CustomerPoNo, + ["ShipmentDate"] = D(n.ShipmentDate), + ["PurchaseContractNo"] = c?.ContractNo ?? n.PurchaseContractNo, + ["ContractNo"] = c?.ContractNo ?? n.PurchaseContractNo ?? n.NoticeNo, + ["SignedPlace"] = c?.SignedPlace, + ["SignedDate"] = D(c?.SignedDate ?? n.NoticeDate), + ["SupplierName"] = n.SupplierName, + ["SupplierContact"] = n.SupplierContact, + ["SupplierPhone"] = n.SupplierPhone, + ["SupplierFax"] = n.SupplierFax, + ["SupplierAddress"] = n.SupplierAddress, + ["InvoiceTitle"] = n.InvoiceTitle, + ["InvoiceTitleAddress"] = n.InvoiceTitleAddress, + ["InvoiceTitlePhone"] = n.InvoiceTitlePhone, + ["InvoiceTitleBankName"] = n.InvoiceTitleBankName, + ["InvoiceTitleBankAccount"] = n.InvoiceTitleBankAccount, + ["InvoiceTitleTaxNo"] = n.InvoiceTitleTaxNo, + ["InvoiceTitleCustomsCode"] = n.InvoiceTitleCustomsCode, + ["InvoicingRequirement"] = n.InvoicingRequirement, + ["StampRequirement"] = n.StampRequirement, + ["ContactName"] = n.ContactName, + ["MailingAddress"] = n.MailingAddress, + ["Remark"] = n.Remark, + ["Currency"] = n.Currency, + ["BuyerName"] = c?.BuyerName ?? n.InvoiceTitle, + ["BuyerAddress"] = c?.BuyerAddress ?? n.InvoiceTitleAddress, + ["BuyerPhone"] = c?.BuyerPhone ?? n.InvoiceTitlePhone, + ["BuyerFax"] = c?.BuyerFax, + ["BuyerBankName"] = c?.BuyerBankName ?? n.InvoiceTitleBankName, + ["BuyerBankAccount"] = c?.BuyerBankAccount ?? n.InvoiceTitleBankAccount, + ["BuyerTaxNo"] = c?.BuyerTaxNo ?? n.InvoiceTitleTaxNo, + ["SellerName"] = c?.SellerName ?? n.SupplierName, + ["SellerAddress"] = c?.SellerAddress ?? n.SupplierAddress, + ["SellerContact"] = c?.SellerContact ?? n.SupplierContact, + ["SellerPhone"] = c?.SellerPhone ?? n.SupplierPhone, + ["SellerFax"] = c?.SellerFax ?? n.SupplierFax, + ["QualityTechnicalTerms"] = c?.QualityTechnicalTerms, + ["DeliveryTerms"] = c?.DeliveryTerms, + ["PackagingTerms"] = c?.PackagingTerms, + ["SettlementTerms"] = c?.SettlementTerms, + ["TaxTerms"] = c?.TaxTerms, + ["IntellectualPropertyTerms"] = c?.IntellectualPropertyTerms, + ["LineCount"] = n.Lines.Count.ToString(CultureInfo.InvariantCulture), + ["TotalQuantity"] = N(n.TotalQuantity), + ["TotalAmountText"] = n.TotalAmountIncludingTax.ToString("#,##0.00", CultureInfo.InvariantCulture), + ["TotalAmountIncludingTax"] = N(n.TotalAmountIncludingTax), + ["TotalAmountExcludingTax"] = N(n.TotalAmountExcludingTax), + ["TotalTaxAmount"] = N(n.TotalTaxAmount), + ["TotalAmountInWords"] = RmbInWords(n.TotalAmountIncludingTax), + }; + } + + private static Dictionary BuildLineValues(SupplierInvoiceNoticeLine l, int index) => new(StringComparer.OrdinalIgnoreCase) + { + ["LineNumber"] = (index + 1).ToString(CultureInfo.InvariantCulture), + ["ProductName"] = string.IsNullOrWhiteSpace(l.ContentDescription) ? l.ProductNameZh : l.ContentDescription, + ["ProductNameEn"] = l.ProductNameEn, + ["InternalSku"] = l.InternalSku, + ["CustomerSku"] = l.CustomerSku, + ["Specification"] = l.Specification, + ["Quantity"] = N(l.Quantity), + ["Unit"] = l.Unit, + ["TaxIncludedUnitPrice"] = N(l.TaxIncludedUnitPrice), + ["TaxExcludingUnitPrice"] = N(l.TaxExcludingUnitPrice), + ["AmountIncludingTax"] = N(l.AmountIncludingTax), + ["AmountExcludingTax"] = N(l.AmountExcludingTax), + ["TaxAmount"] = N(l.TaxAmount), + ["TaxRate"] = N(l.TaxRate), + ["LinePurchaseContractNo"] = l.PurchaseContractNo, + }; + + /// Chinese uppercase RMB amount, e.g. 66211.20 → 陆万陆仟贰佰壹拾壹元贰角. + public static string RmbInWords(decimal amount) + { + const string digits = "零壹贰叁肆伍陆柒捌玖"; + string[] units = ["", "拾", "佰", "仟"]; + string[] sections = ["", "万", "亿", "万亿"]; + + var negative = amount < 0; + var fen = (long)decimal.Round(Math.Abs(amount) * 100, 0, MidpointRounding.AwayFromZero); + var yuan = fen / 100; + var jiao = (int)(fen / 10 % 10); + var cents = (int)(fen % 10); + + var text = new StringBuilder(); + if (yuan == 0) + { + text.Append('零'); + } + else + { + var groups = new List(); + for (var v = yuan; v > 0; v /= 10000) groups.Add((int)(v % 10000)); + var needZero = false; + for (var g = groups.Count - 1; g >= 0; g--) + { + var value = groups[g]; + if (value == 0) { needZero = text.Length > 0; continue; } + if (needZero || (text.Length > 0 && value < 1000)) text.Append('零'); + needZero = false; + var zero = false; + for (var p = 3; p >= 0; p--) + { + var d = value / (int)Math.Pow(10, p) % 10; + if (d == 0) { zero = true; continue; } + if (zero && text.Length > 0 && text[^1] != '零') text.Append('零'); + zero = false; + text.Append(digits[d]).Append(units[p]); + } + text.Append(sections[g]); + } + } + text.Append('元'); + if (jiao == 0 && cents == 0) text.Append('整'); + else + { + if (jiao > 0) text.Append(digits[jiao]).Append('角'); + else if (yuan > 0) text.Append('零'); + if (cents > 0) text.Append(digits[cents]).Append('分'); + } + return (negative ? "负" : "") + text; + } +} diff --git a/src/Leiren.Erp.Application/Billing/BillingExceptions.cs b/src/Leiren.Erp.Application/Billing/BillingExceptions.cs new file mode 100644 index 0000000..2ef34de --- /dev/null +++ b/src/Leiren.Erp.Application/Billing/BillingExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Billing; + +public sealed class BillingNotFoundException(string message) : Exception(message); + +public sealed class BillingConflictException(string message) : Exception(message); + +public sealed class BillingValidationException(IReadOnlyDictionary errors) + : Exception("供应商开票资料校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public BillingValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Billing/BillingService.cs b/src/Leiren.Erp.Application/Billing/BillingService.cs new file mode 100644 index 0000000..416e90c --- /dev/null +++ b/src/Leiren.Erp.Application/Billing/BillingService.cs @@ -0,0 +1,843 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Billing; + +public sealed class BillingService(IBillingDbContext db) +{ + // ---------- Notices ---------- + + public async Task> ListNoticesAsync( + Guid? shippingBatchId, Guid? purchaseContractId, Guid? supplierId, string? status, string? search, + int page, int pageSize, CancellationToken ct = default) + { + var query = db.SupplierInvoiceNotices.AsNoTracking().Include(x => x.Lines).Include(x => x.Invoices).AsQueryable(); + if (shippingBatchId is not null) query = query.Where(x => x.ShippingBatchId == shippingBatchId.Value); + if (purchaseContractId is not null) query = query.Where(x => x.PurchaseContractId == purchaseContractId.Value); + if (supplierId is not null) query = query.Where(x => x.SupplierId == supplierId.Value); + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new BillingValidationException(nameof(status), "开票通知状态无效。"); + query = query.Where(x => x.Status == parsed); + } + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => + x.NoticeNo.Contains(term) || x.SupplierName.Contains(term) || + (x.ExportInvoiceNo != null && x.ExportInvoiceNo.Contains(term)) || + (x.PurchaseContractNo != null && x.PurchaseContractNo.Contains(term)) || + (x.ShipmentNo != null && x.ShipmentNo.Contains(term)) || + (x.SalesOrderNo != null && x.SalesOrderNo.Contains(term))); + } + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(x => new SupplierInvoiceNoticeListItemDto( + x.Id, x.NoticeNo, x.Status.ToString(), x.ShippingBatchId, x.ShipmentNo, x.ExportInvoiceNo, + x.PurchaseContractNo, x.SupplierName, x.Currency, x.TotalAmountIncludingTax, + x.InvoicedAmountIncludingTax, x.RemainingAmountIncludingTax, x.NoticeDate, x.UpdatedAt)).ToList(); + } + + public async Task GetNoticeAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadNoticeAsync(id, ct)); + + public async Task CreateNoticeAsync(CreateSupplierInvoiceNoticeRequest request, CancellationToken ct = default) + { + if (request.Lines is null || request.Lines.Count == 0) + throw new BillingValidationException(nameof(request.Lines), "开票通知至少需要一条明细。"); + var supplierName = TrimOrNull(request.SupplierName); + if (supplierName is null) + throw new BillingValidationException(nameof(request.SupplierName), "供应商不能为空。"); + + var noticeNo = string.IsNullOrWhiteSpace(request.NoticeNo) + ? await GenerateNoticeNoAsync(ct) + : request.NoticeNo.Trim(); + if (await db.SupplierInvoiceNotices.AnyAsync(x => x.NoticeNo == noticeNo, ct)) + throw new BillingConflictException($"开票通知号 {noticeNo} 已存在。"); + + var notice = new SupplierInvoiceNotice + { + NoticeNo = noticeNo, + ShippingBatchId = request.ShippingBatchId, + ShipmentNo = TrimOrNull(request.ShipmentNo), + BillOfLadingNo = TrimOrNull(request.BillOfLadingNo), + VesselName = TrimOrNull(request.VesselName), + VoyageNo = TrimOrNull(request.VoyageNo), + LoadingPort = TrimOrNull(request.LoadingPort), + DestinationPort = TrimOrNull(request.DestinationPort), + ShipmentDate = request.ShipmentDate, + ExportInvoiceNo = TrimOrNull(request.ExportInvoiceNo), + SalesOrderId = request.SalesOrderId, + SalesOrderNo = TrimOrNull(request.SalesOrderNo), + CustomerPoNo = TrimOrNull(request.CustomerPoNo), + PurchaseContractId = request.PurchaseContractId, + PurchaseContractNo = TrimOrNull(request.PurchaseContractNo), + SupplierId = request.SupplierId, + SupplierName = supplierName, + SupplierContact = TrimOrNull(request.SupplierContact), + SupplierPhone = TrimOrNull(request.SupplierPhone), + SupplierFax = TrimOrNull(request.SupplierFax), + SupplierAddress = TrimOrNull(request.SupplierAddress), + InvoiceTitle = TrimOrNull(request.InvoiceTitle), + InvoiceTitleAddress = TrimOrNull(request.InvoiceTitleAddress), + InvoiceTitlePhone = TrimOrNull(request.InvoiceTitlePhone), + InvoiceTitleBankName = TrimOrNull(request.InvoiceTitleBankName), + InvoiceTitleBankAccount = TrimOrNull(request.InvoiceTitleBankAccount), + InvoiceTitleTaxNo = TrimOrNull(request.InvoiceTitleTaxNo), + InvoiceTitleCustomsCode = TrimOrNull(request.InvoiceTitleCustomsCode), + Currency = NormalizeCurrency(request.Currency), + InvoicingRequirement = TrimOrNull(request.InvoicingRequirement), + StampRequirement = TrimOrNull(request.StampRequirement), + ContactName = TrimOrNull(request.ContactName), + MailingAddress = TrimOrNull(request.MailingAddress), + Remark = TrimOrNull(request.Remark), + NoticeDate = request.NoticeDate ?? DateOnly.FromDateTime(DateTime.UtcNow), + }; + notice.Lines = request.Lines.Select(x => BuildLine(notice.Id, x)).ToList(); + notice.BillingContract = BuildBillingContract(notice, request.BillingContractNo, request.SignedPlace, request.SignedDate, + quality: null, delivery: null, packaging: null, settlement: null, tax: null, ip: null); + db.SupplierInvoiceNotices.Add(notice); + await db.SaveChangesAsync(ct); + return ToDto(await LoadNoticeAsync(notice.Id, ct)); + } + + /// + /// One notice (and its billing contract) per supplier of a confirmed + /// shipping batch. Content comes from the batch's confirmed customs + /// declaration: every declaration line keeps the declared customs name and + /// unit; when several suppliers took part in a line (parts, packaging ...) + /// the declared quantity is split between them in proportion to their + /// tax-included purchase amounts for the shipped share, so the suppliers' + /// quantities add up exactly to the declaration. Each supplier invoices its + /// own purchase amount (unit price = amount / allocated quantity). + /// + public async Task GenerateFromShippingBatchAsync( + GenerateBillingNoticesRequest request, CancellationToken ct = default) + { + var batch = await db.ShippingBatches.AsNoTracking().Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == request.ShippingBatchId, ct) + ?? throw new BillingNotFoundException("出货批次不存在。"); + if (batch.Status != ShippingBatchStatus.Confirmed) + throw new BillingConflictException("只有已确认的出货批次可以生成供应商开票通知。"); + if (batch.Lines.Count == 0) + throw new BillingValidationException(nameof(batch.Lines), "出货批次没有出货明细,不能生成开票通知。"); + + var declaration = (await db.CustomsDeclarations.AsNoTracking().Include(x => x.Lines) + .Where(x => x.ShippingBatchId == batch.Id && x.Status == CustomsDeclarationStatus.Confirmed) + .ToListAsync(ct)) + .MaxBy(x => x.Version) + ?? throw new BillingConflictException("开票内容取自报关资料:请先在出货与报关中确认该批次的报关资料。"); + + var shipmentLines = batch.Lines.ToDictionary(x => x.Id); + var salesLineIds = batch.Lines.Select(x => x.SalesOrderLineId).Distinct().ToList(); + var orderedBySalesLine = await db.SalesOrderLines.AsNoTracking() + .Where(x => salesLineIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, x => x.Quantity, ct); + var tasksBySalesLine = (await db.PurchaseTasks.AsNoTracking() + .Where(x => salesLineIds.Contains(x.SalesOrderLineId) && x.Status != PurchaseTaskStatus.Cancelled) + .ToListAsync(ct)) + .GroupBy(x => x.SalesOrderLineId) + .ToDictionary(g => g.Key, g => g.ToList()); + var contractIds = tasksBySalesLine.Values.SelectMany(x => x) + .Select(x => x.PurchaseContractId).Where(x => x is not null).Select(x => x!.Value).Distinct().ToList(); + var contracts = await db.PurchaseContracts.AsNoTracking().Where(x => contractIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct); + + // Supplier key -> allocated lines. + var groups = new Dictionary Tasks, decimal Quantity, decimal Amount)>>(StringComparer.OrdinalIgnoreCase); + foreach (var declared in declaration.Lines.OrderBy(x => x.LineNumber)) + { + if (!shipmentLines.TryGetValue(declared.ShipmentLineId, out var shipment)) + throw new BillingValidationException(nameof(declaration.Lines), $"报关明细 {declared.LineNumber} 对应的出货明细不存在,请作废后重新生成报关资料。"); + if (!tasksBySalesLine.TryGetValue(shipment.SalesOrderLineId, out var tasks) || tasks.Count == 0) + throw new BillingValidationException(nameof(shipment.SalesOrderLineId), $"{shipment.InternalSku} 没有采购任务,无法确定供应商和采购价格。"); + var missingSupplier = tasks.FirstOrDefault(x => string.IsNullOrWhiteSpace(x.SupplierName)); + if (missingSupplier is not null) + throw new BillingValidationException(nameof(PurchaseTask.SupplierName), $"采购任务「{missingSupplier.ContentDescription}」没有供应商,不能生成开票通知。"); + + // Share of the order line that this shipment carries. + var ordered = orderedBySalesLine.GetValueOrDefault(shipment.SalesOrderLineId); + var share = ordered > 0 ? shipment.Quantity / ordered : 1m; + var bySupplier = tasks.GroupBy(SupplierKey).OrderBy(g => g.First().SupplierName).ToList(); + var amounts = bySupplier + .Select(g => decimal.Round(g.Sum(TaxIncludedAmount) * share, 2, MidpointRounding.AwayFromZero)) + .ToArray(); + var quantities = AllocateQuantity(declared.Quantity, amounts); + for (var i = 0; i < bySupplier.Count; i++) + { + if (!groups.TryGetValue(bySupplier[i].Key, out var list)) groups[bySupplier[i].Key] = list = []; + list.Add((declared, shipment, bySupplier[i].ToList(), quantities[i], amounts[i])); + } + } + + // Duplicate guard before creating anything, so a failed run creates no partial notices. + foreach (var group in groups.Values) + { + var first = group[0].Tasks[0]; + var exists = await db.SupplierInvoiceNotices.AnyAsync(x => + x.ShippingBatchId == batch.Id && x.Status != SupplierInvoiceNoticeStatus.Voided && + ((first.SupplierId != null && x.SupplierId == first.SupplierId) || (first.SupplierId == null && x.SupplierName == first.SupplierName)), ct); + if (exists) + throw new BillingConflictException($"出货批次 {batch.BatchNo} 已为供应商「{first.SupplierName}」生成过开票通知。"); + } + + var supplierIds = groups.Values.Select(x => x[0].Tasks[0].SupplierId).Where(x => x is not null).Select(x => x!.Value).ToList(); + var suppliers = await db.Suppliers.AsNoTracking().Where(x => supplierIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct); + // Invoice title / mailing details default to the last notice issued, so they are typed once. + var previous = (await db.SupplierInvoiceNotices.AsNoTracking() + .Where(x => x.InvoiceTitle != null) + .ToListAsync(ct)) + .MaxBy(x => x.CreatedAt); + string? Pick(string? value, string? fallback) => TrimOrNull(value) ?? TrimOrNull(fallback); + + var created = new List(); + foreach (var group in groups.Values.OrderBy(x => x[0].Tasks[0].SupplierName)) + { + var first = group[0].Tasks[0]; + var supplier = first.SupplierId is { } sid ? suppliers.GetValueOrDefault(sid) : null; + var contract = group.SelectMany(x => x.Tasks).Select(x => x.PurchaseContractId) + .Where(x => x is not null).Select(x => contracts.GetValueOrDefault(x!.Value)).FirstOrDefault(x => x is not null); + var notice = new SupplierInvoiceNotice + { + NoticeNo = await GenerateNoticeNoAsync(ct), + ShippingBatchId = batch.Id, + ShipmentNo = batch.BatchNo, + BillOfLadingNo = TrimOrNull(batch.BillOfLadingNo), + VesselName = TrimOrNull(batch.VesselName), + VoyageNo = TrimOrNull(batch.VoyageNo), + LoadingPort = TrimOrNull(batch.LoadingPort), + DestinationPort = TrimOrNull(batch.DestinationPort), + ShipmentDate = request.ShipmentDate ?? declaration.ExportDate ?? batch.ShipmentDate, + ExportInvoiceNo = TrimOrNull(request.ExportInvoiceNo) ?? TrimOrNull(declaration.InvoiceNo) ?? batch.BatchNo, + SalesOrderId = batch.SalesOrderId, + SalesOrderNo = TrimOrNull(batch.SalesOrderNo), + CustomerPoNo = TrimOrNull(batch.CustomerPoNo), + PurchaseContractId = contract?.Id, + PurchaseContractNo = contract?.ContractNo, + SupplierId = first.SupplierId, + SupplierName = first.SupplierName, + SupplierContact = contract?.SupplierContact ?? supplier?.ContactName, + SupplierPhone = contract?.SupplierPhone ?? supplier?.ContactPhone, + SupplierAddress = supplier?.Address, + InvoiceTitle = Pick(request.InvoiceTitle, previous?.InvoiceTitle), + InvoiceTitleAddress = Pick(request.InvoiceTitleAddress, previous?.InvoiceTitleAddress), + InvoiceTitlePhone = Pick(request.InvoiceTitlePhone, previous?.InvoiceTitlePhone), + InvoiceTitleBankName = Pick(request.InvoiceTitleBankName, previous?.InvoiceTitleBankName), + InvoiceTitleBankAccount = Pick(request.InvoiceTitleBankAccount, previous?.InvoiceTitleBankAccount), + InvoiceTitleTaxNo = Pick(request.InvoiceTitleTaxNo, previous?.InvoiceTitleTaxNo), + InvoiceTitleCustomsCode = Pick(request.InvoiceTitleCustomsCode, previous?.InvoiceTitleCustomsCode), + Currency = "CNY", + InvoicingRequirement = Pick(request.InvoicingRequirement, previous?.InvoicingRequirement), + StampRequirement = Pick(request.StampRequirement, previous?.StampRequirement), + ContactName = Pick(request.ContactName, previous?.ContactName), + MailingAddress = Pick(request.MailingAddress, previous?.MailingAddress), + NoticeDate = request.NoticeDate ?? DateOnly.FromDateTime(DateTime.UtcNow), + Lines = group.Select(item => + { + var main = item.Tasks.MaxBy(TaxIncludedAmount)!; + return new SupplierInvoiceNoticeLine + { + ShipmentLineId = item.Shipment.Id, + PurchaseTaskId = main.Id, + PurchaseContractId = main.PurchaseContractId, + PurchaseContractNo = main.PurchaseContractId is { } c ? contracts.GetValueOrDefault(c)?.ContractNo : null, + SalesOrderLineId = item.Shipment.SalesOrderLineId, + ProductId = main.ProductId, + InternalSku = item.Declared.InternalSku, + CustomerSku = item.Declared.CustomerSku, + // Name and unit exactly as declared to customs. + ProductNameZh = item.Declared.CustomsNameZh ?? item.Declared.ProductNameZh, + ProductNameEn = item.Declared.CustomsNameEn ?? item.Declared.ProductNameEn, + ContentDescription = item.Declared.CustomsNameZh ?? item.Declared.ProductNameZh, + Specification = TrimOrNull(item.Declared.DeclarationElements), + Quantity = item.Quantity, + Unit = item.Declared.Unit, + UnitPrice = item.Quantity > 0 ? decimal.Round(item.Amount / item.Quantity, 4, MidpointRounding.AwayFromZero) : 0, + TaxIncluded = true, + TaxRate = main.TaxRate, + }; + }).ToList(), + }; + foreach (var line in notice.Lines) ValidateLine(line); + notice.BillingContract = BuildBillingContract(notice, billingContractNo: null, request.SignedPlace, + request.SignedDate ?? request.NoticeDate, request.QualityTechnicalTerms, request.DeliveryTerms, + request.PackagingTerms, request.SettlementTerms, request.TaxTerms, request.IntellectualPropertyTerms); + foreach (var line in notice.Lines) line.SupplierInvoiceNotice = notice; + created.Add(notice); + db.SupplierInvoiceNotices.Add(notice); + } + + await db.SaveChangesAsync(ct); + var result = new List(); + foreach (var notice in created) result.Add(ToDto(await LoadNoticeAsync(notice.Id, ct))); + return new GenerateBillingNoticesResultDto(result); + } + + private static string SupplierKey(PurchaseTask task) => $"{task.SupplierId}|{task.SupplierName}"; + + private static decimal TaxIncludedAmount(PurchaseTask task) + => task.TaxIncluded ? task.Amount : decimal.Round(task.Amount * (1 + task.TaxRate / 100m), 2, MidpointRounding.AwayFromZero); + + /// + /// Splits a declared quantity between suppliers in proportion to their + /// amounts; the parts always add up to . Whole + /// quantities stay whole (largest remainder) and every supplier gets at + /// least one unit when there are enough; otherwise thousandths are used. + /// + internal static decimal[] AllocateQuantity(decimal total, IReadOnlyList weights) + { + var n = weights.Count; + if (n == 1) return [total]; + var sum = weights.Sum(); + var w = sum > 0 ? weights.ToArray() : Enumerable.Repeat(1m, n).ToArray(); + if (sum <= 0) sum = n; + var step = total == decimal.Truncate(total) && total >= n ? 1m : 0.001m; + + var raw = w.Select(x => total * x / sum).ToArray(); + var parts = raw.Select(x => decimal.Floor(x / step) * step).ToArray(); + var remaining = total - parts.Sum(); + foreach (var i in Enumerable.Range(0, n).OrderByDescending(i => raw[i] - parts[i]).ThenBy(i => i)) + { + if (remaining < step) break; + parts[i] += step; + remaining -= step; + } + parts[Array.IndexOf(parts, parts.Max())] += remaining; // sub-step rounding residue + for (var i = 0; i < n; i++) + { + if (parts[i] > 0) continue; + var donor = Array.IndexOf(parts, parts.Max()); + if (parts[donor] <= step) break; + parts[donor] -= step; + parts[i] += step; + } + return parts; + } + + public async Task UpdateNoticeAsync(Guid id, UpdateSupplierInvoiceNoticeRequest request, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(id, ct); + try { notice.EnsureDraft(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + + if (TrimOrNull(request.SupplierName) is { } name) notice.SupplierName = name; + notice.SupplierId = request.SupplierId ?? notice.SupplierId; + notice.SupplierContact = TrimOrNull(request.SupplierContact); + notice.SupplierPhone = TrimOrNull(request.SupplierPhone); + notice.SupplierFax = TrimOrNull(request.SupplierFax); + notice.SupplierAddress = TrimOrNull(request.SupplierAddress); + notice.ExportInvoiceNo = TrimOrNull(request.ExportInvoiceNo); + notice.PurchaseContractId = request.PurchaseContractId ?? notice.PurchaseContractId; + notice.PurchaseContractNo = TrimOrNull(request.PurchaseContractNo) ?? notice.PurchaseContractNo; + notice.InvoiceTitle = TrimOrNull(request.InvoiceTitle); + notice.InvoiceTitleAddress = TrimOrNull(request.InvoiceTitleAddress); + notice.InvoiceTitlePhone = TrimOrNull(request.InvoiceTitlePhone); + notice.InvoiceTitleBankName = TrimOrNull(request.InvoiceTitleBankName); + notice.InvoiceTitleBankAccount = TrimOrNull(request.InvoiceTitleBankAccount); + notice.InvoiceTitleTaxNo = TrimOrNull(request.InvoiceTitleTaxNo); + notice.InvoiceTitleCustomsCode = TrimOrNull(request.InvoiceTitleCustomsCode); + if (!string.IsNullOrWhiteSpace(request.Currency)) notice.Currency = NormalizeCurrency(request.Currency); + notice.InvoicingRequirement = TrimOrNull(request.InvoicingRequirement); + notice.StampRequirement = TrimOrNull(request.StampRequirement); + notice.ContactName = TrimOrNull(request.ContactName); + notice.MailingAddress = TrimOrNull(request.MailingAddress); + notice.Remark = TrimOrNull(request.Remark); + if (request.NoticeDate is { } noticeDate) notice.NoticeDate = noticeDate; + + if (request.Lines is not null) + { + if (request.Lines.Count == 0) + throw new BillingValidationException(nameof(request.Lines), "开票通知至少需要一条明细。"); + db.SupplierInvoiceNoticeLines.RemoveRange(notice.Lines); + notice.Lines = request.Lines.Select(x => BuildLine(notice.Id, x)).ToList(); + } + notice.Version++; + notice.Touch(); + SyncBillingContractParties(notice); + await db.SaveChangesAsync(ct); + return ToDto(await LoadNoticeAsync(notice.Id, ct)); + } + + public async Task NotifyAsync(Guid id, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(id, ct); + if (notice.Lines.Count == 0) + throw new BillingValidationException(nameof(notice.Lines), "开票通知没有明细,不能通知供应商。"); + if (string.IsNullOrWhiteSpace(notice.ExportInvoiceNo)) + throw new BillingValidationException(nameof(notice.ExportInvoiceNo), "外销发票号不能为空。"); + if (string.IsNullOrWhiteSpace(notice.InvoiceTitle)) + throw new BillingValidationException(nameof(notice.InvoiceTitle), "开票抬头不能为空。"); + if (notice.TotalAmountIncludingTax <= 0) + throw new BillingValidationException(nameof(notice.TotalAmountIncludingTax), "开票通知含税金额必须大于 0。"); + try { notice.Notify(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(notice); + } + + public async Task AwaitInvoiceAsync(Guid id, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(id, ct); + try { notice.MarkAwaitingInvoice(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(notice); + } + + public async Task VoidNoticeAsync(Guid id, VoidBillingRequest? request, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(id, ct); + try { notice.Void(request?.Reason); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + } + + /// + /// Re-splits the batch's declared quantities between its draft supplier + /// notices (single or multiple suppliers per customs item). Every item's + /// quantities must add up to the confirmed declaration; lines set to 0 + /// are removed and a notice left without lines is voided. + /// + public async Task> ReallocateBatchAsync( + Guid shippingBatchId, ReallocateBillingRequest request, CancellationToken ct = default) + { + var notices = await LoadBatchNoticesAsync(shippingBatchId, ct); + if (notices.Any(x => x.Status != SupplierInvoiceNoticeStatus.Draft)) + throw new BillingConflictException("该批次已有开票通知确认,不能再调整各供应商的开票数量。"); + var linesById = notices.SelectMany(x => x.Lines).ToDictionary(x => x.Id); + foreach (var item in request.Lines) + { + if (!linesById.TryGetValue(item.NoticeLineId, out var line)) + throw new BillingValidationException(nameof(request.Lines), "开票明细不属于该出货批次。"); + if (item.Quantity < 0 || item.AmountIncludingTax < 0) + throw new BillingValidationException(nameof(request.Lines), "开票数量和金额不能小于 0。"); + if (item.Quantity == 0 && item.AmountIncludingTax > 0) + throw new BillingValidationException(nameof(request.Lines), $"{line.ContentDescription}:数量为 0 时金额也必须为 0。"); + line.Quantity = item.Quantity; + line.TaxIncluded = true; + line.UnitPrice = item.Quantity > 0 ? decimal.Round(item.AmountIncludingTax / item.Quantity, 4, MidpointRounding.AwayFromZero) : 0; + } + + await EnsureDeclaredTotalsAsync(shippingBatchId, notices, ct); + + foreach (var notice in notices) + { + var removed = notice.Lines.Where(x => x.Quantity == 0).ToList(); + foreach (var line in removed) notice.Lines.Remove(line); + db.SupplierInvoiceNoticeLines.RemoveRange(removed); + if (notice.Lines.Count == 0) + { + notice.Void("开票数量已全部分配给其他供应商"); + continue; + } + notice.Version++; + notice.Touch(); + } + await db.SaveChangesAsync(ct); + return notices.Select(ToDto).ToList(); + } + + /// + /// Final confirmation of a batch's billing: every draft notice is locked + /// and sent to its supplier. Quantities must match the declaration. + /// + public async Task> ConfirmBatchAsync(Guid shippingBatchId, CancellationToken ct = default) + { + var notices = await LoadBatchNoticesAsync(shippingBatchId, ct); + var drafts = notices.Where(x => x.Status == SupplierInvoiceNoticeStatus.Draft).ToList(); + if (drafts.Count == 0) throw new BillingConflictException("该批次没有待确认的开票通知。"); + await EnsureDeclaredTotalsAsync(shippingBatchId, notices, ct); + foreach (var notice in drafts) + { + if (string.IsNullOrWhiteSpace(notice.InvoiceTitle)) + throw new BillingValidationException(nameof(notice.InvoiceTitle), $"{notice.SupplierName} 的开票通知没有发票抬头。"); + if (string.IsNullOrWhiteSpace(notice.ExportInvoiceNo)) + throw new BillingValidationException(nameof(notice.ExportInvoiceNo), $"{notice.SupplierName} 的开票通知没有外销发票号。"); + if (notice.TotalAmountIncludingTax <= 0) + throw new BillingValidationException(nameof(notice.TotalAmountIncludingTax), $"{notice.SupplierName} 的开票含税金额必须大于 0。"); + notice.Notify(); + } + await db.SaveChangesAsync(ct); + return notices.Select(ToDto).ToList(); + } + + private async Task> LoadBatchNoticesAsync(Guid shippingBatchId, CancellationToken ct) + { + var notices = await db.SupplierInvoiceNotices + .Include(x => x.Lines).Include(x => x.Invoices).Include(x => x.BillingContract) + .Where(x => x.ShippingBatchId == shippingBatchId && x.Status != SupplierInvoiceNoticeStatus.Voided) + .ToListAsync(ct); + if (notices.Count == 0) throw new BillingNotFoundException("该出货批次还没有开票通知。"); + return notices; + } + + /// Per customs item, the suppliers' invoiced quantities must equal the declared quantity. + private async Task EnsureDeclaredTotalsAsync(Guid shippingBatchId, IReadOnlyList notices, CancellationToken ct) + { + var declaration = (await db.CustomsDeclarations.AsNoTracking().Include(x => x.Lines) + .Where(x => x.ShippingBatchId == shippingBatchId && x.Status == CustomsDeclarationStatus.Confirmed) + .ToListAsync(ct)) + .MaxBy(x => x.Version); + if (declaration is null) return; + var invoiced = notices.SelectMany(x => x.Lines) + .Where(x => x.ShipmentLineId is not null) + .GroupBy(x => x.ShipmentLineId!.Value) + .ToDictionary(g => g.Key, g => g.Sum(x => x.Quantity)); + foreach (var line in declaration.Lines) + { + var total = invoiced.GetValueOrDefault(line.ShipmentLineId); + if (total != line.Quantity) + throw new BillingValidationException("Quantity", + $"{line.CustomsNameZh ?? line.ProductNameZh}:各供应商开票数量合计 {total:0.###} 与报关数量 {line.Quantity:0.###} 不一致。"); + } + } + + // ---------- Billing purchase/sales contract ---------- + + public async Task GetBillingContractAsync(Guid noticeId, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(noticeId, ct); + if (notice.BillingContract is null) + throw new BillingNotFoundException("开票通知尚未生成购销合同。"); + return ToDto(notice.BillingContract, notice); + } + + public async Task UpdateBillingContractAsync( + Guid noticeId, UpdateSupplierBillingContractRequest request, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(noticeId, ct); + try { notice.EnsureDraft(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + var contract = notice.BillingContract ?? throw new BillingNotFoundException("开票通知尚未生成购销合同。"); + if (TrimOrNull(request.ContractNo) is { } no) contract.ContractNo = no; + contract.SignedPlace = TrimOrNull(request.SignedPlace); + if (request.SignedDate is not null) contract.SignedDate = request.SignedDate; + if (TrimOrNull(request.BuyerName) is { } buyer) contract.BuyerName = buyer; + contract.BuyerAddress = TrimOrNull(request.BuyerAddress); + contract.BuyerPhone = TrimOrNull(request.BuyerPhone); + contract.BuyerFax = TrimOrNull(request.BuyerFax); + contract.BuyerBankName = TrimOrNull(request.BuyerBankName); + contract.BuyerBankAccount = TrimOrNull(request.BuyerBankAccount); + contract.BuyerTaxNo = TrimOrNull(request.BuyerTaxNo); + if (TrimOrNull(request.SellerName) is { } seller) contract.SellerName = seller; + contract.SellerAddress = TrimOrNull(request.SellerAddress); + contract.SellerContact = TrimOrNull(request.SellerContact); + contract.SellerPhone = TrimOrNull(request.SellerPhone); + contract.SellerFax = TrimOrNull(request.SellerFax); + contract.QualityTechnicalTerms = TrimOrNull(request.QualityTechnicalTerms); + contract.DeliveryTerms = TrimOrNull(request.DeliveryTerms); + contract.PackagingTerms = TrimOrNull(request.PackagingTerms); + contract.SettlementTerms = TrimOrNull(request.SettlementTerms); + contract.TaxTerms = TrimOrNull(request.TaxTerms); + contract.IntellectualPropertyTerms = TrimOrNull(request.IntellectualPropertyTerms); + contract.BreachTerms = TrimOrNull(request.BreachTerms); + contract.DisputeResolutionTerms = TrimOrNull(request.DisputeResolutionTerms); + contract.TradeSecurityTerms = TrimOrNull(request.TradeSecurityTerms); + contract.OtherTerms = TrimOrNull(request.OtherTerms); + contract.Version++; + contract.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(contract, notice); + } + + // ---------- Supplier invoices ---------- + + public async Task> ListInvoicesAsync( + Guid? noticeId, string? status, string? search, int page, int pageSize, CancellationToken ct = default) + { + var query = db.SupplierInvoices.AsNoTracking().Include(x => x.SupplierInvoiceNotice).AsQueryable(); + if (noticeId is not null) query = query.Where(x => x.SupplierInvoiceNoticeId == noticeId.Value); + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new BillingValidationException(nameof(status), "供应商发票状态无效。"); + query = query.Where(x => x.Status == parsed); + } + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => x.InvoiceNo.Contains(term) || x.SupplierName.Contains(term) || + (x.InvoiceCode != null && x.InvoiceCode.Contains(term))); + } + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(ToDto).ToList(); + } + + public async Task GetInvoiceAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadInvoiceAsync(id, ct)); + + public async Task RegisterInvoiceAsync(Guid noticeId, RegisterSupplierInvoiceRequest request, CancellationToken ct = default) + { + var notice = await LoadNoticeAsync(noticeId, ct); + var invoiceNo = TrimOrNull(request.InvoiceNo) + ?? throw new BillingValidationException(nameof(request.InvoiceNo), "发票号码不能为空。"); + if (request.AmountIncludingTax <= 0) + throw new BillingValidationException(nameof(request.AmountIncludingTax), "发票含税金额必须大于 0。"); + if (request.AmountExcludingTax < 0 || request.TaxAmount < 0) + throw new BillingValidationException(nameof(request.AmountExcludingTax), "发票不含税金额和税额不能小于 0。"); + if (Math.Abs(request.AmountExcludingTax + request.TaxAmount - request.AmountIncludingTax) > 0.01m) + throw new BillingValidationException(nameof(request.AmountIncludingTax), "发票不含税金额与税额之和必须等于含税金额。"); + if (request.TaxRate is < 0 or > 100) + throw new BillingValidationException(nameof(request.TaxRate), "税率必须在 0 到 100 之间(百分数)。"); + var currency = string.IsNullOrWhiteSpace(request.Currency) ? notice.Currency : NormalizeCurrency(request.Currency); + if (!string.Equals(currency, notice.Currency, StringComparison.OrdinalIgnoreCase)) + throw new BillingValidationException(nameof(request.Currency), "发票币种必须与开票通知币种一致。"); + if (notice.InvoicedAmountIncludingTax + request.AmountIncludingTax > notice.TotalAmountIncludingTax + 0.01m) + throw new BillingValidationException(nameof(request.AmountIncludingTax), + $"累计登记发票含税金额不能超过开票通知含税金额 {notice.TotalAmountIncludingTax}。"); + if (await db.SupplierInvoices.AnyAsync(x => x.InvoiceNo == invoiceNo && x.SupplierName == notice.SupplierName + && x.Status != SupplierInvoiceStatus.Voided, ct)) + throw new BillingConflictException($"供应商发票号 {invoiceNo} 已登记。"); + + try { notice.MarkInvoiceReceived(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + + var invoice = new SupplierInvoice + { + SupplierInvoiceNoticeId = notice.Id, + InvoiceNo = invoiceNo, + InvoiceCode = TrimOrNull(request.InvoiceCode), + InvoiceType = ParseInvoiceType(request.InvoiceType), + SupplierId = notice.SupplierId, + SupplierName = notice.SupplierName, + InvoiceDate = request.InvoiceDate ?? request.ReceivedDate ?? DateOnly.FromDateTime(DateTime.UtcNow), + ReceivedDate = request.ReceivedDate ?? DateOnly.FromDateTime(DateTime.UtcNow), + Currency = currency, + TaxRate = request.TaxRate, + AmountExcludingTax = decimal.Round(request.AmountExcludingTax, 2, MidpointRounding.AwayFromZero), + TaxAmount = decimal.Round(request.TaxAmount, 2, MidpointRounding.AwayFromZero), + AmountIncludingTax = decimal.Round(request.AmountIncludingTax, 2, MidpointRounding.AwayFromZero), + AttachmentReference = TrimOrNull(request.AttachmentReference), + Remark = TrimOrNull(request.Remark), + }; + db.SupplierInvoices.Add(invoice); + await db.SaveChangesAsync(ct); + return ToDto(await LoadInvoiceAsync(invoice.Id, ct)); + } + + public async Task HandInvoiceToFinanceAsync(Guid id, HandSupplierInvoiceToFinanceRequest? request, CancellationToken ct = default) + { + var invoice = await LoadInvoiceAsync(id, ct); + var notice = invoice.SupplierInvoiceNotice ?? await LoadNoticeAsync(invoice.SupplierInvoiceNoticeId, ct); + try { invoice.HandToFinance(request?.HandedBy); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + if (notice.Status == SupplierInvoiceNoticeStatus.InvoiceReceived) + { + try { notice.MarkHandedToFinance(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + } + await db.SaveChangesAsync(ct); + return ToDto(await LoadInvoiceAsync(id, ct)); + } + + public async Task CompleteInvoiceAsync(Guid id, CancellationToken ct = default) + { + var invoice = await LoadInvoiceAsync(id, ct); + var notice = invoice.SupplierInvoiceNotice ?? await LoadNoticeAsync(invoice.SupplierInvoiceNoticeId, ct); + try { invoice.Complete(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + var fullyInvoiced = notice.RemainingAmountIncludingTax <= 0.01m; + var allCompleted = notice.Invoices + .Where(x => x.Status != SupplierInvoiceStatus.Voided) + .All(x => x.Status == SupplierInvoiceStatus.Completed); + if (fullyInvoiced && allCompleted && notice.Status == SupplierInvoiceNoticeStatus.HandedToFinance) + { + try { notice.MarkCompleted(); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + } + await db.SaveChangesAsync(ct); + return ToDto(await LoadInvoiceAsync(id, ct)); + } + + public async Task VoidInvoiceAsync(Guid id, VoidBillingRequest? request, CancellationToken ct = default) + { + var invoice = await LoadInvoiceAsync(id, ct); + var notice = invoice.SupplierInvoiceNotice ?? await LoadNoticeAsync(invoice.SupplierInvoiceNoticeId, ct); + try { invoice.Void(request?.Reason); } catch (InvalidOperationException ex) { throw new BillingConflictException(ex.Message); } + notice.Invoices = notice.Invoices.Count > 0 ? notice.Invoices : [.. await db.SupplierInvoices.Where(x => x.SupplierInvoiceNoticeId == notice.Id).ToListAsync(ct)]; + notice.RevertAfterInvoiceVoid(); + await db.SaveChangesAsync(ct); + } + + // ---------- Helpers ---------- + + private SupplierInvoiceNoticeLine BuildLine(Guid noticeId, BillingNoticeLineRequest request) + { + var line = new SupplierInvoiceNoticeLine + { + SupplierInvoiceNoticeId = noticeId, + ShipmentLineId = request.ShipmentLineId, + PurchaseTaskId = request.PurchaseTaskId, + PurchaseContractId = request.PurchaseContractId, + PurchaseContractNo = TrimOrNull(request.PurchaseContractNo), + SalesOrderLineId = request.SalesOrderLineId, + ProductId = request.ProductId, + InternalSku = TrimOrNull(request.InternalSku), + CustomerSku = TrimOrNull(request.CustomerSku), + ProductNameZh = TrimOrNull(request.ProductNameZh) ?? TrimOrNull(request.ContentDescription) ?? string.Empty, + ProductNameEn = TrimOrNull(request.ProductNameEn), + ContentDescription = TrimOrNull(request.ContentDescription) ?? TrimOrNull(request.ProductNameZh) ?? string.Empty, + Specification = TrimOrNull(request.Specification), + Quantity = request.Quantity, + Unit = TrimOrNull(request.Unit) ?? string.Empty, + UnitPrice = request.UnitPrice, + TaxIncluded = request.TaxIncluded, + TaxRate = request.TaxRate, + }; + ValidateLine(line); + return line; + } + + private static void ValidateLine(SupplierInvoiceNoticeLine line) + { + if (line.Quantity <= 0) + throw new BillingValidationException(nameof(line.Quantity), "开票数量必须大于 0。"); + if (line.UnitPrice < 0) + throw new BillingValidationException(nameof(line.UnitPrice), "开票单价不能小于 0。"); + if (line.TaxRate is < 0 or > 100) + throw new BillingValidationException(nameof(line.TaxRate), "税率必须在 0 到 100 之间(百分数)。"); + if (string.IsNullOrWhiteSpace(line.Unit)) + throw new BillingValidationException(nameof(line.Unit), "开票单位不能为空,必须使用规范中文单位。"); + if (string.IsNullOrWhiteSpace(line.ContentDescription)) + throw new BillingValidationException(nameof(line.ContentDescription), "开票品名不能为空。"); + if (string.IsNullOrWhiteSpace(line.ProductNameZh)) + line.ProductNameZh = line.ContentDescription; + } + + private static SupplierBillingContract BuildBillingContract( + SupplierInvoiceNotice notice, string? billingContractNo, string? signedPlace, DateOnly? signedDate, + string? quality, string? delivery, string? packaging, string? settlement, string? tax, string? ip) + => new() + { + SupplierInvoiceNotice = notice, + ContractNo = TrimOrNull(billingContractNo) ?? notice.PurchaseContractNo ?? notice.NoticeNo, + PurchaseContractNo = notice.PurchaseContractNo, + ExportInvoiceNo = notice.ExportInvoiceNo, + BuyerName = notice.InvoiceTitle ?? string.Empty, + BuyerAddress = notice.InvoiceTitleAddress, + BuyerPhone = notice.InvoiceTitlePhone, + BuyerBankName = notice.InvoiceTitleBankName, + BuyerBankAccount = notice.InvoiceTitleBankAccount, + BuyerTaxNo = notice.InvoiceTitleTaxNo, + SellerSupplierId = notice.SupplierId, + SellerName = notice.SupplierName, + SellerAddress = notice.SupplierAddress, + SellerContact = notice.SupplierContact, + SellerPhone = notice.SupplierPhone, + SellerFax = notice.SupplierFax, + SignedPlace = TrimOrNull(signedPlace), + SignedDate = signedDate ?? notice.NoticeDate, + Currency = notice.Currency, + QualityTechnicalTerms = TrimOrNull(quality), + DeliveryTerms = TrimOrNull(delivery), + PackagingTerms = TrimOrNull(packaging), + SettlementTerms = TrimOrNull(settlement), + TaxTerms = TrimOrNull(tax), + IntellectualPropertyTerms = TrimOrNull(ip), + }; + + private static void SyncBillingContractParties(SupplierInvoiceNotice notice) + { + if (notice.BillingContract is null) return; + var c = notice.BillingContract; + c.PurchaseContractNo = notice.PurchaseContractNo; + c.ExportInvoiceNo = notice.ExportInvoiceNo; + c.BuyerName = notice.InvoiceTitle ?? c.BuyerName; + c.BuyerAddress = notice.InvoiceTitleAddress; + c.BuyerPhone = notice.InvoiceTitlePhone; + c.BuyerBankName = notice.InvoiceTitleBankName; + c.BuyerBankAccount = notice.InvoiceTitleBankAccount; + c.BuyerTaxNo = notice.InvoiceTitleTaxNo; + c.SellerSupplierId = notice.SupplierId; + c.SellerName = notice.SupplierName; + c.SellerAddress = notice.SupplierAddress; + c.SellerContact = notice.SupplierContact; + c.SellerPhone = notice.SupplierPhone; + c.SellerFax = notice.SupplierFax; + c.Currency = notice.Currency; + c.Touch(); + } + + private async Task GenerateNoticeNoAsync(CancellationToken ct) + { + for (var attempt = 0; attempt < 5; attempt++) + { + var candidate = $"BIN-{DateTimeOffset.UtcNow:yyyyMMddHHmmss}-{Guid.NewGuid().ToString("N")[..4].ToUpperInvariant()}"; + if (!await db.SupplierInvoiceNotices.AnyAsync(x => x.NoticeNo == candidate, ct)) + return candidate; + } + return $"BIN-{Guid.NewGuid():N}"; + } + + private async Task LoadNoticeAsync(Guid id, CancellationToken ct) + => await db.SupplierInvoiceNotices + .Include(x => x.Lines) + .Include(x => x.Invoices) + .Include(x => x.BillingContract) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new BillingNotFoundException("开票通知不存在。"); + + private async Task LoadInvoiceAsync(Guid id, CancellationToken ct) + => await db.SupplierInvoices + .Include(x => x.SupplierInvoiceNotice!) + .ThenInclude(x => x.Lines) + .Include(x => x.SupplierInvoiceNotice!) + .ThenInclude(x => x.Invoices) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new BillingNotFoundException("供应商发票不存在。"); + + private static SupplierInvoiceType ParseInvoiceType(string? value) + => string.IsNullOrWhiteSpace(value) + ? SupplierInvoiceType.VatSpecial + : Enum.TryParse(value, ignoreCase: true, out var parsed) + ? parsed + : throw new BillingValidationException(nameof(value), "发票类型无效。"); + + private static string NormalizeCurrency(string? currency) + { + var normalized = string.IsNullOrWhiteSpace(currency) ? "CNY" : currency.Trim().ToUpperInvariant(); + if (normalized.Length != 3) + throw new BillingValidationException(nameof(currency), "币种必须是 3 位代码,如 CNY、USD。"); + return normalized; + } + + private static string? TrimOrNull(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static SupplierInvoiceNoticeLineDto ToDto(SupplierInvoiceNoticeLine l) => new( + l.Id, l.SupplierInvoiceNoticeId, l.ShipmentLineId, l.PurchaseTaskId, l.PurchaseContractId, + l.PurchaseContractNo, l.SalesOrderLineId, l.ProductId, l.InternalSku, l.CustomerSku, + l.ProductNameZh, l.ProductNameEn, l.ContentDescription, l.Specification, l.Quantity, l.Unit, + l.UnitPrice, l.TaxIncluded, l.TaxRate, l.TaxIncludedUnitPrice, l.TaxExcludingUnitPrice, + l.AmountExcludingTax, l.TaxAmount, l.AmountIncludingTax); + + private static SupplierInvoiceNoticeDto ToDto(SupplierInvoiceNotice n) => new( + n.Id, n.NoticeNo, n.Status.ToString(), n.Version, n.ShippingBatchId, n.ShipmentNo, n.BillOfLadingNo, + n.VesselName, n.VoyageNo, n.LoadingPort, n.DestinationPort, n.ShipmentDate, n.ExportInvoiceNo, + n.SalesOrderId, n.SalesOrderNo, n.CustomerPoNo, n.PurchaseContractId, n.PurchaseContractNo, + n.SupplierId, n.SupplierName, n.SupplierContact, n.SupplierPhone, n.SupplierFax, n.SupplierAddress, + n.InvoiceTitle, n.InvoiceTitleAddress, n.InvoiceTitlePhone, n.InvoiceTitleBankName, + n.InvoiceTitleBankAccount, n.InvoiceTitleTaxNo, n.InvoiceTitleCustomsCode, n.Currency, + n.InvoicingRequirement, n.StampRequirement, n.ContactName, n.MailingAddress, n.Remark, n.NoticeDate, + n.TotalQuantity, n.TotalAmountExcludingTax, n.TotalTaxAmount, n.TotalAmountIncludingTax, + n.InvoicedAmountIncludingTax, n.RemainingAmountIncludingTax, + n.CreatedAt, n.UpdatedAt, n.NotifiedAt, n.AwaitingInvoiceAt, n.InvoiceReceivedAt, + n.HandedToFinanceAt, n.CompletedAt, n.VoidedAt, n.VoidReason, + n.Lines.OrderBy(x => x.ProductNameZh).Select(ToDto).ToList(), + n.Invoices.OrderBy(x => x.InvoiceDate).Select(ToDto).ToList(), + n.BillingContract is null ? null : ToDto(n.BillingContract, n)); + + private static SupplierBillingContractDto ToDto(SupplierBillingContract c, SupplierInvoiceNotice notice) => new( + c.Id, c.SupplierInvoiceNoticeId, c.ContractNo, c.PurchaseContractNo, c.ExportInvoiceNo, c.Version, + c.BuyerName, c.BuyerAddress, c.BuyerPhone, c.BuyerFax, c.BuyerBankName, c.BuyerBankAccount, c.BuyerTaxNo, + c.SellerSupplierId, c.SellerName, c.SellerAddress, c.SellerContact, c.SellerPhone, c.SellerFax, + c.SignedPlace, c.SignedDate, c.Currency, c.QualityTechnicalTerms, c.DeliveryTerms, c.PackagingTerms, + c.SettlementTerms, c.TaxTerms, c.IntellectualPropertyTerms, c.BreachTerms, c.DisputeResolutionTerms, + c.TradeSecurityTerms, c.OtherTerms, + notice.TotalAmountExcludingTax, notice.TotalTaxAmount, notice.TotalAmountIncludingTax, + c.CreatedAt, c.UpdatedAt, + notice.Lines.OrderBy(x => x.ProductNameZh).Select(ToDto).ToList()); + + private static SupplierInvoiceDto ToDto(SupplierInvoice i) => new( + i.Id, i.SupplierInvoiceNoticeId, i.SupplierInvoiceNotice?.NoticeNo ?? string.Empty, i.InvoiceNo, + i.InvoiceCode, i.InvoiceType.ToString(), i.SupplierId, i.SupplierName, i.InvoiceDate, i.ReceivedDate, + i.Currency, i.TaxRate, i.AmountExcludingTax, i.TaxAmount, i.AmountIncludingTax, i.Status.ToString(), + i.AttachmentReference, i.Remark, i.CreatedAt, i.UpdatedAt, i.HandedToFinanceAt, i.HandedToFinanceBy, + i.CompletedAt, i.VoidedAt, i.VoidReason); +} diff --git a/src/Leiren.Erp.Application/Billing/IBillingDbContext.cs b/src/Leiren.Erp.Application/Billing/IBillingDbContext.cs new file mode 100644 index 0000000..aa8e050 --- /dev/null +++ b/src/Leiren.Erp.Application/Billing/IBillingDbContext.cs @@ -0,0 +1,26 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Billing; + +/// +/// EF Core boundary for the Billing module; implemented by Infrastructure. +/// Shipping/Purchasing sets are read only to snapshot confirmed-shipment and +/// purchase-task data into a notice at generation time. +/// +public interface IBillingDbContext +{ + DbSet SupplierInvoiceNotices { get; } + DbSet SupplierInvoiceNoticeLines { get; } + DbSet SupplierInvoices { get; } + DbSet SupplierBillingContracts { get; } + DbSet ShippingBatches { get; } + DbSet ShipmentLines { get; } + DbSet PurchaseTasks { get; } + DbSet PurchaseContracts { get; } + DbSet SalesOrderLines { get; } + DbSet Suppliers { get; } + DbSet CustomsDeclarations { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Catalog/CatalogExceptions.cs b/src/Leiren.Erp.Application/Catalog/CatalogExceptions.cs new file mode 100644 index 0000000..278d79c --- /dev/null +++ b/src/Leiren.Erp.Application/Catalog/CatalogExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Catalog; + +public sealed class CatalogNotFoundException(string message) : Exception(message); + +public sealed class CatalogConflictException(string message) : Exception(message); + +public sealed class CatalogValidationException(IReadOnlyDictionary errors) + : Exception("产品资料校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public CatalogValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Catalog/ICatalogDbContext.cs b/src/Leiren.Erp.Application/Catalog/ICatalogDbContext.cs new file mode 100644 index 0000000..d5fe6d4 --- /dev/null +++ b/src/Leiren.Erp.Application/Catalog/ICatalogDbContext.cs @@ -0,0 +1,16 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Catalog; + +/// EF Core boundary for the Catalog module; implemented by Infrastructure. +public interface ICatalogDbContext +{ + DbSet Products { get; } + DbSet Suppliers { get; } + DbSet ProductParts { get; } + DbSet ProductSupplierQuotes { get; } + DbSet ProductChangeLogs { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Catalog/ProductService.cs b/src/Leiren.Erp.Application/Catalog/ProductService.cs new file mode 100644 index 0000000..c67d0d9 --- /dev/null +++ b/src/Leiren.Erp.Application/Catalog/ProductService.cs @@ -0,0 +1,727 @@ +using System.Globalization; +using System.Text.Json; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Catalog; + +public sealed class ProductService(ICatalogDbContext db) +{ + public async Task> ListAsync( + string? search, string? status, int page, int pageSize, CancellationToken ct = default) + { + var query = db.Products.AsNoTracking().AsQueryable(); + + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + { + throw new CatalogValidationException(nameof(status), "产品状态无效。"); + } + + query = query.Where(x => x.Status == parsed); + } + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => + x.InternalSku.Contains(term) || + x.NameZh.Contains(term) || + x.NameEn.Contains(term) || + (x.HsCode != null && x.HsCode.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + + var items = await query + .OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize) + .Take(pageSize) + .ToListAsync(ct); + + return items.Select(ToListItem).ToList(); + } + + public async Task GetAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadAsync(id, ct)); + + public async Task GetCompletenessAsync(Guid id, CancellationToken ct = default) + => BuildCompleteness(await LoadAsync(id, ct)); + + public async Task> ListHistoryAsync(Guid id, CancellationToken ct = default) + { + if (!await db.Products.AnyAsync(x => x.Id == id, ct)) + throw new CatalogNotFoundException("产品不存在。"); + var entries = await db.ProductChangeLogs.AsNoTracking() + .Where(x => x.ProductId == id) + .OrderByDescending(x => x.Id) + .ToListAsync(ct); + return entries.Select(ToDto).ToList(); + } + + /// + /// Completeness per docs/02 §3: only the basic publish fields are + /// required/blocking; purchase, shipping and customs fields are advisory + /// per-use groups and never block publish. + /// + public static ProductCompletenessDto BuildCompleteness(Product product) + { + var required = product.GetMissingPublishFields(); + + var purchase = new List(); + if (product.SupplierQuotes.Count == 0) purchase.Add("SupplierQuote"); + if (string.IsNullOrWhiteSpace(product.PurchaseRequirement)) purchase.Add(nameof(Product.PurchaseRequirement)); + + var shipping = new List(); + if (product.PackingRate is null) shipping.Add(nameof(Product.PackingRate)); + if (product.CartonLength is null) shipping.Add(nameof(Product.CartonLength)); + if (product.CartonWidth is null) shipping.Add(nameof(Product.CartonWidth)); + if (product.CartonHeight is null) shipping.Add(nameof(Product.CartonHeight)); + if (product.CartonGrossWeight is null) shipping.Add(nameof(Product.CartonGrossWeight)); + if (product.CartonNetWeight is null) shipping.Add(nameof(Product.CartonNetWeight)); + + var customs = new List(); + if (string.IsNullOrWhiteSpace(product.HsCode)) customs.Add(nameof(Product.HsCode)); + if (string.IsNullOrWhiteSpace(product.CustomsNameZh)) customs.Add(nameof(Product.CustomsNameZh)); + if (string.IsNullOrWhiteSpace(product.CustomsNameEn)) customs.Add(nameof(Product.CustomsNameEn)); + if (string.IsNullOrWhiteSpace(product.CustomsUnit)) customs.Add(nameof(Product.CustomsUnit)); + if (string.IsNullOrWhiteSpace(product.DeclarationElements)) customs.Add(nameof(Product.DeclarationElements)); + + var optional = purchase.Concat(shipping).Concat(customs).ToList(); + var blocking = required.Select(field => $"发布前必须填写{field}。").ToList(); + return new ProductCompletenessDto( + product.Id, product.Status.ToString(), product.Version, + product.Status == ProductStatus.Draft && required.Count == 0, + required, purchase, shipping, customs, optional, blocking); + } + + public async Task CreateDraftAsync(SaveProductDraftRequest request, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = new Product { Status = ProductStatus.Draft, Version = 1 }; + ApplyDraft(product, request); + await EnsureSkuAvailableAsync(product.InternalSku, excludeId: null, ct); + db.Products.Add(product); + AddChangeLog(product, ProductChangeAction.DraftCreated, NonEmptyFields(Snapshot(product)), + $"创建产品草稿 {product.InternalSku} V{product.Version}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(product); + } + + public async Task UpdateDraftAsync(Guid id, SaveProductDraftRequest request, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadAsync(id, ct); + + if (product.Status == ProductStatus.Published) + { + // Editing a published product creates the next draft version; the + // published version (and anything referencing it) stays untouched. + var draft = CopyAsNewDraft(product); + var before = Snapshot(draft); + ApplyDraft(draft, request); + await EnsureSkuAvailableAsync(draft.InternalSku, draft.Id, ct); + db.Products.Add(draft); + AddChangeLog(draft, ProductChangeAction.DraftVersionCreated, ChangedFields(before, Snapshot(draft)), + $"基于已发布版本 V{product.Version} 创建新草稿 V{draft.Version}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(await LoadAsync(draft.Id, ct)); + } + + if (product.Status != ProductStatus.Draft) + { + throw new CatalogConflictException("已停用或历史版本的产品不能编辑,请基于已发布版本建立新草稿。"); + } + + var beforeSave = Snapshot(product); + ApplyDraft(product, request); + await EnsureSkuAvailableAsync(product.InternalSku, product.Id, ct); + product.Touch(); + AddChangeLog(product, ProductChangeAction.DraftSaved, ChangedFields(beforeSave, Snapshot(product)), + $"保存产品草稿 {product.InternalSku} V{product.Version}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(product); + } + + public async Task PublishAsync(Guid id, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadAsync(id, ct); + if (product.Status != ProductStatus.Draft) + { + throw new CatalogConflictException("只有草稿状态的产品可以发布。"); + } + + // Only the required basic fields block publish (docs/02 §3); + // purchase/shipping/customs gaps are advisory completeness warnings. + var completeness = BuildCompleteness(product); + if (completeness.RequiredMissingFields.Count > 0) + { + throw new CatalogValidationException(completeness.RequiredMissingFields.ToDictionary( + field => field, + field => new[] { $"发布前必须填写{field}。" })); + } + + var currentPublished = await db.Products + .Where(x => x.InternalSku == product.InternalSku + && x.Status == ProductStatus.Published + && x.Id != product.Id) + .ToListAsync(ct); + foreach (var old in currentPublished) + { + old.Status = ProductStatus.Superseded; + old.Touch(); + AddChangeLog(old, ProductChangeAction.Superseded, ["Status"], + $"版本 V{old.Version} 已被 V{product.Version} 取代。", actorUserId, actorUserName); + } + + product.Publish(); + AddChangeLog(product, ProductChangeAction.Published, ["Status"], + $"发布产品 {product.InternalSku} V{product.Version}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(product); + } + + public async Task DisableAsync(Guid id, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadAsync(id, ct); + try + { + product.Disable(); + } + catch (InvalidOperationException ex) + { + throw new CatalogConflictException(ex.Message); + } + + AddChangeLog(product, ProductChangeAction.Disabled, ["Status"], + $"停用产品 {product.InternalSku} V{product.Version}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(product); + } + + public async Task DeleteDraftAsync(Guid id, CancellationToken ct = default) + { + var product = await LoadAsync(id, ct); + if (product.Status != ProductStatus.Draft) + { + throw new CatalogConflictException("只有未发布的草稿产品可以删除;已发布产品只能停用。"); + } + + db.Products.Remove(product); + await db.SaveChangesAsync(ct); + } + + public async Task AddPartAsync(Guid productId, SaveProductPartRequest request, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadDraftAsync(productId, ct); + var part = new ProductPart { ProductId = product.Id }; + ApplyPart(part, request); + await ValidateComponentAsync(part, product.Id, ct); + db.ProductParts.Add(part); + product.Touch(); + AddChangeLog(product, ProductChangeAction.PartAdded, NonEmptyFields(Snapshot(part)), + $"添加零件 {part.Name}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(part); + } + + public async Task UpdatePartAsync( + Guid productId, Guid partId, SaveProductPartRequest request, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadDraftAsync(productId, ct); + var part = product.Parts.SingleOrDefault(x => x.Id == partId) + ?? throw new CatalogNotFoundException("产品零件不存在。"); + var before = Snapshot(part); + ApplyPart(part, request); + await ValidateComponentAsync(part, product.Id, ct); + part.UpdatedAt = DateTimeOffset.UtcNow; + product.Touch(); + AddChangeLog(product, ProductChangeAction.PartUpdated, ChangedFields(before, Snapshot(part)), + $"修改零件 {part.Name}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(part); + } + + public async Task DeletePartAsync(Guid productId, Guid partId, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadDraftAsync(productId, ct); + var part = product.Parts.SingleOrDefault(x => x.Id == partId) + ?? throw new CatalogNotFoundException("产品零件不存在。"); + var summary = $"删除零件 {part.Name}。"; + db.ProductParts.Remove(part); + product.Touch(); + AddChangeLog(product, ProductChangeAction.PartDeleted, ["Name"], summary, actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + } + + public async Task AddQuoteAsync( + Guid productId, CreateSupplierQuoteRequest request, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadDraftAsync(productId, ct); + var values = await ResolveQuoteValuesAsync(product, request, ct); + var quote = new ProductSupplierQuote { ProductId = product.Id }; + ApplyQuote(quote, request, values); + ClearOtherDefaults(product, quote); + + db.ProductSupplierQuotes.Add(quote); + product.Touch(); + AddChangeLog(product, ProductChangeAction.QuoteAdded, + ["SupplierName", "UnitPrice", "Currency"], + $"添加供应商报价 {quote.SupplierName} {quote.UnitPrice.ToString(CultureInfo.InvariantCulture)} {quote.Currency}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(quote); + } + + public async Task UpdateQuoteAsync( + Guid productId, Guid quoteId, CreateSupplierQuoteRequest request, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadDraftAsync(productId, ct); + var quote = product.SupplierQuotes.SingleOrDefault(x => x.Id == quoteId) + ?? throw new CatalogNotFoundException("供应商报价不存在。"); + var before = Snapshot(quote); + var values = await ResolveQuoteValuesAsync(product, request, ct); + ApplyQuote(quote, request, values); + ClearOtherDefaults(product, quote); + product.Touch(); + AddChangeLog(product, ProductChangeAction.QuoteUpdated, ChangedFields(before, Snapshot(quote)), + $"修改供应商报价 {quote.SupplierName} {quote.UnitPrice.ToString(CultureInfo.InvariantCulture)} {quote.Currency}。", actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + return ToDto(quote); + } + + public async Task DeleteQuoteAsync(Guid productId, Guid quoteId, CancellationToken ct = default, Guid? actorUserId = null, string? actorUserName = null) + { + var product = await LoadDraftAsync(productId, ct); + var quote = product.SupplierQuotes.SingleOrDefault(x => x.Id == quoteId) + ?? throw new CatalogNotFoundException("供应商报价不存在。"); + var summary = $"删除供应商报价 {quote.SupplierName} {quote.UnitPrice.ToString(CultureInfo.InvariantCulture)} {quote.Currency}。"; + db.ProductSupplierQuotes.Remove(quote); + product.Touch(); + AddChangeLog(product, ProductChangeAction.QuoteDeleted, + ["SupplierName", "UnitPrice", "Currency"], summary, actorUserId, actorUserName); + await db.SaveChangesAsync(ct); + } + + private readonly record struct QuoteValues( + Guid? ProductPartId, string SupplierName, PurchaseContentType ContentType, string Currency, string PricingUnit); + + private async Task ResolveQuoteValuesAsync( + Product product, CreateSupplierQuoteRequest request, CancellationToken ct) + { + // When a master supplier is selected, its current name becomes the quote + // snapshot; free-text names remain allowed for quotes without a master id. + var supplierName = request.SupplierName?.Trim(); + if (request.SupplierId is { } supplierId) + { + var supplier = await db.Suppliers.AsNoTracking().SingleOrDefaultAsync(x => x.Id == supplierId, ct) + ?? throw new CatalogValidationException(nameof(request.SupplierId), "供应商不存在。"); + if (!supplier.IsActive) + throw new CatalogValidationException(nameof(request.SupplierId), "供应商已停用,不能新增报价。"); + supplierName = supplier.Name; + } + + if (string.IsNullOrWhiteSpace(supplierName)) + { + throw new CatalogValidationException(nameof(request.SupplierName), "供应商名称不能为空。"); + } + + if (request.UnitPrice < 0) + { + throw new CatalogValidationException(nameof(request.UnitPrice), "单价不能小于 0。"); + } + + if (request.TaxRate is < 0 or > 100) + { + throw new CatalogValidationException(nameof(request.TaxRate), "税率必须在 0 到 100 之间(百分数)。"); + } + + if (request.EffectiveFrom is not null && request.EffectiveTo is not null + && request.EffectiveTo < request.EffectiveFrom) + { + throw new CatalogValidationException(nameof(request.EffectiveTo), "失效日期不能早于生效日期。"); + } + + Guid? productPartId = null; + if (request.ProductPartId is not null) + { + var part = product.Parts.SingleOrDefault(x => x.Id == request.ProductPartId.Value) + ?? throw new CatalogValidationException(nameof(request.ProductPartId), "零件不属于当前产品。"); + productPartId = part.Id; + } + + var currency = string.IsNullOrWhiteSpace(request.Currency) ? "CNY" : request.Currency.Trim().ToUpperInvariant(); + if (currency.Length != 3) + { + throw new CatalogValidationException(nameof(request.Currency), "币种必须是 3 位代码,如 CNY、USD。"); + } + + return new QuoteValues( + productPartId, + supplierName, + ParseEnum(request.ContentType, PurchaseContentType.Finished, nameof(request.ContentType)), + currency, + string.IsNullOrWhiteSpace(request.PricingUnit) ? product.Unit : request.PricingUnit.Trim()); + } + + private static void ApplyQuote(ProductSupplierQuote quote, CreateSupplierQuoteRequest request, QuoteValues values) + { + quote.ProductPartId = values.ProductPartId; + quote.SupplierId = request.SupplierId; + quote.SupplierName = values.SupplierName; + quote.SupplierProductName = TrimOrNull(request.SupplierProductName); + quote.SupplierProductSku = TrimOrNull(request.SupplierProductSku); + quote.ContentType = values.ContentType; + quote.UnitPrice = request.UnitPrice; + quote.Currency = values.Currency; + quote.PricingUnit = values.PricingUnit; + quote.TaxIncluded = request.TaxIncluded; + quote.TaxRate = request.TaxRate; + quote.MinimumOrderQuantity = request.MinimumOrderQuantity; + quote.LeadTimeDays = request.LeadTimeDays; + quote.EffectiveFrom = request.EffectiveFrom; + quote.EffectiveTo = request.EffectiveTo; + quote.IsDefault = request.IsDefault; + quote.Requirement = TrimOrNull(request.Requirement); + quote.Remark = TrimOrNull(request.Remark); + } + + private static void ClearOtherDefaults(Product product, ProductSupplierQuote quote) + { + if (!quote.IsDefault) return; + foreach (var other in product.SupplierQuotes.Where(x => x.Id != quote.Id && x.ProductPartId == quote.ProductPartId)) + { + other.IsDefault = false; + } + } + + private static Dictionary Snapshot(ProductSupplierQuote q) => new() + { + [nameof(q.ProductPartId)] = F(q.ProductPartId), [nameof(q.SupplierId)] = F(q.SupplierId), + [nameof(q.SupplierName)] = q.SupplierName, [nameof(q.SupplierProductName)] = q.SupplierProductName, + [nameof(q.SupplierProductSku)] = q.SupplierProductSku, [nameof(q.ContentType)] = F(q.ContentType), + [nameof(q.UnitPrice)] = F(q.UnitPrice), [nameof(q.Currency)] = q.Currency, [nameof(q.PricingUnit)] = q.PricingUnit, + [nameof(q.TaxIncluded)] = F(q.TaxIncluded), [nameof(q.TaxRate)] = F(q.TaxRate), + [nameof(q.MinimumOrderQuantity)] = F(q.MinimumOrderQuantity), [nameof(q.LeadTimeDays)] = F(q.LeadTimeDays), + [nameof(q.EffectiveFrom)] = F(q.EffectiveFrom), [nameof(q.EffectiveTo)] = F(q.EffectiveTo), + [nameof(q.IsDefault)] = F(q.IsDefault), [nameof(q.Requirement)] = q.Requirement, [nameof(q.Remark)] = q.Remark + }; + + private async Task LoadAsync(Guid id, CancellationToken ct) + => await db.Products + .Include(x => x.Parts) + .Include(x => x.SupplierQuotes) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new CatalogNotFoundException("产品不存在。"); + + private async Task LoadDraftAsync(Guid id, CancellationToken ct) + { + var product = await LoadAsync(id, ct); + if (product.Status != ProductStatus.Draft) + { + throw new CatalogConflictException("只有草稿状态的产品可以维护零件和供应商报价;已发布产品请先编辑新版本。"); + } + + return product; + } + + private async Task EnsureSkuAvailableAsync(string sku, Guid? excludeId, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(sku)) return; + + var exists = await db.Products.AnyAsync(x => + x.InternalSku == sku + && x.Status != ProductStatus.Superseded + && (excludeId == null || x.Id != excludeId.Value), ct); + if (exists) + { + throw new CatalogConflictException($"内部货号 {sku} 已被其他产品版本使用。"); + } + } + + private async Task ValidateComponentAsync(ProductPart part, Guid productId, CancellationToken ct) + { + if (part.ComponentProductId is null) return; + if (part.ComponentProductId == productId) + { + throw new CatalogValidationException(nameof(part.ComponentProductId), "零件不能引用产品自身。"); + } + + if (!await db.Products.AnyAsync(x => x.Id == part.ComponentProductId.Value, ct)) + { + throw new CatalogValidationException(nameof(part.ComponentProductId), "引用的零件产品不存在。"); + } + } + + private static Product CopyAsNewDraft(Product source) + { + var draft = new Product + { + InternalSku = source.InternalSku, + NameZh = source.NameZh, + NameEn = source.NameEn, + Category = source.Category, + ProductType = source.ProductType, + Unit = source.Unit, + ProductLength = source.ProductLength, + ProductWidth = source.ProductWidth, + ProductHeight = source.ProductHeight, + DimensionUnit = source.DimensionUnit, + Description = source.Description, + PurchaseRequirement = source.PurchaseRequirement, + QualityRequirement = source.QualityRequirement, + DefaultOrigin = source.DefaultOrigin, + Remark = source.Remark, + PackingRate = source.PackingRate, + CartonLength = source.CartonLength, + CartonWidth = source.CartonWidth, + CartonHeight = source.CartonHeight, + CartonGrossWeight = source.CartonGrossWeight, + CartonNetWeight = source.CartonNetWeight, + CartonMaterial = source.CartonMaterial, + PackagingNote = source.PackagingNote, + HsCode = source.HsCode, + CustomsNameZh = source.CustomsNameZh, + CustomsNameEn = source.CustomsNameEn, + CustomsUnit = source.CustomsUnit, + DeclarationElements = source.DeclarationElements, + OriginCountry = source.OriginCountry, + CustomsRemark = source.CustomsRemark, + Status = ProductStatus.Draft, + Version = source.Version + 1 + }; + + var partIdMap = new Dictionary(); + foreach (var part in source.Parts.OrderBy(x => x.SortOrder)) + { + var copy = new ProductPart + { + Product = draft, + ComponentProductId = part.ComponentProductId, + Name = part.Name, + PartType = part.PartType, + ComponentSku = part.ComponentSku, + QuantityPerProduct = part.QuantityPerProduct, + Unit = part.Unit, + Requirement = part.Requirement, + IsRequired = part.IsRequired, + SortOrder = part.SortOrder, + IsActive = part.IsActive + }; + partIdMap[part.Id] = copy.Id; + draft.Parts.Add(copy); + } + + foreach (var quote in source.SupplierQuotes) + { + draft.SupplierQuotes.Add(new ProductSupplierQuote + { + Product = draft, + ProductPartId = quote.ProductPartId is { } oldPartId && partIdMap.TryGetValue(oldPartId, out var newPartId) ? newPartId : null, + SupplierId = quote.SupplierId, + SupplierName = quote.SupplierName, + SupplierProductName = quote.SupplierProductName, + SupplierProductSku = quote.SupplierProductSku, + ContentType = quote.ContentType, + UnitPrice = quote.UnitPrice, + Currency = quote.Currency, + PricingUnit = quote.PricingUnit, + TaxIncluded = quote.TaxIncluded, + TaxRate = quote.TaxRate, + MinimumOrderQuantity = quote.MinimumOrderQuantity, + LeadTimeDays = quote.LeadTimeDays, + EffectiveFrom = quote.EffectiveFrom, + EffectiveTo = quote.EffectiveTo, + IsDefault = quote.IsDefault, + Requirement = quote.Requirement, + Remark = quote.Remark + }); + } + + return draft; + } + + private static void ApplyDraft(Product product, SaveProductDraftRequest request) + { + product.InternalSku = (request.InternalSku ?? string.Empty).Trim(); + product.NameZh = (request.NameZh ?? string.Empty).Trim(); + product.NameEn = (request.NameEn ?? string.Empty).Trim(); + product.Category = (request.Category ?? string.Empty).Trim(); + product.ProductType = string.IsNullOrWhiteSpace(request.ProductType) + ? null + : ParseEnum(request.ProductType, (ProductType?)null, nameof(request.ProductType)); + product.Unit = (request.Unit ?? string.Empty).Trim(); + product.ProductLength = request.ProductLength; + product.ProductWidth = request.ProductWidth; + product.ProductHeight = request.ProductHeight; + product.DimensionUnit = TrimOrNull(request.DimensionUnit); + product.Description = TrimOrNull(request.Description); + product.PurchaseRequirement = TrimOrNull(request.PurchaseRequirement); + product.QualityRequirement = TrimOrNull(request.QualityRequirement); + product.DefaultOrigin = TrimOrNull(request.DefaultOrigin); + product.Remark = TrimOrNull(request.Remark); + product.PackingRate = request.PackingRate; + product.CartonLength = request.CartonLength; + product.CartonWidth = request.CartonWidth; + product.CartonHeight = request.CartonHeight; + product.CartonGrossWeight = request.CartonGrossWeight; + product.CartonNetWeight = request.CartonNetWeight; + product.CartonMaterial = TrimOrNull(request.CartonMaterial); + product.PackagingNote = TrimOrNull(request.PackagingNote); + product.HsCode = TrimOrNull(request.HsCode); + product.CustomsNameZh = TrimOrNull(request.CustomsNameZh); + product.CustomsNameEn = TrimOrNull(request.CustomsNameEn); + product.CustomsUnit = TrimOrNull(request.CustomsUnit); + product.DeclarationElements = TrimOrNull(request.DeclarationElements); + product.OriginCountry = TrimOrNull(request.OriginCountry); + product.CustomsRemark = TrimOrNull(request.CustomsRemark); + + if (product.PackingRate is <= 0) + { + throw new CatalogValidationException(nameof(request.PackingRate), "装箱率必须大于 0。"); + } + } + + private static void ApplyPart(ProductPart part, SaveProductPartRequest request) + { + if (string.IsNullOrWhiteSpace(request.Name)) + { + throw new CatalogValidationException(nameof(request.Name), "零件名称不能为空。"); + } + + if (string.IsNullOrWhiteSpace(request.Unit)) + { + throw new CatalogValidationException(nameof(request.Unit), "零件计量单位不能为空。"); + } + + if (request.QuantityPerProduct <= 0) + { + throw new CatalogValidationException(nameof(request.QuantityPerProduct), "每套用量必须大于 0。"); + } + + part.Name = request.Name.Trim(); + part.PartType = ParseEnum(request.PartType, ProductPartType.Accessory, nameof(request.PartType)); + part.ComponentProductId = request.ComponentProductId; + part.ComponentSku = TrimOrNull(request.ComponentSku); + part.QuantityPerProduct = request.QuantityPerProduct; + part.Unit = request.Unit.Trim(); + part.Requirement = TrimOrNull(request.Requirement); + part.IsRequired = request.IsRequired; + part.SortOrder = request.SortOrder; + } + + private static T ParseEnum(string? value, T? fallback, string field) where T : struct, Enum + { + if (string.IsNullOrWhiteSpace(value)) + { + return fallback ?? throw new CatalogValidationException(field, $"{field} 不能为空。"); + } + + return Enum.TryParse(value, ignoreCase: true, out var parsed) + ? parsed + : throw new CatalogValidationException(field, $"{field} 的值无效。"); + } + + // Overload used where a non-nullable fallback is supplied. + private static T ParseEnum(string? value, T fallback, string field) where T : struct, Enum + => string.IsNullOrWhiteSpace(value) ? fallback : ParseEnum(value, (T?)null, field); + + private static string? TrimOrNull(string? value) + => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private void AddChangeLog(Product product, ProductChangeAction action, IReadOnlyList changedFields, + string summary, Guid? actorUserId, string? actorUserName) + { + var entry = new ProductChangeLog + { + ProductId = product.Id, + Product = product, + ActorUserId = actorUserId, + ActorUserName = string.IsNullOrWhiteSpace(actorUserName) ? null : actorUserName.Trim()[..Math.Min(200, actorUserName.Trim().Length)], + Action = action, + ProductVersion = product.Version, + ChangedFieldsJson = JsonSerializer.Serialize(changedFields), + Summary = summary.Length <= 500 ? summary : summary[..500] + }; + product.ChangeLogs.Add(entry); + db.ProductChangeLogs.Add(entry); + } + + private static ProductChangeLogDto ToDto(ProductChangeLog entry) + { + IReadOnlyList fields; + try { fields = JsonSerializer.Deserialize>(entry.ChangedFieldsJson) ?? []; } + catch (JsonException) { fields = []; } + return new ProductChangeLogDto(entry.Id, entry.ProductId, entry.ActorUserId, entry.ActorUserName, + entry.Action.ToString(), entry.ProductVersion, fields, entry.Summary, entry.CreatedAt); + } + + private static IReadOnlyList ChangedFields( + IReadOnlyDictionary before, IReadOnlyDictionary after) + => after.Keys.Where(k => !string.Equals(before.GetValueOrDefault(k), after[k], StringComparison.Ordinal)).ToList(); + + private static IReadOnlyList NonEmptyFields(IReadOnlyDictionary snapshot) + => snapshot.Where(x => !string.IsNullOrWhiteSpace(x.Value)).Select(x => x.Key).ToList(); + + private static string? F(object? value) => value switch + { + null => null, + IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), + _ => value.ToString() + }; + + private static Dictionary Snapshot(Product p) => new() + { + [nameof(p.InternalSku)] = p.InternalSku, [nameof(p.NameZh)] = p.NameZh, [nameof(p.NameEn)] = p.NameEn, + [nameof(p.Category)] = p.Category, [nameof(p.ProductType)] = F(p.ProductType), [nameof(p.Unit)] = p.Unit, + [nameof(p.ProductLength)] = F(p.ProductLength), [nameof(p.ProductWidth)] = F(p.ProductWidth), [nameof(p.ProductHeight)] = F(p.ProductHeight), + [nameof(p.DimensionUnit)] = p.DimensionUnit, [nameof(p.Description)] = p.Description, + [nameof(p.PurchaseRequirement)] = p.PurchaseRequirement, [nameof(p.QualityRequirement)] = p.QualityRequirement, + [nameof(p.DefaultOrigin)] = p.DefaultOrigin, [nameof(p.Remark)] = p.Remark, + [nameof(p.PackingRate)] = F(p.PackingRate), [nameof(p.CartonLength)] = F(p.CartonLength), + [nameof(p.CartonWidth)] = F(p.CartonWidth), [nameof(p.CartonHeight)] = F(p.CartonHeight), + [nameof(p.CartonGrossWeight)] = F(p.CartonGrossWeight), [nameof(p.CartonNetWeight)] = F(p.CartonNetWeight), + [nameof(p.CartonMaterial)] = p.CartonMaterial, [nameof(p.PackagingNote)] = p.PackagingNote, + [nameof(p.HsCode)] = p.HsCode, [nameof(p.CustomsNameZh)] = p.CustomsNameZh, [nameof(p.CustomsNameEn)] = p.CustomsNameEn, + [nameof(p.CustomsUnit)] = p.CustomsUnit, [nameof(p.DeclarationElements)] = p.DeclarationElements, + [nameof(p.OriginCountry)] = p.OriginCountry, [nameof(p.CustomsRemark)] = p.CustomsRemark + }; + + private static Dictionary Snapshot(ProductPart p) => new() + { + [nameof(p.Name)] = p.Name, [nameof(p.PartType)] = F(p.PartType), [nameof(p.ComponentProductId)] = F(p.ComponentProductId), + [nameof(p.ComponentSku)] = p.ComponentSku, [nameof(p.QuantityPerProduct)] = F(p.QuantityPerProduct), + [nameof(p.Unit)] = p.Unit, [nameof(p.Requirement)] = p.Requirement, [nameof(p.IsRequired)] = F(p.IsRequired), + [nameof(p.SortOrder)] = F(p.SortOrder), [nameof(p.IsActive)] = F(p.IsActive) + }; + + private static ProductListItemDto ToListItem(Product p) => new( + p.Id, p.InternalSku, p.NameZh, p.NameEn, p.Category, + p.ProductType?.ToString(), p.Unit, p.Status.ToString(), p.Version, + p.HsCode, p.UpdatedAt, p.PublishedAt); + + private static ProductPartDto ToDto(ProductPart part) => new( + part.Id, part.ProductId, part.ComponentProductId, part.Name, part.PartType.ToString(), + part.ComponentSku, part.QuantityPerProduct, part.Unit, part.Requirement, + part.IsRequired, part.SortOrder, part.IsActive); + + private static SupplierQuoteDto ToDto(ProductSupplierQuote q) => new( + q.Id, q.ProductId, q.ProductPartId, q.SupplierId, q.SupplierName, + q.SupplierProductName, q.SupplierProductSku, q.ContentType.ToString(), + q.UnitPrice, q.Currency, q.PricingUnit, q.TaxIncluded, q.TaxRate, + q.MinimumOrderQuantity, q.LeadTimeDays, q.EffectiveFrom, q.EffectiveTo, + q.IsDefault, q.Requirement, q.Remark, q.CreatedAt); + + private static ProductDto ToDto(Product p) => new( + p.Id, p.InternalSku, p.NameZh, p.NameEn, p.Category, p.ProductType?.ToString(), p.Unit, + p.ProductLength, p.ProductWidth, p.ProductHeight, p.DimensionUnit, p.Description, + p.PurchaseRequirement, p.QualityRequirement, p.DefaultOrigin, p.Remark, + p.PackingRate, p.CartonLength, p.CartonWidth, p.CartonHeight, + p.CartonGrossWeight, p.CartonNetWeight, p.CartonMaterial, p.PackagingNote, + p.HsCode, p.CustomsNameZh, p.CustomsNameEn, p.CustomsUnit, p.DeclarationElements, + p.OriginCountry, p.CustomsRemark, + p.Status.ToString(), p.Version, p.CreatedAt, p.UpdatedAt, p.PublishedAt, + p.Parts.OrderBy(x => x.SortOrder).ThenBy(x => x.Name).Select(ToDto).ToList(), + p.SupplierQuotes.OrderByDescending(x => x.CreatedAt).Select(ToDto).ToList()); +} diff --git a/src/Leiren.Erp.Application/Class1.cs b/src/Leiren.Erp.Application/Class1.cs new file mode 100644 index 0000000..a377b2c --- /dev/null +++ b/src/Leiren.Erp.Application/Class1.cs @@ -0,0 +1,6 @@ +namespace Leiren.Erp.Application; + +public class Class1 +{ + +} diff --git a/src/Leiren.Erp.Application/Customs/CiPlDocumentGenerationService.cs b/src/Leiren.Erp.Application/Customs/CiPlDocumentGenerationService.cs new file mode 100644 index 0000000..806c624 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/CiPlDocumentGenerationService.cs @@ -0,0 +1,204 @@ +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +/// +/// Generates customs and customer document workbooks (every shipping-batch +/// ) for a confirmed shipping batch from a mapped +/// XLSX template version. The template file and the generated file both live +/// in the Files module; each regeneration stores a new attachment version of +/// the document package's file and a new document-package version, then locks +/// the template mappings. Unconfirmed batches and templates with unmapped +/// placeholders are refused before any file is produced. +/// +public sealed class CiPlDocumentGenerationService( + ICustomsDbContext db, FileService files, DocumentTemplateMappingService mappings) +{ + public const string OwnerType = "document-package"; + public const string ContentType = + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + + public async Task GenerateAsync( + Guid shippingBatchId, GenerateCiPlDocumentRequest request, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(request); + + if (request.TemplateVersionId is not { } templateVersionId || templateVersionId == Guid.Empty) + throw new CustomsValidationException(nameof(request.TemplateVersionId), "必须选择已完成字段映射的模板版本。"); + + var batch = await db.ShippingBatches.AsNoTracking() + .Include(x => x.Containers) + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == shippingBatchId, ct) + ?? throw new CustomsNotFoundException("出货批次不存在。"); + if (batch.Status != ShippingBatchStatus.Confirmed) + throw new CustomsConflictException("只有已确认的出货批次可以生成单证。"); + if (batch.Lines.Count == 0) + throw new CustomsValidationException(nameof(shippingBatchId), "出货批次没有出货明细,不能生成单证。"); + + var lines = batch.Lines.OrderBy(x => x.CreatedAt).ThenBy(x => x.Id).ToList(); + + // Template bytes come from the Files module; the template version id + // is the immutable template file version id. + byte[] templateBytes; + FileAttachmentDto templateFile; + try + { + templateFile = await files.GetAsync(templateVersionId, ct); + await using var download = (await files.OpenDownloadAsync(templateVersionId, ct)).Content; + using var buffer = new MemoryStream(); + await download.CopyToAsync(buffer, ct); + templateBytes = buffer.ToArray(); + } + catch (FilesNotFoundException) + { + throw new CustomsNotFoundException("模板版本文件不存在。"); + } + if (!string.Equals(templateFile.Extension, ".xlsx", StringComparison.OrdinalIgnoreCase)) + throw new CustomsValidationException(nameof(request.TemplateVersionId), "模板文件必须是 .xlsx 文件。"); + if (templateBytes.Length == 0) + throw new CustomsValidationException(nameof(request.TemplateVersionId), "模板文件内容为空。"); + // The template's own type decides the document kind unless the caller names one. + var kind = ParseKind(request.DocumentKind ?? templateFile.Category); + + TemplateScanResult scan; + try + { + scan = TemplatePlaceholderScanner.Scan(templateBytes); + } + catch (DocumentTemplateValidationException ex) + { + throw new CustomsValidationException(ex.Errors); + } + var scannedNames = scan.Placeholders.Select(x => x.Name).ToList(); + if (scannedNames.Count == 0) + throw new CustomsValidationException(nameof(request.TemplateVersionId), "模板中没有 {{...}} 占位符,不能生成。"); + + // Refuses generation, listing every unmapped placeholder, when the + // mapping profile for this template version is incomplete. + var profile = await mappings.ValidateForGenerationAsync(templateVersionId, scannedNames, ct); + if (!string.IsNullOrWhiteSpace(profile.TemplateReference) + && Guid.TryParse(profile.TemplateReference, out var referencedFileId) + && referencedFileId != templateVersionId) + { + throw new CustomsValidationException(nameof(request.TemplateVersionId), + "映射记录的模板引用与所选模板版本文件不一致,禁止生成。"); + } + + var mappingsByKey = profile.Mappings.ToDictionary( + m => DocumentTemplateFieldMapping.NormalizePlaceholderKey(m.Placeholder), + m => new CiPlMappedField( + m.Placeholder, m.BusinessField, + DocumentTemplateFields.TryGet(m.BusinessField, out var def) ? def.Scope : TemplateFieldScope.Header, + m.NumberFormat), + StringComparer.Ordinal); + + var source = await DocumentRenderSource.LoadAsync(db, batch, ct); + if (DocumentRenderSource.IsCustomsKind(kind) && source.Declaration is null) + throw new CustomsConflictException("报关单证从报关资料取数:请先在出货与报关中填写并确认该批次的报关资料。"); + + var generatedAt = DateTimeOffset.UtcNow; + var rendered = CiPlTemplateRenderer.Render( + templateBytes, batch, lines, kind, source, mappingsByKey, generatedAt); + + var version = (await db.DocumentPackages.AsNoTracking() + .Where(x => x.ShippingBatchId == batch.Id && x.DocumentKind == kind) + .MaxAsync(x => (int?)x.Version, ct) ?? 0) + 1; + + var package = new DocumentPackage + { + ShippingBatchId = batch.Id, + CustomsDeclarationId = DocumentRenderSource.IsCustomsKind(kind) ? source.Declaration?.Id : null, + DocumentKind = kind, + Status = DocumentPackageStatus.Generated, + Version = version, + PackageNo = $"DOC-{batch.BatchNo}-{kind.ToString().ToUpperInvariant()}-{version}", + TemplateReference = profile.TemplateReference ?? templateVersionId.ToString("D"), + TemplateVersionId = templateVersionId, + TemplateVersion = templateFile.Version.ToString(), + OutputFormat = "xlsx", + Currency = batch.Currency, + LineCount = lines.Count, + TotalQuantity = DocumentRenderSource.IsCustomsKind(kind) ? source.Declaration!.TotalQuantity : lines.Sum(x => x.Quantity), + TotalAmount = DocumentRenderSource.IsCustomsKind(kind) ? source.Declaration!.TotalAmount : lines.Sum(x => x.Amount), + TotalCartonCount = lines.Sum(x => x.CartonCount ?? 0), + TotalGrossWeight = lines.Sum(x => x.TotalGrossWeight ?? 0), + TotalNetWeight = lines.Sum(x => x.TotalNetWeight ?? 0), + TotalCbm = lines.Sum(x => x.TotalCbm ?? 0), + GeneratedAt = generatedAt, + GeneratedBy = TrimOrNull(request.GeneratedBy), + Remark = TrimOrNull(request.Remark) + }; + + var fileName = $"{SanitizeFileStem(batch.BatchNo)}-{kind}-{version}.xlsx"; + var category = kind.ToString(); + var description = + $"客户单证 {package.PackageNo};出货批次 {batch.BatchNo};模板版本 {templateVersionId:D};生成时间 {generatedAt:yyyy-MM-dd HH:mm:ss} UTC。"; + + await using var outputStream = new MemoryStream(rendered, writable: false); + + // Regenerating the same batch + kind stores a new version of the + // previous generated file, keeping every earlier file downloadable. + var previousFileId = await db.DocumentPackages.AsNoTracking() + .Where(x => x.ShippingBatchId == batch.Id && x.DocumentKind == kind && x.GeneratedFileReference != null) + .OrderByDescending(x => x.Version) + .Select(x => x.GeneratedFileReference) + .FirstOrDefaultAsync(ct); + + FileAttachmentDto file; + if (previousFileId is not null && Guid.TryParse(previousFileId, out var anchorId)) + { + file = await files.UploadNewVersionAsync( + anchorId, outputStream, fileName, ContentType, category, description, ct: ct); + } + else + { + file = await files.UploadAsync(new UploadFileCommand( + OwnerType, package.Id, category, description, fileName, ContentType, outputStream), ct); + } + + package.GeneratedFileReference = file.Id.ToString("D"); + package.GeneratedFileName = file.OriginalFileName; + + db.DocumentPackages.Add(package); + await db.SaveChangesAsync(ct); + + await mappings.LockAfterGenerationAsync(templateVersionId, package.Id, ct); + + return new CiPlDocumentGenerationResultDto( + ToDto(package), file, $"/api/files/{file.Id}/download", scannedNames); + } + + private static DocumentKind ParseKind(string? value) + { + if (string.IsNullOrWhiteSpace(value) + || !Enum.TryParse(value.Trim(), ignoreCase: true, out var kind)) + { + throw new CustomsValidationException(nameof(GenerateCiPlDocumentRequest.DocumentKind), + "单证类型无效,只能使用报关或客户单证模板生成。"); + } + return kind; + } + + private static string? TrimOrNull(string? v) => string.IsNullOrWhiteSpace(v) ? null : v.Trim(); + + private static string SanitizeFileStem(string batchNo) + { + var invalid = Path.GetInvalidFileNameChars(); + var stem = new string(batchNo.Trim().Select(c => invalid.Contains(c) ? '-' : c).ToArray()); + return string.IsNullOrWhiteSpace(stem) ? "shipment" : stem; + } + + private static DocumentPackageDto ToDto(DocumentPackage p) => new( + p.Id, p.ShippingBatchId, p.CustomsDeclarationId, p.PackageNo, p.DocumentKind.ToString(), + p.Status.ToString(), p.Version, p.TemplateReference, p.TemplateVersion, p.OutputFormat, + p.GeneratedFileReference, p.GeneratedFileName, p.Currency, p.LineCount, p.TotalQuantity, + p.TotalAmount, p.TotalCartonCount, p.TotalGrossWeight, p.TotalNetWeight, p.TotalCbm, + p.GeneratedAt, p.GeneratedBy, p.ConfirmedAt, p.ConfirmedBy, p.ExportedAt, p.ExportedBy, + p.VoidedAt, p.Remark, p.CreatedAt, p.UpdatedAt); +} diff --git a/src/Leiren.Erp.Application/Customs/CiPlTemplateRenderer.cs b/src/Leiren.Erp.Application/Customs/CiPlTemplateRenderer.cs new file mode 100644 index 0000000..e899717 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/CiPlTemplateRenderer.cs @@ -0,0 +1,412 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using ClosedXML.Excel; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; + +namespace Leiren.Erp.Application.Customs; + +/// One resolved placeholder mapping used by the renderer (placeholder key is the normalized name). +public sealed record CiPlMappedField(string Placeholder, string BusinessField, TemplateFieldScope Scope, string? NumberFormat); + +/// +/// Renders a customer CI/PL workbook from a real XLSX template and the +/// confirmed shipping-batch snapshot. Placeholders are discovered by scanning +/// every worksheet's used range (never fixed cell coordinates); the row +/// carrying line-scope placeholders is copied once per shipment line, and all +/// totals are computed in code from the shipment-line snapshots — template +/// formulas are never evaluated or relied upon. +/// +public static partial class CiPlTemplateRenderer +{ + [GeneratedRegex(@"\{\{\s*([^{}]+?)\s*\}\}", RegexOptions.CultureInvariant)] + private static partial Regex TokenRegex(); + + public static byte[] Render( + byte[] templateBytes, + ShippingBatch batch, + IReadOnlyList lines, + DocumentKind kind, + DocumentRenderSource source, + IReadOnlyDictionary mappingsByPlaceholderKey, + DateTimeOffset generatedAt, + bool allowUnmapped = false) + { + ArgumentNullException.ThrowIfNull(templateBytes); + ArgumentNullException.ThrowIfNull(batch); + ArgumentNullException.ThrowIfNull(lines); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(mappingsByPlaceholderKey); + + // Customs documents print the declared quantity / price / HS code; + // every customs-only field (报关品名, 申报要素 ...) is read from the + // declaration line of the same shipment line whenever one exists. + var declaredByShipmentLine = source.Declaration?.Lines.ToDictionary(x => x.ShipmentLineId) + ?? new Dictionary(); + var useDeclared = DocumentRenderSource.IsCustomsKind(kind) && source.Declaration is not null; + var docLines = lines + .Select(l => new DocLine(l, declaredByShipmentLine.GetValueOrDefault(l.Id), useDeclared)) + .ToList(); + var totals = ComputeTotals(docLines); + var context = new RenderContext(batch, docLines, kind, source, totals, generatedAt); + + XLWorkbook workbook; + try + { + workbook = new XLWorkbook(new MemoryStream(templateBytes, writable: false)); + } + catch (Exception ex) + { + throw new CustomsValidationException("TemplateVersionId", $"模板 Excel 文件无法解析(不是有效的 .xlsx 文件):{ex.Message}"); + } + + using (workbook) + { + if (workbook.Worksheets.Count == 0) + throw new CustomsValidationException("TemplateVersionId", "模板工作簿中没有任何工作表。"); + + // Pre-pass: every placeholder in the workbook must be mapped to a + // known business field, otherwise generation is refused with the + // full list of missing placeholders. Previews (allowUnmapped) keep + // unmapped tokens as written so an incomplete mapping can be tested. + var unmapped = new SortedSet(StringComparer.OrdinalIgnoreCase); + foreach (var sheet in workbook.Worksheets) + foreach (var name in ScanPlaceholderNames(sheet)) + if (!mappingsByPlaceholderKey.TryGetValue(NormalizeKey(name), out var field) + || !DocumentTemplateFields.TryGet(field.BusinessField, out _)) + unmapped.Add(name); + if (unmapped.Count > 0 && !allowUnmapped) + { + throw new CustomsValidationException(new Dictionary + { + ["UnmappedPlaceholders"] = unmapped.Select(p => $"{{{{{p}}}}}").ToArray() + }); + } + + var usable = mappingsByPlaceholderKey + .Where(x => DocumentTemplateFields.TryGet(x.Value.BusinessField, out _)) + .ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal); + foreach (var sheet in workbook.Worksheets) + RenderSheet(sheet, context, usable); + + using var output = new MemoryStream(); + workbook.SaveAs(output); + return output.ToArray(); + } + } + + // ---------- Sheet rendering ---------- + + private static void RenderSheet( + IXLWorksheet sheet, RenderContext context, IReadOnlyDictionary mappings) + { + var range = sheet.RangeUsed(); + if (range is null) return; + var firstColumn = range.FirstColumn().ColumnNumber(); + var lastColumn = range.LastColumn().ColumnNumber(); + + // Detail rows carry at least one line-scope placeholder; the template + // block spans from the first to the last such row. + var detailRows = new SortedSet(); + foreach (var cell in range.Cells()) + { + var text = CellTokenText(cell); + if (text is null) continue; + foreach (Match match in TokenRegex().Matches(text)) + { + if (mappings.TryGetValue(NormalizeKey(match.Groups[1].Value.Trim()), out var field) + && field.Scope == TemplateFieldScope.Line) + detailRows.Add(cell.Address.RowNumber); + } + } + + var lineIndexByRow = new Dictionary(); + if (detailRows.Count > 0) + { + var blockStart = detailRows.Min; + var blockEnd = detailRows.Max; + var height = blockEnd - blockStart + 1; + var lineCount = context.Lines.Count; + + var mergedInsideBlock = sheet.MergedRanges + .Select(r => (FirstRow: r.FirstRow().RowNumber(), FirstCol: r.FirstColumn().ColumnNumber(), + LastRow: r.LastRow().RowNumber(), LastCol: r.LastColumn().ColumnNumber())) + .Where(m => m.FirstRow >= blockStart && m.LastRow <= blockEnd) + .ToList(); + var templateHeights = Enumerable.Range(blockStart, height).Select(r => sheet.Row(r).Height).ToList(); + + if (lineCount > 1) + { + var extraRows = (lineCount - 1) * height; + sheet.Row(blockEnd + 1).InsertRowsAbove(extraRows); + + var templateRange = sheet.Range(blockStart, firstColumn, blockEnd, lastColumn); + for (var copy = 1; copy < lineCount; copy++) + { + var targetStart = blockStart + copy * height; + templateRange.CopyTo(sheet.Cell(targetStart, firstColumn)); + for (var r = 0; r < height; r++) + sheet.Row(targetStart + r).Height = templateHeights[r]; + foreach (var m in mergedInsideBlock) + { + var offset = copy * height; + try { sheet.Range(m.FirstRow + offset, m.FirstCol, m.LastRow + offset, m.LastCol).Merge(); } + catch (InvalidOperationException) { /* already merged by the copy */ } + } + } + } + + for (var i = 0; i < lineCount; i++) + for (var r = 0; r < height; r++) + lineIndexByRow[blockStart + i * height + r] = i; + } + + // Replacement pass over the (now expanded) used range. + var expanded = sheet.RangeUsed(); + if (expanded is null) return; + foreach (var cell in expanded.Cells()) + { + var text = CellTokenText(cell); + if (text is null) continue; + + int? lineIndex = lineIndexByRow.TryGetValue(cell.Address.RowNumber, out var idx) ? idx : null; + ReplaceCell(cell, text, context, mappings, lineIndex); + } + } + + private static void ReplaceCell( + IXLCell cell, string text, RenderContext context, + IReadOnlyDictionary mappings, int? lineIndex) + { + var matches = TokenRegex().Matches(text); + if (matches.Count == 0) return; + + // A cell holding exactly one placeholder takes the typed value so + // numbers and dates stay real Excel values. + if (matches.Count == 1 && string.Equals(text.Trim(), matches[0].Value, StringComparison.Ordinal)) + { + // Unmapped tokens (preview only) stay as written. + if (!mappings.TryGetValue(NormalizeKey(matches[0].Groups[1].Value.Trim()), out var field)) return; + var value = ResolveValue(field, context, lineIndex); + SetTypedValue(cell, value, field.NumberFormat); + return; + } + + var replaced = TokenRegex().Replace(text, match => + { + if (!mappings.TryGetValue(NormalizeKey(match.Groups[1].Value.Trim()), out var field)) return match.Value; + var value = ResolveValue(field, context, lineIndex); + return FormatAsText(value); + }); + cell.Value = replaced; + } + + private static object? ResolveValue(CiPlMappedField field, RenderContext context, int? lineIndex) + { + if (!DocumentTemplateFields.TryGet(field.BusinessField, out var definition)) + throw new CustomsValidationException("BusinessField", $"业务字段 \"{field.BusinessField}\" 不在允许字段目录中。"); + + return definition.Scope switch + { + TemplateFieldScope.Line => lineIndex is { } i + ? LineValue(definition.Key, context.Lines[i], i + 1, context) + : throw new CustomsValidationException("TemplateVersionId", + $"明细字段 {definition.Key} 的占位符没有放在明细行中,无法生成。"), + TemplateFieldScope.Total => TotalValue(definition.Key, context.Totals), + _ => HeaderValue(definition.Key, context) + }; + } + + // ---------- Field values (shipment snapshot only) ---------- + + private static object? HeaderValue(string key, RenderContext c) => key switch + { + "BatchNo" => c.Batch.BatchNo, + "SalesOrderNo" => c.Batch.SalesOrderNo, + "CustomerName" => c.Batch.CustomerName, + "CustomerPoNo" => c.Batch.CustomerPoNo, + "Currency" => c.Batch.Currency, + "ShipmentDate" => c.Batch.ShipmentDate, + "CutoffDate" => c.Batch.CutoffDate, + "Etd" => c.Batch.Etd, + "Eta" => c.Batch.Eta, + "VesselName" => c.Batch.VesselName, + "VoyageNo" => c.Batch.VoyageNo, + "BillOfLadingNo" => c.Batch.BillOfLadingNo, + "LoadingPort" => c.Batch.LoadingPort, + "DestinationPort" => c.Batch.DestinationPort, + "DestinationCountry" => c.Batch.DestinationCountry, + "TransportMode" => c.Batch.TransportMode, + "TradeTerm" => c.Batch.TradeTerm, + "FreightForwarder" => c.Batch.FreightForwarder, + "ContainerNumbers" => c.Batch.Containers.Count == 0 + ? null + : string.Join(", ", c.Batch.Containers.Select(x => x.ContainerNo)), + "DeclarationNo" => c.Source.Declaration?.DeclarationNo, + "DocumentKind" => c.Kind.ToString(), + "GeneratedDate" => DateOnly.FromDateTime(c.GeneratedAt.UtcDateTime), + "InvoiceNo" => c.Source.Declaration?.InvoiceNo ?? c.Batch.BatchNo, + "CustomerAddress" => c.Source.Customer?.Address, + "OrderDate" => c.Source.OrderDate, + "ExportDate" => c.Source.Declaration?.ExportDate ?? c.Batch.Etd ?? c.Batch.ShipmentDate, + "DeclarationDate" => c.Source.Declaration?.DeclarationDate, + "TradeMode" => c.Source.Declaration?.TradeMode, + "ExemptionNature" => c.Source.Declaration?.ExemptionNature, + "CurrencyNameZh" => CurrencyNameZh(c.Batch.Currency), + _ => throw UnknownField(key) + }; + + private static object? LineValue(string key, DocLine d, int lineNumber, RenderContext c) + { + var l = d.Shipment; + var declared = d.Declared; + return key switch + { + "LineNumber" => lineNumber, + "InternalSku" => l.InternalSku, + "ProductNameZh" => l.ProductNameZh, + "ProductNameEn" => l.ProductNameEn, + "CustomerSku" => l.CustomerSku, + "CustomerProductName" => l.CustomerProductName, + "HsCode" => d.UseDeclared ? declared!.HsCode : declared?.HsCode ?? l.HsCode, + "Quantity" => d.Quantity, + "Unit" => d.UseDeclared ? declared!.Unit : l.Unit, + "UnitPrice" => d.UseDeclared ? declared!.UnitPrice : l.UnitPrice, + "Amount" => d.Amount, + "PackingRate" => l.PackingRate, + "CartonCount" => l.CartonCount, + "CartonLength" => l.CartonLength, + "CartonWidth" => l.CartonWidth, + "CartonHeight" => l.CartonHeight, + "CartonGrossWeight" => l.CartonGrossWeight, + "CartonNetWeight" => l.CartonNetWeight, + "LineTotalGrossWeight" => l.TotalGrossWeight, + "LineTotalNetWeight" => l.TotalNetWeight, + "LineTotalCbm" => l.TotalCbm, + "Remark" => l.Remark, + "CustomsNameZh" => declared?.CustomsNameZh ?? l.ProductNameZh, + "CustomsNameEn" => declared?.CustomsNameEn ?? l.ProductNameEn, + "DeclarationElements" => declared?.DeclarationElements, + "OriginCountry" => declared?.OriginCountry, + "DomesticSourcePlace" => declared?.DomesticSourcePlace, + "ExemptionInfo" => declared?.ExemptionInfo, + "LineCurrencyZh" => CurrencyNameZh(c.Batch.Currency), + _ => throw UnknownField(key) + }; + } + + private static object? TotalValue(string key, Totals t) => key switch + { + "LineCount" => t.LineCount, + "TotalQuantity" => t.TotalQuantity, + "TotalAmount" => t.TotalAmount, + "TotalCartonCount" => t.TotalCartonCount, + "TotalGrossWeight" => t.TotalGrossWeight, + "TotalNetWeight" => t.TotalNetWeight, + "TotalCbm" => t.TotalCbm, + _ => throw UnknownField(key) + }; + + private static Totals ComputeTotals(IReadOnlyList lines) => new( + lines.Count, + lines.Sum(x => x.Quantity), + lines.Sum(x => x.Amount), + lines.Sum(x => x.Shipment.CartonCount ?? 0), + lines.Sum(x => x.Shipment.TotalGrossWeight ?? 0), + lines.Sum(x => x.Shipment.TotalNetWeight ?? 0), + lines.Sum(x => x.Shipment.TotalCbm ?? 0)); + + /// Chinese currency name used by the customs declaration (币制). + private static string CurrencyNameZh(string currency) => currency.ToUpperInvariant() switch + { + "USD" => "美元", + "CNY" or "RMB" => "人民币", + "EUR" => "欧元", + "GBP" => "英镑", + "JPY" => "日元", + "HKD" => "港币", + "AUD" => "澳大利亚元", + "CAD" => "加拿大元", + _ => currency, + }; + + // ---------- Cell helpers ---------- + + /// Token-bearing text of a cell, or null. Formula cells are skipped: their values are never a data source. + private static string? CellTokenText(IXLCell cell) + { + if (cell.HasFormula) return null; + string text; + try { text = cell.GetString(); } + catch (InvalidOperationException) { return null; } + return text.Contains("{{", StringComparison.Ordinal) ? text : null; + } + + private static IEnumerable ScanPlaceholderNames(IXLWorksheet sheet) + { + var range = sheet.RangeUsed(); + if (range is null) yield break; + foreach (var cell in range.Cells()) + { + var text = CellTokenText(cell); + if (text is null) continue; + foreach (Match match in TokenRegex().Matches(text)) + yield return match.Groups[1].Value.Trim(); + } + } + + private static void SetTypedValue(IXLCell cell, object? value, string? numberFormat) + { + switch (value) + { + case null: cell.Value = string.Empty; break; + case string s: cell.Value = s; break; + case decimal d: cell.Value = d; break; + case int i: cell.Value = i; break; + case DateOnly d: + cell.Value = d.ToDateTime(TimeOnly.MinValue); + if (string.IsNullOrWhiteSpace(numberFormat)) cell.Style.DateFormat.Format = "yyyy-mm-dd"; + break; + case DateTime dt: cell.Value = dt; break; + default: cell.Value = value.ToString(); break; + } + + if (!string.IsNullOrWhiteSpace(numberFormat) && value is not string) + { + try { cell.Style.NumberFormat.Format = numberFormat.Trim(); } + catch (ArgumentException) { /* keep the template cell's own format */ } + } + } + + private static string FormatAsText(object? value) => value switch + { + null => string.Empty, + decimal d => d.ToString(CultureInfo.InvariantCulture), + int i => i.ToString(CultureInfo.InvariantCulture), + DateOnly d => d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + DateTime dt => dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + _ => value.ToString() ?? string.Empty + }; + + private static string NormalizeKey(string placeholder) + => DocumentTemplateFieldMapping.NormalizePlaceholderKey(placeholder); + + private static CustomsValidationException UnknownField(string key) + => new("BusinessField", $"业务字段 \"{key}\" 不在允许字段目录中。"); + + private sealed record Totals( + int LineCount, decimal TotalQuantity, decimal TotalAmount, int TotalCartonCount, + decimal TotalGrossWeight, decimal TotalNetWeight, decimal TotalCbm); + + /// One document line: the shipment line plus its customs-declaration line, if any. + private sealed record DocLine(ShipmentLine Shipment, CustomsDeclarationLine? Declared, bool UseDeclaredValues) + { + public bool UseDeclared => UseDeclaredValues && Declared is not null; + public decimal Quantity => UseDeclared ? Declared!.Quantity : Shipment.Quantity; + public decimal Amount => UseDeclared ? Declared!.Amount : Shipment.Amount; + } + + private sealed record RenderContext( + ShippingBatch Batch, IReadOnlyList Lines, DocumentKind Kind, + DocumentRenderSource Source, Totals Totals, DateTimeOffset GeneratedAt); +} diff --git a/src/Leiren.Erp.Application/Customs/CustomsExceptions.cs b/src/Leiren.Erp.Application/Customs/CustomsExceptions.cs new file mode 100644 index 0000000..17a8082 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/CustomsExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Customs; + +public sealed class CustomsNotFoundException(string message) : Exception(message); + +public sealed class CustomsConflictException(string message) : Exception(message); + +public sealed class CustomsValidationException(IReadOnlyDictionary errors) + : Exception("报关与单证资料校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public CustomsValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Customs/CustomsService.cs b/src/Leiren.Erp.Application/Customs/CustomsService.cs new file mode 100644 index 0000000..fc6cb1a --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/CustomsService.cs @@ -0,0 +1,527 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +public sealed class CustomsService(ICustomsDbContext db, DocumentTemplateMappingService templateMappings) +{ + private static readonly DocumentKind[] CustomsKinds = + [ + DocumentKind.CustomsInvoice, + DocumentKind.CustomsPackingList, + DocumentKind.CustomsSalesContract, + DocumentKind.CustomsDeclarationData + ]; + + // ---------- Customs declarations ---------- + + public async Task> ListAsync( + string? search, string? status, Guid? shippingBatchId, int page, int pageSize, CancellationToken ct = default) + { + var query = db.CustomsDeclarations.AsNoTracking().Include(x => x.Lines).AsQueryable(); + + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new CustomsValidationException(nameof(status), "报关资料状态无效。"); + query = query.Where(x => x.Status == parsed); + } + + if (shippingBatchId is { } batchId) query = query.Where(x => x.ShippingBatchId == batchId); + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => x.ShippingBatchNo.Contains(term) + || x.SalesOrderNo.Contains(term) + || x.CustomerName.Contains(term) + || (x.DeclarationNo != null && x.DeclarationNo.Contains(term)) + || (x.CustomerPoNo != null && x.CustomerPoNo.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(x => new CustomsDeclarationListItemDto( + x.Id, x.ShippingBatchId, x.ShippingBatchNo, x.Version, x.DeclarationNo, + x.SalesOrderNo, x.CustomerName, x.Currency, x.Status.ToString(), + x.TotalQuantity, x.TotalAmount, x.Lines.Count, x.UpdatedAt)).ToList(); + } + + public async Task GetAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadAsync(id, ct)); + + public async Task CreateFromShippingBatchAsync( + CreateCustomsDeclarationRequest request, CancellationToken ct = default) + { + if (request.ShippingBatchId == Guid.Empty) + throw new CustomsValidationException(nameof(request.ShippingBatchId), "必须选择出货批次。"); + + var batch = await db.ShippingBatches.AsNoTracking() + .Include(x => x.Containers) + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == request.ShippingBatchId, ct) + ?? throw new CustomsNotFoundException("出货批次不存在。"); + + if (batch.Status != ShippingBatchStatus.Confirmed) + throw new CustomsConflictException("只有已确认的出货批次可以生成报关资料。"); + if (batch.Lines.Count == 0) + throw new CustomsValidationException(nameof(request.ShippingBatchId), "出货批次没有出货明细,不能生成报关资料。"); + + var hasDraft = await db.CustomsDeclarations.AnyAsync( + x => x.ShippingBatchId == batch.Id && x.Status == CustomsDeclarationStatus.Draft, ct); + if (hasDraft) + throw new CustomsConflictException("该出货批次已有草稿报关资料,请编辑现有草稿或先将其作废。"); + + var overrides = new Dictionary(); + if (request.Lines is not null) + { + var shipmentLineIds = batch.Lines.Select(x => x.Id).ToHashSet(); + foreach (var line in request.Lines) + { + if (!shipmentLineIds.Contains(line.ShipmentLineId)) + throw new CustomsValidationException(nameof(request.Lines), "报关明细覆盖项引用了不属于该出货批次的出货明细。"); + overrides[line.ShipmentLineId] = line; + } + } + + // Product customs defaults are resolved through the sales order lines + // (shipment lines carry no ProductId); they are snapshotted now. + var salesOrderLineIds = batch.Lines.Select(x => x.SalesOrderLineId).Distinct().ToList(); + var productIdBySalesLine = await db.SalesOrderLines.AsNoTracking() + .Where(x => salesOrderLineIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, x => x.ProductId, ct); + var productIds = productIdBySalesLine.Values.Distinct().ToList(); + var products = await db.Products.AsNoTracking() + .Where(x => productIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, ct); + + var version = (await db.CustomsDeclarations.AsNoTracking() + .Where(x => x.ShippingBatchId == batch.Id) + .MaxAsync(x => (int?)x.Version, ct) ?? 0) + 1; + + // Customs details of the latest confirmed declaration carry forward: + // per product (by internal SKU) and, for the header, per customer. + var skus = batch.Lines.Select(x => x.InternalSku).Distinct().ToList(); + var history = (await db.CustomsDeclarationLines.AsNoTracking() + .Where(l => skus.Contains(l.InternalSku) && l.CustomsDeclaration!.Status == CustomsDeclarationStatus.Confirmed) + .Select(l => new { l.CustomsDeclaration!.ConfirmedAt, Line = l }) + .ToListAsync(ct)) + .GroupBy(x => x.Line.InternalSku) + .ToDictionary(g => g.Key, g => g.OrderByDescending(x => x.ConfirmedAt).First().Line); + var lastForCustomer = (await db.CustomsDeclarations.AsNoTracking() + .Where(x => x.CustomerId == batch.CustomerId && x.Status == CustomsDeclarationStatus.Confirmed) + .Select(x => new { x.ConfirmedAt, x.TradeMode, x.ExemptionNature }) + .ToListAsync(ct)) + .OrderByDescending(x => x.ConfirmedAt) + .FirstOrDefault(); + + var declaration = new CustomsDeclaration + { + ShippingBatchId = batch.Id, + Version = version, + DeclarationNo = TrimOrNull(request.DeclarationNo), + InvoiceNo = TrimOrNull(request.InvoiceNo), + ShippingBatchNo = batch.BatchNo, + SalesOrderId = batch.SalesOrderId, + SalesOrderNo = batch.SalesOrderNo, + CustomerId = batch.CustomerId, + CustomerName = batch.CustomerName, + CustomerPoNo = batch.CustomerPoNo, + Currency = batch.Currency, + VesselName = batch.VesselName, + VoyageNo = batch.VoyageNo, + BillOfLadingNo = batch.BillOfLadingNo, + LoadingPort = batch.LoadingPort, + DestinationPort = batch.DestinationPort, + DestinationCountry = batch.DestinationCountry, + TransportMode = batch.TransportMode, + TradeTerm = batch.TradeTerm, + ContainerNumbers = batch.Containers.Count == 0 + ? null + : string.Join(", ", batch.Containers.Select(x => x.ContainerNo)), + TradeMode = TrimOrNull(request.TradeMode) ?? lastForCustomer?.TradeMode, + ExemptionNature = TrimOrNull(request.ExemptionNature) ?? lastForCustomer?.ExemptionNature, + ExportDate = request.ExportDate, + DeclarationDate = request.DeclarationDate, + Remark = TrimOrNull(request.Remark), + Status = CustomsDeclarationStatus.Draft + }; + + var orderedLines = batch.Lines.OrderBy(x => x.CreatedAt).ToList(); + for (var i = 0; i < orderedLines.Count; i++) + { + var source = orderedLines[i]; + overrides.TryGetValue(source.Id, out var ov); + Product? product = null; + if (productIdBySalesLine.TryGetValue(source.SalesOrderLineId, out var productId)) + products.TryGetValue(productId, out product); + history.TryGetValue(source.InternalSku, out var last); + + var quantity = ov?.Quantity ?? source.Quantity; + var unitPrice = ov?.UnitPrice ?? source.UnitPrice; + if (quantity <= 0) + throw new CustomsValidationException($"Lines[{i}].Quantity", "报关数量必须大于 0。"); + if (unitPrice < 0) + throw new CustomsValidationException($"Lines[{i}].UnitPrice", "报关单价不能小于 0。"); + + var line = new CustomsDeclarationLine + { + ShipmentLineId = source.Id, + SalesOrderLineId = source.SalesOrderLineId, + LineNumber = i + 1, + InternalSku = source.InternalSku, + ProductNameZh = source.ProductNameZh, + ProductNameEn = source.ProductNameEn, + CustomerSku = source.CustomerSku, + CustomerProductName = source.CustomerProductName, + HsCode = TrimOrNull(ov?.HsCode) ?? TrimOrNull(last?.HsCode) ?? TrimOrNull(source.HsCode) ?? TrimOrNull(product?.HsCode), + CustomsNameZh = TrimOrNull(ov?.CustomsNameZh) ?? TrimOrNull(last?.CustomsNameZh) ?? TrimOrNull(product?.CustomsNameZh), + CustomsNameEn = TrimOrNull(ov?.CustomsNameEn) ?? TrimOrNull(last?.CustomsNameEn) ?? TrimOrNull(product?.CustomsNameEn), + DeclarationElements = TrimOrNull(ov?.DeclarationElements) ?? TrimOrNull(last?.DeclarationElements) ?? TrimOrNull(product?.DeclarationElements), + OriginCountry = TrimOrNull(ov?.OriginCountry) ?? TrimOrNull(last?.OriginCountry) ?? TrimOrNull(product?.OriginCountry) ?? TrimOrNull(product?.DefaultOrigin), + DomesticSourcePlace = TrimOrNull(ov?.DomesticSourcePlace) ?? TrimOrNull(last?.DomesticSourcePlace), + ExemptionInfo = TrimOrNull(ov?.ExemptionInfo) ?? TrimOrNull(last?.ExemptionInfo), + Quantity = quantity, + Unit = TrimOrNull(ov?.CustomsUnit) ?? TrimOrNull(last?.Unit) ?? TrimOrNull(product?.CustomsUnit) ?? source.Unit, + UnitPrice = unitPrice, + CartonCount = source.CartonCount ?? 0, + TotalGrossWeight = source.TotalGrossWeight ?? 0, + TotalNetWeight = source.TotalNetWeight ?? 0, + TotalCbm = source.TotalCbm ?? 0 + }; + line.RecalculateAmount(); + declaration.Lines.Add(line); + } + + declaration.RecalculateTotals(); + db.CustomsDeclarations.Add(declaration); + await db.SaveChangesAsync(ct); + return ToDto(declaration); + } + + public async Task UpdateAsync( + Guid id, UpdateCustomsDeclarationRequest request, CancellationToken ct = default) + { + var declaration = await LoadAsync(id, ct); + try { declaration.EnsureDraft(); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + + declaration.DeclarationNo = TrimOrNull(request.DeclarationNo); + declaration.InvoiceNo = TrimOrNull(request.InvoiceNo); + declaration.ExportDate = request.ExportDate; + declaration.DeclarationDate = request.DeclarationDate; + declaration.TradeMode = TrimOrNull(request.TradeMode); + declaration.ExemptionNature = TrimOrNull(request.ExemptionNature); + declaration.Remark = TrimOrNull(request.Remark); + + if (request.Lines is not null) + { + var linesById = declaration.Lines.ToDictionary(x => x.Id); + var seen = new HashSet(); + foreach (var r in request.Lines) + { + if (!seen.Add(r.Id) || !linesById.TryGetValue(r.Id, out var line)) + throw new CustomsValidationException(nameof(request.Lines), "报关明细不存在或重复。"); + if (r.Quantity <= 0) + throw new CustomsValidationException(nameof(r.Quantity), "报关数量必须大于 0。"); + if (r.UnitPrice < 0) + throw new CustomsValidationException(nameof(r.UnitPrice), "报关单价不能小于 0。"); + + line.HsCode = TrimOrNull(r.HsCode); + line.CustomsNameZh = TrimOrNull(r.CustomsNameZh); + line.CustomsNameEn = TrimOrNull(r.CustomsNameEn); + line.Unit = TrimOrNull(r.CustomsUnit) ?? line.Unit; + line.DeclarationElements = TrimOrNull(r.DeclarationElements); + line.OriginCountry = TrimOrNull(r.OriginCountry); + line.DomesticSourcePlace = TrimOrNull(r.DomesticSourcePlace); + line.ExemptionInfo = TrimOrNull(r.ExemptionInfo); + line.Quantity = r.Quantity; + line.UnitPrice = r.UnitPrice; + line.Remark = TrimOrNull(r.Remark); + line.RecalculateAmount(); + } + } + + declaration.RecalculateTotals(); + declaration.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(declaration); + } + + public async Task ConfirmAsync( + Guid id, ConfirmCustomsDeclarationRequest? request, CancellationToken ct = default) + { + var declaration = await LoadAsync(id, ct); + + var errors = new Dictionary(); + if (declaration.Lines.Count == 0) errors["Lines"] = ["报关资料至少需要一条明细。"]; + for (var i = 0; i < declaration.Lines.Count; i++) + { + var line = declaration.Lines[i]; + if (string.IsNullOrWhiteSpace(line.HsCode)) errors[$"Lines[{i}].HsCode"] = ["确认前必须填写 HS 编码。"]; + if (string.IsNullOrWhiteSpace(line.CustomsNameZh)) errors[$"Lines[{i}].CustomsNameZh"] = ["确认前必须填写中文报关品名。"]; + if (string.IsNullOrWhiteSpace(line.Unit)) errors[$"Lines[{i}].Unit"] = ["确认前必须填写报关单位。"]; + if (line.Quantity <= 0) errors[$"Lines[{i}].Quantity"] = ["报关数量必须大于 0。"]; + if (line.UnitPrice < 0) errors[$"Lines[{i}].UnitPrice"] = ["报关单价不能小于 0。"]; + } + if (errors.Count > 0) throw new CustomsValidationException(errors); + + declaration.RecalculateTotals(); + try { declaration.Confirm(request?.ConfirmedBy); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(declaration); + } + + public async Task VoidAsync(Guid id, CancellationToken ct = default) + { + var declaration = await LoadAsync(id, ct); + try { declaration.Void(); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(declaration); + } + + // ---------- Document packages ---------- + + public async Task> ListDocumentsAsync( + Guid shippingBatchId, CancellationToken ct = default) + { + await EnsureBatchExistsAsync(shippingBatchId, ct); + var items = await db.DocumentPackages.AsNoTracking() + .Where(x => x.ShippingBatchId == shippingBatchId) + .OrderByDescending(x => x.Id) + .ToListAsync(ct); + return items.Select(ToDto).ToList(); + } + + public async Task> ListDocumentsForCustomsAsync( + Guid customsDeclarationId, CancellationToken ct = default) + { + _ = await LoadAsync(customsDeclarationId, ct); + var items = await db.DocumentPackages.AsNoTracking() + .Where(x => x.CustomsDeclarationId == customsDeclarationId) + .OrderByDescending(x => x.Id) + .ToListAsync(ct); + return items.Select(ToDto).ToList(); + } + + public async Task GetDocumentAsync( + Guid shippingBatchId, Guid documentId, CancellationToken ct = default) + => ToDto(await LoadDocumentAsync(shippingBatchId, documentId, ct)); + + public async Task GenerateDocumentAsync( + Guid shippingBatchId, GenerateDocumentPackageRequest request, CancellationToken ct = default) + { + var batch = await LoadConfirmedBatchAsync(shippingBatchId, ct); + var kind = ParseKind(request.DocumentKind); + + // A mapped template version must be fully mapped before generation; + // this throws listing every unmapped placeholder. An explicit + // TemplateVersionId with no mapping profile is refused as well. + Guid? templateVersionId = request.TemplateVersionId; + DocumentTemplateMappingProfileDto? templateProfile = null; + if (templateVersionId is { } explicitVersionId) + { + templateProfile = await templateMappings.ValidateForGenerationAsync(explicitVersionId, scannedPlaceholders: null, ct); + } + else if (Guid.TryParse(TrimOrNull(request.TemplateReference), out var referenceVersionId) + && await templateMappings.ProfileExistsAsync(referenceVersionId, ct)) + { + templateVersionId = referenceVersionId; + templateProfile = await templateMappings.ValidateForGenerationAsync(referenceVersionId, scannedPlaceholders: null, ct); + } + + CustomsDeclaration? customs = null; + if (request.CustomsDeclarationId is { } customsId) + { + customs = await LoadAsync(customsId, ct); + if (customs.ShippingBatchId != batch.Id) + throw new CustomsValidationException(nameof(request.CustomsDeclarationId), "报关资料不属于该出货批次。"); + } + else if (CustomsKinds.Contains(kind)) + { + customs = await db.CustomsDeclarations.AsNoTracking() + .Include(x => x.Lines) + .Where(x => x.ShippingBatchId == batch.Id && x.Status == CustomsDeclarationStatus.Confirmed) + .OrderByDescending(x => x.Version) + .FirstOrDefaultAsync(ct); + } + + if (CustomsKinds.Contains(kind)) + { + if (customs is null) + throw new CustomsValidationException(nameof(request.CustomsDeclarationId), "生成报关单证前必须先确认该出货批次的报关资料。"); + if (customs.Status != CustomsDeclarationStatus.Confirmed) + throw new CustomsConflictException("只有已确认的报关资料可以生成报关单证包。"); + } + + var version = (await db.DocumentPackages.AsNoTracking() + .Where(x => x.ShippingBatchId == batch.Id && x.DocumentKind == kind) + .MaxAsync(x => (int?)x.Version, ct) ?? 0) + 1; + + var package = new DocumentPackage + { + ShippingBatchId = batch.Id, + CustomsDeclarationId = customs?.Id, + DocumentKind = kind, + Status = DocumentPackageStatus.Generated, + Version = version, + PackageNo = $"DOC-{batch.BatchNo}-{kind.ToString().ToUpperInvariant()}-{version}", + TemplateReference = templateProfile?.TemplateReference ?? TrimOrNull(request.TemplateReference), + TemplateVersion = TrimOrNull(request.TemplateVersion), + TemplateVersionId = templateVersionId, + OutputFormat = TrimOrNull(request.OutputFormat), + GeneratedFileReference = null, + GeneratedFileName = null, + GeneratedAt = DateTimeOffset.UtcNow, + GeneratedBy = TrimOrNull(request.GeneratedBy), + Remark = TrimOrNull(request.Remark) + }; + + if (customs is not null) + { + package.Currency = customs.Currency; + package.LineCount = customs.Lines.Count; + package.TotalQuantity = customs.TotalQuantity; + package.TotalAmount = customs.TotalAmount; + package.TotalCartonCount = customs.TotalCartonCount; + package.TotalGrossWeight = customs.TotalGrossWeight; + package.TotalNetWeight = customs.TotalNetWeight; + package.TotalCbm = customs.TotalCbm; + } + else + { + package.Currency = batch.Currency; + package.LineCount = batch.Lines.Count; + package.TotalQuantity = batch.TotalQuantity; + package.TotalAmount = batch.TotalAmount; + package.TotalCartonCount = batch.TotalCartonCount; + package.TotalGrossWeight = batch.TotalGrossWeight; + package.TotalNetWeight = batch.TotalNetWeight; + package.TotalCbm = batch.TotalCbm; + } + + db.DocumentPackages.Add(package); + await db.SaveChangesAsync(ct); + if (templateProfile is not null && templateVersionId is { } usedVersionId) + await templateMappings.LockAfterGenerationAsync(usedVersionId, package.Id, ct); + return ToDto(package); + } + + public async Task GenerateForCustomsAsync( + Guid customsDeclarationId, GenerateCustomsDocumentPackageRequest request, CancellationToken ct = default) + { + var declaration = await LoadAsync(customsDeclarationId, ct); + if (declaration.Status != CustomsDeclarationStatus.Confirmed) + throw new CustomsConflictException("只有已确认的报关资料可以生成单证包。"); + + return await GenerateDocumentAsync(declaration.ShippingBatchId, new GenerateDocumentPackageRequest( + request.DocumentKind, declaration.Id, request.TemplateReference, request.TemplateVersion, + request.OutputFormat, request.GeneratedBy, request.Remark, request.TemplateVersionId), ct); + } + + public async Task ConfirmDocumentAsync( + Guid shippingBatchId, Guid documentId, DocumentPackageActionRequest? request, CancellationToken ct = default) + { + var package = await LoadDocumentAsync(shippingBatchId, documentId, ct); + try { package.Confirm(request?.Actor); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(package); + } + + public async Task ExportDocumentAsync( + Guid shippingBatchId, Guid documentId, DocumentPackageActionRequest? request, CancellationToken ct = default) + { + var package = await LoadDocumentAsync(shippingBatchId, documentId, ct); + try { package.MarkExported(request?.Actor); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(package); + } + + public async Task VoidDocumentAsync( + Guid shippingBatchId, Guid documentId, CancellationToken ct = default) + { + var package = await LoadDocumentAsync(shippingBatchId, documentId, ct); + try { package.Void(); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return ToDto(package); + } + + // ---------- Helpers ---------- + + private async Task LoadAsync(Guid id, CancellationToken ct) + => await db.CustomsDeclarations + .Include(x => x.Lines.OrderBy(l => l.LineNumber)) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new CustomsNotFoundException("报关资料不存在。"); + + private async Task LoadDocumentAsync(Guid shippingBatchId, Guid documentId, CancellationToken ct) + { + await EnsureBatchExistsAsync(shippingBatchId, ct); + return await db.DocumentPackages.SingleOrDefaultAsync( + x => x.Id == documentId && x.ShippingBatchId == shippingBatchId, ct) + ?? throw new CustomsNotFoundException("单证包不存在。"); + } + + private async Task EnsureBatchExistsAsync(Guid shippingBatchId, CancellationToken ct) + { + if (!await db.ShippingBatches.AsNoTracking().AnyAsync(x => x.Id == shippingBatchId, ct)) + throw new CustomsNotFoundException("出货批次不存在。"); + } + + private async Task LoadConfirmedBatchAsync(Guid shippingBatchId, CancellationToken ct) + { + var batch = await db.ShippingBatches.AsNoTracking() + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == shippingBatchId, ct) + ?? throw new CustomsNotFoundException("出货批次不存在。"); + if (batch.Status != ShippingBatchStatus.Confirmed) + throw new CustomsConflictException("只有已确认的出货批次可以生成单证包。"); + if (batch.Lines.Count == 0) + throw new CustomsValidationException(nameof(shippingBatchId), "出货批次没有出货明细,不能生成单证包。"); + return batch; + } + + private static DocumentKind ParseKind(string? value) + { + if (string.IsNullOrWhiteSpace(value) || !Enum.TryParse(value.Trim(), ignoreCase: true, out var kind)) + throw new CustomsValidationException(nameof(GenerateDocumentPackageRequest.DocumentKind), + "单证类型无效,可选值:CustomsInvoice、CustomsPackingList、CustomsSalesContract、CustomsDeclarationData、CommercialInvoice、PackingList。"); + return kind; + } + + private static string? TrimOrNull(string? v) => string.IsNullOrWhiteSpace(v) ? null : v.Trim(); + + private static CustomsDeclarationLineDto ToDto(CustomsDeclarationLine l) => new( + l.Id, l.CustomsDeclarationId, l.ShipmentLineId, l.SalesOrderLineId, l.LineNumber, + l.InternalSku, l.ProductNameZh, l.ProductNameEn, l.CustomerSku, l.CustomerProductName, + l.HsCode, l.CustomsNameZh, l.CustomsNameEn, l.DeclarationElements, l.OriginCountry, + l.DomesticSourcePlace, l.ExemptionInfo, l.Quantity, l.Unit, l.UnitPrice, l.Amount, + l.CartonCount, l.TotalGrossWeight, l.TotalNetWeight, l.TotalCbm, l.Remark); + + private static CustomsDeclarationDto ToDto(CustomsDeclaration d) => new( + d.Id, d.ShippingBatchId, d.Version, d.DeclarationNo, d.ShippingBatchNo, d.SalesOrderId, + d.SalesOrderNo, d.CustomerId, d.CustomerName, d.CustomerPoNo, d.Currency, d.VesselName, + d.VoyageNo, d.BillOfLadingNo, d.LoadingPort, d.DestinationPort, d.DestinationCountry, + d.TransportMode, d.TradeTerm, d.ContainerNumbers, d.TradeMode, d.ExemptionNature, + d.ExportDate, d.DeclarationDate, d.Status.ToString(), d.TotalQuantity, d.TotalAmount, + d.TotalCartonCount, d.TotalGrossWeight, d.TotalNetWeight, d.TotalCbm, d.Remark, + d.ConfirmedAt, d.ConfirmedBy, d.VoidedAt, d.CreatedAt, d.UpdatedAt, + d.Lines.OrderBy(x => x.LineNumber).Select(ToDto).ToList(), d.InvoiceNo); + + private static DocumentPackageDto ToDto(DocumentPackage p) => new( + p.Id, p.ShippingBatchId, p.CustomsDeclarationId, p.PackageNo, p.DocumentKind.ToString(), + p.Status.ToString(), p.Version, p.TemplateReference, p.TemplateVersion, p.OutputFormat, + p.GeneratedFileReference, p.GeneratedFileName, p.Currency, p.LineCount, p.TotalQuantity, + p.TotalAmount, p.TotalCartonCount, p.TotalGrossWeight, p.TotalNetWeight, p.TotalCbm, + p.GeneratedAt, p.GeneratedBy, p.ConfirmedAt, p.ConfirmedBy, p.ExportedAt, p.ExportedBy, + p.VoidedAt, p.Remark, p.CreatedAt, p.UpdatedAt, p.TemplateVersionId); +} diff --git a/src/Leiren.Erp.Application/Customs/DocumentRenderSource.cs b/src/Leiren.Erp.Application/Customs/DocumentRenderSource.cs new file mode 100644 index 0000000..c73f9e4 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/DocumentRenderSource.cs @@ -0,0 +1,34 @@ +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +/// +/// Data a shipping-batch document is rendered from besides the batch itself: +/// the latest confirmed customs declaration (报关资料), the customer master +/// (address for the "TO" block) and the primary order date. +/// +public sealed record DocumentRenderSource(CustomsDeclaration? Declaration, Customer? Customer, DateOnly? OrderDate) +{ + public static readonly DocumentRenderSource Empty = new(null, null, null); + + /// Customs documents (报关发票/装箱单/外销合同/报关单) are read from the declaration. + public static bool IsCustomsKind(DocumentKind kind) => kind is DocumentKind.CustomsInvoice + or DocumentKind.CustomsPackingList or DocumentKind.CustomsSalesContract or DocumentKind.CustomsDeclarationData; + + public static async Task LoadAsync(ICustomsDbContext db, ShippingBatch batch, CancellationToken ct) + { + var declaration = await db.CustomsDeclarations.AsNoTracking() + .Include(x => x.Lines) + .Where(x => x.ShippingBatchId == batch.Id && x.Status == CustomsDeclarationStatus.Confirmed) + .OrderByDescending(x => x.Version) + .FirstOrDefaultAsync(ct); + var customer = await db.Customers.AsNoTracking().SingleOrDefaultAsync(x => x.Id == batch.CustomerId, ct); + var orderDate = await db.SalesOrders.AsNoTracking() + .Where(x => x.Id == batch.SalesOrderId) + .Select(x => (DateOnly?)x.OrderDate) + .FirstOrDefaultAsync(ct); + return new DocumentRenderSource(declaration, customer, orderDate); + } +} diff --git a/src/Leiren.Erp.Application/Customs/DocumentTemplateCatalogService.cs b/src/Leiren.Erp.Application/Customs/DocumentTemplateCatalogService.cs new file mode 100644 index 0000000..9176e96 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/DocumentTemplateCatalogService.cs @@ -0,0 +1,168 @@ +using Leiren.Erp.Application.Billing; +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Application.Purchasing; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +/// +/// Template editor backend: lists every imported template (current version +/// per template) with its mapping state, and renders previews against chosen +/// test data without storing anything. Shipping-batch kinds render through +/// their field mappings (unmapped placeholders stay visible); purchase-contract +/// templates render with the contract renderer's built-in placeholders. +/// +public sealed class DocumentTemplateCatalogService( + ICustomsDbContext customs, + IPurchasingDbContext purchasing, + FileService files, + DocumentTemplateMappingService mappings, + BillingDocumentExportService billingDocuments) +{ + public IReadOnlyList ListKinds() => DocumentTemplateKinds.All; + + public async Task> ListAsync(CancellationToken ct = default) + { + var current = await files.ListAsync( + DocumentTemplateService.TemplateOwnerType, null, null, null, currentOnly: true, 1, 200, ct); + var result = new List(current.Count); + // A template imported for one customer stores that customer as the file owner. + var ownerIds = current.Select(x => x.OwnerId).Distinct().ToList(); + var customers = await customs.Customers.AsNoTracking() + .Where(x => ownerIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, x => x.Name, ct); + foreach (var item in current) + { + var kind = DocumentTemplateKinds.Find(item.Category); + if (kind is null) continue; + var file = await files.GetAsync(item.Id, ct); + + IReadOnlyList placeholders; + IReadOnlyList unfilled; + var hasProfile = kind.UsesFieldMapping && await mappings.ProfileExistsAsync(item.Id, ct); + var locked = false; + if (hasProfile) + { + var profile = await mappings.GetProfileAsync(item.Id, ct); + placeholders = profile.Placeholders; + unfilled = profile.UnmappedPlaceholders; + locked = profile.IsLocked; + } + else + { + placeholders = TemplatePlaceholderScanner.Scan(await ReadAsync(item.Id, ct)) + .Placeholders.Select(x => x.Name).ToList(); + unfilled = kind.UsesFieldMapping + ? placeholders + : placeholders.Where(x => !kind.BuiltInFields.Contains(x, StringComparer.OrdinalIgnoreCase)).ToList(); + } + + result.Add(new DocumentTemplateListItemDto( + item.FileGroupId, item.Id, + string.IsNullOrWhiteSpace(file.Description) ? Path.GetFileNameWithoutExtension(file.OriginalFileName) : file.Description, + kind.Key, item.Version, item.OriginalFileName, item.UploadedBy, item.CreatedAt, + placeholders, unfilled, hasProfile, locked, + customers.ContainsKey(item.OwnerId) ? item.OwnerId : null, + customers.GetValueOrDefault(item.OwnerId))); + } + return result + .OrderBy(x => DocumentTemplateKinds.All.ToList().FindIndex(k => k.Key == x.DocumentKind)) + .ThenByDescending(x => x.UploadedAt) + .ToList(); + } + + public async Task<(byte[] Bytes, string FileName)> PreviewAsync( + Guid templateVersionId, PreviewDocumentTemplateRequest request, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(request); + FileAttachmentDto template; + try + { + template = await files.GetAsync(templateVersionId, ct); + } + catch (FilesNotFoundException) + { + throw new CustomsNotFoundException("模板版本文件不存在。"); + } + var kind = DocumentTemplateKinds.Find(template.Category) + ?? throw new CustomsValidationException("TemplateVersionId", "该文件不是已导入的单证模板。"); + var bytes = await ReadAsync(templateVersionId, ct); + var stem = Path.GetFileNameWithoutExtension(template.OriginalFileName); + + if (kind.DataSource == DocumentTemplateKinds.PurchaseContract) + { + if (request.PurchaseContractId is not { } contractId) + throw new CustomsValidationException(nameof(request.PurchaseContractId), "请选择一份采购合同作为测试数据。"); + var contract = await purchasing.PurchaseContracts.AsNoTracking() + .Include(x => x.Tasks) + .SingleOrDefaultAsync(x => x.Id == contractId, ct) + ?? throw new CustomsNotFoundException("采购合同不存在。"); + var lines = contract.Tasks.Where(x => x.Status != PurchaseTaskStatus.Cancelled).OrderBy(x => x.CreatedAt).ToList(); + try + { + return (PurchaseContractTemplateRenderer.Render(bytes, contract, lines, DateTimeOffset.UtcNow), $"{stem}-预览.xlsx"); + } + catch (PurchasingValidationException ex) + { + throw new CustomsValidationException(ex.Errors); + } + } + + if (kind.DataSource == DocumentTemplateKinds.SupplierInvoiceNotice) + { + if (request.SupplierInvoiceNoticeId is not { } noticeId) + throw new CustomsValidationException(nameof(request.SupplierInvoiceNoticeId), "请选择一份开票通知作为测试数据。"); + try + { + return (await billingDocuments.PreviewAsync(bytes, noticeId, kind.DisplayName, ct), $"{stem}-预览.xlsx"); + } + catch (BillingValidationException ex) + { + throw new CustomsValidationException(ex.Errors); + } + catch (BillingNotFoundException ex) + { + throw new CustomsNotFoundException(ex.Message); + } + } + if (request.ShippingBatchId is not { } batchId) + throw new CustomsValidationException(nameof(request.ShippingBatchId), "请选择一个出货批次作为测试数据。"); + var batch = await customs.ShippingBatches.AsNoTracking() + .Include(x => x.Containers) + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == batchId, ct) + ?? throw new CustomsNotFoundException("出货批次不存在。"); + if (batch.Lines.Count == 0) + throw new CustomsValidationException(nameof(request.ShippingBatchId), "该出货批次没有出货明细,无法预览。"); + + var mapped = new Dictionary(StringComparer.Ordinal); + if (await mappings.ProfileExistsAsync(templateVersionId, ct)) + { + foreach (var m in (await mappings.GetProfileAsync(templateVersionId, ct)).Mappings) + { + mapped[DocumentTemplateFieldMapping.NormalizePlaceholderKey(m.Placeholder)] = new CiPlMappedField( + m.Placeholder, m.BusinessField, + DocumentTemplateFields.TryGet(m.BusinessField, out var def) ? def.Scope : TemplateFieldScope.Header, + m.NumberFormat); + } + } + + var source = await DocumentRenderSource.LoadAsync(customs, batch, ct); + var rendered = CiPlTemplateRenderer.Render( + bytes, batch, batch.Lines.OrderBy(x => x.CreatedAt).ThenBy(x => x.Id).ToList(), + Enum.Parse(kind.Key), source, mapped, DateTimeOffset.UtcNow, allowUnmapped: true); + return (rendered, $"{stem}-预览.xlsx"); + } + + private async Task ReadAsync(Guid fileId, CancellationToken ct) + { + await using var content = (await files.OpenDownloadAsync(fileId, ct)).Content; + using var buffer = new MemoryStream(); + await content.CopyToAsync(buffer, ct); + return buffer.ToArray(); + } +} diff --git a/src/Leiren.Erp.Application/Customs/DocumentTemplateFields.cs b/src/Leiren.Erp.Application/Customs/DocumentTemplateFields.cs new file mode 100644 index 0000000..95a2c8b --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/DocumentTemplateFields.cs @@ -0,0 +1,104 @@ +using Leiren.Erp.Domain.Enums; + +namespace Leiren.Erp.Application.Customs; + +/// One allowed business field a template placeholder may map to. +public sealed record TemplateFieldDefinition(string Key, string DisplayName, TemplateFieldScope Scope, string ValueType); + +/// +/// The closed catalog of business fields available to CI/PL and customs +/// document templates. Values come from the confirmed shipping-batch snapshot +/// and, for the customs fields, the confirmed customs declaration (报关资料) +/// of the batch — never from current product master data. Customs document +/// kinds take quantity, unit, price and HS code from the declaration. Keys are +/// unique; the line-level weight/CBM keys carry a Line prefix so they +/// cannot collide with the document totals. +/// +public static class DocumentTemplateFields +{ + public static readonly IReadOnlyList All = + [ + // Header — shipping batch / sales order / logistics snapshot + new("BatchNo", "出货批次号", TemplateFieldScope.Header, "String"), + new("SalesOrderNo", "销售订单号", TemplateFieldScope.Header, "String"), + new("CustomerName", "客户名称", TemplateFieldScope.Header, "String"), + new("CustomerPoNo", "客户PO号", TemplateFieldScope.Header, "String"), + new("Currency", "币种", TemplateFieldScope.Header, "String"), + new("ShipmentDate", "出货日期", TemplateFieldScope.Header, "Date"), + new("CutoffDate", "截关日期", TemplateFieldScope.Header, "Date"), + new("Etd", "ETD", TemplateFieldScope.Header, "Date"), + new("Eta", "ETA", TemplateFieldScope.Header, "Date"), + new("VesselName", "船名", TemplateFieldScope.Header, "String"), + new("VoyageNo", "航次", TemplateFieldScope.Header, "String"), + new("BillOfLadingNo", "提单号", TemplateFieldScope.Header, "String"), + new("LoadingPort", "装货港", TemplateFieldScope.Header, "String"), + new("DestinationPort", "目的港", TemplateFieldScope.Header, "String"), + new("DestinationCountry", "目的国", TemplateFieldScope.Header, "String"), + new("TransportMode", "运输方式", TemplateFieldScope.Header, "String"), + new("TradeTerm", "贸易术语", TemplateFieldScope.Header, "String"), + new("FreightForwarder", "货代", TemplateFieldScope.Header, "String"), + new("ContainerNumbers", "集装箱号", TemplateFieldScope.Header, "String"), + new("DeclarationNo", "报关单号", TemplateFieldScope.Header, "String"), + new("DocumentKind", "单证类型", TemplateFieldScope.Header, "String"), + new("GeneratedDate", "生成日期", TemplateFieldScope.Header, "Date"), + new("InvoiceNo", "发票编号", TemplateFieldScope.Header, "String"), + new("CustomerAddress", "客户地址", TemplateFieldScope.Header, "String"), + new("OrderDate", "订单日期", TemplateFieldScope.Header, "Date"), + new("ExportDate", "出口日期", TemplateFieldScope.Header, "Date"), + new("DeclarationDate", "申报日期", TemplateFieldScope.Header, "Date"), + new("TradeMode", "监管方式", TemplateFieldScope.Header, "String"), + new("ExemptionNature", "征免性质", TemplateFieldScope.Header, "String"), + new("CurrencyNameZh", "币制(中文)", TemplateFieldScope.Header, "String"), + + // Line — one value per shipment line (actual packing snapshot) + new("LineNumber", "行号", TemplateFieldScope.Line, "Integer"), + new("InternalSku", "内部货号", TemplateFieldScope.Line, "String"), + new("ProductNameZh", "中文品名", TemplateFieldScope.Line, "String"), + new("ProductNameEn", "英文品名", TemplateFieldScope.Line, "String"), + new("CustomerSku", "客户SKU", TemplateFieldScope.Line, "String"), + new("CustomerProductName", "客户品名", TemplateFieldScope.Line, "String"), + new("HsCode", "HS编码", TemplateFieldScope.Line, "String"), + new("Quantity", "数量", TemplateFieldScope.Line, "Decimal"), + new("Unit", "单位", TemplateFieldScope.Line, "String"), + new("UnitPrice", "单价", TemplateFieldScope.Line, "Decimal"), + new("Amount", "金额", TemplateFieldScope.Line, "Decimal"), + new("PackingRate", "装箱率", TemplateFieldScope.Line, "Integer"), + new("CartonCount", "箱数", TemplateFieldScope.Line, "Integer"), + new("CartonLength", "外箱长(cm)", TemplateFieldScope.Line, "Decimal"), + new("CartonWidth", "外箱宽(cm)", TemplateFieldScope.Line, "Decimal"), + new("CartonHeight", "外箱高(cm)", TemplateFieldScope.Line, "Decimal"), + new("CartonGrossWeight", "单箱毛重", TemplateFieldScope.Line, "Decimal"), + new("CartonNetWeight", "单箱净重", TemplateFieldScope.Line, "Decimal"), + new("LineTotalGrossWeight", "本行总毛重", TemplateFieldScope.Line, "Decimal"), + new("LineTotalNetWeight", "本行总净重", TemplateFieldScope.Line, "Decimal"), + new("LineTotalCbm", "本行总体积(CBM)", TemplateFieldScope.Line, "Decimal"), + new("Remark", "备注", TemplateFieldScope.Line, "String"), + new("CustomsNameZh", "报关中文品名", TemplateFieldScope.Line, "String"), + new("CustomsNameEn", "报关英文品名", TemplateFieldScope.Line, "String"), + new("DeclarationElements", "申报要素", TemplateFieldScope.Line, "String"), + new("OriginCountry", "原产国", TemplateFieldScope.Line, "String"), + new("DomesticSourcePlace", "境内货源地", TemplateFieldScope.Line, "String"), + new("ExemptionInfo", "征免", TemplateFieldScope.Line, "String"), + new("LineCurrencyZh", "币制(明细行)", TemplateFieldScope.Line, "String"), + + // Total — aggregated over the batch snapshot at generation time + new("LineCount", "明细行数", TemplateFieldScope.Total, "Integer"), + new("TotalQuantity", "总数量", TemplateFieldScope.Total, "Decimal"), + new("TotalAmount", "总金额", TemplateFieldScope.Total, "Decimal"), + new("TotalCartonCount", "总箱数", TemplateFieldScope.Total, "Integer"), + new("TotalGrossWeight", "总毛重", TemplateFieldScope.Total, "Decimal"), + new("TotalNetWeight", "总净重", TemplateFieldScope.Total, "Decimal"), + new("TotalCbm", "总体积(CBM)", TemplateFieldScope.Total, "Decimal"), + ]; + + private static readonly Dictionary ByKey = + All.ToDictionary(x => x.Key, StringComparer.OrdinalIgnoreCase); + + public static bool TryGet(string? key, out TemplateFieldDefinition definition) + { + definition = null!; + return !string.IsNullOrWhiteSpace(key) && ByKey.TryGetValue(key.Trim(), out definition!); + } + + public static IReadOnlyList Keys => All.Select(x => x.Key).ToList(); +} diff --git a/src/Leiren.Erp.Application/Customs/DocumentTemplateMappingService.cs b/src/Leiren.Erp.Application/Customs/DocumentTemplateMappingService.cs new file mode 100644 index 0000000..c155098 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/DocumentTemplateMappingService.cs @@ -0,0 +1,432 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +/// +/// Persistence and validation for versioned CI/PL template field mappings. +/// A profile belongs to exactly one immutable template version +/// (, the +/// scanned template file version id). Every placeholder found in the template +/// must map to a field from before a +/// document may be generated; generation locks the profile forever. +/// +public sealed class DocumentTemplateMappingService(IDocumentTemplateMappingDbContext db) +{ + public IReadOnlyList ListFields() + => DocumentTemplateFields.All + .Select(x => new DocumentTemplateFieldDto(x.Key, x.DisplayName, x.Scope.ToString(), x.ValueType)) + .ToList(); + + // ---------- Profiles ---------- + + public async Task CreateProfileAsync( + Guid templateVersionId, CreateDocumentTemplateMappingProfileRequest request, CancellationToken ct = default) + { + if (!await db.FileAttachments.AsNoTracking().AnyAsync(x => x.Id == templateVersionId && !x.IsDeleted, ct)) + throw new CustomsNotFoundException("模板版本(扫描的模板文件)不存在。"); + if (await db.DocumentTemplateMappingProfiles.AsNoTracking().AnyAsync(x => x.TemplateVersionId == templateVersionId, ct)) + throw new CustomsConflictException("该模板版本已存在字段映射,请直接编辑现有映射或上传新模板版本。"); + + var errors = new ErrorBag(); + var placeholders = NormalizePlaceholders(request.Placeholders, errors); + var mappings = ValidateMappingInputs(request.Mappings, placeholders, errors); + errors.ThrowIfAny(); + + var profile = new DocumentTemplateMappingProfile + { + TemplateVersionId = templateVersionId, + TemplateId = request.TemplateId, + TemplateReference = TrimOrNull(request.TemplateReference) ?? templateVersionId.ToString("D"), + DocumentKind = TrimOrNull(request.DocumentKind), + Placeholders = placeholders + }; + foreach (var (placeholder, businessField, numberFormat) in mappings) + profile.Mappings.Add(NewMapping(profile, placeholder, businessField, numberFormat)); + + db.DocumentTemplateMappingProfiles.Add(profile); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + public async Task GetProfileAsync(Guid templateVersionId, CancellationToken ct = default) + => ToDto(await LoadProfileAsync(templateVersionId, ct)); + + public Task ProfileExistsAsync(Guid templateVersionId, CancellationToken ct = default) + => db.DocumentTemplateMappingProfiles.AsNoTracking().AnyAsync(x => x.TemplateVersionId == templateVersionId, ct); + + public async Task> ListProfilesAsync(Guid? templateId, CancellationToken ct = default) + { + IQueryable query = db.DocumentTemplateMappingProfiles.AsNoTracking().Include(x => x.Mappings); + if (templateId is { } id) query = query.Where(x => x.TemplateId == id); + var items = await query.OrderByDescending(x => x.Id).ToListAsync(ct); + return items.Select(ToDto).ToList(); + } + + public async Task UpdateProfileAsync( + Guid templateVersionId, UpdateDocumentTemplateMappingProfileRequest request, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + + var errors = new ErrorBag(); + var placeholders = request.Placeholders is null ? profile.Placeholders : NormalizePlaceholders(request.Placeholders, errors); + if (request.Placeholders is not null) + { + var keys = placeholders.Select(DocumentTemplateFieldMapping.NormalizePlaceholderKey).ToHashSet(StringComparer.Ordinal); + var orphaned = profile.Mappings.Where(m => !keys.Contains(m.PlaceholderKey)).Select(m => m.Placeholder).ToList(); + if (orphaned.Count > 0) + errors.Add("Placeholders", $"以下映射的占位符不在新占位符列表中,请先删除这些映射:{string.Join("、", orphaned)}。"); + } + errors.ThrowIfAny(); + + profile.TemplateId = request.TemplateId; + profile.TemplateReference = TrimOrNull(request.TemplateReference) ?? profile.TemplateReference; + profile.DocumentKind = TrimOrNull(request.DocumentKind); + profile.Placeholders = placeholders; + profile.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + public async Task DeleteProfileAsync(Guid templateVersionId, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + db.DocumentTemplateFieldMappings.RemoveRange(profile.Mappings); + db.DocumentTemplateMappingProfiles.Remove(profile); + await db.SaveChangesAsync(ct); + } + + // ---------- Mapping CRUD ---------- + + public async Task AddMappingAsync( + Guid templateVersionId, SaveDocumentTemplateFieldMappingRequest request, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + + var errors = new ErrorBag(); + var input = ValidateMappingInputs([request], profile.Placeholders, errors); + if (input.Count == 1 && profile.Mappings.Any(m => m.PlaceholderKey == DocumentTemplateFieldMapping.NormalizePlaceholderKey(input[0].Placeholder))) + errors.Add(nameof(request.Placeholder), $"占位符 {input[0].Placeholder} 已有映射,不能重复映射。"); + errors.ThrowIfAny(); + + var (placeholder, businessField, numberFormat) = input[0]; + profile.Mappings.Add(NewMapping(profile, placeholder, businessField, numberFormat)); + profile.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + public async Task UpdateMappingAsync( + Guid templateVersionId, Guid mappingId, SaveDocumentTemplateFieldMappingRequest request, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + var mapping = profile.Mappings.SingleOrDefault(x => x.Id == mappingId) + ?? throw new CustomsNotFoundException("字段映射不存在。"); + + var errors = new ErrorBag(); + var input = ValidateMappingInputs([request], profile.Placeholders, errors); + if (input.Count == 1) + { + var key = DocumentTemplateFieldMapping.NormalizePlaceholderKey(input[0].Placeholder); + if (profile.Mappings.Any(m => m.Id != mappingId && m.PlaceholderKey == key)) + errors.Add(nameof(request.Placeholder), $"占位符 {input[0].Placeholder} 已有映射,不能重复映射。"); + } + errors.ThrowIfAny(); + + var (placeholder, businessField, numberFormat) = input[0]; + mapping.Placeholder = placeholder; + mapping.PlaceholderKey = DocumentTemplateFieldMapping.NormalizePlaceholderKey(placeholder); + mapping.BusinessField = businessField; + mapping.NumberFormat = numberFormat; + mapping.Touch(); + profile.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + public async Task DeleteMappingAsync( + Guid templateVersionId, Guid mappingId, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + var mapping = profile.Mappings.SingleOrDefault(x => x.Id == mappingId) + ?? throw new CustomsNotFoundException("字段映射不存在。"); + db.DocumentTemplateFieldMappings.Remove(mapping); + profile.Mappings.Remove(mapping); + profile.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + public async Task ReplaceMappingsAsync( + Guid templateVersionId, ReplaceDocumentTemplateFieldMappingsRequest request, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + + var errors = new ErrorBag(); + var mappings = ValidateMappingInputs(request.Mappings, profile.Placeholders, errors); + errors.ThrowIfAny(); + + db.DocumentTemplateFieldMappings.RemoveRange(profile.Mappings); + profile.Mappings.Clear(); + foreach (var (placeholder, businessField, numberFormat) in mappings) + profile.Mappings.Add(NewMapping(profile, placeholder, businessField, numberFormat)); + profile.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + public async Task CopyMappingsAsync( + Guid templateVersionId, CopyDocumentTemplateMappingsRequest request, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + await EnsureMutableAsync(profile, ct); + var source = await LoadProfileAsync(request.SourceTemplateVersionId, ct); + + var inputs = source.Mappings + .Select(m => new SaveDocumentTemplateFieldMappingRequest(m.Placeholder, m.BusinessField, m.NumberFormat)) + .ToList(); + var errors = new ErrorBag(); + var mappings = ValidateMappingInputs(inputs, profile.Placeholders, errors); + foreach (var duplicate in mappings.Where(m => profile.Mappings.Any(x => + x.PlaceholderKey == DocumentTemplateFieldMapping.NormalizePlaceholderKey(m.Placeholder)))) + errors.Add(nameof(SaveDocumentTemplateFieldMappingRequest.Placeholder), $"占位符 {duplicate.Placeholder} 已有映射,不能重复映射。"); + errors.ThrowIfAny(); + + foreach (var (placeholder, businessField, numberFormat) in mappings) + profile.Mappings.Add(NewMapping(profile, placeholder, businessField, numberFormat)); + profile.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + // ---------- Generation validation / locking ---------- + + public async Task ValidateAsync( + Guid templateVersionId, IReadOnlyCollection? scannedPlaceholders = null, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + return BuildValidation(profile, scannedPlaceholders); + } + + /// + /// Throws listing every unmapped + /// placeholder (and any unknown placeholder/business field) when this + /// template version is not fully mapped; otherwise returns the profile. + /// Callers generating XLSX must call this before rendering. + /// + public async Task ValidateForGenerationAsync( + Guid templateVersionId, IReadOnlyCollection? scannedPlaceholders = null, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + var result = BuildValidation(profile, scannedPlaceholders); + ThrowIfInvalid(result); + return ToDto(profile); + } + + /// Parameterless-placeholder overload of using the stored scan snapshot. + public Task EnsureGenerationAllowedAsync(Guid templateVersionId, CancellationToken ct = default) + => ValidateForGenerationAsync(templateVersionId, scannedPlaceholders: null, ct); + + /// Locks the profile after a document package was generated from it; locked mappings are immutable. + public async Task LockAfterGenerationAsync( + Guid templateVersionId, Guid documentPackageId, CancellationToken ct = default) + { + var profile = await LoadProfileAsync(templateVersionId, ct); + profile.LockAfterGeneration(documentPackageId); + await db.SaveChangesAsync(ct); + return ToDto(profile); + } + + /// Alias for . + public Task MarkUsedAsync(Guid templateVersionId, Guid documentPackageId, CancellationToken ct = default) + => LockAfterGenerationAsync(templateVersionId, documentPackageId, ct); + + // ---------- Helpers ---------- + + private async Task LoadProfileAsync(Guid templateVersionId, CancellationToken ct) + => await db.DocumentTemplateMappingProfiles + .Include(x => x.Mappings) + .SingleOrDefaultAsync(x => x.TemplateVersionId == templateVersionId, ct) + ?? throw new CustomsNotFoundException("该模板版本尚无字段映射,请先创建映射。"); + + private async Task EnsureMutableAsync(DocumentTemplateMappingProfile profile, CancellationToken ct) + { + if (!profile.IsLocked && + await db.DocumentPackages.AsNoTracking().AnyAsync(x => x.TemplateVersionId == profile.TemplateVersionId, ct)) + profile.IsLocked = true; + try { profile.EnsureMutable(); } + catch (InvalidOperationException ex) { throw new CustomsConflictException(ex.Message); } + } + + private static DocumentTemplateFieldMapping NewMapping( + DocumentTemplateMappingProfile profile, string placeholder, string businessField, string? numberFormat) => new() + { + MappingProfileId = profile.Id, + MappingProfile = profile, + TemplateVersionId = profile.TemplateVersionId, + Placeholder = placeholder, + PlaceholderKey = DocumentTemplateFieldMapping.NormalizePlaceholderKey(placeholder), + BusinessField = businessField, + NumberFormat = numberFormat + }; + + private static List NormalizePlaceholders(IReadOnlyList? raw, ErrorBag errors) + { + var result = new List(); + if (raw is null) return result; + var seen = new HashSet(StringComparer.Ordinal); + foreach (var item in raw) + { + var name = NormalizePlaceholder(item); + if (name is null) + { + errors.Add("Placeholders", $"占位符名称无效:\"{item}\"。"); + continue; + } + if (!seen.Add(DocumentTemplateFieldMapping.NormalizePlaceholderKey(name))) + errors.Add("Placeholders", $"占位符 {name} 在扫描结果中重复。"); + else + result.Add(name); + } + return result; + } + + private static List<(string Placeholder, string BusinessField, string? NumberFormat)> ValidateMappingInputs( + IReadOnlyList? inputs, + IReadOnlyList knownPlaceholders, + ErrorBag errors) + { + var result = new List<(string, string, string?)>(); + if (inputs is null) return result; + + var knownKeys = knownPlaceholders + .Select(DocumentTemplateFieldMapping.NormalizePlaceholderKey) + .ToHashSet(StringComparer.Ordinal); + var seen = new HashSet(StringComparer.Ordinal); + + foreach (var input in inputs) + { + var placeholder = NormalizePlaceholder(input.Placeholder); + if (placeholder is null) + { + errors.Add(nameof(input.Placeholder), $"占位符名称无效:\"{input.Placeholder}\"(应为不含花括号的名称,如 CustomerName)。"); + continue; + } + var key = DocumentTemplateFieldMapping.NormalizePlaceholderKey(placeholder); + if (!seen.Add(key)) + errors.Add(nameof(input.Placeholder), $"占位符 {placeholder} 重复映射。"); + if (knownKeys.Count > 0 && !knownKeys.Contains(key)) + errors.Add(nameof(input.Placeholder), $"占位符 {placeholder} 不在该模板版本的扫描结果中,不能映射。"); + + if (!DocumentTemplateFields.TryGet(input.BusinessField, out var field)) + { + errors.Add(nameof(input.BusinessField), + $"业务字段 \"{input.BusinessField}\" 不在允许字段目录中。允许字段:{string.Join("、", DocumentTemplateFields.Keys)}。"); + continue; + } + + var numberFormat = TrimOrNull(input.NumberFormat); + if (numberFormat is { Length: > 100 }) + { + errors.Add(nameof(input.NumberFormat), "数字/日期格式长度不能超过 100。"); + continue; + } + result.Add((placeholder, field.Key, numberFormat)); + } + return result; + } + + private static DocumentTemplateValidationResultDto BuildValidation( + DocumentTemplateMappingProfile profile, IReadOnlyCollection? scannedPlaceholders) + { + var errors = new ErrorBag(); + var placeholders = scannedPlaceholders is null + ? profile.Placeholders + : NormalizePlaceholders(scannedPlaceholders.ToList(), errors); + var placeholderKeys = placeholders + .Select(DocumentTemplateFieldMapping.NormalizePlaceholderKey) + .ToHashSet(StringComparer.Ordinal); + + var unmapped = placeholders + .Where(p => !profile.Mappings.Any(m => m.PlaceholderKey == DocumentTemplateFieldMapping.NormalizePlaceholderKey(p))) + .ToList(); + var unknownPlaceholders = profile.Mappings + .Where(m => placeholderKeys.Count > 0 && !placeholderKeys.Contains(m.PlaceholderKey)) + .Select(m => m.Placeholder).ToList(); + var unknownFields = profile.Mappings + .Where(m => !DocumentTemplateFields.TryGet(m.BusinessField, out _)) + .Select(m => m.BusinessField).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + + return new DocumentTemplateValidationResultDto( + profile.TemplateVersionId, + placeholders.Count > 0 && unmapped.Count == 0 && unknownPlaceholders.Count == 0 && unknownFields.Count == 0, + placeholders, unmapped, unknownPlaceholders, unknownFields, + profile.Mappings.Count(m => placeholderKeys.Contains(m.PlaceholderKey))); + } + + private static void ThrowIfInvalid(DocumentTemplateValidationResultDto result) + { + if (result.IsValid) return; + var errors = new Dictionary(); + if (result.Placeholders.Count == 0) + errors["Placeholders"] = ["该模板版本没有登记任何扫描占位符,无法确认全部占位符已映射,禁止生成。"]; + if (result.UnmappedPlaceholders.Count > 0) + errors["UnmappedPlaceholders"] = result.UnmappedPlaceholders.Select(p => $"{{{{{p}}}}}").ToArray(); + if (result.UnknownPlaceholders.Count > 0) + errors["UnknownPlaceholders"] = result.UnknownPlaceholders.Select(p => $"{{{{{p}}}}}").ToArray(); + if (result.UnknownBusinessFields.Count > 0) + errors["BusinessField"] = result.UnknownBusinessFields + .Select(f => $"业务字段 \"{f}\" 不在允许字段目录中。允许字段:{string.Join("、", DocumentTemplateFields.Keys)}。").ToArray(); + throw new CustomsValidationException(errors); + } + + private static string? NormalizePlaceholder(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) return null; + var name = raw.Trim(); + if (name.StartsWith("{{", StringComparison.Ordinal) && name.EndsWith("}}", StringComparison.Ordinal) && name.Length > 4) + name = name[2..^2].Trim(); + if (name.Length is 0 or > 200 || name.Contains('{') || name.Contains('}') || name.Contains('\n') || name.Contains('\r')) + return null; + return name; + } + + private static string? TrimOrNull(string? v) => string.IsNullOrWhiteSpace(v) ? null : v.Trim(); + + private static DocumentTemplateFieldMappingDto ToDto(DocumentTemplateFieldMapping m) => new( + m.Id, m.MappingProfileId, m.TemplateVersionId, m.Placeholder, m.BusinessField, + DocumentTemplateFields.TryGet(m.BusinessField, out var field) ? field.Scope.ToString() : "Unknown", + m.NumberFormat, m.CreatedAt, m.UpdatedAt); + + private static DocumentTemplateMappingProfileDto ToDto(DocumentTemplateMappingProfile p) + { + var mappedKeys = p.Mappings.Select(x => x.PlaceholderKey).ToHashSet(StringComparer.Ordinal); + return new DocumentTemplateMappingProfileDto( + p.Id, p.TemplateVersionId, p.TemplateId, p.TemplateReference, p.DocumentKind, + p.Placeholders, p.IsLocked, p.LockedAt, p.LockedByDocumentPackageId, p.CreatedAt, p.UpdatedAt, + p.Mappings.OrderBy(x => x.Placeholder, StringComparer.OrdinalIgnoreCase).Select(ToDto).ToList(), + p.Placeholders.Where(x => !mappedKeys.Contains(DocumentTemplateFieldMapping.NormalizePlaceholderKey(x))).ToList()); + } + + private sealed class ErrorBag + { + private readonly Dictionary> _errors = new(StringComparer.Ordinal); + public void Add(string field, string message) + { + if (!_errors.TryGetValue(field, out var list)) _errors[field] = list = []; + list.Add(message); + } + public void ThrowIfAny() + { + if (_errors.Count > 0) + throw new CustomsValidationException(_errors.ToDictionary(x => x.Key, x => x.Value.ToArray())); + } + } +} diff --git a/src/Leiren.Erp.Application/Customs/ICustomsDbContext.cs b/src/Leiren.Erp.Application/Customs/ICustomsDbContext.cs new file mode 100644 index 0000000..334b6ed --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/ICustomsDbContext.cs @@ -0,0 +1,23 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +/// +/// EF Core boundary for the Customs/Documents module; implemented by Infrastructure. +/// Shipping, Sales, and Catalog sets are read here only to snapshot a confirmed +/// shipping batch and its product customs defaults at creation time. +/// +public interface ICustomsDbContext +{ + DbSet ShippingBatches { get; } + DbSet SalesOrderLines { get; } + DbSet SalesOrders { get; } + DbSet Customers { get; } + DbSet Products { get; } + DbSet CustomsDeclarations { get; } + DbSet CustomsDeclarationLines { get; } + DbSet DocumentPackages { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Customs/IDocumentTemplateMappingDbContext.cs b/src/Leiren.Erp.Application/Customs/IDocumentTemplateMappingDbContext.cs new file mode 100644 index 0000000..1c2feb3 --- /dev/null +++ b/src/Leiren.Erp.Application/Customs/IDocumentTemplateMappingDbContext.cs @@ -0,0 +1,19 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Customs; + +/// +/// EF Core boundary for document-template field mappings; implemented by +/// Infrastructure. FileAttachments/DocumentPackages are read to verify the +/// template version exists and to lock mappings once a package is generated. +/// +public interface IDocumentTemplateMappingDbContext +{ + DbSet DocumentTemplateMappingProfiles { get; } + DbSet DocumentTemplateFieldMappings { get; } + DbSet DocumentPackages { get; } + DbSet FileAttachments { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Dashboard/DashboardService.cs b/src/Leiren.Erp.Application/Dashboard/DashboardService.cs new file mode 100644 index 0000000..b64b3c4 --- /dev/null +++ b/src/Leiren.Erp.Application/Dashboard/DashboardService.cs @@ -0,0 +1,46 @@ +using Leiren.Erp.Contracts; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Dashboard; + +public sealed class DashboardService(IDashboardDbContext db) +{ + public async Task GetSummaryAsync(CancellationToken ct = default) + { + var salesOrders = await SummarizeAsync(db.SalesOrders.AsNoTracking().Select(x => x.Status), ct); + var purchaseTasks = await SummarizeAsync(db.PurchaseTasks.AsNoTracking().Select(x => x.Status), ct); + var purchaseContracts = await SummarizeAsync(db.PurchaseContracts.AsNoTracking().Select(x => x.Status), ct); + var shippingBatches = await SummarizeAsync(db.ShippingBatches.AsNoTracking().Select(x => x.Status), ct); + var customsDeclarations = await SummarizeAsync(db.CustomsDeclarations.AsNoTracking().Select(x => x.Status), ct); + var billingNotices = await SummarizeAsync(db.SupplierInvoiceNotices.AsNoTracking().Select(x => x.Status), ct); + var products = await SummarizeAsync(db.Products.AsNoTracking().Select(x => x.Status), ct); + + return new DashboardSummaryDto( + DateTimeOffset.UtcNow, + salesOrders, + purchaseTasks, + purchaseContracts, + shippingBatches, + customsDeclarations, + billingNotices, + products); + } + + // Every enum value is reported (zero when absent) so clients render a stable summary. + private static async Task SummarizeAsync( + IQueryable statuses, CancellationToken ct) + where TStatus : struct, Enum + { + var rows = await statuses + .GroupBy(status => status) + .Select(group => new { Status = group.Key, Count = group.Count() }) + .ToListAsync(ct); + + var counts = rows.ToDictionary(row => row.Status, row => row.Count); + var byStatus = Enum.GetValues() + .Select(status => new DashboardStatusCountDto(status.ToString(), counts.GetValueOrDefault(status))) + .ToList(); + + return new DashboardSectionDto(byStatus.Sum(item => item.Count), byStatus); + } +} diff --git a/src/Leiren.Erp.Application/Dashboard/IDashboardDbContext.cs b/src/Leiren.Erp.Application/Dashboard/IDashboardDbContext.cs new file mode 100644 index 0000000..63ea06c --- /dev/null +++ b/src/Leiren.Erp.Application/Dashboard/IDashboardDbContext.cs @@ -0,0 +1,16 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Dashboard; + +/// EF Core boundary for read-only dashboard aggregates; implemented by Infrastructure. +public interface IDashboardDbContext +{ + DbSet SalesOrders { get; } + DbSet PurchaseTasks { get; } + DbSet PurchaseContracts { get; } + DbSet ShippingBatches { get; } + DbSet CustomsDeclarations { get; } + DbSet SupplierInvoiceNotices { get; } + DbSet Products { get; } +} diff --git a/src/Leiren.Erp.Application/Documents/DocumentTemplateKinds.cs b/src/Leiren.Erp.Application/Documents/DocumentTemplateKinds.cs new file mode 100644 index 0000000..626b400 --- /dev/null +++ b/src/Leiren.Erp.Application/Documents/DocumentTemplateKinds.cs @@ -0,0 +1,40 @@ +using Leiren.Erp.Application.Billing; +using Leiren.Erp.Application.Purchasing; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Application.Documents; + +/// +/// The closed set of template types the template editor imports. The key is +/// stored as the template file's category. Shipping-batch kinds are the +/// DocumentKind values and are filled through field mappings; the +/// purchase contract uses the renderer's built-in placeholder names. +/// +public static class DocumentTemplateKinds +{ + public const string ShippingBatch = "ShippingBatch"; + /// Kind key and data source of purchase-contract templates. + public const string PurchaseContract = "PurchaseContract"; + /// Data source of the supplier billing documents (开票通知 / 开票购销合同). + public const string SupplierInvoiceNotice = "SupplierInvoiceNotice"; + public const string SupplierInvoiceNoticeKind = "SupplierInvoiceNotice"; + public const string SupplierBillingContractKind = "SupplierBillingContract"; + + public static readonly IReadOnlyList All = + [ + new("CustomsInvoice", "报关发票", ShippingBatch, true, []), + new("CustomsPackingList", "报关装箱单", ShippingBatch, true, []), + new("CustomsSalesContract", "报关外销合同", ShippingBatch, true, []), + new("CustomsDeclarationData", "报关单数据", ShippingBatch, true, []), + new("CommercialInvoice", "客户 CI", ShippingBatch, true, []), + new("PackingList", "客户 PL", ShippingBatch, true, []), + new(PurchaseContract, "采购合同", PurchaseContract, false, PurchaseContractTemplateRenderer.FieldNames), + new(SupplierInvoiceNoticeKind, "开票通知", SupplierInvoiceNotice, false, BillingDocumentRenderer.FieldNames), + new(SupplierBillingContractKind, "开票购销合同", SupplierInvoiceNotice, false, BillingDocumentRenderer.FieldNames), + ]; + + public static DocumentTemplateKindDto? Find(string? key) + => string.IsNullOrWhiteSpace(key) + ? null + : All.FirstOrDefault(x => string.Equals(x.Key, key.Trim(), StringComparison.OrdinalIgnoreCase)); +} diff --git a/src/Leiren.Erp.Application/Documents/DocumentTemplateService.cs b/src/Leiren.Erp.Application/Documents/DocumentTemplateService.cs new file mode 100644 index 0000000..328a95e --- /dev/null +++ b/src/Leiren.Erp.Application/Documents/DocumentTemplateService.cs @@ -0,0 +1,172 @@ +using Leiren.Erp.Application.Files; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Application.Documents; + +/// Optional metadata supplied alongside an uploaded CI/PL template. +public sealed record DocumentTemplateUploadOptions( + string? Name, + string? DocumentKind, + Guid? CustomerId, + string? UploadedBy, + Guid? UploadedByUserId = null); + +/// +/// Stores customer CI/PL .xlsx templates through +/// (content on the server filesystem, metadata in the database) and scans +/// them for placeholders. Scanning happens before storage, so an unreadable +/// workbook or a template without any placeholder never leaves an orphan +/// file behind. No template entity is kept here: the stored file group is +/// the logical template and each file version is one immutable template +/// version, referenced by its file id. +/// +public sealed class DocumentTemplateService(FileService files, FileStorageOptions storageOptions) +{ + public const string TemplateOwnerType = "DocumentTemplate"; + + public async Task UploadAsync( + Stream content, string? originalFileName, string? contentType, + DocumentTemplateUploadOptions options, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(content); + ArgumentNullException.ThrowIfNull(options); + + var bytes = await ReadTemplateBytesAsync(content, originalFileName, ct); + var scan = ScanBytes(bytes); + + await using var stored = new MemoryStream(bytes, writable: false); + var file = await files.UploadAsync(new UploadFileCommand( + OwnerType: TemplateOwnerType, + OwnerId: options.CustomerId ?? Guid.NewGuid(), + Category: RequireKind(options.DocumentKind), + Description: NormalizeOptional(options.Name, 1000, nameof(options.Name)), + OriginalFileName: originalFileName, + ContentType: contentType, + Content: stored, + UploadedByUserId: options.UploadedByUserId, + UploadedBy: options.UploadedBy), ct); + + return ToResult(file, options.Name, options.DocumentKind, options.CustomerId, scan); + } + + /// Stores a new immutable version of the template the given file version belongs to. + public async Task UploadNewVersionAsync( + Guid fileId, Stream content, string? originalFileName, string? contentType, + DocumentTemplateUploadOptions options, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(content); + ArgumentNullException.ThrowIfNull(options); + + var existing = await files.GetAsync(fileId, ct); + EnsureTemplateFile(existing); + + var bytes = await ReadTemplateBytesAsync(content, originalFileName, ct); + var scan = ScanBytes(bytes); + + await using var stored = new MemoryStream(bytes, writable: false); + var file = await files.UploadNewVersionAsync( + fileId, stored, originalFileName, contentType, + options.DocumentKind is null ? existing.Category : RequireKind(options.DocumentKind), + NormalizeOptional(options.Name, 1000, nameof(options.Name)) ?? existing.Description, + options.UploadedByUserId, options.UploadedBy, ct); + + return ToResult(file, options.Name ?? existing.Description, + options.DocumentKind ?? existing.Category, + options.CustomerId, scan); + } + + /// Re-scans an already stored template file version. + public async Task ScanStoredAsync(Guid fileId, CancellationToken ct = default) + { + var file = await files.GetAsync(fileId, ct); + EnsureTemplateFile(file); + + var download = await files.OpenDownloadAsync(fileId, ct); + await using var content = download.Content; + var bytes = await ReadTemplateBytesAsync(content, file.OriginalFileName, ct); + var scan = ScanBytes(bytes); + + return ToResult(file, file.Description, file.Category, null, scan); + } + + private static TemplateScanResult ScanBytes(byte[] bytes) + { + var scan = TemplatePlaceholderScanner.Scan(bytes); + if (scan.Placeholders.Count == 0) + { + var detail = scan.Warnings.Count > 0 ? string.Join(" ", scan.Warnings) : null; + throw new DocumentTemplateValidationException( + "file", "模板中未找到任何 {{...}} 占位符,无法导入。" + (detail is null ? string.Empty : $" {detail}")); + } + return scan; + } + + private async Task ReadTemplateBytesAsync(Stream content, string? originalFileName, CancellationToken ct) + { + var extension = Path.GetExtension(FileService.SanitizeFileName(originalFileName)).ToLowerInvariant(); + if (extension != ".xlsx") + { + throw new DocumentTemplateValidationException( + "file", "模板必须是 .xlsx 文件。"); + } + + var maxBytes = storageOptions.MaxFileSizeBytes > 0 ? storageOptions.MaxFileSizeBytes : 50L * 1024 * 1024; + using var buffer = new MemoryStream(); + var chunk = new byte[81920]; + int read; + while ((read = await content.ReadAsync(chunk.AsMemory(), ct)) > 0) + { + if (buffer.Length + read > maxBytes) + { + throw new DocumentTemplateValidationException( + "file", $"模板文件大小超过上限 {maxBytes} 字节。"); + } + buffer.Write(chunk, 0, read); + } + if (buffer.Length == 0) + { + throw new DocumentTemplateValidationException("file", "模板文件内容为空。"); + } + return buffer.ToArray(); + } + + private static void EnsureTemplateFile(FileAttachmentDto file) + { + if (!string.Equals(file.Extension, ".xlsx", StringComparison.OrdinalIgnoreCase)) + { + throw new DocumentTemplateValidationException( + "file", "只能扫描 .xlsx 模板文件。"); + } + } + + private static DocumentTemplateUploadResultDto ToResult( + FileAttachmentDto file, string? name, string? documentKind, Guid? customerId, TemplateScanResult scan) => new( + TemplateId: file.FileGroupId, + TemplateVersionId: file.Id, + TemplateReference: file.Id.ToString("D"), + SourceFileId: file.Id, + Name: string.IsNullOrWhiteSpace(name) ? Path.GetFileNameWithoutExtension(file.OriginalFileName) : name.Trim(), + DocumentKind: string.IsNullOrWhiteSpace(documentKind) ? file.Category : documentKind.Trim(), + CustomerId: customerId, + File: file, + Worksheets: scan.Worksheets, + Placeholders: scan.Placeholders, + LineRows: scan.LineRows, + Warnings: scan.Warnings); + + private static string RequireKind(string? documentKind) + => DocumentTemplateKinds.Find(documentKind)?.Key + ?? throw new DocumentTemplateValidationException(nameof(documentKind), + $"模板类型无效,可选:{string.Join("、", DocumentTemplateKinds.All.Select(x => $"{x.DisplayName}({x.Key})"))}。"); + + private static string? NormalizeOptional(string? value, int maxLength, string field) + { + if (string.IsNullOrWhiteSpace(value)) return null; + var trimmed = value.Trim(); + if (trimmed.Length > maxLength) + throw new DocumentTemplateValidationException(field, $"长度不能超过 {maxLength} 个字符。"); + if (trimmed.Any(char.IsControl)) + throw new DocumentTemplateValidationException(field, "不能包含控制字符。"); + return trimmed; + } +} diff --git a/src/Leiren.Erp.Application/Documents/TemplatePlaceholderScanner.cs b/src/Leiren.Erp.Application/Documents/TemplatePlaceholderScanner.cs new file mode 100644 index 0000000..0287948 --- /dev/null +++ b/src/Leiren.Erp.Application/Documents/TemplatePlaceholderScanner.cs @@ -0,0 +1,249 @@ +using System.Text.RegularExpressions; +using ClosedXML.Excel; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Application.Documents; + +public sealed class DocumentTemplateValidationException(IReadOnlyDictionary errors) + : Exception("模板文件校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public DocumentTemplateValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} + +public sealed record TemplateScanResult( + IReadOnlyList Worksheets, + IReadOnlyList Placeholders, + IReadOnlyList LineRows, + IReadOnlyList Warnings); + +/// +/// Scans every worksheet of a real .xlsx template for {{...}} tokens. +/// Cells are discovered from each worksheet's used range, never from fixed +/// coordinates. A token is a line-row token when its name carries a line +/// prefix (Line., Lines., Item., Detail., +/// Row., also with :/_ separators); a worksheet row is a +/// detail row when it holds a line-row token or at least two distinct +/// placeholders, which is how a copied detail row appears in CI/PL templates. +/// +public static partial class TemplatePlaceholderScanner +{ + private const string LineScope = "LineRow"; + private const string DocumentScope = "Document"; + private const string MixedScope = "Mixed"; + + private static readonly string[] LinePrefixes = + ["Line", "Lines", "Item", "Items", "Detail", "Details", "Row"]; + + [GeneratedRegex(@"\{\{\s*([^{}]+?)\s*\}\}", RegexOptions.CultureInvariant)] + private static partial Regex TokenRegex(); + + private sealed record Occurrence( + string Name, + string Worksheet, + int WorksheetIndex, + string CellAddress, + int Row, + int Column, + string CellText, + bool IsLineRowToken); + + public static TemplateScanResult Scan(byte[] bytes) + { + ArgumentNullException.ThrowIfNull(bytes); + return Scan(new MemoryStream(bytes, writable: false)); + } + + public static TemplateScanResult Scan(Stream content) + { + ArgumentNullException.ThrowIfNull(content); + + XLWorkbook workbook; + try + { + workbook = new XLWorkbook(content); + } + catch (Exception ex) + { + throw new DocumentTemplateValidationException( + "file", $"Excel 文件无法解析(不是有效的 .xlsx 文件):{ex.Message}"); + } + + using (workbook) + { + var worksheets = workbook.Worksheets.Select(x => x.Name).ToList(); + if (worksheets.Count == 0) + { + throw new DocumentTemplateValidationException( + "file", "工作簿中没有任何工作表。"); + } + + var occurrences = new List(); + var warnings = new List(); + + var worksheetIndex = 0; + foreach (var sheet in workbook.Worksheets) + { + worksheetIndex++; + var range = sheet.RangeUsed(); + if (range is null) continue; + + foreach (var cell in range.CellsUsed()) + { + foreach (var text in CandidateTexts(cell)) + { + ScanCellText(text, sheet.Name, worksheetIndex, cell, occurrences, warnings); + } + } + } + + // A row is a detail row when it carries a line-row token or holds + // at least two distinct placeholders (a copied detail row). + var lineRowKeys = occurrences + .GroupBy(x => (x.Worksheet, x.Row)) + .Where(g => g.Any(x => x.IsLineRowToken) + || g.Select(x => x.Name).Distinct(StringComparer.OrdinalIgnoreCase).Count() >= 2) + .Select(g => g.Key) + .ToHashSet(); + + var locationsByName = new Dictionary>(StringComparer.OrdinalIgnoreCase); + var firstNameByKey = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var occurrence in occurrences) + { + var isOnLineRow = lineRowKeys.Contains((occurrence.Worksheet, occurrence.Row)); + var location = new TemplatePlaceholderLocationDto( + occurrence.Worksheet, + occurrence.CellAddress, + occurrence.Row, + occurrence.Column, + occurrence.CellText, + isOnLineRow ? LineScope : DocumentScope, + occurrence.IsLineRowToken, + isOnLineRow); + if (!locationsByName.TryGetValue(occurrence.Name, out var list)) + { + list = []; + locationsByName[occurrence.Name] = list; + firstNameByKey[occurrence.Name] = occurrence.Name; + } + list.Add(location); + } + + var placeholders = locationsByName + .Select(pair => + { + var name = firstNameByKey[pair.Key]; + var locations = pair.Value; + var scope = locations.All(x => x.IsOnLineRow) ? LineScope + : locations.All(x => !x.IsOnLineRow) ? DocumentScope + : MixedScope; + return new TemplatePlaceholderDto( + name, + "{{" + name + "}}", + scope, + locations.Count, + locations.Any(x => x.IsLineRowToken), + locations.Any(x => x.IsOnLineRow), + locations); + }) + .OrderBy(x => x.Locations[0].Worksheet, StringComparer.Ordinal) + .ThenBy(x => x.Locations[0].Row) + .ThenBy(x => x.Locations[0].Column) + .ToList(); + + var lineRows = occurrences + .Where(x => lineRowKeys.Contains((x.Worksheet, x.Row))) + .GroupBy(x => (x.Worksheet, x.WorksheetIndex, x.Row)) + .OrderBy(g => g.Key.WorksheetIndex) + .ThenBy(g => g.Key.Row) + .Select(g => new TemplateLineRowDto( + g.Key.Worksheet, + g.Key.Row, + g.Select(x => x.Name).Distinct(StringComparer.OrdinalIgnoreCase).ToList(), + g.Select(x => x.CellAddress).Distinct(StringComparer.Ordinal).ToList())) + .ToList(); + + return new TemplateScanResult(worksheets, placeholders, lineRows, warnings); + } + } + + /// Display text of a cell, plus its formula text when it has one. + private static IEnumerable CandidateTexts(IXLCell cell) + { + var seen = new HashSet(StringComparer.Ordinal); + var formatted = cell.GetFormattedString(); + if (!string.IsNullOrEmpty(formatted) && seen.Add(formatted)) + yield return formatted; + + if (cell.HasFormula) + { + var formula = cell.FormulaA1; + if (!string.IsNullOrEmpty(formula) && seen.Add(formula)) + yield return formula; + } + } + + private static void ScanCellText( + string text, string worksheet, int worksheetIndex, IXLCell cell, + List occurrences, List warnings) + { + var address = cell.Address.ToString() ?? string.Empty; + var foundInText = new HashSet(StringComparer.OrdinalIgnoreCase); + + foreach (Match match in TokenRegex().Matches(text)) + { + var name = match.Groups[1].Value.Trim(); + if (name.Length == 0) + { + warnings.Add($"工作表「{worksheet}」单元格 {address} 包含空占位符 {{{{}}}},已忽略。"); + continue; + } + // The same token appearing in both the display text and the + // formula of one cell is a single occurrence. + if (!foundInText.Add(name)) continue; + if (occurrences.Any(x => x.Worksheet == worksheet && x.CellAddress == address + && string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase))) + continue; + occurrences.Add(new Occurrence( + name, worksheet, worksheetIndex, address, + cell.Address.RowNumber, cell.Address.ColumnNumber, + text, IsLineRowToken(name))); + } + + var unclosed = CountOccurrences(text, "{{") - TokenRegex().Matches(text).Count; + if (unclosed > 0) + { + warnings.Add($"工作表「{worksheet}」单元格 {address} 包含 {unclosed} 个未闭合的 {{{{,未计入占位符。"); + } + } + + internal static bool IsLineRowToken(string name) + { + foreach (var prefix in LinePrefixes) + { + if (name.Length > prefix.Length + && name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) + && name[prefix.Length] is '.' or ':' or '_') + { + return true; + } + } + return false; + } + + private static int CountOccurrences(string text, string token) + { + var count = 0; + var index = 0; + while ((index = text.IndexOf(token, index, StringComparison.Ordinal)) >= 0) + { + count++; + index += token.Length; + } + return count; + } +} diff --git a/src/Leiren.Erp.Application/Documents/TokenWorkbookRenderer.cs b/src/Leiren.Erp.Application/Documents/TokenWorkbookRenderer.cs new file mode 100644 index 0000000..b199bcf --- /dev/null +++ b/src/Leiren.Erp.Application/Documents/TokenWorkbookRenderer.cs @@ -0,0 +1,214 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using ClosedXML.Excel; + +namespace Leiren.Erp.Application.Documents; + +/// +/// Placeholder names a built-in (mapping-free) template may use. Line fields +/// mark the row block copied once per line; numeric and date fields become +/// typed Excel values when a cell holds only that placeholder. +/// +public sealed record TokenTemplateFields( + IReadOnlySet LineFields, IReadOnlySet NumericFields, IReadOnlySet DateFields); + +/// +/// Renders the first worksheet of an XLSX template whose cells contain +/// {{Field}} placeholders with fixed (built-in) names. Header and total +/// placeholders are replaced in place; the row block carrying line +/// placeholders is copied once per line, including merged cells and row +/// heights, so a template authored with one sample line grows to any number +/// of lines. Formula cells are left untouched. Errors are reported through +/// so each module keeps its own exception type. +/// +public static partial class TokenWorkbookRenderer +{ + [GeneratedRegex(@"\{\{\s*([^{}]+?)\s*\}\}", RegexOptions.CultureInvariant)] + private static partial Regex TokenRegex(); + + public static byte[] Render( + byte[] templateBytes, + IReadOnlyDictionary headerValues, + IReadOnlyList> lineValues, + TokenTemplateFields fields, + string templateLabel, + Func error) + { + ArgumentNullException.ThrowIfNull(templateBytes); + if (lineValues.Count == 0) throw error($"{templateLabel}没有可导出的明细。"); + + XLWorkbook workbook; + try + { + workbook = new XLWorkbook(new MemoryStream(templateBytes, writable: false)); + } + catch (Exception ex) + { + throw error($"{templateLabel}模板无法解析(不是有效的 .xlsx 文件):{ex.Message}"); + } + + using (workbook) + { + var sheet = workbook.Worksheets.FirstOrDefault() ?? throw error($"{templateLabel}模板没有工作表。"); + if (sheet.RangeUsed() is null) throw error($"{templateLabel}模板没有内容。"); + + var known = new HashSet(headerValues.Keys, StringComparer.OrdinalIgnoreCase); + known.UnionWith(lineValues[0].Keys); + var unknown = ScanTokenNames(sheet).Where(name => !known.Contains(name)).Distinct().ToList(); + if (unknown.Count > 0) + throw error($"模板包含未知占位符:{string.Join("、", unknown.Select(x => "{{" + x + "}}"))}"); + + var lineRows = FindLineRows(sheet, fields.LineFields); + if (lineRows.Count == 0) throw error($"{templateLabel}模板缺少明细行占位符。"); + + var blockStart = lineRows.Min; + var blockHeight = lineRows.Max - blockStart + 1; + CopyLineBlock(sheet, blockStart, lineRows.Max, blockHeight, lineValues.Count); + + var rowLineIndex = new Dictionary(); + for (var i = 0; i < lineValues.Count; i++) + for (var r = 0; r < blockHeight; r++) + rowLineIndex[blockStart + i * blockHeight + r] = i; + + // Line rows see their line's values plus every header/total value + // (e.g. a document number repeated on each line). + var mergedLines = lineValues.Select(line => + { + var merged = new Dictionary(headerValues, StringComparer.OrdinalIgnoreCase); + foreach (var (key, value) in line) merged[key] = value; + return merged; + }).ToList(); + foreach (var cell in sheet.RangeUsed()!.Cells()) + { + if (cell.HasFormula) continue; + IReadOnlyDictionary values = rowLineIndex.TryGetValue(cell.Address.RowNumber, out var index) + ? mergedLines[index] + : headerValues; + ApplyCell(cell, values, fields); + } + + using var output = new MemoryStream(); + workbook.SaveAs(output); + return output.ToArray(); + } + } + + private static void CopyLineBlock(IXLWorksheet sheet, int blockStart, int blockEnd, int blockHeight, int lineCount) + { + if (lineCount <= 1) return; + + var used = sheet.RangeUsed()!; + var firstColumn = used.FirstColumn().ColumnNumber(); + var lastColumn = used.LastColumn().ColumnNumber(); + + var templateHeights = Enumerable.Range(blockStart, blockHeight).Select(row => sheet.Row(row).Height).ToList(); + var mergedInsideBlock = sheet.MergedRanges + .Select(range => ( + FirstRow: range.FirstRow().RowNumber(), + FirstColumn: range.FirstColumn().ColumnNumber(), + LastRow: range.LastRow().RowNumber(), + LastColumn: range.LastColumn().ColumnNumber())) + .Where(range => range.FirstRow >= blockStart && range.LastRow <= blockEnd) + .ToList(); + + sheet.Row(blockEnd + 1).InsertRowsAbove((lineCount - 1) * blockHeight); + + var source = sheet.Range(blockStart, firstColumn, blockEnd, lastColumn); + for (var copy = 1; copy < lineCount; copy++) + { + var targetStart = blockStart + copy * blockHeight; + source.CopyTo(sheet.Cell(targetStart, firstColumn)); + for (var r = 0; r < blockHeight; r++) + { + var height = templateHeights[r]; + if (height > 0) sheet.Row(targetStart + r).Height = height; + } + + var offset = copy * blockHeight; + foreach (var merged in mergedInsideBlock) + { + try + { + sheet.Range(merged.FirstRow + offset, merged.FirstColumn, + merged.LastRow + offset, merged.LastColumn).Merge(); + } + catch (InvalidOperationException) + { + // The copy already produced the merged range. + } + } + } + } + + private static void ApplyCell(IXLCell cell, IReadOnlyDictionary values, TokenTemplateFields fields) + { + var text = cell.Value.ToString(); + if (string.IsNullOrWhiteSpace(text)) return; + + var matches = TokenRegex().Matches(text); + if (matches.Count == 0) return; + + if (matches.Count == 1 && text.Trim().Equals(matches[0].Value, StringComparison.Ordinal)) + { + var name = matches[0].Groups[1].Value.Trim(); + var raw = values.TryGetValue(name, out var value) ? value : null; + + if (raw is null) + { + cell.Value = string.Empty; + return; + } + + if (fields.NumericFields.Contains(name) && + decimal.TryParse(raw, NumberStyles.Number, CultureInfo.InvariantCulture, out var number)) + { + cell.Value = number; + return; + } + + if (fields.DateFields.Contains(name) && + DateTime.TryParseExact(raw, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) + { + cell.Value = date; + cell.Style.NumberFormat.Format = "yyyy-mm-dd"; + return; + } + + cell.Value = raw; + return; + } + + cell.Value = TokenRegex().Replace(text, match => + { + var name = match.Groups[1].Value.Trim(); + return values.TryGetValue(name, out var value) ? value ?? string.Empty : match.Value; + }); + } + + private static SortedSet FindLineRows(IXLWorksheet sheet, IReadOnlySet lineFields) + { + var rows = new SortedSet(); + foreach (var cell in sheet.RangeUsed()!.Cells()) + { + if (cell.HasFormula) continue; + var text = cell.Value.ToString(); + if (!text.Contains("{{", StringComparison.Ordinal)) continue; + foreach (Match match in TokenRegex().Matches(text)) + if (lineFields.Contains(match.Groups[1].Value.Trim())) + rows.Add(cell.Address.RowNumber); + } + return rows; + } + + private static IEnumerable ScanTokenNames(IXLWorksheet sheet) + { + foreach (var cell in sheet.RangeUsed()!.Cells()) + { + if (cell.HasFormula) continue; + var text = cell.Value.ToString(); + if (!text.Contains("{{", StringComparison.Ordinal)) continue; + foreach (Match match in TokenRegex().Matches(text)) + yield return match.Groups[1].Value.Trim(); + } + } +} diff --git a/src/Leiren.Erp.Application/Files/FileService.cs b/src/Leiren.Erp.Application/Files/FileService.cs new file mode 100644 index 0000000..192a194 --- /dev/null +++ b/src/Leiren.Erp.Application/Files/FileService.cs @@ -0,0 +1,356 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Files; + +public sealed class FileService(IFilesDbContext db, IFileStorage storage, FileStorageOptions options) +{ + public async Task UploadAsync(UploadFileCommand command, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(command); + if (command.Content is null) + throw new FilesValidationException("file", "文件内容为空。"); + + var ownerType = NormalizeOwnerType(command.OwnerType); + if (command.OwnerId == Guid.Empty) + throw new FilesValidationException(nameof(command.OwnerId), "附件所属业务对象不能为空。"); + + var originalFileName = SanitizeFileName(command.OriginalFileName); + var extension = ValidateExtension(originalFileName); + var now = DateTimeOffset.UtcNow; + + var file = new FileAttachment + { + FileGroupId = Guid.NewGuid(), + OwnerType = ownerType, + OwnerId = command.OwnerId, + Category = NormalizeOptional(command.Category, 100, nameof(command.Category)), + Description = NormalizeOptional(command.Description, 1000, nameof(command.Description)), + OriginalFileName = originalFileName, + ContentType = SanitizeContentType(command.ContentType, extension), + Extension = extension, + Version = 1, + IsCurrentVersion = true, + UploadedByUserId = command.UploadedByUserId, + UploadedBy = NormalizeOptional(command.UploadedBy, 200, nameof(command.UploadedBy)), + CreatedAt = now, + UpdatedAt = now + }; + file.StorageKey = BuildStorageKey(file, now); + + var written = await storage.SaveAsync(file.StorageKey, command.Content, ct); + if (written.SizeBytes <= 0) + { + await storage.DeleteAsync(file.StorageKey, ct); + throw new FilesValidationException("file", "文件内容为空。"); + } + + file.SizeBytes = written.SizeBytes; + file.Sha256 = written.Sha256; + + try + { + db.FileAttachments.Add(file); + await db.SaveChangesAsync(ct); + } + catch + { + await storage.DeleteAsync(file.StorageKey, CancellationToken.None); + throw; + } + + return ToDto(file); + } + + /// Stores a new immutable version of the file group the given version belongs to. + public async Task UploadNewVersionAsync( + Guid fileId, Stream content, string? originalFileName, string? contentType, + string? category, string? description, Guid? uploadedByUserId = null, string? uploadedBy = null, + CancellationToken ct = default) + { + if (content is null) + throw new FilesValidationException("file", "文件内容为空。"); + + var anchor = await LoadAsync(fileId, ct); + var nextVersion = (await db.FileAttachments + .Where(x => x.FileGroupId == anchor.FileGroupId) + .MaxAsync(x => (int?)x.Version, ct) ?? 0) + 1; + var group = await db.FileAttachments + .Where(x => x.FileGroupId == anchor.FileGroupId && !x.IsDeleted) + .ToListAsync(ct); + if (group.Count == 0) + throw new FilesNotFoundException("文件不存在。"); + + var current = group.SingleOrDefault(x => x.IsCurrentVersion) + ?? throw new FilesConflictException("文件组没有当前版本。"); + var safeName = SanitizeFileName(originalFileName); + var extension = ValidateExtension(safeName); + var now = DateTimeOffset.UtcNow; + + var file = new FileAttachment + { + FileGroupId = current.FileGroupId, + PreviousVersionId = current.Id, + OwnerType = current.OwnerType, + OwnerId = current.OwnerId, + Category = NormalizeOptional(category, 100, nameof(category)) ?? current.Category, + Description = NormalizeOptional(description, 1000, nameof(description)) ?? current.Description, + OriginalFileName = safeName, + ContentType = SanitizeContentType(contentType, extension), + Extension = extension, + Version = nextVersion, + IsCurrentVersion = true, + UploadedByUserId = uploadedByUserId, + UploadedBy = NormalizeOptional(uploadedBy, 200, nameof(uploadedBy)), + CreatedAt = now, + UpdatedAt = now + }; + file.StorageKey = BuildStorageKey(file, now); + + var written = await storage.SaveAsync(file.StorageKey, content, ct); + if (written.SizeBytes <= 0) + { + await storage.DeleteAsync(file.StorageKey, ct); + throw new FilesValidationException("file", "文件内容为空。"); + } + + file.SizeBytes = written.SizeBytes; + file.Sha256 = written.Sha256; + current.IsCurrentVersion = false; + current.Touch(); + + try + { + db.FileAttachments.Add(file); + await db.SaveChangesAsync(ct); + } + catch + { + await storage.DeleteAsync(file.StorageKey, CancellationToken.None); + throw; + } + + return ToDto(file); + } + + public async Task> ListAsync( + string? ownerType, Guid? ownerId, string? category, string? search, bool currentOnly, + int page, int pageSize, CancellationToken ct = default) + { + var query = db.FileAttachments.AsNoTracking().Where(x => !x.IsDeleted); + if (!string.IsNullOrWhiteSpace(ownerType)) + { + var normalized = NormalizeOwnerType(ownerType); + query = query.Where(x => x.OwnerType == normalized); + } + if (ownerId is not null) query = query.Where(x => x.OwnerId == ownerId.Value); + if (!string.IsNullOrWhiteSpace(category)) + { + var normalizedCategory = category.Trim(); + query = query.Where(x => x.Category == normalizedCategory); + } + if (currentOnly) query = query.Where(x => x.IsCurrentVersion); + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => + x.OriginalFileName.Contains(term) || + x.Sha256.Contains(term) || + x.OwnerType.Contains(term) || + (x.Category != null && x.Category.Contains(term)) || + (x.Description != null && x.Description.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(ToListItem).ToList(); + } + + public async Task GetAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadAsync(id, ct)); + + public async Task> ListVersionsAsync(Guid id, CancellationToken ct = default) + { + var file = await LoadAsync(id, ct); + var versions = await db.FileAttachments.AsNoTracking() + .Where(x => x.FileGroupId == file.FileGroupId && !x.IsDeleted) + .OrderByDescending(x => x.Version) + .ToListAsync(ct); + return versions.Select(ToDto).ToList(); + } + + public async Task OpenDownloadAsync(Guid id, CancellationToken ct = default) + { + var file = await LoadAsync(id, ct); + Stream content; + try + { + content = await storage.OpenReadAsync(file.StorageKey, ct); + } + catch (FileNotFoundException) + { + throw new FilesNotFoundException("文件内容不存在或已被移除。"); + } + catch (DirectoryNotFoundException) + { + throw new FilesNotFoundException("文件内容不存在或已被移除。"); + } + + if (content.CanSeek && content.Length != file.SizeBytes) + { + await content.DisposeAsync(); + throw new FilesConflictException("文件内容大小与元数据不一致。"); + } + + return new FileDownloadResult( + new FileDownloadInfo(file.Id, file.OriginalFileName, file.ContentType, file.SizeBytes, file.Sha256), + content); + } + + public async Task DeleteAsync(Guid id, CancellationToken ct = default) + { + var file = await LoadAsync(id, ct); + var wasCurrent = file.IsCurrentVersion; + var groupId = file.FileGroupId; + var storageKey = file.StorageKey; + + file.IsDeleted = true; + file.IsCurrentVersion = false; + file.DeletedAt = DateTimeOffset.UtcNow; + file.Touch(); + + if (wasCurrent) + { + var previous = await db.FileAttachments + .Where(x => x.FileGroupId == groupId && x.Id != id && !x.IsDeleted) + .OrderByDescending(x => x.Version) + .FirstOrDefaultAsync(ct); + if (previous is not null) + { + previous.IsCurrentVersion = true; + previous.Touch(); + } + } + + await db.SaveChangesAsync(ct); + await storage.DeleteAsync(storageKey, ct); + } + + // ---------- Helpers ---------- + + private async Task LoadAsync(Guid id, CancellationToken ct) + => await db.FileAttachments.SingleOrDefaultAsync(x => x.Id == id && !x.IsDeleted, ct) + ?? throw new FilesNotFoundException("文件不存在。"); + + private string BuildStorageKey(FileAttachment file, DateTimeOffset now) + { + var stem = Path.GetFileNameWithoutExtension(file.OriginalFileName); + var safeStem = new string(stem.Select(ch => char.IsLetterOrDigit(ch) || ch is '-' or '_' ? ch : '_').ToArray()).Trim('_'); + if (safeStem.Length == 0) safeStem = "file"; + if (safeStem.Length > 60) safeStem = safeStem[..60]; + // Relative key only; LocalFileStorage resolves it under the configured root. + return $"files/{now.UtcDateTime:yyyy}/{now.UtcDateTime:MM}/{file.OwnerType}/{file.OwnerId:D}/{file.FileGroupId:D}/v{file.Version}-{file.Id:D}-{safeStem}{file.Extension}"; + } + + private string ValidateExtension(string fileName) + { + var extension = Path.GetExtension(fileName).ToLowerInvariant(); + if (string.IsNullOrWhiteSpace(extension) || extension.Length > 20) + throw new FilesValidationException("file", "文件必须包含扩展名。"); + var allowed = options.AllowedExtensions + .Select(x => x.Trim().ToLowerInvariant()) + .Select(x => x.StartsWith('.') ? x : "." + x) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + if (allowed.Count > 0 && !allowed.Contains(extension)) + throw new FilesValidationException("file", $"不允许上传 {extension} 类型的文件。"); + return extension; + } + + internal static string SanitizeFileName(string? originalFileName) + { + if (string.IsNullOrWhiteSpace(originalFileName)) + throw new FilesValidationException("file", "文件名不能为空。"); + + // Take the basename only, treating both separators as path separators on every OS, + // so a Windows-style "..\..\x.pdf" cannot traverse on any host. + var name = originalFileName.Replace('\\', '/'); + var slash = name.LastIndexOf('/'); + if (slash >= 0) name = name[(slash + 1)..]; + name = name.Trim().TrimEnd('.', ' '); + + if (name.Length == 0 || name is "." or "..") + throw new FilesValidationException("file", "文件名无效。"); + + var invalid = Path.GetInvalidFileNameChars(); + var chars = name.Select(ch => ch < 32 || invalid.Contains(ch) ? '_' : ch).ToArray(); + name = new string(chars).Trim().TrimEnd('.', ' '); + if (name.Length == 0 || name is "." or "..") + throw new FilesValidationException("file", "文件名无效。"); + + if (name.Length > 200) + { + var extension = Path.GetExtension(name); + var stem = Path.GetFileNameWithoutExtension(name); + name = stem[..Math.Max(1, 200 - extension.Length)] + extension; + } + return name; + } + + internal static string NormalizeOwnerType(string? ownerType) + { + if (string.IsNullOrWhiteSpace(ownerType)) + throw new FilesValidationException(nameof(ownerType), "附件所属业务对象类型不能为空。"); + var normalized = ownerType.Trim().ToLowerInvariant(); + if (normalized.Length > 100 || normalized is "." or ".." || + !char.IsLetterOrDigit(normalized[0]) || + normalized.Any(ch => !(char.IsLetterOrDigit(ch) || ch is '-' or '_' or '.'))) + throw new FilesValidationException(nameof(ownerType), "附件所属业务对象类型无效。"); + return normalized; + } + + private static string? NormalizeOptional(string? value, int maxLength, string field) + { + if (string.IsNullOrWhiteSpace(value)) return null; + var trimmed = value.Trim(); + if (trimmed.Length > maxLength) + throw new FilesValidationException(field, $"长度不能超过 {maxLength} 个字符。"); + if (trimmed.Any(char.IsControl)) + throw new FilesValidationException(field, "不能包含控制字符。"); + return trimmed; + } + + private static string SanitizeContentType(string? contentType, string extension) + { + var value = contentType?.Split(';', 2)[0].Trim().ToLowerInvariant(); + if (string.IsNullOrWhiteSpace(value) || value.Length > 200 || value.Any(char.IsControl) || !value.Contains('/')) + { + value = extension switch + { + ".pdf" => "application/pdf", + ".png" => "image/png", + ".jpg" or ".jpeg" => "image/jpeg", + ".gif" => "image/gif", + ".webp" => "image/webp", + ".txt" => "text/plain", + ".csv" => "text/csv", + ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".zip" => "application/zip", + _ => "application/octet-stream" + }; + } + return value; + } + + private static FileAttachmentDto ToDto(FileAttachment x) => new( + x.Id, x.FileGroupId, x.PreviousVersionId, x.OwnerType, x.OwnerId, x.Category, x.Description, + x.OriginalFileName, x.StorageKey, x.ContentType, x.Extension, x.SizeBytes, x.Sha256, + x.Version, x.IsCurrentVersion, x.UploadedByUserId, x.UploadedBy, x.CreatedAt, x.UpdatedAt); + + private static FileAttachmentListItemDto ToListItem(FileAttachment x) => new( + x.Id, x.FileGroupId, x.OwnerType, x.OwnerId, x.Category, x.OriginalFileName, x.ContentType, + x.Extension, x.SizeBytes, x.Sha256, x.Version, x.IsCurrentVersion, x.UploadedBy, x.CreatedAt, x.UpdatedAt); +} diff --git a/src/Leiren.Erp.Application/Files/FilesExceptions.cs b/src/Leiren.Erp.Application/Files/FilesExceptions.cs new file mode 100644 index 0000000..d3adf61 --- /dev/null +++ b/src/Leiren.Erp.Application/Files/FilesExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Files; + +public sealed class FilesNotFoundException(string message) : Exception(message); + +public sealed class FilesConflictException(string message) : Exception(message); + +public sealed class FilesValidationException(IReadOnlyDictionary errors) + : Exception("文件资料校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public FilesValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Files/IFileStorage.cs b/src/Leiren.Erp.Application/Files/IFileStorage.cs new file mode 100644 index 0000000..90db8bc --- /dev/null +++ b/src/Leiren.Erp.Application/Files/IFileStorage.cs @@ -0,0 +1,53 @@ +namespace Leiren.Erp.Application.Files; + +/// Configuration for server-side file storage. Content never goes to the database. +public sealed class FileStorageOptions +{ + /// Storage root. Relative values are resolved against the API content root at startup. + public string RootPath { get; set; } = "data/storage"; + + public long MaxFileSizeBytes { get; set; } = 50 * 1024 * 1024; + + public List AllowedExtensions { get; set; } = + [ + ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", + ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", + ".txt", ".csv", ".zip", ".rar", ".7z" + ]; +} + +public sealed record StoredFileWriteResult(long SizeBytes, string Sha256); + +/// +/// Stores file content under relative keys beneath a configured root. +/// Implementations must reject absolute keys and any key escaping the root. +/// +public interface IFileStorage +{ + Task SaveAsync(string storageKey, Stream content, CancellationToken cancellationToken = default); + Task OpenReadAsync(string storageKey, CancellationToken cancellationToken = default); + Task DeleteAsync(string storageKey, CancellationToken cancellationToken = default); + Task ExistsAsync(string storageKey, CancellationToken cancellationToken = default); +} + +/// Upload input carrying the content stream; kept in Application because streams are not wire contracts. +public sealed record UploadFileCommand( + string? OwnerType, + Guid OwnerId, + string? Category, + string? Description, + string? OriginalFileName, + string? ContentType, + Stream Content, + Guid? UploadedByUserId = null, + string? UploadedBy = null); + +public sealed record FileDownloadResult(FileDownloadInfo File, Stream Content); + +/// Download metadata handed to the API layer without exposing a server filesystem path. +public sealed record FileDownloadInfo( + Guid Id, + string OriginalFileName, + string ContentType, + long SizeBytes, + string Sha256); diff --git a/src/Leiren.Erp.Application/Files/IFilesDbContext.cs b/src/Leiren.Erp.Application/Files/IFilesDbContext.cs new file mode 100644 index 0000000..bf4675f --- /dev/null +++ b/src/Leiren.Erp.Application/Files/IFilesDbContext.cs @@ -0,0 +1,12 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Files; + +/// EF Core boundary for the Files module; implemented by Infrastructure. +public interface IFilesDbContext +{ + DbSet FileAttachments { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Finance/PayableService.cs b/src/Leiren.Erp.Application/Finance/PayableService.cs new file mode 100644 index 0000000..ff86f57 --- /dev/null +++ b/src/Leiren.Erp.Application/Finance/PayableService.cs @@ -0,0 +1,83 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Finance; + +/// EF Core boundary for the Finance module; implemented by Infrastructure. +public interface IFinanceDbContext +{ + DbSet SupplierPayables { get; } + DbSet PurchaseContracts { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} + +public sealed class FinanceValidationException(string field, string message) : Exception(message) +{ + public IReadOnlyDictionary Errors { get; } = new Dictionary { [field] = [message] }; +} + +public sealed class FinanceNotFoundException(string message) : Exception(message); + +public sealed class FinanceConflictException(string message) : Exception(message); + +/// +/// Supplier payables: one per confirmed purchase contract (created by the +/// purchasing module on confirmation). Lists are returned whole so the +/// client can filter, sort and total them; paying is a single final step. +/// +public sealed class PayableService(IFinanceDbContext db) +{ + public async Task> ListAsync(CancellationToken ct = default) + { + var items = await db.SupplierPayables.AsNoTracking().ToListAsync(ct); + return items.OrderByDescending(x => x.CreatedAt).Select(ToDto).ToList(); + } + + public async Task PayAsync(Guid id, PaySupplierPayableRequest request, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(request); + var payable = await db.SupplierPayables.SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new FinanceNotFoundException("待付款项不存在。"); + var paidDate = request.PaidDate ?? DateOnly.FromDateTime(DateTime.Today); + if (paidDate > DateOnly.FromDateTime(DateTime.Today)) + throw new FinanceValidationException(nameof(request.PaidDate), "付款日期不能晚于今天。"); + + try + { + payable.MarkPaid(paidDate, Trim(request.PaymentReference), Trim(request.PaidBy), Trim(request.Remark)); + } + catch (InvalidOperationException ex) + { + throw new FinanceConflictException(ex.Message); + } + await db.SaveChangesAsync(ct); + return ToDto(payable); + } + + /// + /// Creates the payable for every confirmed contract that has none — covers + /// contracts confirmed before payables existed. Idempotent. + /// + public async Task BackfillAsync(CancellationToken ct = default) + { + var existing = (await db.SupplierPayables.AsNoTracking().Select(x => x.PurchaseContractId).ToListAsync(ct)).ToHashSet(); + var contracts = await db.PurchaseContracts.Include(x => x.Tasks) + .Where(x => x.Status != PurchaseContractStatus.Draft && x.Status != PurchaseContractStatus.Voided) + .ToListAsync(ct); + var missing = contracts.Where(x => !existing.Contains(x.Id)).ToList(); + foreach (var contract in missing) + db.SupplierPayables.Add(SupplierPayable.ForContract(contract)); + if (missing.Count > 0) await db.SaveChangesAsync(ct); + return missing.Count; + } + + private static string? Trim(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static SupplierPayableDto ToDto(SupplierPayable x) => new( + x.Id, x.PayableNo, x.PurchaseContractId, x.ContractNo, x.SupplierId, x.SupplierName, x.CustomerOrderNo, + x.Currency, x.Amount, x.PaymentTerms, x.Status.ToString(), x.PaidDate, x.PaymentReference, x.PaidBy, + x.PaidAt, x.Remark, x.CreatedAt, x.UpdatedAt); +} diff --git a/src/Leiren.Erp.Application/Identity/IIdentityDbContext.cs b/src/Leiren.Erp.Application/Identity/IIdentityDbContext.cs new file mode 100644 index 0000000..0bc9830 --- /dev/null +++ b/src/Leiren.Erp.Application/Identity/IIdentityDbContext.cs @@ -0,0 +1,17 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Identity; + +/// EF Core boundary for the Identity module; implemented by Infrastructure. +public interface IIdentityDbContext +{ + DbSet Users { get; } + DbSet Roles { get; } + DbSet Permissions { get; } + DbSet UserRoles { get; } + DbSet RolePermissions { get; } + DbSet UserPermissions { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Identity/IdentityExceptions.cs b/src/Leiren.Erp.Application/Identity/IdentityExceptions.cs new file mode 100644 index 0000000..04027cc --- /dev/null +++ b/src/Leiren.Erp.Application/Identity/IdentityExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Identity; + +public sealed class IdentityNotFoundException(string message) : Exception(message); + +public sealed class IdentityConflictException(string message) : Exception(message); + +public sealed class IdentityValidationException(IReadOnlyDictionary errors) + : Exception("授权数据校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public IdentityValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Identity/IdentityService.cs b/src/Leiren.Erp.Application/Identity/IdentityService.cs new file mode 100644 index 0000000..c46914c --- /dev/null +++ b/src/Leiren.Erp.Application/Identity/IdentityService.cs @@ -0,0 +1,364 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Authorization; +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Identity; + +/// +/// Server-side authorization source of truth. Effective permissions are the union of a +/// user's direct permissions and every assigned role's permissions; anything not granted +/// is denied. Password hashing stays with the API host (ASP.NET Core Identity hasher), +/// this service only persists the hash it is given. +/// +public sealed class IdentityService(IIdentityDbContext db) +{ + private static readonly IReadOnlyDictionary SystemRoles = + new Dictionary(StringComparer.Ordinal) + { + ["admin"] = ("系统管理员", AuthorizationCatalog.Permissions.Select(x => x.Code).ToArray()), + ["sales"] = ("销售", ["dashboard:view", "sales:view", "sales:edit", "sales:confirm", "sales:export", "customers:view", "customers:edit", "customers:export", "catalog:view", "files:view", "files:edit", "files:download"]), + ["purchase"] = ("采购", ["dashboard:view", "purchase:view", "purchase:edit", "purchase:confirm", "purchase:generate", "purchase:export", "sales:view", "suppliers:view", "suppliers:edit", "suppliers:export", "catalog:view", "files:view", "files:edit", "files:download"]), + ["shipping"] = ("出货", ["dashboard:view", "shipping:view", "shipping:edit", "shipping:confirm", "shipping:generate", "shipping:export", "sales:view", "catalog:view", "files:view", "files:edit", "files:download"]), + ["customs"] = ("报关", ["dashboard:view", "customs:view", "customs:edit", "customs:confirm", "customs:generate", "customs:export", "shipping:view", "sales:view", "catalog:view", "files:view", "files:edit", "files:download"]), + ["billing"] = ("开票", ["dashboard:view", "billing:view", "billing:edit", "billing:confirm", "billing:generate", "billing:export", "purchase:view", "suppliers:view", "files:view", "files:edit", "files:download"]), + ["catalog"] = ("产品维护", ["dashboard:view", "catalog:view", "catalog:edit", "catalog:publish", "catalog:disable", "catalog:export", "files:view", "files:edit", "files:download"]), + }; + + public IReadOnlyList ListModules() => + AuthorizationCatalog.Modules.Select(x => new ModuleDto(x.Code, x.Name)).ToList(); + + public IReadOnlyList ListPermissions() => + AuthorizationCatalog.Permissions.Select(x => new PermissionDto(x.Code, x.Module, x.Action)).ToList(); + + /// Idempotently creates the permission catalog and system roles. + public async Task EnsureAuthorizationCatalogAsync(CancellationToken ct = default) + { + var existingPermissions = await db.Permissions.ToListAsync(ct); + var byCode = existingPermissions.ToDictionary(x => x.Code, StringComparer.Ordinal); + var changed = false; + foreach (var definition in AuthorizationCatalog.Permissions) + { + if (byCode.ContainsKey(definition.Code)) continue; + var permission = new AppPermission { Code = definition.Code, Module = definition.Module, Action = definition.Action }; + db.Permissions.Add(permission); + byCode[definition.Code] = permission; + changed = true; + } + if (changed) await db.SaveChangesAsync(ct); + + foreach (var (code, (name, permissions)) in SystemRoles) + { + var role = await db.Roles + .Include(x => x.Permissions) + .SingleOrDefaultAsync(x => x.Code == code, ct); + if (role is null) + { + role = new AppRole { Code = code, Name = name, IsSystem = true }; + db.Roles.Add(role); + await db.SaveChangesAsync(ct); + } + + var desired = permissions.ToHashSet(StringComparer.Ordinal); + var currentCodes = await db.RolePermissions + .Where(x => x.RoleId == role.Id) + .Join(db.Permissions, x => x.PermissionId, p => p.Id, (_, p) => p.Code) + .ToListAsync(ct); + var current = currentCodes.ToHashSet(StringComparer.Ordinal); + if (current.SetEquals(desired)) continue; + + var existingLinks = await db.RolePermissions.Where(x => x.RoleId == role.Id).ToListAsync(ct); + db.RolePermissions.RemoveRange(existingLinks); + foreach (var permissionCode in desired) + { + db.RolePermissions.Add(new RolePermission { RoleId = role.Id, PermissionId = byCode[permissionCode].Id }); + } + await db.SaveChangesAsync(ct); + } + } + + public async Task> GetEffectivePermissionsAsync(Guid userId, CancellationToken ct = default) + { + var direct = db.UserPermissions + .Where(x => x.UserId == userId) + .Join(db.Permissions, x => x.PermissionId, p => p.Id, (_, p) => p.Code); + var viaRoles = db.UserRoles + .Where(x => x.UserId == userId) + .Join(db.RolePermissions, ur => ur.RoleId, rp => rp.RoleId, (_, rp) => rp.PermissionId) + .Join(db.Permissions, id => id, p => p.Id, (_, p) => p.Code); + var codes = await direct.Union(viaRoles).ToListAsync(ct); + return codes.OrderBy(x => x, StringComparer.Ordinal).ToList(); + } + + public async Task HasPermissionAsync(Guid userId, string permission, CancellationToken ct = default) + { + if (!AuthorizationCatalog.TryNormalizePermission(permission, out var code)) return false; + var permissions = await GetEffectivePermissionsAsync(userId, ct); + return permissions.Contains(code, StringComparer.Ordinal); + } + + public async Task HasModuleAsync(Guid userId, string module, CancellationToken ct = default) + { + var normalized = AuthorizationCatalog.NormalizeModule(module); + if (normalized is null) return false; + var permissions = await GetEffectivePermissionsAsync(userId, ct); + return permissions.Any(x => AuthorizationCatalog.ModuleOf(x) == normalized); + } + + public async Task CreateUserAsync(CreateUserRequest request, string passwordHash, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(request?.UserName) || string.IsNullOrWhiteSpace(request.DisplayName)) + throw new IdentityValidationException("user", "用户名和显示名称不能为空。"); + if (string.IsNullOrWhiteSpace(passwordHash)) + throw new IdentityValidationException("password", "密码不能为空。"); + + var userName = request.UserName.Trim(); + if (await db.Users.AnyAsync(x => x.UserName == userName, ct)) + throw new IdentityConflictException($"用户名 {userName} 已存在。"); + + var roles = await ResolveRolesAsync(request.RoleCodes, ct); + var permissions = ResolvePermissionCodes(request.Permissions, request.Modules); + + var user = new AppUser + { + UserName = userName, + DisplayName = request.DisplayName.Trim(), + PasswordHash = passwordHash, + IsActive = true, + }; + db.Users.Add(user); + await db.SaveChangesAsync(ct); + + foreach (var role in roles) + db.UserRoles.Add(new UserRole { UserId = user.Id, RoleId = role.Id }); + await AddDirectPermissionsAsync(user.Id, permissions, ct); + await db.SaveChangesAsync(ct); + return await GetUserAsync(user.Id, ct); + } + + public async Task> ListUsersAsync(int page, int pageSize, CancellationToken ct = default) + { + var safePage = Math.Max(1, page); + var safePageSize = Math.Clamp(pageSize, 1, 200); + var users = await db.Users + .OrderBy(x => x.UserName) + .Skip((safePage - 1) * safePageSize) + .Take(safePageSize) + .ToListAsync(ct); + var result = new List(users.Count); + foreach (var user in users) result.Add(await ToDtoAsync(user, ct)); + return result; + } + + public async Task GetUserAsync(Guid userId, CancellationToken ct = default) + { + var user = await db.Users.SingleOrDefaultAsync(x => x.Id == userId, ct) + ?? throw new IdentityNotFoundException("用户不存在。"); + return await ToDtoAsync(user, ct); + } + + public async Task AssignRolesAsync(Guid userId, AssignRolesRequest request, CancellationToken ct = default) + { + _ = await GetUserEntityAsync(userId, ct); + var roles = await ResolveRolesAsync(request?.RoleCodes, ct); + var existing = await db.UserRoles.Where(x => x.UserId == userId).ToListAsync(ct); + db.UserRoles.RemoveRange(existing); + foreach (var role in roles) + db.UserRoles.Add(new UserRole { UserId = userId, RoleId = role.Id }); + await db.SaveChangesAsync(ct); + return await GetUserAsync(userId, ct); + } + + /// + /// Replaces the user's directly granted module access (module:view). Modules that + /// come from roles remain effective and are still reported in the user's module list. + /// + public async Task AssignModulesAsync(Guid userId, AssignModulesRequest request, CancellationToken ct = default) + { + _ = await GetUserEntityAsync(userId, ct); + var modules = NormalizeModules(request?.Modules); + var directView = await db.UserPermissions + .Where(x => x.UserId == userId) + .Join(db.Permissions, up => up.PermissionId, p => p.Id, (up, p) => new { Link = up, p.Code, p.Module, p.Action }) + .Where(x => x.Action == "view") + .ToListAsync(ct); + foreach (var item in directView.Where(x => !modules.Contains(x.Module))) + db.UserPermissions.Remove(item.Link); + var kept = directView.Where(x => modules.Contains(x.Module)).Select(x => x.Module).ToHashSet(StringComparer.Ordinal); + foreach (var module in modules.Where(x => !kept.Contains(x))) + { + var permission = await GetPermissionEntityAsync(AuthorizationCatalog.ViewPermission(module), ct); + db.UserPermissions.Add(new UserPermission { UserId = userId, PermissionId = permission.Id }); + } + await db.SaveChangesAsync(ct); + return await GetUserAsync(userId, ct); + } + + public async Task AssignPermissionsAsync(Guid userId, AssignPermissionsRequest request, CancellationToken ct = default) + { + _ = await GetUserEntityAsync(userId, ct); + var codes = ResolvePermissionCodes(request?.Permissions, null); + var existing = await db.UserPermissions.Where(x => x.UserId == userId).ToListAsync(ct); + db.UserPermissions.RemoveRange(existing); + await AddDirectPermissionsAsync(userId, codes, ct); + await db.SaveChangesAsync(ct); + return await GetUserAsync(userId, ct); + } + + public async Task SetUserActiveAsync(Guid userId, bool isActive, CancellationToken ct = default) + { + var user = await GetUserEntityAsync(userId, ct); + user.IsActive = isActive; + await db.SaveChangesAsync(ct); + return await GetUserAsync(userId, ct); + } + + public async Task AssignRoleToUserAsync(Guid userId, string roleCode, CancellationToken ct = default) + { + var role = await db.Roles.SingleOrDefaultAsync(x => x.Code == roleCode, ct) + ?? throw new IdentityNotFoundException($"角色 {roleCode} 不存在。"); + if (!await db.UserRoles.AnyAsync(x => x.UserId == userId && x.RoleId == role.Id, ct)) + { + db.UserRoles.Add(new UserRole { UserId = userId, RoleId = role.Id }); + await db.SaveChangesAsync(ct); + } + } + + public async Task> ListRolesAsync(CancellationToken ct = default) + { + var roles = await db.Roles.OrderBy(x => x.Code).ToListAsync(ct); + var result = new List(roles.Count); + foreach (var role in roles) result.Add(await ToDtoAsync(role, ct)); + return result; + } + + public async Task CreateRoleAsync(CreateRoleRequest request, CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(request?.Code) || string.IsNullOrWhiteSpace(request.Name)) + throw new IdentityValidationException("role", "角色编码和名称不能为空。"); + var code = request.Code.Trim().ToLowerInvariant(); + if (code.Any(c => !(char.IsLower(c) || char.IsDigit(c) || c is '-' or '_'))) + throw new IdentityValidationException("code", "角色编码只能包含小写字母、数字、连字符和下划线。"); + if (await db.Roles.AnyAsync(x => x.Code == code, ct)) + throw new IdentityConflictException($"角色编码 {code} 已存在。"); + + var permissions = ResolvePermissionCodes(request.Permissions, request.Modules); + var role = new AppRole { Code = code, Name = request.Name.Trim(), Description = request.Description?.Trim(), IsSystem = false }; + db.Roles.Add(role); + await db.SaveChangesAsync(ct); + foreach (var permissionCode in permissions) + { + var permission = await GetPermissionEntityAsync(permissionCode, ct); + db.RolePermissions.Add(new RolePermission { RoleId = role.Id, PermissionId = permission.Id }); + } + await db.SaveChangesAsync(ct); + return await ToDtoAsync(role, ct); + } + + public async Task UpdateRolePermissionsAsync(Guid roleId, UpdateRolePermissionsRequest request, CancellationToken ct = default) + { + var role = await db.Roles.SingleOrDefaultAsync(x => x.Id == roleId, ct) + ?? throw new IdentityNotFoundException("角色不存在。"); + var permissions = ResolvePermissionCodes(request?.Permissions, request?.Modules); + var existing = await db.RolePermissions.Where(x => x.RoleId == roleId).ToListAsync(ct); + db.RolePermissions.RemoveRange(existing); + foreach (var permissionCode in permissions) + { + var permission = await GetPermissionEntityAsync(permissionCode, ct); + db.RolePermissions.Add(new RolePermission { RoleId = role.Id, PermissionId = permission.Id }); + } + await db.SaveChangesAsync(ct); + return await ToDtoAsync(role, ct); + } + + private async Task GetUserEntityAsync(Guid userId, CancellationToken ct) => + await db.Users.SingleOrDefaultAsync(x => x.Id == userId, ct) + ?? throw new IdentityNotFoundException("用户不存在。"); + + private async Task GetPermissionEntityAsync(string code, CancellationToken ct) => + await db.Permissions.SingleOrDefaultAsync(x => x.Code == code, ct) + ?? throw new IdentityNotFoundException($"权限 {code} 不存在,请先初始化权限目录。"); + + private async Task AddDirectPermissionsAsync(Guid userId, IReadOnlyCollection codes, CancellationToken ct) + { + foreach (var code in codes) + { + var permission = await GetPermissionEntityAsync(code, ct); + db.UserPermissions.Add(new UserPermission { UserId = userId, PermissionId = permission.Id }); + } + } + + private async Task> ResolveRolesAsync(IReadOnlyList? roleCodes, CancellationToken ct) + { + if (roleCodes is null || roleCodes.Count == 0) return []; + var codes = roleCodes.Select(x => x?.Trim().ToLowerInvariant()) + .Where(x => !string.IsNullOrEmpty(x)).Select(x => x!).Distinct(StringComparer.Ordinal).ToList(); + var roles = await db.Roles.Where(x => codes.Contains(x.Code)).ToListAsync(ct); + var missing = codes.Except(roles.Select(x => x.Code), StringComparer.Ordinal).ToList(); + if (missing.Count > 0) + throw new IdentityValidationException("roleCodes", $"角色不存在:{string.Join(", ", missing)}"); + return roles; + } + + private static IReadOnlyList ResolvePermissionCodes(IReadOnlyList? permissions, IReadOnlyList? modules) + { + var codes = new HashSet(StringComparer.Ordinal); + if (permissions is not null) + { + foreach (var raw in permissions) + { + if (!AuthorizationCatalog.TryNormalizePermission(raw, out var code)) + throw new IdentityValidationException("permissions", $"未知权限:{raw}"); + codes.Add(code); + } + } + foreach (var module in NormalizeModules(modules)) + codes.Add(AuthorizationCatalog.ViewPermission(module)); + return codes.OrderBy(x => x, StringComparer.Ordinal).ToList(); + } + + private static IReadOnlyList NormalizeModules(IReadOnlyList? modules) + { + if (modules is null || modules.Count == 0) return []; + var result = new HashSet(StringComparer.Ordinal); + foreach (var raw in modules) + { + var module = AuthorizationCatalog.NormalizeModule(raw) + ?? throw new IdentityValidationException("modules", $"未知模块:{raw}"); + result.Add(module); + } + return result.OrderBy(x => x, StringComparer.Ordinal).ToList(); + } + + private async Task ToDtoAsync(AppUser user, CancellationToken ct) + { + var roles = await db.UserRoles + .Where(x => x.UserId == user.Id) + .Join(db.Roles, ur => ur.RoleId, r => r.Id, (_, r) => r.Code) + .ToListAsync(ct); + var directPermissions = await db.UserPermissions + .Where(x => x.UserId == user.Id) + .Join(db.Permissions, up => up.PermissionId, p => p.Id, (_, p) => p.Code) + .ToListAsync(ct); + var directModules = directPermissions.Select(AuthorizationCatalog.ModuleOf) + .Distinct(StringComparer.Ordinal).OrderBy(x => x, StringComparer.Ordinal).ToList(); + var permissions = await GetEffectivePermissionsAsync(user.Id, ct); + var modules = permissions.Select(AuthorizationCatalog.ModuleOf) + .Distinct(StringComparer.Ordinal).OrderBy(x => x, StringComparer.Ordinal).ToList(); + return new UserDto(user.Id, user.UserName, user.DisplayName, user.IsActive, user.CreatedAt, + roles.OrderBy(x => x, StringComparer.Ordinal).ToList(), modules, permissions, + directModules, directPermissions.OrderBy(x => x, StringComparer.Ordinal).ToList()); + } + + private async Task ToDtoAsync(AppRole role, CancellationToken ct) + { + var permissions = await db.RolePermissions + .Where(x => x.RoleId == role.Id) + .Join(db.Permissions, rp => rp.PermissionId, p => p.Id, (_, p) => p.Code) + .ToListAsync(ct); + var modules = permissions.Select(AuthorizationCatalog.ModuleOf) + .Distinct(StringComparer.Ordinal).OrderBy(x => x, StringComparer.Ordinal).ToList(); + return new RoleDto(role.Id, role.Code, role.Name, role.Description, role.IsSystem, + permissions.OrderBy(x => x, StringComparer.Ordinal).ToList(), modules); + } +} diff --git a/src/Leiren.Erp.Application/Leiren.Erp.Application.csproj b/src/Leiren.Erp.Application/Leiren.Erp.Application.csproj new file mode 100644 index 0000000..3e7187c --- /dev/null +++ b/src/Leiren.Erp.Application/Leiren.Erp.Application.csproj @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + net11.0 + enable + enable + + + diff --git a/src/Leiren.Erp.Application/MasterData/IMasterDataDbContext.cs b/src/Leiren.Erp.Application/MasterData/IMasterDataDbContext.cs new file mode 100644 index 0000000..757d104 --- /dev/null +++ b/src/Leiren.Erp.Application/MasterData/IMasterDataDbContext.cs @@ -0,0 +1,22 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.MasterData; + +/// +/// EF Core boundary for the MasterData module; implemented by Infrastructure. +/// Referencing sets are read only to block deleting a supplier that is already +/// used by quotes, purchasing or billing records. +/// +public interface IMasterDataDbContext +{ + DbSet Suppliers { get; } + DbSet ProductSupplierQuotes { get; } + DbSet PurchaseTasks { get; } + DbSet PurchaseContracts { get; } + DbSet SupplierInvoiceNotices { get; } + DbSet SupplierInvoices { get; } + DbSet SupplierBillingContracts { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/MasterData/MasterDataExceptions.cs b/src/Leiren.Erp.Application/MasterData/MasterDataExceptions.cs new file mode 100644 index 0000000..a4c878b --- /dev/null +++ b/src/Leiren.Erp.Application/MasterData/MasterDataExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.MasterData; + +public sealed class MasterDataNotFoundException(string message) : Exception(message); + +public sealed class MasterDataConflictException(string message) : Exception(message); + +public sealed class MasterDataValidationException(IReadOnlyDictionary errors) + : Exception("主数据校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public MasterDataValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/MasterData/SupplierService.cs b/src/Leiren.Erp.Application/MasterData/SupplierService.cs new file mode 100644 index 0000000..4209b72 --- /dev/null +++ b/src/Leiren.Erp.Application/MasterData/SupplierService.cs @@ -0,0 +1,131 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.MasterData; + +public sealed class SupplierService(IMasterDataDbContext db) +{ + public async Task> ListAsync( + string? search, bool? isActive, int page, int pageSize, CancellationToken ct = default) + { + var query = db.Suppliers.AsNoTracking().AsQueryable(); + if (isActive is { } active) query = query.Where(x => x.IsActive == active); + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => x.Name.Contains(term) + || (x.Code != null && x.Code.Contains(term)) + || (x.NameEn != null && x.NameEn.Contains(term)) + || (x.ContactName != null && x.ContactName.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderBy(x => x.Name) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(ToDto).ToList(); + } + + public async Task GetAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadAsync(id, ct)); + + public async Task CreateAsync(SaveSupplierRequest request, CancellationToken ct = default) + { + var supplier = new Supplier(); + Apply(supplier, request); + await EnsureCodeAvailableAsync(supplier.Code, null, ct); + db.Suppliers.Add(supplier); + await db.SaveChangesAsync(ct); + return ToDto(supplier); + } + + public async Task UpdateAsync(Guid id, SaveSupplierRequest request, CancellationToken ct = default) + { + var supplier = await LoadAsync(id, ct); + Apply(supplier, request); + await EnsureCodeAvailableAsync(supplier.Code, supplier.Id, ct); + supplier.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(supplier); + } + + public async Task DeactivateAsync(Guid id, CancellationToken ct = default) + { + var supplier = await LoadAsync(id, ct); + supplier.IsActive = false; + supplier.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(supplier); + } + + public async Task DeleteAsync(Guid id, CancellationToken ct = default) + { + var supplier = await LoadAsync(id, ct); + if (await IsReferencedAsync(id, ct)) + throw new MasterDataConflictException("供应商已被报价、采购或开票记录引用,不能删除;请改为停用。"); + db.Suppliers.Remove(supplier); + await db.SaveChangesAsync(ct); + } + + private async Task IsReferencedAsync(Guid id, CancellationToken ct) + => await db.ProductSupplierQuotes.AnyAsync(x => x.SupplierId == id, ct) + || await db.PurchaseTasks.AnyAsync(x => x.SupplierId == id, ct) + || await db.PurchaseContracts.AnyAsync(x => x.SupplierId == id, ct) + || await db.SupplierInvoiceNotices.AnyAsync(x => x.SupplierId == id, ct) + || await db.SupplierInvoices.AnyAsync(x => x.SupplierId == id, ct) + || await db.SupplierBillingContracts.AnyAsync(x => x.SellerSupplierId == id, ct); + + private async Task LoadAsync(Guid id, CancellationToken ct) + => await db.Suppliers.SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new MasterDataNotFoundException("供应商不存在。"); + + private async Task EnsureCodeAvailableAsync(string? code, Guid? excludeId, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(code)) return; + var exists = await db.Suppliers.AnyAsync( + x => x.Code == code.Trim() && (excludeId == null || x.Id != excludeId.Value), ct); + if (exists) + throw new MasterDataValidationException(nameof(SaveSupplierRequest.Code), $"供应商编码 {code.Trim()} 已存在。"); + } + + private static void Apply(Supplier s, SaveSupplierRequest r) + { + if (string.IsNullOrWhiteSpace(r.Name)) + throw new MasterDataValidationException(nameof(r.Name), "供应商名称不能为空。"); + if (r.DefaultTaxRate is < 0 or > 100) + throw new MasterDataValidationException(nameof(r.DefaultTaxRate), "默认税率必须在 0 到 100 之间(百分数)。"); + if (!string.IsNullOrWhiteSpace(r.ContactEmail) && !r.ContactEmail.Trim().Contains('@')) + throw new MasterDataValidationException(nameof(r.ContactEmail), "邮箱格式无效。"); + + s.Code = TrimOrNull(r.Code); + s.Name = r.Name.Trim(); + s.NameEn = TrimOrNull(r.NameEn); + s.ContactName = TrimOrNull(r.ContactName); + s.Address = TrimOrNull(r.Address); + s.ContactPhone = TrimOrNull(r.ContactPhone); + s.ContactEmail = TrimOrNull(r.ContactEmail); + s.PaymentTerms = TrimOrNull(r.PaymentTerms); + s.DefaultCurrency = NormalizeCurrency(r.DefaultCurrency); + s.TaxNumber = TrimOrNull(r.TaxNumber); + s.DefaultTaxRate = r.DefaultTaxRate; + s.Remark = TrimOrNull(r.Remark); + s.IsActive = r.IsActive; + } + + private static string? NormalizeCurrency(string? value) + { + var currency = TrimOrNull(value)?.ToUpperInvariant(); + if (currency is not null && currency.Length != 3) + throw new MasterDataValidationException(nameof(SaveSupplierRequest.DefaultCurrency), "默认币种必须是 3 位代码,如 CNY、USD。"); + return currency; + } + + private static string? TrimOrNull(string? value) + => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static SupplierDto ToDto(Supplier s) => new( + s.Id, s.Code, s.Name, s.NameEn, s.ContactName, s.Address, s.ContactPhone, s.ContactEmail, + s.PaymentTerms, s.DefaultCurrency, s.TaxNumber, s.DefaultTaxRate, s.Remark, s.IsActive, + s.CreatedAt, s.UpdatedAt); +} diff --git a/src/Leiren.Erp.Application/Purchasing/IPurchasingDbContext.cs b/src/Leiren.Erp.Application/Purchasing/IPurchasingDbContext.cs new file mode 100644 index 0000000..ee8eb86 --- /dev/null +++ b/src/Leiren.Erp.Application/Purchasing/IPurchasingDbContext.cs @@ -0,0 +1,25 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Purchasing; + +/// +/// EF Core boundary for the Purchasing module; implemented by Infrastructure. +/// Sales sets are read here only to validate the explicit +/// generate-from-sales-order command against a confirmed order. +/// +public interface IPurchasingDbContext +{ + DbSet SalesOrders { get; } + DbSet SalesOrderLines { get; } + DbSet Products { get; } + DbSet ProductParts { get; } + DbSet ProductSupplierQuotes { get; } + DbSet Suppliers { get; } + DbSet PurchaseTasks { get; } + DbSet PurchaseContracts { get; } + DbSet PurchaseArrivals { get; } + DbSet SupplierPayables { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Purchasing/PurchaseContractExportService.cs b/src/Leiren.Erp.Application/Purchasing/PurchaseContractExportService.cs new file mode 100644 index 0000000..3082905 --- /dev/null +++ b/src/Leiren.Erp.Application/Purchasing/PurchaseContractExportService.cs @@ -0,0 +1,114 @@ +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Purchasing; + +/// +/// Generates a purchase-contract workbook from the contract's stored snapshot +/// (contract fields plus its purchase-task lines) and stores the result through +/// the Files module. The workbook is rendered from the configured XLSX template; +/// master data (products, suppliers, quotes) is never read here, so later +/// master-data changes cannot alter an exported contract. Re-exporting the same +/// contract stores a new version of the same file group. +/// +public sealed class PurchaseContractExportService( + IPurchasingDbContext db, FileService files, PurchaseContractTemplateOptions template) +{ + public const string OwnerType = "purchase-contract"; + public const string Category = "generated-contract"; + public const string ContentType = + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + + public async Task ExportAsync(Guid contractId, CancellationToken ct = default) + { + var (contract, lines, rendered) = await RenderAsync(contractId, ct); + using var stream = new MemoryStream(rendered); + + var fileName = $"{SanitizeFileStem(contract.ContractNo)}-采购合同.xlsx"; + var description = + $"采购合同 {contract.ContractNo} 导出;合同版本 {contract.Version};状态 {contract.Status};生成时间 {DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss} UTC。"; + + // One logical file per contract: a re-export becomes a new version of + // the existing generated-contract file instead of a second attachment. + var existing = await files.ListAsync(OwnerType, contract.Id, Category, null, true, 1, 1, ct); + var file = existing.Count > 0 + ? await files.UploadNewVersionAsync( + existing[0].Id, stream, fileName, ContentType, Category, description, ct: ct) + : await files.UploadAsync(new UploadFileCommand( + OwnerType, contract.Id, Category, description, fileName, ContentType, stream), ct); + + return new PurchaseContractExportDto( + contract.Id, contract.ContractNo, contract.Version, contract.Status.ToString(), + file, $"/api/files/{file.Id}/download"); + } + + /// Renders the contract workbook without storing a file; used by the confirm preview. + public async Task<(byte[] Bytes, string FileName)> PreviewAsync(Guid contractId, CancellationToken ct = default) + { + var (contract, _, rendered) = await RenderAsync(contractId, ct); + return (rendered, $"{SanitizeFileStem(contract.ContractNo)}-采购合同-预览.xlsx"); + } + + private async Task<(Domain.Entities.PurchaseContract Contract, List Lines, byte[] Bytes)> RenderAsync( + Guid contractId, CancellationToken ct) + { + var contract = await db.PurchaseContracts.AsNoTracking() + .Include(x => x.Tasks) + .SingleOrDefaultAsync(x => x.Id == contractId, ct) + ?? throw new PurchasingNotFoundException("采购合同不存在。"); + + if (contract.Status == PurchaseContractStatus.Voided) + throw new PurchasingConflictException("已作废的采购合同不能导出。"); + + var lines = contract.Tasks + .Where(x => x.Status != PurchaseTaskStatus.Cancelled) + .OrderBy(x => x.CreatedAt) + .ToList(); + if (lines.Count == 0) + throw new PurchasingValidationException(nameof(contract.Tasks), "采购合同没有可导出的采购任务。"); + + var templateBytes = await LoadTemplateAsync(ct); + + var rendered = PurchaseContractTemplateRenderer.Render( + templateBytes, contract, lines, DateTimeOffset.UtcNow); + return (contract, lines, rendered); + } + + /// + /// The most recently imported purchase-contract template (template editor) + /// wins; without one, the configured template file is used. + /// + private async Task LoadTemplateAsync(CancellationToken ct) + { + var imported = (await files.ListAsync( + DocumentTemplateService.TemplateOwnerType, null, DocumentTemplateKinds.PurchaseContract, null, + currentOnly: true, 1, 200, ct)) + .MaxBy(x => x.CreatedAt); + if (imported is not null) + { + await using var content = (await files.OpenDownloadAsync(imported.Id, ct)).Content; + using var buffer = new MemoryStream(); + await content.CopyToAsync(buffer, ct); + return buffer.ToArray(); + } + + try + { + return await File.ReadAllBytesAsync(template.TemplatePath, ct); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + throw new PurchasingValidationException("Template", $"采购合同模板读取失败:{ex.Message}"); + } + } + + private static string SanitizeFileStem(string contractNo) + { + var invalid = Path.GetInvalidFileNameChars(); + var stem = new string(contractNo.Select(ch => invalid.Contains(ch) || ch < 32 ? '_' : ch).ToArray()).Trim(); + return stem.Length == 0 ? "purchase-contract" : stem; + } +} diff --git a/src/Leiren.Erp.Application/Purchasing/PurchaseContractTemplateRenderer.cs b/src/Leiren.Erp.Application/Purchasing/PurchaseContractTemplateRenderer.cs new file mode 100644 index 0000000..ab6cf82 --- /dev/null +++ b/src/Leiren.Erp.Application/Purchasing/PurchaseContractTemplateRenderer.cs @@ -0,0 +1,104 @@ +using System.Globalization; +using Leiren.Erp.Application.Documents; +using Leiren.Erp.Domain.Entities; + +namespace Leiren.Erp.Application.Purchasing; + +/// +/// Renders a purchase-contract workbook from a real XLSX template through +/// : header and total placeholders are +/// replaced in place and the line block is copied once per contract task. +/// Values come from the contract snapshot only. +/// +public static class PurchaseContractTemplateRenderer +{ + private static readonly TokenTemplateFields Fields = new( + new HashSet(StringComparer.OrdinalIgnoreCase) + { + "CustomerPoNo", "LineNumber", "CustomerSku", "InternalSku", "Unit", "ContentDescription", + "ContentType", "PackagingRequirement", "PurchaseRequirement", "Quantity", "UnitPrice", + "Amount", "TaxRate", "TaxIncluded", "DueDate", + }, + new HashSet(StringComparer.OrdinalIgnoreCase) + { + "LineNumber", "Quantity", "UnitPrice", "Amount", "TaxRate", "TotalAmount", "LineCount", "Version", + }, + new HashSet(StringComparer.OrdinalIgnoreCase) + { + "SignedDate", "RequiredCompletionDate", "DueDate", "GeneratedDate", + }); + + public static byte[] Render( + byte[] templateBytes, PurchaseContract contract, IReadOnlyList lines, DateTimeOffset generatedAt) + { + ArgumentNullException.ThrowIfNull(contract); + ArgumentNullException.ThrowIfNull(lines); + return TokenWorkbookRenderer.Render( + templateBytes, BuildHeaderValues(contract, lines, generatedAt), BuildLineValues(contract, lines), + Fields, "采购合同", message => new PurchasingValidationException("Template", message)); + } + + private static Dictionary BuildHeaderValues( + PurchaseContract contract, IReadOnlyList lines, DateTimeOffset generatedAt) + => new(StringComparer.OrdinalIgnoreCase) + { + ["ContractNo"] = contract.ContractNo, + ["SupplierName"] = contract.SupplierName, + ["SupplierContact"] = contract.SupplierContact, + ["SupplierPhone"] = contract.SupplierPhone, + ["CustomerOrderNo"] = contract.CustomerOrderNo, + ["SignedDate"] = contract.SignedDate?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + ["RequiredCompletionDate"] = contract.RequiredCompletionDate?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + ["PaymentTerms"] = contract.PaymentTerms, + ["Currency"] = contract.Currency, + ["Status"] = contract.Status.ToString(), + ["Version"] = contract.Version.ToString(CultureInfo.InvariantCulture), + ["LineCount"] = lines.Count.ToString(CultureInfo.InvariantCulture), + ["TotalAmount"] = lines.Sum(x => x.Amount).ToString("0.####", CultureInfo.InvariantCulture), + ["GeneratedDate"] = generatedAt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + ["Terms"] = contract.Terms, + }; + + private static List> BuildLineValues( + PurchaseContract contract, IReadOnlyList lines) + { + var result = new List>(lines.Count); + for (var i = 0; i < lines.Count; i++) + { + var task = lines[i]; + result.Add(new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["LineNumber"] = (i + 1).ToString(CultureInfo.InvariantCulture), + ["CustomerPoNo"] = task.CustomerPoNo ?? contract.CustomerOrderNo, + ["CustomerSku"] = task.CustomerSku ?? task.InternalSku, + ["InternalSku"] = task.InternalSku, + ["Unit"] = task.Unit, + ["ContentDescription"] = task.ContentDescription, + ["ContentType"] = task.ContentType.ToString(), + ["PackagingRequirement"] = task.PackagingRequirement ?? task.PurchaseRequirement, + ["PurchaseRequirement"] = task.PurchaseRequirement, + ["Quantity"] = task.Quantity.ToString("0.####", CultureInfo.InvariantCulture), + ["UnitPrice"] = task.UnitPrice.ToString("0.####", CultureInfo.InvariantCulture), + ["Amount"] = task.Amount.ToString("0.####", CultureInfo.InvariantCulture), + ["TaxRate"] = task.TaxRate.ToString("0.####", CultureInfo.InvariantCulture), + ["TaxIncluded"] = task.TaxIncluded ? "是" : "否", + ["DueDate"] = task.DueDate?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + }); + } + return result; + } + + /// Header placeholder names; must match the keys of . + private static readonly string[] HeaderFields = + [ + "ContractNo", "SupplierName", "SupplierContact", "SupplierPhone", "CustomerOrderNo", "SignedDate", + "RequiredCompletionDate", "PaymentTerms", "Currency", "Status", "Version", "LineCount", "TotalAmount", + "GeneratedDate", "Terms", + ]; + + /// Every placeholder name a purchase-contract template may use (header + line). + public static IReadOnlyList FieldNames { get; } = [.. HeaderFields, .. Fields.LineFields.Where(x => !HeaderFields.Contains(x, StringComparer.OrdinalIgnoreCase))]; +} + +/// Absolute path of the XLSX template used for purchase-contract exports. +public sealed record PurchaseContractTemplateOptions(string TemplatePath); diff --git a/src/Leiren.Erp.Application/Purchasing/PurchaseService.cs b/src/Leiren.Erp.Application/Purchasing/PurchaseService.cs new file mode 100644 index 0000000..0ac0575 --- /dev/null +++ b/src/Leiren.Erp.Application/Purchasing/PurchaseService.cs @@ -0,0 +1,723 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Purchasing; + +public sealed class PurchaseService(IPurchasingDbContext db) +{ + // ---------- Purchase tasks ---------- + + public async Task> ListTasksAsync( + Guid? salesOrderId, Guid? purchaseContractId, string? status, string? search, + int page, int pageSize, CancellationToken ct = default) + { + var query = db.PurchaseTasks.AsNoTracking().AsQueryable(); + if (salesOrderId is not null) query = query.Where(x => x.SalesOrderId == salesOrderId.Value); + if (purchaseContractId is not null) query = query.Where(x => x.PurchaseContractId == purchaseContractId.Value); + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new PurchasingValidationException(nameof(status), "采购任务状态无效。"); + query = query.Where(x => x.Status == parsed); + } + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => + x.ContentDescription.Contains(term) || + x.SupplierName.Contains(term) || + x.SalesOrderNo.Contains(term) || + (x.CustomerPoNo != null && x.CustomerPoNo.Contains(term)) || + (x.InternalSku != null && x.InternalSku.Contains(term)) || + (x.CustomerSku != null && x.CustomerSku.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(ToListItem).ToList(); + } + + /// + /// Purchasing page view: every non-cancelled customer order grouped with its + /// products and parts, plus the supplier and quantity currently assigned to + /// each row (TBD until a purchase plan exists). + /// + public async Task> GetOverviewAsync(CancellationToken ct = default) + { + var orders = await db.SalesOrders.AsNoTracking() + .Include(x => x.Lines) + .Where(x => x.Status != SalesOrderStatus.Cancelled) + .OrderByDescending(x => x.OrderDate) + .ThenBy(x => x.OrderNumber) + .ToListAsync(ct); + + var tasks = await db.PurchaseTasks.AsNoTracking() + .Where(x => x.Status != PurchaseTaskStatus.Cancelled) + .ToListAsync(ct); + + var productIds = orders.SelectMany(x => x.Lines).Select(x => x.ProductId).Distinct().ToList(); + var products = await db.Products.AsNoTracking() + .Include(x => x.Parts) + .Where(x => productIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, ct); + + var contractIds = tasks + .Where(x => x.PurchaseContractId is not null) + .Select(x => x.PurchaseContractId!.Value) + .Distinct() + .ToList(); + var contractStatuses = contractIds.Count == 0 + ? new Dictionary() + : await db.PurchaseContracts.AsNoTracking() + .Where(x => contractIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, x => x.Status, ct); + + var result = new List(orders.Count); + foreach (var order in orders) + { + var orderTasks = tasks.Where(x => x.SalesOrderId == order.Id).ToList(); + // A draft contract has not been exported/confirmed yet, so the next + // action is still the export step; only a confirmed contract can + // accept arrivals. + var planStatus = orderTasks.Count == 0 + ? "待生成采购方案" + : orderTasks.All(x => x.Status == PurchaseTaskStatus.Completed) + ? "已完成" + : orderTasks.Any(x => x.PurchaseContractId is null + || !contractStatuses.TryGetValue(x.PurchaseContractId.Value, out var status) + || status == PurchaseContractStatus.Draft) + ? "待导出采购合同" + : "待到货确认"; + + var productsDto = new List(); + foreach (var line in order.Lines.OrderBy(x => x.LineNumber)) + { + if (!products.TryGetValue(line.ProductId, out var product)) continue; + var lineTasks = orderTasks.Where(x => x.SalesOrderLineId == line.Id).ToList(); + var parts = product.Parts.Where(x => x.IsActive).OrderBy(x => x.SortOrder).ToList(); + var rows = new List(); + + if (parts.Count == 0) + { + var task = lineTasks.FirstOrDefault(x => x.ProductPartId is null); + rows.Add(new PurchaseOverviewRowDto(null, line.ProductNameZh, + SupplierNameOf(task), task?.Quantity ?? line.Quantity, task?.Unit ?? line.Unit)); + } + else + { + foreach (var part in parts) + { + var task = lineTasks.FirstOrDefault(x => x.ProductPartId == part.Id); + rows.Add(new PurchaseOverviewRowDto(part.Id, part.Name, SupplierNameOf(task), + task?.Quantity ?? line.Quantity * part.QuantityPerProduct, task?.Unit ?? part.Unit)); + } + + // A task can outlive the part it referenced; keep it visible instead of dropping it. + foreach (var task in lineTasks.Where(x => x.ProductPartId is not null && parts.All(p => p.Id != x.ProductPartId))) + rows.Add(new PurchaseOverviewRowDto(task.ProductPartId, task.ContentDescription, SupplierNameOf(task), task.Quantity, task.Unit)); + } + + productsDto.Add(new PurchaseOverviewProductDto(product.Id, line.ProductInternalSku, line.ProductNameZh, rows)); + } + + result.Add(new PurchaseOverviewDto(order.Id, order.OrderNumber, order.CustomerPoNumber, order.CustomerName, + order.Status.ToString(), order.OrderDate, order.RequiredDeliveryDate, planStatus, productsDto, + orderTasks.Count, orderTasks.Count(x => x.PurchaseContractId is null))); + } + + return result; + } + + private static string SupplierNameOf(PurchaseTask? task) + => string.IsNullOrWhiteSpace(task?.SupplierName) ? "TBD" : task!.SupplierName; + + public async Task GetTaskAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadTaskAsync(id, ct)); + + public async Task CreateTaskAsync(CreatePurchaseTaskRequest request, CancellationToken ct = default) + { + var (order, line) = await LoadConfirmedLineAsync(request.SalesOrderId, request.SalesOrderLineId, ct); + var productId = await ResolveProductPartAsync(request.ProductId ?? line.ProductId, request.ProductPartId, ct); + var supplier = await ResolveSupplierAsync(request.SupplierId, request.SupplierName, ct); + + var task = new PurchaseTask + { + SalesOrderId = order.Id, + SalesOrderLineId = line.Id, + ProductId = productId.ProductId, + ProductPartId = productId.PartId, + SalesOrderNo = order.OrderNumber, + CustomerPoNo = order.CustomerPoNumber, + InternalSku = line.ProductInternalSku, + ProductNameZh = line.ProductNameZh, + ProductNameEn = line.ProductNameEn, + CustomerSku = line.CustomerSku + }; + ApplyTaskFields(task, request.ContentDescription, request.ContentType, supplier.Id, + supplier.Name, request.Quantity, request.Unit ?? line.Unit, request.UnitPrice, + request.Currency, request.TaxIncluded, request.TaxRate, request.DueDate, + request.PurchaseRequirement, request.PackagingRequirement, line); + db.PurchaseTasks.Add(task); + await db.SaveChangesAsync(ct); + return ToDto(task); + } + + public async Task GenerateFromSalesOrderAsync( + GeneratePurchaseTasksRequest request, CancellationToken ct = default) + { + var order = await db.SalesOrders.AsNoTracking() + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == request.SalesOrderId, ct) + ?? throw new PurchasingNotFoundException("销售订单不存在。"); + EnsureConfirmed(order); + + var lines = order.Lines.OrderBy(x => x.LineNumber).ToList(); + if (request.SalesOrderLineIds is { Count: > 0 }) + { + var wanted = request.SalesOrderLineIds.Distinct().ToList(); + var missing = wanted.Where(id => lines.All(x => x.Id != id)).ToList(); + if (missing.Count > 0) + throw new PurchasingValidationException(nameof(request.SalesOrderLineIds), "部分订单明细不属于该销售订单。"); + lines = lines.Where(x => wanted.Contains(x.Id)).ToList(); + } + + var taskedLineIds = (await db.PurchaseTasks.AsNoTracking() + .Where(x => x.SalesOrderId == order.Id && x.Status != PurchaseTaskStatus.Cancelled) + .Select(x => x.SalesOrderLineId).ToListAsync(ct)) + .ToHashSet(); + + var created = new List(); + var skipped = new List(); + var assignments = request.Assignments ?? []; + var supplierIds = assignments.Select(x => x.SupplierId).Distinct().ToList(); + var supplierMap = supplierIds.Count == 0 + ? new Dictionary() + : await db.Suppliers.AsNoTracking() + .Where(x => supplierIds.Contains(x.Id)) + .ToDictionaryAsync(x => x.Id, ct); + if (supplierIds.Any(id => !supplierMap.ContainsKey(id))) + throw new PurchasingValidationException(nameof(request.Assignments), "部分供应商不存在。"); + + foreach (var line in lines) + { + if (taskedLineIds.Contains(line.Id)) + { + skipped.Add(line.Id); + continue; + } + + var product = await db.Products.AsNoTracking() + .Include(x => x.Parts) + .Include(x => x.SupplierQuotes) + .SingleOrDefaultAsync(x => x.Id == line.ProductId, ct) + ?? throw new PurchasingValidationException(nameof(line.ProductId), $"订单明细 {line.LineNumber} 引用的产品不存在。"); + + var parts = product.Parts.Where(x => x.IsActive).OrderBy(x => x.SortOrder).ToList(); + if (parts.Count == 0) + { + created.Add(BuildGeneratedTask(order, line, product, part: null, product.SupplierQuotes, assignments, supplierMap)); + } + else + { + created.AddRange(parts.Select(part => + BuildGeneratedTask(order, line, product, part, product.SupplierQuotes, assignments, supplierMap))); + } + } + + db.PurchaseTasks.AddRange(created); + await db.SaveChangesAsync(ct); + return new GeneratePurchaseTasksResultDto(created.Select(x => ToDto(x)).ToList(), skipped); + } + + public async Task UpdateTaskAsync(Guid id, UpdatePurchaseTaskRequest request, CancellationToken ct = default) + { + var task = await LoadTaskAsync(id, ct); + if (task.PurchaseContractId is not null) + throw new PurchasingConflictException("采购任务已加入采购合同,不能直接编辑;请先作废该合同。"); + try { task.EnsureEditable(); } + catch (InvalidOperationException ex) { throw new PurchasingConflictException(ex.Message); } + + var resolved = await ResolveProductPartAsync(request.ProductId ?? task.ProductId, request.ProductPartId, ct); + task.ProductId = resolved.ProductId; + task.ProductPartId = resolved.PartId; + var line = await db.SalesOrderLines.AsNoTracking().SingleOrDefaultAsync(x => x.Id == task.SalesOrderLineId, ct); + var supplier = await ResolveSupplierAsync(request.SupplierId, request.SupplierName, ct); + ApplyTaskFields(task, request.ContentDescription, request.ContentType, supplier.Id, + supplier.Name, request.Quantity, request.Unit, request.UnitPrice, + request.Currency, request.TaxIncluded, request.TaxRate, request.DueDate, + request.PurchaseRequirement, request.PackagingRequirement, line); + task.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(task); + } + + public async Task CancelTaskAsync(Guid id, CancellationToken ct = default) + { + var task = await LoadTaskAsync(id, ct); + if (task.PurchaseContractId is { } contractId) + { + var contract = await db.PurchaseContracts.SingleOrDefaultAsync(x => x.Id == contractId, ct); + if (contract is not null && contract.Status != PurchaseContractStatus.Draft) + throw new PurchasingConflictException("采购任务已随采购合同确认,不能单独取消;请先作废合同。"); + task.PurchaseContractId = null; + task.PurchaseContract = null; + } + + try { task.Cancel(); } + catch (InvalidOperationException ex) { throw new PurchasingConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + } + + // ---------- Purchase contracts ---------- + + public async Task> ListContractsAsync( + string? status, string? search, int page, int pageSize, CancellationToken ct = default) + { + var query = db.PurchaseContracts.AsNoTracking().Include(x => x.Tasks).AsQueryable(); + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new PurchasingValidationException(nameof(status), "采购合同状态无效。"); + query = query.Where(x => x.Status == parsed); + } + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => + x.ContractNo.Contains(term) || x.SupplierName.Contains(term) || + (x.CustomerOrderNo != null && x.CustomerOrderNo.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(x => new PurchaseContractListItemDto( + x.Id, x.ContractNo, x.SupplierName, x.CustomerOrderNo, x.RequiredCompletionDate, + x.Currency, x.Status.ToString(), x.TotalAmount, + x.Tasks.Count(t => t.Status != PurchaseTaskStatus.Cancelled), x.UpdatedAt)).ToList(); + } + + public async Task GetContractAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadContractAsync(id, ct)); + + public async Task CreateContractAsync(CreatePurchaseContractRequest request, CancellationToken ct = default) + { + if (request.TaskIds is null || request.TaskIds.Count == 0) + throw new PurchasingValidationException(nameof(request.TaskIds), "采购合同至少需要一个采购任务。"); + + var taskIds = request.TaskIds.Distinct().ToList(); + var tasks = await db.PurchaseTasks.Where(x => taskIds.Contains(x.Id)).ToListAsync(ct); + if (tasks.Count != taskIds.Count) + throw new PurchasingNotFoundException("部分采购任务不存在。"); + + foreach (var task in tasks) + { + if (task.Status != PurchaseTaskStatus.Pending) + throw new PurchasingConflictException($"采购任务「{task.ContentDescription}」不是待下单状态,不能加入新合同。"); + if (task.PurchaseContractId is not null) + throw new PurchasingConflictException($"采购任务「{task.ContentDescription}」已加入其他采购合同。"); + } + // A master supplier id resolves to the supplier's current name/contact + // snapshot for the contract; otherwise the task snapshot name is used. + Supplier? masterSupplier = null; + if (request.SupplierId is { } contractSupplierId) + { + masterSupplier = await db.Suppliers.AsNoTracking().SingleOrDefaultAsync(x => x.Id == contractSupplierId, ct) + ?? throw new PurchasingValidationException(nameof(request.SupplierId), "供应商不存在。"); + if (!masterSupplier.IsActive) + throw new PurchasingValidationException(nameof(request.SupplierId), "供应商已停用,不能新建采购合同。"); + } + + var supplierName = masterSupplier?.Name ?? (string.IsNullOrWhiteSpace(request.SupplierName) + ? tasks.Select(x => x.SupplierName).FirstOrDefault(x => !string.IsNullOrWhiteSpace(x)) ?? string.Empty + : request.SupplierName.Trim()); + if (string.IsNullOrWhiteSpace(supplierName)) + throw new PurchasingValidationException(nameof(request.SupplierName), "供应商不能为空。"); + if (tasks.Any(x => !string.IsNullOrWhiteSpace(x.SupplierName) && + !string.Equals(x.SupplierName, supplierName, StringComparison.OrdinalIgnoreCase))) + throw new PurchasingConflictException("一份采购合同只能包含同一供应商的采购任务。"); + if (request.SupplierId is not null && tasks.Any(x => x.SupplierId is not null && x.SupplierId != request.SupplierId)) + throw new PurchasingConflictException("采购任务的供应商与合同供应商不一致。"); + if (tasks.Select(x => x.Currency).Distinct(StringComparer.OrdinalIgnoreCase).Count() > 1) + throw new PurchasingConflictException("一份采购合同只能包含同一币种的采购任务。"); + + var contractNo = string.IsNullOrWhiteSpace(request.ContractNo) + ? $"PC-{DateTimeOffset.UtcNow:yyyyMMddHHmmss}-{Guid.NewGuid().ToString("N")[..4].ToUpperInvariant()}" + : request.ContractNo.Trim(); + if (await db.PurchaseContracts.AnyAsync(x => x.ContractNo == contractNo, ct)) + throw new PurchasingConflictException($"采购合同号 {contractNo} 已存在。"); + + var contract = new PurchaseContract + { + ContractNo = contractNo, + SupplierId = request.SupplierId ?? tasks.Select(x => x.SupplierId).FirstOrDefault(x => x is not null), + SupplierName = supplierName, + SupplierContact = TrimOrNull(request.SupplierContact) ?? masterSupplier?.ContactName, + SupplierPhone = TrimOrNull(request.SupplierPhone) ?? masterSupplier?.ContactPhone, + CustomerOrderNo = TrimOrNull(request.CustomerOrderNo) + ?? string.Join(", ", tasks.Select(x => x.SalesOrderNo).Distinct()), + SignedDate = request.SignedDate, + RequiredCompletionDate = request.RequiredCompletionDate, + PaymentTerms = TrimOrNull(request.PaymentTerms) ?? masterSupplier?.PaymentTerms, + Terms = TrimOrNull(request.Terms), + Currency = tasks[0].Currency + }; + if (contract.RequiredCompletionDate is not null && contract.SignedDate is not null && + contract.RequiredCompletionDate < contract.SignedDate) + throw new PurchasingValidationException(nameof(request.RequiredCompletionDate), "完货时间不能早于签约时间。"); + + db.PurchaseContracts.Add(contract); + foreach (var task in tasks) + { + task.PurchaseContractId = contract.Id; + task.Touch(); + } + + await db.SaveChangesAsync(ct); + return ToDto(await LoadContractAsync(contract.Id, ct)); + } + + public async Task UpdateContractAsync( + Guid id, UpdatePurchaseContractRequest request, CancellationToken ct = default) + { + var contract = await LoadContractAsync(id, ct); + if (contract.Status != PurchaseContractStatus.Draft) + throw new PurchasingConflictException("只有草稿状态的采购合同可以修改。"); + if (request.RequiredCompletionDate is not null && request.SignedDate is not null && + request.RequiredCompletionDate < request.SignedDate) + throw new PurchasingValidationException(nameof(request.RequiredCompletionDate), "完货时间不能早于签约时间。"); + + contract.CustomerOrderNo = TrimOrNull(request.CustomerOrderNo); + contract.SignedDate = request.SignedDate; + contract.RequiredCompletionDate = request.RequiredCompletionDate; + contract.PaymentTerms = TrimOrNull(request.PaymentTerms); + contract.Terms = TrimOrNull(request.Terms); + // The version changes only when a draft contract is edited; confirm locks it. + contract.Version++; + contract.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(contract); + } + + public async Task ConfirmContractAsync(Guid id, CancellationToken ct = default) + { + var contract = await LoadContractAsync(id, ct); + if (contract.Tasks.Count(x => x.Status != PurchaseTaskStatus.Cancelled) == 0) + throw new PurchasingValidationException(nameof(contract.Tasks), "采购合同没有可确认的采购任务。"); + if (contract.Tasks.Any(x => x.Status != PurchaseTaskStatus.Pending && x.Status != PurchaseTaskStatus.Cancelled)) + throw new PurchasingConflictException("合同中存在不是待下单状态的采购任务,不能确认。"); + + try { contract.Confirm(); } + catch (InvalidOperationException ex) { throw new PurchasingConflictException(ex.Message); } + + foreach (var task in contract.Tasks.Where(x => x.Status == PurchaseTaskStatus.Pending)) + { + task.Status = PurchaseTaskStatus.Ordered; + task.Touch(); + } + + // A confirmed contract is an amount owed to the supplier. + db.SupplierPayables.Add(SupplierPayable.ForContract(contract)); + await db.SaveChangesAsync(ct); + return ToDto(contract); + } + + public async Task VoidContractAsync(Guid id, CancellationToken ct = default) + { + var contract = await LoadContractAsync(id, ct); + try { contract.Void(); } + catch (InvalidOperationException ex) { throw new PurchasingConflictException(ex.Message); } + + foreach (var task in contract.Tasks) + { + task.PurchaseContractId = null; + if (task.Status == PurchaseTaskStatus.Ordered) + task.Status = PurchaseTaskStatus.Pending; + task.Touch(); + } + + contract.Tasks.Clear(); + var payable = await db.SupplierPayables.SingleOrDefaultAsync(x => x.PurchaseContractId == contract.Id, ct); + if (payable?.Status == SupplierPayableStatus.Paid) + throw new PurchasingConflictException("该采购合同的款项已付款,不能作废。"); + payable?.Void(); + await db.SaveChangesAsync(ct); + } + + // ---------- Arrival / completion ---------- + + public async Task RecordArrivalAsync( + Guid taskId, RecordPurchaseArrivalRequest request, CancellationToken ct = default) + { + var task = await LoadTaskAsync(taskId, ct); + if (task.Status is not (PurchaseTaskStatus.Ordered or PurchaseTaskStatus.PartiallyCompleted)) + throw new PurchasingConflictException(task.Status switch + { + PurchaseTaskStatus.Pending => "采购任务尚未通过已确认的采购合同下单,不能登记到货。", + PurchaseTaskStatus.Completed => "采购任务已全部到货,不能继续登记。", + PurchaseTaskStatus.Cancelled => "采购任务已取消,不能登记到货。", + _ => "当前采购任务状态不能登记到货。" + }); + if (request.Quantity <= 0) + throw new PurchasingValidationException(nameof(request.Quantity), "本次到货数量必须大于 0。"); + if (request.Quantity > task.RemainingQuantity) + throw new PurchasingValidationException(nameof(request.Quantity), + $"本次到货数量不能超过剩余数量 {task.RemainingQuantity}。"); + if (request.PackingRate is <= 0) + throw new PurchasingValidationException(nameof(request.PackingRate), "实际装箱率必须大于 0。"); + if (request.CartonCount is <= 0) + throw new PurchasingValidationException(nameof(request.CartonCount), "实际箱数必须大于 0。"); + foreach (var (value, field) in new[] + { + (request.CartonLength, nameof(request.CartonLength)), + (request.CartonWidth, nameof(request.CartonWidth)), + (request.CartonHeight, nameof(request.CartonHeight)), + (request.CartonGrossWeight, nameof(request.CartonGrossWeight)), + (request.CartonNetWeight, nameof(request.CartonNetWeight)) + }) + { + if (value is < 0) + throw new PurchasingValidationException(field, "实际包装尺寸和重量不能小于 0。"); + } + + var cartonCount = request.CartonCount + ?? (request.PackingRate is { } rate + ? (int)decimal.Ceiling(request.Quantity / rate) + : null); + var arrival = new PurchaseArrival + { + PurchaseTaskId = task.Id, + Quantity = request.Quantity, + ArrivedDate = request.ArrivedDate ?? DateOnly.FromDateTime(DateTime.UtcNow), + PackingRate = request.PackingRate, + CartonCount = cartonCount, + CartonLength = request.CartonLength, + CartonWidth = request.CartonWidth, + CartonHeight = request.CartonHeight, + CartonGrossWeight = request.CartonGrossWeight, + CartonNetWeight = request.CartonNetWeight, + // Carton dimensions are centimetres (product-master convention); + // totals are computed here, never taken from client input. + TotalGrossWeight = cartonCount is { } c && request.CartonGrossWeight is { } gw ? c * gw : null, + TotalNetWeight = cartonCount is { } c2 && request.CartonNetWeight is { } nw ? c2 * nw : null, + TotalCbm = cartonCount is { } c3 && request.CartonLength is { } l && request.CartonWidth is { } w && request.CartonHeight is { } h + ? decimal.Round(l * w * h / 1_000_000m * c3, 4, MidpointRounding.AwayFromZero) + : null, + ExceptionNote = TrimOrNull(request.ExceptionNote), + Remark = TrimOrNull(request.Remark) + }; + + db.PurchaseArrivals.Add(arrival); + task.ApplyArrival(request.Quantity); + + if (task.PurchaseContractId is { } contractId) + { + var contract = await LoadContractAsync(contractId, ct); + contract.RefreshProgress(); + } + + await db.SaveChangesAsync(ct); + return ToDto(arrival); + } + + // ---------- Helpers ---------- + + private async Task<(SalesOrder Order, SalesOrderLine Line)> LoadConfirmedLineAsync( + Guid salesOrderId, Guid salesOrderLineId, CancellationToken ct) + { + var order = await db.SalesOrders.AsNoTracking() + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == salesOrderId, ct) + ?? throw new PurchasingNotFoundException("销售订单不存在。"); + EnsureConfirmed(order); + var line = order.Lines.SingleOrDefault(x => x.Id == salesOrderLineId) + ?? throw new PurchasingValidationException(nameof(salesOrderLineId), "订单明细不属于该销售订单。"); + return (order, line); + } + + private static void EnsureConfirmed(SalesOrder order) + { + if (order.Status != SalesOrderStatus.Confirmed) + throw new PurchasingConflictException("只有已确认的销售订单可以生成采购任务。"); + } + + private PurchaseTask BuildGeneratedTask( + SalesOrder order, SalesOrderLine line, Product product, ProductPart? part, + IReadOnlyCollection quotes, + IReadOnlyList assignments, + IReadOnlyDictionary suppliers) + { + var quote = quotes + .Where(x => x.ProductPartId == part?.Id) + .OrderByDescending(x => x.IsDefault) + .ThenByDescending(x => x.CreatedAt) + .FirstOrDefault(); + var assignment = assignments + .FirstOrDefault(x => x.SalesOrderLineId == line.Id && x.ProductPartId == part?.Id); + var supplier = assignment is null ? null : suppliers[assignment.SupplierId]; + + var contentType = part is null + ? PurchaseContentType.Finished + : ParseContentType(part.PartType.ToString()); + if (!string.IsNullOrWhiteSpace(assignment?.ContentType)) + contentType = ParseContentType(assignment!.ContentType); + + return new PurchaseTask + { + SalesOrderId = order.Id, + SalesOrderLineId = line.Id, + ProductId = product.Id, + ProductPartId = part?.Id, + SalesOrderNo = order.OrderNumber, + CustomerPoNo = order.CustomerPoNumber, + InternalSku = line.ProductInternalSku, + ProductNameZh = line.ProductNameZh, + ProductNameEn = line.ProductNameEn, + CustomerSku = line.CustomerSku, + ContentDescription = assignment is { ContentDescription: { Length: > 0 } description } + ? description.Trim() + : part?.Name ?? line.ProductNameZh, + ContentType = contentType, + SupplierId = assignment?.SupplierId ?? quote?.SupplierId, + SupplierName = supplier?.Name ?? quote?.SupplierName ?? string.Empty, + Quantity = part is null ? line.Quantity : line.Quantity * part.QuantityPerProduct, + Unit = assignment?.Unit is { Length: > 0 } unit ? unit.Trim() : part?.Unit ?? line.Unit, + UnitPrice = assignment?.UnitPrice ?? quote?.UnitPrice ?? 0, + Currency = assignment?.Currency is { Length: > 0 } currency ? currency.Trim() : quote?.Currency ?? "CNY", + TaxIncluded = assignment?.TaxIncluded ?? quote?.TaxIncluded ?? false, + TaxRate = assignment?.TaxRate ?? quote?.TaxRate ?? 0, + DueDate = line.RequiredDeliveryDate ?? order.RequiredDeliveryDate, + PurchaseRequirement = product.PurchaseRequirement, + PackagingRequirement = product.PackagingNote + }; + } + + private async Task<(Guid? ProductId, Guid? PartId)> ResolveProductPartAsync( + Guid? productId, Guid? partId, CancellationToken ct) + { + if (partId is not null) + { + var part = await db.ProductParts.AsNoTracking().SingleOrDefaultAsync(x => x.Id == partId.Value, ct) + ?? throw new PurchasingValidationException(nameof(partId), "产品部件不存在。"); + if (productId is not null && part.ProductId != productId.Value) + throw new PurchasingValidationException(nameof(partId), "产品部件不属于指定产品。"); + return (part.ProductId, part.Id); + } + + if (productId is not null && !await db.Products.AnyAsync(x => x.Id == productId.Value, ct)) + throw new PurchasingValidationException(nameof(productId), "产品不存在。"); + return (productId, null); + } + + /// + /// Resolves an optional master supplier id to the snapshot name stored on the + /// task. Without an id the caller-provided (snapshot) name is kept as-is. + /// + private async Task<(Guid? Id, string? Name)> ResolveSupplierAsync( + Guid? supplierId, string? supplierName, CancellationToken ct) + { + if (supplierId is not { } id) return (null, supplierName); + var supplier = await db.Suppliers.AsNoTracking().SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new PurchasingValidationException(nameof(supplierId), "供应商不存在。"); + if (!supplier.IsActive) + throw new PurchasingValidationException(nameof(supplierId), "供应商已停用,不能用于采购任务。"); + return (supplier.Id, supplier.Name); + } + + private static void ApplyTaskFields( + PurchaseTask task, string? contentDescription, string? contentType, Guid? supplierId, + string? supplierName, decimal quantity, string? unit, decimal unitPrice, string? currency, + bool taxIncluded, decimal taxRate, DateOnly? dueDate, string? purchaseRequirement, + string? packagingRequirement, SalesOrderLine? line) + { + if (quantity <= 0) + throw new PurchasingValidationException(nameof(quantity), "采购数量必须大于 0。"); + if (unitPrice < 0) + throw new PurchasingValidationException(nameof(unitPrice), "采购单价不能小于 0。"); + if (taxRate is < 0 or > 100) + throw new PurchasingValidationException(nameof(taxRate), "税率必须在 0 到 100 之间(百分数)。"); + if (quantity < task.ArrivedQuantity) + throw new PurchasingValidationException(nameof(quantity), "采购数量不能小于已到货数量。"); + + var normalizedCurrency = string.IsNullOrWhiteSpace(currency) ? "CNY" : currency.Trim().ToUpperInvariant(); + if (normalizedCurrency.Length != 3) + throw new PurchasingValidationException(nameof(currency), "币种必须是 3 位代码,如 CNY、USD。"); + + task.ContentDescription = string.IsNullOrWhiteSpace(contentDescription) + ? (line?.ProductNameZh ?? task.ContentDescription) + : contentDescription.Trim(); + if (string.IsNullOrWhiteSpace(task.ContentDescription)) + throw new PurchasingValidationException(nameof(contentDescription), "采购内容不能为空。"); + task.ContentType = ParseContentType(contentType); + task.SupplierId = supplierId; + task.SupplierName = (supplierName ?? string.Empty).Trim(); + task.Quantity = quantity; + task.Unit = string.IsNullOrWhiteSpace(unit) ? (line?.Unit ?? task.Unit) : unit.Trim(); + if (string.IsNullOrWhiteSpace(task.Unit)) + throw new PurchasingValidationException(nameof(unit), "采购单位不能为空。"); + task.UnitPrice = unitPrice; + task.Currency = normalizedCurrency; + task.TaxIncluded = taxIncluded; + task.TaxRate = taxRate; + task.DueDate = dueDate; + task.PurchaseRequirement = TrimOrNull(purchaseRequirement); + task.PackagingRequirement = TrimOrNull(packagingRequirement); + } + + private async Task LoadTaskAsync(Guid id, CancellationToken ct) + => await db.PurchaseTasks + .Include(x => x.Arrivals) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new PurchasingNotFoundException("采购任务不存在。"); + + private async Task LoadContractAsync(Guid id, CancellationToken ct) + => await db.PurchaseContracts + .Include(x => x.Tasks) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new PurchasingNotFoundException("采购合同不存在。"); + + private static PurchaseContentType ParseContentType(string? value) + => string.IsNullOrWhiteSpace(value) + ? PurchaseContentType.Finished + : Enum.TryParse(value, ignoreCase: true, out var parsed) + ? parsed + : throw new PurchasingValidationException(nameof(value), "采购内容类型无效。"); + + private static string? TrimOrNull(string? value) + => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + + private static PurchaseTaskListItemDto ToListItem(PurchaseTask t) => new( + t.Id, t.SalesOrderId, t.SalesOrderLineId, t.PurchaseContractId, + t.ProductId, t.ProductPartId, t.SupplierId, t.SalesOrderNo, + t.CustomerPoNo, t.InternalSku, t.CustomerSku, t.ContentDescription, t.ContentType.ToString(), + t.SupplierName, t.Quantity, t.Unit, t.UnitPrice, t.Currency, t.TaxIncluded, t.TaxRate, t.Amount, t.DueDate, + t.Status.ToString(), t.ArrivedQuantity, t.RemainingQuantity, t.UpdatedAt); + + private static PurchaseTaskDto ToDto(PurchaseTask t) => new( + t.Id, t.SalesOrderId, t.SalesOrderLineId, t.PurchaseContractId, t.ProductId, t.ProductPartId, + t.SalesOrderNo, t.CustomerPoNo, t.InternalSku, t.ProductNameZh, t.ProductNameEn, t.CustomerSku, + t.ContentDescription, t.ContentType.ToString(), t.SupplierId, t.SupplierName, t.Quantity, t.Unit, + t.UnitPrice, t.Currency, t.TaxIncluded, t.TaxRate, t.Amount, t.DueDate, t.PurchaseRequirement, + t.PackagingRequirement, t.Status.ToString(), t.ArrivedQuantity, t.RemainingQuantity, + t.CreatedAt, t.UpdatedAt, t.CompletedAt, + t.Arrivals.OrderBy(x => x.ArrivedDate).ThenBy(x => x.CreatedAt).Select(ToDto).ToList()); + + private static PurchaseArrivalDto ToDto(PurchaseArrival a) => new( + a.Id, a.PurchaseTaskId, a.Quantity, a.ArrivedDate, a.PackingRate, a.CartonCount, + a.CartonLength, a.CartonWidth, a.CartonHeight, a.CartonGrossWeight, a.CartonNetWeight, + a.TotalGrossWeight, a.TotalNetWeight, a.TotalCbm, a.ExceptionNote, a.Remark, a.CreatedAt); + + private static PurchaseContractDto ToDto(PurchaseContract c) => new( + c.Id, c.ContractNo, c.SupplierId, c.SupplierName, c.SupplierContact, c.SupplierPhone, + c.CustomerOrderNo, c.SignedDate, c.RequiredCompletionDate, c.PaymentTerms, c.Terms, + c.Currency, c.Status.ToString(), c.Version, c.TotalAmount, c.CreatedAt, c.UpdatedAt, + c.ConfirmedAt, c.CompletedAt, + c.Tasks.OrderBy(x => x.CreatedAt).Select(ToListItem).ToList()); +} diff --git a/src/Leiren.Erp.Application/Purchasing/PurchasingExceptions.cs b/src/Leiren.Erp.Application/Purchasing/PurchasingExceptions.cs new file mode 100644 index 0000000..5c8cb0c --- /dev/null +++ b/src/Leiren.Erp.Application/Purchasing/PurchasingExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Purchasing; + +public sealed class PurchasingNotFoundException(string message) : Exception(message); + +public sealed class PurchasingConflictException(string message) : Exception(message); + +public sealed class PurchasingValidationException(IReadOnlyDictionary errors) + : Exception("采购资料校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public PurchasingValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Sales/ISalesDbContext.cs b/src/Leiren.Erp.Application/Sales/ISalesDbContext.cs new file mode 100644 index 0000000..4eaeefe --- /dev/null +++ b/src/Leiren.Erp.Application/Sales/ISalesDbContext.cs @@ -0,0 +1,25 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Sales; + +/// +/// EF Core boundary for the Sales module; implemented by Infrastructure. +/// Purchase/shipment/billing sets are read-only here and used solely to +/// compute the workbench summary from source records; Sales never writes them. +/// +public interface ISalesDbContext +{ + DbSet Customers { get; } + DbSet SalesOrders { get; } + DbSet SalesOrderLines { get; } + DbSet Products { get; } + DbSet PurchaseTasks { get; } + DbSet PurchaseArrivals { get; } + DbSet ShipmentLines { get; } + DbSet SupplierInvoiceNotices { get; } + DbSet SupplierInvoiceNoticeLines { get; } + DbSet SupplierInvoices { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Sales/PoExcelImportService.cs b/src/Leiren.Erp.Application/Sales/PoExcelImportService.cs new file mode 100644 index 0000000..b42ced7 --- /dev/null +++ b/src/Leiren.Erp.Application/Sales/PoExcelImportService.cs @@ -0,0 +1,727 @@ +using System.Globalization; +using ClosedXML.Excel; +using Leiren.Erp.Application.Files; +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Sales; + +/// Order-header values supplied alongside the uploaded PO workbook (multipart form fields). +public sealed record PoExcelImportOptions( + Guid? CustomerId, + string? CustomerPoNumber, + string? OrderNumber, + DateOnly? OrderDate, + DateOnly? RequiredDeliveryDate, + string? Currency, + string? TransportMode, + string? LoadingPort, + string? DestinationPort, + string? DestinationCountry, + string? TradeTerm, + string? PaymentTerms, + string? ShippingNote, + string? Remark, + string? SheetName, + bool CreateDraft, + bool AttachOriginal, + string? UploadedBy); + +/// +/// Header-driven customer-PO (.xlsx) importer. Columns are located by header +/// name (Chinese/English aliases), never by fixed cell coordinates, and the +/// header row / worksheet are discovered from those names. Every non-blank +/// data row is returned with its real worksheet row number and explicit +/// errors; a draft order is created only when every row is valid, so no row +/// can be silently skipped. +/// +public sealed class PoExcelImportService( + ISalesDbContext db, + SalesOrderService salesOrders, + FileService files, + FileStorageOptions storageOptions) +{ + private const string FieldInternalSku = "InternalSku"; + private const string FieldCustomerSku = "CustomerSku"; + private const string FieldCustomerProductName = "CustomerProductName"; + private const string FieldQuantity = "Quantity"; + private const string FieldUnit = "Unit"; + private const string FieldPackingRate = "PackingRate"; + private const string FieldUnitPrice = "UnitPrice"; + private const string FieldAmount = "Amount"; + private const string FieldRequiredDeliveryDate = "RequiredDeliveryDate"; + private const string FieldCustomerRemark = "CustomerRemark"; + private const string FieldRemark = "Remark"; + + private static readonly string[] RequiredFields = [FieldInternalSku, FieldQuantity]; + + public async Task ImportAsync( + Stream content, + string? fileName, + string? contentType, + PoExcelImportOptions options, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(content); + ArgumentNullException.ThrowIfNull(options); + + var safeFileName = fileName?.Trim() ?? string.Empty; + if (safeFileName.Length == 0 || + !string.Equals(Path.GetExtension(safeFileName), ".xlsx", StringComparison.OrdinalIgnoreCase)) + throw new SalesValidationException("file", "PO 导入只接受真实 .xlsx 文件。"); + + if (options.AttachOriginal && !options.CreateDraft) + throw new SalesValidationException( + "attachOriginal", + "保存原始 PO 附件需要同时创建草稿订单(createDraft=true),因为附件必须关联到订单。"); + + var bytes = await ReadAllBytesAsync(content, ct); + + var preview = await ParsePreviewAsync(bytes, safeFileName, options.SheetName, ct); + if (!options.CreateDraft || !preview.CanCreateDraft) + return new PoImportResultDto(preview, null, null); + + if (options.CustomerId is not { } customerId || customerId == Guid.Empty) + throw new SalesValidationException("customerId", "创建草稿订单时必须选择客户。"); + + var request = new SaveSalesOrderRequest( + options.OrderNumber, + customerId, + options.CustomerPoNumber, + options.OrderDate, + options.RequiredDeliveryDate, + options.Currency, + options.TransportMode, + options.LoadingPort, + options.DestinationPort, + options.DestinationCountry, + options.TradeTerm, + options.PaymentTerms, + options.ShippingNote, + PoAttachmentReference: null, + PoAttachmentFileName: null, + options.Remark, + preview.Rows.Select(x => new SalesOrderLineRequest( + x.ProductId!.Value, + x.CustomerSku, + x.CustomerProductName, + x.Quantity!.Value, + x.Unit, + x.PackingRate, + x.UnitPrice ?? 0m, + x.RequiredDeliveryDate, + x.CustomerRemark, + x.Remark)).ToList()); + + var created = await salesOrders.CreateAsync(request, ct); + + FileAttachmentDto? attachment = null; + if (options.AttachOriginal) + { + await using var original = new MemoryStream(bytes, writable: false); + attachment = await files.UploadAsync(new UploadFileCommand( + OwnerType: "SalesOrder", + OwnerId: created.Id, + Category: "CustomerPO", + Description: "原始客户 PO Excel(PO 导入)", + OriginalFileName: safeFileName, + ContentType: contentType, + Content: original, + UploadedByUserId: null, + UploadedBy: options.UploadedBy), ct); + + // Point the order at the stored original PO through the existing + // attachment reference fields; the file itself stays in FileService. + var order = await db.SalesOrders.SingleAsync(x => x.Id == created.Id, ct); + order.PoAttachmentReference = attachment.Id.ToString("D"); + order.PoAttachmentFileName = attachment.OriginalFileName; + order.Touch(); + await db.SaveChangesAsync(ct); + created = await salesOrders.GetAsync(created.Id, ct); + } + + return new PoImportResultDto(preview, created, attachment); + } + + // ---------- Workbook parsing ---------- + + private async Task ParsePreviewAsync( + byte[] bytes, string fileName, string? requestedSheetName, CancellationToken ct) + { + XLWorkbook workbook; + try + { + workbook = new XLWorkbook(new MemoryStream(bytes, writable: false)); + } + catch (Exception ex) + { + throw new SalesValidationException("file", $"Excel 文件无法解析(不是有效的 .xlsx 文件):{ex.Message}"); + } + + using (workbook) + { + var sheets = workbook.Worksheets.ToList(); + var availableSheets = sheets.Select(x => x.Name).ToList(); + if (sheets.Count == 0) + { + return EmptyPreview(fileName, null, availableSheets, + [new PoImportIssueDto(null, "file", "工作簿中没有任何工作表。")]); + } + + SheetCandidate? candidate = null; + var selectionIssues = new List(); + + if (!string.IsNullOrWhiteSpace(requestedSheetName)) + { + var sheet = sheets.FirstOrDefault(x => + string.Equals(x.Name, requestedSheetName.Trim(), StringComparison.OrdinalIgnoreCase)); + if (sheet is null) + { + return EmptyPreview(fileName, requestedSheetName.Trim(), availableSheets, + [new PoImportIssueDto(null, "sheetName", + $"工作表「{requestedSheetName.Trim()}」不存在。可用工作表:{string.Join("、", availableSheets)}。")]); + } + + var (found, ambiguity) = ScanSheet(sheet); + if (ambiguity is not null) + return EmptyPreview(fileName, sheet.Name, availableSheets, [ambiguity]); + if (found is null) + return EmptyPreview(fileName, sheet.Name, availableSheets, MissingHeaderIssues(sheet)); + candidate = found; + } + else + { + var candidates = new List(); + var ambiguities = new List(); + foreach (var sheet in sheets) + { + var (found, ambiguity) = ScanSheet(sheet); + if (found is not null) candidates.Add(found); + if (ambiguity is not null) ambiguities.Add(ambiguity); + } + + if (ambiguities.Count > 0) + return EmptyPreview(fileName, null, availableSheets, ambiguities); + if (candidates.Count > 1) + { + return EmptyPreview(fileName, null, availableSheets, + [new PoImportIssueDto(null, "sheetName", + $"多个工作表都包含可识别的 PO 表头({string.Join("、", candidates.Select(x => x.Sheet.Name))}),无法确定导入哪一个,请指定 sheetName。")]); + } + if (candidates.Count == 0) + { + return EmptyPreview(fileName, null, availableSheets, + [new PoImportIssueDto(null, "headers", + $"未在任何工作表中找到同时包含必填表头「{FieldLabel(FieldInternalSku)}」和「{FieldLabel(FieldQuantity)}」的表头行。" + + $"必填表头:{string.Join("、", RequiredFields.Select(FieldLabel))}。请检查表头名称,或指定 sheetName 后重试。")]); + } + candidate = candidates[0]; + } + + selectionIssues.AddRange(candidate.Map.Issues); + + var parsedRows = ParseDataRows(candidate); + await ResolveProductsAsync(parsedRows, ct); + + var rows = parsedRows.Select(x => x.ToDto()).ToList(); + if (rows.Count == 0) + selectionIssues.Add(new PoImportIssueDto(null, "rows", "表头之后没有数据行。")); + + var canCreate = selectionIssues.Count == 0 && rows.Count > 0 && rows.All(x => x.IsValid); + return new PoImportPreviewDto( + fileName, + candidate.Sheet.Name, + availableSheets, + candidate.HeaderRow, + candidate.Map.Headers, + candidate.Map.UnrecognizedHeaders, + selectionIssues, + rows, + candidate.BlankRowNumbers, + rows.Count, + rows.Count(x => x.IsValid), + rows.Count(x => !x.IsValid), + canCreate); + } + } + + private static PoImportPreviewDto EmptyPreview( + string fileName, string? sheetName, IReadOnlyList availableSheets, + IReadOnlyList issues) => new( + fileName, sheetName, availableSheets, null, [], [], issues, [], [], 0, 0, 0, false); + + /// Finds the header row of one sheet by recognized header names (first 50 used rows). + private static (SheetCandidate? Candidate, PoImportIssueDto? Ambiguity) ScanSheet(IXLWorksheet sheet) + { + var range = sheet.RangeUsed(); + if (range is null) return (null, null); + + var firstRow = range.FirstRow().RowNumber(); + var lastRow = range.LastRow().RowNumber(); + var firstColumn = range.FirstColumn().ColumnNumber(); + var lastColumn = range.LastColumn().ColumnNumber(); + var scanEnd = Math.Min(lastRow, firstRow + 49); + + var qualified = new List(); + for (var row = firstRow; row <= scanEnd; row++) + { + var map = MapHeaders(sheet, row, firstColumn, lastColumn); + if (map.Columns.ContainsKey(FieldInternalSku) && map.Columns.ContainsKey(FieldQuantity)) + qualified.Add(new SheetCandidate(sheet, row, firstColumn, lastColumn, lastRow, map)); + } + + if (qualified.Count == 0) return (null, null); + + var bestScore = qualified.Max(x => x.Map.Columns.Count); + var best = qualified.Where(x => x.Map.Columns.Count == bestScore).ToList(); + if (best.Count > 1) + { + return (null, new PoImportIssueDto(null, "headers", + $"工作表「{sheet.Name}」中第 {string.Join("、", best.Select(x => x.HeaderRow))} 行都包含同等完整的 PO 表头,表头行不明确,请删除多余表头行或整理文件后重试。")); + } + return (best[0], null); + } + + private static IReadOnlyList MissingHeaderIssues(IXLWorksheet sheet) + { + var range = sheet.RangeUsed(); + if (range is null) + return [new PoImportIssueDto(null, "headers", $"工作表「{sheet.Name}」是空的,没有可识别的表头行。")]; + + var firstRow = range.FirstRow().RowNumber(); + var lastRow = range.LastRow().RowNumber(); + var firstColumn = range.FirstColumn().ColumnNumber(); + var lastColumn = range.LastColumn().ColumnNumber(); + var scanEnd = Math.Min(lastRow, firstRow + 49); + + HeaderMap? best = null; + var bestRow = firstRow; + for (var row = firstRow; row <= scanEnd; row++) + { + var map = MapHeaders(sheet, row, firstColumn, lastColumn); + if (best is null || map.Columns.Count > best.Columns.Count) + { + best = map; + bestRow = row; + } + } + + var issues = new List(); + if (best is not null) issues.AddRange(best.Issues); + foreach (var field in RequiredFields.Where(f => best is null || !best.Columns.ContainsKey(f))) + { + issues.Add(new PoImportIssueDto(bestRow, field, + $"缺少必填表头「{FieldLabel(field)}」。已识别表头:{(best is null || best.Headers.Count == 0 ? "(无)" : string.Join("、", best.Headers))}。")); + } + if (issues.Count == 0) + issues.Add(new PoImportIssueDto(null, "headers", $"工作表「{sheet.Name}」中未找到可识别的表头行。")); + return issues; + } + + private static HeaderMap MapHeaders(IXLWorksheet sheet, int row, int firstColumn, int lastColumn) + { + var map = new HeaderMap(); + for (var column = firstColumn; column <= lastColumn; column++) + { + var header = CellText(sheet.Cell(row, column)); + if (string.IsNullOrWhiteSpace(header)) continue; + map.Headers.Add(header); + map.HeadersInColumnOrder[column] = header; + + if (!HeaderAliases.TryGetValue(NormalizeHeader(header), out var field)) + { + map.UnrecognizedHeaders.Add(header); + continue; + } + if (map.Columns.TryGetValue(field, out var existingColumn)) + { + map.Issues.Add(new PoImportIssueDto(row, field, + $"表头字段「{FieldLabel(field)}」不明确:第 {XLHelper.GetColumnLetterFromNumber(existingColumn)} 列与第 {XLHelper.GetColumnLetterFromNumber(column)} 列都映射到该字段,请只保留一列。")); + continue; + } + map.Columns[field] = column; + } + return map; + } + + private static List ParseDataRows(SheetCandidate candidate) + { + var sheet = candidate.Sheet; + var rows = new List(); + + for (var rowNumber = candidate.HeaderRow + 1; rowNumber <= candidate.LastRow; rowNumber++) + { + var raw = new Dictionary(StringComparer.Ordinal); + var anyValue = false; + for (var column = candidate.FirstColumn; column <= candidate.LastColumn; column++) + { + var text = CellText(sheet.Cell(rowNumber, column)); + if (!string.IsNullOrWhiteSpace(text)) anyValue = true; + if (candidate.Map.HeadersInColumnOrder.TryGetValue(column, out var header)) + { + if (header is not null) + { + var key = header; + if (raw.ContainsKey(key)) key = $"{header}(列 {XLHelper.GetColumnLetterFromNumber(column)})"; + raw[key] = text; + } + } + } + + if (!anyValue) + { + candidate.BlankRowNumbers.Add(rowNumber); + continue; + } + + var parsed = new ParsedRow { RowNumber = rowNumber, RawValues = raw }; + string? Text(string field) => + candidate.Map.Columns.TryGetValue(field, out var col) ? CellText(sheet.Cell(rowNumber, col)) : null; + IXLCell? Cell(string field) => + candidate.Map.Columns.TryGetValue(field, out var col) ? sheet.Cell(rowNumber, col) : null; + + parsed.InternalSku = Text(FieldInternalSku); + if (string.IsNullOrWhiteSpace(parsed.InternalSku)) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldInternalSku, "内部货号为空。")); + parsed.CustomerSku = Text(FieldCustomerSku); + parsed.CustomerProductName = Text(FieldCustomerProductName); + parsed.Unit = Text(FieldUnit); + parsed.CustomerRemark = Text(FieldCustomerRemark); + parsed.Remark = Text(FieldRemark); + + var quantityCell = Cell(FieldQuantity); + var quantityText = Text(FieldQuantity); + if (quantityCell is null || string.IsNullOrWhiteSpace(quantityText)) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldQuantity, "数量为空。")); + else if (!TryParseDecimal(quantityCell, out var quantity)) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldQuantity, $"数量「{quantityText}」不是有效数字。")); + else if (quantity <= 0) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldQuantity, "数量必须大于 0。")); + else + parsed.Quantity = quantity; + + var packingText = Text(FieldPackingRate); + if (!string.IsNullOrWhiteSpace(packingText)) + { + if (!TryParseDecimal(Cell(FieldPackingRate)!, out var packing)) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldPackingRate, $"装箱率「{packingText}」不是有效数字。")); + else if (packing <= 0 || packing != Math.Truncate(packing) || packing > int.MaxValue) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldPackingRate, $"装箱率「{packingText}」必须是大于 0 的整数。")); + else + parsed.PackingRate = (int)packing; + } + + var priceText = Text(FieldUnitPrice); + if (!string.IsNullOrWhiteSpace(priceText)) + { + if (!TryParseDecimal(Cell(FieldUnitPrice)!, out var price)) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldUnitPrice, $"单价「{priceText}」不是有效数字。")); + else if (price < 0) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldUnitPrice, "单价不能小于 0。")); + else + parsed.UnitPrice = price; + } + + var amountText = Text(FieldAmount); + if (!string.IsNullOrWhiteSpace(amountText)) + { + if (!TryParseDecimal(Cell(FieldAmount)!, out var amount)) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldAmount, $"金额「{amountText}」不是有效数字。")); + else + { + parsed.Amount = amount; + if (parsed.Quantity is { } q && parsed.UnitPrice is { } p && + Math.Abs(amount - q * p) > 0.05m) + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldAmount, + $"金额 {amount} 与数量×单价({q}×{p}={q * p})不一致。")); + } + } + + var dateCell = Cell(FieldRequiredDeliveryDate); + var dateText = Text(FieldRequiredDeliveryDate); + if (dateCell is not null && !string.IsNullOrWhiteSpace(dateText)) + { + if (TryParseDate(dateCell, out var date)) + parsed.RequiredDeliveryDate = date; + else + parsed.Errors.Add(new PoImportIssueDto(rowNumber, FieldRequiredDeliveryDate, $"交期「{dateText}」不是有效日期。")); + } + + rows.Add(parsed); + } + return rows; + } + + private async Task ResolveProductsAsync(List rows, CancellationToken ct) + { + var skus = rows.Select(x => x.InternalSku) + .Where(x => !string.IsNullOrWhiteSpace(x)) + .Select(x => x!.Trim()) + .Distinct(StringComparer.Ordinal) + .ToList(); + if (skus.Count == 0) return; + + var products = (await db.Products.AsNoTracking() + .Where(x => skus.Contains(x.InternalSku)) + .Select(x => new { x.Id, x.InternalSku, x.NameZh, x.NameEn, x.Status }) + .ToListAsync(ct)) + .Select(x => new ProductLookup(x.Id, x.InternalSku, x.NameZh, x.NameEn, x.Status)) + .ToList(); + + // Case-variant SKUs are not matched by the exact query above; fall back + // to a key-only scan so they resolve instead of being reported missing. + var missing = skus.Where(s => products.All(p => + !string.Equals(p.InternalSku, s, StringComparison.OrdinalIgnoreCase))).ToList(); + if (missing.Count > 0) + { + var allKeys = (await db.Products.AsNoTracking() + .Select(x => new { x.Id, x.InternalSku, x.NameZh, x.NameEn, x.Status }) + .ToListAsync(ct)) + .Select(x => new ProductLookup(x.Id, x.InternalSku, x.NameZh, x.NameEn, x.Status)); + products.AddRange(allKeys.Where(p => missing.Contains(p.InternalSku, StringComparer.OrdinalIgnoreCase))); + } + + var bySku = products + .GroupBy(x => x.InternalSku, StringComparer.OrdinalIgnoreCase) + .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase); + + foreach (var row in rows) + { + if (string.IsNullOrWhiteSpace(row.InternalSku)) continue; + var sku = row.InternalSku.Trim(); + if (!bySku.TryGetValue(sku, out var matches)) + { + row.Errors.Add(new PoImportIssueDto(row.RowNumber, FieldInternalSku, $"产品货号「{sku}」不存在。")); + continue; + } + if (matches.Count > 1) + { + row.Errors.Add(new PoImportIssueDto(row.RowNumber, FieldInternalSku, $"产品货号「{sku}」对应多个产品,无法确定。")); + continue; + } + var product = matches[0]; + row.ProductId = product.Id; + row.ProductInternalSku = product.InternalSku; + row.ProductNameZh = product.NameZh; + row.ProductNameEn = product.NameEn; + if (product.Status != ProductStatus.Published) + row.Errors.Add(new PoImportIssueDto(row.RowNumber, FieldInternalSku, + $"产品 {product.InternalSku} 未发布(当前状态 {product.Status}),不能加入订单。")); + } + } + + // ---------- Cell helpers ---------- + + private static string? CellText(IXLCell cell) + { + if (cell.IsEmpty()) return null; + try + { + if (cell.DataType == XLDataType.DateTime) + return cell.GetDateTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + var text = cell.GetString(); + return string.IsNullOrWhiteSpace(text) ? null : text.Trim(); + } + catch (Exception) + { + var text = cell.Value.ToString(); + return string.IsNullOrWhiteSpace(text) ? null : text.Trim(); + } + } + + private static bool TryParseDecimal(IXLCell cell, out decimal value) + { + value = 0; + if (cell.IsEmpty()) return false; + if (cell.DataType == XLDataType.Number) + { + try { value = cell.GetValue(); return true; } + catch (Exception) { return false; } + } + if (cell.DataType is XLDataType.DateTime or XLDataType.Boolean) return false; + + var text = CellText(cell); + if (string.IsNullOrWhiteSpace(text)) return false; + var cleaned = text.Replace(",", string.Empty).Replace(" ", string.Empty) + .Trim('¥', '¥', '$', '€', '£'); + return decimal.TryParse(cleaned, NumberStyles.Number | NumberStyles.AllowCurrencySymbol, + CultureInfo.InvariantCulture, out value) + || decimal.TryParse(cleaned, NumberStyles.Number, CultureInfo.CurrentCulture, out value); + } + + private static bool TryParseDate(IXLCell cell, out DateOnly value) + { + value = default; + if (cell.IsEmpty()) return false; + if (cell.DataType == XLDataType.DateTime) + { + value = DateOnly.FromDateTime(cell.GetDateTime()); + return true; + } + if (cell.DataType == XLDataType.Number) + { + try + { + var serial = cell.GetValue(); + if (serial is <= 0 or > 100000) return false; + value = DateOnly.FromDateTime(DateTime.FromOADate(serial)); + return true; + } + catch (Exception) { return false; } + } + + var text = CellText(cell); + if (string.IsNullOrWhiteSpace(text)) return false; + // ISO-style formats first so slash dates are not silently reinterpreted. + string[] formats = + [ + "yyyy-MM-dd", "yyyy/MM/dd", "yyyy/M/d", "yyyy.MM.dd", "yyyy年M月d日", + "M/d/yyyy", "MM/dd/yyyy", "d/M/yyyy", "dd/MM/yyyy" + ]; + if (DateOnly.TryParseExact(text, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out value)) + return true; + return DateOnly.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out value); + } + + private async Task ReadAllBytesAsync(Stream content, CancellationToken ct) + { + var maxBytes = storageOptions.MaxFileSizeBytes > 0 ? storageOptions.MaxFileSizeBytes : 50L * 1024 * 1024; + await using var buffer = new MemoryStream(); + var chunk = new byte[81920]; + int read; + while ((read = await content.ReadAsync(chunk, ct)) > 0) + { + if (buffer.Length + read > maxBytes) + throw new SalesValidationException("file", $"PO 文件超过大小上限({maxBytes} 字节)。"); + buffer.Write(chunk, 0, read); + } + if (buffer.Length == 0) + throw new SalesValidationException("file", "PO 文件内容为空。"); + return buffer.ToArray(); + } + + // ---------- Header aliases ---------- + + private static string NormalizeHeader(string header) + => new(header.Trim().ToLowerInvariant().Where(char.IsLetterOrDigit).ToArray()); + + private static string FieldLabel(string field) => field switch + { + FieldInternalSku => "内部货号", + FieldCustomerSku => "客户货号", + FieldCustomerProductName => "客户英文描述", + FieldQuantity => "数量", + FieldUnit => "单位", + FieldPackingRate => "装箱率", + FieldUnitPrice => "单价", + FieldAmount => "金额", + FieldRequiredDeliveryDate => "交期", + FieldCustomerRemark => "客户备注", + FieldRemark => "备注", + _ => field + }; + + private static readonly IReadOnlyDictionary HeaderAliases = BuildHeaderAliases(); + + private static IReadOnlyDictionary BuildHeaderAliases() + { + var map = new Dictionary(StringComparer.Ordinal); + void Add(string field, params string[] aliases) + { + foreach (var alias in aliases) map[NormalizeHeader(alias)] = field; + } + + Add(FieldInternalSku, + "Internal SKU", "InternalSku", "Product SKU", "Product Code", "Product No", "Product Number", + "Item Code", "Item No", "Item Number", "Article", "Article No", "Article Number", "SKU", + "内部货号", "内部编号", "产品货号", "产品编号", "产品料号", "货号", "商品编号", "料号"); + Add(FieldCustomerSku, + "Customer SKU", "Customer Item", "Customer Item No", "Customer Item Code", + "Customer Product Code", "Customer Part No", "Customer Part Number", "Customer No", + "客户货号", "客户SKU", "客户料号", "客户编号", "客户产品编号"); + Add(FieldCustomerProductName, + "Customer Product Name", "Customer Description", "Customer Product Description", + "English Description", "Product Description", "Item Description", "Description", + "Description EN", "Product Name EN", "English Name", "Product Description EN", + "英文品名", "英文名称", "英文描述", "客户品名", "客户描述", "客户产品名称", "产品英文名", "商品英文描述"); + Add(FieldQuantity, + "Quantity", "Qty", "Order Quantity", "Order Qty", "Ordered Quantity", "Ordered Qty", + "Purchase Quantity", "Quantity Ordered", "Qty Pcs", "Quantity Pcs", + "数量", "订购数量", "订单数量", "采购数量", "下单数量"); + Add(FieldUnit, + "Unit", "UOM", "Unit of Measure", "单位", "计量单位"); + Add(FieldPackingRate, + "Packing Rate", "Pack Rate", "Quantity Per Carton", "Qty Per Carton", "Pcs Per Carton", + "Pieces Per Carton", "Per Carton", "Qty Per Ctn", "Pcs Per Ctn", "Quantity Per Ctn", "Packing Quantity", + "装箱率", "每箱数量", "每箱件数", "入数", "单箱数量", "装箱数", "每箱装箱数"); + Add(FieldUnitPrice, + "Unit Price", "Price", "Unit Cost", "Sale Price", "Selling Price", "Unit Amount", + "单价", "价格", "未税单价"); + Add(FieldAmount, + "Amount", "Line Amount", "Total Amount", "Total Price", "Total", + "金额", "小计", "总金额", "行金额"); + Add(FieldRequiredDeliveryDate, + "Required Delivery Date", "Delivery Date", "Requested Delivery Date", "Requested Date", + "Required Date", "Delivery", "ETA", "ETD", "Ship Date", + "交期", "交货日期", "交货期", "要求交期", "要求交货日期", "到货日期", "出货日期"); + Add(FieldCustomerRemark, + "Customer Remark", "Customer Remarks", "Customer Note", "Customer Notes", "客户备注"); + Add(FieldRemark, + "Remark", "Remarks", "Note", "Notes", "备注", "说明"); + return map; + } + + // ---------- Internal parse state ---------- + + private sealed class HeaderMap + { + public Dictionary Columns { get; } = new(StringComparer.Ordinal); + public List Headers { get; } = []; + public List UnrecognizedHeaders { get; } = []; + public List Issues { get; } = []; + /// Column number -> original header text, for raw-row preservation. + public Dictionary HeadersInColumnOrder { get; } = new(); + } + + private sealed class SheetCandidate( + IXLWorksheet sheet, int headerRow, int firstColumn, int lastColumn, int lastRow, HeaderMap map) + { + public IXLWorksheet Sheet { get; } = sheet; + public int HeaderRow { get; } = headerRow; + public int FirstColumn { get; } = firstColumn; + public int LastColumn { get; } = lastColumn; + public int LastRow { get; } = lastRow; + public HeaderMap Map { get; } = map; + public List BlankRowNumbers { get; } = []; + } + + private sealed class ParsedRow + { + public int RowNumber { get; set; } + public string? InternalSku { get; set; } + public Guid? ProductId { get; set; } + public string? ProductInternalSku { get; set; } + public string? ProductNameZh { get; set; } + public string? ProductNameEn { get; set; } + public string? CustomerSku { get; set; } + public string? CustomerProductName { get; set; } + public decimal? Quantity { get; set; } + public string? Unit { get; set; } + public int? PackingRate { get; set; } + public decimal? UnitPrice { get; set; } + public decimal? Amount { get; set; } + public DateOnly? RequiredDeliveryDate { get; set; } + public string? CustomerRemark { get; set; } + public string? Remark { get; set; } + public IReadOnlyDictionary RawValues { get; set; } = new Dictionary(); + public List Errors { get; } = []; + + public PoImportRowDto ToDto() => new( + RowNumber, InternalSku, ProductId, ProductInternalSku, ProductNameZh, ProductNameEn, + CustomerSku, CustomerProductName, Quantity, Unit, PackingRate, UnitPrice, Amount, + RequiredDeliveryDate, CustomerRemark, Remark, RawValues, Errors.ToList()); + } + + private sealed record ProductLookup(Guid Id, string InternalSku, string NameZh, string NameEn, ProductStatus Status); +} diff --git a/src/Leiren.Erp.Application/Sales/SalesExceptions.cs b/src/Leiren.Erp.Application/Sales/SalesExceptions.cs new file mode 100644 index 0000000..4b674d4 --- /dev/null +++ b/src/Leiren.Erp.Application/Sales/SalesExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Sales; + +public sealed class SalesNotFoundException(string message) : Exception(message); + +public sealed class SalesConflictException(string message) : Exception(message); + +public sealed class SalesValidationException(IReadOnlyDictionary errors) + : Exception("客户订单校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public SalesValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Sales/SalesOrderService.cs b/src/Leiren.Erp.Application/Sales/SalesOrderService.cs new file mode 100644 index 0000000..3390fa4 --- /dev/null +++ b/src/Leiren.Erp.Application/Sales/SalesOrderService.cs @@ -0,0 +1,587 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Sales; + +public sealed class SalesOrderService(ISalesDbContext db) +{ + // ---------- Customers ---------- + + public async Task> ListCustomersAsync( + string? search, bool? isActive, int page, int pageSize, CancellationToken ct = default) + { + var query = db.Customers.AsNoTracking().AsQueryable(); + if (isActive is { } active) query = query.Where(x => x.IsActive == active); + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => x.Name.Contains(term) + || (x.Code != null && x.Code.Contains(term)) + || (x.NameEn != null && x.NameEn.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderBy(x => x.Name) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(ToDto).ToList(); + } + + public async Task GetCustomerAsync(Guid id, CancellationToken ct = default) + => ToDto(await LoadCustomerAsync(id, ct)); + + public async Task CreateCustomerAsync(SaveCustomerRequest request, CancellationToken ct = default) + { + var customer = new Customer(); + ApplyCustomer(customer, request); + await EnsureCustomerCodeAvailableAsync(customer.Code, null, ct); + db.Customers.Add(customer); + await db.SaveChangesAsync(ct); + return ToDto(customer); + } + + public async Task UpdateCustomerAsync(Guid id, SaveCustomerRequest request, CancellationToken ct = default) + { + var customer = await LoadCustomerAsync(id, ct); + ApplyCustomer(customer, request); + await EnsureCustomerCodeAvailableAsync(customer.Code, customer.Id, ct); + customer.Touch(); + await db.SaveChangesAsync(ct); + return ToDto(customer); + } + + // ---------- Sales orders ---------- + + public async Task> ListAsync( + string? search, string? status, Guid? customerId, int page, int pageSize, CancellationToken ct = default) + { + var query = db.SalesOrders.AsNoTracking().Include(x => x.Lines).AsQueryable(); + + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new SalesValidationException(nameof(status), "客户订单状态无效。"); + query = query.Where(x => x.Status == parsed); + } + + if (customerId is { } cid) query = query.Where(x => x.CustomerId == cid); + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => x.OrderNumber.Contains(term) + || x.CustomerPoNumber.Contains(term) + || x.CustomerName.Contains(term)); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + var summaries = await ComputeSummariesAsync(items, ct); + return items.Select(x => new SalesOrderListItemDto( + x.Id, x.OrderNumber, x.CustomerId, x.CustomerName, x.CustomerPoNumber, + x.OrderDate, x.RequiredDeliveryDate, x.Currency, x.Status.ToString(), + x.TotalAmount, x.Lines.Count, x.UpdatedAt, summaries[x.Id])).ToList(); + } + + public async Task GetAsync(Guid id, CancellationToken ct = default) + => await ToDtoAsync(await LoadOrderAsync(id, ct), ct); + + public async Task CreateAsync(SaveSalesOrderRequest request, CancellationToken ct = default) + { + var customer = await ResolveCustomerAsync(request.CustomerId, ct); + var lines = await BuildLinesAsync(request, ct); + + var order = new SalesOrder { Status = SalesOrderStatus.Draft }; + ApplyOrder(order, request, customer); + order.OrderNumber = await ResolveOrderNumberAsync(request.OrderNumber, null, ct); + foreach (var line in lines) order.Lines.Add(line); + order.RecalculateTotal(); + + db.SalesOrders.Add(order); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(order, ct); + } + + public async Task UpdateAsync(Guid id, SaveSalesOrderRequest request, CancellationToken ct = default) + { + var order = await LoadOrderAsync(id, ct); + EnsureDraft(order); + + var customer = await ResolveCustomerAsync(request.CustomerId, ct); + var lines = await BuildLinesAsync(request, ct); + + ApplyOrder(order, request, customer); + order.OrderNumber = await ResolveOrderNumberAsync(request.OrderNumber, order.Id, ct); + + // Full-line replacement: lines are owned by the order (cascade delete). + db.SalesOrderLines.RemoveRange(order.Lines); + order.Lines.Clear(); + foreach (var line in lines) order.Lines.Add(line); + order.RecalculateTotal(); + order.Touch(); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(await LoadOrderAsync(order.Id, ct), ct); + } + + public async Task ConfirmAsync(Guid id, ConfirmSalesOrderRequest? request, CancellationToken ct = default) + { + var order = await LoadOrderAsync(id, ct); + EnsureDraft(order); + + var errors = new Dictionary(); + var customer = await db.Customers.AsNoTracking().SingleOrDefaultAsync(x => x.Id == order.CustomerId, ct); + if (customer is null) errors["CustomerId"] = ["客户不存在。"]; + else if (!customer.IsActive) errors["CustomerId"] = ["客户已停用,不能确认订单。"]; + if (string.IsNullOrWhiteSpace(order.CustomerPoNumber)) errors["CustomerPoNumber"] = ["确认前必须填写客户 PO 号。"]; + if (order.Lines.Count == 0) errors["Lines"] = ["确认前订单至少需要一条明细。"]; + + // Products must still be Published at confirmation time. + var productIds = order.Lines.Select(x => x.ProductId).Distinct().ToList(); + var products = await db.Products.AsNoTracking() + .Where(x => productIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct); + for (var i = 0; i < order.Lines.Count; i++) + { + var line = order.Lines[i]; + if (!products.TryGetValue(line.ProductId, out var product)) + errors[$"Lines[{i}].ProductId"] = ["产品不存在。"]; + else if (product.Status != ProductStatus.Published) + errors[$"Lines[{i}].ProductId"] = [$"产品 {product.InternalSku} 未发布(当前状态 {product.Status}),不能确认订单。"]; + if (line.Quantity <= 0) errors[$"Lines[{i}].Quantity"] = ["数量必须大于 0。"]; + } + + if (errors.Count > 0) throw new SalesValidationException(errors); + + order.RecalculateTotal(); + try { order.Confirm(request?.ConfirmedBy); } + catch (InvalidOperationException ex) { throw new SalesConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return await ToDtoAsync(order, ct); + } + + public async Task CancelAsync(Guid id, CancelSalesOrderRequest? request, CancellationToken ct = default) + { + var order = await LoadOrderAsync(id, ct); + try { order.Cancel(request?.Reason); } + catch (InvalidOperationException ex) { throw new SalesConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return await ToDtoAsync(order, ct); + } + + /// Deletes a draft order with its lines; confirmed orders can only be cancelled. + public async Task DeleteAsync(Guid id, CancellationToken ct = default) + { + var order = await LoadOrderAsync(id, ct); + EnsureDraft(order); + db.SalesOrderLines.RemoveRange(order.Lines); + db.SalesOrders.Remove(order); + await db.SaveChangesAsync(ct); + } + + // ---------- Helpers ---------- + + private static void EnsureDraft(SalesOrder order) + { + try { order.EnsureDraft(); } + catch (InvalidOperationException ex) { throw new SalesConflictException(ex.Message); } + } + + private async Task LoadCustomerAsync(Guid id, CancellationToken ct) + => await db.Customers.SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new SalesNotFoundException("客户不存在。"); + + private async Task LoadOrderAsync(Guid id, CancellationToken ct) + => await db.SalesOrders.Include(x => x.Lines.OrderBy(l => l.LineNumber)).Include(x => x.Customer) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new SalesNotFoundException("客户订单不存在。"); + + private async Task ResolveCustomerAsync(Guid customerId, CancellationToken ct) + { + if (customerId == Guid.Empty) + throw new SalesValidationException(nameof(SaveSalesOrderRequest.CustomerId), "必须选择客户。"); + var customer = await db.Customers.SingleOrDefaultAsync(x => x.Id == customerId, ct); + if (customer is null) + throw new SalesValidationException(nameof(SaveSalesOrderRequest.CustomerId), "客户不存在。"); + if (!customer.IsActive) + throw new SalesValidationException(nameof(SaveSalesOrderRequest.CustomerId), "客户已停用,不能用于新订单。"); + return customer; + } + + private async Task> BuildLinesAsync(SaveSalesOrderRequest request, CancellationToken ct) + { + if (request.Lines is null || request.Lines.Count == 0) + throw new SalesValidationException(nameof(request.Lines), "订单至少需要一条明细。"); + + var productIds = request.Lines.Select(x => x.ProductId).Distinct().ToList(); + var products = await db.Products.AsNoTracking() + .Where(x => productIds.Contains(x.Id)).ToDictionaryAsync(x => x.Id, ct); + + var errors = new Dictionary(); + var lines = new List(request.Lines.Count); + for (var i = 0; i < request.Lines.Count; i++) + { + var r = request.Lines[i]; + if (r.ProductId == Guid.Empty || !products.TryGetValue(r.ProductId, out var product)) + { + errors[$"Lines[{i}].ProductId"] = ["产品不存在。"]; + continue; + } + var lineValid = true; + // Only Published products may be sold; Draft/Disabled/Superseded are rejected. + if (product.Status != ProductStatus.Published) + { + errors[$"Lines[{i}].ProductId"] = [$"产品 {product.InternalSku} 未发布(当前状态 {product.Status}),不能加入订单。"]; + lineValid = false; + } + if (r.Quantity <= 0) { errors[$"Lines[{i}].Quantity"] = ["数量必须大于 0。"]; lineValid = false; } + if (r.UnitPrice < 0) { errors[$"Lines[{i}].UnitPrice"] = ["单价不能小于 0。"]; lineValid = false; } + if (r.PackingRate is <= 0) { errors[$"Lines[{i}].PackingRate"] = ["装箱率必须大于 0。"]; lineValid = false; } + if (!lineValid) continue; + + var line = new SalesOrderLine + { + LineNumber = i + 1, + ProductId = product.Id, + ProductInternalSku = product.InternalSku, + ProductNameZh = product.NameZh, + ProductNameEn = product.NameEn, + ProductHsCode = product.HsCode, + CustomerSku = TrimOrNull(r.CustomerSku), + CustomerProductNameOverride = TrimOrNull(r.CustomerProductNameOverride), + Quantity = r.Quantity, + Unit = string.IsNullOrWhiteSpace(r.Unit) ? product.Unit : r.Unit.Trim(), + PackingRate = r.PackingRate ?? product.PackingRate, + UnitPrice = r.UnitPrice, + RequiredDeliveryDate = r.RequiredDeliveryDate ?? request.RequiredDeliveryDate, + CustomerRemark = TrimOrNull(r.CustomerRemark), + Remark = TrimOrNull(r.Remark), + }; + line.RecalculateAmount(); + lines.Add(line); + } + + if (errors.Count > 0) throw new SalesValidationException(errors); + return lines; + } + + private async Task ResolveOrderNumberAsync(string? requested, Guid? excludeId, CancellationToken ct) + { + var number = TrimOrNull(requested); + number ??= $"SO-{DateTime.UtcNow:yyyyMMdd}-{Guid.NewGuid().ToString("N")[..8].ToUpperInvariant()}"; + var exists = await db.SalesOrders.AnyAsync( + x => x.OrderNumber == number && (excludeId == null || x.Id != excludeId.Value), ct); + if (exists) throw new SalesValidationException(nameof(SaveSalesOrderRequest.OrderNumber), $"订单号 {number} 已存在。"); + return number; + } + + private async Task EnsureCustomerCodeAvailableAsync(string? code, Guid? excludeId, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(code)) return; + var exists = await db.Customers.AnyAsync( + x => x.Code == code.Trim() && (excludeId == null || x.Id != excludeId.Value), ct); + if (exists) throw new SalesValidationException(nameof(SaveCustomerRequest.Code), $"客户编码 {code.Trim()} 已存在。"); + } + + private static void ApplyCustomer(Customer c, SaveCustomerRequest r) + { + if (string.IsNullOrWhiteSpace(r.Name)) + throw new SalesValidationException(nameof(r.Name), "客户名称不能为空。"); + c.Code = TrimOrNull(r.Code); + c.Name = r.Name.Trim(); + c.NameEn = TrimOrNull(r.NameEn); + c.Country = TrimOrNull(r.Country); + c.Address = TrimOrNull(r.Address); + c.ContactName = TrimOrNull(r.ContactName); + c.ContactEmail = TrimOrNull(r.ContactEmail); + c.ContactPhone = TrimOrNull(r.ContactPhone); + c.PaymentTerms = TrimOrNull(r.PaymentTerms); + c.DefaultCurrency = NormalizeCurrency(r.DefaultCurrency); + c.TradeTerm = TrimOrNull(r.TradeTerm); + c.Remark = TrimOrNull(r.Remark); + c.IsActive = r.IsActive; + } + + private static void ApplyOrder(SalesOrder o, SaveSalesOrderRequest r, Customer customer) + { + if (string.IsNullOrWhiteSpace(r.CustomerPoNumber)) + throw new SalesValidationException(nameof(r.CustomerPoNumber), "客户 PO 号不能为空。"); + o.CustomerId = customer.Id; + o.CustomerName = customer.Name; + o.CustomerPoNumber = r.CustomerPoNumber.Trim(); + o.OrderDate = r.OrderDate ?? DateOnly.FromDateTime(DateTime.UtcNow); + o.RequiredDeliveryDate = r.RequiredDeliveryDate; + o.Currency = NormalizeCurrency(r.Currency) ?? customer.DefaultCurrency ?? "USD"; + o.TransportMode = TrimOrNull(r.TransportMode); + o.LoadingPort = TrimOrNull(r.LoadingPort); + o.DestinationPort = TrimOrNull(r.DestinationPort); + o.DestinationCountry = TrimOrNull(r.DestinationCountry) ?? customer.Country; + o.TradeTerm = TrimOrNull(r.TradeTerm) ?? customer.TradeTerm; + o.PaymentTerms = TrimOrNull(r.PaymentTerms) ?? customer.PaymentTerms; + o.ShippingNote = TrimOrNull(r.ShippingNote); + o.PoAttachmentReference = TrimOrNull(r.PoAttachmentReference); + o.PoAttachmentFileName = TrimOrNull(r.PoAttachmentFileName); + o.Remark = TrimOrNull(r.Remark); + } + + private static string? NormalizeCurrency(string? value) + { + var v = TrimOrNull(value); + if (v is null) return null; + if (v.Length != 3) throw new SalesValidationException("Currency", "币种必须为 3 位代码(如 USD、CNY)。"); + return v.ToUpperInvariant(); + } + + private static string? TrimOrNull(string? v) => string.IsNullOrWhiteSpace(v) ? null : v.Trim(); + + // ---------- Workbench summary (computed, never persisted) ---------- + + private sealed record TaskProgress(Guid Id, Guid SalesOrderId, Guid SalesOrderLineId, decimal Quantity); + + private sealed record NoticeProgress( + Guid Id, Guid SalesOrderId, Guid? SupplierId, string SupplierName, string Currency, + SupplierInvoiceNoticeStatus Status, decimal TotalAmountIncludingTax); + + private sealed record InvoiceProgress( + Guid NoticeId, SupplierInvoiceStatus Status, decimal AmountIncludingTax); + + private async Task ToDtoAsync(SalesOrder order, CancellationToken ct) + { + var summaries = await ComputeSummariesAsync([order], ct); + return ToDto(order, summaries[order.Id]); + } + + private async Task> ComputeSummariesAsync( + IReadOnlyList orders, CancellationToken ct) + { + if (orders.Count == 0) + return new Dictionary(); + + var orderIds = orders.Select(x => x.Id).ToList(); + + // Cancelled purchase tasks no longer represent purchasing work. + var tasks = await db.PurchaseTasks.AsNoTracking() + .Where(x => orderIds.Contains(x.SalesOrderId) && x.Status != PurchaseTaskStatus.Cancelled) + .Select(x => new TaskProgress(x.Id, x.SalesOrderId, x.SalesOrderLineId, x.Quantity)) + .ToListAsync(ct); + + var taskIds = tasks.Select(x => x.Id).ToList(); + var arrivedByTask = taskIds.Count == 0 + ? new Dictionary() + : (await db.PurchaseArrivals.AsNoTracking() + .Where(x => taskIds.Contains(x.PurchaseTaskId)) + .Select(x => new { x.PurchaseTaskId, x.Quantity }) + .ToListAsync(ct)) + .GroupBy(x => x.PurchaseTaskId) + .ToDictionary(g => g.Key, g => g.Sum(x => x.Quantity)); + + // Same convention as ShippingService's over-shipment guard: lines of + // cancelled batches do not count as shipped, all others do. + var shippedByLine = (await db.ShipmentLines.AsNoTracking() + .Where(x => orderIds.Contains(x.SalesOrderId) + && x.ShippingBatch!.Status != ShippingBatchStatus.Cancelled) + .Select(x => new { x.SalesOrderId, x.SalesOrderLineId, x.Quantity }) + .ToListAsync(ct)) + .GroupBy(x => (x.SalesOrderId, x.SalesOrderLineId)) + .ToDictionary(g => g.Key, g => g.Sum(x => x.Quantity)); + + // Billing is derived, never stored on the order: non-voided notices + // linked to the order, grouped by supplier below, plus their + // non-voided (active) invoices. + var noticeRows = await db.SupplierInvoiceNotices.AsNoTracking() + .Where(x => x.SalesOrderId != null && orderIds.Contains(x.SalesOrderId.Value) + && x.Status != SupplierInvoiceNoticeStatus.Voided) + .Select(x => new { x.Id, SalesOrderId = x.SalesOrderId!.Value, x.SupplierId, x.SupplierName, x.Currency, x.Status }) + .ToListAsync(ct); + var noticeIds = noticeRows.Select(x => x.Id).ToList(); + var noticeTotals = noticeIds.Count == 0 + ? new Dictionary() + : (await db.SupplierInvoiceNoticeLines.AsNoTracking() + .Where(x => noticeIds.Contains(x.SupplierInvoiceNoticeId)) + .Select(x => new { x.SupplierInvoiceNoticeId, x.Quantity, x.UnitPrice, x.TaxIncluded, x.TaxRate }) + .ToListAsync(ct)) + .GroupBy(x => x.SupplierInvoiceNoticeId) + .ToDictionary(g => g.Key, g => g.Sum(x => NoticeLineAmountIncludingTax(x.Quantity, x.UnitPrice, x.TaxIncluded, x.TaxRate))); + var notices = noticeRows.Select(x => new NoticeProgress( + x.Id, x.SalesOrderId, x.SupplierId, x.SupplierName, x.Currency, x.Status, + noticeTotals.TryGetValue(x.Id, out var total) ? total : 0m)).ToList(); + var invoices = noticeIds.Count == 0 + ? new List() + : await db.SupplierInvoices.AsNoTracking() + .Where(x => noticeIds.Contains(x.SupplierInvoiceNoticeId) && x.Status != SupplierInvoiceStatus.Voided) + .Select(x => new InvoiceProgress(x.SupplierInvoiceNoticeId, x.Status, x.AmountIncludingTax)) + .ToListAsync(ct); + + return orders.ToDictionary( + x => x.Id, + x => ComputeSummary(x, tasks.Where(t => t.SalesOrderId == x.Id).ToList(), arrivedByTask, shippedByLine, + notices.Where(n => n.SalesOrderId == x.Id).ToList(), invoices)); + } + + private static SalesOrderWorkbenchSummaryDto ComputeSummary( + SalesOrder order, + IReadOnlyList tasks, + IReadOnlyDictionary arrivedByTask, + IReadOnlyDictionary<(Guid SalesOrderId, Guid SalesOrderLineId), decimal> shippedByLine, + IReadOnlyList notices, + IReadOnlyList allInvoices) + { + var lines = order.Lines.OrderBy(x => x.LineNumber).ToList(); + var orderedQuantity = lines.Sum(x => x.Quantity); + + decimal Arrived(TaskProgress t) => arrivedByTask.TryGetValue(t.Id, out var q) ? q : 0m; + bool TaskComplete(TaskProgress t) => t.Quantity > 0 && Arrived(t) >= t.Quantity; + + var tasksByLine = tasks.GroupBy(x => x.SalesOrderLineId) + .ToDictionary(g => g.Key, g => g.ToList()); + var purchaseCompletedLines = lines.Count(line => + tasksByLine.TryGetValue(line.Id, out var lineTasks) + && lineTasks.Count > 0 + && lineTasks.All(TaskComplete)); + var isPurchaseComplete = lines.Count > 0 && purchaseCompletedLines == lines.Count; + + var purchaseTaskQuantity = tasks.Sum(x => x.Quantity); + var arrivedQuantity = tasks.Sum(Arrived); + var purchasePercent = purchaseTaskQuantity > 0 + ? Math.Round(tasks.Sum(t => Math.Min(Arrived(t), t.Quantity)) / purchaseTaskQuantity * 100m, 2) + : 0m; + + decimal shippedRaw = 0m, shippedCapped = 0m, remaining = 0m; + foreach (var line in lines) + { + var shipped = shippedByLine.TryGetValue((order.Id, line.Id), out var q) ? q : 0m; + shippedRaw += shipped; + shippedCapped += Math.Min(shipped, line.Quantity); + remaining += Math.Max(line.Quantity - shipped, 0m); + } + + var isFullyShipped = lines.Count > 0 && orderedQuantity > 0 && remaining == 0m; + var shipmentPercent = orderedQuantity > 0 + ? Math.Round(shippedCapped / orderedQuantity * 100m, 2) + : 0m; + var isReadyToShip = order.Status == SalesOrderStatus.Confirmed && isPurchaseComplete && !isFullyShipped; + + var workbenchStatus = + order.Status == SalesOrderStatus.Cancelled ? "Cancelled" : + order.Status == SalesOrderStatus.Draft ? "Draft" : + isFullyShipped ? "Completed" : + shippedRaw > 0 ? "PartiallyShipped" : + isPurchaseComplete ? "ReadyToShip" : + tasks.Count == 0 ? "PendingPurchase" : + "PurchaseInProgress"; + + var supplierBillings = ComputeSupplierBillings(notices, allInvoices); + var noticeIds = notices.Select(x => x.Id).ToHashSet(); + var orderInvoices = allInvoices.Where(x => noticeIds.Contains(x.NoticeId)).ToList(); + var completedNotices = notices.Count(x => IsNoticeBillingComplete(x, allInvoices)); + var billingNoticeAmount = notices.Sum(x => x.TotalAmountIncludingTax); + var billingInvoicedAmount = orderInvoices.Sum(x => x.AmountIncludingTax); + var billingCompletedAmount = orderInvoices + .Where(x => x.Status == SupplierInvoiceStatus.Completed).Sum(x => x.AmountIncludingTax); + var isBillingComplete = notices.Count > 0 && completedNotices == notices.Count; + var billingStatus = isBillingComplete ? "Completed" + : orderInvoices.Count > 0 || completedNotices > 0 ? "PartiallyCompleted" + : "Pending"; + var billingPercent = billingNoticeAmount > 0 + ? Math.Round(billingCompletedAmount / billingNoticeAmount * 100m, 2) + : 0m; + + return new SalesOrderWorkbenchSummaryDto( + workbenchStatus, + lines.Count, + lines.Count(line => tasksByLine.ContainsKey(line.Id)), + purchaseCompletedLines, + tasks.Count, + tasks.Count(TaskComplete), + orderedQuantity, + purchaseTaskQuantity, + arrivedQuantity, + shippedRaw, + remaining, + purchasePercent, + shipmentPercent, + isPurchaseComplete, + isReadyToShip, + isFullyShipped, + billingStatus, + supplierBillings.Count, + notices.Count, + completedNotices, + orderInvoices.Count, + orderInvoices.Count(x => x.Status == SupplierInvoiceStatus.Completed), + billingNoticeAmount, + billingInvoicedAmount, + billingCompletedAmount, + Math.Max(billingNoticeAmount - billingInvoicedAmount, 0m), + billingPercent, + isBillingComplete, + supplierBillings); + } + + // Same tax-inclusive amount as SupplierInvoiceNoticeLine.AmountIncludingTax. + private static decimal NoticeLineAmountIncludingTax(decimal quantity, decimal unitPrice, bool taxIncluded, decimal taxRate) + => taxIncluded + ? decimal.Round(quantity * unitPrice, 2, MidpointRounding.AwayFromZero) + : decimal.Round(quantity * decimal.Round(unitPrice * (1 + taxRate / 100m), 4, MidpointRounding.AwayFromZero), + 2, MidpointRounding.AwayFromZero); + + private static bool IsNoticeBillingComplete(NoticeProgress notice, IReadOnlyList allInvoices) + { + if (notice.Status != SupplierInvoiceNoticeStatus.Completed || notice.TotalAmountIncludingTax <= 0) + return false; + var invoices = allInvoices.Where(x => x.NoticeId == notice.Id).ToList(); + return invoices.Count > 0 + && invoices.All(x => x.Status == SupplierInvoiceStatus.Completed) + && invoices.Sum(x => x.AmountIncludingTax) >= notice.TotalAmountIncludingTax - 0.01m; + } + + private static IReadOnlyList ComputeSupplierBillings( + IReadOnlyList notices, IReadOnlyList allInvoices) + => notices + .GroupBy(x => (x.SupplierId, x.SupplierName, x.Currency)) + .OrderBy(g => g.Key.SupplierName, StringComparer.OrdinalIgnoreCase) + .ThenBy(g => g.Key.Currency, StringComparer.OrdinalIgnoreCase) + .Select(g => + { + var groupInvoices = allInvoices.Where(x => g.Any(n => n.Id == x.NoticeId)).ToList(); + var noticeAmount = g.Sum(x => x.TotalAmountIncludingTax); + var invoiced = groupInvoices.Sum(x => x.AmountIncludingTax); + var completedAmount = groupInvoices + .Where(x => x.Status == SupplierInvoiceStatus.Completed).Sum(x => x.AmountIncludingTax); + var completedNotices = g.Count(x => IsNoticeBillingComplete(x, allInvoices)); + var isComplete = completedNotices == g.Count(); + return new SalesOrderSupplierBillingSummaryDto( + g.Key.SupplierId, g.Key.SupplierName, g.Key.Currency, + isComplete ? "Completed" : groupInvoices.Count > 0 || completedNotices > 0 ? "PartiallyCompleted" : "Pending", + g.Count(), completedNotices, + groupInvoices.Count, + groupInvoices.Count(x => x.Status == SupplierInvoiceStatus.Completed), + noticeAmount, invoiced, completedAmount, + Math.Max(noticeAmount - invoiced, 0m), + noticeAmount > 0 ? Math.Round(completedAmount / noticeAmount * 100m, 2) : 0m, + isComplete); + }).ToList(); + + private static CustomerDto ToDto(Customer c) => new( + c.Id, c.Code, c.Name, c.NameEn, c.Country, c.Address, c.ContactName, c.ContactEmail, + c.ContactPhone, c.PaymentTerms, c.DefaultCurrency, c.TradeTerm, c.Remark, c.IsActive, + c.CreatedAt, c.UpdatedAt); + + private static SalesOrderLineDto ToDto(SalesOrderLine l) => new( + l.Id, l.SalesOrderId, l.LineNumber, l.ProductId, l.ProductInternalSku, l.ProductNameZh, + l.ProductNameEn, l.ProductHsCode, l.CustomerSku, l.CustomerProductNameOverride, + l.EffectiveCustomerProductName, l.Quantity, l.Unit, l.PackingRate, + l.PackingRate is > 0 ? Math.Ceiling(l.Quantity / l.PackingRate.Value) : null, + l.UnitPrice, l.Amount, l.RequiredDeliveryDate, l.CustomerRemark, l.Remark); + + private static SalesOrderDto ToDto(SalesOrder o, SalesOrderWorkbenchSummaryDto summary) => new( + o.Id, o.OrderNumber, o.CustomerId, o.CustomerName, o.CustomerPoNumber, o.OrderDate, + o.RequiredDeliveryDate, o.Currency, o.Status.ToString(), o.TransportMode, o.LoadingPort, + o.DestinationPort, o.DestinationCountry, o.TradeTerm, o.PaymentTerms, o.ShippingNote, + o.PoAttachmentReference, o.PoAttachmentFileName, o.TotalAmount, + o.Lines.Sum(x => x.Quantity), o.Remark, o.ConfirmedAt, o.ConfirmedBy, o.CancelledAt, + o.CancellationReason, o.CreatedAt, o.UpdatedAt, + o.Lines.OrderBy(x => x.LineNumber).Select(ToDto).ToList(), summary); +} diff --git a/src/Leiren.Erp.Application/Shipping/IShippingDbContext.cs b/src/Leiren.Erp.Application/Shipping/IShippingDbContext.cs new file mode 100644 index 0000000..0aa8ef5 --- /dev/null +++ b/src/Leiren.Erp.Application/Shipping/IShippingDbContext.cs @@ -0,0 +1,23 @@ +using Leiren.Erp.Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Shipping; + +/// +/// EF Core boundary for the Shipping module; implemented by Infrastructure. +/// Sales/Purchasing sets are read here only to validate shipment lines against +/// a confirmed sales order and its purchase completion (arrivals). +/// +public interface IShippingDbContext +{ + DbSet SalesOrders { get; } + DbSet SalesOrderLines { get; } + DbSet Products { get; } + DbSet PurchaseTasks { get; } + DbSet PurchaseArrivals { get; } + DbSet ShippingBatches { get; } + DbSet ShippingContainers { get; } + DbSet ShipmentLines { get; } + + Task SaveChangesAsync(CancellationToken cancellationToken = default); +} diff --git a/src/Leiren.Erp.Application/Shipping/ShippingExceptions.cs b/src/Leiren.Erp.Application/Shipping/ShippingExceptions.cs new file mode 100644 index 0000000..f12a242 --- /dev/null +++ b/src/Leiren.Erp.Application/Shipping/ShippingExceptions.cs @@ -0,0 +1,16 @@ +namespace Leiren.Erp.Application.Shipping; + +public sealed class ShippingNotFoundException(string message) : Exception(message); + +public sealed class ShippingConflictException(string message) : Exception(message); + +public sealed class ShippingValidationException(IReadOnlyDictionary errors) + : Exception("出货资料校验失败。") +{ + public IReadOnlyDictionary Errors { get; } = errors; + + public ShippingValidationException(string field, string message) + : this(new Dictionary { [field] = [message] }) + { + } +} diff --git a/src/Leiren.Erp.Application/Shipping/ShippingService.cs b/src/Leiren.Erp.Application/Shipping/ShippingService.cs new file mode 100644 index 0000000..8349575 --- /dev/null +++ b/src/Leiren.Erp.Application/Shipping/ShippingService.cs @@ -0,0 +1,630 @@ +using Leiren.Erp.Contracts; +using Leiren.Erp.Domain.Entities; +using Leiren.Erp.Domain.Enums; +using Microsoft.EntityFrameworkCore; + +namespace Leiren.Erp.Application.Shipping; + +public sealed class ShippingService(IShippingDbContext db) +{ + // ---------- Batches ---------- + + public async Task> ListBatchesAsync( + Guid? salesOrderId, string? status, string? search, + int page, int pageSize, CancellationToken ct = default) + { + var query = db.ShippingBatches.AsNoTracking() + .Include(x => x.Lines).Include(x => x.Containers).AsQueryable(); + if (salesOrderId is not null) + query = query.Where(x => x.SalesOrderId == salesOrderId.Value || x.Lines.Any(l => l.SalesOrderId == salesOrderId.Value)); + if (!string.IsNullOrWhiteSpace(status)) + { + if (!Enum.TryParse(status, ignoreCase: true, out var parsed)) + throw new ShippingValidationException(nameof(status), "出货批次状态无效。"); + query = query.Where(x => x.Status == parsed); + } + + if (!string.IsNullOrWhiteSpace(search)) + { + var term = search.Trim(); + query = query.Where(x => + x.BatchNo.Contains(term) || x.SalesOrderNo.Contains(term) || + x.CustomerName.Contains(term) || + (x.CustomerPoNo != null && x.CustomerPoNo.Contains(term)) || + (x.BillOfLadingNo != null && x.BillOfLadingNo.Contains(term)) || + (x.VesselName != null && x.VesselName.Contains(term))); + } + + page = Math.Max(page, 1); + pageSize = Math.Clamp(pageSize, 1, 200); + var items = await query.OrderByDescending(x => x.Id) + .Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(ct); + return items.Select(x => new ShippingBatchListItemDto( + x.Id, x.BatchNo, x.SalesOrderId, x.SalesOrderNo, x.CustomerPoNo, x.CustomerName, + x.Status.ToString(), x.Etd, x.Eta, x.VesselName, x.BillOfLadingNo, x.DestinationPort, + x.Lines.Count, x.Containers.Count, x.TotalCartonCount, x.TotalCbm, x.TotalAmount, + x.Currency, x.UpdatedAt, x.CustomerId)).ToList(); + } + + public async Task GetBatchAsync(Guid id, CancellationToken ct = default) + => await ToDtoAsync(await LoadBatchAsync(id, ct), ct); + + /// Confirmed orders whose arrived finished goods are not fully in shipping batches yet. + public async Task> ListReadyOrdersAsync(CancellationToken ct = default) + { + var orders = await db.SalesOrders.AsNoTracking() + .Include(x => x.Lines).ThenInclude(x => x.Product) + .Where(x => x.Status == SalesOrderStatus.Confirmed) + .ToListAsync(ct); + var lineIds = orders.SelectMany(x => x.Lines).Select(x => x.Id).ToList(); + + var tasks = await db.PurchaseTasks.AsNoTracking() + .Where(x => lineIds.Contains(x.SalesOrderLineId) && x.Status != PurchaseTaskStatus.Cancelled) + .Select(x => new { x.SalesOrderLineId, x.Quantity, x.ArrivedQuantity }) + .ToListAsync(ct); + var arrivals = await db.PurchaseArrivals.AsNoTracking() + .Where(x => x.CartonLength != null && lineIds.Contains(x.PurchaseTask!.SalesOrderLineId)) + .Select(x => new + { + x.Id, x.PurchaseTask!.SalesOrderLineId, x.ArrivedDate, x.CreatedAt, x.PackingRate, + x.CartonLength, x.CartonWidth, x.CartonHeight, x.CartonGrossWeight, x.CartonNetWeight + }) + .ToListAsync(ct); + var shipped = await db.ShipmentLines.AsNoTracking() + .Where(x => lineIds.Contains(x.SalesOrderLineId) && x.ShippingBatch!.Status != ShippingBatchStatus.Cancelled) + .Select(x => new { x.SalesOrderLineId, x.Quantity }) + .ToListAsync(ct); + + var result = new List(); + foreach (var order in orders.OrderByDescending(x => x.OrderDate).ThenBy(x => x.OrderNumber, StringComparer.Ordinal)) + { + var lines = new List(); + foreach (var line in order.Lines.OrderBy(x => x.LineNumber)) + { + var lineTasks = tasks.Where(x => x.SalesOrderLineId == line.Id).ToList(); + if (lineTasks.Count == 0) continue; + var arrived = FinishedArrived(lineTasks.Select(x => (x.Quantity, x.ArrivedQuantity)), line.Quantity); + var shippedQuantity = shipped.Where(x => x.SalesOrderLineId == line.Id).Sum(x => x.Quantity); + var available = arrived - shippedQuantity; + if (available <= 0) continue; + + var arrival = arrivals.Where(x => x.SalesOrderLineId == line.Id) + .OrderByDescending(x => x.ArrivedDate).ThenByDescending(x => x.CreatedAt) + .FirstOrDefault(); + var product = line.Product; + lines.Add(new ShippingReadyLineDto( + line.Id, line.ProductInternalSku, line.ProductNameZh, line.Unit, + line.Quantity, arrived, shippedQuantity, available, arrival?.Id, + arrival?.PackingRate ?? line.PackingRate ?? product?.PackingRate, + arrival?.CartonLength ?? product?.CartonLength, + arrival?.CartonWidth ?? product?.CartonWidth, + arrival?.CartonHeight ?? product?.CartonHeight, + arrival?.CartonGrossWeight ?? product?.CartonGrossWeight, + arrival?.CartonNetWeight ?? product?.CartonNetWeight)); + } + if (lines.Count == 0) continue; + result.Add(new ShippingReadyOrderDto( + order.Id, order.OrderNumber, order.CustomerId, order.CustomerPoNumber, order.CustomerName, order.Currency, + order.OrderDate, order.RequiredDeliveryDate, order.LoadingPort, order.DestinationPort, order.DestinationCountry, + order.TransportMode, order.TradeTerm, lines)); + } + return result; + } + + public async Task CreateBatchAsync(CreateShippingBatchRequest request, CancellationToken ct = default) + { + var order = await db.SalesOrders.AsNoTracking() + .SingleOrDefaultAsync(x => x.Id == request.SalesOrderId, ct) + ?? throw new ShippingNotFoundException("销售订单不存在。"); + if (order.Status != SalesOrderStatus.Confirmed) + throw new ShippingConflictException("只有已确认的销售订单可以建立出货批次。"); + + var batchNo = string.IsNullOrWhiteSpace(request.BatchNo) + ? $"SH-{DateTimeOffset.UtcNow:yyyyMMddHHmmss}-{Guid.NewGuid().ToString("N")[..4].ToUpperInvariant()}" + : request.BatchNo.Trim(); + if (await db.ShippingBatches.AnyAsync(x => x.BatchNo == batchNo, ct)) + throw new ShippingConflictException($"出货批次号 {batchNo} 已存在。"); + + var batch = new ShippingBatch + { + BatchNo = batchNo, + SalesOrderId = order.Id, + CustomerId = order.CustomerId, + SalesOrderNo = order.OrderNumber, + CustomerName = order.CustomerName, + CustomerPoNo = order.CustomerPoNumber, + Currency = order.Currency, + LoadingPort = TrimOrNull(request.LoadingPort) ?? TrimOrNull(order.LoadingPort), + DestinationPort = TrimOrNull(request.DestinationPort) ?? TrimOrNull(order.DestinationPort), + DestinationCountry = TrimOrNull(request.DestinationCountry) ?? TrimOrNull(order.DestinationCountry), + TransportMode = TrimOrNull(request.TransportMode) ?? TrimOrNull(order.TransportMode), + TradeTerm = TrimOrNull(request.TradeTerm) ?? TrimOrNull(order.TradeTerm) + }; + ApplyHeader(batch, request.ShipmentDate, request.CutoffDate, request.Etd, request.Eta, + request.VesselName, request.VoyageNo, request.BillOfLadingNo, + request.LoadingPort ?? order.LoadingPort, request.DestinationPort ?? order.DestinationPort, + request.DestinationCountry ?? order.DestinationCountry, + request.TransportMode ?? order.TransportMode, request.TradeTerm ?? order.TradeTerm, + request.FreightForwarder, request.Remark); + ValidateDates(batch); + + db.ShippingBatches.Add(batch); + + if (request.Containers is not null) + { + foreach (var containerRequest in request.Containers) + { + var container = new ShippingContainer { ShippingBatchId = batch.Id }; + ApplyContainer(batch, container, containerRequest); + batch.Containers.Add(container); + db.ShippingContainers.Add(container); + } + } + + if (request.Lines is not null) + { + foreach (var lineRequest in request.Lines) + { + var line = new ShipmentLine { ShippingBatchId = batch.Id }; + await ApplyLineAsync(batch, line, lineRequest, ct); + batch.Lines.Add(line); + db.ShipmentLines.Add(line); + } + } + + await RefreshOrderReferencesAsync(batch, ct); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(await LoadBatchAsync(batch.Id, ct), ct); + } + + public async Task UpdateBatchAsync( + Guid id, UpdateShippingBatchRequest request, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(id, ct); + EnsureDraft(batch); + + if (!string.IsNullOrWhiteSpace(request.BatchNo)) + { + var batchNo = request.BatchNo.Trim(); + if (!string.Equals(batchNo, batch.BatchNo, StringComparison.Ordinal) && + await db.ShippingBatches.AnyAsync(x => x.Id != id && x.BatchNo == batchNo, ct)) + throw new ShippingConflictException($"出货批次号 {batchNo} 已存在。"); + batch.BatchNo = batchNo; + } + + ApplyHeader(batch, request.ShipmentDate, request.CutoffDate, request.Etd, request.Eta, + request.VesselName, request.VoyageNo, request.BillOfLadingNo, + request.LoadingPort, request.DestinationPort, request.DestinationCountry, + request.TransportMode, request.TradeTerm, request.FreightForwarder, request.Remark); + ValidateDates(batch); + batch.Touch(); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(batch, ct); + } + + public async Task ConfirmBatchAsync(Guid id, string? confirmedBy, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(id, ct); + EnsureDraft(batch); + if (batch.Lines.Count == 0) + throw new ShippingValidationException(nameof(batch.Lines), "出货批次至少需要一条出货明细。"); + if (string.IsNullOrWhiteSpace(batch.LoadingPort)) + throw new ShippingValidationException(nameof(batch.LoadingPort), "确认出货前必须填写起运港。"); + if (string.IsNullOrWhiteSpace(batch.DestinationPort)) + throw new ShippingValidationException(nameof(batch.DestinationPort), "确认出货前必须填写目的港。"); + + foreach (var line in batch.Lines) + { + if (line.CartonCount is null or <= 0 || line.CartonLength is null or <= 0 || + line.CartonWidth is null or <= 0 || line.CartonHeight is null or <= 0 || + line.CartonGrossWeight is null or <= 0 || line.CartonNetWeight is null or <= 0) + throw new ShippingValidationException(nameof(line.CartonCount), + $"出货明细「{line.InternalSku}」的实际包装快照不完整(箱数、单箱尺寸、单箱毛净重必填)。"); + await ValidateCumulativeAsync(batch, line, line.Quantity, ct); + } + + try { batch.Confirm(confirmedBy); } + catch (InvalidOperationException ex) { throw new ShippingConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + return await ToDtoAsync(batch, ct); + } + + public async Task CancelBatchAsync(Guid id, string? reason, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(id, ct); + try { batch.Cancel(reason); } + catch (InvalidOperationException ex) { throw new ShippingConflictException(ex.Message); } + await db.SaveChangesAsync(ct); + } + + // ---------- Containers ---------- + + public async Task AddContainerAsync( + Guid batchId, SaveShippingContainerRequest request, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(batchId, ct); + EnsureDraft(batch); + var container = new ShippingContainer { ShippingBatchId = batch.Id }; + ApplyContainer(batch, container, request); + batch.Containers.Add(container); + db.ShippingContainers.Add(container); + batch.Touch(); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(await LoadBatchAsync(batch.Id, ct), ct); + } + + public async Task UpdateContainerAsync( + Guid batchId, Guid containerId, SaveShippingContainerRequest request, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(batchId, ct); + EnsureDraft(batch); + var container = batch.Containers.SingleOrDefault(x => x.Id == containerId) + ?? throw new ShippingNotFoundException("集装箱不存在。"); + ApplyContainer(batch, container, request, excluding: container); + container.Touch(); + batch.Touch(); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(batch, ct); + } + + public async Task RemoveContainerAsync( + Guid batchId, Guid containerId, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(batchId, ct); + EnsureDraft(batch); + var container = batch.Containers.SingleOrDefault(x => x.Id == containerId) + ?? throw new ShippingNotFoundException("集装箱不存在。"); + foreach (var line in batch.Lines.Where(x => x.ShippingContainerId == containerId)) + { + line.ShippingContainerId = null; + line.ShippingContainer = null; + line.Touch(); + } + + batch.Containers.Remove(container); + db.ShippingContainers.Remove(container); + batch.Touch(); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(batch, ct); + } + + // ---------- Shipment lines ---------- + + public async Task AddLineAsync( + Guid batchId, SaveShipmentLineRequest request, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(batchId, ct); + EnsureDraft(batch); + var line = new ShipmentLine { ShippingBatchId = batch.Id }; + await ApplyLineAsync(batch, line, request, ct); + batch.Lines.Add(line); + db.ShipmentLines.Add(line); + batch.Touch(); + await RefreshOrderReferencesAsync(batch, ct); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(await LoadBatchAsync(batch.Id, ct), ct); + } + + public async Task UpdateLineAsync( + Guid batchId, Guid lineId, SaveShipmentLineRequest request, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(batchId, ct); + EnsureDraft(batch); + var line = batch.Lines.SingleOrDefault(x => x.Id == lineId) + ?? throw new ShippingNotFoundException("出货明细不存在。"); + await ApplyLineAsync(batch, line, request, ct); + line.Touch(); + batch.Touch(); + await RefreshOrderReferencesAsync(batch, ct); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(await LoadBatchAsync(batch.Id, ct), ct); + } + + public async Task RemoveLineAsync( + Guid batchId, Guid lineId, CancellationToken ct = default) + { + var batch = await LoadBatchAsync(batchId, ct); + EnsureDraft(batch); + var line = batch.Lines.SingleOrDefault(x => x.Id == lineId) + ?? throw new ShippingNotFoundException("出货明细不存在。"); + batch.Lines.Remove(line); + db.ShipmentLines.Remove(line); + batch.Touch(); + await RefreshOrderReferencesAsync(batch, ct); + await db.SaveChangesAsync(ct); + return await ToDtoAsync(batch, ct); + } + + // ---------- Helpers ---------- + + /// + /// Batch order number / PO become the list of every order its lines come + /// from (e.g. "SC-1 / SC-2"); with no lines the primary order is kept. + /// + private async Task RefreshOrderReferencesAsync(ShippingBatch batch, CancellationToken ct) + { + var orderIds = batch.Lines.Select(x => x.SalesOrderId).Append(batch.SalesOrderId).Distinct().ToList(); + var orders = await db.SalesOrders.AsNoTracking() + .Where(x => orderIds.Contains(x.Id)) + .Select(x => new { x.Id, x.OrderNumber, x.CustomerPoNumber }) + .ToListAsync(ct); + var used = batch.Lines.Count == 0 ? [batch.SalesOrderId] : batch.Lines.Select(x => x.SalesOrderId).Distinct().ToList(); + var ordered = orders.Where(x => used.Contains(x.Id)).OrderBy(x => x.OrderNumber, StringComparer.Ordinal).ToList(); + if (ordered.Count == 0) return; + batch.SalesOrderNo = string.Join(" / ", ordered.Select(x => x.OrderNumber)); + batch.CustomerPoNo = string.Join(" / ", ordered.Select(x => x.CustomerPoNumber).Where(x => !string.IsNullOrWhiteSpace(x))); + } + + private async Task ApplyLineAsync( + ShippingBatch batch, ShipmentLine line, SaveShipmentLineRequest request, CancellationToken ct) + { + var salesLine = await db.SalesOrderLines.AsNoTracking() + .Include(x => x.Product) + .Include(x => x.SalesOrder) + .SingleOrDefaultAsync(x => x.Id == request.SalesOrderLineId, ct) + ?? throw new ShippingValidationException(nameof(request.SalesOrderLineId), "订单明细不存在。"); + // One container may carry several orders of the same customer and currency. + var lineOrder = salesLine.SalesOrder!; + if (lineOrder.Status != SalesOrderStatus.Confirmed) + throw new ShippingConflictException($"订单 {lineOrder.OrderNumber} 未确认,不能出货。"); + if (lineOrder.CustomerId != batch.CustomerId) + throw new ShippingValidationException(nameof(request.SalesOrderLineId), $"订单 {lineOrder.OrderNumber} 不属于客户 {batch.CustomerName},不能拼在同一出货批次。"); + if (!string.Equals(lineOrder.Currency, batch.Currency, StringComparison.OrdinalIgnoreCase)) + throw new ShippingValidationException(nameof(request.SalesOrderLineId), $"订单 {lineOrder.OrderNumber} 的币种 {lineOrder.Currency} 与出货批次 {batch.Currency} 不同。"); + + if (request.Quantity <= 0) + throw new ShippingValidationException(nameof(request.Quantity), "出货数量必须大于 0。"); + if (request.UnitPrice is < 0) + throw new ShippingValidationException(nameof(request.UnitPrice), "出货单价不能小于 0。"); + if (request.PackingRate is <= 0) + throw new ShippingValidationException(nameof(request.PackingRate), "实际装箱率必须大于 0。"); + if (request.CartonCount is <= 0) + throw new ShippingValidationException(nameof(request.CartonCount), "实际箱数必须大于 0。"); + foreach (var (value, field) in new[] + { + (request.CartonLength, nameof(request.CartonLength)), + (request.CartonWidth, nameof(request.CartonWidth)), + (request.CartonHeight, nameof(request.CartonHeight)), + (request.CartonGrossWeight, nameof(request.CartonGrossWeight)), + (request.CartonNetWeight, nameof(request.CartonNetWeight)) + }) + { + if (value is < 0) + throw new ShippingValidationException(field, "实际包装尺寸和重量不能小于 0。"); + } + + ShippingContainer? container = null; + if (request.ShippingContainerId is { } containerId) + { + container = batch.Containers.SingleOrDefault(x => x.Id == containerId); + if (container is null && + !await db.ShippingContainers.AsNoTracking() + .AnyAsync(x => x.Id == containerId && x.ShippingBatchId == batch.Id, ct)) + throw new ShippingValidationException(nameof(request.ShippingContainerId), "集装箱不属于该出货批次。"); + } + else if (!string.IsNullOrWhiteSpace(request.ContainerNo)) + { + container = batch.Containers.SingleOrDefault(x => + string.Equals(x.ContainerNo, request.ContainerNo.Trim(), StringComparison.OrdinalIgnoreCase)) + ?? throw new ShippingValidationException(nameof(request.ContainerNo), $"集装箱 {request.ContainerNo} 不在该出货批次中。"); + } + + PurchaseTask? task = null; + if (request.PurchaseTaskId is { } taskId) + { + task = await db.PurchaseTasks.AsNoTracking().SingleOrDefaultAsync(x => x.Id == taskId, ct) + ?? throw new ShippingValidationException(nameof(request.PurchaseTaskId), "采购任务不存在。"); + if (task.SalesOrderLineId != salesLine.Id) + throw new ShippingValidationException(nameof(request.PurchaseTaskId), "采购任务不属于该订单明细。"); + if (task.Status == PurchaseTaskStatus.Cancelled) + throw new ShippingValidationException(nameof(request.PurchaseTaskId), "采购任务已取消,不能用于出货。"); + } + + PurchaseArrival? arrival = null; + if (request.PurchaseArrivalId is { } arrivalId) + { + arrival = await db.PurchaseArrivals.AsNoTracking() + .Include(x => x.PurchaseTask) + .SingleOrDefaultAsync(x => x.Id == arrivalId, ct) + ?? throw new ShippingValidationException(nameof(request.PurchaseArrivalId), "采购到货记录不存在。"); + if (arrival.PurchaseTask is null || arrival.PurchaseTask.SalesOrderLineId != salesLine.Id) + throw new ShippingValidationException(nameof(request.PurchaseArrivalId), "采购到货记录不属于该订单明细。"); + if (task is not null && task.Id != arrival.PurchaseTaskId) + throw new ShippingValidationException(nameof(request.PurchaseArrivalId), "采购到货记录与采购任务不一致。"); + task ??= arrival.PurchaseTask; + } + + await ValidateCumulativeAsync(batch, line, request.Quantity, ct, salesLine); + + var product = salesLine.Product; + line.SalesOrderId = salesLine.SalesOrderId; + line.SalesOrderLineId = salesLine.Id; + line.ShippingContainerId = container?.Id ?? request.ShippingContainerId; + line.ShippingContainer = container; + line.PurchaseTaskId = task?.Id ?? request.PurchaseTaskId; + line.PurchaseArrivalId = arrival?.Id; + line.InternalSku = salesLine.ProductInternalSku; + line.ProductNameZh = salesLine.ProductNameZh; + line.ProductNameEn = salesLine.ProductNameEn; + line.CustomerSku = salesLine.CustomerSku; + line.CustomerProductName = salesLine.EffectiveCustomerProductName; + line.HsCode = salesLine.ProductHsCode ?? product?.HsCode; + line.OrderedQuantity = salesLine.Quantity; + line.Quantity = request.Quantity; + line.Unit = salesLine.Unit; + line.UnitPrice = request.UnitPrice ?? salesLine.UnitPrice; + + // Actual packing: explicit input wins, then the linked arrival's + // actuals, then product-master defaults (frozen into this line). + line.PackingRate = request.PackingRate ?? arrival?.PackingRate ?? salesLine.PackingRate ?? product?.PackingRate; + line.CartonLength = request.CartonLength ?? arrival?.CartonLength ?? product?.CartonLength; + line.CartonWidth = request.CartonWidth ?? arrival?.CartonWidth ?? product?.CartonWidth; + line.CartonHeight = request.CartonHeight ?? arrival?.CartonHeight ?? product?.CartonHeight; + line.CartonGrossWeight = request.CartonGrossWeight ?? arrival?.CartonGrossWeight ?? product?.CartonGrossWeight; + line.CartonNetWeight = request.CartonNetWeight ?? arrival?.CartonNetWeight ?? product?.CartonNetWeight; + line.CartonCount = request.CartonCount + ?? (line.PackingRate is { } rate ? (int?)decimal.Ceiling(request.Quantity / rate) : null) + ?? (arrival is not null && arrival.Quantity == request.Quantity ? arrival.CartonCount : null); + line.Remark = TrimOrNull(request.Remark); + line.RecalculateAmount(); + line.RecalculatePackingTotals(); + } + + /// + /// Enforces ordered-quantity and purchase-completion limits for one line: + /// cumulative shipped (all non-cancelled batches, including this batch's + /// other lines) may not exceed the ordered quantity, and — when finished- + /// goods purchase tasks exist for the sales line — may not exceed their + /// cumulative arrived quantity. + /// + private async Task ValidateCumulativeAsync( + ShippingBatch batch, ShipmentLine current, decimal newQuantity, + CancellationToken ct, SalesOrderLine? knownSalesLine = null) + { + var salesLine = knownSalesLine ?? await db.SalesOrderLines.AsNoTracking() + .SingleOrDefaultAsync(x => x.Id == current.SalesOrderLineId, ct) + ?? throw new ShippingValidationException(nameof(current.SalesOrderLineId), "订单明细不存在。"); + + var shippedInOtherBatches = await db.ShipmentLines.AsNoTracking() + .Where(x => x.SalesOrderLineId == salesLine.Id && + x.ShippingBatchId != batch.Id && + x.ShippingBatch!.Status != ShippingBatchStatus.Cancelled) + .SumAsync(x => (decimal?)x.Quantity, ct) ?? 0; + var shippedInThisBatch = batch.Lines + .Where(x => x.Id != current.Id && x.SalesOrderLineId == salesLine.Id) + .Sum(x => x.Quantity); + var cumulative = shippedInOtherBatches + shippedInThisBatch + newQuantity; + if (cumulative > salesLine.Quantity) + throw new ShippingValidationException(nameof(newQuantity), + $"出货数量累计 {cumulative} 超过订单数量 {salesLine.Quantity}。"); + + var (hasTasks, arrived) = await GetFinishedArrivedAsync(salesLine.Id, salesLine.Quantity, ct); + if (hasTasks && cumulative > arrived) + throw new ShippingValidationException(nameof(newQuantity), + $"出货数量累计 {cumulative} 超过成品已到货数量 {arrived}。"); + } + + /// + /// Finished quantity arrived for a sales line: every part (purchase task) + /// is needed for one finished unit, so the least-arrived part limits it. + /// + private async Task<(bool HasTasks, decimal Arrived)> GetFinishedArrivedAsync( + Guid salesOrderLineId, decimal lineQuantity, CancellationToken ct) + { + var tasks = await db.PurchaseTasks.AsNoTracking() + .Where(x => x.SalesOrderLineId == salesOrderLineId && x.Status != PurchaseTaskStatus.Cancelled) + .Select(x => new { x.Quantity, x.ArrivedQuantity }) + .ToListAsync(ct); + return tasks.Count == 0 + ? (false, 0) + : (true, FinishedArrived(tasks.Select(x => (x.Quantity, x.ArrivedQuantity)), lineQuantity)); + } + + private static decimal FinishedArrived(IEnumerable<(decimal Quantity, decimal Arrived)> parts, decimal lineQuantity) + { + var ratio = parts.Min(x => x.Quantity <= 0 ? 0 : x.Arrived / x.Quantity); + return Math.Floor(Math.Min(ratio, 1) * lineQuantity); + } + + private static void ApplyContainer( + ShippingBatch batch, ShippingContainer container, + SaveShippingContainerRequest request, ShippingContainer? excluding = null) + { + if (string.IsNullOrWhiteSpace(request.ContainerNo)) + throw new ShippingValidationException(nameof(request.ContainerNo), "集装箱号不能为空。"); + var containerNo = request.ContainerNo.Trim(); + if (batch.Containers.Any(x => x != excluding && + string.Equals(x.ContainerNo, containerNo, StringComparison.OrdinalIgnoreCase))) + throw new ShippingConflictException($"集装箱号 {containerNo} 已在该出货批次中。"); + container.ContainerNo = containerNo; + container.ContainerType = TrimOrNull(request.ContainerType); + container.SealNo = TrimOrNull(request.SealNo); + container.Remark = TrimOrNull(request.Remark); + } + + private static void ApplyHeader( + ShippingBatch batch, DateOnly? shipmentDate, DateOnly? cutoffDate, DateOnly? etd, DateOnly? eta, + string? vesselName, string? voyageNo, string? billOfLadingNo, + string? loadingPort, string? destinationPort, string? destinationCountry, + string? transportMode, string? tradeTerm, string? freightForwarder, string? remark) + { + batch.ShipmentDate = shipmentDate; + batch.CutoffDate = cutoffDate; + batch.Etd = etd; + batch.Eta = eta; + batch.VesselName = TrimOrNull(vesselName); + batch.VoyageNo = TrimOrNull(voyageNo); + batch.BillOfLadingNo = TrimOrNull(billOfLadingNo); + batch.LoadingPort = TrimOrNull(loadingPort); + batch.DestinationPort = TrimOrNull(destinationPort); + batch.DestinationCountry = TrimOrNull(destinationCountry); + batch.TransportMode = TrimOrNull(transportMode); + batch.TradeTerm = TrimOrNull(tradeTerm); + batch.FreightForwarder = TrimOrNull(freightForwarder); + batch.Remark = TrimOrNull(remark); + } + + private static void ValidateDates(ShippingBatch batch) + { + if (batch.Eta is not null && batch.Etd is not null && batch.Eta < batch.Etd) + throw new ShippingValidationException(nameof(batch.Eta), "ETA 不能早于 ETD。"); + if (batch.CutoffDate is not null && batch.Etd is not null && batch.CutoffDate > batch.Etd) + throw new ShippingValidationException(nameof(batch.CutoffDate), "截关日期不能晚于 ETD。"); + } + + private static void EnsureDraft(ShippingBatch batch) + { + try { batch.EnsureDraft(); } + catch (InvalidOperationException ex) { throw new ShippingConflictException(ex.Message); } + } + + private async Task LoadBatchAsync(Guid id, CancellationToken ct) + => await db.ShippingBatches + .Include(x => x.Containers) + .Include(x => x.Lines) + .SingleOrDefaultAsync(x => x.Id == id, ct) + ?? throw new ShippingNotFoundException("出货批次不存在。"); + + private async Task ToDtoAsync(ShippingBatch batch, CancellationToken ct) + { + var arrivedByLine = new Dictionary(); + var otherShippedByLine = new Dictionary(); + foreach (var salesLineId in batch.Lines.Select(x => x.SalesOrderLineId).Distinct()) + { + var (_, arrived) = await GetFinishedArrivedAsync(salesLineId, batch.Lines.First(x => x.SalesOrderLineId == salesLineId).OrderedQuantity, ct); + arrivedByLine[salesLineId] = arrived; + otherShippedByLine[salesLineId] = await db.ShipmentLines.AsNoTracking() + .Where(x => x.SalesOrderLineId == salesLineId && + x.ShippingBatchId != batch.Id && + x.ShippingBatch!.Status != ShippingBatchStatus.Cancelled) + .SumAsync(x => (decimal?)x.Quantity, ct) ?? 0; + } + + return new ShippingBatchDto( + batch.Id, batch.BatchNo, batch.SalesOrderId, batch.CustomerId, batch.SalesOrderNo, + batch.CustomerName, batch.CustomerPoNo, batch.Currency, batch.Status.ToString(), + batch.ShipmentDate, batch.CutoffDate, batch.Etd, batch.Eta, batch.VesselName, + batch.VoyageNo, batch.BillOfLadingNo, batch.LoadingPort, batch.DestinationPort, + batch.DestinationCountry, batch.TransportMode, batch.TradeTerm, batch.FreightForwarder, + batch.Remark, batch.TotalQuantity, batch.TotalCartonCount, batch.TotalGrossWeight, + batch.TotalNetWeight, batch.TotalCbm, batch.TotalAmount, batch.ConfirmedAt, + batch.ConfirmedBy, batch.CancelledAt, batch.CancellationReason, + batch.CreatedAt, batch.UpdatedAt, + batch.Containers.OrderBy(x => x.CreatedAt).Select(x => new ShippingContainerDto( + x.Id, x.ShippingBatchId, x.ContainerNo, x.ContainerType, x.SealNo, x.Remark, + x.CreatedAt, x.UpdatedAt)).ToList(), + batch.Lines.OrderBy(x => x.CreatedAt).Select(x => new ShipmentLineDto( + x.Id, x.ShippingBatchId, x.ShippingContainerId, x.SalesOrderId, x.SalesOrderLineId, + x.PurchaseTaskId, x.PurchaseArrivalId, x.InternalSku, x.ProductNameZh, x.ProductNameEn, + x.CustomerSku, x.CustomerProductName, x.HsCode, x.OrderedQuantity, x.Quantity, x.Unit, + x.UnitPrice, x.Amount, + arrivedByLine.GetValueOrDefault(x.SalesOrderLineId), + otherShippedByLine.GetValueOrDefault(x.SalesOrderLineId), + x.PackingRate, x.CartonCount, x.CartonLength, x.CartonWidth, x.CartonHeight, + x.CartonGrossWeight, x.CartonNetWeight, x.TotalGrossWeight, x.TotalNetWeight, + x.TotalCbm, x.Remark, x.CreatedAt, x.UpdatedAt)).ToList()); + } + + private static string? TrimOrNull(string? value) + => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); +} diff --git a/src/Leiren.Erp.Backup/Leiren.Erp.Backup.csproj b/src/Leiren.Erp.Backup/Leiren.Erp.Backup.csproj new file mode 100644 index 0000000..8bd9d69 --- /dev/null +++ b/src/Leiren.Erp.Backup/Leiren.Erp.Backup.csproj @@ -0,0 +1,14 @@ + + + + + + + + Exe + net11.0 + enable + enable + + + diff --git a/src/Leiren.Erp.Backup/Program.cs b/src/Leiren.Erp.Backup/Program.cs new file mode 100644 index 0000000..5f89cf5 --- /dev/null +++ b/src/Leiren.Erp.Backup/Program.cs @@ -0,0 +1,262 @@ +using System.Text.Json; +using Leiren.Erp.Infrastructure.Backup; + +internal static class Program +{ + private const int ExitOk = 0; + private const int ExitFailure = 1; + private const int ExitUsage = 2; + + private static async Task Main(string[] args) + { + if (args.Length == 0 || IsHelp(args[0])) + { + PrintUsage(); + return args.Length == 0 ? ExitUsage : ExitOk; + } + + try + { + return args[0].ToLowerInvariant() switch + { + "backup" => await RunBackupAsync(args[1..]).ConfigureAwait(false), + "verify" => await RunVerifyAsync(args[1..]).ConfigureAwait(false), + _ => UnknownCommand(args[0]), + }; + } + catch (BackupException ex) + { + Console.Error.WriteLine($"备份失败:{ex.Message}"); + return ExitFailure; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException) + { + Console.Error.WriteLine($"备份失败:{ex.Message}"); + return ExitFailure; + } + } + + private static async Task RunBackupAsync(string[] args) + { + var parsed = CliArgs.Parse(args); + var options = await LoadOptionsAsync(parsed).ConfigureAwait(false); + ApplyOverrides(options, parsed); + var dryRun = parsed.HasFlag("--dry-run"); + + // The database connection string may be injected by the scheduler via + // environment instead of a config file or a shell-visible argument. + if (options.IncludeDatabase && string.IsNullOrWhiteSpace(options.DatabaseConnectionString)) + { + options.DatabaseConnectionString = Environment.GetEnvironmentVariable("LEIREN_ERP_CONNECTION_STRING"); + } + + var service = new FileBackupService(); + var result = await service.RunAsync(options, dryRun).ConfigureAwait(false); + + if (result.DryRun) + { + Console.WriteLine("DRY-RUN:仅枚举并校验源文件,未写入任何备份文件。"); + } + else + { + Console.WriteLine($"备份完成:{result.BackupId}"); + Console.WriteLine($"备份目录:{result.BackupDirectory}"); + Console.WriteLine($"清单文件:{result.ManifestPath}"); + } + + Console.WriteLine($"文件数:{result.FileCount}"); + Console.WriteLine($"文件总字节:{result.TotalFileBytes}"); + Console.WriteLine(result.DatabaseIncluded + ? $"数据库已包含:{result.DatabaseBytes} 字节" + : "数据库未包含(IncludeDatabase=false)。"); + return ExitOk; + } + + private static async Task RunVerifyAsync(string[] args) + { + var parsed = CliArgs.Parse(args); + var backupDirectory = parsed.GetValue("--backup") ?? parsed.GetValue("--path"); + if (string.IsNullOrWhiteSpace(backupDirectory)) + { + Console.Error.WriteLine("verify 需要 --backup <备份目录>。"); + PrintUsage(); + return ExitUsage; + } + + var service = new FileBackupService(); + var result = await service.VerifyAsync(backupDirectory).ConfigureAwait(false); + if (!result.IsValid) + { + Console.Error.WriteLine($"备份校验失败:{result.BackupDirectory}"); + foreach (var error in result.Errors) + { + Console.Error.WriteLine($" - {error}"); + } + + return ExitFailure; + } + + Console.WriteLine($"备份校验通过:{result.BackupId}"); + Console.WriteLine($"已校验文件:{result.CheckedFiles} 个,{result.CheckedBytes} 字节"); + Console.WriteLine(result.DatabaseChecked ? "数据库备份已校验。" : "清单中无数据库备份。"); + return ExitOk; + } + + private static async Task LoadOptionsAsync(CliArgs args) + { + var configPath = args.GetValue("--config"); + if (string.IsNullOrWhiteSpace(configPath)) + { + return new BackupOptions(); + } + + if (!File.Exists(configPath)) + { + throw new BackupException($"备份配置文件不存在:{configPath}"); + } + + try + { + var json = await File.ReadAllTextAsync(configPath).ConfigureAwait(false); + return JsonSerializer.Deserialize(json, new JsonSerializerOptions + { + PropertyNameCaseInsensitive = true, + }) ?? throw new BackupException($"备份配置文件为空:{configPath}"); + } + catch (JsonException ex) + { + throw new BackupException($"备份配置文件 JSON 无效:{ex.Message}", ex); + } + } + + private static void ApplyOverrides(BackupOptions options, CliArgs args) + { + foreach (var source in args.GetValues("--source")) + { + var separator = source.IndexOf('='); + if (separator <= 0) + { + throw new BackupException($"--source 格式应为 Name=Path,收到:{source}"); + } + + options.Sources.Add(new BackupSourceOptions + { + Name = source[..separator], + Path = source[(separator + 1)..], + }); + } + + if (args.GetValue("--destination") is { } destination) + { + options.DestinationPath = destination; + } + + if (args.HasFlag("--include-database")) + { + options.IncludeDatabase = true; + } + + if (args.GetValue("--database-provider") is { } provider) + { + options.DatabaseProvider = provider; + } + + if (args.GetValue("--database-connection-string") is { } connectionString) + { + options.DatabaseConnectionString = connectionString; + } + + if (args.GetValue("--pg-dump-path") is { } pgDumpPath) + { + options.PgDumpPath = pgDumpPath; + } + + if (args.HasFlag("--allow-empty")) + { + options.AllowEmpty = true; + } + } + + private static int UnknownCommand(string command) + { + Console.Error.WriteLine($"未知命令:{command}"); + PrintUsage(); + return ExitUsage; + } + + private static bool IsHelp(string arg) => arg is "--help" or "-h" or "help"; + + private static void PrintUsage() + { + Console.WriteLine(""" + Leiren.Erp.Backup - 文件/模板与数据库备份工具 + + 用法: + Leiren.Erp.Backup backup [--config backup.json] [选项] + Leiren.Erp.Backup verify --backup <备份目录> + + backup 选项: + --config JSON 配置文件(见 deploy/windows/backup.example.json) + --source 备份源目录,可重复;Name 仅字母/数字/-/_/. + --destination 备份根目录(其下按时间戳建子目录) + --include-database 同时包含数据库备份 + --database-provider + --database-connection-string 建议改用配置文件或环境变量 LEIREN_ERP_CONNECTION_STRING + --pg-dump-path pg_dump 完整路径(默认从 PATH 查找) + --allow-empty 允许空备份(默认拒绝) + --dry-run 仅枚举/哈希源文件,不写入任何内容 + + 退出码:0 成功,1 备份或校验失败,2 用法错误。 + 失败时不会生成可被误认的完成备份;完成前会按 manifest.json 的 SHA-256 自校验。 + """); + } + + private sealed class CliArgs + { + private readonly Dictionary> _values = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _flags = new(StringComparer.OrdinalIgnoreCase); + + public static CliArgs Parse(string[] args) + { + var parsed = new CliArgs(); + for (var i = 0; i < args.Length; i++) + { + var arg = args[i]; + if (arg is "--dry-run" or "--include-database" or "--allow-empty") + { + parsed._flags.Add(arg); + continue; + } + + if (arg.StartsWith("--", StringComparison.Ordinal)) + { + if (i + 1 >= args.Length || args[i + 1].StartsWith("--", StringComparison.Ordinal)) + { + throw new BackupException($"选项 {arg} 缺少值。"); + } + + if (!parsed._values.TryGetValue(arg, out var list)) + { + list = []; + parsed._values[arg] = list; + } + + list.Add(args[++i]); + continue; + } + + throw new BackupException($"无法识别的参数:{arg}"); + } + + return parsed; + } + + public bool HasFlag(string name) => _flags.Contains(name); + + public string? GetValue(string name) + => _values.TryGetValue(name, out var list) && list.Count > 0 ? list[^1] : null; + + public IReadOnlyList GetValues(string name) + => _values.TryGetValue(name, out var list) ? list : []; + } +} diff --git a/src/Leiren.Erp.Client/ApiClient.cs b/src/Leiren.Erp.Client/ApiClient.cs new file mode 100644 index 0000000..917bfe2 --- /dev/null +++ b/src/Leiren.Erp.Client/ApiClient.cs @@ -0,0 +1,259 @@ +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; + +namespace Leiren.Erp.Client; + +public sealed record LoginResponse(Guid UserId, string UserName, string DisplayName, string AccessToken, string RefreshToken); + +public sealed class ApiException : Exception +{ + public ApiException(string message) : base(message) { } + public ApiException(string message, Exception innerException) : base(message, innerException) { } + public ApiException(string message, int statusCode) : base(message) => StatusCode = statusCode; + public int? StatusCode { get; } + public bool IsForbidden => StatusCode == (int)HttpStatusCode.Forbidden; +} + +public sealed class ApiClient +{ + private readonly HttpClient httpClient; + private readonly SemaphoreSlim refreshGate = new(1, 1); + public ApiClient(string? baseUrl = null) + { + var address = string.IsNullOrWhiteSpace(baseUrl) ? "http://127.0.0.1:5118" : baseUrl.Trim(); + httpClient = new HttpClient + { + BaseAddress = new Uri(address, UriKind.Absolute), + Timeout = TimeSpan.FromSeconds(15) + }; + } + + public string? AccessToken { get; private set; } + public string? RefreshToken { get; private set; } + public LoginResponse? CurrentUser { get; private set; } + public bool IsAuthenticated => !string.IsNullOrWhiteSpace(AccessToken); + public event Action? SessionChanged; + + public async Task LoginAsync(string userName, string password, CancellationToken cancellationToken = default) + { + var result = await SendAsync(HttpMethod.Post, "/api/auth/login", + new { userName, password }, cancellationToken); + return ApplySession(result); + } + + public async Task RefreshAsync(string refreshToken, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(refreshToken)) throw new ApiException("保持登录凭据为空。"); + await refreshGate.WaitAsync(cancellationToken); + try + { + return await RefreshCoreAsync(refreshToken, cancellationToken); + } + finally { refreshGate.Release(); } + } + + private async Task RefreshAccessTokenAsync(CancellationToken cancellationToken) + { + await refreshGate.WaitAsync(cancellationToken); + try + { + var refreshToken = RefreshToken; + if (string.IsNullOrWhiteSpace(refreshToken)) + throw new ApiException("登录已失效,请重新登录。"); + await RefreshCoreAsync(refreshToken, cancellationToken); + } + finally { refreshGate.Release(); } + } + + private async Task RefreshCoreAsync(string refreshToken, CancellationToken cancellationToken) + { + var result = await SendAsync(HttpMethod.Post, "/api/auth/refresh", + new { refreshToken }, cancellationToken); + return ApplySession(result); + } + + public async Task RevokeRefreshTokenAsync(string? refreshToken, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(refreshToken)) return; + try + { + using var response = await SendRawAsync(HttpMethod.Post, "/api/auth/logout", new { refreshToken }, cancellationToken); + } + catch (ApiException) { } + } + + private LoginResponse ApplySession(LoginResponse result) + { + if (string.IsNullOrWhiteSpace(result.AccessToken) || string.IsNullOrWhiteSpace(result.RefreshToken)) + throw new ApiException("服务器返回了空的登录凭据。"); + AccessToken = result.AccessToken; + RefreshToken = result.RefreshToken; + CurrentUser = result; + httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); + SessionChanged?.Invoke(result); + return result; + } + + public Task GetAsync(string url, CancellationToken cancellationToken = default) + => SendAsync(HttpMethod.Get, url, null, cancellationToken); + + public Task PostAsync(string url, object? body = null, CancellationToken cancellationToken = default) + => SendAsync(HttpMethod.Post, url, body, cancellationToken); + + /// POST for endpoints that answer 204 No Content. + public async Task PostAsync(string url, object? body = null, CancellationToken cancellationToken = default) + { + using var response = await SendRawAsync(HttpMethod.Post, url, body, cancellationToken); + } + + public Task PutAsync(string url, object? body = null, CancellationToken cancellationToken = default) + => SendAsync(HttpMethod.Put, url, body, cancellationToken); + + public async Task DeleteAsync(string url, CancellationToken cancellationToken = default) + { + using var response = await SendRawAsync(HttpMethod.Delete, url, null, cancellationToken); + } + + public async Task GetBytesAsync(string url, CancellationToken cancellationToken = default) + { + using var response = await SendRawAsync(HttpMethod.Get, url, null, cancellationToken); + return await response.Content.ReadAsByteArrayAsync(cancellationToken); + } + + /// POST whose response is a file (e.g. a rendered preview workbook). + public async Task PostBytesAsync(string url, object? body, CancellationToken cancellationToken = default) + { + using var response = await SendRawAsync(HttpMethod.Post, url, body, cancellationToken); + return await response.Content.ReadAsByteArrayAsync(cancellationToken); + } + + /// Uploads one file as multipart/form-data (field "file") with extra text fields. + public Task UploadAsync(string url, string filePath, IReadOnlyDictionary fields, CancellationToken cancellationToken = default) + { + var bytes = File.ReadAllBytes(filePath); + HttpContent Build() + { + var form = new MultipartFormDataContent(); + foreach (var (key, value) in fields) + if (!string.IsNullOrWhiteSpace(value)) form.Add(new StringContent(value), key); + var file = new ByteArrayContent(bytes); + file.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + form.Add(file, "file", Path.GetFileName(filePath)); + return form; + } + return SendAsync(HttpMethod.Post, url, (Func)Build, cancellationToken); + } + + public void Logout() + { + AccessToken = null; + CurrentUser = null; + httpClient.DefaultRequestHeaders.Authorization = null; + } + + private async Task SendAsync(HttpMethod method, string url, object? body, CancellationToken cancellationToken) + { + using var response = await SendRawAsync(method, url, body, cancellationToken); + try + { + return await response.Content.ReadFromJsonAsync(cancellationToken: cancellationToken) + ?? throw new ApiException("服务器返回了空结果。"); + } + catch (JsonException ex) + { + throw new ApiException("服务器返回的数据格式不正确。", ex); + } + } + + private async Task SendRawAsync(HttpMethod method, string url, object? body, CancellationToken cancellationToken) + { + try + { + using var request = new HttpRequestMessage(method, url); + if (body is Func contentFactory) + request.Content = contentFactory(); // rebuilt when the request is retried after a token refresh + else if (body is not null) + request.Content = JsonContent.Create(body); + + var response = await httpClient.SendAsync(request, cancellationToken); + if (response.IsSuccessStatusCode) return response; + if (response.StatusCode == HttpStatusCode.Unauthorized && + !string.Equals(url, "/api/auth/refresh", StringComparison.OrdinalIgnoreCase) && + !string.IsNullOrWhiteSpace(RefreshToken)) + { + response.Dispose(); + await RefreshAccessTokenAsync(cancellationToken); + return await SendRawAsync(method, url, body, cancellationToken); + } + + using (response) + { + var message = await ReadErrorAsync(response, cancellationToken); + if (response.StatusCode == HttpStatusCode.Forbidden && !message.Contains("403", StringComparison.Ordinal)) + message = $"无权限(403):{message}"; + throw new ApiException(message, (int)response.StatusCode); + } + } + catch (ApiException) + { + throw; + } + catch (HttpRequestException ex) + { + throw new ApiException("无法连接服务器,请确认服务器已启动后重试。", ex); + } + catch (TaskCanceledException ex) when (!cancellationToken.IsCancellationRequested) + { + throw new ApiException("连接服务器超时,请稍后重试。", ex); + } + catch (JsonException ex) + { + throw new ApiException("服务器返回的数据格式不正确。", ex); + } + } + + private static async Task ReadErrorAsync(HttpResponseMessage response, CancellationToken cancellationToken) + { + try + { + var text = await response.Content.ReadAsStringAsync(cancellationToken); + if (!string.IsNullOrWhiteSpace(text)) + { + using var document = JsonDocument.Parse(text); + var root = document.RootElement; + var message = GetString(root, "detail") ?? GetString(root, "title"); + if (root.TryGetProperty("errors", out var errors) && errors.ValueKind == JsonValueKind.Object) + { + var parts = new List(); + foreach (var field in errors.EnumerateObject()) + { + var messages = field.Value.ValueKind == JsonValueKind.Array + ? string.Join(" ", field.Value.EnumerateArray().Select(x => x.GetString()).Where(x => !string.IsNullOrWhiteSpace(x))) + : field.Value.GetString() ?? string.Empty; + if (!string.IsNullOrWhiteSpace(messages)) parts.Add(messages); + } + + if (parts.Count > 0) return string.Join(" ", parts); + } + + if (!string.IsNullOrWhiteSpace(message)) return message; + } + } + catch (JsonException) + { + } + + return response.StatusCode == HttpStatusCode.Unauthorized + ? "用户名或密码不正确,或登录已失效。" + : $"服务器请求失败({(int)response.StatusCode})。"; + } + + private static string? GetString(JsonElement element, string name) + => element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; +} diff --git a/src/Leiren.Erp.Client/App.xaml b/src/Leiren.Erp.Client/App.xaml new file mode 100644 index 0000000..a45cc4f --- /dev/null +++ b/src/Leiren.Erp.Client/App.xaml @@ -0,0 +1,220 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Leiren.Erp.Client/App.xaml.cs b/src/Leiren.Erp.Client/App.xaml.cs new file mode 100644 index 0000000..e072ca2 --- /dev/null +++ b/src/Leiren.Erp.Client/App.xaml.cs @@ -0,0 +1,70 @@ +using System.Windows; + +namespace Leiren.Erp.Client; + +/// +/// Start-up: restore a kept session silently; only when that is not possible +/// show the login window, then open the main window. +/// +public partial class App : Application +{ + private ClientSettings settings = null!; + private ApiClient api = null!; + + protected override async void OnStartup(StartupEventArgs e) + { + base.OnStartup(e); + ShutdownMode = ShutdownMode.OnExplicitShutdown; + settings = ClientSettings.Load(); + settings.Save(); + api = new ApiClient(settings.ApiBaseUrl); + api.SessionChanged += SaveSession; + + var (session, message) = await RestoreSessionAsync(); + session ??= SignIn(message); + if (session is null) + { + Shutdown(); + return; + } + + var main = new MainWindow(api, settings, session, SignIn); + MainWindow = main; + ShutdownMode = ShutdownMode.OnMainWindowClose; + main.Show(); + } + + /// Shows the login window; null when the user closes it. + private LoginResponse? SignIn(string? message) + { + var login = new LoginWindow(api, settings, message); + return login.ShowDialog() == true ? login.Result : null; + } + + private async Task<(LoginResponse? Session, string? Message)> RestoreSessionAsync() + { + if (!settings.KeepSignedIn || string.IsNullOrWhiteSpace(settings.RefreshToken)) return (null, null); + try + { + return (await api.RefreshAsync(settings.RefreshToken), null); + } + catch (ApiException) + { + api.Logout(); + settings.ClearSession(); + return (null, "保持登录已失效,请重新登录。"); + } + catch + { + return (null, "无法恢复登录,请检查服务器连接。"); + } + } + + /// Persists (or forgets) the refresh token whenever the session changes. + private void SaveSession(LoginResponse result) + { + settings.UserName = settings.KeepSignedIn ? result.UserName : settings.UserName; + settings.RefreshToken = settings.KeepSignedIn ? result.RefreshToken : null; + settings.Save(); + } +} diff --git a/src/Leiren.Erp.Client/AssemblyInfo.cs b/src/Leiren.Erp.Client/AssemblyInfo.cs new file mode 100644 index 0000000..cc29e7f --- /dev/null +++ b/src/Leiren.Erp.Client/AssemblyInfo.cs @@ -0,0 +1,10 @@ +using System.Windows; + +[assembly:ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] diff --git a/src/Leiren.Erp.Client/ClientSettings.cs b/src/Leiren.Erp.Client/ClientSettings.cs new file mode 100644 index 0000000..8f33b12 --- /dev/null +++ b/src/Leiren.Erp.Client/ClientSettings.cs @@ -0,0 +1,120 @@ +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Leiren.Erp.Client; + +public sealed class ClientSettings +{ + private const string Section = "Client"; + private readonly Dictionary values = new(StringComparer.OrdinalIgnoreCase); + + private ClientSettings(string filePath) + { + FilePath = filePath; + } + + public string FilePath { get; } + + public string ApiBaseUrl + { + get => Get("ApiBaseUrl") ?? "http://127.0.0.1:5118"; + set => Set("ApiBaseUrl", string.IsNullOrWhiteSpace(value) ? "http://127.0.0.1:5118" : value.Trim()); + } + + public bool KeepSignedIn + { + get => !values.TryGetValue("KeepSignedIn", out var text) || + !bool.TryParse(text, out var value) || value; + set => Set("KeepSignedIn", value.ToString()); + } + + public string? UserName + { + get => Get("UserName"); + set => Set("UserName", value); + } + + public string? RefreshToken + { + get + { + var protectedValue = Get("RefreshToken"); + if (string.IsNullOrWhiteSpace(protectedValue)) return null; + try + { + var protectedBytes = Convert.FromBase64String(protectedValue); + var plainBytes = ProtectedData.Unprotect(protectedBytes, null, DataProtectionScope.CurrentUser); + return Encoding.UTF8.GetString(plainBytes); + } + catch (FormatException) { return null; } + catch (CryptographicException) { return null; } + } + set + { + if (string.IsNullOrWhiteSpace(value)) + { + values.Remove("RefreshToken"); + return; + } + + var plainBytes = Encoding.UTF8.GetBytes(value); + var protectedBytes = ProtectedData.Protect(plainBytes, null, DataProtectionScope.CurrentUser); + Set("RefreshToken", Convert.ToBase64String(protectedBytes)); + } + } + + public static ClientSettings Load() + { + var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "LeirenErp"); + var settings = new ClientSettings(Path.Combine(directory, "settings.ini")); + if (!File.Exists(settings.FilePath)) return settings; + + string? section = null; + foreach (var rawLine in File.ReadLines(settings.FilePath, Encoding.UTF8)) + { + var line = rawLine.Trim(); + if (line.Length == 0 || line.StartsWith(';') || line.StartsWith('#')) continue; + if (line.StartsWith('[') && line.EndsWith(']')) + { + section = line[1..^1].Trim(); + continue; + } + if (!string.Equals(section, Section, StringComparison.OrdinalIgnoreCase)) continue; + var separator = line.IndexOf('='); + if (separator <= 0) continue; + settings.values[line[..separator].Trim()] = line[(separator + 1)..].Trim(); + } + return settings; + } + + /// Forgets the session; the user name and the "保持登录" choice stay for the next sign-in. + public void ClearSession() + { + RefreshToken = null; + Save(); + } + + public void Save() + { + var directory = Path.GetDirectoryName(FilePath)!; + Directory.CreateDirectory(directory); + var content = new StringBuilder() + .AppendLine("; Leiren ERP client settings") + .AppendLine("[Client]") + .Append("ApiBaseUrl=").AppendLine(ApiBaseUrl) + .Append("KeepSignedIn=").AppendLine(KeepSignedIn.ToString()) + .Append("UserName=").AppendLine(UserName ?? string.Empty); + var refreshToken = Get("RefreshToken"); + if (!string.IsNullOrWhiteSpace(refreshToken)) content.Append("RefreshToken=").AppendLine(refreshToken); + File.WriteAllText(FilePath, content.ToString(), new UTF8Encoding(false)); + } + + private string? Get(string key) => values.TryGetValue(key, out var value) ? value : null; + + private void Set(string key, string? value) + { + if (string.IsNullOrWhiteSpace(value)) values.Remove(key); + else values[key] = value; + } +} diff --git a/src/Leiren.Erp.Client/Controls/DialogKit.cs b/src/Leiren.Erp.Client/Controls/DialogKit.cs new file mode 100644 index 0000000..6bffd16 --- /dev/null +++ b/src/Leiren.Erp.Client/Controls/DialogKit.cs @@ -0,0 +1,84 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; + +namespace Leiren.Erp.Client.Controls; + +/// Shared look for the code-built dialogs (template editor, container numbers). +public static class DialogKit +{ + public static readonly Brush Ink = Freeze(Color.FromRgb(0x18, 0x21, 0x2F)); + public static readonly Brush Muted = Freeze(Color.FromRgb(0x77, 0x83, 0x97)); + public static readonly Brush Line = Freeze(Color.FromRgb(0xD6, 0xDE, 0xEA)); + public static readonly Brush Blue = Freeze(Color.FromRgb(0x26, 0x67, 0xE8)); + public static readonly Brush Error = Freeze(Color.FromRgb(0xB4, 0x23, 0x18)); + public static readonly Brush Orange = Freeze(Color.FromRgb(0xB9, 0x68, 0x17)); + public static readonly Brush Green = Freeze(Color.FromRgb(0x16, 0x84, 0x5B)); + public static readonly Brush Wash = Freeze(Color.FromRgb(0xF5, 0xF6, 0xF8)); + + private static Brush Freeze(Color color) + { + var brush = new SolidColorBrush(color); + brush.Freeze(); + return brush; + } + + public static Window Window(Window? owner, string title, double width, double height) => new() + { + Title = title, + Width = width, + Height = height, + MinWidth = Math.Min(width, 640), + MinHeight = Math.Min(height, 420), + Owner = owner, + WindowStartupLocation = owner is null ? WindowStartupLocation.CenterScreen : WindowStartupLocation.CenterOwner, + Background = Wash, + }; + + public static TextBlock Heading(string text) => new() + { + Text = text, FontSize = 16, FontWeight = FontWeights.SemiBold, Foreground = Ink, TextWrapping = TextWrapping.Wrap, + }; + + public static TextBlock Note(string text, Brush? color = null) => new() + { + Text = text, FontSize = 12, Foreground = color ?? Muted, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 4, 0, 0), + }; + + public static StackPanel Field(string label, UIElement control) + { + var panel = new StackPanel { Margin = new Thickness(0, 0, 0, 12) }; + panel.Children.Add(new TextBlock { Text = label, FontSize = 11, Foreground = Muted, FontWeight = FontWeights.SemiBold, Margin = new Thickness(0, 0, 0, 5) }); + panel.Children.Add(control); + return panel; + } + + public static TextBox TextBox(string text = "") => new() + { + Text = text, Height = 32, VerticalContentAlignment = VerticalAlignment.Center, Padding = new Thickness(8, 0, 8, 0), BorderBrush = Line, + }; + + public static Button Primary(string label) => new() + { + Content = label, MinWidth = 90, Height = 34, Padding = new Thickness(14, 0, 14, 0), Background = Blue, + Foreground = Brushes.White, BorderThickness = new Thickness(0), FontWeight = FontWeights.SemiBold, + }; + + public static Button Secondary(string label) => new() + { + Content = label, MinWidth = 90, Height = 34, Padding = new Thickness(14, 0, 14, 0), Background = Brushes.White, + Foreground = Ink, BorderBrush = Line, + }; + + /// Right-aligned button row with spacing. + public static StackPanel Buttons(params Button[] buttons) + { + var row = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(0, 12, 0, 0) }; + for (var i = 0; i < buttons.Length; i++) + { + if (i > 0) buttons[i].Margin = new Thickness(10, 0, 0, 0); + row.Children.Add(buttons[i]); + } + return row; + } +} diff --git a/src/Leiren.Erp.Client/Controls/DisplayTextConverter.cs b/src/Leiren.Erp.Client/Controls/DisplayTextConverter.cs new file mode 100644 index 0000000..3abc1a5 --- /dev/null +++ b/src/Leiren.Erp.Client/Controls/DisplayTextConverter.cs @@ -0,0 +1,20 @@ +using System.Globalization; +using System.Windows.Data; +using Leiren.Erp.Client.Pages; + +namespace Leiren.Erp.Client.Controls; + +/// Shows stored enum / flag values in Chinese (part and product types, yes/no). +public sealed class DisplayTextConverter : IValueConverter +{ + public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => value switch + { + bool flag => flag ? "是" : "否", + string text => ProductPage.TypeName(text), + null => "-", + _ => value.ToString() ?? "-", + }; + + public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) + => throw new NotSupportedException(); +} diff --git a/src/Leiren.Erp.Client/Controls/FluentIcons.cs b/src/Leiren.Erp.Client/Controls/FluentIcons.cs new file mode 100644 index 0000000..c927898 --- /dev/null +++ b/src/Leiren.Erp.Client/Controls/FluentIcons.cs @@ -0,0 +1,43 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; + +namespace Leiren.Erp.Client.Controls; + +/// +/// Glyphs of the installed Segoe Fluent Icons font (Windows 11; falls back to +/// Segoe MDL2 Assets on Windows 10, which shares the code points used here). +/// Icons inherit the foreground of the button or text they sit in. +/// +public static class FluentIcons +{ + public static readonly FontFamily Font = new("Segoe Fluent Icons, Segoe MDL2 Assets"); + + public const string Add = "\uE710"; + public const string Refresh = "\uE72C"; + public const string Edit = "\uE70F"; + public const string Delete = "\uE74D"; + public const string Download = "\uE896"; + public const string CheckMark = "\uE73E"; + public const string Close = "\uE711"; + public const string Forward = "\uE72A"; + public const string SignOut = "\uF3B1"; + + public static TextBlock Glyph(string glyph, double size = 14, Brush? foreground = null) + { + var block = new TextBlock { Text = glyph, FontFamily = Font, FontSize = size, VerticalAlignment = VerticalAlignment.Center }; + if (foreground is not null) block.Foreground = foreground; + return block; + } + + /// Button content: an icon followed by a label. + public static StackPanel Label(string glyph, string text, double size = 13) + { + var panel = new StackPanel { Orientation = Orientation.Horizontal }; + var icon = Glyph(glyph, size); + icon.Margin = new Thickness(0, 1, 7, 0); + panel.Children.Add(icon); + panel.Children.Add(new TextBlock { Text = text, VerticalAlignment = VerticalAlignment.Center }); + return panel; + } +} diff --git a/src/Leiren.Erp.Client/Controls/PageFrame.cs b/src/Leiren.Erp.Client/Controls/PageFrame.cs new file mode 100644 index 0000000..919b447 --- /dev/null +++ b/src/Leiren.Erp.Client/Controls/PageFrame.cs @@ -0,0 +1,35 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; +using Leiren.Erp.Client.Pages; + +namespace Leiren.Erp.Client.Controls; + +/// +/// Gives the master-data pages (products, customers, suppliers, settings) the +/// same dark header band as the workflow workspace: only the page title. +/// +public sealed class PageFrame : UserControl, ILoadablePage +{ + private readonly UIElement page; + + public PageFrame(string title, UIElement page) + { + this.page = page; + var root = new Grid { Background = new SolidColorBrush(Color.FromRgb(0xF5, 0xF6, 0xF8)) }; + root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + root.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }); + + // Same padding, size and height as the workspace header (whose action buttons are 34 px tall). + var titleText = new TextBlock { Text = title, Foreground = Brushes.White, FontSize = 24, FontWeight = FontWeights.SemiBold, VerticalAlignment = VerticalAlignment.Center }; + var band = new Grid { MinHeight = 34, Children = { titleText } }; + root.Children.Add(new Border { Background = new SolidColorBrush(Color.FromRgb(0x12, 0x20, 0x33)), Padding = new Thickness(28, 20, 28, 20), Child = band }); + + var content = new Border { Padding = new Thickness(28, 22, 28, 24), Child = page }; + Grid.SetRow(content, 1); + root.Children.Add(content); + Content = root; + } + + public Task ActivateAsync() => page is ILoadablePage loadable ? loadable.ActivateAsync() : Task.CompletedTask; +} diff --git a/src/Leiren.Erp.Client/Controls/XlsxPreviewView.cs b/src/Leiren.Erp.Client/Controls/XlsxPreviewView.cs new file mode 100644 index 0000000..53a9713 --- /dev/null +++ b/src/Leiren.Erp.Client/Controls/XlsxPreviewView.cs @@ -0,0 +1,233 @@ +using System.IO; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Effects; +using System.Windows.Media.Imaging; +using ExcelRenderer; +using ExcelRenderer.Fonts; +using ExcelRenderer.Rendering; + +namespace Leiren.Erp.Client.Controls; + +/// +/// Real-rendered XLSX preview: ExcelRenderer draws the first worksheet +/// (merges, borders, fills, row heights) as one continuous image. The page +/// fits the view by default; a click zooms to 100 % keeping the clicked point +/// under the cursor, dragging pans, and another click returns to fit. +/// +public sealed class XlsxPreviewView : UserControl +{ + private const double Dpi = 144; + private const double DragThreshold = 4; + + private readonly ScrollViewer scroll; + private readonly TextBlock placeholder; + private readonly Border page; + private readonly Image image = new() { Stretch = Stretch.Uniform, Cursor = Cursors.Hand }; + + // Natural (100 %) size in WPF units: the bitmap is rendered at 144 DPI, layout is 96. + private Size naturalSize; + private bool actualSize; + private bool pressed; + private bool dragged; + private Point pressPoint; + private Point pressOffset; + + public XlsxPreviewView() + { + placeholder = new TextBlock + { + Text = "尚未生成预览", + Foreground = new SolidColorBrush(Color.FromRgb(0x66, 0x70, 0x85)), + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(0, 40, 0, 0), + }; + page = new Border + { + Background = Brushes.White, + Margin = new Thickness(16), + Padding = new Thickness(16), + Visibility = Visibility.Collapsed, + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + Effect = new DropShadowEffect { BlurRadius = 8, ShadowDepth = 1, Opacity = 0.25 }, + Child = image, + }; + var content = new Grid(); + content.Children.Add(placeholder); + content.Children.Add(page); + scroll = new ScrollViewer + { + Background = new SolidColorBrush(Color.FromRgb(0xE4, 0xE7, 0xEC)), + HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled, + VerticalScrollBarVisibility = ScrollBarVisibility.Disabled, + Content = content, + }; + scroll.PreviewMouseLeftButtonDown += OnMouseDown; + scroll.PreviewMouseMove += OnMouseMove; + scroll.PreviewMouseLeftButtonUp += OnMouseUp; + Content = scroll; + } + + public bool HasImage => image.Source is not null; + + /// Shows a status text instead of the page (loading, empty, error). + public void ShowMessage(string text) + { + image.Source = null; + page.Visibility = Visibility.Collapsed; + placeholder.Text = text; + placeholder.Visibility = Visibility.Visible; + } + + /// Renders the workbook off the UI thread and shows it fitted to the view. + public async Task ShowAsync(byte[] xlsx) + { + ShowMessage("正在渲染预览…"); + var images = await Task.Run(() => RenderAsync(xlsx)); + if (images.Count == 0) throw new InvalidOperationException("工作表没有可渲染的内容。"); + + var bitmap = new BitmapImage(); + bitmap.BeginInit(); + bitmap.CacheOption = BitmapCacheOption.OnLoad; + bitmap.StreamSource = new MemoryStream(images[0]); + bitmap.EndInit(); + bitmap.Freeze(); + + naturalSize = new Size(bitmap.PixelWidth * 96 / Dpi, bitmap.PixelHeight * 96 / Dpi); + image.Source = bitmap; + placeholder.Visibility = Visibility.Collapsed; + page.Visibility = Visibility.Visible; + SetActualSize(false, null); + } + + /// + /// Fit mode scales the page down to the visible area (never above 100 %); + /// actual-size mode shows it at 100 % with scrolling, keeping the clicked + /// point under the cursor. + /// + private void SetActualSize(bool value, Point? anchorInViewport) + { + Point? relative = null; + if (value && anchorInViewport is { } anchor && image.ActualWidth > 0) + { + var onImage = scroll.TranslatePoint(anchor, image); + relative = new Point( + Math.Clamp(onImage.X / image.ActualWidth, 0, 1), + Math.Clamp(onImage.Y / image.ActualHeight, 0, 1)); + } + + actualSize = value; + var visibility = value ? ScrollBarVisibility.Auto : ScrollBarVisibility.Disabled; + scroll.HorizontalScrollBarVisibility = visibility; + scroll.VerticalScrollBarVisibility = visibility; + image.Width = value ? naturalSize.Width : double.NaN; + image.Height = value ? naturalSize.Height : double.NaN; + image.MaxWidth = naturalSize.Width; + image.MaxHeight = naturalSize.Height; + image.Cursor = value ? Cursors.SizeAll : Cursors.Hand; + scroll.UpdateLayout(); + + if (relative is { } r && anchorInViewport is { } a) + { + var target = image.TranslatePoint(new Point(r.X * naturalSize.Width, r.Y * naturalSize.Height), scroll); + scroll.ScrollToHorizontalOffset(scroll.HorizontalOffset + target.X - a.X); + scroll.ScrollToVerticalOffset(scroll.VerticalOffset + target.Y - a.Y); + } + } + + private void OnMouseDown(object sender, MouseButtonEventArgs e) + { + if (image.Source is null || IsInScrollBar(e.OriginalSource as DependencyObject)) return; + pressed = true; + dragged = false; + pressPoint = e.GetPosition(scroll); + pressOffset = new Point(scroll.HorizontalOffset, scroll.VerticalOffset); + scroll.CaptureMouse(); + e.Handled = true; + } + + private static bool IsInScrollBar(DependencyObject? element) + { + for (; element is not null; element = element is Visual ? VisualTreeHelper.GetParent(element) : null) + if (element is ScrollBar) return true; + return false; + } + + private void OnMouseMove(object sender, MouseEventArgs e) + { + if (!pressed) return; + var delta = e.GetPosition(scroll) - pressPoint; + if (!dragged && Math.Abs(delta.X) < DragThreshold && Math.Abs(delta.Y) < DragThreshold) return; + dragged = true; + if (!actualSize) return; + scroll.ScrollToHorizontalOffset(pressOffset.X - delta.X); + scroll.ScrollToVerticalOffset(pressOffset.Y - delta.Y); + } + + private void OnMouseUp(object sender, MouseButtonEventArgs e) + { + if (!pressed) return; + pressed = false; + scroll.ReleaseMouseCapture(); + if (!dragged) SetActualSize(!actualSize, e.GetPosition(scroll)); + e.Handled = true; + } + + private static async Task> RenderAsync(byte[] xlsx) + { + using var input = new MemoryStream(xlsx); + var sink = new MemorySink(); + await ExcelConverter.RenderAsync(input, new RenderRequest + { + OutputFormat = OutputFormat.Png, + ImageLayout = ImageLayoutMode.Continuous, + Dpi = Dpi, + // The package's bundled fonts are Japanese, and scanning every + // system font costs seconds; register the Windows Simplified + // Chinese face (DengXian, regular + bold) explicitly instead. + FontOptions = new FontOptions + { + UseFontPack = false, + AllowSystemFonts = false, + Policy = FontPolicy.PreferRequested, + FontFiles = [WindowsFont("Deng.ttf"), WindowsFont("Dengb.ttf")], + FallbackFamilies = ["DengXian"], + }, + }, sink); + return sink.Images; + } + + private static string WindowsFont(string file) + => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), file); + + /// Collects each rendered PNG in memory; the renderer serialises sink calls. + private sealed class MemorySink : IRenderOutputSink + { + private MemoryStream? current; + public List Images { get; } = []; + + public ValueTask OpenAsync(ArtifactDescriptor artifact, CancellationToken cancellationToken) + { + current = new MemoryStream(); + return ValueTask.FromResult(current); + } + + public ValueTask CompleteAsync(ArtifactDescriptor artifact, long byteLength, CancellationToken cancellationToken) + { + Images.Add(current!.ToArray()); + current = null; + return ValueTask.CompletedTask; + } + + public ValueTask AbortAsync(ArtifactDescriptor artifact, Exception error, CancellationToken cancellationToken) + { + current = null; + return ValueTask.CompletedTask; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/BillingAllocationWindow.cs b/src/Leiren.Erp.Client/Documents/BillingAllocationWindow.cs new file mode 100644 index 0000000..0792e17 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/BillingAllocationWindow.cs @@ -0,0 +1,223 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Splits each customs item of a shipped batch between its suppliers: per +/// supplier the invoiced quantity and tax-included amount (unit price is +/// derived). One supplier may take the whole quantity (others 0). Each item's +/// quantities must add up to the declared quantity before saving. +/// +public sealed class BillingAllocationWindow +{ + private sealed class Row(SupplierInvoiceNoticeDto notice, SupplierInvoiceNoticeLineDto line) + { + public SupplierInvoiceNoticeDto Notice { get; } = notice; + public SupplierInvoiceNoticeLineDto Line { get; } = line; + public TextBox Quantity { get; } = DialogKit.TextBox(line.Quantity.ToString("0.###", CultureInfo.InvariantCulture)); + public TextBox Amount { get; } = DialogKit.TextBox(line.AmountIncludingTax.ToString("0.00", CultureInfo.InvariantCulture)); + public TextBlock Price { get; } = DialogKit.Note(""); + } + + private sealed class Item + { + public required string Name { get; init; } + public required string Unit { get; init; } + public required decimal Target { get; init; } + public List Rows { get; } = []; + public TextBlock Status { get; } = DialogKit.Note(""); + } + + private readonly ApiClient api; + private readonly Guid batchId; + private readonly IReadOnlyList noticeIds; + private readonly Window window; + private readonly StackPanel body = new(); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button save = DialogKit.Primary("保存分配"); + private readonly List items = []; + + public BillingAllocationWindow(ApiClient api, Guid batchId, string batchNo, IReadOnlyList noticeIds, Window? owner) + { + this.api = api; + this.batchId = batchId; + this.noticeIds = noticeIds; + window = DialogKit.Window(owner, $"分配开票数量 · {batchNo}", 900, 700); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + save.IsEnabled = false; + save.Click += async (_, _) => await SaveAsync(); + + var root = new DockPanel { Margin = new Thickness(20) }; + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading($"分配开票数量 · {batchNo}")); + top.Children.Add(DialogKit.Note( + "每个报关品名可以由一个或多个供应商开票:数量合计必须等于报关数量;金额为该供应商的含税开票金额,单价自动计算。某供应商不开该品名时数量和金额都填 0;一个供应商所有品名都为 0 时其开票通知作废。")); + top.Children.Add(new Border { Height = 10 }); + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + var bottom = new StackPanel(); + bottom.Children.Add(error); + bottom.Children.Add(DialogKit.Buttons(cancel, save)); + DockPanel.SetDock(bottom, Dock.Bottom); + root.Children.Add(bottom); + root.Children.Add(new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = body }); + window.Content = root; + window.Loaded += async (_, _) => await LoadAsync(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task LoadAsync() + { + try + { + var notices = new List(); + foreach (var id in noticeIds) notices.Add(await api.GetAsync($"/api/billing/notices/{id}")); + foreach (var group in notices + .SelectMany(n => n.Lines.Select(l => (Notice: n, Line: l))) + .GroupBy(x => x.Line.ShipmentLineId ?? x.Line.Id)) + { + var first = group.First().Line; + var item = new Item { Name = first.ContentDescription, Unit = first.Unit, Target = group.Sum(x => x.Line.Quantity) }; + foreach (var (notice, line) in group.OrderBy(x => x.Notice.SupplierName, StringComparer.CurrentCulture)) + item.Rows.Add(new Row(notice, line)); + items.Add(item); + } + Render(); + save.IsEnabled = items.Count > 0; + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } + + private static decimal? Parse(TextBox box) + => decimal.TryParse(box.Text.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var value) ? value : null; + + private void Render() + { + body.Children.Clear(); + foreach (var item in items) + { + var card = new StackPanel(); + card.Children.Add(new TextBlock + { + Text = $"{item.Name} · 报关数量 {item.Target:0.###} {item.Unit}", + FontSize = 13, FontWeight = FontWeights.SemiBold, Foreground = DialogKit.Ink, Margin = new Thickness(0, 0, 0, 8), + }); + var grid = new Grid(); + foreach (var width in new[] { 2.2, 1, 1, 1, 0.6 }) + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(width, GridUnitType.Star) }); + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + string[] headers = ["供应商", $"数量({item.Unit})", "含税金额(元)", "含税单价", ""]; + for (var c = 0; c < headers.Length; c++) + { + var header = DialogKit.Note(headers[c]); + Grid.SetColumn(header, c); + grid.Children.Add(header); + } + for (var r = 0; r < item.Rows.Count; r++) + { + var row = item.Rows[r]; + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + var all = DialogKit.Secondary("全部给它"); + all.MinWidth = 0; + all.Height = 32; + all.Click += (_, _) => GiveAll(item, row); + UIElement[] cells = + [ + new TextBlock { Text = row.Notice.SupplierName, VerticalAlignment = VerticalAlignment.Center, Foreground = DialogKit.Ink, TextWrapping = TextWrapping.Wrap }, + row.Quantity, row.Amount, row.Price, all, + ]; + for (var c = 0; c < cells.Length; c++) + { + if (cells[c] is FrameworkElement fe) fe.Margin = new Thickness(c == 0 ? 0 : 8, 6, 0, 0); + Grid.SetRow(cells[c], r + 1); + Grid.SetColumn(cells[c], c); + grid.Children.Add(cells[c]); + } + row.Quantity.TextChanged += (_, _) => Update(item); + row.Amount.TextChanged += (_, _) => Update(item); + } + card.Children.Add(grid); + card.Children.Add(item.Status); + body.Children.Add(new Border + { + Background = System.Windows.Media.Brushes.White, BorderBrush = DialogKit.Line, BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(8), Padding = new Thickness(14), Margin = new Thickness(0, 0, 0, 10), Child = card, + }); + Update(item); + } + } + + /// One supplier invoices the whole item: it takes the quantity and the item's total amount. + private static void GiveAll(Item item, Row target) + { + var total = item.Rows.Sum(x => Parse(x.Amount) ?? 0); + foreach (var row in item.Rows) + { + var isTarget = row == target; + row.Quantity.Text = (isTarget ? item.Target : 0).ToString("0.###", CultureInfo.InvariantCulture); + row.Amount.Text = (isTarget ? total : 0).ToString("0.00", CultureInfo.InvariantCulture); + } + } + + private static void Update(Item item) + { + foreach (var row in item.Rows) + { + var q = Parse(row.Quantity); + var a = Parse(row.Amount); + row.Price.Text = q is > 0 && a is not null ? (a.Value / q.Value).ToString("0.0000", CultureInfo.InvariantCulture) : "—"; + row.Price.VerticalAlignment = VerticalAlignment.Center; + } + var sum = item.Rows.Sum(x => Parse(x.Quantity) ?? 0); + var diff = item.Target - sum; + item.Status.Text = diff == 0 + ? $"合计 {sum:0.###} {item.Unit},与报关数量一致。" + : $"合计 {sum:0.###} {item.Unit},{(diff > 0 ? "还差" : "多出")} {Math.Abs(diff):0.###} {item.Unit}。"; + item.Status.Foreground = diff == 0 ? DialogKit.Green : DialogKit.Orange; + } + + private async Task SaveAsync() + { + error.Text = string.Empty; + var lines = new List(); + foreach (var item in items) + { + foreach (var row in item.Rows) + { + if (Parse(row.Quantity) is not { } q || q < 0 || Parse(row.Amount) is not { } a || a < 0) + { + error.Text = $"{item.Name} · {row.Notice.SupplierName}:请填写不小于 0 的数量和金额。"; + return; + } + lines.Add(new BillingAllocationLineRequest(row.Line.Id, q, a)); + } + if (item.Rows.Sum(x => Parse(x.Quantity) ?? 0) != item.Target) + { + error.Text = $"{item.Name}:各供应商数量合计必须等于报关数量 {item.Target:0.###}。"; + return; + } + } + save.IsEnabled = false; + try + { + await api.PutAsync>($"/api/billing/notices/shipping-batches/{batchId}/allocation", + new ReallocateBillingRequest(lines)); + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/BillingNoticeEditWindow.cs b/src/Leiren.Erp.Client/Documents/BillingNoticeEditWindow.cs new file mode 100644 index 0000000..99bc065 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/BillingNoticeEditWindow.cs @@ -0,0 +1,146 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Edits a draft 开票通知's header (supplier contact, invoice title, mailing +/// and requirements). Quantities and amounts are changed in the batch +/// allocation window so every customs item stays consistent. +/// +public sealed class BillingNoticeEditWindow +{ + private readonly ApiClient api; + private readonly Guid noticeId; + private readonly Window window; + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button save = DialogKit.Primary("保存"); + private readonly Dictionary boxes = []; + private SupplierInvoiceNoticeDto? notice; + + private static readonly (string Key, string Label)[] FieldList = + [ + ("exportInvoiceNo", "外销发票号"), ("noticeDate", "通知日期 (yyyy-MM-dd)"), + ("supplierContact", "供应商联系人"), ("supplierPhone", "供应商电话"), + ("supplierFax", "供应商传真"), ("supplierAddress", "供应商地址"), + ("invoiceTitle", "发票抬头"), ("invoiceTitleAddress", "地址"), + ("invoiceTitlePhone", "电话"), ("invoiceTitleBankName", "开户银行"), + ("invoiceTitleBankAccount", "帐号"), ("invoiceTitleTaxNo", "税号"), + ("invoiceTitleCustomsCode", "海关代码"), ("mailingAddress", "寄件地址"), + ("contactName", "联系人"), ("invoicingRequirement", "开票要求"), + ("stampRequirement", "盖章要求"), ("remark", "备注"), + ]; + + public BillingNoticeEditWindow(ApiClient api, Guid noticeId, string title, Window? owner) + { + this.api = api; + this.noticeId = noticeId; + window = DialogKit.Window(owner, $"编辑开票通知 · {title}", 760, 760); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + save.IsEnabled = false; + save.Click += async (_, _) => await SaveAsync(); + + var root = new DockPanel { Margin = new Thickness(20) }; + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading($"编辑开票通知 · {title}")); + top.Children.Add(DialogKit.Note("开票数量和金额在批次的“分配数量”中调整,保证各供应商合计与报关单一致。")); + top.Children.Add(new Border { Height = 12 }); + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + var bottom = new StackPanel(); + bottom.Children.Add(error); + bottom.Children.Add(DialogKit.Buttons(cancel, save)); + DockPanel.SetDock(bottom, Dock.Bottom); + root.Children.Add(bottom); + + var grid = new Grid(); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + for (var i = 0; i < FieldList.Length; i++) + { + if (i % 2 == 0) grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + var box = DialogKit.TextBox(); + boxes[FieldList[i].Key] = box; + var field = DialogKit.Field(FieldList[i].Label, box); + field.Margin = new Thickness(i % 2 == 0 ? 0 : 10, 0, 0, 12); + Grid.SetRow(field, i / 2); + Grid.SetColumn(field, i % 2); + grid.Children.Add(field); + } + root.Children.Add(new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = grid }); + window.Content = root; + window.Loaded += async (_, _) => await LoadAsync(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task LoadAsync() + { + try + { + var n = notice = await api.GetAsync($"/api/billing/notices/{noticeId}"); + void Set(string key, string? value) => boxes[key].Text = value ?? string.Empty; + Set("exportInvoiceNo", n.ExportInvoiceNo); + Set("noticeDate", n.NoticeDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); + Set("supplierContact", n.SupplierContact); + Set("supplierPhone", n.SupplierPhone); + Set("supplierFax", n.SupplierFax); + Set("supplierAddress", n.SupplierAddress); + Set("invoiceTitle", n.InvoiceTitle); + Set("invoiceTitleAddress", n.InvoiceTitleAddress); + Set("invoiceTitlePhone", n.InvoiceTitlePhone); + Set("invoiceTitleBankName", n.InvoiceTitleBankName); + Set("invoiceTitleBankAccount", n.InvoiceTitleBankAccount); + Set("invoiceTitleTaxNo", n.InvoiceTitleTaxNo); + Set("invoiceTitleCustomsCode", n.InvoiceTitleCustomsCode); + Set("mailingAddress", n.MailingAddress); + Set("contactName", n.ContactName); + Set("invoicingRequirement", n.InvoicingRequirement); + Set("stampRequirement", n.StampRequirement); + Set("remark", n.Remark); + save.IsEnabled = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } + + private string? Value(string key) => boxes[key].Text.Trim() is { Length: > 0 } text ? text : null; + + private async Task SaveAsync() + { + if (notice is null) return; + error.Text = string.Empty; + DateOnly? date = null; + if (Value("noticeDate") is { } raw) + { + if (!DateOnly.TryParse(raw, CultureInfo.InvariantCulture, out var parsed)) { error.Text = "通知日期格式应为 yyyy-MM-dd。"; return; } + date = parsed; + } + if (Value("invoiceTitle") is null) { error.Text = "请填写发票抬头。"; return; } + save.IsEnabled = false; + try + { + var request = new UpdateSupplierInvoiceNoticeRequest( + Value("exportInvoiceNo"), notice.PurchaseContractId, notice.PurchaseContractNo, notice.SupplierId, notice.SupplierName, + Value("supplierContact"), Value("supplierPhone"), Value("supplierFax"), Value("supplierAddress"), + Value("invoiceTitle"), Value("invoiceTitleAddress"), Value("invoiceTitlePhone"), Value("invoiceTitleBankName"), + Value("invoiceTitleBankAccount"), Value("invoiceTitleTaxNo"), Value("invoiceTitleCustomsCode"), notice.Currency, + Value("invoicingRequirement"), Value("stampRequirement"), Value("contactName"), Value("mailingAddress"), + Value("remark"), date, null); + await api.PutAsync($"/api/billing/notices/{noticeId}", request); + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/BillingNoticeWindow.cs b/src/Leiren.Erp.Client/Documents/BillingNoticeWindow.cs new file mode 100644 index 0000000..dd98d52 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/BillingNoticeWindow.cs @@ -0,0 +1,138 @@ +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Generates the supplier 开票通知 (one per supplier, each with its 开票购销合同) +/// for a shipped batch. Lines come from the confirmed customs declaration on +/// the server; here only the invoice title, mailing and contract details are +/// entered — prefilled from the most recent notice, so they are typed once. +/// +public sealed class BillingNoticeWindow +{ + private readonly ApiClient api; + private readonly ShippingBatchListItemDto batch; + private readonly Window window; + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button save = DialogKit.Primary("生成开票通知"); + private readonly Dictionary boxes = []; + + private static readonly (string Key, string Label)[] FieldList = + [ + ("exportInvoiceNo", "外销发票号(空则取报关资料的发票编号)"), + ("invoiceTitle", "发票抬头"), + ("invoiceTitleAddress", "地址"), + ("invoiceTitlePhone", "电话"), + ("invoiceTitleBankName", "开户银行"), + ("invoiceTitleBankAccount", "帐号"), + ("invoiceTitleTaxNo", "税号"), + ("invoiceTitleCustomsCode", "海关代码"), + ("mailingAddress", "寄件地址"), + ("contactName", "联系人"), + ("signedPlace", "合同签订地点"), + ]; + + /// Notices created by the dialog (one per supplier). + public IReadOnlyList Created { get; private set; } = []; + + public BillingNoticeWindow(ApiClient api, ShippingBatchListItemDto batch, Window? owner) + { + this.api = api; + this.batch = batch; + window = DialogKit.Window(owner, $"生成开票通知 · {batch.BatchNo}", 760, 760); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + save.Click += async (_, _) => await SaveAsync(); + + var root = new DockPanel { Margin = new Thickness(20) }; + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading("生成供应商开票通知")); + top.Children.Add(DialogKit.Note( + "每个供应商生成一份开票通知和开票用购销合同。品名、单位取自已确认的报关资料;一个产品有多个供应商时,报关数量按各供应商采购金额比例拆分,合计与报关单一致,金额为各供应商自己的含税采购金额。")); + top.Children.Add(new Border { Height = 12 }); + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + var bottom = new StackPanel(); + bottom.Children.Add(error); + bottom.Children.Add(DialogKit.Buttons(cancel, save)); + DockPanel.SetDock(bottom, Dock.Bottom); + root.Children.Add(bottom); + + var grid = new Grid(); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + for (var i = 0; i < FieldList.Length; i++) + { + if (i % 2 == 0) grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + var box = DialogKit.TextBox(); + boxes[FieldList[i].Key] = box; + var field = DialogKit.Field(FieldList[i].Label, box); + field.Margin = new Thickness(i % 2 == 0 ? 0 : 10, 0, 0, 12); + Grid.SetRow(field, i / 2); + Grid.SetColumn(field, i % 2); + grid.Children.Add(field); + } + root.Children.Add(new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = grid }); + window.Content = root; + window.Loaded += async (_, _) => await PrefillAsync(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task PrefillAsync() + { + try + { + var latest = (await api.GetAsync>("/api/billing/notices?page=1&pageSize=200")) + .OrderByDescending(x => x.NoticeDate).ThenByDescending(x => x.NoticeNo, StringComparer.Ordinal).FirstOrDefault(); + if (latest is null) return; + var n = await api.GetAsync($"/api/billing/notices/{latest.Id}"); + boxes["invoiceTitle"].Text = n.InvoiceTitle ?? ""; + boxes["invoiceTitleAddress"].Text = n.InvoiceTitleAddress ?? ""; + boxes["invoiceTitlePhone"].Text = n.InvoiceTitlePhone ?? ""; + boxes["invoiceTitleBankName"].Text = n.InvoiceTitleBankName ?? ""; + boxes["invoiceTitleBankAccount"].Text = n.InvoiceTitleBankAccount ?? ""; + boxes["invoiceTitleTaxNo"].Text = n.InvoiceTitleTaxNo ?? ""; + boxes["invoiceTitleCustomsCode"].Text = n.InvoiceTitleCustomsCode ?? ""; + boxes["mailingAddress"].Text = n.MailingAddress ?? ""; + boxes["contactName"].Text = n.ContactName ?? ""; + } + catch (ApiException ex) + { + error.Text = $"读取上一份开票通知失败:{ex.Message}"; + } + } + + private string? Value(string key) => boxes[key].Text.Trim() is { Length: > 0 } text ? text : null; + + private async Task SaveAsync() + { + error.Text = string.Empty; + if (Value("invoiceTitle") is null) { error.Text = "请填写发票抬头。"; return; } + save.IsEnabled = false; + try + { + var request = new GenerateBillingNoticesRequest( + batch.Id, Value("exportInvoiceNo"), null, null, + Value("invoiceTitle"), Value("invoiceTitleAddress"), Value("invoiceTitlePhone"), Value("invoiceTitleBankName"), + Value("invoiceTitleBankAccount"), Value("invoiceTitleTaxNo"), Value("invoiceTitleCustomsCode"), + null, null, Value("contactName"), Value("mailingAddress"), Value("signedPlace"), null, + null, null, null, null, null, null); + var result = await api.PostAsync("/api/billing/notices/generate-from-shipping-batch", request); + Created = result.Notices; + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + finally + { + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/ContainerNumbersWindow.cs b/src/Leiren.Erp.Client/Documents/ContainerNumbersWindow.cs new file mode 100644 index 0000000..04f8903 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/ContainerNumbersWindow.cs @@ -0,0 +1,119 @@ +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Records the real container and seal numbers of a draft shipping batch +/// after loading; the packing wizard creates the containers with placeholder +/// numbers marked "柜号待补". +/// +public sealed class ContainerNumbersWindow +{ + private const string PendingRemark = "柜号待补"; + + private sealed record Row(ShippingContainerDto Container, TextBox Number, TextBox Seal); + + private readonly ApiClient api; + private readonly Guid batchId; + private readonly Window window; + private readonly StackPanel rows = new(); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button save = DialogKit.Primary("保存"); + private readonly List rowControls = []; + + public ContainerNumbersWindow(ApiClient api, Guid batchId, string batchNo, Window? owner) + { + this.api = api; + this.batchId = batchId; + window = DialogKit.Window(owner, $"柜号 / 封条号 · {batchNo}", 640, 460); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + save.IsEnabled = false; + save.Click += async (_, _) => await SaveAsync(); + + var root = new DockPanel { Margin = new Thickness(20) }; + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading("补录柜号与封条号")); + top.Children.Add(DialogKit.Note("装柜后填写实际集装箱号和封条号;确认出货前可以随时修改。")); + top.Children.Add(new Border { Height = 12 }); + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + var bottom = new StackPanel(); + bottom.Children.Add(error); + bottom.Children.Add(DialogKit.Buttons(cancel, save)); + DockPanel.SetDock(bottom, Dock.Bottom); + root.Children.Add(bottom); + root.Children.Add(new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = rows }); + window.Content = root; + window.Loaded += async (_, _) => await LoadAsync(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task LoadAsync() + { + try + { + var batch = await api.GetAsync($"/api/shipping-batches/{batchId}"); + foreach (var container in batch.Containers) + { + var pending = container.Remark == PendingRemark; + var number = DialogKit.TextBox(pending ? string.Empty : container.ContainerNo); + var seal = DialogKit.TextBox(container.SealNo ?? string.Empty); + var grid = new Grid { Margin = new Thickness(0, 0, 0, 6) }; + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(110) }); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(12) }); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.Children.Add(new TextBlock { Text = $"{container.ContainerType ?? "集装箱"}{(pending ? $"({container.ContainerNo})" : "")}", VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(0, 0, 0, 20), Foreground = DialogKit.Ink }); + var numberField = DialogKit.Field("集装箱号", number); + Grid.SetColumn(numberField, 1); + grid.Children.Add(numberField); + var sealField = DialogKit.Field("封条号", seal); + Grid.SetColumn(sealField, 3); + grid.Children.Add(sealField); + rows.Children.Add(grid); + rowControls.Add(new Row(container, number, seal)); + } + if (rowControls.Count == 0) rows.Children.Add(DialogKit.Note("该批次没有集装箱。")); + save.IsEnabled = rowControls.Count > 0; + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } + + private async Task SaveAsync() + { + error.Text = string.Empty; + save.IsEnabled = false; + try + { + foreach (var row in rowControls) + { + var number = row.Number.Text.Trim(); + var seal = row.Seal.Text.Trim(); + var pending = number.Length == 0; + var request = new SaveShippingContainerRequest( + pending ? row.Container.ContainerNo : number, + row.Container.ContainerType, + seal.Length == 0 ? null : seal, + pending ? PendingRemark : null); + if (request.ContainerNo == row.Container.ContainerNo && request.SealNo == row.Container.SealNo && request.Remark == row.Container.Remark) + continue; + await api.PutAsync($"/api/shipping-batches/{batchId}/containers/{row.Container.Id}", request); + } + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/CustomsDeclarationWindow.cs b/src/Leiren.Erp.Client/Documents/CustomsDeclarationWindow.cs new file mode 100644 index 0000000..ff54537 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/CustomsDeclarationWindow.cs @@ -0,0 +1,299 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// 报关资料 of one shipped batch. Opening a batch without a live declaration +/// creates a draft snapshot; the server prefills customs names, HS codes, +/// declaration elements, trade mode etc. from the latest confirmed +/// declaration of the same product / customer. Drafts are edited and saved +/// here; confirming (with a second confirmation) locks the declaration so the +/// customs documents and supplier billing read from it. A confirmed +/// declaration can only be voided, after which reopening creates a new +/// version. +/// +public sealed class CustomsDeclarationWindow +{ + private sealed record LineControls( + CustomsDeclarationLineDto Line, TextBox HsCode, TextBox NameZh, TextBox NameEn, TextBox Unit, + TextBox Elements, TextBox Origin, TextBox SourcePlace, TextBox Exemption, TextBox Quantity, TextBox UnitPrice); + + private readonly ApiClient api; + private readonly Guid batchId; + private readonly Window window; + private readonly StackPanel body = new(); + private readonly TextBlock status = DialogKit.Note(""); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button voidButton = DialogKit.Secondary("作废"); + private readonly Button save = DialogKit.Primary("保存"); + private readonly Button confirm = DialogKit.Primary("确认报关单"); + private readonly TextBox declarationNo = DialogKit.TextBox(); + private readonly TextBox invoiceNo = DialogKit.TextBox(); + private readonly TextBox exportDate = DialogKit.TextBox(); + private readonly TextBox declarationDate = DialogKit.TextBox(); + private readonly TextBox tradeMode = DialogKit.TextBox(); + private readonly TextBox exemptionNature = DialogKit.TextBox(); + private readonly TextBox remark = DialogKit.TextBox(); + private readonly List lines = []; + private CustomsDeclarationDto? declaration; + + public bool Changed { get; private set; } + + public CustomsDeclarationWindow(ApiClient api, Guid batchId, string batchNo, Window? owner) + { + this.api = api; + this.batchId = batchId; + window = DialogKit.Window(owner, $"报关资料 · {batchNo}", 1180, 820); + + var close = DialogKit.Secondary("关闭"); + close.Click += (_, _) => window.Close(); + voidButton.Click += async (_, _) => await VoidAsync(); + save.Click += async (_, _) => await SaveAsync(showToast: true); + confirm.Click += async (_, _) => await ConfirmAsync(); + confirm.Background = DialogKit.Green; + foreach (var b in new[] { voidButton, save, confirm }) b.IsEnabled = false; + + var root = new DockPanel { Margin = new Thickness(20) }; + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading($"报关资料 · {batchNo}")); + top.Children.Add(status); + top.Children.Add(new Border { Height = 10 }); + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + var bottom = new StackPanel(); + bottom.Children.Add(error); + bottom.Children.Add(DialogKit.Buttons(voidButton, close, save, confirm)); + DockPanel.SetDock(bottom, Dock.Bottom); + root.Children.Add(bottom); + root.Children.Add(new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = body }); + window.Content = root; + window.Loaded += async (_, _) => await LoadAsync(); + } + + public void ShowDialog() => window.ShowDialog(); + + private async Task LoadAsync() + { + error.Text = string.Empty; + try + { + var list = await api.GetAsync>($"/api/customs/?shippingBatchId={batchId}&page=1&pageSize=50"); + var live = list.Where(x => x.Status != "Voided").OrderByDescending(x => x.Version).FirstOrDefault(); + if (live is null) + { + declaration = await api.PostAsync("/api/customs/", + new CreateCustomsDeclarationRequest(batchId, null, null, null, null, null, null, null)); + Changed = true; + } + else + { + declaration = await api.GetAsync($"/api/customs/{live.Id}"); + } + Render(); + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } + + private void Render() + { + if (declaration is not { } d) return; + var draft = d.Status == "Draft"; + status.Text = draft + ? $"第 {d.Version} 版 · 草稿。报关品名、HS 编码、申报要素等已按该产品最近一次确认的报关单预填,没有历史的取产品资料。" + : $"第 {d.Version} 版 · 已确认({d.ConfirmedAt?.ToLocalTime():yyyy-MM-dd HH:mm} {d.ConfirmedBy})。报关单证和开票取数以此为准;如需修改请先作废,再重新打开生成新版本。"; + status.Foreground = draft ? DialogKit.Muted : DialogKit.Green; + save.IsEnabled = draft; + confirm.IsEnabled = draft; + save.Visibility = confirm.Visibility = draft ? Visibility.Visible : Visibility.Collapsed; + voidButton.IsEnabled = true; + + body.Children.Clear(); + lines.Clear(); + + body.Children.Add(Section("基本信息")); + body.Children.Add(DialogKit.Note( + $"{d.CustomerName} · 订单 {d.SalesOrderNo} · PO {d.CustomerPoNo ?? "—"} · {d.LoadingPort ?? "—"} → {d.DestinationPort ?? "—"} · 柜号 {d.ContainerNumbers ?? "—"}")); + body.Children.Add(new Border { Height = 8 }); + var header = Columns(4); + Place(header, 0, 0, "报关单号", Set(declarationNo, d.DeclarationNo, draft)); + Place(header, 0, 1, "发票编号(空则用出货批次号)", Set(invoiceNo, d.InvoiceNo, draft)); + Place(header, 0, 2, "出口日期 (yyyy-MM-dd)", Set(exportDate, d.ExportDate?.ToString("yyyy-MM-dd"), draft)); + Place(header, 0, 3, "申报日期 (yyyy-MM-dd)", Set(declarationDate, d.DeclarationDate?.ToString("yyyy-MM-dd"), draft)); + Place(header, 1, 0, "监管方式 / 贸易方式", Set(tradeMode, d.TradeMode, draft)); + Place(header, 1, 1, "征免性质", Set(exemptionNature, d.ExemptionNature, draft)); + Place(header, 1, 2, "备注", Set(remark, d.Remark, draft)); + body.Children.Add(header); + + body.Children.Add(Section($"报关明细({d.Lines.Count} 项 · 合计 {d.TotalQuantity:N0} · {d.Currency} {d.TotalAmount:N2} · {d.TotalCartonCount} 箱 · 毛重 {d.TotalGrossWeight:N1} kg)")); + foreach (var line in d.Lines.OrderBy(x => x.LineNumber)) + { + var controls = new LineControls(line, + Set(DialogKit.TextBox(), line.HsCode, draft), Set(DialogKit.TextBox(), line.CustomsNameZh, draft), + Set(DialogKit.TextBox(), line.CustomsNameEn, draft), Set(DialogKit.TextBox(), line.Unit, draft), + Set(DialogKit.TextBox(), line.DeclarationElements, draft), Set(DialogKit.TextBox(), line.OriginCountry, draft), + Set(DialogKit.TextBox(), line.DomesticSourcePlace, draft), Set(DialogKit.TextBox(), line.ExemptionInfo, draft), + Set(DialogKit.TextBox(), line.Quantity.ToString("0.####", CultureInfo.InvariantCulture), draft), + Set(DialogKit.TextBox(), line.UnitPrice.ToString("0.####", CultureInfo.InvariantCulture), draft)); + lines.Add(controls); + + var card = new StackPanel(); + card.Children.Add(new TextBlock + { + Text = $"{line.LineNumber}. {line.InternalSku} · {line.ProductNameZh} · {line.CartonCount} 箱 · 毛重 {line.TotalGrossWeight:N1} kg · 净重 {line.TotalNetWeight:N1} kg", + FontSize = 13, FontWeight = FontWeights.SemiBold, Foreground = DialogKit.Ink, Margin = new Thickness(0, 0, 0, 8), + }); + var grid = Columns(5); + Place(grid, 0, 0, "HS 编码", controls.HsCode); + Place(grid, 0, 1, "中文品名", controls.NameZh); + Place(grid, 0, 2, "英文品名", controls.NameEn); + Place(grid, 0, 3, "报关单位", controls.Unit); + Place(grid, 0, 4, "原产国", controls.Origin); + Place(grid, 1, 0, "境内货源地", controls.SourcePlace); + Place(grid, 1, 1, "征免", controls.Exemption); + Place(grid, 1, 2, "数量", controls.Quantity); + Place(grid, 1, 3, $"单价 ({d.Currency})", controls.UnitPrice); + Place(grid, 1, 4, "金额", new TextBlock { Text = line.Amount.ToString("N2"), FontSize = 13, Foreground = DialogKit.Ink, VerticalAlignment = VerticalAlignment.Center, Height = 32, Padding = new Thickness(0, 7, 0, 0) }); + card.Children.Add(grid); + card.Children.Add(DialogKit.Field("申报要素", controls.Elements)); + body.Children.Add(new Border + { + Background = System.Windows.Media.Brushes.White, BorderBrush = DialogKit.Line, BorderThickness = new Thickness(1), + CornerRadius = new CornerRadius(8), Padding = new Thickness(14), Margin = new Thickness(0, 0, 0, 10), Child = card, + }); + } + } + + private static TextBlock Section(string text) => new() + { + Text = text, FontSize = 13, FontWeight = FontWeights.SemiBold, Foreground = DialogKit.Ink, Margin = new Thickness(0, 10, 0, 8), + }; + + private static TextBox Set(TextBox box, string? value, bool editable) + { + box.Text = value ?? string.Empty; + box.IsReadOnly = !editable; + box.Background = editable ? System.Windows.Media.Brushes.White : DialogKit.Wash; + return box; + } + + private static Grid Columns(int count) + { + var grid = new Grid(); + for (var i = 0; i < count; i++) grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + return grid; + } + + private static void Place(Grid grid, int row, int column, string label, UIElement control) + { + var field = DialogKit.Field(label, control); + field.Margin = new Thickness(column == 0 ? 0 : 8, 0, 0, 10); + Grid.SetRow(field, row); + Grid.SetColumn(field, column); + grid.Children.Add(field); + } + + private static string? Optional(TextBox box) => box.Text.Trim() is { Length: > 0 } text ? text : null; + + private bool TryBuildRequest(out UpdateCustomsDeclarationRequest request) + { + request = null!; + DateOnly? ParseDate(TextBox box, string label) + { + if (Optional(box) is not { } text) return null; + if (DateOnly.TryParse(text, CultureInfo.InvariantCulture, out var date)) return date; + throw new FormatException($"{label}格式应为 yyyy-MM-dd。"); + } + try + { + var lineRequests = lines.Select(x => + { + if (!decimal.TryParse(x.Quantity.Text.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var quantity) || quantity <= 0) + throw new FormatException($"第 {x.Line.LineNumber} 项数量必须是大于 0 的数字。"); + if (!decimal.TryParse(x.UnitPrice.Text.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var price) || price < 0) + throw new FormatException($"第 {x.Line.LineNumber} 项单价必须是不小于 0 的数字。"); + return new UpdateCustomsLineRequest(x.Line.Id, Optional(x.HsCode), Optional(x.NameZh), Optional(x.NameEn), Optional(x.Unit), + Optional(x.Elements), Optional(x.Origin), Optional(x.SourcePlace), Optional(x.Exemption), quantity, price, x.Line.Remark); + }).ToList(); + request = new UpdateCustomsDeclarationRequest( + Optional(declarationNo), ParseDate(exportDate, "出口日期"), ParseDate(declarationDate, "申报日期"), + Optional(tradeMode), Optional(exemptionNature), Optional(remark), lineRequests, Optional(invoiceNo)); + return true; + } + catch (FormatException ex) + { + error.Text = ex.Message; + return false; + } + } + + private async Task SaveAsync(bool showToast) + { + if (declaration is null) return false; + error.Text = string.Empty; + if (!TryBuildRequest(out var request)) return false; + save.IsEnabled = confirm.IsEnabled = false; + try + { + declaration = await api.PutAsync($"/api/customs/{declaration.Id}", request); + Changed = true; + Render(); + if (showToast) status.Text = "已保存。" + status.Text; + return true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + save.IsEnabled = confirm.IsEnabled = true; + return false; + } + } + + private async Task ConfirmAsync() + { + if (declaration is null) return; + if (!await SaveAsync(showToast: false)) return; + var answer = MessageBox.Show(window, + $"确认报关单 {declaration.DeclarationNo ?? declaration.ShippingBatchNo}?确认后不能再修改,报关单证和开票将以此为准。", + "确认报关单", MessageBoxButton.YesNo, MessageBoxImage.Warning); + if (answer != MessageBoxResult.Yes) return; + try + { + declaration = await api.PostAsync($"/api/customs/{declaration.Id}/confirm", + new ConfirmCustomsDeclarationRequest(api.CurrentUser?.DisplayName ?? api.CurrentUser?.UserName)); + Changed = true; + Render(); + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } + + private async Task VoidAsync() + { + if (declaration is null) return; + var answer = MessageBox.Show(window, + $"作废第 {declaration.Version} 版报关资料?作废后重新打开会按历史信息生成新版本。", + "作废报关资料", MessageBoxButton.YesNo, MessageBoxImage.Warning); + if (answer != MessageBoxResult.Yes) return; + try + { + await api.PostAsync($"/api/customs/{declaration.Id}/void", null); + Changed = true; + window.Close(); + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/PayableConfirmWindow.cs b/src/Leiren.Erp.Client/Documents/PayableConfirmWindow.cs new file mode 100644 index 0000000..3f23fa6 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/PayableConfirmWindow.cs @@ -0,0 +1,82 @@ +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Confirms payment of one supplier payable. Entering the payment details is +/// the first confirmation; a second explicit dialog follows because a recorded +/// payment cannot be undone. +/// +public sealed class PayableConfirmWindow +{ + private readonly ApiClient api; + private readonly SupplierPayableDto payable; + private readonly Window window; + private readonly DatePicker paidDate = new() { SelectedDate = DateTime.Today, DisplayDateEnd = DateTime.Today, Height = 32 }; + private readonly TextBox reference = DialogKit.TextBox(); + private readonly TextBox remark = DialogKit.TextBox(); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button pay = DialogKit.Primary("确认付款"); + + public PayableConfirmWindow(ApiClient api, SupplierPayableDto payable, Window? owner) + { + this.api = api; + this.payable = payable; + window = DialogKit.Window(owner, $"确认付款 · {payable.ContractNo}", 560, 470); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + pay.Click += async (_, _) => await PayAsync(); + + var panel = new StackPanel { Margin = new Thickness(20) }; + panel.Children.Add(DialogKit.Heading($"{payable.SupplierName}")); + panel.Children.Add(DialogKit.Note($"采购合同 {payable.ContractNo} · 客户订单 {payable.CustomerOrderNo ?? "—"} · 付款条件 {payable.PaymentTerms ?? "未填"}")); + panel.Children.Add(new TextBlock + { + Text = $"{payable.Currency} {payable.Amount:N2}", + FontSize = 24, + FontWeight = FontWeights.SemiBold, + Foreground = DialogKit.Blue, + Margin = new Thickness(0, 12, 0, 14), + }); + panel.Children.Add(DialogKit.Field("付款日期", paidDate)); + panel.Children.Add(DialogKit.Field("付款凭证号 / 银行流水号(可选)", reference)); + panel.Children.Add(DialogKit.Field("备注(可选)", remark)); + panel.Children.Add(error); + panel.Children.Add(DialogKit.Buttons(cancel, pay)); + window.Content = panel; + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task PayAsync() + { + error.Text = string.Empty; + if (paidDate.SelectedDate is not { } date) { error.Text = "请选择付款日期。"; return; } + if (date.Date > DateTime.Today) { error.Text = "付款日期不能晚于今天。"; return; } + + var answer = MessageBox.Show(window, + $"确认已向 {payable.SupplierName} 支付 {payable.Currency} {payable.Amount:N2}({date:yyyy-MM-dd})?\n\n付款记录保存后不能撤销。", + "二次确认付款", MessageBoxButton.YesNo, MessageBoxImage.Warning); + if (answer != MessageBoxResult.Yes) return; + + pay.IsEnabled = false; + try + { + await api.PostAsync($"/api/payables/{payable.Id}/pay", new PaySupplierPayableRequest( + DateOnly.FromDateTime(date), + string.IsNullOrWhiteSpace(reference.Text) ? null : reference.Text.Trim(), + string.IsNullOrWhiteSpace(remark.Text) ? null : remark.Text.Trim(), + api.CurrentUser?.DisplayName ?? api.CurrentUser?.UserName)); + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + pay.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/SupplierInvoiceRegisterWindow.cs b/src/Leiren.Erp.Client/Documents/SupplierInvoiceRegisterWindow.cs new file mode 100644 index 0000000..daa4a8d --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/SupplierInvoiceRegisterWindow.cs @@ -0,0 +1,104 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Registers the VAT invoice a supplier returned for a confirmed 开票通知. +/// The amount defaults to what is still un-invoiced; excluding-tax amount and +/// tax are derived from the tax rate. +/// +public sealed class SupplierInvoiceRegisterWindow +{ + private readonly ApiClient api; + private readonly SupplierInvoiceNoticeListItemDto notice; + private readonly Window window; + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly TextBlock split = DialogKit.Note(""); + private readonly Button save = DialogKit.Primary("登记发票"); + private readonly TextBox invoiceNo = DialogKit.TextBox(); + private readonly TextBox invoiceDate = DialogKit.TextBox(DateTime.Today.ToString("yyyy-MM-dd")); + private readonly TextBox amount; + private readonly TextBox taxRate = DialogKit.TextBox("13"); + private readonly TextBox remark = DialogKit.TextBox(); + + public SupplierInvoiceRegisterWindow(ApiClient api, SupplierInvoiceNoticeListItemDto notice, Window? owner) + { + this.api = api; + this.notice = notice; + amount = DialogKit.TextBox(notice.RemainingAmountIncludingTax.ToString("0.00", CultureInfo.InvariantCulture)); + window = DialogKit.Window(owner, $"登记供应商发票 · {notice.SupplierName}", 620, 560); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + save.Click += async (_, _) => await SaveAsync(); + amount.TextChanged += (_, _) => UpdateSplit(); + taxRate.TextChanged += (_, _) => UpdateSplit(); + + var panel = new StackPanel { Margin = new Thickness(20) }; + panel.Children.Add(DialogKit.Heading($"登记供应商发票 · {notice.SupplierName}")); + panel.Children.Add(DialogKit.Note( + $"开票通知 {notice.NoticeNo} · 应开 {notice.Currency} {notice.TotalAmountIncludingTax:N2} · 已登记 {notice.InvoicedAmountIncludingTax:N2} · 待开 {notice.RemainingAmountIncludingTax:N2}")); + panel.Children.Add(new Border { Height = 12 }); + var grid = new Grid(); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + grid.ColumnDefinitions.Add(new ColumnDefinition()); + (string, UIElement)[] fields = [("发票号码", invoiceNo), ("开票日期 (yyyy-MM-dd)", invoiceDate), ("含税金额(元)", amount), ("税率 (%)", taxRate)]; + for (var i = 0; i < fields.Length; i++) + { + if (i % 2 == 0) grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + var field = DialogKit.Field(fields[i].Item1, fields[i].Item2); + field.Margin = new Thickness(i % 2 == 0 ? 0 : 10, 0, 0, 12); + Grid.SetRow(field, i / 2); + Grid.SetColumn(field, i % 2); + grid.Children.Add(field); + } + panel.Children.Add(grid); + panel.Children.Add(split); + panel.Children.Add(new Border { Height = 8 }); + panel.Children.Add(DialogKit.Field("备注", remark)); + panel.Children.Add(error); + panel.Children.Add(DialogKit.Buttons(cancel, save)); + window.Content = panel; + UpdateSplit(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private static decimal? Parse(TextBox box) + => decimal.TryParse(box.Text.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var value) ? value : null; + + private (decimal Excluding, decimal Tax)? Split() + { + if (Parse(amount) is not { } total || Parse(taxRate) is not { } rate) return null; + var excluding = decimal.Round(total / (1 + rate / 100m), 2, MidpointRounding.AwayFromZero); + return (excluding, total - excluding); + } + + private void UpdateSplit() + => split.Text = Split() is { } s ? $"不含税金额 {s.Excluding:N2} · 税额 {s.Tax:N2}" : "请填写有效的金额和税率。"; + + private async Task SaveAsync() + { + error.Text = string.Empty; + if (invoiceNo.Text.Trim().Length == 0) { error.Text = "请填写发票号码。"; return; } + if (!DateOnly.TryParse(invoiceDate.Text.Trim(), CultureInfo.InvariantCulture, out var date)) { error.Text = "开票日期格式应为 yyyy-MM-dd。"; return; } + if (Parse(amount) is not { } total || total <= 0 || Split() is not { } s) { error.Text = "含税金额必须大于 0,税率必须是数字。"; return; } + save.IsEnabled = false; + try + { + await api.PostAsync($"/api/billing/notices/{notice.Id}/invoices", new RegisterSupplierInvoiceRequest( + invoiceNo.Text.Trim(), null, "VatSpecial", date, DateOnly.FromDateTime(DateTime.Today), notice.Currency, + Parse(taxRate), s.Excluding, s.Tax, total, null, remark.Text.Trim() is { Length: > 0 } r ? r : null)); + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/TemplateImportWindow.cs b/src/Leiren.Erp.Client/Documents/TemplateImportWindow.cs new file mode 100644 index 0000000..8a11ad4 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/TemplateImportWindow.cs @@ -0,0 +1,147 @@ +using System.IO; +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Imports an XLSX template of any supported type, or uploads a new version +/// of an existing template (type fixed). The server scans the workbook and +/// rejects files without {{...}} placeholders. +/// +public sealed class TemplateImportWindow +{ + private readonly ApiClient api; + private readonly DocumentTemplateListItemDto? existing; + private readonly Window window; + private readonly TextBox path = DialogKit.TextBox(); + private readonly TextBox name = DialogKit.TextBox(); + private readonly ComboBox kind = new() { Height = 32, DisplayMemberPath = nameof(DocumentTemplateKindDto.DisplayName) }; + private readonly ComboBox customer = new() { Height = 32, DisplayMemberPath = nameof(CustomerChoice.Label) }; + + /// Customer a template is dedicated to; Id null = 通用(所有客户). + private sealed record CustomerChoice(Guid? Id, string Label); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button save = DialogKit.Primary("导入"); + + /// The uploaded template version, set when the dialog returns true. + public DocumentTemplateUploadResultDto? Result { get; private set; } + + public TemplateImportWindow(ApiClient api, IReadOnlyList kinds, Window? owner, DocumentTemplateListItemDto? existing = null) + { + this.api = api; + this.existing = existing; + window = DialogKit.Window(owner, existing is null ? "导入模板" : $"上传新版本 · {existing.Name}", 620, 500); + + path.IsReadOnly = true; + var browse = DialogKit.Secondary("选择文件…"); + browse.Margin = new Thickness(8, 0, 0, 0); + browse.Click += (_, _) => Browse(); + var pathRow = new DockPanel(); + DockPanel.SetDock(browse, Dock.Right); + pathRow.Children.Add(browse); + pathRow.Children.Add(path); + + kind.ItemsSource = kinds; + kind.SelectedItem = existing is null ? kinds.FirstOrDefault() : kinds.FirstOrDefault(x => x.Key == existing.DocumentKind); + kind.IsEnabled = existing is null; + name.Text = existing?.Name ?? string.Empty; + customer.IsEnabled = existing is null; + customer.ItemsSource = new[] { new CustomerChoice(existing?.CustomerId, existing?.CustomerName ?? "通用(所有客户)") }; + customer.SelectedIndex = 0; + kind.SelectionChanged += (_, _) => UpdateCustomerState(); + + var cancel = DialogKit.Secondary("取消"); + cancel.Click += (_, _) => window.DialogResult = false; + save.Content = existing is null ? "导入" : "上传新版本"; + save.Click += async (_, _) => await SaveAsync(); + + var panel = new StackPanel { Margin = new Thickness(20) }; + panel.Children.Add(DialogKit.Heading(existing is null ? "导入单证模板" : "上传模板新版本")); + panel.Children.Add(DialogKit.Note(existing is null + ? "支持报关单证、客户 CI/PL、采购合同、开票通知和开票购销合同模板(.xlsx)。单元格中用 {{字段}} 标出要填充的位置,明细行占位符所在行会按明细逐行复制。" + : "新版本保留模板类型;已用于生成单证的旧版本映射被锁定,新版本需要重新确认字段映射(会自动带入同名占位符的旧映射)。")); + panel.Children.Add(new Border { Height = 14 }); + panel.Children.Add(DialogKit.Field("模板文件(.xlsx)", pathRow)); + panel.Children.Add(DialogKit.Field("模板类型", kind)); + panel.Children.Add(DialogKit.Field("模板名称(可选,默认取文件名)", name)); + panel.Children.Add(DialogKit.Field("适用客户(客户专用模板生成单证时按批次客户自动勾选)", customer)); + panel.Children.Add(error); + panel.Children.Add(DialogKit.Buttons(cancel, save)); + window.Content = panel; + if (existing is null) window.Loaded += async (_, _) => await LoadCustomersAsync(); + UpdateCustomerState(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task LoadCustomersAsync() + { + try + { + var customers = await api.GetAsync>("/api/customers/?page=1&pageSize=200"); + customer.ItemsSource = new[] { new CustomerChoice(null, "通用(所有客户)") } + .Concat(customers.Where(x => x.IsActive).OrderBy(x => x.Name).Select(x => new CustomerChoice(x.Id, x.Name))) + .ToList(); + customer.SelectedIndex = 0; + } + catch (ApiException ex) + { + error.Text = $"加载客户失败:{ex.Message}"; + } + } + + /// Purchase-contract templates are never customer specific. + private void UpdateCustomerState() + { + var shipping = kind.SelectedItem is DocumentTemplateKindDto { UsesFieldMapping: true }; + customer.IsEnabled = existing is null && shipping; + if (!shipping && existing is null) customer.SelectedIndex = 0; + } + + private void Browse() + { + var dialog = new Microsoft.Win32.OpenFileDialog { Filter = "Excel 模板 (*.xlsx)|*.xlsx", CheckFileExists = true }; + if (dialog.ShowDialog(window) != true) return; + path.Text = dialog.FileName; + if (name.Text.Length == 0) name.Text = Path.GetFileNameWithoutExtension(dialog.FileName); + } + + private async Task SaveAsync() + { + error.Text = string.Empty; + if (!File.Exists(path.Text)) { error.Text = "请选择要导入的 .xlsx 模板文件。"; return; } + if (kind.SelectedItem is not DocumentTemplateKindDto selected) { error.Text = "请选择模板类型。"; return; } + + save.IsEnabled = false; + try + { + var fields = new Dictionary + { + ["name"] = name.Text.Trim(), + ["documentKind"] = selected.Key, + ["customerId"] = (customer.SelectedItem as CustomerChoice)?.Id?.ToString("D"), + ["uploadedBy"] = api.CurrentUser?.DisplayName ?? api.CurrentUser?.UserName, + }; + var url = existing is null + ? "/api/document-templates/upload" + : $"/api/document-templates/{existing.TemplateVersionId}/versions"; + Result = await api.UploadAsync(url, path.Text, fields); + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + catch (IOException ex) + { + error.Text = $"读取文件失败:{ex.Message}"; + } + finally + { + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/TemplateMappingWindow.cs b/src/Leiren.Erp.Client/Documents/TemplateMappingWindow.cs new file mode 100644 index 0000000..3c8b4e9 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/TemplateMappingWindow.cs @@ -0,0 +1,191 @@ +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Maps every placeholder of one template version to a business field. Rows +/// are prefilled from the saved mapping, else from the previous template +/// version's mapping, else from a business field with the same key. A mapping +/// already used to generate documents is locked and shown read-only. +/// +public sealed class TemplateMappingWindow +{ + private sealed record FieldOption(string? Key, string Label); + private sealed record Row(TemplatePlaceholderDto Placeholder, ComboBox Combo); + + private readonly ApiClient api; + private readonly DocumentTemplateListItemDto template; + private readonly Window window; + private readonly StackPanel rows = new(); + private readonly TextBlock status = DialogKit.Note("正在读取模板…"); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly Button save = DialogKit.Primary("保存映射"); + private readonly List rowControls = []; + private DocumentTemplateMappingProfileDto? profile; + + public TemplateMappingWindow(ApiClient api, DocumentTemplateListItemDto template, Window? owner) + { + this.api = api; + this.template = template; + window = DialogKit.Window(owner, $"字段映射 · {template.Name}", 860, 720); + + var cancel = DialogKit.Secondary("关闭"); + cancel.Click += (_, _) => window.DialogResult = false; + save.IsEnabled = false; + save.Click += async (_, _) => await SaveAsync(); + + var root = new DockPanel { Margin = new Thickness(20) }; + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading($"{template.Name} · v{template.Version}")); + top.Children.Add(DialogKit.Note("为每个 {{占位符}} 选择要填入的业务字段。选了“明细”字段的占位符所在行会按出货明细逐行复制填充;表头和合计字段只填一次。")); + top.Children.Add(status); + top.Children.Add(new Border { Height = 10 }); + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + + var bottom = new StackPanel(); + bottom.Children.Add(error); + bottom.Children.Add(DialogKit.Buttons(cancel, save)); + DockPanel.SetDock(bottom, Dock.Bottom); + root.Children.Add(bottom); + + root.Children.Add(new ScrollViewer + { + VerticalScrollBarVisibility = ScrollBarVisibility.Auto, + Content = new Border { Background = System.Windows.Media.Brushes.White, BorderBrush = DialogKit.Line, BorderThickness = new Thickness(1), Padding = new Thickness(12), Child = rows }, + }); + window.Content = root; + window.Loaded += async (_, _) => await LoadAsync(); + } + + public bool? ShowDialog() => window.ShowDialog(); + + private async Task TryGetProfileAsync(Guid templateVersionId) + { + try + { + return await api.GetAsync($"/api/document-templates/{templateVersionId}/mapping-profile"); + } + catch (ApiException ex) when (ex.StatusCode == 404) + { + return null; + } + } + + private async Task LoadAsync() + { + try + { + var fields = await api.GetAsync>("/api/document-templates/fields"); + var scan = await api.GetAsync($"/api/document-templates/{template.TemplateVersionId}/scan"); + profile = await TryGetProfileAsync(template.TemplateVersionId); + + // A new template version starts from the previous version's choices. + Dictionary suggestions = new(StringComparer.OrdinalIgnoreCase); + var source = profile; + if (source is null) + { + var file = await api.GetAsync($"/api/files/{template.TemplateVersionId}"); + if (file.PreviousVersionId is { } previous) source = await TryGetProfileAsync(previous); + } + foreach (var m in source?.Mappings ?? []) suggestions[m.Placeholder] = m.BusinessField; + + var options = Options(fields.OrderBy(x => x.Scope switch { "Header" => 0, "Line" => 1, _ => 2 })); + foreach (var placeholder in scan.Placeholders) + { + var preferred = suggestions.GetValueOrDefault(placeholder.Name) + ?? fields.FirstOrDefault(x => string.Equals(x.Key, placeholder.Name, StringComparison.OrdinalIgnoreCase))?.Key; + var combo = new ComboBox + { + Height = 30, + ItemsSource = options, + DisplayMemberPath = nameof(FieldOption.Label), + SelectedItem = options.FirstOrDefault(x => x.Key is not null && string.Equals(x.Key, preferred, StringComparison.OrdinalIgnoreCase)) ?? options[0], + IsEnabled = profile?.IsLocked != true, + }; + combo.SelectionChanged += (_, _) => UpdateStatus(); + rowControls.Add(new Row(placeholder, combo)); + rows.Children.Add(RowView(placeholder, combo)); + } + + save.IsEnabled = profile?.IsLocked != true && rowControls.Count > 0; + UpdateStatus(); + } + catch (ApiException ex) + { + status.Text = string.Empty; + error.Text = ex.Message; + } + } + + private static List Options(IEnumerable fields) + { + var scopeName = new Dictionary { ["Header"] = "表头", ["Line"] = "明细", ["Total"] = "合计" }; + var list = new List { new(null, "(未映射)") }; + list.AddRange(fields.Select(x => new FieldOption(x.Key, $"{scopeName.GetValueOrDefault(x.Scope, x.Scope)} · {x.DisplayName}({x.Key})"))); + return list; + } + + private static UIElement RowView(TemplatePlaceholderDto placeholder, ComboBox combo) + { + var grid = new Grid { Margin = new Thickness(0, 0, 0, 8) }; + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1.4, GridUnitType.Star) }); + var info = new StackPanel { VerticalAlignment = VerticalAlignment.Center }; + info.Children.Add(new TextBlock { Text = placeholder.RawToken, FontWeight = FontWeights.SemiBold, Foreground = DialogKit.Ink }); + var where = placeholder.Locations.FirstOrDefault(); + info.Children.Add(new TextBlock + { + Text = $"{where?.Worksheet}!{where?.CellAddress}{(placeholder.OccurrenceCount > 1 ? $" 等 {placeholder.OccurrenceCount} 处" : "")}", + FontSize = 11, + Foreground = DialogKit.Muted, + }); + grid.Children.Add(info); + Grid.SetColumn(combo, 1); + grid.Children.Add(combo); + return grid; + } + + private void UpdateStatus() + { + var mapped = rowControls.Count(x => (x.Combo.SelectedItem as FieldOption)?.Key is not null); + status.Text = profile?.IsLocked == true + ? "该版本已用于生成单证,映射已锁定;如需修改请上传模板新版本。" + : $"已映射 {mapped} / {rowControls.Count} 个占位符{(mapped < rowControls.Count ? ",未映射的占位符在预览中保持原样,生成单证前必须全部映射" : ",可以用于生成单证")}。"; + status.Foreground = profile?.IsLocked == true || mapped < rowControls.Count ? DialogKit.Orange : DialogKit.Green; + } + + private async Task SaveAsync() + { + error.Text = string.Empty; + save.IsEnabled = false; + try + { + var mappings = rowControls + .Where(x => (x.Combo.SelectedItem as FieldOption)?.Key is not null) + .Select(x => new SaveDocumentTemplateFieldMappingRequest( + x.Placeholder.Name, + ((FieldOption)x.Combo.SelectedItem).Key, + profile?.Mappings.FirstOrDefault(m => string.Equals(m.Placeholder, x.Placeholder.Name, StringComparison.OrdinalIgnoreCase))?.NumberFormat)) + .ToList(); + profile = profile is null + ? await api.PostAsync( + $"/api/document-templates/{template.TemplateVersionId}/mapping-profile", + new CreateDocumentTemplateMappingProfileRequest( + template.TemplateId, null, template.DocumentKind, + rowControls.Select(x => x.Placeholder.Name).ToList(), mappings)) + : await api.PutAsync( + $"/api/document-templates/{template.TemplateVersionId}/mappings", + new ReplaceDocumentTemplateFieldMappingsRequest(mappings)); + window.DialogResult = true; + } + catch (ApiException ex) + { + error.Text = ex.Message; + save.IsEnabled = true; + } + } +} diff --git a/src/Leiren.Erp.Client/Documents/TemplatePreviewWindow.cs b/src/Leiren.Erp.Client/Documents/TemplatePreviewWindow.cs new file mode 100644 index 0000000..718a728 --- /dev/null +++ b/src/Leiren.Erp.Client/Documents/TemplatePreviewWindow.cs @@ -0,0 +1,163 @@ +using System.IO; +using System.Windows; +using System.Windows.Controls; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Contracts; + +namespace Leiren.Erp.Client.Documents; + +/// +/// Renders a template against chosen test data (a shipping batch, or a +/// purchase contract for purchase-contract templates) with the real XLSX +/// renderer. Nothing is stored; unmapped placeholders stay visible. +/// +public sealed class TemplatePreviewWindow +{ + private sealed record TestData(Guid Id, string Label); + + private readonly ApiClient api; + private readonly DocumentTemplateListItemDto template; + private readonly DocumentTemplateKindDto kind; + private readonly Window window; + private readonly ComboBox data = new() { Height = 32, MinWidth = 420, DisplayMemberPath = nameof(TestData.Label) }; + private readonly Button render = DialogKit.Primary("预览"); + private readonly Button saveAs = DialogKit.Secondary("另存为 xlsx"); + private readonly TextBlock error = DialogKit.Note("", DialogKit.Error); + private readonly XlsxPreviewView preview = new(); + private byte[]? lastRendered; + + private bool UsesContract => kind.DataSource == "PurchaseContract"; + private bool UsesNotice => kind.DataSource == "SupplierInvoiceNotice"; + private string DataLabel => UsesContract ? "测试采购合同" : UsesNotice ? "测试开票通知" : "测试出货批次"; + + public TemplatePreviewWindow(ApiClient api, DocumentTemplateListItemDto template, DocumentTemplateKindDto kind, Window? owner) + { + this.api = api; + this.template = template; + this.kind = kind; + window = DialogKit.Window(owner, $"预览测试 · {template.Name}", 1200, 840); + + render.Click += async (_, _) => await RenderAsync(); + saveAs.IsEnabled = false; + saveAs.Click += async (_, _) => await SaveAsAsync(); + + var bar = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 10, 0, 8) }; + bar.Children.Add(new TextBlock { Text = DataLabel, VerticalAlignment = VerticalAlignment.Center, Foreground = DialogKit.Muted, Margin = new Thickness(0, 0, 8, 0) }); + bar.Children.Add(data); + render.Margin = new Thickness(10, 0, 0, 0); + bar.Children.Add(render); + saveAs.Margin = new Thickness(10, 0, 0, 0); + bar.Children.Add(saveAs); + + var top = new StackPanel(); + top.Children.Add(DialogKit.Heading($"{kind.DisplayName} · {template.Name} · v{template.Version}")); + top.Children.Add(DialogKit.Note(template.UnmappedPlaceholders.Count == 0 + ? "选择测试数据后预览。单击预览放大到 100%,按住拖动查看,再次单击恢复适应窗口。" + : $"还有 {template.UnmappedPlaceholders.Count} 个占位符未{(kind.UsesFieldMapping ? "映射" : "识别")}({string.Join("、", template.UnmappedPlaceholders.Take(8).Select(x => "{{" + x + "}}"))}),预览中保持原样。", + template.UnmappedPlaceholders.Count == 0 ? null : DialogKit.Orange)); + top.Children.Add(bar); + top.Children.Add(error); + + var close = DialogKit.Secondary("关闭"); + close.Click += (_, _) => window.Close(); + + var root = new DockPanel { Margin = new Thickness(16) }; + DockPanel.SetDock(top, Dock.Top); + root.Children.Add(top); + var buttons = DialogKit.Buttons(close); + DockPanel.SetDock(buttons, Dock.Bottom); + root.Children.Add(buttons); + root.Children.Add(preview); + window.Content = root; + preview.ShowMessage("选择测试数据后点击“预览”。"); + window.Loaded += async (_, _) => await LoadDataAsync(); + } + + public void ShowDialog() => window.ShowDialog(); + + private async Task LoadDataAsync() + { + try + { + List items; + if (UsesContract) + { + var contracts = await api.GetAsync>("/api/purchase-contracts/?page=1&pageSize=200"); + items = contracts + .Where(x => x.Status != "Voided" && x.TaskCount > 0) + .Select(x => new TestData(x.Id, $"{x.ContractNo} · {x.SupplierName} · {x.CustomerOrderNo} · {x.Status}")) + .ToList(); + } + else if (UsesNotice) + { + var notices = await api.GetAsync>("/api/billing/notices?page=1&pageSize=200"); + items = notices + .Where(x => x.Status != "Voided") + .Select(x => new TestData(x.Id, $"{x.NoticeNo} · {x.SupplierName} · 出货 {x.ShipmentNo ?? "—"}")) + .ToList(); + } + else + { + var batches = await api.GetAsync>("/api/shipping-batches?page=1&pageSize=200"); + items = batches + .Where(x => x.Status != "Cancelled" && x.LineCount > 0) + .Select(x => new TestData(x.Id, $"{x.BatchNo} · {x.SalesOrderNo} · {x.CustomerName} · {(x.Status == "Confirmed" ? "已出货" : "待确认出货")}")) + .ToList(); + } + data.ItemsSource = items; + data.SelectedItem = items.FirstOrDefault(); + render.IsEnabled = items.Count > 0; + if (items.Count == 0) + preview.ShowMessage(UsesContract ? "没有可用作测试数据的采购合同。" + : UsesNotice ? "没有可用作测试数据的开票通知,请先在出货与报关中为已出货批次生成开票通知。" + : "没有可用作测试数据的出货批次,请先在出货与报关中装箱。"); + } + catch (ApiException ex) + { + error.Text = ex.Message; + } + } + + private async Task RenderAsync() + { + if (data.SelectedItem is not TestData selected) return; + error.Text = string.Empty; + render.IsEnabled = false; + try + { + var request = UsesContract ? new PreviewDocumentTemplateRequest(null, selected.Id) + : UsesNotice ? new PreviewDocumentTemplateRequest(null, null, selected.Id) + : new PreviewDocumentTemplateRequest(selected.Id, null); + preview.ShowMessage("正在生成预览…"); + lastRendered = await api.PostBytesAsync($"/api/document-templates/{template.TemplateVersionId}/preview", request); + await preview.ShowAsync(lastRendered); + saveAs.IsEnabled = true; + } + catch (ApiException ex) + { + preview.ShowMessage("预览失败"); + error.Text = ex.Message; + } + catch (Exception ex) + { + preview.ShowMessage("预览失败"); + error.Text = $"渲染预览失败:{ex.Message}"; + } + finally + { + render.IsEnabled = true; + } + } + + private async Task SaveAsAsync() + { + if (lastRendered is null) return; + var dialog = new Microsoft.Win32.SaveFileDialog + { + FileName = $"{template.Name}-预览.xlsx", + Filter = "Excel 工作簿 (*.xlsx)|*.xlsx", + }; + if (dialog.ShowDialog(window) != true) return; + await File.WriteAllBytesAsync(dialog.FileName, lastRendered); + } +} diff --git a/src/Leiren.Erp.Client/Leiren.Erp.Client.csproj b/src/Leiren.Erp.Client/Leiren.Erp.Client.csproj new file mode 100644 index 0000000..bfc647f --- /dev/null +++ b/src/Leiren.Erp.Client/Leiren.Erp.Client.csproj @@ -0,0 +1,18 @@ + + + + WinExe + net11.0-windows + enable + enable + true + + + + + + + + + + diff --git a/src/Leiren.Erp.Client/LoginWindow.xaml b/src/Leiren.Erp.Client/LoginWindow.xaml new file mode 100644 index 0000000..c9cf7c6 --- /dev/null +++ b/src/Leiren.Erp.Client/LoginWindow.xaml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Leiren.Erp.Client/MainWindow.xaml.cs b/src/Leiren.Erp.Client/MainWindow.xaml.cs new file mode 100644 index 0000000..f75b588 --- /dev/null +++ b/src/Leiren.Erp.Client/MainWindow.xaml.cs @@ -0,0 +1,176 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; +using Leiren.Erp.Client.Controls; +using Leiren.Erp.Client.Pages; +using Leiren.Erp.Client.Wizards; + +namespace Leiren.Erp.Client; + +public partial class MainWindow : Window +{ + private static readonly Brush ActiveNavBackground = new SolidColorBrush(Color.FromRgb(0x20, 0x3B, 0x5E)); + private static readonly Brush InactiveNavForeground = new SolidColorBrush(Color.FromRgb(0xA9, 0xB8, 0xCA)); + + private readonly ClientSettings clientSettings; + private readonly ApiClient apiClient; + private readonly Func signIn; + private FlowWorkspace? workspace; + private Button? activeNavButton; + + /// Shows the login window again after logout; null result closes the app. + public MainWindow(ApiClient apiClient, ClientSettings clientSettings, LoginResponse session, Func signIn) + { + this.apiClient = apiClient; + this.clientSettings = clientSettings; + this.signIn = signIn; + InitializeComponent(); + ShowShell(session); + } + + private void ShowShell(LoginResponse result) + { + var display = string.IsNullOrWhiteSpace(result.DisplayName) ? result.UserName : result.DisplayName; + SideUserText.Text = display; + SideAccountText.Text = $"账号 {result.UserName}"; + UserAvatarText.Text = string.IsNullOrWhiteSpace(display) ? "?" : display[..1]; + ToastText.Text = string.Empty; + workspace ??= new FlowWorkspace(apiClient, HandleWorkspaceNavigation, ShowToast); + PageHost.Content = workspace; + var first = NavPanel.Children.OfType