CaiWuXiTong/app/Support/CourierBills/ShippingLookup.php

297 lines
15 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 App\Support\CourierBills;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\DB;
/**
* 按快递单号读发货数据(jst_oms_shipping)和报价核算结果(jst_oms_shipping_freight)。
*
* 发货数据一行一个商品;对账按单号聚合,口径同发货数据页「合并」:
* 数量/重量/体积/金额/运费求和,商品ID、条形码拼接,长宽高取最大,其余取第一个非空值。
* 一个单号对应多个包裹(source_id)时,核算运费按包裹相加;任一包裹没核算成功就算「未核算」。
*/
final class ShippingLookup
{
private const CHUNK = 500;
public const COLUMNS = [
'express_no' => '快递单号', 'trade_no' => '交易单号', 'item_id' => '商品ID', 'barcode' => '条形码',
'product_name' => '商品名称', 'qty' => '数量', 'pkg_count' => '件数', 'receiver_state' => '省',
'buyer_nick' => '买家昵称', 'receiver_name' => '收货姓名', 'shop_name' => '店铺名称', 'express_name1' => '快递名称1',
'warehouse_name' => '仓库', 'ship_time' => '发货时间', 'freight' => '运费', 'online_weight' => '线上重量',
'actual_weight' => '实称重量', 'length_cm' => '长(cm)', 'width_cm' => '宽(cm)', 'height_cm' => '高(cm)',
'volume_cm3' => '体积(cm³)', 'receiver_city' => '市', 'receiver_district' => '区', 'supplier_name' => '供应商',
'receiver_address' => '收货详细地址', 'receiver_mobile' => '手机号码', 'receiver_phone' => '座机号码',
'express_name2' => '快递名称2', 'platform' => '平台', 'buyer_memo' => '买家留言', 'seller_memo' => '卖家备注',
'package_no' => '配货单号', 'amount' => '金额', 'product_code' => '货号', 'download_time' => '下载时间',
'pay_time' => '付款时间', 'freight_rate' => '费率', 'freight_formula' => '公式', 'weight_kg' => '重量(kg)',
'settle_weight_kg' => '结算重量(kg)', 'settle_volume_cm3' => '结算体积(cm³)', 'recon_weight_kg' => '对账重量(kg)',
'recon_volume_cm3' => '对账体积(cm³)', 'finished_barcode' => '成品条码', 'finished_name' => '成品名称',
'finished_supplier' => '成品供应商', 'settle_freight' => '结算运费', 'front_no' => '换单前单号',
'qc_freight' => '核算运费', 'qc_diff' => '核算-聚水潭运费', 'qc_quote_version' => '报价版本',
'qc_settle_weight' => '核算结算重量(kg)', 'qc_charge_weight' => '计费重量(kg)', 'qc_first_price' => '首重(元)',
'qc_rate' => '续重/费率', 'qc_miandan' => '面单(元)', 'qc_flat_price' => '一口价(元)',
'qc_extra_fee' => '多件/超长加收(元)', 'qc_formula' => '核算公式', 'qc_status' => '核算状态',
];
/** 文本列:导出时保持文本,长数字不变科学计数法。 */
public const TEXT_COLUMNS = ['express_no', 'trade_no', 'item_id', 'barcode', 'receiver_mobile', 'receiver_phone',
'package_no', 'product_code', 'finished_barcode', 'front_no', 'qc_quote_version'];
private const SUM = ['qty', 'freight', 'online_weight', 'actual_weight', 'volume_cm3', 'weight_kg', 'settle_weight_kg',
'settle_volume_cm3', 'recon_weight_kg', 'recon_volume_cm3', 'amount', 'settle_freight'];
private const CONCAT = ['item_id', 'barcode', 'product_name', 'supplier_name', 'finished_barcode', 'finished_name', 'finished_supplier'];
private const MAX = ['length_cm', 'width_cm', 'height_cm'];
public function connection(): ConnectionInterface
{
return DB::connection((string) config('jushuitan.connection', 'jushuitan_local'));
}
/**
* 对账用的单号摘要。
*
* @param list<string> $waybills
* @return array<string,array{ship_time:?string,express_name:?string,calc_freight:?float,charge_weight:?float}> 键为大写单号
*/
public function summaries(array $waybills): array
{
$result = [];
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
$rows = $this->connection()->table('jst_oms_shipping')->whereIn('express_no', $chunk)
->orderBy('id')->get(['express_no', 'express_name1', 'ship_time', 'source_id']);
$packages = [];
foreach ($rows as $row) {
$key = strtoupper(trim((string) $row->express_no));
$item = $result[$key] ?? ['ship_time' => null, 'express_name' => null, 'calc_freight' => null, 'charge_weight' => null, '_sources' => []];
if ($row->ship_time !== null && ($item['ship_time'] === null || (string) $row->ship_time < $item['ship_time'])) {
$item['ship_time'] = (string) $row->ship_time;
}
$item['express_name'] ??= self::blank($row->express_name1);
if ($row->source_id !== null) {
$item['_sources'][(int) $row->source_id] = true;
$packages[(int) $row->source_id] = true;
}
$result[$key] = $item;
}
$freights = $this->freights(array_keys($packages));
foreach ($result as $key => $item) {
if (! isset($item['_sources'])) {
continue;
}
$total = 0.0;
$weight = 0.0;
$ok = $item['_sources'] !== [];
foreach (array_keys($item['_sources']) as $source) {
$freight = $freights[$source] ?? null;
if ($freight === null || strtoupper((string) $freight->status) !== 'OK' || $freight->freight === null) {
$ok = false;
break;
}
$total += (float) $freight->freight;
$weight += (float) $freight->charge_weight;
}
unset($item['_sources']);
$item['calc_freight'] = $ok ? round($total, 2) : null;
$item['charge_weight'] = $ok ? round($weight, 4) : null;
$result[$key] = $item;
}
}
return $result;
}
/**
* 导出用的整行发货数据(含核算列),按单号合并。
*
* @param list<string> $waybills
* @return array<string,array<string,mixed>> 键为大写单号
*/
public function details(array $waybills): array
{
$result = [];
foreach (array_chunk(array_values(array_unique($waybills)), self::CHUNK) as $chunk) {
$rows = $this->connection()->table('jst_oms_shipping')->whereIn('express_no', $chunk)->orderBy('id')->get();
$sources = [];
foreach ($rows as $row) {
$row = (array) $row;
// 组合件拆件后明细存部件值,合并取整行值(m_*),口径同发货数据页。
foreach (['product_name' => 'm_name', 'volume_cm3' => 'm_volume_cm3', 'length_cm' => 'm_length_cm',
'width_cm' => 'm_width_cm', 'height_cm' => 'm_height_cm'] as $column => $merged) {
if (($row[$merged] ?? null) !== null && $row[$merged] !== '') {
$row[$column] = $row[$merged];
}
}
$key = strtoupper(trim((string) $row['express_no']));
$sources[$key][(int) ($row['source_id'] ?? 0)] = true;
if (! isset($result[$key])) {
$result[$key] = array_intersect_key($row, self::COLUMNS);
foreach (self::CONCAT as $column) {
$result[$key][$column] = self::blank($row[$column] ?? null);
}
continue;
}
$merged = &$result[$key];
foreach (self::SUM as $column) {
if (($row[$column] ?? null) !== null) {
$merged[$column] = round((float) ($merged[$column] ?? 0) + (float) $row[$column], 4);
}
}
foreach (self::CONCAT as $column) {
$value = self::blank($row[$column] ?? null);
if ($value !== null && ! in_array($value, explode(',', (string) $merged[$column]), true)) {
$merged[$column] = $merged[$column] === null ? $value : $merged[$column] . ',' . $value;
}
}
foreach (self::MAX as $column) {
if (($row[$column] ?? null) !== null) {
$merged[$column] = max((float) ($merged[$column] ?? 0), (float) $row[$column]);
}
}
foreach (self::COLUMNS as $column => $_) {
if (array_key_exists($column, $row) && ($merged[$column] ?? null) === null) {
$merged[$column] = $row[$column];
}
}
unset($merged);
}
$ids = [];
foreach ($sources as $set) {
$ids += $set;
}
$freights = $this->freights(array_keys($ids));
foreach ($sources as $key => $set) {
$parts = array_values(array_filter(array_map(static fn (int $id) => $freights[$id] ?? null, array_keys($set))));
if ($parts === []) {
continue;
}
$first = $parts[0];
$sum = static fn (string $field): ?float => array_reduce($parts,
static fn (?float $carry, object $p): ?float => $p->{$field} === null ? $carry : (float) $carry + (float) $p->{$field}, null);
$freight = $sum('freight');
$jst = $sum('jst_freight');
$result[$key] += [
'qc_freight' => $freight, 'qc_diff' => $freight !== null && $jst !== null ? round($freight - $jst, 2) : null,
'qc_quote_version' => $first->quote_version, 'qc_settle_weight' => $sum('settle_weight'),
'qc_charge_weight' => $sum('charge_weight'), 'qc_first_price' => $first->first_price, 'qc_rate' => $first->rate,
'qc_miandan' => $sum('miandan'), 'qc_flat_price' => $first->flat_price, 'qc_extra_fee' => $sum('extra_fee'),
'qc_formula' => $first->formula,
'qc_status' => implode(';', array_unique(array_map(static fn (object $p): string => (string) $p->status, $parts))),
];
if (count($set) > 1) {
$result[$key]['pkg_count'] = count($set) . '个包裹';
}
}
}
return $result;
}
/**
* 当月发货、快递名称属于本分组的单号(用于找「快递未提供」)。
*
* @param list<string> $expressNames
* @return \Generator<int,array{waybill:string,ship_time:?string,express_name:?string}>
*/
public function monthWaybills(array $expressNames, string $month): \Generator
{
if ($expressNames === []) {
return;
}
// 按天走 ship_time 索引,单次只扫一天的发货行。
$day = strtotime($month . '-01');
$end = strtotime($month . '-01 +1 month');
for (; $day < $end; $day = strtotime('+1 day', $day)) {
$rows = $this->connection()->table('jst_oms_shipping')
->where('ship_time', '>=', date('Y-m-d 00:00:00', $day))
->where('ship_time', '<', date('Y-m-d 00:00:00', strtotime('+1 day', $day)))
->whereIn('express_name1', $expressNames)
->whereNotNull('express_no')->where('express_no', '<>', '')
->get(['express_no', 'ship_time', 'express_name1']);
foreach ($rows as $row) {
yield ['waybill' => strtoupper(trim((string) $row->express_no)), 'ship_time' => (string) $row->ship_time,
'express_name' => self::blank($row->express_name1)];
}
}
}
/**
* 某月发货数据里各快递名称1 的发货行数(按天走 ship_time 索引)。
*
* @return array<string,int>
*/
public function monthExpressNames(string $month): array
{
$counts = [];
$day = strtotime($month . '-01');
$end = strtotime($month . '-01 +1 month');
for (; $day < $end; $day = strtotime('+1 day', $day)) {
$rows = $this->connection()->table('jst_oms_shipping')
->where('ship_time', '>=', date('Y-m-d 00:00:00', $day))
->where('ship_time', '<', date('Y-m-d 00:00:00', strtotime('+1 day', $day)))
->whereNotNull('express_name1')->where('express_name1', '<>', '')
->groupBy('express_name1')->selectRaw('express_name1, COUNT(*) as n')->get();
foreach ($rows as $row) {
$name = trim((string) $row->express_name1);
$counts[$name] = ($counts[$name] ?? 0) + (int) $row->n;
}
}
return $counts;
}
/**
* 换单:发货数据里「换单前单号」是这些单号的包裹(快递常按换单前的旧单号开账单)。
*
* @param list<string> $waybills
* @return array<string,array{0:string,1:?string}> 旧单号(大写)=> [新快递单号, 新单号的快递名称1]
*/
public function replacedBy(array $waybills): array
{
$result = [];
try {
// front_no 没有索引,通常用一次查询覆盖一张账单的未匹配单号。
foreach (array_chunk(array_values(array_unique($waybills)), 10000) as $chunk) {
foreach ($this->connection()->table('jst_oms_shipping')->whereIn('front_no', $chunk)
->whereNotNull('express_no')->where('express_no', '<>', '')
->orderBy('id')->get(['front_no', 'express_no', 'express_name1']) as $row) {
$old = strtoupper(trim((string) $row->front_no));
$result[$old] ??= [strtoupper(trim((string) $row->express_no)), self::blank($row->express_name1)];
}
}
} catch (\Illuminate\Database\QueryException $error) {
report($error);
}
return $result;
}
/** @return array<int,object> source_id => 核算结果 */
private function freights(array $sourceIds): array
{
$result = [];
foreach (array_chunk($sourceIds, self::CHUNK) as $chunk) {
try {
foreach ($this->connection()->table('jst_oms_shipping_freight')->whereIn('source_id', $chunk)->get() as $row) {
$result[(int) $row->source_id] = $row;
}
} catch (\Illuminate\Database\QueryException $error) {
report($error);
return [];
}
}
return $result;
}
private static function blank(mixed $value): ?string
{
$value = trim((string) $value);
return $value === '' ? null : $value;
}
}