From 1cf60dd7b0a89c781965876b44c759d473c2bcb4 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Wed, 18 Nov 2026 13:55:40 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E5=8F=91=E8=B4=A7=E6=95=B0=E6=8D=AE):=20?= =?UTF-8?q?=E6=8C=89=E6=8A=A5=E4=BB=B7=E7=AE=A1=E7=90=86=E7=9A=84=E6=8A=A5?= =?UTF-8?q?=E4=BB=B7=E6=A0=B8=E7=AE=97=E8=BF=90=E8=B4=B9=EF=BC=8C=E7=BB=93?= =?UTF-8?q?=E6=9E=9C=E6=98=BE=E7=A4=BA=E5=9C=A8=E5=8F=91=E8=B4=A7=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E9=A1=B5=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 从 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 Claude-Session: https://claude.ai/code/session_014nvGZkg27YMEdhry6eiuwf --- app/Http/Controllers/Business/Pages.php | 14 + .../Console/CalcShippingFreight.php | 36 + ..._create_jst_oms_shipping_freight_table.php | 57 + modules/EcommerceFinance/Providers/Main.php | 21 + .../Repositories/ShippingOrderRepository.php | 79 +- .../Services/Freight/FreightCarrierRules.php | 1223 +++++++++++++++++ .../Services/Freight/QuoteSheet.php | 292 ++++ .../Freight/ShippingFreightCalculator.php | 1014 ++++++++++++++ .../Freight/ShippingFreightService.php | 314 +++++ .../Jushuitan/ShippingReplicaSynchronizer.php | 24 +- .../courier-payables/shipping-data.blade.php | 14 + .../Business/ShippingFreightServiceTest.php | 103 ++ .../ShippingFreightCalculatorTest.php | 132 ++ .../ShippingReplicaSynchronizerTest.php | 12 +- 14 files changed, 3324 insertions(+), 11 deletions(-) create mode 100644 modules/EcommerceFinance/Console/CalcShippingFreight.php create mode 100644 modules/EcommerceFinance/Database/Migrations/2026_11_15_000001_create_jst_oms_shipping_freight_table.php create mode 100644 modules/EcommerceFinance/Services/Freight/FreightCarrierRules.php create mode 100644 modules/EcommerceFinance/Services/Freight/QuoteSheet.php create mode 100644 modules/EcommerceFinance/Services/Freight/ShippingFreightCalculator.php create mode 100644 modules/EcommerceFinance/Services/Freight/ShippingFreightService.php create mode 100644 tests/Feature/Business/ShippingFreightServiceTest.php create mode 100644 tests/Unit/EcommerceFinance/ShippingFreightCalculatorTest.php diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index de3b4377..a47273fb 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -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'], ]; } diff --git a/modules/EcommerceFinance/Console/CalcShippingFreight.php b/modules/EcommerceFinance/Console/CalcShippingFreight.php new file mode 100644 index 00000000..12450067 --- /dev/null +++ b/modules/EcommerceFinance/Console/CalcShippingFreight.php @@ -0,0 +1,36 @@ +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; + } +} diff --git a/modules/EcommerceFinance/Database/Migrations/2026_11_15_000001_create_jst_oms_shipping_freight_table.php b/modules/EcommerceFinance/Database/Migrations/2026_11_15_000001_create_jst_oms_shipping_freight_table.php new file mode 100644 index 00000000..bece6d57 --- /dev/null +++ b/modules/EcommerceFinance/Database/Migrations/2026_11_15_000001_create_jst_oms_shipping_freight_table.php @@ -0,0 +1,57 @@ +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'); + } +}; diff --git a/modules/EcommerceFinance/Providers/Main.php b/modules/EcommerceFinance/Providers/Main.php index 9108f754..f130a0cc 100644 --- a/modules/EcommerceFinance/Providers/Main.php +++ b/modules/EcommerceFinance/Providers/Main.php @@ -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) { diff --git a/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php b/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php index 290575e7..bdd070e0 100644 --- a/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php +++ b/modules/EcommerceFinance/Repositories/ShippingOrderRepository.php @@ -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> $rows + * @return list> + */ + 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 $filters */ private function filteredQuery(array $filters): Builder { diff --git a/modules/EcommerceFinance/Services/Freight/FreightCarrierRules.php b/modules/EcommerceFinance/Services/Freight/FreightCarrierRules.php new file mode 100644 index 00000000..18a5190a --- /dev/null +++ b/modules/EcommerceFinance/Services/Freight/FreightCarrierRules.php @@ -0,0 +1,1223 @@ + '北京韵达', + '北京韵达-浩泰源' => '北京韵达', + '北京韵达-锦辉' => '北京韵达', + '北京韵达-永超' => '北京韵达', + ]; + + /** 发货日期早于此日不核算(报价核算从 2026-11 起)。 */ + public const START_DATE = '2026-11-01'; + + /** @return array> */ + public static function all(): array + { + return [ + '新北中通' => [ + 'mode' => 'A', + 'coef' => 8000, + ], + '新北中通其他' => [ + 'mode' => 'A', + 'coef' => 8000, + ], + '樵舍中通' => [ + 'mode' => 'A', + 'coef' => 10000, + ], + '樵舍中通-上楼' => [ + 'mode' => 'A', + 'coef' => 10000, + ], + '江西新建中通' => [ + 'mode' => 'A10', + 'coef' => 10000, + ], + '武进极兔' => [ + 'mode' => 'ASEG', + 'coef' => 8000, + ], + '武进极兔-上楼' => [ + 'mode' => 'ASEG', + 'coef' => 8000, + ], + '常州圆通其他' => [ + 'mode' => 'ASEG', + 'coef' => 6000, + ], + '常州圆通-上楼' => [ + 'mode' => 'ASEG', + 'coef' => 6000, + ], + '苏夏申通' => [ + 'mode' => 'ASEG', + 'coef' => 8000, + ], + '沭阳德邦' => [ + 'mode' => 'A', + 'coef' => 6000, + ], + '沭阳德邦其他' => [ + 'mode' => 'A', + 'coef' => 6000, + ], + '沭阳德邦超长' => [ + 'mode' => 'A', + 'coef' => 6000, + 'add' => 10, + ], + '沭阳德邦超长其他' => [ + 'mode' => 'A', + 'coef' => 6000, + 'add' => 10, + ], + '睢宁中通' => [ + 'mode' => 'B3SEG', + 'coef' => 6000, + ], + '山东中通快运' => [ + 'mode' => 'C', + 'first' => 10, + 'coef' => 8000, + ], + '小件宿迁圆通' => [ + 'mode' => 'B3', + 'coef' => 8000, + ], + '新北中通配件' => [ + 'mode' => 'B3', + 'coef' => null, + ], + '新北中通其他配件' => [ + 'mode' => 'B3', + 'coef' => null, + ], + '景瓴十方顺丰小件' => [ + 'mode' => 'C', + 'first' => 3, + 'coef' => 6000, + ], + '景瓴十方顺丰小件-西安' => [ + 'mode' => 'C', + 'first' => 3, + 'coef' => 6000, + ], + '景瓴十方顺丰小件-泰安' => [ + 'mode' => 'C', + 'first' => 3, + 'coef' => 6000, + ], + '景瓴十方顺丰小件-泰州' => [ + 'mode' => 'C', + 'first' => 3, + 'coef' => 6000, + ], + '景瓴十方顺丰大件-西安' => [ + 'mode' => 'C', + 'first' => 20, + 'coef' => 3000, + ], + '景瓴十方顺丰大件-泰安' => [ + 'mode' => 'C', + 'first' => 20, + 'coef' => 3000, + ], + '景瓴十方顺丰大件' => [ + 'mode' => 'C', + 'first' => 20, + 'coef' => 6000, + ], + '景瓴十方顺丰大件-泰州' => [ + 'mode' => 'C', + 'first' => 20, + 'coef' => 3000, + ], + '名屋居安能快运' => [ + 'mode' => 'C', + 'first' => 20, + 'coef' => 6000, + 'ceil' => true, + ], + '盛强安能快运' => [ + 'mode' => 'C', + 'first' => 1, + 'coef' => 8000, + ], + '盛强京东' => [ + 'mode' => 'C', + 'first' => 1, + 'coef' => 8000, + ], + '迈当中通快运' => [ + 'mode' => 'C', + 'first' => 10, + 'coef' => 8000, + 'roundw' => true, + ], + '顺兴中通快运' => [ + 'mode' => 'SX', + 'coef' => 6000, + ], + '彩艺德邦' => [ + 'mode' => 'D', + 'coef' => 10000, + 'mode_by_ver' => [ + 'QB-192' => [ + 'dcols' => [2, 3], + 'no_long' => true, + ], + 'QB-193' => [ + 'dcols' => [2, 3], + 'no_long' => true, + ], + ], + ], + '彩艺德邦其他' => [ + 'mode' => 'D', + 'coef' => 10000, + 'mode_by_ver' => [ + 'QB-192' => [ + 'dcols' => [2, 3], + 'no_long' => true, + ], + 'QB-193' => [ + 'dcols' => [2, 3], + 'no_long' => true, + ], + ], + ], + '华韵顺心捷达' => [ + 'mode' => 'F', + ], + '华韵安能' => [ + 'mode' => 'F', + ], + '华韵京东' => [ + 'mode' => 'F', + ], + '菏泽顺帆顺丰' => [ + 'mode' => 'E', + 'coef' => null, + ], + '派雅极兔' => [ + 'mode' => 'E', + 'coef' => null, + ], + '卿德客极兔' => [ + 'mode' => 'E', + 'coef' => null, + ], + '卿德客申通' => [ + 'mode' => 'E', + 'coef' => null, + ], + '钦诺极兔' => [ + 'mode' => 'E', + 'coef' => null, + ], + '钦诺邮政' => [ + 'mode' => 'E', + 'coef' => null, + ], + '派雅韵达' => [ + 'mode' => 'E', + 'coef' => null, + ], + '派雅圆通' => [ + 'mode' => 'E', + 'coef' => null, + ], + '盛强极兔' => [ + 'mode' => 'E', + 'coef' => null, + ], + '木际德邦' => [ + 'mode' => 'E', + 'coef' => null, + ], + '木际中通' => [ + 'mode' => 'E', + 'coef' => null, + ], + '靓阁快递' => [ + 'mode' => 'E', + 'coef' => null, + ], + '靓阁顺丰' => [ + 'mode' => 'E', + 'coef' => null, + ], + '靓阁德邦' => [ + 'mode' => 'E', + 'coef' => null, + ], + '靓阁安能' => [ + 'mode' => 'E', + 'coef' => null, + ], + '靓阁德邦其他' => [ + 'mode' => 'E', + 'coef' => null, + ], + '钦诺德邦' => [ + 'mode' => 'E', + 'coef' => null, + ], + '淼缘中通快运' => [ + 'mode' => 'MY', + 'coef' => null, + ], + '迈当极兔' => [ + 'mode' => 'MDJT', + 'coef' => 8000, + ], + '沐野竹木邮政' => [ + 'mode' => 'B3SEG', + 'coef' => null, + 'ceil' => true, + 'mode_by_ver' => [ + 'QB-186' => [ + 'mode' => 'E', + ], + 'QB-187' => [ + 'mode' => 'E', + ], + 'QB-188' => [ + 'mode' => 'E', + ], + 'QB-189' => [ + 'mode' => 'E', + ], + 'QB-190' => [ + 'mode' => 'E', + ], + 'QB-191' => [ + 'mode' => 'E', + ], + 'QB-202' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-203' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-204' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-205' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-206' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-207' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-208' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + ], + ], + '沐野竹木极兔' => [ + 'mode' => 'B3SEG', + 'coef' => null, + 'ceil' => true, + 'mode_by_ver' => [ + 'QB-186' => [ + 'mode' => 'E', + ], + 'QB-187' => [ + 'mode' => 'E', + ], + 'QB-188' => [ + 'mode' => 'E', + ], + 'QB-189' => [ + 'mode' => 'E', + ], + 'QB-190' => [ + 'mode' => 'E', + ], + 'QB-191' => [ + 'mode' => 'E', + ], + 'QB-202' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-203' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-204' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-205' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-206' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-207' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-208' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + ], + ], + '沐野竹木中通' => [ + 'mode' => 'B3SEG', + 'coef' => null, + 'ceil' => true, + 'mode_by_ver' => [ + 'QB-186' => [ + 'mode' => 'E', + ], + 'QB-187' => [ + 'mode' => 'E', + ], + 'QB-188' => [ + 'mode' => 'E', + ], + 'QB-189' => [ + 'mode' => 'E', + ], + 'QB-190' => [ + 'mode' => 'E', + ], + 'QB-191' => [ + 'mode' => 'E', + ], + 'QB-202' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-203' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-204' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-205' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-206' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-207' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-208' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + ], + ], + '沐野竹木韵达' => [ + 'mode' => 'B3SEG', + 'coef' => null, + 'ceil' => true, + 'mode_by_ver' => [ + 'QB-186' => [ + 'mode' => 'E', + ], + 'QB-187' => [ + 'mode' => 'E', + ], + 'QB-188' => [ + 'mode' => 'E', + ], + 'QB-189' => [ + 'mode' => 'E', + ], + 'QB-190' => [ + 'mode' => 'E', + ], + 'QB-191' => [ + 'mode' => 'E', + ], + 'QB-202' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-203' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-204' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-205' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-206' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-207' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-208' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + ], + ], + '沐野竹木申通' => [ + 'mode' => 'B3SEG', + 'coef' => null, + 'ceil' => true, + 'mode_by_ver' => [ + 'QB-186' => [ + 'mode' => 'E', + ], + 'QB-187' => [ + 'mode' => 'E', + ], + 'QB-188' => [ + 'mode' => 'E', + ], + 'QB-189' => [ + 'mode' => 'E', + ], + 'QB-190' => [ + 'mode' => 'E', + ], + 'QB-191' => [ + 'mode' => 'E', + ], + 'QB-202' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-203' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-204' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-205' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-206' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-207' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-208' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + ], + ], + '沐野竹木圆通' => [ + 'mode' => 'B3SEG', + 'coef' => null, + 'ceil' => true, + 'mode_by_ver' => [ + 'QB-186' => [ + 'mode' => 'E', + ], + 'QB-187' => [ + 'mode' => 'E', + ], + 'QB-188' => [ + 'mode' => 'E', + ], + 'QB-189' => [ + 'mode' => 'E', + ], + 'QB-190' => [ + 'mode' => 'E', + ], + 'QB-191' => [ + 'mode' => 'E', + ], + 'QB-202' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-203' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-204' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-205' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-206' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-207' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-208' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + ], + ], + '沐野竹木顺丰' => [ + 'mode' => 'MYSF', + 'coef' => null, + 'mode_by_ver' => [ + 'QB-201' => [ + 'mode' => 'E', + 'ceil' => true, + ], + 'QB-202' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-203' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-204' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-205' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-206' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-207' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + 'QB-208' => [ + 'mode' => 'FMD', + 'flat_max' => 3, + 'md_col' => 4, + 'rate_col' => 5, + 'ceil' => true, + ], + ], + ], + '浩浦韵达' => [ + 'mode' => 'BARCODE', + ], + '浩浦极兔' => [ + 'mode' => 'BARCODE', + ], + '霸州百世快运-雅柏' => [ + 'mode' => 'A', + 'coef' => 10000, + 'minw' => 10, + ], + '北京韵达' => [ + 'mode' => 'B6', + 'coef' => 10000, + 'coef_by_ver' => [ + 'QB-095' => 8000, + 'QB-199' => 8000, + 'QB-200' => 8000, + ], + 'perkg_add_md' => true, + ], + '宿迁中通快运' => [ + 'mode' => 'C', + 'first' => 15, + 'coef' => 8000, + 'main_fee' => 3.5, + 'sub_fee' => 0.8, + ], + '苏北顺丰干配大件' => [ + 'mode' => 'C', + 'first' => 20, + 'coef' => 5000, + ], + '苏北顺丰干配小件' => [ + 'mode' => 'C', + 'first' => 3, + 'coef' => 5000, + ], + '常州德邦' => [ + 'mode' => 'C', + 'first' => 3, + 'coef' => 6000, + 'overlen' => [160, 7], + 'sub_fee' => 3.5, + ], + '崔桥顺丰干配' => [ + 'mode' => 'C', + 'first' => 2, + 'coef' => 6000, + 'ceil05' => true, + ], + '睢宁德邦' => [ + 'mode' => 'C', + 'first' => 10, + 'coef' => 6000, + 'overlen' => [200, 10], + ], + '河北中通小件-江三' => [ + 'mode' => 'B6', + 'coef' => 10000, + ], + '山东顺丰干配' => [ + 'mode' => 'C', + 'first' => 5, + 'coef' => 11000, + ], + '山东顺丰大件' => [ + 'mode' => 'C', + 'first' => 20, + 'coef' => 5000, + ], + '廊坊德邦' => [ + 'mode' => 'C', + 'first' => 1, + 'coef' => 7000, + 'minw' => 10, + 'overlen' => [160, 10], + ], + '廊坊德邦临时' => [ + 'mode' => 'C', + 'first' => 1, + 'coef' => 7000, + 'minw' => 10, + 'overlen' => [160, 10], + ], + '曹县韵达小件' => [ + 'mode' => 'E', + 'coef' => 8000, + ], + '曹县韵达-唯品' => [ + 'mode' => 'C', + 'first' => 1, + 'coef' => 8000, + 'ceil' => true, + ], + '曹县韵达' => [ + 'mode' => 'CYD', + 'coef' => 8000, + ], + '曹县韵达-温县' => [ + 'mode' => 'CYD', + 'coef' => 8000, + ], + '河北中通-江三' => [ + 'mode' => 'A', + 'coef' => 10000, + ], + '常州安能新' => [ + 'mode' => 'A', + 'coef' => 10000, + 'coef_big' => [380000, 5000], + 'minw' => 13, + ], + '常州安能' => [ + 'mode' => 'A', + 'coef' => 10000, + 'coef_big' => [380000, 5000], + 'minw' => 13, + ], + '苏北极兔-滚轮' => [ + 'mode' => 'PERQTY', + 'coef' => null, + ], + '苏北极兔-滤网' => [ + 'mode' => 'PERQTY', + 'coef' => null, + ], + '苏北极兔-挂钩' => [ + 'mode' => 'PERQTY', + 'coef' => null, + ], + '百世快运' => [ + 'mode' => 'A', + 'coef' => 5000, + 'minw' => 13, + ], + '苏北宿迁圆通' => [ + 'mode' => 'YT2', + 'coef' => 6000, + ], + '睢宁宿迁圆通' => [ + 'mode' => 'YT2', + 'coef' => 6000, + ], + '常州中通快运' => [ + 'mode' => 'ZTKY', + 'coef' => 8000, + 'coef_big' => [300000, 5000], + 'minw' => 10, + ], + '曹县德邦' => [ + 'mode' => 'D', + 'coef' => 10000, + ], + '曹县德邦其他' => [ + 'mode' => 'D', + 'coef' => 10000, + ], + '曹县德邦超长' => [ + 'mode' => 'D', + 'coef' => 10000, + 'always_long' => true, + ], + '曹县德邦超长其他' => [ + 'mode' => 'D', + 'coef' => 10000, + 'always_long' => true, + ], + '曹县德邦小件' => [ + 'mode' => 'D3', + 'coef' => 12000, + ], + '曹县德邦小件其他' => [ + 'mode' => 'D3', + 'coef' => 12000, + ], + '顺安申通' => [ + 'mode' => 'B6C', + 'coef' => 8000, + 'flat_max' => 10, + ], + '飞燕申通' => [ + 'mode' => 'A', + 'coef' => 10000, + ], + '飞燕德邦' => [ + 'mode' => 'E', + 'coef' => null, + ], + '飞燕中通' => [ + 'mode' => 'E', + 'coef' => null, + ], + '仁凯申通' => [ + 'mode' => 'E', + 'coef' => null, + ], + '仁凯百世快运' => [ + 'mode' => 'E', + 'coef' => null, + ], + '茗悦邮政' => [ + 'mode' => 'E', + 'coef' => null, + ], + '雅梵邮政' => [ + 'mode' => 'E', + 'coef' => null, + ], + '祥和圆通' => [ + 'mode' => 'E', + 'coef' => null, + ], + '祥和极兔' => [ + 'mode' => 'E', + 'coef' => null, + ], + '祥和中通' => [ + 'mode' => 'E', + 'coef' => null, + ], + '祥和韵达' => [ + 'mode' => 'E', + 'coef' => null, + ], + '恒思极兔' => [ + 'mode' => 'E', + 'coef' => null, + ], + '恒思中通' => [ + 'mode' => 'E', + 'coef' => null, + ], + '恒思德邦' => [ + 'mode' => 'E', + 'coef' => null, + ], + '恒思德邦其他' => [ + 'mode' => 'E', + 'coef' => null, + ], + '森美邮政电商标快' => [ + 'mode' => 'E', + 'coef' => null, + ], + '森美邮政唯品' => [ + 'mode' => 'E', + 'coef' => null, + ], + '森美德邦' => [ + 'mode' => 'E', + 'coef' => null, + ], + '森美邮政' => [ + 'mode' => 'E', + 'coef' => null, + ], + '丽彪中通' => [ + 'mode' => 'E', + 'coef' => null, + ], + '丽彪圆通' => [ + 'mode' => 'E', + 'coef' => null, + ], + '沂海极兔' => [ + 'mode' => 'E', + 'coef' => null, + ], + '沂海韵达' => [ + 'mode' => 'E', + 'coef' => null, + ], + '沂海申通' => [ + 'mode' => 'E', + 'coef' => null, + ], + '源沃百世快运' => [ + 'mode' => 'E', + 'coef' => null, + ], + '尚然韵达' => [ + 'mode' => 'E', + 'coef' => null, + ], + '春霖德邦快递' => [ + 'mode' => 'E', + 'coef' => null, + 'remote_add' => [ + '新疆' => 46, + '西藏' => 46, + ], + ], + '缔格申通' => [ + 'mode' => 'B3R', + 'coef' => 8000, + ], + '缔格圆通' => [ + 'mode' => 'B3R', + 'coef' => 8000, + ], + '四强申通' => [ + 'mode' => 'A', + 'coef' => 10000, + 'ceil' => true, + ], + '森卓韵达大件' => [ + 'mode' => 'A', + 'coef' => 10000, + 'ceil' => true, + ], + '雅梵圆通' => [ + 'mode' => 'B6C', + 'coef' => 8000, + ], + '雅梵极兔' => [ + 'mode' => 'YFJT', + 'coef' => 8000, + ], + '洛宁顺丰干配' => [ + 'mode' => 'LNSF', + 'coef' => 3000, + ], + '洛宁德邦快递' => [ + 'mode' => 'LNDB', + 'coef' => null, + ], + '柏卡顺丰干配' => [ + 'mode' => 'C2', + 'coef' => 10000, + 'first' => 5, + 'fc' => 2, + 'rc' => 3, + ], + '飞燕武进申通' => [ + 'mode' => 'E', + 'coef' => null, + ], + '飞燕京东快递' => [ + 'mode' => 'E', + 'coef' => null, + ], + '景瓴十方顺丰小件-莒南' => [ + 'mode' => 'C', + 'first' => 3, + 'coef' => 6000, + 'coef_ddb' => 9000, + ], + '景瓴十方顺丰大件-莒南' => [ + 'mode' => 'C', + 'first' => 20, + 'coef' => 3000, + ], + '鑫木圆通' => [ + 'mode' => 'FMD', + 'coef' => 10000, + 'ceil' => true, + 'flat_max' => 5, + 'md' => 5.0, + 'rate_col' => 6, + ], + '武进韵达' => [ + 'mode' => 'FMD', + 'coef' => 8000, + 'flat_max' => 3, + 'md' => 3.5, + 'rate_col' => 2, + ], + '四强圆通' => [ + 'mode' => 'A', + 'coef' => 10000, + ], + '木际邮政' => [ + 'mode' => 'E', + 'coef' => null, + ], + '千优快递' => [ + 'mode' => 'QY', + 'coef' => null, + ], + '金禾盛中通快运' => [ + 'mode' => 'A', + 'coef' => 10000, + 'ceil' => true, + ], + '丽彪申通' => [ + 'mode' => 'E', + 'coef' => 8000, + 'ceil' => true, + ], + '丽彪申通小件' => [ + 'mode' => 'E', + 'coef' => 8000, + 'ceil' => true, + ], + '丽彪韵达' => [ + 'mode' => 'E', + 'coef' => 8000, + 'ceil' => true, + ], + '森卓韵达小件' => [ + 'mode' => 'E', + 'coef' => 10000, + 'ceil' => true, + ], + '顾顾德邦' => [ + 'mode' => 'C', + 'first' => 4, + 'coef' => 9000, + 'ceil' => true, + 'overlen' => [159.99, 2], + ], + ]; + } + + /** @return array|null */ + public static function for(string $carrier): ?array + { + return self::all()[$carrier] ?? null; + } + + public static function isFreeWarehouse(?string $warehouse): bool + { + $w = trim((string) $warehouse); + + return in_array($w, self::FREE_WAREHOUSES, true) || str_contains($w, '配件'); + } +} diff --git a/modules/EcommerceFinance/Services/Freight/QuoteSheet.php b/modules/EcommerceFinance/Services/Freight/QuoteSheet.php new file mode 100644 index 00000000..f887bc04 --- /dev/null +++ b/modules/EcommerceFinance/Services/Freight/QuoteSheet.php @@ -0,0 +1,292 @@ +> $vals + * @return array{head:list,rows:array>,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 $cols + * @return list + */ + 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>,1:array,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; + } +} diff --git a/modules/EcommerceFinance/Services/Freight/ShippingFreightCalculator.php b/modules/EcommerceFinance/Services/Freight/ShippingFreightCalculator.php new file mode 100644 index 00000000..ab62ea30 --- /dev/null +++ b/modules/EcommerceFinance/Services/Freight/ShippingFreightCalculator.php @@ -0,0 +1,1014 @@ + $pkg 包裹:express_name1, receiver_state, receiver_city, online_weight, actual_weight, + * weight_kg, length_cm, width_cm, height_cm, volume_cm3, warehouse_name, pkg_count, barcodes + * @param array{id:string,p:?array,rules:string,vals:array}|null $quote 发货日生效的报价版本 + * @param array|null $cfg 该快递的计费方式(FreightCarrierRules),含 _name=报价名称 + * @return array + */ + public function calculate(array $pkg, ?array $quote, ?array $cfg): array + { + $d = ['fee' => null, 'status' => '', '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' => '', 'mode' => '', 'region' => null]; + $bad = static function (string $msg) use (&$d): array { + $d['status'] = $msg; + + return $d; + }; + if ($cfg === null) { + return $bad('计费方式未配置'); + } + if ($quote === null || $quote['p'] === null) { + return $bad('发货日没有生效的报价'); + } + $name = (string) ($cfg['_name'] ?? ''); + $d['ver'] = $quote['id']; + $d['mode'] = $cfg['mode']; + if (isset($cfg['coef_by_ver'][$quote['id']])) { + $cfg['coef'] = $cfg['coef_by_ver'][$quote['id']]; + } + if (isset($cfg['mode_by_ver'][$quote['id']])) { + $cfg = array_merge($cfg, $cfg['mode_by_ver'][$quote['id']]); + $d['mode'] = $cfg['mode']; + } + $barcodes = array_values(array_filter(array_map(static fn ($b) => mb_strtoupper(trim($b)), explode(',', (string) ($pkg['barcodes'] ?? ''))), static fn ($b) => $b !== '')); + if (! empty($cfg['coef_ddb']) && array_filter($barcodes, static fn ($b) => str_starts_with($b, 'DDB')) !== []) { + $cfg['coef'] = $cfg['coef_ddb']; + } + $prov = QuoteSheet::province($pkg['receiver_state'] ?? ''); + $city = (string) ($pkg['receiver_city'] ?? ''); + + if ($cfg['mode'] === 'BARCODE') { + return $this->barcode($d, $quote, $prov, $barcodes, $bad); + } + + $p = $quote['p']; + $head = $p['head']; + $ck = null; + foreach (QuoteSheet::CITY_KEYS as $k) { + if ($city !== '' && str_contains($city, $k) && array_key_exists($k, $p['rows'])) { + $ck = $k; + break; + } + } + $row = $ck !== null ? $p['rows'][$ck] : ($p['rows'][$prov] ?? null); + $d['region'] = $ck ?? $prov; + + $on = self::pos($pkg['online_weight'] ?? null); + $act = self::pos($pkg['actual_weight'] ?? null); + $wt = self::pos($pkg['weight_kg'] ?? null); + [$base, $src] = $act ? [$act, '实称重量'] : ($on ? [$on, '线上重量'] : [$wt, '重量']); + $d['base_w'] = $base; + $d['base_src'] = $src; + $L = self::pos($pkg['length_cm'] ?? null); + $W = self::pos($pkg['width_cm'] ?? null); + $H = self::pos($pkg['height_cm'] ?? null); + $vol = ($L && $W && $H) ? $L * $W * $H : self::pos($pkg['volume_cm3'] ?? null); + $coef = $cfg['coef'] ?? null; + if (! empty($cfg['coef_big']) && $vol && $vol > $cfg['coef_big'][0]) { + $coef = $cfg['coef_big'][1]; + } + $d['coef'] = $coef; + $d['free'] = FreightCarrierRules::isFreeWarehouse($pkg['warehouse_name'] ?? ''); + if ($d['free'] || ! $coef) { + $settle = $base; + } else { + $d['vol_w'] = $vol ? round($vol / $coef, 4) : 0.0; + $settle = max($base, $d['vol_w']); + } + $d['settle_w'] = round($settle, 4); + if ($row === null) { + return $bad("报价无此省份({$prov})"); + } + $w = $settle; + $minw = null; + if (! empty($cfg['minw']) && $w < $cfg['minw']) { + $w = (float) $cfg['minw']; + $minw = $cfg['minw']; + } + if (! empty($cfg['ceil05'])) { + $w = ceil(round($w * 2, 6)) / 2; + } + if (! empty($cfg['ceil'])) { + $w = ceil(round($w, 6)); + } + if (! empty($cfg['roundw'])) { + $w = self::rhalf($w); + } + $g = static fn (?int $i) => ($i !== null && $i < count($row)) ? $row[$i] : null; + $need = static function (...$vals): bool { + foreach ($vals as $v) { + if (! is_float($v)) { + return false; + } + } + + return true; + }; + $f = static fn ($x): string => self::fmt($x); + $lin = static function (float $a, float $b, float $ww) use (&$d, $f): array { + $d['miandan'] = $a; + $d['rate'] = $b; + + return [$a + $b * $ww, "面单{$f($a)}+费率{$f($b)}×{$f($ww)}kg"]; + }; + $col = static fn (array $pats, array $ex = []) => QuoteSheet::col($head, $pats, 1, $ex); + $m = $cfg['mode']; + $fee = null; + $F = ''; + $n = $d['free'] ? 1 : self::pieces($pkg); + + // 整省「X元/公斤」报价(如北京韵达 海南/新疆) + if (preg_match('/^\s*([\d.]+)\s*元\s*\/\s*(kg|公斤)\s*$/iu', QuoteSheet::text($g(1)), $pk0)) { + $any = false; + for ($i = 2, $c = count($row); $i < $c; $i++) { + if (is_float($row[$i])) { + $any = true; + break; + } + } + if (! $any) { + $m = '_PERKG'; + $v = (float) $pk0[1]; + $fee = $v * $w; + $d['rate'] = $v; + $F = "该省按{$f($v)}元/公斤×{$f($w)}kg"; + if (! empty($cfg['perkg_add_md'])) { + $mds = []; + $mi = $col(['面单']); + if ($mi !== null) { + foreach ($p['rows'] as $r_) { + if ($mi < count($r_) && is_float($r_[$mi])) { + $key = self::fmt($r_[$mi]); + $mds[$key] = ($mds[$key] ?? 0) + 1; + } + } + } + if (preg_match('/面单费?\s*([\d.]+)\s*元/u', (string) $quote['rules'], $mr)) { + $mds = [self::fmt((float) $mr[1]) => 1]; + } + if ($mds !== []) { + $best = null; + foreach ($mds as $k => $cnt) { // 出现次数最多的面单(同数取先出现的) + if ($best === null || $cnt > $mds[$best]) { + $best = $k; + } + } + $md0 = (float) $best; + $fee += $md0; + $d['miandan'] = $md0; + $F = "面单{$f($md0)}+" . $F; + } + } + } + } + + switch ($m) { + case '_PERKG': + break; + case 'A': + $a = $g($col(['面单'])); + $b = $g($col(['费率']) ?? $col(['\d+\s*-\s*\d+\s*kg'], ['面单'])); + if (preg_match('/([\d.]+)\s*元\s*\/\s*(kg|公斤)/iu', QuoteSheet::text($a), $pk) && ! $need($a, $b)) { + $v = (float) $pk[1]; + $fee = $v * $w; + $d['rate'] = $v; + $F = "{$f($v)}元/kg×{$f($w)}kg"; + } else { + if (! $need($a, $b)) { + return $bad('报价单元格无数值(' . self::show($a) . ',' . self::show($b) . ')'); + } + [$fee, $F] = $lin($a, $b, $w); + } + break; + case 'A10': + $a = $g($col(['面单'])); + $b = $g($col(['≤10'])); + $c = $g($col(['>10'])); + if (! $need($a, $b, $c)) { + return $bad('报价单元格无数值'); + } + if ($w <= 10) { + [$fee, $F] = $lin($a, $b, $w); + } else { + $d['miandan'] = $a; + $d['rate'] = $f($b) . '/' . $f($c); + $fee = $a + 10 * $b + ($w - 10) * $c; + $F = "面单{$f($a)}+10kg×{$f($b)}+({$f($w)}-10)kg×{$f($c)}"; + } + break; + case 'ASEG': + $mi = $col(['面单']); + $a = $g($mi); + if (! is_float($a)) { + foreach (array_slice($row, 1) as $c) { + if (is_string($c) && preg_match('/^([\d.]+)\+G\*([\d.]+)/u', str_replace(' ', '', $c), $mm)) { + [$fee, $F] = $lin((float) $mm[1], (float) $mm[2], $w); + break; + } + } + if ($fee === null) { + return $bad('报价单元格无数值'); + } + } else { + $bands = []; + for ($i = 1, $c = count($head); $i < $c; $i++) { + if ($i === $mi || ! preg_match('/kg|KG|公斤/u', $head[$i])) { + continue; + } + $t = str_replace(' ', '', $head[$i]); + if (preg_match('/([\d.]+)\s*(?:kg|KG|公斤)?\s*[-~]\s*([\d.]+)/u', $t, $mm)) { + $bands[] = [(float) $mm[1], (float) $mm[2], $i]; + } elseif (preg_match('/([\d.]+)\s*(?:kg|KG|公斤)\s*以上/u', $t, $mm)) { + $bands[] = [(float) $mm[1], 1e9, $i]; + } elseif (preg_match('/超([\d.]+)/u', $t, $mm)) { + $bands[] = [(float) $mm[1], 1e9, $i]; + } + } + $rate = null; + foreach ($bands as [$lo, $hi, $i]) { + if ($w <= $hi + 1e-9) { + $rate = $g($i); + break; + } + } + if ($rate === null && $bands !== []) { + $rate = $g(end($bands)[2]); + } + if (! $need($a, $rate)) { + return $bad('报价单元格无数值(' . self::show($a) . ',' . self::show($rate) . ')'); + } + [$fee, $F] = $lin($a, $rate, $w); + } + break; + case 'B3SEG': + $segs = array_values(array_filter(QuoteSheet::bands($head, range(1, max(1, count($head) - 1))), static fn ($s) => $s[1] <= 3.0001)); + $mi = $col(['面单']); + $rcols = []; + foreach ($head as $i => $h) { + if (str_contains($h, '费率') || str_contains($h, '元/kg')) { + $rcols[] = $i; + } + } + if ($w <= 3) { + [$v, $seg] = self::band($segs, $w, $g, $head); + if (! $need($v)) { + return $bad('一口价无数值(' . self::show($v) . ')'); + } + $fee = $v; + $d['flat'] = $v; + $F = "{$f($w)}kg落在{$seg}段,一口价{$f($v)}"; + } else { + $a = $g($mi); + $rate = $rcols ? $g($rcols[0]) : null; + if (count($rcols) > 1 && preg_match('/([\d.]+)\s*[-~]\s*([\d.]+)/u', $head[$rcols[0]], $mm) && $w > (float) $mm[2]) { + $rate = $g($rcols[1]); + } + if (! $need($a, $rate)) { + return $bad('报价单元格无数值(' . self::show($a) . ',' . self::show($rate) . ')'); + } + [$fee, $F] = $lin($a, $rate, $w); + } + break; + case 'B3': + if ($name === '小件宿迁圆通') { + $a = null; + if (preg_match('/面单\s*([\d.]+)/u', $p['top'] . ' ' . implode(' ', $head), $mm) || preg_match('/面单\s*([\d.]+)/u', (string) $quote['rules'], $mm)) { + $a = (float) $mm[1]; + } + if ($w <= 3) { + $v = $g($col(['0-3'])); + if (! $need($v)) { + return $bad('报价单元格无数值'); + } + $fee = $v; + $d['flat'] = $v; + $F = "{$f($w)}kg≤3kg,一口价{$f($v)}"; + } else { + $rate = $w <= 50 ? $g($col(['3.01-50'])) : $g($col(['50公斤以上'])); + if (! $need($a, $rate)) { + return $bad('报价单元格无数值'); + } + [$fee, $F] = $lin($a, $rate, $w); + } + } elseif ($w <= 3) { + $v = $g($col(['一口价'])); + if (! $need($v)) { + return $bad('报价单元格无数值'); + } + $fee = $v; + $d['flat'] = $v; + $F = "{$f($w)}kg≤3kg,一口价{$f($v)}"; + } else { + $a = $g($col(['面单'])); + $b = $g($col(['费率'])); + if (! $need($a, $b)) { + return $bad('报价单元格无数值'); + } + [$fee, $F] = $lin($a, $b, $w); + } + break; + case 'C': + $a = $g($col(['首重'])); + $b = $g($col(['费率', '续重'], ['首重'])); + if (! $need($a, $b)) { + return $bad('报价单元格无数值(' . self::show($a) . ',' . self::show($b) . ')'); + } + $fk = (float) $cfg['first']; + if ($name === '宿迁中通快运') { + $fkc = $g(1); + $a = $g(2); + $b = $g(3); + if (is_float($fkc)) { + $fk = $fkc; + } + if (! $need($a, $b)) { + return $bad('报价单元格无数值'); + } + } + $d['first_kg'] = $fk; + $d['first_price'] = $a; + $d['rate'] = $b; + if ($w <= $fk) { + $fee = $a; + $F = "{$f($w)}kg≤首重{$f($fk)}kg,首重价{$f($a)}"; + } else { + $fee = $a + ($w - $fk) * $b; + $F = "首重{$f($a)}+({$f($w)}-{$f($fk)})kg×续重{$f($b)}"; + } + if (! empty($cfg['main_fee'])) { + $fee += $cfg['main_fee']; + $d['miandan'] = (float) $cfg['main_fee']; + $F .= "+主面单{$f($cfg['main_fee'])}"; + } + if (! empty($cfg['sub_fee']) && $n > 1) { + $fee += $cfg['sub_fee'] * ($n - 1); + $d['extra'] += $cfg['sub_fee'] * ($n - 1); + $F .= "+子面单{$f($cfg['sub_fee'])}×({$n}-1)"; + } + break; + case 'SX': + $a = $g(1); + $b = $g(4); + if (! $need($a, $b)) { + return $bad('报价单元格无数值'); + } + [$d['first_kg'], $d['first_price'], $d['rate']] = [10.0, $a, $b]; + if ($w <= 10) { + $fee = $a; + $F = "{$f($w)}kg≤10kg,首重最低收费{$f($a)}"; + } else { + $fee = $a + ($w - 10) * $b; + $F = "首重最低收费{$f($a)}+({$f($w)}-10)kg×{$f($b)}"; + } + break; + case 'D': + $dc = $cfg['dcols'] ?? [1, 2]; + $wr = self::rhalf($w); + $a = $g($dc[0]); + $b = $g($dc[1]); + if (! $need($a, $b)) { + return $bad('报价单元格无数值'); + } + [$d['first_kg'], $d['first_price'], $d['rate']] = [5.0, $a, $b]; + if ($wr <= 5) { + $fee = $a + 1; + $F = "重量四舍五入{$f($wr)}kg≤5kg,首重{$f($a)}+1"; + } else { + $fee = ($wr - 5) * $b + $a + 1; + $F = "({$f($wr)}-5)kg×续重{$f($b)}+首重{$f($a)}+1"; + } + if (empty($cfg['no_long']) && (max($L, $W, $H) > 160 || ! empty($cfg['always_long']))) { + $fee += 8; + $d['extra'] += 8; + $F .= ! empty($cfg['always_long']) ? '+超长8' : '+单边超160cm 8'; + } + $w = $wr; + break; + case 'F': + $a = $g(1); + if (! $need($a) || ! ($L && $W && $H)) { + return $bad('报价或尺寸无数值'); + } + $d['rate'] = $a; + $fee = $a * $L * $W * $H / 1e6; + $F = "费率{$f($a)}×{$f($L)}×{$f($W)}×{$f($H)}/1000000"; + break; + case 'E': + $cols = []; + for ($i = 1, $c = count($head); $i < $c; $i++) { + if (! preg_match('/备注/u', $head[$i])) { + $cols[] = $i; + } + } + $bands = QuoteSheet::bands($head, $cols); + if ($bands === []) { + return $bad('一口价表头无法识别'); + } + [$v, $seg] = self::band($bands, $w, $g, $head); + $inRange = false; + foreach ($bands as $bd) { + if ($w <= $bd[1] + 1e-9) { + $inRange = true; + break; + } + } + if ($v === null && ! $inRange) { + return $bad('超出报价公斤段(' . number_format($w, 2, '.', '') . 'kg)'); + } + if (! $need($v)) { + return $bad('该段不发/无价(' . self::show($v) . ')'); + } + $fee = $v; + $d['flat'] = $v; + $F = "{$f($w)}kg落在" . ($seg !== '' ? $seg : '一口价') . "段,一口价{$f($v)}"; + break; + case 'YFJT': + $bands = array_values(array_filter(QuoteSheet::bands($head, [1, 2, 3]), static fn ($s) => $s[1] <= 3.0001)); + if ($w <= 3) { + [$v, $seg] = self::band($bands, $w, $g, $head); + if (! $need($v)) { + return $bad('一口价无数值(' . self::show($v) . ')'); + } + $fee = $v; + $d['flat'] = $v; + $F = "{$f($w)}kg落在{$seg}段,一口价{$f($v)}"; + } else { + $t = QuoteSheet::text($g(4)); + if (! preg_match('/^\s*([\d.]+)\s*\+\s*([\d.]+)/u', $t, $mm)) { + return $bad("报价单元格无数值({$t})"); + } + $a = (float) $mm[1]; + $b = (float) $mm[2]; + [$d['first_kg'], $d['first_price'], $d['rate']] = [3.0, $a, $b]; + $fee = $a + ($w - 3) * $b; + $F = "{$f($a)}+({$f($w)}-3)kg×{$f($b)}"; + } + break; + case 'FMD': + $fm = (float) $cfg['flat_max']; + $rc = (int) $cfg['rate_col']; + $md = isset($cfg['md_col']) ? $g((int) $cfg['md_col']) : (float) $cfg['md']; + if (preg_match('/^\s*([\d.]+)\s*元\/kg/iu', QuoteSheet::text($g(1)), $pk) && ! $need($g(2))) { + $x = (float) $pk[1]; + $fee = $x * $w; + $d['rate'] = $x; + $F = "整省按{$f($x)}元/kg×{$f($w)}kg"; + } + $bands = array_values(array_filter(QuoteSheet::bands($head, $rc > 1 ? range(1, $rc - 1) : []), static fn ($s) => $s[1] <= $fm + 0.0001)); + if ($fee !== null) { + break; + } + if ($w <= $fm) { + [$v, $seg] = self::band($bands, $w, $g, $head); + if (! $need($v)) { + return $bad('一口价无数值(' . self::show($v) . ')'); + } + $fee = $v; + $d['flat'] = $v; + $F = "{$f($w)}kg落在{$seg}段,一口价{$f($v)}"; + } else { + $b = $g($rc); + if (! $need($b, $md)) { + return $bad('报价单元格无数值(' . self::show($md) . ',' . self::show($b) . ')'); + } + [$fee, $F] = $lin($md, $b, $w); + } + break; + case 'C2': + $fk = (float) $cfg['first']; + $a = $g((int) $cfg['fc']); + $b = $g((int) $cfg['rc']); + if (! $need($a, $b)) { + return $bad('报价单元格无数值(' . self::show($a) . ',' . self::show($b) . ')'); + } + [$d['first_kg'], $d['first_price'], $d['rate']] = [$fk, $a, $b]; + if ($w <= $fk) { + $fee = $a; + $F = "{$f($w)}kg≤首重{$f($fk)}kg,首重价{$f($a)}"; + } else { + $fee = $a + ($w - $fk) * $b; + $F = "首重{$f($a)}+({$f($w)}-{$f($fk)})kg×续重{$f($b)}"; + } + break; + case 'LNSF': + $r = $this->luoningSf($d, $quote, $prov, $city, $w); + if (isset($r['error'])) { + return $bad($r['error']); + } + [$fee, $F] = [$r['fee'], $r['F']]; + break; + case 'LNDB': + $r = $this->luoningDb($d, $row, $vol, $w); + if (isset($r['error'])) { + return $bad($r['error']); + } + [$fee, $F, $w] = [$r['fee'], $r['F'], $r['w']]; + break; + case 'MY': + if ($w <= 1) { + [$v, $seg] = [$g(2), '0-1kg']; + } elseif ($w <= 3) { + [$v, $seg] = [$g(3), '1.01-3kg']; + } elseif ($w <= 5) { + [$v, $seg] = [$g(4), '3.01-5kg']; + } elseif ($w <= 10) { + [$v, $seg] = [[$g(5), $g(6)], '']; + } else { + [$v, $seg] = [[$g(7), $g(8)], '']; + } + if (is_array($v)) { + if (! $need(...$v)) { + return $bad('报价单元格无数值'); + } + [$fee, $F] = $lin($v[0], $v[1], $w); + } else { + if (! $need($v)) { + return $bad('无价(' . self::show($v) . ')'); + } + $fee = $v; + $d['flat'] = $v; + $F = "{$f($w)}kg落在{$seg}段,一口价{$f($v)}"; + } + break; + case 'MDJT': + $wc = ceil(round($w, 6)); + if ($w <= 3) { + $v = $g(1); + if (! $need($v)) { + return $bad('报价单元格无数值'); + } + $fee = $v; + $d['flat'] = $v; + $F = "{$f($w)}kg≤3kg,一口价{$f($v)}"; + } else { + $a = $g(2); + $b = $wc <= 10 ? $g(3) : $g(4); + if (! $need($a, $b)) { + return $bad('报价单元格无数值'); + } + [$fee, $F] = $lin($a, $b, $wc); + $F .= '(重量向上取整)'; + } + $w = $wc; + break; + case 'MYSF': + [$a3, $r35, $a5, $r520] = [$g(2), $g(3), $g(4), $g(5)]; + if (! $need($a3, $r35, $a5, $r520)) { + return $bad('报价单元格无数值'); + } + if ($w <= 3) { + [$d['first_kg'], $d['first_price']] = [3.0, $a3]; + $fee = $a3; + $F = "{$f($w)}kg≤3kg,首重{$f($a3)}"; + } elseif ($w <= 5) { + [$d['first_kg'], $d['first_price'], $d['rate']] = [3.0, $a3, $r35]; + $fee = $a3 + ($w - 3) * $r35; + $F = "首重{$f($a3)}+({$f($w)}-3)kg×{$f($r35)}"; + } else { + [$d['first_kg'], $d['first_price'], $d['rate']] = [5.0, $a5, $r520]; + $fee = $a5 + ($w - 5) * $r520; + $F = "5kg首重{$f($a5)}+({$f($w)}-5)kg×{$f($r520)}"; + } + break; + case 'B6': + $segs = array_values(array_filter(QuoteSheet::bands($head, range(1, max(1, count($head) - 1))), static fn ($s) => $s[1] <= 6.0001)); + $mi = $col(['面单']); + $ri = $col(['费率', '元\/公斤', '6\.01-50'], ['面单']); + if ($ri === null) { + foreach ($head as $i => $h) { + if ($i !== $mi && preg_match('/6(\.01)?\s*公斤以上|6公斤以上/u', $h) && ! str_contains($h, '面单')) { + $ri = $i; + break; + } + } + } + $a = $g($mi); + $b = $g($ri); + $v = null; + $seg = ''; + if ($w <= 6) { + [$v, $seg] = self::band($segs, $w, $g, $head); + } + if ($w <= 6 && $need($v)) { + $fee = $v; + $d['flat'] = $v; + $F = "{$f($w)}kg落在{$seg}段,一口价{$f($v)}"; + } else { + if (! $need($a, $b)) { + return $bad('报价单元格无数值(' . self::show($a) . ',' . self::show($b) . ')'); + } + [$fee, $F] = $lin($a, $b, $w); + } + break; + case 'CYD': + if ($w <= 3) { + $v = $w <= 2 ? $g(1) : $g(2); + if (! $need($v)) { + return $bad('报价单元格无数值'); + } + $fee = $v; + $d['flat'] = $v; + $F = "{$f($w)}kg≤3kg,一口价{$f($v)}"; + } else { + $a = $g(3); + $b = $g(4); + if (! $need($a, $b)) { + return $bad('报价单元格无数值'); + } + [$d['first_kg'], $d['first_price'], $d['rate']] = [1.0, $a, $b]; + $fee = $a + ($w - 1) * $b; + $F = "首重{$f($a)}+({$f($w)}-1)kg×{$f($b)}"; + } + break; + case 'D3': + $wr = self::rhalf($w); + $a = $g(1); + $b = $g(2); + if (! $need($a, $b)) { + return $bad('报价单元格无数值(' . self::show($a) . ',' . self::show($b) . ')'); + } + [$d['first_kg'], $d['first_price'], $d['rate']] = [3.0, $a, $b]; + if ($wr <= 3) { + $fee = $a; + $F = "重量四舍五入{$f($wr)}kg≤3kg,首重{$f($a)}"; + } else { + $fee = ($wr - 3) * $b + $a; + $F = "({$f($wr)}-3)kg×续重{$f($b)}+首重{$f($a)}"; + } + if (max($L, $W, $H) > 160) { + $fee += 8; + $d['extra'] += 8; + $F .= '+单边超160cm 8'; + } + $w = $wr; + break; + case 'PERQTY': + $v = $g(1); + if (! $need($v)) { + return $bad('无价(' . self::show($v) . ')'); + } + $d['flat'] = $v; + $fee = $v; + $F = "一口价{$f($v)}/单(按包裹计,不乘件数)"; + break; + case 'YT2': + if ($w <= 3) { + $a = $g($col(['0-3公斤面单'])); + $b = $g($col(['0-3公斤费率'])); + } else { + $a = $g($col(['3公斤以上面单'])); + $b = $w <= 35 ? $g($col(['3-35'])) : ($w <= 50 ? $g($col(['35-50'])) : $g($col(['50公斤以上']))); + } + if (! $need($a, $b)) { + return $bad('报价单元格无数值'); + } + [$fee, $F] = $lin($a, $b, $w); + break; + case 'ZTKY': + $b = $g($col(['费率'])); + $a = $g($col(['面单'])); + if (! $need($a, $b)) { + return $bad('报价单元格无数值'); + } + $d['miandan'] = $a; + $d['rate'] = $b; + $fee = $a * $n + $b * $w; + $d['extra'] += $a * ($n - 1); + $F = "面单{$f($a)}×{$n}件+费率{$f($b)}×{$f($w)}kg"; + break; + case 'B3R': + $oi = $col(['0-3']); + $mi = $col(['面单']); + $rb = []; + for ($i = 1, $c = count($head); $i < $c; $i++) { + if (in_array($i, [$oi, $mi], true) || (! str_contains($head[$i], '费率') && ! preg_match('/kg|KG/u', $head[$i]))) { + continue; + } + $t = str_replace(' ', '', $head[$i]); + if (preg_match('/([\d.]+)\s*[-~]\s*([\d.]+)/u', $t, $mm) && (float) $mm[1] >= 3) { + $rb[] = [(float) $mm[2], $i]; + continue; + } + if (preg_match('/([\d.]+)\s*(KG|kg)以上/u', $t)) { + $rb[] = [1e9, $i]; + } + } + if ($w <= 3) { + $v = $g($oi); + if (! $need($v)) { + return $bad('一口价无数值(' . self::show($v) . ')'); + } + $fee = $v; + $d['flat'] = $v; + $F = "{$f($w)}kg≤3kg,一口价{$f($v)}"; + } else { + $a = $g($mi); + $b = null; + usort($rb, static fn ($x, $y) => $x <=> $y); + foreach ($rb as [$hi, $i]) { + if ($w <= $hi + 1e-9) { + $b = $g($i); + break; + } + } + if (! $need($a, $b)) { + return $bad('报价单元格无数值(' . self::show($a) . ',' . self::show($b) . ')'); + } + [$fee, $F] = $lin($a, $b, $w); + } + break; + case 'B6C': + $fm = (float) ($cfg['flat_max'] ?? 6); + $segs = array_values(array_filter(QuoteSheet::bands($head, range(1, max(1, count($head) - 1))), static fn ($s) => $s[1] <= $fm + 0.0001)); + if ($w <= $fm) { + [$v, $seg] = self::band($segs, $w, $g, $head); + if (! $need($v)) { + return $bad('一口价无数值(' . self::show($v) . ')'); + } + $fee = $v; + $d['flat'] = $v; + $F = "{$f($w)}kg落在{$seg}段,一口价{$f($v)}"; + } else { + $a = $g($col(['首重'])); + $b = $g($col(['续重'])); + if (! $need($a, $b)) { + return $bad('报价单元格无数值(' . self::show($a) . ',' . self::show($b) . ')'); + } + [$d['first_kg'], $d['first_price'], $d['rate']] = [1.0, $a, $b]; + $fee = $a + ($w - 1) * $b; + $F = "首重{$f($a)}+({$f($w)}-1)kg×续重{$f($b)}"; + } + break; + case 'QY': + [$a5, $a10, $b] = [$g(1), $g(2), $g(3)]; + if ($w <= 5) { + if (! $need($a5)) { + return $bad('无价(' . self::show($a5) . ')'); + } + $fee = $a5; + $d['flat'] = $a5; + $F = "{$f($w)}kg≤5kg,一口价{$f($a5)}"; + } elseif ($w <= 10) { + if (! $need($a10)) { + return $bad('无价(' . self::show($a10) . ')'); + } + $fee = $a10; + $d['flat'] = $a10; + $F = "{$f($w)}kg在5-10kg,一口价{$f($a10)}"; + } else { + if (! $need($a10, $b)) { + return $bad('报价单元格无数值'); + } + [$d['first_kg'], $d['first_price'], $d['rate']] = [10.0, $a10, $b]; + $fee = $a10 + ($w - 10) * $b; + $F = "首重{$f($a10)}+({$f($w)}-10)kg×{$f($b)}"; + } + break; + default: + return $bad('计费方式未配置'); + } + + if (! empty($cfg['overlen']) && max($L, $W, $H) > $cfg['overlen'][0]) { + $fee += $cfg['overlen'][1]; + $d['extra'] += $cfg['overlen'][1]; + $F .= '+超长(' . $f(max($L, $W, $H)) . 'cm>' . $f($cfg['overlen'][0]) . ')' . $f($cfg['overlen'][1]); + } + if ($minw !== null) { + $F .= "(不足{$minw}kg按{$minw}kg)"; + } + if (! empty($cfg['ceil05'])) { + $F .= '(重量向上取0.5)'; + } + $ra = $cfg['remote_add'][$d['region']] ?? null; + if ($ra) { + $fee += $ra; + $d['extra'] += $ra; + $F .= "+偏远加收{$f($ra)}"; + } + if (! empty($cfg['add'])) { + $fee += $cfg['add']; + $d['extra'] += $cfg['add']; + $F .= "+超长{$f($cfg['add'])}"; + } + if (! empty($cfg['ceil']) && $m !== 'MDJT') { + $F .= '(重量向上取整)'; + } + if (! empty($cfg['roundw'])) { + $F .= '(重量四舍五入)'; + } + $d['charge_w'] = round($w, 4); + $d['fee'] = round($fee, 2); + $d['status'] = 'OK'; + $d['formula'] = $F . ' = ' . number_format($d['fee'], 2, '.', ''); + + return $d; + } + + private function barcode(array $d, array $quote, string $prov, array $bcs, callable $bad): array + { + [$table, $nogo] = QuoteSheet::barcodeTable($quote['vals']); + $d['region'] = $prov; + if ($bcs === []) { + return $bad('发货数据无商品条码'); + } + $hit = array_values(array_filter($bcs, static fn ($b) => isset($table[$b]))); + if ($hit === []) { + return $bad('报价无此条码(' . mb_substr(implode(',', $bcs), 0, 60) . ')'); + } + $uniq = array_values(array_unique($hit)); + if (count($uniq) > 1) { + sort($uniq); + + return $bad('包裹含多个报价条码(' . implode(',', $uniq) . '),待确认'); + } + if (isset($nogo[$prov])) { + return $bad("{$prov}不发货"); + } + $price = null; + foreach ($table[$hit[0]] as [$ps, $v]) { + if ($ps !== null && isset($ps[$prov])) { + $price = $v; + break; + } + } + if ($price === null) { + foreach ($table[$hit[0]] as [$ps, $v]) { + if ($ps === null) { + $price = $v; + break; + } + } + } + if (! is_float($price)) { + $d['status'] = "该条码在{$prov}无价(" . self::show($price) . ')'; + + return $d; + } + $d['flat'] = $price; + $d['fee'] = round($price, 2); + $d['status'] = 'OK'; + $d['formula'] = "条码{$hit[0]}发{$prov},一口价" . self::fmt($price) . ' = ' . number_format($d['fee'], 2, '.', ''); + $extra = array_values(array_filter($bcs, static fn ($b) => ! isset($table[$b]))); + if ($extra !== []) { + $d['formula'] .= '(忽略非报价条码' . implode(',', $extra) . ')'; + } + + return $d; + } + + /** 洛宁顺丰干配:普通省份干配首重20kg;特殊省份(陆运/卡航)按 1/3/20/60kg 分段。 */ + private function luoningSf(array &$d, array $quote, string $prov, string $city, float $w): array + { + $cand = []; + foreach (array_slice($quote['vals'], 2) as $r_) { + if (is_array($r_) && ($r_[0] ?? null) && QuoteSheet::province($r_[0]) === $prov) { + $cand[] = $r_; + } + } + if ($cand === []) { + return ['error' => "报价无此省份({$prov})"]; + } + $cshort = mb_substr((string) preg_replace('/(市|地区|自治州|州|盟)$/u', '', $city), 0, 2); + $rr = $cand[0]; + if ($cshort !== '') { + foreach ($cand as $r_) { + if (str_contains(QuoteSheet::text($r_[1] ?? null), $cshort) || str_contains(QuoteSheet::text($r_[2] ?? null), $cshort)) { + $rr = $r_; + break; + } + } + } + $rr = array_map([QuoteSheet::class, 'num'], $rr); + $gg = static fn (int $i) => $rr[$i] ?? null; + $f = static fn ($x): string => self::fmt($x); + $is = static fn (...$v): bool => array_filter($v, static fn ($x) => ! is_float($x)) === []; + $t3 = QuoteSheet::text($rr[3] ?? null); + if (! (str_contains($t3, '陆运') || str_contains($t3, '卡航'))) { + [$a, $b] = [$gg(4), $gg(5)]; + if (! $is($a, $b)) { + return ['error' => '报价单元格无数值']; + } + [$d['first_kg'], $d['first_price'], $d['rate']] = [20.0, $a, $b]; + [$fee, $F] = $w <= 20 ? [$a, "干配:{$f($w)}kg≤20kg,首重价{$f($a)}"] : [$a + ($w - 20) * $b, "干配:首重{$f($a)}+({$f($w)}-20)kg×续重{$f($b)}"]; + } elseif ($w <= 20) { + [$a, $b] = $w <= 3 ? [$gg(6), $gg(7)] : [$gg(8), $gg(9)]; + if (! $is($a, $b)) { + return ['error' => '报价单元格无数值']; + } + [$fee, $F] = $w <= 3 + ? [$a + max($w - 1, 0) * $b, "陆运(特殊省份):1kg首重{$f($a)}+({$f($w)}-1)kg×{$f($b)}"] + : [$a + ($w - 3) * $b, "陆运(特殊省份):3kg价{$f($a)}+({$f($w)}-3)kg×{$f($b)}"]; + [$d['first_price'], $d['rate']] = [$a, $b]; + } else { + [$a, $b] = $w <= 60 ? [$gg(12), $gg(13)] : [$gg(14), $gg(15)]; + if (! $is($a, $b)) { + return ['error' => '报价单元格无数值']; + } + [$fee, $F] = $w <= 60 + ? [$a + ($w - 20) * $b, "卡航(特殊省份):20kg价{$f($a)}+({$f($w)}-20)kg×{$f($b)}"] + : [$a + ($w - 60) * $b, "卡航(特殊省份):60kg价{$f($a)}+({$f($w)}-60)kg×{$f($b)}"]; + [$d['first_price'], $d['rate']] = [$a, $b]; + } + if (count($cand) > 1) { + $d['region'] = $prov . '/' . QuoteSheet::text($rr[1] ?? null); + } + + return ['fee' => $fee, 'F' => $F]; + } + + /** 洛宁德邦:<30kg 按小件(泡比默认3000)、否则大件(泡比默认5000),重量四舍五入且不低于1kg。 */ + private function luoningDb(array &$d, array $row, float $vol, float $w): array + { + $rw = static fn (float $x): float => max(1.0, self::rhalf($x)); + $g = static fn (int $i) => $row[$i] ?? null; + [$fk1, $a1, $b1, $c1, $fk2, $a2, $b2, $c2] = [$g(1), $g(2), $g(3), $g(4), $g(5), $g(6), $g(7), $g(8)]; + foreach ([$fk1, $a1, $b1, $fk2, $a2, $b2] as $v) { + if (! is_float($v)) { + return ['error' => '报价单元格无数值']; + } + } + $c1 = is_float($c1) ? $c1 : 3000.0; + $c2 = is_float($c2) ? $c2 : 5000.0; + $f = static fn ($x): string => self::fmt($x); + $bw = (float) ($d['base_w'] ?? 0); + $s1 = ($d['free'] || ! $vol) ? $bw : max($bw, $vol / $c1); + if ($rw($s1) < $fk2) { + $ww = $rw($s1); + $d['coef'] = $c1; + $d['vol_w'] = $vol && ! $d['free'] ? round($vol / $c1, 4) : null; + [$d['first_kg'], $d['first_price'], $d['rate']] = [$fk1, $a1, $b1]; + $fee = $ww <= $fk1 ? $a1 : $a1 + ($ww - $fk1) * $b1; + $F = "小件(<30kg,泡比{$f($c1)}):" . ($ww <= $fk1 ? "{$f($ww)}kg≤{$f($fk1)}kg首重{$f($a1)}" : "首重{$f($a1)}+({$f($ww)}-{$f($fk1)})kg×续重{$f($b1)}"); + $d['settle_w'] = round($s1, 4); + } else { + $s2 = ($d['free'] || ! $vol) ? $bw : max($bw, $vol / $c2); + $ww = $rw($s2); + $d['coef'] = $c2; + $d['vol_w'] = $vol && ! $d['free'] ? round($vol / $c2, 4) : null; + [$d['first_kg'], $d['first_price'], $d['rate']] = [$fk2, $a2, $b2]; + $fee = $ww <= $fk2 ? $a2 : $a2 + ($ww - $fk2) * $b2; + $F = "大件(≥30kg,泡比{$f($c2)}):" . ($ww <= $fk2 ? "{$f($ww)}kg≤{$f($fk2)}kg首重{$f($a2)}" : "首重{$f($a2)}+({$f($ww)}-{$f($fk2)})kg×续重{$f($b2)}"); + $d['settle_w'] = round($s2, 4); + } + + return ['fee' => $fee, 'F' => $F, 'w' => $ww]; + } + + /** 重量落在哪个段:返回 [单元格值, 段表头]。 */ + private static function band(array $bands, float $w, callable $g, array $head): array + { + foreach ($bands as [$lo, $hi, $i]) { + if ($w <= $hi + 1e-9) { + return [$g($i), trim((string) $head[$i])]; + } + } + + return [null, '']; + } + + public static function pieces(array $pkg): int + { + return preg_match('/^\s*\d+\s*\/\s*(\d+)/u', (string) ($pkg['pkg_count'] ?? ''), $m) ? (int) $m[1] : 1; + } + + private static function pos(mixed $x): float + { + return is_numeric($x) && (float) $x > 0 ? (float) $x : 0.0; + } + + private static function rhalf(float $x): float + { + return round($x, 0, PHP_ROUND_HALF_UP); + } + + public static function fmt(mixed $x): string + { + if ($x === null) { + return ''; + } + if (! is_numeric($x)) { + return (string) $x; + } + + return rtrim(rtrim(sprintf('%.4f', (float) $x), '0'), '.'); + } + + private static function show(mixed $v): string + { + return $v === null ? 'None' : (is_float($v) ? self::fmt($v) : (string) $v); + } +} diff --git a/modules/EcommerceFinance/Services/Freight/ShippingFreightService.php b/modules/EcommerceFinance/Services/Freight/ShippingFreightService.php new file mode 100644 index 00000000..851880d9 --- /dev/null +++ b/modules/EcommerceFinance/Services/Freight/ShippingFreightService.php @@ -0,0 +1,314 @@ +>|null 报价名称 => 版本 */ + private ?array $versions = null; + + /** @var array 报价名称|日期 => 解析好的报价 */ + private array $resolved = []; + + /** @var array 版本 id => 解析好的报价 */ + private array $parsed = []; + + /** @var array 待重算:报价名称 => 最早日期 */ + private static array $pending = []; + + /** 已登记「请求结束后重算」的应用实例(spl_object_id)。 */ + private static ?int $flushRegisteredFor = null; + + public function __construct(private readonly ShippingFreightCalculator $calculator) + { + $this->db = DB::connection((string) config('jushuitan.connection', 'jushuitan_local')); + } + + /** + * 核算发货时间在 [from, to) 的包裹;$carriers 为空表示全部快递。 + * + * @param list|null $carriers 报价名称(发货数据快递名称) + * @return array{packages:int,ok:int} + */ + public function recalculate(string $from, string $to, ?array $carriers = null): array + { + $from = max(substr($from, 0, 10), FreightCarrierRules::START_DATE) . ' 00:00:00'; + $to = strlen($to) === 10 ? $to . ' 00:00:00' : $to; + if ($from >= $to) { + return ['packages' => 0, 'ok' => 0]; + } + $this->versions = null; + $this->resolved = []; + $names = null; + if ($carriers !== null) { + $names = []; + foreach ($carriers as $c) { + $c = trim($c); + $names[$c] = true; + foreach (FreightCarrierRules::ALIAS as $alias => $target) { + if ($target === $c) { + $names[$alias] = true; + } + } + } + $names = array_keys($names); + if ($names === []) { + return ['packages' => 0, 'ok' => 0]; + } + } + + $total = 0; + $ok = 0; + $last = 0; + while (true) { + $q = $this->db->table('jst_oms_shipping') + ->where('ship_time', '>=', $from)->where('ship_time', '<', $to) + ->where('source_id', '>', $last) + ->whereNotNull('source_id'); + if ($names !== null) { + $q->whereIn('express_name1', $names); + } + $ids = $q->distinct()->orderBy('source_id')->limit(self::CHUNK)->pluck('source_id')->map(static fn ($v) => (int) $v)->all(); + if ($ids === []) { + break; + } + $last = end($ids); + $rows = []; + $now = now()->format('Y-m-d H:i:s'); + foreach ($this->packages($ids) as $pkg) { + $r = $this->calculatePackage($pkg); + $rows[] = $this->resultRow($pkg, $r, $now); + $ok += $r['status'] === 'OK' ? 1 : 0; + } + $this->db->transaction(function () use ($ids, $rows): void { + $this->db->table('jst_oms_shipping_freight')->whereIn('source_id', $ids)->delete(); + foreach (array_chunk($rows, 500) as $part) { + $this->db->table('jst_oms_shipping_freight')->insert($part); + } + }); + $total += count($rows); + if (count($ids) < self::CHUNK) { + break; + } + } + + return ['packages' => $total, 'ok' => $ok]; + } + + /** + * 单个包裹核算(合并口径字段)。 + * + * @param array $pkg + * @return array + */ + public function calculatePackage(array $pkg): array + { + $name = trim((string) ($pkg['express_name1'] ?? '')); + $name = FreightCarrierRules::ALIAS[$name] ?? $name; + $cfg = FreightCarrierRules::for($name); + if ($cfg !== null) { + $cfg['_name'] = $name; + } + $versions = $this->versions()[$name] ?? null; + if ($versions === null || $versions->isEmpty()) { + $r = $this->calculator->calculate($pkg, null, $cfg); + $r['status'] = '报价管理里没有「' . $name . '」的报价'; + + return $r; + } + + return $this->calculator->calculate($pkg, $this->quoteAt($name, substr((string) $pkg['ship_time'], 0, 10)), $cfg); + } + + /** + * 报价版本变更后登记待重算(同一请求内合并,请求结束后执行)。 + */ + public static function queueCarrier(?string $carrier, mixed $fromDate): void + { + $carrier = trim((string) $carrier); + if ($carrier === '') { + return; + } + $day = $fromDate instanceof \DateTimeInterface ? $fromDate->format('Y-m-d') : substr((string) $fromDate, 0, 10); + $day = $day !== '' ? max($day, FreightCarrierRules::START_DATE) : FreightCarrierRules::START_DATE; + if (! isset(self::$pending[$carrier]) || $day < self::$pending[$carrier]) { + self::$pending[$carrier] = $day; + } + $app = app(); + if (self::$flushRegisteredFor !== spl_object_id($app)) { + self::$flushRegisteredFor = spl_object_id($app); + $app->terminating(static function (): void { + self::flushPending(); + }); + } + } + + public static function flushPending(): void + { + $pending = self::$pending; + self::$pending = []; + if ($pending === []) { + return; + } + $to = Carbon::tomorrow()->format('Y-m-d'); + $service = app(self::class); + foreach ($pending as $carrier => $from) { + try { + $service->recalculate($from, $to, [$carrier]); + } catch (\Throwable $e) { + report($e); + } + } + } + + /** @return array> */ + private function versions(): array + { + if ($this->versions !== null) { + return $this->versions; + } + $companyId = function_exists('company_id') && company_id() ? (int) company_id() : (int) config('jushuitan.freight_company_id', 1); + $all = CourierQuoteVersion::query()->allCompanies() + ->where('company_id', $companyId) + ->with([ + 'change' => static fn ($q) => $q->allCompanies(), + 'signature' => static fn ($q) => $q->allCompanies(), + ]) + ->get(); + + return $this->versions = $all->groupBy(static fn (CourierQuoteVersion $v) => trim((string) $v->company_name))->all(); + } + + private function quoteAt(string $name, string $day): ?array + { + $key = $name . '|' . $day; + if (array_key_exists($key, $this->resolved)) { + return $this->resolved[$key]; + } + $version = CourierRequoteService::resolveAt($this->versions()[$name] ?? collect(), Carbon::parse($day)); + if ($version === null) { + return $this->resolved[$key] = null; + } + if (! isset($this->parsed[$version->id])) { + $vals = json_decode((string) $version->values_json, true); + $vals = is_array($vals) ? $vals : []; + $this->parsed[$version->id] = [ + 'id' => (string) $version->version_code, + 'p' => QuoteSheet::parse($vals), + 'rules' => (string) ($version->billing_rules ?? ''), + 'vals' => $vals, + ]; + } + + return $this->resolved[$key] = $this->parsed[$version->id]; + } + + /** + * 按包裹(快递单号)汇总发货明细(与发货数据合并口径一致)。实称/线上/重量是整个包裹的重量,只记在包裹第一行商品上 + * (其余行为空),取包裹那一行的值;采购退货等没有整包重量的,每行记单重×数量,合计即整包预估重量。 + * 长宽高取最大(组合件取整行值),体积/运费合计,条码去重拼接。 + * + * @param list $ids + * @return list> + */ + private function packages(array $ids): array + { + $rows = $this->db->table('jst_oms_shipping')->whereIn('source_id', $ids)->orderBy('id') + ->get(['id', 'source_id', 'express_no', 'express_name1', 'warehouse_name', 'receiver_state', 'receiver_city', 'ship_time', + 'pkg_count', 'online_weight', 'actual_weight', 'weight_kg', 'length_cm', 'width_cm', 'height_cm', 'volume_cm3', + 'm_length_cm', 'm_width_cm', 'm_height_cm', 'm_volume_cm3', 'barcode', 'freight']); + $out = []; + foreach ($rows as $r) { + $sid = (int) $r->source_id; + $p = &$out[$sid]; + if ($p === null) { + $p = ['source_id' => $sid, 'express_no' => null, 'express_name1' => null, 'warehouse_name' => null, 'receiver_state' => null, + 'receiver_city' => null, 'ship_time' => null, 'pkg_count' => null, 'online_weight' => null, 'actual_weight' => null, + 'weight_kg' => null, 'length_cm' => null, 'width_cm' => null, 'height_cm' => null, 'volume_cm3' => null, + 'barcodes' => [], 'freight' => null]; + } + foreach (['express_no', 'express_name1', 'warehouse_name', 'receiver_state', 'receiver_city', 'ship_time', 'pkg_count'] as $c) { + $v = $r->{$c}; + if ($v !== null && $v !== '' && ($p[$c] === null || (string) $v > (string) $p[$c])) { + $p[$c] = $v; // 对齐合并口径 MAX() + } + } + foreach (['online_weight', 'actual_weight', 'weight_kg', 'freight'] as $c) { + if ($r->{$c} !== null) { + $p[$c] = (float) $p[$c] + (float) $r->{$c}; + } + } + $vol = $r->m_volume_cm3 ?? $r->volume_cm3; + if ($vol !== null) { + $p['volume_cm3'] = (float) $p['volume_cm3'] + (float) $vol; + } + foreach (['length_cm' => 'm_length_cm', 'width_cm' => 'm_width_cm', 'height_cm' => 'm_height_cm'] as $c => $mc) { + $v = $r->{$mc} ?? $r->{$c}; + if ($v !== null && ($p[$c] === null || (float) $v > (float) $p[$c])) { + $p[$c] = (float) $v; + } + } + $bc = trim((string) $r->barcode); + if ($bc !== '' && ! in_array($bc, $p['barcodes'], true)) { + $p['barcodes'][] = $bc; + } + unset($p); + } + foreach ($out as &$p) { + $p['barcodes'] = implode(',', $p['barcodes']); + } + unset($p); + + return array_values($out); + } + + /** @return array */ + private function resultRow(array $pkg, array $r, string $now): array + { + $num = static fn ($v, int $dp = 4) => is_numeric($v) ? round((float) $v, $dp) : null; + + return [ + 'source_id' => $pkg['source_id'], + 'express_no' => $pkg['express_no'] !== null ? mb_substr((string) $pkg['express_no'], 0, 64) : null, + 'express_name' => $pkg['express_name1'] !== null ? mb_substr((string) $pkg['express_name1'], 0, 100) : null, + 'ship_date' => $pkg['ship_time'] !== null ? substr((string) $pkg['ship_time'], 0, 10) : null, + 'quote_version' => $r['ver'], + 'status' => mb_substr((string) $r['status'], 0, 255), + 'base_source' => $r['base_src'] !== '' ? $r['base_src'] : null, + 'base_weight' => $num($r['base_w']), + 'volume_weight' => $num($r['vol_w']), + 'coef' => is_numeric($r['coef']) ? (int) $r['coef'] : null, + 'free_warehouse' => (bool) $r['free'], + 'settle_weight' => $num($r['settle_w']), + 'charge_weight' => $num($r['charge_w']), + 'first_kg' => $num($r['first_kg'], 2), + 'first_price' => $num($r['first_price']), + 'rate' => $r['rate'] === null ? null : mb_substr(is_float($r['rate']) ? ShippingFreightCalculator::fmt($r['rate']) : (string) $r['rate'], 0, 32), + 'miandan' => $num($r['miandan']), + 'flat_price' => $num($r['flat']), + 'extra_fee' => (float) $r['extra'] > 0 ? round((float) $r['extra'], 4) : null, + 'freight' => $r['status'] === 'OK' ? $num($r['fee'], 2) : null, + 'jst_freight' => $num($pkg['freight'], 2), + 'formula' => $r['formula'] !== '' ? $r['formula'] : null, + 'calculated_at' => $now, + ]; + } +} diff --git a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php index a580890c..e1b64552 100644 --- a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php +++ b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php @@ -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; } diff --git a/resources/views/business/pages/courier-payables/shipping-data.blade.php b/resources/views/business/pages/courier-payables/shipping-data.blade.php index d7a6e1e1..7a438122 100644 --- a/resources/views/business/pages/courier-payables/shipping-data.blade.php +++ b/resources/views/business/pages/courier-payables/shipping-data.blade.php @@ -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) { diff --git a/tests/Feature/Business/ShippingFreightServiceTest.php b/tests/Feature/Business/ShippingFreightServiceTest.php new file mode 100644 index 00000000..6fd3b507 --- /dev/null +++ b/tests/Feature/Business/ShippingFreightServiceTest.php @@ -0,0 +1,103 @@ +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, + ]); + } +} diff --git a/tests/Unit/EcommerceFinance/ShippingFreightCalculatorTest.php b/tests/Unit/EcommerceFinance/ShippingFreightCalculatorTest.php new file mode 100644 index 00000000..b3df0b4e --- /dev/null +++ b/tests/Unit/EcommerceFinance/ShippingFreightCalculatorTest.php @@ -0,0 +1,132 @@ + $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']); + } +} diff --git a/tests/Unit/EcommerceFinance/ShippingReplicaSynchronizerTest.php b/tests/Unit/EcommerceFinance/ShippingReplicaSynchronizerTest.php index 7972f093..3fb9038e 100644 --- a/tests/Unit/EcommerceFinance/ShippingReplicaSynchronizerTest.php +++ b/tests/Unit/EcommerceFinance/ShippingReplicaSynchronizerTest.php @@ -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);