代发单家导出保留原账单并追加对账分类 (#1572)

This commit is contained in:
limeng 2026-11-30 15:16:05 +08:00
parent bb316015d0
commit 63e5c5298c
4 changed files with 490 additions and 8 deletions

View File

@ -3,6 +3,7 @@
namespace App\Http\Controllers\Business;
use App\Support\CourierBills\StreamingWorkbook;
use App\Support\DropshipFreight\DropshipExporter;
use App\Support\DropshipFreight\DropshipFreightStore;
use App\Support\DropshipFreight\DropshipReconciler;
use Illuminate\Database\QueryException;
@ -171,8 +172,32 @@ final class DropshipFreightController extends Controller
$billed = $this->store->db()->table('dropship_bill_lines')->where('bill_month', $month)->distinct()->pluck('factory_id')->map('intval')->all();
$factories = $factories->filter(fn ($f) => in_array((int) $f->id, $billed, true))->values();
}
if (! empty($data['factory'])) {
// 单家:和快递账单对账的导出一样,以厂家原始账单为底,后面接汇总、对账(厂家原始列 + 发货数据)和各分类
$factory = $factories->first();
$name = str_replace(['/', '\\'], '-', (string) $factory->name) . '_' . $month . '_代发运费对账(内部版).xlsx';
$path = tempnam(sys_get_temp_dir(), 'dropship_download_');
if ($path === false) {
throw new RuntimeException('无法创建导出文件。');
}
$output = fopen($path, 'wb');
try {
$this->guard(fn () => app(DropshipExporter::class)->export($factory, $month, $output));
} catch (\Throwable $error) {
fclose($output);
@unlink($path);
throw $error;
} finally {
if (is_resource($output)) {
fclose($output);
}
}
return response()->download($path, $name)->deleteFileAfterSend(true);
}
$own = $this->store->ownExpressNames();
$name = ($factories->count() === 1 ? $factories->first()->name : '代发厂家') . $month . '代发运费对账.xlsx';
$name = '代发厂家' . $month . '代发运费对账.xlsx';
return response()->streamDownload(function () use ($factories, $month, $own): void {
$book = new StreamingWorkbook();

View File

@ -0,0 +1,321 @@
<?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;
}
}

View File

@ -44,13 +44,17 @@ final class DropshipReconciler
/**
* @return array{rows:list<array<string,mixed>>,summary:array<string,mixed>}
*/
public function factoryMonth(object $factory, string $month, ?array $own = null): array
public function factoryMonth(object $factory, string $month, ?array $own = null, bool $withSources = false): array
{
$own = array_flip($own ?? $this->store->ownExpressNames());
$keywords = DropshipFreightStore::splitKeywords((string) $factory->keywords);
$bill = $this->store->db()->table('dropship_bill_lines')->where('factory_id', $factory->id)->where('bill_month', $month)
->get(['waybill_no', 'amount'])->groupBy('waybill_no')
->map(static fn ($rows): float => round((float) $rows->sum('amount'), 2))->all();
$columns = $withSources ? ['waybill_no', 'amount', 'file_id', 'sheet', 'row_no'] : ['waybill_no', 'amount'];
$lines = $this->store->db()->table('dropship_bill_lines')->where('factory_id', $factory->id)->where('bill_month', $month)
->orderBy('id')->get($columns)->groupBy('waybill_no');
$bill = $lines->map(static fn ($rows): float => round((float) $rows->sum('amount'), 2))->all();
$sources = $withSources ? $lines->map(static fn ($rows): array => ['file_id' => (int) $rows->first()->file_id,
'sheet' => (string) $rows->first()->sheet, 'row_no' => (int) $rows->first()->row_no])->all() : [];
unset($lines);
// 数字单号做数组键会变成整数,查库前转回字符串(整数和 varchar 比较会用不上索引)
$billed = array_map('strval', array_keys($bill));
$system = array_values(array_diff($this->dropshipWaybills($factory, $keywords, $own, $month), $billed));
@ -110,11 +114,12 @@ final class DropshipReconciler
$note = '换单:实际发出 ' . $swap . '(' . ($i['express'] ?? '无快递名称1') . ')' . ($note !== null ? ';' . $note : '')
. ($i === null ? ';新单号发货数据里也查不到' : '');
}
$rows[] = self::row($waybill, $i, $bill[$waybill], $category, $categoryMonth, $note);
$rows[] = self::row($waybill, $i, $bill[$waybill], $category, $categoryMonth, $note) + ($sources[$waybill] ?? [])
+ ['ship_waybill' => $swap ?? $waybill];
}
$system = array_values(array_filter($system, static fn (string $w): bool => ! isset($covered[$w])));
foreach ($system as $waybill) {
$rows[] = self::row($waybill, $info[$waybill] ?? null, null, Category::UNPROVIDED, null, '厂家账单里没有,不付');
$rows[] = self::row($waybill, $info[$waybill] ?? null, null, Category::UNPROVIDED, null, '厂家账单里没有,不付') + ['ship_waybill' => $waybill];
}
$order = array_flip(array_keys(self::LABELS));
usort($rows, static fn (array $a, array $b): int => [$order[$a['status']], (string) $a['ship_time']] <=> [$order[$b['status']], (string) $b['ship_time']]);

View File

@ -8,6 +8,7 @@ use App\Support\CourierBills\Category;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\ShippingLookup;
use App\Support\DropshipFreight\DropshipFreightStore;
use App\Support\DropshipFreight\DropshipExporter;
use App\Support\DropshipFreight\DropshipReconciler;
use App\Support\DropshipFreight\FactoryBillParser;
use Illuminate\Http\UploadedFile;
@ -140,7 +141,35 @@ final class DropshipFreightTest extends FeatureTestCase
$this->get($page(['df_view' => 'factory', 'factory' => $factory->id, 'month' => '2026-10', 'status' => 'attention']))->assertOk()
->assertDontSeeText('773444000004');
$this->get(route("business.$section.dropship-freight.export", ['month' => '2026-10']))->assertOk();
$this->get(route("business.$section.dropship-freight.export", ['month' => '2026-10', 'factory' => $factory->id]))->assertOk();
$before = $db->table('dropship_bill_lines')->orderBy('id')->get()->toJson();
$filesBefore = $db->table('dropship_bill_files')->orderBy('id')->get()->toJson();
$export = $this->get(route("business.$section.dropship-freight.export", ['month' => '2026-10', 'factory' => $factory->id]))->assertOk();
$out = $export->baseResponse->getFile()->getPathname();
$book = \PhpOffice\PhpSpreadsheet\IOFactory::load($out);
$names = $book->getSheetNames();
$this->assertSame('运费+货款', $names[0]);
foreach (['汇总', '对账', '前月补提供-9月', '跨月订单-11月', '快递不符', '匹配不到', '厂家未提供', '说明'] as $sheet) {
$this->assertContains($sheet, $names);
}
$recon = $book->getSheetByName('对账')->toArray(null, false, false);
$this->assertSame(['快递单号', '快递公司', '运费', '称重重量', '首重', '面单', '快递单号'], array_slice($recon[0], 0, 7));
$row = collect($recon)->first(fn ($r) => $r[0] === '773444000002');
$this->assertSame('卿德客申通', $row[1]);
$this->assertEquals(6, $row[2]);
$this->assertSame('一致但运费有差', $row[count($row) - 2]);
$swapRow = collect($recon)->first(fn ($r) => $r[0] === 'OLD0000001');
$this->assertSame('773444000020', $swapRow[6]);
$summary = $book->getSheetByName('汇总')->toArray(null, false, false);
$this->assertSame('10月运费', $summary[1][0]);
$total = collect($summary)->first(fn ($r) => $r[0] === '合计');
$this->assertEquals(63, $total[1]);
$this->assertEquals(29, $total[2]);
$this->assertSame([3, 1], [count($book->getSheetByName('快递不符')->toArray()) - 1, count($book->getSheetByName('匹配不到')->toArray()) - 1]);
$book->disconnectWorksheets();
@unlink($out);
// 早期账单没有 raw 列也能直接导出;只读原文件,不重读入库,不改金额和文件状态。
$this->assertSame($before, $db->table('dropship_bill_lines')->orderBy('id')->get()->toJson());
$this->assertSame($filesBefore, $db->table('dropship_bill_files')->orderBy('id')->get()->toJson());
// 同一份账单再传:重复导入,不读入
$again = new UploadedFile($this->xlsx(['账单' => [['快递单号', '运费'], ['773444000001', 8], ['773444000002', 6]]]), '卿德客10月补.xlsx', null, null, true);
@ -202,6 +231,108 @@ final class DropshipFreightTest extends FeatureTestCase
$this->assertSame(1, $store->db()->table('dropship_bill_lines')->where('waybill_no', '773449999999')->count());
}
public function test_single_export_preserves_original_workbook_and_first_source_row_without_changing_bills(): void
{
Storage::fake('local');
$store = app(DropshipFreightStore::class);
$id = $store->saveFactory(null, ['name' => '导出测试', 'warehouse' => self::WAREHOUSE, 'keywords' => '卿德客']);
$path = $this->xlsx([
'运费' => [['原始账单'], [], ['快递单号', '运费', '备注', '备注'],
['00012345678901234567', 4, ' 保留空格 ', '=1+1'], ['00012345678901234567', 6, '第二件', '00001']],
'汇总' => [['厂家自己的汇总']],
'对账' => [['厂家自己的对账']],
]);
$original = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
$sheet = $original->getSheetByName('运费');
$sheet->mergeCells('A1:D1');
$sheet->getStyle('A1')->getFont()->setBold(true)->setSize(18);
$sheet->setCellValue('E4', '=B4*2');
(new Xlsx($original))->save($path);
$original->disconnectWorksheets();
$file = $store->upload([new UploadedFile($path, '导出测试.xlsx', null, null, true)], '2026-10', 'tester')[0];
$db = $store->db();
// 模拟已核对的金额:导出取当前账单结果,不再次解析入库覆盖。
$db->table('dropship_bill_lines')->where('file_id', $file)->update(['amount' => 11]);
$before = $db->table('dropship_bill_lines')->get()->toJson();
$this->ship('00012345678901234567', '卿德客申通', self::WAREHOUSE, '2026-10-03 09:00:00', 1, 10);
$out = tempnam(sys_get_temp_dir(), 'dropship_export_');
$handle = fopen($out, 'wb');
try {
app(DropshipExporter::class)->export(collect($store->factories())->firstWhere('id', $id), '2026-10', $handle);
} finally {
fclose($handle);
}
$book = \PhpOffice\PhpSpreadsheet\IOFactory::load($out);
$this->assertSame(['运费', '汇总', '对账'], array_slice($book->getSheetNames(), 0, 3));
$this->assertTrue($book->getSheetByName('运费')->getStyle('A1')->getFont()->getBold());
$this->assertSame(['A1:D1' => 'A1:D1'], $book->getSheetByName('运费')->getMergeCells());
$this->assertSame('=B4*2', $book->getSheetByName('运费')->getCell('E4')->getValue());
$this->assertSame('厂家自己的汇总', $book->getSheetByName('汇总')->getCell('A1')->getValue());
$data = $book->getSheetByName('对账(系统)')->toArray(null, false, false);
$this->assertSame(['快递单号', '运费', '备注', '备注(2)'], array_slice($data[0], 0, 4));
$this->assertSame(['00012345678901234567', 4, ' 保留空格 ', '=1+1'], array_slice($data[1], 0, 4));
$this->assertEquals(11, $data[1][count($data[0]) - 4]);
$this->assertContains($book->getSheetByName('对账(系统)')->getCell('D2')->getDataType(), [
\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_INLINE,
]);
$book->disconnectWorksheets();
$sourceZip = new \ZipArchive();
$resultZip = new \ZipArchive();
$sourceZip->open($path);
$resultZip->open($out);
$this->assertSame($sourceZip->getFromName('xl/worksheets/sheet1.xml'), $resultZip->getFromName('xl/worksheets/sheet1.xml'));
$sourceZip->close();
$resultZip->close();
$this->assertSame($before, $db->table('dropship_bill_lines')->get()->toJson());
@unlink($path);
@unlink($out);
}
public function test_single_export_supports_csv_and_multiple_original_files(): void
{
Storage::fake('local');
$store = app(DropshipFreightStore::class);
$id = $store->saveFactory(null, ['name' => '导出测试', 'warehouse' => self::WAREHOUSE, 'keywords' => '卿德客']);
$store->upload([
UploadedFile::fake()->createWithContent('导出测试.csv', "快递单号,运费,备注\nCSV001,4,00001\n"),
new UploadedFile($this->xlsx(['明细' => [['快递单号', '运费', '额外'], ['XLSX001', 7, ' 原样 ']]]), '导出测试.xlsx', null, null, true),
], '2026-10', 'tester');
$out = tempnam(sys_get_temp_dir(), 'dropship_export_');
$handle = fopen($out, 'wb');
try {
app(DropshipExporter::class)->export(collect($store->factories())->firstWhere('id', $id), '2026-10', $handle);
} finally {
fclose($handle);
}
$book = \PhpOffice\PhpSpreadsheet\IOFactory::load($out);
$this->assertSame('明细', $book->getSheetNames()[0]);
$this->assertContains('文件1-csv', $book->getSheetNames());
$data = $book->getSheetByName('匹配不到')->toArray(null, false, false);
$this->assertSame(['快递单号', '运费', '备注', '额外'], array_slice($data[0], 0, 4));
$csv = collect(array_slice($data, 1))->first(fn ($r) => $r[0] === 'CSV001');
$xlsx = collect(array_slice($data, 1))->first(fn ($r) => $r[0] === 'XLSX001');
$this->assertSame('00001', $csv[2]);
$this->assertSame(' 原样 ', $xlsx[3]);
$book->disconnectWorksheets();
@unlink($out);
}
public function test_missing_original_file_returns_an_error_instead_of_a_partial_download(): void
{
Storage::fake('local');
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->withExceptionHandling();
$store = app(DropshipFreightStore::class);
$id = $store->saveFactory(null, ['name' => '导出测试', 'warehouse' => self::WAREHOUSE, 'keywords' => '卿德客']);
$file = $store->upload([UploadedFile::fake()->createWithContent('导出测试.csv', "快递单号,运费\nCSV001,4\n")], '2026-10', 'tester')[0];
Storage::disk('local')->delete($store->db()->table('dropship_bill_files')->where('id', $file)->value('stored_path'));
$page = route('business.pages.show', ['section' => 'courier-payables-final', 'page' => 'dropship-freight-reconciliation']);
$this->from($page)->get(route('business.courier-payables-final.dropship-freight.export', ['month' => '2026-10', 'factory' => $id]))
->assertRedirect($page)->assertSessionHasErrors('dropship');
$this->assertSame(1, $store->db()->table('dropship_bill_lines')->count());
$this->assertSame('parsed', $store->db()->table('dropship_bill_files')->value('status'));
}
public function test_keyword_helpers(): void
{
$this->assertSame('卿德客', DropshipFreightStore::warehouseCore('工厂-山东卿德客代发仓'));