Spaces:
Running
Running
File size: 10,142 Bytes
13240d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | using System.Text;
using BakeryErp.Infrastructure.Database;
namespace BakeryErp.Infrastructure.Repositories;
public sealed class ReportCenterRepository
{
private readonly DatabaseOptions _options;
public ReportCenterRepository(DatabaseOptions options)
{
_options = options;
}
public IReadOnlyList<LocalReportDefinition> List()
{
return LocalDataStoreFile.Load(_options)
.ReportDefinitions
.OrderBy(static report => report.ReportCategory)
.ThenBy(static report => report.ReportCode)
.ToList();
}
public LocalReportDefinition? Find(Guid id)
{
return LocalDataStoreFile.Load(_options)
.ReportDefinitions
.FirstOrDefault(report => report.Id == id);
}
public ReportCenterSummary GetSummary()
{
var store = LocalDataStoreFile.Load(_options);
return new ReportCenterSummary(
store.ReportDefinitions.Count,
store.ReportDefinitions.Count(static report => report.Status == LocalReportStatus.PendingApproval),
store.ReportDefinitions.Count(static report => report.Status == LocalReportStatus.Approved),
store.StockBalances.Count,
store.PurchaseOrders.Count,
store.PettyCashTransactions.Count,
store.TransferOrders.Count,
store.StoreReturns.Count);
}
public SaveReportDefinitionResult Save(LocalReportDefinition report)
{
var store = LocalDataStoreFile.Load(_options);
var reportCode = report.ReportCode.Trim().ToUpperInvariant();
if (string.IsNullOrWhiteSpace(reportCode) ||
string.IsNullOrWhiteSpace(report.ReportName) ||
string.IsNullOrWhiteSpace(report.ReportCategory))
{
return SaveReportDefinitionResult.ValidationError("報表代號、名稱與分類為必填。");
}
var duplicatedCode = store.ReportDefinitions.Any(existing =>
existing.Id != report.Id &&
string.Equals(existing.ReportCode, reportCode, StringComparison.OrdinalIgnoreCase));
if (duplicatedCode)
{
return SaveReportDefinitionResult.ValidationError("報表代號已存在,請改用其他代號。");
}
var existingReport = store.ReportDefinitions.FirstOrDefault(existing => existing.Id == report.Id);
if (existingReport is null)
{
report.Id = report.Id == Guid.Empty ? Guid.NewGuid() : report.Id;
report.ReportCode = reportCode;
report.ReportName = report.ReportName.Trim();
report.ReportCategory = report.ReportCategory.Trim();
report.Description = BlankToNull(report.Description);
report.Status = LocalReportStatus.PendingApproval;
report.CreatedAt = DateTime.UtcNow;
store.ReportDefinitions.Add(report);
}
else
{
if (existingReport.Status == LocalReportStatus.Approved)
{
return SaveReportDefinitionResult.ValidationError("已審核報表不可編輯。");
}
existingReport.ReportCode = reportCode;
existingReport.ReportName = report.ReportName.Trim();
existingReport.ReportCategory = report.ReportCategory.Trim();
existingReport.Description = BlankToNull(report.Description);
existingReport.Status = LocalReportStatus.PendingApproval;
existingReport.UpdatedAt = DateTime.UtcNow;
}
LocalDataStoreFile.Save(_options, store);
return SaveReportDefinitionResult.Success();
}
public void Approve(Guid id)
{
Update(id, report =>
{
report.Status = LocalReportStatus.Approved;
report.ApprovedAt = DateTime.UtcNow;
});
}
public void Cancel(Guid id)
{
Update(id, report => report.Status = LocalReportStatus.Cancelled);
}
public CsvExport Export(string reportCode)
{
var store = LocalDataStoreFile.Load(_options);
return reportCode.ToUpperInvariant() switch
{
"RPT-INVENTORY" => ExportInventory(store),
"RPT-PURCHASE" => ExportPurchases(store),
"RPT-PETTYCASH" => ExportPettyCash(store),
"RPT-TRANSFERS" => ExportTransfers(store),
"RPT-RETURNS" => ExportReturns(store),
_ => ExportReportDefinitions(store)
};
}
public static string GetStatusName(LocalReportStatus status)
{
return status switch
{
LocalReportStatus.Draft => "草稿",
LocalReportStatus.PendingApproval => "待審核",
LocalReportStatus.Approved => "已審核",
LocalReportStatus.Cancelled => "已取消",
_ => status.ToString()
};
}
private static CsvExport ExportInventory(LocalDataStore store)
{
var rows = store.StockBalances.Select(stock => new[]
{
stock.WarehouseName,
stock.ItemSku,
stock.ItemName,
stock.QuantityOnHand.ToString("0.##"),
stock.SafetyStockQuantity.ToString("0.##"),
stock.Unit
});
return Csv("inventory-report.csv", ["倉庫", "品項代號", "品項名稱", "現有庫存", "安全庫存", "單位"], rows);
}
private static CsvExport ExportPurchases(LocalDataStore store)
{
var rows = store.PurchaseOrders.Select(order => new[]
{
order.OrderNumber,
order.SupplierName,
order.OrderDate.ToString("yyyy-MM-dd"),
order.ItemName,
order.Quantity.ToString("0.##"),
order.UnitPrice.ToString("0.##"),
order.LineAmount.ToString("0.##"),
PurchaseRepository.GetStatusName(order.Status)
});
return Csv("purchase-report.csv", ["採購單號", "供應商", "日期", "品項", "數量", "單價", "金額", "狀態"], rows);
}
private static CsvExport ExportPettyCash(LocalDataStore store)
{
var rows = store.PettyCashTransactions.Select(transaction => new[]
{
transaction.TransactionNumber,
transaction.StoreName,
transaction.TransactionDate.ToString("yyyy-MM-dd"),
PettyCashRepository.GetTransactionTypeName(transaction.TransactionType),
transaction.ExpenseCategory,
transaction.Amount.ToString("0.##"),
PettyCashRepository.GetStatusName(transaction.Status)
});
return Csv("petty-cash-report.csv", ["單號", "門市", "日期", "類型", "分類", "金額", "狀態"], rows);
}
private static CsvExport ExportTransfers(LocalDataStore store)
{
var rows = store.TransferOrders.Select(order => new[]
{
order.TransferNumber,
order.StoreName,
order.ItemName,
order.RequestedQuantity.ToString("0.##"),
order.ShippedQuantity.ToString("0.##"),
order.ReceivedQuantity.ToString("0.##"),
order.DifferenceQuantity.ToString("0.##"),
TransferRepository.GetStatusName(order.Status)
});
return Csv("transfer-report.csv", ["調撥單號", "門市", "品項", "叫貨", "出庫", "收貨", "差異", "狀態"], rows);
}
private static CsvExport ExportReturns(LocalDataStore store)
{
var rows = store.StoreReturns.Select(item => new[]
{
item.ReturnNumber,
item.StoreName,
item.ItemName,
item.Quantity.ToString("0.##"),
item.Reason,
StoreReturnRepository.GetStatusName(item.Status),
StoreReturnRepository.GetDispositionName(item.Disposition)
});
return Csv("store-return-report.csv", ["退貨單號", "門市", "品項", "數量", "原因", "狀態", "處理方式"], rows);
}
private static CsvExport ExportReportDefinitions(LocalDataStore store)
{
var rows = store.ReportDefinitions.Select(report => new[]
{
report.ReportCode,
report.ReportName,
report.ReportCategory,
ReportCenterRepository.GetStatusName(report.Status)
});
return Csv("report-definitions.csv", ["報表代號", "報表名稱", "分類", "狀態"], rows);
}
private static CsvExport Csv(string fileName, IReadOnlyList<string> headers, IEnumerable<IReadOnlyList<string>> rows)
{
var builder = new StringBuilder();
builder.AppendLine(string.Join(",", headers.Select(EscapeCsv)));
foreach (var row in rows)
{
builder.AppendLine(string.Join(",", row.Select(EscapeCsv)));
}
return new CsvExport(fileName, "\uFEFF" + builder);
}
private static string EscapeCsv(string value)
{
var normalized = value.Replace("\"", "\"\"", StringComparison.Ordinal);
return $"\"{normalized}\"";
}
private void Update(Guid id, Action<LocalReportDefinition> update)
{
var store = LocalDataStoreFile.Load(_options);
var report = store.ReportDefinitions.FirstOrDefault(existing => existing.Id == id);
if (report is null)
{
return;
}
update(report);
report.UpdatedAt = DateTime.UtcNow;
LocalDataStoreFile.Save(_options, store);
}
private static string? BlankToNull(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
}
public sealed record ReportCenterSummary(
int ReportCount,
int PendingApprovalCount,
int ApprovedCount,
int InventoryRows,
int PurchaseRows,
int PettyCashRows,
int TransferRows,
int ReturnRows);
public sealed record CsvExport(string FileName, string Content);
public sealed record SaveReportDefinitionResult(bool IsSuccess, string? ErrorMessage)
{
public static SaveReportDefinitionResult Success() => new(true, null);
public static SaveReportDefinitionResult ValidationError(string message) => new(false, message);
}
|