CaiWuXiTong/modules/EcommerceFinance/Services/Freight/ShippingFreightService.php

375 lines
16 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 = [];
$this->measured = null;
$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);
}
}
}
/** 核算所属公司:有当前公司用当前公司,命令行等没有当前公司时用 jushuitan.freight_company_id。 */
private function companyId(): int
{
return function_exists('company_id') && company_id() ? (int) company_id() : (int) config('jushuitan.freight_company_id', 1);
}
/** @return array<string,Collection<int,CourierQuoteVersion>> */
private function versions(): array
{
if ($this->versions !== null) {
return $this->versions;
}
$companyId = $this->companyId();
$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', 'qty', 'freight']);
$measured = $this->measuredWeights();
$out = [];
$mw = [];
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;
}
// 称重重量:包裹里每个条码都有导入称重时,按 Σ 称重×数量 作为整单重量;
// 只有部分条码有称重时不用(线上/实称重量是整单重量,拆不出单件,没法和称重拼在一起)
$m = &$mw[$sid];
$m ??= ['sum' => 0.0, 'hit' => false, 'ok' => true];
$carrier = trim((string) $r->express_name1);
$unit = $bc === '' ? null : ($measured[$carrier . "\0" . mb_strtoupper($bc)]
?? $measured[(FreightCarrierRules::ALIAS[$carrier] ?? $carrier) . "\0" . mb_strtoupper($bc)] ?? null);
if ($unit !== null) {
$qty = (float) ($r->qty ?? 0);
$m['sum'] += $unit * ($qty > 0 ? $qty : 1);
$m['hit'] = true;
} else {
$m['ok'] = false;
}
unset($p, $m);
}
foreach ($out as $sid => &$p) {
$p['barcodes'] = implode(',', $p['barcodes']);
$p['measured_weight'] = ! empty($mw[$sid]['hit']) && $mw[$sid]['ok'] ? round($mw[$sid]['sum'], 4) : null;
}
unset($p);
return array_values($out);
}
/** @var array<string,float>|null 快递名称\0条码(大写) => 每件称重重量 kg */
private ?array $measured = null;
/**
* 发货数据页导入的称重重量(条码 × 适用快递名称)。表在系统主库;读不到时按没有称重处理。
*
* @return array<string,float>
*/
private function measuredWeights(): array
{
if ($this->measured !== null) {
return $this->measured;
}
$this->measured = [];
try {
// 和报价同一个公司:命令行没有当前公司时也不能混用别家公司的称重重量
$query = DB::table('shipping_measured_weights')->where('company_id', $this->companyId());
foreach ($query->get(['carrier_name', 'barcode', 'weight_kg']) as $row) {
$this->measured[trim((string) $row->carrier_name) . "\0" . mb_strtoupper(trim((string) $row->barcode))] = (float) $row->weight_kg;
}
} catch (\Throwable $e) {
report($e);
}
return $this->measured;
}
/** 导入称重重量后,这些快递从核算起始日起重算(请求结束后执行)。 */
public static function queueMeasuredCarriers(array $carriers): void
{
foreach (array_unique($carriers) as $carrier) {
$carrier = trim((string) $carrier);
self::queueCarrier(FreightCarrierRules::ALIAS[$carrier] ?? $carrier, FreightCarrierRules::START_DATE);
}
}
/** @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,
];
}
}