CaiWuXiTong/app/Support/DropshipFreight/DropshipExporter.php

353 lines
19 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 App\Support\CourierBills\XlsxFormula;
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;
$baseCount = 0;
foreach ($files as $file) {
$names = 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;
if ($names !== null) {
$baseFileId = (int) $file->id;
$baseCount = count($names);
// 和手工版一样:原账单的表叫「厂家账单」,一个文件几张表的叫「厂家账单-原表名」
$book->renameBase(array_combine($names, array_map(static fn (string $n): string => self::originalName(0, $n, count($names)), $names)));
break;
}
}
$book->putFirst(['汇总']);
$this->writeSummary($book, $factory, $month, $rows);
[$originals, $sources, $original] = $this->writeOriginal($book, $files, $baseFileId, $index, $baseCount);
$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
{
$template = $this->store->summaryTemplate($factory, $month);
$billTotal = $settleTotal = null;
foreach ($rows as $r) {
if ($r['bill'] !== null) {
$billTotal = (float) $billTotal + (float) $r['bill'];
}
if ($r['settle'] !== null) {
$settleTotal = (float) $settleTotal + (float) $r['settle'];
}
}
$labels = $template['labels'];
if (($billTotal !== null || $settleTotal !== null) && ! array_filter($labels, [DropshipSummaryTemplate::class, 'isFreight'])) {
array_unshift($labels, '运费');
}
$book->row('汇总', [$template['title'], ...array_slice(array_pad($template['headers'], 3, ''), 0, 3)], true);
$sums = [0.0, 0.0];
foreach ($labels as $index => $label) {
$n = $index + 2;
[$bill, $settle] = DropshipSummaryTemplate::isFreight($label)
? [$billTotal === null ? null : round($billTotal, 2), $settleTotal === null ? null : round($settleTotal, 2)] : [null, null];
$sums[0] += (float) $bill;
$sums[1] += (float) $settle;
$book->row('汇总', [$label, $bill, $settle, self::diff($n, $bill, $settle)]);
}
$last = count($labels) + 1;
$n = $last + 1;
$book->row('汇总', [$template['total'], new XlsxFormula('SUM(B2:B' . $last . ')', round($sums[0], 2)),
new XlsxFormula('SUM(C2:C' . $last . ')', round($sums[1], 2)), new XlsxFormula('N(B' . $n . ')-N(C' . $n . ')', round($sums[0] - $sums[1], 2))], true);
}
/** 差异 = 原始 − 简尚,两格都空就空着(公式,手工填了会跟着算)。 */
private static function diff(int $row, ?float $bill, ?float $settle): XlsxFormula
{
return new XlsxFormula('IF(COUNT(B' . $row . ':C' . $row . ')=0,"",N(B' . $row . ')-N(C' . $row . '))',
$bill === null && $settle === null ? '' : round((float) $bill - (float) $settle, 2));
}
/** 原账单的表名:「厂家账单」;第 2 个文件起「厂家账单2」;一个文件几张表的加「-原表名」。 */
private static function originalName(int $fileIndex, string $sheet, int $sheetCount): string
{
$name = '厂家账单' . ($fileIndex > 0 ? $fileIndex + 1 : '');
return $sheetCount > 1 ? mb_substr($name . '-' . $sheet, 0, 31) : $name;
}
/** 流式复制原表并建立磁盘临时索引;只按已入库的表/行定位原始列。 */
private function writeOriginal(StreamingWorkbook $book, $files, ?int $baseFileId, PDO $index, int $baseCount = 0): 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();
$nextOrdinal = $baseFileId !== null ? 1 : 0;
foreach ($files->values() as $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;
$sheetCount = $isBase ? $baseCount : max(1, $read->count());
// 底稿(原样保留的那份)叫「厂家账单」,其余文件按顺序「厂家账单2」「厂家账单3」…
$ordinal = $isBase ? 0 : $nextOrdinal++;
foreach ($reader->sheets($path, strtolower(pathinfo($path, PATHINFO_EXTENSION)), true) as $sheet => $sheetRows) {
$name = self::originalName($ordinal, (string) $sheet, $sheetCount);
if (! $isBase) {
$base = $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;
}
}