From f7daee930582c468c0c86f2767adfb5361648863 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Fri, 16 Oct 2026 23:50:25 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=BA=97=E9=93=BA=E7=BB=B4=E5=BA=A6?= =?UTF-8?q?=E6=8A=A5=E8=A1=A8=E9=94=80=E9=87=8F=E6=94=B9=E5=8F=96=E4=B8=9A?= =?UTF-8?q?=E7=BB=A9=E6=98=8E=E7=BB=86=E7=9A=84=E8=AE=A2=E5=8D=95=E5=AE=9E?= =?UTF-8?q?=E4=BB=98/=E5=AE=9E=E6=94=B6=E9=87=91=E9=A2=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 店铺维度报表(店铺管理 → 店铺维度报表)的销量原来按平台账单收入汇总,改为按 业绩明细(店铺收款匹配订单明细)的「订单实付/实收金额」汇总: - 新增镜像表 store_report_paid_sales_rows:业绩明细按「店铺名称 + 发生时间」 预汇总,页面按发生日期与主体生效/失效时间关联,拆分到对应主体期间; - StoreReportRepository 的销量(period_sales / sales_NN)改读该汇总表, 收入(rolling_12m_income / income_NN,主体维度经营报表用)仍读平台账单日汇总, 两个口径分开统计、互不覆盖; - StoreReportMirrorSynchronizer 增加 syncPaidSales():用「行数 + 最近写入时间 + 订单实付合计」指纹判断业绩明细是否变化,变化才全量重建,未变化沿用当前版本; - 新增命令 business-mirror:sync-store-report-paid-sales(含 --force),并在 store-receipt:order-match:sync 成功后自动刷新一次。 验证:StoreReportRepositoryTest / StoreReportRepositoryFilterTest / StoreReportMirrorSyncTest 共 23 个用例、110 个断言通过。 --- .../Commands/SyncStoreReceiptOrderMatches.php | 33 +++++++ .../Commands/SyncStoreReportMirror.php | 4 +- .../Commands/SyncStoreReportPaidSales.php | 50 ++++++++++ config/business_data.php | 5 + config/business_navigation.php | 2 +- ...00_create_store_report_paid_sales_rows.php | 62 ++++++++++++ .../Repositories/StoreReportRepository.php | 83 +++++++++++----- .../Services/StoreReportLogic.php | 13 ++- .../StoreReportMirrorSynchronizer.php | 99 +++++++++++++++++++ .../Console/StoreReportMirrorSyncTest.php | 81 +++++++++++++++ .../StoreReportRepositoryFilterTest.php | 10 ++ .../StoreReportRepositoryTest.php | 62 ++++++++++++ 12 files changed, 477 insertions(+), 27 deletions(-) create mode 100644 app/Console/Commands/SyncStoreReportPaidSales.php create mode 100644 database/migrations/2026_10_16_234000_create_store_report_paid_sales_rows.php diff --git a/app/Console/Commands/SyncStoreReceiptOrderMatches.php b/app/Console/Commands/SyncStoreReceiptOrderMatches.php index 5cb1f72b..3446373e 100644 --- a/app/Console/Commands/SyncStoreReceiptOrderMatches.php +++ b/app/Console/Commands/SyncStoreReceiptOrderMatches.php @@ -11,6 +11,7 @@ use App\Business\JstOrderLabelPlantingRules; use Modules\EcommerceFinance\Services\AccountLedgerRemarkMap; use Modules\EcommerceFinance\Services\AccountMappingStore; use Modules\EcommerceFinance\Services\LedgerRemarkFilter; +use Modules\EcommerceFinance\Services\StoreReportMirrorSynchronizer; use Throwable; /** @@ -910,9 +911,41 @@ class SyncStoreReceiptOrderMatches extends Command return self::FAILURE; } + // 业绩明细变了,顺手刷新店铺维度报表的销量汇总(销量=这里的订单实付/实收金额)。 + // 汇总失败不影响业绩明细本身,只提示一次,避免把已写入的账期数据判成失败。 + if (! (bool) $this->option('dry-run')) { + $this->refreshStoreReportPaidSales(); + } + return self::SUCCESS; } + /** 按最新业绩明细重建店铺维度报表的销量汇总(失败只提示,不中断)。 */ + private function refreshStoreReportPaidSales(): void + { + try { + $result = app(StoreReportMirrorSynchronizer::class)->syncPaidSales(); + } catch (Throwable $exception) { + $this->warn('店铺维度报表销量汇总刷新失败:' . $exception->getMessage()); + + return; + } + + if ($result['status'] === 'skipped') { + return; + } + + if ($result['status'] !== 'succeeded') { + $this->warn('店铺维度报表销量汇总刷新失败(可在界面稍后再试或联系开发排查)。'); + + return; + } + + $this->line($result['changed'] + ? sprintf(' 店铺维度报表销量汇总:已重建 %d 行。', $result['stored_rows']) + : sprintf(' 店铺维度报表销量汇总:业绩明细无变化,沿用 %d 行。', $result['stored_rows'])); + } + /** * 只回填「种菜金额」:不读账单,直接按业绩明细里已有的「订单号」判断是不是种菜订单, diff --git a/app/Console/Commands/SyncStoreReportMirror.php b/app/Console/Commands/SyncStoreReportMirror.php index ba82fb3a..fdbe45d1 100644 --- a/app/Console/Commands/SyncStoreReportMirror.php +++ b/app/Console/Commands/SyncStoreReportMirror.php @@ -38,7 +38,7 @@ class SyncStoreReportMirror extends Command } $this->info(sprintf( - '店铺报表镜像:流程期间 %s/%d 行,主体变更 %s(检查 %d 店,新增 %d 条),账单 %s/%d 行,日汇总 %s/%d 行。', + '店铺报表镜像:流程期间 %s/%d 行,主体变更 %s(检查 %d 店,新增 %d 条),账单 %s/%d 行,日汇总 %s/%d 行,销量汇总 %s/%d 行。', $result['lifecycles']['status'], $result['lifecycles']['source_rows'], $result['period_changes']['status'], @@ -48,6 +48,8 @@ class SyncStoreReportMirror extends Command $result['bills']['source_rows'], $result['daily']['status'], $result['daily']['source_rows'], + $result['paid_sales']['status'], + $result['paid_sales']['stored_rows'], )); return self::SUCCESS; diff --git a/app/Console/Commands/SyncStoreReportPaidSales.php b/app/Console/Commands/SyncStoreReportPaidSales.php new file mode 100644 index 00000000..7dd68029 --- /dev/null +++ b/app/Console/Commands/SyncStoreReportPaidSales.php @@ -0,0 +1,50 @@ +syncPaidSales((bool) $this->option('force')); + } catch (Throwable $exception) { + $this->error('店铺维度报表销量汇总失败:' . $exception->getMessage()); + + return self::FAILURE; + } + + if ($result['status'] === 'skipped') { + $this->warn('镜像里还没有业绩明细表,销量汇总未执行。'); + + return self::SUCCESS; + } + + if ($result['status'] !== 'succeeded') { + $this->error('店铺维度报表销量汇总失败,页面继续读取上一版数据。'); + + return self::FAILURE; + } + + $this->info($result['changed'] + ? sprintf('销量汇总已重建:业绩明细 %d 行 → 汇总 %d 行。', $result['source_rows'], $result['stored_rows']) + : sprintf('业绩明细没有变化,沿用当前销量汇总(%d 行)。', $result['stored_rows'])); + + return self::SUCCESS; + } +} diff --git a/config/business_data.php b/config/business_data.php index da05a165..f0145a54 100644 --- a/config/business_data.php +++ b/config/business_data.php @@ -177,5 +177,10 @@ return [ 'target_store' => 'mariadb', 'consumer' => '店铺经营报表', ], + 'store_report_paid_sales_rows' => [ + 'role' => 'aggregate', + 'target_store' => 'mariadb', + 'consumer' => '店铺维度报表销量(业绩明细订单实付/实收金额)', + ], ], ]; diff --git a/config/business_navigation.php b/config/business_navigation.php index 85c85e29..28be9414 100644 --- a/config/business_navigation.php +++ b/config/business_navigation.php @@ -252,7 +252,7 @@ $navigation = [ 'directory' => [ 'icon' => 'query_stats', 'status' => '共享镜像', - 'description' => '店铺资料、主体生效区间和平台账单统一读取团队共享业务镜像;销量按账单收入汇总。', + 'description' => '店铺资料、主体生效区间统一读取团队共享业务镜像;销量取业绩明细的「订单实付/实收金额」,按店铺和发生时间汇总后落到主体期间。', 'empty' => '店铺维度报表尚未完成共享数据导入。', 'fields' => [ ['name' => 'erp_store_name', 'label' => 'ERP系统店铺名称'], diff --git a/database/migrations/2026_10_16_234000_create_store_report_paid_sales_rows.php b/database/migrations/2026_10_16_234000_create_store_report_paid_sales_rows.php new file mode 100644 index 00000000..90bf104d --- /dev/null +++ b/database/migrations/2026_10_16_234000_create_store_report_paid_sales_rows.php @@ -0,0 +1,62 @@ +connection()); + + if (! $schema->hasTable('store_report_paid_sales_rows')) { + $schema->create('store_report_paid_sales_rows', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->uuid('generation'); + $table->string('store_name', 191); + $table->date('occurred_on'); + $table->decimal('paid_amount', 20, 4)->default(0); + $table->unsignedInteger('order_count')->default(0); + $table->dateTime('updated_at'); + $table->unique( + ['generation', 'store_name', 'occurred_on'], + 'store_report_paid_generation_store_date_unique', + ); + $table->index(['generation', 'occurred_on'], 'store_report_paid_generation_date_index'); + }); + } + + // 业绩明细按月/平台整体重写,用指纹判断是否需要重建销量汇总。 + if ($schema->hasTable('store_report_import_states') + && ! $schema->hasColumn('store_report_import_states', 'source_fingerprint')) { + $schema->table('store_report_import_states', function (Blueprint $table): void { + $table->string('source_fingerprint', 64)->nullable()->after('source_files_json'); + }); + } + } + + public function down(): void + { + $schema = Schema::connection($this->connection()); + $schema->dropIfExists('store_report_paid_sales_rows'); + if ($schema->hasTable('store_report_import_states') + && $schema->hasColumn('store_report_import_states', 'source_fingerprint')) { + $schema->table('store_report_import_states', function (Blueprint $table): void { + $table->dropColumn('source_fingerprint'); + }); + } + } +}; diff --git a/modules/EcommerceFinance/Repositories/StoreReportRepository.php b/modules/EcommerceFinance/Repositories/StoreReportRepository.php index db0ed977..38c361f5 100644 --- a/modules/EcommerceFinance/Repositories/StoreReportRepository.php +++ b/modules/EcommerceFinance/Repositories/StoreReportRepository.php @@ -14,14 +14,36 @@ use RuntimeException; * 页面不扫描千万级原始账单,也不依赖开发机或镜像中不存在的 SQLite。 * 期间由 StoreReportPeriodBuilder 按期初数据和爬虫变更生成:变更店铺的老主体 * 失效时间为变更日前一天、新主体从变更日当天生效,收入按实际日期归集,不重复统计。 + * + * 两列金额口径不同,页面分别展示: + * 销量(period_sales / sales_NN):业绩明细(店铺收款匹配订单明细)的「订单实付/实收金额」, + * 按「店铺名称 + 发生时间」预汇总到 store_report_paid_sales_rows,再按发生日期落到主体期间; + * 收入(rolling_12m_income / income_NN):平台账单日汇总 store_report_daily_rows 的收入, + * 供主体维度经营报表按主体汇总使用。 */ class StoreReportRepository { // 保留同步命令使用的数据集键;页面只读生命周期与日汇总。 public const BILLS_DATASET = 'store-report.platform-bills'; public const LIFECYCLES_DATASET = 'store-report.store-lifecycles'; - /** @deprecated Kept for existing synchronizer/test contracts. */ + /** 平台账单日汇总:主体维度经营报表的「收入」列仍按这里取数。 */ public const DAILY_DATASET = 'store-report.daily-sales'; + /** 销量数据集:业绩明细「订单实付/实收金额」按「店铺名称 + 发生日期」预汇总。 */ + public const PAID_SALES_DATASET = 'store-report.paid-sales'; + /** 销量汇总表;由业绩明细表汇总而来,页面按店铺名与发生日期关联主体期间。 */ + public const PAID_SALES_TABLE = 'store_report_paid_sales_rows'; + /** 业绩明细表(店铺收款匹配订单明细),销量汇总的唯一上游。 */ + public const PAID_SALES_SOURCE_TABLE = 'store_receipt_order_match_rows'; + + /** + * 销量来源:业绩明细的「订单实付/实收金额」(按店铺 + 发生日期预汇总)。 + * + * @var array{table:string,amount:string} + */ + private const SALES_SOURCE = ['table' => self::PAID_SALES_TABLE, 'amount' => 'paid_amount']; + + /** @var array{table:string,amount:string} 收入来源:平台账单日汇总。 */ + private const INCOME_SOURCE = ['table' => 'store_report_daily_rows', 'amount' => 'income']; private const DEFAULT_EFFECTIVE_AT = '2026-07-01'; private const DEFAULT_EXPIRES_AT = '2999-01-01'; @@ -90,6 +112,7 @@ class StoreReportRepository return []; } + $salesGeneration = $this->activeGeneration(self::PAID_SALES_DATASET); $dailyGeneration = $this->activeGeneration(self::DAILY_DATASET); // 期间由期初数据、系统主体和爬虫变更生成,同一店铺不再展开流程历史重复行。 $periods = $this->periods->build($stores); @@ -102,8 +125,10 @@ class StoreReportRepository $singleNames[] = $name; } } - $singleSales = $this->singlePeriodSales($singleNames, $dailyGeneration); - $splitSales = $this->periodSales($multiPeriod, $dailyGeneration); + $singleSales = $this->singlePeriodTotals($singleNames, $salesGeneration, self::SALES_SOURCE); + $splitSales = $this->periodTotals($multiPeriod, $salesGeneration, self::SALES_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(); $rollingMonths = collect(range(12, 1))->map( @@ -129,19 +154,22 @@ class StoreReportRepository $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' => []]); $monthly = []; $monthlyIncome = []; for ($month = 1; $month <= 12; $month++) { $monthKey = sprintf('%d-%02d', $reportYear, $month); $monthly[sprintf('sales_%02d', $month)] = (float) ($saleData['months'][$monthKey] ?? 0); $monthlyIncome[sprintf('income_%02d', $month)] = $monthKey >= $currentMonth->format('Y-m') - || ! array_key_exists($monthKey, $saleData['months']) + || ! array_key_exists($monthKey, $incomeData['months']) ? null - : (float) $saleData['months'][$monthKey]; + : (float) $incomeData['months'][$monthKey]; } $rollingSales = array_sum(array_map( - static fn (string $month): float => (float) ($saleData['months'][$month] ?? 0), + static fn (string $month): float => (float) ($incomeData['months'][$month] ?? 0), $rollingMonths, )); @@ -160,7 +188,7 @@ class StoreReportRepository ? ($expiresAt === self::DEFAULT_EXPIRES_AT ? '存续中' : $expiresAt) : '-', 'period_sales' => (float) $saleData['period'], - 'rolling_12m_income' => array_intersect($rollingMonths, array_keys($saleData['months'])) === [] + 'rolling_12m_income' => array_intersect($rollingMonths, array_keys($incomeData['months'])) === [] ? null : $rollingSales, ...$monthly, @@ -220,12 +248,13 @@ class StoreReportRepository } /** - * 多期间店铺按每个期间的主体生效日、失效日(含当天)拆分日汇总收入。 + * 多期间店铺按每个期间的主体生效日、失效日(含当天)拆分金额。 * * @param array>> $periodsByStore + * @param array{table:string,amount:string} $source 金额来源表与金额列(表名、列名来自类常量,不接受外部输入) * @return array}>> */ - private function periodSales(array $periodsByStore, string $dailyGeneration): array + private function periodTotals(array $periodsByStore, string $generation, array $source): array { $flat = []; foreach ($periodsByStore as $name => $list) { @@ -242,6 +271,8 @@ class StoreReportRepository $month = $this->connection->getDriverName() === 'sqlite' ? "substr(d.occurred_on, 1, 7)" : "DATE_FORMAT(d.occurred_on, '%Y-%m')"; + $table = $source['table']; + $amount = $source['amount']; $collected = []; foreach (array_chunk($flat, 200) as $chunk) { $selects = []; @@ -252,17 +283,17 @@ class StoreReportRepository } $rows = $this->select( "SELECT p.period_key, {$month} AS bill_month, - SUM(COALESCE(d.income, 0)) AS income_total + SUM(COALESCE(d.{$amount}, 0)) AS amount_total FROM (" . implode(' UNION ALL ', $selects) . ") AS p - INNER JOIN store_report_daily_rows AS d + INNER JOIN {$table} AS d ON d.store_name = p.store_name AND d.generation = ? AND d.occurred_on >= p.effective_at AND d.occurred_on <= p.expires_at GROUP BY p.period_key, {$month}", - [...$bindings, $dailyGeneration], + [...$bindings, $generation], ); - $this->collectSales($collected, $rows, 'period_key'); + $this->collectTotals($collected, $rows, 'period_key'); } $result = []; @@ -274,8 +305,14 @@ class StoreReportRepository return $result; } - /** @return array}> */ - private function singlePeriodSales(array $names, string $dailyGeneration): array + /** + * 单期间店铺的金额按月汇总;生效、失效时间用统一的默认窗口兜底。 + * + * @param list $names + * @param array{table:string,amount:string} $source + * @return array}> + */ + private function singlePeriodTotals(array $names, string $generation, array $source): array { if ($names === []) { return []; @@ -284,31 +321,33 @@ class StoreReportRepository $month = $this->connection->getDriverName() === 'sqlite' ? "substr(occurred_on, 1, 7)" : "DATE_FORMAT(occurred_on, '%Y-%m')"; + $table = $source['table']; + $amount = $source['amount']; $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(income, 0)) AS income_total - FROM store_report_daily_rows + SUM(COALESCE({$amount}, 0)) AS amount_total + FROM {$table} WHERE generation = ? AND store_name IN ($placeholders) AND occurred_on >= ? AND occurred_on < ? GROUP BY store_name, {$month}", - [$dailyGeneration, ...$chunk, self::DEFAULT_EFFECTIVE_AT, self::DEFAULT_EXPIRES_AT], + [$generation, ...$chunk, self::DEFAULT_EFFECTIVE_AT, self::DEFAULT_EXPIRES_AT], ); - $this->collectSales($result, $rows, 'store_name'); + $this->collectTotals($result, $rows, 'store_name'); } return $result; } /** @param array}> $result */ - private function collectSales(array &$result, array $rows, string $keyColumn): void + private function collectTotals(array &$result, array $rows, string $keyColumn): void { foreach ($rows as $row) { $key = (string) $row[$keyColumn]; - $result[$key]['period'] = ($result[$key]['period'] ?? 0.0) + (float) $row['income_total']; - $result[$key]['months'][(string) $row['bill_month']] = ($result[$key]['months'][(string) $row['bill_month']] ?? 0.0) + (float) $row['income_total']; + $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']; } } diff --git a/modules/EcommerceFinance/Services/StoreReportLogic.php b/modules/EcommerceFinance/Services/StoreReportLogic.php index 76a4dd2f..8643a35e 100644 --- a/modules/EcommerceFinance/Services/StoreReportLogic.php +++ b/modules/EcommerceFinance/Services/StoreReportLogic.php @@ -72,11 +72,18 @@ class StoreReportLogic ], [ 'code' => 'R8', - 'object' => '收入归属', - 'logic' => '期间销量按日汇总的实际发生日期归属:变更日当天归新主体,老主体统计到变更日前一天,主体切换不重复统计、不少计收入。', - 'source' => 'store_report_daily_rows + 主体期间', + 'object' => '销量归属', + 'logic' => '期间销量按实际发生日期归属:变更日当天归新主体,老主体统计到变更日前一天,主体切换不重复统计、不少计销量。', + 'source' => 'store_report_paid_sales_rows + 主体期间', 'priority' => '按日归属,区间不重叠', ], + [ + 'code' => 'R9', + 'object' => '销量口径', + 'logic' => '销量=业绩明细(店铺收款匹配订单明细)的「订单实付/实收金额」,按「店铺名称 + 发生时间」汇总;订单实付为空的未匹配行不计入。收入列仍按平台账单日汇总,两个口径分开统计、不互相覆盖。', + 'source' => 'store_receipt_order_match_rows → store_report_paid_sales_rows', + 'priority' => '与业绩明细同口径', + ], ], ]; } diff --git a/modules/EcommerceFinance/Services/StoreReportMirrorSynchronizer.php b/modules/EcommerceFinance/Services/StoreReportMirrorSynchronizer.php index 70353e07..92143eff 100644 --- a/modules/EcommerceFinance/Services/StoreReportMirrorSynchronizer.php +++ b/modules/EcommerceFinance/Services/StoreReportMirrorSynchronizer.php @@ -62,6 +62,7 @@ class StoreReportMirrorSynchronizer 'period_changes' => $periodChanges, 'bills' => $bills, 'daily' => $this->syncDailySummary($dailyBatchSize, $dailyMaxBatches), + 'paid_sales' => $this->syncPaidSales(), ]; } @@ -445,6 +446,104 @@ class StoreReportMirrorSynchronizer && ! empty($state->initial_completed_at); } + /** + * 店铺维度报表的「销量」:把业绩明细的「订单实付/实收金额」按「店铺名称 + 发生日期」预汇总。 + * + * 业绩明细由 store-receipt:order-match:sync 按「账期 + 平台」整体重写,这里用 + * 「行数 + 最近写入时间 + 金额合计」的指纹判断是否变化:没变化就复用当前版本, + * 变化时全量重建(源表 60 万行左右,汇总后每店铺每天一行)。 + * + * @return array{status:string,source_rows:int,stored_rows:int,changed:bool} + */ + public function syncPaidSales(bool $force = false): array + { + if (! Schema::connection($this->connection->getName()) + ->hasTable(StoreReportRepository::PAID_SALES_SOURCE_TABLE)) { + return ['status' => 'skipped', 'source_rows' => 0, 'stored_rows' => 0, 'changed' => false]; + } + + $state = $this->state(StoreReportRepository::PAID_SALES_DATASET); + try { + $fingerprint = $this->paidSalesFingerprint(); + $active = trim((string) ($state->active_generation ?? '')); + if (! $force && $active !== '' && ! empty($state->initial_completed_at) + && (string) ($state->source_fingerprint ?? '') === $fingerprint) { + return [ + 'status' => 'succeeded', + 'source_rows' => 0, + 'stored_rows' => (int) ($state->row_count ?? 0), + 'changed' => false, + ]; + } + + $now = now(); + $generation = (string) Str::uuid(); + $this->connection->statement( + 'INSERT INTO ' . StoreReportRepository::PAID_SALES_TABLE + . ' (generation, store_name, occurred_on, paid_amount, order_count, updated_at)' + . ' SELECT ?, store_name, occurred_date, SUM(COALESCE(paid_amount, 0)), COUNT(paid_amount), ?' + . ' 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', + [$generation, $now->format('Y-m-d H:i:s')], + ); + $stored = (int) $this->connection->table(StoreReportRepository::PAID_SALES_TABLE) + ->where('generation', $generation)->count(); + $sourceRows = (int) ($this->connection->table(StoreReportRepository::PAID_SALES_SOURCE_TABLE)->count()); + $this->connection->table('store_report_import_states') + ->where('dataset_key', StoreReportRepository::PAID_SALES_DATASET) + ->update([ + 'status' => 'succeeded', + 'run_mode' => 'full', + 'active_generation' => $generation, + 'pending_generation' => null, + 'row_count' => $stored, + 'source_fingerprint' => $fingerprint, + 'initial_completed_at' => $state->initial_completed_at ?? $now, + 'last_attempted_at' => $now, + 'last_succeeded_at' => $now, + 'last_error_code' => null, + 'updated_at' => $now, + ]); + // 版本切换成功后再清理上一版,避免中途失败时页面读到被清空的当前版本。 + $this->connection->table(StoreReportRepository::PAID_SALES_TABLE) + ->where('generation', '<>', $generation)->delete(); + + return ['status' => 'succeeded', 'source_rows' => $sourceRows, 'stored_rows' => $stored, 'changed' => true]; + } catch (Throwable $exception) { + $this->connection->table('store_report_import_states') + ->where('dataset_key', StoreReportRepository::PAID_SALES_DATASET) + ->update([ + 'status' => 'failed', + 'last_attempted_at' => now(), + 'last_error_code' => class_basename($exception), + 'updated_at' => now(), + ]); + + return [ + 'status' => 'failed', + 'source_rows' => 0, + 'stored_rows' => (int) ($state->row_count ?? 0), + 'changed' => false, + ]; + } + } + + /** 业绩明细是否变化的指纹:行数 + 最近写入时间 + 订单实付合计。 */ + private function paidSalesFingerprint(): string + { + $row = $this->connection->selectOne( + 'SELECT COUNT(*) AS rows_total, MAX(imported_at) AS last_imported_at,' + . ' COALESCE(SUM(paid_amount), 0) AS paid_total FROM ' . StoreReportRepository::PAID_SALES_SOURCE_TABLE, + ); + + return hash('sha256', implode('|', [ + (string) ($row->rows_total ?? 0), + (string) ($row->last_imported_at ?? ''), + (string) ($row->paid_total ?? '0'), + ])); + } + /** @param array{upserts:array>,deletes:array} $mapped */ private function dailyDeltas(string $generation, array $mapped): array { diff --git a/tests/Feature/Console/StoreReportMirrorSyncTest.php b/tests/Feature/Console/StoreReportMirrorSyncTest.php index dad2bda2..31ee3a46 100644 --- a/tests/Feature/Console/StoreReportMirrorSyncTest.php +++ b/tests/Feature/Console/StoreReportMirrorSyncTest.php @@ -222,6 +222,65 @@ class StoreReportMirrorSyncTest extends TestCase ]); } + public function test_paid_sales_summary_rebuilds_from_performance_details_only_when_source_changes(): void + { + $mirror = DB::connection('business_mirror'); + $mirror->table('store_receipt_order_match_rows')->insert([ + $this->perfRow('k1', '2026-08-02', '店铺A', 100.5), + $this->perfRow('k2', '2026-08-02', '店铺A', 9.5), + // 未匹配行没有订单实付,落到 0,不计入销量金额。 + $this->perfRow('k3', '2026-08-03', '店铺A', null), + $this->perfRow('k4', '2026-08-03', '店铺B', 20), + ]); + $upstream = $this->createMock(StoreReportUpstreamRepository::class); + $upstream->method('lifecycleBatch')->willReturn([]); + $upstream->method('billBatch')->willReturn([]); + $synchronizer = new StoreReportMirrorSynchronizer($upstream, app('db')); + + $first = $synchronizer->sync(100, 2); + $generation = $mirror->table('store_report_paid_sales_rows')->value('generation'); + + $this->assertSame('succeeded', $first['paid_sales']['status']); + $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, + ], 'business_mirror'); + $this->assertDatabaseHas('store_report_paid_sales_rows', [ + 'generation' => $generation, 'store_name' => '店铺B', 'occurred_on' => '2026-08-03', + 'paid_amount' => 20, 'order_count' => 1, + ], 'business_mirror'); + $this->assertSame(3, $mirror->table('store_report_paid_sales_rows')->count()); + $this->assertDatabaseHas('store_report_import_states', [ + 'dataset_key' => StoreReportRepository::PAID_SALES_DATASET, 'status' => 'succeeded', 'row_count' => 3, + ], 'business_mirror'); + + // 业绩明细没有变化:沿用同一版本,不重复全量重建。 + $second = $synchronizer->sync(100, 2); + $this->assertSame('succeeded', $second['paid_sales']['status']); + $this->assertFalse($second['paid_sales']['changed']); + $this->assertSame($generation, $mirror->table('store_report_paid_sales_rows')->value('generation')); + + // 账期重写后指纹变化:重建并只保留新版本,页面不会读到两个版本。 + $mirror->table('store_receipt_order_match_rows')->insert($this->perfRow('k5', '2026-08-04', '店铺B', 5, '2026-10-16 12:00:00')); + $third = $synchronizer->sync(100, 2); + $newGeneration = $mirror->table('store_report_paid_sales_rows')->where('occurred_on', '2026-08-04')->value('generation'); + $this->assertTrue($third['paid_sales']['changed']); + $this->assertNotSame($generation, $newGeneration); + $this->assertSame(4, $mirror->table('store_report_paid_sales_rows')->count()); + $this->assertSame(0, $mirror->table('store_report_paid_sales_rows')->where('generation', $generation)->count()); + } + + /** @return array */ + private function perfRow(string $key, string $occurredOn, string $store, ?float $paid, string $importedAt = '2026-10-16 10:00:00'): array + { + return [ + 'report_month' => '2026-08-01', 'platform' => '淘系支付宝', 'row_key' => $key, + 'occurred_date' => $occurredOn, 'store_name' => $store, + 'paid_amount' => $paid, 'imported_at' => $importedAt, + ]; + } + private function createTables(): void { $schema = Schema::connection('business_mirror'); @@ -234,6 +293,7 @@ class StoreReportMirrorSyncTest extends TestCase $table->unsignedBigInteger('cursor_id')->nullable(); $table->unsignedBigInteger('row_count')->default(0); $table->text('source_files_json')->nullable(); + $table->string('source_fingerprint')->nullable(); $table->dateTime('last_attempted_at')->nullable(); $table->dateTime('last_succeeded_at')->nullable(); $table->dateTime('initial_completed_at')->nullable(); @@ -294,6 +354,27 @@ class StoreReportMirrorSyncTest extends TestCase $table->string('business_key')->unique(); $table->timestamps(); }); + // 销量汇总表与它的上游业绩明细表。 + $schema->create('store_report_paid_sales_rows', function (Blueprint $table): void { + $table->increments('id'); + $table->string('generation'); + $table->string('store_name'); + $table->date('occurred_on'); + $table->decimal('paid_amount', 20, 4)->default(0); + $table->unsignedInteger('order_count')->default(0); + $table->dateTime('updated_at')->nullable(); + $table->unique(['generation', 'store_name', 'occurred_on']); + }); + $schema->create('store_receipt_order_match_rows', function (Blueprint $table): void { + $table->string('report_month'); + $table->string('platform')->nullable(); + $table->string('row_key'); + $table->date('occurred_date')->nullable(); + $table->string('store_name')->nullable(); + $table->decimal('paid_amount', 20, 4)->nullable(); + $table->dateTime('imported_at'); + $table->primary(['report_month', 'row_key']); + }); $schema->create('ops_crawl_shop_company', function (Blueprint $table): void { $table->increments('id'); $table->string('shop_name'); diff --git a/tests/Unit/EcommerceFinance/StoreReportRepositoryFilterTest.php b/tests/Unit/EcommerceFinance/StoreReportRepositoryFilterTest.php index 8a5ad8a1..d7fefbc0 100644 --- a/tests/Unit/EcommerceFinance/StoreReportRepositoryFilterTest.php +++ b/tests/Unit/EcommerceFinance/StoreReportRepositoryFilterTest.php @@ -13,6 +13,7 @@ class StoreReportRepositoryFilterTest extends TestCase { private StoreReportRepository $repository; private string $dailyGeneration = '22222222-2222-4222-8222-222222222222'; + private string $paidGeneration = '33333333-3333-4333-8333-333333333333'; /** @var array> */ private array $stores = [ @@ -53,9 +54,18 @@ class StoreReportRepositoryFilterTest extends TestCase $table->decimal('income', 20, 4)->default(0); $table->decimal('expense', 20, 4)->default(0); }); + $schema->create('store_report_paid_sales_rows', function (Blueprint $table): void { + $table->increments('id'); + $table->string('generation'); + $table->string('store_name'); + $table->date('occurred_on'); + $table->decimal('paid_amount', 20, 4)->default(0); + $table->unsignedInteger('order_count')->default(0); + }); DB::connection('business_mirror')->table('store_report_import_states')->insert([ ['dataset_key' => StoreReportRepository::LIFECYCLES_DATASET, 'active_generation' => 'lifecycle-live', 'initial_completed_at' => now()], ['dataset_key' => StoreReportRepository::DAILY_DATASET, 'active_generation' => $this->dailyGeneration, 'initial_completed_at' => now()], + ['dataset_key' => StoreReportRepository::PAID_SALES_DATASET, 'active_generation' => $this->paidGeneration, 'initial_completed_at' => now()], ]); $this->repository = new StoreReportRepository(app('db')); } diff --git a/tests/Unit/EcommerceFinance/StoreReportRepositoryTest.php b/tests/Unit/EcommerceFinance/StoreReportRepositoryTest.php index 2be1f47b..42749bf2 100644 --- a/tests/Unit/EcommerceFinance/StoreReportRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/StoreReportRepositoryTest.php @@ -23,6 +23,7 @@ class StoreReportRepositoryTest extends TestCase { private StoreReportRepository $repository; private string $dailyGeneration = '22222222-2222-4222-8222-222222222222'; + private string $paidGeneration = '33333333-3333-4333-8333-333333333333'; protected function setUp(): void { @@ -56,6 +57,15 @@ class StoreReportRepositoryTest extends TestCase $table->decimal('income', 20, 4)->default(0); $table->decimal('expense', 20, 4)->default(0); }); + // 销量来源:业绩明细「订单实付/实收金额」按店铺 + 发生日期的预汇总。 + $schema->create('store_report_paid_sales_rows', function (Blueprint $table): void { + $table->increments('id'); + $table->string('generation'); + $table->string('store_name'); + $table->date('occurred_on'); + $table->decimal('paid_amount', 20, 4)->default(0); + $table->unsignedInteger('order_count')->default(0); + }); $schema->create('ops_fys_shop_info', function (Blueprint $table): void { $table->increments('Id'); $table->string('erpShopName'); @@ -70,6 +80,7 @@ class StoreReportRepositoryTest extends TestCase DB::connection('business_mirror')->table('store_report_import_states')->insert([ ['dataset_key' => StoreReportRepository::LIFECYCLES_DATASET, 'active_generation' => 'lifecycle-live', 'initial_completed_at' => now()], ['dataset_key' => StoreReportRepository::DAILY_DATASET, 'active_generation' => $this->dailyGeneration, 'initial_completed_at' => now()], + ['dataset_key' => StoreReportRepository::PAID_SALES_DATASET, 'active_generation' => $this->paidGeneration, 'initial_completed_at' => now()], ]); $this->repository = new StoreReportRepository(app('db')); } @@ -213,6 +224,37 @@ class StoreReportRepositoryTest extends TestCase $this->repository->rows([['erp_store_name' => '店铺A']], 2026); } + public function test_sales_use_performance_details_paid_amount_and_income_keeps_bill_summary(): void + { + Carbon::setTestNow('2026-09-15 10:00:00'); + // 同一店铺同一天:账单收入 100,业绩明细订单实付 88 —— 销量取实付、收入取账单。 + $this->insertIncome('店铺A', '2026-07-05', 100); + $this->insertPaidSales('店铺A', '2026-07-05', 88); + $this->insertPaidSales('店铺A', '2026-08-03', 5); + + $rows = $this->repository->rows([ + ['erp_store_name' => '店铺A', 'company_name' => '主体甲', 'store_status' => '0'], + ], 2026); + + $this->assertCount(1, $rows); + $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(100.0, (float) $rows[0]['income_07']); + $this->assertSame(100.0, (float) $rows[0]['rolling_12m_income']); + } + + public function test_unfinished_sales_summary_is_reported_instead_of_returning_misleading_zeroes(): void + { + DB::connection('business_mirror')->table('store_report_import_states') + ->where('dataset_key', StoreReportRepository::PAID_SALES_DATASET) + ->update(['active_generation' => null, 'initial_completed_at' => null]); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('store_report_dataset_not_ready'); + $this->repository->rows([['erp_store_name' => '店铺A']], 2026); + } + public function test_upstream_business_information_exposes_shared_store_report_rows(): void { $this->insertBill('店铺A', '2026-07-05', 60); @@ -307,6 +349,14 @@ class StoreReportRepositoryTest extends TestCase } private function insertBill(string $store, string $occurredOn, float $income): void + { + $this->insertIncome($store, $occurredOn, $income); + // 销量与收入同源不同表:默认按同额写入业绩明细的订单实付,需要区分口径的用例单独调用。 + $this->insertPaidSales($store, $occurredOn, $income); + } + + /** 平台账单日汇总的收入行(主体维度经营报表的「收入」列)。 */ + private function insertIncome(string $store, string $occurredOn, float $income): void { DB::connection('business_mirror')->table('store_report_daily_rows')->insert([ 'generation' => $this->dailyGeneration, @@ -317,6 +367,18 @@ class StoreReportRepositoryTest extends TestCase ]); } + /** 业绩明细「订单实付/实收金额」按店铺 + 发生日期的预汇总行。 */ + private function insertPaidSales(string $store, string $occurredOn, float $paid): void + { + DB::connection('business_mirror')->table('store_report_paid_sales_rows')->insert([ + 'generation' => $this->paidGeneration, + 'store_name' => $store, + 'occurred_on' => $occurredOn, + 'paid_amount' => $paid, + 'order_count' => 1, + ]); + } + private function insertChange(string $store, string $company, string $observedOn, ?string $taxNo = null): void { DB::connection('business_mirror')->table('store_report_shop_period_changes')->insert([ -- 2.47.2