feat(供应商应付): 支持退货对账完整批量导入 #1499

Closed
sumu wants to merge 3 commits from feature/sumu-supplier-return-reconciliation-import into main
10 changed files with 287 additions and 19 deletions

View File

@ -0,0 +1,118 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Http\UploadedFile;
use Modules\EcommerceFinance\Services\PayablesFinalImportRunner;
use Modules\EcommerceFinance\Services\PayablesFinalRegistry;
use Throwable;
class ImportPayablesFinal extends Command
{
protected $signature = 'payables:final-import
{--directory= : 已解压 CSV 文件目录}
{--section=supplier-payables-final : 终版目录}
{--dataset=payment-reconciliation : 数据集页面}
{--company=1 : 公司 ID}
{--user= : 操作人 ID}';
protected $description = '将终版页面的 CSV 文件分片导入业务数据库';
public function handle(
PayablesFinalRegistry $registry,
PayablesFinalImportRunner $runner,
): int {
$directory = trim((string) $this->option('directory'));
$section = trim((string) $this->option('section'));
$dataset = trim((string) $this->option('dataset'));
$companyId = max(1, (int) $this->option('company'));
$userId = $this->option('user') === null ? null : max(1, (int) $this->option('user'));
if ($directory === '' || ! is_dir($directory)) {
$this->error('导入目录不存在。');
return self::FAILURE;
}
if (! $registry->supports($section, $dataset)) {
$this->error('不支持的终版页面。');
return self::FAILURE;
}
$files = glob(rtrim($directory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '*.csv') ?: [];
sort($files, SORT_NATURAL);
if ($files === []) {
$this->error('导入目录中没有 CSV 文件。');
return self::FAILURE;
}
$fields = $registry->fields($section, $dataset);
$storeDataset = 'final:'
. ($section === PayablesFinalRegistry::SECTION_COURIER ? 'courier' : 'supplier')
. ':'
. $dataset;
$totalCreated = 0;
$totalUpdated = 0;
$totalRows = 0;
try {
foreach ($files as $index => $path) {
$file = new UploadedFile(
$path,
basename($path),
'text/csv',
null,
true,
);
$prepared = $runner->prepare(
$file,
$fields,
$storeDataset,
$companyId,
$userId,
);
$token = $prepared['token'];
$offset = 0;
$created = 0;
$updated = 0;
do {
$progress = $runner->process($token, $offset, null, $companyId);
$offset = $progress['offset'];
$created = $progress['created'];
$updated = $progress['updated'];
} while (! $progress['done']);
$totalCreated += $created;
$totalUpdated += $updated;
$totalRows += (int) $prepared['total'];
$this->line(sprintf(
'[%d/%d] %s:%s 行,新增 %s,更新 %s',
$index + 1,
count($files),
basename($path),
number_format((int) $prepared['total']),
number_format($created),
number_format($updated),
));
}
} catch (Throwable $exception) {
report($exception);
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'导入完成:文件 %s 个,读取 %s 行,新增 %s,更新 %s。',
number_format(count($files)),
number_format($totalRows),
number_format($totalCreated),
number_format($totalUpdated),
));
return self::SUCCESS;
}
}

View File

@ -4843,7 +4843,7 @@ class Pages extends Controller
$perPage,
$currentPage,
$keyword,
$dataset === 'payment-reconciliation',
in_array($dataset, ['payment-reconciliation', 'return-reconciliation'], true),
);
$pagedRows = $paged['rows'];
$totalRows = $paged['total'];

View File

@ -47,6 +47,7 @@
"planting-details:sync-work-orders",
"planting-details:import",
"payables:unpriced-cycle",
"payables:final-import",
"product-catalog:import-authoritative-export",
"product:monthly-weighted-average:base",
"store-violations:import-rules",

View File

@ -8,7 +8,7 @@ is_import=0
CAIWU_BATCH_CALLER_DIR="$PWD"
export CAIWU_BATCH_CALLER_DIR
case "${1:-}" in
*:import|*:import-*|*:import:*|payables:unpriced-cycle|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
jushuitan:calc-freight) ;;
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
*) echo 'Unsupported finance batch command' >&2; exit 64 ;;

View File

@ -219,6 +219,10 @@ class PayablesFinalImportRunner
'import' => $this->rowMessage($firstRow, $line, $exception),
]);
}
if ($dataset === 'final:supplier:return-reconciliation' && isset($normalized['send_time'])) {
$normalized['summary_month'] = substr((string) $normalized['send_time'], 0, 7);
$normalized['date'] = $normalized['send_time'];
}
$key = $recordKey !== ''
? $recordKey

View File

@ -105,6 +105,10 @@ class PayablesFinalImporter
'import' => "第 {$line} 行:" . collect($exception->errors())->flatten()->first(),
]);
}
if ($storeDataset === 'final:supplier:return-reconciliation' && isset($values['send_time'])) {
$values['summary_month'] = substr((string) $values['send_time'], 0, 7);
$values['date'] = $values['send_time'];
}
if ($key === '') {
$key = $preserveSourceRows

View File

@ -85,7 +85,8 @@ class PayablesFinalRegistry
* - insert:锚点列之后插入的列(锚点列名 => 列定义);
* - append:追加到末尾的列。
* 货款对账在「月份」后补入库单号、采购单号、日期,末尾补未发出、对账人;
* 退货对账去掉「快递名称」,在「标题」后插入 wms 配货单号,在「标记多标签」后补创建人。
* 退货对账去掉「快递名称」,在「标题」后插入 wms 配货单号,
* 在「快递单号」后补第二次发货时间和原条码,在「标记多标签」后补创建人。
*/
private const SUPPLIER_FIELD_PATCHES = [
'payment-reconciliation' => [
@ -103,6 +104,10 @@ class PayablesFinalRegistry
'remove' => ['express_name'],
'insert' => [
'title' => ['wms_pick_no' => ['label' => 'wms配货单号', 'type' => 'text']],
'express_no' => [
'io_date' => ['label' => '发货时间', 'type' => 'date'],
'original_barcode' => ['label' => '原条码', 'type' => 'text'],
],
'labels' => ['creator' => ['label' => '创建人', 'type' => 'text']],
],
],
@ -180,7 +185,9 @@ class PayablesFinalRegistry
if ($inserts !== []) {
$ordered = [];
foreach ($fields as $key => $definition) {
$ordered[$key] = $definition;
if (! array_key_exists($key, $ordered)) {
$ordered[$key] = $definition;
}
foreach ($inserts[$key] ?? [] as $insertedKey => $insertedDefinition) {
$ordered[$insertedKey] = $insertedDefinition;
}

View File

@ -0,0 +1,46 @@
<?php
namespace Tests\Feature\Business;
use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore;
use Tests\Feature\FeatureTestCase;
class PayablesFinalImportCommandTest extends FeatureTestCase
{
public function test_command_imports_every_csv_in_a_directory(): void
{
$directory = sys_get_temp_dir() . '/payables-final-command-' . uniqid('', true);
mkdir($directory, 0777, true);
file_put_contents(
$directory . '/part-01.csv',
"\xEF\xBB\xBF月份,供应商,货号,商品编码,规格名称,数量,单价,金额\n"
. "2026-09,供应商甲,SKU-1,BAR-1,规格甲,2,10,20\n",
);
file_put_contents(
$directory . '/part-02.csv',
"\xEF\xBB\xBF月份,供应商,货号,商品编码,规格名称,数量,单价,金额\n"
. "2026-09,供应商乙,SKU-2,BAR-2,规格乙,1,30,30\n",
);
try {
$this->artisan('payables:final-import', [
'--directory' => $directory,
'--company' => (int) $this->company->id,
'--user' => (int) $this->user->id,
])
->expectsOutputToContain('文件 2 个,读取 2 行')
->assertExitCode(0);
$rows = app(SupplierPayableOverrideStore::class)->listRows(
'final:supplier:payment-reconciliation',
(int) $this->company->id,
);
$this->assertCount(2, $rows);
$this->assertSame(['供应商甲', '供应商乙'], array_column($rows, 'supplier'));
} finally {
@unlink($directory . '/part-01.csv');
@unlink($directory . '/part-02.csv');
@rmdir($directory);
}
}
}

View File

@ -197,6 +197,40 @@ class PayablesFinalImportRunnerTest extends FeatureTestCase
$this->assertCount(2, app(SupplierPayableOverrideStore::class)->listRows($dataset, (int) $this->company->id));
}
public function test_runner_derives_return_month_and_sort_date_from_send_time(): void
{
$header = [
'记录标识', '月份', '发货时间', '明细供应商', '条形码', '商品名称', '发货量', '单价',
'金额', '预估单价', '预估金额', '供应商条码', '备注', '标题', 'wms配货单号',
'仓库名称', '快递单号', '发货时间', '原条码', '标记多标签', '创建人', '对账人',
];
$row = 'src:return:1,2026-08,2026-09-30,退货供应商,RC-1,退货商品,1,10,10,,,SB-1,备注,标题,WMS-1,华东仓,SF-1,2026-09-30,OB-1,普通退货,创建人甲,对账人乙';
$file = UploadedFile::fake()->createWithContent(
'returns.csv',
"\xEF\xBB\xBF" . implode(',', $header) . "\n{$row}\n",
);
$runner = app(PayablesFinalImportRunner::class);
$fields = app(PayablesFinalRegistry::class)->fields(
'supplier-payables-final',
'return-reconciliation',
);
$dataset = 'final:supplier:return-reconciliation';
$prepared = $runner->prepare($file, $fields, $dataset, (int) $this->company->id, (int) $this->user->id);
$progress = $runner->process($prepared['token'], 0, 10);
$row = app(SupplierPayableOverrideStore::class)->findRow(
$dataset,
'src:return:1',
(int) $this->company->id,
);
$this->assertTrue($progress['done']);
$this->assertSame('2026-09', $row['summary_month']);
$this->assertSame('2026-09-30', $row['date']);
$this->assertSame('2026-09-30', $row['io_date']);
$this->assertSame('普通退货', $row['labels']);
}
public function test_import_endpoints_accept_uploads_and_chunks(): void
{
$file = UploadedFile::fake()->createWithContent(

View File

@ -427,12 +427,13 @@ class SupplierPayableFinalPagesTest extends FeatureTestCase
try {
file_put_contents($path, $response->streamedContent());
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
$header = $spreadsheet->getSheet(0)->rangeToArray('A1:T1')[0];
$header = $spreadsheet->getSheet(0)->rangeToArray('A1:V1')[0];
$spreadsheet->disconnectWorksheets();
$this->assertSame([
'记录标识', '月份', '发货时间', '明细供应商', '条形码', '商品名称', '发货量', '单价', '金额', '预估单价',
'预估金额', '供应商条码', '备注', '标题', 'wms配货单号', '仓库名称', '快递单号', '标记多标签', '创建人', '对账人',
'预估金额', '供应商条码', '备注', '标题', 'wms配货单号', '仓库名称', '快递单号', '发货时间', '原条码',
'标记多标签', '创建人', '对账人',
], $header);
$this->assertNotContains('快递名称', $header);
} finally {
@ -440,12 +441,53 @@ class SupplierPayableFinalPagesTest extends FeatureTestCase
}
}
public function test_final_return_reconciliation_lists_latest_month_and_date_first(): void
{
app(SupplierPayableOverrideStore::class)->saveBatch(
'final:supplier:return-reconciliation',
[
'return:old' => [
'summary_month' => '2026-08',
'date' => '2026-08-31',
'send_time' => '2026-08-31',
'barcode' => 'RETURN-OLD',
],
'return:september-older' => [
'summary_month' => '2026-09',
'date' => '2026-09-01',
'send_time' => '2026-09-01',
'barcode' => 'RETURN-SEP-OLD',
],
'return:september-newer' => [
'summary_month' => '2026-09',
'date' => '2026-09-30',
'send_time' => '2026-09-30',
'barcode' => 'RETURN-SEP-NEW',
],
],
(int) $this->company->id,
(int) $this->user->id,
);
$this->loginAs()
->get(route('business.pages.show', [
'section' => 'supplier-payables-final',
'page' => 'return-reconciliation',
]))
->assertOk()
->assertSeeInOrder([
'RETURN-SEP-NEW',
'RETURN-SEP-OLD',
'RETURN-OLD',
]);
}
public function test_final_return_reconciliation_import_keeps_wms_and_creator_columns(): void
{
$file = UploadedFile::fake()->createWithContent(
'return-reconciliation.csv',
"\xEF\xBB\xBF月份,发货时间,明细供应商,条形码,商品名称,发货量,单价,金额,预估单价,预估金额,供应商条码,备注,标题,wms配货单号,仓库名称,快递单号,标记多标签,创建人,对账人\n"
. "2026-09,2026-09-01,退货供应商,BC-1,商品甲,3,10,30,9,27,SB-1,备注甲,标题甲,WMS-1,华南仓,SF-9,多标签,创建人甲,对账人乙\n",
"\xEF\xBB\xBF月份,发货时间,明细供应商,条形码,商品名称,发货量,单价,金额,预估单价,预估金额,供应商条码,备注,标题,wms配货单号,仓库名称,快递单号,发货时间,原条码,标记多标签,创建人,对账人\n"
. "2026-08,2026-09-01,退货供应商,BC-1,商品甲,3,10,30,9,27,SB-1,备注甲,标题甲,WMS-1,华南仓,SF-9,2026-09-01,OB-1,普通退货,创建人甲,对账人乙\n",
);
$this->loginAs()
@ -467,14 +509,26 @@ class SupplierPayableFinalPagesTest extends FeatureTestCase
->assertSeeText('wms配货单号')
->assertSeeText('创建人')
->assertSeeText('WMS-1')
->assertSeeText('2026-09')
->assertSeeText('OB-1')
->assertSeeText('创建人甲')
->assertDontSeeText('快递名称');
$export = $this->loginAs()->get(route('business.supplier-payables-final.return-reconciliation.export'));
$export->assertOk();
$this->assertStringContainsString('备注,标题,wms配货单号', $export->streamedContent());
$this->assertStringContainsString('备注,标题,wms配货单号,仓库名称,快递单号,发货时间,原条码', $export->streamedContent());
$this->assertStringContainsString('标记多标签,创建人,对账人', $export->streamedContent());
$this->assertStringNotContainsString('快递名称', $export->streamedContent());
$saved = DB::connection(config('database.supplier_payable_maintenance_connection'))
->table('supplier_payable_overrides')
->where('company_id', $this->company->id)
->where('dataset', 'final:supplier:return-reconciliation')
->first();
$values = json_decode((string) $saved->values, true);
$this->assertSame('2026-09', $values['summary_month']);
$this->assertSame('2026-09-01', $values['date']);
$this->assertSame('2026-09-01', $values['io_date']);
}
public function test_final_return_reconciliation_page_paginates_fifteen_rows(): void
@ -510,15 +564,15 @@ class SupplierPayableFinalPagesTest extends FeatureTestCase
->assertOk()
->assertSeeText('每页 15 条')
->assertSeeText('第 1 页 / 共 2 页')
->assertSeeText('RC-01')
->assertDontSeeText('RC-16');
->assertSeeText('RC-20')
->assertDontSeeText('RC-01');
$this->loginAs()->get($url(2))
->assertOk()
->assertSeeText('第 2 页 / 共 2 页')
->assertSeeText('RC-16')
->assertSeeText('RC-20')
->assertDontSeeText('RC-01');
->assertSeeText('RC-05')
->assertSeeText('RC-01')
->assertDontSeeText('RC-20');
}
public function test_final_payment_reconciliation_page_paginates_fifteen_rows(): void
@ -557,15 +611,15 @@ class SupplierPayableFinalPagesTest extends FeatureTestCase
->assertOk()
->assertSeeText('每页 15 条')
->assertSeeText('第 1 页 / 共 2 页')
->assertSeeText('PM-01')
->assertDontSeeText('PM-16');
->assertSeeText('PM-20')
->assertDontSeeText('PM-01');
$this->loginAs()->get($url(2))
->assertOk()
->assertSeeText('第 2 页 / 共 2 页')
->assertSeeText('PM-16')
->assertSeeText('PM-20')
->assertDontSeeText('PM-01');
->assertSeeText('PM-05')
->assertSeeText('PM-01')
->assertDontSeeText('PM-20');
}
public function test_final_supplier_payables_report_paginates_and_freezes_through_supplier(): void