diff --git a/app/Console/Commands/SyncPromotionExpenses.php b/app/Console/Commands/SyncPromotionExpenses.php new file mode 100644 index 00000000..ca94a2a9 --- /dev/null +++ b/app/Console/Commands/SyncPromotionExpenses.php @@ -0,0 +1,74 @@ +dateRange(); + $result = $synchronizer->sync($from, $to); + } catch (Throwable $exception) { + Log::error('推广费用共享镜像同步失败。', ['exception' => $exception::class]); + $this->error('推广费用同步失败,页面继续显示上一版数据。'); + + return self::FAILURE; + } + + if ($result['days'] === 0) { + $this->warn('上游暂无推广费用数据,未写入镜像。'); + + return self::SUCCESS; + } + + $this->info(sprintf( + '推广费用同步完成:%s 至 %s(源数据截至 %s),%d 天,源记录 %d 条,汇总镜像 %d 行。', + $result['from'], + $result['to'], + $result['effective_to'] ?? '无', + $result['days'], + $result['source_rows'], + $result['stored_rows'], + )); + + return self::SUCCESS; + } + + /** @return array{0:Carbon,1:Carbon} */ + private function dateRange(): array + { + $toInput = trim((string) $this->option('to')); + $fromInput = trim((string) $this->option('from')); + $to = $toInput === '' + ? now('Asia/Shanghai')->startOfDay() + : Carbon::createFromFormat('Y-m-d', $toInput, 'Asia/Shanghai')->startOfDay(); + $from = $fromInput !== '' + ? Carbon::createFromFormat('Y-m-d', $fromInput, 'Asia/Shanghai')->startOfDay() + : ($this->option('full') + ? Carbon::parse(self::HISTORY_START, 'Asia/Shanghai')->startOfDay() + : $to->copy()->subDays(max(1, (int) $this->option('days')) - 1)); + + if ($from->gt($to)) { + throw new \InvalidArgumentException('开始日期不能晚于结束日期。'); + } + + return [$from, $to]; + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 65083b24..ac5976c4 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -48,6 +48,14 @@ class Kernel extends ConsoleKernel ->withoutOverlapping(60) ->runInBackground(); + // 聚水潭推广费用按日期、平台、店铺自动汇总到共享镜像;最近 7 天覆盖迟到修订。 + $schedule->command('business-mirror:sync-promotion-expenses --days=7 --quiet') + ->dailyAt('03:10') + ->timezone('Asia/Shanghai') + ->withoutOverlapping(90) + ->appendOutputTo(storage_path('logs/promotion-expense-sync.log')) + ->runInBackground(); + // 退款待确认四张镜像每天 06:00 专属刷新,确保 10:00 前完成; // 同步失败状态由财务驾驶舱展示。 $schedule->command('business-mirror:sync-tables --daily-only --max-batches=0') diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 94c5fb01..1c0c491f 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -106,6 +106,7 @@ use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore; use Modules\EcommerceFinance\Services\SupplierFreeShippingStore; use Modules\EcommerceFinance\View\PlatformPromotionAccountPageData; use Modules\EcommerceFinance\View\OrderDataPageData; +use Modules\EcommerceFinance\View\PromotionExpensePageData; use Modules\EcommerceFinance\View\SupplierNegativeAlertPageData; use Modules\EcommerceFinance\View\SupplierPayableForecastPageData; use RuntimeException; @@ -1292,6 +1293,55 @@ class Pages extends Controller ], 200, ['Cache-Control' => 'private, no-store']); } + public function exportPromotionExpenses(Request $request): StreamedResponse + { + $filters = $request->validate([ + 'month' => ['nullable', 'date_format:Y-m'], + 'platform' => ['nullable', 'string', 'max:64'], + 'store_name' => ['nullable', 'string', 'max:255'], + ]); + $month = trim((string) ($filters['month'] ?? '')) ?: now('Asia/Shanghai')->format('Y-m'); + $rows = app(PromotionExpensePageData::class)->exportRows( + $month, + trim((string) ($filters['platform'] ?? '')), + trim((string) ($filters['store_name'] ?? '')), + ); + + return response()->streamDownload(function () use ($rows): void { + $out = fopen('php://output', 'w'); + fwrite($out, "\xEF\xBB\xBF"); + fputcsv($out, [ + '平台', + '店铺名称', + '源记录', + '直接推广费', + '分摊推广费', + '推广费用合计', + '直接营销费', + '分摊营销费', + '营销费用合计', + '费用合计', + ]); + foreach ($rows as $row) { + fputcsv($out, [ + $row['platform'] ?? '', + $row['store_name'] ?? '', + (int) ($row['source_rows'] ?? 0), + number_format((float) ($row['push_fee'] ?? 0), 2, '.', ''), + number_format((float) ($row['shared_push_fee'] ?? 0), 2, '.', ''), + number_format((float) ($row['push_fee_total'] ?? 0), 2, '.', ''), + number_format((float) ($row['marketing_fee'] ?? 0), 2, '.', ''), + number_format((float) ($row['shared_marketing_fee'] ?? 0), 2, '.', ''), + number_format((float) ($row['marketing_fee_total'] ?? 0), 2, '.', ''), + number_format((float) ($row['total_fee'] ?? 0), 2, '.', ''), + ]); + } + fclose($out); + }, '聚水潭推广费用_' . $month . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + ]); + } + /** * 账单明细导出:按页面同一套筛选条件流式导出 CSV(全部筛选结果)。 */ @@ -5664,6 +5714,7 @@ class Pages extends Controller 'payable-cloud-warehouse-vehicle-fee' => $this->contentForDingPayableWorkflows(), 'online-daifa-price' => $this->contentForOnlineDaifaPrice(), 'product-costs' => $this->contentForProductCosts(), + 'promotion-expenses' => app(PromotionExpensePageData::class)->page(), 'financial-analysis' => $this->contentForFinancialAnalysis(), 'oa-process' => $this->contentForProcessDetails(), 'invoice-data' => app(\Modules\EcommerceFinance\View\InvoiceDataPageData::class)->page(request()), diff --git a/database/migrations/2026_11_27_120000_create_promotion_expense_daily_rows.php b/database/migrations/2026_11_27_120000_create_promotion_expense_daily_rows.php new file mode 100644 index 00000000..d23e347c --- /dev/null +++ b/database/migrations/2026_11_27_120000_create_promotion_expense_daily_rows.php @@ -0,0 +1,70 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if ($schema->hasTable('promotion_expense_daily_rows')) { + return; + } + + $schema->create('promotion_expense_daily_rows', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->date('report_date'); + $table->string('platform', 64); + $table->string('store_name', 255); + $table->unsignedBigInteger('source_rows')->default(0); + $table->decimal('push_fee', 20, 2)->default(0); + $table->decimal('shared_push_fee', 20, 2)->default(0); + $table->decimal('push_fee_total', 20, 2)->default(0); + $table->decimal('marketing_fee', 20, 2)->default(0); + $table->decimal('shared_marketing_fee', 20, 2)->default(0); + $table->decimal('marketing_fee_total', 20, 2)->default(0); + $table->decimal('total_fee', 20, 2)->default(0); + $table->timestamp('synced_at')->useCurrent(); + + $table->unique( + ['report_date', 'platform', 'store_name'], + 'promotion_expense_daily_unique', + ); + $table->index( + ['report_date', 'platform'], + 'promotion_expense_date_platform_index', + ); + $table->index( + ['platform', 'report_date'], + 'promotion_expense_platform_date_index', + ); + $table->index( + ['store_name', 'report_date'], + 'promotion_expense_store_date_index', + ); + }); + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + Schema::connection($this->connection())->dropIfExists('promotion_expense_daily_rows'); + } +}; diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 8ff830c0..06c0b8e2 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -215,6 +215,8 @@ CRON_TZ=Asia/Shanghai # 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。 3,13,23,33,43,53 * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --source=snapshot --page-size=500 --max-pages=20 --quiet >/dev/null 2>&1 0 5 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables operations_replica.rpt.jst_Orders --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-online-daifa-price --quiet' >/dev/null 2>&1 +# 聚水潭推广费用:每天汇总最近 7 天,覆盖迟到改单并供财务经营报表直接读取。 +10 3 * * * root /usr/bin/timeout 1800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-promotion-expenses --days=7 --quiet >/dev/null 2>&1 # 聚水潭订单标签明细:先核对 2026-10-01 起逐日覆盖,补历史缺口,再刷新最近 7 天。 10 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jst-order-labels:sync-daily --from=2026-10-01 --company=1 --quiet >/dev/null 2>&1 # 业绩明细种菜金额:每天 09:30 核查标签覆盖,同步本月/上月种菜报销并重算种菜金额。 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index 7bdcb7b5..ff7aab6e 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -219,6 +219,8 @@ CRON_TZ=Asia/Shanghai # 镜像价格观测独立保存,按索引分批续传,不替代正式操作历史。 3,13,23,33,43,53 * * * * root /usr/bin/flock -n /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-jushuitan-cost-price-history --source=snapshot --page-size=500 --max-pages=20 --quiet >/dev/null 2>&1 0 5 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-tables operations_replica.rpt.jst_Orders --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-online-daifa-price --quiet' >/dev/null 2>&1 +# 聚水潭推广费用:每天汇总最近 7 天,覆盖迟到改单并供财务经营报表直接读取。 +10 3 * * * root /usr/bin/timeout 1800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-promotion-expenses --days=7 --quiet >/dev/null 2>&1 # 聚水潭订单标签明细:先核对 2026-10-01 起逐日覆盖,补历史缺口,再刷新最近 7 天。 10 6 * * * root /bin/sh /opt/caiwuxitong/run-finance-batch.sh jst-order-labels:sync-daily --from=2026-10-01 --company=1 --quiet >/dev/null 2>&1 # 业绩明细种菜金额:每天 09:30 核查标签覆盖,同步本月/上月种菜报销并重算种菜金额。 diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index e6ed2d95..fb4b961a 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -10,7 +10,7 @@ export CAIWU_BATCH_CALLER_DIR case "${1:-}" in *:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;; jushuitan:calc-freight) ;; - jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;; + jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;; *) echo 'Unsupported finance batch command' >&2; exit 64 ;; esac case "${1:-}" in diff --git a/docs/上游业务镜像清单.md b/docs/上游业务镜像清单.md index 56bf38ff..9e852eb2 100644 --- a/docs/上游业务镜像清单.md +++ b/docs/上游业务镜像清单.md @@ -44,6 +44,7 @@ | 已接入待首次同步 | 店铺营销账户余额的京东账户读取 `js_data_middle_platform.dbo.jd_jzt_finance_records` 镜像 `jsm_jd_jzt_finance_records`;按 `id` 稳定断点、`updated_at` 重叠增量,页面不直连上游。 | | 本次接入 | 普通商品资料的工作平台采购价格接入 `jiansun.dbo.pm_priceAdjustment`(镜像 `js_pm_price_adjustment`):按 `skuCode` 关联 `jst_sku.sku_id`,取 `effectTime` 不晚于当前时间的最新 `purchasePrice`,并在页面和导出中标记“工作平台价格”;源表没有可靠更新时间,按 `Id` 稳定键追加,首次全量完成前只显示普通商品自身采购价。 | | 待有效凭据后首次同步 | 普通商品当前成本价、商品类型和更新时间继续读取 `operations_replica.rpt.jst_sku`;`rpt.fys_skuCostPriceUpdate` 是一 SKU 一行的旧快照,不能充当变价历史。完整成本价变更仍读取聚水潭经典开放平台“商品操作日志查询”接口 `worklog.query`,只镜像操作内容含“采购价”的记录到 `jushuitan_cost_price_history_rows`;经典接口必须在服务器私有配置中使用同一应用的 `JUSHUITAN_PARTNER_ID / JUSHUITAN_PARTNER_KEY / JUSHUITAN_TOKEN`,不得把新开放平台的 App Key / App Secret / Access Token 混用。页面在首次同步完成前明确显示待同步或失败,不把 0 条解释为真实无历史。 | +| 本次接入 | 财务经营报表 › 推广费用从 `operations_replica.rpt.dws_sn_sales_full_info_di` 按“日期 + 平台 + 店铺”汇总推广费用、营销费用及各自直接/分摊金额,写入 `promotion_expense_daily_rows`;页面只读共享镜像。生产每天 03:10 自动重算最近 7 天并整日替换,覆盖迟到改单与删除;首次历史从 2026-01-01 起用 `business-mirror:sync-promotion-expenses --full` 补入。 | | 本次接入 | 流程明细读取 `operations_replica/rpt.ding_Workflow + rpt.ding_WorkflowScheme` 的结构化审批主表、费用明细和付款明细,写入 `ding_process_detail_mirror`、`ding_process_payment_mirror` 与付款按明细行分摊的 `ding_process_payment_line_mirror`;主表的 `originatorDeptName` 作为发起人部门单独保留,费用明细行的“店铺”字段规范化写入 `store_name`。审批表单表头的 `收款人全称 / 开户银行 / 银行账号` 分别写入 `payee_name / payee_bank_name / payee_bank_account`,同一审批下的每条费用明细继承对应值;行级或付款明细存在更具体值时优先使用。禁止先把明细表和付款表铺平成 CSV 后逐行求和;付款明细必须按“对应序号”关联到代表明细行,但合计始终读取独立付款事实。管理费用按分摊后的付款月份统计,跨月分笔付款不会把整张审批重复计入多月。每个纳入范围的源审批至少保留一条页面记录,没有费用金额的审批以空金额显示,不静默隐藏。首次全量先运行 `business-mirror:sync-ding-process-details --full --dry-run` 校验,再使用 `business-mirror:sync-ding-process-details --full` 发布;日常通过 `updateAt/createAt` 48 小时重叠增量同步。当前纳入日常报销、应付、线上代发、种菜、快递面单、固定资产、日常物品、样品、一次性采买、板材、工资、外贸费用和种菜充值等 14 个财务流程;发现新的明细流程编码时全量同步报错并保留上一版。 | | 本次接入 | 财务经营报表 › 管理费用使用 `oa_process_account_mapping` 保存流程科目映射;当前快照包含原工作簿 191 个科目和补充的 `5601.11.01 货代费`、`1221.07 种菜备用金`、`5602.11.03.19 AI阿里云软件费`,共 194 个科目,其中 37 个进费比科目和 126 个分摊规则。页面按打款时间提供整月选择并默认展示上个月 OA 流程中审批状态为“已完成”、涉及付款且出纳已打款的明细,不涉及付款或出纳未打款的数据不进入汇总,按费用大类和二级汇总进费比/不进费比/未映射金额,点击二级查看三级汇总与 9 列明细模板。审批完成时间写入 `ding_process_detail_mirror.approval_finished_at`,页面月份筛选使用 `ding_process_detail_mirror.paid_at`;钉钉副本把费用明细表保存为未命名字段时,按配置中的金额列识别包含该列的未命名表格组件,避免只抓到付款明细而漏掉费用科目和金额。明细行没有科目时,使用同一审批表单表头的 `科目编码 / 科目名称` 回填;行级科目始终优先。 | | 本次接入 | 订单利润的包材费、快递费、账单费用直接读取聚胜算订单利润页面接口 `pf.erp321.com/WebApi/PF/OrderSku/GetOrderSkuList`(支付/发货时间口径各分页抓取),导入 `ops_shengsuan_order_profit_rows`,页面按“店铺 + 线上/内部单号”原样回填,不把 0 或推算值写入缺口。异常订单再通过 `GetPfOrderDetList` 按每批最多 50 单抓取完整订单商品明细,保存至 `ops_shengsuan_order_profit_detail_snapshots`,包括全部订单字段、销售商品明细、退货商品明细和缺成本商品编码。主表抓取脚本为 `scripts/order-profit-shengsuan-sync.py`,明细补同步脚本为 `scripts/order-profit-shengsuan-details-sync.py`;导入命令分别为 `order-profit:import-shengsuan-rows`、`order-profit:import-shengsuan-details`。脚本依赖本机已登录胜算的 Chrome 调试窗口,不能由服务器容器直连页面。`成本/运费异常`按主表“商品成本或快递费任一为0/空”筛选,分别标记“成本异常”“运费异常”,并在订单下按具体商品编码展示缺成本条码,以发货时间为监控日期。 | diff --git a/modules/EcommerceFinance/Repositories/PromotionExpenseMirrorRepository.php b/modules/EcommerceFinance/Repositories/PromotionExpenseMirrorRepository.php new file mode 100644 index 00000000..e1eeb7fc --- /dev/null +++ b/modules/EcommerceFinance/Repositories/PromotionExpenseMirrorRepository.php @@ -0,0 +1,405 @@ +connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')); + } + + public function available(): bool + { + try { + return Schema::connection($this->connection->getName())->hasTable(self::TABLE); + } catch (Throwable) { + return false; + } + } + + /** @return array{code:string,status:string,last_succeeded_at:?string,last_error:?string,latest_date:?string,row_count:int} */ + public function syncStatus(): array + { + if (! $this->available()) { + return [ + 'code' => 'unavailable', + 'status' => 'unavailable', + 'last_succeeded_at' => null, + 'last_error' => null, + 'latest_date' => null, + 'row_count' => 0, + ]; + } + + $state = Schema::connection($this->connection->getName())->hasTable(self::STATE_TABLE) + ? $this->connection->table(self::STATE_TABLE) + ->where('dataset_key', self::DATASET_KEY) + ->first() + : null; + $latestDate = $this->connection->table(self::TABLE)->max('report_date'); + $status = (string) ($state->status ?? 'pending'); + $lastSucceededAt = $state->last_succeeded_at ?? null; + + return [ + 'code' => match (true) { + $state === null => 'pending', + $status === 'failed' => 'failed', + $lastSucceededAt === null => 'pending', + default => 'ready', + }, + 'status' => $status, + 'last_succeeded_at' => $lastSucceededAt === null ? null : (string) $lastSucceededAt, + 'last_error' => $state->last_error_code ?? null, + 'latest_date' => $latestDate === null ? null : substr((string) $latestDate, 0, 10), + 'row_count' => (int) ($state->mirror_row_count ?? 0), + ]; + } + + /** @return list */ + public function monthOptions(string $fromMonth, string $toMonth): array + { + if (! $this->available()) { + return []; + } + + $month = $this->monthExpression(); + $months = $this->connection->table(self::TABLE) + ->whereBetween('report_date', [$fromMonth . '-01', $this->monthEnd($toMonth)]) + ->selectRaw($month . ' AS report_month') + ->distinct() + ->orderByDesc('report_month') + ->pluck('report_month') + ->map(static fn (mixed $value): string => substr((string) $value, 0, 7)) + ->filter(static fn (string $value): bool => preg_match('/^\d{4}-\d{2}$/', $value) === 1) + ->values() + ->all(); + + return array_values(array_unique($months)); + } + + /** @return list */ + public function platforms(): array + { + if (! $this->available()) { + return []; + } + + return $this->connection->table(self::TABLE) + ->whereNotNull('platform') + ->where('platform', '<>', '') + ->distinct() + ->orderBy('platform') + ->pluck('platform') + ->map(static fn (mixed $value): string => trim((string) $value)) + ->filter() + ->values() + ->all(); + } + + /** @return list */ + public function stores(string $month, string $platform = ''): array + { + if (! $this->available()) { + return []; + } + + $query = $this->connection->table(self::TABLE) + ->whereBetween('report_date', [$month . '-01', $this->monthEnd($month)]) + ->whereNotNull('store_name') + ->where('store_name', '<>', ''); + if ($platform !== '') { + $query->where('platform', $platform); + } + + return $query->distinct() + ->orderBy('store_name') + ->pluck('store_name') + ->map(static fn (mixed $value): string => trim((string) $value)) + ->filter() + ->values() + ->all(); + } + + /** @return array */ + public function periods( + string $fromMonth, + string $toMonth, + string $platform = '', + string $store = '', + ): array { + if (! $this->available()) { + return []; + } + + $query = $this->connection->table(self::TABLE) + ->whereBetween('report_date', [$fromMonth . '-01', $this->monthEnd($toMonth)]); + $this->applyScope($query, $platform, $store); + + $month = $this->monthExpression(); + $rows = $query + ->selectRaw($month . ' AS period') + ->selectRaw('COALESCE(SUM(source_rows), 0) AS source_rows') + ->selectRaw('COALESCE(SUM(push_fee_total), 0) AS push_fee_total') + ->selectRaw('COALESCE(SUM(marketing_fee_total), 0) AS marketing_fee_total') + ->selectRaw('COALESCE(SUM(total_fee), 0) AS total_fee') + ->groupByRaw($month) + ->orderBy('period') + ->get(); + + return $rows->map(static fn (object $row): array => [ + 'period' => substr((string) $row->period, 0, 7), + 'source_rows' => (int) $row->source_rows, + 'push_fee_total' => round((float) $row->push_fee_total, 2), + 'marketing_fee_total' => round((float) $row->marketing_fee_total, 2), + 'total_fee' => round((float) $row->total_fee, 2), + ])->values()->all(); + } + + /** + * @return array{ + * rows:list>, + * total:int, + * current_page:int, + * last_page:int, + * per_page:int, + * totals:array{push_fee:float,shared_push_fee:float,push_fee_total:float,marketing_fee:float,shared_marketing_fee:float,marketing_fee_total:float,total_fee:float} + * } + */ + public function details( + string $month, + string $platform = '', + string $store = '', + int $page = 1, + int $limit = 50, + ): array { + $page = max(1, $page); + $limit = min(max($limit, 1), 100); + if (! $this->available()) { + return $this->emptyDetails($page, $limit); + } + + $aggregated = $this->aggregateDetails($month, $platform, $store); + $total = $aggregated['total']; + + return [ + 'rows' => array_slice($aggregated['rows'], ($page - 1) * $limit, $limit), + 'total' => $total, + 'current_page' => $page, + 'last_page' => max(1, (int) ceil($total / $limit)), + 'per_page' => $limit, + 'totals' => $aggregated['totals'], + ]; + } + + /** @return list> */ + public function exportDetails(string $month, string $platform = '', string $store = ''): array + { + if (! $this->available()) { + return []; + } + + return $this->aggregateDetails($month, $platform, $store)['rows']; + } + + /** + * @return array{ + * rows:list>, + * total:int, + * totals:array{push_fee:float,shared_push_fee:float,push_fee_total:float,marketing_fee:float,shared_marketing_fee:float,marketing_fee_total:float,total_fee:float} + * } + */ + private function aggregateDetails(string $month, string $platform, string $store): array + { + $query = $this->connection->table(self::TABLE) + ->whereBetween('report_date', [$month . '-01', $this->monthEnd($month)]); + $this->applyScope($query, $platform, $store); + + $rows = $query + ->select(['platform', 'store_name']) + ->selectRaw('COALESCE(SUM(source_rows), 0) AS source_rows') + ->selectRaw('COALESCE(SUM(push_fee), 0) AS push_fee') + ->selectRaw('COALESCE(SUM(shared_push_fee), 0) AS shared_push_fee') + ->selectRaw('COALESCE(SUM(push_fee_total), 0) AS push_fee_total') + ->selectRaw('COALESCE(SUM(marketing_fee), 0) AS marketing_fee') + ->selectRaw('COALESCE(SUM(shared_marketing_fee), 0) AS shared_marketing_fee') + ->selectRaw('COALESCE(SUM(marketing_fee_total), 0) AS marketing_fee_total') + ->selectRaw('COALESCE(SUM(total_fee), 0) AS total_fee') + ->groupBy('platform', 'store_name') + ->get() + ->map(static fn (object $row): array => [ + 'platform' => (string) $row->platform, + 'store_name' => (string) $row->store_name, + 'source_rows' => (int) $row->source_rows, + 'push_fee' => round((float) $row->push_fee, 2), + 'shared_push_fee' => round((float) $row->shared_push_fee, 2), + 'push_fee_total' => round((float) $row->push_fee_total, 2), + 'marketing_fee' => round((float) $row->marketing_fee, 2), + 'shared_marketing_fee' => round((float) $row->shared_marketing_fee, 2), + 'marketing_fee_total' => round((float) $row->marketing_fee_total, 2), + 'total_fee' => round((float) $row->total_fee, 2), + ]) + ->sort(static function (array $left, array $right): int { + return ([$right['total_fee'], $right['push_fee_total']] + <=> [$left['total_fee'], $left['push_fee_total']]) + ?: strcmp($left['platform'], $right['platform']) + ?: strcmp($left['store_name'], $right['store_name']); + }) + ->values(); + + $totals = [ + 'push_fee' => round((float) $rows->sum('push_fee'), 2), + 'shared_push_fee' => round((float) $rows->sum('shared_push_fee'), 2), + 'push_fee_total' => round((float) $rows->sum('push_fee_total'), 2), + 'marketing_fee' => round((float) $rows->sum('marketing_fee'), 2), + 'shared_marketing_fee' => round((float) $rows->sum('shared_marketing_fee'), 2), + 'marketing_fee_total' => round((float) $rows->sum('marketing_fee_total'), 2), + 'total_fee' => round((float) $rows->sum('total_fee'), 2), + ]; + + return [ + 'rows' => $rows->all(), + 'total' => $rows->count(), + 'totals' => $totals, + ]; + } + + /** @param list> $rows */ + public function replaceDate(string $date, array $rows): int + { + $now = now(); + $normalized = array_map(fn (array $row): array => [ + 'report_date' => $date, + 'platform' => (string) ($row['platform'] ?? '未标记'), + 'store_name' => (string) ($row['store_name'] ?? '未标记'), + 'source_rows' => (int) ($row['source_rows'] ?? 0), + 'push_fee' => round((float) ($row['push_fee'] ?? 0), 2), + 'shared_push_fee' => round((float) ($row['shared_push_fee'] ?? 0), 2), + 'push_fee_total' => round((float) ($row['push_fee_total'] ?? 0), 2), + 'marketing_fee' => round((float) ($row['marketing_fee'] ?? 0), 2), + 'shared_marketing_fee' => round((float) ($row['shared_marketing_fee'] ?? 0), 2), + 'marketing_fee_total' => round((float) ($row['marketing_fee_total'] ?? 0), 2), + 'total_fee' => round( + (float) ($row['push_fee_total'] ?? 0) + (float) ($row['marketing_fee_total'] ?? 0), + 2, + ), + 'synced_at' => $now, + ], $rows); + + $this->connection->transaction(function () use ($date, $normalized): void { + $this->connection->table(self::TABLE)->where('report_date', $date)->delete(); + foreach (array_chunk($normalized, 1000) as $chunk) { + $this->connection->table(self::TABLE)->insert($chunk); + } + }); + + return count($normalized); + } + + public function recordSyncState(string $status, int $rowCount, ?string $error = null): void + { + if (! Schema::connection($this->connection->getName())->hasTable(self::STATE_TABLE)) { + return; + } + + $now = now(); + $values = [ + 'source_key' => 'operations_replica', + 'source_object' => 'rpt.dws_sn_sales_full_info_di', + 'target_table' => self::TABLE, + 'status' => $status, + 'last_attempted_at' => $now, + 'mirror_row_count' => $rowCount, + 'last_error_code' => $error, + 'updated_at' => $now, + ]; + if ($status === 'succeeded') { + $values['last_succeeded_at'] = $now; + $values['initial_completed_at'] = $now; + } + + $query = $this->connection->table(self::STATE_TABLE) + ->where('dataset_key', self::DATASET_KEY); + if ($query->exists()) { + $query->update($values); + + return; + } + + $this->connection->table(self::STATE_TABLE)->insert($values + [ + 'dataset_key' => self::DATASET_KEY, + 'created_at' => $now, + ]); + } + + public function count(): int + { + return $this->available() ? (int) $this->connection->table(self::TABLE)->count() : 0; + } + + private function applyScope(Builder $query, string $platform, string $store): void + { + if ($platform !== '') { + $query->where('platform', $platform); + } + if ($store !== '') { + $query->where('store_name', $store); + } + } + + private function monthExpression(): string + { + return $this->connection->getDriverName() === 'sqlite' + ? "strftime('%Y-%m', report_date)" + : "DATE_FORMAT(report_date, '%Y-%m')"; + } + + private function monthEnd(string $month): string + { + return Carbon::createFromFormat('Y-m-d', $month . '-01', 'Asia/Shanghai') + ->endOfMonth() + ->toDateString(); + } + + /** @return array{rows:list,total:int,current_page:int,last_page:int,per_page:int,totals:array} */ + private function emptyDetails(int $page, int $limit): array + { + return [ + 'rows' => [], + 'total' => 0, + 'current_page' => $page, + 'last_page' => 1, + 'per_page' => $limit, + 'totals' => [ + 'push_fee' => 0.0, + 'shared_push_fee' => 0.0, + 'push_fee_total' => 0.0, + 'marketing_fee' => 0.0, + 'shared_marketing_fee' => 0.0, + 'marketing_fee_total' => 0.0, + 'total_fee' => 0.0, + ], + ]; + } +} diff --git a/modules/EcommerceFinance/Services/PromotionExpenseMirrorSynchronizer.php b/modules/EcommerceFinance/Services/PromotionExpenseMirrorSynchronizer.php new file mode 100644 index 00000000..33f314e0 --- /dev/null +++ b/modules/EcommerceFinance/Services/PromotionExpenseMirrorSynchronizer.php @@ -0,0 +1,146 @@ +upstream = $factory->forSourceWithTimeout(self::SOURCE, 120); + } + + /** + * @return array{ + * from:string,to:string,effective_to:?string,days:int,source_rows:int,stored_rows:int + * } + */ + public function sync(Carbon $from, Carbon $to): array + { + if ($from->gt($to)) { + throw new RuntimeException('推广费用同步开始日期不能晚于结束日期。'); + } + + $this->repository->recordSyncState('running', $this->repository->count()); + try { + $latestDate = $this->latestSourceDate(); + $effectiveTo = $latestDate === null + ? null + : Carbon::parse(min($to->toDateString(), $latestDate), 'Asia/Shanghai')->startOfDay(); + if ($effectiveTo === null || $from->gt($effectiveTo)) { + $this->repository->recordSyncState('succeeded', $this->repository->count()); + + return [ + 'from' => $from->toDateString(), + 'to' => $to->toDateString(), + 'effective_to' => $effectiveTo?->toDateString(), + 'days' => 0, + 'source_rows' => 0, + 'stored_rows' => 0, + ]; + } + + $cursor = $from->copy()->startOfDay(); + $sourceRows = 0; + $storedRows = 0; + $days = 0; + + while ($cursor->lte($effectiveTo)) { + $chunkEnd = $cursor->copy()->addDays(self::CHUNK_DAYS - 1)->startOfDay(); + if ($chunkEnd->gt($effectiveTo)) { + $chunkEnd = $effectiveTo->copy(); + } + + $rows = $this->fetchAggregates($cursor->toDateString(), $chunkEnd->toDateString()); + $byDate = []; + foreach ($rows as $row) { + $date = substr((string) ($row['report_date'] ?? ''), 0, 10); + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) !== 1) { + continue; + } + $byDate[$date][] = $row; + $sourceRows += (int) ($row['source_rows'] ?? 0); + } + + for ($date = $cursor->copy(); $date->lte($chunkEnd); $date->addDay()) { + $storedRows += $this->repository->replaceDate( + $date->toDateString(), + $byDate[$date->toDateString()] ?? [], + ); + $days++; + } + + $cursor = $chunkEnd->addDay()->startOfDay(); + } + + $this->repository->recordSyncState('succeeded', $this->repository->count()); + + return [ + 'from' => $from->toDateString(), + 'to' => $to->toDateString(), + 'effective_to' => $effectiveTo->toDateString(), + 'days' => $days, + 'source_rows' => $sourceRows, + 'stored_rows' => $storedRows, + ]; + } catch (Throwable $exception) { + $this->repository->recordSyncState( + 'failed', + $this->repository->count(), + class_basename($exception), + ); + throw $exception; + } + } + + /** @return list> */ + protected function fetchAggregates(string $from, string $to): array + { + $sql = 'SELECT CONVERT(varchar(10), c.stat_date, 23) AS report_date,' + . " ISNULL(NULLIF(LTRIM(RTRIM(c.platform)), N''), N'未标记') AS platform," + . " ISNULL(NULLIF(LTRIM(RTRIM(c.shop_name)), N''), N'未标记') AS store_name," + . ' COUNT_BIG(*) AS source_rows,' + . ' COALESCE(SUM(CAST(COALESCE(c.push_fee, 0) AS decimal(38,2))), 0) AS push_fee,' + . ' COALESCE(SUM(CAST(COALESCE(c.shared_push_fee_sum, 0) AS decimal(38,2))), 0) AS shared_push_fee,' + . ' COALESCE(SUM(CAST(COALESCE(c.push_fee_total, 0) AS decimal(38,2))), 0) AS push_fee_total,' + . ' COALESCE(SUM(CAST(COALESCE(c.marketing_fee, 0) AS decimal(38,2))), 0) AS marketing_fee,' + . ' COALESCE(SUM(CAST(COALESCE(c.shared_market_fee_sum, 0) AS decimal(38,2))), 0) AS shared_marketing_fee,' + . ' COALESCE(SUM(CAST(COALESCE(c.marketing_fee_total, 0) AS decimal(38,2))), 0) AS marketing_fee_total' + . ' FROM rpt.dws_sn_sales_full_info_di c' + . ' WHERE c.stat_date >= CAST(? AS date)' + . ' AND c.stat_date < DATEADD(day, 1, CAST(? AS date))' + . ' GROUP BY CONVERT(varchar(10), c.stat_date, 23),' + . " ISNULL(NULLIF(LTRIM(RTRIM(c.platform)), N''), N'未标记')," + . " ISNULL(NULLIF(LTRIM(RTRIM(c.shop_name)), N''), N'未标记')"; + + return $this->upstream->select($sql, [$from, $to]); + } + + protected function latestSourceDate(): ?string + { + $value = $this->upstream->scalar( + 'SELECT CONVERT(varchar(10), MAX(c.stat_date), 23) FROM rpt.dws_sn_sales_full_info_di c', + ); + + return $value === null || trim((string) $value) === '' + ? null + : substr(trim((string) $value), 0, 10); + } +} diff --git a/modules/EcommerceFinance/View/PromotionExpensePageData.php b/modules/EcommerceFinance/View/PromotionExpensePageData.php new file mode 100644 index 00000000..b99100f0 --- /dev/null +++ b/modules/EcommerceFinance/View/PromotionExpensePageData.php @@ -0,0 +1,204 @@ + '近 6 个月', + '12' => '近 12 个月', + 'ytd' => '本年至今', + ]; + + public function __construct(private readonly PromotionExpenseMirrorRepository $repository) + { + } + + public function page(): array + { + $range = (string) request()->query('range', '12'); + if (! array_key_exists($range, self::RANGE_OPTIONS)) { + $range = '12'; + } + [$fromMonth, $toMonth] = $this->monthRange($range); + $platform = trim((string) request()->query('platform', '')); + $store = trim((string) request()->query('store_name', '')); + + try { + $status = $this->repository->syncStatus(); + $platforms = $this->repository->platforms(); + $months = $this->repository->monthOptions($fromMonth, $toMonth); + $requestedMonth = trim((string) request()->query('month', '')); + $month = preg_match('/^\d{4}-\d{2}$/', $requestedMonth) === 1 + ? $requestedMonth + : ($months[0] ?? $toMonth); + $periods = $this->filledPeriods( + $this->repository->periods($fromMonth, $toMonth, $platform, $store), + $fromMonth, + $toMonth, + ); + $summary = $this->summary($periods, $month); + $details = $this->repository->details( + $month, + $platform, + $store, + max(1, (int) request()->query('page', 1)), + 50, + ); + $rows = new LengthAwarePaginator( + $details['rows'], + $details['total'], + $details['per_page'], + $details['current_page'], + [ + 'path' => request()->url(), + 'query' => request()->query(), + ], + ); + $stores = $this->repository->stores($month, $platform); + + return [ + 'view' => 'business.pages.financial-operations.promotion-expenses', + 'promotionExpenseRange' => $range, + 'promotionExpenseRangeOptions' => self::RANGE_OPTIONS, + 'promotionExpenseFromMonth' => $fromMonth, + 'promotionExpenseToMonth' => $toMonth, + 'promotionExpenseMonth' => $month, + 'promotionExpenseMonths' => $months, + 'promotionExpensePlatform' => $platform, + 'promotionExpensePlatforms' => $platforms, + 'promotionExpenseStore' => $store, + 'promotionExpenseStores' => $stores, + 'promotionExpensePeriods' => $periods, + 'promotionExpenseSummary' => $summary, + 'promotionExpenseTotals' => $details['totals'], + 'promotionExpenseRows' => $rows, + 'promotionExpenseSync' => $status, + 'promotionExpenseError' => $status['code'] === 'unavailable' + ? '推广费用共享镜像尚未初始化,请完成数据库升级并等待自动同步。' + : null, + ]; + } catch (Throwable $exception) { + report($exception); + $emptyRows = new LengthAwarePaginator([], 0, 50, 1, [ + 'path' => request()->url(), + 'query' => request()->query(), + ]); + + return [ + 'view' => 'business.pages.financial-operations.promotion-expenses', + 'promotionExpenseRange' => $range, + 'promotionExpenseRangeOptions' => self::RANGE_OPTIONS, + 'promotionExpenseFromMonth' => $fromMonth, + 'promotionExpenseToMonth' => $toMonth, + 'promotionExpenseMonth' => $toMonth, + 'promotionExpenseMonths' => [], + 'promotionExpensePlatform' => $platform, + 'promotionExpensePlatforms' => [], + 'promotionExpenseStore' => $store, + 'promotionExpenseStores' => [], + 'promotionExpensePeriods' => [], + 'promotionExpenseSummary' => $this->emptySummary(), + 'promotionExpenseTotals' => [], + 'promotionExpenseRows' => $emptyRows, + 'promotionExpenseSync' => [], + 'promotionExpenseError' => '推广费用数据暂时无法读取,请稍后重试。', + ]; + } + } + + public function exportRows(string $month, string $platform = '', string $store = ''): array + { + return $this->repository->exportDetails($month, $platform, $store); + } + + /** @return array{0:string,1:string} */ + private function monthRange(string $range): array + { + $current = Carbon::now('Asia/Shanghai')->startOfMonth(); + $from = match ($range) { + '6' => $current->copy()->subMonthsNoOverflow(5), + 'ytd' => $current->copy()->startOfYear(), + default => $current->copy()->subMonthsNoOverflow(11), + }; + + return [$from->format('Y-m'), $current->format('Y-m')]; + } + + /** + * @param list $rows + * @return list + */ + private function filledPeriods(array $rows, string $fromMonth, string $toMonth): array + { + $byMonth = array_column($rows, null, 'period'); + $periods = []; + $cursor = Carbon::createFromFormat('Y-m-d', $fromMonth . '-01', 'Asia/Shanghai')->startOfMonth(); + $end = Carbon::createFromFormat('Y-m-d', $toMonth . '-01', 'Asia/Shanghai')->startOfMonth(); + while ($cursor->lte($end)) { + $period = $cursor->format('Y-m'); + $periods[] = $byMonth[$period] ?? [ + 'period' => $period, + 'source_rows' => 0, + 'push_fee_total' => 0.0, + 'marketing_fee_total' => 0.0, + 'total_fee' => 0.0, + ]; + $cursor->addMonthNoOverflow(); + } + + return $periods; + } + + /** @param list> $periods */ + private function summary(array $periods, string $month): array + { + $currentIndex = null; + foreach ($periods as $index => $period) { + if ($period['period'] === $month) { + $currentIndex = $index; + break; + } + } + $current = $currentIndex === null ? $this->emptyPeriod($month) : $periods[$currentIndex]; + $previousRows = $currentIndex === null ? [] : array_slice($periods, 0, $currentIndex); + $previous = $previousRows === [] ? null : end($previousRows); + $previousTotal = (float) ($previous['total_fee'] ?? 0); + + return array_replace($current, [ + 'previous_period' => $previous['period'] ?? null, + 'previous_total_fee' => round($previousTotal, 2), + 'total_change_rate' => $previousTotal !== 0.0 + ? round((($current['total_fee'] - $previousTotal) / abs($previousTotal)) * 100, 1) + : null, + ]); + } + + /** @return array */ + private function emptyPeriod(string $month): array + { + return [ + 'period' => $month, + 'source_rows' => 0, + 'push_fee_total' => 0.0, + 'marketing_fee_total' => 0.0, + 'total_fee' => 0.0, + ]; + } + + /** @return array */ + private function emptySummary(): array + { + return array_replace($this->emptyPeriod(''), [ + 'previous_period' => null, + 'previous_total_fee' => 0.0, + 'total_change_rate' => null, + ]); + } +} diff --git a/resources/views/business/pages/financial-operations/promotion-expenses.blade.php b/resources/views/business/pages/financial-operations/promotion-expenses.blade.php new file mode 100644 index 00000000..8738ca6f --- /dev/null +++ b/resources/views/business/pages/financial-operations/promotion-expenses.blade.php @@ -0,0 +1,533 @@ +@php + $periods = $promotionExpensePeriods ?? []; + $summary = $promotionExpenseSummary ?? []; + $rows = $promotionExpenseRows; + $sync = $promotionExpenseSync ?? []; + $error = $promotionExpenseError ?? null; + $money = static fn (mixed $value): string => number_format((float) $value, 2); + $moneyWan = static fn (mixed $value): string => number_format((float) $value / 10000, 2); + $percent = static fn (mixed $value): string => number_format((float) $value, 1); + $range = $promotionExpenseRange ?? '12'; + $rangeOptions = $promotionExpenseRangeOptions ?? []; + $month = $promotionExpenseMonth ?? ''; + $months = $promotionExpenseMonths ?? []; + $platform = $promotionExpensePlatform ?? ''; + $platforms = $promotionExpensePlatforms ?? []; + $store = $promotionExpenseStore ?? ''; + $stores = $promotionExpenseStores ?? []; + $exportUrl = route('business.financial-operations.promotion-expenses.export', array_filter([ + 'month' => $month, + 'platform' => $platform, + 'store_name' => $store, + ], static fn (mixed $value): bool => $value !== null && $value !== '')); +@endphp + +
+ + +
+
+ + + + +
+
+ + + + 导出本月明细 + +
+
+ +
+ 数据来源:聚水潭经营分析副本 + 最新数据日期:{{ $sync['latest_date'] ?? '—' }} + 最近自动同步:{{ $sync['last_succeeded_at'] ?? '尚未完成' }} + @if (($sync['code'] ?? '') === 'ready') + 已同步 + @elseif (($sync['code'] ?? '') === 'failed') + 同步异常,当前展示上一版数据 + @else + 等待首次同步 + @endif +
+ + @if ($error) + + @endif + + @if (! $error) +
+
+ {{ $month }} 源记录 + {{ number_format((int) ($summary['source_rows'] ?? 0)) }} 条 + 按订单行汇总后去重到平台与店铺 +
+
+ {{ $month }} 推广费用 + ¥{{ $money($summary['push_fee_total'] ?? 0) }} + 直接推广费 + 分摊推广费 +
+
+ {{ $month }} 营销费用 + ¥{{ $money($summary['marketing_fee_total'] ?? 0) }} + 直接营销费 + 分摊营销费 +
+
+ {{ $month }} 费用合计 + ¥{{ $moneyWan($summary['total_fee'] ?? 0) }} 万 + + @if (($summary['total_change_rate'] ?? null) === null) + 上月无可比数据 + @else + 较 {{ $summary['previous_period'] }} {{ $summary['total_change_rate'] > 0 ? '+' : '' }}{{ $percent($summary['total_change_rate']) }}% + @endif + +
+
+ +

+ 费用口径:推广费用取聚水潭经营分析中的直接推广费与分摊推广费,营销费用同样分别保留直接值和分摊值。 + 每日自动同步最近数据,同一天重跑时会整日替换,避免订单改单或删除后留下旧汇总。 +

+ +
+
+ 月度推广费用对比 + {{ $promotionExpenseFromMonth }} 至 {{ $promotionExpenseToMonth }} · 最近月份优先 +
+
+ + + + + + + + + + + + @forelse (array_reverse($periods) as $period) + + + + + + + + @empty + + + + @endforelse + +
月份源记录推广费用(元)营销费用(元)费用合计(元)
+ {{ $period['period'] }} + @if ($period['period'] === $month) + 当前 + @endif + {{ number_format((int) $period['source_rows']) }}¥{{ $money($period['push_fee_total']) }}¥{{ $money($period['marketing_fee_total']) }}¥{{ $money($period['total_fee']) }}
所选区间暂无推广费用数据。
+
+
+ +
+
+ {{ $month }} 平台与店铺明细 + 按费用合计从高到低 · 共 {{ number_format($rows->total()) }} 个平台店铺组合 +
+
+ + + + + + + + + + + + + + + + + @forelse ($rows as $row) + + + + + + + + + + + + + @empty + + + + @endforelse + + @if ($rows->isNotEmpty()) + + + + + + + + + + + + + + @endif +
平台店铺名称源记录直接推广费分摊推广费推广费用直接营销费分摊营销费营销费用费用合计
{{ $row['platform'] }}{{ $row['store_name'] }}{{ number_format((int) $row['source_rows']) }}¥{{ $money($row['push_fee']) }}¥{{ $money($row['shared_push_fee']) }}¥{{ $money($row['push_fee_total']) }}¥{{ $money($row['marketing_fee']) }}¥{{ $money($row['shared_marketing_fee']) }}¥{{ $money($row['marketing_fee_total']) }}¥{{ $money($row['total_fee']) }}
+ 该月尚无推广费用镜像,自动同步完成后会在这里展示。 +
合计{{ number_format((int) ($promotionExpenseTotals['source_rows'] ?? ($summary['source_rows'] ?? 0))) }}¥{{ $money($promotionExpenseTotals['push_fee'] ?? 0) }}¥{{ $money($promotionExpenseTotals['shared_push_fee'] ?? 0) }}¥{{ $money($promotionExpenseTotals['push_fee_total'] ?? 0) }}¥{{ $money($promotionExpenseTotals['marketing_fee'] ?? 0) }}¥{{ $money($promotionExpenseTotals['shared_marketing_fee'] ?? 0) }}¥{{ $money($promotionExpenseTotals['marketing_fee_total'] ?? 0) }}¥{{ $money($promotionExpenseTotals['total_fee'] ?? 0) }}
+
+
+ + @if ($rows->total() > 0) + 第 {{ $rows->firstItem() }} - {{ $rows->lastItem() }} 条 / 共 {{ $rows->total() }} 条 + @else + 暂无记录 + @endif + + @if ($rows->lastPage() > 1) + + @endif +
+
+ @endif +
diff --git a/routes/admin.php b/routes/admin.php index d98b8ae1..dad0ae7d 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -353,6 +353,10 @@ Route::get('workspace/product-inventory/monthly-weighted-average-price/export', ->middleware('business.page:financial-operations,product-costs') ->name('business.financial-operations.product-costs.pending-details.export'); + Route::get('workspace/financial-operations/promotion-expenses/export', 'Business\Pages@exportPromotionExpenses') + ->middleware('business.page:financial-operations,promotion-expenses') + ->name('business.financial-operations.promotion-expenses.export'); + Route::get('workspace/financial-operations/financial-analysis/export', 'Business\Pages@exportFinancialAnalysis') ->middleware('business.page:financial-operations,financial-analysis') ->name('business.financial-operations.financial-analysis.export'); diff --git a/tests/Feature/Business/PromotionExpensePageTest.php b/tests/Feature/Business/PromotionExpensePageTest.php new file mode 100644 index 00000000..d4d601f8 --- /dev/null +++ b/tests/Feature/Business/PromotionExpensePageTest.php @@ -0,0 +1,124 @@ +hasTable(PromotionExpenseMirrorRepository::TABLE)) { + $schema->create(PromotionExpenseMirrorRepository::TABLE, function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->date('report_date'); + $table->string('platform', 64); + $table->string('store_name', 255); + $table->unsignedBigInteger('source_rows')->default(0); + $table->decimal('push_fee', 20, 2)->default(0); + $table->decimal('shared_push_fee', 20, 2)->default(0); + $table->decimal('push_fee_total', 20, 2)->default(0); + $table->decimal('marketing_fee', 20, 2)->default(0); + $table->decimal('shared_marketing_fee', 20, 2)->default(0); + $table->decimal('marketing_fee_total', 20, 2)->default(0); + $table->decimal('total_fee', 20, 2)->default(0); + $table->timestamp('synced_at')->nullable(); + }); + } + if (! $schema->hasTable(PromotionExpenseMirrorRepository::STATE_TABLE)) { + $schema->create(PromotionExpenseMirrorRepository::STATE_TABLE, function (Blueprint $table): void { + $table->string('dataset_key', 191)->primary(); + $table->string('source_key', 64); + $table->string('source_object', 191); + $table->string('target_table', 64); + $table->string('status', 24); + $table->dateTime('initial_completed_at')->nullable(); + $table->dateTime('last_attempted_at')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + $table->unsignedBigInteger('mirror_row_count')->default(0); + $table->string('last_error_code', 120)->nullable(); + $table->timestamps(); + }); + } + } + + public function test_page_and_export_use_the_automatic_promotion_expense_mirror(): void + { + Carbon::setTestNow(Carbon::parse('2026-11-27 10:00:00', 'Asia/Shanghai')); + DB::connection('business_mirror')->table(PromotionExpenseMirrorRepository::TABLE)->insert([ + [ + 'report_date' => '2026-10-31', + 'platform' => '淘系', + 'store_name' => '天猫-甲店', + 'source_rows' => 100, + 'push_fee' => 1000, + 'shared_push_fee' => 2000, + 'push_fee_total' => 3000, + 'marketing_fee' => 300, + 'shared_marketing_fee' => 200, + 'marketing_fee_total' => 500, + 'total_fee' => 3500, + ], + [ + 'report_date' => '2026-11-25', + 'platform' => '抖音', + 'store_name' => '抖音-乙店', + 'source_rows' => 200, + 'push_fee' => 4000, + 'shared_push_fee' => 1000, + 'push_fee_total' => 5000, + 'marketing_fee' => 800, + 'shared_marketing_fee' => 200, + 'marketing_fee_total' => 1000, + 'total_fee' => 6000, + ], + ]); + DB::connection('business_mirror')->table(PromotionExpenseMirrorRepository::STATE_TABLE)->insert([ + 'dataset_key' => PromotionExpenseMirrorRepository::DATASET_KEY, + 'source_key' => 'operations_replica', + 'source_object' => 'rpt.dws_sn_sales_full_info_di', + 'target_table' => PromotionExpenseMirrorRepository::TABLE, + 'status' => 'succeeded', + 'initial_completed_at' => '2026-11-27 03:10:00', + 'last_attempted_at' => '2026-11-27 03:10:00', + 'last_succeeded_at' => '2026-11-27 03:10:00', + 'mirror_row_count' => 2, + 'created_at' => '2026-11-27 03:10:00', + 'updated_at' => '2026-11-27 03:10:00', + ]); + + $this->loginAs() + ->get(route('business.pages.show', [ + 'section' => 'financial-operations', + 'page' => 'promotion-expenses', + 'month' => '2026-11', + ])) + ->assertOk() + ->assertSeeText('月度推广费用对比') + ->assertSeeText('抖音-乙店') + ->assertSeeText('¥5,000.00') + ->assertSeeText('¥1,000.00') + ->assertSeeText('¥6,000.00') + ->assertSeeText('200 条') + ->assertSeeText('2026-11-25'); + + $response = $this->get(route('business.financial-operations.promotion-expenses.export', [ + 'month' => '2026-11', + 'platform' => '抖音', + ])); + $response->assertOk(); + $this->assertStringContainsString( + '聚水潭推广费用_2026-11.csv', + rawurldecode((string) $response->headers->get('content-disposition')), + ); + $this->assertStringContainsString('抖音,抖音-乙店,200,4000.00', $response->streamedContent()); + } +} diff --git a/tests/Unit/Deployment/PromotionExpenseScheduleTest.php b/tests/Unit/Deployment/PromotionExpenseScheduleTest.php new file mode 100644 index 00000000..1bf64cc8 --- /dev/null +++ b/tests/Unit/Deployment/PromotionExpenseScheduleTest.php @@ -0,0 +1,24 @@ +assertIsString($contents); + $this->assertStringContainsString($schedule, $contents, $file); + } + + $runner = file_get_contents($root . '/deploy/run-finance-batch.sh'); + $this->assertIsString($runner); + $this->assertStringContainsString('business-mirror:sync-promotion-expenses', $runner); + } +} diff --git a/tests/Unit/EcommerceFinance/PromotionExpenseMirrorRepositoryTest.php b/tests/Unit/EcommerceFinance/PromotionExpenseMirrorRepositoryTest.php new file mode 100644 index 00000000..1096e013 --- /dev/null +++ b/tests/Unit/EcommerceFinance/PromotionExpenseMirrorRepositoryTest.php @@ -0,0 +1,173 @@ +createMirrorTables(); + $this->repository = new PromotionExpenseMirrorRepository(); + } + + public function test_it_builds_monthly_and_store_summaries_from_the_daily_mirror(): void + { + DB::connection('business_mirror')->table(PromotionExpenseMirrorRepository::TABLE)->insert([ + [ + 'report_date' => '2026-10-01', + 'platform' => '淘系', + 'store_name' => '天猫-甲店', + 'source_rows' => 10, + 'push_fee' => 20, + 'shared_push_fee' => 30, + 'push_fee_total' => 50, + 'marketing_fee' => 5, + 'shared_marketing_fee' => 10, + 'marketing_fee_total' => 15, + 'total_fee' => 65, + 'synced_at' => '2026-11-27 03:10:00', + ], + [ + 'report_date' => '2026-10-02', + 'platform' => '拼多多', + 'store_name' => '拼多多-乙店', + 'source_rows' => 20, + 'push_fee' => 40, + 'shared_push_fee' => 10, + 'push_fee_total' => 50, + 'marketing_fee' => 5, + 'shared_marketing_fee' => 0, + 'marketing_fee_total' => 5, + 'total_fee' => 55, + 'synced_at' => '2026-11-27 03:10:00', + ], + [ + 'report_date' => '2026-11-25', + 'platform' => '抖音', + 'store_name' => '抖音-丙店', + 'source_rows' => 30, + 'push_fee' => 60, + 'shared_push_fee' => 10, + 'push_fee_total' => 70, + 'marketing_fee' => 8, + 'shared_marketing_fee' => 2, + 'marketing_fee_total' => 10, + 'total_fee' => 80, + 'synced_at' => '2026-11-27 03:10:00', + ], + ]); + + $this->assertSame( + [['period' => '2026-10', 'source_rows' => 30, 'push_fee_total' => 100.0, 'marketing_fee_total' => 20.0, 'total_fee' => 120.0]], + $this->repository->periods('2026-10', '2026-10'), + ); + + $details = $this->repository->details('2026-10', '', '', 1, 1); + $this->assertSame(2, $details['total']); + $this->assertCount(1, $details['rows']); + $this->assertSame('天猫-甲店', $details['rows'][0]['store_name']); + $this->assertSame(120.0, $details['totals']['total_fee']); + + $filtered = $this->repository->details('2026-10', '拼多多', '拼多多-乙店', 1, 50); + $this->assertSame(1, $filtered['total']); + $this->assertSame(55.0, $filtered['rows'][0]['total_fee']); + } + + public function test_replacing_one_date_removes_stale_store_rows_for_that_date_only(): void + { + DB::connection('business_mirror')->table(PromotionExpenseMirrorRepository::TABLE)->insert([ + [ + 'report_date' => '2026-10-01', + 'platform' => '淘系', + 'store_name' => '旧店', + 'source_rows' => 1, + 'push_fee_total' => 1, + 'marketing_fee_total' => 0, + 'total_fee' => 1, + ], + [ + 'report_date' => '2026-10-02', + 'platform' => '淘系', + 'store_name' => '保留店', + 'source_rows' => 1, + 'push_fee_total' => 1, + 'marketing_fee_total' => 0, + 'total_fee' => 1, + ], + ]); + + $stored = $this->repository->replaceDate('2026-10-01', [[ + 'platform' => '淘系', + 'store_name' => '新店', + 'source_rows' => 2, + 'push_fee' => 10, + 'shared_push_fee' => 5, + 'push_fee_total' => 15, + 'marketing_fee' => 3, + 'shared_marketing_fee' => 2, + 'marketing_fee_total' => 5, + ]]); + + $this->assertSame(1, $stored); + $this->assertDatabaseMissing(PromotionExpenseMirrorRepository::TABLE, [ + 'report_date' => '2026-10-01', + 'store_name' => '旧店', + ], 'business_mirror'); + $this->assertDatabaseHas(PromotionExpenseMirrorRepository::TABLE, [ + 'report_date' => '2026-10-01', + 'store_name' => '新店', + 'total_fee' => 20, + ], 'business_mirror'); + $this->assertDatabaseHas(PromotionExpenseMirrorRepository::TABLE, [ + 'report_date' => '2026-10-02', + 'store_name' => '保留店', + ], 'business_mirror'); + } + + private function createMirrorTables(): void + { + $schema = Schema::connection('business_mirror'); + if (! $schema->hasTable(PromotionExpenseMirrorRepository::TABLE)) { + $schema->create(PromotionExpenseMirrorRepository::TABLE, function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->date('report_date'); + $table->string('platform', 64); + $table->string('store_name', 255); + $table->unsignedBigInteger('source_rows')->default(0); + $table->decimal('push_fee', 20, 2)->default(0); + $table->decimal('shared_push_fee', 20, 2)->default(0); + $table->decimal('push_fee_total', 20, 2)->default(0); + $table->decimal('marketing_fee', 20, 2)->default(0); + $table->decimal('shared_marketing_fee', 20, 2)->default(0); + $table->decimal('marketing_fee_total', 20, 2)->default(0); + $table->decimal('total_fee', 20, 2)->default(0); + $table->timestamp('synced_at')->nullable(); + }); + } + if (! $schema->hasTable(PromotionExpenseMirrorRepository::STATE_TABLE)) { + $schema->create(PromotionExpenseMirrorRepository::STATE_TABLE, function (Blueprint $table): void { + $table->string('dataset_key', 191)->primary(); + $table->string('source_key', 64); + $table->string('source_object', 191); + $table->string('target_table', 64); + $table->string('status', 24); + $table->dateTime('initial_completed_at')->nullable(); + $table->dateTime('last_attempted_at')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + $table->unsignedBigInteger('mirror_row_count')->default(0); + $table->string('last_error_code', 120)->nullable(); + $table->timestamps(); + }); + } + } +} diff --git a/tests/Unit/EcommerceFinance/PromotionExpenseMirrorSynchronizerTest.php b/tests/Unit/EcommerceFinance/PromotionExpenseMirrorSynchronizerTest.php new file mode 100644 index 00000000..94ad2a7d --- /dev/null +++ b/tests/Unit/EcommerceFinance/PromotionExpenseMirrorSynchronizerTest.php @@ -0,0 +1,141 @@ +hasTable(PromotionExpenseMirrorRepository::TABLE)) { + $schema->create(PromotionExpenseMirrorRepository::TABLE, function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->date('report_date'); + $table->string('platform', 64); + $table->string('store_name', 255); + $table->unsignedBigInteger('source_rows')->default(0); + $table->decimal('push_fee', 20, 2)->default(0); + $table->decimal('shared_push_fee', 20, 2)->default(0); + $table->decimal('push_fee_total', 20, 2)->default(0); + $table->decimal('marketing_fee', 20, 2)->default(0); + $table->decimal('shared_marketing_fee', 20, 2)->default(0); + $table->decimal('marketing_fee_total', 20, 2)->default(0); + $table->decimal('total_fee', 20, 2)->default(0); + $table->timestamp('synced_at')->nullable(); + }); + } + if (! $schema->hasTable(PromotionExpenseMirrorRepository::STATE_TABLE)) { + $schema->create(PromotionExpenseMirrorRepository::STATE_TABLE, function (Blueprint $table): void { + $table->string('dataset_key', 191)->primary(); + $table->string('source_key', 64); + $table->string('source_object', 191); + $table->string('target_table', 64); + $table->string('status', 24); + $table->dateTime('initial_completed_at')->nullable(); + $table->dateTime('last_attempted_at')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + $table->unsignedBigInteger('mirror_row_count')->default(0); + $table->string('last_error_code', 120)->nullable(); + $table->timestamps(); + }); + } + } + + public function test_it_replaces_each_day_with_the_latest_upstream_aggregate(): void + { + DB::connection('business_mirror')->table(PromotionExpenseMirrorRepository::TABLE)->insert([ + 'report_date' => '2026-10-01', + 'platform' => '淘系', + 'store_name' => '旧店', + 'source_rows' => 1, + 'push_fee_total' => 1, + 'marketing_fee_total' => 0, + 'total_fee' => 1, + ]); + + $factory = Mockery::mock(UpstreamReadOnlyQueryFactory::class); + $factory->shouldReceive('forSourceWithTimeout') + ->once() + ->andReturn(Mockery::mock(UpstreamReadOnlyQuery::class)); + $synchronizer = new class($factory, new PromotionExpenseMirrorRepository()) extends PromotionExpenseMirrorSynchronizer { + protected function latestSourceDate(): ?string + { + return '2026-10-02'; + } + + protected function fetchAggregates(string $from, string $to): array + { + return [ + [ + 'report_date' => '2026-10-01', + 'platform' => '淘系', + 'store_name' => '新店', + 'source_rows' => 5, + 'push_fee' => 10, + 'shared_push_fee' => 20, + 'push_fee_total' => 30, + 'marketing_fee' => 4, + 'shared_marketing_fee' => 6, + 'marketing_fee_total' => 10, + ], + [ + 'report_date' => '2026-10-02', + 'platform' => '拼多多', + 'store_name' => '乙店', + 'source_rows' => 7, + 'push_fee' => 40, + 'shared_push_fee' => 0, + 'push_fee_total' => 40, + 'marketing_fee' => 5, + 'shared_marketing_fee' => 0, + 'marketing_fee_total' => 5, + ], + ]; + } + }; + + $result = $synchronizer->sync( + Carbon::parse('2026-10-01', 'Asia/Shanghai'), + Carbon::parse('2026-10-03', 'Asia/Shanghai'), + ); + + $this->assertSame(2, $result['days']); + $this->assertSame(12, $result['source_rows']); + $this->assertSame(2, $result['stored_rows']); + $this->assertDatabaseMissing(PromotionExpenseMirrorRepository::TABLE, [ + 'report_date' => '2026-10-01', + 'store_name' => '旧店', + ], 'business_mirror'); + $this->assertDatabaseHas(PromotionExpenseMirrorRepository::TABLE, [ + 'report_date' => '2026-10-01', + 'store_name' => '新店', + 'total_fee' => 40, + ], 'business_mirror'); + $this->assertDatabaseHas(PromotionExpenseMirrorRepository::TABLE, [ + 'report_date' => '2026-10-02', + 'store_name' => '乙店', + 'total_fee' => 45, + ], 'business_mirror'); + $this->assertDatabaseMissing(PromotionExpenseMirrorRepository::TABLE, [ + 'report_date' => '2026-10-03', + ], 'business_mirror'); + $this->assertDatabaseHas(PromotionExpenseMirrorRepository::STATE_TABLE, [ + 'dataset_key' => PromotionExpenseMirrorRepository::DATASET_KEY, + 'status' => 'succeeded', + 'mirror_row_count' => 2, + ], 'business_mirror'); + } +}