CaiWuXiTong/app/Support/DropshipFreight/DropshipExporter.php

322 lines
17 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\DropshipFreight;
use App\Support\CourierBills\BillWorkbookReader;
use App\Support\CourierBills\Category;
use App\Support\CourierBills\ShippingLookup;
use App\Support\CourierBills\StatementExporter;
use App\Support\CourierBills\StreamingWorkbook;
use Illuminate\Support\Facades\Storage;
use PDO;
use PDOStatement;
use RuntimeException;
/**
* 代发运费对账单导出(内部版),和快递账单对账的导出一个样子:
* 以厂家发来的原始账单为底(每张表原样不动),后面追加 汇总、对账、前月补提供-X月、跨月订单-X月、快递不符、重复、匹配不到、未发出、
* 厂家未提供、说明;没有数据的表不生成。
* 对账类子表的列顺序:厂家账单原始列(一单多行取第一行)→ 财务指定的 25 列 → 发货数据其余字段 → 厂家运费合计、结算运费、分类、说明。
*/
final class DropshipExporter
{
private const CHUNK = 500;
public function __construct(
private readonly DropshipFreightStore $store,
private readonly DropshipReconciler $reconciler,
private readonly ShippingLookup $shipping,
) {}
/** @param resource $output */
public function export(object $factory, string $month, $output): void
{
// 原始列只在本次导出临时索引中保存,导出不重读入库、不改变已有账单金额。
$path = tempnam(sys_get_temp_dir(), 'dropship_export_');
if ($path === false) {
throw new RuntimeException('无法创建导出临时文件。');
}
$index = null;
try {
$index = new PDO('sqlite:' . $path);
$index->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$index->exec('PRAGMA cache_size=-2048');
$index->exec('CREATE TABLE originals (file INTEGER, sheet TEXT, row INTEGER, raw TEXT, PRIMARY KEY (file, sheet, row))');
$this->write($factory, $month, $output, $index);
} finally {
$index = null;
@unlink($path);
}
}
/** @param resource $output */
private function write(object $factory, string $month, $output, PDO $index): void
{
$result = $this->reconciler->factoryMonth($factory, $month, null, true);
$rows = $result['rows'];
$files = $this->store->db()->table('dropship_bill_files')->where('factory_id', $factory->id)->where('bill_month', $month)
->where('status', 'parsed')->orderBy('id')->get();
$book = new StreamingWorkbook();
$baseFileId = null;
foreach ($files as $file) {
if (strtolower(pathinfo($file->stored_path, PATHINFO_EXTENSION)) === 'xlsx'
&& is_file(Storage::disk('local')->path($file->stored_path))
&& $book->base(Storage::disk('local')->path($file->stored_path)) !== null) {
$baseFileId = (int) $file->id;
break;
}
}
$this->writeSummary($book, $factory, $month, $rows);
[$originals, $sources, $original] = $this->writeOriginal($book, $files, $baseFileId, $index);
$lookup = $index->prepare('SELECT raw FROM originals WHERE file = ? AND sheet = ? AND row = ?');
$rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(StatementExporter::FRONT, static fn ($f) => $f[0] !== '_')));
$tail = ['厂家运费(这一单合计)', '结算运费', '分类', '说明'];
// 对账类:本月一致 / 运费有差 / 系统未核算,和前月补提供、跨月订单(按月份各一张)
$sheets = ['对账' => static fn (array $r): bool => in_array($r['status'], [Category::MATCH, Category::DIFF, Category::UNCALCULATED], true)];
foreach ([Category::PRIOR, Category::LATER] as $category) {
foreach (array_unique(array_filter(array_map(static fn (array $r): ?string => $r['status'] === $category ? $r['status_month'] : null, $rows))) as $m) {
$sheets[Category::label($category, $m)] = static fn (array $r): bool => $r['status'] === $category && $r['status_month'] === $m;
}
}
foreach ($sheets as $name => $test) {
$picked = array_values(array_filter($rows, $test));
if ($picked === []) {
continue;
}
$book->row($name, [...$original, ...array_keys(StatementExporter::FRONT), ...array_values($rest), ...$tail], true);
foreach (array_chunk($picked, self::CHUNK) as $chunk) {
$details = $this->shipping->details(array_map(static fn (array $r): string => (string) $r['ship_waybill'], $chunk));
foreach ($chunk as $r) {
$ship = $details[strtoupper((string) $r['ship_waybill'])] ?? [];
$cells = $this->originalCells($r, $sources, $original, $lookup);
foreach (StatementExporter::FRONT as $field) {
$cells[] = $this->front($field, $r, $ship);
}
foreach (array_keys($rest) as $field) {
$cells[] = self::value($field, $ship[$field] ?? null);
}
$book->row($name, [...$cells, $r['bill'], $r['settle'], $r['label'], $r['note']]);
}
}
}
// 不付的:只放厂家原始列和说明
foreach ([Category::MISMATCH => '快递不符', Category::DUPLICATE => '重复', Category::UNMATCHED => '匹配不到', Category::UNSHIPPED => '未发出'] as $category => $name) {
$picked = array_values(array_filter($rows, static fn (array $r): bool => $r['status'] === $category));
if ($picked === []) {
continue;
}
$book->row($name, [...$original, '发货数据快递名称1', '发货数据仓库', '厂家运费(这一单合计)', '说明'], true);
foreach ($picked as $r) {
$book->row($name, [...$this->originalCells($r, $sources, $original, $lookup), $r['express'], $r['warehouse'], $r['bill'], $r['note']]);
}
}
// 厂家未提供:系统认出是这家的代发单、厂家账单里没有,不付
$picked = array_values(array_filter($rows, static fn (array $r): bool => $r['status'] === Category::UNPROVIDED));
if ($picked !== []) {
$name = '厂家未提供';
$book->row($name, [...array_values(ShippingLookup::COLUMNS), '我方核算运费'], true);
foreach (array_chunk($picked, self::CHUNK) as $chunk) {
$details = $this->shipping->details(array_map(static fn (array $r): string => (string) $r['waybill'], $chunk));
foreach ($chunk as $r) {
$ship = $details[strtoupper((string) $r['waybill'])] ?? ['express_no' => $r['waybill']];
$book->row($name, [...array_map(static fn (string $f) => self::value($f, $ship[$f] ?? null), array_keys(ShippingLookup::COLUMNS)), $r['calc']]);
}
}
}
$this->writeNotes($book, $rows, $originals);
$book->writeTo($output);
}
/** 汇总:按分类,厂家运费 / 结算运费(我方核算)/ 差异,口径同手工代发账单的「运费」那一行。 */
private function writeSummary(StreamingWorkbook $book, object $factory, string $month, array $rows): void
{
$book->row('汇总', [$factory->name . ' ' . $month . ' 代发运费', '厂家运费', '结算运费(我方核算)', '差异', '单数'], true);
$groups = [];
foreach ($rows as $r) {
$label = in_array($r['status'], [Category::MATCH, Category::DIFF, Category::UNCALCULATED], true)
? (int) substr($month, 5, 2) . '月运费' : $r['label'];
$groups[$label] ??= ['bill' => null, 'settle' => null, 'n' => 0];
$groups[$label]['n']++;
if ($r['bill'] !== null) {
$groups[$label]['bill'] = (float) $groups[$label]['bill'] + (float) $r['bill'];
}
if ($r['settle'] !== null) {
$groups[$label]['settle'] = (float) $groups[$label]['settle'] + (float) $r['settle'];
}
}
$bill = $settle = 0.0;
foreach ($groups as $label => $g) {
$book->row('汇总', [$label, $g['bill'] === null ? null : round($g['bill'], 2), $g['settle'] === null ? null : round($g['settle'], 2),
round((float) $g['bill'] - (float) $g['settle'], 2), $g['n']]);
$bill += (float) $g['bill'];
$settle += (float) $g['settle'];
}
$book->row('汇总', ['合计', round($bill, 2), round($settle, 2), round($bill - $settle, 2), count($rows)], true);
$book->row('汇总', []);
$book->row('汇总', ['代发仓:' . $factory->warehouse . ';代发快递关键字:' . $factory->keywords
. '。一致类和前月补提供按我方核算运费结算;厂家没开的、快递不符、重复、匹配不到、未发出、跨月订单本月不付。']);
}
/** 流式复制原表并建立磁盘临时索引;只按已入库的表/行定位原始列。 */
private function writeOriginal(StreamingWorkbook $book, $files, ?int $baseFileId, PDO $index): array
{
$originals = [];
$used = [];
foreach (['汇总', '对账', '快递不符', '重复', '匹配不到', '未发出', '厂家未提供', '说明'] as $name) {
$used[mb_strtolower($book->nameOf($name))] = true;
}
foreach (range(1, 12) as $month) {
$used[mb_strtolower($book->nameOf('前月补提供-' . $month . '月'))] = true;
$used[mb_strtolower($book->nameOf('跨月订单-' . $month . '月'))] = true;
}
$sources = [];
$union = [];
$insert = $index->prepare('INSERT INTO originals VALUES (?, ?, ?, ?)');
$index->beginTransaction();
$reader = new BillWorkbookReader();
foreach ($files->values() as $fileIndex => $file) {
$path = Storage::disk('local')->path($file->stored_path);
if (! is_file($path)) {
throw new \RuntimeException('厂家账单原文件缺失,无法完整导出:' . $file->original_name);
}
$read = 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 => $sheetRows) {
$name = (string) $sheet;
if (! $isBase) {
$base = '文件' . ($fileIndex + 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;
}
$written = 0;
$count = 0;
$headers = null;
$scanned = 0;
$readFreight = (bool) ($read->get((string) $sheet)['read'] ?? false);
foreach ($sheetRows as $number => $row) {
if (array_filter($row, static fn ($v): bool => $v !== null && $v !== '') !== []) {
$count++;
}
if (! $isBase) {
while (++$written < $number) {
$book->row($name, []);
}
$book->row($name, $row);
}
if ($readFreight && $headers === null && ++$scanned <= 15 && FactoryBillParser::findColumns($row) !== null) {
$headers = self::headerNames($row);
$sources[$file->id . ':' . mb_substr((string) $sheet, 0, 64)] = $headers;
foreach ($headers as $header) {
$union[$header] = true;
}
} elseif ($headers !== null) {
$insert->execute([$file->id, mb_substr((string) $sheet, 0, 64), $number, json_encode($row, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)]);
}
}
$originals[] = [$name, (bool) ($read->get((string) $sheet)['read'] ?? false), $count, $isBase];
}
}
$index->commit();
return [$originals, $sources, array_keys($union)];
}
private function writeNotes(StreamingWorkbook $book, array $rows, array $originals): void
{
$count = static fn (array $statuses): int => count(array_filter($rows, static fn (array $r): bool => in_array($r['status'], $statuses, true)));
$book->row('说明', ['子表', '是什么', '行数'], true);
foreach ($originals as [$name, $read, $lines, $isBase]) {
$book->row('说明', [$name, ($isBase ? '厂家原始账单,原文件原样(内容、格式、公式都没动)' : '厂家原始账单(另一个文件,按值复制,格式没保留)')
. ';' . ($read ? '读了这张表的运费。' : '这张表没读运费(货款、记账、退货等)。'), $lines]);
}
foreach ([
['对账', '本月发货、是这家代发单的单号(一致、运费有差、系统未核算),按我方核算运费结算。前面是厂家账单原始列,后面接我方核算的 25 列和发货数据其余字段。', [Category::MATCH, Category::DIFF, Category::UNCALCULATED]],
['前月补提供-X月', '上月及以前发货、厂家这次才开的单,按我方核算运费结算。', [Category::PRIOR]],
['跨月订单-X月', '下个月才发货的单,本月不付,留到发货那个月。', [Category::LATER]],
['快递不符', '发货数据查得到,但不是这家代发单(不是这家代发仓发的、快递名称1 不含关键字,或是自有快递),不付。', [Category::MISMATCH]],
['重复', '以前月份的账单已开过这个包裹(换单前后单号算同一包裹),不付。', [Category::DUPLICATE]],
['匹配不到', '发货数据里哪个月都查不到这个单号,不付。', [Category::UNMATCHED]],
['未发出', '在未发出明细里、货没发出去的单,不付。', [Category::UNSHIPPED]],
['厂家未提供', '系统认出是这家本月的代发单,但厂家账单里没有,不付。', [Category::UNPROVIDED]],
] as [$name, $text, $statuses]) {
$book->row('说明', [$name, $text, $count($statuses)]);
}
}
/** 同一张表的重名/空白列保留各自位置,避免列名本身带序号时覆盖。 */
private static function headerNames(array $headers): array
{
$names = [];
$used = [];
foreach ($headers as $column => $header) {
$base = trim((string) $header) ?: '列' . ($column + 1);
$name = $base;
for ($n = 2; isset($used[$name]); $n++) {
$name = $base . '(' . $n . ')';
}
$used[$name] = true;
$names[] = $name;
}
return $names;
}
/** @return list<string|float|null> */
private function originalCells(array $r, array $sources, array $original, PDOStatement $lookup): array
{
$names = $sources[($r['file_id'] ?? '') . ':' . ($r['sheet'] ?? '')] ?? [];
$lookup->execute([$r['file_id'] ?? 0, $r['sheet'] ?? '', $r['row_no'] ?? 0]);
$json = $lookup->fetchColumn();
$lookup->closeCursor();
if ($names === [] || $json === false) {
throw new RuntimeException('原始账单行缺失,无法完整导出:' . $r['waybill']);
}
$raw = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
$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_int($value) || is_float($value) ? (float) $value : (string) $value;
}, $original);
}
private function front(string $field, array $r, array $ship): string|float|null
{
return match ($field) {
'_measured' => $ship['qc_measured_weight'] ?? null,
'_unshipped' => null,
'_weight_diff' => null,
'_freight_diff' => $r['bill'] !== null && ($ship['qc_freight'] ?? null) !== null ? round((float) $r['bill'] - (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;
}
}