CaiWuXiTong/modules/EcommerceFinance/Console/AlignShippingWeights.php

65 lines
3.1 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 Modules\EcommerceFinance\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Modules\EcommerceFinance\Services\Freight\ShippingFreightService;
use Modules\EcommerceFinance\Services\Jushuitan\ShippingReplicaSynchronizer;
use Throwable;
/**
* 只按聚水潭销售出库单校正发货数据的 线上重量/实称重量(整单)、发货时间,再重算报价核算运费(含称重重量)。
* 不重扫发货明细(那一步要读几十万行、查几万次副本库,整月同步一直超时),只按天查销售出库单,几分钟跑完一个月。
*
* php artisan jushuitan:align-weights --from=2026-09-01 --to=2026-12-01
*
* 按月逐段跑,某个月失败不影响已完成的月份;不要和 jushuitan:sync-shipping 同时跑。
*/
class AlignShippingWeights extends Command
{
protected $signature = 'jushuitan:align-weights {--from= : 发货日期起(含) YYYY-MM-DD} {--to= : 发货日期止(不含) YYYY-MM-DD} {--skip-freight : 只校正重量,不重算运费}';
protected $description = '按销售出库单校正发货数据线上/实称重量与发货时间,并重算核算运费';
public function handle(ShippingReplicaSynchronizer $sync, ShippingFreightService $freight): int
{
$from = (string) $this->option('from');
$to = (string) $this->option('to');
$validDate = static fn (string $date): bool => preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)
&& checkdate((int) substr($date, 5, 2), (int) substr($date, 8, 2), (int) substr($date, 0, 4));
if (! $validDate($from) || ! $validDate($to) || $from >= $to) {
$this->error('--from / --to 需要 YYYY-MM-DD,且 from 早于 to');
return self::FAILURE;
}
$failed = 0;
$cur = Carbon::parse($from);
$end = Carbon::parse($to);
while ($cur->lt($end)) {
$next = $cur->copy()->addMonthNoOverflow()->startOfMonth();
if ($next->gt($end)) {
$next = $end->copy();
}
[$a, $b] = [$cur->format('Y-m-d H:i:s'), $next->format('Y-m-d H:i:s')];
$label = $cur->format('Y-m-d') . ' ~ ' . $next->format('Y-m-d');
$t0 = microtime(true);
try {
$al = $sync->alignWithOutbound($a, $b);
$this->info(sprintf('%s 按销售出库单校正:发货时间 %d 个包裹,线上/实称重量 %d 个包裹(%d 秒)', $label, $al['ship_time'], $al['weight'], (int) (microtime(true) - $t0)));
if (! $this->option('skip-freight')) {
$t1 = microtime(true);
$fr = $freight->recalculate($cur->format('Y-m-d'), $next->format('Y-m-d'));
$this->info(sprintf('%s 重算运费:包裹 %d 个,核算成功 %d 个(%d 秒)', $label, $fr['packages'], $fr['ok'], (int) (microtime(true) - $t1)));
}
} catch (Throwable $e) {
$failed++;
$this->error($label . ' 失败:' . mb_substr($e->getMessage(), 0, 500));
}
$cur = $next;
}
return $failed === 0 ? self::SUCCESS : self::FAILURE;
}
}