Initial commit

This commit is contained in:
2026-11-16 18:25:21 +08:00
commit c7264cc50d
229 changed files with 33543 additions and 0 deletions
@@ -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<string, Guid> sessions,
PasswordHasher<AppUser> 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<string, string[]> { ["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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
+127
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
public static class BearerAuthorization
{
public static bool TryGetUserId(HttpContext context, ConcurrentDictionary<string, Guid> 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);
}
/// <summary>Returns null when authorized; otherwise the 401/403 result to return.</summary>
public static async Task<IResult?> AuthorizeAsync(
HttpContext context,
ConcurrentDictionary<string, Guid> sessions,
string requiredPermission,
CancellationToken cancellationToken = default)
{
if (!TryGetUserId(context, sessions, out var userId))
{
return Unauthorized();
}
var database = context.RequestServices.GetRequiredService<ErpDbContext>();
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<IdentityService>();
return await identity.HasPermissionAsync(user.Id, requiredPermission, cancellationToken)
? null
: Forbidden($"缺少权限:{requiredPermission}");
}
public static async Task<AppUser?> GetCurrentUserAsync(
HttpContext context,
ConcurrentDictionary<string, Guid> sessions,
CancellationToken cancellationToken = default)
{
if (!TryGetUserId(context, sessions, out var userId)) return null;
var database = context.RequestServices.GetRequiredService<ErpDbContext>();
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);
/// <summary>Permission required for a business route, or null when the route is not authorization-protected here.</summary>
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;
}
}
+122
View File
@@ -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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
+141
View File
@@ -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<string, Guid> 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<string, Guid> 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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
@@ -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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
+94
View File
@@ -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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
+14
View File
@@ -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;
}
}
@@ -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<IFormCollection> 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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
@@ -0,0 +1,104 @@
using Leiren.Erp.Application.Customs;
using Leiren.Erp.Contracts;
namespace Leiren.Erp.Api;
/// <summary>
/// Versioned placeholder-to-business-field mapping CRUD for scanned XLSX
/// document templates. <c>{templateVersionId}</c> 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.
/// </summary>
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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
+129
View File
@@ -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<IFormCollection> 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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
+40
View File
@@ -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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
+129
View File
@@ -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<HealthCheckResult> Checks);
/// <summary>
/// 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).
/// </summary>
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<IResult> RunReadinessAsync(HttpContext context, ErpDbContext database)
{
var configuration = context.RequestServices.GetRequiredService<IConfiguration>();
var timeout = DefaultDatabaseTimeout;
if (TimeSpan.TryParse(configuration["HealthChecks:DatabaseTimeout"], out var configured) && configured > TimeSpan.Zero)
{
timeout = configured;
}
var checks = new List<HealthCheckResult>
{
await CheckDatabaseAsync(database, timeout, context.RequestAborted),
CheckFileStorage(context.RequestServices.GetRequiredService<FileStorageOptions>()),
};
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<HealthCheckResult> 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 */ }
}
}
}
}
+28
View File
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="11.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="11.0.0-rc.3.26522.148">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="11.0.0-rc.3.26522.148" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Leiren.Erp.Application\Leiren.Erp.Application.csproj" />
<ProjectReference Include="..\Leiren.Erp.Infrastructure\Leiren.Erp.Infrastructure.csproj" />
<ProjectReference Include="..\Leiren.Erp.Contracts\Leiren.Erp.Contracts.csproj" />
</ItemGroup>
<ItemGroup>
<Content Include="templates\**\*" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project>
+54
View File
@@ -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 <accessToken> with the accessToken returned by login.
GET {{Leiren.Erp.Api_HostAddress}}/api/auth/me
Authorization: Bearer <accessToken>
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
+64
View File
@@ -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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
+398
View File
@@ -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<ICatalogDbContext>(sp => sp.GetRequiredService<ErpDbContext>());
builder.Services.AddScoped<ISalesDbContext>(sp => sp.GetRequiredService<ErpDbContext>());
builder.Services.AddScoped<IPurchasingDbContext>(sp => sp.GetRequiredService<ErpDbContext>());
builder.Services.AddScoped<IShippingDbContext>(sp => sp.GetRequiredService<ErpDbContext>());
builder.Services.AddScoped<IFilesDbContext>(sp => sp.GetRequiredService<ErpDbContext>());
builder.Services.AddScoped<IBillingDbContext>(sp => sp.GetRequiredService<ErpDbContext>());
builder.Services.AddScoped<IFinanceDbContext>(sp => sp.GetRequiredService<ErpDbContext>());
builder.Services.AddScoped<IIdentityDbContext>(sp => sp.GetRequiredService<ErpDbContext>());
builder.Services.AddScoped<ICustomsDbContext>(sp => sp.GetRequiredService<ErpDbContext>());
builder.Services.AddScoped<IDocumentTemplateMappingDbContext>(sp => sp.GetRequiredService<ErpDbContext>());
builder.Services.AddScoped<IMasterDataDbContext>(sp => sp.GetRequiredService<ErpDbContext>());
builder.Services.AddScoped<IDashboardDbContext>(sp => sp.GetRequiredService<ErpDbContext>());
builder.Services.AddScoped<DashboardService>();
builder.Services.AddScoped<DocumentTemplateMappingService>();
builder.Services.AddScoped<ProductService>();
builder.Services.AddScoped<SupplierService>();
builder.Services.AddScoped<SalesOrderService>();
builder.Services.AddScoped<PoExcelImportService>();
builder.Services.AddScoped<PurchaseService>();
builder.Services.AddScoped<PurchaseContractExportService>();
builder.Services.AddScoped<DocumentTemplateCatalogService>();
builder.Services.AddScoped<ShippingService>();
builder.Services.AddScoped<FileService>();
builder.Services.AddScoped<DocumentTemplateService>();
// 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<BillingDocumentExportService>();
builder.Services.AddSingleton<IFileStorage, LocalFileStorage>();
builder.Services.AddScoped<BillingService>();
builder.Services.AddScoped<PayableService>();
builder.Services.AddScoped<CustomsService>();
builder.Services.AddScoped<CiPlDocumentGenerationService>();
builder.Services.AddScoped<IdentityService>();
builder.Services.AddOpenApi();
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ErpDbContext>();
// 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<PayableService>().BackfillAsync();
var identityService = scope.ServiceProvider.GetRequiredService<IdentityService>();
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<AppUser>();
var sessions = new ConcurrentDictionary<string, Guid>(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<Guid, string> createAccessToken = userId =>
{
var accessToken = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
sessions[accessToken] = userId;
return accessToken;
};
Func<string, string> hashRefreshToken = static token =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
Func<Guid, (string Token, RefreshSession Session)> 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<string, string[]>
{
["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<string, string[]>
{
["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<string, string[]>
{
["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<string, string[]>
{
["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();
@@ -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"
}
}
}
}
+128
View File
@@ -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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
+85
View File
@@ -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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
@@ -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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
+87
View File
@@ -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<IResult> Handle(Func<Task<IResult>> 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);
}
}
}
@@ -0,0 +1,14 @@
{
"ConnectionStrings": {
"Default": "Data Source=data/leiren-dev.db"
},
"Database": {
"Provider": "Sqlite"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
+27
View File
@@ -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"
]
}
}
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,77 @@
using Leiren.Erp.Application.Documents;
using Leiren.Erp.Application.Files;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Billing;
/// <summary>Absolute paths of the built-in 开票通知 / 开票购销合同 templates.</summary>
public sealed record BillingTemplateOptions(string NoticeTemplatePath, string ContractTemplatePath);
/// <summary>
/// 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.
/// </summary>
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");
}
/// <summary>Renders a template file against a notice for the template editor preview.</summary>
public async Task<byte[]> 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<byte[]> 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;
}
}
@@ -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;
/// <summary>
/// Renders the supplier 开票通知书 and 开票用产品购销合同 from a notice
/// snapshot (whose lines were taken from the customs declaration) through
/// <see cref="TokenWorkbookRenderer"/>. Both document types share one
/// built-in placeholder catalog.
/// </summary>
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<string>(StringComparer.OrdinalIgnoreCase)
{
"LineNumber", "ProductName", "ProductNameEn", "InternalSku", "CustomerSku", "Specification", "Quantity", "Unit",
"TaxIncludedUnitPrice", "TaxExcludingUnitPrice", "AmountIncludingTax", "AmountExcludingTax", "TaxAmount", "TaxRate",
"LinePurchaseContractNo",
},
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"LineNumber", "Quantity", "TaxIncludedUnitPrice", "TaxExcludingUnitPrice", "AmountIncludingTax", "AmountExcludingTax",
"TaxAmount", "TaxRate", "LineCount", "TotalQuantity", "TotalAmountIncludingTax", "TotalAmountExcludingTax", "TotalTaxAmount",
},
new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "NoticeDate", "ShipmentDate", "SignedDate" });
/// <summary>Every placeholder name a 开票通知 / 开票购销合同 template may use.</summary>
public static IReadOnlyList<string> 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<string, string?>)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<string, string?> 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<string, string?> 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,
};
/// <summary>Chinese uppercase RMB amount, e.g. 66211.20 → 陆万陆仟贰佰壹拾壹元贰角.</summary>
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<int>();
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;
}
}
@@ -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<string, string[]> errors)
: Exception("供应商开票资料校验失败。")
{
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
public BillingValidationException(string field, string message)
: this(new Dictionary<string, string[]> { [field] = [message] })
{
}
}
@@ -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<IReadOnlyList<SupplierInvoiceNoticeListItemDto>> 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<SupplierInvoiceNoticeStatus>(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<SupplierInvoiceNoticeDto> GetNoticeAsync(Guid id, CancellationToken ct = default)
=> ToDto(await LoadNoticeAsync(id, ct));
public async Task<SupplierInvoiceNoticeDto> 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));
}
/// <summary>
/// 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).
/// </summary>
public async Task<GenerateBillingNoticesResultDto> 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<string, List<(CustomsDeclarationLine Declared, ShipmentLine Shipment, List<PurchaseTask> 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<SupplierInvoiceNotice>();
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<SupplierInvoiceNoticeDto>();
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);
/// <summary>
/// Splits a declared quantity between suppliers in proportion to their
/// amounts; the parts always add up to <paramref name="total"/>. Whole
/// quantities stay whole (largest remainder) and every supplier gets at
/// least one unit when there are enough; otherwise thousandths are used.
/// </summary>
internal static decimal[] AllocateQuantity(decimal total, IReadOnlyList<decimal> 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<SupplierInvoiceNoticeDto> 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<SupplierInvoiceNoticeDto> 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<SupplierInvoiceNoticeDto> 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);
}
/// <summary>
/// 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.
/// </summary>
public async Task<IReadOnlyList<SupplierInvoiceNoticeDto>> 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();
}
/// <summary>
/// Final confirmation of a batch's billing: every draft notice is locked
/// and sent to its supplier. Quantities must match the declaration.
/// </summary>
public async Task<IReadOnlyList<SupplierInvoiceNoticeDto>> 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<List<SupplierInvoiceNotice>> 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;
}
/// <summary>Per customs item, the suppliers' invoiced quantities must equal the declared quantity.</summary>
private async Task EnsureDeclaredTotalsAsync(Guid shippingBatchId, IReadOnlyList<SupplierInvoiceNotice> 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<SupplierBillingContractDto> 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<SupplierBillingContractDto> 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<IReadOnlyList<SupplierInvoiceDto>> 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<SupplierInvoiceStatus>(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<SupplierInvoiceDto> GetInvoiceAsync(Guid id, CancellationToken ct = default)
=> ToDto(await LoadInvoiceAsync(id, ct));
public async Task<SupplierInvoiceDto> 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<SupplierInvoiceDto> 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<SupplierInvoiceDto> 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<string> 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<SupplierInvoiceNotice> 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<SupplierInvoice> 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<SupplierInvoiceType>(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);
}
@@ -0,0 +1,26 @@
using Leiren.Erp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Billing;
/// <summary>
/// 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.
/// </summary>
public interface IBillingDbContext
{
DbSet<SupplierInvoiceNotice> SupplierInvoiceNotices { get; }
DbSet<SupplierInvoiceNoticeLine> SupplierInvoiceNoticeLines { get; }
DbSet<SupplierInvoice> SupplierInvoices { get; }
DbSet<SupplierBillingContract> SupplierBillingContracts { get; }
DbSet<ShippingBatch> ShippingBatches { get; }
DbSet<ShipmentLine> ShipmentLines { get; }
DbSet<PurchaseTask> PurchaseTasks { get; }
DbSet<PurchaseContract> PurchaseContracts { get; }
DbSet<SalesOrderLine> SalesOrderLines { get; }
DbSet<Supplier> Suppliers { get; }
DbSet<CustomsDeclaration> CustomsDeclarations { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
@@ -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<string, string[]> errors)
: Exception("产品资料校验失败。")
{
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
public CatalogValidationException(string field, string message)
: this(new Dictionary<string, string[]> { [field] = [message] })
{
}
}
@@ -0,0 +1,16 @@
using Leiren.Erp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Catalog;
/// <summary>EF Core boundary for the Catalog module; implemented by Infrastructure.</summary>
public interface ICatalogDbContext
{
DbSet<Product> Products { get; }
DbSet<Supplier> Suppliers { get; }
DbSet<ProductPart> ProductParts { get; }
DbSet<ProductSupplierQuote> ProductSupplierQuotes { get; }
DbSet<ProductChangeLog> ProductChangeLogs { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
@@ -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<IReadOnlyList<ProductListItemDto>> 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<ProductStatus>(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<ProductDto> GetAsync(Guid id, CancellationToken ct = default)
=> ToDto(await LoadAsync(id, ct));
public async Task<ProductCompletenessDto> GetCompletenessAsync(Guid id, CancellationToken ct = default)
=> BuildCompleteness(await LoadAsync(id, ct));
public async Task<IReadOnlyList<ProductChangeLogDto>> 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();
}
/// <summary>
/// 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.
/// </summary>
public static ProductCompletenessDto BuildCompleteness(Product product)
{
var required = product.GetMissingPublishFields();
var purchase = new List<string>();
if (product.SupplierQuotes.Count == 0) purchase.Add("SupplierQuote");
if (string.IsNullOrWhiteSpace(product.PurchaseRequirement)) purchase.Add(nameof(Product.PurchaseRequirement));
var shipping = new List<string>();
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<string>();
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<ProductDto> 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<ProductDto> 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<ProductDto> 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<ProductDto> 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<ProductPartDto> 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<ProductPartDto> 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<SupplierQuoteDto> 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<SupplierQuoteDto> 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<QuoteValues> 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<PurchaseContentType>(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<string, string?> 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<Product> 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<Product> 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<Guid, Guid>();
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<ProductType>(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<T>(string? value, T? fallback, string field) where T : struct, Enum
{
if (string.IsNullOrWhiteSpace(value))
{
return fallback ?? throw new CatalogValidationException(field, $"{field} 不能为空。");
}
return Enum.TryParse<T>(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<T>(string? value, T fallback, string field) where T : struct, Enum
=> string.IsNullOrWhiteSpace(value) ? fallback : ParseEnum<T>(value, (T?)null, field);
private static string? TrimOrNull(string? value)
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private void AddChangeLog(Product product, ProductChangeAction action, IReadOnlyList<string> 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<string> fields;
try { fields = JsonSerializer.Deserialize<List<string>>(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<string> ChangedFields(
IReadOnlyDictionary<string, string?> before, IReadOnlyDictionary<string, string?> after)
=> after.Keys.Where(k => !string.Equals(before.GetValueOrDefault(k), after[k], StringComparison.Ordinal)).ToList();
private static IReadOnlyList<string> NonEmptyFields(IReadOnlyDictionary<string, string?> 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<string, string?> 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<string, string?> 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());
}
+6
View File
@@ -0,0 +1,6 @@
namespace Leiren.Erp.Application;
public class Class1
{
}
@@ -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;
/// <summary>
/// Generates customs and customer document workbooks (every shipping-batch
/// <see cref="DocumentKind"/>) 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.
/// </summary>
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<CiPlDocumentGenerationResultDto> 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<DocumentKind>(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);
}
@@ -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;
/// <summary>One resolved placeholder mapping used by the renderer (placeholder key is the normalized name).</summary>
public sealed record CiPlMappedField(string Placeholder, string BusinessField, TemplateFieldScope Scope, string? NumberFormat);
/// <summary>
/// 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.
/// </summary>
public static partial class CiPlTemplateRenderer
{
[GeneratedRegex(@"\{\{\s*([^{}]+?)\s*\}\}", RegexOptions.CultureInvariant)]
private static partial Regex TokenRegex();
public static byte[] Render(
byte[] templateBytes,
ShippingBatch batch,
IReadOnlyList<ShipmentLine> lines,
DocumentKind kind,
DocumentRenderSource source,
IReadOnlyDictionary<string, CiPlMappedField> 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<Guid, CustomsDeclarationLine>();
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<string>(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<string, string[]>
{
["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<string, CiPlMappedField> 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<int>();
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<int, int>();
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<string, CiPlMappedField> 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<DocLine> 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));
/// <summary>Chinese currency name used by the customs declaration (币制).</summary>
private static string CurrencyNameZh(string currency) => currency.ToUpperInvariant() switch
{
"USD" => "美元",
"CNY" or "RMB" => "人民币",
"EUR" => "欧元",
"GBP" => "英镑",
"JPY" => "日元",
"HKD" => "港币",
"AUD" => "澳大利亚元",
"CAD" => "加拿大元",
_ => currency,
};
// ---------- Cell helpers ----------
/// <summary>Token-bearing text of a cell, or null. Formula cells are skipped: their values are never a data source.</summary>
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<string> 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);
/// <summary>One document line: the shipment line plus its customs-declaration line, if any.</summary>
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<DocLine> Lines, DocumentKind Kind,
DocumentRenderSource Source, Totals Totals, DateTimeOffset GeneratedAt);
}
@@ -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<string, string[]> errors)
: Exception("报关与单证资料校验失败。")
{
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
public CustomsValidationException(string field, string message)
: this(new Dictionary<string, string[]> { [field] = [message] })
{
}
}
@@ -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<IReadOnlyList<CustomsDeclarationListItemDto>> 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<CustomsDeclarationStatus>(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<CustomsDeclarationDto> GetAsync(Guid id, CancellationToken ct = default)
=> ToDto(await LoadAsync(id, ct));
public async Task<CustomsDeclarationDto> 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<Guid, CustomsLineOverrideRequest>();
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<CustomsDeclarationDto> 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<Guid>();
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<CustomsDeclarationDto> ConfirmAsync(
Guid id, ConfirmCustomsDeclarationRequest? request, CancellationToken ct = default)
{
var declaration = await LoadAsync(id, ct);
var errors = new Dictionary<string, string[]>();
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<CustomsDeclarationDto> 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<IReadOnlyList<DocumentPackageDto>> 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<IReadOnlyList<DocumentPackageDto>> 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<DocumentPackageDto> GetDocumentAsync(
Guid shippingBatchId, Guid documentId, CancellationToken ct = default)
=> ToDto(await LoadDocumentAsync(shippingBatchId, documentId, ct));
public async Task<DocumentPackageDto> 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<DocumentPackageDto> 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<DocumentPackageDto> 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<DocumentPackageDto> 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<DocumentPackageDto> 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<CustomsDeclaration> 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<DocumentPackage> 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<ShippingBatch> 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<DocumentKind>(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);
}
@@ -0,0 +1,34 @@
using Leiren.Erp.Domain.Entities;
using Leiren.Erp.Domain.Enums;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Customs;
/// <summary>
/// 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.
/// </summary>
public sealed record DocumentRenderSource(CustomsDeclaration? Declaration, Customer? Customer, DateOnly? OrderDate)
{
public static readonly DocumentRenderSource Empty = new(null, null, null);
/// <summary>Customs documents (报关发票/装箱单/外销合同/报关单) are read from the declaration.</summary>
public static bool IsCustomsKind(DocumentKind kind) => kind is DocumentKind.CustomsInvoice
or DocumentKind.CustomsPackingList or DocumentKind.CustomsSalesContract or DocumentKind.CustomsDeclarationData;
public static async Task<DocumentRenderSource> 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);
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
public sealed class DocumentTemplateCatalogService(
ICustomsDbContext customs,
IPurchasingDbContext purchasing,
FileService files,
DocumentTemplateMappingService mappings,
BillingDocumentExportService billingDocuments)
{
public IReadOnlyList<DocumentTemplateKindDto> ListKinds() => DocumentTemplateKinds.All;
public async Task<IReadOnlyList<DocumentTemplateListItemDto>> ListAsync(CancellationToken ct = default)
{
var current = await files.ListAsync(
DocumentTemplateService.TemplateOwnerType, null, null, null, currentOnly: true, 1, 200, ct);
var result = new List<DocumentTemplateListItemDto>(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<string> placeholders;
IReadOnlyList<string> 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<string, CiPlMappedField>(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<DocumentKind>(kind.Key), source, mapped, DateTimeOffset.UtcNow, allowUnmapped: true);
return (rendered, $"{stem}-预览.xlsx");
}
private async Task<byte[]> 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();
}
}
@@ -0,0 +1,104 @@
using Leiren.Erp.Domain.Enums;
namespace Leiren.Erp.Application.Customs;
/// <summary>One allowed business field a template placeholder may map to.</summary>
public sealed record TemplateFieldDefinition(string Key, string DisplayName, TemplateFieldScope Scope, string ValueType);
/// <summary>
/// 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 <c>Line</c> prefix so they
/// cannot collide with the document totals.
/// </summary>
public static class DocumentTemplateFields
{
public static readonly IReadOnlyList<TemplateFieldDefinition> 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<string, TemplateFieldDefinition> 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<string> Keys => All.Select(x => x.Key).ToList();
}
@@ -0,0 +1,432 @@
using Leiren.Erp.Contracts;
using Leiren.Erp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Customs;
/// <summary>
/// Persistence and validation for versioned CI/PL template field mappings.
/// A profile belongs to exactly one immutable template version
/// (<see cref="DocumentTemplateMappingProfile.TemplateVersionId"/>, the
/// scanned template file version id). Every placeholder found in the template
/// must map to a field from <see cref="DocumentTemplateFields"/> before a
/// document may be generated; generation locks the profile forever.
/// </summary>
public sealed class DocumentTemplateMappingService(IDocumentTemplateMappingDbContext db)
{
public IReadOnlyList<DocumentTemplateFieldDto> ListFields()
=> DocumentTemplateFields.All
.Select(x => new DocumentTemplateFieldDto(x.Key, x.DisplayName, x.Scope.ToString(), x.ValueType))
.ToList();
// ---------- Profiles ----------
public async Task<DocumentTemplateMappingProfileDto> 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<DocumentTemplateMappingProfileDto> GetProfileAsync(Guid templateVersionId, CancellationToken ct = default)
=> ToDto(await LoadProfileAsync(templateVersionId, ct));
public Task<bool> ProfileExistsAsync(Guid templateVersionId, CancellationToken ct = default)
=> db.DocumentTemplateMappingProfiles.AsNoTracking().AnyAsync(x => x.TemplateVersionId == templateVersionId, ct);
public async Task<IReadOnlyList<DocumentTemplateMappingProfileDto>> ListProfilesAsync(Guid? templateId, CancellationToken ct = default)
{
IQueryable<DocumentTemplateMappingProfile> 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<DocumentTemplateMappingProfileDto> 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<DocumentTemplateMappingProfileDto> 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<DocumentTemplateMappingProfileDto> 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<DocumentTemplateMappingProfileDto> 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<DocumentTemplateMappingProfileDto> 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<DocumentTemplateMappingProfileDto> 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<DocumentTemplateValidationResultDto> ValidateAsync(
Guid templateVersionId, IReadOnlyCollection<string>? scannedPlaceholders = null, CancellationToken ct = default)
{
var profile = await LoadProfileAsync(templateVersionId, ct);
return BuildValidation(profile, scannedPlaceholders);
}
/// <summary>
/// Throws <see cref="CustomsValidationException"/> 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.
/// </summary>
public async Task<DocumentTemplateMappingProfileDto> ValidateForGenerationAsync(
Guid templateVersionId, IReadOnlyCollection<string>? scannedPlaceholders = null, CancellationToken ct = default)
{
var profile = await LoadProfileAsync(templateVersionId, ct);
var result = BuildValidation(profile, scannedPlaceholders);
ThrowIfInvalid(result);
return ToDto(profile);
}
/// <summary>Parameterless-placeholder overload of <see cref="ValidateForGenerationAsync"/> using the stored scan snapshot.</summary>
public Task<DocumentTemplateMappingProfileDto> EnsureGenerationAllowedAsync(Guid templateVersionId, CancellationToken ct = default)
=> ValidateForGenerationAsync(templateVersionId, scannedPlaceholders: null, ct);
/// <summary>Locks the profile after a document package was generated from it; locked mappings are immutable.</summary>
public async Task<DocumentTemplateMappingProfileDto> LockAfterGenerationAsync(
Guid templateVersionId, Guid documentPackageId, CancellationToken ct = default)
{
var profile = await LoadProfileAsync(templateVersionId, ct);
profile.LockAfterGeneration(documentPackageId);
await db.SaveChangesAsync(ct);
return ToDto(profile);
}
/// <summary>Alias for <see cref="LockAfterGenerationAsync"/>.</summary>
public Task<DocumentTemplateMappingProfileDto> MarkUsedAsync(Guid templateVersionId, Guid documentPackageId, CancellationToken ct = default)
=> LockAfterGenerationAsync(templateVersionId, documentPackageId, ct);
// ---------- Helpers ----------
private async Task<DocumentTemplateMappingProfile> 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<string> NormalizePlaceholders(IReadOnlyList<string>? raw, ErrorBag errors)
{
var result = new List<string>();
if (raw is null) return result;
var seen = new HashSet<string>(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<SaveDocumentTemplateFieldMappingRequest>? inputs,
IReadOnlyList<string> 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<string>(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<string>? 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<string, string[]>();
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<string, List<string>> _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()));
}
}
}
@@ -0,0 +1,23 @@
using Leiren.Erp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Customs;
/// <summary>
/// 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.
/// </summary>
public interface ICustomsDbContext
{
DbSet<ShippingBatch> ShippingBatches { get; }
DbSet<SalesOrderLine> SalesOrderLines { get; }
DbSet<SalesOrder> SalesOrders { get; }
DbSet<Customer> Customers { get; }
DbSet<Product> Products { get; }
DbSet<CustomsDeclaration> CustomsDeclarations { get; }
DbSet<CustomsDeclarationLine> CustomsDeclarationLines { get; }
DbSet<DocumentPackage> DocumentPackages { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
@@ -0,0 +1,19 @@
using Leiren.Erp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Customs;
/// <summary>
/// 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.
/// </summary>
public interface IDocumentTemplateMappingDbContext
{
DbSet<DocumentTemplateMappingProfile> DocumentTemplateMappingProfiles { get; }
DbSet<DocumentTemplateFieldMapping> DocumentTemplateFieldMappings { get; }
DbSet<DocumentPackage> DocumentPackages { get; }
DbSet<FileAttachment> FileAttachments { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
@@ -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<DashboardSummaryDto> 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<DashboardSectionDto> SummarizeAsync<TStatus>(
IQueryable<TStatus> 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<TStatus>()
.Select(status => new DashboardStatusCountDto(status.ToString(), counts.GetValueOrDefault(status)))
.ToList();
return new DashboardSectionDto(byStatus.Sum(item => item.Count), byStatus);
}
}
@@ -0,0 +1,16 @@
using Leiren.Erp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Dashboard;
/// <summary>EF Core boundary for read-only dashboard aggregates; implemented by Infrastructure.</summary>
public interface IDashboardDbContext
{
DbSet<SalesOrder> SalesOrders { get; }
DbSet<PurchaseTask> PurchaseTasks { get; }
DbSet<PurchaseContract> PurchaseContracts { get; }
DbSet<ShippingBatch> ShippingBatches { get; }
DbSet<CustomsDeclaration> CustomsDeclarations { get; }
DbSet<SupplierInvoiceNotice> SupplierInvoiceNotices { get; }
DbSet<Product> Products { get; }
}
@@ -0,0 +1,40 @@
using Leiren.Erp.Application.Billing;
using Leiren.Erp.Application.Purchasing;
using Leiren.Erp.Contracts;
namespace Leiren.Erp.Application.Documents;
/// <summary>
/// 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
/// <c>DocumentKind</c> values and are filled through field mappings; the
/// purchase contract uses the renderer's built-in placeholder names.
/// </summary>
public static class DocumentTemplateKinds
{
public const string ShippingBatch = "ShippingBatch";
/// <summary>Kind key and data source of purchase-contract templates.</summary>
public const string PurchaseContract = "PurchaseContract";
/// <summary>Data source of the supplier billing documents (开票通知 / 开票购销合同).</summary>
public const string SupplierInvoiceNotice = "SupplierInvoiceNotice";
public const string SupplierInvoiceNoticeKind = "SupplierInvoiceNotice";
public const string SupplierBillingContractKind = "SupplierBillingContract";
public static readonly IReadOnlyList<DocumentTemplateKindDto> 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));
}
@@ -0,0 +1,172 @@
using Leiren.Erp.Application.Files;
using Leiren.Erp.Contracts;
namespace Leiren.Erp.Application.Documents;
/// <summary>Optional metadata supplied alongside an uploaded CI/PL template.</summary>
public sealed record DocumentTemplateUploadOptions(
string? Name,
string? DocumentKind,
Guid? CustomerId,
string? UploadedBy,
Guid? UploadedByUserId = null);
/// <summary>
/// Stores customer CI/PL .xlsx templates through <see cref="FileService"/>
/// (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.
/// </summary>
public sealed class DocumentTemplateService(FileService files, FileStorageOptions storageOptions)
{
public const string TemplateOwnerType = "DocumentTemplate";
public async Task<DocumentTemplateUploadResultDto> 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);
}
/// <summary>Stores a new immutable version of the template the given file version belongs to.</summary>
public async Task<DocumentTemplateUploadResultDto> 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);
}
/// <summary>Re-scans an already stored template file version.</summary>
public async Task<DocumentTemplateUploadResultDto> 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<byte[]> 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;
}
}
@@ -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<string, string[]> errors)
: Exception("模板文件校验失败。")
{
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
public DocumentTemplateValidationException(string field, string message)
: this(new Dictionary<string, string[]> { [field] = [message] })
{
}
}
public sealed record TemplateScanResult(
IReadOnlyList<string> Worksheets,
IReadOnlyList<TemplatePlaceholderDto> Placeholders,
IReadOnlyList<TemplateLineRowDto> LineRows,
IReadOnlyList<string> Warnings);
/// <summary>
/// Scans every worksheet of a real .xlsx template for <c>{{...}}</c> 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 (<c>Line.</c>, <c>Lines.</c>, <c>Item.</c>, <c>Detail.</c>,
/// <c>Row.</c>, also with <c>:</c>/<c>_</c> 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.
/// </summary>
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<Occurrence>();
var warnings = new List<string>();
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<string, List<TemplatePlaceholderLocationDto>>(StringComparer.OrdinalIgnoreCase);
var firstNameByKey = new Dictionary<string, string>(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);
}
}
/// <summary>Display text of a cell, plus its formula text when it has one.</summary>
private static IEnumerable<string> CandidateTexts(IXLCell cell)
{
var seen = new HashSet<string>(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<Occurrence> occurrences, List<string> warnings)
{
var address = cell.Address.ToString() ?? string.Empty;
var foundInText = new HashSet<string>(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;
}
}
@@ -0,0 +1,214 @@
using System.Globalization;
using System.Text.RegularExpressions;
using ClosedXML.Excel;
namespace Leiren.Erp.Application.Documents;
/// <summary>
/// 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.
/// </summary>
public sealed record TokenTemplateFields(
IReadOnlySet<string> LineFields, IReadOnlySet<string> NumericFields, IReadOnlySet<string> DateFields);
/// <summary>
/// Renders the first worksheet of an XLSX template whose cells contain
/// <c>{{Field}}</c> 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
/// <paramref name="error"/> so each module keeps its own exception type.
/// </summary>
public static partial class TokenWorkbookRenderer
{
[GeneratedRegex(@"\{\{\s*([^{}]+?)\s*\}\}", RegexOptions.CultureInvariant)]
private static partial Regex TokenRegex();
public static byte[] Render(
byte[] templateBytes,
IReadOnlyDictionary<string, string?> headerValues,
IReadOnlyList<IReadOnlyDictionary<string, string?>> lineValues,
TokenTemplateFields fields,
string templateLabel,
Func<string, Exception> 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<string>(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<int, int>();
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<string, string?>(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<string, string?> 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<string, string?> 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<int> FindLineRows(IXLWorksheet sheet, IReadOnlySet<string> lineFields)
{
var rows = new SortedSet<int>();
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<string> 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();
}
}
}
@@ -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<FileAttachmentDto> 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);
}
/// <summary>Stores a new immutable version of the file group the given version belongs to.</summary>
public async Task<FileAttachmentDto> 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<IReadOnlyList<FileAttachmentListItemDto>> 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<FileAttachmentDto> GetAsync(Guid id, CancellationToken ct = default)
=> ToDto(await LoadAsync(id, ct));
public async Task<IReadOnlyList<FileAttachmentDto>> 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<FileDownloadResult> 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<FileAttachment> 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);
}
@@ -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<string, string[]> errors)
: Exception("文件资料校验失败。")
{
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
public FilesValidationException(string field, string message)
: this(new Dictionary<string, string[]> { [field] = [message] })
{
}
}
@@ -0,0 +1,53 @@
namespace Leiren.Erp.Application.Files;
/// <summary>Configuration for server-side file storage. Content never goes to the database.</summary>
public sealed class FileStorageOptions
{
/// <summary>Storage root. Relative values are resolved against the API content root at startup.</summary>
public string RootPath { get; set; } = "data/storage";
public long MaxFileSizeBytes { get; set; } = 50 * 1024 * 1024;
public List<string> 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);
/// <summary>
/// Stores file content under relative keys beneath a configured root.
/// Implementations must reject absolute keys and any key escaping the root.
/// </summary>
public interface IFileStorage
{
Task<StoredFileWriteResult> SaveAsync(string storageKey, Stream content, CancellationToken cancellationToken = default);
Task<Stream> OpenReadAsync(string storageKey, CancellationToken cancellationToken = default);
Task DeleteAsync(string storageKey, CancellationToken cancellationToken = default);
Task<bool> ExistsAsync(string storageKey, CancellationToken cancellationToken = default);
}
/// <summary>Upload input carrying the content stream; kept in Application because streams are not wire contracts.</summary>
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);
/// <summary>Download metadata handed to the API layer without exposing a server filesystem path.</summary>
public sealed record FileDownloadInfo(
Guid Id,
string OriginalFileName,
string ContentType,
long SizeBytes,
string Sha256);
@@ -0,0 +1,12 @@
using Leiren.Erp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Files;
/// <summary>EF Core boundary for the Files module; implemented by Infrastructure.</summary>
public interface IFilesDbContext
{
DbSet<FileAttachment> FileAttachments { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
@@ -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;
/// <summary>EF Core boundary for the Finance module; implemented by Infrastructure.</summary>
public interface IFinanceDbContext
{
DbSet<SupplierPayable> SupplierPayables { get; }
DbSet<PurchaseContract> PurchaseContracts { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
public sealed class FinanceValidationException(string field, string message) : Exception(message)
{
public IReadOnlyDictionary<string, string[]> Errors { get; } = new Dictionary<string, string[]> { [field] = [message] };
}
public sealed class FinanceNotFoundException(string message) : Exception(message);
public sealed class FinanceConflictException(string message) : Exception(message);
/// <summary>
/// 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.
/// </summary>
public sealed class PayableService(IFinanceDbContext db)
{
public async Task<IReadOnlyList<SupplierPayableDto>> ListAsync(CancellationToken ct = default)
{
var items = await db.SupplierPayables.AsNoTracking().ToListAsync(ct);
return items.OrderByDescending(x => x.CreatedAt).Select(ToDto).ToList();
}
public async Task<SupplierPayableDto> 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);
}
/// <summary>
/// Creates the payable for every confirmed contract that has none — covers
/// contracts confirmed before payables existed. Idempotent.
/// </summary>
public async Task<int> 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);
}
@@ -0,0 +1,17 @@
using Leiren.Erp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Identity;
/// <summary>EF Core boundary for the Identity module; implemented by Infrastructure.</summary>
public interface IIdentityDbContext
{
DbSet<AppUser> Users { get; }
DbSet<AppRole> Roles { get; }
DbSet<AppPermission> Permissions { get; }
DbSet<UserRole> UserRoles { get; }
DbSet<RolePermission> RolePermissions { get; }
DbSet<UserPermission> UserPermissions { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
@@ -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<string, string[]> errors)
: Exception("授权数据校验失败。")
{
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
public IdentityValidationException(string field, string message)
: this(new Dictionary<string, string[]> { [field] = [message] })
{
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
public sealed class IdentityService(IIdentityDbContext db)
{
private static readonly IReadOnlyDictionary<string, (string Name, string[] Permissions)> SystemRoles =
new Dictionary<string, (string, string[])>(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<ModuleDto> ListModules() =>
AuthorizationCatalog.Modules.Select(x => new ModuleDto(x.Code, x.Name)).ToList();
public IReadOnlyList<PermissionDto> ListPermissions() =>
AuthorizationCatalog.Permissions.Select(x => new PermissionDto(x.Code, x.Module, x.Action)).ToList();
/// <summary>Idempotently creates the permission catalog and system roles.</summary>
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<IReadOnlyList<string>> 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<bool> 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<bool> 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<UserDto> 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<IReadOnlyList<UserDto>> 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<UserDto>(users.Count);
foreach (var user in users) result.Add(await ToDtoAsync(user, ct));
return result;
}
public async Task<UserDto> 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<UserDto> 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);
}
/// <summary>
/// Replaces the user's directly granted module access (<c>module:view</c>). Modules that
/// come from roles remain effective and are still reported in the user's module list.
/// </summary>
public async Task<UserDto> 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<UserDto> 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<UserDto> 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<IReadOnlyList<RoleDto>> ListRolesAsync(CancellationToken ct = default)
{
var roles = await db.Roles.OrderBy(x => x.Code).ToListAsync(ct);
var result = new List<RoleDto>(roles.Count);
foreach (var role in roles) result.Add(await ToDtoAsync(role, ct));
return result;
}
public async Task<RoleDto> 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<RoleDto> 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<AppUser> GetUserEntityAsync(Guid userId, CancellationToken ct) =>
await db.Users.SingleOrDefaultAsync(x => x.Id == userId, ct)
?? throw new IdentityNotFoundException("用户不存在。");
private async Task<AppPermission> 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<string> 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<IReadOnlyList<AppRole>> ResolveRolesAsync(IReadOnlyList<string>? 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<string> ResolvePermissionCodes(IReadOnlyList<string>? permissions, IReadOnlyList<string>? modules)
{
var codes = new HashSet<string>(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<string> NormalizeModules(IReadOnlyList<string>? modules)
{
if (modules is null || modules.Count == 0) return [];
var result = new HashSet<string>(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<UserDto> 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<RoleDto> 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);
}
}
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="ClosedXML" Version="0.105.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="11.0.0-rc.3.26522.148" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Leiren.Erp.Domain\Leiren.Erp.Domain.csproj" />
<ProjectReference Include="..\Leiren.Erp.Contracts\Leiren.Erp.Contracts.csproj" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
@@ -0,0 +1,22 @@
using Leiren.Erp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.MasterData;
/// <summary>
/// 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.
/// </summary>
public interface IMasterDataDbContext
{
DbSet<Supplier> Suppliers { get; }
DbSet<ProductSupplierQuote> ProductSupplierQuotes { get; }
DbSet<PurchaseTask> PurchaseTasks { get; }
DbSet<PurchaseContract> PurchaseContracts { get; }
DbSet<SupplierInvoiceNotice> SupplierInvoiceNotices { get; }
DbSet<SupplierInvoice> SupplierInvoices { get; }
DbSet<SupplierBillingContract> SupplierBillingContracts { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
@@ -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<string, string[]> errors)
: Exception("主数据校验失败。")
{
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
public MasterDataValidationException(string field, string message)
: this(new Dictionary<string, string[]> { [field] = [message] })
{
}
}
@@ -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<IReadOnlyList<SupplierDto>> 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<SupplierDto> GetAsync(Guid id, CancellationToken ct = default)
=> ToDto(await LoadAsync(id, ct));
public async Task<SupplierDto> 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<SupplierDto> 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<SupplierDto> 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<bool> 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<Supplier> 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);
}
@@ -0,0 +1,25 @@
using Leiren.Erp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Purchasing;
/// <summary>
/// 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.
/// </summary>
public interface IPurchasingDbContext
{
DbSet<SalesOrder> SalesOrders { get; }
DbSet<SalesOrderLine> SalesOrderLines { get; }
DbSet<Product> Products { get; }
DbSet<ProductPart> ProductParts { get; }
DbSet<ProductSupplierQuote> ProductSupplierQuotes { get; }
DbSet<Supplier> Suppliers { get; }
DbSet<PurchaseTask> PurchaseTasks { get; }
DbSet<PurchaseContract> PurchaseContracts { get; }
DbSet<PurchaseArrival> PurchaseArrivals { get; }
DbSet<SupplierPayable> SupplierPayables { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<PurchaseContractExportDto> 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");
}
/// <summary>Renders the contract workbook without storing a file; used by the confirm preview.</summary>
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<Domain.Entities.PurchaseTask> 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);
}
/// <summary>
/// The most recently imported purchase-contract template (template editor)
/// wins; without one, the configured template file is used.
/// </summary>
private async Task<byte[]> 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;
}
}
@@ -0,0 +1,104 @@
using System.Globalization;
using Leiren.Erp.Application.Documents;
using Leiren.Erp.Domain.Entities;
namespace Leiren.Erp.Application.Purchasing;
/// <summary>
/// Renders a purchase-contract workbook from a real XLSX template through
/// <see cref="TokenWorkbookRenderer"/>: 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.
/// </summary>
public static class PurchaseContractTemplateRenderer
{
private static readonly TokenTemplateFields Fields = new(
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"CustomerPoNo", "LineNumber", "CustomerSku", "InternalSku", "Unit", "ContentDescription",
"ContentType", "PackagingRequirement", "PurchaseRequirement", "Quantity", "UnitPrice",
"Amount", "TaxRate", "TaxIncluded", "DueDate",
},
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"LineNumber", "Quantity", "UnitPrice", "Amount", "TaxRate", "TotalAmount", "LineCount", "Version",
},
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"SignedDate", "RequiredCompletionDate", "DueDate", "GeneratedDate",
});
public static byte[] Render(
byte[] templateBytes, PurchaseContract contract, IReadOnlyList<PurchaseTask> 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<string, string?> BuildHeaderValues(
PurchaseContract contract, IReadOnlyList<PurchaseTask> 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<Dictionary<string, string?>> BuildLineValues(
PurchaseContract contract, IReadOnlyList<PurchaseTask> lines)
{
var result = new List<Dictionary<string, string?>>(lines.Count);
for (var i = 0; i < lines.Count; i++)
{
var task = lines[i];
result.Add(new Dictionary<string, string?>(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;
}
/// <summary>Header placeholder names; must match the keys of <see cref="BuildHeaderValues"/>.</summary>
private static readonly string[] HeaderFields =
[
"ContractNo", "SupplierName", "SupplierContact", "SupplierPhone", "CustomerOrderNo", "SignedDate",
"RequiredCompletionDate", "PaymentTerms", "Currency", "Status", "Version", "LineCount", "TotalAmount",
"GeneratedDate", "Terms",
];
/// <summary>Every placeholder name a purchase-contract template may use (header + line).</summary>
public static IReadOnlyList<string> FieldNames { get; } = [.. HeaderFields, .. Fields.LineFields.Where(x => !HeaderFields.Contains(x, StringComparer.OrdinalIgnoreCase))];
}
/// <summary>Absolute path of the XLSX template used for purchase-contract exports.</summary>
public sealed record PurchaseContractTemplateOptions(string TemplatePath);
@@ -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<IReadOnlyList<PurchaseTaskListItemDto>> 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<PurchaseTaskStatus>(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();
}
/// <summary>
/// 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).
/// </summary>
public async Task<IReadOnlyList<PurchaseOverviewDto>> 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<Guid, PurchaseContractStatus>()
: await db.PurchaseContracts.AsNoTracking()
.Where(x => contractIds.Contains(x.Id))
.ToDictionaryAsync(x => x.Id, x => x.Status, ct);
var result = new List<PurchaseOverviewDto>(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<PurchaseOverviewProductDto>();
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<PurchaseOverviewRowDto>();
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<PurchaseTaskDto> GetTaskAsync(Guid id, CancellationToken ct = default)
=> ToDto(await LoadTaskAsync(id, ct));
public async Task<PurchaseTaskDto> 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<GeneratePurchaseTasksResultDto> 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<PurchaseTask>();
var skipped = new List<Guid>();
var assignments = request.Assignments ?? [];
var supplierIds = assignments.Select(x => x.SupplierId).Distinct().ToList();
var supplierMap = supplierIds.Count == 0
? new Dictionary<Guid, Supplier>()
: 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<PurchaseTaskDto> 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<IReadOnlyList<PurchaseContractListItemDto>> 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<PurchaseContractStatus>(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<PurchaseContractDto> GetContractAsync(Guid id, CancellationToken ct = default)
=> ToDto(await LoadContractAsync(id, ct));
public async Task<PurchaseContractDto> 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<PurchaseContractDto> 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<PurchaseContractDto> 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<PurchaseArrivalDto> 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<ProductSupplierQuote> quotes,
IReadOnlyList<PurchaseTaskAssignmentDto> assignments,
IReadOnlyDictionary<Guid, Supplier> 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);
}
/// <summary>
/// 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.
/// </summary>
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<PurchaseTask> LoadTaskAsync(Guid id, CancellationToken ct)
=> await db.PurchaseTasks
.Include(x => x.Arrivals)
.SingleOrDefaultAsync(x => x.Id == id, ct)
?? throw new PurchasingNotFoundException("采购任务不存在。");
private async Task<PurchaseContract> 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<PurchaseContentType>(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());
}
@@ -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<string, string[]> errors)
: Exception("采购资料校验失败。")
{
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
public PurchasingValidationException(string field, string message)
: this(new Dictionary<string, string[]> { [field] = [message] })
{
}
}
@@ -0,0 +1,25 @@
using Leiren.Erp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Sales;
/// <summary>
/// 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.
/// </summary>
public interface ISalesDbContext
{
DbSet<Customer> Customers { get; }
DbSet<SalesOrder> SalesOrders { get; }
DbSet<SalesOrderLine> SalesOrderLines { get; }
DbSet<Product> Products { get; }
DbSet<PurchaseTask> PurchaseTasks { get; }
DbSet<PurchaseArrival> PurchaseArrivals { get; }
DbSet<ShipmentLine> ShipmentLines { get; }
DbSet<SupplierInvoiceNotice> SupplierInvoiceNotices { get; }
DbSet<SupplierInvoiceNoticeLine> SupplierInvoiceNoticeLines { get; }
DbSet<SupplierInvoice> SupplierInvoices { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
@@ -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;
/// <summary>Order-header values supplied alongside the uploaded PO workbook (multipart form fields).</summary>
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);
/// <summary>
/// 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.
/// </summary>
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<PoImportResultDto> 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<PoImportPreviewDto> 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<PoImportIssueDto>();
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<SheetCandidate>();
var ambiguities = new List<PoImportIssueDto>();
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<string> availableSheets,
IReadOnlyList<PoImportIssueDto> issues) => new(
fileName, sheetName, availableSheets, null, [], [], issues, [], [], 0, 0, 0, false);
/// <summary>Finds the header row of one sheet by recognized header names (first 50 used rows).</summary>
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<SheetCandidate>();
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<PoImportIssueDto> 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<PoImportIssueDto>();
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<ParsedRow> ParseDataRows(SheetCandidate candidate)
{
var sheet = candidate.Sheet;
var rows = new List<ParsedRow>();
for (var rowNumber = candidate.HeaderRow + 1; rowNumber <= candidate.LastRow; rowNumber++)
{
var raw = new Dictionary<string, string?>(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<ParsedRow> 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<decimal>(); 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<double>();
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<byte[]> 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<string, string> HeaderAliases = BuildHeaderAliases();
private static IReadOnlyDictionary<string, string> BuildHeaderAliases()
{
var map = new Dictionary<string, string>(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<string, int> Columns { get; } = new(StringComparer.Ordinal);
public List<string> Headers { get; } = [];
public List<string> UnrecognizedHeaders { get; } = [];
public List<PoImportIssueDto> Issues { get; } = [];
/// <summary>Column number -> original header text, for raw-row preservation.</summary>
public Dictionary<int, string> 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<int> 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<string, string?> RawValues { get; set; } = new Dictionary<string, string?>();
public List<PoImportIssueDto> 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);
}
@@ -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<string, string[]> errors)
: Exception("客户订单校验失败。")
{
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
public SalesValidationException(string field, string message)
: this(new Dictionary<string, string[]> { [field] = [message] })
{
}
}
@@ -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<IReadOnlyList<CustomerDto>> 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<CustomerDto> GetCustomerAsync(Guid id, CancellationToken ct = default)
=> ToDto(await LoadCustomerAsync(id, ct));
public async Task<CustomerDto> 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<CustomerDto> 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<IReadOnlyList<SalesOrderListItemDto>> 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<SalesOrderStatus>(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<SalesOrderDto> GetAsync(Guid id, CancellationToken ct = default)
=> await ToDtoAsync(await LoadOrderAsync(id, ct), ct);
public async Task<SalesOrderDto> 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<SalesOrderDto> 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<SalesOrderDto> ConfirmAsync(Guid id, ConfirmSalesOrderRequest? request, CancellationToken ct = default)
{
var order = await LoadOrderAsync(id, ct);
EnsureDraft(order);
var errors = new Dictionary<string, string[]>();
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<SalesOrderDto> 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);
}
/// <summary>Deletes a draft order with its lines; confirmed orders can only be cancelled.</summary>
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<Customer> LoadCustomerAsync(Guid id, CancellationToken ct)
=> await db.Customers.SingleOrDefaultAsync(x => x.Id == id, ct)
?? throw new SalesNotFoundException("客户不存在。");
private async Task<SalesOrder> 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<Customer> 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<List<SalesOrderLine>> 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<string, string[]>();
var lines = new List<SalesOrderLine>(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<string> 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<SalesOrderDto> ToDtoAsync(SalesOrder order, CancellationToken ct)
{
var summaries = await ComputeSummariesAsync([order], ct);
return ToDto(order, summaries[order.Id]);
}
private async Task<IReadOnlyDictionary<Guid, SalesOrderWorkbenchSummaryDto>> ComputeSummariesAsync(
IReadOnlyList<SalesOrder> orders, CancellationToken ct)
{
if (orders.Count == 0)
return new Dictionary<Guid, SalesOrderWorkbenchSummaryDto>();
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<Guid, decimal>()
: (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<Guid, decimal>()
: (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<InvoiceProgress>()
: 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<TaskProgress> tasks,
IReadOnlyDictionary<Guid, decimal> arrivedByTask,
IReadOnlyDictionary<(Guid SalesOrderId, Guid SalesOrderLineId), decimal> shippedByLine,
IReadOnlyList<NoticeProgress> notices,
IReadOnlyList<InvoiceProgress> 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<InvoiceProgress> 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<SalesOrderSupplierBillingSummaryDto> ComputeSupplierBillings(
IReadOnlyList<NoticeProgress> notices, IReadOnlyList<InvoiceProgress> 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);
}
@@ -0,0 +1,23 @@
using Leiren.Erp.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Shipping;
/// <summary>
/// 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).
/// </summary>
public interface IShippingDbContext
{
DbSet<SalesOrder> SalesOrders { get; }
DbSet<SalesOrderLine> SalesOrderLines { get; }
DbSet<Product> Products { get; }
DbSet<PurchaseTask> PurchaseTasks { get; }
DbSet<PurchaseArrival> PurchaseArrivals { get; }
DbSet<ShippingBatch> ShippingBatches { get; }
DbSet<ShippingContainer> ShippingContainers { get; }
DbSet<ShipmentLine> ShipmentLines { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}
@@ -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<string, string[]> errors)
: Exception("出货资料校验失败。")
{
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
public ShippingValidationException(string field, string message)
: this(new Dictionary<string, string[]> { [field] = [message] })
{
}
}
@@ -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<IReadOnlyList<ShippingBatchListItemDto>> 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<ShippingBatchStatus>(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<ShippingBatchDto> GetBatchAsync(Guid id, CancellationToken ct = default)
=> await ToDtoAsync(await LoadBatchAsync(id, ct), ct);
/// <summary>Confirmed orders whose arrived finished goods are not fully in shipping batches yet.</summary>
public async Task<IReadOnlyList<ShippingReadyOrderDto>> 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<ShippingReadyOrderDto>();
foreach (var order in orders.OrderByDescending(x => x.OrderDate).ThenBy(x => x.OrderNumber, StringComparer.Ordinal))
{
var lines = new List<ShippingReadyLineDto>();
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<ShippingBatchDto> 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<ShippingBatchDto> 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<ShippingBatchDto> 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<ShippingBatchDto> 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<ShippingBatchDto> 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<ShippingBatchDto> 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<ShippingBatchDto> 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<ShippingBatchDto> 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<ShippingBatchDto> 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 ----------
/// <summary>
/// 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.
/// </summary>
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();
}
/// <summary>
/// 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.
/// </summary>
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}。");
}
/// <summary>
/// Finished quantity arrived for a sales line: every part (purchase task)
/// is needed for one finished unit, so the least-arrived part limits it.
/// </summary>
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<ShippingBatch> 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<ShippingBatchDto> ToDtoAsync(ShippingBatch batch, CancellationToken ct)
{
var arrivedByLine = new Dictionary<Guid, decimal>();
var otherShippedByLine = new Dictionary<Guid, decimal>();
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();
}
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\Leiren.Erp.Infrastructure\Leiren.Erp.Infrastructure.csproj" />
</ItemGroup>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+262
View File
@@ -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<int> 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<int> 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<int> 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<BackupOptions> 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<BackupOptions>(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 <file> JSON 配置文件(见 deploy/windows/backup.example.json)
--source <Name=Path> 备份源目录,可重复;Name 仅字母/数字/-/_/.
--destination <dir> 备份根目录(其下按时间戳建子目录)
--include-database 同时包含数据库备份
--database-provider <Sqlite|PostgreSql>
--database-connection-string <cs> 建议改用配置文件或环境变量 LEIREN_ERP_CONNECTION_STRING
--pg-dump-path <path> pg_dump 完整路径(默认从 PATH 查找)
--allow-empty 允许空备份(默认拒绝)
--dry-run 仅枚举/哈希源文件,不写入任何内容
退出码:0 成功,1 备份或校验失败,2 用法错误。
失败时不会生成可被误认的完成备份;完成前会按 manifest.json 的 SHA-256 自校验。
""");
}
private sealed class CliArgs
{
private readonly Dictionary<string, List<string>> _values = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> _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<string> GetValues(string name)
=> _values.TryGetValue(name, out var list) ? list : [];
}
}
+259
View File
@@ -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<LoginResponse>? SessionChanged;
public async Task<LoginResponse> LoginAsync(string userName, string password, CancellationToken cancellationToken = default)
{
var result = await SendAsync<LoginResponse>(HttpMethod.Post, "/api/auth/login",
new { userName, password }, cancellationToken);
return ApplySession(result);
}
public async Task<LoginResponse> 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<LoginResponse> RefreshCoreAsync(string refreshToken, CancellationToken cancellationToken)
{
var result = await SendAsync<LoginResponse>(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<T> GetAsync<T>(string url, CancellationToken cancellationToken = default)
=> SendAsync<T>(HttpMethod.Get, url, null, cancellationToken);
public Task<T> PostAsync<T>(string url, object? body = null, CancellationToken cancellationToken = default)
=> SendAsync<T>(HttpMethod.Post, url, body, cancellationToken);
/// <summary>POST for endpoints that answer 204 No Content.</summary>
public async Task PostAsync(string url, object? body = null, CancellationToken cancellationToken = default)
{
using var response = await SendRawAsync(HttpMethod.Post, url, body, cancellationToken);
}
public Task<T> PutAsync<T>(string url, object? body = null, CancellationToken cancellationToken = default)
=> SendAsync<T>(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<byte[]> GetBytesAsync(string url, CancellationToken cancellationToken = default)
{
using var response = await SendRawAsync(HttpMethod.Get, url, null, cancellationToken);
return await response.Content.ReadAsByteArrayAsync(cancellationToken);
}
/// <summary>POST whose response is a file (e.g. a rendered preview workbook).</summary>
public async Task<byte[]> PostBytesAsync(string url, object? body, CancellationToken cancellationToken = default)
{
using var response = await SendRawAsync(HttpMethod.Post, url, body, cancellationToken);
return await response.Content.ReadAsByteArrayAsync(cancellationToken);
}
/// <summary>Uploads one file as multipart/form-data (field "file") with extra text fields.</summary>
public Task<T> UploadAsync<T>(string url, string filePath, IReadOnlyDictionary<string, string?> 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<T>(HttpMethod.Post, url, (Func<HttpContent>)Build, cancellationToken);
}
public void Logout()
{
AccessToken = null;
CurrentUser = null;
httpClient.DefaultRequestHeaders.Authorization = null;
}
private async Task<T> SendAsync<T>(HttpMethod method, string url, object? body, CancellationToken cancellationToken)
{
using var response = await SendRawAsync(method, url, body, cancellationToken);
try
{
return await response.Content.ReadFromJsonAsync<T>(cancellationToken: cancellationToken)
?? throw new ApiException("服务器返回了空结果。");
}
catch (JsonException ex)
{
throw new ApiException("服务器返回的数据格式不正确。", ex);
}
}
private async Task<HttpResponseMessage> SendRawAsync(HttpMethod method, string url, object? body, CancellationToken cancellationToken)
{
try
{
using var request = new HttpRequestMessage(method, url);
if (body is Func<HttpContent> 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<string> 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<string>();
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;
}
+220
View File
@@ -0,0 +1,220 @@
<Application x:Class="Leiren.Erp.Client.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Leiren.Erp.Client">
<Application.Resources>
<!-- One look for every page and dialog: white controls, light borders, rounded corners. -->
<SolidColorBrush x:Key="Ink" Color="#18212F" />
<SolidColorBrush x:Key="LineBrush" Color="#D6DEEA" />
<SolidColorBrush x:Key="AccentBrush" Color="#2667E8" />
<Style TargetType="Button">
<Setter Property="Background" Value="White" />
<Setter Property="Foreground" Value="#41516A" />
<Setter Property="BorderBrush" Value="{StaticResource LineBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Padding" Value="13,7" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="8" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="Center" RecognizesAccessKey="True" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True"><Setter TargetName="Bd" Property="Opacity" Value="0.86" /></Trigger>
<Trigger Property="IsPressed" Value="True"><Setter TargetName="Bd" Property="Opacity" Value="0.72" /></Trigger>
<Trigger Property="IsEnabled" Value="False"><Setter TargetName="Bd" Property="Opacity" Value="0.45" /></Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="PrimaryAction" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Background" Value="{StaticResource AccentBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource AccentBrush}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style TargetType="TextBox">
<Setter Property="BorderBrush" Value="{StaticResource LineBrush}" />
<Setter Property="Background" Value="White" />
<Setter Property="Padding" Value="6,3" />
<Setter Property="MinHeight" Value="30" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
<Style TargetType="PasswordBox">
<Setter Property="BorderBrush" Value="{StaticResource LineBrush}" />
<Setter Property="Padding" Value="6,3" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
<!-- Combo box: white field, light border, rounded, Fluent chevron; same look as the text boxes. -->
<Style x:Key="ComboToggle" TargetType="ToggleButton">
<Setter Property="Focusable" Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Border Background="Transparent">
<TextBlock Text="&#xE70D;" FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets" FontSize="10" Foreground="#667085"
HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="ComboBox">
<Setter Property="Background" Value="White" />
<Setter Property="BorderBrush" Value="{StaticResource LineBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Foreground" Value="{StaticResource Ink}" />
<Setter Property="Padding" Value="9,5,28,5" />
<Setter Property="MinHeight" Value="32" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="ScrollViewer.CanContentScroll" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBox">
<Grid>
<Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="6" />
<ToggleButton Style="{StaticResource ComboToggle}" ClickMode="Press"
IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" />
<ContentPresenter x:Name="ContentSite" IsHitTestVisible="False" Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="Left"
Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" />
<TextBox x:Name="PART_EditableTextBox" Visibility="Collapsed" Margin="4,1,24,1" Padding="5,3"
Background="Transparent" BorderThickness="0" MinHeight="0" VerticalContentAlignment="Center"
IsReadOnly="{TemplateBinding IsReadOnly}" />
<Popup x:Name="PART_Popup" Placement="Bottom" AllowsTransparency="True" Focusable="False"
IsOpen="{TemplateBinding IsDropDownOpen}" PopupAnimation="Fade">
<Border Background="White" BorderBrush="{StaticResource LineBrush}" BorderThickness="1" CornerRadius="6" Margin="0,4,0,0"
MinWidth="{Binding ActualWidth, RelativeSource={RelativeSource TemplatedParent}}" MaxHeight="{TemplateBinding MaxDropDownHeight}" Padding="4">
<ScrollViewer SnapsToDevicePixels="True">
<ItemsPresenter KeyboardNavigation.DirectionalNavigation="Contained" />
</ScrollViewer>
</Border>
</Popup>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEditable" Value="True">
<Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Visible" />
<Setter TargetName="ContentSite" Property="Visibility" Value="Hidden" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True"><Setter TargetName="Bd" Property="BorderBrush" Value="#AFC1DA" /></Trigger>
<Trigger Property="IsKeyboardFocusWithin" Value="True"><Setter TargetName="Bd" Property="BorderBrush" Value="{StaticResource AccentBrush}" /></Trigger>
<Trigger Property="IsEnabled" Value="False"><Setter Property="Opacity" Value="0.55" /></Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="ComboBoxItem">
<Setter Property="Padding" Value="8,6" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBoxItem">
<Border x:Name="Bd" Background="Transparent" CornerRadius="4" Padding="{TemplateBinding Padding}">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True"><Setter TargetName="Bd" Property="Background" Value="#F2F5FA" /></Trigger>
<Trigger Property="IsSelected" Value="True"><Setter TargetName="Bd" Property="Background" Value="#EAF2FF" /></Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Date picker: same field look as the combo box, Fluent calendar glyph, placeholder 选择日期. -->
<Style TargetType="DatePickerTextBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DatePickerTextBox">
<Grid>
<ScrollViewer x:Name="PART_ContentHost" Margin="0" VerticalAlignment="Center" />
<ContentControl x:Name="PART_Watermark" Foreground="#98A2B3" IsHitTestVisible="False" Focusable="False"
VerticalAlignment="Center" Opacity="0" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="DatePicker">
<Setter Property="Background" Value="White" />
<Setter Property="BorderBrush" Value="{StaticResource LineBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Foreground" Value="{StaticResource Ink}" />
<Setter Property="Padding" Value="9,0,4,0" />
<Setter Property="MinHeight" Value="32" />
<Setter Property="IsTodayHighlighted" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DatePicker">
<Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="6" Padding="{TemplateBinding Padding}">
<Grid x:Name="PART_Root">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<DatePickerTextBox x:Name="PART_TextBox" VerticalContentAlignment="Center" Background="Transparent" BorderThickness="0" />
<Button x:Name="PART_Button" Grid.Column="1" Focusable="False" Width="28" Padding="0" Background="Transparent" BorderThickness="0"
Foreground="#667085" Cursor="Hand">
<TextBlock Text="&#xE787;" FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets" FontSize="13" HorizontalAlignment="Center" />
</Button>
<Popup x:Name="PART_Popup" PlacementTarget="{Binding ElementName=PART_TextBox}" Placement="Bottom" StaysOpen="False" AllowsTransparency="True" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True"><Setter TargetName="Bd" Property="BorderBrush" Value="#AFC1DA" /></Trigger>
<Trigger Property="IsKeyboardFocusWithin" Value="True"><Setter TargetName="Bd" Property="BorderBrush" Value="{StaticResource AccentBrush}" /></Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="DataGrid">
<Setter Property="Background" Value="White" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="GridLinesVisibility" Value="Horizontal" />
<Setter Property="HorizontalGridLinesBrush" Value="#EEF1F6" />
<Setter Property="HeadersVisibility" Value="Column" />
<Setter Property="RowHeight" Value="34" />
<Setter Property="FontSize" Value="12" />
<Setter Property="Foreground" Value="{StaticResource Ink}" />
<Setter Property="RowHeaderWidth" Value="0" />
</Style>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="#F5F6F8" />
<Setter Property="Foreground" Value="#667085" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="FontSize" Value="12" />
<Setter Property="Padding" Value="10,8" />
<Setter Property="BorderBrush" Value="#E4E7EC" />
<Setter Property="BorderThickness" Value="0,0,0,1" />
</Style>
<Style TargetType="DataGridCell">
<Setter Property="Padding" Value="10,0" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridCell">
<Border Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}">
<ContentPresenter VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="#EAF2FF" />
<Setter Property="Foreground" Value="{StaticResource Ink}" />
</Trigger>
</Style.Triggers>
</Style>
</Application.Resources>
</Application>
+70
View File
@@ -0,0 +1,70 @@
using System.Windows;
namespace Leiren.Erp.Client;
/// <summary>
/// Start-up: restore a kept session silently; only when that is not possible
/// show the login window, then open the main window.
/// </summary>
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();
}
/// <summary>Shows the login window; null when the user closes it.</summary>
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, "无法恢复登录,请检查服务器连接。");
}
}
/// <summary>Persists (or forgets) the refresh token whenever the session changes.</summary>
private void SaveSession(LoginResponse result)
{
settings.UserName = settings.KeepSignedIn ? result.UserName : settings.UserName;
settings.RefreshToken = settings.KeepSignedIn ? result.RefreshToken : null;
settings.Save();
}
}
+10
View File
@@ -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)
)]
+120
View File
@@ -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<string, string> 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;
}
/// <summary>Forgets the session; the user name and the "保持登录" choice stay for the next sign-in.</summary>
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;
}
}
@@ -0,0 +1,84 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Leiren.Erp.Client.Controls;
/// <summary>Shared look for the code-built dialogs (template editor, container numbers).</summary>
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,
};
/// <summary>Right-aligned button row with spacing.</summary>
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;
}
}
@@ -0,0 +1,20 @@
using System.Globalization;
using System.Windows.Data;
using Leiren.Erp.Client.Pages;
namespace Leiren.Erp.Client.Controls;
/// <summary>Shows stored enum / flag values in Chinese (part and product types, yes/no).</summary>
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();
}
@@ -0,0 +1,43 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Leiren.Erp.Client.Controls;
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>Button content: an icon followed by a label.</summary>
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;
}
}
@@ -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;
/// <summary>
/// Gives the master-data pages (products, customers, suppliers, settings) the
/// same dark header band as the workflow workspace: only the page title.
/// </summary>
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;
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>Shows a status text instead of the page (loading, empty, error).</summary>
public void ShowMessage(string text)
{
image.Source = null;
page.Visibility = Visibility.Collapsed;
placeholder.Text = text;
placeholder.Visibility = Visibility.Visible;
}
/// <summary>Renders the workbook off the UI thread and shows it fitted to the view.</summary>
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);
}
/// <summary>
/// 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.
/// </summary>
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<List<byte[]>> 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);
/// <summary>Collects each rendered PNG in memory; the renderer serialises sink calls.</summary>
private sealed class MemorySink : IRenderOutputSink
{
private MemoryStream? current;
public List<byte[]> Images { get; } = [];
public ValueTask<Stream> OpenAsync(ArtifactDescriptor artifact, CancellationToken cancellationToken)
{
current = new MemoryStream();
return ValueTask.FromResult<Stream>(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;
}
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<Row> Rows { get; } = [];
public TextBlock Status { get; } = DialogKit.Note("");
}
private readonly ApiClient api;
private readonly Guid batchId;
private readonly IReadOnlyList<Guid> 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<Item> items = [];
public BillingAllocationWindow(ApiClient api, Guid batchId, string batchNo, IReadOnlyList<Guid> 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<SupplierInvoiceNoticeDto>();
foreach (var id in noticeIds) notices.Add(await api.GetAsync<SupplierInvoiceNoticeDto>($"/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);
}
}
/// <summary>One supplier invoices the whole item: it takes the quantity and the item's total amount.</summary>
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<BillingAllocationLineRequest>();
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<List<SupplierInvoiceNoticeDto>>($"/api/billing/notices/shipping-batches/{batchId}/allocation",
new ReallocateBillingRequest(lines));
window.DialogResult = true;
}
catch (ApiException ex)
{
error.Text = ex.Message;
save.IsEnabled = true;
}
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<string, TextBox> 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<SupplierInvoiceNoticeDto>($"/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<SupplierInvoiceNoticeDto>($"/api/billing/notices/{noticeId}", request);
window.DialogResult = true;
}
catch (ApiException ex)
{
error.Text = ex.Message;
save.IsEnabled = true;
}
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<string, TextBox> boxes = [];
private static readonly (string Key, string Label)[] FieldList =
[
("exportInvoiceNo", "外销发票号(空则取报关资料的发票编号)"),
("invoiceTitle", "发票抬头"),
("invoiceTitleAddress", "地址"),
("invoiceTitlePhone", "电话"),
("invoiceTitleBankName", "开户银行"),
("invoiceTitleBankAccount", "帐号"),
("invoiceTitleTaxNo", "税号"),
("invoiceTitleCustomsCode", "海关代码"),
("mailingAddress", "寄件地址"),
("contactName", "联系人"),
("signedPlace", "合同签订地点"),
];
/// <summary>Notices created by the dialog (one per supplier).</summary>
public IReadOnlyList<SupplierInvoiceNoticeDto> 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<List<SupplierInvoiceNoticeListItemDto>>("/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<SupplierInvoiceNoticeDto>($"/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<GenerateBillingNoticesResultDto>("/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;
}
}
}
@@ -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;
/// <summary>
/// Records the real container and seal numbers of a draft shipping batch
/// after loading; the packing wizard creates the containers with placeholder
/// numbers marked "柜号待补".
/// </summary>
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<Row> 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<ShippingBatchDto>($"/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<ShippingBatchDto>($"/api/shipping-batches/{batchId}/containers/{row.Container.Id}", request);
}
window.DialogResult = true;
}
catch (ApiException ex)
{
error.Text = ex.Message;
save.IsEnabled = true;
}
}
}
@@ -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;
/// <summary>
/// 报关资料 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.
/// </summary>
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<LineControls> 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<List<CustomsDeclarationListItemDto>>($"/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<CustomsDeclarationDto>("/api/customs/",
new CreateCustomsDeclarationRequest(batchId, null, null, null, null, null, null, null));
Changed = true;
}
else
{
declaration = await api.GetAsync<CustomsDeclarationDto>($"/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<bool> 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<CustomsDeclarationDto>($"/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<CustomsDeclarationDto>($"/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<CustomsDeclarationDto>($"/api/customs/{declaration.Id}/void", null);
Changed = true;
window.Close();
}
catch (ApiException ex)
{
error.Text = ex.Message;
}
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<SupplierPayableDto>($"/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;
}
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<SupplierInvoiceDto>($"/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;
}
}
}
@@ -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;
/// <summary>
/// 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 <c>{{...}}</c> placeholders.
/// </summary>
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) };
/// <summary>Customer a template is dedicated to; Id null = 通用(所有客户).</summary>
private sealed record CustomerChoice(Guid? Id, string Label);
private readonly TextBlock error = DialogKit.Note("", DialogKit.Error);
private readonly Button save = DialogKit.Primary("导入");
/// <summary>The uploaded template version, set when the dialog returns true.</summary>
public DocumentTemplateUploadResultDto? Result { get; private set; }
public TemplateImportWindow(ApiClient api, IReadOnlyList<DocumentTemplateKindDto> 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<List<CustomerDto>>("/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}";
}
}
/// <summary>Purchase-contract templates are never customer specific.</summary>
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<string, string?>
{
["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<DocumentTemplateUploadResultDto>(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;
}
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<Row> 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<DocumentTemplateMappingProfileDto?> TryGetProfileAsync(Guid templateVersionId)
{
try
{
return await api.GetAsync<DocumentTemplateMappingProfileDto>($"/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<List<DocumentTemplateFieldDto>>("/api/document-templates/fields");
var scan = await api.GetAsync<DocumentTemplateUploadResultDto>($"/api/document-templates/{template.TemplateVersionId}/scan");
profile = await TryGetProfileAsync(template.TemplateVersionId);
// A new template version starts from the previous version's choices.
Dictionary<string, string> suggestions = new(StringComparer.OrdinalIgnoreCase);
var source = profile;
if (source is null)
{
var file = await api.GetAsync<FileAttachmentDto>($"/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<FieldOption> Options(IEnumerable<DocumentTemplateFieldDto> fields)
{
var scopeName = new Dictionary<string, string> { ["Header"] = "表头", ["Line"] = "明细", ["Total"] = "合计" };
var list = new List<FieldOption> { 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<DocumentTemplateMappingProfileDto>(
$"/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<DocumentTemplateMappingProfileDto>(
$"/api/document-templates/{template.TemplateVersionId}/mappings",
new ReplaceDocumentTemplateFieldMappingsRequest(mappings));
window.DialogResult = true;
}
catch (ApiException ex)
{
error.Text = ex.Message;
save.IsEnabled = true;
}
}
}

Some files were not shown because too many files have changed in this diff Show More