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
This commit is contained in:
limeng 2026-11-18 13:55:40 +08:00
parent 957504ac1e
commit 1cf60dd7b0
14 changed files with 3324 additions and 11 deletions

View File

@ -6525,6 +6525,20 @@ class Pages extends Controller
['field' => 'finished_supplier', 'label' => '成品供应商', 'type' => 'text'],
['field' => 'settle_freight', 'label' => '结算运费', 'type' => 'number'],
['field' => 'front_no', 'label' => '换单前单号', 'type' => 'identifier'],
// 报价核算(按报价管理里发货日生效的报价)
['field' => 'qc_freight', 'label' => '核算运费', 'type' => 'number'],
['field' => 'qc_diff', 'label' => '核算-聚水潭运费', 'type' => 'number'],
['field' => 'qc_quote_version', 'label' => '报价版本', 'type' => 'identifier'],
['field' => 'qc_basis', 'label' => '结算重量依据', 'type' => 'text'],
['field' => 'qc_settle_weight', 'label' => '核算结算重量(kg)', 'type' => 'number'],
['field' => 'qc_charge_weight', 'label' => '计费重量(kg)', 'type' => 'number'],
['field' => 'qc_first_price', 'label' => '首重(元)', 'type' => 'number'],
['field' => 'qc_rate', 'label' => '续重/费率', 'type' => 'text'],
['field' => 'qc_miandan', 'label' => '面单(元)', 'type' => 'number'],
['field' => 'qc_flat_price', 'label' => '一口价(元)', 'type' => 'number'],
['field' => 'qc_extra_fee', 'label' => '多件/超长加收(元)', 'type' => 'number'],
['field' => 'qc_formula', 'label' => '核算公式', 'type' => 'text'],
['field' => 'qc_status', 'label' => '核算状态', 'type' => 'text'],
];
}

View File

@ -0,0 +1,36 @@
<?php
namespace Modules\EcommerceFinance\Console;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\Freight\FreightCarrierRules;
use Modules\EcommerceFinance\Services\Freight\ShippingFreightService;
/**
* 按报价管理的报价核算发货数据运费(结果显示在发货数据页面「报价核算」列)。
*
* php artisan jushuitan:calc-freight --from=2026-11-01 --to=2026-11-16
* php artisan jushuitan:calc-freight --from=2026-11-01 --to=2026-11-16 --carrier=北京韵达 --carrier=常州德邦
*/
class CalcShippingFreight extends Command
{
protected $signature = 'jushuitan:calc-freight {--from= : 发货日期起(含)} {--to= : 发货日期止(不含)} {--carrier=* : 只核算这些快递(报价名称)}';
protected $description = '按报价管理的报价核算发货数据运费';
public function handle(ShippingFreightService $service): int
{
$from = (string) ($this->option('from') ?: FreightCarrierRules::START_DATE);
$to = (string) ($this->option('to') ?: now()->addDay()->format('Y-m-d'));
if (! preg_match('/^\d{4}-\d{2}-\d{2}$/', $from) || ! preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) {
$this->error('--from / --to 需要 YYYY-MM-DD');
return self::FAILURE;
}
$carriers = array_values(array_filter(array_map('trim', (array) $this->option('carrier'))));
$res = $service->recalculate($from, $to, $carriers === [] ? null : $carriers);
$this->info(sprintf('运费核算完成:%s ~ %s,包裹 %d 个,核算成功 %d 个,无法核算 %d 个', $from, $to, $res['packages'], $res['ok'], $res['packages'] - $res['ok']));
return self::SUCCESS;
}
}

View File

@ -0,0 +1,57 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* 发货数据「报价核算」结果:每个包裹(source_id)一行,按报价管理里发货日生效的报价核算运费。
* 只存核算结果,不改 jst_oms_shipping 原始发货数据;发货数据页面按 source_id 关联显示。
*/
return new class extends Migration
{
private function schema(): \Illuminate\Database\Schema\Builder
{
return Schema::connection((string) config('jushuitan.connection', 'jushuitan_local'));
}
public function up(): void
{
$schema = $this->schema();
if ($schema->hasTable('jst_oms_shipping_freight')) {
return;
}
$schema->create('jst_oms_shipping_freight', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedBigInteger('source_id')->unique()->comment('包裹(jst_oms_shipping.source_id)');
$table->string('express_no', 64)->nullable();
$table->string('express_name', 100)->nullable()->comment('发货数据快递名称1');
$table->date('ship_date')->nullable()->index();
$table->string('quote_version', 32)->nullable()->comment('使用的报价版本号');
$table->string('status', 255)->nullable()->comment('OK 或无法核算的原因');
$table->string('base_source', 16)->nullable()->comment('实称重量/线上重量/重量');
$table->decimal('base_weight', 14, 4)->nullable();
$table->decimal('volume_weight', 14, 4)->nullable();
$table->unsignedInteger('coef')->nullable()->comment('计泡系数');
$table->boolean('free_warehouse')->default(false)->comment('免抛仓:不计泡、不收多件费');
$table->decimal('settle_weight', 14, 4)->nullable()->comment('结算重量 max(重量,体积重)');
$table->decimal('charge_weight', 14, 4)->nullable()->comment('计费重量(取整/起算后)');
$table->decimal('first_kg', 10, 2)->nullable();
$table->decimal('first_price', 14, 4)->nullable();
$table->string('rate', 32)->nullable()->comment('续重/费率');
$table->decimal('miandan', 14, 4)->nullable();
$table->decimal('flat_price', 14, 4)->nullable()->comment('一口价');
$table->decimal('extra_fee', 14, 4)->nullable()->comment('多件/超长/偏远加收');
$table->decimal('freight', 14, 2)->nullable()->comment('核算运费');
$table->decimal('jst_freight', 14, 2)->nullable()->comment('核算时的聚水潭运费');
$table->text('formula')->nullable();
$table->timestamp('calculated_at')->nullable();
$table->index(['express_name', 'ship_date'], 'jst_freight_express_date_index');
});
}
public function down(): void
{
$this->schema()->dropIfExists('jst_oms_shipping_freight');
}
};

View File

@ -8,7 +8,9 @@ use Modules\EcommerceFinance\Console\ImportShengsuanOrderProfitDetails;
use Modules\EcommerceFinance\Console\ProcessDingRefreshRequests;
use Modules\EcommerceFinance\Console\DiagnoseJushuitanPackage;
use Modules\EcommerceFinance\Console\ImportShengsuanOrderProfitRows;
use Modules\EcommerceFinance\Console\CalcShippingFreight;
use Modules\EcommerceFinance\Console\SyncJushuitanShipping;
use Modules\EcommerceFinance\Services\Freight\ShippingFreightService;
use Modules\EcommerceFinance\Services\JianSunSnapshotRefresher;
use Modules\EcommerceFinance\Services\OperationsReplicaSnapshotRefresher;
use Modules\EcommerceFinance\Services\UpstreamSnapshotRefresherRegistry;
@ -21,9 +23,12 @@ class Main extends Provider
$this->loadTranslationsFrom(__DIR__ . '/../Resources/lang', 'ecommerce-finance');
$this->loadMigrationsFrom(__DIR__ . '/../Database/Migrations');
$this->registerFreightRecalculation();
if ($this->app->runningInConsole()) {
$this->commands([
SyncJushuitanShipping::class,
CalcShippingFreight::class,
ProcessDingRefreshRequests::class,
DiagnoseJushuitanPackage::class,
ImportShengsuanOrderProfitRows::class,
@ -33,6 +38,22 @@ class Main extends Provider
}
}
/**
* 报价管理里报价版本新增、作废、签署归档后,按该快递从执行日期起自动重算发货数据的报价核算运费
* (同一请求内合并,请求结束后执行)。
*/
private function registerFreightRecalculation(): void
{
$queue = static fn ($version) => ShippingFreightService::queueCarrier($version?->company_name, $version?->effective_date);
\App\Models\Business\CourierQuoteVersion::saved($queue);
\App\Models\Business\CourierQuoteVersion::deleted($queue);
$bySignature = static function ($signature) use ($queue): void {
$version = \App\Models\Business\CourierQuoteVersion::query()->allCompanies()->find($signature->quote_version_id);
$queue($version);
};
\App\Models\Business\CourierQuoteSignature::saved($bySignature);
}
public function register(): void
{
$this->app->singleton(UpstreamSnapshotRefresherRegistry::class, function ($app) {

View File

@ -44,7 +44,7 @@ class ShippingOrderRepository
->forPage($page, $perPage)
->get()->map(fn ($r) => $this->detailRow((array) $r))->all();
return ['data' => $rows, 'total' => $total];
return ['data' => $this->attachFreight($rows, true), 'total' => $total];
}
// 合并:按包裹(source_id)归并
@ -64,7 +64,7 @@ class ShippingOrderRepository
->orderByDesc('source_id')
->get()->map(fn ($r) => (array) $r)->all();
return ['data' => $rows, 'total' => $total];
return ['data' => $this->attachFreight($rows, false), 'total' => $total];
}
/** 仅批量读取本月配件及其交易单号对应的三个月首发候选;复用发货数据合并口径。 */
@ -180,8 +180,8 @@ class ShippingOrderRepository
if ($rows === []) {
return;
}
foreach ($rows as $row) {
yield $this->detailRow((array) $row);
foreach ($this->attachFreight(array_map(fn ($row) => $this->detailRow((array) $row), $rows), true) as $row) {
yield $row;
}
$last = (int) $rows[array_key_last($rows)]->id;
if (count($rows) < $batchSize) {
@ -206,8 +206,8 @@ class ShippingOrderRepository
if ($rows === []) {
return;
}
foreach ($rows as $row) {
yield (array) $row;
foreach ($this->attachFreight(array_map(fn ($row) => (array) $row, $rows), false) as $row) {
yield $row;
}
$last = (int) $rows[array_key_last($rows)]->source_id;
if (count($rows) < $batchSize) {
@ -216,6 +216,73 @@ class ShippingOrderRepository
}
}
/** 报价核算结果列(jst_oms_shipping_freight):页面/导出列名 => 结果表字段。 */
public const FREIGHT_COLUMNS = [
'qc_freight' => 'freight', 'qc_diff' => null, 'qc_quote_version' => 'quote_version', 'qc_basis' => null,
'qc_settle_weight' => 'settle_weight', 'qc_charge_weight' => 'charge_weight', 'qc_first_price' => 'first_price',
'qc_rate' => 'rate', 'qc_miandan' => 'miandan', 'qc_flat_price' => 'flat_price', 'qc_extra_fee' => 'extra_fee',
'qc_formula' => 'formula', 'qc_status' => 'status',
];
/**
* 把报价核算结果并到发货数据行上。合并口径每个包裹一行;明细口径只放在包裹的第一行,避免求和重复。
*
* @param list<array<string,mixed>> $rows
* @return list<array<string,mixed>>
*/
private function attachFreight(array $rows, bool $detail): array
{
$ids = array_values(array_unique(array_filter(array_map(static fn ($r) => (int) ($r['source_id'] ?? 0), $rows))));
if ($ids === []) {
return $rows;
}
try {
$results = $this->db->table('jst_oms_shipping_freight')->whereIn('source_id', $ids)->get()->keyBy('source_id')->all();
$firstIds = $detail
? $this->db->table('jst_oms_shipping')->whereIn('source_id', $ids)->groupBy('source_id')
->selectRaw('source_id, MIN(id) as first_id')->pluck('first_id', 'source_id')->all()
: [];
} catch (\Throwable) {
return $rows; // 结果表未迁移时不影响发货数据显示
}
foreach ($rows as &$row) {
$sid = (int) ($row['source_id'] ?? 0);
$res = $results[$sid] ?? null;
if ($res === null || ($detail && (int) ($firstIds[$sid] ?? 0) !== (int) ($row['id'] ?? -1))) {
continue;
}
foreach (self::FREIGHT_COLUMNS as $key => $field) {
if ($field !== null) {
$row[$key] = $res->{$field};
}
}
$row['qc_diff'] = $res->freight !== null && $res->jst_freight !== null
? round((float) $res->freight - (float) $res->jst_freight, 2) : null;
$row['qc_basis'] = $this->freightBasis($res);
}
unset($row);
return $rows;
}
/** 结算重量依据,如「实称重量 5.2kg;体积重 6.1kg(÷8000)」「线上重量 3kg;免抛仓不计泡」。 */
private function freightBasis(object $res): ?string
{
if ($res->base_source === null) {
return null;
}
$kg = static fn ($v): string => rtrim(rtrim(number_format((float) $v, 4, '.', ''), '0'), '.');
$text = $res->base_source . ' ' . $kg($res->base_weight) . 'kg';
if ((bool) $res->free_warehouse) {
return $text . ';免抛仓不计泡';
}
if ($res->coef !== null && $res->volume_weight !== null) {
return $text . ';体积重 ' . $kg($res->volume_weight) . 'kg(÷' . $res->coef . ')';
}
return $text . ';不计泡';
}
/** @param array<string,string> $filters */
private function filteredQuery(array $filters): Builder
{

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,292 @@
<?php
namespace Modules\EcommerceFinance\Services\Freight;
/**
* 报价表(报价管理 values_json 单元格)解析:找表头、按省份取行、识别重量段表头、条码报价表。
* 与离线核算脚本(10 月核对过的口径)一一对应,单元格里的数字/文字按原样参与判断。
*/
final class QuoteSheet
{
public const CITY_KEYS = ['深圳', '舟山', '拉萨', '广州'];
public const PROVINCES = ['北京', '天津', '上海', '重庆', '河北', '山西', '辽宁', '吉林', '黑龙', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '海南', '四川', '贵州', '云南', '陕西', '甘肃', '青海', '台湾', '内蒙', '广西', '西藏', '宁夏', '新疆'];
private const HEADER_FIRST_CELLS = ['省份', '目的地', '地区', '公斤段', '条形码'];
private const BARCODE_RE = '/[A-Za-z]{2,}\d[A-Za-z0-9\-]{5,}/u';
/** 单元格转文字(对齐 Python str:整数值的小数写成 3.0,空/0 视为空)。 */
public static function text(mixed $cell): string
{
if ($cell === null || $cell === false || $cell === '' || $cell === 0 || $cell === 0.0) {
return '';
}
if (is_float($cell)) {
return floor($cell) == $cell && abs($cell) < 1e15 ? sprintf('%.1f', $cell) : (string) $cell;
}
return (string) $cell;
}
/** 数字单元格转 float;文字原样(去空白)返回;空返回 null。 */
public static function num(mixed $cell): float|string|null
{
if ($cell === null) {
return null;
}
if (is_int($cell) || is_float($cell)) {
return (float) $cell;
}
$t = trim((string) $cell);
if ($t !== '' && is_numeric($t)) {
return (float) $t;
}
return $t === '' ? null : $t;
}
/** 省份名归一到两字(黑龙/内蒙/广西/宁夏/新疆/西藏 前缀)。 */
public static function province(mixed $name): string
{
$s = (string) preg_replace('/\s/u', '', (string) ($name ?? ''));
foreach (['黑龙', '内蒙', '广西', '宁夏', '新疆', '西藏'] as $p) {
if (str_starts_with($s, $p)) {
return $p;
}
}
$s = (string) preg_replace('/((维吾尔|壮族|回族)?自治区|省|市)$/u', '', $s);
return mb_substr($s, 0, 2);
}
/**
* @param list<list<mixed>> $vals
* @return array{head:list<string>,rows:array<string,list<mixed>>,top:string}|null
*/
public static function parse(array $vals): ?array
{
$h = null;
foreach ($vals as $i => $r) {
if (is_array($r) && $r !== [] && in_array(str_replace(' ', '', trim(self::text($r[0] ?? null))), self::HEADER_FIRST_CELLS, true)) {
$h = $i;
break;
}
}
if ($h === null) {
return null;
}
$ncol = 0;
foreach ($vals as $r) {
$ncol = max($ncol, is_array($r) ? count($r) : 0);
}
$head = [];
for ($i = 0; $i < $ncol; $i++) {
$head[] = str_replace("\n", ' ', self::text($vals[$h][$i] ?? null));
}
$start = $h + 1;
$next = $vals[$h + 1] ?? [];
$c0 = is_array($next) && $next !== [] ? trim(self::text($next[0] ?? null)) : '';
if (is_array($next) && $next !== [] && in_array($c0, ['', '省份'], true) && self::anyTruthy(array_slice($next, 1))) {
for ($i = 0; $i < $ncol; $i++) {
$head[$i] = $head[$i] . ' ' . self::text($next[$i] ?? null);
}
$start = $h + 2;
}
$rows = [];
foreach (array_slice($vals, $start) as $r) {
if (! is_array($r) || $r === [] || ($r[0] ?? null) === null) {
continue;
}
$name = (string) preg_replace('/\s/u', '', self::rawText($r[0]));
if ($name === '' || mb_strlen($name) > 8) {
continue;
}
$key = in_array($name, ['深圳', '舟山', '拉萨'], true) ? $name : self::province($name);
if (! array_key_exists($key, $rows)) {
$row = [];
for ($i = 0; $i < $ncol; $i++) {
$row[] = self::num($r[$i] ?? null);
}
$rows[$key] = $row;
}
foreach (self::CITY_KEYS as $ck) { // 城市单独报价行(如 深圳市 / 深圳广州)
if (str_contains($name, $ck) && $ck !== $key && ! array_key_exists($ck, $rows)) {
$rows[$ck] = $rows[$key];
}
}
}
$top = implode(' ', array_map(static fn ($c) => self::text($c), is_array($vals[0] ?? null) ? $vals[0] : []));
return ['head' => $head, 'rows' => $rows, 'top' => $top];
}
/** 第一个匹配任一正则、且不匹配排除正则的表头列号(从 $start 起)。 */
public static function col(array $head, array $patterns, int $start = 1, array $exclude = []): ?int
{
for ($i = $start, $n = count($head); $i < $n; $i++) {
$t = $head[$i];
$hit = false;
foreach ($patterns as $p) {
if (preg_match('/' . $p . '/u', $t)) {
$hit = true;
break;
}
}
if (! $hit) {
continue;
}
foreach ($exclude as $e) {
if (preg_match('/' . $e . '/u', $t)) {
continue 2;
}
}
return $i;
}
return null;
}
/**
* 表头里的重量段:[下限, 上限, 列号]。识别 0-1kg、500g-1kg、300g、3kg、一口价 等写法。
*
* @param iterable<int> $cols
* @return list<array{0:float,1:float,2:int}>
*/
public static function bands(array $head, iterable $cols): array
{
$out = [];
foreach ($cols as $i) {
$t = str_replace([' ', '~', '~'], ['', '-', '-'], (string) ($head[$i] ?? ''));
if (preg_match('/(\d+)g-([\d.]+)kg/iu', $t, $m)) {
$out[] = [(float) $m[1] / 1000, (float) $m[2], $i];
} elseif (preg_match('/^(\d+)g(一口价)?$/iu', $t, $m)) {
$out[] = [0.0, (float) $m[1] / 1000, $i];
} elseif (preg_match('/([\d.]+)\s*[-~]\s*([\d.]+)/u', $t, $m) && is_numeric($m[1]) && is_numeric($m[2])) {
$out[] = [(float) $m[1], (float) $m[2], $i];
} elseif (preg_match('/([\d.]+)\s*(kg|公斤|KG)/u', $t, $m) && is_numeric($m[1])) {
$out[] = [0.0, (float) $m[1], $i];
} elseif (str_contains($t, '一口价')) {
$out[] = [0.0, 1e9, $i];
}
}
return $out;
}
/** 文字里出现的省份(两字简称)。 */
public static function provincesIn(mixed $text): array
{
$t = (string) preg_replace('/\s/u', '', self::text($text));
$out = [];
foreach (self::PROVINCES as $p) {
if (str_contains($t, $p)) {
$out[$p] = true;
}
}
return $out;
}
/**
* 按条码报价的表:{条码: [[省份集合|null(其余), 价格]]}、不发省份、布局。
*
* @return array{0:array<string,list<array{0:?array,1:mixed}>>,1:array<string,bool>,2:string}
*/
public static function barcodeTable(array $vals): array
{
$table = [];
$nogo = [];
foreach ($vals as $r) {
foreach ((array) $r as $c) {
$s = self::text($c);
if ($s !== '' && str_contains($s, '不发') && ! preg_match(self::BARCODE_RE, $s)) {
$nogo += self::provincesIn($c);
}
}
}
$isBarcode = static fn ($c): bool => (bool) preg_match('/^' . trim(self::BARCODE_RE, '/u') . '$/u', trim(self::text($c)));
$rowsBc = array_values(array_filter($vals, static fn ($r) => is_array($r) && ($r[0] ?? null) && $isBarcode($r[0])));
if ($rowsBc !== []) {
$hdr = null;
foreach ($vals as $r) {
foreach ((array) $r as $c) {
$s = self::text($c);
if ($s !== '' && (str_contains($s, '剩余') || str_contains($s, '其余') || str_contains($s, '其他'))) {
$hdr = $r;
break 2;
}
}
}
$regions = [];
if ($hdr !== null) {
foreach ($hdr as $i => $c) {
$s = self::text($c);
if ($i === 0 || $s === '') {
continue;
}
$regions[] = [$i, (str_contains($s, '剩余') || str_contains($s, '其余') || str_contains($s, '其他')) ? null : self::provincesIn($c)];
}
} else {
$regions = [[1, null]];
}
foreach ($rowsBc as $r) {
$bc = mb_strtoupper(trim(self::text($r[0])));
$table[$bc] = array_map(static fn ($reg) => [$reg[1], self::num($r[$reg[0]] ?? null)], $regions);
}
return [$table, $nogo, 'rows'];
}
foreach ($vals as $hi => $r) {
$groups = [];
foreach ((array) $r as $i => $c) {
$s = self::text($c);
if ($s !== '' && preg_match_all(self::BARCODE_RE, $s, $mm)) {
$groups[] = [$i, array_map('mb_strtoupper', $mm[0])];
}
}
if ($groups === []) {
continue;
}
$provRows = [];
foreach (array_slice($vals, $hi + 1) as $rr) {
if (is_array($rr) && ($rr[0] ?? null)) {
$k = self::province($rr[0]);
if (in_array($k, self::PROVINCES, true)) {
$provRows[$k] = $rr;
}
}
}
foreach ($groups as [$i, $bcs]) {
foreach ($bcs as $bc) {
$list = [];
foreach ($provRows as $p => $rr) {
$list[] = [[$p => true], self::num($rr[$i] ?? null)];
}
$table[$bc] = $list;
}
}
return [$table, $nogo, 'cols'];
}
return [[], $nogo, 'none'];
}
private static function rawText(mixed $cell): string
{
return is_float($cell) ? self::text($cell) : (string) $cell;
}
private static function anyTruthy(array $cells): bool
{
foreach ($cells as $c) {
if ($c !== null && $c !== '' && $c !== 0 && $c !== 0.0 && $c !== false) {
return true;
}
}
return false;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,314 @@
<?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,
];
}
}

View File

@ -306,6 +306,20 @@ class ShippingReplicaSynchronizer
$progress('按销售出库单校正(发货时间/线上实称重量)跳过:' . $e->getMessage());
}
}
// 报价核算运费(报价管理的报价):只核算核算起始日以后的发货数据,失败不影响同步结果
if ($toS > \Modules\EcommerceFinance\Services\Freight\FreightCarrierRules::START_DATE) {
try {
$fr = app(\Modules\EcommerceFinance\Services\Freight\ShippingFreightService::class)->recalculate($fromS, $toS);
if ($progress && $fr['packages'] > 0) {
$progress('报价核算运费:' . $fr['packages'] . ' 个包裹,核算成功 ' . $fr['ok'] . ' 个');
}
} catch (Throwable $e) {
report($e);
if ($progress) {
$progress('报价核算运费跳过:' . mb_substr($e->getMessage(), 0, 160));
}
}
}
} else {
$total = $this->syncExpress(false, $fromS, $toS, $limit, $now, $progress);
$this->applyPendingWarehouses($progress);
@ -685,8 +699,10 @@ class ShippingReplicaSynchronizer
{
$message = strtolower($e->getMessage());
// 20047 DBPROCESS is dead:副本库查询超时后连接被断开,重连后重查同一批即可
return str_contains($message, 'pdo_dblib: dbnextrow() returned fail')
|| str_contains($message, 'adaptive server connection timed out [20003]');
|| str_contains($message, 'adaptive server connection timed out [20003]')
|| str_contains($message, 'dbprocess is dead or not enabled');
}
/** 并入自动发货仓:jst_Orders 已发货但不在发货明细表。 */
@ -1164,7 +1180,7 @@ class ShippingReplicaSynchronizer
private function loadViewHeads(array $ioIds): array
{
$out = [];
foreach (array_chunk(array_values(array_unique(array_filter($ioIds))), 300) as $chunk) {
foreach (array_chunk(array_values(array_unique(array_filter($ioIds))), 100) as $chunk) {
if ($chunk === []) {
continue;
}
@ -2035,8 +2051,8 @@ class ShippingReplicaSynchronizer
$this->ioShop = [];
$this->ioExpress = [];
$this->ioWare = [];
// 发货数据视图是计算视图,IN 列表过长时副本库容易超时:按 300 个出库单一批
foreach (array_chunk(array_values(array_unique(array_filter($ioIds))), 300) as $chunk) {
// 发货数据视图是计算视图,IN 列表过长时副本库容易超时(11 月起 300 个一批常被断开):按 100 个出库单一批
foreach (array_chunk(array_values(array_unique(array_filter($ioIds))), 100) as $chunk) {
if ($chunk === []) {
continue;
}

View File

@ -53,6 +53,20 @@
['finished_supplier','成品供应商','left','text'],
['settle_freight','结算运费','right','money'],
['front_no','换单前单号','left','mono'],
// 报价核算(按报价管理里发货日生效的报价;合并口径每个包裹一行,明细口径只在包裹第一行)
['qc_freight','核算运费','right','money'],
['qc_diff','核算-聚水潭运费','right','money'],
['qc_quote_version','报价版本','left','mono'],
['qc_basis','结算重量依据','left','text'],
['qc_settle_weight','核算结算重量(kg)','right','num'],
['qc_charge_weight','计费重量(kg)','right','num'],
['qc_first_price','首重(元)','right','num'],
['qc_rate','续重/费率','right','text'],
['qc_miandan','面单(元)','right','num'],
['qc_flat_price','一口价(元)','right','num'],
['qc_extra_fee','多件/超长加收(元)','right','num'],
['qc_formula','核算公式','left','text'],
['qc_status','核算状态','left','text'],
];
$fmt = function ($v, $type) {

View File

@ -0,0 +1,103 @@
<?php
namespace Tests\Feature\Business;
use App\Models\Business\CourierQuoteChange;
use App\Models\Business\CourierQuoteVersion;
use Illuminate\Support\Facades\DB;
use Modules\EcommerceFinance\Repositories\ShippingOrderRepository;
use Modules\EcommerceFinance\Services\Freight\ShippingFreightService;
use Tests\Feature\FeatureTestCase;
class ShippingFreightServiceTest extends FeatureTestCase
{
public function test_packages_are_priced_by_the_quote_in_force_on_the_ship_date_and_shown_on_shipping_rows(): void
{
$this->version('QB-901', '新北中通', '2026-10-01', '2026-11-10', [['省份', '面单', '费率'], ['江苏', 3.5, 0.7]]);
$this->version('QB-902', '新北中通', '2026-11-11', null, [['省份', '面单', '费率'], ['江苏', 3.0, 0.6]]);
$db = DB::connection('business_mirror');
$row = static fn (int $sid, int $sku, string $time, array $extra = []) => $extra + [
'source_id' => $sid, 'sku_source_id' => $sku, 'express_no' => 'ZT' . $sid, 'express_name1' => '新北中通',
'warehouse_name' => '简尚-崔桥工厂仓', 'receiver_state' => '江苏省', 'receiver_city' => '南京市', 'ship_time' => $time,
'pkg_count' => '1/1', 'barcode' => 'SJ' . $sid . '-' . $sku, 'qty' => 1, 'freight' => 5,
'online_weight' => null, 'length_cm' => null, 'width_cm' => null, 'height_cm' => null,
];
$db->table('jst_oms_shipping')->insert([
// 两件商品一个包裹:重量求和 2+1=3kg,长宽高取最大 50×40×30 → 体积重 7.5kg
$row(1, 1, '2026-11-05 10:00:00', ['online_weight' => 2, 'length_cm' => 50, 'width_cm' => 40, 'height_cm' => 30]),
$row(1, 2, '2026-11-05 10:00:00', ['online_weight' => 1, 'length_cm' => 10, 'width_cm' => 10, 'height_cm' => 10, 'freight' => null]),
// 11-11 起用新报价;免抛仓不计泡
$row(2, 1, '2026-11-12 09:00:00', ['online_weight' => 4, 'length_cm' => 50, 'width_cm' => 40, 'height_cm' => 30, 'warehouse_name' => '常州简尚家居有限公司']),
// 核算起始日(11-01)以前不核算
$row(3, 1, '2026-10-30 09:00:00', ['online_weight' => 4]),
// 报价管理里没有的快递
$row(4, 1, '2026-11-12 09:00:00', ['online_weight' => 4, 'express_name1' => '某某快递']),
]);
$res = app(ShippingFreightService::class)->recalculate('2026-10-01', '2026-12-01');
$this->assertSame(['packages' => 3, 'ok' => 2], $res);
$r1 = $db->table('jst_oms_shipping_freight')->where('source_id', 1)->sole();
$this->assertSame('QB-901', $r1->quote_version);
$this->assertEquals(8.75, $r1->freight);
$this->assertEquals(7.5, $r1->settle_weight);
$this->assertEquals(5, $r1->jst_freight);
$r2 = $db->table('jst_oms_shipping_freight')->where('source_id', 2)->sole();
$this->assertSame('QB-902', $r2->quote_version);
$this->assertEquals(5.4, $r2->freight);
$this->assertSame(0, $db->table('jst_oms_shipping_freight')->where('source_id', 3)->count());
$this->assertSame('报价管理里没有「某某快递」的报价', $db->table('jst_oms_shipping_freight')->where('source_id', 4)->value('status'));
// 发货数据页面:合并口径每个包裹带核算列,明细口径只在包裹第一行
$attach = new \ReflectionMethod(ShippingOrderRepository::class, 'attachFreight');
$repo = app(ShippingOrderRepository::class);
$merged = $attach->invoke($repo, [['id' => 99, 'source_id' => 1]], false);
$this->assertEquals(8.75, $merged[0]['qc_freight']);
$this->assertEquals(3.75, $merged[0]['qc_diff']);
$this->assertSame('QB-901', $merged[0]['qc_quote_version']);
$this->assertSame('线上重量 3kg;体积重 7.5kg(÷8000)', $merged[0]['qc_basis']);
$ids = $db->table('jst_oms_shipping')->where('source_id', 1)->orderBy('id')->pluck('id')->all();
$detail = $attach->invoke($repo, [['id' => $ids[0], 'source_id' => 1], ['id' => $ids[1], 'source_id' => 1]], true);
$this->assertEquals(8.75, $detail[0]['qc_freight']);
$this->assertArrayNotHasKey('qc_freight', $detail[1]);
}
public function test_quote_changes_recalculate_that_carrier_from_the_effective_date(): void
{
DB::connection('business_mirror')->table('jst_oms_shipping')->insert([
'source_id' => 11, 'sku_source_id' => 1, 'express_no' => 'ZT11', 'express_name1' => '新北中通', 'warehouse_name' => '简尚-崔桥工厂仓',
'receiver_state' => '江苏省', 'ship_time' => '2026-11-16 09:00:00', 'pkg_count' => '1/1', 'online_weight' => 2,
]);
$this->version('QB-911', '新北中通', '2026-11-01', null, [['省份', '面单', '费率'], ['江苏', 3.0, 1.0]]);
ShippingFreightService::flushPending();
$this->assertEquals(5.0, DB::connection('business_mirror')->table('jst_oms_shipping_freight')->where('source_id', 11)->value('freight'));
// 补录 11-15 起的新报价:审核生效后自动按新报价重算
$this->version('QB-912', '新北中通', '2026-11-15', null, [['省份', '面单', '费率'], ['江苏', 4.0, 1.0]]);
ShippingFreightService::flushPending();
$row = DB::connection('business_mirror')->table('jst_oms_shipping_freight')->where('source_id', 11)->sole();
$this->assertSame('QB-912', $row->quote_version);
$this->assertEquals(6.0, $row->freight);
}
private function version(string $code, string $name, string $from, ?string $to, array $vals): CourierQuoteVersion
{
$change = CourierQuoteChange::create([
'company_id' => $this->company->id, 'number' => 'BG-T-' . $code, 'source_quote_id' => $code,
'source_sheet_name' => $name, 'carrier_name' => $name, 'quote_type' => '标准快递报价', 'change_type' => '面单调整',
'status' => CourierQuoteChange::STATUS_APPROVED, 'effective_date' => $from, 'is_retrospective' => false,
'recalculation_status' => CourierQuoteChange::RECALCULATION_NOT_REQUIRED, 'summary' => '测试报价',
'created_by' => $this->user->id, 'submitted_by' => $this->user->id, 'submitted_at' => now(),
'approved_by' => $this->user->id, 'approved_at' => now(),
]);
return CourierQuoteVersion::create([
'company_id' => $this->company->id, 'version_code' => $code, 'source_quote_id' => $code, 'source_change_id' => $change->id,
'sheet_name' => $name, 'company_name' => $name, 'carrier_name' => $name, 'quote_type' => '标准快递报价',
'effective_date' => $from, 'end_date' => $to, 'source_range' => 'A1:C2',
'values_json' => json_encode($vals, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
'formulas_json' => json_encode([[]], JSON_THROW_ON_ERROR), 'status' => 'approved',
'signature_status' => '历史签署资料已归档', 'created_by' => $this->user->id, 'approved_by' => $this->user->id,
]);
}
}

View File

@ -0,0 +1,132 @@
<?php
namespace Tests\Unit\EcommerceFinance;
use Modules\EcommerceFinance\Services\Freight\FreightCarrierRules;
use Modules\EcommerceFinance\Services\Freight\QuoteSheet;
use Modules\EcommerceFinance\Services\Freight\ShippingFreightCalculator;
use PHPUnit\Framework\TestCase;
class ShippingFreightCalculatorTest extends TestCase
{
private function quote(array $vals, string $id = 'QB-001', string $rules = ''): array
{
return ['id' => $id, 'p' => QuoteSheet::parse($vals), 'rules' => $rules, 'vals' => $vals];
}
private function cfg(string $name): array
{
return FreightCarrierRules::for($name) + ['_name' => $name];
}
private function pkg(array $over = []): array
{
return $over + [
'express_name1' => '新北中通', 'receiver_state' => '江苏省', 'receiver_city' => '南京市', 'warehouse_name' => '简尚-崔桥工厂仓',
'online_weight' => 2.0, 'actual_weight' => null, 'weight_kg' => 1.0, 'length_cm' => 50, 'width_cm' => 40, 'height_cm' => 30,
'volume_cm3' => null, 'pkg_count' => '1/1', 'barcodes' => 'SJ0001N01V01',
];
}
public function test_waybill_rate_uses_volume_weight_and_free_warehouses_do_not(): void
{
$calc = new ShippingFreightCalculator();
$q = $this->quote([['省份', '面单', '费率'], ['江苏', 3.5, 0.7], ['广东', 4, 1.1]]);
// 50×40×30 ÷ 8000 = 7.5kg > 线上 2kg:按体积重
$r = $calc->calculate($this->pkg(), $q, $this->cfg('新北中通'));
$this->assertSame('OK', $r['status']);
$this->assertSame(7.5, $r['settle_w']);
$this->assertSame(8.75, $r['fee']);
$this->assertSame('面单3.5+费率0.7×7.5kg = 8.75', $r['formula']);
// 免抛仓、仓库名含「配件」:不计泡,按线上重量
foreach (['常州简尚家居有限公司', '配件-山东沂海配件单仓'] as $wh) {
$r = $calc->calculate($this->pkg(['warehouse_name' => $wh]), $q, $this->cfg('新北中通'));
$this->assertTrue($r['free']);
$this->assertSame(4.9, $r['fee']);
}
// 实称优先于线上重量
$r = $calc->calculate($this->pkg(['actual_weight' => 9.0, 'length_cm' => null]), $q, $this->cfg('新北中通'));
$this->assertSame('实称重量', $r['base_src']);
$this->assertSame(9.8, $r['fee']);
}
public function test_first_weight_with_extra_pieces_and_over_length(): void
{
$calc = new ShippingFreightCalculator();
$q = $this->quote([['省份', '首重3kg', '续重'], ['江苏', 7, 1.5]]);
// 常州德邦:首重3kg,多件每件 3.5,单边超 160cm 加 7
$r = $calc->calculate($this->pkg(['express_name1' => '常州德邦', 'online_weight' => 5.0, 'length_cm' => 170, 'width_cm' => 10, 'height_cm' => 10, 'pkg_count' => '1/3']), $q, $this->cfg('常州德邦'));
$this->assertSame('OK', $r['status']);
// 5kg(体积 17000÷6000=2.83 < 5):7 + 2×1.5 + 3.5×2 + 7
$this->assertSame(24.0, $r['fee']);
$this->assertSame(14.0, $r['extra']);
// 免抛仓不收多件费
$r = $calc->calculate($this->pkg(['express_name1' => '常州德邦', 'warehouse_name' => '常州简尚家居有限公司', 'online_weight' => 5.0, 'length_cm' => 10, 'width_cm' => 10, 'height_cm' => 10, 'pkg_count' => '1/3']), $q, $this->cfg('常州德邦'));
$this->assertSame(10.0, $r['fee']);
}
public function test_flat_bands_city_rows_and_per_kg_provinces(): void
{
$calc = new ShippingFreightCalculator();
// 重量段一口价(菏泽顺帆顺丰:不计泡)
$q = $this->quote([['省份', '0-1kg', '1-2kg', '2-3kg'], ['浙江', 3, 4, 5]]);
$r = $calc->calculate($this->pkg(['express_name1' => '菏泽顺帆顺丰', 'receiver_state' => '浙江省', 'online_weight' => 1.5]), $q, $this->cfg('菏泽顺帆顺丰'));
$this->assertSame(4.0, $r['fee']);
$r = $calc->calculate($this->pkg(['express_name1' => '菏泽顺帆顺丰', 'receiver_state' => '浙江省', 'online_weight' => 3.5]), $q, $this->cfg('菏泽顺帆顺丰'));
$this->assertStringStartsWith('超出报价公斤段', $r['status']);
// 城市单独报价行:深圳优先于广东
$q = $this->quote([['省份', '面单', '费率'], ['广东', 4, 1.1], ['深圳', 5.1, 1.7]]);
$r = $calc->calculate($this->pkg(['receiver_state' => '广东省', 'receiver_city' => '深圳市', 'length_cm' => null]), $q, $this->cfg('新北中通'));
$this->assertSame('深圳', $r['region']);
$this->assertSame(8.5, $r['fee']);
// 整省「X元/公斤」+ 报价说明里的面单(北京韵达)
$q = $this->quote([['省份', '0-1kg', '面单', '6.01-50kg'], ['北京', 3, 2.5, 1.2], ['新疆', '15元/公斤', null, null]], 'QB-200', '面单费2元');
$r = $calc->calculate($this->pkg(['express_name1' => '北京韵达', 'receiver_state' => '新疆维吾尔自治区', 'online_weight' => 2.0, 'length_cm' => null]), $q, $this->cfg('北京韵达'));
$this->assertSame(32.0, $r['fee']);
$this->assertSame('面单2+该省按15元/公斤×2kg = 32.00', $r['formula']);
}
public function test_version_specific_coefficients_and_ddb_barcodes(): void
{
$calc = new ShippingFreightCalculator();
$grid = [['省份', '0-1kg', '面单', '6.01-50kg'], ['北京', 3, 2.5, 1.2]];
$pkg = $this->pkg(['express_name1' => '北京韵达', 'receiver_state' => '北京', 'online_weight' => 1.0, 'length_cm' => 100, 'width_cm' => 40, 'height_cm' => 20]);
// QB-200 系数 8000:80000/8000=10kg;QB-198 按报价 10000:8kg
$this->assertSame(10.0, $calc->calculate($pkg, $this->quote($grid, 'QB-200'), $this->cfg('北京韵达'))['settle_w']);
$this->assertSame(8.0, $calc->calculate($pkg, $this->quote($grid, 'QB-198'), $this->cfg('北京韵达'))['settle_w']);
// 洞洞板(DDB 开头条码)在景瓴小件-莒南按 9000 计泡
$q = $this->quote([['省份', '首重3kg', '续重'], ['江苏', 6, 2]]);
$base = $this->pkg(['express_name1' => '景瓴十方顺丰小件-莒南', 'online_weight' => 1.0, 'length_cm' => 90, 'width_cm' => 50, 'height_cm' => 20]);
$this->assertSame(15.0, $calc->calculate($base, $q, $this->cfg('景瓴十方顺丰小件-莒南'))['settle_w']);
$this->assertSame(10.0, $calc->calculate(['barcodes' => 'DDB0012N01V01'] + $base, $q, $this->cfg('景瓴十方顺丰小件-莒南'))['settle_w']);
}
public function test_missing_quote_or_rules_explain_why(): void
{
$calc = new ShippingFreightCalculator();
$this->assertSame('发货日没有生效的报价', $calc->calculate($this->pkg(), null, $this->cfg('新北中通'))['status']);
$this->assertSame('计费方式未配置', $calc->calculate($this->pkg(), $this->quote([['省份', '面单', '费率'], ['江苏', 3, 1]]), null)['status']);
$r = $calc->calculate($this->pkg(['receiver_state' => '西藏自治区']), $this->quote([['省份', '面单', '费率'], ['江苏', 3, 1]]), $this->cfg('新北中通'));
$this->assertSame('报价无此省份(西藏)', $r['status']);
$this->assertNull($r['fee']);
}
public function test_barcode_quotes_pick_the_package_barcode_price(): void
{
$calc = new ShippingFreightCalculator();
$q = $this->quote([['条形码', '江苏浙江上海', '其余省份'], ['HPYD001N01V01', 6, 9], ['新疆西藏不发', null, null]]);
$r = $calc->calculate($this->pkg(['express_name1' => '浩浦韵达', 'receiver_state' => '浙江省', 'barcodes' => 'HPYD001N01V01']), $q, $this->cfg('浩浦韵达'));
$this->assertSame(6.0, $r['fee']);
$r = $calc->calculate($this->pkg(['express_name1' => '浩浦韵达', 'receiver_state' => '四川省', 'barcodes' => 'HPYD001N01V01']), $q, $this->cfg('浩浦韵达'));
$this->assertSame(9.0, $r['fee']);
$r = $calc->calculate($this->pkg(['express_name1' => '浩浦韵达', 'receiver_state' => '新疆', 'barcodes' => 'HPYD001N01V01']), $q, $this->cfg('浩浦韵达'));
$this->assertSame('新疆不发货', $r['status']);
}
}

View File

@ -191,6 +191,16 @@ class ShippingReplicaSynchronizerTest extends TestCase
->orderBy('source_id')->pluck('source_id')->map(fn ($id) => (int) $id)->all());
}
public function test_dead_dblib_process_after_replica_timeout_is_treated_as_transient(): void
{
$factory = $this->createMock(UpstreamReadOnlyQueryFactory::class);
$factory->method('forSource')->willReturn($this->createMock(UpstreamReadOnlyQuery::class));
$sync = new ShippingReplicaSynchronizer($factory);
$method = new \ReflectionMethod($sync, 'isTransientCursorFailure');
$this->assertTrue($method->invoke($sync, new PDOException('SQLSTATE[HY000]: General error: 20047 DBPROCESS is dead or not enabled [20047] (severity 9)')));
$this->assertFalse($method->invoke($sync, new PDOException('SQLSTATE[42S22]: Invalid column name')));
}
public function test_non_transient_upstream_failure_is_not_retried(): void
{
$calls = 0;
@ -1292,7 +1302,7 @@ class ShippingReplicaSynchronizerTest extends TestCase
$load = new \ReflectionMethod($sync, 'loadViewItems');
$load->setAccessible(true);
$load->invoke($sync, array_merge(['12', '41', '99'], array_map('strval', range(1000, 1400))));
$this->assertSame([300, 104], $chunks); // 视图按 300 个出库单一批
$this->assertSame([100, 100, 100, 100, 4], $chunks); // 视图按 100 个出库单一批(300 个一批副本库常超时断开)
$pending = new \ReflectionProperty($sync, 'pendingWarehouse');
$pending->setAccessible(true);