CaiWuXiTong/modules/EcommerceFinance/Services/Freight/ShippingFreightService.php
limeng 1cf60dd7b0 feat(发货数据): 按报价管理的报价核算运费,结果显示在发货数据页面
从 2026-11-01 起,按发货日在报价管理里生效的报价版本(与报价管理「当前生效」同一判断:未作废、
已审核/签署生效、执行期间覆盖发货日,取执行日期最新)逐包裹核算运费,写入 jst_oms_shipping_freight。
- 结算重量:实称>线上>重量;按各快递计泡系数取 max(重量, 长×宽×高÷系数);免抛仓(含「配件」仓)不计泡、不收多件费;
  超长费计入,其他附加费不计;城市单独报价、整省「X元/公斤」、洞洞板 9000、个别版本系数等按 10 月逐单核对的口径;
- 计算引擎移植自 10 月离线核算脚本,10 月 29.5 万个包裹逐单比对结果一致(仅 x.xx5 边界按正确四舍五入进位);
- 发货数据同步完成后核算该窗口;报价版本新增/作废/签署归档后按该快递从执行日期起自动重算;
- 新命令 jushuitan:calc-freight --from --to [--carrier];
- 发货数据页面/导出新增「报价核算」列:核算运费、核算-聚水潭运费、报价版本、结算重量依据、核算结算重量、
  计费重量、首重、续重/费率、面单、一口价、多件/超长加收、核算公式、核算状态(合并口径每包裹一行,明细只在第一行)。

同时修复发货数据同步 11 月起频繁失败:副本库查发货视图超时后报 20047 DBPROCESS is dead,
原重试只识别 20003/dbnextrow,整次同步失败(11-17 只同步到 62%)。现把 20047 视为可重连重试,
发货视图每批出库单由 300 降到 100。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhry6eiuwf
2026-11-18 13:55:40 +08:00

315 lines
13 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\Services\Freight;
use App\Models\Business\CourierQuoteVersion;
use App\Support\CourierRequoteService;
use Carbon\Carbon;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
/**
* 发货数据报价核算:按包裹汇总发货数据(合并口径),找发货日生效的报价版本,算出运费写入 jst_oms_shipping_freight。
*
* - 发货数据同步完成后核算该窗口;
* - 报价管理里报价版本新增/作废/签署归档后,按该快递、从执行日期起自动重算(请求结束后执行);
* - 只核算 FreightCarrierRules::START_DATE 起的发货数据。
*/
class ShippingFreightService
{
private const CHUNK = 2000;
private ConnectionInterface $db;
/** @var array<string,Collection<int,CourierQuoteVersion>>|null 报价名称 => 版本 */
private ?array $versions = null;
/** @var array<string,?array> 报价名称|日期 => 解析好的报价 */
private array $resolved = [];
/** @var array<int,array> 版本 id => 解析好的报价 */
private array $parsed = [];
/** @var array<string,string> 待重算:报价名称 => 最早日期 */
private static array $pending = [];
/** 已登记「请求结束后重算」的应用实例(spl_object_id)。 */
private static ?int $flushRegisteredFor = null;
public function __construct(private readonly ShippingFreightCalculator $calculator)
{
$this->db = DB::connection((string) config('jushuitan.connection', 'jushuitan_local'));
}
/**
* 核算发货时间在 [from, to) 的包裹;$carriers 为空表示全部快递。
*
* @param list<string>|null $carriers 报价名称(发货数据快递名称)
* @return array{packages:int,ok:int}
*/
public function recalculate(string $from, string $to, ?array $carriers = null): array
{
$from = max(substr($from, 0, 10), FreightCarrierRules::START_DATE) . ' 00:00:00';
$to = strlen($to) === 10 ? $to . ' 00:00:00' : $to;
if ($from >= $to) {
return ['packages' => 0, 'ok' => 0];
}
$this->versions = null;
$this->resolved = [];
$names = null;
if ($carriers !== null) {
$names = [];
foreach ($carriers as $c) {
$c = trim($c);
$names[$c] = true;
foreach (FreightCarrierRules::ALIAS as $alias => $target) {
if ($target === $c) {
$names[$alias] = true;
}
}
}
$names = array_keys($names);
if ($names === []) {
return ['packages' => 0, 'ok' => 0];
}
}
$total = 0;
$ok = 0;
$last = 0;
while (true) {
$q = $this->db->table('jst_oms_shipping')
->where('ship_time', '>=', $from)->where('ship_time', '<', $to)
->where('source_id', '>', $last)
->whereNotNull('source_id');
if ($names !== null) {
$q->whereIn('express_name1', $names);
}
$ids = $q->distinct()->orderBy('source_id')->limit(self::CHUNK)->pluck('source_id')->map(static fn ($v) => (int) $v)->all();
if ($ids === []) {
break;
}
$last = end($ids);
$rows = [];
$now = now()->format('Y-m-d H:i:s');
foreach ($this->packages($ids) as $pkg) {
$r = $this->calculatePackage($pkg);
$rows[] = $this->resultRow($pkg, $r, $now);
$ok += $r['status'] === 'OK' ? 1 : 0;
}
$this->db->transaction(function () use ($ids, $rows): void {
$this->db->table('jst_oms_shipping_freight')->whereIn('source_id', $ids)->delete();
foreach (array_chunk($rows, 500) as $part) {
$this->db->table('jst_oms_shipping_freight')->insert($part);
}
});
$total += count($rows);
if (count($ids) < self::CHUNK) {
break;
}
}
return ['packages' => $total, 'ok' => $ok];
}
/**
* 单个包裹核算(合并口径字段)。
*
* @param array<string,mixed> $pkg
* @return array<string,mixed>
*/
public function calculatePackage(array $pkg): array
{
$name = trim((string) ($pkg['express_name1'] ?? ''));
$name = FreightCarrierRules::ALIAS[$name] ?? $name;
$cfg = FreightCarrierRules::for($name);
if ($cfg !== null) {
$cfg['_name'] = $name;
}
$versions = $this->versions()[$name] ?? null;
if ($versions === null || $versions->isEmpty()) {
$r = $this->calculator->calculate($pkg, null, $cfg);
$r['status'] = '报价管理里没有「' . $name . '」的报价';
return $r;
}
return $this->calculator->calculate($pkg, $this->quoteAt($name, substr((string) $pkg['ship_time'], 0, 10)), $cfg);
}
/**
* 报价版本变更后登记待重算(同一请求内合并,请求结束后执行)。
*/
public static function queueCarrier(?string $carrier, mixed $fromDate): void
{
$carrier = trim((string) $carrier);
if ($carrier === '') {
return;
}
$day = $fromDate instanceof \DateTimeInterface ? $fromDate->format('Y-m-d') : substr((string) $fromDate, 0, 10);
$day = $day !== '' ? max($day, FreightCarrierRules::START_DATE) : FreightCarrierRules::START_DATE;
if (! isset(self::$pending[$carrier]) || $day < self::$pending[$carrier]) {
self::$pending[$carrier] = $day;
}
$app = app();
if (self::$flushRegisteredFor !== spl_object_id($app)) {
self::$flushRegisteredFor = spl_object_id($app);
$app->terminating(static function (): void {
self::flushPending();
});
}
}
public static function flushPending(): void
{
$pending = self::$pending;
self::$pending = [];
if ($pending === []) {
return;
}
$to = Carbon::tomorrow()->format('Y-m-d');
$service = app(self::class);
foreach ($pending as $carrier => $from) {
try {
$service->recalculate($from, $to, [$carrier]);
} catch (\Throwable $e) {
report($e);
}
}
}
/** @return array<string,Collection<int,CourierQuoteVersion>> */
private function versions(): array
{
if ($this->versions !== null) {
return $this->versions;
}
$companyId = function_exists('company_id') && company_id() ? (int) company_id() : (int) config('jushuitan.freight_company_id', 1);
$all = CourierQuoteVersion::query()->allCompanies()
->where('company_id', $companyId)
->with([
'change' => static fn ($q) => $q->allCompanies(),
'signature' => static fn ($q) => $q->allCompanies(),
])
->get();
return $this->versions = $all->groupBy(static fn (CourierQuoteVersion $v) => trim((string) $v->company_name))->all();
}
private function quoteAt(string $name, string $day): ?array
{
$key = $name . '|' . $day;
if (array_key_exists($key, $this->resolved)) {
return $this->resolved[$key];
}
$version = CourierRequoteService::resolveAt($this->versions()[$name] ?? collect(), Carbon::parse($day));
if ($version === null) {
return $this->resolved[$key] = null;
}
if (! isset($this->parsed[$version->id])) {
$vals = json_decode((string) $version->values_json, true);
$vals = is_array($vals) ? $vals : [];
$this->parsed[$version->id] = [
'id' => (string) $version->version_code,
'p' => QuoteSheet::parse($vals),
'rules' => (string) ($version->billing_rules ?? ''),
'vals' => $vals,
];
}
return $this->resolved[$key] = $this->parsed[$version->id];
}
/**
* 按包裹(快递单号)汇总发货明细(与发货数据合并口径一致)。实称/线上/重量是整个包裹的重量,只记在包裹第一行商品上
* (其余行为空),取包裹那一行的值;采购退货等没有整包重量的,每行记单重×数量,合计即整包预估重量。
* 长宽高取最大(组合件取整行值),体积/运费合计,条码去重拼接。
*
* @param list<int> $ids
* @return list<array<string,mixed>>
*/
private function packages(array $ids): array
{
$rows = $this->db->table('jst_oms_shipping')->whereIn('source_id', $ids)->orderBy('id')
->get(['id', 'source_id', 'express_no', 'express_name1', 'warehouse_name', 'receiver_state', 'receiver_city', 'ship_time',
'pkg_count', 'online_weight', 'actual_weight', 'weight_kg', 'length_cm', 'width_cm', 'height_cm', 'volume_cm3',
'm_length_cm', 'm_width_cm', 'm_height_cm', 'm_volume_cm3', 'barcode', 'freight']);
$out = [];
foreach ($rows as $r) {
$sid = (int) $r->source_id;
$p = &$out[$sid];
if ($p === null) {
$p = ['source_id' => $sid, 'express_no' => null, 'express_name1' => null, 'warehouse_name' => null, 'receiver_state' => null,
'receiver_city' => null, 'ship_time' => null, 'pkg_count' => null, 'online_weight' => null, 'actual_weight' => null,
'weight_kg' => null, 'length_cm' => null, 'width_cm' => null, 'height_cm' => null, 'volume_cm3' => null,
'barcodes' => [], 'freight' => null];
}
foreach (['express_no', 'express_name1', 'warehouse_name', 'receiver_state', 'receiver_city', 'ship_time', 'pkg_count'] as $c) {
$v = $r->{$c};
if ($v !== null && $v !== '' && ($p[$c] === null || (string) $v > (string) $p[$c])) {
$p[$c] = $v; // 对齐合并口径 MAX()
}
}
foreach (['online_weight', 'actual_weight', 'weight_kg', 'freight'] as $c) {
if ($r->{$c} !== null) {
$p[$c] = (float) $p[$c] + (float) $r->{$c};
}
}
$vol = $r->m_volume_cm3 ?? $r->volume_cm3;
if ($vol !== null) {
$p['volume_cm3'] = (float) $p['volume_cm3'] + (float) $vol;
}
foreach (['length_cm' => 'm_length_cm', 'width_cm' => 'm_width_cm', 'height_cm' => 'm_height_cm'] as $c => $mc) {
$v = $r->{$mc} ?? $r->{$c};
if ($v !== null && ($p[$c] === null || (float) $v > (float) $p[$c])) {
$p[$c] = (float) $v;
}
}
$bc = trim((string) $r->barcode);
if ($bc !== '' && ! in_array($bc, $p['barcodes'], true)) {
$p['barcodes'][] = $bc;
}
unset($p);
}
foreach ($out as &$p) {
$p['barcodes'] = implode(',', $p['barcodes']);
}
unset($p);
return array_values($out);
}
/** @return array<string,mixed> */
private function resultRow(array $pkg, array $r, string $now): array
{
$num = static fn ($v, int $dp = 4) => is_numeric($v) ? round((float) $v, $dp) : null;
return [
'source_id' => $pkg['source_id'],
'express_no' => $pkg['express_no'] !== null ? mb_substr((string) $pkg['express_no'], 0, 64) : null,
'express_name' => $pkg['express_name1'] !== null ? mb_substr((string) $pkg['express_name1'], 0, 100) : null,
'ship_date' => $pkg['ship_time'] !== null ? substr((string) $pkg['ship_time'], 0, 10) : null,
'quote_version' => $r['ver'],
'status' => mb_substr((string) $r['status'], 0, 255),
'base_source' => $r['base_src'] !== '' ? $r['base_src'] : null,
'base_weight' => $num($r['base_w']),
'volume_weight' => $num($r['vol_w']),
'coef' => is_numeric($r['coef']) ? (int) $r['coef'] : null,
'free_warehouse' => (bool) $r['free'],
'settle_weight' => $num($r['settle_w']),
'charge_weight' => $num($r['charge_w']),
'first_kg' => $num($r['first_kg'], 2),
'first_price' => $num($r['first_price']),
'rate' => $r['rate'] === null ? null : mb_substr(is_float($r['rate']) ? ShippingFreightCalculator::fmt($r['rate']) : (string) $r['rate'], 0, 32),
'miandan' => $num($r['miandan']),
'flat_price' => $num($r['flat']),
'extra_fee' => (float) $r['extra'] > 0 ? round((float) $r['extra'], 4) : null,
'freight' => $r['status'] === 'OK' ? $num($r['fee'], 2) : null,
'jst_freight' => $num($pkg['freight'], 2),
'formula' => $r['formula'] !== '' ? $r['formula'] : null,
'calculated_at' => $now,
];
}
}