Files
Leiren.Erp/src/Leiren.Erp.Application/Billing/BillingDocumentExportService.cs
T
2026-11-16 18:25:21 +08:00

78 lines
3.6 KiB
C#

using Leiren.Erp.Application.Documents;
using Leiren.Erp.Application.Files;
using Microsoft.EntityFrameworkCore;
namespace Leiren.Erp.Application.Billing;
/// <summary>Absolute paths of the built-in 开票通知 / 开票购销合同 templates.</summary>
public sealed record BillingTemplateOptions(string NoticeTemplatePath, string ContractTemplatePath);
/// <summary>
/// Renders a supplier notice's 开票通知书 or 开票用产品购销合同 as XLSX.
/// The most recently imported template of that type (template editor) wins;
/// without one the configured built-in template is used. Nothing is stored.
/// </summary>
public sealed class BillingDocumentExportService(IBillingDbContext db, FileService files, BillingTemplateOptions options)
{
public async Task<(byte[] Bytes, string FileName)> RenderAsync(Guid noticeId, string kind, CancellationToken ct = default)
{
var (label, fallbackPath) = kind switch
{
DocumentTemplateKinds.SupplierInvoiceNoticeKind => ("开票通知", options.NoticeTemplatePath),
DocumentTemplateKinds.SupplierBillingContractKind => ("开票购销合同", options.ContractTemplatePath),
_ => throw new BillingValidationException(nameof(kind), "单据类型只能是开票通知或开票购销合同。"),
};
var notice = await db.SupplierInvoiceNotices.AsNoTracking()
.Include(x => x.Lines)
.Include(x => x.BillingContract)
.SingleOrDefaultAsync(x => x.Id == noticeId, ct)
?? throw new BillingNotFoundException("开票通知不存在。");
var template = await LoadTemplateAsync(kind, fallbackPath, label, ct);
var bytes = BillingDocumentRenderer.Render(template, notice, label);
return (bytes, $"{Sanitize(notice.NoticeNo)}-{Sanitize(notice.SupplierName)}-{label}.xlsx");
}
/// <summary>Renders a template file against a notice for the template editor preview.</summary>
public async Task<byte[]> PreviewAsync(byte[] template, Guid noticeId, string label, CancellationToken ct = default)
{
var notice = await db.SupplierInvoiceNotices.AsNoTracking()
.Include(x => x.Lines)
.Include(x => x.BillingContract)
.SingleOrDefaultAsync(x => x.Id == noticeId, ct)
?? throw new BillingNotFoundException("开票通知不存在。");
return BillingDocumentRenderer.Render(template, notice, label);
}
private async Task<byte[]> LoadTemplateAsync(string kind, string fallbackPath, string label, CancellationToken ct)
{
var imported = (await files.ListAsync(
DocumentTemplateService.TemplateOwnerType, null, kind, null, currentOnly: true, 1, 200, ct))
.MaxBy(x => x.CreatedAt);
if (imported is not null)
{
await using var content = (await files.OpenDownloadAsync(imported.Id, ct)).Content;
using var buffer = new MemoryStream();
await content.CopyToAsync(buffer, ct);
return buffer.ToArray();
}
try
{
return await File.ReadAllBytesAsync(fallbackPath, ct);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
throw new BillingValidationException("Template", $"{label}模板读取失败:{ex.Message}");
}
}
private static string Sanitize(string value)
{
var invalid = Path.GetInvalidFileNameChars();
var stem = new string(value.Select(ch => invalid.Contains(ch) || ch < 32 ? '_' : ch).ToArray()).Trim();
return stem.Length == 0 ? "billing" : stem;
}
}