CaiWuXiTong/app/Support/CourierBills/BillSurchargeQuoteCalculator.php

122 lines
8.9 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 Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer as ServiceFees;
use Modules\EcommerceFinance\Services\WorkOrderWaybillLookup;
/** 账单按票核价:只读现有报价及共享镜像,不将账单金额当作结算依据。 */
final class BillSurchargeQuoteCalculator
{
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);
$freights = $shipping->summaries($waybills);
$needsService = $rules->contains(fn ($r) => $r->mode === '聚工单客服核实');
$workOrders = $needsService ? $this->workOrders($waybills, $month) : [];
$rows = $notes = $metadata = [];
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;
}
$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] ?? []);
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|string
{
if ($rule->mode === '取发出运费') {
if (! in_array(trim($rule->condition), ['取发出运费', '等于发出运费'], true)) return '计费条件尚未支持自动核验';
if (! in_array(trim($rule->standard), ['取发出运费', '等于发出运费'], true)) return '计价标准尚未支持自动核验';
if (($freight['calc_freight'] ?? null) === null) return '发出运费尚未核算完成';
$amount = round($freight['calc_freight'], 2);
return [['settlement_amount' => $amount, 'evidence' => '取本票已核算发出运费 ' . number_format($amount, 2, '.', '') . ' 元']];
}
if ($rule->mode === '按尺寸/最长边') {
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 = match (trim((string) ($v[ServiceFees::FEE_TYPE] ?? ''))) {
'拦截退回运费' => '退回费', default => 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 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', '<', date('Y-m-d', strtotime($month . '-01 +1 month')))
->orderBy('w.Id')->get(['l.waybill', 'w.woNo', 'w.created', 'w.status', 'w.businessFieldList']);
$result = [];
foreach ($rows as $row) $result[strtoupper($row->waybill)][$row->woNo] = $row;
return $result;
}
}