>|null 报价名称 => 版本 */ private ?array $versions = null; /** @var array 报价名称|日期 => 解析好的报价 */ private array $resolved = []; /** @var array 版本 id => 解析好的报价 */ private array $parsed = []; /** @var array 待重算:报价名称 => 最早日期 */ 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|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 $pkg * @return array */ 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> */ 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 $ids * @return list> */ 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 */ 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, ]; } }