feat: 主体报表接入上月店铺结算收入 (#1075)
新增动态上月店铺结算收入列。 金额取业绩明细收入金额,按店铺日汇总和主体期间拆分后汇总。 验证:36 项测试、277 个断言通过。
This commit is contained in:
parent
6a1a718e89
commit
d512e5d9ba
@ -789,6 +789,7 @@ SQL);
|
||||
'entity' => $entity,
|
||||
'company_type' => $row['company_type'] ?? null,
|
||||
'rolling_12m_income' => null,
|
||||
'previous_month_settlement_income' => null,
|
||||
'can_change_entity' => null,
|
||||
'plan' => null,
|
||||
'new_entity' => null,
|
||||
@ -799,6 +800,11 @@ SQL);
|
||||
}
|
||||
|
||||
$this->sumNullable($entities[$entity], 'rolling_12m_income', $row['rolling_12m_income'] ?? null);
|
||||
$this->sumNullable(
|
||||
$entities[$entity],
|
||||
'previous_month_settlement_income',
|
||||
$row['previous_month_settlement_income'] ?? null,
|
||||
);
|
||||
for ($month = 1; $month <= 12; $month++) {
|
||||
$key = sprintf('income_%02d', $month);
|
||||
$entities[$entity][$key] ??= null;
|
||||
@ -1049,7 +1055,7 @@ SQL);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (['rolling_12m_income', ...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12))] as $key) {
|
||||
foreach (['rolling_12m_income', 'previous_month_settlement_income', ...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12))] as $key) {
|
||||
$needle = str_replace(',', '', trim((string) ($filters[$key] ?? '')));
|
||||
if ($needle !== '' && (! is_numeric($needle) || ! is_numeric($row[$key] ?? null)
|
||||
|| abs((float) $row[$key] - (float) $needle) > 0.000001)) {
|
||||
@ -1067,6 +1073,7 @@ SQL);
|
||||
$key = (string) ($filters['_sort'] ?? 'entity');
|
||||
$allowed = [
|
||||
'city', 'entity', 'company_type', 'tax_type', 'business_registration_type', 'rolling_12m_income',
|
||||
'previous_month_settlement_income',
|
||||
...array_map(static fn (int $month): string => sprintf('income_%02d', $month), range(1, 12)),
|
||||
'can_change_entity', 'plan', 'new_entity',
|
||||
];
|
||||
|
||||
@ -12,7 +12,7 @@ $navigation = [
|
||||
'directory' => [
|
||||
'icon' => 'query_stats',
|
||||
'status' => '收入汇总',
|
||||
'description' => '按主体生效、失效日期归属账单收入;当前页面一行一个主体,收入来自 SQLite bills.income。',
|
||||
'description' => '按主体生效、失效日期归属账单收入;上月店铺结算收入取业绩明细收入金额,按店铺、主体期间汇总。',
|
||||
'empty' => '经营报表尚未同步。完成店铺主体和销量镜像接入后,这里会显示可追溯的主体数据。',
|
||||
'fields' => [
|
||||
['name' => 'city', 'label' => '市'],
|
||||
@ -28,6 +28,7 @@ $navigation = [
|
||||
]],
|
||||
['name' => 'business_registration_type', 'label' => '工商类型', 'kind' => 'badge'],
|
||||
['name' => 'rolling_12m_income', 'label' => '最近12个月累计收入', 'kind' => 'number'],
|
||||
['name' => 'previous_month_settlement_income', 'label' => '店铺结算收入-客服公司', 'kind' => 'number'],
|
||||
...array_map(static fn (int $month): array => ['name' => sprintf('income_%02d', $month), 'label' => $month . '月收入', 'kind' => 'number'], range(1, 12)),
|
||||
['name' => 'can_change_entity', 'label' => '能否变更主体'],
|
||||
['name' => 'plan', 'label' => '规划'],
|
||||
|
||||
@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 主体维度经营报表的上月店铺结算收入:
|
||||
* 业绩明细「收入金额」按店铺 + 发生日期预汇总,与销量共用一份日汇总。
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
private function connection(): string
|
||||
{
|
||||
return (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
}
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
$schema = Schema::connection($this->connection());
|
||||
if (! $schema->hasTable('store_report_paid_sales_rows')
|
||||
|| $schema->hasColumn('store_report_paid_sales_rows', 'settlement_income')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$schema->table('store_report_paid_sales_rows', function (Blueprint $table): void {
|
||||
$table->decimal('settlement_income', 20, 4)
|
||||
->nullable()
|
||||
->after('paid_amount');
|
||||
});
|
||||
|
||||
// 新列需要从业绩明细重新汇总一次;清空指纹后,下一次同步会原子重建当前版本。
|
||||
if ($schema->hasTable('store_report_import_states')) {
|
||||
$schema->getConnection()->table('store_report_import_states')
|
||||
->where('dataset_key', 'store-report.paid-sales')
|
||||
->update(['source_fingerprint' => null]);
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$schema = Schema::connection($this->connection());
|
||||
if ($schema->hasTable('store_report_paid_sales_rows')
|
||||
&& $schema->hasColumn('store_report_paid_sales_rows', 'settlement_income')) {
|
||||
$schema->table('store_report_paid_sales_rows', function (Blueprint $table): void {
|
||||
$table->dropColumn('settlement_income');
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -30,21 +30,22 @@
|
||||
| 4 | 税务类型 | 主体税务类型,优先读取 `fin_companies.tax_type`,缺失时使用 `rpt.fys_companyInfo.taxCategoryAndType` |
|
||||
| 5 | 工商类型 | 主体工商类型,读取 `fin_companies.business_type`;仅“核定”和“个人独资企业”为有效值,其他统一显示 `/` |
|
||||
| 6 | 最近12个月累计收入 | 最近12个完整自然月收入合计,排除当前月 |
|
||||
| 7 | 1月收入 | 当前年份 1 月收入,当前月或无账单时为空 |
|
||||
| 8 | 2月收入 | 当前年份 2 月收入,当前月或无账单时为空 |
|
||||
| 9 | 3月收入 | 当前年份 3 月收入,当前月或无账单时为空 |
|
||||
| 10 | 4月收入 | 当前年份 4 月收入,当前月或无账单时为空 |
|
||||
| 11 | 5月收入 | 当前年份 5 月收入,当前月或无账单时为空 |
|
||||
| 12 | 6月收入 | 当前年份 6 月收入,当前月或无账单时为空 |
|
||||
| 13 | 7月收入 | 当前年份 7 月收入,当前月或无账单时为空 |
|
||||
| 14 | 8月收入 | 当前年份 8 月收入,当前月或无账单时为空 |
|
||||
| 15 | 9月收入 | 当前年份 9 月收入,当前月或无账单时为空 |
|
||||
| 16 | 10月收入 | 当前年份 10 月收入,当前月或无账单时为空 |
|
||||
| 17 | 11月收入 | 当前年份 11 月收入,当前月或无账单时为空 |
|
||||
| 18 | 12月收入 | 当前年份 12 月收入,当前月或无账单时为空 |
|
||||
| 19 | 能否变更主体 | 逻辑暂未提供,先留空/按统一缺失值规则展示 |
|
||||
| 20 | 规划 | 逻辑暂未提供,先留空/按统一缺失值规则展示 |
|
||||
| 21 | 新主体(变更流程同步新主体) | 逻辑暂未提供,先留空/按统一缺失值规则展示 |
|
||||
| 7 | 上月店铺结算收入-客服公司 | 按运行时上一个完整自然月动态命名,例如当前为 11 月时显示「10月店铺结算收入-客服公司」;金额取业绩明细 `store_receipt_order_match_rows.income_amount`,按店铺主体期间拆分后汇总到主体 |
|
||||
| 8 | 1月收入 | 当前年份 1 月收入,当前月或无账单时为空 |
|
||||
| 9 | 2月收入 | 当前年份 2 月收入,当前月或无账单时为空 |
|
||||
| 10 | 3月收入 | 当前年份 3 月收入,当前月或无账单时为空 |
|
||||
| 11 | 4月收入 | 当前年份 4 月收入,当前月或无账单时为空 |
|
||||
| 12 | 5月收入 | 当前年份 5 月收入,当前月或无账单时为空 |
|
||||
| 13 | 6月收入 | 当前年份 6 月收入,当前月或无账单时为空 |
|
||||
| 14 | 7月收入 | 当前年份 7 月收入,当前月或无账单时为空 |
|
||||
| 15 | 8月收入 | 当前年份 8 月收入,当前月或无账单时为空 |
|
||||
| 16 | 9月收入 | 当前年份 9 月收入,当前月或无账单时为空 |
|
||||
| 17 | 10月收入 | 当前年份 10 月收入,当前月或无账单时为空 |
|
||||
| 18 | 11月收入 | 当前年份 11 月收入,当前月或无账单时为空 |
|
||||
| 19 | 12月收入 | 当前年份 12 月收入,当前月或无账单时为空 |
|
||||
| 20 | 能否变更主体 | 逻辑暂未提供,先留空/按统一缺失值规则展示 |
|
||||
| 21 | 规划 | 逻辑暂未提供,先留空/按统一缺失值规则展示 |
|
||||
| 22 | 新主体(变更流程同步新主体) | 逻辑暂未提供,先留空/按统一缺失值规则展示 |
|
||||
|
||||
以下字段明确删除,不得出现在主体维度经营报表中:
|
||||
|
||||
@ -57,7 +58,7 @@
|
||||
- 连续12个月店铺累计收入(原“连续12个月店铺累计销量”)
|
||||
- 其他仅描述单个店铺的字段
|
||||
|
||||
“销量”在本报表中统一改为“收入”。所有收入数值均来自 SQLite `bills.income`,不以件数、利润或其他金额字段替代。
|
||||
“销量”在本报表中统一改为“收入”。原有最近 12 个月和 1–12 月收入均来自 SQLite `bills.income`,不以件数、利润或其他金额字段替代;新增「上月店铺结算收入-客服公司」单独使用业绩明细收入金额口径。
|
||||
|
||||
## 4. 数据来源和职责
|
||||
|
||||
@ -136,7 +137,7 @@ AND bills.occurred_at < expires_at
|
||||
|
||||
### 5.2 收入口径
|
||||
|
||||
所有收入指标严格使用:
|
||||
原有最近 12 个月累计收入及 1–12 月收入严格使用:
|
||||
|
||||
```sql
|
||||
SUM(bills.income)
|
||||
@ -150,6 +151,20 @@ SUM(bills.income)
|
||||
|
||||
不使用 `expense`,不计算利润、净收入或件数,不从 `rpt` 读取收入金额。
|
||||
|
||||
「上月店铺结算收入-客服公司」不使用上述 SQLite `bills.income`,而是取业绩明细:
|
||||
|
||||
```text
|
||||
store_receipt_order_match_rows.income_amount
|
||||
↓ 按 store_name + occurred_date 汇总
|
||||
store_report_paid_sales_rows.settlement_income
|
||||
↓ 按店铺主体生命周期区间拆分
|
||||
店铺/期间结算收入
|
||||
↓ 按主体名称 SUM
|
||||
主体上月店铺结算收入
|
||||
```
|
||||
|
||||
该列按运行时当前月的上一个完整自然月展示;例如当前为 2026 年 11 月,列名为「10月店铺结算收入-客服公司」。金额只取业绩明细「收入金额」,不叠加优惠、冲减、违约赔付或退款金额。
|
||||
|
||||
### 5.3 主体合并
|
||||
|
||||
先按店铺名称和生命周期切分账单,再按主体名称合并:
|
||||
@ -161,7 +176,7 @@ rpt 店铺入口
|
||||
↓ 按月 SUM
|
||||
店铺/生命周期月度收入
|
||||
↓ 按主体名称 SUM
|
||||
主体月度收入和主体滚动12个月收入
|
||||
主体月度收入、主体滚动12个月收入和主体上月店铺结算收入
|
||||
```
|
||||
|
||||
同一个主体名称在多个店铺、多个主体生命周期或多个平台出现时,全部合并为一行。
|
||||
|
||||
@ -15,7 +15,10 @@ use RuntimeException;
|
||||
* 期间由 StoreReportPeriodBuilder 按期初数据和爬虫变更生成:变更店铺的老主体
|
||||
* 失效时间为变更日前一天、新主体从变更日当天生效,收入按实际日期归集,不重复统计。
|
||||
*
|
||||
* 两列金额口径不同,页面分别展示:
|
||||
* 主体报表另增加「上月店铺结算收入」:
|
||||
* 业绩明细「收入金额」按「店铺名称 + 发生日期」预汇总,再按发生日期落到主体期间。
|
||||
*
|
||||
* 三列金额口径不同,页面分别展示:
|
||||
* 销量(period_sales / sales_NN):业绩明细(店铺收款匹配订单明细)的
|
||||
* 「收入金额 + 优惠金额 + 冲减金额 + 违约赔付(冲减收入) + 退款金额」合计,按「店铺名称 + 发生日期」
|
||||
* 预汇总到 store_report_paid_sales_rows,再按发生日期落到主体期间;
|
||||
@ -37,15 +40,20 @@ class StoreReportRepository
|
||||
public const PAID_SALES_SOURCE_TABLE = 'store_receipt_order_match_rows';
|
||||
|
||||
/**
|
||||
* 销量来源:收入+优惠+冲减+退款四项合计(按店铺 + 发生日期预汇总)。
|
||||
* 列名沿用历史命名 paid_amount,避免共享镜像表结构变更影响线上旧版本。
|
||||
* 业绩明细日汇总同时提供销量与店铺结算收入,页面一次查询取回两列。
|
||||
*
|
||||
* @var array{table:string,amount:string}
|
||||
* @var array{table:string,amounts:array<string,string>}
|
||||
*/
|
||||
private const SALES_SOURCE = ['table' => self::PAID_SALES_TABLE, 'amount' => 'paid_amount'];
|
||||
private const PERFORMANCE_DETAIL_SOURCE = [
|
||||
'table' => self::PAID_SALES_TABLE,
|
||||
'amounts' => ['sales' => 'paid_amount', 'settlement_income' => 'settlement_income'],
|
||||
];
|
||||
|
||||
/** @var array{table:string,amount:string} 收入来源:平台账单日汇总。 */
|
||||
private const INCOME_SOURCE = ['table' => 'store_report_daily_rows', 'amount' => 'income'];
|
||||
/** @var array{table:string,amounts:array<string,string>} 收入来源:平台账单日汇总。 */
|
||||
private const INCOME_SOURCE = [
|
||||
'table' => 'store_report_daily_rows',
|
||||
'amounts' => ['income' => 'income'],
|
||||
];
|
||||
|
||||
private const DEFAULT_EFFECTIVE_AT = '2026-07-01';
|
||||
private const DEFAULT_EXPIRES_AT = '2999-01-01';
|
||||
@ -127,12 +135,13 @@ class StoreReportRepository
|
||||
$singleNames[] = $name;
|
||||
}
|
||||
}
|
||||
$singleSales = $this->singlePeriodTotals($singleNames, $salesGeneration, self::SALES_SOURCE);
|
||||
$splitSales = $this->periodTotals($multiPeriod, $salesGeneration, self::SALES_SOURCE);
|
||||
$singlePerformanceDetails = $this->singlePeriodTotals($singleNames, $salesGeneration, self::PERFORMANCE_DETAIL_SOURCE);
|
||||
$splitPerformanceDetails = $this->periodTotals($multiPeriod, $salesGeneration, self::PERFORMANCE_DETAIL_SOURCE);
|
||||
$singleIncome = $this->singlePeriodTotals($singleNames, $dailyGeneration, self::INCOME_SOURCE);
|
||||
$splitIncome = $this->periodTotals($multiPeriod, $dailyGeneration, self::INCOME_SOURCE);
|
||||
$reportYear = $reportYear ?? (int) now()->format('Y');
|
||||
$currentMonth = now()->startOfMonth();
|
||||
$previousMonthKey = $currentMonth->copy()->subMonthNoOverflow()->format('Y-m');
|
||||
$rollingMonths = collect(range(12, 1))->map(
|
||||
static fn (int $monthsAgo): string => $currentMonth->copy()->subMonthsNoOverflow($monthsAgo)->format('Y-m'),
|
||||
)->all();
|
||||
@ -153,12 +162,15 @@ class StoreReportRepository
|
||||
$split = count($list) > 1;
|
||||
|
||||
foreach ($list as $index => $period) {
|
||||
$saleData = $split
|
||||
? ($splitSales[$storeName][$index] ?? ['period' => 0.0, 'months' => []])
|
||||
: ($singleSales[$storeName] ?? ['period' => 0.0, 'months' => []]);
|
||||
$incomeData = $split
|
||||
? ($splitIncome[$storeName][$index] ?? ['period' => 0.0, 'months' => []])
|
||||
: ($singleIncome[$storeName] ?? ['period' => 0.0, 'months' => []]);
|
||||
$performanceDetailData = $split
|
||||
? ($splitPerformanceDetails[$storeName][$index] ?? [])
|
||||
: ($singlePerformanceDetails[$storeName] ?? []);
|
||||
$saleData = $performanceDetailData['sales'] ?? ['period' => 0.0, 'months' => []];
|
||||
$incomeData = ($split
|
||||
? ($splitIncome[$storeName][$index] ?? [])
|
||||
: ($singleIncome[$storeName] ?? []))['income'] ?? ['period' => 0.0, 'months' => []];
|
||||
$settlementIncomeData = $performanceDetailData['settlement_income']
|
||||
?? ['period' => 0.0, 'months' => []];
|
||||
$monthly = [];
|
||||
$monthlyIncome = [];
|
||||
for ($month = 1; $month <= 12; $month++) {
|
||||
@ -190,6 +202,9 @@ class StoreReportRepository
|
||||
? ($expiresAt === self::DEFAULT_EXPIRES_AT ? '存续中' : $expiresAt)
|
||||
: '-',
|
||||
'period_sales' => (float) $saleData['period'],
|
||||
'previous_month_settlement_income' => array_key_exists($previousMonthKey, $settlementIncomeData['months'])
|
||||
? (float) $settlementIncomeData['months'][$previousMonthKey]
|
||||
: null,
|
||||
'rolling_12m_income' => array_intersect($rollingMonths, array_keys($incomeData['months'])) === []
|
||||
? null
|
||||
: $rollingSales,
|
||||
@ -253,8 +268,8 @@ class StoreReportRepository
|
||||
* 多期间店铺按每个期间的主体生效日、失效日(含当天)拆分金额。
|
||||
*
|
||||
* @param array<string,list<array<string,mixed>>> $periodsByStore
|
||||
* @param array{table:string,amount:string} $source 金额来源表与金额列(表名、列名来自类常量,不接受外部输入)
|
||||
* @return array<string,array<int,array{period:float,months:array<string,float>}>>
|
||||
* @param array{table:string,amounts:array<string,string>} $source 金额来源表与金额列(表名、列名来自类常量,不接受外部输入)
|
||||
* @return array<string,array<int,array<string,array{period:float,months:array<string,float>}>>>
|
||||
*/
|
||||
private function periodTotals(array $periodsByStore, string $generation, array $source): array
|
||||
{
|
||||
@ -274,7 +289,7 @@ class StoreReportRepository
|
||||
? "substr(d.occurred_on, 1, 7)"
|
||||
: "DATE_FORMAT(d.occurred_on, '%Y-%m')";
|
||||
$table = $source['table'];
|
||||
$amount = $source['amount'];
|
||||
$amountSelect = $this->amountSelect('d', $source['amounts']);
|
||||
$collected = [];
|
||||
foreach (array_chunk($flat, 200) as $chunk) {
|
||||
$selects = [];
|
||||
@ -284,8 +299,7 @@ class StoreReportRepository
|
||||
array_push($bindings, $row['key'], $row['store'], $row['effective_at'], $row['expires_at']);
|
||||
}
|
||||
$rows = $this->select(
|
||||
"SELECT p.period_key, {$month} AS bill_month,
|
||||
SUM(COALESCE(d.{$amount}, 0)) AS amount_total
|
||||
"SELECT p.period_key, {$month} AS bill_month, {$amountSelect}
|
||||
FROM (" . implode(' UNION ALL ', $selects) . ") AS p
|
||||
INNER JOIN {$table} AS d
|
||||
ON d.store_name = p.store_name
|
||||
@ -295,13 +309,13 @@ class StoreReportRepository
|
||||
GROUP BY p.period_key, {$month}",
|
||||
[...$bindings, $generation],
|
||||
);
|
||||
$this->collectTotals($collected, $rows, 'period_key');
|
||||
$this->collectTotals($collected, $rows, 'period_key', array_keys($source['amounts']));
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($collected as $key => $sales) {
|
||||
foreach ($collected as $key => $amounts) {
|
||||
[$store, $index] = explode("\x1f", (string) $key, 2) + [1 => '0'];
|
||||
$result[$store][(int) $index] = $sales;
|
||||
$result[$store][(int) $index] = $amounts;
|
||||
}
|
||||
|
||||
return $result;
|
||||
@ -311,8 +325,8 @@ class StoreReportRepository
|
||||
* 单期间店铺的金额按月汇总;生效、失效时间用统一的默认窗口兜底。
|
||||
*
|
||||
* @param list<string> $names
|
||||
* @param array{table:string,amount:string} $source
|
||||
* @return array<string,array{period:float,months:array<string,float>}>
|
||||
* @param array{table:string,amounts:array<string,string>} $source
|
||||
* @return array<string,array<string,array{period:float,months:array<string,float>}>>
|
||||
*/
|
||||
private function singlePeriodTotals(array $names, string $generation, array $source): array
|
||||
{
|
||||
@ -324,32 +338,53 @@ class StoreReportRepository
|
||||
? "substr(occurred_on, 1, 7)"
|
||||
: "DATE_FORMAT(occurred_on, '%Y-%m')";
|
||||
$table = $source['table'];
|
||||
$amount = $source['amount'];
|
||||
$amountSelect = $this->amountSelect('', $source['amounts']);
|
||||
$result = [];
|
||||
foreach ($this->nameChunks($names) as $chunk) {
|
||||
$placeholders = implode(',', array_fill(0, count($chunk), '?'));
|
||||
$rows = $this->select(
|
||||
"SELECT store_name, {$month} AS bill_month,
|
||||
SUM(COALESCE({$amount}, 0)) AS amount_total
|
||||
"SELECT store_name, {$month} AS bill_month, {$amountSelect}
|
||||
FROM {$table}
|
||||
WHERE generation = ? AND store_name IN ($placeholders)
|
||||
AND occurred_on >= ? AND occurred_on < ?
|
||||
GROUP BY store_name, {$month}",
|
||||
[$generation, ...$chunk, self::DEFAULT_EFFECTIVE_AT, self::DEFAULT_EXPIRES_AT],
|
||||
);
|
||||
$this->collectTotals($result, $rows, 'store_name');
|
||||
$this->collectTotals($result, $rows, 'store_name', array_keys($source['amounts']));
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** @param array<string,array{period:float,months:array<string,float>}> $result */
|
||||
private function collectTotals(array &$result, array $rows, string $keyColumn): void
|
||||
/** @param array<string,string> $amounts */
|
||||
private function amountSelect(string $alias, array $amounts): string
|
||||
{
|
||||
$prefix = $alias === '' ? '' : $alias . '.';
|
||||
|
||||
return implode(', ', array_map(
|
||||
static fn (string $column, string $key): string => "SUM({$prefix}{$column}) AS amount_{$key}",
|
||||
$amounts,
|
||||
array_keys($amounts),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,array<string,array{period:float,months:array<string,float>}>> $result
|
||||
* @param list<string> $amountNames
|
||||
*/
|
||||
private function collectTotals(array &$result, array $rows, string $keyColumn, array $amountNames): void
|
||||
{
|
||||
foreach ($rows as $row) {
|
||||
$key = (string) $row[$keyColumn];
|
||||
$result[$key]['period'] = ($result[$key]['period'] ?? 0.0) + (float) $row['amount_total'];
|
||||
$result[$key]['months'][(string) $row['bill_month']] = ($result[$key]['months'][(string) $row['bill_month']] ?? 0.0) + (float) $row['amount_total'];
|
||||
foreach ($amountNames as $name) {
|
||||
$value = $row['amount_' . $name] ?? null;
|
||||
if ($value === null) {
|
||||
continue;
|
||||
}
|
||||
$result[$key][$name]['period'] = ($result[$key][$name]['period'] ?? 0.0) + (float) $value;
|
||||
$result[$key][$name]['months'][(string) $row['bill_month']] =
|
||||
($result[$key][$name]['months'][(string) $row['bill_month']] ?? 0.0) + (float) $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -84,6 +84,13 @@ class StoreReportLogic
|
||||
'source' => 'store_receipt_order_match_rows → store_report_paid_sales_rows',
|
||||
'priority' => '与业绩明细同口径',
|
||||
],
|
||||
[
|
||||
'code' => 'R10',
|
||||
'object' => '上月店铺结算收入',
|
||||
'logic' => '主体维度经营报表按运行时上一个完整自然月展示「N月店铺结算收入-客服公司」;金额只取业绩明细「收入金额」,按店铺和发生日期汇总后,再按现有主体生效/失效区间拆分并汇总到主体。',
|
||||
'source' => 'store_receipt_order_match_rows.income_amount → store_report_paid_sales_rows.settlement_income',
|
||||
'priority' => '与销量分开统计',
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@ -447,9 +447,9 @@ class StoreReportMirrorSynchronizer
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺维度报表的「销量」:把业绩明细的
|
||||
* 店铺维度报表的「销量」与「店铺结算收入」:把业绩明细的
|
||||
* 「收入金额 + 优惠金额 + 冲减金额 + 违约赔付(冲减收入) + 退款金额」
|
||||
* 按「店铺名称 + 发生日期」预汇总。
|
||||
* 及单独的「收入金额」按「店铺名称 + 发生日期」预汇总。
|
||||
*
|
||||
* 业绩明细由 store-receipt:order-match:sync 按「账期 + 平台」整体重写,这里用
|
||||
* 「行数 + 最近写入时间 + 金额合计」的指纹判断是否变化:没变化就复用当前版本,
|
||||
@ -500,11 +500,11 @@ class StoreReportMirrorSynchronizer
|
||||
$generation = (string) Str::uuid();
|
||||
$this->connection->statement(
|
||||
'INSERT INTO ' . StoreReportRepository::PAID_SALES_TABLE
|
||||
. ' (generation, store_name, occurred_on, paid_amount, order_count, updated_at)'
|
||||
. ' (generation, store_name, occurred_on, paid_amount, settlement_income, order_count, updated_at)'
|
||||
. ' SELECT ?, store_name, occurred_date,'
|
||||
. ' SUM(COALESCE(income_amount, 0) + COALESCE(discount_amount, 0)'
|
||||
. ' + COALESCE(offset_amount, 0) + COALESCE(default_compensation_amount, 0)'
|
||||
. ' + COALESCE(refund_amount, 0)), COUNT(*), ?'
|
||||
. ' + COALESCE(refund_amount, 0)), SUM(income_amount), COUNT(*), ?'
|
||||
. ' FROM ' . StoreReportRepository::PAID_SALES_SOURCE_TABLE
|
||||
. " WHERE store_name IS NOT NULL AND store_name <> '' AND occurred_date IS NOT NULL"
|
||||
. ' GROUP BY store_name, occurred_date',
|
||||
@ -567,11 +567,11 @@ class StoreReportMirrorSynchronizer
|
||||
->where('generation', $generation)->whereIn('occurred_on', $dates)->delete();
|
||||
$this->connection->statement(
|
||||
'INSERT INTO ' . StoreReportRepository::PAID_SALES_TABLE
|
||||
. ' (generation, store_name, occurred_on, paid_amount, order_count, updated_at)'
|
||||
. ' (generation, store_name, occurred_on, paid_amount, settlement_income, order_count, updated_at)'
|
||||
. ' SELECT ?, store_name, occurred_date,'
|
||||
. ' SUM(COALESCE(income_amount, 0) + COALESCE(discount_amount, 0)'
|
||||
. ' + COALESCE(offset_amount, 0) + COALESCE(default_compensation_amount, 0)'
|
||||
. ' + COALESCE(refund_amount, 0)), COUNT(*), ?'
|
||||
. ' + COALESCE(refund_amount, 0)), SUM(income_amount), COUNT(*), ?'
|
||||
. ' FROM ' . StoreReportRepository::PAID_SALES_SOURCE_TABLE
|
||||
. " WHERE store_name IS NOT NULL AND store_name <> '' AND occurred_date IN ("
|
||||
. implode(',', array_fill(0, count($dates), '?')) . ') GROUP BY store_name, occurred_date',
|
||||
@ -590,14 +590,15 @@ class StoreReportMirrorSynchronizer
|
||||
});
|
||||
}
|
||||
|
||||
/** 业绩明细是否变化的指纹:行数 + 最近写入时间 + 销量口径四项金额合计。 */
|
||||
/** 业绩明细是否变化的指纹:行数 + 最近写入时间 + 销量合计 + 收入金额合计。 */
|
||||
private function paidSalesFingerprint(): string
|
||||
{
|
||||
$row = $this->connection->selectOne(
|
||||
'SELECT COUNT(*) AS rows_total, MAX(imported_at) AS last_imported_at,'
|
||||
. ' COALESCE(SUM(COALESCE(income_amount, 0) + COALESCE(discount_amount, 0)'
|
||||
. ' + COALESCE(offset_amount, 0) + COALESCE(default_compensation_amount, 0)'
|
||||
. ' + COALESCE(refund_amount, 0)), 0) AS sales_total'
|
||||
. ' + COALESCE(refund_amount, 0)), 0) AS sales_total,'
|
||||
. ' COALESCE(SUM(income_amount), 0) AS settlement_income_total'
|
||||
. ' FROM ' . StoreReportRepository::PAID_SALES_SOURCE_TABLE,
|
||||
);
|
||||
|
||||
@ -605,6 +606,7 @@ class StoreReportMirrorSynchronizer
|
||||
(string) ($row->rows_total ?? 0),
|
||||
(string) ($row->last_imported_at ?? ''),
|
||||
(string) ($row->sales_total ?? '0'),
|
||||
(string) ($row->settlement_income_total ?? '0'),
|
||||
]));
|
||||
}
|
||||
|
||||
|
||||
@ -11,7 +11,7 @@ use Modules\EcommerceFinance\Repositories\StoreReportRepository;
|
||||
class StoreReportPaidSalesChanges
|
||||
{
|
||||
public const TABLE = 'store_report_paid_sales_dirty_dates';
|
||||
public const VERSION = 'dates:v1:';
|
||||
public const VERSION = 'dates:v2-settlement-income:';
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct(DatabaseManager $database)
|
||||
|
||||
@ -65,6 +65,19 @@
|
||||
return $field;
|
||||
})->values()->all();
|
||||
}
|
||||
if ($directoryPageKey === 'company-management/subject-operating-report') {
|
||||
$previousSettlementMonthLabel = now()
|
||||
->startOfMonth()
|
||||
->subMonthNoOverflow()
|
||||
->format('n');
|
||||
$directoryFields = collect($directoryFields)->map(function (array $field) use ($previousSettlementMonthLabel): array {
|
||||
if (($field['name'] ?? null) === 'previous_month_settlement_income') {
|
||||
$field['label'] = $previousSettlementMonthLabel . '月店铺结算收入-客服公司';
|
||||
}
|
||||
|
||||
return $field;
|
||||
})->values()->all();
|
||||
}
|
||||
$directoryStatusCountData = request()->attributes->get('directory.status-counts');
|
||||
$directoryStatusCountData = is_array($directoryStatusCountData) ? $directoryStatusCountData : [];
|
||||
$directoryStatusCountFields = collect($directoryStatusCountData['fields'] ?? [])
|
||||
@ -1723,7 +1736,7 @@
|
||||
data-directory-user="{{ auth()->id() ?? 'guest' }}"
|
||||
data-directory-section="{{ $section['slug'] ?? '' }}"
|
||||
data-directory-tab="{{ $activeTab['slug'] ?? '' }}"
|
||||
data-directory-column-preference-version="{{ in_array($directoryPageKey, ['company-management/subject-operating-report', 'store-management/store-report'], true) ? 'empty-month-columns-v1' : '' }}"
|
||||
data-directory-column-preference-version="{{ $directoryPageKey === 'company-management/subject-operating-report' ? 'subject-settlement-income-v1' : ($directoryPageKey === 'store-management/store-report' ? 'empty-month-columns-v1' : '') }}"
|
||||
aria-label="{{ $page['title'] ?? $section['title'] }}"
|
||||
>
|
||||
@if ($directoryUsesFieldQuery)
|
||||
|
||||
@ -110,7 +110,7 @@ class PrototypePageTest extends FeatureTestCase
|
||||
]))
|
||||
->keyBy('key');
|
||||
$expectedFieldCounts = [
|
||||
'company-management/subject-operating-report' => 21,
|
||||
'company-management/subject-operating-report' => 22,
|
||||
'company-management/company-cost-arrangement' => 10,
|
||||
'company-management/tax-forecast' => 21,
|
||||
'company-management/company-plan' => 13,
|
||||
@ -158,6 +158,7 @@ class PrototypePageTest extends FeatureTestCase
|
||||
|
||||
public function testSubjectOperatingReportReadsSharedStoreReportRows(): void
|
||||
{
|
||||
Carbon::setTestNow('2026-11-11 10:00:00');
|
||||
$service = Mockery::mock(UpstreamBusinessInformation::class);
|
||||
$service->shouldReceive('paginate')->once()->with('company-management', 'subject-operating-report', 50)
|
||||
->andReturnUsing(function (): LengthAwarePaginator {
|
||||
@ -196,6 +197,7 @@ class PrototypePageTest extends FeatureTestCase
|
||||
'tax_type' => '小规模纳税人',
|
||||
'business_registration_type' => '个人独资企业',
|
||||
'rolling_12m_income' => 100,
|
||||
'previous_month_settlement_income' => 88,
|
||||
'can_change_entity' => null,
|
||||
'plan' => null,
|
||||
'new_entity' => null,
|
||||
@ -212,6 +214,7 @@ class PrototypePageTest extends FeatureTestCase
|
||||
->assertOk()
|
||||
->assertSeeText('收入汇总')
|
||||
->assertSeeTextInOrder(['公司类型', '税务类型', '工商类型', '最近12个月累计收入'])
|
||||
->assertSeeText('10月店铺结算收入-客服公司')
|
||||
->assertSeeText('测试主体')
|
||||
->assertSeeText('小规模纳税人')
|
||||
->assertSeeText('个人独资企业')
|
||||
@ -246,20 +249,20 @@ class PrototypePageTest extends FeatureTestCase
|
||||
|
||||
$augustResponse
|
||||
->assertOk()
|
||||
->assertSeeTextInOrder(['最近12个月累计收入', '1月收入', '12月收入'])
|
||||
->assertSeeTextInOrder(['最近12个月累计收入', '7月店铺结算收入-客服公司', '1月收入', '12月收入'])
|
||||
->assertDontSeeText('ERP系统店铺名称')
|
||||
->assertDontSeeText('连续12个月店铺累计收入');
|
||||
|
||||
Carbon::setTestNow('2027-01-01 00:00:00');
|
||||
|
||||
$septemberResponse = $this->get(route('business.pages.show', [
|
||||
$septemberResponse = $this->loginAs()->get(route('business.pages.show', [
|
||||
'section' => 'company-management',
|
||||
'page' => 'subject-operating-report',
|
||||
]));
|
||||
|
||||
$septemberResponse
|
||||
->assertOk()
|
||||
->assertSeeTextInOrder(['最近12个月累计收入', '1月收入', '12月收入']);
|
||||
->assertSeeTextInOrder(['最近12个月累计收入', '12月店铺结算收入-客服公司', '1月收入', '12月收入']);
|
||||
}
|
||||
|
||||
public function testSubjectOperatingReportHidesMonthsWithoutDataAndKeepsThemSelectable(): void
|
||||
@ -302,8 +305,8 @@ class PrototypePageTest extends FeatureTestCase
|
||||
$this->assertStringContainsString('value="income_01" data-directory-query-column', $html);
|
||||
$this->assertStringNotContainsString('value="income_01" data-directory-query-column checked', $html);
|
||||
$this->assertStringContainsString('value="income_03" data-directory-query-column checked', $html);
|
||||
$this->assertStringContainsString('筛选字段 19/21', $html);
|
||||
$this->assertStringContainsString('data-directory-column-preference-version="empty-month-columns-v1"', $html);
|
||||
$this->assertStringContainsString('筛选字段 20/22', $html);
|
||||
$this->assertStringContainsString('data-directory-column-preference-version="subject-settlement-income-v1"', $html);
|
||||
|
||||
// 手动勾选(columns 参数)后,对应月份列恢复显示。
|
||||
$restored = $this->get(route('business.pages.show', [
|
||||
|
||||
@ -246,7 +246,7 @@ class StoreReportMirrorSyncTest extends TestCase
|
||||
$this->assertTrue($first['paid_sales']['changed']);
|
||||
$this->assertDatabaseHas('store_report_paid_sales_rows', [
|
||||
'generation' => $generation, 'store_name' => '店铺A', 'occurred_on' => '2026-08-02',
|
||||
'paid_amount' => 110, 'order_count' => 2,
|
||||
'paid_amount' => 110, 'settlement_income' => 110, 'order_count' => 2,
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('store_report_paid_sales_rows', [
|
||||
'generation' => $generation, 'store_name' => '店铺B', 'occurred_on' => '2026-08-03',
|
||||
@ -254,7 +254,7 @@ class StoreReportMirrorSyncTest extends TestCase
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('store_report_paid_sales_rows', [
|
||||
'generation' => $generation, 'store_name' => '店铺C', 'occurred_on' => '2026-08-04',
|
||||
'paid_amount' => 85, 'order_count' => 1,
|
||||
'paid_amount' => 85, 'settlement_income' => 100, 'order_count' => 1,
|
||||
], 'business_mirror');
|
||||
$this->assertSame(4, $mirror->table('store_report_paid_sales_rows')->count());
|
||||
$this->assertDatabaseHas('store_report_import_states', [
|
||||
@ -383,6 +383,7 @@ class StoreReportMirrorSyncTest extends TestCase
|
||||
$table->string('store_name');
|
||||
$table->date('occurred_on');
|
||||
$table->decimal('paid_amount', 20, 4)->default(0);
|
||||
$table->decimal('settlement_income', 20, 4)->nullable();
|
||||
$table->unsignedInteger('order_count')->default(0);
|
||||
$table->dateTime('updated_at')->nullable();
|
||||
$table->unique(['generation', 'store_name', 'occurred_on']);
|
||||
|
||||
@ -26,6 +26,7 @@ class StoreReportPaidSalesIncrementalTest extends TestCase
|
||||
$table->timestamp('initial_completed_at')->nullable();
|
||||
});
|
||||
(require base_path('database/migrations/2026_10_16_234000_create_store_report_paid_sales_rows.php'))->up();
|
||||
(require base_path('database/migrations/2026_11_11_130000_add_settlement_income_to_store_report_paid_sales_rows.php'))->up();
|
||||
$schema->create('store_receipt_order_match_rows', function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('platform');
|
||||
@ -54,6 +55,7 @@ class StoreReportPaidSalesIncrementalTest extends TestCase
|
||||
$db->table('store_receipt_order_match_rows')->where('id', 1)->update(['income_amount' => 120]);
|
||||
$this->assertTrue($sync->syncPaidSales()['changed']);
|
||||
$this->assertSame(118.0, (float) $db->table('store_report_paid_sales_rows')->where('occurred_on', '2026-10-01')->value('paid_amount'));
|
||||
$this->assertSame(140.0, (float) $db->table('store_report_paid_sales_rows')->where('occurred_on', '2026-10-01')->value('settlement_income'));
|
||||
$this->assertSame($untouchedId, $db->table('store_report_paid_sales_rows')->where('occurred_on', '2026-09-30')->value('id'));
|
||||
$db->enableQueryLog();
|
||||
$this->assertFalse($sync->syncPaidSales()['changed']);
|
||||
|
||||
@ -63,6 +63,7 @@ class StoreReportRepositoryTest extends TestCase
|
||||
$table->string('store_name');
|
||||
$table->date('occurred_on');
|
||||
$table->decimal('paid_amount', 20, 4)->default(0);
|
||||
$table->decimal('settlement_income', 20, 4)->nullable();
|
||||
$table->unsignedInteger('order_count')->default(0);
|
||||
});
|
||||
$schema->create('ops_fys_shop_info', function (Blueprint $table): void {
|
||||
@ -143,6 +144,28 @@ class StoreReportRepositoryTest extends TestCase
|
||||
$this->assertCount(0, $this->repository->rows([['erp_store_name' => '店铺A']], 2026, ['sales_07' => '130']));
|
||||
}
|
||||
|
||||
public function test_previous_month_settlement_income_uses_income_amount_and_store_periods(): void
|
||||
{
|
||||
Carbon::setTestNow('2026-11-01 10:00:00');
|
||||
config(['store_report_initial_periods.shops' => [
|
||||
'店铺A' => [
|
||||
'previous_company' => '主体甲',
|
||||
'company' => '主体乙',
|
||||
'changed_at' => '2026-10-16',
|
||||
],
|
||||
]]);
|
||||
$this->insertSales('店铺A', '2026-10-15', 81, 11.25);
|
||||
$this->insertSales('店铺A', '2026-10-16', 92, 22.5);
|
||||
|
||||
$rows = $this->repository->rows([
|
||||
['erp_store_name' => '店铺A', 'store_name' => '前台店铺A', 'company_name' => '主体乙', 'store_status' => '0'],
|
||||
], 2026);
|
||||
|
||||
$this->assertSame(['主体甲', '主体乙'], array_column($rows, 'entity'));
|
||||
$this->assertSame([11.25, 22.5], array_column($rows, 'previous_month_settlement_income'));
|
||||
$this->assertSame([81.0, 92.0], array_column($rows, 'sales_10'));
|
||||
}
|
||||
|
||||
public function test_store_name_sort_is_accepted_and_applied(): void
|
||||
{
|
||||
request()->merge(['sort' => 'store_name', 'direction' => 'asc']);
|
||||
@ -229,7 +252,7 @@ class StoreReportRepositoryTest extends TestCase
|
||||
// 同一店铺同一天:账单收入 100,业绩明细四项金额合计 88 —— 销量取合计、收入取账单。
|
||||
$this->insertIncome('店铺A', '2026-07-05', 100);
|
||||
$this->insertSales('店铺A', '2026-07-05', 88);
|
||||
$this->insertSales('店铺A', '2026-08-03', 5);
|
||||
$this->insertSales('店铺A', '2026-08-03', 5, 7);
|
||||
|
||||
$rows = $this->repository->rows([
|
||||
['erp_store_name' => '店铺A', 'company_name' => '主体甲', 'store_status' => '0'],
|
||||
@ -239,6 +262,7 @@ class StoreReportRepositoryTest extends TestCase
|
||||
$this->assertSame(93.0, $rows[0]['period_sales']);
|
||||
$this->assertSame(88.0, $rows[0]['sales_07']);
|
||||
$this->assertSame(5.0, $rows[0]['sales_08']);
|
||||
$this->assertSame(7.0, $rows[0]['previous_month_settlement_income']);
|
||||
$this->assertSame(100.0, (float) $rows[0]['income_07']);
|
||||
$this->assertSame(100.0, (float) $rows[0]['rolling_12m_income']);
|
||||
}
|
||||
@ -362,7 +386,7 @@ class StoreReportRepositoryTest extends TestCase
|
||||
$this->insertBill('店铺B', '2026-08-11', 40);
|
||||
$mirror = Mockery::mock(BusinessInformationMirrorRepository::class);
|
||||
$mirror->shouldReceive('ready')->with('store-information.read')->andReturnTrue();
|
||||
$mirror->shouldReceive('allStores')->times(7)->andReturn([
|
||||
$mirror->shouldReceive('allStores')->times(9)->andReturn([
|
||||
['erp_store_name' => '店铺A', 'company_name' => '主体甲', 'store_status' => '0'],
|
||||
['erp_store_name' => '店铺B', 'company_name' => '主体甲', 'store_status' => '0'],
|
||||
]);
|
||||
@ -397,6 +421,7 @@ class StoreReportRepositoryTest extends TestCase
|
||||
$this->assertCount(1, $rows);
|
||||
$this->assertSame('主体甲', $rows[0]->entity);
|
||||
$this->assertSame(90.0, $rows[0]->rolling_12m_income);
|
||||
$this->assertSame(70.0, $rows[0]->previous_month_settlement_income);
|
||||
$this->assertSame(20.0, $rows[0]->income_07);
|
||||
$this->assertSame(70.0, $rows[0]->income_08);
|
||||
$this->assertSame('小规模纳税人', $rows[0]->tax_type);
|
||||
@ -411,6 +436,11 @@ class StoreReportRepositoryTest extends TestCase
|
||||
|
||||
request()->merge(['income_08' => '70.00']);
|
||||
$this->assertSame(1, $service->paginate('company-management', 'subject-operating-report', 50)->total());
|
||||
request()->merge(['income_08' => null, 'previous_month_settlement_income' => '70.00']);
|
||||
$this->assertSame(1, $service->paginate('company-management', 'subject-operating-report', 50)->total());
|
||||
request()->merge(['previous_month_settlement_income' => '70.01']);
|
||||
$this->assertSame(0, $service->paginate('company-management', 'subject-operating-report', 50)->total());
|
||||
request()->merge(['previous_month_settlement_income' => null]);
|
||||
request()->merge(['company_status' => '正常']);
|
||||
$this->assertSame(1, $service->paginate('company-management', 'subject-operating-report', 50)->total());
|
||||
request()->merge(['company_status' => '已注销']);
|
||||
@ -549,13 +579,19 @@ class StoreReportRepositoryTest extends TestCase
|
||||
}
|
||||
|
||||
/** 业绩明细「收入+优惠+冲减+退款金额」按店铺 + 发生日期的预汇总行。 */
|
||||
private function insertSales(string $store, string $occurredOn, float $amount): void
|
||||
private function insertSales(
|
||||
string $store,
|
||||
string $occurredOn,
|
||||
float $amount,
|
||||
?float $settlementIncome = null,
|
||||
): void
|
||||
{
|
||||
DB::connection('business_mirror')->table('store_report_paid_sales_rows')->insert([
|
||||
'generation' => $this->paidGeneration,
|
||||
'store_name' => $store,
|
||||
'occurred_on' => $occurredOn,
|
||||
'paid_amount' => $amount,
|
||||
'settlement_income' => $settlementIncome ?? $amount,
|
||||
'order_count' => 1,
|
||||
]);
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user