549 lines
26 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 Carbon\CarbonImmutable;
use Generator;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use RuntimeException;
/**
* 补记账:记账扣过的单,快递后来退回了,在后面的账期把多扣的补回去。
*
* - 补哪几个月:对账分组里设(不补 / 补上月 / 补前两个月),没设就按上月小汇总里的补记账类目识别
* (「补9月记账」「补8月记账」→ 补前两个月;「2026.8-9月记账补款」→ 补前两个月;「补记账」「9月记账补款」→ 补上月)。最多补两个月,超期不补。
* - 当时扣的:记账明细里那个扣款月份这单的「结算记账」合计。
* - 现在应扣:优先采用人工复核;否则按原未退回行的退回匹配和原因自动计算,资料缺失先不补。
* - 本期补款 = 当时扣的 − 现在应扣;补记账台账里补过的单不再补。
* - 对账单确认时,这期补的单记进补记账台账;取消确认就撤掉。
*/
final class Rebooks
{
/** 记账明细的数据集(快递应付 → 记账明细)。 */
public const BOOKKEEPING_DATASET = 'courier:bookkeeping-details';
public const MAX_MONTHS = 2;
public const RULES = [0 => '不补', 1 => '补上月', 2 => '补前两个月'];
private ?bool $hasMonthIndex = null;
public static function db(): ConnectionInterface
{
return CourierBillMatcher::db();
}
/**
* 小汇总里补记账类目(已顺延到本月)要补几个月:类目里提到的扣款月份离本月最远的那个;没写月份的算补上月。0 = 小汇总里没有补记账。
*
* @param list<string>|null $labels
*/
public static function monthsFromLabels(?array $labels, string $month): int
{
$current = (int) substr($month, 5, 2);
$result = 0;
foreach ($labels ?? [] as $label) {
$label = SummaryTemplate::normalize((string) $label);
if (! self::isRebookLabel($label)) {
continue;
}
$mentioned = self::monthsIn($label);
if ($mentioned === []) {
$result = max($result, 1);
continue;
}
foreach ($mentioned as $m) {
$lag = ($current - $m + 12) % 12;
if ($lag >= 1) {
$result = max($result, min($lag, self::MAX_MONTHS));
}
}
}
return $result;
}
/** 是不是补记账类目:「补9月记账」「2026.8-9月记账补款」「补记账」「9月记账补款」。 */
public static function isRebookLabel(string $label): bool
{
$label = SummaryTemplate::normalize($label);
return str_contains($label, '记账') && (str_starts_with($label, '补') || str_contains($label, '记账补'));
}
/** 类目里写到的月份(「2026.8-9月」→ 8、9)。 @return list<int> */
public static function monthsIn(string $label): array
{
$months = [];
preg_match_all('/(?:\d{4}[.年])?(\d{1,2})(?:-(?:\d{4}[.年])?(\d{1,2}))?月/u', $label, $matches, PREG_SET_ORDER);
foreach ($matches as $m) {
$a = (int) $m[1];
$b = isset($m[2]) && $m[2] !== '' ? (int) $m[2] : $a;
if ($a < 1 || $a > 12 || $b < 1 || $b > 12) {
continue;
}
for ($i = $a, $n = 0; $n < 12; $i = $i % 12 + 1, $n++) {
$months[] = $i;
if ($i === $b) {
break;
}
}
}
return array_values(array_unique($months));
}
/** 小汇总类目是不是这个扣款月份的补记账行:写了这个月、或范围里含这个月、或没写月份。 */
public static function labelCovers(string $label, int $deductMonth): bool
{
if (! self::isRebookLabel($label)) {
return false;
}
$months = self::monthsIn(SummaryTemplate::normalize($label));
return $months === [] || in_array($deductMonth, $months, true);
}
/**
* 这家这个月补几个月。
*
* @param list<string>|null $template 上月小汇总类目(已顺延)
* @return array{months:int,source:string}
*/
public static function rule(object $group, string $month, ?array $template): array
{
if (isset($group->rebook_months) && $group->rebook_months !== null && $group->rebook_months !== '') {
return ['months' => min(max((int) $group->rebook_months, 0), self::MAX_MONTHS), 'source' => 'group'];
}
return ['months' => self::monthsFromLabels($template, $month), 'source' => 'summary'];
}
/** 要补的扣款月份:本月往前 1..n 个月。 @return list<string> */
public static function window(string $month, int $months): array
{
$base = CarbonImmutable::createFromFormat('Y-m-d', $month . '-01');
$result = [];
for ($i = min($months, self::MAX_MONTHS); $i >= 1; $i--) {
$result[] = $base->subMonthsNoOverflow($i)->format('Y-m');
}
return $result;
}
/**
* 一张对账单的补记账明细(含资料缺失、已经补过的,金额为 0 的不补)。
*
* @return array{months:int,source:string,window:list<string>,rows:list<array<string,mixed>>}
*/
public function forStatement(int $statementId, ?array $template = null): array
{
$db = self::db();
$statement = $db->table('courier_bill_statements')->find($statementId);
if ($statement === null) {
throw new RuntimeException('对账单不存在。');
}
if ($statement->status === 'confirmed') {
return $this->confirmedPlan($statement);
}
$group = $db->table('courier_bill_groups')->find($statement->group_id);
$template ??= app(CourierBillMatcher::class)->templateFor($statementId);
$rule = self::rule($group, (string) $statement->bill_month, $template);
$window = self::window((string) $statement->bill_month, $rule['months']);
$names = array_values(array_filter(array_map('trim', (array) json_decode((string) $group->express_names, true))));
return $rule + ['window' => $window, 'rows' => $window === [] || $names === []
? [] : $this->rows($names, $window, (string) $statement->bill_month, $statementId)];
}
/** 已确认账单只读确认时记录,不随复核、分组或原记账明细变化。 */
private function confirmedPlan(object $statement): array
{
$rows = [];
foreach (self::db()->table('courier_bill_rebooks')->where('statement_id', $statement->id)
->orderBy('deduct_month')->orderBy('waybill_no')->cursor() as $record) {
$info = json_decode((string) $record->details, true) ?: [];
$rows[] = ['deduct_month' => $record->deduct_month, 'waybill' => $record->waybill_no,
'carrier' => $info['carrier'] ?? '', 'deducted' => (float) $record->deducted,
'refunded' => null, 'current' => (float) $record->current, 'amount' => (float) $record->amount,
'status' => '本期补款', 'info' => $info];
}
$window = array_values(array_unique(array_column($rows, 'deduct_month')));
$months = $window === [] ? 0 : min(self::MAX_MONTHS, (int) CarbonImmutable::parse($window[0] . '-01')
->diffInMonths(CarbonImmutable::parse($statement->bill_month . '-01')));
return ['months' => $months, 'source' => 'confirmed', 'window' => $window, 'rows' => $rows];
}
/**
* 这家的扣款单:按单号 + 扣款月份合计「结算记账」,带上已补、复核和本期补款。
*
* @param list<string> $names 快递名称1
* @param list<string> $window 扣款月份
* @return list<array<string,mixed>>
*/
public function rows(array $names, array $window, string $month, ?int $statementId = null): array
{
$names = array_flip($names);
$deductions = [];
$sourceRows = [];
foreach ($this->bookkeeping($window) as $row) {
$carrier = trim((string) ($row['carrier'] ?? ''));
if (! isset($names[$carrier])) {
continue;
}
$sourceRows[] = $row;
}
$sourceRows = app(RebookReturns::class)->annotate($sourceRows);
foreach ($sourceRows as $row) {
$carrier = trim((string) ($row['carrier'] ?? ''));
$waybill = Waybill::normalize((string) (($row['tracking_no_clean'] ?? '') ?: ($row['tracking_no'] ?? '')));
if ($waybill === null) {
continue;
}
$key = $waybill . '|' . $row['summary_month'];
$deductions[$key] ??= ['deduct_month' => (string) $row['summary_month'], 'waybill' => $waybill, 'carrier' => $carrier,
'deducted' => '0', 'info' => $row, 'sources' => []];
$deductions[$key]['sources'][] = $row;
$deductions[$key]['deducted'] = bcadd($deductions[$key]['deducted'], (string) (($row['settle_bookkeeping'] ?? '') ?: '0'), 4);
}
if ($deductions === []) {
return [];
}
$waybills = array_values(array_unique(array_column($deductions, 'waybill')));
$refunded = [];
$reviews = [];
foreach (array_chunk($waybills, 1000) as $chunk) {
foreach (self::db()->table('courier_bill_rebooks')->whereIn('waybill_no', $chunk)->whereIn('deduct_month', $window)
->when($statementId !== null, fn ($q) => $q->where(fn ($q) => $q->whereNull('statement_id')->orWhere('statement_id', '<>', $statementId)))
->get(['waybill_no', 'deduct_month', 'refund_month', 'amount']) as $r) {
$k = strtoupper($r->waybill_no) . '|' . $r->deduct_month;
$refunded[$k] = ['amount' => (float) ($refunded[$k]['amount'] ?? 0) + (float) $r->amount,
'month' => min($refunded[$k]['month'] ?? $r->refund_month, $r->refund_month)];
}
foreach (self::db()->table('courier_bill_rebook_reviews')->whereIn('waybill_no', $chunk)->whereIn('deduct_month', $window)
->get(['waybill_no', 'deduct_month', 'current_amount']) as $r) {
$reviews[strtoupper($r->waybill_no) . '|' . $r->deduct_month] = (float) $r->current_amount;
}
}
$rows = [];
foreach ($deductions as $key => $d) {
$k = strtoupper($d['waybill']) . '|' . $d['deduct_month'];
$deducted = round((float) $d['deducted'], 2);
$current = $reviews[$k] ?? null;
$automatic = false;
$missingData = false;
foreach ($d['sources'] as $source) {
$missingData = $missingData || str_contains((string) ($source['_return_status'] ?? ''), '缺失');
}
if ($current === null) {
$current = self::returnedAmount($d['sources']);
$automatic = $current !== null;
}
$done = $refunded[$k] ?? null;
[$status, $amount] = match (true) {
$done !== null => ['已补(' . $done['month'] . ')', 0.0],
$deducted <= 0 => ['没扣', 0.0],
$current === null && $missingData => ['资料缺失待核对', 0.0],
$current === null => ['无新增退回,不补', 0.0],
$current >= $deducted => ['仍应扣,不补', 0.0],
default => ['本期补款', round($deducted - $current, 2)],
};
$d['info']['_rebook_sources'] = $d['sources'];
$d['info']['_automatic_current'] = $automatic;
$rows[] = ['deduct_month' => $d['deduct_month'], 'waybill' => $d['waybill'], 'carrier' => $d['carrier'],
'deducted' => $deducted, 'refunded' => $done === null ? null : round($done['amount'], 2), 'current' => $current,
'amount' => $amount, 'status' => $status, 'info' => $d['info']];
}
usort($rows, static fn (array $a, array $b): int => [$a['deduct_month'], $a['waybill']] <=> [$b['deduct_month'], $b['waybill']]);
return $rows;
}
/** 只重算有退回证据的原未退回行;同单其他行沿用原应扣,缺少任一行金额则整单暂缓。 */
private static function returnedAmount(array $sources): ?float
{
$matched = false;
$amount = '0';
foreach ($sources as $source) {
if (str_contains((string) ($source['_return_status'] ?? ''), '缺失')) {
return null;
}
$matched = $matched || isset($source['_return_current']);
$amount = bcadd($amount, (string) ($source['_return_current'] ?? (($source['settle_bookkeeping'] ?? '') ?: '0')), 4);
}
return $matched ? round((float) $amount, 2) : null;
}
/** 页面、导出共用自动补款金额;人工填写的小汇总不覆盖,已确认账单不重算。 */
public function summaryItems(int $statementId, iterable $items, ?array $plan = null): \Illuminate\Support\Collection
{
$items = collect($items);
$plan ??= $this->forStatement($statementId);
if ($plan['source'] === 'confirmed') return $items;
$automaticMonths = [];
foreach ($plan['rows'] as $row) {
if ($row['info']['_automatic_current'] ?? false) $automaticMonths[$row['deduct_month']] = true;
}
if ($automaticMonths === []) return $items;
$totals = self::totals($plan['rows']);
$allocated = [];
$affected = [];
foreach ($plan['window'] as $month) {
$item = $items->first(fn ($item) => SummaryTemplate::normalize($item->label) === self::label($month))
?? $items->first(fn ($item) => self::labelCovers($item->label, (int) substr($month, 5, 2)));
if ($item === null || $item->manual) continue;
$allocated[$item->id] = round(($allocated[$item->id] ?? 0) + ($totals[$month] ?? 0), 2);
if (isset($automaticMonths[$month])) $affected[$item->id] = true;
}
return $items->map(function ($item) use ($allocated, $affected) {
$copy = clone $item;
if (isset($affected[$item->id])) $copy->self_amount = $allocated[$item->id];
return $copy;
});
}
/** 各扣款月份本期补款合计(只算要补的)。 @param list<array<string,mixed>> $rows @return array<string,float> */
public static function totals(array $rows): array
{
$totals = [];
foreach ($rows as $row) {
if ($row['amount'] > 0) {
$totals[$row['deduct_month']] = round(($totals[$row['deduct_month']] ?? 0) + $row['amount'], 2);
}
}
ksort($totals);
return $totals;
}
/** 小汇总里补记账那一行的名字:「补9月记账」。 */
public static function label(string $deductMonth): string
{
return '补' . (int) substr($deductMonth, 5, 2) . '月记账';
}
/** 导出子表名:一个月「补9月记账」,两个月「2026.9-10月记账补款」。 @param list<string> $window */
public static function sheetName(array $window): string
{
if (count($window) <= 1) {
return self::label($window[0] ?? '');
}
$first = $window[0];
$last = $window[count($window) - 1];
return substr($first, 0, 4) . '.' . (int) substr($first, 5, 2) . '-' . (substr($last, 0, 4) !== substr($first, 0, 4) ? substr($last, 0, 4) . '.' : '')
. (int) substr($last, 5, 2) . '月记账补款';
}
/** 对账单确认:这期补的单记进补记账台账。 */
public function record(int $statementId): int
{
$statement = self::db()->table('courier_bill_statements')->find($statementId);
$plan = $this->forStatement($statementId);
$items = self::db()->table('courier_bill_summary_items')->where('statement_id', $statementId)->orderBy('sort')->get();
foreach ($this->summaryItems($statementId, $items, $plan) as $item) {
if ($item->self_amount !== $items->firstWhere('id', $item->id)->self_amount) {
self::db()->table('courier_bill_summary_items')->where('id', $item->id)->update(['self_amount' => $item->self_amount]);
}
}
$this->assertSummaryMatches($statementId, $plan['rows']);
$now = now();
$buffer = [];
foreach ($plan['rows'] as $row) {
if ($row['amount'] <= 0) {
continue;
}
$buffer[] = ['group_id' => $statement->group_id, 'waybill_no' => $row['waybill'], 'deduct_month' => $row['deduct_month'],
'refund_month' => $statement->bill_month, 'deducted' => $row['deducted'], 'current' => $row['current'],
'amount' => $row['amount'], 'statement_id' => $statementId, 'source' => 'statement',
'details' => json_encode($row['info'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), 'created_at' => $now];
}
$inserted = 0;
foreach (array_chunk($buffer, 500) as $chunk) {
$count = self::db()->table('courier_bill_rebooks')->insertOrIgnore($chunk);
if ($count !== count($chunk)) {
throw new RuntimeException('补记账状态已变化,存在已经补过的单号,请重新匹配核对后确认。');
}
$inserted += $count;
}
return $inserted;
}
/** 手工回填或复核变化不能让小汇总金额与逐单补款记录不一致。 */
private function assertSummaryMatches(int $statementId, array $rows): void
{
$actual = [];
foreach (self::db()->table('courier_bill_summary_items')->where('statement_id', $statementId)
->orderBy('sort')->get(['label', 'self_amount']) as $item) {
$label = SummaryTemplate::normalize($item->label);
if (self::isRebookLabel($label)) {
$actual[$label] = round(($actual[$label] ?? 0) + (float) $item->self_amount, 2);
}
}
$expected = [];
foreach (self::totals($rows) as $month => $amount) {
$label = self::label($month);
if (! array_key_exists($label, $actual)) {
foreach (array_keys($actual) as $candidate) {
if (self::labelCovers($candidate, (int) substr($month, 5, 2))) {
$label = $candidate;
break;
}
}
}
$expected[$label] = round(($expected[$label] ?? 0) + $amount, 2);
}
foreach (array_unique([...array_keys($actual), ...array_keys($expected)]) as $label) {
if (bccomp((string) ($actual[$label] ?? 0), (string) ($expected[$label] ?? 0), 2) !== 0) {
throw new RuntimeException('补记账小汇总与逐单复核金额不一致,请更新复核记账并重新匹配核对后确认。');
}
}
}
public function forget(int $statementId): void
{
self::db()->table('courier_bill_rebooks')->where('statement_id', $statementId)->delete();
}
/**
* 导入已经补过的记录(系统上线前手工补的):单号、扣款月份、补款账期、补款金额,可带「对账分组」。
*
* @return array{rows:int,inserted:int,rejected:int}
*/
public function importRefunds(string $path, string $extension): array
{
$groups = collect(app(CourierBillStore::class)->groups())->keyBy(static fn ($g): string => (string) $g->name);
return $this->importSheet($path, $extension, [
'waybill' => ['单号', '快递单号', '物流单号', '运单号'], 'deduct' => ['扣款月份', '记账月份', '月份'],
'refund' => ['补款账期', '补款月份'], 'amount' => ['补款金额', '需补款', '补款'], 'group' => ['对账分组', '快递名称', '账单快递名称'],
], ['waybill', 'deduct', 'refund', 'amount'], function (array $v) use ($groups): ?array {
$amount = BillParser::number($v['amount'] ?? null);
if ($amount === null || ($refund = CourierBillStore::month((string) ($v['refund'] ?? ''))) === null) {
return null;
}
return ['table' => 'courier_bill_rebooks', 'row' => ['group_id' => $groups->get(trim((string) ($v['group'] ?? '')))?->id,
'refund_month' => $refund, 'amount' => round($amount, 2), 'deducted' => null, 'current' => null,
'statement_id' => null, 'source' => 'import', 'created_at' => now()]];
});
}
/**
* 导入复核记账(这单现在应扣多少):单号、扣款月份、现应扣。同一单号同一扣款月份再导就覆盖。
*
* @return array{rows:int,inserted:int,rejected:int}
*/
public function importReviews(string $path, string $extension, string $sourceName): array
{
return $this->importSheet($path, $extension, [
'waybill' => ['单号', '快递单号', '物流单号', '运单号'], 'deduct' => ['扣款月份', '记账月份', '月份'],
'current' => ['现应扣', '现在应扣', '复核记账', '应扣金额'],
], ['waybill', 'deduct', 'current'], function (array $v) use ($sourceName): ?array {
$current = BillParser::number($v['current'] ?? null);
if ($current === null) {
return null;
}
return ['table' => 'courier_bill_rebook_reviews', 'upsert' => ['current_amount', 'source_name', 'updated_at'],
'row' => ['current_amount' => round($current, 2), 'source_name' => mb_substr($sourceName, 0, 255), 'updated_at' => now()]];
});
}
/**
* @param array<string,list<string>> $columns
* @param list<string> $required
* @param callable(array<string,mixed>):?array{table:string,row:array<string,mixed>,upsert?:list<string>} $build
* @return array{rows:int,inserted:int,rejected:int}
*/
private function importSheet(string $path, string $extension, array $columns, array $required, callable $build): array
{
$reader = new BillWorkbookReader();
$rows = $inserted = $rejected = 0;
$buffers = [];
$flush = function () use (&$buffers, &$inserted): void {
foreach ($buffers as $table => [$upsert, $records]) {
foreach (array_chunk(array_values($records), 500) as $chunk) {
$inserted += $upsert === null ? self::db()->table($table)->insertOrIgnore($chunk)
: self::db()->table($table)->upsert($chunk, ['waybill_no', 'deduct_month'], $upsert);
}
}
$buffers = [];
};
foreach ($reader->sheets($path, $extension) as $sheetRows) {
$index = null;
foreach ($sheetRows as $row) {
if ($index === null) {
$header = array_map(static fn ($v): string => preg_replace('/\s+/u', '', (string) $v) ?? '', $row);
$found = [];
foreach ($columns as $field => $names) {
foreach ($names as $name) {
if (($i = array_search($name, $header, true)) !== false) {
$found[$field] = $i;
break;
}
}
}
if (array_diff($required, array_keys($found)) !== []) {
throw new RuntimeException('表头须含' . implode('', array_map(static fn (string $f): string => '「' . $columns[$f][0] . '」', $required)) . '。');
}
$index = $found;
continue;
}
$values = [];
foreach ($index as $field => $i) {
$values[$field] = $row[$i] ?? null;
}
if (trim((string) ($values['waybill'] ?? '')) === '' && trim((string) ($values['deduct'] ?? '')) === '') {
continue;
}
$rows++;
$waybill = Waybill::normalize((string) ($values['waybill'] ?? ''));
$deduct = CourierBillStore::month((string) ($values['deduct'] ?? ''));
$built = $waybill === null || $deduct === null ? null : $build($values);
if ($built === null) {
$rejected++;
continue;
}
$record = ['waybill_no' => strtoupper($waybill), 'deduct_month' => $deduct] + $built['row'];
$key = $record['waybill_no'] . '|' . $deduct . '|' . ($record['refund_month'] ?? '');
$buffers[$built['table']] ??= [$built['upsert'] ?? null, []];
$buffers[$built['table']][1][$key] = $record; // 同一文件里重复的后一行为准
if (count($buffers[$built['table']][1]) >= 500) {
$flush();
}
}
break; // 只读第一张表
}
$flush();
return ['rows' => $rows, 'inserted' => $inserted, 'rejected' => $rejected];
}
/**
* 记账明细里这几个扣款月份的行。
*
* @param list<string> $months
* @return Generator<int,array<string,mixed>>
*/
private function bookkeeping(array $months): Generator
{
$connection = DB::connection(config('database.supplier_payable_maintenance_connection'));
$this->hasMonthIndex ??= Schema::connection($connection->getName())->hasColumn('supplier_payable_overrides', 'summary_month_key');
$query = $connection->table('supplier_payable_overrides')->select(['id', 'values'])
->where('company_id', (int) (company_id() ?: 1))->where('dataset', self::BOOKKEEPING_DATASET)
->whereIn($this->hasMonthIndex ? 'summary_month_key' : 'values->summary_month', $months);
// 保留 rows() 的 trim 后精确匹配,避免 SQL 原值筛选漏掉带首尾空白的快递名称。
foreach ($query->lazyById(500) as $record) {
$values = json_decode((string) $record->values, true);
if (is_array($values)) {
yield $values;
}
}
}
}