CaiWuXiTong/modules/EcommerceFinance/Services/PromotionExpenseMirrorSynchronizer.php

147 lines
5.7 KiB
PHP

<?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);
}
}