382 lines
21 KiB
PHP
382 lines
21 KiB
PHP
<?php
|
||
|
||
namespace App\Support\CourierBills;
|
||
|
||
use Illuminate\Support\Facades\Storage;
|
||
|
||
/**
|
||
* 对账单导出(内部版)。一张账单拆成了几家(合并账单)时,几家一起导出成一个文件:汇总页每家一个小汇总,
|
||
* 明细子表合在一起,末列注明对账分组,和财务手工做的对账表一样。
|
||
* 导出文件以快递发来的原始账单为底:原文件的每张表一个字节不改,后面追加汇总、对账、前月补提供-X月、跨月订单-X月、快递不符、重复、
|
||
* 匹配不到、未发出、未提供、说明;没有数据的工作表不生成。
|
||
*
|
||
* 对账类子表的列顺序:快递原始列 → 财务指定的 25 列 → 发货数据其余字段 → 处理结果。
|
||
*/
|
||
final class StatementExporter
|
||
{
|
||
/** 财务指定的 25 列 => 取值来源(发货数据字段,或 _ 开头的计算项)。 */
|
||
public const FRONT = [
|
||
'称重重量' => '_measured', '首重' => 'qc_first_price', '面单' => 'qc_miandan', '快递单号' => 'express_no',
|
||
'交易单号' => 'trade_no', '商品ID' => 'item_id', '条形码' => 'barcode', '商品名称' => 'product_name', '数量' => 'qty',
|
||
'计费重量' => 'qc_charge_weight', '续重/费率' => 'qc_rate', '核算运费' => 'qc_freight', '重量差' => '_weight_diff',
|
||
'运费差' => '_freight_diff', '省' => 'receiver_state', '买家昵称' => 'buyer_nick', '收货姓名' => 'receiver_name',
|
||
'店铺名称' => 'shop_name', '快递名称1' => 'express_name1', '仓库' => 'warehouse_name', '发货时间' => 'ship_time',
|
||
'未发出' => '_unshipped', '运费' => 'freight', '线上重量' => 'online_weight', '实称重量' => 'actual_weight',
|
||
];
|
||
|
||
private const CHUNK = 500;
|
||
|
||
public function __construct(private readonly ShippingLookup $shipping) {}
|
||
|
||
/**
|
||
* 和这张对账单同一张账单的所有对账单:它用到的账单文件拆到的各家,加上「合并账单」相同、同月的各家。本张排第一。
|
||
*
|
||
* @return list<int>
|
||
*/
|
||
public function related(int $statementId): array
|
||
{
|
||
$db = CourierBillMatcher::db();
|
||
$statement = $db->table('courier_bill_statements')->find($statementId);
|
||
if ($statement === null) {
|
||
throw new \RuntimeException('对账单不存在。');
|
||
}
|
||
$ids = collect([$statementId]);
|
||
do {
|
||
$previous = $ids->count();
|
||
$fileIds = $db->table('courier_bill_lines')->whereIn('statement_id', $ids)->distinct()->pluck('file_id')
|
||
->merge($db->table('courier_bill_files')->whereIn('statement_id', $ids)->pluck('id'))->unique();
|
||
$fromFiles = $db->table('courier_bill_lines')->whereIn('file_id', $fileIds)->distinct()->pluck('statement_id')
|
||
->merge($db->table('courier_bill_files')->whereIn('id', $fileIds)->whereNotNull('statement_id')->pluck('statement_id'));
|
||
$bundles = $db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||
->whereIn('s.id', $ids)->pluck('g.bundle')->filter(fn ($bundle) => trim((string) $bundle) !== '')->unique();
|
||
$ids = $ids->merge($db->table('courier_bill_statements as s')->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')
|
||
->where('s.bill_month', $statement->bill_month)
|
||
->where(fn ($q) => $q->whereIn('s.id', $fromFiles)->orWhere(fn ($q) => $q->whereIn('g.bundle', $bundles)->where('s.line_count', '>', 0)))
|
||
->pluck('s.id'))->map(static fn ($id): int => (int) $id)->unique();
|
||
} while ($ids->count() > $previous);
|
||
$others = $ids->map(static fn ($id): int => (int) $id)->unique()->reject(static fn (int $id): bool => $id === $statementId)->sort()->values()->all();
|
||
|
||
return [$statementId, ...$others];
|
||
}
|
||
|
||
/** @param resource $output */
|
||
public function export(int $statementId, $output): void
|
||
{
|
||
$db = CourierBillMatcher::db();
|
||
$ids = $this->related($statementId);
|
||
$multi = count($ids) > 1;
|
||
$groupNames = [];
|
||
$book = new StreamingWorkbook();
|
||
$files = $this->files($ids);
|
||
$baseFileId = null;
|
||
foreach ($files as $file) {
|
||
if (strtolower(pathinfo($file->stored_path, PATHINFO_EXTENSION)) === 'xlsx'
|
||
&& $book->base(Storage::disk('local')->path($file->stored_path)) !== null) {
|
||
$baseFileId = (int) $file->id;
|
||
break;
|
||
}
|
||
}
|
||
|
||
// 汇总:每家一个小汇总
|
||
foreach ($ids as $index => $id) {
|
||
$statement = $db->table('courier_bill_statements')->find($id);
|
||
$group = $db->table('courier_bill_groups')->find($statement->group_id);
|
||
$groupNames[$id] = $group->name;
|
||
if ($index > 0) {
|
||
$book->row('汇总', []);
|
||
$book->row('汇总', []);
|
||
}
|
||
$book->row('汇总', [$group->name . ' ' . $statement->bill_month, '快递提供金额', '自算金额', '差异'], true);
|
||
$bill = 0.0;
|
||
$self = 0.0;
|
||
foreach ($db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get() as $item) {
|
||
$b = $item->bill_amount === null ? null : (float) $item->bill_amount;
|
||
$s = $item->self_amount === null ? null : (float) $item->self_amount;
|
||
$book->row('汇总', [$item->label, $b, $s, round((float) $b - (float) $s, 2)]);
|
||
$bill += (float) $b;
|
||
$self += (float) $s;
|
||
}
|
||
$book->row('汇总', ['合计', round($bill, 4), round($self, 2), round($bill - $self, 2)], true);
|
||
}
|
||
$tail = $multi ? ['对账分组'] : [];
|
||
$groupCell = static fn (object $line): array => $multi ? [$groupNames[(int) $line->statement_id] ?? ''] : [];
|
||
|
||
[$sources, $original] = $this->originalHeaders($ids);
|
||
$rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(self::FRONT, static fn ($f) => $f[0] !== '_')));
|
||
$fullHeader = [...$original, ...array_keys(self::FRONT), ...array_values($rest), '差异原因', '处理结果', ...$tail];
|
||
|
||
// 原始账单:底文件原封不动;第 2 个及以后的文件按值复制
|
||
$originals = $this->writeOriginal($book, $files, $baseFileId);
|
||
|
||
$sheets = [
|
||
'对账' => [Category::MATCH, Category::DIFF, Category::UNCALCULATED],
|
||
];
|
||
foreach ($db->table('courier_bill_lines')->whereIn('statement_id', $ids)->whereIn('category', [Category::PRIOR, Category::LATER])
|
||
->distinct()->orderBy('category_month')->get(['category', 'category_month']) as $row) {
|
||
$sheets[Category::label((string) $row->category, (string) $row->category_month)] = [(string) $row->category, (string) $row->category_month];
|
||
}
|
||
foreach ($sheets as $name => $filter) {
|
||
$headerWritten = false;
|
||
$this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $rest, $fullHeader, $groupCell, &$headerWritten): void {
|
||
if (! $headerWritten) {
|
||
$book->row($name, $fullHeader, true);
|
||
$headerWritten = true;
|
||
}
|
||
$details = $this->shipping->details(array_map(static fn ($l): string => $l->waybill_no, $lines));
|
||
foreach ($lines as $line) {
|
||
$ship = $details[strtoupper($line->waybill_no)] ?? [];
|
||
$cells = $this->originalCells($line, $sources, $original);
|
||
foreach (self::FRONT as $field) {
|
||
$cells[] = $this->front($field, $line, $ship);
|
||
}
|
||
foreach (array_keys($rest) as $field) {
|
||
$cells[] = self::value($field, $ship[$field] ?? null);
|
||
}
|
||
$cells[] = CourierBillMatcher::diffReason((string) $line->category, $line->bill_weight, $line->charge_weight);
|
||
$cells[] = Category::RESOLUTIONS[$line->resolution] ?? null;
|
||
$book->row($name, [...$cells, ...$groupCell($line)]);
|
||
}
|
||
});
|
||
}
|
||
|
||
foreach ([Category::MISMATCH => '快递不符', Category::DUPLICATE => '重复', Category::UNMATCHED => '匹配不到', Category::UNSHIPPED => '未发出'] as $category => $name) {
|
||
$extra = $category === Category::UNSHIPPED ? ['未发出来源'] : ($category === Category::MISMATCH ? ['发货数据快递名称1'] : []);
|
||
$headerWritten = false;
|
||
$this->lines($ids, [$category], function (array $lines) use ($book, $name, $category, $sources, $original, $extra, $tail, $groupCell, &$headerWritten): void {
|
||
if (! $headerWritten) {
|
||
$book->row($name, [...$original, ...$extra, '处理结果', ...$tail], true);
|
||
$headerWritten = true;
|
||
}
|
||
foreach ($lines as $line) {
|
||
$cells = $this->originalCells($line, $sources, $original);
|
||
if ($extra !== []) {
|
||
$cells[] = $category === Category::UNSHIPPED ? $line->unshipped_sources : $line->express_name;
|
||
}
|
||
$cells[] = Category::RESOLUTIONS[$line->resolution] ?? null;
|
||
$book->row($name, [...$cells, ...$groupCell($line)]);
|
||
}
|
||
});
|
||
}
|
||
|
||
// 未提供:发货数据有、账单没有
|
||
$headerWritten = false;
|
||
$db->table('courier_bill_unprovided')->whereIn('statement_id', $ids)->orderBy('id')
|
||
->chunk(self::CHUNK, function ($rows) use ($book, $tail, $groupCell, &$headerWritten): void {
|
||
if (! $headerWritten) {
|
||
$book->row('未提供', [...array_values(ShippingLookup::COLUMNS), ...$tail], true);
|
||
$headerWritten = true;
|
||
}
|
||
$details = $this->shipping->details($rows->pluck('waybill_no')->all());
|
||
foreach ($rows as $row) {
|
||
$ship = $details[strtoupper($row->waybill_no)] ?? ['express_no' => $row->waybill_no];
|
||
$book->row('未提供', [...array_map(static fn (string $field) => self::value($field, $ship[$field] ?? null), array_keys(ShippingLookup::COLUMNS)), ...$groupCell($row)]);
|
||
}
|
||
});
|
||
|
||
$this->writeNotes($book, $ids, $originals);
|
||
$book->writeTo($output);
|
||
}
|
||
|
||
/**
|
||
* 底稿内的工作表留在原工作簿。其他文件的工作表按原行列复制值。
|
||
*
|
||
* @return list<array{string,bool,?string,int,bool}>
|
||
*/
|
||
private function writeOriginal(StreamingWorkbook $book, \Illuminate\Support\Collection $files, ?int $baseFileId): array
|
||
{
|
||
$originals = [];
|
||
$used = [];
|
||
$reader = new BillWorkbookReader();
|
||
foreach ($files->values() as $index => $file) {
|
||
$path = Storage::disk('local')->path($file->stored_path);
|
||
if (! is_file($path)) {
|
||
throw new \RuntimeException('原始账单文件缺失,无法完整导出:' . $file->original_name);
|
||
}
|
||
$info = collect((array) json_decode((string) $file->sheets, true))->keyBy('sheet');
|
||
$isBase = (int) $file->id === $baseFileId;
|
||
foreach ($reader->sheets($path, strtolower(pathinfo($path, PATHINFO_EXTENSION)), true) as $sheet => $rows) {
|
||
$name = (string) $sheet;
|
||
if (! $isBase) {
|
||
$base = '文件' . ($index + 1) . '-' . $name;
|
||
$name = $book->nameOf($base);
|
||
for ($n = 2; isset($used[mb_strtolower($name)]); $n++) {
|
||
$suffix = '-' . $n;
|
||
$name = $book->nameOf(mb_substr($base, 0, 31 - mb_strlen($suffix)) . $suffix);
|
||
}
|
||
$used[mb_strtolower($name)] = true;
|
||
}
|
||
$meta = $info->get($sheet, ['skipped' => '没有内容']);
|
||
$written = 0;
|
||
$count = 0;
|
||
foreach ($rows as $number => $row) {
|
||
if (array_filter($row, static fn ($value): bool => $value !== null && $value !== '') !== []) {
|
||
$count++;
|
||
}
|
||
if (! $isBase) {
|
||
while (++$written < $number) {
|
||
$book->row($name, []);
|
||
}
|
||
$book->row($name, $row);
|
||
}
|
||
}
|
||
$originals[] = [$name, ! isset($meta['skipped']), $meta['skipped'] ?? null, $count, $isBase];
|
||
}
|
||
}
|
||
|
||
return $originals;
|
||
}
|
||
|
||
/** 说明:每张子表是什么、各多少行,以及行数怎么对上。 */
|
||
private function writeNotes(StreamingWorkbook $book, array $ids, array $originals): void
|
||
{
|
||
$db = CourierBillMatcher::db();
|
||
$files = $this->files($ids);
|
||
$read = $db->table('courier_bill_lines')->whereIn('statement_id', $ids)->count();
|
||
$rejected = (int) $files->sum('rejected_count');
|
||
$count = static fn (array $categories) => $db->table('courier_bill_lines')->whereIn('statement_id', $ids)->whereIn('category', $categories)->count();
|
||
$rows = [];
|
||
foreach ($originals as [$name, $isRead, $reason, $lines, $isBase]) {
|
||
$description = $isBase ? '快递原始账单,原文件原样(内容、格式、公式都没动)' : '快递原始账单(另一个文件,按值复制,格式没保留)';
|
||
$detail = match (true) {
|
||
$isRead => '已核对运费。',
|
||
str_starts_with((string) $reason, '附加费') => '附加费表,金额按费用项目进入小汇总。',
|
||
default => '没有核对:' . preg_replace('/,?(整表跳过|未读入)$/u', '', (string) $reason) . '。',
|
||
};
|
||
$rows[] = [$name, $description . ';' . $detail, $lines];
|
||
}
|
||
$rows = [
|
||
...$rows,
|
||
[$book->nameOf('对账'), '本月发货、发货数据里找得到、属于这家快递的单号(运费一致或有差)。前面是快递原始列,后面接我方核算的 25 列(称重重量、首重、面单、计费重量、续重/费率、核算运费、重量差、运费差……)和发货数据其余字段。', $count(Category::PAYABLE)],
|
||
['前月补提供-X月', '发货时间在账单月之前、结算台账里没结算过的单号:快递之前漏报、这次补上的。', $count([Category::PRIOR])],
|
||
['跨月订单-X月', '发货时间在账单月之后的单号,本月不结算。', $count([Category::LATER])],
|
||
[$book->nameOf('快递不符'), '发货数据里有这个单号,但快递名称1 不是这家(也不在同一张合并账单里)。', $count([Category::MISMATCH])],
|
||
[$book->nameOf('重复'), '本账单里重复出现(第二次起),或之前月份已结算过的单号。', $count([Category::DUPLICATE])],
|
||
[$book->nameOf('匹配不到'), '发货数据里查不到这个单号。', $count([Category::UNMATCHED])],
|
||
[$book->nameOf('未发出'), '单号在「未发出明细」里(现场拦截、换单、仓内未发),不结算。', $count([Category::UNSHIPPED])],
|
||
[$book->nameOf('未提供'), '发货数据里本月由这家发出、但账单里没有的单号,只列出来核对,不计金额。', $db->table('courier_bill_unprovided')->whereIn('statement_id', $ids)->count()],
|
||
];
|
||
$book->row('说明', ['子表', '是什么', '行数'], true);
|
||
foreach ($rows as $row) {
|
||
$book->row('说明', $row);
|
||
}
|
||
$book->row('说明', []);
|
||
$book->row('说明', ['行数怎么对上', '运费表读入的账单行 ' . $read . ' 行 = 对账 + 前月补提供 + 跨月订单 + 快递不符 + 重复 + 匹配不到 + 未发出。'
|
||
. ($rejected > 0 ? '另有 ' . $rejected . ' 行单号格式不对(如被 Excel 截断成科学计数法)没读入。' : '')
|
||
. '运费表里的标题行、合计行、空单号行不算账单行。行数是有内容的行(含表头、标题、合计)。没有数据的子表不生成。']);
|
||
}
|
||
|
||
/** @return \Illuminate\Support\Collection<int,object> */
|
||
private function files(array $ids)
|
||
{
|
||
$db = CourierBillMatcher::db();
|
||
$fileIds = $db->table('courier_bill_lines')->whereIn('statement_id', $ids)->distinct()->pluck('file_id');
|
||
|
||
return $db->table('courier_bill_files')->where(fn ($q) => $q->whereIn('statement_id', $ids)->orWhereIn('id', $fileIds))->orderBy('id')->get();
|
||
}
|
||
|
||
/**
|
||
* 所有账单文件各工作表表头的并集(按出现顺序;同一表里重名的列加序号)。
|
||
*
|
||
* @return array{0:array<string,list<string>>,1:list<string>} [文件:工作表 => 该表的列名, 并集列名]
|
||
*/
|
||
private function originalHeaders(array $statementIds): array
|
||
{
|
||
$sources = [];
|
||
$union = [];
|
||
$db = CourierBillMatcher::db();
|
||
$fileIds = $db->table('courier_bill_lines')->whereIn('statement_id', $statementIds)->distinct()->pluck('file_id');
|
||
$files = $db->table('courier_bill_files')->where(fn ($q) => $q->whereIn('statement_id', $statementIds)->orWhereIn('id', $fileIds))
|
||
->orderBy('id')->get(['id', 'sheets']);
|
||
foreach ($files as $file) {
|
||
foreach ((array) json_decode((string) $file->sheets, true) as $sheet) {
|
||
if (isset($sheet['skipped'])) {
|
||
continue;
|
||
}
|
||
$names = [];
|
||
$count = [];
|
||
foreach ($sheet['headers'] as $index => $header) {
|
||
$header = trim((string) $header);
|
||
$header = $header === '' ? '列' . ($index + 1) : $header;
|
||
$count[$header] = ($count[$header] ?? 0) + 1;
|
||
$names[] = $count[$header] > 1 ? $header . $count[$header] : $header;
|
||
}
|
||
$sources[$file->id . ':' . $sheet['sheet']] = $names;
|
||
foreach ($names as $name) {
|
||
$union[$name] = true;
|
||
}
|
||
}
|
||
}
|
||
|
||
return [$sources, array_keys($union)];
|
||
}
|
||
|
||
/** @return list<string|float|null> */
|
||
private function originalCells(object $line, array $sources, array $original): array
|
||
{
|
||
$names = $sources[$line->file_id . ':' . $line->sheet] ?? [];
|
||
$raw = (array) json_decode((string) $line->raw, true);
|
||
$byName = [];
|
||
foreach ($names as $index => $name) {
|
||
$byName[$name] = $raw[$index] ?? null;
|
||
}
|
||
|
||
return array_map(static function (string $name) use ($byName) {
|
||
$value = $byName[$name] ?? null;
|
||
if ($value === null || $value === '') {
|
||
return null;
|
||
}
|
||
// 金额/重量这类纯数字写成数值;长数字(单号、手机号)保持文本。
|
||
return is_numeric($value) && strlen(preg_replace('/\D/', '', (string) $value)) < 11 && ! preg_match('/^0\d/', (string) $value)
|
||
? (float) $value : (string) $value;
|
||
}, $original);
|
||
}
|
||
|
||
private function front(string $field, object $line, array $ship): string|float|null
|
||
{
|
||
return match ($field) {
|
||
'_measured' => null,
|
||
'_unshipped' => $line->unshipped_sources,
|
||
'_weight_diff' => $line->bill_weight !== null && ($ship['qc_charge_weight'] ?? null) !== null
|
||
? round((float) $line->bill_weight - (float) $ship['qc_charge_weight'], 4) : null,
|
||
'_freight_diff' => $line->bill_amount !== null && ($ship['qc_freight'] ?? null) !== null
|
||
? round((float) $line->bill_amount - (float) $ship['qc_freight'], 2) : null,
|
||
default => self::value($field, $ship[$field] ?? null),
|
||
};
|
||
}
|
||
|
||
private static function value(string $field, mixed $value): string|float|null
|
||
{
|
||
if ($value === null || $value === '') {
|
||
return null;
|
||
}
|
||
if (in_array($field, ShippingLookup::TEXT_COLUMNS, true) || ! is_numeric($value)) {
|
||
return (string) $value;
|
||
}
|
||
|
||
return (float) $value;
|
||
}
|
||
|
||
/**
|
||
* 按 id 顺序分批读账单行。$filter:null = 全部;[分类...];或 [分类, 月份](前月补提供/跨月订单)。
|
||
*/
|
||
private function lines(array $statementIds, ?array $filter, callable $each, ?callable $onFirst = null): void
|
||
{
|
||
$query = CourierBillMatcher::db()->table('courier_bill_lines')->whereIn('statement_id', $statementIds);
|
||
if ($filter !== null) {
|
||
if (count($filter) === 2 && in_array($filter[0], [Category::PRIOR, Category::LATER], true)) {
|
||
$query->where('category', $filter[0])->where('category_month', $filter[1]);
|
||
} else {
|
||
$query->whereIn('category', $filter);
|
||
}
|
||
}
|
||
$first = true;
|
||
$query->chunkById(self::CHUNK, function ($rows) use ($each, $onFirst, &$first): void {
|
||
if ($first && $onFirst !== null) {
|
||
$onFirst();
|
||
}
|
||
$first = false;
|
||
$each($rows->all());
|
||
});
|
||
}
|
||
}
|