Compare commits
10 Commits
63eb02f1a5
...
fdbefca650
| Author | SHA1 | Date | |
|---|---|---|---|
| fdbefca650 | |||
| 4a7d012a58 | |||
| d330db84fc | |||
| c79e9bd6e8 | |||
| 3f308c2d0c | |||
| 5dfaac01fd | |||
| 21a689edec | |||
| 76366cbc30 | |||
| b0bb87d97c | |||
| b5aa060faf |
Submodule TakeoutSaaS.Docs updated: 6680599912...6daa444c5e
@@ -0,0 +1,285 @@
|
||||
namespace TakeoutSaaS.TenantApi.Contracts.Finance;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表列表请求。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportListRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public string StoreId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 周期类型(daily/weekly/monthly)。
|
||||
/// </summary>
|
||||
public string? PeriodType { get; set; } = "daily";
|
||||
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; set; } = 20;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表详情请求。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportDetailRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public string StoreId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 报表 ID。
|
||||
/// </summary>
|
||||
public string ReportId { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表批量导出请求。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportBatchExportRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public string StoreId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 周期类型(daily/weekly/monthly)。
|
||||
/// </summary>
|
||||
public string? PeriodType { get; set; } = "daily";
|
||||
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; set; } = 20;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表列表行响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportListItemResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 报表 ID。
|
||||
/// </summary>
|
||||
public string ReportId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 日期文案。
|
||||
/// </summary>
|
||||
public string DateText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 营业额。
|
||||
/// </summary>
|
||||
public decimal RevenueAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 订单数。
|
||||
/// </summary>
|
||||
public int OrderCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 客单价。
|
||||
/// </summary>
|
||||
public decimal AverageOrderValue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 退款率(百分数)。
|
||||
/// </summary>
|
||||
public decimal RefundRatePercent { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 成本总额。
|
||||
/// </summary>
|
||||
public decimal CostTotalAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 净利润。
|
||||
/// </summary>
|
||||
public decimal NetProfitAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 利润率(百分数)。
|
||||
/// </summary>
|
||||
public decimal ProfitRatePercent { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 状态编码。
|
||||
/// </summary>
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态文案。
|
||||
/// </summary>
|
||||
public string StatusText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 是否可下载。
|
||||
/// </summary>
|
||||
public bool CanDownload { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表列表响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportListResultResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 列表。
|
||||
/// </summary>
|
||||
public List<FinanceBusinessReportListItemResponse> Items { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 总数。
|
||||
/// </summary>
|
||||
public int Total { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// KPI 响应项。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportKpiResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 指标键。
|
||||
/// </summary>
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 指标名称。
|
||||
/// </summary>
|
||||
public string Label { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 指标值文案。
|
||||
/// </summary>
|
||||
public string ValueText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 同比变化率(百分数)。
|
||||
/// </summary>
|
||||
public decimal YoyChangeRate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 环比变化率(百分数)。
|
||||
/// </summary>
|
||||
public decimal MomChangeRate { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 明细行响应项。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportBreakdownItemResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 明细键。
|
||||
/// </summary>
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 明细名称。
|
||||
/// </summary>
|
||||
public string Label { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 占比(百分数)。
|
||||
/// </summary>
|
||||
public decimal RatioPercent { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表详情响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportDetailResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 报表 ID。
|
||||
/// </summary>
|
||||
public string ReportId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 标题。
|
||||
/// </summary>
|
||||
public string Title { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 周期类型编码。
|
||||
/// </summary>
|
||||
public string PeriodType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态编码。
|
||||
/// </summary>
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态文案。
|
||||
/// </summary>
|
||||
public string StatusText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// KPI 列表。
|
||||
/// </summary>
|
||||
public List<FinanceBusinessReportKpiResponse> Kpis { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 收入明细(按渠道)。
|
||||
/// </summary>
|
||||
public List<FinanceBusinessReportBreakdownItemResponse> IncomeBreakdowns { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 成本明细(按类别)。
|
||||
/// </summary>
|
||||
public List<FinanceBusinessReportBreakdownItemResponse> CostBreakdowns { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表导出响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportExportResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 文件名。
|
||||
/// </summary>
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Base64 文件内容。
|
||||
/// </summary>
|
||||
public string FileContentBase64 { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 导出总记录数。
|
||||
/// </summary>
|
||||
public int TotalCount { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,533 @@
|
||||
namespace TakeoutSaaS.TenantApi.Contracts.Finance;
|
||||
|
||||
/// <summary>
|
||||
/// 保存发票设置请求。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceSettingSaveRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 企业名称。
|
||||
/// </summary>
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 纳税人识别号。
|
||||
/// </summary>
|
||||
public string TaxpayerNumber { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 注册地址。
|
||||
/// </summary>
|
||||
public string? RegisteredAddress { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 注册电话。
|
||||
/// </summary>
|
||||
public string? RegisteredPhone { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开户银行。
|
||||
/// </summary>
|
||||
public string? BankName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 银行账号。
|
||||
/// </summary>
|
||||
public string? BankAccount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用电子普通发票。
|
||||
/// </summary>
|
||||
public bool EnableElectronicNormalInvoice { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用电子专用发票。
|
||||
/// </summary>
|
||||
public bool EnableElectronicSpecialInvoice { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用自动开票。
|
||||
/// </summary>
|
||||
public bool EnableAutoIssue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 自动开票单张最大金额。
|
||||
/// </summary>
|
||||
public decimal AutoIssueMaxAmount { get; set; } = 10_000m;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票记录列表请求。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceRecordListRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 开始日期(yyyy-MM-dd)。
|
||||
/// </summary>
|
||||
public string? StartDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 结束日期(yyyy-MM-dd)。
|
||||
/// </summary>
|
||||
public string? EndDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 状态(pending/issued/voided)。
|
||||
/// </summary>
|
||||
public string? Status { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 类型(normal/special)。
|
||||
/// </summary>
|
||||
public string? InvoiceType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 关键词(发票号/公司名/申请人)。
|
||||
/// </summary>
|
||||
public string? Keyword { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; set; } = 10;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票记录详情请求。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceRecordDetailRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 发票记录 ID。
|
||||
/// </summary>
|
||||
public string RecordId { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票开票请求。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceRecordIssueRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 发票记录 ID。
|
||||
/// </summary>
|
||||
public string RecordId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 接收邮箱(可选)。
|
||||
/// </summary>
|
||||
public string? ContactEmail { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开票备注。
|
||||
/// </summary>
|
||||
public string? IssueRemark { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票作废请求。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceRecordVoidRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 发票记录 ID。
|
||||
/// </summary>
|
||||
public string RecordId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 作废原因。
|
||||
/// </summary>
|
||||
public string VoidReason { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票申请请求。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceRecordApplyRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 申请人。
|
||||
/// </summary>
|
||||
public string ApplicantName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开票抬头(公司名)。
|
||||
/// </summary>
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 纳税人识别号。
|
||||
/// </summary>
|
||||
public string? TaxpayerNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 发票类型(normal/special)。
|
||||
/// </summary>
|
||||
public string InvoiceType { get; set; } = "normal";
|
||||
|
||||
/// <summary>
|
||||
/// 开票金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 关联订单号。
|
||||
/// </summary>
|
||||
public string OrderNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 接收邮箱。
|
||||
/// </summary>
|
||||
public string? ContactEmail { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 联系电话。
|
||||
/// </summary>
|
||||
public string? ContactPhone { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 申请备注。
|
||||
/// </summary>
|
||||
public string? ApplyRemark { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 申请时间(可空)。
|
||||
/// </summary>
|
||||
public DateTime? AppliedAt { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票设置响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceSettingResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 企业名称。
|
||||
/// </summary>
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 纳税人识别号。
|
||||
/// </summary>
|
||||
public string TaxpayerNumber { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 注册地址。
|
||||
/// </summary>
|
||||
public string? RegisteredAddress { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 注册电话。
|
||||
/// </summary>
|
||||
public string? RegisteredPhone { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开户银行。
|
||||
/// </summary>
|
||||
public string? BankName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 银行账号。
|
||||
/// </summary>
|
||||
public string? BankAccount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用电子普通发票。
|
||||
/// </summary>
|
||||
public bool EnableElectronicNormalInvoice { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用电子专用发票。
|
||||
/// </summary>
|
||||
public bool EnableElectronicSpecialInvoice { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用自动开票。
|
||||
/// </summary>
|
||||
public bool EnableAutoIssue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 自动开票单张最大金额。
|
||||
/// </summary>
|
||||
public decimal AutoIssueMaxAmount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票统计响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceStatsResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 本月已开票金额。
|
||||
/// </summary>
|
||||
public decimal CurrentMonthIssuedAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 本月已开票张数。
|
||||
/// </summary>
|
||||
public int CurrentMonthIssuedCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 待开票数量。
|
||||
/// </summary>
|
||||
public int PendingCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已作废数量。
|
||||
/// </summary>
|
||||
public int VoidedCount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票记录列表项响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceRecordResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 记录 ID。
|
||||
/// </summary>
|
||||
public string RecordId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 发票号码。
|
||||
/// </summary>
|
||||
public string InvoiceNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 申请人。
|
||||
/// </summary>
|
||||
public string ApplicantName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开票抬头(公司名)。
|
||||
/// </summary>
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 发票类型编码。
|
||||
/// </summary>
|
||||
public string InvoiceType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 发票类型文案。
|
||||
/// </summary>
|
||||
public string InvoiceTypeText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 关联订单号。
|
||||
/// </summary>
|
||||
public string OrderNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态编码。
|
||||
/// </summary>
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态文案。
|
||||
/// </summary>
|
||||
public string StatusText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 申请时间(本地显示字符串)。
|
||||
/// </summary>
|
||||
public string AppliedAt { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票记录详情响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceRecordDetailResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 记录 ID。
|
||||
/// </summary>
|
||||
public string RecordId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 发票号码。
|
||||
/// </summary>
|
||||
public string InvoiceNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 申请人。
|
||||
/// </summary>
|
||||
public string ApplicantName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开票抬头(公司名)。
|
||||
/// </summary>
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 纳税人识别号。
|
||||
/// </summary>
|
||||
public string? TaxpayerNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 发票类型编码。
|
||||
/// </summary>
|
||||
public string InvoiceType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 发票类型文案。
|
||||
/// </summary>
|
||||
public string InvoiceTypeText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 关联订单号。
|
||||
/// </summary>
|
||||
public string OrderNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 接收邮箱。
|
||||
/// </summary>
|
||||
public string? ContactEmail { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 联系电话。
|
||||
/// </summary>
|
||||
public string? ContactPhone { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 申请备注。
|
||||
/// </summary>
|
||||
public string? ApplyRemark { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 状态编码。
|
||||
/// </summary>
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态文案。
|
||||
/// </summary>
|
||||
public string StatusText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 申请时间(本地显示字符串)。
|
||||
/// </summary>
|
||||
public string AppliedAt { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开票时间(本地显示字符串)。
|
||||
/// </summary>
|
||||
public string? IssuedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开票人 ID。
|
||||
/// </summary>
|
||||
public string? IssuedByUserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开票备注。
|
||||
/// </summary>
|
||||
public string? IssueRemark { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 作废时间(本地显示字符串)。
|
||||
/// </summary>
|
||||
public string? VoidedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 作废人 ID。
|
||||
/// </summary>
|
||||
public string? VoidedByUserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 作废原因。
|
||||
/// </summary>
|
||||
public string? VoidReason { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票开票结果响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceIssueResultResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 记录 ID。
|
||||
/// </summary>
|
||||
public string RecordId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 发票号码。
|
||||
/// </summary>
|
||||
public string InvoiceNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开票抬头。
|
||||
/// </summary>
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 接收邮箱。
|
||||
/// </summary>
|
||||
public string? ContactEmail { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开票时间(本地显示字符串)。
|
||||
/// </summary>
|
||||
public string IssuedAt { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态编码。
|
||||
/// </summary>
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态文案。
|
||||
/// </summary>
|
||||
public string StatusText { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票记录分页响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceRecordListResultResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 列表项。
|
||||
/// </summary>
|
||||
public List<FinanceInvoiceRecordResponse> Items { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 总条数。
|
||||
/// </summary>
|
||||
public int TotalCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 统计。
|
||||
/// </summary>
|
||||
public FinanceInvoiceStatsResponse Stats { get; set; } = new();
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
namespace TakeoutSaaS.TenantApi.Contracts.Finance;
|
||||
|
||||
/// <summary>
|
||||
/// 到账统计请求。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementStatsRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public string StoreId { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账筛选请求。
|
||||
/// </summary>
|
||||
public class FinanceSettlementFilterRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public string StoreId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开始日期(yyyy-MM-dd)。
|
||||
/// </summary>
|
||||
public string? StartDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 结束日期(yyyy-MM-dd)。
|
||||
/// </summary>
|
||||
public string? EndDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 渠道(wechat/alipay)。
|
||||
/// </summary>
|
||||
public string? Channel { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账列表请求。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementListRequest : FinanceSettlementFilterRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; set; } = 20;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账明细请求。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementDetailRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public string StoreId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 到账日期(yyyy-MM-dd)。
|
||||
/// </summary>
|
||||
public string ArrivedDate { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 渠道(wechat/alipay)。
|
||||
/// </summary>
|
||||
public string Channel { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账统计响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementStatsResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 今日到账。
|
||||
/// </summary>
|
||||
public decimal TodayArrivedAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 昨日到账。
|
||||
/// </summary>
|
||||
public decimal YesterdayArrivedAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 本月到账。
|
||||
/// </summary>
|
||||
public decimal CurrentMonthArrivedAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 本月交易笔数。
|
||||
/// </summary>
|
||||
public int CurrentMonthTransactionCount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账账户信息响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementAccountResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 银行名称。
|
||||
/// </summary>
|
||||
public string BankName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开户名。
|
||||
/// </summary>
|
||||
public string BankAccountName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 脱敏银行账号。
|
||||
/// </summary>
|
||||
public string BankAccountNoMasked { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 脱敏微信商户号。
|
||||
/// </summary>
|
||||
public string WechatMerchantNoMasked { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 脱敏支付宝 PID。
|
||||
/// </summary>
|
||||
public string AlipayPidMasked { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 结算周期文案。
|
||||
/// </summary>
|
||||
public string SettlementPeriodText { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账列表行响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementListItemResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 到账日期。
|
||||
/// </summary>
|
||||
public string ArrivedDate { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 渠道编码。
|
||||
/// </summary>
|
||||
public string Channel { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 渠道文案。
|
||||
/// </summary>
|
||||
public string ChannelText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 交易笔数。
|
||||
/// </summary>
|
||||
public int TransactionCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 到账金额。
|
||||
/// </summary>
|
||||
public decimal ArrivedAmount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账列表响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementListResultResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 列表项。
|
||||
/// </summary>
|
||||
public List<FinanceSettlementListItemResponse> Items { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 总数。
|
||||
/// </summary>
|
||||
public int Total { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账明细行响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementDetailItemResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 订单号。
|
||||
/// </summary>
|
||||
public string OrderNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 支付时间。
|
||||
/// </summary>
|
||||
public string PaidAt { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账明细响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementDetailResultResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 明细列表。
|
||||
/// </summary>
|
||||
public List<FinanceSettlementDetailItemResponse> Items { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账导出响应。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementExportResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// 文件名。
|
||||
/// </summary>
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 文件内容(Base64)。
|
||||
/// </summary>
|
||||
public string FileContentBase64 { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 导出总数。
|
||||
/// </summary>
|
||||
public int TotalCount { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
using System.Globalization;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Commands;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Queries;
|
||||
using TakeoutSaaS.Domain.Tenants.Enums;
|
||||
using TakeoutSaaS.Module.Authorization.Attributes;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
using TakeoutSaaS.Shared.Abstractions.Results;
|
||||
using TakeoutSaaS.Shared.Web.Api;
|
||||
using TakeoutSaaS.TenantApi.Contracts.Finance;
|
||||
|
||||
namespace TakeoutSaaS.TenantApi.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// 财务中心发票管理。
|
||||
/// </summary>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/tenant/v{version:apiVersion}/finance/invoice")]
|
||||
public sealed class FinanceInvoiceController(IMediator mediator) : BaseApiController
|
||||
{
|
||||
private const string ViewPermission = "tenant:finance:invoice:view";
|
||||
private const string IssuePermission = "tenant:finance:invoice:issue";
|
||||
private const string VoidPermission = "tenant:finance:invoice:void";
|
||||
private const string SettingsPermission = "tenant:finance:invoice:settings";
|
||||
|
||||
/// <summary>
|
||||
/// 查询发票设置详情。
|
||||
/// </summary>
|
||||
[HttpGet("settings/detail")]
|
||||
[PermissionAuthorize(ViewPermission, SettingsPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceInvoiceSettingResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceInvoiceSettingResponse>> SettingsDetail(CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new GetFinanceInvoiceSettingDetailQuery(), cancellationToken);
|
||||
return ApiResponse<FinanceInvoiceSettingResponse>.Ok(MapSetting(result));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存发票设置。
|
||||
/// </summary>
|
||||
[HttpPost("settings/save")]
|
||||
[PermissionAuthorize(SettingsPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceInvoiceSettingResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceInvoiceSettingResponse>> SettingsSave(
|
||||
[FromBody] FinanceInvoiceSettingSaveRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new SaveFinanceInvoiceSettingCommand
|
||||
{
|
||||
CompanyName = request.CompanyName,
|
||||
TaxpayerNumber = request.TaxpayerNumber,
|
||||
RegisteredAddress = request.RegisteredAddress,
|
||||
RegisteredPhone = request.RegisteredPhone,
|
||||
BankName = request.BankName,
|
||||
BankAccount = request.BankAccount,
|
||||
EnableElectronicNormalInvoice = request.EnableElectronicNormalInvoice,
|
||||
EnableElectronicSpecialInvoice = request.EnableElectronicSpecialInvoice,
|
||||
EnableAutoIssue = request.EnableAutoIssue,
|
||||
AutoIssueMaxAmount = request.AutoIssueMaxAmount
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceInvoiceSettingResponse>.Ok(MapSetting(result));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询发票记录分页。
|
||||
/// </summary>
|
||||
[HttpGet("record/list")]
|
||||
[PermissionAuthorize(ViewPermission, IssuePermission, VoidPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceInvoiceRecordListResultResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceInvoiceRecordListResultResponse>> RecordList(
|
||||
[FromQuery] FinanceInvoiceRecordListRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new GetFinanceInvoiceRecordListQuery
|
||||
{
|
||||
StartDateUtc = ParseDateOrNull(request.StartDate, nameof(request.StartDate)),
|
||||
EndDateUtc = ParseDateOrNull(request.EndDate, nameof(request.EndDate)),
|
||||
Status = ParseStatusOrNull(request.Status),
|
||||
InvoiceType = ParseInvoiceTypeOrNull(request.InvoiceType),
|
||||
Keyword = request.Keyword,
|
||||
Page = request.Page,
|
||||
PageSize = request.PageSize
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceInvoiceRecordListResultResponse>.Ok(new FinanceInvoiceRecordListResultResponse
|
||||
{
|
||||
Items = result.Items.Select(MapRecord).ToList(),
|
||||
Page = result.Page,
|
||||
PageSize = result.PageSize,
|
||||
TotalCount = result.TotalCount,
|
||||
Stats = new FinanceInvoiceStatsResponse
|
||||
{
|
||||
CurrentMonthIssuedAmount = result.Stats.CurrentMonthIssuedAmount,
|
||||
CurrentMonthIssuedCount = result.Stats.CurrentMonthIssuedCount,
|
||||
PendingCount = result.Stats.PendingCount,
|
||||
VoidedCount = result.Stats.VoidedCount
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询发票记录详情。
|
||||
/// </summary>
|
||||
[HttpGet("record/detail")]
|
||||
[PermissionAuthorize(ViewPermission, IssuePermission, VoidPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceInvoiceRecordDetailResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceInvoiceRecordDetailResponse>> RecordDetail(
|
||||
[FromQuery] FinanceInvoiceRecordDetailRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new GetFinanceInvoiceRecordDetailQuery
|
||||
{
|
||||
RecordId = StoreApiHelpers.ParseRequiredSnowflake(request.RecordId, nameof(request.RecordId))
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceInvoiceRecordDetailResponse>.Ok(MapRecordDetail(result));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票开票。
|
||||
/// </summary>
|
||||
[HttpPost("record/issue")]
|
||||
[PermissionAuthorize(IssuePermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceInvoiceIssueResultResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceInvoiceIssueResultResponse>> RecordIssue(
|
||||
[FromBody] FinanceInvoiceRecordIssueRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new IssueFinanceInvoiceRecordCommand
|
||||
{
|
||||
RecordId = StoreApiHelpers.ParseRequiredSnowflake(request.RecordId, nameof(request.RecordId)),
|
||||
ContactEmail = request.ContactEmail,
|
||||
IssueRemark = request.IssueRemark
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceInvoiceIssueResultResponse>.Ok(MapIssueResult(result));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 作废发票。
|
||||
/// </summary>
|
||||
[HttpPost("record/void")]
|
||||
[PermissionAuthorize(VoidPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceInvoiceRecordDetailResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceInvoiceRecordDetailResponse>> RecordVoid(
|
||||
[FromBody] FinanceInvoiceRecordVoidRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new VoidFinanceInvoiceRecordCommand
|
||||
{
|
||||
RecordId = StoreApiHelpers.ParseRequiredSnowflake(request.RecordId, nameof(request.RecordId)),
|
||||
VoidReason = request.VoidReason
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceInvoiceRecordDetailResponse>.Ok(MapRecordDetail(result));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 申请发票。
|
||||
/// </summary>
|
||||
[HttpPost("record/apply")]
|
||||
[PermissionAuthorize(ViewPermission, IssuePermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceInvoiceRecordDetailResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceInvoiceRecordDetailResponse>> RecordApply(
|
||||
[FromBody] FinanceInvoiceRecordApplyRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await mediator.Send(new ApplyFinanceInvoiceRecordCommand
|
||||
{
|
||||
ApplicantName = request.ApplicantName,
|
||||
CompanyName = request.CompanyName,
|
||||
TaxpayerNumber = request.TaxpayerNumber,
|
||||
InvoiceType = request.InvoiceType,
|
||||
Amount = request.Amount,
|
||||
OrderNo = request.OrderNo,
|
||||
ContactEmail = request.ContactEmail,
|
||||
ContactPhone = request.ContactPhone,
|
||||
ApplyRemark = request.ApplyRemark,
|
||||
AppliedAt = request.AppliedAt
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceInvoiceRecordDetailResponse>.Ok(MapRecordDetail(result));
|
||||
}
|
||||
|
||||
private static DateTime? ParseDateOrNull(string? value, string fieldName)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(value)
|
||||
? null
|
||||
: StoreApiHelpers.ParseDateOnly(value, fieldName);
|
||||
}
|
||||
|
||||
private static TenantInvoiceStatus? ParseStatusOrNull(string? value)
|
||||
{
|
||||
var normalized = (value ?? string.Empty).Trim().ToLowerInvariant();
|
||||
if (string.IsNullOrWhiteSpace(normalized))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalized switch
|
||||
{
|
||||
"pending" => TenantInvoiceStatus.Pending,
|
||||
"issued" => TenantInvoiceStatus.Issued,
|
||||
"voided" => TenantInvoiceStatus.Voided,
|
||||
_ => throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法")
|
||||
};
|
||||
}
|
||||
|
||||
private static TenantInvoiceType? ParseInvoiceTypeOrNull(string? value)
|
||||
{
|
||||
var normalized = (value ?? string.Empty).Trim().ToLowerInvariant();
|
||||
if (string.IsNullOrWhiteSpace(normalized))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalized switch
|
||||
{
|
||||
"normal" => TenantInvoiceType.Normal,
|
||||
"special" => TenantInvoiceType.Special,
|
||||
_ => throw new BusinessException(ErrorCodes.BadRequest, "invoiceType 参数不合法")
|
||||
};
|
||||
}
|
||||
|
||||
private static FinanceInvoiceSettingResponse MapSetting(FinanceInvoiceSettingDto source)
|
||||
{
|
||||
return new FinanceInvoiceSettingResponse
|
||||
{
|
||||
CompanyName = source.CompanyName,
|
||||
TaxpayerNumber = source.TaxpayerNumber,
|
||||
RegisteredAddress = source.RegisteredAddress,
|
||||
RegisteredPhone = source.RegisteredPhone,
|
||||
BankName = source.BankName,
|
||||
BankAccount = source.BankAccount,
|
||||
EnableElectronicNormalInvoice = source.EnableElectronicNormalInvoice,
|
||||
EnableElectronicSpecialInvoice = source.EnableElectronicSpecialInvoice,
|
||||
EnableAutoIssue = source.EnableAutoIssue,
|
||||
AutoIssueMaxAmount = source.AutoIssueMaxAmount
|
||||
};
|
||||
}
|
||||
|
||||
private static FinanceInvoiceRecordResponse MapRecord(FinanceInvoiceRecordDto source)
|
||||
{
|
||||
return new FinanceInvoiceRecordResponse
|
||||
{
|
||||
RecordId = source.RecordId.ToString(),
|
||||
InvoiceNo = source.InvoiceNo,
|
||||
ApplicantName = source.ApplicantName,
|
||||
CompanyName = source.CompanyName,
|
||||
InvoiceType = source.InvoiceType,
|
||||
InvoiceTypeText = source.InvoiceTypeText,
|
||||
Amount = source.Amount,
|
||||
OrderNo = source.OrderNo,
|
||||
Status = source.Status,
|
||||
StatusText = source.StatusText,
|
||||
AppliedAt = source.AppliedAt.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)
|
||||
};
|
||||
}
|
||||
|
||||
private static FinanceInvoiceRecordDetailResponse MapRecordDetail(FinanceInvoiceRecordDetailDto source)
|
||||
{
|
||||
return new FinanceInvoiceRecordDetailResponse
|
||||
{
|
||||
RecordId = source.RecordId.ToString(),
|
||||
InvoiceNo = source.InvoiceNo,
|
||||
ApplicantName = source.ApplicantName,
|
||||
CompanyName = source.CompanyName,
|
||||
TaxpayerNumber = source.TaxpayerNumber,
|
||||
InvoiceType = source.InvoiceType,
|
||||
InvoiceTypeText = source.InvoiceTypeText,
|
||||
Amount = source.Amount,
|
||||
OrderNo = source.OrderNo,
|
||||
ContactEmail = source.ContactEmail,
|
||||
ContactPhone = source.ContactPhone,
|
||||
ApplyRemark = source.ApplyRemark,
|
||||
Status = source.Status,
|
||||
StatusText = source.StatusText,
|
||||
AppliedAt = source.AppliedAt.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
IssuedAt = source.IssuedAt?.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
IssuedByUserId = source.IssuedByUserId?.ToString(),
|
||||
IssueRemark = source.IssueRemark,
|
||||
VoidedAt = source.VoidedAt?.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
VoidedByUserId = source.VoidedByUserId?.ToString(),
|
||||
VoidReason = source.VoidReason
|
||||
};
|
||||
}
|
||||
|
||||
private static FinanceInvoiceIssueResultResponse MapIssueResult(FinanceInvoiceIssueResultDto source)
|
||||
{
|
||||
return new FinanceInvoiceIssueResultResponse
|
||||
{
|
||||
RecordId = source.RecordId.ToString(),
|
||||
InvoiceNo = source.InvoiceNo,
|
||||
CompanyName = source.CompanyName,
|
||||
Amount = source.Amount,
|
||||
ContactEmail = source.ContactEmail,
|
||||
IssuedAt = source.IssuedAt.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
Status = source.Status,
|
||||
StatusText = source.StatusText
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
using TakeoutSaaS.Application.App.Stores.Services;
|
||||
using TakeoutSaaS.Domain.Finance.Enums;
|
||||
using TakeoutSaaS.Infrastructure.App.Persistence;
|
||||
using TakeoutSaaS.Module.Authorization.Attributes;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
using TakeoutSaaS.Shared.Abstractions.Results;
|
||||
using TakeoutSaaS.Shared.Web.Api;
|
||||
using TakeoutSaaS.TenantApi.Contracts.Finance;
|
||||
|
||||
namespace TakeoutSaaS.TenantApi.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// 财务中心经营报表。
|
||||
/// </summary>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/tenant/v{version:apiVersion}/finance/report")]
|
||||
public sealed class FinanceReportController(
|
||||
IMediator mediator,
|
||||
TakeoutAppDbContext dbContext,
|
||||
StoreContextService storeContextService) : BaseApiController
|
||||
{
|
||||
private const string ViewPermission = "tenant:statistics:report:view";
|
||||
private const string ExportPermission = "tenant:statistics:report:export";
|
||||
|
||||
/// <summary>
|
||||
/// 查询经营报表列表。
|
||||
/// </summary>
|
||||
[HttpGet("list")]
|
||||
[PermissionAuthorize(ViewPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceBusinessReportListResultResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceBusinessReportListResultResponse>> List(
|
||||
[FromQuery] FinanceBusinessReportListRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验门店访问权限并解析查询参数。
|
||||
var storeId = StoreApiHelpers.ParseRequiredSnowflake(request.StoreId, nameof(request.StoreId));
|
||||
await EnsureStoreAccessibleAsync(storeId, cancellationToken);
|
||||
var periodType = ParsePeriodType(request.PeriodType);
|
||||
|
||||
// 2. 发起查询并返回结果。
|
||||
var result = await mediator.Send(new SearchFinanceBusinessReportListQuery
|
||||
{
|
||||
StoreId = storeId,
|
||||
PeriodType = periodType,
|
||||
Page = Math.Max(1, request.Page),
|
||||
PageSize = Math.Clamp(request.PageSize, 1, 200)
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceBusinessReportListResultResponse>.Ok(new FinanceBusinessReportListResultResponse
|
||||
{
|
||||
Items = result.Items.Select(MapListItem).ToList(),
|
||||
Total = result.Total,
|
||||
Page = result.Page,
|
||||
PageSize = result.PageSize
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询经营报表详情。
|
||||
/// </summary>
|
||||
[HttpGet("detail")]
|
||||
[PermissionAuthorize(ViewPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceBusinessReportDetailResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceBusinessReportDetailResponse>> Detail(
|
||||
[FromQuery] FinanceBusinessReportDetailRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验门店访问权限并解析参数。
|
||||
var storeId = StoreApiHelpers.ParseRequiredSnowflake(request.StoreId, nameof(request.StoreId));
|
||||
await EnsureStoreAccessibleAsync(storeId, cancellationToken);
|
||||
var reportId = StoreApiHelpers.ParseRequiredSnowflake(request.ReportId, nameof(request.ReportId));
|
||||
|
||||
// 2. 发起详情查询。
|
||||
var detail = await mediator.Send(new GetFinanceBusinessReportDetailQuery
|
||||
{
|
||||
StoreId = storeId,
|
||||
ReportId = reportId
|
||||
}, cancellationToken);
|
||||
|
||||
if (detail is null)
|
||||
{
|
||||
return ApiResponse<FinanceBusinessReportDetailResponse>.Error(ErrorCodes.NotFound, "经营报表不存在");
|
||||
}
|
||||
|
||||
return ApiResponse<FinanceBusinessReportDetailResponse>.Ok(MapDetail(detail));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 导出单条报表 PDF。
|
||||
/// </summary>
|
||||
[HttpGet("export/pdf")]
|
||||
[PermissionAuthorize(ExportPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceBusinessReportExportResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceBusinessReportExportResponse>> ExportPdf(
|
||||
[FromQuery] FinanceBusinessReportDetailRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验门店访问权限并解析参数。
|
||||
var storeId = StoreApiHelpers.ParseRequiredSnowflake(request.StoreId, nameof(request.StoreId));
|
||||
await EnsureStoreAccessibleAsync(storeId, cancellationToken);
|
||||
var reportId = StoreApiHelpers.ParseRequiredSnowflake(request.ReportId, nameof(request.ReportId));
|
||||
|
||||
// 2. 执行导出。
|
||||
var export = await mediator.Send(new ExportFinanceBusinessReportPdfQuery
|
||||
{
|
||||
StoreId = storeId,
|
||||
ReportId = reportId
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceBusinessReportExportResponse>.Ok(MapExport(export));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 导出单条报表 Excel。
|
||||
/// </summary>
|
||||
[HttpGet("export/excel")]
|
||||
[PermissionAuthorize(ExportPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceBusinessReportExportResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceBusinessReportExportResponse>> ExportExcel(
|
||||
[FromQuery] FinanceBusinessReportDetailRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验门店访问权限并解析参数。
|
||||
var storeId = StoreApiHelpers.ParseRequiredSnowflake(request.StoreId, nameof(request.StoreId));
|
||||
await EnsureStoreAccessibleAsync(storeId, cancellationToken);
|
||||
var reportId = StoreApiHelpers.ParseRequiredSnowflake(request.ReportId, nameof(request.ReportId));
|
||||
|
||||
// 2. 执行导出。
|
||||
var export = await mediator.Send(new ExportFinanceBusinessReportExcelQuery
|
||||
{
|
||||
StoreId = storeId,
|
||||
ReportId = reportId
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceBusinessReportExportResponse>.Ok(MapExport(export));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 批量导出报表 ZIP(PDF + Excel)。
|
||||
/// </summary>
|
||||
[HttpGet("export/batch")]
|
||||
[PermissionAuthorize(ExportPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceBusinessReportExportResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceBusinessReportExportResponse>> ExportBatch(
|
||||
[FromQuery] FinanceBusinessReportBatchExportRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 校验门店访问权限并解析参数。
|
||||
var storeId = StoreApiHelpers.ParseRequiredSnowflake(request.StoreId, nameof(request.StoreId));
|
||||
await EnsureStoreAccessibleAsync(storeId, cancellationToken);
|
||||
var periodType = ParsePeriodType(request.PeriodType);
|
||||
|
||||
// 2. 执行批量导出。
|
||||
var export = await mediator.Send(new ExportFinanceBusinessReportBatchQuery
|
||||
{
|
||||
StoreId = storeId,
|
||||
PeriodType = periodType,
|
||||
Page = Math.Max(1, request.Page),
|
||||
PageSize = Math.Clamp(request.PageSize, 1, 200)
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceBusinessReportExportResponse>.Ok(MapExport(export));
|
||||
}
|
||||
|
||||
private async Task EnsureStoreAccessibleAsync(long storeId, CancellationToken cancellationToken)
|
||||
{
|
||||
var (tenantId, merchantId) = StoreApiHelpers.GetTenantMerchantContext(storeContextService);
|
||||
await StoreApiHelpers.EnsureStoreAccessibleAsync(dbContext, tenantId, merchantId, storeId, cancellationToken);
|
||||
}
|
||||
|
||||
private static FinanceBusinessReportPeriodType ParsePeriodType(string? value)
|
||||
{
|
||||
return (value ?? string.Empty).Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"" or "daily" => FinanceBusinessReportPeriodType.Daily,
|
||||
"weekly" => FinanceBusinessReportPeriodType.Weekly,
|
||||
"monthly" => FinanceBusinessReportPeriodType.Monthly,
|
||||
_ => throw new BusinessException(ErrorCodes.BadRequest, "periodType 参数不合法")
|
||||
};
|
||||
}
|
||||
|
||||
private static FinanceBusinessReportListItemResponse MapListItem(FinanceBusinessReportListItemDto source)
|
||||
{
|
||||
return new FinanceBusinessReportListItemResponse
|
||||
{
|
||||
ReportId = source.ReportId,
|
||||
DateText = source.DateText,
|
||||
RevenueAmount = source.RevenueAmount,
|
||||
OrderCount = source.OrderCount,
|
||||
AverageOrderValue = source.AverageOrderValue,
|
||||
RefundRatePercent = source.RefundRatePercent,
|
||||
CostTotalAmount = source.CostTotalAmount,
|
||||
NetProfitAmount = source.NetProfitAmount,
|
||||
ProfitRatePercent = source.ProfitRatePercent,
|
||||
Status = source.Status,
|
||||
StatusText = source.StatusText,
|
||||
CanDownload = source.CanDownload
|
||||
};
|
||||
}
|
||||
|
||||
private static FinanceBusinessReportDetailResponse MapDetail(FinanceBusinessReportDetailDto source)
|
||||
{
|
||||
return new FinanceBusinessReportDetailResponse
|
||||
{
|
||||
ReportId = source.ReportId,
|
||||
Title = source.Title,
|
||||
PeriodType = source.PeriodType,
|
||||
Status = source.Status,
|
||||
StatusText = source.StatusText,
|
||||
Kpis = source.Kpis.Select(item => new FinanceBusinessReportKpiResponse
|
||||
{
|
||||
Key = item.Key,
|
||||
Label = item.Label,
|
||||
ValueText = item.ValueText,
|
||||
YoyChangeRate = item.YoyChangeRate,
|
||||
MomChangeRate = item.MomChangeRate
|
||||
}).ToList(),
|
||||
IncomeBreakdowns = source.IncomeBreakdowns.Select(MapBreakdown).ToList(),
|
||||
CostBreakdowns = source.CostBreakdowns.Select(MapBreakdown).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
private static FinanceBusinessReportBreakdownItemResponse MapBreakdown(FinanceBusinessReportBreakdownItemDto source)
|
||||
{
|
||||
return new FinanceBusinessReportBreakdownItemResponse
|
||||
{
|
||||
Key = source.Key,
|
||||
Label = source.Label,
|
||||
Amount = source.Amount,
|
||||
RatioPercent = source.RatioPercent
|
||||
};
|
||||
}
|
||||
|
||||
private static FinanceBusinessReportExportResponse MapExport(FinanceBusinessReportExportDto source)
|
||||
{
|
||||
return new FinanceBusinessReportExportResponse
|
||||
{
|
||||
FileName = source.FileName,
|
||||
FileContentBase64 = source.FileContentBase64,
|
||||
TotalCount = source.TotalCount
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
using System.Globalization;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Queries;
|
||||
using TakeoutSaaS.Application.App.Stores.Services;
|
||||
using TakeoutSaaS.Domain.Payments.Enums;
|
||||
using TakeoutSaaS.Infrastructure.App.Persistence;
|
||||
using TakeoutSaaS.Module.Authorization.Attributes;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
using TakeoutSaaS.Shared.Abstractions.Results;
|
||||
using TakeoutSaaS.Shared.Web.Api;
|
||||
using TakeoutSaaS.TenantApi.Contracts.Finance;
|
||||
|
||||
namespace TakeoutSaaS.TenantApi.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// 财务中心到账查询。
|
||||
/// </summary>
|
||||
[ApiVersion("1.0")]
|
||||
[Authorize]
|
||||
[Route("api/tenant/v{version:apiVersion}/finance/settlement")]
|
||||
public sealed class FinanceSettlementController(
|
||||
IMediator mediator,
|
||||
TakeoutAppDbContext dbContext,
|
||||
StoreContextService storeContextService) : BaseApiController
|
||||
{
|
||||
private const string ViewPermission = "tenant:finance:settlement:view";
|
||||
private const string ExportPermission = "tenant:finance:settlement:export";
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账统计。
|
||||
/// </summary>
|
||||
[HttpGet("stats")]
|
||||
[PermissionAuthorize(ViewPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceSettlementStatsResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceSettlementStatsResponse>> Stats(
|
||||
[FromQuery] FinanceSettlementStatsRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var storeId = StoreApiHelpers.ParseRequiredSnowflake(request.StoreId, nameof(request.StoreId));
|
||||
await EnsureStoreAccessibleAsync(storeId, cancellationToken);
|
||||
|
||||
var stats = await mediator.Send(new GetFinanceSettlementStatsQuery
|
||||
{
|
||||
StoreId = storeId
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceSettlementStatsResponse>.Ok(new FinanceSettlementStatsResponse
|
||||
{
|
||||
TodayArrivedAmount = stats.TodayArrivedAmount,
|
||||
YesterdayArrivedAmount = stats.YesterdayArrivedAmount,
|
||||
CurrentMonthArrivedAmount = stats.CurrentMonthArrivedAmount,
|
||||
CurrentMonthTransactionCount = stats.CurrentMonthTransactionCount
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账账户信息。
|
||||
/// </summary>
|
||||
[HttpGet("account")]
|
||||
[PermissionAuthorize(ViewPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceSettlementAccountResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceSettlementAccountResponse>> Account(
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var account = await mediator.Send(new GetFinanceSettlementAccountQuery(), cancellationToken);
|
||||
if (account is null)
|
||||
{
|
||||
return ApiResponse<FinanceSettlementAccountResponse>.Error(ErrorCodes.NotFound, "结算账户信息不存在");
|
||||
}
|
||||
|
||||
return ApiResponse<FinanceSettlementAccountResponse>.Ok(new FinanceSettlementAccountResponse
|
||||
{
|
||||
BankName = account.BankName,
|
||||
BankAccountName = account.BankAccountName,
|
||||
BankAccountNoMasked = account.BankAccountNoMasked,
|
||||
WechatMerchantNoMasked = account.WechatMerchantNoMasked,
|
||||
AlipayPidMasked = account.AlipayPidMasked,
|
||||
SettlementPeriodText = account.SettlementPeriodText
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账汇总列表。
|
||||
/// </summary>
|
||||
[HttpGet("list")]
|
||||
[PermissionAuthorize(ViewPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceSettlementListResultResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceSettlementListResultResponse>> List(
|
||||
[FromQuery] FinanceSettlementListRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var parsed = await ParseFilterAsync(request, cancellationToken);
|
||||
|
||||
var result = await mediator.Send(new SearchFinanceSettlementListQuery
|
||||
{
|
||||
StoreId = parsed.StoreId,
|
||||
StartAt = parsed.StartAt,
|
||||
EndAt = parsed.EndAt,
|
||||
PaymentMethod = parsed.PaymentMethod,
|
||||
Page = Math.Max(1, request.Page),
|
||||
PageSize = Math.Clamp(request.PageSize, 1, 200)
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceSettlementListResultResponse>.Ok(new FinanceSettlementListResultResponse
|
||||
{
|
||||
Items = result.Items.Select(MapListItem).ToList(),
|
||||
Total = result.Total,
|
||||
Page = result.Page,
|
||||
PageSize = result.PageSize
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账明细(展开行)。
|
||||
/// </summary>
|
||||
[HttpGet("detail")]
|
||||
[PermissionAuthorize(ViewPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceSettlementDetailResultResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceSettlementDetailResultResponse>> Detail(
|
||||
[FromQuery] FinanceSettlementDetailRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var storeId = StoreApiHelpers.ParseRequiredSnowflake(request.StoreId, nameof(request.StoreId));
|
||||
await EnsureStoreAccessibleAsync(storeId, cancellationToken);
|
||||
|
||||
var arrivedDate = ParseRequiredDate(request.ArrivedDate, nameof(request.ArrivedDate));
|
||||
var paymentMethod = ParseRequiredSettlementChannel(request.Channel);
|
||||
|
||||
var result = await mediator.Send(new GetFinanceSettlementDetailQuery
|
||||
{
|
||||
StoreId = storeId,
|
||||
ArrivedDate = arrivedDate,
|
||||
PaymentMethod = paymentMethod,
|
||||
Take = 50
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceSettlementDetailResultResponse>.Ok(new FinanceSettlementDetailResultResponse
|
||||
{
|
||||
Items = result.Items.Select(MapDetailItem).ToList()
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 导出到账汇总 CSV。
|
||||
/// </summary>
|
||||
[HttpGet("export")]
|
||||
[PermissionAuthorize(ExportPermission)]
|
||||
[ProducesResponseType(typeof(ApiResponse<FinanceSettlementExportResponse>), StatusCodes.Status200OK)]
|
||||
public async Task<ApiResponse<FinanceSettlementExportResponse>> Export(
|
||||
[FromQuery] FinanceSettlementFilterRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var parsed = await ParseFilterAsync(request, cancellationToken);
|
||||
|
||||
var result = await mediator.Send(new ExportFinanceSettlementCsvQuery
|
||||
{
|
||||
StoreId = parsed.StoreId,
|
||||
StartAt = parsed.StartAt,
|
||||
EndAt = parsed.EndAt,
|
||||
PaymentMethod = parsed.PaymentMethod
|
||||
}, cancellationToken);
|
||||
|
||||
return ApiResponse<FinanceSettlementExportResponse>.Ok(new FinanceSettlementExportResponse
|
||||
{
|
||||
FileName = result.FileName,
|
||||
FileContentBase64 = result.FileContentBase64,
|
||||
TotalCount = result.TotalCount
|
||||
});
|
||||
}
|
||||
|
||||
private async Task<(long StoreId, DateTime? StartAt, DateTime? EndAt, PaymentMethod? PaymentMethod)> ParseFilterAsync(
|
||||
FinanceSettlementFilterRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var storeId = StoreApiHelpers.ParseRequiredSnowflake(request.StoreId, nameof(request.StoreId));
|
||||
await EnsureStoreAccessibleAsync(storeId, cancellationToken);
|
||||
|
||||
var startAt = ParseDateOrNull(request.StartDate);
|
||||
var endAt = ParseDateOrNull(request.EndDate)?.AddDays(1);
|
||||
if (startAt.HasValue && endAt.HasValue && startAt >= endAt)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "开始日期不能晚于结束日期");
|
||||
}
|
||||
|
||||
return (storeId, startAt, endAt, ParseOptionalSettlementChannel(request.Channel));
|
||||
}
|
||||
|
||||
private async Task EnsureStoreAccessibleAsync(long storeId, CancellationToken cancellationToken)
|
||||
{
|
||||
var (tenantId, merchantId) = StoreApiHelpers.GetTenantMerchantContext(storeContextService);
|
||||
await StoreApiHelpers.EnsureStoreAccessibleAsync(dbContext, tenantId, merchantId, storeId, cancellationToken);
|
||||
}
|
||||
|
||||
private static DateTime ParseRequiredDate(string? value, string parameterName)
|
||||
{
|
||||
return ParseDateOrNull(value)
|
||||
?? throw new BusinessException(ErrorCodes.BadRequest, $"{parameterName} 必填,格式为 yyyy-MM-dd");
|
||||
}
|
||||
|
||||
private static DateTime? ParseDateOrNull(string? value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (DateTime.TryParseExact(
|
||||
value,
|
||||
"yyyy-MM-dd",
|
||||
CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.None,
|
||||
out var parsed))
|
||||
{
|
||||
return DateTime.SpecifyKind(parsed.Date, DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "日期格式必须为 yyyy-MM-dd");
|
||||
}
|
||||
|
||||
private static PaymentMethod ParseRequiredSettlementChannel(string? channel)
|
||||
{
|
||||
return ParseOptionalSettlementChannel(channel)
|
||||
?? throw new BusinessException(ErrorCodes.BadRequest, "channel 必填,仅支持 wechat 或 alipay");
|
||||
}
|
||||
|
||||
private static PaymentMethod? ParseOptionalSettlementChannel(string? channel)
|
||||
{
|
||||
return (channel ?? string.Empty).Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"wechat" => PaymentMethod.WeChatPay,
|
||||
"alipay" => PaymentMethod.Alipay,
|
||||
"" => null,
|
||||
_ => throw new BusinessException(ErrorCodes.BadRequest, "channel 仅支持 wechat 或 alipay")
|
||||
};
|
||||
}
|
||||
|
||||
private static FinanceSettlementListItemResponse MapListItem(FinanceSettlementListItemDto source)
|
||||
{
|
||||
return new FinanceSettlementListItemResponse
|
||||
{
|
||||
ArrivedDate = source.ArrivedDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
Channel = source.Channel,
|
||||
ChannelText = source.ChannelText,
|
||||
TransactionCount = source.TransactionCount,
|
||||
ArrivedAmount = source.ArrivedAmount
|
||||
};
|
||||
}
|
||||
|
||||
private static FinanceSettlementDetailItemResponse MapDetailItem(FinanceSettlementDetailItemDto source)
|
||||
{
|
||||
return new FinanceSettlementDetailItemResponse
|
||||
{
|
||||
OrderNo = source.OrderNo,
|
||||
Amount = source.Amount,
|
||||
PaidAt = source.PaidAt.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// 申请发票记录命令。
|
||||
/// </summary>
|
||||
public sealed class ApplyFinanceInvoiceRecordCommand : IRequest<FinanceInvoiceRecordDetailDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 申请人。
|
||||
/// </summary>
|
||||
public string ApplicantName { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开票抬头(公司名)。
|
||||
/// </summary>
|
||||
public string CompanyName { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 纳税人识别号。
|
||||
/// </summary>
|
||||
public string? TaxpayerNumber { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 发票类型(normal/special)。
|
||||
/// </summary>
|
||||
public string InvoiceType { get; init; } = "normal";
|
||||
|
||||
/// <summary>
|
||||
/// 开票金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 关联订单号。
|
||||
/// </summary>
|
||||
public string OrderNo { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 接收邮箱。
|
||||
/// </summary>
|
||||
public string? ContactEmail { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 联系电话。
|
||||
/// </summary>
|
||||
public string? ContactPhone { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 申请备注。
|
||||
/// </summary>
|
||||
public string? ApplyRemark { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 申请时间(可空,默认当前 UTC)。
|
||||
/// </summary>
|
||||
public DateTime? AppliedAt { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// 开票命令。
|
||||
/// </summary>
|
||||
public sealed class IssueFinanceInvoiceRecordCommand : IRequest<FinanceInvoiceIssueResultDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 发票记录 ID。
|
||||
/// </summary>
|
||||
public long RecordId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 接收邮箱(可选,传入会覆盖原值)。
|
||||
/// </summary>
|
||||
public string? ContactEmail { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 开票备注。
|
||||
/// </summary>
|
||||
public string? IssueRemark { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// 保存发票设置命令。
|
||||
/// </summary>
|
||||
public sealed class SaveFinanceInvoiceSettingCommand : IRequest<FinanceInvoiceSettingDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 企业名称。
|
||||
/// </summary>
|
||||
public string CompanyName { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 纳税人识别号。
|
||||
/// </summary>
|
||||
public string TaxpayerNumber { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 注册地址。
|
||||
/// </summary>
|
||||
public string? RegisteredAddress { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 注册电话。
|
||||
/// </summary>
|
||||
public string? RegisteredPhone { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 开户银行。
|
||||
/// </summary>
|
||||
public string? BankName { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 银行账号。
|
||||
/// </summary>
|
||||
public string? BankAccount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用电子普通发票。
|
||||
/// </summary>
|
||||
public bool EnableElectronicNormalInvoice { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用电子专用发票。
|
||||
/// </summary>
|
||||
public bool EnableElectronicSpecialInvoice { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用自动开票。
|
||||
/// </summary>
|
||||
public bool EnableAutoIssue { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 自动开票单张最大金额。
|
||||
/// </summary>
|
||||
public decimal AutoIssueMaxAmount { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// 作废发票命令。
|
||||
/// </summary>
|
||||
public sealed class VoidFinanceInvoiceRecordCommand : IRequest<FinanceInvoiceRecordDetailDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 发票记录 ID。
|
||||
/// </summary>
|
||||
public long RecordId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 作废原因。
|
||||
/// </summary>
|
||||
public string VoidReason { get; init; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
|
||||
/// <summary>
|
||||
/// 发票开票结果 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceIssueResultDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 记录 ID。
|
||||
/// </summary>
|
||||
public long RecordId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 发票号码。
|
||||
/// </summary>
|
||||
public string InvoiceNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开票抬头。
|
||||
/// </summary>
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 接收邮箱。
|
||||
/// </summary>
|
||||
public string? ContactEmail { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开票时间(UTC)。
|
||||
/// </summary>
|
||||
public DateTime IssuedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 状态编码。
|
||||
/// </summary>
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态文案。
|
||||
/// </summary>
|
||||
public string StatusText { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
|
||||
/// <summary>
|
||||
/// 发票记录详情 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceRecordDetailDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 记录 ID。
|
||||
/// </summary>
|
||||
public long RecordId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 发票号码。
|
||||
/// </summary>
|
||||
public string InvoiceNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 申请人。
|
||||
/// </summary>
|
||||
public string ApplicantName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开票抬头(公司名)。
|
||||
/// </summary>
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 纳税人识别号。
|
||||
/// </summary>
|
||||
public string? TaxpayerNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 发票类型编码。
|
||||
/// </summary>
|
||||
public string InvoiceType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 发票类型文案。
|
||||
/// </summary>
|
||||
public string InvoiceTypeText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 关联订单号。
|
||||
/// </summary>
|
||||
public string OrderNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 接收邮箱。
|
||||
/// </summary>
|
||||
public string? ContactEmail { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 联系电话。
|
||||
/// </summary>
|
||||
public string? ContactPhone { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 申请备注。
|
||||
/// </summary>
|
||||
public string? ApplyRemark { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 状态编码。
|
||||
/// </summary>
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态文案。
|
||||
/// </summary>
|
||||
public string StatusText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 申请时间(UTC)。
|
||||
/// </summary>
|
||||
public DateTime AppliedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开票时间(UTC)。
|
||||
/// </summary>
|
||||
public DateTime? IssuedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开票人 ID。
|
||||
/// </summary>
|
||||
public long? IssuedByUserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开票备注。
|
||||
/// </summary>
|
||||
public string? IssueRemark { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 作废时间(UTC)。
|
||||
/// </summary>
|
||||
public DateTime? VoidedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 作废人 ID。
|
||||
/// </summary>
|
||||
public long? VoidedByUserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 作废原因。
|
||||
/// </summary>
|
||||
public string? VoidReason { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
|
||||
/// <summary>
|
||||
/// 发票记录列表项 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceRecordDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 记录 ID。
|
||||
/// </summary>
|
||||
public long RecordId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 发票号码。
|
||||
/// </summary>
|
||||
public string InvoiceNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 申请人。
|
||||
/// </summary>
|
||||
public string ApplicantName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开票抬头(公司名)。
|
||||
/// </summary>
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 发票类型编码。
|
||||
/// </summary>
|
||||
public string InvoiceType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 发票类型文案。
|
||||
/// </summary>
|
||||
public string InvoiceTypeText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 关联订单号。
|
||||
/// </summary>
|
||||
public string OrderNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态编码。
|
||||
/// </summary>
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态文案。
|
||||
/// </summary>
|
||||
public string StatusText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 申请时间(UTC)。
|
||||
/// </summary>
|
||||
public DateTime AppliedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
|
||||
/// <summary>
|
||||
/// 发票记录分页结果 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceRecordListResultDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 列表项。
|
||||
/// </summary>
|
||||
public List<FinanceInvoiceRecordDto> Items { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 总条数。
|
||||
/// </summary>
|
||||
public int TotalCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 统计。
|
||||
/// </summary>
|
||||
public FinanceInvoiceStatsDto Stats { get; set; } = new();
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
|
||||
/// <summary>
|
||||
/// 发票设置 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceSettingDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 企业名称。
|
||||
/// </summary>
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 纳税人识别号。
|
||||
/// </summary>
|
||||
public string TaxpayerNumber { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 注册地址。
|
||||
/// </summary>
|
||||
public string? RegisteredAddress { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 注册电话。
|
||||
/// </summary>
|
||||
public string? RegisteredPhone { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开户银行。
|
||||
/// </summary>
|
||||
public string? BankName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 银行账号。
|
||||
/// </summary>
|
||||
public string? BankAccount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用电子普通发票。
|
||||
/// </summary>
|
||||
public bool EnableElectronicNormalInvoice { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用电子专用发票。
|
||||
/// </summary>
|
||||
public bool EnableElectronicSpecialInvoice { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用自动开票。
|
||||
/// </summary>
|
||||
public bool EnableAutoIssue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 自动开票单张最大金额。
|
||||
/// </summary>
|
||||
public decimal AutoIssueMaxAmount { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
|
||||
/// <summary>
|
||||
/// 发票统计 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceInvoiceStatsDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 本月已开票金额。
|
||||
/// </summary>
|
||||
public decimal CurrentMonthIssuedAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 本月已开票张数。
|
||||
/// </summary>
|
||||
public int CurrentMonthIssuedCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 待开票数量。
|
||||
/// </summary>
|
||||
public int PendingCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已作废数量。
|
||||
/// </summary>
|
||||
public int VoidedCount { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Commands;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
using TakeoutSaaS.Domain.Tenants.Entities;
|
||||
using TakeoutSaaS.Domain.Tenants.Enums;
|
||||
using TakeoutSaaS.Domain.Tenants.Repositories;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice;
|
||||
|
||||
/// <summary>
|
||||
/// 发票模块 DTO 构造器。
|
||||
/// </summary>
|
||||
internal static class FinanceInvoiceDtoFactory
|
||||
{
|
||||
public static FinanceInvoiceSettingDto CreateDefaultSettingDto()
|
||||
{
|
||||
return new FinanceInvoiceSettingDto
|
||||
{
|
||||
CompanyName = string.Empty,
|
||||
TaxpayerNumber = string.Empty,
|
||||
RegisteredAddress = null,
|
||||
RegisteredPhone = null,
|
||||
BankName = null,
|
||||
BankAccount = null,
|
||||
EnableElectronicNormalInvoice = true,
|
||||
EnableElectronicSpecialInvoice = false,
|
||||
EnableAutoIssue = false,
|
||||
AutoIssueMaxAmount = 10_000m
|
||||
};
|
||||
}
|
||||
|
||||
public static FinanceInvoiceSettingDto ToSettingDto(TenantInvoiceSetting source)
|
||||
{
|
||||
return new FinanceInvoiceSettingDto
|
||||
{
|
||||
CompanyName = source.CompanyName,
|
||||
TaxpayerNumber = source.TaxpayerNumber,
|
||||
RegisteredAddress = source.RegisteredAddress,
|
||||
RegisteredPhone = source.RegisteredPhone,
|
||||
BankName = source.BankName,
|
||||
BankAccount = source.BankAccount,
|
||||
EnableElectronicNormalInvoice = source.EnableElectronicNormalInvoice,
|
||||
EnableElectronicSpecialInvoice = source.EnableElectronicSpecialInvoice,
|
||||
EnableAutoIssue = source.EnableAutoIssue,
|
||||
AutoIssueMaxAmount = decimal.Round(source.AutoIssueMaxAmount, 2, MidpointRounding.AwayFromZero)
|
||||
};
|
||||
}
|
||||
|
||||
public static TenantInvoiceSetting CreateSettingEntity(
|
||||
SaveFinanceInvoiceSettingCommand request,
|
||||
string companyName,
|
||||
string taxpayerNumber,
|
||||
string? registeredAddress,
|
||||
string? registeredPhone,
|
||||
string? bankName,
|
||||
string? bankAccount,
|
||||
decimal autoIssueMaxAmount)
|
||||
{
|
||||
return new TenantInvoiceSetting
|
||||
{
|
||||
CompanyName = companyName,
|
||||
TaxpayerNumber = taxpayerNumber,
|
||||
RegisteredAddress = registeredAddress,
|
||||
RegisteredPhone = registeredPhone,
|
||||
BankName = bankName,
|
||||
BankAccount = bankAccount,
|
||||
EnableElectronicNormalInvoice = request.EnableElectronicNormalInvoice,
|
||||
EnableElectronicSpecialInvoice = request.EnableElectronicSpecialInvoice,
|
||||
EnableAutoIssue = request.EnableAutoIssue,
|
||||
AutoIssueMaxAmount = autoIssueMaxAmount
|
||||
};
|
||||
}
|
||||
|
||||
public static void ApplySettingChanges(
|
||||
TenantInvoiceSetting entity,
|
||||
SaveFinanceInvoiceSettingCommand request,
|
||||
string companyName,
|
||||
string taxpayerNumber,
|
||||
string? registeredAddress,
|
||||
string? registeredPhone,
|
||||
string? bankName,
|
||||
string? bankAccount,
|
||||
decimal autoIssueMaxAmount)
|
||||
{
|
||||
entity.CompanyName = companyName;
|
||||
entity.TaxpayerNumber = taxpayerNumber;
|
||||
entity.RegisteredAddress = registeredAddress;
|
||||
entity.RegisteredPhone = registeredPhone;
|
||||
entity.BankName = bankName;
|
||||
entity.BankAccount = bankAccount;
|
||||
entity.EnableElectronicNormalInvoice = request.EnableElectronicNormalInvoice;
|
||||
entity.EnableElectronicSpecialInvoice = request.EnableElectronicSpecialInvoice;
|
||||
entity.EnableAutoIssue = request.EnableAutoIssue;
|
||||
entity.AutoIssueMaxAmount = autoIssueMaxAmount;
|
||||
}
|
||||
|
||||
public static FinanceInvoiceStatsDto ToStatsDto(TenantInvoiceRecordStatsSnapshot source)
|
||||
{
|
||||
return new FinanceInvoiceStatsDto
|
||||
{
|
||||
CurrentMonthIssuedAmount = decimal.Round(source.CurrentMonthIssuedAmount, 2, MidpointRounding.AwayFromZero),
|
||||
CurrentMonthIssuedCount = source.CurrentMonthIssuedCount,
|
||||
PendingCount = source.PendingCount,
|
||||
VoidedCount = source.VoidedCount
|
||||
};
|
||||
}
|
||||
|
||||
public static FinanceInvoiceRecordDto ToRecordDto(TenantInvoiceRecord source)
|
||||
{
|
||||
return new FinanceInvoiceRecordDto
|
||||
{
|
||||
RecordId = source.Id,
|
||||
InvoiceNo = source.InvoiceNo,
|
||||
ApplicantName = source.ApplicantName,
|
||||
CompanyName = source.CompanyName,
|
||||
InvoiceType = FinanceInvoiceMapping.ToInvoiceTypeText(source.InvoiceType),
|
||||
InvoiceTypeText = FinanceInvoiceMapping.ToInvoiceTypeDisplayText(source.InvoiceType),
|
||||
Amount = decimal.Round(source.Amount, 2, MidpointRounding.AwayFromZero),
|
||||
OrderNo = source.OrderNo,
|
||||
Status = FinanceInvoiceMapping.ToStatusText(source.Status),
|
||||
StatusText = FinanceInvoiceMapping.ToStatusDisplayText(source.Status),
|
||||
AppliedAt = source.AppliedAt
|
||||
};
|
||||
}
|
||||
|
||||
public static FinanceInvoiceRecordDetailDto ToRecordDetailDto(TenantInvoiceRecord source)
|
||||
{
|
||||
return new FinanceInvoiceRecordDetailDto
|
||||
{
|
||||
RecordId = source.Id,
|
||||
InvoiceNo = source.InvoiceNo,
|
||||
ApplicantName = source.ApplicantName,
|
||||
CompanyName = source.CompanyName,
|
||||
TaxpayerNumber = source.TaxpayerNumber,
|
||||
InvoiceType = FinanceInvoiceMapping.ToInvoiceTypeText(source.InvoiceType),
|
||||
InvoiceTypeText = FinanceInvoiceMapping.ToInvoiceTypeDisplayText(source.InvoiceType),
|
||||
Amount = decimal.Round(source.Amount, 2, MidpointRounding.AwayFromZero),
|
||||
OrderNo = source.OrderNo,
|
||||
ContactEmail = source.ContactEmail,
|
||||
ContactPhone = source.ContactPhone,
|
||||
ApplyRemark = source.ApplyRemark,
|
||||
Status = FinanceInvoiceMapping.ToStatusText(source.Status),
|
||||
StatusText = FinanceInvoiceMapping.ToStatusDisplayText(source.Status),
|
||||
AppliedAt = source.AppliedAt,
|
||||
IssuedAt = source.IssuedAt,
|
||||
IssuedByUserId = source.IssuedByUserId,
|
||||
IssueRemark = source.IssueRemark,
|
||||
VoidedAt = source.VoidedAt,
|
||||
VoidedByUserId = source.VoidedByUserId,
|
||||
VoidReason = source.VoidReason
|
||||
};
|
||||
}
|
||||
|
||||
public static FinanceInvoiceIssueResultDto ToIssueResultDto(TenantInvoiceRecord source)
|
||||
{
|
||||
return new FinanceInvoiceIssueResultDto
|
||||
{
|
||||
RecordId = source.Id,
|
||||
InvoiceNo = source.InvoiceNo,
|
||||
CompanyName = source.CompanyName,
|
||||
Amount = decimal.Round(source.Amount, 2, MidpointRounding.AwayFromZero),
|
||||
ContactEmail = source.ContactEmail,
|
||||
IssuedAt = source.IssuedAt ?? DateTime.UtcNow,
|
||||
Status = FinanceInvoiceMapping.ToStatusText(source.Status),
|
||||
StatusText = FinanceInvoiceMapping.ToStatusDisplayText(source.Status)
|
||||
};
|
||||
}
|
||||
|
||||
public static TenantInvoiceRecord CreateRecordEntity(
|
||||
long tenantId,
|
||||
string invoiceNo,
|
||||
string applicantName,
|
||||
string companyName,
|
||||
string? taxpayerNumber,
|
||||
TenantInvoiceType invoiceType,
|
||||
decimal amount,
|
||||
string orderNo,
|
||||
string? contactEmail,
|
||||
string? contactPhone,
|
||||
string? applyRemark,
|
||||
DateTime appliedAt)
|
||||
{
|
||||
return new TenantInvoiceRecord
|
||||
{
|
||||
TenantId = tenantId,
|
||||
InvoiceNo = invoiceNo,
|
||||
ApplicantName = applicantName,
|
||||
CompanyName = companyName,
|
||||
TaxpayerNumber = taxpayerNumber,
|
||||
InvoiceType = invoiceType,
|
||||
Amount = amount,
|
||||
OrderNo = orderNo,
|
||||
ContactEmail = contactEmail,
|
||||
ContactPhone = contactPhone,
|
||||
ApplyRemark = applyRemark,
|
||||
Status = TenantInvoiceStatus.Pending,
|
||||
AppliedAt = appliedAt
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
using System.Net.Mail;
|
||||
using TakeoutSaaS.Domain.Tenants.Enums;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice;
|
||||
|
||||
/// <summary>
|
||||
/// 发票模块映射与参数标准化。
|
||||
/// </summary>
|
||||
internal static class FinanceInvoiceMapping
|
||||
{
|
||||
public static TenantInvoiceType ParseInvoiceTypeRequired(string? value)
|
||||
{
|
||||
return ParseInvoiceTypeOptional(value)
|
||||
?? throw new BusinessException(ErrorCodes.BadRequest, "invoiceType 参数不合法");
|
||||
}
|
||||
|
||||
public static TenantInvoiceType? ParseInvoiceTypeOptional(string? value)
|
||||
{
|
||||
var normalized = (value ?? string.Empty).Trim().ToLowerInvariant();
|
||||
if (string.IsNullOrWhiteSpace(normalized))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalized switch
|
||||
{
|
||||
"normal" => TenantInvoiceType.Normal,
|
||||
"special" => TenantInvoiceType.Special,
|
||||
_ => throw new BusinessException(ErrorCodes.BadRequest, "invoiceType 参数不合法")
|
||||
};
|
||||
}
|
||||
|
||||
public static TenantInvoiceStatus? ParseStatusOptional(string? value)
|
||||
{
|
||||
var normalized = (value ?? string.Empty).Trim().ToLowerInvariant();
|
||||
if (string.IsNullOrWhiteSpace(normalized))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalized switch
|
||||
{
|
||||
"pending" => TenantInvoiceStatus.Pending,
|
||||
"issued" => TenantInvoiceStatus.Issued,
|
||||
"voided" => TenantInvoiceStatus.Voided,
|
||||
_ => throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法")
|
||||
};
|
||||
}
|
||||
|
||||
public static string ToInvoiceTypeText(TenantInvoiceType value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
TenantInvoiceType.Normal => "normal",
|
||||
TenantInvoiceType.Special => "special",
|
||||
_ => "normal"
|
||||
};
|
||||
}
|
||||
|
||||
public static string ToInvoiceTypeDisplayText(TenantInvoiceType value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
TenantInvoiceType.Normal => "普票",
|
||||
TenantInvoiceType.Special => "专票",
|
||||
_ => "普票"
|
||||
};
|
||||
}
|
||||
|
||||
public static string ToStatusText(TenantInvoiceStatus value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
TenantInvoiceStatus.Pending => "pending",
|
||||
TenantInvoiceStatus.Issued => "issued",
|
||||
TenantInvoiceStatus.Voided => "voided",
|
||||
_ => "pending"
|
||||
};
|
||||
}
|
||||
|
||||
public static string ToStatusDisplayText(TenantInvoiceStatus value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
TenantInvoiceStatus.Pending => "待开票",
|
||||
TenantInvoiceStatus.Issued => "已开票",
|
||||
TenantInvoiceStatus.Voided => "已作废",
|
||||
_ => "待开票"
|
||||
};
|
||||
}
|
||||
|
||||
public static string NormalizeCompanyName(string? value)
|
||||
{
|
||||
return NormalizeRequiredText(value, "companyName", 128);
|
||||
}
|
||||
|
||||
public static string NormalizeApplicantName(string? value)
|
||||
{
|
||||
return NormalizeRequiredText(value, "applicantName", 64);
|
||||
}
|
||||
|
||||
public static string NormalizeOrderNo(string? value)
|
||||
{
|
||||
return NormalizeRequiredText(value, "orderNo", 32);
|
||||
}
|
||||
|
||||
public static string NormalizeTaxpayerNumber(string? value)
|
||||
{
|
||||
return NormalizeRequiredText(value, "taxpayerNumber", 64);
|
||||
}
|
||||
|
||||
public static string? NormalizeOptionalTaxpayerNumber(string? value)
|
||||
{
|
||||
return NormalizeOptionalText(value, "taxpayerNumber", 64);
|
||||
}
|
||||
|
||||
public static string? NormalizeOptionalKeyword(string? value)
|
||||
{
|
||||
return NormalizeOptionalText(value, "keyword", 64);
|
||||
}
|
||||
|
||||
public static string? NormalizeOptionalEmail(string? value)
|
||||
{
|
||||
var normalized = NormalizeOptionalText(value, "contactEmail", 128);
|
||||
if (normalized is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_ = new MailAddress(normalized);
|
||||
return normalized;
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "contactEmail 参数不合法");
|
||||
}
|
||||
}
|
||||
|
||||
public static string? NormalizeOptionalPhone(string? value)
|
||||
{
|
||||
return NormalizeOptionalText(value, "contactPhone", 32);
|
||||
}
|
||||
|
||||
public static string? NormalizeOptionalRemark(string? value, string fieldName, int maxLength = 256)
|
||||
{
|
||||
return NormalizeOptionalText(value, fieldName, maxLength);
|
||||
}
|
||||
|
||||
public static string NormalizeVoidReason(string? value)
|
||||
{
|
||||
return NormalizeRequiredText(value, "voidReason", 256);
|
||||
}
|
||||
|
||||
public static decimal NormalizeAmount(decimal value)
|
||||
{
|
||||
if (value <= 0)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "amount 参数不合法");
|
||||
}
|
||||
|
||||
return decimal.Round(value, 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
public static decimal NormalizeAutoIssueMaxAmount(decimal value)
|
||||
{
|
||||
if (value <= 0)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "autoIssueMaxAmount 参数不合法");
|
||||
}
|
||||
|
||||
return decimal.Round(value, 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
public static (DateTime? StartUtc, DateTime? EndUtc) NormalizeDateRange(DateTime? startUtc, DateTime? endUtc)
|
||||
{
|
||||
DateTime? normalizedStart = null;
|
||||
DateTime? normalizedEnd = null;
|
||||
|
||||
if (startUtc.HasValue)
|
||||
{
|
||||
var utcValue = NormalizeUtc(startUtc.Value);
|
||||
normalizedStart = new DateTime(utcValue.Year, utcValue.Month, utcValue.Day, 0, 0, 0, DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
if (endUtc.HasValue)
|
||||
{
|
||||
var utcValue = NormalizeUtc(endUtc.Value);
|
||||
normalizedEnd = new DateTime(utcValue.Year, utcValue.Month, utcValue.Day, 0, 0, 0, DateTimeKind.Utc)
|
||||
.AddDays(1)
|
||||
.AddTicks(-1);
|
||||
}
|
||||
|
||||
if (normalizedStart.HasValue && normalizedEnd.HasValue && normalizedStart > normalizedEnd)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "开始日期不能晚于结束日期");
|
||||
}
|
||||
|
||||
return (normalizedStart, normalizedEnd);
|
||||
}
|
||||
|
||||
public static DateTime NormalizeUtc(DateTime value)
|
||||
{
|
||||
return value.Kind switch
|
||||
{
|
||||
DateTimeKind.Utc => value,
|
||||
DateTimeKind.Local => value.ToUniversalTime(),
|
||||
_ => DateTime.SpecifyKind(value, DateTimeKind.Utc)
|
||||
};
|
||||
}
|
||||
|
||||
public static string BuildInvoiceNo(DateTime nowUtc)
|
||||
{
|
||||
var utcNow = NormalizeUtc(nowUtc);
|
||||
return $"INV{utcNow:yyyyMMddHHmmssfff}{Random.Shared.Next(100, 999)}";
|
||||
}
|
||||
|
||||
private static string NormalizeRequiredText(string? value, string fieldName, int maxLength)
|
||||
{
|
||||
var normalized = (value ?? string.Empty).Trim();
|
||||
if (string.IsNullOrWhiteSpace(normalized))
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, $"{fieldName} 参数不合法");
|
||||
}
|
||||
|
||||
if (normalized.Length > maxLength)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, $"{fieldName} 长度不能超过 {maxLength}");
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static string? NormalizeOptionalText(string? value, string fieldName, int maxLength)
|
||||
{
|
||||
var normalized = (value ?? string.Empty).Trim();
|
||||
if (normalized.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (normalized.Length > maxLength)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, $"{fieldName} 长度不能超过 {maxLength}");
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Commands;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
using TakeoutSaaS.Domain.Tenants.Entities;
|
||||
using TakeoutSaaS.Domain.Tenants.Enums;
|
||||
using TakeoutSaaS.Domain.Tenants.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
using TakeoutSaaS.Shared.Abstractions.Security;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 申请发票处理器。
|
||||
/// </summary>
|
||||
public sealed class ApplyFinanceInvoiceRecordCommandHandler(
|
||||
ITenantInvoiceRepository repository,
|
||||
ITenantProvider tenantProvider,
|
||||
ICurrentUserAccessor currentUserAccessor)
|
||||
: IRequestHandler<ApplyFinanceInvoiceRecordCommand, FinanceInvoiceRecordDetailDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceInvoiceRecordDetailDto> Handle(
|
||||
ApplyFinanceInvoiceRecordCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var invoiceType = FinanceInvoiceMapping.ParseInvoiceTypeRequired(request.InvoiceType);
|
||||
var applicantName = FinanceInvoiceMapping.NormalizeApplicantName(request.ApplicantName);
|
||||
var companyName = FinanceInvoiceMapping.NormalizeCompanyName(request.CompanyName);
|
||||
var taxpayerNumber = FinanceInvoiceMapping.NormalizeOptionalTaxpayerNumber(request.TaxpayerNumber);
|
||||
var amount = FinanceInvoiceMapping.NormalizeAmount(request.Amount);
|
||||
var orderNo = FinanceInvoiceMapping.NormalizeOrderNo(request.OrderNo);
|
||||
var contactEmail = FinanceInvoiceMapping.NormalizeOptionalEmail(request.ContactEmail);
|
||||
var contactPhone = FinanceInvoiceMapping.NormalizeOptionalPhone(request.ContactPhone);
|
||||
var applyRemark = FinanceInvoiceMapping.NormalizeOptionalRemark(request.ApplyRemark, "applyRemark");
|
||||
var appliedAt = request.AppliedAt.HasValue
|
||||
? FinanceInvoiceMapping.NormalizeUtc(request.AppliedAt.Value)
|
||||
: DateTime.UtcNow;
|
||||
|
||||
if (invoiceType == TenantInvoiceType.Special && string.IsNullOrWhiteSpace(taxpayerNumber))
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "专票必须填写纳税人识别号");
|
||||
}
|
||||
|
||||
var setting = await repository.GetSettingAsync(tenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.BadRequest, "请先完成发票设置");
|
||||
EnsureTypeEnabled(setting, invoiceType);
|
||||
|
||||
var invoiceNo = await GenerateInvoiceNoAsync(tenantId, cancellationToken);
|
||||
var entity = FinanceInvoiceDtoFactory.CreateRecordEntity(
|
||||
tenantId,
|
||||
invoiceNo,
|
||||
applicantName,
|
||||
companyName,
|
||||
taxpayerNumber,
|
||||
invoiceType,
|
||||
amount,
|
||||
orderNo,
|
||||
contactEmail,
|
||||
contactPhone,
|
||||
applyRemark,
|
||||
appliedAt);
|
||||
|
||||
if (setting.EnableAutoIssue && amount <= setting.AutoIssueMaxAmount)
|
||||
{
|
||||
entity.Status = TenantInvoiceStatus.Issued;
|
||||
entity.IssuedAt = DateTime.UtcNow;
|
||||
entity.IssuedByUserId = currentUserAccessor.IsAuthenticated ? currentUserAccessor.UserId : null;
|
||||
entity.IssueRemark = "系统自动开票";
|
||||
}
|
||||
|
||||
await repository.AddRecordAsync(entity, cancellationToken);
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return FinanceInvoiceDtoFactory.ToRecordDetailDto(entity);
|
||||
}
|
||||
|
||||
private static void EnsureTypeEnabled(TenantInvoiceSetting setting, TenantInvoiceType type)
|
||||
{
|
||||
if (type == TenantInvoiceType.Normal && !setting.EnableElectronicNormalInvoice)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "电子普通发票未启用");
|
||||
}
|
||||
|
||||
if (type == TenantInvoiceType.Special && !setting.EnableElectronicSpecialInvoice)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "电子专用发票未启用");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string> GenerateInvoiceNoAsync(long tenantId, CancellationToken cancellationToken)
|
||||
{
|
||||
for (var index = 0; index < 10; index += 1)
|
||||
{
|
||||
var invoiceNo = FinanceInvoiceMapping.BuildInvoiceNo(DateTime.UtcNow);
|
||||
var exists = await repository.ExistsInvoiceNoAsync(tenantId, invoiceNo, cancellationToken);
|
||||
if (!exists)
|
||||
{
|
||||
return invoiceNo;
|
||||
}
|
||||
}
|
||||
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "生成发票号码失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Queries;
|
||||
using TakeoutSaaS.Domain.Tenants.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 发票记录详情查询处理器。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceInvoiceRecordDetailQueryHandler(
|
||||
ITenantInvoiceRepository repository,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetFinanceInvoiceRecordDetailQuery, FinanceInvoiceRecordDetailDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceInvoiceRecordDetailDto> Handle(
|
||||
GetFinanceInvoiceRecordDetailQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var record = await repository.FindRecordByIdAsync(tenantId, request.RecordId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "发票记录不存在");
|
||||
|
||||
return FinanceInvoiceDtoFactory.ToRecordDetailDto(record);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Queries;
|
||||
using TakeoutSaaS.Domain.Tenants.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 发票记录分页查询处理器。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceInvoiceRecordListQueryHandler(
|
||||
ITenantInvoiceRepository repository,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetFinanceInvoiceRecordListQuery, FinanceInvoiceRecordListResultDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceInvoiceRecordListResultDto> Handle(
|
||||
GetFinanceInvoiceRecordListQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var keyword = FinanceInvoiceMapping.NormalizeOptionalKeyword(request.Keyword);
|
||||
var (startUtc, endUtc) = FinanceInvoiceMapping.NormalizeDateRange(request.StartDateUtc, request.EndDateUtc);
|
||||
var page = Math.Max(1, request.Page);
|
||||
var pageSize = Math.Clamp(request.PageSize, 1, 200);
|
||||
|
||||
var (items, totalCount) = await repository.SearchRecordsAsync(
|
||||
tenantId,
|
||||
startUtc,
|
||||
endUtc,
|
||||
request.Status,
|
||||
request.InvoiceType,
|
||||
keyword,
|
||||
page,
|
||||
pageSize,
|
||||
cancellationToken);
|
||||
|
||||
var statsSnapshot = await repository.GetStatsAsync(tenantId, DateTime.UtcNow, cancellationToken);
|
||||
|
||||
return new FinanceInvoiceRecordListResultDto
|
||||
{
|
||||
Items = items.Select(FinanceInvoiceDtoFactory.ToRecordDto).ToList(),
|
||||
Page = page,
|
||||
PageSize = pageSize,
|
||||
TotalCount = totalCount,
|
||||
Stats = FinanceInvoiceDtoFactory.ToStatsDto(statsSnapshot)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Queries;
|
||||
using TakeoutSaaS.Domain.Tenants.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 发票设置详情查询处理器。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceInvoiceSettingDetailQueryHandler(
|
||||
ITenantInvoiceRepository repository,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetFinanceInvoiceSettingDetailQuery, FinanceInvoiceSettingDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceInvoiceSettingDto> Handle(
|
||||
GetFinanceInvoiceSettingDetailQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var setting = await repository.GetSettingAsync(tenantId, cancellationToken);
|
||||
|
||||
return setting is null
|
||||
? FinanceInvoiceDtoFactory.CreateDefaultSettingDto()
|
||||
: FinanceInvoiceDtoFactory.ToSettingDto(setting);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Commands;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
using TakeoutSaaS.Domain.Tenants.Entities;
|
||||
using TakeoutSaaS.Domain.Tenants.Enums;
|
||||
using TakeoutSaaS.Domain.Tenants.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
using TakeoutSaaS.Shared.Abstractions.Security;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 发票开票处理器。
|
||||
/// </summary>
|
||||
public sealed class IssueFinanceInvoiceRecordCommandHandler(
|
||||
ITenantInvoiceRepository repository,
|
||||
ITenantProvider tenantProvider,
|
||||
ICurrentUserAccessor currentUserAccessor)
|
||||
: IRequestHandler<IssueFinanceInvoiceRecordCommand, FinanceInvoiceIssueResultDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceInvoiceIssueResultDto> Handle(
|
||||
IssueFinanceInvoiceRecordCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var record = await repository.FindRecordByIdAsync(tenantId, request.RecordId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "发票记录不存在");
|
||||
|
||||
if (record.Status != TenantInvoiceStatus.Pending)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "仅待开票记录允许开票");
|
||||
}
|
||||
|
||||
var setting = await repository.GetSettingAsync(tenantId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.BadRequest, "请先完成发票设置");
|
||||
EnsureTypeEnabled(setting, record.InvoiceType);
|
||||
|
||||
record.ContactEmail = FinanceInvoiceMapping.NormalizeOptionalEmail(request.ContactEmail) ?? record.ContactEmail;
|
||||
record.IssueRemark = FinanceInvoiceMapping.NormalizeOptionalRemark(request.IssueRemark, "issueRemark");
|
||||
record.Status = TenantInvoiceStatus.Issued;
|
||||
record.IssuedAt = DateTime.UtcNow;
|
||||
record.IssuedByUserId = currentUserAccessor.IsAuthenticated ? currentUserAccessor.UserId : null;
|
||||
|
||||
await repository.UpdateRecordAsync(record, cancellationToken);
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return FinanceInvoiceDtoFactory.ToIssueResultDto(record);
|
||||
}
|
||||
|
||||
private static void EnsureTypeEnabled(TenantInvoiceSetting setting, TenantInvoiceType type)
|
||||
{
|
||||
if (type == TenantInvoiceType.Normal && !setting.EnableElectronicNormalInvoice)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "电子普通发票未启用");
|
||||
}
|
||||
|
||||
if (type == TenantInvoiceType.Special && !setting.EnableElectronicSpecialInvoice)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "电子专用发票未启用");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Commands;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
using TakeoutSaaS.Domain.Tenants.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 保存发票设置处理器。
|
||||
/// </summary>
|
||||
public sealed class SaveFinanceInvoiceSettingCommandHandler(
|
||||
ITenantInvoiceRepository repository,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<SaveFinanceInvoiceSettingCommand, FinanceInvoiceSettingDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceInvoiceSettingDto> Handle(
|
||||
SaveFinanceInvoiceSettingCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!request.EnableElectronicNormalInvoice && !request.EnableElectronicSpecialInvoice)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "至少启用一种发票类型");
|
||||
}
|
||||
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var companyName = FinanceInvoiceMapping.NormalizeCompanyName(request.CompanyName);
|
||||
var taxpayerNumber = FinanceInvoiceMapping.NormalizeTaxpayerNumber(request.TaxpayerNumber);
|
||||
var registeredAddress = FinanceInvoiceMapping.NormalizeOptionalRemark(request.RegisteredAddress, "registeredAddress", 256);
|
||||
var registeredPhone = FinanceInvoiceMapping.NormalizeOptionalPhone(request.RegisteredPhone);
|
||||
var bankName = FinanceInvoiceMapping.NormalizeOptionalRemark(request.BankName, "bankName", 128);
|
||||
var bankAccount = FinanceInvoiceMapping.NormalizeOptionalRemark(request.BankAccount, "bankAccount", 64);
|
||||
var autoIssueMaxAmount = FinanceInvoiceMapping.NormalizeAutoIssueMaxAmount(request.AutoIssueMaxAmount);
|
||||
|
||||
var setting = await repository.GetSettingAsync(tenantId, cancellationToken);
|
||||
if (setting is null)
|
||||
{
|
||||
setting = FinanceInvoiceDtoFactory.CreateSettingEntity(
|
||||
request,
|
||||
companyName,
|
||||
taxpayerNumber,
|
||||
registeredAddress,
|
||||
registeredPhone,
|
||||
bankName,
|
||||
bankAccount,
|
||||
autoIssueMaxAmount);
|
||||
|
||||
await repository.AddSettingAsync(setting, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
FinanceInvoiceDtoFactory.ApplySettingChanges(
|
||||
setting,
|
||||
request,
|
||||
companyName,
|
||||
taxpayerNumber,
|
||||
registeredAddress,
|
||||
registeredPhone,
|
||||
bankName,
|
||||
bankAccount,
|
||||
autoIssueMaxAmount);
|
||||
|
||||
await repository.UpdateSettingAsync(setting, cancellationToken);
|
||||
}
|
||||
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
return FinanceInvoiceDtoFactory.ToSettingDto(setting);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Commands;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
using TakeoutSaaS.Domain.Tenants.Enums;
|
||||
using TakeoutSaaS.Domain.Tenants.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
using TakeoutSaaS.Shared.Abstractions.Security;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 发票作废处理器。
|
||||
/// </summary>
|
||||
public sealed class VoidFinanceInvoiceRecordCommandHandler(
|
||||
ITenantInvoiceRepository repository,
|
||||
ITenantProvider tenantProvider,
|
||||
ICurrentUserAccessor currentUserAccessor)
|
||||
: IRequestHandler<VoidFinanceInvoiceRecordCommand, FinanceInvoiceRecordDetailDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceInvoiceRecordDetailDto> Handle(
|
||||
VoidFinanceInvoiceRecordCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var record = await repository.FindRecordByIdAsync(tenantId, request.RecordId, cancellationToken)
|
||||
?? throw new BusinessException(ErrorCodes.NotFound, "发票记录不存在");
|
||||
|
||||
if (record.Status != TenantInvoiceStatus.Issued)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.BadRequest, "仅已开票记录允许作废");
|
||||
}
|
||||
|
||||
record.Status = TenantInvoiceStatus.Voided;
|
||||
record.VoidReason = FinanceInvoiceMapping.NormalizeVoidReason(request.VoidReason);
|
||||
record.VoidedAt = DateTime.UtcNow;
|
||||
record.VoidedByUserId = currentUserAccessor.IsAuthenticated ? currentUserAccessor.UserId : null;
|
||||
|
||||
await repository.UpdateRecordAsync(record, cancellationToken);
|
||||
await repository.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return FinanceInvoiceDtoFactory.ToRecordDetailDto(record);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 查询发票记录详情。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceInvoiceRecordDetailQuery : IRequest<FinanceInvoiceRecordDetailDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 发票记录 ID。
|
||||
/// </summary>
|
||||
public long RecordId { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
using TakeoutSaaS.Domain.Tenants.Enums;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 查询发票记录分页。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceInvoiceRecordListQuery : IRequest<FinanceInvoiceRecordListResultDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 开始日期(UTC)。
|
||||
/// </summary>
|
||||
public DateTime? StartDateUtc { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 结束日期(UTC)。
|
||||
/// </summary>
|
||||
public DateTime? EndDateUtc { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 状态筛选。
|
||||
/// </summary>
|
||||
public TenantInvoiceStatus? Status { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 类型筛选。
|
||||
/// </summary>
|
||||
public TenantInvoiceType? InvoiceType { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 关键词。
|
||||
/// </summary>
|
||||
public string? Keyword { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; init; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; init; } = 20;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Invoice.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 查询发票设置详情。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceInvoiceSettingDetailQuery : IRequest<FinanceInvoiceSettingDto>
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表列表行 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportListItemDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 报表 ID。
|
||||
/// </summary>
|
||||
public string ReportId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 日期文案。
|
||||
/// </summary>
|
||||
public string DateText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 营业额。
|
||||
/// </summary>
|
||||
public decimal RevenueAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 订单数。
|
||||
/// </summary>
|
||||
public int OrderCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 客单价。
|
||||
/// </summary>
|
||||
public decimal AverageOrderValue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 退款率(百分数)。
|
||||
/// </summary>
|
||||
public decimal RefundRatePercent { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 成本总额。
|
||||
/// </summary>
|
||||
public decimal CostTotalAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 净利润。
|
||||
/// </summary>
|
||||
public decimal NetProfitAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 利润率(百分数)。
|
||||
/// </summary>
|
||||
public decimal ProfitRatePercent { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 状态编码。
|
||||
/// </summary>
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态文案。
|
||||
/// </summary>
|
||||
public string StatusText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 是否可下载。
|
||||
/// </summary>
|
||||
public bool CanDownload { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表列表结果 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportListResultDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 列表项。
|
||||
/// </summary>
|
||||
public List<FinanceBusinessReportListItemDto> Items { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 总数。
|
||||
/// </summary>
|
||||
public int Total { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表 KPI DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportKpiDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 指标键。
|
||||
/// </summary>
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 指标名称。
|
||||
/// </summary>
|
||||
public string Label { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 指标值文本。
|
||||
/// </summary>
|
||||
public string ValueText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 同比变化率(百分数)。
|
||||
/// </summary>
|
||||
public decimal YoyChangeRate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 环比变化率(百分数)。
|
||||
/// </summary>
|
||||
public decimal MomChangeRate { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表明细行 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportBreakdownItemDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 明细键。
|
||||
/// </summary>
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 明细名称。
|
||||
/// </summary>
|
||||
public string Label { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 占比(百分数)。
|
||||
/// </summary>
|
||||
public decimal RatioPercent { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表详情 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportDetailDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 报表 ID。
|
||||
/// </summary>
|
||||
public string ReportId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 标题。
|
||||
/// </summary>
|
||||
public string Title { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 周期类型编码。
|
||||
/// </summary>
|
||||
public string PeriodType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态编码。
|
||||
/// </summary>
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 状态文案。
|
||||
/// </summary>
|
||||
public string StatusText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 关键指标。
|
||||
/// </summary>
|
||||
public List<FinanceBusinessReportKpiDto> Kpis { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 收入明细(按渠道)。
|
||||
/// </summary>
|
||||
public List<FinanceBusinessReportBreakdownItemDto> IncomeBreakdowns { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 成本明细(按类别)。
|
||||
/// </summary>
|
||||
public List<FinanceBusinessReportBreakdownItemDto> CostBreakdowns { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表导出 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportExportDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 文件名。
|
||||
/// </summary>
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Base64 文件内容。
|
||||
/// </summary>
|
||||
public string FileContentBase64 { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 总记录数。
|
||||
/// </summary>
|
||||
public int TotalCount { get; set; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Domain.Finance.Services;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表批量导出处理器(ZIP:PDF + Excel)。
|
||||
/// </summary>
|
||||
public sealed class ExportFinanceBusinessReportBatchQueryHandler(
|
||||
IFinanceBusinessReportRepository financeBusinessReportRepository,
|
||||
IFinanceBusinessReportExportService financeBusinessReportExportService,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<ExportFinanceBusinessReportBatchQuery, FinanceBusinessReportExportDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceBusinessReportExportDto> Handle(
|
||||
ExportFinanceBusinessReportBatchQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 读取租户上下文并归一化分页参数。
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var normalizedPage = Math.Max(1, request.Page);
|
||||
var normalizedPageSize = Math.Clamp(request.PageSize, 1, 200);
|
||||
|
||||
// 2. 确保成本配置并补齐快照。
|
||||
await financeBusinessReportRepository.EnsureDefaultCostProfilesAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
cancellationToken);
|
||||
await financeBusinessReportRepository.QueueSnapshotsForPageAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
request.PeriodType,
|
||||
normalizedPage,
|
||||
normalizedPageSize,
|
||||
cancellationToken);
|
||||
|
||||
// 3. 查询导出明细集合(允许实时补算)。
|
||||
var details = await financeBusinessReportRepository.ListBatchDetailsAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
request.PeriodType,
|
||||
normalizedPage,
|
||||
normalizedPageSize,
|
||||
allowRealtimeBuild: true,
|
||||
cancellationToken);
|
||||
|
||||
// 4. 生成批量 PDF/Excel 并打包 ZIP。
|
||||
var periodCode = FinanceBusinessReportMapping.ToPeriodTypeCode(request.PeriodType);
|
||||
var zipBytes = await CreateZipAsync(
|
||||
details,
|
||||
periodCode,
|
||||
financeBusinessReportExportService,
|
||||
cancellationToken);
|
||||
|
||||
return new FinanceBusinessReportExportDto
|
||||
{
|
||||
FileName = string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"business-report-batch-{request.StoreId}-{periodCode}-{DateTime.UtcNow:yyyyMMddHHmmss}.zip"),
|
||||
FileContentBase64 = Convert.ToBase64String(zipBytes),
|
||||
TotalCount = details.Count
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<byte[]> CreateZipAsync(
|
||||
IReadOnlyList<Domain.Finance.Models.FinanceBusinessReportDetailSnapshot> details,
|
||||
string periodCode,
|
||||
IFinanceBusinessReportExportService exportService,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (details.Count == 0)
|
||||
{
|
||||
using var emptyStream = new MemoryStream();
|
||||
using (var emptyArchive = new ZipArchive(emptyStream, ZipArchiveMode.Create, true))
|
||||
{
|
||||
var entry = emptyArchive.CreateEntry("README.txt");
|
||||
await using var writer = new StreamWriter(entry.Open());
|
||||
await writer.WriteAsync("No business report data in current selection.");
|
||||
}
|
||||
|
||||
return emptyStream.ToArray();
|
||||
}
|
||||
|
||||
var pdfBytes = await exportService.ExportBatchPdfAsync(details, cancellationToken);
|
||||
var excelBytes = await exportService.ExportBatchExcelAsync(details, cancellationToken);
|
||||
|
||||
using var stream = new MemoryStream();
|
||||
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
|
||||
{
|
||||
var pdfEntry = archive.CreateEntry($"business-report-{periodCode}.pdf");
|
||||
await using (var pdfEntryStream = pdfEntry.Open())
|
||||
{
|
||||
await pdfEntryStream.WriteAsync(pdfBytes, cancellationToken);
|
||||
}
|
||||
|
||||
var excelEntry = archive.CreateEntry($"business-report-{periodCode}.xlsx");
|
||||
await using (var excelEntryStream = excelEntry.Open())
|
||||
{
|
||||
await excelEntryStream.WriteAsync(excelBytes, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Globalization;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Domain.Finance.Services;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表 Excel 导出处理器。
|
||||
/// </summary>
|
||||
public sealed class ExportFinanceBusinessReportExcelQueryHandler(
|
||||
IFinanceBusinessReportRepository financeBusinessReportRepository,
|
||||
IFinanceBusinessReportExportService financeBusinessReportExportService,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<ExportFinanceBusinessReportExcelQuery, FinanceBusinessReportExportDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceBusinessReportExportDto> Handle(
|
||||
ExportFinanceBusinessReportExcelQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 读取租户上下文并确保成本配置存在。
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
await financeBusinessReportRepository.EnsureDefaultCostProfilesAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
cancellationToken);
|
||||
|
||||
// 2. 查询报表详情(允许实时补算)。
|
||||
var detail = await financeBusinessReportRepository.GetDetailAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
request.ReportId,
|
||||
allowRealtimeBuild: true,
|
||||
cancellationToken);
|
||||
|
||||
if (detail is null)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.NotFound, "经营报表不存在");
|
||||
}
|
||||
|
||||
// 3. 导出 Excel 并返回 Base64。
|
||||
var fileBytes = await financeBusinessReportExportService.ExportSingleExcelAsync(detail, cancellationToken);
|
||||
var periodCode = FinanceBusinessReportMapping.ToPeriodTypeCode(detail.PeriodType);
|
||||
return new FinanceBusinessReportExportDto
|
||||
{
|
||||
FileName = string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"business-report-{request.StoreId}-{periodCode}-{request.ReportId}.xlsx"),
|
||||
FileContentBase64 = Convert.ToBase64String(fileBytes),
|
||||
TotalCount = 1
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Globalization;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Domain.Finance.Services;
|
||||
using TakeoutSaaS.Shared.Abstractions.Constants;
|
||||
using TakeoutSaaS.Shared.Abstractions.Exceptions;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表 PDF 导出处理器。
|
||||
/// </summary>
|
||||
public sealed class ExportFinanceBusinessReportPdfQueryHandler(
|
||||
IFinanceBusinessReportRepository financeBusinessReportRepository,
|
||||
IFinanceBusinessReportExportService financeBusinessReportExportService,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<ExportFinanceBusinessReportPdfQuery, FinanceBusinessReportExportDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceBusinessReportExportDto> Handle(
|
||||
ExportFinanceBusinessReportPdfQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 读取租户上下文并确保成本配置存在。
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
await financeBusinessReportRepository.EnsureDefaultCostProfilesAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
cancellationToken);
|
||||
|
||||
// 2. 查询报表详情(允许实时补算)。
|
||||
var detail = await financeBusinessReportRepository.GetDetailAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
request.ReportId,
|
||||
allowRealtimeBuild: true,
|
||||
cancellationToken);
|
||||
|
||||
if (detail is null)
|
||||
{
|
||||
throw new BusinessException(ErrorCodes.NotFound, "经营报表不存在");
|
||||
}
|
||||
|
||||
// 3. 导出 PDF 并返回 Base64。
|
||||
var fileBytes = await financeBusinessReportExportService.ExportSinglePdfAsync(detail, cancellationToken);
|
||||
var periodCode = FinanceBusinessReportMapping.ToPeriodTypeCode(detail.PeriodType);
|
||||
return new FinanceBusinessReportExportDto
|
||||
{
|
||||
FileName = string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"business-report-{request.StoreId}-{periodCode}-{request.ReportId}.pdf"),
|
||||
FileContentBase64 = Convert.ToBase64String(fileBytes),
|
||||
TotalCount = 1
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
using System.Globalization;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
using TakeoutSaaS.Domain.Finance.Enums;
|
||||
using TakeoutSaaS.Domain.Finance.Models;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表映射工具。
|
||||
/// </summary>
|
||||
internal static class FinanceBusinessReportMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// 映射列表行 DTO。
|
||||
/// </summary>
|
||||
public static FinanceBusinessReportListItemDto ToListItem(FinanceBusinessReportListItemSnapshot source)
|
||||
{
|
||||
return new FinanceBusinessReportListItemDto
|
||||
{
|
||||
ReportId = source.ReportId.ToString(CultureInfo.InvariantCulture),
|
||||
DateText = FormatPeriodText(source.PeriodType, source.PeriodStartAt, source.PeriodEndAt),
|
||||
RevenueAmount = RoundMoney(source.RevenueAmount),
|
||||
OrderCount = Math.Max(0, source.OrderCount),
|
||||
AverageOrderValue = RoundMoney(source.AverageOrderValue),
|
||||
RefundRatePercent = RoundPercent(source.RefundRate),
|
||||
CostTotalAmount = RoundMoney(source.CostTotalAmount),
|
||||
NetProfitAmount = RoundMoney(source.NetProfitAmount),
|
||||
ProfitRatePercent = RoundPercent(source.ProfitRate),
|
||||
Status = ToStatusCode(source.Status),
|
||||
StatusText = ToStatusText(source.Status),
|
||||
CanDownload = source.Status == FinanceBusinessReportStatus.Succeeded
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 映射详情 DTO。
|
||||
/// </summary>
|
||||
public static FinanceBusinessReportDetailDto ToDetail(FinanceBusinessReportDetailSnapshot source)
|
||||
{
|
||||
return new FinanceBusinessReportDetailDto
|
||||
{
|
||||
ReportId = source.ReportId.ToString(CultureInfo.InvariantCulture),
|
||||
Title = BuildTitle(source.PeriodType, source.PeriodStartAt, source.PeriodEndAt),
|
||||
PeriodType = ToPeriodTypeCode(source.PeriodType),
|
||||
Status = ToStatusCode(source.Status),
|
||||
StatusText = ToStatusText(source.Status),
|
||||
Kpis = source.Kpis.Select(ToKpi).ToList(),
|
||||
IncomeBreakdowns = source.IncomeBreakdowns.Select(ToBreakdown).ToList(),
|
||||
CostBreakdowns = source.CostBreakdowns.Select(ToBreakdown).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 周期类型编码。
|
||||
/// </summary>
|
||||
public static string ToPeriodTypeCode(FinanceBusinessReportPeriodType value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
FinanceBusinessReportPeriodType.Daily => "daily",
|
||||
FinanceBusinessReportPeriodType.Weekly => "weekly",
|
||||
FinanceBusinessReportPeriodType.Monthly => "monthly",
|
||||
_ => "daily"
|
||||
};
|
||||
}
|
||||
|
||||
private static FinanceBusinessReportKpiDto ToKpi(FinanceBusinessReportKpiSnapshot source)
|
||||
{
|
||||
return new FinanceBusinessReportKpiDto
|
||||
{
|
||||
Key = source.Key,
|
||||
Label = source.Label,
|
||||
ValueText = FormatKpiValue(source.Key, source.Value),
|
||||
YoyChangeRate = RoundRate(source.YoyChangeRate),
|
||||
MomChangeRate = RoundRate(source.MomChangeRate)
|
||||
};
|
||||
}
|
||||
|
||||
private static FinanceBusinessReportBreakdownItemDto ToBreakdown(FinanceBusinessReportBreakdownSnapshot source)
|
||||
{
|
||||
return new FinanceBusinessReportBreakdownItemDto
|
||||
{
|
||||
Key = source.Key,
|
||||
Label = source.Label,
|
||||
Amount = RoundMoney(source.Amount),
|
||||
RatioPercent = RoundPercent(source.Ratio)
|
||||
};
|
||||
}
|
||||
|
||||
private static string FormatPeriodText(
|
||||
FinanceBusinessReportPeriodType periodType,
|
||||
DateTime startAt,
|
||||
DateTime endAt)
|
||||
{
|
||||
return periodType switch
|
||||
{
|
||||
FinanceBusinessReportPeriodType.Daily => startAt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
FinanceBusinessReportPeriodType.Weekly =>
|
||||
$"{startAt:MM-dd} ~ {endAt.AddDays(-1):MM-dd}",
|
||||
FinanceBusinessReportPeriodType.Monthly => startAt.ToString("yyyy年M月", CultureInfo.InvariantCulture),
|
||||
_ => startAt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
|
||||
};
|
||||
}
|
||||
|
||||
private static string BuildTitle(
|
||||
FinanceBusinessReportPeriodType periodType,
|
||||
DateTime startAt,
|
||||
DateTime endAt)
|
||||
{
|
||||
return periodType switch
|
||||
{
|
||||
FinanceBusinessReportPeriodType.Daily => $"{startAt:yyyy年M月d日} 经营日报",
|
||||
FinanceBusinessReportPeriodType.Weekly => $"{startAt:yyyy年M月d日}~{endAt.AddDays(-1):M月d日} 经营周报",
|
||||
FinanceBusinessReportPeriodType.Monthly => $"{startAt:yyyy年M月} 经营月报",
|
||||
_ => "经营报表"
|
||||
};
|
||||
}
|
||||
|
||||
private static string ToStatusCode(FinanceBusinessReportStatus status)
|
||||
{
|
||||
return status switch
|
||||
{
|
||||
FinanceBusinessReportStatus.Queued => "queued",
|
||||
FinanceBusinessReportStatus.Running => "running",
|
||||
FinanceBusinessReportStatus.Succeeded => "succeeded",
|
||||
FinanceBusinessReportStatus.Failed => "failed",
|
||||
_ => "queued"
|
||||
};
|
||||
}
|
||||
|
||||
private static string ToStatusText(FinanceBusinessReportStatus status)
|
||||
{
|
||||
return status switch
|
||||
{
|
||||
FinanceBusinessReportStatus.Queued => "排队中",
|
||||
FinanceBusinessReportStatus.Running => "生成中",
|
||||
FinanceBusinessReportStatus.Succeeded => "已生成",
|
||||
FinanceBusinessReportStatus.Failed => "生成失败",
|
||||
_ => "排队中"
|
||||
};
|
||||
}
|
||||
|
||||
private static string FormatKpiValue(string key, decimal value)
|
||||
{
|
||||
if (key is "order_count")
|
||||
{
|
||||
return Math.Round(value, 0, MidpointRounding.AwayFromZero).ToString("0", CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
if (key is "refund_rate" or "profit_rate")
|
||||
{
|
||||
return $"{RoundPercent(value):0.##}%";
|
||||
}
|
||||
|
||||
if (key is "average_order_value")
|
||||
{
|
||||
return $"¥{RoundMoney(value):0.##}";
|
||||
}
|
||||
|
||||
return $"¥{RoundMoney(value):0.##}";
|
||||
}
|
||||
|
||||
private static decimal RoundMoney(decimal value)
|
||||
{
|
||||
return decimal.Round(value, 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
private static decimal RoundPercent(decimal value)
|
||||
{
|
||||
return decimal.Round(value * 100m, 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
|
||||
private static decimal RoundRate(decimal value)
|
||||
{
|
||||
return decimal.Round(value, 2, MidpointRounding.AwayFromZero);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表详情查询处理器。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceBusinessReportDetailQueryHandler(
|
||||
IFinanceBusinessReportRepository financeBusinessReportRepository,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetFinanceBusinessReportDetailQuery, FinanceBusinessReportDetailDto?>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceBusinessReportDetailDto?> Handle(
|
||||
GetFinanceBusinessReportDetailQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 读取租户上下文并确保成本配置存在。
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
await financeBusinessReportRepository.EnsureDefaultCostProfilesAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
cancellationToken);
|
||||
|
||||
// 2. 查询详情(允许实时补算)并映射输出。
|
||||
var detail = await financeBusinessReportRepository.GetDetailAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
request.ReportId,
|
||||
allowRealtimeBuild: true,
|
||||
cancellationToken);
|
||||
|
||||
return detail is null ? null : FinanceBusinessReportMapping.ToDetail(detail);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表分页查询处理器。
|
||||
/// </summary>
|
||||
public sealed class SearchFinanceBusinessReportListQueryHandler(
|
||||
IFinanceBusinessReportRepository financeBusinessReportRepository,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<SearchFinanceBusinessReportListQuery, FinanceBusinessReportListResultDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceBusinessReportListResultDto> Handle(
|
||||
SearchFinanceBusinessReportListQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// 1. 读取租户上下文并归一化分页参数。
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var normalizedPage = Math.Max(1, request.Page);
|
||||
var normalizedPageSize = Math.Clamp(request.PageSize, 1, 200);
|
||||
|
||||
// 2. 确保成本配置并补齐分页周期快照。
|
||||
await financeBusinessReportRepository.EnsureDefaultCostProfilesAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
cancellationToken);
|
||||
await financeBusinessReportRepository.QueueSnapshotsForPageAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
request.PeriodType,
|
||||
normalizedPage,
|
||||
normalizedPageSize,
|
||||
cancellationToken);
|
||||
|
||||
// 3. 查询分页快照并映射输出。
|
||||
var pageSnapshot = await financeBusinessReportRepository.SearchPageAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
request.PeriodType,
|
||||
normalizedPage,
|
||||
normalizedPageSize,
|
||||
cancellationToken);
|
||||
|
||||
return new FinanceBusinessReportListResultDto
|
||||
{
|
||||
Items = pageSnapshot.Items.Select(FinanceBusinessReportMapping.ToListItem).ToList(),
|
||||
Total = pageSnapshot.TotalCount,
|
||||
Page = normalizedPage,
|
||||
PageSize = normalizedPageSize
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
using TakeoutSaaS.Domain.Finance.Enums;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 批量导出经营报表(ZIP:PDF + Excel)。
|
||||
/// </summary>
|
||||
public sealed class ExportFinanceBusinessReportBatchQuery : IRequest<FinanceBusinessReportExportDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public long StoreId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 周期类型。
|
||||
/// </summary>
|
||||
public FinanceBusinessReportPeriodType PeriodType { get; init; } = FinanceBusinessReportPeriodType.Daily;
|
||||
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; init; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; init; } = 20;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 导出经营报表 Excel。
|
||||
/// </summary>
|
||||
public sealed class ExportFinanceBusinessReportExcelQuery : IRequest<FinanceBusinessReportExportDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public long StoreId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 报表 ID。
|
||||
/// </summary>
|
||||
public long ReportId { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 导出经营报表 PDF。
|
||||
/// </summary>
|
||||
public sealed class ExportFinanceBusinessReportPdfQuery : IRequest<FinanceBusinessReportExportDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public long StoreId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 报表 ID。
|
||||
/// </summary>
|
||||
public long ReportId { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 查询经营报表详情。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceBusinessReportDetailQuery : IRequest<FinanceBusinessReportDetailDto?>
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public long StoreId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 报表 ID。
|
||||
/// </summary>
|
||||
public long ReportId { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Dto;
|
||||
using TakeoutSaaS.Domain.Finance.Enums;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 查询经营报表分页列表。
|
||||
/// </summary>
|
||||
public sealed class SearchFinanceBusinessReportListQuery : IRequest<FinanceBusinessReportListResultDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public long StoreId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 周期类型。
|
||||
/// </summary>
|
||||
public FinanceBusinessReportPeriodType PeriodType { get; init; } = FinanceBusinessReportPeriodType.Daily;
|
||||
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; init; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; init; } = 20;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using FluentValidation;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表批量导出查询验证器。
|
||||
/// </summary>
|
||||
public sealed class ExportFinanceBusinessReportBatchQueryValidator : AbstractValidator<ExportFinanceBusinessReportBatchQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// 初始化验证规则。
|
||||
/// </summary>
|
||||
public ExportFinanceBusinessReportBatchQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.StoreId).GreaterThan(0);
|
||||
RuleFor(x => x.Page).GreaterThan(0);
|
||||
RuleFor(x => x.PageSize).InclusiveBetween(1, 200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using FluentValidation;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表 Excel 导出查询验证器。
|
||||
/// </summary>
|
||||
public sealed class ExportFinanceBusinessReportExcelQueryValidator : AbstractValidator<ExportFinanceBusinessReportExcelQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// 初始化验证规则。
|
||||
/// </summary>
|
||||
public ExportFinanceBusinessReportExcelQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.StoreId).GreaterThan(0);
|
||||
RuleFor(x => x.ReportId).GreaterThan(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using FluentValidation;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表 PDF 导出查询验证器。
|
||||
/// </summary>
|
||||
public sealed class ExportFinanceBusinessReportPdfQueryValidator : AbstractValidator<ExportFinanceBusinessReportPdfQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// 初始化验证规则。
|
||||
/// </summary>
|
||||
public ExportFinanceBusinessReportPdfQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.StoreId).GreaterThan(0);
|
||||
RuleFor(x => x.ReportId).GreaterThan(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using FluentValidation;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表详情查询验证器。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceBusinessReportDetailQueryValidator : AbstractValidator<GetFinanceBusinessReportDetailQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// 初始化验证规则。
|
||||
/// </summary>
|
||||
public GetFinanceBusinessReportDetailQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.StoreId).GreaterThan(0);
|
||||
RuleFor(x => x.ReportId).GreaterThan(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using FluentValidation;
|
||||
using TakeoutSaaS.Application.App.Finance.Reports.Queries;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Reports.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表分页查询验证器。
|
||||
/// </summary>
|
||||
public sealed class SearchFinanceBusinessReportListQueryValidator : AbstractValidator<SearchFinanceBusinessReportListQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// 初始化验证规则。
|
||||
/// </summary>
|
||||
public SearchFinanceBusinessReportListQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.StoreId).GreaterThan(0);
|
||||
RuleFor(x => x.Page).GreaterThan(0);
|
||||
RuleFor(x => x.PageSize).InclusiveBetween(1, 200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
namespace TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
|
||||
/// <summary>
|
||||
/// 到账查询汇总行 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementListItemDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 到账日期(UTC 日期)。
|
||||
/// </summary>
|
||||
public DateTime ArrivedDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 渠道编码(wechat/alipay)。
|
||||
/// </summary>
|
||||
public string Channel { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 渠道文案。
|
||||
/// </summary>
|
||||
public string ChannelText { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 交易笔数。
|
||||
/// </summary>
|
||||
public int TransactionCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 到账金额。
|
||||
/// </summary>
|
||||
public decimal ArrivedAmount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账查询分页结果 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementListResultDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 列表项。
|
||||
/// </summary>
|
||||
public List<FinanceSettlementListItemDto> Items { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 总数。
|
||||
/// </summary>
|
||||
public int Total { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前页码。
|
||||
/// </summary>
|
||||
public int Page { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账明细行 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementDetailItemDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 订单号。
|
||||
/// </summary>
|
||||
public string OrderNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 支付时间(UTC)。
|
||||
/// </summary>
|
||||
public DateTime PaidAt { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账明细结果 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementDetailResultDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 明细列表。
|
||||
/// </summary>
|
||||
public List<FinanceSettlementDetailItemDto> Items { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账统计 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementStatsDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 今日到账金额。
|
||||
/// </summary>
|
||||
public decimal TodayArrivedAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 昨日到账金额。
|
||||
/// </summary>
|
||||
public decimal YesterdayArrivedAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 本月到账金额。
|
||||
/// </summary>
|
||||
public decimal CurrentMonthArrivedAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 本月交易笔数。
|
||||
/// </summary>
|
||||
public int CurrentMonthTransactionCount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账账户信息 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementAccountDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 银行名称。
|
||||
/// </summary>
|
||||
public string BankName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开户名。
|
||||
/// </summary>
|
||||
public string BankAccountName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 脱敏银行账号。
|
||||
/// </summary>
|
||||
public string BankAccountNoMasked { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 脱敏微信商户号。
|
||||
/// </summary>
|
||||
public string WechatMerchantNoMasked { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 脱敏支付宝 PID。
|
||||
/// </summary>
|
||||
public string AlipayPidMasked { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 结算周期文案。
|
||||
/// </summary>
|
||||
public string SettlementPeriodText { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账导出 DTO。
|
||||
/// </summary>
|
||||
public sealed class FinanceSettlementExportDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 文件名。
|
||||
/// </summary>
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 文件内容 Base64。
|
||||
/// </summary>
|
||||
public string FileContentBase64 { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 导出总数。
|
||||
/// </summary>
|
||||
public int TotalCount { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Queries;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Settlement.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 到账汇总导出处理器。
|
||||
/// </summary>
|
||||
public sealed class ExportFinanceSettlementCsvQueryHandler(
|
||||
IFinanceTransactionRepository financeTransactionRepository,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<ExportFinanceSettlementCsvQuery, FinanceSettlementExportDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceSettlementExportDto> Handle(
|
||||
ExportFinanceSettlementCsvQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var rows = await financeTransactionRepository.ListSettlementForExportAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
request.StartAt,
|
||||
request.EndAt,
|
||||
request.PaymentMethod,
|
||||
cancellationToken);
|
||||
|
||||
var list = rows.Select(FinanceSettlementMapping.ToListItem).ToList();
|
||||
var csv = BuildCsv(list);
|
||||
return new FinanceSettlementExportDto
|
||||
{
|
||||
FileName = $"settlement-{request.StoreId}-{DateTime.UtcNow:yyyyMMddHHmmss}.csv",
|
||||
FileContentBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(csv)),
|
||||
TotalCount = list.Count
|
||||
};
|
||||
}
|
||||
|
||||
private static string BuildCsv(IReadOnlyList<FinanceSettlementListItemDto> rows)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append('\uFEFF');
|
||||
sb.AppendLine("到账日期,支付渠道,交易笔数,到账金额");
|
||||
|
||||
foreach (var row in rows)
|
||||
{
|
||||
sb.AppendLine(string.Join(',',
|
||||
Escape(row.ArrivedDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)),
|
||||
Escape(row.ChannelText),
|
||||
Escape(row.TransactionCount.ToString(CultureInfo.InvariantCulture)),
|
||||
Escape(FinanceSettlementMapping.FormatAmount(row.ArrivedAmount))));
|
||||
}
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static string Escape(string? value)
|
||||
{
|
||||
var normalized = value ?? string.Empty;
|
||||
if (normalized.Contains(',') || normalized.Contains('"') || normalized.Contains('\n'))
|
||||
{
|
||||
return $"\"{normalized.Replace("\"", "\"\"", StringComparison.Ordinal)}\"";
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Globalization;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
using TakeoutSaaS.Domain.Finance.Models;
|
||||
using TakeoutSaaS.Domain.Payments.Enums;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Settlement.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 到账查询映射辅助。
|
||||
/// </summary>
|
||||
internal static class FinanceSettlementMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// 支付方式转渠道编码。
|
||||
/// </summary>
|
||||
public static string ToChannelCode(PaymentMethod paymentMethod)
|
||||
{
|
||||
return paymentMethod switch
|
||||
{
|
||||
PaymentMethod.WeChatPay => "wechat",
|
||||
PaymentMethod.Alipay => "alipay",
|
||||
_ => "unknown"
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 支付方式转渠道文案。
|
||||
/// </summary>
|
||||
public static string ToChannelText(PaymentMethod paymentMethod)
|
||||
{
|
||||
return paymentMethod switch
|
||||
{
|
||||
PaymentMethod.WeChatPay => "微信支付",
|
||||
PaymentMethod.Alipay => "支付宝",
|
||||
_ => "未知渠道"
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 映射到账汇总行。
|
||||
/// </summary>
|
||||
public static FinanceSettlementListItemDto ToListItem(FinanceSettlementListItemSnapshot source)
|
||||
{
|
||||
return new FinanceSettlementListItemDto
|
||||
{
|
||||
ArrivedDate = source.ArrivedDate,
|
||||
Channel = ToChannelCode(source.PaymentMethod),
|
||||
ChannelText = ToChannelText(source.PaymentMethod),
|
||||
TransactionCount = source.TransactionCount,
|
||||
ArrivedAmount = decimal.Round(source.ArrivedAmount, 2, MidpointRounding.AwayFromZero)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 映射到账明细行。
|
||||
/// </summary>
|
||||
public static FinanceSettlementDetailItemDto ToDetailItem(FinanceSettlementDetailItemSnapshot source)
|
||||
{
|
||||
return new FinanceSettlementDetailItemDto
|
||||
{
|
||||
OrderNo = source.OrderNo,
|
||||
Amount = decimal.Round(source.Amount, 2, MidpointRounding.AwayFromZero),
|
||||
PaidAt = source.PaidAt
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 格式化金额(导出场景)。
|
||||
/// </summary>
|
||||
public static string FormatAmount(decimal value)
|
||||
{
|
||||
return decimal.Round(value, 2, MidpointRounding.AwayFromZero)
|
||||
.ToString("0.00", CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Queries;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Settlement.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 到账账户信息查询处理器。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceSettlementAccountQueryHandler(
|
||||
IFinanceTransactionRepository financeTransactionRepository,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetFinanceSettlementAccountQuery, FinanceSettlementAccountDto?>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceSettlementAccountDto?> Handle(
|
||||
GetFinanceSettlementAccountQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var snapshot = await financeTransactionRepository.GetSettlementAccountAsync(
|
||||
tenantId,
|
||||
cancellationToken);
|
||||
|
||||
if (snapshot is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new FinanceSettlementAccountDto
|
||||
{
|
||||
BankName = snapshot.BankName,
|
||||
BankAccountName = snapshot.BankAccountName,
|
||||
BankAccountNoMasked = snapshot.BankAccountNoMasked,
|
||||
WechatMerchantNoMasked = snapshot.WechatMerchantNoMasked,
|
||||
AlipayPidMasked = snapshot.AlipayPidMasked,
|
||||
SettlementPeriodText = snapshot.SettlementPeriodText
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Queries;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Settlement.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 到账明细查询处理器。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceSettlementDetailQueryHandler(
|
||||
IFinanceTransactionRepository financeTransactionRepository,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetFinanceSettlementDetailQuery, FinanceSettlementDetailResultDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceSettlementDetailResultDto> Handle(
|
||||
GetFinanceSettlementDetailQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var rows = await financeTransactionRepository.GetSettlementDetailsAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
request.ArrivedDate,
|
||||
request.PaymentMethod,
|
||||
request.Take,
|
||||
cancellationToken);
|
||||
|
||||
return new FinanceSettlementDetailResultDto
|
||||
{
|
||||
Items = rows.Select(FinanceSettlementMapping.ToDetailItem).ToList()
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Queries;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Settlement.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 到账统计查询处理器。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceSettlementStatsQueryHandler(
|
||||
IFinanceTransactionRepository financeTransactionRepository,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<GetFinanceSettlementStatsQuery, FinanceSettlementStatsDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceSettlementStatsDto> Handle(
|
||||
GetFinanceSettlementStatsQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var snapshot = await financeTransactionRepository.GetSettlementStatsAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
DateTime.UtcNow,
|
||||
cancellationToken);
|
||||
|
||||
return new FinanceSettlementStatsDto
|
||||
{
|
||||
TodayArrivedAmount = snapshot.TodayArrivedAmount,
|
||||
YesterdayArrivedAmount = snapshot.YesterdayArrivedAmount,
|
||||
CurrentMonthArrivedAmount = snapshot.CurrentMonthArrivedAmount,
|
||||
CurrentMonthTransactionCount = snapshot.CurrentMonthTransactionCount
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Queries;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Settlement.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// 到账汇总分页查询处理器。
|
||||
/// </summary>
|
||||
public sealed class SearchFinanceSettlementListQueryHandler(
|
||||
IFinanceTransactionRepository financeTransactionRepository,
|
||||
ITenantProvider tenantProvider)
|
||||
: IRequestHandler<SearchFinanceSettlementListQuery, FinanceSettlementListResultDto>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceSettlementListResultDto> Handle(
|
||||
SearchFinanceSettlementListQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantId = tenantProvider.GetCurrentTenantId();
|
||||
var normalizedPage = Math.Max(1, request.Page);
|
||||
var normalizedPageSize = Math.Clamp(request.PageSize, 1, 200);
|
||||
|
||||
var snapshot = await financeTransactionRepository.SearchSettlementPageAsync(
|
||||
tenantId,
|
||||
request.StoreId,
|
||||
request.StartAt,
|
||||
request.EndAt,
|
||||
request.PaymentMethod,
|
||||
normalizedPage,
|
||||
normalizedPageSize,
|
||||
cancellationToken);
|
||||
|
||||
return new FinanceSettlementListResultDto
|
||||
{
|
||||
Items = snapshot.Items.Select(FinanceSettlementMapping.ToListItem).ToList(),
|
||||
Total = snapshot.TotalCount,
|
||||
Page = normalizedPage,
|
||||
PageSize = normalizedPageSize
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
using TakeoutSaaS.Domain.Payments.Enums;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Settlement.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 导出到账汇总 CSV。
|
||||
/// </summary>
|
||||
public sealed class ExportFinanceSettlementCsvQuery : IRequest<FinanceSettlementExportDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店标识。
|
||||
/// </summary>
|
||||
public long StoreId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 开始时间(UTC,闭区间)。
|
||||
/// </summary>
|
||||
public DateTime? StartAt { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 结束时间(UTC,开区间)。
|
||||
/// </summary>
|
||||
public DateTime? EndAt { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 支付方式筛选。
|
||||
/// </summary>
|
||||
public PaymentMethod? PaymentMethod { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Settlement.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账账户信息。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceSettlementAccountQuery : IRequest<FinanceSettlementAccountDto?>
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
using TakeoutSaaS.Domain.Payments.Enums;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Settlement.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账明细。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceSettlementDetailQuery : IRequest<FinanceSettlementDetailResultDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店标识。
|
||||
/// </summary>
|
||||
public long StoreId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 到账日期(UTC 日期)。
|
||||
/// </summary>
|
||||
public DateTime ArrivedDate { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 渠道(微信/支付宝)。
|
||||
/// </summary>
|
||||
public PaymentMethod PaymentMethod { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 限制条数。
|
||||
/// </summary>
|
||||
public int Take { get; init; } = 20;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Settlement.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账统计。
|
||||
/// </summary>
|
||||
public sealed class GetFinanceSettlementStatsQuery : IRequest<FinanceSettlementStatsDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店标识。
|
||||
/// </summary>
|
||||
public long StoreId { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using MediatR;
|
||||
using TakeoutSaaS.Application.App.Finance.Settlement.Dto;
|
||||
using TakeoutSaaS.Domain.Payments.Enums;
|
||||
|
||||
namespace TakeoutSaaS.Application.App.Finance.Settlement.Queries;
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账汇总分页。
|
||||
/// </summary>
|
||||
public sealed class SearchFinanceSettlementListQuery : IRequest<FinanceSettlementListResultDto>
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店标识。
|
||||
/// </summary>
|
||||
public long StoreId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 开始时间(UTC,闭区间)。
|
||||
/// </summary>
|
||||
public DateTime? StartAt { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 结束时间(UTC,开区间)。
|
||||
/// </summary>
|
||||
public DateTime? EndAt { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 支付方式筛选。
|
||||
/// </summary>
|
||||
public PaymentMethod? PaymentMethod { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 页码。
|
||||
/// </summary>
|
||||
public int Page { get; init; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 每页条数。
|
||||
/// </summary>
|
||||
public int PageSize { get; init; } = 20;
|
||||
}
|
||||
@@ -60,6 +60,16 @@ public sealed record SubmitTenantVerificationCommand : IRequest<TenantVerificati
|
||||
/// </summary>
|
||||
public string? BankName { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 微信商户号。
|
||||
/// </summary>
|
||||
public string? WeChatMerchantNo { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 支付宝 PID。
|
||||
/// </summary>
|
||||
public string? AlipayPid { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 其他补充资料 JSON。
|
||||
/// </summary>
|
||||
|
||||
@@ -71,6 +71,16 @@ public sealed class TenantVerificationDto
|
||||
/// </summary>
|
||||
public string? BankName { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 微信商户号。
|
||||
/// </summary>
|
||||
public string? WeChatMerchantNo { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 支付宝 PID。
|
||||
/// </summary>
|
||||
public string? AlipayPid { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 附加资料(JSON)。
|
||||
/// </summary>
|
||||
|
||||
@@ -54,6 +54,8 @@ public sealed class SubmitTenantVerificationCommandHandler(
|
||||
profile.BankAccountName = request.BankAccountName;
|
||||
profile.BankAccountNumber = request.BankAccountNumber;
|
||||
profile.BankName = request.BankName;
|
||||
profile.WeChatMerchantNo = request.WeChatMerchantNo;
|
||||
profile.AlipayPid = request.AlipayPid;
|
||||
profile.AdditionalDataJson = request.AdditionalDataJson;
|
||||
profile.Status = TenantVerificationStatus.Pending;
|
||||
profile.SubmittedAt = DateTime.UtcNow;
|
||||
|
||||
@@ -31,6 +31,8 @@ internal static class TenantMapping
|
||||
BankAccountName = profile.BankAccountName,
|
||||
BankAccountNumber = profile.BankAccountNumber,
|
||||
BankName = profile.BankName,
|
||||
WeChatMerchantNo = profile.WeChatMerchantNo,
|
||||
AlipayPid = profile.AlipayPid,
|
||||
AdditionalDataJson = profile.AdditionalDataJson,
|
||||
SubmittedAt = profile.SubmittedAt,
|
||||
ReviewRemarks = profile.ReviewRemarks,
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
using TakeoutSaaS.Domain.Finance.Enums;
|
||||
using TakeoutSaaS.Shared.Abstractions.Entities;
|
||||
|
||||
namespace TakeoutSaaS.Domain.Finance.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表快照实体。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportSnapshot : MultiTenantEntityBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 所属门店 ID。
|
||||
/// </summary>
|
||||
public long StoreId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 周期类型。
|
||||
/// </summary>
|
||||
public FinanceBusinessReportPeriodType PeriodType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 周期开始时间(UTC,含)。
|
||||
/// </summary>
|
||||
public DateTime PeriodStartAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 周期结束时间(UTC,不含)。
|
||||
/// </summary>
|
||||
public DateTime PeriodEndAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 生成状态。
|
||||
/// </summary>
|
||||
public FinanceBusinessReportStatus Status { get; set; } = FinanceBusinessReportStatus.Queued;
|
||||
|
||||
/// <summary>
|
||||
/// 营业额。
|
||||
/// </summary>
|
||||
public decimal RevenueAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 订单数。
|
||||
/// </summary>
|
||||
public int OrderCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 客单价。
|
||||
/// </summary>
|
||||
public decimal AverageOrderValue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 退款率(0-1)。
|
||||
/// </summary>
|
||||
public decimal RefundRate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 成本总额。
|
||||
/// </summary>
|
||||
public decimal CostTotalAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 净利润。
|
||||
/// </summary>
|
||||
public decimal NetProfitAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 利润率(0-1)。
|
||||
/// </summary>
|
||||
public decimal ProfitRate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// KPI 比较快照 JSON(同比/环比)。
|
||||
/// </summary>
|
||||
public string KpiComparisonJson { get; set; } = "[]";
|
||||
|
||||
/// <summary>
|
||||
/// 收入明细快照 JSON(按渠道)。
|
||||
/// </summary>
|
||||
public string IncomeBreakdownJson { get; set; } = "[]";
|
||||
|
||||
/// <summary>
|
||||
/// 成本明细快照 JSON(按类别)。
|
||||
/// </summary>
|
||||
public string CostBreakdownJson { get; set; } = "[]";
|
||||
|
||||
/// <summary>
|
||||
/// 生成开始时间(UTC)。
|
||||
/// </summary>
|
||||
public DateTime? StartedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 生成完成时间(UTC)。
|
||||
/// </summary>
|
||||
public DateTime? FinishedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 最近一次失败信息。
|
||||
/// </summary>
|
||||
public string? LastError { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 重试次数。
|
||||
/// </summary>
|
||||
public int RetryCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 调度任务 ID。
|
||||
/// </summary>
|
||||
public string? HangfireJobId { get; set; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
using TakeoutSaaS.Domain.Finance.Enums;
|
||||
using TakeoutSaaS.Shared.Abstractions.Entities;
|
||||
|
||||
namespace TakeoutSaaS.Domain.Finance.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 成本日覆盖实体。
|
||||
/// </summary>
|
||||
public sealed class FinanceCostDailyOverride : MultiTenantEntityBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public long StoreId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 业务日期(UTC 日期)。
|
||||
/// </summary>
|
||||
public DateTime BusinessDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 成本分类。
|
||||
/// </summary>
|
||||
public FinanceCostCategory Category { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 覆盖金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 备注。
|
||||
/// </summary>
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
using TakeoutSaaS.Domain.Finance.Enums;
|
||||
using TakeoutSaaS.Shared.Abstractions.Entities;
|
||||
|
||||
namespace TakeoutSaaS.Domain.Finance.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 成本配置实体(类别级规则)。
|
||||
/// </summary>
|
||||
public sealed class FinanceCostProfile : MultiTenantEntityBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public long StoreId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 成本分类。
|
||||
/// </summary>
|
||||
public FinanceCostCategory Category { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 计算模式。
|
||||
/// </summary>
|
||||
public FinanceCostCalcMode CalcMode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 比例值(0-1,Ratio 模式使用)。
|
||||
/// </summary>
|
||||
public decimal Ratio { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 固定日金额(FixedDaily 模式使用)。
|
||||
/// </summary>
|
||||
public decimal FixedDailyAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 生效开始日期(UTC 日期)。
|
||||
/// </summary>
|
||||
public DateTime EffectiveFrom { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 生效结束日期(UTC 日期,含,null 表示长期)。
|
||||
/// </summary>
|
||||
public DateTime? EffectiveTo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用。
|
||||
/// </summary>
|
||||
public bool IsEnabled { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 排序值。
|
||||
/// </summary>
|
||||
public int SortOrder { get; set; } = 100;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace TakeoutSaaS.Domain.Finance.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表周期类型。
|
||||
/// </summary>
|
||||
public enum FinanceBusinessReportPeriodType
|
||||
{
|
||||
/// <summary>
|
||||
/// 日报。
|
||||
/// </summary>
|
||||
Daily = 1,
|
||||
|
||||
/// <summary>
|
||||
/// 周报。
|
||||
/// </summary>
|
||||
Weekly = 2,
|
||||
|
||||
/// <summary>
|
||||
/// 月报。
|
||||
/// </summary>
|
||||
Monthly = 3
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
namespace TakeoutSaaS.Domain.Finance.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表快照状态。
|
||||
/// </summary>
|
||||
public enum FinanceBusinessReportStatus
|
||||
{
|
||||
/// <summary>
|
||||
/// 已排队。
|
||||
/// </summary>
|
||||
Queued = 1,
|
||||
|
||||
/// <summary>
|
||||
/// 生成中。
|
||||
/// </summary>
|
||||
Running = 2,
|
||||
|
||||
/// <summary>
|
||||
/// 已生成。
|
||||
/// </summary>
|
||||
Succeeded = 3,
|
||||
|
||||
/// <summary>
|
||||
/// 生成失败。
|
||||
/// </summary>
|
||||
Failed = 4
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace TakeoutSaaS.Domain.Finance.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// 成本计算模式。
|
||||
/// </summary>
|
||||
public enum FinanceCostCalcMode
|
||||
{
|
||||
/// <summary>
|
||||
/// 按营业额比例计算。
|
||||
/// </summary>
|
||||
Ratio = 1,
|
||||
|
||||
/// <summary>
|
||||
/// 按固定日金额计算。
|
||||
/// </summary>
|
||||
FixedDaily = 2
|
||||
}
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
using TakeoutSaaS.Domain.Finance.Enums;
|
||||
|
||||
namespace TakeoutSaaS.Domain.Finance.Models;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表 KPI 快照项。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportKpiSnapshot
|
||||
{
|
||||
/// <summary>
|
||||
/// 指标键。
|
||||
/// </summary>
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 指标名称。
|
||||
/// </summary>
|
||||
public string Label { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 指标值。
|
||||
/// </summary>
|
||||
public decimal Value { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 同比变化率(百分数,如 3.5 表示 +3.5%)。
|
||||
/// </summary>
|
||||
public decimal YoyChangeRate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 环比变化率(百分数,如 2.1 表示 +2.1%)。
|
||||
/// </summary>
|
||||
public decimal MomChangeRate { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表明细行快照。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportBreakdownSnapshot
|
||||
{
|
||||
/// <summary>
|
||||
/// 明细键。
|
||||
/// </summary>
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 明细名称。
|
||||
/// </summary>
|
||||
public string Label { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 占比(0-1)。
|
||||
/// </summary>
|
||||
public decimal Ratio { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表列表行快照。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportListItemSnapshot
|
||||
{
|
||||
/// <summary>
|
||||
/// 报表 ID。
|
||||
/// </summary>
|
||||
public long ReportId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 周期类型。
|
||||
/// </summary>
|
||||
public FinanceBusinessReportPeriodType PeriodType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 周期开始时间(UTC,含)。
|
||||
/// </summary>
|
||||
public DateTime PeriodStartAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 周期结束时间(UTC,不含)。
|
||||
/// </summary>
|
||||
public DateTime PeriodEndAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 状态。
|
||||
/// </summary>
|
||||
public FinanceBusinessReportStatus Status { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 营业额。
|
||||
/// </summary>
|
||||
public decimal RevenueAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 订单数。
|
||||
/// </summary>
|
||||
public int OrderCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 客单价。
|
||||
/// </summary>
|
||||
public decimal AverageOrderValue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 退款率(0-1)。
|
||||
/// </summary>
|
||||
public decimal RefundRate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 成本总额。
|
||||
/// </summary>
|
||||
public decimal CostTotalAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 净利润。
|
||||
/// </summary>
|
||||
public decimal NetProfitAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 利润率(0-1)。
|
||||
/// </summary>
|
||||
public decimal ProfitRate { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表分页快照。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportPageSnapshot
|
||||
{
|
||||
/// <summary>
|
||||
/// 列表。
|
||||
/// </summary>
|
||||
public List<FinanceBusinessReportListItemSnapshot> Items { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 总数。
|
||||
/// </summary>
|
||||
public int TotalCount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表详情快照。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportDetailSnapshot
|
||||
{
|
||||
/// <summary>
|
||||
/// 报表 ID。
|
||||
/// </summary>
|
||||
public long ReportId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 门店 ID。
|
||||
/// </summary>
|
||||
public long StoreId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 周期类型。
|
||||
/// </summary>
|
||||
public FinanceBusinessReportPeriodType PeriodType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 周期开始时间(UTC,含)。
|
||||
/// </summary>
|
||||
public DateTime PeriodStartAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 周期结束时间(UTC,不含)。
|
||||
/// </summary>
|
||||
public DateTime PeriodEndAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 状态。
|
||||
/// </summary>
|
||||
public FinanceBusinessReportStatus Status { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 营业额。
|
||||
/// </summary>
|
||||
public decimal RevenueAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 订单数。
|
||||
/// </summary>
|
||||
public int OrderCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 客单价。
|
||||
/// </summary>
|
||||
public decimal AverageOrderValue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 退款率(0-1)。
|
||||
/// </summary>
|
||||
public decimal RefundRate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 成本总额。
|
||||
/// </summary>
|
||||
public decimal CostTotalAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 净利润。
|
||||
/// </summary>
|
||||
public decimal NetProfitAmount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 利润率(0-1)。
|
||||
/// </summary>
|
||||
public decimal ProfitRate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 关键指标快照列表。
|
||||
/// </summary>
|
||||
public List<FinanceBusinessReportKpiSnapshot> Kpis { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 收入明细(按渠道)。
|
||||
/// </summary>
|
||||
public List<FinanceBusinessReportBreakdownSnapshot> IncomeBreakdowns { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// 成本明细(按类别)。
|
||||
/// </summary>
|
||||
public List<FinanceBusinessReportBreakdownSnapshot> CostBreakdowns { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 待处理报表任务快照。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportPendingSnapshot
|
||||
{
|
||||
/// <summary>
|
||||
/// 快照 ID。
|
||||
/// </summary>
|
||||
public long SnapshotId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 租户 ID。
|
||||
/// </summary>
|
||||
public long TenantId { get; set; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
using TakeoutSaaS.Domain.Payments.Enums;
|
||||
|
||||
namespace TakeoutSaaS.Domain.Finance.Models;
|
||||
|
||||
/// <summary>
|
||||
/// 到账查询汇总行。
|
||||
/// </summary>
|
||||
public sealed record FinanceSettlementListItemSnapshot
|
||||
{
|
||||
/// <summary>
|
||||
/// 到账日期(UTC 日期)。
|
||||
/// </summary>
|
||||
public required DateTime ArrivedDate { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 支付方式。
|
||||
/// </summary>
|
||||
public required PaymentMethod PaymentMethod { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 交易笔数。
|
||||
/// </summary>
|
||||
public required int TransactionCount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 到账金额。
|
||||
/// </summary>
|
||||
public required decimal ArrivedAmount { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账查询明细行。
|
||||
/// </summary>
|
||||
public sealed record FinanceSettlementDetailItemSnapshot
|
||||
{
|
||||
/// <summary>
|
||||
/// 订单号。
|
||||
/// </summary>
|
||||
public required string OrderNo { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 支付金额。
|
||||
/// </summary>
|
||||
public required decimal Amount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 支付时间(UTC)。
|
||||
/// </summary>
|
||||
public required DateTime PaidAt { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账查询分页快照。
|
||||
/// </summary>
|
||||
public sealed record FinanceSettlementPageSnapshot
|
||||
{
|
||||
/// <summary>
|
||||
/// 列表项。
|
||||
/// </summary>
|
||||
public required IReadOnlyList<FinanceSettlementListItemSnapshot> Items { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 总数。
|
||||
/// </summary>
|
||||
public required int TotalCount { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账概览统计快照。
|
||||
/// </summary>
|
||||
public sealed record FinanceSettlementStatsSnapshot
|
||||
{
|
||||
/// <summary>
|
||||
/// 今日到账。
|
||||
/// </summary>
|
||||
public required decimal TodayArrivedAmount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 昨日到账。
|
||||
/// </summary>
|
||||
public required decimal YesterdayArrivedAmount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 本月到账。
|
||||
/// </summary>
|
||||
public required decimal CurrentMonthArrivedAmount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 本月交易笔数。
|
||||
/// </summary>
|
||||
public required int CurrentMonthTransactionCount { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 到账账户信息快照。
|
||||
/// </summary>
|
||||
public sealed record FinanceSettlementAccountSnapshot
|
||||
{
|
||||
/// <summary>
|
||||
/// 银行名称。
|
||||
/// </summary>
|
||||
public required string BankName { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 开户名。
|
||||
/// </summary>
|
||||
public required string BankAccountName { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 脱敏银行账号。
|
||||
/// </summary>
|
||||
public required string BankAccountNoMasked { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 微信商户号(脱敏)。
|
||||
/// </summary>
|
||||
public required string WechatMerchantNoMasked { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 支付宝 PID(脱敏)。
|
||||
/// </summary>
|
||||
public required string AlipayPidMasked { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 结算周期文案。
|
||||
/// </summary>
|
||||
public required string SettlementPeriodText { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using TakeoutSaaS.Domain.Finance.Enums;
|
||||
using TakeoutSaaS.Domain.Finance.Models;
|
||||
|
||||
namespace TakeoutSaaS.Domain.Finance.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表仓储契约。
|
||||
/// </summary>
|
||||
public interface IFinanceBusinessReportRepository
|
||||
{
|
||||
/// <summary>
|
||||
/// 确保门店存在默认成本配置。
|
||||
/// </summary>
|
||||
Task EnsureDefaultCostProfilesAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 为指定分页周期补齐快照并排队。
|
||||
/// </summary>
|
||||
Task QueueSnapshotsForPageAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
FinanceBusinessReportPeriodType periodType,
|
||||
int page,
|
||||
int pageSize,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 查询经营报表分页结果。
|
||||
/// </summary>
|
||||
Task<FinanceBusinessReportPageSnapshot> SearchPageAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
FinanceBusinessReportPeriodType periodType,
|
||||
int page,
|
||||
int pageSize,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 查询经营报表详情。
|
||||
/// </summary>
|
||||
Task<FinanceBusinessReportDetailSnapshot?> GetDetailAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
long reportId,
|
||||
bool allowRealtimeBuild,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 查询批量导出详情集合。
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<FinanceBusinessReportDetailSnapshot>> ListBatchDetailsAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
FinanceBusinessReportPeriodType periodType,
|
||||
int page,
|
||||
int pageSize,
|
||||
bool allowRealtimeBuild,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 拉取待处理任务。
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<FinanceBusinessReportPendingSnapshot>> GetPendingSnapshotsAsync(
|
||||
int take,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 执行报表快照生成。
|
||||
/// </summary>
|
||||
Task GenerateSnapshotAsync(
|
||||
long snapshotId,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -63,4 +63,55 @@ public interface IFinanceTransactionRepository
|
||||
PaymentMethod? paymentMethod,
|
||||
string? keyword,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账概览统计。
|
||||
/// </summary>
|
||||
Task<FinanceSettlementStatsSnapshot> GetSettlementStatsAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime currentUtc,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账账户信息。
|
||||
/// </summary>
|
||||
Task<FinanceSettlementAccountSnapshot?> GetSettlementAccountAsync(
|
||||
long tenantId,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账汇总分页。
|
||||
/// </summary>
|
||||
Task<FinanceSettlementPageSnapshot> SearchSettlementPageAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime? startAt,
|
||||
DateTime? endAt,
|
||||
PaymentMethod? paymentMethod,
|
||||
int page,
|
||||
int pageSize,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账明细。
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<FinanceSettlementDetailItemSnapshot>> GetSettlementDetailsAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime arrivedDate,
|
||||
PaymentMethod paymentMethod,
|
||||
int take,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 查询到账导出数据。
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<FinanceSettlementListItemSnapshot>> ListSettlementForExportAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime? startAt,
|
||||
DateTime? endAt,
|
||||
PaymentMethod? paymentMethod,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
using TakeoutSaaS.Domain.Finance.Models;
|
||||
|
||||
namespace TakeoutSaaS.Domain.Finance.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表导出服务契约。
|
||||
/// </summary>
|
||||
public interface IFinanceBusinessReportExportService
|
||||
{
|
||||
/// <summary>
|
||||
/// 导出单条报表 PDF。
|
||||
/// </summary>
|
||||
Task<byte[]> ExportSinglePdfAsync(
|
||||
FinanceBusinessReportDetailSnapshot detail,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 导出单条报表 Excel。
|
||||
/// </summary>
|
||||
Task<byte[]> ExportSingleExcelAsync(
|
||||
FinanceBusinessReportDetailSnapshot detail,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 导出批量报表 PDF。
|
||||
/// </summary>
|
||||
Task<byte[]> ExportBatchPdfAsync(
|
||||
IReadOnlyList<FinanceBusinessReportDetailSnapshot> details,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 导出批量报表 Excel。
|
||||
/// </summary>
|
||||
Task<byte[]> ExportBatchExcelAsync(
|
||||
IReadOnlyList<FinanceBusinessReportDetailSnapshot> details,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
using TakeoutSaaS.Domain.Tenants.Enums;
|
||||
using TakeoutSaaS.Shared.Abstractions.Entities;
|
||||
|
||||
namespace TakeoutSaaS.Domain.Tenants.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 租户发票记录。
|
||||
/// </summary>
|
||||
public sealed class TenantInvoiceRecord : MultiTenantEntityBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 发票号码。
|
||||
/// </summary>
|
||||
public string InvoiceNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 申请人。
|
||||
/// </summary>
|
||||
public string ApplicantName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 开票抬头(公司名)。
|
||||
/// </summary>
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 纳税人识别号快照。
|
||||
/// </summary>
|
||||
public string? TaxpayerNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 发票类型。
|
||||
/// </summary>
|
||||
public TenantInvoiceType InvoiceType { get; set; } = TenantInvoiceType.Normal;
|
||||
|
||||
/// <summary>
|
||||
/// 开票金额。
|
||||
/// </summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 关联订单号。
|
||||
/// </summary>
|
||||
public string OrderNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 接收邮箱。
|
||||
/// </summary>
|
||||
public string? ContactEmail { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 联系电话。
|
||||
/// </summary>
|
||||
public string? ContactPhone { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 申请备注。
|
||||
/// </summary>
|
||||
public string? ApplyRemark { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 发票状态。
|
||||
/// </summary>
|
||||
public TenantInvoiceStatus Status { get; set; } = TenantInvoiceStatus.Pending;
|
||||
|
||||
/// <summary>
|
||||
/// 申请时间(UTC)。
|
||||
/// </summary>
|
||||
public DateTime AppliedAt { get; set; } = DateTime.UtcNow;
|
||||
|
||||
/// <summary>
|
||||
/// 开票时间(UTC)。
|
||||
/// </summary>
|
||||
public DateTime? IssuedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开票人 ID。
|
||||
/// </summary>
|
||||
public long? IssuedByUserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开票备注。
|
||||
/// </summary>
|
||||
public string? IssueRemark { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 作废时间(UTC)。
|
||||
/// </summary>
|
||||
public DateTime? VoidedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 作废人 ID。
|
||||
/// </summary>
|
||||
public long? VoidedByUserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 作废原因。
|
||||
/// </summary>
|
||||
public string? VoidReason { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using TakeoutSaaS.Shared.Abstractions.Entities;
|
||||
|
||||
namespace TakeoutSaaS.Domain.Tenants.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 租户发票开票基础设置。
|
||||
/// </summary>
|
||||
public sealed class TenantInvoiceSetting : MultiTenantEntityBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 企业名称。
|
||||
/// </summary>
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 纳税人识别号。
|
||||
/// </summary>
|
||||
public string TaxpayerNumber { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 注册地址。
|
||||
/// </summary>
|
||||
public string? RegisteredAddress { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 注册电话。
|
||||
/// </summary>
|
||||
public string? RegisteredPhone { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开户银行。
|
||||
/// </summary>
|
||||
public string? BankName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 银行账号。
|
||||
/// </summary>
|
||||
public string? BankAccount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用电子普通发票。
|
||||
/// </summary>
|
||||
public bool EnableElectronicNormalInvoice { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用电子专用发票。
|
||||
/// </summary>
|
||||
public bool EnableElectronicSpecialInvoice { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用自动开票。
|
||||
/// </summary>
|
||||
public bool EnableAutoIssue { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 自动开票单张最大金额。
|
||||
/// </summary>
|
||||
public decimal AutoIssueMaxAmount { get; set; } = 10_000m;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using TakeoutSaaS.Domain.Tenants.Enums;
|
||||
using TakeoutSaaS.Shared.Abstractions.Entities;
|
||||
|
||||
@@ -63,6 +64,18 @@ public sealed class TenantVerificationProfile : AuditableEntityBase
|
||||
/// </summary>
|
||||
public string? BankName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 微信商户号。
|
||||
/// </summary>
|
||||
[MaxLength(64)]
|
||||
public string? WeChatMerchantNo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 支付宝 PID。
|
||||
/// </summary>
|
||||
[MaxLength(64)]
|
||||
public string? AlipayPid { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 附加资料(JSON)。
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace TakeoutSaaS.Domain.Tenants.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// 租户发票状态。
|
||||
/// </summary>
|
||||
public enum TenantInvoiceStatus
|
||||
{
|
||||
/// <summary>
|
||||
/// 待开票。
|
||||
/// </summary>
|
||||
Pending = 1,
|
||||
|
||||
/// <summary>
|
||||
/// 已开票。
|
||||
/// </summary>
|
||||
Issued = 2,
|
||||
|
||||
/// <summary>
|
||||
/// 已作废。
|
||||
/// </summary>
|
||||
Voided = 3
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace TakeoutSaaS.Domain.Tenants.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// 租户发票类型。
|
||||
/// </summary>
|
||||
public enum TenantInvoiceType
|
||||
{
|
||||
/// <summary>
|
||||
/// 电子普通发票。
|
||||
/// </summary>
|
||||
Normal = 1,
|
||||
|
||||
/// <summary>
|
||||
/// 电子专用发票。
|
||||
/// </summary>
|
||||
Special = 2
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using TakeoutSaaS.Domain.Tenants.Entities;
|
||||
using TakeoutSaaS.Domain.Tenants.Enums;
|
||||
|
||||
namespace TakeoutSaaS.Domain.Tenants.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// 租户发票仓储契约。
|
||||
/// </summary>
|
||||
public interface ITenantInvoiceRepository
|
||||
{
|
||||
/// <summary>
|
||||
/// 查询租户发票设置。
|
||||
/// </summary>
|
||||
Task<TenantInvoiceSetting?> GetSettingAsync(long tenantId, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 新增发票设置。
|
||||
/// </summary>
|
||||
Task AddSettingAsync(TenantInvoiceSetting entity, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 更新发票设置。
|
||||
/// </summary>
|
||||
Task UpdateSettingAsync(TenantInvoiceSetting entity, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 分页查询发票记录。
|
||||
/// </summary>
|
||||
Task<(IReadOnlyList<TenantInvoiceRecord> Items, int TotalCount)> SearchRecordsAsync(
|
||||
long tenantId,
|
||||
DateTime? startUtc,
|
||||
DateTime? endUtc,
|
||||
TenantInvoiceStatus? status,
|
||||
TenantInvoiceType? invoiceType,
|
||||
string? keyword,
|
||||
int page,
|
||||
int pageSize,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 获取发票页统计。
|
||||
/// </summary>
|
||||
Task<TenantInvoiceRecordStatsSnapshot> GetStatsAsync(
|
||||
long tenantId,
|
||||
DateTime nowUtc,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 根据标识查询发票记录。
|
||||
/// </summary>
|
||||
Task<TenantInvoiceRecord?> FindRecordByIdAsync(
|
||||
long tenantId,
|
||||
long recordId,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 判断租户下发票号码是否已存在。
|
||||
/// </summary>
|
||||
Task<bool> ExistsInvoiceNoAsync(
|
||||
long tenantId,
|
||||
string invoiceNo,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 新增发票记录。
|
||||
/// </summary>
|
||||
Task AddRecordAsync(TenantInvoiceRecord entity, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 更新发票记录。
|
||||
/// </summary>
|
||||
Task UpdateRecordAsync(TenantInvoiceRecord entity, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 持久化变更。
|
||||
/// </summary>
|
||||
Task SaveChangesAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发票页面统计快照。
|
||||
/// </summary>
|
||||
public sealed record TenantInvoiceRecordStatsSnapshot
|
||||
{
|
||||
/// <summary>
|
||||
/// 本月已开票金额。
|
||||
/// </summary>
|
||||
public decimal CurrentMonthIssuedAmount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 本月已开票张数。
|
||||
/// </summary>
|
||||
public int CurrentMonthIssuedCount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 待开票张数。
|
||||
/// </summary>
|
||||
public int PendingCount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 已作废张数。
|
||||
/// </summary>
|
||||
public int VoidedCount { get; init; }
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using TakeoutSaaS.Application.App.Stores.Services;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Domain.Finance.Services;
|
||||
using TakeoutSaaS.Domain.Coupons.Repositories;
|
||||
using TakeoutSaaS.Domain.Deliveries.Repositories;
|
||||
using TakeoutSaaS.Domain.Inventory.Repositories;
|
||||
@@ -56,6 +57,7 @@ public static class AppServiceCollectionExtensions
|
||||
services.AddScoped<IStoredCardRepository, EfStoredCardRepository>();
|
||||
services.AddScoped<IOrderRepository, EfOrderRepository>();
|
||||
services.AddScoped<IFinanceCostRepository, EfFinanceCostRepository>();
|
||||
services.AddScoped<IFinanceBusinessReportRepository, EfFinanceBusinessReportRepository>();
|
||||
services.AddScoped<IFinanceTransactionRepository, EfFinanceTransactionRepository>();
|
||||
services.AddScoped<IPaymentRepository, EfPaymentRepository>();
|
||||
services.AddScoped<IDeliveryRepository, EfDeliveryRepository>();
|
||||
@@ -69,6 +71,7 @@ public static class AppServiceCollectionExtensions
|
||||
services.AddScoped<ITenantQuotaUsageRepository, EfTenantQuotaUsageRepository>();
|
||||
services.AddScoped<ITenantQuotaUsageHistoryRepository, EfTenantQuotaUsageHistoryRepository>();
|
||||
services.AddScoped<ITenantVisibilityRoleRuleRepository, TenantVisibilityRoleRuleRepository>();
|
||||
services.AddScoped<ITenantInvoiceRepository, EfTenantInvoiceRepository>();
|
||||
services.AddScoped<IInventoryRepository, EfInventoryRepository>();
|
||||
services.AddScoped<IQuotaPackageRepository, EfQuotaPackageRepository>();
|
||||
services.AddScoped<IStatisticsRepository, EfStatisticsRepository>();
|
||||
@@ -79,6 +82,7 @@ public static class AppServiceCollectionExtensions
|
||||
services.AddScoped<IBillingDomainService, BillingDomainService>();
|
||||
services.AddScoped<IBillingExportService, BillingExportService>();
|
||||
services.AddScoped<IMerchantExportService, MerchantExportService>();
|
||||
services.AddScoped<IFinanceBusinessReportExportService, FinanceBusinessReportExportService>();
|
||||
|
||||
// 2. (空行后) 门店配置服务
|
||||
services.AddScoped<IGeoJsonValidationService, GeoJsonValidationService>();
|
||||
|
||||
@@ -95,6 +95,26 @@ public sealed class TakeoutAppDbContext(
|
||||
/// </summary>
|
||||
public DbSet<TenantVisibilityRoleRule> TenantVisibilityRoleRules => Set<TenantVisibilityRoleRule>();
|
||||
/// <summary>
|
||||
/// 租户发票设置。
|
||||
/// </summary>
|
||||
public DbSet<TenantInvoiceSetting> TenantInvoiceSettings => Set<TenantInvoiceSetting>();
|
||||
/// <summary>
|
||||
/// 租户发票记录。
|
||||
/// </summary>
|
||||
public DbSet<TenantInvoiceRecord> TenantInvoiceRecords => Set<TenantInvoiceRecord>();
|
||||
/// <summary>
|
||||
/// 经营报表快照。
|
||||
/// </summary>
|
||||
public DbSet<FinanceBusinessReportSnapshot> FinanceBusinessReportSnapshots => Set<FinanceBusinessReportSnapshot>();
|
||||
/// <summary>
|
||||
/// 成本配置。
|
||||
/// </summary>
|
||||
public DbSet<FinanceCostProfile> FinanceCostProfiles => Set<FinanceCostProfile>();
|
||||
/// <summary>
|
||||
/// 成本日覆盖。
|
||||
/// </summary>
|
||||
public DbSet<FinanceCostDailyOverride> FinanceCostDailyOverrides => Set<FinanceCostDailyOverride>();
|
||||
/// <summary>
|
||||
/// 成本录入汇总。
|
||||
/// </summary>
|
||||
public DbSet<FinanceCostEntry> FinanceCostEntries => Set<FinanceCostEntry>();
|
||||
@@ -534,6 +554,11 @@ public sealed class TakeoutAppDbContext(
|
||||
ConfigureTenantAnnouncementRead(modelBuilder.Entity<TenantAnnouncementRead>());
|
||||
ConfigureTenantVerificationProfile(modelBuilder.Entity<TenantVerificationProfile>());
|
||||
ConfigureTenantVisibilityRoleRule(modelBuilder.Entity<TenantVisibilityRoleRule>());
|
||||
ConfigureTenantInvoiceSetting(modelBuilder.Entity<TenantInvoiceSetting>());
|
||||
ConfigureTenantInvoiceRecord(modelBuilder.Entity<TenantInvoiceRecord>());
|
||||
ConfigureFinanceBusinessReportSnapshot(modelBuilder.Entity<FinanceBusinessReportSnapshot>());
|
||||
ConfigureFinanceCostProfile(modelBuilder.Entity<FinanceCostProfile>());
|
||||
ConfigureFinanceCostDailyOverride(modelBuilder.Entity<FinanceCostDailyOverride>());
|
||||
ConfigureFinanceCostEntry(modelBuilder.Entity<FinanceCostEntry>());
|
||||
ConfigureFinanceCostEntryItem(modelBuilder.Entity<FinanceCostEntryItem>());
|
||||
ConfigureQuotaPackage(modelBuilder.Entity<QuotaPackage>());
|
||||
@@ -1053,6 +1078,114 @@ public sealed class TakeoutAppDbContext(
|
||||
builder.HasIndex(x => x.TenantId).IsUnique();
|
||||
}
|
||||
|
||||
private static void ConfigureTenantInvoiceSetting(EntityTypeBuilder<TenantInvoiceSetting> builder)
|
||||
{
|
||||
builder.ToTable("finance_invoice_settings");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.TenantId).IsRequired();
|
||||
builder.Property(x => x.CompanyName).HasMaxLength(128).IsRequired();
|
||||
builder.Property(x => x.TaxpayerNumber).HasMaxLength(64).IsRequired();
|
||||
builder.Property(x => x.RegisteredAddress).HasMaxLength(256);
|
||||
builder.Property(x => x.RegisteredPhone).HasMaxLength(32);
|
||||
builder.Property(x => x.BankName).HasMaxLength(128);
|
||||
builder.Property(x => x.BankAccount).HasMaxLength(64);
|
||||
builder.Property(x => x.EnableElectronicNormalInvoice).IsRequired();
|
||||
builder.Property(x => x.EnableElectronicSpecialInvoice).IsRequired();
|
||||
builder.Property(x => x.EnableAutoIssue).IsRequired();
|
||||
builder.Property(x => x.AutoIssueMaxAmount).HasPrecision(18, 2).IsRequired();
|
||||
|
||||
builder.HasIndex(x => x.TenantId).IsUnique();
|
||||
}
|
||||
|
||||
private static void ConfigureTenantInvoiceRecord(EntityTypeBuilder<TenantInvoiceRecord> builder)
|
||||
{
|
||||
builder.ToTable("finance_invoice_records");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.TenantId).IsRequired();
|
||||
builder.Property(x => x.InvoiceNo).HasMaxLength(32).IsRequired();
|
||||
builder.Property(x => x.ApplicantName).HasMaxLength(64).IsRequired();
|
||||
builder.Property(x => x.CompanyName).HasMaxLength(128).IsRequired();
|
||||
builder.Property(x => x.TaxpayerNumber).HasMaxLength(64);
|
||||
builder.Property(x => x.InvoiceType).HasConversion<int>().IsRequired();
|
||||
builder.Property(x => x.Amount).HasPrecision(18, 2).IsRequired();
|
||||
builder.Property(x => x.OrderNo).HasMaxLength(32).IsRequired();
|
||||
builder.Property(x => x.ContactEmail).HasMaxLength(128);
|
||||
builder.Property(x => x.ContactPhone).HasMaxLength(32);
|
||||
builder.Property(x => x.ApplyRemark).HasMaxLength(256);
|
||||
builder.Property(x => x.Status).HasConversion<int>().IsRequired();
|
||||
builder.Property(x => x.AppliedAt).IsRequired();
|
||||
builder.Property(x => x.IssueRemark).HasMaxLength(256);
|
||||
builder.Property(x => x.VoidReason).HasMaxLength(256);
|
||||
|
||||
builder.HasIndex(x => new { x.TenantId, x.InvoiceNo }).IsUnique();
|
||||
builder.HasIndex(x => new { x.TenantId, x.OrderNo });
|
||||
builder.HasIndex(x => new { x.TenantId, x.Status, x.AppliedAt });
|
||||
builder.HasIndex(x => new { x.TenantId, x.Status, x.IssuedAt });
|
||||
builder.HasIndex(x => new { x.TenantId, x.InvoiceType, x.AppliedAt });
|
||||
}
|
||||
|
||||
private static void ConfigureFinanceBusinessReportSnapshot(EntityTypeBuilder<FinanceBusinessReportSnapshot> builder)
|
||||
{
|
||||
builder.ToTable("finance_business_report_snapshots");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.TenantId).IsRequired();
|
||||
builder.Property(x => x.StoreId).IsRequired();
|
||||
builder.Property(x => x.PeriodType).HasConversion<int>().IsRequired();
|
||||
builder.Property(x => x.PeriodStartAt).IsRequired();
|
||||
builder.Property(x => x.PeriodEndAt).IsRequired();
|
||||
builder.Property(x => x.Status).HasConversion<int>().IsRequired();
|
||||
builder.Property(x => x.RevenueAmount).HasPrecision(18, 2);
|
||||
builder.Property(x => x.OrderCount).IsRequired();
|
||||
builder.Property(x => x.AverageOrderValue).HasPrecision(18, 2);
|
||||
builder.Property(x => x.RefundRate).HasPrecision(9, 4);
|
||||
builder.Property(x => x.CostTotalAmount).HasPrecision(18, 2);
|
||||
builder.Property(x => x.NetProfitAmount).HasPrecision(18, 2);
|
||||
builder.Property(x => x.ProfitRate).HasPrecision(9, 4);
|
||||
builder.Property(x => x.KpiComparisonJson).HasColumnType("text").IsRequired();
|
||||
builder.Property(x => x.IncomeBreakdownJson).HasColumnType("text").IsRequired();
|
||||
builder.Property(x => x.CostBreakdownJson).HasColumnType("text").IsRequired();
|
||||
builder.Property(x => x.LastError).HasMaxLength(1024);
|
||||
builder.Property(x => x.HangfireJobId).HasMaxLength(64);
|
||||
builder.Property(x => x.RetryCount).HasDefaultValue(0);
|
||||
|
||||
builder.HasIndex(x => new { x.TenantId, x.StoreId, x.PeriodType, x.PeriodStartAt }).IsUnique();
|
||||
builder.HasIndex(x => new { x.TenantId, x.StoreId, x.PeriodType, x.Status, x.PeriodStartAt });
|
||||
builder.HasIndex(x => new { x.TenantId, x.Status, x.CreatedAt });
|
||||
}
|
||||
|
||||
private static void ConfigureFinanceCostProfile(EntityTypeBuilder<FinanceCostProfile> builder)
|
||||
{
|
||||
builder.ToTable("finance_cost_profiles");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.TenantId).IsRequired();
|
||||
builder.Property(x => x.StoreId).IsRequired();
|
||||
builder.Property(x => x.Category).HasConversion<int>().IsRequired();
|
||||
builder.Property(x => x.CalcMode).HasConversion<int>().IsRequired();
|
||||
builder.Property(x => x.Ratio).HasPrecision(9, 6).IsRequired();
|
||||
builder.Property(x => x.FixedDailyAmount).HasPrecision(18, 2).IsRequired();
|
||||
builder.Property(x => x.EffectiveFrom).IsRequired();
|
||||
builder.Property(x => x.EffectiveTo);
|
||||
builder.Property(x => x.IsEnabled).IsRequired();
|
||||
builder.Property(x => x.SortOrder).HasDefaultValue(100);
|
||||
|
||||
builder.HasIndex(x => new { x.TenantId, x.StoreId, x.Category, x.EffectiveFrom, x.EffectiveTo });
|
||||
builder.HasIndex(x => new { x.TenantId, x.StoreId, x.IsEnabled, x.SortOrder });
|
||||
}
|
||||
|
||||
private static void ConfigureFinanceCostDailyOverride(EntityTypeBuilder<FinanceCostDailyOverride> builder)
|
||||
{
|
||||
builder.ToTable("finance_cost_daily_overrides");
|
||||
builder.HasKey(x => x.Id);
|
||||
builder.Property(x => x.TenantId).IsRequired();
|
||||
builder.Property(x => x.StoreId).IsRequired();
|
||||
builder.Property(x => x.BusinessDate).IsRequired();
|
||||
builder.Property(x => x.Category).HasConversion<int>().IsRequired();
|
||||
builder.Property(x => x.Amount).HasPrecision(18, 2).IsRequired();
|
||||
builder.Property(x => x.Remark).HasMaxLength(256);
|
||||
|
||||
builder.HasIndex(x => new { x.TenantId, x.StoreId, x.BusinessDate, x.Category }).IsUnique();
|
||||
builder.HasIndex(x => new { x.TenantId, x.StoreId, x.BusinessDate });
|
||||
}
|
||||
private static void ConfigureFinanceCostEntry(EntityTypeBuilder<FinanceCostEntry> builder)
|
||||
{
|
||||
builder.ToTable("finance_cost_entries");
|
||||
@@ -2313,4 +2446,3 @@ public sealed class TakeoutAppDbContext(
|
||||
builder.HasIndex(x => new { x.TenantId, x.QuotaPackageId, x.PurchasedAt });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,761 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using TakeoutSaaS.Domain.Finance.Entities;
|
||||
using TakeoutSaaS.Domain.Finance.Enums;
|
||||
using TakeoutSaaS.Domain.Finance.Models;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Domain.Orders.Enums;
|
||||
using TakeoutSaaS.Domain.Payments.Enums;
|
||||
using TakeoutSaaS.Infrastructure.App.Persistence;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Infrastructure.App.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表 EF Core 仓储实现。
|
||||
/// </summary>
|
||||
public sealed class EfFinanceBusinessReportRepository(
|
||||
TakeoutAppDbContext context,
|
||||
ITenantContextAccessor tenantContextAccessor) : IFinanceBusinessReportRepository
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
private static readonly FinanceCostCategory[] CostCategoryOrder =
|
||||
[
|
||||
FinanceCostCategory.FoodMaterial,
|
||||
FinanceCostCategory.Labor,
|
||||
FinanceCostCategory.FixedExpense,
|
||||
FinanceCostCategory.PackagingConsumable
|
||||
];
|
||||
private static readonly DeliveryType[] IncomeChannelOrder =
|
||||
[
|
||||
DeliveryType.Delivery,
|
||||
DeliveryType.Pickup,
|
||||
DeliveryType.DineIn
|
||||
];
|
||||
private static readonly IReadOnlyDictionary<FinanceCostCategory, (FinanceCostCalcMode Mode, decimal Ratio, decimal Fixed)> DefaultCostProfileMap =
|
||||
new Dictionary<FinanceCostCategory, (FinanceCostCalcMode, decimal, decimal)>
|
||||
{
|
||||
[FinanceCostCategory.FoodMaterial] = (FinanceCostCalcMode.Ratio, 0.36m, 0m),
|
||||
[FinanceCostCategory.Labor] = (FinanceCostCalcMode.Ratio, 0.19m, 0m),
|
||||
[FinanceCostCategory.FixedExpense] = (FinanceCostCalcMode.FixedDaily, 0m, 190m),
|
||||
[FinanceCostCategory.PackagingConsumable] = (FinanceCostCalcMode.Ratio, 0.04m, 0m)
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task EnsureDefaultCostProfilesAsync(long tenantId, long storeId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (tenantId <= 0 || storeId <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var existing = await context.FinanceCostProfiles
|
||||
.AsNoTracking()
|
||||
.Where(item => item.TenantId == tenantId && item.StoreId == storeId && item.DeletedAt == null)
|
||||
.Select(item => item.Category)
|
||||
.Distinct()
|
||||
.ToListAsync(cancellationToken);
|
||||
var missing = CostCategoryOrder.Where(item => !existing.Contains(item)).ToList();
|
||||
if (missing.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var effectiveFrom = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
var entities = missing.Select((category, index) =>
|
||||
{
|
||||
var profile = DefaultCostProfileMap[category];
|
||||
return new FinanceCostProfile
|
||||
{
|
||||
TenantId = tenantId,
|
||||
StoreId = storeId,
|
||||
Category = category,
|
||||
CalcMode = profile.Mode,
|
||||
Ratio = profile.Ratio,
|
||||
FixedDailyAmount = profile.Fixed,
|
||||
EffectiveFrom = effectiveFrom,
|
||||
IsEnabled = true,
|
||||
SortOrder = (index + 1) * 10
|
||||
};
|
||||
}).ToList();
|
||||
|
||||
await context.FinanceCostProfiles.AddRangeAsync(entities, cancellationToken);
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task QueueSnapshotsForPageAsync(long tenantId, long storeId, FinanceBusinessReportPeriodType periodType, int page, int pageSize, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (tenantId <= 0 || storeId <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
var periods = BuildPagedPeriods(periodType, page, pageSize, now);
|
||||
var starts = periods.Select(item => item.StartAt).ToHashSet();
|
||||
var existing = await context.FinanceBusinessReportSnapshots
|
||||
.Where(item =>
|
||||
item.TenantId == tenantId &&
|
||||
item.StoreId == storeId &&
|
||||
item.PeriodType == periodType &&
|
||||
item.DeletedAt == null &&
|
||||
starts.Contains(item.PeriodStartAt))
|
||||
.OrderByDescending(item => item.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
var map = existing.GroupBy(item => item.PeriodStartAt).ToDictionary(group => group.Key, group => group.First());
|
||||
|
||||
var changed = false;
|
||||
foreach (var period in periods)
|
||||
{
|
||||
if (!map.TryGetValue(period.StartAt, out var snapshot))
|
||||
{
|
||||
await context.FinanceBusinessReportSnapshots.AddAsync(new FinanceBusinessReportSnapshot
|
||||
{
|
||||
TenantId = tenantId,
|
||||
StoreId = storeId,
|
||||
PeriodType = periodType,
|
||||
PeriodStartAt = period.StartAt,
|
||||
PeriodEndAt = period.EndAt,
|
||||
Status = FinanceBusinessReportStatus.Queued
|
||||
}, cancellationToken);
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (snapshot.PeriodEndAt != period.EndAt)
|
||||
{
|
||||
snapshot.PeriodEndAt = period.EndAt;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (snapshot.Status == FinanceBusinessReportStatus.Failed && snapshot.RetryCount < 5)
|
||||
{
|
||||
snapshot.Status = FinanceBusinessReportStatus.Queued;
|
||||
snapshot.LastError = null;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (now >= period.StartAt
|
||||
&& now < period.EndAt
|
||||
&& snapshot.Status == FinanceBusinessReportStatus.Succeeded
|
||||
&& (!snapshot.FinishedAt.HasValue || snapshot.FinishedAt.Value.AddMinutes(30) <= now))
|
||||
{
|
||||
snapshot.Status = FinanceBusinessReportStatus.Queued;
|
||||
snapshot.StartedAt = null;
|
||||
snapshot.FinishedAt = null;
|
||||
snapshot.LastError = null;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed)
|
||||
{
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceBusinessReportPageSnapshot> SearchPageAsync(long tenantId, long storeId, FinanceBusinessReportPeriodType periodType, int page, int pageSize, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var normalizedPage = Math.Max(1, page);
|
||||
var normalizedPageSize = Math.Clamp(pageSize, 1, 200);
|
||||
var query = context.FinanceBusinessReportSnapshots
|
||||
.AsNoTracking()
|
||||
.Where(item =>
|
||||
item.TenantId == tenantId &&
|
||||
item.StoreId == storeId &&
|
||||
item.PeriodType == periodType &&
|
||||
item.DeletedAt == null);
|
||||
|
||||
var totalCount = await query.CountAsync(cancellationToken);
|
||||
if (totalCount == 0)
|
||||
{
|
||||
return new FinanceBusinessReportPageSnapshot();
|
||||
}
|
||||
|
||||
var items = await query
|
||||
.OrderByDescending(item => item.PeriodStartAt)
|
||||
.ThenByDescending(item => item.Id)
|
||||
.Skip((normalizedPage - 1) * normalizedPageSize)
|
||||
.Take(normalizedPageSize)
|
||||
.Select(item => new FinanceBusinessReportListItemSnapshot
|
||||
{
|
||||
ReportId = item.Id,
|
||||
PeriodType = item.PeriodType,
|
||||
PeriodStartAt = item.PeriodStartAt,
|
||||
PeriodEndAt = item.PeriodEndAt,
|
||||
Status = item.Status,
|
||||
RevenueAmount = item.RevenueAmount,
|
||||
OrderCount = item.OrderCount,
|
||||
AverageOrderValue = item.AverageOrderValue,
|
||||
RefundRate = item.RefundRate,
|
||||
CostTotalAmount = item.CostTotalAmount,
|
||||
NetProfitAmount = item.NetProfitAmount,
|
||||
ProfitRate = item.ProfitRate
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return new FinanceBusinessReportPageSnapshot
|
||||
{
|
||||
Items = items,
|
||||
TotalCount = totalCount
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceBusinessReportDetailSnapshot?> GetDetailAsync(long tenantId, long storeId, long reportId, bool allowRealtimeBuild, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var snapshot = await context.FinanceBusinessReportSnapshots
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(item => item.TenantId == tenantId && item.StoreId == storeId && item.Id == reportId && item.DeletedAt == null, cancellationToken);
|
||||
if (snapshot is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (allowRealtimeBuild && snapshot.Status != FinanceBusinessReportStatus.Succeeded)
|
||||
{
|
||||
await GenerateSnapshotAsync(reportId, cancellationToken);
|
||||
snapshot = await context.FinanceBusinessReportSnapshots
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(item => item.TenantId == tenantId && item.StoreId == storeId && item.Id == reportId && item.DeletedAt == null, cancellationToken);
|
||||
if (snapshot is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return new FinanceBusinessReportDetailSnapshot
|
||||
{
|
||||
ReportId = snapshot.Id,
|
||||
StoreId = snapshot.StoreId,
|
||||
PeriodType = snapshot.PeriodType,
|
||||
PeriodStartAt = snapshot.PeriodStartAt,
|
||||
PeriodEndAt = snapshot.PeriodEndAt,
|
||||
Status = snapshot.Status,
|
||||
RevenueAmount = snapshot.RevenueAmount,
|
||||
OrderCount = snapshot.OrderCount,
|
||||
AverageOrderValue = snapshot.AverageOrderValue,
|
||||
RefundRate = snapshot.RefundRate,
|
||||
CostTotalAmount = snapshot.CostTotalAmount,
|
||||
NetProfitAmount = snapshot.NetProfitAmount,
|
||||
ProfitRate = snapshot.ProfitRate,
|
||||
Kpis = Deserialize<FinanceBusinessReportKpiSnapshot>(snapshot.KpiComparisonJson),
|
||||
IncomeBreakdowns = Deserialize<FinanceBusinessReportBreakdownSnapshot>(snapshot.IncomeBreakdownJson),
|
||||
CostBreakdowns = Deserialize<FinanceBusinessReportBreakdownSnapshot>(snapshot.CostBreakdownJson)
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<FinanceBusinessReportDetailSnapshot>> ListBatchDetailsAsync(long tenantId, long storeId, FinanceBusinessReportPeriodType periodType, int page, int pageSize, bool allowRealtimeBuild, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var normalizedPage = Math.Max(1, page);
|
||||
var normalizedPageSize = Math.Clamp(pageSize, 1, 200);
|
||||
var reportIds = await context.FinanceBusinessReportSnapshots
|
||||
.AsNoTracking()
|
||||
.Where(item => item.TenantId == tenantId && item.StoreId == storeId && item.PeriodType == periodType && item.DeletedAt == null)
|
||||
.OrderByDescending(item => item.PeriodStartAt)
|
||||
.ThenByDescending(item => item.Id)
|
||||
.Skip((normalizedPage - 1) * normalizedPageSize)
|
||||
.Take(normalizedPageSize)
|
||||
.Select(item => item.Id)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var list = new List<FinanceBusinessReportDetailSnapshot>(reportIds.Count);
|
||||
foreach (var reportId in reportIds)
|
||||
{
|
||||
var detail = await GetDetailAsync(tenantId, storeId, reportId, allowRealtimeBuild, cancellationToken);
|
||||
if (detail is not null)
|
||||
{
|
||||
list.Add(detail);
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<FinanceBusinessReportPendingSnapshot>> GetPendingSnapshotsAsync(int take, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var normalizedTake = Math.Clamp(take, 1, 200);
|
||||
if ((tenantContextAccessor.Current?.TenantId ?? 0) != 0)
|
||||
{
|
||||
return await QueryPendingAsync(normalizedTake, cancellationToken);
|
||||
}
|
||||
|
||||
var tenantIds = await context.Tenants.AsNoTracking().Where(item => item.DeletedAt == null && item.Id > 0).Select(item => item.Id).ToListAsync(cancellationToken);
|
||||
var pending = new List<(long SnapshotId, long TenantId, DateTime CreatedAt)>();
|
||||
foreach (var tenantId in tenantIds)
|
||||
{
|
||||
using (tenantContextAccessor.EnterTenantScope(tenantId, "finance-report"))
|
||||
{
|
||||
var rows = await context.FinanceBusinessReportSnapshots
|
||||
.AsNoTracking()
|
||||
.Where(item =>
|
||||
item.DeletedAt == null &&
|
||||
(item.Status == FinanceBusinessReportStatus.Queued || (item.Status == FinanceBusinessReportStatus.Failed && item.RetryCount < 3)))
|
||||
.OrderBy(item => item.CreatedAt)
|
||||
.ThenBy(item => item.Id)
|
||||
.Take(normalizedTake)
|
||||
.Select(item => new { item.Id, item.TenantId, item.CreatedAt })
|
||||
.ToListAsync(cancellationToken);
|
||||
pending.AddRange(rows.Select(item => (item.Id, item.TenantId, item.CreatedAt)));
|
||||
}
|
||||
}
|
||||
|
||||
return pending.OrderBy(item => item.CreatedAt).ThenBy(item => item.SnapshotId).Take(normalizedTake).Select(item => new FinanceBusinessReportPendingSnapshot { SnapshotId = item.SnapshotId, TenantId = item.TenantId }).ToList();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task GenerateSnapshotAsync(long snapshotId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var snapshot = await context.FinanceBusinessReportSnapshots.FirstOrDefaultAsync(item => item.Id == snapshotId && item.DeletedAt == null, cancellationToken);
|
||||
if (snapshot is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (snapshot.Status == FinanceBusinessReportStatus.Running
|
||||
&& snapshot.StartedAt.HasValue
|
||||
&& snapshot.StartedAt.Value.AddMinutes(10) > DateTime.UtcNow)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
snapshot.Status = FinanceBusinessReportStatus.Running;
|
||||
snapshot.StartedAt = DateTime.UtcNow;
|
||||
snapshot.LastError = null;
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
await EnsureDefaultCostProfilesAsync(snapshot.TenantId, snapshot.StoreId, cancellationToken);
|
||||
var report = await BuildComputedSnapshotAsync(snapshot.TenantId, snapshot.StoreId, snapshot.PeriodType, snapshot.PeriodStartAt, snapshot.PeriodEndAt, cancellationToken);
|
||||
snapshot.RevenueAmount = report.RevenueAmount;
|
||||
snapshot.OrderCount = report.OrderCount;
|
||||
snapshot.AverageOrderValue = report.AverageOrderValue;
|
||||
snapshot.RefundRate = report.RefundRate;
|
||||
snapshot.CostTotalAmount = report.CostTotalAmount;
|
||||
snapshot.NetProfitAmount = report.NetProfitAmount;
|
||||
snapshot.ProfitRate = report.ProfitRate;
|
||||
snapshot.KpiComparisonJson = JsonSerializer.Serialize(report.Kpis, JsonOptions);
|
||||
snapshot.IncomeBreakdownJson = JsonSerializer.Serialize(report.IncomeBreakdowns, JsonOptions);
|
||||
snapshot.CostBreakdownJson = JsonSerializer.Serialize(report.CostBreakdowns, JsonOptions);
|
||||
snapshot.Status = FinanceBusinessReportStatus.Succeeded;
|
||||
snapshot.FinishedAt = DateTime.UtcNow;
|
||||
snapshot.LastError = null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
snapshot.Status = FinanceBusinessReportStatus.Failed;
|
||||
snapshot.FinishedAt = DateTime.UtcNow;
|
||||
snapshot.RetryCount += 1;
|
||||
snapshot.LastError = ex.Message[..Math.Min(1024, ex.Message.Length)];
|
||||
}
|
||||
|
||||
await context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<FinanceBusinessReportPendingSnapshot>> QueryPendingAsync(int take, CancellationToken cancellationToken)
|
||||
{
|
||||
return await context.FinanceBusinessReportSnapshots
|
||||
.AsNoTracking()
|
||||
.Where(item =>
|
||||
item.DeletedAt == null &&
|
||||
(item.Status == FinanceBusinessReportStatus.Queued
|
||||
|| (item.Status == FinanceBusinessReportStatus.Failed && item.RetryCount < 3)))
|
||||
.OrderBy(item => item.CreatedAt)
|
||||
.ThenBy(item => item.Id)
|
||||
.Take(take)
|
||||
.Select(item => new FinanceBusinessReportPendingSnapshot
|
||||
{
|
||||
SnapshotId = item.Id,
|
||||
TenantId = item.TenantId
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private async Task<ComputedReportSnapshot> BuildComputedSnapshotAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
FinanceBusinessReportPeriodType periodType,
|
||||
DateTime startAt,
|
||||
DateTime endAt,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var current = await BuildRawMetricsAsync(tenantId, storeId, startAt, endAt, cancellationToken);
|
||||
var previous = ResolvePreviousPeriod(periodType, startAt, endAt);
|
||||
var yearAgo = (startAt.AddYears(-1), endAt.AddYears(-1));
|
||||
var mom = await BuildRawMetricsAsync(tenantId, storeId, previous.StartAt, previous.EndAt, cancellationToken);
|
||||
var yoy = await BuildRawMetricsAsync(tenantId, storeId, yearAgo.Item1, yearAgo.Item2, cancellationToken);
|
||||
|
||||
return current with
|
||||
{
|
||||
Kpis = BuildKpis(current, mom, yoy)
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<ComputedReportSnapshot> BuildRawMetricsAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime startAt,
|
||||
DateTime endAt,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var summary = await QueryRevenueSummaryAsync(tenantId, storeId, startAt, endAt, cancellationToken);
|
||||
var averageOrderValue = summary.OrderCount <= 0 ? 0m : RoundMoney(summary.RevenueAmount / summary.OrderCount);
|
||||
var refundRate = summary.OrderCount <= 0 ? 0m : RoundRatio((decimal)summary.RefundOrderCount / summary.OrderCount);
|
||||
var incomeBreakdowns = await QueryIncomeBreakdownsAsync(tenantId, storeId, startAt, endAt, summary.RevenueAmount, cancellationToken);
|
||||
var dailyRevenueMap = await QueryDailyRevenueMapAsync(tenantId, storeId, startAt, endAt, cancellationToken);
|
||||
var costBreakdowns = await BuildCostBreakdownsAsync(tenantId, storeId, startAt, endAt, dailyRevenueMap, cancellationToken);
|
||||
var costTotalAmount = RoundMoney(costBreakdowns.Sum(item => item.Amount));
|
||||
var netProfitAmount = RoundMoney(summary.RevenueAmount - costTotalAmount);
|
||||
var profitRate = summary.RevenueAmount <= 0 ? 0m : RoundRatio(netProfitAmount / summary.RevenueAmount);
|
||||
|
||||
return new ComputedReportSnapshot
|
||||
{
|
||||
RevenueAmount = summary.RevenueAmount,
|
||||
OrderCount = summary.OrderCount,
|
||||
AverageOrderValue = averageOrderValue,
|
||||
RefundRate = refundRate,
|
||||
CostTotalAmount = costTotalAmount,
|
||||
NetProfitAmount = netProfitAmount,
|
||||
ProfitRate = profitRate,
|
||||
Kpis = [],
|
||||
IncomeBreakdowns = incomeBreakdowns,
|
||||
CostBreakdowns = costBreakdowns
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<(decimal RevenueAmount, int OrderCount, int RefundOrderCount)> QueryRevenueSummaryAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime startAt,
|
||||
DateTime endAt,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var paidBaseQuery =
|
||||
from payment in context.PaymentRecords.AsNoTracking()
|
||||
join order in context.Orders.AsNoTracking()
|
||||
on payment.OrderId equals order.Id
|
||||
where payment.TenantId == tenantId
|
||||
&& order.TenantId == tenantId
|
||||
&& order.StoreId == storeId
|
||||
&& payment.Status == PaymentStatus.Paid
|
||||
&& (payment.PaidAt ?? payment.CreatedAt) >= startAt
|
||||
&& (payment.PaidAt ?? payment.CreatedAt) < endAt
|
||||
select new { payment.Amount, payment.OrderId };
|
||||
|
||||
var paidAmount = await paidBaseQuery.Select(item => item.Amount).DefaultIfEmpty(0m).SumAsync(cancellationToken);
|
||||
var orderCount = await paidBaseQuery.Select(item => item.OrderId).Distinct().CountAsync(cancellationToken);
|
||||
|
||||
var refundBaseQuery =
|
||||
from refund in context.PaymentRefundRecords.AsNoTracking()
|
||||
join order in context.Orders.AsNoTracking()
|
||||
on refund.OrderId equals order.Id
|
||||
where refund.TenantId == tenantId
|
||||
&& order.TenantId == tenantId
|
||||
&& order.StoreId == storeId
|
||||
&& refund.Status == PaymentRefundStatus.Succeeded
|
||||
&& (refund.CompletedAt ?? refund.RequestedAt) >= startAt
|
||||
&& (refund.CompletedAt ?? refund.RequestedAt) < endAt
|
||||
select new { refund.Amount, refund.OrderId };
|
||||
|
||||
var refundAmount = await refundBaseQuery.Select(item => item.Amount).DefaultIfEmpty(0m).SumAsync(cancellationToken);
|
||||
var refundOrderCount = await refundBaseQuery.Select(item => item.OrderId).Distinct().CountAsync(cancellationToken);
|
||||
return (RoundMoney(paidAmount - refundAmount), orderCount, refundOrderCount);
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyDictionary<DateTime, decimal>> QueryDailyRevenueMapAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime startAt,
|
||||
DateTime endAt,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var paidRows = await (
|
||||
from payment in context.PaymentRecords.AsNoTracking()
|
||||
join order in context.Orders.AsNoTracking()
|
||||
on payment.OrderId equals order.Id
|
||||
where payment.TenantId == tenantId
|
||||
&& order.TenantId == tenantId
|
||||
&& order.StoreId == storeId
|
||||
&& payment.Status == PaymentStatus.Paid
|
||||
&& (payment.PaidAt ?? payment.CreatedAt) >= startAt
|
||||
&& (payment.PaidAt ?? payment.CreatedAt) < endAt
|
||||
group payment by (payment.PaidAt ?? payment.CreatedAt).Date into grouped
|
||||
select new { BusinessDate = grouped.Key, Amount = grouped.Sum(item => item.Amount) })
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var refundRows = await (
|
||||
from refund in context.PaymentRefundRecords.AsNoTracking()
|
||||
join order in context.Orders.AsNoTracking()
|
||||
on refund.OrderId equals order.Id
|
||||
where refund.TenantId == tenantId
|
||||
&& order.TenantId == tenantId
|
||||
&& order.StoreId == storeId
|
||||
&& refund.Status == PaymentRefundStatus.Succeeded
|
||||
&& (refund.CompletedAt ?? refund.RequestedAt) >= startAt
|
||||
&& (refund.CompletedAt ?? refund.RequestedAt) < endAt
|
||||
group refund by (refund.CompletedAt ?? refund.RequestedAt).Date into grouped
|
||||
select new { BusinessDate = grouped.Key, Amount = grouped.Sum(item => item.Amount) })
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var map = new Dictionary<DateTime, decimal>();
|
||||
foreach (var row in paidRows)
|
||||
{
|
||||
var date = ToUtcDate(row.BusinessDate);
|
||||
map[date] = map.GetValueOrDefault(date, 0m) + row.Amount;
|
||||
}
|
||||
|
||||
foreach (var row in refundRows)
|
||||
{
|
||||
var date = ToUtcDate(row.BusinessDate);
|
||||
map[date] = map.GetValueOrDefault(date, 0m) - row.Amount;
|
||||
}
|
||||
|
||||
return map.ToDictionary(item => item.Key, item => RoundMoney(item.Value));
|
||||
}
|
||||
|
||||
private async Task<List<FinanceBusinessReportBreakdownSnapshot>> QueryIncomeBreakdownsAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime startAt,
|
||||
DateTime endAt,
|
||||
decimal totalRevenue,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var paidRows = await (
|
||||
from payment in context.PaymentRecords.AsNoTracking()
|
||||
join order in context.Orders.AsNoTracking()
|
||||
on payment.OrderId equals order.Id
|
||||
where payment.TenantId == tenantId
|
||||
&& order.TenantId == tenantId
|
||||
&& order.StoreId == storeId
|
||||
&& payment.Status == PaymentStatus.Paid
|
||||
&& (payment.PaidAt ?? payment.CreatedAt) >= startAt
|
||||
&& (payment.PaidAt ?? payment.CreatedAt) < endAt
|
||||
group payment by order.DeliveryType into grouped
|
||||
select new { DeliveryType = grouped.Key, Amount = grouped.Sum(item => item.Amount) })
|
||||
.ToListAsync(cancellationToken);
|
||||
var refundRows = await (
|
||||
from refund in context.PaymentRefundRecords.AsNoTracking()
|
||||
join order in context.Orders.AsNoTracking()
|
||||
on refund.OrderId equals order.Id
|
||||
where refund.TenantId == tenantId
|
||||
&& order.TenantId == tenantId
|
||||
&& order.StoreId == storeId
|
||||
&& refund.Status == PaymentRefundStatus.Succeeded
|
||||
&& (refund.CompletedAt ?? refund.RequestedAt) >= startAt
|
||||
&& (refund.CompletedAt ?? refund.RequestedAt) < endAt
|
||||
group refund by order.DeliveryType into grouped
|
||||
select new { DeliveryType = grouped.Key, Amount = grouped.Sum(item => item.Amount) })
|
||||
.ToListAsync(cancellationToken);
|
||||
var paidMap = paidRows.ToDictionary(item => item.DeliveryType, item => item.Amount);
|
||||
var refundMap = refundRows.ToDictionary(item => item.DeliveryType, item => item.Amount);
|
||||
|
||||
return IncomeChannelOrder.Select(channel =>
|
||||
{
|
||||
var amount = paidMap.GetValueOrDefault(channel, 0m) - refundMap.GetValueOrDefault(channel, 0m);
|
||||
return new FinanceBusinessReportBreakdownSnapshot
|
||||
{
|
||||
Key = channel switch
|
||||
{
|
||||
DeliveryType.Delivery => "delivery",
|
||||
DeliveryType.Pickup => "pickup",
|
||||
DeliveryType.DineIn => "dine_in",
|
||||
_ => "delivery"
|
||||
},
|
||||
Label = channel switch
|
||||
{
|
||||
DeliveryType.Delivery => "外卖",
|
||||
DeliveryType.Pickup => "自提",
|
||||
DeliveryType.DineIn => "堂食",
|
||||
_ => "外卖"
|
||||
},
|
||||
Amount = RoundMoney(amount),
|
||||
Ratio = totalRevenue <= 0 ? 0m : RoundRatio(amount / totalRevenue)
|
||||
};
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
private async Task<List<FinanceBusinessReportBreakdownSnapshot>> BuildCostBreakdownsAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime startAt,
|
||||
DateTime endAt,
|
||||
IReadOnlyDictionary<DateTime, decimal> dailyRevenueMap,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var profiles = await context.FinanceCostProfiles.AsNoTracking()
|
||||
.Where(item => item.TenantId == tenantId && item.StoreId == storeId && item.DeletedAt == null && item.IsEnabled)
|
||||
.OrderBy(item => item.SortOrder).ThenByDescending(item => item.EffectiveFrom).ToListAsync(cancellationToken);
|
||||
var overrides = await context.FinanceCostDailyOverrides.AsNoTracking()
|
||||
.Where(item => item.TenantId == tenantId && item.StoreId == storeId && item.DeletedAt == null && item.BusinessDate >= startAt.Date && item.BusinessDate < endAt.Date)
|
||||
.ToListAsync(cancellationToken);
|
||||
var overrideMap = overrides.ToDictionary(item => $"{item.BusinessDate:yyyyMMdd}:{(int)item.Category}", item => item.Amount);
|
||||
var categoryAmountMap = CostCategoryOrder.ToDictionary(item => item, _ => 0m);
|
||||
|
||||
for (var businessDay = startAt.Date; businessDay < endAt.Date; businessDay = businessDay.AddDays(1))
|
||||
{
|
||||
var dayRevenue = dailyRevenueMap.GetValueOrDefault(ToUtcDate(businessDay), 0m);
|
||||
foreach (var category in CostCategoryOrder)
|
||||
{
|
||||
var key = $"{businessDay:yyyyMMdd}:{(int)category}";
|
||||
decimal amount;
|
||||
if (overrideMap.TryGetValue(key, out var overrideAmount))
|
||||
{
|
||||
amount = overrideAmount;
|
||||
}
|
||||
else
|
||||
{
|
||||
var profile = profiles.FirstOrDefault(item =>
|
||||
item.Category == category &&
|
||||
item.EffectiveFrom.Date <= businessDay &&
|
||||
(!item.EffectiveTo.HasValue || item.EffectiveTo.Value.Date >= businessDay));
|
||||
var defaults = DefaultCostProfileMap[category];
|
||||
var mode = profile?.CalcMode ?? defaults.Mode;
|
||||
var ratio = profile?.Ratio ?? defaults.Ratio;
|
||||
var fixedDaily = profile?.FixedDailyAmount ?? defaults.Fixed;
|
||||
amount = mode == FinanceCostCalcMode.FixedDaily ? fixedDaily : dayRevenue * Math.Max(0m, ratio);
|
||||
}
|
||||
|
||||
categoryAmountMap[category] += RoundMoney(amount);
|
||||
}
|
||||
}
|
||||
|
||||
var totalCostAmount = categoryAmountMap.Sum(item => item.Value);
|
||||
return CostCategoryOrder.Select(category => new FinanceBusinessReportBreakdownSnapshot
|
||||
{
|
||||
Key = category switch
|
||||
{
|
||||
FinanceCostCategory.FoodMaterial => "food_material",
|
||||
FinanceCostCategory.Labor => "labor",
|
||||
FinanceCostCategory.FixedExpense => "fixed_expense",
|
||||
FinanceCostCategory.PackagingConsumable => "packaging_consumable",
|
||||
_ => "food_material"
|
||||
},
|
||||
Label = category switch
|
||||
{
|
||||
FinanceCostCategory.FoodMaterial => "食材成本",
|
||||
FinanceCostCategory.Labor => "人工成本",
|
||||
FinanceCostCategory.FixedExpense => "固定成本",
|
||||
FinanceCostCategory.PackagingConsumable => "包装成本",
|
||||
_ => "食材成本"
|
||||
},
|
||||
Amount = RoundMoney(categoryAmountMap[category]),
|
||||
Ratio = totalCostAmount <= 0m ? 0m : RoundRatio(categoryAmountMap[category] / totalCostAmount)
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
private static List<FinanceBusinessReportKpiSnapshot> BuildKpis(ComputedReportSnapshot current, ComputedReportSnapshot mom, ComputedReportSnapshot yoy)
|
||||
{
|
||||
var definitions = new List<(string Key, string Label, decimal Current, decimal PrevMom, decimal PrevYoy)>
|
||||
{
|
||||
("revenue", "营业额", current.RevenueAmount, mom.RevenueAmount, yoy.RevenueAmount),
|
||||
("order_count", "订单数", current.OrderCount, mom.OrderCount, yoy.OrderCount),
|
||||
("average_order_value", "客单价", current.AverageOrderValue, mom.AverageOrderValue, yoy.AverageOrderValue),
|
||||
("refund_rate", "退款率", current.RefundRate, mom.RefundRate, yoy.RefundRate),
|
||||
("net_profit", "净利润", current.NetProfitAmount, mom.NetProfitAmount, yoy.NetProfitAmount),
|
||||
("profit_rate", "利润率", current.ProfitRate, mom.ProfitRate, yoy.ProfitRate)
|
||||
};
|
||||
|
||||
return definitions.Select(item => new FinanceBusinessReportKpiSnapshot
|
||||
{
|
||||
Key = item.Key,
|
||||
Label = item.Label,
|
||||
Value = item.Current,
|
||||
MomChangeRate = CalculateChangeRate(item.Current, item.PrevMom),
|
||||
YoyChangeRate = CalculateChangeRate(item.Current, item.PrevYoy)
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
private static (DateTime StartAt, DateTime EndAt) ResolvePreviousPeriod(FinanceBusinessReportPeriodType periodType, DateTime startAt, DateTime endAt)
|
||||
{
|
||||
return periodType switch
|
||||
{
|
||||
FinanceBusinessReportPeriodType.Daily => (startAt.AddDays(-1), endAt.AddDays(-1)),
|
||||
FinanceBusinessReportPeriodType.Weekly => (startAt.AddDays(-7), endAt.AddDays(-7)),
|
||||
FinanceBusinessReportPeriodType.Monthly => (startAt.AddMonths(-1), endAt.AddMonths(-1)),
|
||||
_ => (startAt.AddDays(-1), endAt.AddDays(-1))
|
||||
};
|
||||
}
|
||||
|
||||
private static List<(DateTime StartAt, DateTime EndAt)> BuildPagedPeriods(FinanceBusinessReportPeriodType periodType, int page, int pageSize, DateTime now)
|
||||
{
|
||||
var normalizedPage = Math.Max(1, page);
|
||||
var normalizedPageSize = Math.Clamp(pageSize, 1, 200);
|
||||
var offsetStart = (normalizedPage - 1) * normalizedPageSize;
|
||||
var today = ToUtcDate(now);
|
||||
var list = new List<(DateTime StartAt, DateTime EndAt)>(normalizedPageSize);
|
||||
for (var index = 0; index < normalizedPageSize; index++)
|
||||
{
|
||||
var offset = offsetStart + index;
|
||||
if (periodType == FinanceBusinessReportPeriodType.Weekly)
|
||||
{
|
||||
var weekStart = GetWeekStart(today).AddDays(-7 * offset);
|
||||
list.Add((weekStart, weekStart.AddDays(7)));
|
||||
}
|
||||
else if (periodType == FinanceBusinessReportPeriodType.Monthly)
|
||||
{
|
||||
var monthStart = new DateTime(today.Year, today.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(-offset);
|
||||
list.Add((monthStart, monthStart.AddMonths(1)));
|
||||
}
|
||||
else
|
||||
{
|
||||
var dayStart = today.AddDays(-offset);
|
||||
list.Add((dayStart, dayStart.AddDays(1)));
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static List<TItem> Deserialize<TItem>(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize<List<TItem>>(json, JsonOptions) ?? [];
|
||||
}
|
||||
catch
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record ComputedReportSnapshot
|
||||
{
|
||||
public decimal RevenueAmount { get; init; }
|
||||
|
||||
public int OrderCount { get; init; }
|
||||
|
||||
public decimal AverageOrderValue { get; init; }
|
||||
|
||||
public decimal RefundRate { get; init; }
|
||||
|
||||
public decimal CostTotalAmount { get; init; }
|
||||
|
||||
public decimal NetProfitAmount { get; init; }
|
||||
|
||||
public decimal ProfitRate { get; init; }
|
||||
|
||||
public List<FinanceBusinessReportKpiSnapshot> Kpis { get; init; } = [];
|
||||
|
||||
public List<FinanceBusinessReportBreakdownSnapshot> IncomeBreakdowns { get; init; } = [];
|
||||
|
||||
public List<FinanceBusinessReportBreakdownSnapshot> CostBreakdowns { get; init; } = [];
|
||||
}
|
||||
|
||||
private static decimal CalculateChangeRate(decimal currentValue, decimal previousValue) => previousValue <= 0m ? (currentValue <= 0m ? 0m : 100m) : RoundRate((currentValue - previousValue) / previousValue * 100m);
|
||||
private static decimal RoundMoney(decimal value) => decimal.Round(value, 2, MidpointRounding.AwayFromZero);
|
||||
private static decimal RoundRate(decimal value) => decimal.Round(value, 2, MidpointRounding.AwayFromZero);
|
||||
private static decimal RoundRatio(decimal value) => decimal.Round(value, 4, MidpointRounding.AwayFromZero);
|
||||
private static DateTime ToUtcDate(DateTime value) => new(value.Year, value.Month, value.Day, 0, 0, 0, DateTimeKind.Utc);
|
||||
private static DateTime GetWeekStart(DateTime date) => date.AddDays(0 - (((int)date.DayOfWeek + 6) % 7));
|
||||
}
|
||||
@@ -171,6 +171,203 @@ public sealed class EfFinanceTransactionRepository(TakeoutAppDbContext context)
|
||||
return rows.Select(MapToRecord).ToList();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceSettlementStatsSnapshot> GetSettlementStatsAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime currentUtc,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var utcNow = NormalizeUtc(currentUtc);
|
||||
var todayStart = new DateTime(utcNow.Year, utcNow.Month, utcNow.Day, 0, 0, 0, DateTimeKind.Utc);
|
||||
var tomorrowStart = todayStart.AddDays(1);
|
||||
var yesterdayStart = todayStart.AddDays(-1);
|
||||
var monthStart = new DateTime(utcNow.Year, utcNow.Month, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
var monthEnd = monthStart.AddMonths(1);
|
||||
|
||||
var query = BuildSettlementPaymentQuery(
|
||||
tenantId,
|
||||
storeId,
|
||||
startAt: null,
|
||||
endAt: null,
|
||||
paymentMethod: null);
|
||||
|
||||
var summary = await query
|
||||
.GroupBy(_ => 1)
|
||||
.Select(group => new
|
||||
{
|
||||
TodayArrivedAmount = group
|
||||
.Where(item => item.PaidAt >= todayStart && item.PaidAt < tomorrowStart)
|
||||
.Sum(item => item.Amount),
|
||||
YesterdayArrivedAmount = group
|
||||
.Where(item => item.PaidAt >= yesterdayStart && item.PaidAt < todayStart)
|
||||
.Sum(item => item.Amount),
|
||||
CurrentMonthArrivedAmount = group
|
||||
.Where(item => item.PaidAt >= monthStart && item.PaidAt < monthEnd)
|
||||
.Sum(item => item.Amount),
|
||||
CurrentMonthTransactionCount = group
|
||||
.Count(item => item.PaidAt >= monthStart && item.PaidAt < monthEnd)
|
||||
})
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (summary is null)
|
||||
{
|
||||
return new FinanceSettlementStatsSnapshot
|
||||
{
|
||||
TodayArrivedAmount = 0,
|
||||
YesterdayArrivedAmount = 0,
|
||||
CurrentMonthArrivedAmount = 0,
|
||||
CurrentMonthTransactionCount = 0
|
||||
};
|
||||
}
|
||||
|
||||
return new FinanceSettlementStatsSnapshot
|
||||
{
|
||||
TodayArrivedAmount = decimal.Round(summary.TodayArrivedAmount, 2, MidpointRounding.AwayFromZero),
|
||||
YesterdayArrivedAmount = decimal.Round(summary.YesterdayArrivedAmount, 2, MidpointRounding.AwayFromZero),
|
||||
CurrentMonthArrivedAmount = decimal.Round(summary.CurrentMonthArrivedAmount, 2, MidpointRounding.AwayFromZero),
|
||||
CurrentMonthTransactionCount = summary.CurrentMonthTransactionCount
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceSettlementAccountSnapshot?> GetSettlementAccountAsync(
|
||||
long tenantId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var profile = await context.TenantVerificationProfiles
|
||||
.AsNoTracking()
|
||||
.Where(item => item.TenantId == tenantId && item.DeletedAt == null)
|
||||
.Select(item => new
|
||||
{
|
||||
item.BankName,
|
||||
item.BankAccountName,
|
||||
item.BankAccountNumber,
|
||||
item.WeChatMerchantNo,
|
||||
item.AlipayPid
|
||||
})
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (profile is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new FinanceSettlementAccountSnapshot
|
||||
{
|
||||
BankName = (profile.BankName ?? string.Empty).Trim(),
|
||||
BankAccountName = (profile.BankAccountName ?? string.Empty).Trim(),
|
||||
BankAccountNoMasked = MaskBankAccountNo(profile.BankAccountNumber),
|
||||
WechatMerchantNoMasked = MaskWechatMerchantNo(profile.WeChatMerchantNo),
|
||||
AlipayPidMasked = MaskAlipayPid(profile.AlipayPid),
|
||||
SettlementPeriodText = "T+1 自动到账"
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<FinanceSettlementPageSnapshot> SearchSettlementPageAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime? startAt,
|
||||
DateTime? endAt,
|
||||
PaymentMethod? paymentMethod,
|
||||
int page,
|
||||
int pageSize,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var normalizedPage = Math.Max(1, page);
|
||||
var normalizedPageSize = Math.Clamp(pageSize, 1, 200);
|
||||
|
||||
var groupedQuery = BuildSettlementPaymentQuery(tenantId, storeId, startAt, endAt, paymentMethod)
|
||||
.GroupBy(item => new { ArrivedDate = item.PaidAt.Date, item.PaymentMethod })
|
||||
.Select(group => new FinanceSettlementListItemSnapshot
|
||||
{
|
||||
ArrivedDate = DateTime.SpecifyKind(group.Key.ArrivedDate, DateTimeKind.Utc),
|
||||
PaymentMethod = group.Key.PaymentMethod,
|
||||
TransactionCount = group.Count(),
|
||||
ArrivedAmount = decimal.Round(group.Sum(item => item.Amount), 2, MidpointRounding.AwayFromZero)
|
||||
});
|
||||
|
||||
var totalCount = await groupedQuery.CountAsync(cancellationToken);
|
||||
if (totalCount == 0)
|
||||
{
|
||||
return new FinanceSettlementPageSnapshot
|
||||
{
|
||||
Items = [],
|
||||
TotalCount = 0
|
||||
};
|
||||
}
|
||||
|
||||
var items = await groupedQuery
|
||||
.OrderByDescending(item => item.ArrivedDate)
|
||||
.ThenBy(item => item.PaymentMethod)
|
||||
.Skip((normalizedPage - 1) * normalizedPageSize)
|
||||
.Take(normalizedPageSize)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return new FinanceSettlementPageSnapshot
|
||||
{
|
||||
Items = items,
|
||||
TotalCount = totalCount
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<FinanceSettlementDetailItemSnapshot>> GetSettlementDetailsAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime arrivedDate,
|
||||
PaymentMethod paymentMethod,
|
||||
int take,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var arrivedDay = NormalizeUtc(arrivedDate);
|
||||
var dayStart = new DateTime(arrivedDay.Year, arrivedDay.Month, arrivedDay.Day, 0, 0, 0, DateTimeKind.Utc);
|
||||
var dayEnd = dayStart.AddDays(1);
|
||||
var normalizedTake = Math.Clamp(take, 1, 200);
|
||||
|
||||
return await BuildSettlementPaymentQuery(
|
||||
tenantId,
|
||||
storeId,
|
||||
dayStart,
|
||||
dayEnd,
|
||||
paymentMethod)
|
||||
.OrderByDescending(item => item.PaidAt)
|
||||
.ThenByDescending(item => item.PaymentRecordId)
|
||||
.Select(item => new FinanceSettlementDetailItemSnapshot
|
||||
{
|
||||
OrderNo = item.OrderNo,
|
||||
Amount = decimal.Round(item.Amount, 2, MidpointRounding.AwayFromZero),
|
||||
PaidAt = item.PaidAt
|
||||
})
|
||||
.Take(normalizedTake)
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<FinanceSettlementListItemSnapshot>> ListSettlementForExportAsync(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime? startAt,
|
||||
DateTime? endAt,
|
||||
PaymentMethod? paymentMethod,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return await BuildSettlementPaymentQuery(tenantId, storeId, startAt, endAt, paymentMethod)
|
||||
.GroupBy(item => new { ArrivedDate = item.PaidAt.Date, item.PaymentMethod })
|
||||
.Select(group => new FinanceSettlementListItemSnapshot
|
||||
{
|
||||
ArrivedDate = DateTime.SpecifyKind(group.Key.ArrivedDate, DateTimeKind.Utc),
|
||||
PaymentMethod = group.Key.PaymentMethod,
|
||||
TransactionCount = group.Count(),
|
||||
ArrivedAmount = decimal.Round(group.Sum(item => item.Amount), 2, MidpointRounding.AwayFromZero)
|
||||
})
|
||||
.OrderByDescending(item => item.ArrivedDate)
|
||||
.ThenBy(item => item.PaymentMethod)
|
||||
.Take(20_000)
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private IQueryable<TransactionProjection> BuildQuery(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
@@ -385,6 +582,50 @@ public sealed class EfFinanceTransactionRepository(TakeoutAppDbContext context)
|
||||
return query;
|
||||
}
|
||||
|
||||
private IQueryable<SettlementPaymentProjection> BuildSettlementPaymentQuery(
|
||||
long tenantId,
|
||||
long storeId,
|
||||
DateTime? startAt,
|
||||
DateTime? endAt,
|
||||
PaymentMethod? paymentMethod)
|
||||
{
|
||||
var query =
|
||||
from payment in context.PaymentRecords.AsNoTracking()
|
||||
join order in context.Orders.AsNoTracking()
|
||||
on payment.OrderId equals order.Id
|
||||
where payment.TenantId == tenantId
|
||||
&& order.TenantId == tenantId
|
||||
&& order.StoreId == storeId
|
||||
&& payment.Status == PaymentStatus.Paid
|
||||
&& payment.PaidAt.HasValue
|
||||
&& (payment.Method == PaymentMethod.WeChatPay || payment.Method == PaymentMethod.Alipay)
|
||||
select new SettlementPaymentProjection
|
||||
{
|
||||
PaymentRecordId = payment.Id,
|
||||
OrderNo = order.OrderNo,
|
||||
PaymentMethod = payment.Method,
|
||||
Amount = payment.Amount,
|
||||
PaidAt = payment.PaidAt!.Value
|
||||
};
|
||||
|
||||
if (startAt.HasValue)
|
||||
{
|
||||
query = query.Where(item => item.PaidAt >= startAt.Value);
|
||||
}
|
||||
|
||||
if (endAt.HasValue)
|
||||
{
|
||||
query = query.Where(item => item.PaidAt < endAt.Value);
|
||||
}
|
||||
|
||||
if (paymentMethod.HasValue)
|
||||
{
|
||||
query = query.Where(item => item.PaymentMethod == paymentMethod.Value);
|
||||
}
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
private static FinanceTransactionRecord MapToRecord(TransactionProjection source)
|
||||
{
|
||||
return new FinanceTransactionRecord
|
||||
@@ -503,4 +744,60 @@ public sealed class EfFinanceTransactionRepository(TakeoutAppDbContext context)
|
||||
|
||||
public int? PointBalanceAfterChange { get; init; }
|
||||
}
|
||||
|
||||
private sealed class SettlementPaymentProjection
|
||||
{
|
||||
public required long PaymentRecordId { get; init; }
|
||||
|
||||
public required string OrderNo { get; init; }
|
||||
|
||||
public required PaymentMethod PaymentMethod { get; init; }
|
||||
|
||||
public required decimal Amount { get; init; }
|
||||
|
||||
public required DateTime PaidAt { get; init; }
|
||||
}
|
||||
|
||||
private static DateTime NormalizeUtc(DateTime value)
|
||||
{
|
||||
return value.Kind switch
|
||||
{
|
||||
DateTimeKind.Utc => value,
|
||||
DateTimeKind.Local => value.ToUniversalTime(),
|
||||
_ => DateTime.SpecifyKind(value, DateTimeKind.Utc)
|
||||
};
|
||||
}
|
||||
|
||||
private static string MaskBankAccountNo(string? value)
|
||||
{
|
||||
var digits = new string((value ?? string.Empty).Where(char.IsDigit).ToArray());
|
||||
if (digits.Length >= 4)
|
||||
{
|
||||
return $"****{digits[^4..]}";
|
||||
}
|
||||
|
||||
return digits;
|
||||
}
|
||||
|
||||
private static string MaskWechatMerchantNo(string? value)
|
||||
{
|
||||
var normalized = (value ?? string.Empty).Trim();
|
||||
if (normalized.Length >= 4)
|
||||
{
|
||||
return $"{normalized[..2]}{new string('x', normalized.Length - 2)}";
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private static string MaskAlipayPid(string? value)
|
||||
{
|
||||
var normalized = (value ?? string.Empty).Trim();
|
||||
if (normalized.Length > 6)
|
||||
{
|
||||
return $"{normalized[..4]}{new string('x', normalized.Length - 4)}";
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using TakeoutSaaS.Domain.Tenants.Entities;
|
||||
using TakeoutSaaS.Domain.Tenants.Enums;
|
||||
using TakeoutSaaS.Domain.Tenants.Repositories;
|
||||
using TakeoutSaaS.Infrastructure.App.Persistence;
|
||||
|
||||
namespace TakeoutSaaS.Infrastructure.App.Repositories;
|
||||
|
||||
/// <summary>
|
||||
/// 租户发票仓储 EF Core 实现。
|
||||
/// </summary>
|
||||
public sealed class EfTenantInvoiceRepository(TakeoutAppDbContext context) : ITenantInvoiceRepository
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public Task<TenantInvoiceSetting?> GetSettingAsync(long tenantId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return context.TenantInvoiceSettings
|
||||
.Where(item => item.TenantId == tenantId)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task AddSettingAsync(TenantInvoiceSetting entity, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return context.TenantInvoiceSettings.AddAsync(entity, cancellationToken).AsTask();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task UpdateSettingAsync(TenantInvoiceSetting entity, CancellationToken cancellationToken = default)
|
||||
{
|
||||
context.TenantInvoiceSettings.Update(entity);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<(IReadOnlyList<TenantInvoiceRecord> Items, int TotalCount)> SearchRecordsAsync(
|
||||
long tenantId,
|
||||
DateTime? startUtc,
|
||||
DateTime? endUtc,
|
||||
TenantInvoiceStatus? status,
|
||||
TenantInvoiceType? invoiceType,
|
||||
string? keyword,
|
||||
int page,
|
||||
int pageSize,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var normalizedPage = Math.Max(1, page);
|
||||
var normalizedPageSize = Math.Clamp(pageSize, 1, 500);
|
||||
|
||||
var query = BuildRecordQuery(tenantId, startUtc, endUtc, status, invoiceType, keyword);
|
||||
|
||||
var totalCount = await query.CountAsync(cancellationToken);
|
||||
if (totalCount == 0)
|
||||
{
|
||||
return ([], 0);
|
||||
}
|
||||
|
||||
var items = await query
|
||||
.OrderByDescending(item => item.AppliedAt)
|
||||
.ThenByDescending(item => item.Id)
|
||||
.Skip((normalizedPage - 1) * normalizedPageSize)
|
||||
.Take(normalizedPageSize)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return (items, totalCount);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<TenantInvoiceRecordStatsSnapshot> GetStatsAsync(
|
||||
long tenantId,
|
||||
DateTime nowUtc,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var utcNow = NormalizeUtc(nowUtc);
|
||||
var monthStart = new DateTime(utcNow.Year, utcNow.Month, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
var summary = await context.TenantInvoiceRecords
|
||||
.AsNoTracking()
|
||||
.Where(item => item.TenantId == tenantId)
|
||||
.GroupBy(_ => 1)
|
||||
.Select(group => new
|
||||
{
|
||||
CurrentMonthIssuedAmount = group
|
||||
.Where(item =>
|
||||
item.Status == TenantInvoiceStatus.Issued &&
|
||||
item.IssuedAt.HasValue &&
|
||||
item.IssuedAt.Value >= monthStart &&
|
||||
item.IssuedAt.Value <= utcNow)
|
||||
.Sum(item => item.Amount),
|
||||
CurrentMonthIssuedCount = group
|
||||
.Count(item =>
|
||||
item.Status == TenantInvoiceStatus.Issued &&
|
||||
item.IssuedAt.HasValue &&
|
||||
item.IssuedAt.Value >= monthStart &&
|
||||
item.IssuedAt.Value <= utcNow),
|
||||
PendingCount = group.Count(item => item.Status == TenantInvoiceStatus.Pending),
|
||||
VoidedCount = group.Count(item => item.Status == TenantInvoiceStatus.Voided)
|
||||
})
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
if (summary is null)
|
||||
{
|
||||
return new TenantInvoiceRecordStatsSnapshot();
|
||||
}
|
||||
|
||||
return new TenantInvoiceRecordStatsSnapshot
|
||||
{
|
||||
CurrentMonthIssuedAmount = summary.CurrentMonthIssuedAmount,
|
||||
CurrentMonthIssuedCount = summary.CurrentMonthIssuedCount,
|
||||
PendingCount = summary.PendingCount,
|
||||
VoidedCount = summary.VoidedCount
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<TenantInvoiceRecord?> FindRecordByIdAsync(
|
||||
long tenantId,
|
||||
long recordId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return context.TenantInvoiceRecords
|
||||
.Where(item => item.TenantId == tenantId && item.Id == recordId)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<bool> ExistsInvoiceNoAsync(
|
||||
long tenantId,
|
||||
string invoiceNo,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return context.TenantInvoiceRecords
|
||||
.AsNoTracking()
|
||||
.AnyAsync(
|
||||
item => item.TenantId == tenantId && item.InvoiceNo == invoiceNo,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task AddRecordAsync(TenantInvoiceRecord entity, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return context.TenantInvoiceRecords.AddAsync(entity, cancellationToken).AsTask();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task UpdateRecordAsync(TenantInvoiceRecord entity, CancellationToken cancellationToken = default)
|
||||
{
|
||||
context.TenantInvoiceRecords.Update(entity);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task SaveChangesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
return context.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private IQueryable<TenantInvoiceRecord> BuildRecordQuery(
|
||||
long tenantId,
|
||||
DateTime? startUtc,
|
||||
DateTime? endUtc,
|
||||
TenantInvoiceStatus? status,
|
||||
TenantInvoiceType? invoiceType,
|
||||
string? keyword)
|
||||
{
|
||||
var query = context.TenantInvoiceRecords
|
||||
.AsNoTracking()
|
||||
.Where(item => item.TenantId == tenantId);
|
||||
|
||||
if (startUtc.HasValue)
|
||||
{
|
||||
var normalizedStart = NormalizeUtc(startUtc.Value);
|
||||
query = query.Where(item => item.AppliedAt >= normalizedStart);
|
||||
}
|
||||
|
||||
if (endUtc.HasValue)
|
||||
{
|
||||
var normalizedEnd = NormalizeUtc(endUtc.Value);
|
||||
query = query.Where(item => item.AppliedAt <= normalizedEnd);
|
||||
}
|
||||
|
||||
if (status.HasValue)
|
||||
{
|
||||
query = query.Where(item => item.Status == status.Value);
|
||||
}
|
||||
|
||||
if (invoiceType.HasValue)
|
||||
{
|
||||
query = query.Where(item => item.InvoiceType == invoiceType.Value);
|
||||
}
|
||||
|
||||
var normalizedKeyword = (keyword ?? string.Empty).Trim();
|
||||
if (!string.IsNullOrWhiteSpace(normalizedKeyword))
|
||||
{
|
||||
var like = $"%{normalizedKeyword}%";
|
||||
query = query.Where(item =>
|
||||
EF.Functions.ILike(item.InvoiceNo, like) ||
|
||||
EF.Functions.ILike(item.CompanyName, like) ||
|
||||
EF.Functions.ILike(item.ApplicantName, like) ||
|
||||
EF.Functions.ILike(item.OrderNo, like));
|
||||
}
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
private static DateTime NormalizeUtc(DateTime value)
|
||||
{
|
||||
return value.Kind switch
|
||||
{
|
||||
DateTimeKind.Utc => value,
|
||||
DateTimeKind.Local => value.ToUniversalTime(),
|
||||
_ => DateTime.SpecifyKind(value, DateTimeKind.Utc)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
using ClosedXML.Excel;
|
||||
using QuestPDF.Fluent;
|
||||
using QuestPDF.Helpers;
|
||||
using QuestPDF.Infrastructure;
|
||||
using System.Globalization;
|
||||
using TakeoutSaaS.Domain.Finance.Enums;
|
||||
using TakeoutSaaS.Domain.Finance.Models;
|
||||
using TakeoutSaaS.Domain.Finance.Services;
|
||||
|
||||
namespace TakeoutSaaS.Infrastructure.App.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表导出服务实现(PDF / Excel)。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportExportService : IFinanceBusinessReportExportService
|
||||
{
|
||||
public FinanceBusinessReportExportService()
|
||||
{
|
||||
QuestPDF.Settings.License = LicenseType.Community;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<byte[]> ExportSinglePdfAsync(
|
||||
FinanceBusinessReportDetailSnapshot detail,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(detail);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return Task.FromResult(BuildPdf([detail]));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<byte[]> ExportSingleExcelAsync(
|
||||
FinanceBusinessReportDetailSnapshot detail,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(detail);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
using var workbook = new XLWorkbook();
|
||||
var worksheet = workbook.Worksheets.Add("经营报表");
|
||||
WriteDetailWorksheet(worksheet, detail);
|
||||
|
||||
using var stream = new MemoryStream();
|
||||
workbook.SaveAs(stream);
|
||||
return Task.FromResult(stream.ToArray());
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<byte[]> ExportBatchPdfAsync(
|
||||
IReadOnlyList<FinanceBusinessReportDetailSnapshot> details,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(details);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return Task.FromResult(BuildPdf(details));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<byte[]> ExportBatchExcelAsync(
|
||||
IReadOnlyList<FinanceBusinessReportDetailSnapshot> details,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(details);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
using var workbook = new XLWorkbook();
|
||||
var summary = workbook.Worksheets.Add("汇总");
|
||||
WriteSummaryWorksheet(summary, details);
|
||||
|
||||
for (var index = 0; index < details.Count; index++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var detail = details[index];
|
||||
var sheetName = $"报表{index + 1:D2}";
|
||||
var worksheet = workbook.Worksheets.Add(sheetName);
|
||||
WriteDetailWorksheet(worksheet, detail);
|
||||
}
|
||||
|
||||
using var stream = new MemoryStream();
|
||||
workbook.SaveAs(stream);
|
||||
return Task.FromResult(stream.ToArray());
|
||||
}
|
||||
|
||||
private static byte[] BuildPdf(IReadOnlyList<FinanceBusinessReportDetailSnapshot> details)
|
||||
{
|
||||
var source = details.Count == 0
|
||||
? [new FinanceBusinessReportDetailSnapshot()]
|
||||
: details;
|
||||
|
||||
var document = Document.Create(container =>
|
||||
{
|
||||
foreach (var detail in source)
|
||||
{
|
||||
container.Page(page =>
|
||||
{
|
||||
page.Size(PageSizes.A4);
|
||||
page.Margin(24);
|
||||
page.DefaultTextStyle(x => x.FontSize(10));
|
||||
|
||||
page.Content().Column(column =>
|
||||
{
|
||||
column.Spacing(8);
|
||||
column.Item().Text(BuildTitle(detail)).FontSize(16).SemiBold();
|
||||
column.Item().Text($"状态:{ResolveStatusText(detail.Status)}");
|
||||
|
||||
column.Item().Element(section => BuildKpiSection(section, detail.Kpis));
|
||||
column.Item().Element(section => BuildBreakdownSection(section, "收入明细(按渠道)", detail.IncomeBreakdowns));
|
||||
column.Item().Element(section => BuildBreakdownSection(section, "成本明细(按类别)", detail.CostBreakdowns));
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return document.GeneratePdf();
|
||||
}
|
||||
|
||||
private static void BuildKpiSection(IContainer container, IReadOnlyList<FinanceBusinessReportKpiSnapshot> kpis)
|
||||
{
|
||||
container.Border(1).BorderColor(Colors.Grey.Lighten2).Padding(10).Column(column =>
|
||||
{
|
||||
column.Spacing(4);
|
||||
column.Item().Text("关键指标").SemiBold();
|
||||
|
||||
if (kpis.Count == 0)
|
||||
{
|
||||
column.Item().Text("暂无数据");
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var item in kpis)
|
||||
{
|
||||
column.Item().Row(row =>
|
||||
{
|
||||
row.RelativeItem().Text(item.Label);
|
||||
row.RelativeItem().AlignRight().Text(FormatKpiValue(item.Key, item.Value));
|
||||
row.RelativeItem().AlignRight().Text(
|
||||
$"同比 {FormatSignedRate(item.YoyChangeRate)} | 环比 {FormatSignedRate(item.MomChangeRate)}");
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void BuildBreakdownSection(
|
||||
IContainer container,
|
||||
string title,
|
||||
IReadOnlyList<FinanceBusinessReportBreakdownSnapshot> rows)
|
||||
{
|
||||
container.Border(1).BorderColor(Colors.Grey.Lighten2).Padding(10).Column(column =>
|
||||
{
|
||||
column.Spacing(4);
|
||||
column.Item().Text(title).SemiBold();
|
||||
|
||||
if (rows.Count == 0)
|
||||
{
|
||||
column.Item().Text("暂无数据");
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var item in rows)
|
||||
{
|
||||
column.Item().Row(row =>
|
||||
{
|
||||
row.RelativeItem().Text(item.Label);
|
||||
row.ConstantItem(80).AlignRight().Text(FormatPercent(item.Ratio));
|
||||
row.ConstantItem(120).AlignRight().Text(FormatCurrency(item.Amount));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void WriteSummaryWorksheet(
|
||||
IXLWorksheet worksheet,
|
||||
IReadOnlyList<FinanceBusinessReportDetailSnapshot> details)
|
||||
{
|
||||
worksheet.Cell(1, 1).Value = "报表标题";
|
||||
worksheet.Cell(1, 2).Value = "状态";
|
||||
worksheet.Cell(1, 3).Value = "营业额";
|
||||
worksheet.Cell(1, 4).Value = "订单数";
|
||||
worksheet.Cell(1, 5).Value = "客单价";
|
||||
worksheet.Cell(1, 6).Value = "退款率";
|
||||
worksheet.Cell(1, 7).Value = "成本总额";
|
||||
worksheet.Cell(1, 8).Value = "净利润";
|
||||
worksheet.Cell(1, 9).Value = "利润率";
|
||||
|
||||
for (var index = 0; index < details.Count; index++)
|
||||
{
|
||||
var row = index + 2;
|
||||
var detail = details[index];
|
||||
worksheet.Cell(row, 1).Value = BuildTitle(detail);
|
||||
worksheet.Cell(row, 2).Value = ResolveStatusText(detail.Status);
|
||||
worksheet.Cell(row, 3).Value = detail.RevenueAmount;
|
||||
worksheet.Cell(row, 4).Value = detail.OrderCount;
|
||||
worksheet.Cell(row, 5).Value = detail.AverageOrderValue;
|
||||
worksheet.Cell(row, 6).Value = detail.RefundRate;
|
||||
worksheet.Cell(row, 7).Value = detail.CostTotalAmount;
|
||||
worksheet.Cell(row, 8).Value = detail.NetProfitAmount;
|
||||
worksheet.Cell(row, 9).Value = detail.ProfitRate;
|
||||
}
|
||||
|
||||
worksheet.Columns().AdjustToContents();
|
||||
}
|
||||
|
||||
private static void WriteDetailWorksheet(
|
||||
IXLWorksheet worksheet,
|
||||
FinanceBusinessReportDetailSnapshot detail)
|
||||
{
|
||||
var row = 1;
|
||||
|
||||
worksheet.Cell(row, 1).Value = BuildTitle(detail);
|
||||
worksheet.Range(row, 1, row, 4).Merge().Style.Font.SetBold();
|
||||
row += 2;
|
||||
|
||||
worksheet.Cell(row, 1).Value = "关键指标";
|
||||
worksheet.Cell(row, 1).Style.Font.SetBold();
|
||||
row += 1;
|
||||
|
||||
worksheet.Cell(row, 1).Value = "指标";
|
||||
worksheet.Cell(row, 2).Value = "值";
|
||||
worksheet.Cell(row, 3).Value = "同比";
|
||||
worksheet.Cell(row, 4).Value = "环比";
|
||||
row += 1;
|
||||
|
||||
foreach (var item in detail.Kpis)
|
||||
{
|
||||
worksheet.Cell(row, 1).Value = item.Label;
|
||||
worksheet.Cell(row, 2).Value = FormatKpiValue(item.Key, item.Value);
|
||||
worksheet.Cell(row, 3).Value = FormatSignedRate(item.YoyChangeRate);
|
||||
worksheet.Cell(row, 4).Value = FormatSignedRate(item.MomChangeRate);
|
||||
row += 1;
|
||||
}
|
||||
|
||||
row += 1;
|
||||
row = WriteBreakdownTable(worksheet, row, "收入明细(按渠道)", detail.IncomeBreakdowns);
|
||||
row += 1;
|
||||
_ = WriteBreakdownTable(worksheet, row, "成本明细(按类别)", detail.CostBreakdowns);
|
||||
|
||||
worksheet.Columns().AdjustToContents();
|
||||
}
|
||||
|
||||
private static int WriteBreakdownTable(
|
||||
IXLWorksheet worksheet,
|
||||
int startRow,
|
||||
string title,
|
||||
IReadOnlyList<FinanceBusinessReportBreakdownSnapshot> rows)
|
||||
{
|
||||
var row = startRow;
|
||||
worksheet.Cell(row, 1).Value = title;
|
||||
worksheet.Cell(row, 1).Style.Font.SetBold();
|
||||
row += 1;
|
||||
|
||||
worksheet.Cell(row, 1).Value = "名称";
|
||||
worksheet.Cell(row, 2).Value = "占比";
|
||||
worksheet.Cell(row, 3).Value = "金额";
|
||||
row += 1;
|
||||
|
||||
foreach (var item in rows)
|
||||
{
|
||||
worksheet.Cell(row, 1).Value = item.Label;
|
||||
worksheet.Cell(row, 2).Value = FormatPercent(item.Ratio);
|
||||
worksheet.Cell(row, 3).Value = item.Amount;
|
||||
row += 1;
|
||||
}
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
private static string FormatCurrency(decimal value) => $"¥{value:0.##}";
|
||||
private static string FormatPercent(decimal ratioValue) => $"{ratioValue * 100m:0.##}%";
|
||||
private static string FormatSignedRate(decimal rate) => $"{(rate >= 0m ? "+" : string.Empty)}{rate:0.##}%";
|
||||
private static string BuildTitle(FinanceBusinessReportDetailSnapshot detail) => detail.PeriodType switch
|
||||
{
|
||||
FinanceBusinessReportPeriodType.Daily => $"{detail.PeriodStartAt:yyyy年M月d日} 经营日报",
|
||||
FinanceBusinessReportPeriodType.Weekly => $"{detail.PeriodStartAt:yyyy年M月d日}~{detail.PeriodEndAt.AddDays(-1):M月d日} 经营周报",
|
||||
FinanceBusinessReportPeriodType.Monthly => $"{detail.PeriodStartAt:yyyy年M月} 经营月报",
|
||||
_ => detail.PeriodStartAt == default
|
||||
? "经营报表"
|
||||
: detail.PeriodStartAt.ToString("yyyy-MM-dd 经营报表", CultureInfo.InvariantCulture)
|
||||
};
|
||||
private static string ResolveStatusText(FinanceBusinessReportStatus status) => status switch
|
||||
{
|
||||
FinanceBusinessReportStatus.Queued => "排队中",
|
||||
FinanceBusinessReportStatus.Running => "生成中",
|
||||
FinanceBusinessReportStatus.Succeeded => "已生成",
|
||||
FinanceBusinessReportStatus.Failed => "生成失败",
|
||||
_ => "未知"
|
||||
};
|
||||
|
||||
private static string FormatKpiValue(string key, decimal value)
|
||||
{
|
||||
if (key == "order_count")
|
||||
{
|
||||
return $"{decimal.Round(value, 0, MidpointRounding.AwayFromZero):0}";
|
||||
}
|
||||
|
||||
if (key is "refund_rate" or "profit_rate")
|
||||
{
|
||||
return $"{value * 100m:0.##}%";
|
||||
}
|
||||
|
||||
return FormatCurrency(value);
|
||||
}
|
||||
}
|
||||
10972
src/Infrastructure/TakeoutSaaS.Infrastructure/Migrations/20260304071623_AddFinanceInvoiceModule.Designer.cs
generated
Normal file
10972
src/Infrastructure/TakeoutSaaS.Infrastructure/Migrations/20260304071623_AddFinanceInvoiceModule.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,214 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace TakeoutSaaS.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddFinanceInvoiceModule : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "finance_cost_entries",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
Dimension = table.Column<int>(type: "integer", nullable: false, comment: "统计维度。"),
|
||||
StoreId = table.Column<long>(type: "bigint", nullable: true, comment: "门店标识(租户汇总维度为空)。"),
|
||||
CostMonth = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "成本月份(统一存储为 UTC 每月第一天 00:00:00)。"),
|
||||
Category = table.Column<int>(type: "integer", nullable: false, comment: "成本分类。"),
|
||||
TotalAmount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "分类总金额。"),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间(UTC)。"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间(UTC),从未更新时为 null。"),
|
||||
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间(UTC),未删除时为 null。"),
|
||||
CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识,匿名或系统操作时为 null。"),
|
||||
UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识,匿名或系统操作时为 null。"),
|
||||
DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识(软删除),未删除时为 null。"),
|
||||
TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_finance_cost_entries", x => x.Id);
|
||||
},
|
||||
comment: "成本录入月度汇总实体(按维度 + 分类)。");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "finance_invoice_records",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
InvoiceNo = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false, comment: "发票号码。"),
|
||||
ApplicantName = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false, comment: "申请人。"),
|
||||
CompanyName = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false, comment: "开票抬头(公司名)。"),
|
||||
TaxpayerNumber = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true, comment: "纳税人识别号快照。"),
|
||||
InvoiceType = table.Column<int>(type: "integer", nullable: false, comment: "发票类型。"),
|
||||
Amount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "开票金额。"),
|
||||
OrderNo = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false, comment: "关联订单号。"),
|
||||
ContactEmail = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: true, comment: "接收邮箱。"),
|
||||
ContactPhone = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: true, comment: "联系电话。"),
|
||||
ApplyRemark = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true, comment: "申请备注。"),
|
||||
Status = table.Column<int>(type: "integer", nullable: false, comment: "发票状态。"),
|
||||
AppliedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "申请时间(UTC)。"),
|
||||
IssuedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "开票时间(UTC)。"),
|
||||
IssuedByUserId = table.Column<long>(type: "bigint", nullable: true, comment: "开票人 ID。"),
|
||||
IssueRemark = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true, comment: "开票备注。"),
|
||||
VoidedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "作废时间(UTC)。"),
|
||||
VoidedByUserId = table.Column<long>(type: "bigint", nullable: true, comment: "作废人 ID。"),
|
||||
VoidReason = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true, comment: "作废原因。"),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间(UTC)。"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间(UTC),从未更新时为 null。"),
|
||||
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间(UTC),未删除时为 null。"),
|
||||
CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识,匿名或系统操作时为 null。"),
|
||||
UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识,匿名或系统操作时为 null。"),
|
||||
DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识(软删除),未删除时为 null。"),
|
||||
TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_finance_invoice_records", x => x.Id);
|
||||
},
|
||||
comment: "租户发票记录。");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "finance_invoice_settings",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
CompanyName = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false, comment: "企业名称。"),
|
||||
TaxpayerNumber = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false, comment: "纳税人识别号。"),
|
||||
RegisteredAddress = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true, comment: "注册地址。"),
|
||||
RegisteredPhone = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: true, comment: "注册电话。"),
|
||||
BankName = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: true, comment: "开户银行。"),
|
||||
BankAccount = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true, comment: "银行账号。"),
|
||||
EnableElectronicNormalInvoice = table.Column<bool>(type: "boolean", nullable: false, comment: "是否启用电子普通发票。"),
|
||||
EnableElectronicSpecialInvoice = table.Column<bool>(type: "boolean", nullable: false, comment: "是否启用电子专用发票。"),
|
||||
EnableAutoIssue = table.Column<bool>(type: "boolean", nullable: false, comment: "是否启用自动开票。"),
|
||||
AutoIssueMaxAmount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "自动开票单张最大金额。"),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间(UTC)。"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间(UTC),从未更新时为 null。"),
|
||||
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间(UTC),未删除时为 null。"),
|
||||
CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识,匿名或系统操作时为 null。"),
|
||||
UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识,匿名或系统操作时为 null。"),
|
||||
DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识(软删除),未删除时为 null。"),
|
||||
TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_finance_invoice_settings", x => x.Id);
|
||||
},
|
||||
comment: "租户发票开票基础设置。");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "finance_cost_entry_items",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
EntryId = table.Column<long>(type: "bigint", nullable: false, comment: "关联汇总行标识。"),
|
||||
Dimension = table.Column<int>(type: "integer", nullable: false, comment: "统计维度。"),
|
||||
StoreId = table.Column<long>(type: "bigint", nullable: true, comment: "门店标识(租户汇总维度为空)。"),
|
||||
CostMonth = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "成本月份(统一存储为 UTC 每月第一天 00:00:00)。"),
|
||||
Category = table.Column<int>(type: "integer", nullable: false, comment: "成本分类。"),
|
||||
ItemName = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false, comment: "明细名称。"),
|
||||
Amount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "明细金额。"),
|
||||
Quantity = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: true, comment: "数量(人工类可用)。"),
|
||||
UnitPrice = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: true, comment: "单价(人工类可用)。"),
|
||||
SortOrder = table.Column<int>(type: "integer", nullable: false, defaultValue: 100, comment: "排序值。"),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间(UTC)。"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间(UTC),从未更新时为 null。"),
|
||||
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间(UTC),未删除时为 null。"),
|
||||
CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识,匿名或系统操作时为 null。"),
|
||||
UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识,匿名或系统操作时为 null。"),
|
||||
DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识(软删除),未删除时为 null。"),
|
||||
TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_finance_cost_entry_items", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_finance_cost_entry_items_finance_cost_entries_EntryId",
|
||||
column: x => x.EntryId,
|
||||
principalTable: "finance_cost_entries",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
},
|
||||
comment: "成本录入明细项实体。");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_cost_entries_TenantId_Dimension_StoreId_CostMonth",
|
||||
table: "finance_cost_entries",
|
||||
columns: new[] { "TenantId", "Dimension", "StoreId", "CostMonth" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_cost_entries_TenantId_Dimension_StoreId_CostMonth_C~",
|
||||
table: "finance_cost_entries",
|
||||
columns: new[] { "TenantId", "Dimension", "StoreId", "CostMonth", "Category" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_cost_entry_items_EntryId",
|
||||
table: "finance_cost_entry_items",
|
||||
column: "EntryId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_cost_entry_items_TenantId_Dimension_StoreId_CostMon~",
|
||||
table: "finance_cost_entry_items",
|
||||
columns: new[] { "TenantId", "Dimension", "StoreId", "CostMonth", "Category", "SortOrder" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_invoice_records_TenantId_InvoiceNo",
|
||||
table: "finance_invoice_records",
|
||||
columns: new[] { "TenantId", "InvoiceNo" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_invoice_records_TenantId_InvoiceType_AppliedAt",
|
||||
table: "finance_invoice_records",
|
||||
columns: new[] { "TenantId", "InvoiceType", "AppliedAt" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_invoice_records_TenantId_OrderNo",
|
||||
table: "finance_invoice_records",
|
||||
columns: new[] { "TenantId", "OrderNo" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_invoice_records_TenantId_Status_AppliedAt",
|
||||
table: "finance_invoice_records",
|
||||
columns: new[] { "TenantId", "Status", "AppliedAt" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_invoice_records_TenantId_Status_IssuedAt",
|
||||
table: "finance_invoice_records",
|
||||
columns: new[] { "TenantId", "Status", "IssuedAt" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_invoice_settings_TenantId",
|
||||
table: "finance_invoice_settings",
|
||||
column: "TenantId",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "finance_cost_entry_items");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "finance_invoice_records");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "finance_invoice_settings");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "finance_cost_entries");
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,42 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace TakeoutSaaS.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddTenantVerificationSettlementChannels : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "AlipayPid",
|
||||
table: "tenant_verification_profiles",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: true,
|
||||
comment: "支付宝 PID。");
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "WeChatMerchantNo",
|
||||
table: "tenant_verification_profiles",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: true,
|
||||
comment: "微信商户号。");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "AlipayPid",
|
||||
table: "tenant_verification_profiles");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "WeChatMerchantNo",
|
||||
table: "tenant_verification_profiles");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using TakeoutSaaS.Infrastructure.App.Persistence;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace TakeoutSaaS.Infrastructure.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// 新增经营报表快照与成本配置表结构。
|
||||
/// </summary>
|
||||
[DbContext(typeof(TakeoutAppDbContext))]
|
||||
[Migration("20260305090000_AddFinanceBusinessReportModule")]
|
||||
public sealed class AddFinanceBusinessReportModule : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "finance_business_report_snapshots",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
StoreId = table.Column<long>(type: "bigint", nullable: false, comment: "所属门店 ID。"),
|
||||
PeriodType = table.Column<int>(type: "integer", nullable: false, comment: "周期类型。"),
|
||||
PeriodStartAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "周期开始时间(UTC,含)。"),
|
||||
PeriodEndAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "周期结束时间(UTC,不含)。"),
|
||||
Status = table.Column<int>(type: "integer", nullable: false, comment: "生成状态。"),
|
||||
RevenueAmount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "营业额。"),
|
||||
OrderCount = table.Column<int>(type: "integer", nullable: false, comment: "订单数。"),
|
||||
AverageOrderValue = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "客单价。"),
|
||||
RefundRate = table.Column<decimal>(type: "numeric(9,4)", precision: 9, scale: 4, nullable: false, comment: "退款率(0-1)。"),
|
||||
CostTotalAmount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "成本总额。"),
|
||||
NetProfitAmount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "净利润。"),
|
||||
ProfitRate = table.Column<decimal>(type: "numeric(9,4)", precision: 9, scale: 4, nullable: false, comment: "利润率(0-1)。"),
|
||||
KpiComparisonJson = table.Column<string>(type: "text", nullable: false, comment: "KPI 比较快照 JSON(同比/环比)。"),
|
||||
IncomeBreakdownJson = table.Column<string>(type: "text", nullable: false, comment: "收入明细快照 JSON(按渠道)。"),
|
||||
CostBreakdownJson = table.Column<string>(type: "text", nullable: false, comment: "成本明细快照 JSON(按类别)。"),
|
||||
StartedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "生成开始时间(UTC)。"),
|
||||
FinishedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "生成完成时间(UTC)。"),
|
||||
LastError = table.Column<string>(type: "character varying(1024)", maxLength: 1024, nullable: true, comment: "最近一次失败信息。"),
|
||||
RetryCount = table.Column<int>(type: "integer", nullable: false, defaultValue: 0, comment: "重试次数。"),
|
||||
HangfireJobId = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true, comment: "调度任务 ID。"),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间(UTC)。"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间(UTC),从未更新时为 null。"),
|
||||
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间(UTC),未删除时为 null。"),
|
||||
CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识,匿名或系统操作时为 null。"),
|
||||
UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识,匿名或系统操作时为 null。"),
|
||||
DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识(软删除),未删除时为 null。"),
|
||||
TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_finance_business_report_snapshots", x => x.Id);
|
||||
},
|
||||
comment: "经营报表快照实体。");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "finance_cost_profiles",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
StoreId = table.Column<long>(type: "bigint", nullable: false, comment: "门店 ID。"),
|
||||
Category = table.Column<int>(type: "integer", nullable: false, comment: "成本分类。"),
|
||||
CalcMode = table.Column<int>(type: "integer", nullable: false, comment: "计算模式。"),
|
||||
Ratio = table.Column<decimal>(type: "numeric(9,6)", precision: 9, scale: 6, nullable: false, comment: "比例值(0-1)。"),
|
||||
FixedDailyAmount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "固定日金额。"),
|
||||
EffectiveFrom = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "生效开始日期(UTC 日期)。"),
|
||||
EffectiveTo = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "生效结束日期(UTC 日期,含)。"),
|
||||
IsEnabled = table.Column<bool>(type: "boolean", nullable: false, comment: "是否启用。"),
|
||||
SortOrder = table.Column<int>(type: "integer", nullable: false, defaultValue: 100, comment: "排序值。"),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间(UTC)。"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间(UTC),从未更新时为 null。"),
|
||||
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间(UTC),未删除时为 null。"),
|
||||
CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识,匿名或系统操作时为 null。"),
|
||||
UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识,匿名或系统操作时为 null。"),
|
||||
DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识(软删除),未删除时为 null。"),
|
||||
TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_finance_cost_profiles", x => x.Id);
|
||||
},
|
||||
comment: "成本配置实体(类别级规则)。");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "finance_cost_daily_overrides",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
StoreId = table.Column<long>(type: "bigint", nullable: false, comment: "门店 ID。"),
|
||||
BusinessDate = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "业务日期(UTC 日期)。"),
|
||||
Category = table.Column<int>(type: "integer", nullable: false, comment: "成本分类。"),
|
||||
Amount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "覆盖金额。"),
|
||||
Remark = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true, comment: "备注。"),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间(UTC)。"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间(UTC),从未更新时为 null。"),
|
||||
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间(UTC),未删除时为 null。"),
|
||||
CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识,匿名或系统操作时为 null。"),
|
||||
UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识,匿名或系统操作时为 null。"),
|
||||
DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识(软删除),未删除时为 null。"),
|
||||
TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_finance_cost_daily_overrides", x => x.Id);
|
||||
},
|
||||
comment: "成本日覆盖实体。");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_business_report_snapshots_TenantId_Status_CreatedAt",
|
||||
table: "finance_business_report_snapshots",
|
||||
columns: new[] { "TenantId", "Status", "CreatedAt" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_business_report_snapshots_TenantId_StoreId_PeriodType_S~",
|
||||
table: "finance_business_report_snapshots",
|
||||
columns: new[] { "TenantId", "StoreId", "PeriodType", "Status", "PeriodStartAt" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_business_report_snapshots_TenantId_StoreId_PeriodType_P~",
|
||||
table: "finance_business_report_snapshots",
|
||||
columns: new[] { "TenantId", "StoreId", "PeriodType", "PeriodStartAt" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_cost_daily_overrides_TenantId_StoreId_BusinessDate",
|
||||
table: "finance_cost_daily_overrides",
|
||||
columns: new[] { "TenantId", "StoreId", "BusinessDate" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_cost_daily_overrides_TenantId_StoreId_BusinessDate_Cate~",
|
||||
table: "finance_cost_daily_overrides",
|
||||
columns: new[] { "TenantId", "StoreId", "BusinessDate", "Category" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_cost_profiles_TenantId_StoreId_Category_EffectiveFrom_E~",
|
||||
table: "finance_cost_profiles",
|
||||
columns: new[] { "TenantId", "StoreId", "Category", "EffectiveFrom", "EffectiveTo" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_cost_profiles_TenantId_StoreId_IsEnabled_SortOrder",
|
||||
table: "finance_cost_profiles",
|
||||
columns: new[] { "TenantId", "StoreId", "IsEnabled", "SortOrder" });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "finance_business_report_snapshots");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "finance_cost_daily_overrides");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "finance_cost_profiles");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
using TakeoutSaaS.Infrastructure.App.Persistence;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace TakeoutSaaS.Infrastructure.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// 新增财务中心发票管理表结构。
|
||||
/// </summary>
|
||||
[DbContext(typeof(TakeoutAppDbContext))]
|
||||
[Migration("20260305103000_AddFinanceInvoiceModule")]
|
||||
public sealed class AddFinanceInvoiceModule : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "finance_invoice_records",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
InvoiceNo = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false, comment: "发票号码。"),
|
||||
ApplicantName = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false, comment: "申请人。"),
|
||||
CompanyName = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false, comment: "开票抬头(公司名)。"),
|
||||
TaxpayerNumber = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true, comment: "纳税人识别号快照。"),
|
||||
InvoiceType = table.Column<int>(type: "integer", nullable: false, comment: "发票类型。"),
|
||||
Amount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "开票金额。"),
|
||||
OrderNo = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false, comment: "关联订单号。"),
|
||||
ContactEmail = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: true, comment: "接收邮箱。"),
|
||||
ContactPhone = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: true, comment: "联系电话。"),
|
||||
ApplyRemark = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true, comment: "申请备注。"),
|
||||
Status = table.Column<int>(type: "integer", nullable: false, comment: "发票状态。"),
|
||||
AppliedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "申请时间(UTC)。"),
|
||||
IssuedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "开票时间(UTC)。"),
|
||||
IssuedByUserId = table.Column<long>(type: "bigint", nullable: true, comment: "开票人 ID。"),
|
||||
IssueRemark = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true, comment: "开票备注。"),
|
||||
VoidedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "作废时间(UTC)。"),
|
||||
VoidedByUserId = table.Column<long>(type: "bigint", nullable: true, comment: "作废人 ID。"),
|
||||
VoidReason = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true, comment: "作废原因。"),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间(UTC)。"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间(UTC),从未更新时为 null。"),
|
||||
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间(UTC),未删除时为 null。"),
|
||||
CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识,匿名或系统操作时为 null。"),
|
||||
UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识,匿名或系统操作时为 null。"),
|
||||
DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识(软删除),未删除时为 null。"),
|
||||
TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_finance_invoice_records", x => x.Id);
|
||||
},
|
||||
comment: "租户发票记录。");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "finance_invoice_settings",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
|
||||
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
|
||||
CompanyName = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: false, comment: "企业名称。"),
|
||||
TaxpayerNumber = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false, comment: "纳税人识别号。"),
|
||||
RegisteredAddress = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true, comment: "注册地址。"),
|
||||
RegisteredPhone = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: true, comment: "注册电话。"),
|
||||
BankName = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: true, comment: "开户银行。"),
|
||||
BankAccount = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true, comment: "银行账号。"),
|
||||
EnableElectronicNormalInvoice = table.Column<bool>(type: "boolean", nullable: false, comment: "是否启用电子普通发票。"),
|
||||
EnableElectronicSpecialInvoice = table.Column<bool>(type: "boolean", nullable: false, comment: "是否启用电子专用发票。"),
|
||||
EnableAutoIssue = table.Column<bool>(type: "boolean", nullable: false, comment: "是否启用自动开票。"),
|
||||
AutoIssueMaxAmount = table.Column<decimal>(type: "numeric(18,2)", precision: 18, scale: 2, nullable: false, comment: "自动开票单张最大金额。"),
|
||||
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间(UTC)。"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间(UTC),从未更新时为 null。"),
|
||||
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间(UTC),未删除时为 null。"),
|
||||
CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识,匿名或系统操作时为 null。"),
|
||||
UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识,匿名或系统操作时为 null。"),
|
||||
DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识(软删除),未删除时为 null。"),
|
||||
TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_finance_invoice_settings", x => x.Id);
|
||||
},
|
||||
comment: "租户发票开票基础设置。");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_invoice_records_TenantId_InvoiceNo",
|
||||
table: "finance_invoice_records",
|
||||
columns: new[] { "TenantId", "InvoiceNo" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_invoice_records_TenantId_InvoiceType_AppliedAt",
|
||||
table: "finance_invoice_records",
|
||||
columns: new[] { "TenantId", "InvoiceType", "AppliedAt" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_invoice_records_TenantId_OrderNo",
|
||||
table: "finance_invoice_records",
|
||||
columns: new[] { "TenantId", "OrderNo" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_invoice_records_TenantId_Status_AppliedAt",
|
||||
table: "finance_invoice_records",
|
||||
columns: new[] { "TenantId", "Status", "AppliedAt" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_invoice_records_TenantId_Status_IssuedAt",
|
||||
table: "finance_invoice_records",
|
||||
columns: new[] { "TenantId", "Status", "IssuedAt" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_finance_invoice_settings_TenantId",
|
||||
table: "finance_invoice_settings",
|
||||
column: "TenantId",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "finance_invoice_records");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "finance_invoice_settings");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using TakeoutSaaS.Infrastructure.Identity.Persistence;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace TakeoutSaaS.Infrastructure.Migrations.IdentityDb;
|
||||
|
||||
/// <summary>
|
||||
/// 写入经营报表菜单与权限定义。
|
||||
/// </summary>
|
||||
[DbContext(typeof(IdentityDbContext))]
|
||||
[Migration("20260305093000_SeedFinanceReportMenuAndPermissions")]
|
||||
public sealed class SeedFinanceReportMenuAndPermissions : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.Sql(
|
||||
"""
|
||||
DO $$
|
||||
DECLARE
|
||||
v_parent_permission_id bigint;
|
||||
v_view_permission_id bigint;
|
||||
v_export_permission_id bigint;
|
||||
v_parent_menu_id bigint;
|
||||
v_report_menu_id bigint;
|
||||
v_permission_seed_base bigint := 840200000000000000;
|
||||
v_menu_seed_base bigint := 850200000000000000;
|
||||
BEGIN
|
||||
-- 1. 确保统计权限分组存在。
|
||||
SELECT "Id"
|
||||
INTO v_parent_permission_id
|
||||
FROM public.permissions
|
||||
WHERE "Code" = 'group:tenant:statistics'
|
||||
ORDER BY "Id"
|
||||
LIMIT 1;
|
||||
|
||||
IF v_parent_permission_id IS NULL THEN
|
||||
v_parent_permission_id := v_permission_seed_base + 1;
|
||||
INSERT INTO public.permissions (
|
||||
"Id", "Name", "Code", "Description",
|
||||
"CreatedAt", "UpdatedAt", "DeletedAt",
|
||||
"CreatedBy", "UpdatedBy", "DeletedBy",
|
||||
"ParentId", "SortOrder", "Type", "Portal")
|
||||
VALUES (
|
||||
v_parent_permission_id, '经营分析', 'group:tenant:statistics', '经营分析权限分组',
|
||||
NOW(), NULL, NULL,
|
||||
NULL, NULL, NULL,
|
||||
0, 5300, 'group', 1)
|
||||
ON CONFLICT ("Code") DO NOTHING;
|
||||
END IF;
|
||||
|
||||
-- 2. Upsert 经营报表查看权限。
|
||||
INSERT INTO public.permissions (
|
||||
"Id", "Name", "Code", "Description",
|
||||
"CreatedAt", "UpdatedAt", "DeletedAt",
|
||||
"CreatedBy", "UpdatedBy", "DeletedBy",
|
||||
"ParentId", "SortOrder", "Type", "Portal")
|
||||
VALUES (
|
||||
v_permission_seed_base + 11, '经营报表查看', 'tenant:statistics:report:view', '查看经营报表列表与详情',
|
||||
NOW(), NULL, NULL,
|
||||
NULL, NULL, NULL,
|
||||
v_parent_permission_id, 5310, 'leaf', 1)
|
||||
ON CONFLICT ("Code") DO UPDATE
|
||||
SET "Name" = EXCLUDED."Name",
|
||||
"Description" = EXCLUDED."Description",
|
||||
"ParentId" = EXCLUDED."ParentId",
|
||||
"SortOrder" = EXCLUDED."SortOrder",
|
||||
"Type" = EXCLUDED."Type",
|
||||
"Portal" = EXCLUDED."Portal",
|
||||
"DeletedAt" = NULL,
|
||||
"DeletedBy" = NULL,
|
||||
"UpdatedAt" = NOW();
|
||||
|
||||
-- 3. Upsert 经营报表导出权限。
|
||||
INSERT INTO public.permissions (
|
||||
"Id", "Name", "Code", "Description",
|
||||
"CreatedAt", "UpdatedAt", "DeletedAt",
|
||||
"CreatedBy", "UpdatedBy", "DeletedBy",
|
||||
"ParentId", "SortOrder", "Type", "Portal")
|
||||
VALUES (
|
||||
v_permission_seed_base + 12, '经营报表导出', 'tenant:statistics:report:export', '导出经营报表 PDF / Excel / ZIP',
|
||||
NOW(), NULL, NULL,
|
||||
NULL, NULL, NULL,
|
||||
v_parent_permission_id, 5320, 'leaf', 1)
|
||||
ON CONFLICT ("Code") DO UPDATE
|
||||
SET "Name" = EXCLUDED."Name",
|
||||
"Description" = EXCLUDED."Description",
|
||||
"ParentId" = EXCLUDED."ParentId",
|
||||
"SortOrder" = EXCLUDED."SortOrder",
|
||||
"Type" = EXCLUDED."Type",
|
||||
"Portal" = EXCLUDED."Portal",
|
||||
"DeletedAt" = NULL,
|
||||
"DeletedBy" = NULL,
|
||||
"UpdatedAt" = NOW();
|
||||
|
||||
SELECT "Id" INTO v_view_permission_id
|
||||
FROM public.permissions
|
||||
WHERE "Code" = 'tenant:statistics:report:view'
|
||||
LIMIT 1;
|
||||
|
||||
SELECT "Id" INTO v_export_permission_id
|
||||
FROM public.permissions
|
||||
WHERE "Code" = 'tenant:statistics:report:export'
|
||||
LIMIT 1;
|
||||
|
||||
-- 4. 确保租户端财务父菜单存在。
|
||||
SELECT "Id"
|
||||
INTO v_parent_menu_id
|
||||
FROM public.menu_definitions
|
||||
WHERE "Portal" = 1 AND "Path" = '/finance' AND "DeletedAt" IS NULL
|
||||
ORDER BY "Id"
|
||||
LIMIT 1;
|
||||
|
||||
IF v_parent_menu_id IS NULL THEN
|
||||
v_parent_menu_id := v_menu_seed_base + 1;
|
||||
INSERT INTO public.menu_definitions (
|
||||
"Id", "ParentId", "Name", "Path", "Component", "Title", "Icon",
|
||||
"IsIframe", "Link", "KeepAlive", "SortOrder",
|
||||
"RequiredPermissions", "MetaPermissions", "MetaRoles", "AuthListJson",
|
||||
"CreatedAt", "UpdatedAt", "DeletedAt", "CreatedBy", "UpdatedBy", "DeletedBy", "Portal")
|
||||
VALUES (
|
||||
v_parent_menu_id, 0, 'Finance', '/finance', 'BasicLayout', '财务中心', 'lucide:wallet',
|
||||
FALSE, NULL, FALSE, 500,
|
||||
'', '', '', NULL,
|
||||
NOW(), NULL, NULL, NULL, NULL, NULL, 1)
|
||||
ON CONFLICT ("Id") DO NOTHING;
|
||||
END IF;
|
||||
|
||||
-- 5. Upsert 经营报表菜单。
|
||||
SELECT "Id"
|
||||
INTO v_report_menu_id
|
||||
FROM public.menu_definitions
|
||||
WHERE "Portal" = 1
|
||||
AND ("Path" = '/finance/report' OR ("Path" = 'report' AND "Component" = '/finance/report/index'))
|
||||
ORDER BY "DeletedAt" NULLS FIRST, "Id"
|
||||
LIMIT 1;
|
||||
|
||||
IF v_report_menu_id IS NULL THEN
|
||||
v_report_menu_id := v_menu_seed_base + 11;
|
||||
INSERT INTO public.menu_definitions (
|
||||
"Id", "ParentId", "Name", "Path", "Component", "Title", "Icon",
|
||||
"IsIframe", "Link", "KeepAlive", "SortOrder",
|
||||
"RequiredPermissions", "MetaPermissions", "MetaRoles", "AuthListJson",
|
||||
"CreatedAt", "UpdatedAt", "DeletedAt", "CreatedBy", "UpdatedBy", "DeletedBy", "Portal")
|
||||
VALUES (
|
||||
v_report_menu_id, v_parent_menu_id, 'BusinessReport', '/finance/report', '/finance/report/index', '经营报表', 'lucide:file-bar-chart-2',
|
||||
FALSE, NULL, TRUE, 530,
|
||||
'tenant:statistics:report:view', 'tenant:statistics:report:view,tenant:statistics:report:export', '', NULL,
|
||||
NOW(), NULL, NULL, NULL, NULL, NULL, 1)
|
||||
ON CONFLICT ("Id") DO NOTHING;
|
||||
ELSE
|
||||
UPDATE public.menu_definitions
|
||||
SET "ParentId" = v_parent_menu_id,
|
||||
"Name" = 'BusinessReport',
|
||||
"Path" = '/finance/report',
|
||||
"Component" = '/finance/report/index',
|
||||
"Title" = '经营报表',
|
||||
"Icon" = 'lucide:file-bar-chart-2',
|
||||
"IsIframe" = FALSE,
|
||||
"Link" = NULL,
|
||||
"KeepAlive" = TRUE,
|
||||
"SortOrder" = 530,
|
||||
"RequiredPermissions" = 'tenant:statistics:report:view',
|
||||
"MetaPermissions" = 'tenant:statistics:report:view,tenant:statistics:report:export',
|
||||
"MetaRoles" = '',
|
||||
"DeletedAt" = NULL,
|
||||
"DeletedBy" = NULL,
|
||||
"UpdatedAt" = NOW(),
|
||||
"Portal" = 1
|
||||
WHERE "Id" = v_report_menu_id;
|
||||
END IF;
|
||||
|
||||
-- 6. 为 tenant-admin 角色授予权限。
|
||||
INSERT INTO public.role_permissions (
|
||||
"Id", "RoleId", "PermissionId", "CreatedAt", "UpdatedAt", "DeletedAt",
|
||||
"CreatedBy", "UpdatedBy", "DeletedBy", "TenantId", "Portal")
|
||||
SELECT
|
||||
ABS(HASHTEXTEXTENDED('tenant-admin:report:' || role."Id"::text || ':' || permission_id::text, 0)),
|
||||
role."Id",
|
||||
permission_id,
|
||||
NOW(), NULL, NULL,
|
||||
NULL, NULL, NULL,
|
||||
role."TenantId",
|
||||
1
|
||||
FROM public.roles role
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT UNNEST(ARRAY[v_view_permission_id, v_export_permission_id]) AS permission_id
|
||||
) item
|
||||
WHERE role."Code" = 'tenant-admin'
|
||||
AND role."DeletedAt" IS NULL
|
||||
AND item.permission_id IS NOT NULL
|
||||
ON CONFLICT ("RoleId", "PermissionId") DO UPDATE
|
||||
SET "DeletedAt" = NULL,
|
||||
"DeletedBy" = NULL,
|
||||
"UpdatedAt" = NOW(),
|
||||
"Portal" = 1;
|
||||
|
||||
-- 7. 为 tenant-admin 角色模板授予权限。
|
||||
INSERT INTO public.role_template_permissions (
|
||||
"Id", "RoleTemplateId", "PermissionCode",
|
||||
"CreatedAt", "UpdatedAt", "DeletedAt",
|
||||
"CreatedBy", "UpdatedBy", "DeletedBy")
|
||||
SELECT
|
||||
ABS(HASHTEXTEXTENDED('template-report:' || template."Id"::text || ':' || item.permission_code, 0)),
|
||||
template."Id",
|
||||
item.permission_code,
|
||||
NOW(), NULL, NULL,
|
||||
NULL, NULL, NULL
|
||||
FROM public.role_templates template
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT UNNEST(ARRAY['tenant:statistics:report:view', 'tenant:statistics:report:export']) AS permission_code
|
||||
) item
|
||||
WHERE template."TemplateCode" = 'tenant-admin'
|
||||
AND template."DeletedAt" IS NULL
|
||||
ON CONFLICT ("RoleTemplateId", "PermissionCode") DO UPDATE
|
||||
SET "DeletedAt" = NULL,
|
||||
"DeletedBy" = NULL,
|
||||
"UpdatedAt" = NOW();
|
||||
END $$;
|
||||
""");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.Sql(
|
||||
"""
|
||||
DO $$
|
||||
BEGIN
|
||||
DELETE FROM public.role_permissions
|
||||
WHERE "PermissionId" IN (
|
||||
SELECT "Id"
|
||||
FROM public.permissions
|
||||
WHERE "Code" IN ('tenant:statistics:report:view', 'tenant:statistics:report:export'));
|
||||
|
||||
DELETE FROM public.role_template_permissions
|
||||
WHERE "PermissionCode" IN ('tenant:statistics:report:view', 'tenant:statistics:report:export');
|
||||
|
||||
DELETE FROM public.menu_definitions
|
||||
WHERE "Portal" = 1 AND "Path" = '/finance/report';
|
||||
|
||||
DELETE FROM public.permissions
|
||||
WHERE "Code" IN ('tenant:statistics:report:view', 'tenant:statistics:report:export');
|
||||
END $$;
|
||||
""");
|
||||
}
|
||||
}
|
||||
@@ -9711,6 +9711,11 @@ namespace TakeoutSaaS.Infrastructure.Migrations
|
||||
.HasColumnType("text")
|
||||
.HasComment("附加资料(JSON)。");
|
||||
|
||||
b.Property<string>("AlipayPid")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasComment("支付宝 PID。");
|
||||
|
||||
b.Property<string>("BankAccountName")
|
||||
.HasMaxLength(128)
|
||||
.HasColumnType("character varying(128)")
|
||||
@@ -9810,6 +9815,11 @@ namespace TakeoutSaaS.Infrastructure.Migrations
|
||||
.HasColumnType("bigint")
|
||||
.HasComment("最后更新人用户标识,匿名或系统操作时为 null。");
|
||||
|
||||
b.Property<string>("WeChatMerchantNo")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasComment("微信商户号。");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TenantId")
|
||||
|
||||
@@ -71,6 +71,7 @@ public static class SchedulerServiceCollectionExtensions
|
||||
services.AddScoped<SubscriptionExpiryCheckJob>();
|
||||
services.AddScoped<SubscriptionAutoRenewalJob>();
|
||||
services.AddScoped<BillingOverdueProcessJob>();
|
||||
services.AddScoped<FinanceBusinessReportRefreshJob>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using TakeoutSaaS.Domain.Finance.Repositories;
|
||||
using TakeoutSaaS.Shared.Abstractions.Tenancy;
|
||||
|
||||
namespace TakeoutSaaS.Module.Scheduler.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// 经营报表快照刷新任务:消费排队中的报表快照并触发生成。
|
||||
/// </summary>
|
||||
public sealed class FinanceBusinessReportRefreshJob(
|
||||
IFinanceBusinessReportRepository financeBusinessReportRepository,
|
||||
ITenantContextAccessor tenantContextAccessor,
|
||||
ILogger<FinanceBusinessReportRefreshJob> logger)
|
||||
{
|
||||
private const int BatchSize = 80;
|
||||
|
||||
/// <summary>
|
||||
/// 执行报表快照刷新。
|
||||
/// </summary>
|
||||
public async Task ExecuteAsync()
|
||||
{
|
||||
// 1. 拉取待处理快照任务。
|
||||
var pendingList = await financeBusinessReportRepository.GetPendingSnapshotsAsync(BatchSize, CancellationToken.None);
|
||||
if (pendingList.Count == 0)
|
||||
{
|
||||
logger.LogDebug("定时任务:经营报表快照刷新无待处理任务");
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 逐租户上下文执行生成。
|
||||
var successCount = 0;
|
||||
var failedCount = 0;
|
||||
foreach (var pending in pendingList)
|
||||
{
|
||||
var previousContext = tenantContextAccessor.Current;
|
||||
try
|
||||
{
|
||||
tenantContextAccessor.Current = new TenantContext(
|
||||
pending.TenantId,
|
||||
$"tenant-{pending.TenantId}",
|
||||
"scheduler");
|
||||
|
||||
await financeBusinessReportRepository.GenerateSnapshotAsync(
|
||||
pending.SnapshotId,
|
||||
CancellationToken.None);
|
||||
successCount += 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failedCount += 1;
|
||||
logger.LogError(
|
||||
ex,
|
||||
"定时任务:经营报表快照刷新失败 SnapshotId={SnapshotId}, TenantId={TenantId}",
|
||||
pending.SnapshotId,
|
||||
pending.TenantId);
|
||||
}
|
||||
finally
|
||||
{
|
||||
tenantContextAccessor.Current = previousContext;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 记录执行结果。
|
||||
logger.LogInformation(
|
||||
"定时任务:经营报表快照刷新完成,处理 {TotalCount} 条,成功 {SuccessCount} 条,失败 {FailedCount} 条",
|
||||
pendingList.Count,
|
||||
successCount,
|
||||
failedCount);
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,13 @@ public sealed class RecurringJobRegistrar(
|
||||
job => job.ExecuteAsync(),
|
||||
billingOptions.OverdueBillingProcessCron);
|
||||
|
||||
// 4. (空行后) 门店管理自动化任务
|
||||
// 4. 经营报表快照刷新任务
|
||||
RecurringJob.AddOrUpdate<FinanceBusinessReportRefreshJob>(
|
||||
"finance.business-report-refresh",
|
||||
job => job.ExecuteAsync(),
|
||||
"*/10 * * * *");
|
||||
|
||||
// 5. (空行后) 门店管理自动化任务
|
||||
RecurringJob.AddOrUpdate<BusinessStatusAutoSwitchJob>(
|
||||
"stores.business-status-auto-switch",
|
||||
job => job.ExecuteAsync(),
|
||||
|
||||
Reference in New Issue
Block a user