CaiWuXiTong/app/Support/CourierBills/BillSurchargeQuoteCalculator.php

330 lines
24 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Support\CourierBills;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer as ServiceFees;
use Modules\EcommerceFinance\Services\WorkOrderWaybillLookup;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
/** 账单按票核价:只读现有报价及共享镜像,不将账单金额当作结算依据。 */
final class BillSurchargeQuoteCalculator
{
public const BUYER_CONFIRMATIONS = 'courier-surcharge-buyer-confirmations';
public static function buyerConfirmationKey(int $ruleId, string $month, string $waybill, string $workOrder): string
{
return implode('|', [$ruleId, $month, strtoupper(trim($waybill)), $workOrder]);
}
/** 所有附加费均按自然月含账单当月,匹配最近3个月。 */
public static function window(string $month): array
{
$start = Carbon::parse($month . '-01')->startOfMonth();
$months = 3;
return ['from' => $start->copy()->subMonthsNoOverflow($months - 1)->toDateString(),
'until' => $start->copy()->addMonth()->toDateString(), 'months' => $months];
}
public function calculate(array $input, string $scope, string $month, array $allowedCouriers): array
{
if ($input === [] || $allowedCouriers === []) return ['rows' => [], 'notes' => [], 'metadata' => []];
$rules = DB::table('business_courier_surcharge_quotes')->where('company_id', (int) (company_id() ?: 1))
->where('status', 'active')->whereNull('deleted_at')->whereIn('courier', $allowedCouriers)
->where('scope', $scope === 'dropship' ? '代发仓' : '自有快递')
->orderByDesc('effective_at')->orderByDesc('id')->get();
$waybills = array_values(array_unique(array_column($input, 'waybill_no')));
$shipping = app(ShippingLookup::class);
$ships = $shipping->details($waybills, $allowedCouriers);
$freights = $shipping->summaries($waybills, $allowedCouriers);
$needsService = $rules->contains(fn ($r) => in_array($r->mode, ['聚工单客服核实', '固定单价'], true)
|| ($r->mode === '取发出运费' && trim($r->condition) === '查件扣单并且买家原因'));
$workOrders = $needsService ? $this->workOrders($waybills, $month) : [];
$returns = $rules->contains(fn ($r) => $r->mode === '固定单价' && str_contains($r->condition, '已退回'))
? $this->receivedReturns($workOrders, $month) : [];
$confirmations = $this->buyerConfirmations($rules, $workOrders, $month);
$rows = $notes = $metadata = [];
$window = self::window($month);
foreach ($input as $fee) {
$wb = strtoupper($fee['waybill_no']); $type = SurchargeSettlementMatcher::type($fee['item']);
$ship = $ships[$wb] ?? []; $courier = $ship['express_name1'] ?? '';
$date = substr((string) ($ship['ship_time'] ?? ''), 0, 10);
$metadata[$wb] = ['courier_name' => $courier ?: null, 'platform_product_id' => $ship['item_id'] ?? null,
'product_code' => $ship['barcode'] ?? null, 'shop_name' => $ship['shop_name'] ?? null,
'online_order_no' => $ship['trade_no'] ?? null];
if($date !== '' && $date >= date('Y-m-d', strtotime($month . '-01 +1 month'))){
$notes[$wb][$type]='发货日期晚于账单月份,未计入本月';
continue;
}
$candidates = $rules->filter(fn ($r) => $r->courier === $courier
&& in_array($type, array_map([SurchargeSettlementMatcher::class, 'type'], json_decode($r->types, true) ?: []), true));
$rule = $candidates->first(fn ($r) => $date !== '' && substr($r->effective_at, 0, 10)
<= ($r->mode === '聚工单客服核实' ? $month . '-31' : $date));
if ($rule === null) {
$notes[$wb][$type] = $candidates->isEmpty() ? '该快递没有启用的对应费用报价' : '发货日期未达到报价生效日或没有发货记录';
continue;
}
// 买家原因必须按当前工单核验,缺少依据时不能回退到旧结算金额。
if ($rule->mode === '固定单价'
|| ($rule->mode === '取发出运费' && trim($rule->condition) === '查件扣单并且买家原因')) $rows[$wb][$type] = [];
if ($date < $window['from']) {
$notes[$wb][$type] = '发货日期超出匹配范围:' . $window['from'] . ' 至 ' . Carbon::parse($window['until'])->subDay()->toDateString();
continue;
}
$base = ['rule_id' => $rule->id, 'courier_name' => $courier, 'waybill' => $wb, 'surcharge_type' => $type,
'shipped_at' => $ship['ship_time'] ?? null, 'source_created_at' => null,
'platform_product_id' => $ship['item_id'] ?? null, 'product_code' => $ship['barcode'] ?? null,
'shop_name' => $ship['shop_name'] ?? null, 'online_order_no' => $ship['trade_no'] ?? null,
'source_kind' => 'bill_quote', 'source_key' => $wb . '|' . $type, 'outbound_io_id' => null];
$result = $this->price($rule, $type, $ship, $freights[$wb] ?? [], $workOrders[$wb] ?? [],
$confirmations[$rule->id][$wb] ?? [], $returns);
if (is_string($result)) { $notes[$wb][$type] = '报价 #' . $rule->id . ':' . $result; continue; }
foreach ($result as $price) $rows[$wb][$type][] = (object) array_replace($base, $price,
['settlement_status' => '已计算', 'evidence' => '报价 #' . $rule->id . ';' . $price['evidence']]);
}
return compact('rows', 'notes', 'metadata');
}
private function price(object $rule, string $type, array $ship, array $freight, array $orders, array $confirmations, array $returns): array|string
{
if ($rule->mode === '固定单价') return $this->fixedPrice($rule, $type, $orders, $returns);
if ($rule->mode === '取发出运费') {
if (! in_array(trim($rule->condition), ['取发出运费', '等于发出运费', '查件扣单并且买家原因'], true)) return '计费条件尚未支持自动核验';
if (! in_array(trim($rule->standard), ['取发出运费', '等于发出运费'], true)) return '计价标准尚未支持自动核验';
$evidence = '';
if (trim($rule->condition) === '查件扣单并且买家原因') {
$reason = $this->buyerReason($rule, $orders, $confirmations);
if (is_string($reason)) return $reason;
if (! $reason['eligible']) return [['settlement_amount' => 0, 'evidence' => $reason['evidence']]];
$evidence = $reason['evidence'] . ';';
}
if (($freight['calc_freight'] ?? null) === null) return '发出运费尚未核算完成';
$amount = round($freight['calc_freight'], 2);
return [['settlement_amount' => $amount, 'evidence' => $evidence . '取本票已核算发出运费 ' . number_format($amount, 2, '.', '') . ' 元']];
}
if ($rule->mode === '按尺寸/最长边') {
$combined = $this->sizeWeightRule($rule);
if ($combined !== null) {
$weight = $freight['charge_weight'] ?? null;
if (! is_numeric($weight) || (float) $weight <= 0) return '缺少已核算计费重量,无法检查超长超重费';
$sides = [(float) ($ship['length_cm'] ?? 0), (float) ($ship['width_cm'] ?? 0), (float) ($ship['height_cm'] ?? 0)];
if (min($sides) <= 0) return '发货商品缺少完整尺寸,无法检查超长超重费';
$max = max($sides);
$eligible = $max > $combined['length_cm'] || (float) $weight > $combined['weight'];
$amount = $eligible ? round(max($combined['minimum'], (float) $weight * $combined['rate']), 2) : 0.0;
return [['settlement_amount' => $amount, 'evidence' =>
'最长边 ' . $max . 'cm,计费重量 ' . $weight . 'kg;报价条件:最长边>' . $combined['length_cm']
. 'cm 或计费重量>' . $combined['weight'] . 'kg;'
. ($eligible ? 'max(' . $weight . '×' . $combined['rate'] . '元/kg,最低' . $combined['minimum'] . '元)' : '未达到条件,不计费')
. ',按票计一次']];
}
if (! preg_match('/^(?:单边(?:长)?超|最长边超过?)\s*(\d+(?:\.\d+)?)\s*(?:cm|厘米)$/iu', trim($rule->condition), $threshold)
|| ! preg_match('/^(\d+(?:\.\d+)?)\s*元?\s*\/\s*单$/u', trim($rule->standard), $price)) return '尺寸计费条件或单价尚未支持自动核验';
$sides = [(float) ($ship['length_cm'] ?? 0), (float) ($ship['width_cm'] ?? 0), (float) ($ship['height_cm'] ?? 0)];
if (min($sides) <= 0) return '发货商品缺少完整尺寸';
$max = max($sides); $amount = $max > (float) $threshold[1] ? (float) $price[1] : 0;
return [['settlement_amount' => $amount, 'evidence' => '最长边 ' . $max . 'cm,报价阈值 ' . $threshold[1] . 'cm,按票计费']];
}
if ($rule->mode !== '聚工单客服核实') return '计费方式“' . $rule->mode . '”尚未接入账单自动核价';
if (trim($rule->standard) !== '读取聚工单附加费明细') return '客服计价标准尚未支持自动核验';
$condition = trim($rule->condition);
if (preg_match('/^重量\s*(\d+(?:\.\d+)?)\s*(?:kg|公斤|千克)以上[,,、]?上楼费聚工单客服回复通过$/iu', $condition, $weight)) {
if (($freight['charge_weight'] ?? null) === null) return '缺少已核算计费重量,无法检查上楼费门槛';
if ((float) $freight['charge_weight'] < (float) $weight[1]) return [['settlement_amount' => 0,
'evidence' => '本票计费重量 ' . $freight['charge_weight'] . 'kg,未达到 ' . $weight[1] . 'kg 门槛,不计费']];
} elseif (! in_array($condition, ['聚工单客服回复通过', '改地址客服回复通过'], true)) return '客服附加条件尚未支持自动核验';
$result = []; $found = false;
foreach ($orders as $order) {
$fields = [];
foreach (json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [] as $f) if (isset($f['fieldId'])) $fields[$f['fieldId']] = $f;
if (($fields['logisticsField']['value'] ?? '') !== $rule->courier
|| substr($order->created, 0, 10) < substr($rule->effective_at, 0, 10)
|| in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true)) continue;
$cents = 0;
foreach ($fields[ServiceFees::FEE_TABLE]['childFieldList'] ?? [] as $line) {
$v = array_column($line, 'value', 'fieldId');
$actualType = SurchargeSettlementMatcher::type((string) ($v[ServiceFees::FEE_TYPE] ?? ''));
if ($actualType !== $type) continue;
$found = true;
if (($v[ServiceFees::FEE_APPROVAL] ?? '') !== '通过') continue;
$amount = trim((string) ($v[ServiceFees::FEE_AMOUNT] ?? ''));
if (! preg_match('/^\d{1,9}(?:\.\d{1,2})?$/D', $amount)) return '客服已通过的费用金额无效';
$cents += (int) round((float) $amount * 100);
}
if ($cents > 0) $result[] = ['settlement_amount' => $cents / 100,
'source_kind' => ServiceFees::KIND, 'source_key' => $order->woNo, 'source_created_at' => $order->created,
'evidence' => '聚工单 ' . $order->woNo . ' 附加费明细逐项审核通过'];
}
return $result ?: ($found ? '对应工单附加费未审核通过' : '未找到对应单号、费用类型和快递的客服费用明细');
}
/** 同一张报价明确列出超长或超重条件,按整票计费重量和最低金额收取。 */
private function sizeWeightRule(object $rule): ?array
{
$pattern = '/^最长边大于(\d+(?:\.\d+)?)米[;;]②?计费重量大于(\d+(?:\.\d+)?)KG[,,]即认定为超长超重货[,,]该单货物将在原收费基础上加收超长超重费[。.]加收标准按照计费重量[×*](\d+(?:\.\d+)?)元\/KG计算[,,]最低加收(\d+(?:\.\d+)?)元\/(?:票|单)[。.]?$/iu';
$condition = preg_replace('/\s+/u', '', $rule->condition);
$standard = preg_replace('/\s+/u', '', $rule->standard);
if (! preg_match($pattern, $condition, $c) || ! preg_match($pattern, $standard, $s)
|| array_map('floatval', array_slice($c, 1)) !== array_map('floatval', array_slice($s, 1))) return null;
if (min(array_map('floatval', array_slice($c, 1))) <= 0) return null;
return ['length_cm' => (float) $c[1] * 100, 'weight' => (float) $c[2],
'rate' => (float) $c[3], 'minimum' => (float) $c[4]];
}
private function buyerReason(object $rule, array $orders, array $confirmations, bool $requireBuyer = true, bool $allowDamage = false): array|string
{
$reasons = [];
foreach ($orders as $order) {
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
if (($fields['logisticsField'] ?? '') !== $rule->courier
|| substr($order->created, 0, 10) < substr($rule->effective_at, 0, 10)
|| in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true)) continue;
$reasons[] = ['order' => $order, 'order_id' => (string) ($fields['o_id'] ?? ''),
'reason' => trim((string) ($fields['SELECT_CASCADEField1413856620250813172526'] ?? ''))];
}
if ($reasons === []) return '未找到有效的同快递查件工单,无法核实买家原因';
// 同票多工单以最新扣单原因核验;其他查件操作不覆盖扣单原因,费用仍按票只计一次。
usort($reasons, fn ($a, $b) => [$b['order']->created, $b['order']->source_id] <=> [$a['order']->created, $a['order']->source_id]);
$deductions = array_values(array_filter($reasons, fn ($r) => trim(explode('/', $r['reason'], 2)[0]) === '扣单'));
$latest = $deductions[0] ?? $reasons[0];
[$operation, $cause] = array_map('trim', array_pad(explode('/', $latest['reason'], 2), 2, ''));
if ($operation === '' || ($requireBuyer && ($cause === '' || $cause === '买家-'))) return '查件工单原因不完整,无法核实买家原因';
$eligible = $operation === '扣单' && (! $requireBuyer || str_starts_with($cause, '买家-')
|| ($allowDamage && in_array($cause, ['快递-破损', '破损'], true)));
$confirmation = $confirmations[$latest['order']->woNo] ?? [];
if (! $eligible && $operation === '扣单' && ($confirmation['buyer_reason_confirmed'] ?? false) === true
&& ($confirmation['original_reason'] ?? '') === $latest['reason'] && trim($confirmation['evidence'] ?? '') !== '') {
return ['eligible' => true, 'evidence' => '聚工单 ' . $latest['order']->woNo . ' 原因:' . $latest['reason']
. ';人工确认买家原因:' . $confirmation['evidence']];
}
return ['eligible' => $eligible, 'order_id' => $latest['order_id'], 'operation' => $operation,
'evidence' => '聚工单 ' . $latest['order']->woNo . ' 原因:' . $latest['reason']
. ($eligible ? ($requireBuyer ? ($allowDamage ? ',符合买家原因或破损条件' : ',符合买家原因条件') : ',符合扣单条件')
: ($allowDamage ? ',不符合买家原因或破损条件,不计费' : ',不符合扣单且买家原因条件,不计费'))];
}
private function fixedPrice(object $rule, string $type, array $orders, array $returns): array|string
{
if (! preg_match('/^(\d{1,9}(?:\.\d{1,2})?)\s*元?\s*\/\s*(?:单|票)$/u', trim($rule->standard), $price)) {
return '固定单价格式不支持,请填写如30元/单';
}
$condition = trim($rule->condition);
$evidence = '';
if (in_array($condition, ['查件扣单', '查件扣单并且买家原因', '查件扣单并且买家原因或破损', '查件扣单并且买家原因已退回', '查件扣单并且买家原因已退回的'], true)) {
$reason = $this->buyerReason($rule, $orders, [], $condition !== '查件扣单', $condition === '查件扣单并且买家原因或破损');
if (is_string($reason)) return $reason;
if (! $reason['eligible']) return [['settlement_amount' => 0, 'evidence' => $reason['evidence']]];
$evidence = $reason['evidence'];
if (str_contains($condition, '已退回')) {
$received = $returns[$reason['order_id']] ?? null;
if ($received === null) return '未找到对应订单在匹配范围内的有效退回进仓明细,待核实';
$evidence .= ';退回进仓 ' . $received;
}
} elseif (preg_match('/^查件类型\/查件原因是([^\/]+)\/([^\/]+)$/u', $condition, $path)) {
$expected = trim($path[1]) . '/' . trim($path[2]);
$allowedReasons = array_map(static fn ($reason) => trim($path[1]) . '/' . trim($reason), explode('或', $path[2]));
$candidates = array_filter($orders, static function ($order) use ($rule): bool {
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
return ($fields['logisticsField'] ?? '') === $rule->courier
&& substr($order->created, 0, 10) >= substr($rule->effective_at, 0, 10)
&& ! in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true);
});
if ($candidates === []) return '未找到同快递的有效查件工单,无法核验查件类型和原因';
usort($candidates, static fn ($a, $b) => [$b->created, $b->source_id] <=> [$a->created, $a->source_id]);
$latest = $candidates[0];
$fields = array_column(json_decode($latest->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
$actual = trim((string) ($fields['SELECT_CASCADEField1413856620250813172526'] ?? ''));
if ($actual === '') return '查件工单未填写查件类型和原因,待核实';
$evidence = '聚工单 ' . $latest->woNo . ' 查件类型/原因为“' . $actual . '”';
if (! in_array($actual, $allowedReasons, true)) return [['settlement_amount' => 0, 'evidence' => $evidence . ',不符合报价条件“' . $expected . '”,不计费']];
$evidence .= ',符合报价条件';
} elseif (in_array($condition, ['聚工单客服回复通过', '改地址客服回复通过'], true)) {
$approved = false;
foreach ($orders as $order) {
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], null, 'fieldId');
if (($fields['logisticsField']['value'] ?? '') !== $rule->courier
|| substr($order->created, 0, 10) < substr($rule->effective_at, 0, 10)
|| in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true)) continue;
// 改地址固定报价也接受工单中明确的客服通过回复,不把“已联系快递修改”视作通过。
$reason = (string) ($fields['SELECT_CASCADEField1413856620250813172526']['value'] ?? '');
if ($type === '改地址' && str_starts_with($reason, '改地址')
&& (in_array(trim((string) ($fields['SELECT_CASCADEField1413856620250814100750']['value'] ?? '')), ['通过', '已通过'], true)
|| in_array(trim((string) ($fields['TEXTField1413856620250902151101']['value'] ?? '')), ['通过', '已通过', '客服回复已通过'], true))) {
$approved = true;
$evidence = '聚工单 ' . $order->woNo . ' 改地址客服明确回复已通过';
}
foreach ($fields[ServiceFees::FEE_TABLE]['childFieldList'] ?? [] as $line) {
$values = array_column($line, 'value', 'fieldId');
if (SurchargeSettlementMatcher::type((string) ($values[ServiceFees::FEE_TYPE] ?? '')) === $type
&& ($values[ServiceFees::FEE_APPROVAL] ?? '') === '通过') {
$approved = true;
$evidence = '聚工单 ' . $order->woNo . ' 对应费用客服审核通过';
}
}
}
if (! $approved) return '未找到同快递、同费用类型的客服审核通过明细';
} elseif (! in_array($condition, ['', '固定单价', '按单收取', '每单收取'], true)) {
return '固定单价的计费条件尚未支持自动核验';
}
$amount = (float) $price[1];
return [['settlement_amount' => $amount, 'evidence' => ($evidence === '' ? '' : $evidence . ';')
. '固定单价 ' . number_format($amount, 2, '.', '') . ' 元/单,按票计一次']];
}
/** 只按本批工单订单ID关联已有售后镜像,使用o_id/as_id索引,不扫描退回件全表。 */
private function receivedReturns(array $orders, string $month): array
{
$ids = [];
foreach ($orders as $records) foreach ($records as $order) {
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
$id = trim((string) ($fields['o_id'] ?? ''));
if (ctype_digit($id) && $id !== '0') $ids[$id] = true;
}
if ($ids === []) return [];
$db = DB::connection(config('upstream_mirrors.connection', 'business_mirror'));
if (! $db->getSchemaBuilder()->hasTable('ops_jst_return_refund_info') || ! $db->getSchemaBuilder()->hasTable('ops_jst_return_refund_item')) return [];
$result = [];
foreach (array_chunk(array_keys($ids), 300) as $chunk) {
$rows = $db->table('ops_jst_return_refund_info as h')->join('ops_jst_return_refund_item as i', 'i.as_id', '=', 'h.as_id')
->whereIn('h.o_id', $chunk)->where('i.r_qty', '>', 0)
->where('i.receive_date', '>=', self::window($month)['from'])->where('i.receive_date', '<', self::window($month)['until'])
->select('h.o_id')->selectRaw('MIN(' . $db->getQueryGrammar()->wrap('i.receive_date') . ') AS received_at')->groupBy('h.o_id')->get();
foreach ($rows as $row) $result[(string) $row->o_id] = $row->received_at;
}
return $result;
}
private function buyerConfirmations(iterable $rules, array $orders, string $month): array
{
$rows = [];
foreach ($rules as $rule) {
if ($rule->mode !== '取发出运费' || trim($rule->condition) !== '查件扣单并且买家原因') continue;
foreach ($orders as $waybill => $records) foreach ($records as $order) {
$rows[] = ['id' => self::buyerConfirmationKey((int) $rule->id, $month, $waybill, $order->woNo),
'rule_id' => $rule->id, 'waybill' => $waybill, 'work_order' => $order->woNo];
}
}
if ($rows === []) return [];
$result = [];
foreach (app(SupplierPayableOverrideStore::class)->decorate(self::BUYER_CONFIRMATIONS, $rows, (int) (company_id() ?: 1)) as $row) {
if ($row['_overridden']) $result[$row['rule_id']][$row['waybill']][$row['work_order']] = $row;
}
return $result;
}
private function workOrders(array $waybills, string $month): array
{
if (! app(WorkOrderWaybillLookup::class)->ready()) return [];
$rows = DB::connection(config('upstream_mirrors.connection', 'business_mirror'))
->table(WorkOrderWaybillLookup::TABLE . ' as l')->join(WorkOrderWaybillLookup::SOURCE . ' as w', 'w._mirror_key', '=', 'l.mirror_key')
->whereIn('l.waybill', $waybills)->where('w.created', '>=', self::window($month)['from'])
->where('w.created', '<', self::window($month)['until'])
->orderBy('w.Id')->get(['l.waybill', 'w.Id as source_id', 'w.woNo', 'w.created', 'w.status', 'w.businessFieldList']);
$result = [];
foreach ($rows as $row) $result[strtoupper($row->waybill)][$row->woNo] = $row;
return $result;
}
}