CaiWuXiTong/app/Console/Commands/SyncReturnedParcels.php

61 lines
3.0 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Modules\EcommerceFinance\Services\ReturnedParcelSynchronizer;
use Throwable;
class SyncReturnedParcels extends Command
{
protected $signature = 'business-mirror:sync-returned-parcels {--from= : 进仓开始日期(含)} {--to= : 进仓结束日期(含)} {--deduplicate : 只合并现有镜像中两来源相同的售后商品,不读取上游} {--match-surcharges : 同步成功后刷新已有未确认账单附加费}';
protected $description = '同步聚水潭售后退货退款到快递应付退回件明细';
public function handle(ReturnedParcelSynchronizer $synchronizer): int
{
$from = (string) ($this->option('from') ?: ReturnedParcelSynchronizer::START);
$to = (string) ($this->option('to') ?: now('Asia/Shanghai')->toDateString());
foreach ([$from, $to] as $date) {
if (! preg_match('/^(\d{4})-(\d{2})-(\d{2})$/D', $date, $parts)
|| ! checkdate((int) $parts[2], (int) $parts[3], (int) $parts[1])) {
$this->error('日期需要 YYYY-MM-DD。');
return self::FAILURE;
}
}
if ($from < ReturnedParcelSynchronizer::START || $from > $to) {
$this->error('开始日期不得早于 2026-10-01,且不能晚于结束日期。');
return self::FAILURE;
}
if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) {
$this->error('请通过服务器 run-finance-batch.sh 执行同步。');
return self::FAILURE;
}
$lock = Cache::lock('courier-returned-parcels-sync', 2100);
if (! $lock->get()) {
$this->warn('退回件同步正在运行,本次跳过。');
return self::SUCCESS;
}
try {
if ($this->option('deduplicate')) {
$this->info('退回件来源校准完成:合并重复商品明细 '.$synchronizer->deduplicate().' 行。');
return self::SUCCESS;
}
$result = $synchronizer->sync($from, $to, fn (int $n, int $total) => $this->line("已扫描 {$n} / {$total} 行"));
$this->info(sprintf('退回件同步完成:%s 至 %s,%d 条商品明细,耗时 %.2f 秒,PHP 峰值 %.2f MiB。',
$from, $to, $result['rows'], $result['seconds'], $result['peak_mb']));
if ($this->option('match-surcharges')) {
// 新退回可能属于更早账期,沿用既有确认和人工保留保护。
return $this->call(MatchBillSurcharges::class, ['--all' => true, '--existing-only' => true, '--all-months' => true, '--refresh-rebooks' => true]);
}
return self::SUCCESS;
} catch (Throwable $exception) {
report($exception);
$this->error('退回件同步失败,保留上次完整结果;使用相同日期可继续未完成批次。');
return self::FAILURE;
} finally {
$lock->release();
}
}
}