Initial commit
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user