CaiWuXiTong/app/Support/CourierBills/CourierBillMatcher.php

355 lines
19 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 App\Support\UnshippedWaybills;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\DB;
use RuntimeException;
/**
* 对账单自动分类:逐行判断分类、算自算金额,重算「快递未提供」和自动小汇总行。
*/
final class CourierBillMatcher
{
private ?AccessoryDeductions $deductions = null;
public function __construct(
private readonly ShippingLookup $shipping,
private readonly UnshippedWaybills $unshipped,
) {}
public static function db(): ConnectionInterface
{
return DB::connection('business_mirror');
}
public function match(int $statementId): void
{
$db = self::db();
$statement = $db->table('courier_bill_statements')->find($statementId);
if ($statement === null) {
throw new RuntimeException('对账单不存在。');
}
if ($statement->status === 'confirmed') {
throw new RuntimeException('对账单已确认结算,先撤销确认再重新匹配。');
}
$group = $db->table('courier_bill_groups')->find($statement->group_id);
$names = array_values(array_filter(array_map('trim', (array) json_decode((string) $group->express_names, true))));
$month = (string) $statement->bill_month;
$lines = $db->table('courier_bill_lines')->where('statement_id', $statementId)->orderBy('id')
->get(['id', 'waybill_no', 'bill_amount', 'resolution'])->all();
$waybills = array_values(array_unique(array_map(static fn ($l): string => strtoupper($l->waybill_no), $lines)));
$settled = [];
foreach (array_chunk($waybills, 500) as $chunk) {
foreach ($db->table('courier_bill_ledger')->where('group_id', $statement->group_id)->whereIn('waybill_no', $chunk)
->where('settle_month', '<>', $month)->get(['waybill_no', 'settle_month']) as $row) {
$settled[strtoupper($row->waybill_no)] = $row->settle_month;
}
}
$unshipped = $this->unshipped->unshippedSources($waybills);
$unshipped = array_change_key_case($unshipped, CASE_UPPER);
$shipping = $this->shipping->summaries($waybills);
// 发货数据里查不到的单号,看是不是换单前的旧单号:旧面单没有发出去,归「未发出」,注明换成了哪个单号
$missing = array_values(array_filter($waybills, static fn (string $w): bool => ! isset($shipping[$w]) && ! isset($unshipped[$w])));
foreach ($missing === [] ? [] : $this->shipping->replacedBy($missing) as $old => [$new, $express]) {
$unshipped[$old] = ['换单:已换成 ' . $new . ($express !== null ? '(' . $express . ')' : '')];
}
$nameSet = array_flip($names);
$seen = [];
$updates = [];
foreach ($lines as $line) {
$key = strtoupper($line->waybill_no);
$ship = $shipping[$key] ?? null;
[$category, $categoryMonth] = self::categorize(
isset($seen[$key]), $settled[$key] ?? null, isset($unshipped[$key]), $ship, $nameSet, $month,
$line->bill_amount === null ? null : (float) $line->bill_amount,
);
$seen[$key] = true;
$updates[$line->id] = [
'category' => $category,
'category_month' => $categoryMonth,
'ship_time' => $ship['ship_time'] ?? null,
'express_name' => $ship['express_name'] ?? null,
'calc_freight' => $ship['calc_freight'] ?? null,
'charge_weight' => $ship['charge_weight'] ?? null,
'unshipped_sources' => isset($unshipped[$key]) ? mb_substr(implode('、', $unshipped[$key]), 0, 128) : null,
'self_amount' => self::selfAmount($category, $ship['calc_freight'] ?? null, $line->bill_amount, $line->resolution),
];
}
$billed = array_flip($waybills);
$unprovided = [];
foreach ($this->shipping->monthWaybills($names, $month) as $row) {
if (! isset($billed[$row['waybill']]) && ! isset($unprovided[$row['waybill']])) {
$unprovided[$row['waybill']] = $row;
}
}
$unprovidedFreight = $unprovided === [] ? [] : $this->shipping->summaries(array_keys($unprovided));
$db->transaction(function () use ($db, $statementId, $updates, $unprovided, $unprovidedFreight): void {
foreach ($updates as $id => $values) {
$db->table('courier_bill_lines')->where('id', $id)->update($values);
}
$db->table('courier_bill_unprovided')->where('statement_id', $statementId)->delete();
foreach (array_chunk(array_values($unprovided), 500) as $chunk) {
$db->table('courier_bill_unprovided')->insert(array_map(static fn (array $row): array => [
'statement_id' => $statementId, 'waybill_no' => $row['waybill'], 'ship_time' => $row['ship_time'],
'express_name' => $row['express_name'], 'calc_freight' => $unprovidedFreight[$row['waybill']]['calc_freight'] ?? null,
], $chunk));
}
$this->refreshSummary($statementId);
$db->table('courier_bill_statements')->where('id', $statementId)->update(['matched_at' => now(), 'updated_at' => now()]);
});
}
/**
* 分类判断,命中即停:
* 重复(本账单第二次及以后出现,或结算台账里别的月份已结算)→ 未发出 → 匹配不到 → 快递不符
* → 前月补提供 / 跨月订单(按发货月份)→ 一致 / 一致但运费有差 / 一致(系统未核算)。
*
* @param array{ship_time:?string,express_name:?string,calc_freight:?float}|null $ship
* @param array<string,int> $nameSet
* @return array{0:string,1:?string}
*/
public static function categorize(bool $seenInBill, ?string $settledMonth, bool $unshipped, ?array $ship,
array $nameSet, string $month, ?float $billAmount): array
{
if ($seenInBill || $settledMonth !== null) {
return [Category::DUPLICATE, $settledMonth];
}
if ($unshipped) {
return [Category::UNSHIPPED, null];
}
if ($ship === null) {
return [Category::UNMATCHED, null];
}
if (! isset($nameSet[(string) $ship['express_name']])) {
return [Category::MISMATCH, null];
}
$shipMonth = $ship['ship_time'] !== null ? substr((string) $ship['ship_time'], 0, 7) : $month;
if ($shipMonth < $month) {
return [Category::PRIOR, $shipMonth];
}
if ($shipMonth > $month) {
return [Category::LATER, $shipMonth];
}
if ($ship['calc_freight'] === null) {
return [Category::UNCALCULATED, null];
}
if ($billAmount !== null && abs($billAmount - (float) $ship['calc_freight']) <= 0.01) {
return [Category::MATCH, null];
}
return [Category::DIFF, null];
}
/** 自算金额:处理结果优先;否则一致类和前月补提供按核算运费,其余为 0。 */
public static function selfAmount(string $category, ?float $calcFreight, mixed $billAmount, ?string $resolution): ?float
{
return match ($resolution) {
'agree' => $billAmount === null ? null : (float) $billAmount,
'exclude', 'defer' => 0.0,
default => in_array($category, [...Category::PAYABLE, Category::PRIOR], true) ? $calcFreight : 0.0,
};
}
/** 按处理结果重算一批行的自算金额,再刷新小汇总。 */
public function resolve(int $statementId, array $lineIds, ?string $resolution, string $user): int
{
$db = self::db();
if ($db->table('courier_bill_statements')->where('id', $statementId)->value('status') === 'confirmed') {
throw new RuntimeException('对账单已确认结算,先撤销确认再修改。');
}
$count = 0;
$db->transaction(function () use ($db, $statementId, $lineIds, $resolution, $user, &$count): void {
foreach (array_chunk($lineIds, 500) as $chunk) {
$lines = $db->table('courier_bill_lines')->where('statement_id', $statementId)->whereIn('id', $chunk)
->get(['id', 'category', 'calc_freight', 'bill_amount']);
foreach ($lines as $line) {
$db->table('courier_bill_lines')->where('id', $line->id)->update([
'resolution' => $resolution,
'resolved_by' => $resolution === null ? null : $user,
'resolved_at' => $resolution === null ? null : now(),
'self_amount' => self::selfAmount((string) $line->category,
$line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $resolution),
]);
$count++;
}
}
$this->refreshSummary($statementId);
});
return $count;
}
/**
* 重建自动小汇总行(手工行保留)。项目名称照财务习惯写,保证归集规则落到正确的列:
* 「X月运费」→ 成品;「跨月订单-X月,本月不结算」「快递不符(未匹配本快递发货数据)」→ 匹配不到。
*/
public function refreshSummary(int $statementId): void
{
$db = self::db();
$month = (string) $db->table('courier_bill_statements')->where('id', $statementId)->value('bill_month');
$rows = $db->table('courier_bill_lines')->where('statement_id', $statementId)
->groupBy('category', 'category_month')
->selectRaw('category, category_month, SUM(bill_amount) as bill, SUM(self_amount) as self')
->get();
$items = [];
$label = static fn (string $category, ?string $m): string => match ($category) {
Category::MATCH => (int) substr($month, 5, 2) . '月运费',
Category::DIFF => (int) substr($month, 5, 2) . '月运费-价格差',
Category::UNCALCULATED => (int) substr($month, 5, 2) . '月运费-系统未核算',
Category::PRIOR => (int) substr((string) $m, 5, 2) . '月运费(前月补提供)',
Category::LATER => '跨月订单-' . (int) substr((string) $m, 5, 2) . '月,本月不结算',
Category::DUPLICATE => '重复',
Category::UNSHIPPED => '未发出',
Category::UNMATCHED => '匹配不到',
Category::MISMATCH => '快递不符(未匹配本快递发货数据)',
default => '待匹配',
};
$order = [Category::MATCH => 1, Category::DIFF => 1, Category::UNCALCULATED => 1, Category::PRIOR => 2, Category::LATER => 3,
Category::DUPLICATE => 4, Category::UNSHIPPED => 5, Category::UNMATCHED => 6, Category::MISMATCH => 7];
foreach ($rows as $row) {
$category = (string) ($row->category ?? '');
$name = $label($category, $row->category === Category::DUPLICATE ? null : $row->category_month);
$items[$name] ??= ['bill' => 0.0, 'self' => 0.0, 'sort' => ($order[$category] ?? 9) * 100 + (int) substr((string) $row->category_month, 5, 2)];
$items[$name]['bill'] += (float) $row->bill;
$items[$name]['self'] += (float) $row->self;
}
// 运费有差的再分原因:计费重量和账单重量不一样的算「重量差」,其余算「价格差」
$weight = $db->table('courier_bill_lines')->where('statement_id', $statementId)->where('category', Category::DIFF)
->whereNotNull('bill_weight')->whereNotNull('charge_weight')->whereRaw('ROUND(ABS(bill_weight - charge_weight), 4) > 0.005')
->selectRaw('COUNT(*) as n, COALESCE(SUM(bill_amount),0) as bill, COALESCE(SUM(self_amount),0) as self')->first();
$priceLabel = (int) substr($month, 5, 2) . '月运费-价格差';
if ((int) $weight->n > 0 && isset($items[$priceLabel])) {
$weightLabel = (int) substr($month, 5, 2) . '月运费-重量差';
$items[$weightLabel] = ['bill' => (float) $weight->bill, 'self' => (float) $weight->self, 'sort' => $items[$priceLabel]['sort']];
$items[$priceLabel]['bill'] -= (float) $weight->bill;
$items[$priceLabel]['self'] -= (float) $weight->self;
if ((int) $weight->n === (int) $db->table('courier_bill_lines')->where('statement_id', $statementId)->where('category', Category::DIFF)->count()) {
unset($items[$priceLabel]);
}
}
$m = (int) substr($month, 5, 2);
foreach (['运费' => 100, '运费-重量差' => 101, '运费-价格差' => 102, '运费-系统未核算' => 103] as $suffix => $sort) {
if (isset($items[$m . '月' . $suffix])) {
$items[$m . '月' . $suffix]['sort'] = $sort;
}
}
uasort($items, static fn (array $a, array $b): int => $a['sort'] <=> $b['sort']);
$this->addAccessoryDeduction($statementId, $month, $items);
$manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip();
$fees = $this->surchargeItems($statementId);
$sort = 8000;
foreach ($fees as $item => $sum) {
if (! isset($manualLabels[$item]) && ! isset($items[$item])) {
$items[$item] = ['bill' => $sum, 'self' => $sum, 'sort' => $sort++];
}
}
$db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', false)->delete();
$sort = 0;
foreach ($items as $name => $item) {
$db->table('courier_bill_summary_items')->insert([
'statement_id' => $statementId, 'label' => $name, 'bill_amount' => $item['bill'] === null ? null : round($item['bill'], 4),
'self_amount' => round($item['self'], 2), 'manual' => false, 'sort' => ++$sort,
]);
}
$totals = $db->table('courier_bill_lines')->where('statement_id', $statementId)
->selectRaw('COUNT(*) as line_count, COALESCE(SUM(bill_amount),0) as bill')->first();
$db->table('courier_bill_statements')->where('id', $statementId)->update([
'line_count' => (int) $totals->line_count, 'bill_amount' => round((float) $totals->bill, 2), 'updated_at' => now(),
]);
}
/**
* 「配件补发扣款」页里本月首发快递属于这个分组的可扣款金额,作为一行自动小汇总(快递金额空、自算为负)。
* 已经手工加了配件补发扣款类的行时不再自动加,免得扣两次。
*
* @param array<string,array{bill:?float,self:float,sort:int}> $items
*/
private function addAccessoryDeduction(int $statementId, string $month, array &$items): void
{
$db = self::db();
$manual = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
->contains(static fn ($label): bool => SummaryMapper::classify((string) $label) === 'AL');
if ($manual) {
return;
}
$names = (array) json_decode((string) $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
->where('s.id', $statementId)->value('g.express_names'), true);
$this->deductions ??= app(AccessoryDeductions::class);
$total = $this->deductions->total($month, array_values(array_filter(array_map('trim', $names))));
if ($total === null) {
$existing = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)
->where('manual', false)->where('label', '配件补发扣款')->value('self_amount');
$total = -(float) $existing;
}
if ($total > 0) {
$items['配件补发扣款'] = ['bill' => null, 'self' => -$total, 'sort' => 9000];
}
}
/**
* 这张对账单分到的附加费,按费用项目合计(快递开的金额,自算先按同额,不逐单核对)。
* 合并账单里的附加费按单号的快递名称1 归到对应分组;查不到的归文件所属的那张对账单。
*
* @return array<string,float>
*/
private function surchargeItems(int $statementId): array
{
$db = self::db();
$fileIds = $db->table('courier_bill_lines')->where('statement_id', $statementId)->distinct()->pluck('file_id')
->merge($db->table('courier_bill_files')->where('statement_id', $statementId)->pluck('id'))
->map(static fn ($id): int => (int) $id)->unique()->values()->all();
if ($fileIds === []) {
return [];
}
$result = [];
$primaryIds = $db->table('courier_bill_files')->whereIn('id', $fileIds)->pluck('statement_id', 'id');
foreach ($primaryIds as $fileId => $primaryId) {
$primary = (int) $primaryId;
$rows = $db->table('courier_bill_surcharges')->where('file_id', $fileId);
if (! (clone $rows)->exists()) {
continue;
}
$shared = $db->table('courier_bill_lines')->where('file_id', $fileId)->distinct()->pluck('statement_id')
->map(static fn ($id): int => (int) $id)->push($primary)->filter()->unique()->values()->all();
$names = [];
if (count($shared) > 1) {
foreach ($db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
->whereIn('s.id', $shared)->orderBy('s.id')->get(['s.id', 'g.express_names']) as $statement) {
foreach ((array) json_decode((string) $statement->express_names, true) as $name) {
$names[trim((string) $name)] ??= (int) $statement->id;
}
}
}
$rows->chunkById(500, function ($chunk) use ($names, $primary, $statementId, &$result): void {
$shipping = $names === [] ? [] : $this->shipping->summaries($chunk->pluck('waybill_no')->filter()->all());
foreach ($chunk as $row) {
$express = $shipping[strtoupper((string) $row->waybill_no)]['express_name'] ?? '';
if (($names[$express] ?? $primary) !== $statementId) {
continue;
}
$item = preg_replace('/\s+/u', '', (string) $row->item) ?? '';
$result[$item] = ($result[$item] ?? 0) + (float) $row->amount;
}
});
}
return array_map(static fn (float $v): float => round($v, 4), $result);
}
/** 运费差异原因(导出「对账」用):重量差 / 价格差 / 系统未核算;一致的为 null。 */
public static function diffReason(string $category, mixed $billWeight, mixed $chargeWeight): ?string
{
return match ($category) {
Category::UNCALCULATED => '系统未核算',
Category::DIFF => $billWeight !== null && $chargeWeight !== null && round(abs((float) $billWeight - (float) $chargeWeight), 4) > 0.005 ? '重量差' : '价格差',
default => null,
};
}
}