228 lines
11 KiB
PHP
228 lines
11 KiB
PHP
<?php
|
||
|
||
namespace App\Support\CourierBills;
|
||
|
||
/**
|
||
* 单家对账单导出(内部版)。工作表:汇总、运费、对账、前月补提供-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) {}
|
||
|
||
/** @param resource $output */
|
||
public function export(int $statementId, $output): void
|
||
{
|
||
$db = CourierBillMatcher::db();
|
||
$statement = $db->table('courier_bill_statements')->find($statementId);
|
||
$group = $db->table('courier_bill_groups')->find($statement->group_id);
|
||
$book = new StreamingWorkbook();
|
||
|
||
// 汇总
|
||
$book->row('汇总', [$group->name . ' ' . $statement->bill_month, '快递提供金额', '自算金额', '差异'], true);
|
||
$bill = 0.0;
|
||
$self = 0.0;
|
||
foreach ($db->table('courier_bill_summary_items')->where('statement_id', $statementId)->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, 2), round($self, 2), round($bill - $self, 2)], true);
|
||
|
||
[$sources, $original] = $this->originalHeaders($statementId);
|
||
$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), '处理结果'];
|
||
|
||
// 运费:快递原始账单行
|
||
$this->lines($statementId, null, function (array $lines) use ($book, $sources, $original): void {
|
||
foreach ($lines as $line) {
|
||
$book->row('运费', $this->originalCells($line, $sources, $original));
|
||
}
|
||
}, fn () => $book->row('运费', $original, true));
|
||
|
||
$sheets = [
|
||
'对账' => [Category::MATCH, Category::DIFF, Category::UNCALCULATED],
|
||
];
|
||
foreach ($db->table('courier_bill_lines')->where('statement_id', $statementId)->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($statementId, $filter, function (array $lines) use ($book, $name, $sources, $original, $rest, $fullHeader, &$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[] = Category::RESOLUTIONS[$line->resolution] ?? null;
|
||
$book->row($name, $cells);
|
||
}
|
||
});
|
||
}
|
||
|
||
foreach ([Category::MISMATCH => '快递不符', Category::DUPLICATE => '重复', Category::UNMATCHED => '匹配不到', Category::UNSHIPPED => '未发出'] as $category => $name) {
|
||
$extra = $category === Category::UNSHIPPED ? ['未发出来源'] : ($category === Category::MISMATCH ? ['发货数据快递名称1'] : []);
|
||
$headerWritten = false;
|
||
$this->lines($statementId, [$category], function (array $lines) use ($book, $name, $category, $sources, $original, $extra, &$headerWritten): void {
|
||
if (! $headerWritten) {
|
||
$book->row($name, [...$original, ...$extra, '处理结果'], 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);
|
||
}
|
||
});
|
||
}
|
||
|
||
// 未提供:发货数据有、账单没有
|
||
$headerWritten = false;
|
||
$db->table('courier_bill_unprovided')->where('statement_id', $statementId)->orderBy('id')
|
||
->chunk(self::CHUNK, function ($rows) use ($book, &$headerWritten): void {
|
||
if (! $headerWritten) {
|
||
$book->row('未提供', array_values(ShippingLookup::COLUMNS), 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)));
|
||
}
|
||
});
|
||
|
||
$book->writeTo($output);
|
||
}
|
||
|
||
/**
|
||
* 所有账单文件各工作表表头的并集(按出现顺序;同一表里重名的列加序号)。
|
||
*
|
||
* @return array{0:array<string,list<string>>,1:list<string>} [文件:工作表 => 该表的列名, 并集列名]
|
||
*/
|
||
private function originalHeaders(int $statementId): array
|
||
{
|
||
$sources = [];
|
||
$union = [];
|
||
$files = CourierBillMatcher::db()->table('courier_bill_files')->where('statement_id', $statementId)->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(int $statementId, ?array $filter, callable $each, ?callable $onFirst = null): void
|
||
{
|
||
$query = CourierBillMatcher::db()->table('courier_bill_lines')->where('statement_id', $statementId);
|
||
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());
|
||
});
|
||
}
|
||
}
|