代发及快递账单导出按手工版排汇总 (#1590)
This commit is contained in:
parent
510d143d74
commit
6a3a6c0346
46
app/Console/Commands/ImportDropshipSummaryTemplates.php
Normal file
46
app/Console/Commands/ImportDropshipSummaryTemplates.php
Normal file
@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Support\DropshipFreight\DropshipFreightStore;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* 导入代发厂家手工汇总的样子(JSON:[{"factory":"厂家名","title":"10月临沂恒思","headers":["原始","简尚核对","差异"],"labels":["运费",…],"total":"合计"}]),
|
||||
* 导出代发对账时「汇总」表照它套。页面上「导入手工汇总」读的是手工做好的账单本身;这个命令给整理好的清单用(如 10 月首批)。
|
||||
*/
|
||||
final class ImportDropshipSummaryTemplates extends Command
|
||||
{
|
||||
protected $signature = 'dropship-freight:import-summary-templates {file : JSON 文件} {--month= : 这些汇总是哪个月的账单,如 2026-10}';
|
||||
|
||||
protected $description = '导入代发厂家手工汇总的样子,作为代发对账导出「汇总」表的模板';
|
||||
|
||||
public function handle(DropshipFreightStore $store): int
|
||||
{
|
||||
$month = (string) $this->option('month');
|
||||
if (! preg_match('/^20\d{2}-(0[1-9]|1[0-2])$/', $month)) {
|
||||
$this->error('--month 要写成 2026-10 这样');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$blocks = json_decode((string) @file_get_contents((string) $this->argument('file')), true);
|
||||
if (! is_array($blocks)) {
|
||||
$this->error('读不了 JSON 文件');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$blocks = array_values(array_filter(array_map(static fn ($b): ?array => is_array($b) && isset($b['title'], $b['headers'], $b['labels'])
|
||||
&& is_array($b['headers']) && is_array($b['labels'])
|
||||
? ['title' => (string) $b['title'], 'headers' => array_map('strval', $b['headers']), 'labels' => array_map('strval', $b['labels']),
|
||||
'total' => isset($b['total']) ? (string) $b['total'] : '合计', 'factory' => isset($b['factory']) ? (string) $b['factory'] : null,
|
||||
'source' => isset($b['source']) ? (string) $b['source'] : null]
|
||||
: null, $blocks)));
|
||||
$result = $store->saveSummaryTemplates($blocks, $month);
|
||||
$this->info('读到 ' . $result['blocks'] . ' 家,记下 ' . count($result['saved']) . ' 家 ' . $month . ' 的汇总样子:' . implode('、', $result['saved']));
|
||||
if ($result['unknown'] !== []) {
|
||||
$this->warn('系统里没找到这些厂家(没有代发运费的厂家可以不管):' . implode('、', $result['unknown']));
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -117,6 +117,26 @@ final class DropshipFreightController extends Controller
|
||||
. ' 个,失败 ' . $files->where('status', 'failed')->count() . ' 个。');
|
||||
}
|
||||
|
||||
public function importSummaryTemplates(Request $request)
|
||||
{
|
||||
$data = $request->validate([
|
||||
'month' => ['required', 'date_format:Y-m'],
|
||||
'files' => ['required', 'array', 'max:80'], 'files.*' => ['file', 'max:51200'],
|
||||
], [], ['files' => '手工汇总', 'files.*' => '手工汇总']);
|
||||
$files = [];
|
||||
foreach ($data['files'] as $file) {
|
||||
if (! in_array(strtolower($file->getClientOriginalExtension()), ['xlsx', 'xls'], true)) {
|
||||
throw ValidationException::withMessages(['templates' => '只支持 xlsx、xls:' . $file->getClientOriginalName()]);
|
||||
}
|
||||
$files[] = [$file->getClientOriginalName(), (string) $file->getRealPath()];
|
||||
}
|
||||
$result = $this->guard(fn () => $this->store->importSummaryTemplates($files, $data['month']));
|
||||
|
||||
return $this->back($request, ['df_view' => 'upload', 'month' => $data['month']], '读到 ' . $result['blocks'] . ' 份汇总,记下 '
|
||||
. count($result['saved']) . ' 家 ' . $data['month'] . ' 的汇总样子' . ($result['saved'] !== [] ? ':' . implode('、', $result['saved']) : '')
|
||||
. ($result['unknown'] !== [] ? '。没认出的:' . implode('、', array_slice($result['unknown'], 0, 20)) . '(文件名或汇总标题里要有厂家名)' : '') . '。');
|
||||
}
|
||||
|
||||
public function assign(Request $request, int $file)
|
||||
{
|
||||
$data = $request->validate(['factory_id' => ['required', 'integer']]);
|
||||
|
||||
@ -76,6 +76,8 @@ final class StatementExporter
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 和手工版一样,汇总排第一张
|
||||
$book->putFirst(['汇总']);
|
||||
|
||||
// 汇总:每家一个小汇总
|
||||
foreach ($ids as $index => $id) {
|
||||
|
||||
@ -33,6 +33,12 @@ final class StreamingWorkbook
|
||||
/** @var array{path:string,workbook:string,rels:string,styles:?string,stylesXml:?string,names:array<string,true>}|null */
|
||||
private ?array $base = null;
|
||||
|
||||
/** @var array<string,string> 原文件里要改名的表:原名 => 新名 */
|
||||
private array $renames = [];
|
||||
|
||||
/** @var list<string> 排在原文件各表前面的新表(如「汇总」),其余新表排在原文件后面 */
|
||||
private array $first = [];
|
||||
|
||||
/**
|
||||
* 以这个原始 xlsx 为底:原文件的所有工作表原封不动,后面写的表追加在它后面。必须在写任何行之前调用。
|
||||
* 文件不是普通 xlsx(xls、csv、带宏的、Strict 格式、打不开的)时返回 false,照旧生成新文件。
|
||||
@ -150,7 +156,47 @@ final class StreamingWorkbook
|
||||
}
|
||||
}
|
||||
|
||||
/** @param list<string|int|float|null> $cells */
|
||||
/**
|
||||
* 给原文件(base())里的表改名,如「Sheet1」→「厂家账单」。只改表名和引用这张表的公式(单元格公式、条件格式、数据验证、
|
||||
* 图表、定义的名称),单元格内容和格式不动。必须在 base() 之后、写任何行之前调用。
|
||||
*
|
||||
* @param array<string,string> $renames 原名 => 新名
|
||||
*/
|
||||
public function renameBase(array $renames): void
|
||||
{
|
||||
if ($this->base === null || $this->sheets !== []) {
|
||||
return;
|
||||
}
|
||||
$names = array_keys($this->base['names']);
|
||||
$taken = [];
|
||||
$result = [];
|
||||
foreach ($renames as $old => $new) {
|
||||
$old = (string) $old;
|
||||
$new = self::sheetName((string) $new);
|
||||
if ($new === '' || $old === $new || ! isset($this->base['names'][mb_strtolower($old)]) || isset($taken[mb_strtolower($new)])) {
|
||||
continue;
|
||||
}
|
||||
$taken[mb_strtolower($new)] = true;
|
||||
$result[$old] = $new;
|
||||
}
|
||||
// 没改名的表名不能和新名撞
|
||||
foreach ($names as $name) {
|
||||
if (! in_array($name, array_map('mb_strtolower', array_keys($result)), true) && isset($taken[$name])) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
$this->renames = $result;
|
||||
$kept = array_diff($names, array_map('mb_strtolower', array_keys($result)));
|
||||
$this->base['names'] = array_fill_keys([...$kept, ...array_keys($taken)], true);
|
||||
}
|
||||
|
||||
/** 这些新表排在最前面(在原文件的表前面),打开文件时停在第一张。没有原文件时按写入先后排。 @param list<string> $sheets */
|
||||
public function putFirst(array $sheets): void
|
||||
{
|
||||
$this->first = array_values(array_unique(array_map(fn (string $sheet): string => $this->nameOf($sheet), $sheets)));
|
||||
}
|
||||
|
||||
/** @param list<string|int|float|XlsxFormula|null> $cells */
|
||||
public function row(string $sheet, array $cells, bool $bold = false): void
|
||||
{
|
||||
$sheet = $this->nameOf($sheet);
|
||||
@ -171,7 +217,13 @@ final class StreamingWorkbook
|
||||
}
|
||||
$reference = self::column($index + 1) . $number;
|
||||
$style = $bold ? ' s="' . $this->boldStyle . '"' : '';
|
||||
if (is_int($value) || is_float($value)) {
|
||||
if ($value instanceof XlsxFormula) {
|
||||
$cached = $value->cached;
|
||||
$xml .= '<c r="' . $reference . '"' . $style . (is_string($cached) ? ' t="str"' : '') . '><f>' . self::escape($value->expression) . '</f>'
|
||||
. (is_int($cached) || is_float($cached) ? '<v>' . self::number($cached) . '</v>' : (is_string($cached) ? '<v>' . self::escape($cached) . '</v>' : ''))
|
||||
. '</c>';
|
||||
$width = is_int($cached) || is_float($cached) ? strlen(self::number($cached)) : 8;
|
||||
} elseif (is_int($value) || is_float($value)) {
|
||||
$xml .= '<c r="' . $reference . '"' . $style . '><v>' . self::number($value) . '</v></c>';
|
||||
$width = strlen(self::number($value));
|
||||
} else {
|
||||
@ -270,6 +322,9 @@ final class StreamingWorkbook
|
||||
$rels = self::dom($zip, $this->base['rels']);
|
||||
$types = self::dom($zip, '[Content_Types].xml');
|
||||
$sheetsNode = $book->getElementsByTagNameNS(self::MAIN_NS, 'sheets')->item(0);
|
||||
if ($this->renames !== []) {
|
||||
$this->applyRenames($zip, $book);
|
||||
}
|
||||
$maxId = 0;
|
||||
foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'sheet') as $sheet) {
|
||||
$maxId = max($maxId, (int) $sheet->getAttribute('sheetId'));
|
||||
@ -281,6 +336,8 @@ final class StreamingWorkbook
|
||||
$relationshipIds[$relationship->getAttribute('Id')] = true;
|
||||
}
|
||||
$n = 0;
|
||||
$originalCount = $book->getElementsByTagNameNS(self::MAIN_NS, 'sheet')->length;
|
||||
$firstNodes = [];
|
||||
foreach (array_keys($this->sheets) as $name) {
|
||||
do {
|
||||
$n++;
|
||||
@ -293,6 +350,9 @@ final class StreamingWorkbook
|
||||
$sheet->setAttribute('sheetId', (string) ($maxId + $n));
|
||||
$sheet->setAttributeNS(self::REL_NS, 'r:id', $relationshipId);
|
||||
$sheetsNode->appendChild($sheet);
|
||||
if (in_array($name, $this->first, true)) {
|
||||
$firstNodes[array_search($name, $this->first, true)] = $sheet;
|
||||
}
|
||||
$rel = $rels->createElementNS(self::PKG_REL_NS, 'Relationship');
|
||||
$rel->setAttribute('Id', $relationshipId);
|
||||
$rel->setAttribute('Type', self::REL_NS . '/worksheet');
|
||||
@ -303,6 +363,9 @@ final class StreamingWorkbook
|
||||
$override->setAttribute('ContentType', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml');
|
||||
$types->documentElement->appendChild($override);
|
||||
}
|
||||
if ($firstNodes !== []) {
|
||||
$this->moveToFront($zip, $book, $sheetsNode, $firstNodes, $originalCount);
|
||||
}
|
||||
if ($this->base['styles'] === null) {
|
||||
// 原文件没有 styles.xml:补一份只含普通和加粗两种样式的
|
||||
$styleNumber = 0;
|
||||
@ -332,6 +395,110 @@ final class StreamingWorkbook
|
||||
}
|
||||
}
|
||||
|
||||
/** @return list<string> 写进文件的表顺序:putFirst 的在前 */
|
||||
private function orderedNames(): array
|
||||
{
|
||||
$first = array_values(array_filter($this->first, fn (string $name): bool => isset($this->sheets[$name])));
|
||||
|
||||
return [...$first, ...array_values(array_diff(array_keys($this->sheets), $first))];
|
||||
}
|
||||
|
||||
/**
|
||||
* 把新表挪到原文件各表前面:定义名称里按位置记的 localSheetId 跟着往后移,打开时停在第一张,
|
||||
* 原文件里「选中的表」标记去掉(不然打开时会同时选中两张表)。
|
||||
*
|
||||
* @param array<int,DOMElement> $nodes 位置 => 新表的 sheet 元素
|
||||
*/
|
||||
private function moveToFront(ZipArchive $zip, DOMDocument $book, \DOMNode $sheetsNode, array $nodes, int $originalCount): void
|
||||
{
|
||||
ksort($nodes);
|
||||
$anchor = $sheetsNode->firstChild;
|
||||
while ($anchor !== null && ! ($anchor instanceof DOMElement && $anchor->localName === 'sheet')) {
|
||||
$anchor = $anchor->nextSibling;
|
||||
}
|
||||
foreach ($nodes as $node) {
|
||||
$sheetsNode->insertBefore($node, $anchor);
|
||||
}
|
||||
$shift = count($nodes);
|
||||
foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'definedName') as $defined) {
|
||||
if ($defined->hasAttribute('localSheetId') && (int) $defined->getAttribute('localSheetId') < $originalCount) {
|
||||
$defined->setAttribute('localSheetId', (string) ((int) $defined->getAttribute('localSheetId') + $shift));
|
||||
}
|
||||
}
|
||||
foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'workbookView') as $view) {
|
||||
$view->setAttribute('activeTab', '0');
|
||||
$view->setAttribute('firstSheet', '0');
|
||||
}
|
||||
if ($book->getElementsByTagNameNS(self::MAIN_NS, 'workbookView')->length === 0) {
|
||||
$views = $book->createElementNS(self::MAIN_NS, 'bookViews');
|
||||
$view = $book->createElementNS(self::MAIN_NS, 'workbookView');
|
||||
$view->setAttribute('activeTab', '0');
|
||||
$views->appendChild($view);
|
||||
$book->documentElement->insertBefore($views, $sheetsNode);
|
||||
}
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$part = (string) $zip->getNameIndex($i);
|
||||
if (! preg_match('#^xl/worksheets/[^/]+\.xml$#i', $part) || str_contains($part, 'cbr_sheet')) {
|
||||
continue;
|
||||
}
|
||||
$xml = $zip->getFromIndex($i);
|
||||
if ($xml !== false && str_contains($xml, 'tabSelected="1"')) {
|
||||
$zip->addFromString($part, str_replace(' tabSelected="1"', '', $xml));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 原文件表改名:workbook.xml 里的表名、定义的名称,和各部件里引用这些表的公式。 */
|
||||
private function applyRenames(ZipArchive $zip, DOMDocument $book): void
|
||||
{
|
||||
foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'sheet') as $sheet) {
|
||||
$name = $sheet->getAttribute('name');
|
||||
if (isset($this->renames[$name])) {
|
||||
$sheet->setAttribute('name', $this->renames[$name]);
|
||||
}
|
||||
}
|
||||
foreach ($book->getElementsByTagNameNS(self::MAIN_NS, 'definedName') as $defined) {
|
||||
$text = self::renameInFormula($defined->textContent, $this->renames);
|
||||
if ($text !== $defined->textContent) {
|
||||
while ($defined->firstChild !== null) {
|
||||
$defined->removeChild($defined->firstChild);
|
||||
}
|
||||
$defined->appendChild($book->createTextNode($text));
|
||||
}
|
||||
}
|
||||
$escaped = [];
|
||||
foreach ($this->renames as $old => $new) {
|
||||
$escaped[self::escape($old)] = self::escape($new);
|
||||
}
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$part = (string) $zip->getNameIndex($i);
|
||||
if (! preg_match('#^xl/(worksheets|charts|chartsheets)/[^/]+\.xml$#i', $part)) {
|
||||
continue;
|
||||
}
|
||||
$xml = $zip->getFromIndex($i);
|
||||
if ($xml === false || ! array_filter(array_keys($escaped), static fn (string $old): bool => str_contains($xml, $old))) {
|
||||
continue;
|
||||
}
|
||||
$changed = preg_replace_callback('#(<((?:\w+:)?(?:f|formula\d?))(?:\s[^>]*)?(?<!/)>)(.*?)(</\2>)#s',
|
||||
static fn (array $m): string => $m[1] . self::renameInFormula($m[3], $escaped) . $m[4], $xml);
|
||||
if (is_string($changed) && $changed !== $xml) {
|
||||
$zip->addFromString($part, $changed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 公式里 Sheet1!A1、'Sheet 1'!A1 这样的表引用换成新表名(新名一律加单引号)。 */
|
||||
private static function renameInFormula(string $formula, array $renames): string
|
||||
{
|
||||
foreach ($renames as $old => $new) {
|
||||
$quotedNew = "'" . str_replace("'", "''", (string) $new) . "'!";
|
||||
$formula = str_replace("'" . str_replace("'", "''", (string) $old) . "'!", $quotedNew, $formula);
|
||||
$formula = preg_replace('/(?<![\p{L}\p{N}_.\'\]])' . preg_quote((string) $old, '/') . '!/u', $quotedNew, $formula) ?? $formula;
|
||||
}
|
||||
|
||||
return $formula;
|
||||
}
|
||||
|
||||
private const STYLES = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
|
||||
. '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
|
||||
. '<fonts count="2"><font><sz val="11"/><name val="Calibri"/></font><font><b/><sz val="11"/><name val="Calibri"/></font></fonts>'
|
||||
@ -351,7 +518,7 @@ final class StreamingWorkbook
|
||||
$contentTypes = '';
|
||||
$workbook = '';
|
||||
$relations = '';
|
||||
foreach (array_keys($this->sheets) as $i => $name) {
|
||||
foreach ($this->orderedNames() as $i => $name) {
|
||||
$n = $i + 1;
|
||||
$zip->addFile($this->finishSheet($name), 'xl/worksheets/sheet' . $n . '.xml');
|
||||
$contentTypes .= '<Override PartName="/xl/worksheets/sheet' . $n . '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
|
||||
|
||||
12
app/Support/CourierBills/XlsxFormula.php
Normal file
12
app/Support/CourierBills/XlsxFormula.php
Normal file
@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\CourierBills;
|
||||
|
||||
/** StreamingWorkbook::row() 里的公式单元格:写成 Excel 公式,带上算好的值(不重算的查看器也能看到数)。 */
|
||||
final class XlsxFormula
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $expression,
|
||||
public readonly int|float|string|null $cached = null,
|
||||
) {}
|
||||
}
|
||||
@ -7,6 +7,7 @@ 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;
|
||||
@ -14,7 +15,7 @@ use RuntimeException;
|
||||
|
||||
/**
|
||||
* 代发运费对账单导出(内部版),和快递账单对账的导出一个样子:
|
||||
* 以厂家发来的原始账单为底(每张表原样不动),后面追加 汇总、对账、前月补提供-X月、跨月订单-X月、快递不符、重复、匹配不到、未发出、
|
||||
* 和手工版一样:第一张是「汇总」(照这家上月手工汇总的样子),然后是厂家发来的原始账单(表名改叫「厂家账单」,内容原样不动),后面接 对账、前月补提供-X月、跨月订单-X月、快递不符、重复、匹配不到、未发出、
|
||||
* 厂家未提供、说明;没有数据的表不生成。
|
||||
* 对账类子表的列顺序:厂家账单原始列(一单多行取第一行)→ 财务指定的 25 列 → 发货数据其余字段 → 厂家运费合计、结算运费、分类、说明。
|
||||
*/
|
||||
@ -58,17 +59,22 @@ final class DropshipExporter
|
||||
->where('status', 'parsed')->orderBy('id')->get();
|
||||
$book = new StreamingWorkbook();
|
||||
$baseFileId = null;
|
||||
$baseCount = 0;
|
||||
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) {
|
||||
$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);
|
||||
[$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 = ['厂家运费(这一单合计)', '结算运费', '分类', '说明'];
|
||||
@ -132,10 +138,42 @@ final class DropshipExporter
|
||||
$book->writeTo($output);
|
||||
}
|
||||
|
||||
/** 汇总:按分类,厂家运费 / 结算运费(我方核算)/ 差异,口径同手工代发账单的「运费」那一行。 */
|
||||
/**
|
||||
* 汇总:照这家上月手工汇总的样子(标题、表头、类目顺序),月份顺延。运费行系统填(厂家开的运费合计 / 按我方核算的结算运费),
|
||||
* 货款、记账等先空着手工填;差异和合计行是公式,手工填了会跟着算。下面再附运费按分类的明细,说明运费差在哪。
|
||||
*/
|
||||
private function writeSummary(StreamingWorkbook $book, object $factory, string $month, array $rows): void
|
||||
{
|
||||
$book->row('汇总', [$factory->name . ' ' . $month . ' 代发运费', '厂家运费', '结算运费(我方核算)', '差异', '单数'], true);
|
||||
$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);
|
||||
|
||||
// 运费按分类:厂家开的每一单落在哪一类、结算多少
|
||||
$groups = [];
|
||||
foreach ($rows as $r) {
|
||||
$label = in_array($r['status'], [Category::MATCH, Category::DIFF, Category::UNCALCULATED], true)
|
||||
@ -149,21 +187,37 @@ final class DropshipExporter
|
||||
$groups[$label]['settle'] = (float) $groups[$label]['settle'] + (float) $r['settle'];
|
||||
}
|
||||
}
|
||||
$bill = $settle = 0.0;
|
||||
$book->row('汇总', []);
|
||||
$book->row('汇总', []);
|
||||
$book->row('汇总', ['运费按分类', '厂家运费', '结算运费(我方核算)', '差异', '单数'], true);
|
||||
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('汇总', ['合计', round((float) $billTotal, 2), round((float) $settleTotal, 2), round((float) $billTotal - (float) $settleTotal, 2), count($rows)], true);
|
||||
$book->row('汇总', []);
|
||||
$book->row('汇总', ['代发仓:' . $factory->warehouse . ';代发快递关键字:' . $factory->keywords
|
||||
. '。一致类和前月补提供按我方核算运费结算;厂家没开的、快递不符、重复、匹配不到、未发出、跨月订单本月不付。']);
|
||||
. '。一致类和前月补提供按我方核算运费结算;厂家没开的、快递不符、重复、匹配不到、未发出、跨月订单本月不付。'
|
||||
. ($template['from'] === null ? '这家还没导入过手工汇总,汇总表用的默认样子。' : '汇总表照 ' . $template['from'] . ' 手工汇总的样子排。')]);
|
||||
}
|
||||
|
||||
/** 差异 = 原始 − 简尚,两格都空就空着(公式,手工填了会跟着算)。 */
|
||||
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): array
|
||||
private function writeOriginal(StreamingWorkbook $book, $files, ?int $baseFileId, PDO $index, int $baseCount = 0): array
|
||||
{
|
||||
$originals = [];
|
||||
$used = [];
|
||||
@ -179,17 +233,21 @@ final class DropshipExporter
|
||||
$insert = $index->prepare('INSERT INTO originals VALUES (?, ?, ?, ?)');
|
||||
$index->beginTransaction();
|
||||
$reader = new BillWorkbookReader();
|
||||
foreach ($files->values() as $fileIndex => $file) {
|
||||
$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 = (string) $sheet;
|
||||
$name = self::originalName($ordinal, (string) $sheet, $sheetCount);
|
||||
if (! $isBase) {
|
||||
$base = '文件' . ($fileIndex + 1) . '-' . $name;
|
||||
$base = $name;
|
||||
$name = $book->nameOf($base);
|
||||
for ($n = 2; isset($used[mb_strtolower($name)]); $n++) {
|
||||
$suffix = '-' . $n;
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Support\DropshipFreight;
|
||||
|
||||
use App\Support\CourierBills\BillWorkbookReader;
|
||||
use App\Support\CourierBills\CourierBillStore;
|
||||
use App\Support\CourierBills\ShippingLookup;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
@ -198,6 +199,93 @@ final class DropshipFreightStore
|
||||
Storage::disk(self::DISK)->delete($file->stored_path);
|
||||
}
|
||||
|
||||
/**
|
||||
* 这家这个月导出用的汇总样子:这个月或之前最近一个月的手工汇总,月份顺延到这个月;一份都没有就用默认样子。
|
||||
*
|
||||
* @return array{title:string,headers:list<string>,labels:list<string>,total:string,from:?string}
|
||||
*/
|
||||
public function summaryTemplate(object $factory, string $month): array
|
||||
{
|
||||
$row = $this->db()->table('dropship_summary_templates')->where('factory_id', $factory->id)->where('bill_month', '<=', $month)
|
||||
->orderByDesc('bill_month')->first();
|
||||
if ($row === null) {
|
||||
return DropshipSummaryTemplate::fallback($month, (string) $factory->name) + ['from' => null];
|
||||
}
|
||||
$delta = ((int) substr($month, 0, 4) - (int) substr((string) $row->bill_month, 0, 4)) * 12
|
||||
+ (int) substr($month, 5, 2) - (int) substr((string) $row->bill_month, 5, 2);
|
||||
$template = DropshipSummaryTemplate::roll(['title' => (string) $row->title, 'headers' => array_values((array) json_decode((string) $row->headers, true)),
|
||||
'labels' => array_values((array) json_decode((string) $row->labels, true)), 'total' => (string) $row->total_label], $delta);
|
||||
|
||||
return $template + ['from' => (string) $row->bill_month];
|
||||
}
|
||||
|
||||
/**
|
||||
* 从手工做好的代发账单(带「汇总」表)里读汇总的样子。
|
||||
*
|
||||
* @param list<array{0:string,1:string}> $files [原文件名, 路径]
|
||||
* @return array{blocks:int,saved:list<string>,unknown:list<string>}
|
||||
*/
|
||||
public function importSummaryTemplates(array $files, string $month): array
|
||||
{
|
||||
$reader = new BillWorkbookReader();
|
||||
$blocks = [];
|
||||
$unknown = [];
|
||||
foreach ($files as [$name, $path]) {
|
||||
$template = DropshipSummaryTemplate::find($reader->sheets($path, strtolower(pathinfo($name, PATHINFO_EXTENSION))));
|
||||
if ($template === null) {
|
||||
$unknown[] = $name . '(没找到汇总)';
|
||||
continue;
|
||||
}
|
||||
$blocks[] = $template + ['source' => $name, 'fallback' => $name];
|
||||
}
|
||||
$result = $this->saveSummaryTemplates($blocks, $month);
|
||||
$result['unknown'] = [...$unknown, ...$result['unknown']];
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{title:string,headers:list<string>,labels:list<string>,total?:string,factory?:?string,source?:?string,fallback?:?string}> $blocks
|
||||
* factory = 厂家名(有就按它认),否则按标题里的厂家名认,再不行按文件名认
|
||||
* @return array{blocks:int,saved:list<string>,unknown:list<string>}
|
||||
*/
|
||||
public function saveSummaryTemplates(array $blocks, string $month): array
|
||||
{
|
||||
$factories = $this->factories();
|
||||
$saved = [];
|
||||
$unknown = [];
|
||||
foreach ($blocks as $block) {
|
||||
$factory = null;
|
||||
foreach ([$block['factory'] ?? null, DropshipSummaryTemplate::titleName((string) $block['title']), $block['fallback'] ?? null] as $hint) {
|
||||
$hint = trim((string) $hint);
|
||||
if ($hint === '') {
|
||||
continue;
|
||||
}
|
||||
$factory = collect($factories)->first(static fn ($f): bool => (string) $f->name === $hint) ?? self::identify($hint, $factories);
|
||||
if ($factory !== null) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($factory === null) {
|
||||
$unknown[] = ($block['factory'] ?? null) ?: (($block['source'] ?? null) ?: $block['title']);
|
||||
continue;
|
||||
}
|
||||
$headers = array_values(array_map('strval', (array) $block['headers']));
|
||||
$this->db()->table('dropship_summary_templates')->updateOrInsert(
|
||||
['factory_id' => $factory->id, 'bill_month' => $month],
|
||||
['title' => mb_substr((string) $block['title'], 0, 255),
|
||||
'headers' => json_encode(array_slice(array_pad($headers, 3, ''), 0, 3), JSON_UNESCAPED_UNICODE),
|
||||
'labels' => json_encode(array_values(array_map('strval', (array) $block['labels'])), JSON_UNESCAPED_UNICODE),
|
||||
'total_label' => mb_substr((string) (($block['total'] ?? '') ?: '合计'), 0, 32),
|
||||
'source' => isset($block['source']) ? mb_substr((string) $block['source'], 0, 255) : null,
|
||||
'created_at' => now(), 'updated_at' => now()],
|
||||
);
|
||||
$saved[(int) $factory->id] = (string) $factory->name;
|
||||
}
|
||||
|
||||
return ['blocks' => count($blocks), 'saved' => array_values($saved), 'unknown' => array_values(array_unique($unknown))];
|
||||
}
|
||||
|
||||
/** @param list<object> $factories */
|
||||
private function register(string $name, string $path, string $month, array $factories, string $user): int
|
||||
{
|
||||
|
||||
131
app/Support/DropshipFreight/DropshipSummaryTemplate.php
Normal file
131
app/Support/DropshipFreight/DropshipSummaryTemplate.php
Normal file
@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\DropshipFreight;
|
||||
|
||||
use App\Support\CourierBills\SummaryTemplate;
|
||||
|
||||
/**
|
||||
* 代发对账「汇总」表的样子,照这家上个月手工做的汇总套:
|
||||
* 10月临沂恒思 | 原始 | 简尚核对 | 差异 或 10月 | 厂家金额 | 简尚金额 | 差异
|
||||
* 运费 | … 运费 / 货款 / 记账 …
|
||||
* 记账 / 代发 / 退货 … 汇总
|
||||
* 合计
|
||||
* 标题和类目名里的月份按账单月份顺延。系统算得出的(运费)填进去,其余空着手工填,合计行是公式。
|
||||
*/
|
||||
final class DropshipSummaryTemplate
|
||||
{
|
||||
public const TOTALS = ['合计', '汇总', '总计'];
|
||||
|
||||
/** 没有手工汇总可参照时用的样子(手工汇总里最常见的那种)。 */
|
||||
public const DEFAULT = ['title' => '{month}月{factory}', 'headers' => ['原始', '简尚核对', '差异'], 'labels' => ['运费', '记账', '代发', '退货'], 'total' => '合计'];
|
||||
|
||||
/**
|
||||
* 从手工做好的代发账单里找汇总块:标题格以「X月」开头,右边三格里有「简尚…」和「差异/差额」。优先看名字带「汇总」的表。
|
||||
*
|
||||
* @param iterable<string, iterable<int, array<int,mixed>>> $sheets 表名 => 行
|
||||
* @return array{title:string,headers:list<string>,labels:list<string>,total:string}|null
|
||||
*/
|
||||
public static function find(iterable $sheets): ?array
|
||||
{
|
||||
$ordered = [];
|
||||
foreach ($sheets as $name => $rows) {
|
||||
$rows = self::firstRows($rows, 60);
|
||||
str_contains((string) $name, '汇总') ? array_unshift($ordered, $rows) : $ordered[] = $rows;
|
||||
}
|
||||
foreach ($ordered as $rows) {
|
||||
if (($template = self::parse($rows)) !== null) {
|
||||
return $template;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @param list<array<int,mixed>> $rows */
|
||||
public static function parse(array $rows): ?array
|
||||
{
|
||||
foreach ($rows as $i => $row) {
|
||||
$row = array_values($row);
|
||||
foreach ($row as $c => $value) {
|
||||
if (! is_string($value) || ! preg_match('/^\s*(\d{4}[.年])?\d{1,2}月/u', $value)) {
|
||||
continue;
|
||||
}
|
||||
$headers = array_map(static fn ($v): string => trim((string) $v), array_slice($row, $c + 1, 3));
|
||||
if (count($headers) < 3 || ! array_filter($headers, static fn (string $h): bool => str_contains($h, '简尚'))
|
||||
|| ! array_filter($headers, static fn (string $h): bool => str_contains($h, '差'))) {
|
||||
continue;
|
||||
}
|
||||
$labels = [];
|
||||
$total = '合计';
|
||||
foreach (array_slice($rows, $i + 1, 30) as $next) {
|
||||
$next = array_values($next);
|
||||
$label = trim((string) ($next[$c] ?? ''));
|
||||
if ($label === '') {
|
||||
if ($labels !== []) {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (preg_match('/^[\d.\-\s]+$/u', $label)) {
|
||||
continue;
|
||||
}
|
||||
if (in_array($label, self::TOTALS, true)) {
|
||||
$total = $label;
|
||||
break;
|
||||
}
|
||||
$labels[] = $label;
|
||||
}
|
||||
if ($labels === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return ['title' => trim($value), 'headers' => $headers, 'labels' => $labels, 'total' => $total];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 模板月份顺延 $delta 个月(标题和类目名里的「X月」)。 */
|
||||
public static function roll(array $template, int $delta): array
|
||||
{
|
||||
$template['title'] = SummaryTemplate::roll((string) $template['title'], $delta);
|
||||
$template['labels'] = array_map(static fn (string $l): string => SummaryTemplate::roll($l, $delta), array_values($template['labels']));
|
||||
|
||||
return $template;
|
||||
}
|
||||
|
||||
public static function fallback(string $month, string $factory): array
|
||||
{
|
||||
$template = self::DEFAULT;
|
||||
$template['title'] = str_replace(['{month}', '{factory}'], [(string) (int) substr($month, 5, 2), $factory], $template['title']);
|
||||
|
||||
return $template;
|
||||
}
|
||||
|
||||
/** 「运费」「10月运费」「运费10月」算运费行(系统填)。 */
|
||||
public static function isFreight(string $label): bool
|
||||
{
|
||||
return (bool) preg_match('/^((\d{1,2}月)?运费|运费(\d{1,2}月)?)$/u', trim($label));
|
||||
}
|
||||
|
||||
/** 标题去掉月份,剩下的是厂家名(可能为空,如「10月」)。 */
|
||||
public static function titleName(string $title): string
|
||||
{
|
||||
return trim(preg_replace('/^\s*(\d{4}[.年])?\d{1,2}月(份)?/u', '', $title) ?? '');
|
||||
}
|
||||
|
||||
/** @return list<array<int,mixed>> */
|
||||
private static function firstRows(iterable $rows, int $limit): array
|
||||
{
|
||||
$result = [];
|
||||
foreach ($rows as $row) {
|
||||
$result[] = (array) $row;
|
||||
if (count($result) >= $limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 代发厂家手工汇总的样子(标题、表头、类目,不存金额):导出代发对账时「汇总」表照它套,月份顺延。
|
||||
*/
|
||||
return new class extends Migration {
|
||||
public function up(): void
|
||||
{
|
||||
Schema::connection('business_mirror')->create('dropship_summary_templates', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('factory_id');
|
||||
$table->char('bill_month', 7)->comment('这份手工汇总是哪个月的账单');
|
||||
$table->string('title', 255)->comment('标题格,如「10月临沂恒思」「10月」');
|
||||
$table->text('headers')->comment('JSON:右边三格表头,如 原始/简尚核对/差异');
|
||||
$table->text('labels')->comment('JSON:类目名,按手工汇总的顺序');
|
||||
$table->string('total_label', 32)->default('合计');
|
||||
$table->string('source', 255)->nullable()->comment('从哪个文件读的');
|
||||
$table->timestamps();
|
||||
$table->unique(['factory_id', 'bill_month'], 'dropship_summary_template_factory_month');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::connection('business_mirror')->dropIfExists('dropship_summary_templates');
|
||||
}
|
||||
};
|
||||
@ -12,6 +12,17 @@
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="cbr-panel" aria-label="导入手工汇总">
|
||||
<h3>导入手工汇总(只读样子)</h3>
|
||||
<form method="POST" action="{{ $action('import-summary-templates') }}" enctype="multipart/form-data" class="cbr-panel-body cbr-form">
|
||||
@csrf
|
||||
<label>这些汇总是哪个月的<input type="month" name="month" value="{{ $month }}" required></label>
|
||||
<input type="file" name="files[]" multiple required accept=".xlsx,.xls" aria-label="手工做好的代发账单">
|
||||
<button type="submit">导入汇总样子</button>
|
||||
<span class="cbr-muted">导出单家对账时,「汇总」表照这家手工汇总的样子排:标题、表头(原始 / 简尚核对 / 差异,或 厂家金额 / 简尚金额 / 差异)、类目顺序都照抄,月份自动顺延;运费系统填,货款、记账等先空着手工填,合计行是公式。传手工做好的代发账单(带「汇总」表)就行,只读样子不读金额;按文件名或汇总标题认厂家。没传过的厂家用「原始 / 简尚核对 / 差异」和 运费、记账、代发、退货。</span>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="cbr-panel" aria-label="本月已上传文件">
|
||||
<h3>{{ $month }} 已上传文件</h3>
|
||||
<div class="cbr-scroll">
|
||||
|
||||
@ -754,6 +754,7 @@ foreach (['courier-payables', 'courier-payables-final'] as $courierBillSection)
|
||||
->group(function () use ($courierBillSection) {
|
||||
$controller = \App\Http\Controllers\Business\DropshipFreightController::class;
|
||||
Route::post('upload', [$controller, 'upload'])->name('upload')->defaults('section', $courierBillSection);
|
||||
Route::post('summary-templates/import', [$controller, 'importSummaryTemplates'])->name('import-summary-templates')->defaults('section', $courierBillSection);
|
||||
Route::post('files/{file}/assign', [$controller, 'assign'])->whereNumber('file')->name('assign')->defaults('section', $courierBillSection);
|
||||
Route::post('files/{file}/delete', [$controller, 'deleteFile'])->whereNumber('file')->name('delete-file')->defaults('section', $courierBillSection);
|
||||
Route::post('factories', [$controller, 'saveFactory'])->name('save-factory')->defaults('section', $courierBillSection);
|
||||
|
||||
@ -309,7 +309,7 @@ final class CourierBillReconciliationTest extends FeatureTestCase
|
||||
app(StatementExporter::class)->export($statementId, $handle);
|
||||
fclose($handle);
|
||||
$book = IOFactory::createReader('Xlsx')->load($path);
|
||||
$this->assertSame(['Sheet1', '汇总', '对账', '匹配不到', '未提供', '说明'], $book->getSheetNames());
|
||||
$this->assertSame(['汇总', 'Sheet1', '对账', '匹配不到', '未提供', '说明'], $book->getSheetNames());
|
||||
$recon = $book->getSheetByName('对账');
|
||||
$header = $recon->rangeToArray('A1:AE1')[0];
|
||||
$this->assertSame(['运单号', '运费', '收件人电话', '称重重量', '首重'], array_slice($header, 0, 5));
|
||||
@ -717,7 +717,7 @@ final class CourierBillReconciliationTest extends FeatureTestCase
|
||||
app(StatementExporter::class)->export((int) $file->statement_id, $handle);
|
||||
fclose($handle);
|
||||
$book = IOFactory::createReader('Xlsx')->load($out);
|
||||
$this->assertSame(['账单明细', '退货数据', '加收&上楼费'], array_slice($book->getSheetNames(), 0, 3));
|
||||
$this->assertSame(['汇总', '账单明细', '退货数据', '加收&上楼费'], array_slice($book->getSheetNames(), 0, 4)); // 和手工版一样汇总排第一
|
||||
$this->assertSame('南昌中通退货10.23', (string) $book->getSheetByName('退货数据')->getCell('A1')->getValue());
|
||||
$this->assertSame(3, $book->getSheetByName('加收&上楼费')->getHighestRow());
|
||||
$notes = $book->getSheetByName('说明')->toArray();
|
||||
@ -824,7 +824,7 @@ final class CourierBillReconciliationTest extends FeatureTestCase
|
||||
app(StatementExporter::class)->export($id, $handle);
|
||||
fclose($handle);
|
||||
$book = IOFactory::createReader('Xlsx')->load($output);
|
||||
$names = [$book->getSheetNames()[0], mb_substr('文件2-' . $sheetName, 0, 31)];
|
||||
$names = [$book->getSheetNames()[1], mb_substr('文件2-' . $sheetName, 0, 31)];
|
||||
$this->assertSame($sheetName, $names[0]);
|
||||
$this->assertNotSame($names[0], $names[1]);
|
||||
foreach ($names as $index => $name) {
|
||||
@ -857,7 +857,8 @@ final class CourierBillReconciliationTest extends FeatureTestCase
|
||||
for ($index = 0; $index < $baseZip->numFiles; $index++) {
|
||||
$part = $baseZip->getNameIndex($index);
|
||||
if (str_starts_with($part, 'xl/worksheets/')) {
|
||||
$this->assertSame($baseZip->getFromName($part), $exportZip->getFromName($part), $part);
|
||||
// 汇总挪到第一张、打开时停在汇总:原表只去掉「选中」标记,其余一个字节都不改
|
||||
$this->assertSame(str_replace(' tabSelected="1"', '', $baseZip->getFromName($part)), $exportZip->getFromName($part), $part);
|
||||
}
|
||||
}
|
||||
$exportZip->close();
|
||||
|
||||
@ -141,13 +141,25 @@ 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();
|
||||
// 导入这家 10 月手工做好的账单:只读汇总的样子(标题、表头、类目),导出汇总照它排
|
||||
$manual = new UploadedFile($this->xlsx(['运费+货款' => [['快递单号', '运费'], ['1', 2]], '汇总' => [
|
||||
['10月', '厂家金额', '简尚金额', '差异'], ['运费', 37923.5, 37612.5, 311], ['货款', 151323.6, 151323.6, 0], ['记账', null, -3645.9, 3645.9],
|
||||
['汇总', 189247.1, 185290.2, 3956.9],
|
||||
]]), '卿德客10月手工.xlsx', null, null, true);
|
||||
$this->post(route("business.$section.dropship-freight.import-summary-templates"), ['month' => '2026-10', 'files' => [$manual]])
|
||||
->assertRedirect()->assertSessionHas('dropship_message');
|
||||
$this->assertSame(['10月', '["运费","货款","记账"]', '汇总'], array_values((array) $db->table('dropship_summary_templates')
|
||||
->where('factory_id', $factory->id)->where('bill_month', '2026-10')->first(['title', 'labels', 'total_label'])));
|
||||
$november = app(DropshipFreightStore::class)->summaryTemplate($f, '2026-11');
|
||||
$this->assertSame(['11月', ['运费', '货款', '记账'], '2026-10'], [$november['title'], $november['labels'], $november['from']]);
|
||||
$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]);
|
||||
$this->assertSame(['汇总', '厂家账单'], array_slice($names, 0, 2)); // 和手工版一样:汇总第一张,原账单叫「厂家账单」
|
||||
$this->assertSame('卿德客申通', $book->getSheetByName('厂家账单')->getCell('B2')->getValue());
|
||||
foreach (['汇总', '对账', '前月补提供-9月', '跨月订单-11月', '快递不符', '匹配不到', '厂家未提供', '说明'] as $sheet) {
|
||||
$this->assertContains($sheet, $names);
|
||||
}
|
||||
@ -159,8 +171,17 @@ final class DropshipFreightTest extends FeatureTestCase
|
||||
$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]);
|
||||
$sheet = $book->getSheetByName('汇总');
|
||||
$summary = $sheet->toArray(null, false, false);
|
||||
$this->assertSame(['10月', '厂家金额', '简尚金额', '差异'], array_slice($summary[0], 0, 4));
|
||||
$this->assertSame(['运费', '货款', '记账', '汇总'], [$summary[1][0], $summary[2][0], $summary[3][0], $summary[4][0]]);
|
||||
$this->assertEquals([63, 29], [$summary[1][1], $summary[1][2]]);
|
||||
$this->assertNull($summary[2][1]); // 货款先空着手工填
|
||||
$this->assertSame('=SUM(B2:B4)', $sheet->getCell('B5')->getValue()); // 合计是公式,手工填了跟着算
|
||||
$sheet->setCellValue('C4', -100);
|
||||
$this->assertEquals(100, $sheet->getCell('D4')->getCalculatedValue());
|
||||
$this->assertEquals(-71, $sheet->getCell('C5')->getCalculatedValue());
|
||||
$this->assertContains('10月运费', array_column($summary, 0)); // 下面附运费按分类
|
||||
$total = collect($summary)->first(fn ($r) => $r[0] === '合计');
|
||||
$this->assertEquals(63, $total[1]);
|
||||
$this->assertEquals(29, $total[2]);
|
||||
@ -263,16 +284,18 @@ final class DropshipFreightTest extends FeatureTestCase
|
||||
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(['汇总', '厂家账单-运费', '厂家账单-汇总', '厂家账单-对账', '对账'], array_slice($book->getSheetNames(), 0, 5));
|
||||
$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());
|
||||
$this->assertSame(['10月导出测试', '原始', '简尚核对', '差异'], array_slice($book->getSheetByName('汇总')->toArray(null, false, false)[0], 0, 4));
|
||||
$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(), [
|
||||
$this->assertContains($book->getSheetByName('对账')->getCell('D2')->getDataType(), [
|
||||
\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_INLINE,
|
||||
]);
|
||||
$book->disconnectWorksheets();
|
||||
@ -280,7 +303,8 @@ final class DropshipFreightTest extends FeatureTestCase
|
||||
$resultZip = new \ZipArchive();
|
||||
$sourceZip->open($path);
|
||||
$resultZip->open($out);
|
||||
$this->assertSame($sourceZip->getFromName('xl/worksheets/sheet1.xml'), $resultZip->getFromName('xl/worksheets/sheet1.xml'));
|
||||
// 原表一个字节都不改,只去掉「选中」标记(打开时停在汇总)
|
||||
$this->assertSame(str_replace(' tabSelected="1"', '', $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());
|
||||
@ -305,8 +329,9 @@ final class DropshipFreightTest extends FeatureTestCase
|
||||
fclose($handle);
|
||||
}
|
||||
$book = \PhpOffice\PhpSpreadsheet\IOFactory::load($out);
|
||||
$this->assertSame('明细', $book->getSheetNames()[0]);
|
||||
$this->assertContains('文件1-csv', $book->getSheetNames());
|
||||
$this->assertSame(['汇总', '厂家账单', '厂家账单2'], array_slice($book->getSheetNames(), 0, 3)); // xlsx 原样做底叫「厂家账单」,csv 按值复制
|
||||
$this->assertSame(' 原样 ', (string) $book->getSheetByName('厂家账单')->getCell('C2')->getValue());
|
||||
$this->assertSame('CSV001', (string) $book->getSheetByName('厂家账单2')->getCell('A2')->getValue());
|
||||
$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');
|
||||
|
||||
54
tests/Unit/StreamingWorkbookTest.php
Normal file
54
tests/Unit/StreamingWorkbookTest.php
Normal file
@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit;
|
||||
|
||||
use App\Support\CourierBills\StreamingWorkbook;
|
||||
use App\Support\CourierBills\XlsxFormula;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
use PhpOffice\PhpSpreadsheet\NamedRange;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class StreamingWorkbookTest extends TestCase
|
||||
{
|
||||
public function test_base_sheets_renamed_with_formulas_and_summary_put_first(): void
|
||||
{
|
||||
$source = new Spreadsheet();
|
||||
$bill = $source->getActiveSheet()->setTitle('Sheet1');
|
||||
$bill->fromArray([['单号', '运费'], ['A1', 5], ['A2', 7]]);
|
||||
$total = $source->createSheet()->setTitle('账单 总表');
|
||||
$total->setCellValue('A1', '=SUM(Sheet1!B2:B3)');
|
||||
$total->setCellValue('A2', "=SUM('Sheet1'!B2:B3)+'账单 总表'!B1");
|
||||
$total->setCellValue('B1', 1);
|
||||
$source->addNamedRange(new NamedRange('运费列', $bill, '$B$2:$B$3'));
|
||||
$source->addNamedRange(new NamedRange('本表', $total, '$B$1', true));
|
||||
$source->setActiveSheetIndex(1);
|
||||
$path = tempnam(sys_get_temp_dir(), 'swb') . '.xlsx';
|
||||
(new Xlsx($source))->save($path);
|
||||
|
||||
$book = new StreamingWorkbook();
|
||||
$this->assertSame(['Sheet1', '账单 总表'], $book->base($path));
|
||||
$book->renameBase(['Sheet1' => '厂家账单-Sheet1', '账单 总表' => '厂家账单-账单 总表']);
|
||||
$book->putFirst(['汇总']);
|
||||
$book->row('汇总', ['10月', '原始', '简尚核对', '差异'], true);
|
||||
$book->row('汇总', ['运费', 12, 10, new XlsxFormula('N(B2)-N(C2)', 2)]);
|
||||
$book->row('对账', ['单号']);
|
||||
$out = tempnam(sys_get_temp_dir(), 'swo') . '.xlsx';
|
||||
$book->writeTo($handle = fopen($out, 'wb'));
|
||||
fclose($handle);
|
||||
|
||||
$result = IOFactory::load($out);
|
||||
$this->assertSame(['汇总', '厂家账单-Sheet1', '厂家账单-账单 总表', '对账'], $result->getSheetNames());
|
||||
$this->assertSame(0, $result->getActiveSheetIndex());
|
||||
$totalSheet = $result->getSheetByName('厂家账单-账单 总表');
|
||||
$this->assertSame("=SUM('厂家账单-Sheet1'!B2:B3)", $totalSheet->getCell('A1')->getValue());
|
||||
$this->assertEquals(12, $totalSheet->getCell('A1')->getCalculatedValue());
|
||||
$this->assertEquals(13, $totalSheet->getCell('A2')->getCalculatedValue());
|
||||
$this->assertSame("'厂家账单-Sheet1'!\$B\$2:\$B\$3", ltrim((string) $result->getNamedRange('运费列')->getValue(), '='));
|
||||
$this->assertSame('厂家账单-账单 总表', $result->getNamedRange('本表', $totalSheet)?->getWorksheet()?->getTitle());
|
||||
$this->assertEquals(2, $result->getSheetByName('汇总')->getCell('D2')->getCalculatedValue());
|
||||
$this->assertSame('=N(B2)-N(C2)', $result->getSheetByName('汇总')->getCell('D2')->getValue());
|
||||
$this->assertSame(5, (int) $result->getSheetByName('厂家账单-Sheet1')->getCell('B2')->getValue());
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user