feat(推广费用): 自动同步聚水潭推广费用到共享镜像 #1506
74
app/Console/Commands/SyncPromotionExpenses.php
Normal file
74
app/Console/Commands/SyncPromotionExpenses.php
Normal file
@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\EcommerceFinance\Services\PromotionExpenseMirrorSynchronizer;
|
||||
use Throwable;
|
||||
|
||||
class SyncPromotionExpenses extends Command
|
||||
{
|
||||
private const HISTORY_START = '2026-01-01';
|
||||
|
||||
protected $signature = 'business-mirror:sync-promotion-expenses
|
||||
{--from= : 开始日期(含)}
|
||||
{--to= : 结束日期(含)}
|
||||
{--days=7 : 未指定 from/to 时同步最近多少天}
|
||||
{--full : 从 2026-01-01 开始完整校准}';
|
||||
|
||||
protected $description = '按日期、平台和店铺自动汇总聚水潭推广费用到共享镜像';
|
||||
|
||||
public function handle(PromotionExpenseMirrorSynchronizer $synchronizer): int
|
||||
{
|
||||
try {
|
||||
[$from, $to] = $this->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];
|
||||
}
|
||||
}
|
||||
@ -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')
|
||||
|
||||
@ -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()),
|
||||
|
||||
@ -0,0 +1,70 @@
|
||||
<?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
|
||||
{
|
||||
if (app()->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');
|
||||
}
|
||||
};
|
||||
@ -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 核查标签覆盖,同步本月/上月种菜报销并重算种菜金额。
|
||||
|
||||
@ -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 核查标签覆盖,同步本月/上月种菜报销并重算种菜金额。
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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/空”筛选,分别标记“成本异常”“运费异常”,并在订单下按具体商品编码展示缺成本条码,以发货时间为监控日期。 |
|
||||
|
||||
@ -0,0 +1,405 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Repositories;
|
||||
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 聚水潭推广费用日汇总镜像。
|
||||
*
|
||||
* 页面只读此表;上游按“日期 + 平台 + 店铺”聚合后再落库,避免订单级
|
||||
* 大表在页面请求中现场扫描。
|
||||
*/
|
||||
class PromotionExpenseMirrorRepository
|
||||
{
|
||||
public const TABLE = 'promotion_expense_daily_rows';
|
||||
|
||||
public const STATE_TABLE = 'business_mirror_table_states';
|
||||
|
||||
public const DATASET_KEY = 'derived.promotion-expenses-daily';
|
||||
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->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<string> */
|
||||
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<string> */
|
||||
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<string> */
|
||||
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<int,array{period:string,source_rows:int,push_fee_total:float,marketing_fee_total:float,total_fee:float}> */
|
||||
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<array<string,mixed>>,
|
||||
* 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<array<string,mixed>> */
|
||||
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<array<string,mixed>>,
|
||||
* 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<array<string,mixed>> $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<mixed>,total:int,current_page:int,last_page:int,per_page:int,totals:array<string,float>} */
|
||||
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,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
use Modules\EcommerceFinance\Repositories\PromotionExpenseMirrorRepository;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 从聚水潭经营分析副本按日期聚合推广费用,写入页面专用共享镜像。
|
||||
*/
|
||||
class PromotionExpenseMirrorSynchronizer
|
||||
{
|
||||
private const SOURCE = 'operations_replica';
|
||||
|
||||
private const SOURCE_OBJECT = 'rpt.dws_sn_sales_full_info_di';
|
||||
|
||||
private const CHUNK_DAYS = 3;
|
||||
|
||||
private readonly UpstreamReadOnlyQuery $upstream;
|
||||
|
||||
public function __construct(
|
||||
UpstreamReadOnlyQueryFactory $factory,
|
||||
private readonly PromotionExpenseMirrorRepository $repository,
|
||||
) {
|
||||
$this->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<array<string,mixed>> */
|
||||
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);
|
||||
}
|
||||
}
|
||||
204
modules/EcommerceFinance/View/PromotionExpensePageData.php
Normal file
204
modules/EcommerceFinance/View/PromotionExpensePageData.php
Normal file
@ -0,0 +1,204 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\View;
|
||||
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Modules\EcommerceFinance\Repositories\PromotionExpenseMirrorRepository;
|
||||
use Throwable;
|
||||
|
||||
/** 财务经营报表 › 推广费用。 */
|
||||
class PromotionExpensePageData
|
||||
{
|
||||
public const RANGE_OPTIONS = [
|
||||
'6' => '近 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<array{period:string,source_rows:int,push_fee_total:float,marketing_fee_total:float,total_fee:float}> $rows
|
||||
* @return list<array{period:string,source_rows:int,push_fee_total:float,marketing_fee_total:float,total_fee:float}>
|
||||
*/
|
||||
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<array<string,mixed>> $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<string,mixed> */
|
||||
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<string,mixed> */
|
||||
private function emptySummary(): array
|
||||
{
|
||||
return array_replace($this->emptyPeriod(''), [
|
||||
'previous_period' => null,
|
||||
'previous_total_fee' => 0.0,
|
||||
'total_change_rate' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -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
|
||||
|
||||
<div class="promotion-expense-page">
|
||||
<style>
|
||||
.promotion-expense-page {
|
||||
--pe-ink: var(--vip-content-ink, #171717);
|
||||
--pe-muted: var(--vip-content-muted, #595959);
|
||||
--pe-border: var(--vip-border, #d8d2c7);
|
||||
--pe-surface: var(--vip-surface, #ffffff);
|
||||
--pe-soft: var(--vip-content-accent-soft, #f7f0de);
|
||||
--pe-accent: var(--vip-content-accent, #b9954f);
|
||||
--pe-accent-dark: var(--vip-content-accent-dark, #856632);
|
||||
--pe-success: var(--vip-success, #53793e);
|
||||
--pe-warning: var(--vip-warning, #935f07);
|
||||
color: var(--pe-ink);
|
||||
font-family: "JetBrains Mono", "Microsoft YaHei", "PingFang SC", monospace;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
.promotion-expense-toolbar {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
padding: 1rem;
|
||||
border: 1px solid var(--pe-border);
|
||||
border-radius: 0.5rem;
|
||||
background: var(--pe-surface);
|
||||
}
|
||||
.promotion-expense-filters,
|
||||
.promotion-expense-actions {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.promotion-expense-field {
|
||||
display: flex;
|
||||
min-width: 10rem;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
.promotion-expense-field > span {
|
||||
color: var(--pe-muted);
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.promotion-expense-field select,
|
||||
.promotion-expense-field input {
|
||||
height: 2.125rem;
|
||||
min-width: 10rem;
|
||||
padding: 0 0.65rem;
|
||||
border: 1px solid var(--pe-border);
|
||||
border-radius: 0.5rem;
|
||||
outline: none;
|
||||
background: var(--pe-surface);
|
||||
color: var(--pe-ink);
|
||||
font: inherit;
|
||||
}
|
||||
.promotion-expense-field select:focus,
|
||||
.promotion-expense-field input:focus {
|
||||
border-color: var(--pe-accent-dark);
|
||||
box-shadow: 0 0 0 3px rgba(133, 102, 50, 0.2);
|
||||
}
|
||||
.promotion-expense-button {
|
||||
display: inline-flex;
|
||||
height: 2.125rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.35rem;
|
||||
padding: 0 0.85rem;
|
||||
border: 1px solid var(--pe-border);
|
||||
border-radius: 0.5rem;
|
||||
background: var(--pe-surface);
|
||||
color: var(--pe-ink);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
}
|
||||
.promotion-expense-button.is-primary {
|
||||
border-color: var(--pe-accent-dark);
|
||||
background: var(--pe-accent-dark);
|
||||
color: #fff;
|
||||
}
|
||||
.promotion-expense-button:focus-visible {
|
||||
outline: 3px solid rgba(133, 102, 50, 0.2);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.promotion-expense-sync {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 0.75rem;
|
||||
color: var(--pe-muted);
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
.promotion-expense-sync strong {
|
||||
color: var(--pe-ink);
|
||||
font-weight: 600;
|
||||
}
|
||||
.promotion-expense-sync .is-ready {
|
||||
color: var(--pe-success);
|
||||
}
|
||||
.promotion-expense-alert {
|
||||
margin-top: 0.75rem;
|
||||
padding: 0.75rem 1rem;
|
||||
border: 1px solid #b80000;
|
||||
border-radius: 0.5rem;
|
||||
background: #fff5f5;
|
||||
color: #b80000;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.promotion-expense-kpis {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
margin-top: 0.75rem;
|
||||
border: 1px solid var(--pe-border);
|
||||
border-radius: 0.5rem;
|
||||
background: var(--pe-surface);
|
||||
}
|
||||
.promotion-expense-kpi {
|
||||
min-width: 0;
|
||||
padding: 0.9rem 1rem;
|
||||
border-right: 1px solid var(--pe-border);
|
||||
}
|
||||
.promotion-expense-kpi:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
.promotion-expense-kpi > span {
|
||||
display: block;
|
||||
color: var(--pe-muted);
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
.promotion-expense-kpi > strong {
|
||||
display: block;
|
||||
margin-top: 0.35rem;
|
||||
overflow: hidden;
|
||||
color: var(--pe-ink);
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1.25;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.promotion-expense-kpi > small {
|
||||
display: block;
|
||||
margin-top: 0.25rem;
|
||||
color: var(--pe-muted);
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
.promotion-expense-kpi .is-increase { color: var(--pe-warning); }
|
||||
.promotion-expense-kpi .is-saving { color: var(--pe-success); }
|
||||
.promotion-expense-rule {
|
||||
margin: 0.75rem 0 0;
|
||||
padding: 0.7rem 0.9rem;
|
||||
border: 1px solid var(--pe-border);
|
||||
border-left: 3px solid var(--pe-accent);
|
||||
border-radius: 0.5rem;
|
||||
background: var(--pe-soft);
|
||||
color: var(--pe-muted);
|
||||
font-size: 0.6875rem;
|
||||
line-height: 1.65;
|
||||
}
|
||||
.promotion-expense-card {
|
||||
margin-top: 0.75rem;
|
||||
border: 1px solid var(--pe-border);
|
||||
border-radius: 0.5rem;
|
||||
background: var(--pe-surface);
|
||||
}
|
||||
.promotion-expense-card__head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
padding: 0.9rem 1rem;
|
||||
border-bottom: 1px solid var(--pe-border);
|
||||
}
|
||||
.promotion-expense-card__head strong { font-size: 0.8125rem; }
|
||||
.promotion-expense-card__head span {
|
||||
color: var(--pe-muted);
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
.promotion-expense-table-wrap {
|
||||
max-height: 28rem;
|
||||
overflow: auto;
|
||||
scrollbar-color: var(--pe-accent) #f1ece3;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
.promotion-expense-table {
|
||||
width: 100%;
|
||||
min-width: 68rem;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.75rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.promotion-expense-table th,
|
||||
.promotion-expense-table td {
|
||||
padding: 0.65rem 0.7rem;
|
||||
border-right: 1px solid #eee8dd;
|
||||
border-bottom: 1px solid #eee8dd;
|
||||
text-align: left;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.promotion-expense-table th:last-child,
|
||||
.promotion-expense-table td:last-child { border-right: 0; }
|
||||
.promotion-expense-table thead th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
background: var(--pe-soft);
|
||||
color: var(--pe-muted);
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.promotion-expense-table tbody tr:hover td { background: #fcfaf4; }
|
||||
.promotion-expense-table tfoot td {
|
||||
background: #f8f4eb;
|
||||
font-weight: 700;
|
||||
}
|
||||
.promotion-expense-table .is-number {
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.promotion-expense-table .is-text {
|
||||
min-width: 9rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.promotion-expense-pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
padding: 0.75rem 1rem;
|
||||
color: var(--pe-muted);
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
.promotion-expense-pagination__links {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.promotion-expense-pagination a,
|
||||
.promotion-expense-pagination span {
|
||||
color: var(--pe-accent-dark);
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
}
|
||||
.promotion-expense-pagination .is-disabled {
|
||||
color: var(--pe-muted);
|
||||
cursor: default;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.promotion-expense-empty {
|
||||
padding: 2.5rem 1rem;
|
||||
color: var(--pe-muted);
|
||||
text-align: center;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.promotion-expense-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.promotion-expense-kpi:nth-child(2) { border-right: 0; }
|
||||
.promotion-expense-kpi:nth-child(-n + 2) { border-bottom: 1px solid var(--pe-border); }
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.promotion-expense-toolbar,
|
||||
.promotion-expense-filters,
|
||||
.promotion-expense-actions,
|
||||
.promotion-expense-field { width: 100%; align-items: stretch; }
|
||||
.promotion-expense-field select,
|
||||
.promotion-expense-field input { width: 100%; }
|
||||
.promotion-expense-kpis { grid-template-columns: 1fr; }
|
||||
.promotion-expense-kpi { border-right: 0; border-bottom: 1px solid var(--pe-border); }
|
||||
.promotion-expense-kpi:last-child { border-bottom: 0; }
|
||||
}
|
||||
</style>
|
||||
|
||||
<form method="GET" class="promotion-expense-toolbar" aria-label="推广费用筛选">
|
||||
<div class="promotion-expense-filters">
|
||||
<label class="promotion-expense-field">
|
||||
<span>统计区间</span>
|
||||
<select name="range">
|
||||
@foreach ($rangeOptions as $value => $label)
|
||||
<option value="{{ $value }}" @selected((string) $range === (string) $value)>{{ $label }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
<label class="promotion-expense-field">
|
||||
<span>明细月份</span>
|
||||
<select name="month">
|
||||
@forelse ($months as $optionMonth)
|
||||
<option value="{{ $optionMonth }}" @selected($month === $optionMonth)>{{ $optionMonth }}</option>
|
||||
@empty
|
||||
<option value="{{ $month }}">{{ $month }}</option>
|
||||
@endforelse
|
||||
</select>
|
||||
</label>
|
||||
<label class="promotion-expense-field">
|
||||
<span>平台</span>
|
||||
<select name="platform">
|
||||
<option value="">全部平台</option>
|
||||
@foreach ($platforms as $optionPlatform)
|
||||
<option value="{{ $optionPlatform }}" @selected($platform === $optionPlatform)>{{ $optionPlatform }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
<label class="promotion-expense-field">
|
||||
<span>店铺名称</span>
|
||||
<select name="store_name">
|
||||
<option value="">全部店铺</option>
|
||||
@foreach ($stores as $optionStore)
|
||||
<option value="{{ $optionStore }}" @selected($store === $optionStore)>{{ $optionStore }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="promotion-expense-actions">
|
||||
<button type="submit" class="promotion-expense-button is-primary">
|
||||
<span class="material-icons-outlined" aria-hidden="true">search</span>
|
||||
<span>查询</span>
|
||||
</button>
|
||||
<a class="promotion-expense-button" href="{{ $exportUrl }}">
|
||||
<span class="material-icons-outlined" aria-hidden="true">download</span>
|
||||
<span>导出本月明细</span>
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="promotion-expense-sync" role="status">
|
||||
<span>数据来源:聚水潭经营分析副本</span>
|
||||
<span>最新数据日期:<strong>{{ $sync['latest_date'] ?? '—' }}</strong></span>
|
||||
<span>最近自动同步:<strong>{{ $sync['last_succeeded_at'] ?? '尚未完成' }}</strong></span>
|
||||
@if (($sync['code'] ?? '') === 'ready')
|
||||
<span class="is-ready">已同步</span>
|
||||
@elseif (($sync['code'] ?? '') === 'failed')
|
||||
<span>同步异常,当前展示上一版数据</span>
|
||||
@else
|
||||
<span>等待首次同步</span>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
@if ($error)
|
||||
<div class="promotion-expense-alert" role="alert">{{ $error }}</div>
|
||||
@endif
|
||||
|
||||
@if (! $error)
|
||||
<section class="promotion-expense-kpis" aria-label="{{ $month }} 推广费用汇总">
|
||||
<div class="promotion-expense-kpi">
|
||||
<span>{{ $month }} 源记录</span>
|
||||
<strong>{{ number_format((int) ($summary['source_rows'] ?? 0)) }} 条</strong>
|
||||
<small>按订单行汇总后去重到平台与店铺</small>
|
||||
</div>
|
||||
<div class="promotion-expense-kpi">
|
||||
<span>{{ $month }} 推广费用</span>
|
||||
<strong>¥{{ $money($summary['push_fee_total'] ?? 0) }}</strong>
|
||||
<small>直接推广费 + 分摊推广费</small>
|
||||
</div>
|
||||
<div class="promotion-expense-kpi">
|
||||
<span>{{ $month }} 营销费用</span>
|
||||
<strong>¥{{ $money($summary['marketing_fee_total'] ?? 0) }}</strong>
|
||||
<small>直接营销费 + 分摊营销费</small>
|
||||
</div>
|
||||
<div class="promotion-expense-kpi">
|
||||
<span>{{ $month }} 费用合计</span>
|
||||
<strong>¥{{ $moneyWan($summary['total_fee'] ?? 0) }} 万</strong>
|
||||
<small class="{{ ($summary['total_change_rate'] ?? 0) > 0 ? 'is-increase' : (($summary['total_change_rate'] ?? 0) < 0 ? 'is-saving' : '') }}">
|
||||
@if (($summary['total_change_rate'] ?? null) === null)
|
||||
上月无可比数据
|
||||
@else
|
||||
较 {{ $summary['previous_period'] }} {{ $summary['total_change_rate'] > 0 ? '+' : '' }}{{ $percent($summary['total_change_rate']) }}%
|
||||
@endif
|
||||
</small>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<p class="promotion-expense-rule">
|
||||
费用口径:推广费用取聚水潭经营分析中的直接推广费与分摊推广费,营销费用同样分别保留直接值和分摊值。
|
||||
每日自动同步最近数据,同一天重跑时会整日替换,避免订单改单或删除后留下旧汇总。
|
||||
</p>
|
||||
|
||||
<section class="promotion-expense-card" aria-labelledby="promotion-expense-monthly-title">
|
||||
<div class="promotion-expense-card__head">
|
||||
<strong id="promotion-expense-monthly-title">月度推广费用对比</strong>
|
||||
<span>{{ $promotionExpenseFromMonth }} 至 {{ $promotionExpenseToMonth }} · 最近月份优先</span>
|
||||
</div>
|
||||
<div class="promotion-expense-table-wrap">
|
||||
<table class="promotion-expense-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">月份</th>
|
||||
<th scope="col" class="is-number">源记录</th>
|
||||
<th scope="col" class="is-number">推广费用(元)</th>
|
||||
<th scope="col" class="is-number">营销费用(元)</th>
|
||||
<th scope="col" class="is-number">费用合计(元)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@forelse (array_reverse($periods) as $period)
|
||||
<tr>
|
||||
<td class="is-text">
|
||||
{{ $period['period'] }}
|
||||
@if ($period['period'] === $month)
|
||||
<span class="promotion-expense-button" aria-label="当前明细月份">当前</span>
|
||||
@endif
|
||||
</td>
|
||||
<td class="is-number">{{ number_format((int) $period['source_rows']) }}</td>
|
||||
<td class="is-number">¥{{ $money($period['push_fee_total']) }}</td>
|
||||
<td class="is-number">¥{{ $money($period['marketing_fee_total']) }}</td>
|
||||
<td class="is-number">¥{{ $money($period['total_fee']) }}</td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr>
|
||||
<td colspan="5" class="promotion-expense-empty">所选区间暂无推广费用数据。</td>
|
||||
</tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="promotion-expense-card" aria-labelledby="promotion-expense-store-title">
|
||||
<div class="promotion-expense-card__head">
|
||||
<strong id="promotion-expense-store-title">{{ $month }} 平台与店铺明细</strong>
|
||||
<span>按费用合计从高到低 · 共 {{ number_format($rows->total()) }} 个平台店铺组合</span>
|
||||
</div>
|
||||
<div class="promotion-expense-table-wrap">
|
||||
<table class="promotion-expense-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">平台</th>
|
||||
<th scope="col">店铺名称</th>
|
||||
<th scope="col" class="is-number">源记录</th>
|
||||
<th scope="col" class="is-number">直接推广费</th>
|
||||
<th scope="col" class="is-number">分摊推广费</th>
|
||||
<th scope="col" class="is-number">推广费用</th>
|
||||
<th scope="col" class="is-number">直接营销费</th>
|
||||
<th scope="col" class="is-number">分摊营销费</th>
|
||||
<th scope="col" class="is-number">营销费用</th>
|
||||
<th scope="col" class="is-number">费用合计</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@forelse ($rows as $row)
|
||||
<tr>
|
||||
<td class="is-text">{{ $row['platform'] }}</td>
|
||||
<td class="is-text">{{ $row['store_name'] }}</td>
|
||||
<td class="is-number">{{ number_format((int) $row['source_rows']) }}</td>
|
||||
<td class="is-number">¥{{ $money($row['push_fee']) }}</td>
|
||||
<td class="is-number">¥{{ $money($row['shared_push_fee']) }}</td>
|
||||
<td class="is-number">¥{{ $money($row['push_fee_total']) }}</td>
|
||||
<td class="is-number">¥{{ $money($row['marketing_fee']) }}</td>
|
||||
<td class="is-number">¥{{ $money($row['shared_marketing_fee']) }}</td>
|
||||
<td class="is-number">¥{{ $money($row['marketing_fee_total']) }}</td>
|
||||
<td class="is-number">¥{{ $money($row['total_fee']) }}</td>
|
||||
</tr>
|
||||
@empty
|
||||
<tr>
|
||||
<td colspan="10" class="promotion-expense-empty">
|
||||
该月尚无推广费用镜像,自动同步完成后会在这里展示。
|
||||
</td>
|
||||
</tr>
|
||||
@endforelse
|
||||
</tbody>
|
||||
@if ($rows->isNotEmpty())
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td colspan="2">合计</td>
|
||||
<td class="is-number">{{ number_format((int) ($promotionExpenseTotals['source_rows'] ?? ($summary['source_rows'] ?? 0))) }}</td>
|
||||
<td class="is-number">¥{{ $money($promotionExpenseTotals['push_fee'] ?? 0) }}</td>
|
||||
<td class="is-number">¥{{ $money($promotionExpenseTotals['shared_push_fee'] ?? 0) }}</td>
|
||||
<td class="is-number">¥{{ $money($promotionExpenseTotals['push_fee_total'] ?? 0) }}</td>
|
||||
<td class="is-number">¥{{ $money($promotionExpenseTotals['marketing_fee'] ?? 0) }}</td>
|
||||
<td class="is-number">¥{{ $money($promotionExpenseTotals['shared_marketing_fee'] ?? 0) }}</td>
|
||||
<td class="is-number">¥{{ $money($promotionExpenseTotals['marketing_fee_total'] ?? 0) }}</td>
|
||||
<td class="is-number">¥{{ $money($promotionExpenseTotals['total_fee'] ?? 0) }}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
@endif
|
||||
</table>
|
||||
</div>
|
||||
<footer class="promotion-expense-pagination">
|
||||
<span>
|
||||
@if ($rows->total() > 0)
|
||||
第 {{ $rows->firstItem() }} - {{ $rows->lastItem() }} 条 / 共 {{ $rows->total() }} 条
|
||||
@else
|
||||
暂无记录
|
||||
@endif
|
||||
</span>
|
||||
@if ($rows->lastPage() > 1)
|
||||
<div class="promotion-expense-pagination__links">
|
||||
@if ($rows->onFirstPage())
|
||||
<span class="is-disabled">上一页</span>
|
||||
@else
|
||||
<a href="{{ $rows->previousPageUrl() }}">上一页</a>
|
||||
@endif
|
||||
<span>{{ $rows->currentPage() }} / {{ $rows->lastPage() }}</span>
|
||||
@if ($rows->hasMorePages())
|
||||
<a href="{{ $rows->nextPageUrl() }}">下一页</a>
|
||||
@else
|
||||
<span class="is-disabled">下一页</span>
|
||||
@endif
|
||||
</div>
|
||||
@endif
|
||||
</footer>
|
||||
</section>
|
||||
@endif
|
||||
</div>
|
||||
@ -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');
|
||||
|
||||
124
tests/Feature/Business/PromotionExpensePageTest.php
Normal file
124
tests/Feature/Business/PromotionExpensePageTest.php
Normal file
@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Business;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Modules\EcommerceFinance\Repositories\PromotionExpenseMirrorRepository;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
|
||||
class PromotionExpensePageTest extends FeatureTestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$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();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
24
tests/Unit/Deployment/PromotionExpenseScheduleTest.php
Normal file
24
tests/Unit/Deployment/PromotionExpenseScheduleTest.php
Normal file
@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Deployment;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class PromotionExpenseScheduleTest extends TestCase
|
||||
{
|
||||
public function test_release_and_batch_scripts_schedule_promotion_expense_sync(): void
|
||||
{
|
||||
$root = dirname(__DIR__, 3);
|
||||
$schedule = '10 3 * * * root /usr/bin/timeout 1800 /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-promotion-expenses --days=7 --quiet';
|
||||
|
||||
foreach (['deploy/activate-release.sh', 'deploy/activate-incremental-release.sh'] as $file) {
|
||||
$contents = file_get_contents($root . '/' . $file);
|
||||
$this->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);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\EcommerceFinance;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Modules\EcommerceFinance\Repositories\PromotionExpenseMirrorRepository;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PromotionExpenseMirrorRepositoryTest extends TestCase
|
||||
{
|
||||
private PromotionExpenseMirrorRepository $repository;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->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();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,141 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\EcommerceFinance;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Mockery;
|
||||
use Modules\EcommerceFinance\Repositories\PromotionExpenseMirrorRepository;
|
||||
use Modules\EcommerceFinance\Services\PromotionExpenseMirrorSynchronizer;
|
||||
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQuery;
|
||||
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PromotionExpenseMirrorSynchronizerTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$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();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user