57 lines
2.9 KiB
PHP
57 lines
2.9 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Console;
|
||
|
||
use Illuminate\Console\Command;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Modules\EcommerceFinance\Services\Freight\FreightCarrierRules;
|
||
use Modules\EcommerceFinance\Services\Freight\ShippingFreightService;
|
||
|
||
/**
|
||
* 按报价管理的报价核算发货数据运费(结果显示在发货数据页面「报价核算」列)。
|
||
*
|
||
* php artisan jushuitan:calc-freight --from=2026-11-01 --to=2026-11-16
|
||
* php artisan jushuitan:calc-freight --from=2026-11-01 --to=2026-11-16 --carrier=北京韵达 --carrier=常州德邦
|
||
*/
|
||
class CalcShippingFreight extends Command
|
||
{
|
||
protected $signature = 'jushuitan:calc-freight {--from= : 发货日期起(含)} {--to= : 发货日期止(不含)} {--carrier=* : 只核算这些快递(报价名称)} {--source-id=* : 仅重算已核对的包裹ID,最多2000个,须同时指定快递}';
|
||
|
||
protected $description = '按报价管理的报价核算发货数据运费';
|
||
|
||
public function handle(ShippingFreightService $service): int
|
||
{
|
||
$from = (string) ($this->option('from') ?: FreightCarrierRules::START_DATE);
|
||
$to = (string) ($this->option('to') ?: now()->addDay()->format('Y-m-d'));
|
||
if (! preg_match('/^\d{4}-\d{2}-\d{2}$/', $from) || ! preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) {
|
||
$this->error('--from / --to 需要 YYYY-MM-DD');
|
||
|
||
return self::FAILURE;
|
||
}
|
||
$carriers = array_values(array_filter(array_map('trim', (array) $this->option('carrier'))));
|
||
$ids = (array) $this->option('source-id');
|
||
if ($ids !== []) {
|
||
if ($carriers === [] || count($ids) > 2000 || array_filter($ids, static fn ($id) => !is_string($id) || !preg_match('/^[1-9][0-9]{0,14}$/', $id))) {
|
||
$this->error('定向核算需要指定快递,并提供最多2000个有效包裹ID');
|
||
return self::FAILURE;
|
||
}
|
||
$ids = array_values(array_unique(array_map('intval', $ids)));
|
||
$matched = DB::connection((string) config('jushuitan.connection', 'jushuitan_local'))
|
||
->table('jst_oms_shipping')->whereIn('source_id', $ids)
|
||
->whereIn('express_name1', $carriers)
|
||
->where('ship_time', '>=', max($from, FreightCarrierRules::START_DATE) . ' 00:00:00')
|
||
->where('ship_time', '<', $to . ' 00:00:00')->distinct()->count('source_id');
|
||
if ($matched !== count($ids)) {
|
||
$this->error('目标包裹不全部属于指定快递和日期范围,未执行核算');
|
||
return self::FAILURE;
|
||
}
|
||
$res = $service->recalculateSourceIds($ids);
|
||
} else {
|
||
$res = $service->recalculate($from, $to, $carriers === [] ? null : $carriers);
|
||
}
|
||
$this->info(sprintf('运费核算完成:%s ~ %s,包裹 %d 个,核算成功 %d 个,无法核算 %d 个', $from, $to, $res['packages'], $res['ok'], $res['packages'] - $res['ok']));
|
||
|
||
return self::SUCCESS;
|
||
}
|
||
}
|