feat(顾家对账): 按灵珊虚拟过账生成ERP导入 #1335

Merged
chenxi merged 1 commits from feature/administrator-kuka-erp-import into main 2026-11-21 11:06:03 +08:00
7 changed files with 525 additions and 45 deletions

View File

@ -6,6 +6,7 @@ use App\Business\KukaPostingBase\KukaPostingBaseRepository;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
class KukaReconciliationPageData
@ -385,6 +386,9 @@ class KukaReconciliationPageData
$this->formatQuantity($row['quantity']),
$this->formatQuantity($row['quantity']),
], array_values($inventory));
$virtualRows = $this->virtualRows($lineItems, $generatedAt);
$erpRecipients = $this->loadErpRecipients($companyId);
$erpRows = $this->erpRows($virtualRows, $generatedAt, $erpRecipients);
$views = [
'posting-data' => $this->paginate(
@ -407,10 +411,10 @@ class KukaReconciliationPageData
$page,
),
'lingshan-virtual-posting' => $this->paginate(
$this->virtualRows($lineItems, $generatedAt),
$virtualRows,
$page,
),
'erp-product-import' => $this->paginate($this->erpRows($lineItems), $page),
'erp-product-import' => $this->paginate($erpRows, $page),
'invoice-entry-template' => $this->paginate(
$this->invoiceRows($lineItems),
$page,
@ -446,8 +450,8 @@ class KukaReconciliationPageData
'receiver_address_rows' => $addressRows,
];
$empty['notices'] = [
'erp' => $phoneRows === 0
? '聚水潭收货人镜像当前没有手机或电话字段,ERP 导入的收货手机保持空白。'
'erp' => $erpRecipients === []
? '工作簿5收货人池尚未导入,ERP导入的收货人字段暂时为空。'
: null,
];
@ -492,47 +496,68 @@ class KukaReconciliationPageData
}
/**
* @param list<array<string, mixed>> $lineItems
* @param list<array<int, string>> $virtualRows
* @param list<object> $recipients
* @return list<array<int, string>>
*/
private function erpRows(array $lineItems): array
private function erpRows(array $virtualRows, string $generatedAt, array $recipients): array
{
return array_map(fn (array $row): array => [
$row['year'],
$row['month'],
$row['store'],
$row['order_no'],
$row['product_code'],
$this->formatQuantity($row['quantity']),
$row['internal_order_no'],
'0',
$row['sales_unit_price'],
$row['sales_amount'],
$row['sales_amount'],
$row['order_date'],
$row['payment_date'],
$row['shipping_date'],
$row['product_name'],
$row['product_spec'],
$row['receiver_name'],
$row['receiver_phone'],
$row['receiver_mobile'],
$row['buyer_memo'],
$row['receiver_zip'],
$row['receiver_state'],
$row['receiver_city'],
$row['receiver_district'],
'',
$row['receiver_address'],
$row['express_name'],
$row['freight'],
$row['order_status'],
$row['seller_memo'],
'',
$row['buyer_nick'],
$row['store'],
'',
], $lineItems);
$orderedAt = Carbon::parse($generatedAt);
$recipientCount = count($recipients);
$dateFormat = 'Y/n/j H:i:s';
return array_map(function (array $row, int $index) use (
$orderedAt,
$recipientCount,
$recipients,
$dateFormat,
): array {
$recipient = $recipientCount === 0
? null
: $recipients[$index % $recipientCount];
$amount = (string) ($row[9] ?? '0.00');
$quantity = $this->normalizeDecimal($row[5] ?? '') ?? '1';
$unitPrice = $this->divideMoney($amount, $quantity);
$paidAt = $orderedAt->copy()->addMinutes(5);
$deliveryAt = $orderedAt->copy()->addDays(5);
return [
$row[0],
$row[1],
'616',
$row[12],
$row[3],
$row[5],
'',
'0',
$unitPrice,
$amount,
$amount,
$orderedAt->format($dateFormat),
$paidAt->format($dateFormat),
$deliveryAt->format($dateFormat),
'',
'',
$recipient?->receiver_name ?? '',
'',
$recipient?->receiver_mobile ?? '',
'',
'',
$recipient?->receiver_state ?? '',
$recipient?->receiver_city ?? '',
$recipient?->receiver_district ?? '',
'',
$recipient?->receiver_address ?? '',
'',
'0.00',
'',
'',
'',
$recipient?->buyer_nick ?? '',
'',
'',
];
}, array_values($virtualRows), array_keys(array_values($virtualRows)));
}
/**
@ -686,6 +711,32 @@ class KukaReconciliationPageData
return $best;
}
/**
* @return list<object>
*/
private function loadErpRecipients(int $companyId): array
{
if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_erp_recipient_rows')) {
return [];
}
return $this->connection()
->table('kuka_posting_erp_recipient_rows')
->where('company_id', $companyId)
->orderBy('sort_order')
->orderBy('id')
->get([
'receiver_name',
'receiver_mobile',
'receiver_state',
'receiver_city',
'receiver_district',
'receiver_address',
'buyer_nick',
])
->all();
}
/**
* @param list<string> $materials
* @return array<string, array{account: string, name: string}>

View File

@ -0,0 +1,164 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use PhpOffice\PhpSpreadsheet\IOFactory;
use RuntimeException;
use Throwable;
class ImportKukaErpRecipients extends Command
{
protected $signature = 'kuka-posting:import-erp-recipients
{file : 工作簿5.xlsx 路径}
{--company=1 : 公司 ID}
{--sheet=Sheet1 : 工作表名称}';
protected $description = '导入顾家ERP商品导入使用的收货人池';
public function handle(): int
{
try {
$path = (string) $this->argument('file');
if (! is_file($path)) {
throw new RuntimeException('导入文件不存在。');
}
$connectionName = (string) config('upstream_mirrors.connection', 'business_mirror');
if (! Schema::connection($connectionName)->hasTable('kuka_posting_erp_recipient_rows')) {
throw new RuntimeException('ERP收货人池表尚未建立。');
}
$rows = $this->readRows($path, (string) $this->option('sheet'));
if ($rows === []) {
throw new RuntimeException('工作簿中没有可导入的收货人数据。');
}
$companyId = max(1, (int) $this->option('company'));
$now = now();
DB::connection($connectionName)->transaction(function () use ($connectionName, $companyId, $now, $rows): void {
$connection = DB::connection($connectionName);
$connection->table('kuka_posting_erp_recipient_rows')
->where('company_id', $companyId)
->delete();
$connection->table('kuka_posting_erp_recipient_rows')->insert(array_map(
fn (array $row, int $index): array => $row + [
'company_id' => $companyId,
'sort_order' => $index + 1,
'imported_at' => $now,
'created_at' => $now,
'updated_at' => $now,
],
$rows,
array_keys($rows),
));
});
$this->info('已导入 ERP 收货人池:'.count($rows).' 条。');
return self::SUCCESS;
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
}
/**
* @return list<array{receiver_name:string,receiver_mobile:string,receiver_state:string,receiver_city:string,receiver_district:string,receiver_address:string,buyer_nick:string,source_row_number:int,row_hash:string}>
*/
private function readRows(string $path, string $sheetName): array
{
$spreadsheet = IOFactory::load($path);
$sheet = $sheetName === ''
? $spreadsheet->getActiveSheet()
: $spreadsheet->getSheetByName($sheetName);
if ($sheet === null) {
throw new RuntimeException('工作簿中没有指定工作表:'.$sheetName);
}
$data = $sheet->toArray(null, false, false, false);
$headers = [
'收货人(必填)',
'收货人手机(必填)',
'收货人的所在省份(必填)',
'收货人的所在城市(必填)',
'收货人的所在区(县)(必填)',
'收货地址(必填)',
'买家昵称(必填)',
];
$headerIndex = null;
$columns = [];
foreach (array_slice($data, 0, 20, true) as $rowIndex => $row) {
$candidate = [];
foreach ($row as $columnIndex => $value) {
$label = trim((string) $value);
if (in_array($label, $headers, true)) {
$candidate[$label] = $columnIndex;
}
}
if (count($candidate) === count($headers)) {
$headerIndex = (int) $rowIndex;
$columns = $candidate;
break;
}
}
if ($headerIndex === null) {
throw new RuntimeException('未找到工作簿5的标准表头。');
}
$rows = [];
foreach (array_slice($data, $headerIndex + 1, null, true) as $rowIndex => $row) {
$values = [];
foreach ($headers as $header) {
$values[$header] = trim((string) ($row[$columns[$header]] ?? ''));
}
if ($values['收货人(必填)'] === 'clientName'
|| $values['收货人手机(必填)'] === 'clientMobile') {
continue;
}
foreach ($headers as $header) {
if ($values[$header] === '') {
throw new RuntimeException('第 '.($rowIndex + 1).' 行存在必填字段为空。');
}
}
$mobile = $this->normalizeMobile($values['收货人手机(必填)']);
if ($mobile === '') {
throw new RuntimeException('第 '.($rowIndex + 1).' 行收货人手机无效。');
}
$normalized = [
'receiver_name' => $values['收货人(必填)'],
'receiver_mobile' => $mobile,
'receiver_state' => $values['收货人的所在省份(必填)'],
'receiver_city' => $values['收货人的所在城市(必填)'],
'receiver_district' => $values['收货人的所在区(县)(必填)'],
'receiver_address' => $values['收货地址(必填)'],
'buyer_nick' => $values['买家昵称(必填)'],
'source_row_number' => (int) $rowIndex + 1,
];
$normalized['row_hash'] = hash('sha256', json_encode(
$normalized,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
));
$rows[] = $normalized;
}
return $rows;
}
private function normalizeMobile(mixed $value): string
{
$mobile = trim((string) $value);
if ($mobile === '') {
return '';
}
if (is_numeric($mobile) && preg_match('/^\d+(?:\.0+)?$/', $mobile) === 1) {
return number_format((float) $mobile, 0, '', '');
}
return preg_replace('/\s+/u', '', $mobile) ?? '';
}
}

View File

@ -0,0 +1,53 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): void
{
$schema = Schema::connection($this->connection());
if ($schema->hasTable('kuka_posting_erp_recipient_rows')) {
return;
}
$schema->create('kuka_posting_erp_recipient_rows', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedBigInteger('company_id')->default(1);
$table->unsignedInteger('sort_order');
$table->string('receiver_name', 191);
$table->string('receiver_mobile', 32);
$table->string('receiver_state', 64);
$table->string('receiver_city', 64);
$table->string('receiver_district', 64);
$table->string('receiver_address', 500);
$table->string('buyer_nick', 191);
$table->unsignedInteger('source_row_number')->nullable();
$table->char('row_hash', 64);
$table->timestamp('imported_at');
$table->timestamps();
$table->unique(
['company_id', 'row_hash'],
'kuka_erp_recipient_company_row_unique',
);
$table->index(
['company_id', 'sort_order'],
'kuka_erp_recipient_company_sort',
);
});
}
public function down(): void
{
Schema::connection($this->connection())
->dropIfExists('kuka_posting_erp_recipient_rows');
}
};

View File

@ -59,7 +59,7 @@
'slug' => 'erp-product-import',
'title' => '顾家ERP商品导入',
'icon' => 'inventory_2',
'description' => '已按工作簿4“顾家ERP商品导入”子表的双行表头放入字段和导入编码。',
'description' => '按灵珊虚拟过账生成,收货人字段循环使用工作簿5数据。',
'source_sheet' => '顾家ERP商品导入',
'numeric_columns' => [5, 8, 9, 10, 27],
'money_columns' => [8, 9, 10, 27],

View File

@ -273,6 +273,22 @@ class KukaReconciliationPageTest extends FeatureTestCase
'express_name1' => '测试快递',
'freight' => '5.00',
]);
$connection->table('kuka_posting_erp_recipient_rows')->insert([
'company_id' => $this->company->id,
'sort_order' => 1,
'receiver_name' => '张三',
'receiver_mobile' => '13800000000',
'receiver_state' => '江苏省',
'receiver_city' => '常州市',
'receiver_district' => '武进区',
'receiver_address' => '江苏省常州市武进区测试路1号',
'buyer_nick' => 'buyer-1',
'source_row_number' => 2,
'row_hash' => str_repeat('d', 64),
'imported_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
$response = $this->loginAs()
->get(route('business.pages.show', [

View File

@ -0,0 +1,75 @@
<?php
namespace Tests\Feature\Console;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Tests\TestCase;
class ImportKukaErpRecipientsTest extends TestCase
{
public function test_command_imports_workbook_rows_and_replaces_previous_pool(): void
{
config([
'database.connections.business_mirror' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
'upstream_mirrors.connection' => 'business_mirror',
]);
DB::purge('business_mirror');
Schema::connection('business_mirror')->create('kuka_posting_erp_recipient_rows', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedBigInteger('company_id')->default(1);
$table->unsignedInteger('sort_order');
$table->string('receiver_name');
$table->string('receiver_mobile');
$table->string('receiver_state');
$table->string('receiver_city');
$table->string('receiver_district');
$table->string('receiver_address');
$table->string('buyer_nick');
$table->unsignedInteger('source_row_number')->nullable();
$table->char('row_hash', 64);
$table->timestamp('imported_at');
$table->timestamps();
});
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Sheet1');
$sheet->fromArray([
['收货人(必填)', '收货人手机(必填)', '收货人的所在省份(必填)', '收货人的所在城市(必填)', '收货人的所在区(县)(必填)', '收货地址(必填)', '买家昵称(必填)'],
['clientName', 'clientMobile', 'clientProvince', 'clientCity', 'clientArea', 'clientAddress', 'buyerNick'],
['测试甲', '13800000001', '江苏省', '常州市', '武进区', '测试路1号', '昵称甲'],
['测试乙', '13800000002', '江苏省', '常州市', '新北区', '测试路2号', '昵称乙'],
]);
$path = tempnam(sys_get_temp_dir(), 'kuka-recipients-');
(new Xlsx($spreadsheet))->save($path);
try {
$this->artisan('kuka-posting:import-erp-recipients', ['file' => $path])
->expectsOutput('已导入 ERP 收货人池:2 条。')
->assertSuccessful();
$this->artisan('kuka-posting:import-erp-recipients', ['file' => $path])
->assertSuccessful();
$rows = DB::connection('business_mirror')
->table('kuka_posting_erp_recipient_rows')
->orderBy('sort_order')
->get();
$this->assertCount(2, $rows);
$this->assertSame('测试甲', $rows[0]->receiver_name);
$this->assertSame('13800000001', $rows[0]->receiver_mobile);
$this->assertSame(3, (int) $rows[0]->source_row_number);
$this->assertSame('测试乙', $rows[1]->receiver_name);
$this->assertSame('昵称乙', $rows[1]->buyer_nick);
} finally {
@unlink($path);
}
}
}

View File

@ -67,6 +67,54 @@ class KukaReconciliationPageDataTest extends TestCase
$table->string('express_name1')->nullable();
$table->decimal('freight', 18, 2)->nullable();
});
$schema->create('kuka_posting_erp_recipient_rows', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedBigInteger('company_id')->default(1);
$table->unsignedInteger('sort_order');
$table->string('receiver_name');
$table->string('receiver_mobile');
$table->string('receiver_state');
$table->string('receiver_city');
$table->string('receiver_district');
$table->string('receiver_address');
$table->string('buyer_nick');
});
$connection = DB::connection('business_mirror');
$connection->table('kuka_posting_erp_recipient_rows')->insert([
[
'company_id' => 1,
'sort_order' => 1,
'receiver_name' => '张三',
'receiver_mobile' => '13800000000',
'receiver_state' => '江苏省',
'receiver_city' => '常州市',
'receiver_district' => '武进区',
'receiver_address' => '江苏省常州市武进区测试路1号',
'buyer_nick' => 'buyer-1',
],
[
'company_id' => 1,
'sort_order' => 2,
'receiver_name' => '李四',
'receiver_mobile' => '13900000000',
'receiver_state' => '浙江省',
'receiver_city' => '杭州市',
'receiver_district' => '西湖区',
'receiver_address' => '浙江省杭州市西湖区测试路2号',
'buyer_nick' => 'buyer-2',
],
[
'company_id' => 1,
'sort_order' => 3,
'receiver_name' => '王五',
'receiver_mobile' => '13700000000',
'receiver_state' => '上海市',
'receiver_city' => '上海市',
'receiver_district' => '浦东新区',
'receiver_address' => '上海市浦东新区测试路3号',
'buyer_nick' => 'buyer-3',
],
]);
}
public function test_builds_rule_based_rows_for_each_reconciliation_view(): void
@ -188,14 +236,38 @@ class KukaReconciliationPageDataTest extends TestCase
$this->assertSame('', $virtual[15]);
$erp = $data['views']['erp-product-import']['rows'][0];
$this->assertSame('616', $erp[2]);
$this->assertSame($virtual[12], $erp[3]);
$this->assertSame('M-1', $erp[4]);
$this->assertSame('2', $erp[5]);
$this->assertSame('0', $erp[7]);
$this->assertSame('11.11', $erp[8]);
$this->assertSame('22.22', $erp[9]);
$this->assertSame('22.22', $erp[10]);
$erpOrderedAt = \Illuminate\Support\Carbon::parse($data['generated_at']);
$this->assertSame($erpOrderedAt->format('Y/n/j H:i:s'), $erp[11]);
$this->assertSame($erpOrderedAt->copy()->addMinutes(5)->format('Y/n/j H:i:s'), $erp[12]);
$this->assertSame($erpOrderedAt->copy()->addDays(5)->format('Y/n/j H:i:s'), $erp[13]);
$this->assertSame('', $erp[14]);
$this->assertSame('', $erp[15]);
$this->assertSame('张三', $erp[16]);
$this->assertSame('', $erp[17]);
$this->assertSame('13800000000', $erp[18]);
$this->assertSame('', $erp[19]);
$this->assertSame('', $erp[20]);
$this->assertSame('江苏省', $erp[21]);
$this->assertSame('常州市', $erp[22]);
$this->assertSame('武进区', $erp[23]);
$this->assertSame('', $erp[24]);
$this->assertSame('江苏省常州市武进区测试路1号', $erp[25]);
$this->assertSame('顺丰', $erp[26]);
$this->assertSame('8.00', $erp[27]);
$this->assertSame('', $erp[26]);
$this->assertSame('0.00', $erp[27]);
$this->assertSame('', $erp[28]);
$this->assertSame('', $erp[29]);
$this->assertSame('', $erp[30]);
$this->assertSame('buyer-1', $erp[31]);
$this->assertSame('', $erp[32]);
$this->assertSame('', $erp[33]);
$invoice = $data['views']['invoice-entry-template']['rows'][0];
$this->assertSame('宁波顾家望业家居有限公司', $invoice[2]);
@ -260,6 +332,55 @@ class KukaReconciliationPageDataTest extends TestCase
$this->assertSame('11.12', $virtual[9]);
}
public function test_erp_import_maps_virtual_rows_and_cycles_recipients(): void
{
$connection = DB::connection('business_mirror');
$connection->table('kuka_posting_base_imports')->insert([
'company_id' => 1,
'period' => '2026-10',
'completed_at' => '2026-11-01 08:00:00',
]);
for ($index = 1; $index <= 4; $index++) {
$this->insertBaseRow(
$index + 1,
$this->payload(
'O-'.$index,
'P-'.$index,
'S-'.$index,
'I-'.$index,
'M-1',
'1',
'10.00',
),
);
}
$data = app(KukaReconciliationPageData::class)->build(
Request::create('/', 'GET', ['period' => '2026-10']),
1,
);
$virtualRows = $data['views']['lingshan-virtual-posting']['rows'];
$erpRows = $data['views']['erp-product-import']['rows'];
$this->assertCount(4, $erpRows);
$this->assertSame(['张三', '李四', '王五', '张三'], array_column($erpRows, 16));
$this->assertSame(
['13800000000', '13900000000', '13700000000', '13800000000'],
array_column($erpRows, 18),
);
foreach ($erpRows as $index => $erp) {
$this->assertSame('616', $erp[2]);
$this->assertSame($virtualRows[$index][12], $erp[3]);
$this->assertSame('M-1', $erp[4]);
$this->assertSame('1', $erp[5]);
$this->assertSame('0', $erp[7]);
$this->assertSame('11.11', $erp[8]);
$this->assertSame('11.11', $erp[9]);
$this->assertSame('11.11', $erp[10]);
$this->assertSame('0.00', $erp[27]);
}
}
public function test_posting_export_returns_every_material_row_without_pagination(): void
{
$connection = DB::connection('business_mirror');