677 lines
30 KiB
PHP
677 lines
30 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services\Freight;
|
||
|
||
use App\Models\Business\CourierQuoteVersion;
|
||
use App\Support\CourierRequoteService;
|
||
use App\Support\ReturnRouteFreightCalculator;
|
||
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, private readonly ReturnRouteFreightCalculator $returnRoutes)
|
||
{
|
||
$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;
|
||
$this->returnRoutes->reset();
|
||
$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
|
||
{
|
||
if (isset($pkg['merged_into'])) {
|
||
return self::zeroResult('快递单号 ' . $pkg['express_no'] . ' 和同包裹的其他订单合成一个包裹发出,运费已算在那个订单上,这里记 0');
|
||
}
|
||
if (! empty($pkg['no_waybill_dup'])) {
|
||
return self::zeroResult('没有快递单号,同一交易单号已有带快递单号的包裹计费,这一行不是实际发出的包裹,这里记 0');
|
||
}
|
||
$name = trim((string) ($pkg['express_name1'] ?? ''));
|
||
$name = FreightCarrierRules::ALIAS[$name] ?? $name;
|
||
if (ReturnRouteFreightCalculator::supports($name)) {
|
||
return $this->calculateReturnRoute($pkg, $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);
|
||
}
|
||
|
||
private function calculateReturnRoute(array $pkg, string $carrier): array
|
||
{
|
||
// 复用落库字段;返货按吨/方取高,不套用普通快递计泡系数。
|
||
$result = $this->calculator->calculate($pkg, null, null);
|
||
$weight = null;
|
||
foreach (['measured_weight'=>'称重重量', 'actual_weight'=>'实称重量', 'online_weight'=>'线上重量', 'weight_kg'=>'重量'] as $field=>$source) {
|
||
if (is_numeric($pkg[$field] ?? null) && (float) $pkg[$field] > 0) {
|
||
$weight = (float) $pkg[$field];
|
||
$result['base_w'] = $result['settle_w'] = $result['charge_w'] = $weight;
|
||
$result['base_src'] = $source;
|
||
break;
|
||
}
|
||
}
|
||
$destination = implode(' ', array_filter(array_map(static fn($field) => trim((string) ($pkg[$field] ?? '')),
|
||
['receiver_state', 'receiver_city', 'receiver_district', 'receiver_address', 'receiver_name'])));
|
||
// 采购退货出库 source_id = 3000000000 + io_id,退回唯一供应商时用厂家名匹配具体线路。
|
||
// 普通发货的商品供应商不是收货方;多供应商包裹也不能任选一家套价。
|
||
$suppliers = $pkg['supplier_names'] ?? [];
|
||
$purchaseReturn = (int) ($pkg['source_id'] ?? 0) >= 3000000000;
|
||
$destinationName = $purchaseReturn && count($suppliers) === 1 ? $suppliers[0] : null;
|
||
// 采购退货按明细长×宽×高×数量核算。旧视图合并体积可能被重复分摊,不能沿用。
|
||
$volume = $pkg[$purchaseReturn ? 'detail_volume_cm3' : 'volume_cm3'] ?? null;
|
||
$route = $this->returnRoutes->calculate($carrier, (string) ($pkg['warehouse_name'] ?? ''), $destination,
|
||
$weight, $volume !== null ? (float) $volume : null,
|
||
substr((string) ($pkg['ship_time'] ?? ''), 0, 10), $destinationName);
|
||
$result['mode'] = 'RETURN_ROUTE';
|
||
$result['status'] = $route['covered'] ? 'OK' : $route['reason'];
|
||
if (! $route['covered']) return $result;
|
||
|
||
$result['ver'] = $route['quote_id'];
|
||
$result['fee'] = $route['payable'];
|
||
$result['extra'] = $route['delivery_fee'];
|
||
$result['region'] = $route['origin'] . '→' . $route['destination'];
|
||
$fmt = [ShippingFreightCalculator::class, 'fmt'];
|
||
$quantity = static fn (float $value): string => rtrim(rtrim(sprintf('%.8f', $value), '0'), '.');
|
||
$result['formula'] = '逆向物流报价 ' . $result['region'] . ';max('
|
||
. $quantity($route['tons']) . '吨×' . $fmt($route['ton_price']) . '=' . $fmt($route['by_ton']) . ','
|
||
. $quantity($route['cubic_meters']) . '方×' . $fmt($route['volume_price']) . '=' . $fmt($route['by_volume'])
|
||
. ')+派送费' . $fmt($route['delivery_fee']) . '=' . $fmt($route['payable'])
|
||
. ($route['pending_confirmation'] ? ';报价待物流确认' : '');
|
||
|
||
return $result;
|
||
}
|
||
|
||
/**
|
||
* 报价版本变更后登记待重算(同一请求内合并,请求结束后执行)。
|
||
*/
|
||
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
|
||
{
|
||
$heads = [];
|
||
foreach (array_chunk($ids, 1000) as $chunk) {
|
||
foreach ($this->db->table('jst_oms_shipping')->whereIn('source_id', $chunk)
|
||
->get(['source_id', 'express_no', 'trade_no', 'ship_time']) as $r) {
|
||
$sid = (int) $r->source_id;
|
||
$h = &$heads[$sid];
|
||
$h ??= ['l' => '', 'trade' => '', 'time' => ''];
|
||
$l = ltrim(trim((string) $r->express_no), '@');
|
||
if ($l !== '' && $l > $h['l']) {
|
||
$h['l'] = $l;
|
||
}
|
||
$t = trim((string) $r->trade_no);
|
||
if ($t !== '' && $h['trade'] === '') {
|
||
$h['trade'] = $t;
|
||
}
|
||
if ((string) $r->ship_time > $h['time']) {
|
||
$h['time'] = (string) $r->ship_time;
|
||
}
|
||
unset($h);
|
||
}
|
||
}
|
||
[$primaryOf, $folded] = $this->sharedWaybills($heads);
|
||
$load = $ids;
|
||
foreach ($folded as $p => $sids) {
|
||
$load[] = $p;
|
||
array_push($load, ...$sids);
|
||
}
|
||
foreach ($primaryOf as $sid => $p) {
|
||
$load[] = $p;
|
||
}
|
||
$agg = [];
|
||
foreach ($this->aggregate(array_values(array_unique($load))) as $pkg) {
|
||
$agg[$pkg['source_id']] = $pkg;
|
||
}
|
||
$dupTrades = $this->tradesWithWaybill($heads);
|
||
|
||
$out = [];
|
||
foreach ($ids as $sid) {
|
||
$pkg = $agg[$sid] ?? null;
|
||
if ($pkg === null) {
|
||
continue;
|
||
}
|
||
if (isset($primaryOf[$sid])) {
|
||
$pkg['merged_into'] = $primaryOf[$sid];
|
||
} elseif (isset($folded[$sid])) {
|
||
$pkg = $this->fold($pkg, array_values(array_filter(array_map(static fn ($s) => $agg[$s] ?? null, $folded[$sid]))));
|
||
} elseif (($heads[$sid]['l'] ?? '') === '' && isset($dupTrades[$heads[$sid]['trade'] ?? ''])) {
|
||
$pkg['no_waybill_dup'] = true;
|
||
}
|
||
$out[] = $pkg;
|
||
}
|
||
|
||
return $out;
|
||
}
|
||
|
||
/**
|
||
* 同一快递单号挂在几个订单(source_id)上:合单发货,或同包裹的另一个订单没有商品明细。
|
||
* 出库单校正后整包重量只记在主包裹(最早一行有商品明细的订单;都没有商品就取最早一行),
|
||
* 这时其他订单要并进主包裹一起核算一次运费。仍带自己线上/实称重量、且有商品的订单
|
||
* (同一单号分批出库、各有出库单)照旧单独核算。
|
||
*
|
||
* @param array<int,array{l:string,trade:string,time:string}> $heads
|
||
* @return array{0:array<int,int>,1:array<int,list<int>>} [被并入的 source_id => 主包裹, 主包裹 => 并入的 source_id 列表]
|
||
*/
|
||
private function sharedWaybills(array $heads): array
|
||
{
|
||
$nos = [];
|
||
$min = null;
|
||
$max = null;
|
||
foreach ($heads as $h) {
|
||
if ($h['l'] !== '') {
|
||
$nos[$h['l']] = true;
|
||
$min = $min === null || $h['time'] < $min ? $h['time'] : $min;
|
||
$max = $max === null || $h['time'] > $max ? $h['time'] : $max;
|
||
}
|
||
}
|
||
if ($nos === []) {
|
||
return [[], []];
|
||
}
|
||
$from = date('Y-m-d H:i:s', strtotime((string) $min) - 15 * 86400);
|
||
$to = date('Y-m-d H:i:s', strtotime((string) $max) + 15 * 86400);
|
||
$by = []; // 单号 => source_id => [最早行 id, 最早有商品行 id, 有重量, 发货时间]
|
||
foreach (array_chunk(array_keys($nos), 500) as $chunk) {
|
||
$variants = [];
|
||
foreach ($chunk as $l) {
|
||
$variants[] = (string) $l;
|
||
$variants[] = '@' . $l;
|
||
}
|
||
foreach ($this->db->table('jst_oms_shipping')->whereIn('express_no', $variants)
|
||
->where('ship_time', '>=', $from)->where('ship_time', '<', $to)
|
||
->get(['id', 'source_id', 'express_no', 'barcode', 'online_weight', 'actual_weight', 'ship_time']) as $r) {
|
||
$l = ltrim(trim((string) $r->express_no), '@');
|
||
$sid = (int) $r->source_id;
|
||
$e = &$by[$l][$sid];
|
||
$e ??= [PHP_INT_MAX, PHP_INT_MAX, false, (string) $r->ship_time];
|
||
$id = (int) $r->id;
|
||
$e[0] = min($e[0], $id);
|
||
if (trim((string) $r->barcode) !== '') {
|
||
$e[1] = min($e[1], $id);
|
||
}
|
||
$e[2] = $e[2] || $r->online_weight !== null || $r->actual_weight !== null;
|
||
unset($e);
|
||
}
|
||
}
|
||
$primaryOf = [];
|
||
$folded = [];
|
||
foreach ($by as $sids) {
|
||
if (count($sids) < 2) {
|
||
continue;
|
||
}
|
||
$withItems = array_filter($sids, static fn ($e) => $e[1] !== PHP_INT_MAX);
|
||
$pool = $withItems !== [] ? $withItems : $sids;
|
||
uasort($pool, static fn ($a, $b) => ($a[1] === PHP_INT_MAX ? $a[0] : $a[1]) <=> ($b[1] === PHP_INT_MAX ? $b[0] : $b[1]));
|
||
$p = (int) array_key_first($pool);
|
||
$pt = strtotime($sids[$p][3]);
|
||
foreach ($sids as $sid => $e) {
|
||
$hasItems = $e[1] !== PHP_INT_MAX;
|
||
if ($sid === $p || ($hasItems && $e[2]) || abs(strtotime($e[3]) - $pt) > 86400) {
|
||
continue;
|
||
}
|
||
$primaryOf[$sid] = $p;
|
||
$folded[$p][] = $sid;
|
||
}
|
||
}
|
||
|
||
return [$primaryOf, $folded];
|
||
}
|
||
|
||
/**
|
||
* 本批里没有快递单号的包裹,它的交易单号是否已有带快递单号的包裹。
|
||
*
|
||
* @param array<int,array{l:string,trade:string,time:string}> $heads
|
||
* @return array<string,true>
|
||
*/
|
||
private function tradesWithWaybill(array $heads): array
|
||
{
|
||
$trades = [];
|
||
$min = null;
|
||
$max = null;
|
||
foreach ($heads as $h) {
|
||
if ($h['l'] === '' && $h['trade'] !== '') {
|
||
$trades[$h['trade']] = true;
|
||
$min = $min === null || $h['time'] < $min ? $h['time'] : $min;
|
||
$max = $max === null || $h['time'] > $max ? $h['time'] : $max;
|
||
}
|
||
}
|
||
if ($trades === []) {
|
||
return [];
|
||
}
|
||
$from = date('Y-m-d H:i:s', strtotime((string) $min) - 15 * 86400);
|
||
$to = date('Y-m-d H:i:s', strtotime((string) $max) + 15 * 86400);
|
||
$hit = [];
|
||
foreach (array_chunk(array_keys($trades), 500) as $chunk) {
|
||
foreach ($this->db->table('jst_oms_shipping')->whereIn('trade_no', array_map('strval', $chunk))
|
||
->where('ship_time', '>=', $from)->where('ship_time', '<', $to)
|
||
->whereNotNull('express_no')->where('express_no', '<>', '')
|
||
->distinct()->pluck('trade_no') as $t) {
|
||
$hit[trim((string) $t)] = true;
|
||
}
|
||
}
|
||
|
||
return $hit;
|
||
}
|
||
|
||
/**
|
||
* 把并入的订单合进主包裹:商品、体积相加,尺寸取最大;整包重量只记一次(取最大,不相加)。
|
||
* 聚水潭运费(jst_freight)仍各记各的,按单号汇总时不会重复。
|
||
*
|
||
* @param array<string,mixed> $pkg
|
||
* @param list<array<string,mixed>> $others
|
||
* @return array<string,mixed>
|
||
*/
|
||
private function fold(array $pkg, array $others): array
|
||
{
|
||
$codes = array_filter(explode(',', (string) $pkg['barcodes']), static fn ($b) => $b !== '');
|
||
$measured = $pkg['measured_weight'];
|
||
$measuredOk = $pkg['barcodes'] === '' || $measured !== null;
|
||
foreach ($others as $o) {
|
||
foreach (['online_weight', 'actual_weight', 'weight_kg'] as $c) {
|
||
if ($o[$c] !== null && ($pkg[$c] === null || (float) $o[$c] > (float) $pkg[$c])) {
|
||
$pkg[$c] = (float) $o[$c];
|
||
}
|
||
}
|
||
if ($o['volume_cm3'] !== null) {
|
||
$pkg['volume_cm3'] = (float) $pkg['volume_cm3'] + (float) $o['volume_cm3'];
|
||
}
|
||
$pkg['detail_volume_complete'] = $pkg['detail_volume_complete'] && $o['detail_volume_complete'];
|
||
if ($o['detail_volume_cm3'] !== null) {
|
||
$pkg['detail_volume_cm3'] = (float) $pkg['detail_volume_cm3'] + (float) $o['detail_volume_cm3'];
|
||
}
|
||
$pkg['supplier_names'] = array_values(array_unique(array_merge($pkg['supplier_names'], $o['supplier_names'])));
|
||
foreach (['length_cm', 'width_cm', 'height_cm'] as $c) {
|
||
if ($o[$c] !== null && ($pkg[$c] === null || (float) $o[$c] > (float) $pkg[$c])) {
|
||
$pkg[$c] = (float) $o[$c];
|
||
}
|
||
}
|
||
if ($o['barcodes'] !== '') {
|
||
foreach (explode(',', (string) $o['barcodes']) as $b) {
|
||
if (! in_array($b, $codes, true)) {
|
||
$codes[] = $b;
|
||
}
|
||
}
|
||
if ($o['measured_weight'] === null) {
|
||
$measuredOk = false;
|
||
} else {
|
||
$measured = (float) $measured + (float) $o['measured_weight'];
|
||
}
|
||
}
|
||
}
|
||
$pkg['barcodes'] = implode(',', $codes);
|
||
$pkg['measured_weight'] = $measuredOk && $measured !== null ? round((float) $measured, 4) : null;
|
||
if (! $pkg['detail_volume_complete']) {
|
||
$pkg['detail_volume_cm3'] = null;
|
||
}
|
||
|
||
return $pkg;
|
||
}
|
||
|
||
/** 不单独计费的行:状态 OK、运费 0,公式写明原因。 */
|
||
private static function zeroResult(string $why): array
|
||
{
|
||
return ['fee' => 0.0, 'status' => 'OK', 'ver' => null, 'base_w' => null, 'base_src' => '', 'vol_w' => null, 'coef' => null,
|
||
'free' => false, 'settle_w' => null, 'charge_w' => null, 'miandan' => null, 'first_kg' => null, 'first_price' => null,
|
||
'rate' => null, 'flat' => null, 'extra' => 0.0, 'formula' => $why, 'mode' => '', 'region' => null];
|
||
}
|
||
|
||
/**
|
||
* @param list<int> $ids
|
||
* @return list<array<string,mixed>>
|
||
*/
|
||
private function aggregate(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',
|
||
'receiver_district', 'receiver_address', 'receiver_name', 'supplier_name', '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, 'receiver_district' => null, 'receiver_address' => null, 'receiver_name' => 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,
|
||
'detail_volume_cm3' => null, 'detail_volume_complete' => true,
|
||
'barcodes' => [], 'supplier_names' => [], 'freight' => null];
|
||
}
|
||
foreach (['express_no', 'express_name1', 'warehouse_name', 'receiver_state', 'receiver_city', 'receiver_district',
|
||
'receiver_address', 'receiver_name', '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 ($r->volume_cm3 !== null) {
|
||
$p['detail_volume_cm3'] = (float) $p['detail_volume_cm3'] + (float) $r->volume_cm3;
|
||
}
|
||
if ((float) $r->qty > 0 && ($r->volume_cm3 === null || (float) $r->volume_cm3 <= 0)) {
|
||
$p['detail_volume_complete'] = false;
|
||
}
|
||
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);
|
||
$supplier = trim((string) $r->supplier_name);
|
||
if ($supplier !== '' && ! in_array($supplier, $p['supplier_names'], true)) {
|
||
$p['supplier_names'][] = $supplier;
|
||
}
|
||
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) {
|
||
if (! $p['detail_volume_complete']) $p['detail_volume_cm3'] = null;
|
||
$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,
|
||
];
|
||
}
|
||
}
|