CaiWuXiTong/app/Support/CourierBills/CourierBillStore.php

1031 lines
48 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\Database\ConnectionInterface;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RuntimeException;
use Throwable;
use ZipArchive;
/**
* 对账分组、账单上传入库、确认结算与结算台账。
*/
final class CourierBillStore
{
public const EXTENSIONS = ['xlsx', 'xls', 'csv', 'zip'];
private const DISK = 'local';
public function __construct(
private readonly BillParser $parser,
private readonly CourierBillMatcher $matcher,
private readonly ShippingLookup $shipping,
) {}
public function db(): ConnectionInterface
{
return CourierBillMatcher::db();
}
/** @return list<object> 分组,express_names 已解码成数组 */
public function groups(): array
{
return $this->db()->table('courier_bill_groups')->orderBy('name')->get()->map(static function ($group) {
$group->express_names = array_values((array) json_decode((string) $group->express_names, true));
return $group;
})->all();
}
/** @param array{name:string,express_names:list<string>,summary_carrier:?string,owner:?string,keywords:?string,waybill_header:?string,amount_header:?string,weight_header:?string} $data */
public function saveGroup(?int $id, array $data): int
{
$values = [
'name' => trim($data['name']),
'express_names' => json_encode(array_values(array_unique(array_filter(array_map('trim', $data['express_names'])))), JSON_UNESCAPED_UNICODE),
'summary_carrier' => self::blank($data['summary_carrier'] ?? null),
'bundle' => self::blank($data['bundle'] ?? null),
'owner' => self::blank($data['owner'] ?? null),
'keywords' => self::blank($data['keywords'] ?? null),
'waybill_header' => self::blank($data['waybill_header'] ?? null),
'amount_header' => self::blank($data['amount_header'] ?? null),
'weight_header' => self::blank($data['weight_header'] ?? null),
'updated_at' => now(),
];
if ($id === null) {
return (int) $this->db()->table('courier_bill_groups')->insertGetId($values + ['created_at' => now()]);
}
$this->db()->table('courier_bill_groups')->where('id', $id)->update($values);
return $id;
}
/**
* 按文件名找分组:分组名称、承运商、快递名称1、文件名关键字,以及它们「-」前面的部分(如「河北中通-江三」的「河北中通」),
* 取文件名里命中的最长一个;最长的只属于一个分组才算识别成功,否则留给人选。
*
* @param list<object> $groups
*/
public static function identify(string $fileName, array $groups): ?object
{
$scores = self::scores($fileName, $groups);
if ($scores === []) {
return null;
}
$best = max($scores);
$hits = array_keys($scores, $best, true);
return count($hits) === 1 ? collect($groups)->firstWhere('id', $hits[0]) : null;
}
/**
* 文件名里出现的所有分组(不止最长的那个),用来决定一份合并账单可以拆进哪些分组。
*
* @param list<object> $groups
* @return list<int>
*/
public static function namedGroupIds(string $fileName, array $groups): array
{
return array_map('intval', array_keys(self::scores($fileName, $groups)));
}
/**
* @param list<object> $groups
* @return array<int,int> 分组 id => 文件名里命中的最长名字的字数
*/
private static function scores(string $fileName, array $groups): array
{
$name = preg_replace('/\s+/u', '', pathinfo($fileName, PATHINFO_FILENAME)) ?? '';
$full = [];
foreach ($groups as $group) {
$full[$group->id] = self::needles($group);
}
$scores = [];
foreach ($groups as $group) {
$candidates = $full[$group->id];
// 「-」前面的部分只在不和别的分组撞名时才用(「常州圆通」同时是「常州圆通其他」的开头,就不能代表「常州圆通-上楼」)。
foreach ($full[$group->id] as $needle) {
$base = preg_split('/[--—((]/u', $needle)[0] ?? '';
if ($base === $needle || mb_strlen($base) < 3) {
continue;
}
$clash = false;
foreach ($full as $id => $others) {
foreach ($id === $group->id ? [] : $others as $other) {
if (str_contains($other, $base)) {
$clash = true;
break 2;
}
}
}
if (! $clash) {
$candidates[] = $base;
}
}
$length = 0;
foreach ($candidates as $needle) {
if (mb_strlen($needle) > $length && str_contains($name, $needle)) {
$length = mb_strlen($needle);
}
}
if ($length > 0) {
$scores[(int) $group->id] = $length;
}
}
return $scores;
}
/** @return list<string> 分组名称、承运商、快递名称1、文件名关键字(去空白,至少 2 个字) */
private static function needles(object $group): array
{
$needles = [];
foreach ([$group->name, (string) $group->summary_carrier, ...$group->express_names,
...array_map('trim', preg_split('/[,,、]/u', (string) $group->keywords) ?: [])] as $needle) {
$needle = preg_replace('/\s+/u', '', (string) $needle) ?? '';
if (mb_strlen($needle) >= 2) {
$needles[] = $needle;
}
}
return array_values(array_unique($needles));
}
/**
* 从快递应付汇总生成分组:每个承运商(承运中、或本月有快递提供金额的)一个分组,
* 分组名称 = 承运商 = 快递名称1,负责人取汇总表「负责人」。已有分组(同名或归到同一承运商)的跳过。
*
* @param list<array{cells:array<string,mixed>}> $summaryRows
* @return array{created:int,skipped:int}
*/
public function groupsFromSummary(array $summaryRows): array
{
$existing = [];
foreach ($this->groups() as $group) {
$existing[$group->name] = true;
$existing[(string) ($group->summary_carrier ?: $group->name)] = true;
}
$created = 0;
$skipped = 0;
foreach ($summaryRows as $row) {
$cells = $row['cells'];
$carrier = trim((string) ($cells['H'] ?? ''));
$active = trim((string) ($cells['E'] ?? '')) === '承运' || abs((float) ($cells['K'] ?? 0)) > 0.004;
if ($carrier === '' || ! $active || isset($existing[$carrier])) {
$skipped++;
continue;
}
$owner = trim((string) ($cells['D'] ?? ''));
$this->saveGroup(null, ['name' => $carrier, 'express_names' => [$carrier], 'summary_carrier' => $carrier,
'owner' => in_array($owner, ['', '/', '不合作'], true) ? null : $owner]);
$existing[$carrier] = true;
$created++;
}
return ['created' => $created, 'skipped' => $skipped];
}
/** 分组导入/导出的表头(导出的文件改完可以直接再导入)。 */
public const GROUP_HEADERS = ['分组名称', '快递名称1', '归到承运商', '合并账单', '负责人', '文件名关键字', '单号列', '运费列', '重量列'];
/**
* 导入分组:按「分组名称」新增或覆盖。快递名称1 多个用顿号、逗号或换行分隔。
*
* @return array{created:int,updated:int,skipped:int}
*/
public function importGroups(string $path, string $extension): array
{
return $this->db()->transaction(fn (): array => $this->readGroups($path, $extension), 3);
}
private function readGroups(string $path, string $extension): array
{
$existing = collect($this->groups())->keyBy('name');
$created = 0;
$updated = 0;
$skipped = 0;
foreach ((new BillWorkbookReader())->sheets($path, $extension) as $rows) {
$columns = null;
foreach ($rows as $row) {
$cells = array_map(static fn ($v): string => trim((string) $v), $row);
if ($columns === null) {
$header = array_map(static fn ($v): string => preg_replace('/\s+/u', '', $v) ?? '', $cells);
if (in_array('分组名称', $header, true)) {
$columns = array_flip(array_intersect($header, self::GROUP_HEADERS));
}
continue;
}
$value = static fn (string $key): string => isset($columns[$key]) ? ($cells[$columns[$key]] ?? '') : '';
$name = $value('分组名称');
$names = preg_split('/[\r\n,,、;;]+/u', $value('快递名称1')) ?: [];
if ($name === '') {
continue;
}
$names = array_values(array_filter(array_map('trim', $names)));
if ($names === []) {
$names = [$value('归到承运商') ?: $name];
}
$old = $existing->get($name);
$bundle = isset($columns['合并账单']) ? $value('合并账单') : ($old->bundle ?? null);
$id = $this->saveGroup($old?->id, ['name' => $name, 'express_names' => $names, 'summary_carrier' => $value('归到承运商'),
'bundle' => $bundle, 'owner' => $value('负责人'), 'keywords' => $value('文件名关键字'), 'waybill_header' => $value('单号列'),
'amount_header' => $value('运费列'), 'weight_header' => $value('重量列')]);
$existing->put($name, (object) ['id' => $id, 'bundle' => $bundle]);
$old === null ? $created++ : $updated++;
}
if ($columns !== null) {
break;
}
}
if ($created + $updated === 0) {
throw new RuntimeException('没有读到分组:表头须含「分组名称」「快递名称1」,可带「归到承运商」「负责人」「文件名关键字」「单号列」「运费列」「重量列」。');
}
return ['created' => $created, 'updated' => $updated, 'skipped' => $skipped];
}
/** 删除分组(只允许还没有对账单的分组)。 */
public function deleteGroup(int $id): void
{
if ($this->db()->table('courier_bill_statements')->where('group_id', $id)->exists()) {
throw new RuntimeException('这个分组已经有对账单,不能删除;可以改名或改快递名称1。');
}
if ($this->db()->table('courier_bill_ledger')->where('group_id', $id)->exists()
|| $this->db()->table('courier_bill_files')->where('group_id', $id)->exists()) {
throw new RuntimeException('这个分组关联了结算台账或账单文件,不能删除。');
}
$this->db()->table('courier_bill_groups')->where('id', $id)->delete();
}
/** 把一个快递名称1 加进分组。 */
public function addExpressName(int $groupId, string $expressName): void
{
$group = collect($this->groups())->firstWhere('id', $groupId);
if ($group === null) {
throw new RuntimeException('分组不存在。');
}
$this->saveGroup($groupId, ['name' => $group->name, 'express_names' => [...$group->express_names, trim($expressName)],
'summary_carrier' => $group->summary_carrier, 'bundle' => $group->bundle, 'owner' => $group->owner, 'keywords' => $group->keywords,
'waybill_header' => $group->waybill_header, 'amount_header' => $group->amount_header, 'weight_header' => $group->weight_header]);
}
/**
* 发货数据里该月有发货、但还没归到任何分组的快递名称1,附「最像的分组」建议(共同前缀最长的)。
*
* @param array<string,int> $counts 快递名称1 => 发货行数
* @return list<array{name:string,rows:int,suggest:?int}>
*/
public function unassignedExpressNames(array $counts): array
{
$groups = $this->groups();
$assigned = [];
foreach ($groups as $group) {
foreach ($group->express_names as $name) {
$assigned[$name] = true;
}
}
$result = [];
foreach ($counts as $name => $rows) {
if (isset($assigned[$name])) {
continue;
}
$suggest = null;
$best = 1;
foreach ($groups as $group) {
foreach ([$group->name, ...$group->express_names] as $candidate) {
$length = self::commonPrefix((string) $name, (string) $candidate);
if ($length > $best) {
$best = $length;
$suggest = (int) $group->id;
}
}
}
$result[] = ['name' => (string) $name, 'rows' => $rows, 'suggest' => $suggest];
}
usort($result, static fn (array $a, array $b): int => $b['rows'] <=> $a['rows']);
return $result;
}
private static function commonPrefix(string $a, string $b): int
{
$a = mb_str_split($a);
$b = mb_str_split($b);
$n = 0;
while (isset($a[$n], $b[$n]) && $a[$n] === $b[$n]) {
$n++;
}
return $n;
}
/**
* 保存上传的文件(zip 展开成多个文件),能识别分组的直接读入并对账。
*
* 选了分组时第一个是主分组,其余是这份账单还可能包含的分组;没选就按文件名识别。
* 「合并账单」相同的分组、文件名里出现的分组也会自动算进去:账单行按发货数据的快递名称1 拆到各自分组。
*
* @param list<UploadedFile> $files
* @param list<int> $groupIds
* @return list<int> 文件记录 id
*/
public function upload(array $files, string $month, array $groupIds, string $user): array
{
$groups = $this->groups();
$ids = [];
foreach ($files as $file) {
$extension = strtolower($file->getClientOriginalExtension());
if ($extension === 'zip') {
foreach ($this->unzip($file->getRealPath()) as [$name, $path]) {
$ids[] = $this->register($name, $path, $month, $groupIds, $groups, $user);
}
continue;
}
$ids[] = $this->register($file->getClientOriginalName(), $file->getRealPath(), $month, $groupIds, $groups, $user);
}
foreach ($this->statementsOfFiles($ids) as $statementId) {
$this->matcher->match($statementId);
}
return $ids;
}
/** 给待选分组的文件指定分组,读入并对账。 */
public function assign(int $fileId, int $groupId): void
{
$file = $this->db()->table('courier_bill_files')->find($fileId);
if ($file === null || $file->status !== 'pending_group') {
throw new RuntimeException('这个文件不是待选分组状态。');
}
$group = collect($this->groups())->firstWhere('id', $groupId);
if ($group === null) {
throw new RuntimeException('分组不存在。');
}
$this->ingest($fileId, $group);
foreach ($this->statementsOfFiles([$fileId]) as $statementId) {
$this->matcher->match($statementId);
}
}
/** 删除一个已上传文件及其账单行(涉及的对账单都未确认时)。 */
public function deleteFile(int $fileId): void
{
$db = $this->db();
$file = $db->table('courier_bill_files')->find($fileId);
if ($file === null) {
return;
}
$statements = $this->statementsOfFiles([$fileId]);
if ($statements !== [] && $db->table('courier_bill_statements')->whereIn('id', $statements)->where('status', 'confirmed')->exists()) {
throw new RuntimeException('这个文件的账单行所在的对账单已确认结算,不能删除。');
}
$db->transaction(function () use ($db, $file): void {
$db->table('courier_bill_lines')->where('file_id', $file->id)->delete();
$db->table('courier_bill_files')->where('id', $file->id)->delete();
});
Storage::disk(self::DISK)->delete($file->stored_path);
foreach ($statements as $statementId) {
$this->refresh($statementId);
}
}
/**
* 这些文件的账单行落在哪些对账单(一份合并账单可能拆进好几张)。
*
* @param list<int> $fileIds
* @return list<int>
*/
public function statementsOfFiles(array $fileIds): array
{
if ($fileIds === []) {
return [];
}
$ids = $this->db()->table('courier_bill_lines')->whereIn('file_id', $fileIds)->distinct()->pluck('statement_id')
->merge($this->db()->table('courier_bill_files')->whereIn('id', $fileIds)->whereNotNull('statement_id')->pluck('statement_id'));
return $ids->map(static fn ($id): int => (int) $id)->unique()->values()->all();
}
/**
* @param list<int> $groupIds
* @param list<object> $groups
*/
private function register(string $name, string $path, string $month, array $groupIds, array $groups, string $user): int
{
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
$stored = 'courier-bills/' . $month . '/' . Str::uuid() . '.' . $extension;
Storage::disk(self::DISK)->put($stored, fopen($path, 'rb'));
$groupIds = array_values(array_unique(array_map('intval', $groupIds)));
$group = $groupIds !== []
? collect($groups)->firstWhere('id', $groupIds[0])
: self::identify($name, $groups);
$extra = array_values(array_diff(array_unique([...array_slice($groupIds, 1), ...self::namedGroupIds($name, $groups)]), [(int) ($group->id ?? 0)]));
$id = (int) $this->db()->table('courier_bill_files')->insertGetId([
'bill_month' => $month, 'original_name' => mb_substr($name, 0, 255), 'stored_path' => $stored,
'status' => 'pending_group', 'uploaded_by' => mb_substr($user, 0, 64), 'created_at' => now(), 'updated_at' => now(),
'extra_group_ids' => $extra === [] ? null : json_encode($extra),
'message' => $group === null ? '没有识别出是哪家快递,请选择分组' : null,
]);
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
$this->db()->table('courier_bill_files')->where('id', $id)->update(['status' => 'failed', 'message' => '不支持的文件类型']);
return $id;
}
if ($group !== null) {
$this->ingest($id, $group);
}
return $id;
}
/** 读文件、写账单行到主分组的对账单,再按快递名称1 拆到同一合并账单等可拆入的分组。 */
private function ingest(int $fileId, object $group, bool $reread = false): void
{
$db = $this->db();
$file = $db->table('courier_bill_files')->find($fileId);
$statement = $db->table('courier_bill_statements')->where('group_id', $group->id)->where('bill_month', $file->bill_month)->first();
if ($statement !== null && $statement->status === 'confirmed') {
$db->table('courier_bill_files')->where('id', $fileId)->update(['status' => 'failed', 'group_id' => $group->id,
'message' => '这家快递本月对账单已确认结算,先撤销确认再上传']);
return;
}
$statementId = (int) ($statement?->id ?? $db->table('courier_bill_statements')->insertGetId([
'group_id' => $group->id, 'bill_month' => $file->bill_month, 'status' => 'open', 'created_at' => now(), 'updated_at' => now(),
]));
$path = Storage::disk(self::DISK)->path($file->stored_path);
$extension = strtolower(pathinfo($file->stored_path, PATHINFO_EXTENSION));
$sheets = [];
$rejected = [];
$rejectedCount = 0;
$rows = 0;
$amount = 0.0;
$buffer = [];
$overlap = null;
try {
$split = $db->transaction(function () use ($db, $path, $extension, $group, $file, $fileId, $statementId, $reread, &$sheets, &$rejected, &$rejectedCount, &$rows, &$amount, &$buffer, &$overlap): string {
if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') {
throw new RuntimeException('这家快递本月对账单已确认结算,先撤销确认再上传。');
}
$previousLastId = $reread ? (int) $db->table('courier_bill_lines')->where('file_id', $fileId)->max('id') : null;
if (! $reread) {
$db->table('courier_bill_lines')->where('file_id', $fileId)->delete();
}
$overrides = ['waybill_header' => $group->waybill_header, 'amount_header' => $group->amount_header, 'weight_header' => $group->weight_header];
foreach ($this->parser->parse($path, $extension, $overrides) as $item) {
if ($item['type'] === 'sheet') {
$sheets[] = isset($item['skipped'])
? ['sheet' => $item['sheet'], 'skipped' => $item['skipped']]
: ['sheet' => $item['sheet'], 'header_row' => $item['header_row'], 'headers' => $item['headers'],
'waybill' => $item['waybill'], 'amount' => $item['amount'], 'weight' => $item['weight']];
continue;
}
if ($item['type'] === 'reject') {
$rejectedCount++;
if (count($rejected) < 50) {
$rejected[] = ['sheet' => $item['sheet'], 'row' => $item['row'], 'value' => $item['value'], 'reason' => $item['reason']];
}
continue;
}
$rows++;
$amount += (float) $item['amount'];
$buffer[] = [
'statement_id' => $statementId, 'file_id' => $fileId, 'sheet' => mb_substr($item['sheet'], 0, 64),
'row_no' => $item['row'], 'waybill_no' => $item['waybill'], 'bill_amount' => $item['amount'],
'bill_weight' => $item['weight'], 'raw' => json_encode($item['raw'], JSON_UNESCAPED_UNICODE),
];
if (count($buffer) >= 500) {
$this->insertLines($buffer, $previousLastId);
$buffer = [];
}
}
if ($buffer !== []) {
$this->insertLines($buffer, $previousLastId);
}
if ($reread && ! array_filter($sheets, static fn (array $s): bool => ! isset($s['skipped']))) {
throw new RuntimeException('没有找到含单号和运费列的工作表,已保留原账单。');
}
if ($reread) {
$db->table('courier_bill_lines')->where('file_id', $fileId)->where('id', '<=', $previousLastId)->delete();
}
$overlap = $this->overlap($fileId, (string) $file->bill_month, $reread);
if ($overlap !== null && $overlap[1] * 2 >= $overlap[2]) {
$db->table('courier_bill_lines')->where('file_id', $fileId)->delete();
return '';
}
return $this->split($fileId, $group, (string) $file->bill_month, $statementId, $reread);
});
} catch (Throwable $error) {
if ($reread) {
throw new RuntimeException('重新读取「' . $file->original_name . '」失败:' . $error->getMessage(), 0, $error);
}
report($error);
$db->table('courier_bill_files')->where('id', $fileId)->update([
'status' => 'failed', 'group_id' => $group->id, 'message' => mb_substr('读取失败:' . $error->getMessage(), 0, 255), 'updated_at' => now(),
]);
return;
}
if ($overlap !== null && $overlap[1] * 2 >= $overlap[2]) {
$db->table('courier_bill_files')->where('id', $fileId)->update([
'status' => 'failed', 'group_id' => $group->id, 'statement_id' => null, 'row_count' => 0, 'amount' => 0,
'message' => mb_substr('重复导入:和「' . $overlap[0] . '」有 ' . $overlap[1] . '/' . $overlap[2]
. ' 个单号相同(至少一半),这份没有读入,可以删掉。要换成新版本的账单,先删掉旧的那份再上传', 0, 255),
'updated_at' => now(),
]);
return;
}
$usable = array_filter($sheets, static fn (array $s): bool => ! isset($s['skipped']));
$notes = [];
if ($usable === []) {
$notes[] = '没有找到含单号和运费列的工作表';
}
if ($split !== '') {
$notes[] = $split;
}
if ($overlap !== null) {
$notes[] = $overlap[1] . ' 个单号在「' . $overlap[0] . '」里已经有了,请在对账明细中核对重复项';
}
if ($rejectedCount > 0) {
$notes[] = '有 ' . $rejectedCount . ' 行单号被拒收';
}
$db->table('courier_bill_files')->where('id', $fileId)->update([
'group_id' => $group->id, 'statement_id' => $statementId,
'status' => $usable === [] ? 'failed' : 'parsed',
'sheets' => json_encode($sheets, JSON_UNESCAPED_UNICODE),
'row_count' => $rows, 'amount' => round($amount, 2), 'rejected_count' => $rejectedCount,
'rejected_rows' => $rejected === [] ? null : json_encode($rejected, JSON_UNESCAPED_UNICODE),
'message' => $notes === [] ? null : mb_substr(implode(';', $notes), 0, 255),
'updated_at' => now(),
]);
}
/**
* 合并账单拆分:可拆入的分组 = 「合并账单」相同的分组 + 上传时额外选的 + 文件名里出现的。
* 单号在发货数据里的快递名称1 属于其中哪个分组,就把这一行挪到那个分组本月的对账单;
* 其余(发货数据里没有的、属于别的快递的)留在主分组,照常判「匹配不到」「快递不符」。
*
* 留在主分组、但在发货数据里属于别的快递的行,按快递名称1 汇总成提示:属于哪个分组(可能是新加进这张账单的快递),
* 或者还没有分组。
*
* @return string 拆分说明和提示,都没有时为空
*/
private function split(int $fileId, object $primary, string $month, int $primaryStatementId, bool $requireOpenTargets = false): string
{
$db = $this->db();
$groups = collect($this->groups());
$extra = array_map('intval', (array) json_decode((string) $db->table('courier_bill_files')->where('id', $fileId)->value('extra_group_ids'), true));
$bundle = trim((string) ($primary->bundle ?? ''));
$targets = $groups->filter(static fn ($g): bool => (int) $g->id !== (int) $primary->id
&& (in_array((int) $g->id, $extra, true) || ($bundle !== '' && trim((string) $g->bundle) === $bundle)));
$own = array_flip($groups->firstWhere('id', $primary->id)->express_names ?? []);
$byName = [];
foreach ($targets as $target) {
foreach ($target->express_names as $name) {
if (! isset($own[$name])) {
$byName[$name] ??= $target;
}
}
}
$owners = [];
foreach ($groups as $group) {
foreach ($group->express_names as $name) {
$owners[$name] ??= $group;
}
}
$lines = $db->table('courier_bill_lines')->where('file_id', $fileId)->where('statement_id', $primaryStatementId)->orderBy('id')->get(['id', 'waybill_no']);
$ship = $this->shipping->summaries($lines->pluck('waybill_no')->map(static fn ($w): string => strtoupper((string) $w))->unique()->values()->all());
$moves = [];
$strangers = [];
foreach ($lines as $line) {
$name = $ship[strtoupper((string) $line->waybill_no)]['express_name'] ?? null;
if ($name === null || isset($own[$name])) {
continue;
}
if (isset($byName[$name])) {
$moves[(int) $byName[$name]->id][] = (int) $line->id;
} else {
$strangers[$name] = ($strangers[$name] ?? 0) + 1;
}
}
$notes = [];
$kept = $lines->count();
foreach ($moves as $groupId => $ids) {
$target = $groups->firstWhere('id', $groupId);
$statement = $db->table('courier_bill_statements')->where('group_id', $groupId)->where('bill_month', $month)->lockForUpdate()->first();
if ($statement !== null && $statement->status === 'confirmed') {
if ($requireOpenTargets) {
throw new RuntimeException('「' . $target->name . '」本月已确认结算,撤销确认后才能重新拆分。');
}
$notes[] = $target->name . ' 本月已确认结算,' . count($ids) . ' 行未拆入';
continue;
}
$statementId = (int) ($statement?->id ?? $db->table('courier_bill_statements')->insertGetId([
'group_id' => $groupId, 'bill_month' => $month, 'status' => 'open', 'created_at' => now(), 'updated_at' => now(),
]));
foreach (array_chunk($ids, 500) as $chunk) {
$db->table('courier_bill_lines')->whereIn('id', $chunk)->update(['statement_id' => $statementId]);
}
$kept -= count($ids);
$notes[] = $target->name . ' ' . count($ids) . ' 行';
}
$parts = $kept < $lines->count()
? ['合并账单已拆分:' . $primary->name . ' ' . $kept . ' 行,' . implode(',', $notes)]
: $notes;
arsort($strangers);
$inGroups = [];
$noGroup = [];
foreach ($strangers as $name => $count) {
$owner = $owners[$name] ?? null;
if ($owner !== null) {
$inGroups[$owner->name] = ($inGroups[$owner->name] ?? 0) + $count;
} else {
$noGroup[] = $count . ' 行的快递名称1「' . $name . '」还没建分组';
}
}
foreach (array_slice($inGroups, 0, 3, true) as $name => $count) {
$parts[] = '另有 ' . $count . ' 行属于「' . $name . '」,没拆入(是同一张账单的话,把它加进合并账单后点「重新匹配」)';
}
array_push($parts, ...array_slice($noGroup, 0, 3));
return implode(';', $parts);
}
/**
* 重新拆分一个文件:先把它的账单行都收回主分组,再按当前的分组设置拆一遍(合并账单里新加了一家时用)。
* 涉及的对账单有已确认结算的就不动。
*
* @return list<int> 前后涉及的对账单
*/
public function resplit(int $fileId): array
{
return $this->db()->transaction(fn (): array => $this->resplitFile($fileId));
}
private function resplitFile(int $fileId): array
{
$db = $this->db();
$file = $db->table('courier_bill_files')->lockForUpdate()->find($fileId);
$before = $this->statementsOfFiles([$fileId]);
if ($file === null || $file->status !== 'parsed' || $file->statement_id === null) {
return $before;
}
$statements = $db->table('courier_bill_statements')->whereIn('id', $before)->orderBy('id')->lockForUpdate()->get(['status']);
if ($statements->contains('status', 'confirmed')) {
return $before;
}
$group = collect($this->groups())->firstWhere('id', (int) $file->group_id);
if ($group === null) {
return $before;
}
$db->table('courier_bill_lines')->where('file_id', $fileId)->update(['statement_id' => $file->statement_id]);
$notes = array_filter([$this->split($fileId, $group, (string) $file->bill_month, (int) $file->statement_id, true),
$file->rejected_count > 0 ? '有 ' . $file->rejected_count . ' 行单号被拒收' : '']);
$db->table('courier_bill_files')->where('id', $fileId)->update([
'message' => $notes === [] ? null : mb_substr(implode(';', $notes), 0, 255), 'updated_at' => now(),
]);
return array_values(array_unique([...$before, ...$this->statementsOfFiles([$fileId])]));
}
/**
* 按当前规则重读原始文件。人工处理结果按工作表、原始行号和单号保留,避免同单号的多行互相覆盖。
*
* @return list<int> 前后涉及的对账单
*/
public function reread(int $fileId): array
{
return $this->db()->transaction(fn (): array => $this->rereadFile($fileId));
}
private function rereadFile(int $fileId): array
{
$db = $this->db();
$file = $db->table('courier_bill_files')->lockForUpdate()->find($fileId);
$before = $this->statementsOfFiles([$fileId]);
if ($file === null || $file->status !== 'parsed' || $file->statement_id === null) {
return $before;
}
$statements = $db->table('courier_bill_statements')->whereIn('id', $before)->orderBy('id')->lockForUpdate()->get(['status']);
if ($statements->contains('status', 'confirmed')) {
throw new RuntimeException('这个文件涉及的对账单已确认结算,先撤销确认再重新读取。');
}
$group = collect($this->groups())->firstWhere('id', (int) $file->group_id);
if ($group === null || ! Storage::disk(self::DISK)->exists($file->stored_path)) {
throw new RuntimeException('原始账单文件或对账分组不存在,无法重新读取,已保留原账单。');
}
$this->ingest($fileId, $group, true);
return array_values(array_unique([...$before, ...$this->statementsOfFiles([$fileId])]));
}
private static function lineKey(string $sheet, int $row, string $waybill): string
{
return json_encode([mb_substr($sheet, 0, 64), $row, $waybill], JSON_UNESCAPED_UNICODE);
}
/** 每批至多 500 行;旧行留到解析成功后才删除,用于逐批恢复对应原始行的人工处理。 */
private function insertLines(array $lines, ?int $previousLastId): void
{
$db = $this->db();
if ($previousLastId !== null) {
$kept = $db->table('courier_bill_lines')->where('file_id', $lines[0]['file_id'])
->where('id', '<=', $previousLastId)->whereNotNull('resolution')
->whereIn('waybill_no', array_unique(array_column($lines, 'waybill_no')))
->whereIn('sheet', array_unique(array_column($lines, 'sheet')))
->whereIn('row_no', array_unique(array_column($lines, 'row_no')))
->get(['sheet', 'row_no', 'waybill_no', 'resolution', 'resolved_by', 'resolved_at'])
->keyBy(static fn ($line): string => self::lineKey($line->sheet, $line->row_no, $line->waybill_no));
foreach ($lines as &$line) {
$old = $kept->get(self::lineKey($line['sheet'], $line['row_no'], $line['waybill_no']));
$line += ['resolution' => $old?->resolution, 'resolved_by' => $old?->resolved_by, 'resolved_at' => $old?->resolved_at];
}
unset($line);
}
$db->table('courier_bill_lines')->insert($lines);
}
/**
* 同月重合最多的文件:[文件名, 重合的唯一单号数, 本文件唯一单号数]。
* 数据库聚合避免将整份账单的单号和匹配行加载到 PHP;重读时保留最早上传的那份。
*
* @return array{0:string,1:int,2:int}|null
*/
private function overlap(int $fileId, string $month, bool $earlierOnly = false): ?array
{
$db = $this->db();
$total = $db->table('courier_bill_lines')->where('file_id', $fileId)->distinct()->count('waybill_no');
if ($total === 0) {
return null;
}
$hit = $db->table('courier_bill_lines as other')
->join('courier_bill_files as file', 'file.id', '=', 'other.file_id')
->where('file.bill_month', $month)->where('file.id', $earlierOnly ? '<' : '<>', $fileId)
->whereExists(function ($query) use ($fileId): void {
$query->selectRaw('1')->from('courier_bill_lines as mine')->where('mine.file_id', $fileId)
->whereColumn('mine.waybill_no', 'other.waybill_no');
})
->groupBy('file.id', 'file.original_name')->select('file.original_name')
->selectRaw('COUNT(DISTINCT ' . $db->getQueryGrammar()->wrap('other.waybill_no') . ') AS hits')
->orderByDesc('hits')->orderBy('file.id')->first();
return $hit === null ? null : [(string) $hit->original_name, (int) $hit->hits, $total];
}
/**
* 「重新匹配」:按当前规则重读文件、按当前分组重新拆分,再把涉及的对账单逐一重新匹配。
*
* @return list<int> 重新匹配了的对账单
*/
public function rematch(int $statementId): array
{
return $this->db()->transaction(fn (): array => $this->rematchStatements($statementId));
}
private function rematchStatements(int $statementId): array
{
$db = $this->db();
if ($db->table('courier_bill_statements')->where('id', $statementId)->lockForUpdate()->value('status') === 'confirmed') {
throw new RuntimeException('对账单已确认结算,先撤销确认再重新匹配。');
}
$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()->all();
$statements = [$statementId];
sort($fileIds);
foreach ($fileIds as $fileId) {
array_push($statements, ...$this->rereadFile($fileId));
}
$done = [];
foreach (array_unique($statements) as $id) {
if ($db->table('courier_bill_statements')->where('id', $id)->value('status') === 'confirmed') {
continue;
}
$this->refresh((int) $id);
$done[] = (int) $id;
}
return $done;
}
/** 有账单行就重新匹配;行都被拆走了就清空快递未提供、重算小汇总。 */
private function refresh(int $statementId): void
{
if ($this->db()->table('courier_bill_lines')->where('statement_id', $statementId)->exists()) {
$this->matcher->match($statementId);
return;
}
$this->db()->table('courier_bill_unprovided')->where('statement_id', $statementId)->delete();
$this->matcher->refreshSummary($statementId);
}
/** @return list<array{0:string,1:string}> [文件名, 临时路径] */
private function unzip(string $path): array
{
$zip = new ZipArchive();
if ($zip->open($path) !== true) {
throw new RuntimeException('zip 文件打不开。');
}
$files = [];
try {
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = (string) $zip->getNameIndex($i);
$flags = $zip->statIndex($i, ZipArchive::FL_ENC_RAW);
$raw = is_array($flags) ? (string) $flags['name'] : $name;
if (! mb_check_encoding($raw, 'UTF-8')) {
$name = (string) mb_convert_encoding($raw, 'UTF-8', 'GB18030');
}
$base = basename($name);
if (str_ends_with($name, '/') || str_starts_with($base, '.') || str_starts_with($name, '__MACOSX')
|| ! in_array(strtolower(pathinfo($base, PATHINFO_EXTENSION)), ['xlsx', 'xls', 'csv'], true)) {
continue;
}
$target = tempnam(sys_get_temp_dir(), 'bill_zip_');
$in = $zip->getStream($zip->getNameIndex($i));
$out = fopen((string) $target, 'wb');
stream_copy_to_stream($in, $out);
fclose($in);
fclose($out);
$files[] = [$base, (string) $target];
}
} finally {
$zip->close();
}
return $files;
}
/** 确认结算:锁定对账单,结算台账记下这批单号。 */
public function confirm(int $statementId, string $user): void
{
$db = $this->db();
$db->transaction(function () use ($db, $statementId, $user): void {
$statement = $db->table('courier_bill_statements')->lockForUpdate()->find($statementId);
if ($statement === null || $statement->status === 'confirmed') {
throw new RuntimeException('对账单不存在或已确认。');
}
$db->table('courier_bill_ledger')->where('statement_id', $statement->id)->delete();
$buffer = [];
$seen = [];
$lines = $db->table('courier_bill_lines')->where('statement_id', $statement->id)
->where(static function ($query): void {
$query->whereIn('category', [...Category::PAYABLE, Category::PRIOR])->orWhere('resolution', 'agree');
})
->where(static fn ($query) => $query->whereNull('resolution')->orWhere('resolution', 'agree'))
->orderBy('id')->get(['waybill_no', 'self_amount', 'bill_amount']);
foreach ($lines as $line) {
if (isset($seen[$line->waybill_no])) {
continue;
}
$seen[$line->waybill_no] = true;
$buffer[] = ['group_id' => $statement->group_id, 'waybill_no' => $line->waybill_no, 'settle_month' => $statement->bill_month,
'amount' => $line->self_amount ?? $line->bill_amount, 'statement_id' => $statement->id, 'created_at' => now()];
if (count($buffer) >= 500) {
$db->table('courier_bill_ledger')->insertOrIgnore($buffer);
$buffer = [];
}
}
if ($buffer !== []) {
$db->table('courier_bill_ledger')->insertOrIgnore($buffer);
}
$db->table('courier_bill_statements')->where('id', $statement->id)->update([
'status' => 'confirmed', 'confirmed_at' => now(), 'confirmed_by' => mb_substr($user, 0, 64), 'updated_at' => now(),
]);
});
}
public function unconfirm(int $statementId): void
{
$db = $this->db();
$db->transaction(function () use ($db, $statementId): void {
$db->table('courier_bill_ledger')->where('statement_id', $statementId)->delete();
$db->table('courier_bill_statements')->where('id', $statementId)->update([
'status' => 'open', 'confirmed_at' => null, 'confirmed_by' => null, 'updated_at' => now(),
]);
});
}
/** 手工小汇总行(附加费、记账、补发配件、违约金、借支、车费……)。 */
public function addSummaryItem(int $statementId, string $label, ?float $bill, ?float $self): void
{
$this->assertOpen($statementId);
$sort = (int) $this->db()->table('courier_bill_summary_items')->where('statement_id', $statementId)->max('sort');
$this->db()->table('courier_bill_summary_items')->insert([
'statement_id' => $statementId, 'label' => mb_substr(trim($label), 0, 255), 'bill_amount' => $bill,
'self_amount' => $self, 'manual' => true, 'sort' => max($sort, 1000) + 1,
]);
}
public function deleteSummaryItem(int $statementId, int $itemId): void
{
$this->assertOpen($statementId);
$this->db()->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('id', $itemId)
->where('manual', true)->delete();
}
/**
* 导入历史已结算单号:表头含 分组、单号、结算月份,可选 金额。
*
* @return array{rows:int,inserted:int,unknown_groups:list<string>,rejected:int}
*/
public function importLedger(string $path, string $extension): array
{
$groups = collect($this->groups())->keyBy('name');
$reader = new BillWorkbookReader();
$rows = 0;
$inserted = 0;
$rejected = 0;
$unknown = [];
$buffer = [];
$flush = function () use (&$buffer, &$inserted): void {
if ($buffer !== []) {
$inserted += $this->db()->table('courier_bill_ledger')->insertOrIgnore($buffer);
$buffer = [];
}
};
foreach ($reader->sheets($path, $extension) as $sheetRows) {
$columns = null;
foreach ($sheetRows as $row) {
if ($columns === null) {
$header = array_map(static fn ($v): string => preg_replace('/\s+/u', '', (string) $v) ?? '', $row);
$find = static fn (array $names): ?int => collect($names)->map(static fn ($n) => array_search($n, $header, true))
->first(static fn ($i) => $i !== false);
$columns = ['group' => $find(['分组', '对账分组']), 'waybill' => $find(['单号', '快递单号', '运单号', '运单编号']),
'month' => $find(['结算月份', '月份']), 'amount' => $find(['金额', '运费', '结算金额'])];
if ($columns['group'] === null || $columns['waybill'] === null || $columns['month'] === null) {
throw new RuntimeException('表头须含「分组」「单号」「结算月份」三列(金额可选)。');
}
continue;
}
$groupName = trim((string) ($row[$columns['group']] ?? ''));
$waybillRaw = trim((string) ($row[$columns['waybill']] ?? ''));
if ($groupName === '' && $waybillRaw === '') {
continue;
}
$rows++;
$group = $groups->get($groupName);
if ($group === null) {
$unknown[$groupName] = true;
$rejected++;
continue;
}
$waybill = Waybill::normalize($waybillRaw);
$month = self::month((string) ($row[$columns['month']] ?? ''));
if ($waybill === null || $month === null) {
$rejected++;
continue;
}
$buffer[] = ['group_id' => $group->id, 'waybill_no' => $waybill, 'settle_month' => $month,
'amount' => $columns['amount'] === null ? null : BillParser::number($row[$columns['amount']] ?? null),
'statement_id' => null, 'created_at' => now()];
if (count($buffer) >= 500) {
$flush();
}
}
break;
}
$flush();
return ['rows' => $rows, 'inserted' => $inserted, 'unknown_groups' => array_keys($unknown), 'rejected' => $rejected];
}
private function assertOpen(int $statementId): void
{
if ($this->db()->table('courier_bill_statements')->where('id', $statementId)->value('status') !== 'open') {
throw new RuntimeException('对账单已确认结算,先撤销确认再修改。');
}
}
/** 「2026-10」「2026.10」「2026年10月」「202610」或 Excel 日期序号 → YYYY-MM。 */
public static function month(string $value): ?string
{
$value = trim($value);
if (preg_match('/^(20\d{2})\D{0,2}(\d{1,2})/u', $value, $m) && (int) $m[2] >= 1 && (int) $m[2] <= 12) {
return $m[1] . '-' . str_pad($m[2], 2, '0', STR_PAD_LEFT);
}
if (preg_match('/^\d{5}(\.\d+)?$/', $value)) {
return date('Y-m', (int) round(((float) $value - 25569) * 86400));
}
return null;
}
private static function blank(?string $value): ?string
{
$value = trim((string) $value);
return $value === '' ? null : $value;
}
}