75 lines
2.6 KiB
PHP
75 lines
2.6 KiB
PHP
<?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];
|
||
}
|
||
}
|