using AgriculturalPlatform.Api.Data; using Microsoft.EntityFrameworkCore; namespace AgriculturalPlatform.Api.Services; /// 业务单号生成:前缀 + 日期 + 当日序号(如 CG20260812-0001) public class NumberGenerator(AppDbContext db) { public async Task NextAsync(string prefix, DateOnly? date = null) { var day = date ?? DateOnly.FromDateTime(DateTime.Now); var seq = 1; try { // 从各单据表按当日已存在数量生成序号 var todayStart = day.ToDateTime(TimeOnly.MinValue); var todayEnd = todayStart.AddDays(1); var count = prefix switch { "CG" => await db.PurchaseOrders.CountAsync(x => x.CreatedAt >= todayStart && x.CreatedAt < todayEnd), "ZF" => await db.PaymentRecords.CountAsync(x => x.CreatedAt >= todayStart && x.CreatedAt < todayEnd), "FP" => await db.Invoices.CountAsync(x => x.CreatedAt >= todayStart && x.CreatedAt < todayEnd), "PK" => await db.Invoices .Where(x => x.CreatedAt >= todayStart && x.CreatedAt < todayEnd && x.BatchNo != "") .Select(x => x.BatchNo).Distinct().CountAsync(), _ => 0 }; seq = count + 1; } catch { // 数据库不可用时使用随机序号 } return $"{prefix}{day:yyyyMMdd}-{seq:D4}"; } }