feat(内部流转): 增加精选供应链标签三

This commit is contained in:
huilan 2026-11-19 16:46:58 +08:00
parent 8b46486b87
commit 0282fea3fd
4 changed files with 262 additions and 0 deletions

View File

@ -0,0 +1,35 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\InternalFlowWorkbookImporter;
use Throwable;
class SyncInternalFlowCompanies extends Command
{
protected $signature = 'internal-flow:sync-companies';
protected $description = '将内部流转配置公司补齐到当前数据集,并同步其固定标签';
public function handle(InternalFlowWorkbookImporter $importer): int
{
try {
$result = $importer->syncConfiguredCompanies();
} catch (Throwable $exception) {
report($exception);
$this->error('内部流转公司标签同步失败:' . $exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'内部流转公司标签同步完成:新增 %s 家,更新 %s 家,配置共 %s 家。',
number_format($result['inserted']),
number_format($result['updated']),
number_format($result['total']),
));
return self::SUCCESS;
}
}

View File

@ -1,6 +1,13 @@
<?php
return [
/*
* 这些公司即使尚未出现在最新工作簿中,也会保留在内部流转报表里;
* 标签以此处配置为准,金额仍由经营报表和工作簿导入结果提供。
*/
'company_tags' => [
'常州精选供应链有限公司' => '3',
],
/*
* 这些公司以指定收票金额倒推收入:成本金额 ÷ cost_to_income_rate。
* receipt_field 只在对应公司行显示为可填写。

View File

@ -75,6 +75,8 @@ class InternalFlowWorkbookImporter
throw new RuntimeException('表格中没有可导入的数据行,请检查“' . self::SHEET_TITLE . '”工作表。');
}
$rows = $this->withConfiguredCompanies($rows);
$now = Carbon::now();
$sourceFile = basename($realPath);
@ -102,6 +104,145 @@ class InternalFlowWorkbookImporter
];
}
/**
* 将配置公司补齐到当前已导入数据集,并同步固定标签。
*
* @return array{inserted:int,updated:int,total:int}
*/
public function syncConfiguredCompanies(): array
{
if (! Schema::connection($this->connection->getName())->hasTable(self::TABLE)) {
throw new RuntimeException('内部流转数据表尚未创建,请先执行数据库迁移。');
}
$companyTags = $this->configuredCompanyTags();
if ($companyTags === []) {
return ['inserted' => 0, 'updated' => 0, 'total' => 0];
}
return $this->connection->transaction(function () use ($companyTags): array {
$table = $this->connection->table(self::TABLE);
if (! $table->exists()) {
throw new RuntimeException('内部流转数据尚未导入,请先导入工作簿。');
}
$nextSortOrder = (int) $this->connection->table(self::TABLE)->max('sort_order') + 1;
$now = Carbon::now();
$inserted = 0;
$updated = 0;
foreach ($companyTags as $companyName => $tag) {
$existing = $this->connection->table(self::TABLE)
->where('company_name', $companyName)
->first();
if ($existing === null) {
$this->connection->table(self::TABLE)->insert(
$this->configuredCompanyRow($companyName, $tag, $nextSortOrder, $now),
);
$nextSortOrder++;
$inserted++;
continue;
}
if (trim((string) ($existing->tag ?? '')) !== $tag) {
$this->connection->table(self::TABLE)
->where('id', $existing->id)
->update([
'tag' => $tag,
'updated_at' => $now,
]);
$updated++;
}
}
return [
'inserted' => $inserted,
'updated' => $updated,
'total' => count($companyTags),
];
});
}
/**
* @param list<array<string,mixed>> $rows
* @return list<array<string,mixed>>
*/
private function withConfiguredCompanies(array $rows): array
{
$companyTags = $this->configuredCompanyTags();
if ($companyTags === []) {
return $rows;
}
$positions = [];
foreach ($rows as $index => $row) {
$positions[trim((string) ($row['company_name'] ?? ''))] = $index;
}
$nextSortOrder = count($rows) + 1;
foreach ($companyTags as $companyName => $tag) {
if (array_key_exists($companyName, $positions)) {
$rows[$positions[$companyName]]['tag'] = $tag;
continue;
}
$rows[] = $this->configuredCompanyRow($companyName, $tag, $nextSortOrder);
$nextSortOrder++;
}
return $rows;
}
/**
* @return array<string,string>
*/
private function configuredCompanyTags(): array
{
$companyTags = [];
foreach ((array) config('internal_flow_report.company_tags', []) as $companyName => $tag) {
$companyName = trim((string) $companyName);
$tag = trim((string) $tag);
if ($companyName === '' || $tag === '') {
continue;
}
$companyTags[$companyName] = $tag;
}
return $companyTags;
}
/**
* @return array<string,mixed>
*/
private function configuredCompanyRow(
string $companyName,
string $tag,
int $sortOrder,
?Carbon $now = null,
): array {
$row = [
'company_name' => $companyName,
'tag' => $tag,
'sort_order' => $sortOrder,
];
foreach (array_column(self::COLUMNS, 'field') as $field) {
$row[$field] ??= null;
}
if ($now !== null) {
$row += [
'source_file' => null,
'imported_at' => $now,
'created_at' => $now,
'updated_at' => $now,
];
}
return $row;
}
/**
* @return array{0: list<array<string,mixed>>, 1: int}
*/

View File

@ -24,6 +24,7 @@ class InternalFlowReportImportTest extends TestCase
'upstream_mirrors.connection' => 'business_mirror',
]);
DB::purge('business_mirror');
config(['internal_flow_report.company_tags' => []]);
$migration = require base_path(
'database/migrations/2026_10_05_000000_create_business_internal_flow_records_table.php'
@ -152,6 +153,84 @@ class InternalFlowReportImportTest extends TestCase
$this->assertSame('示例丙家居有限公司', $paged['data'][0]['company_name']);
}
public function testImportAddsConfiguredCompaniesAndOverridesTheirTags(): void
{
config([
'internal_flow_report.company_tags' => [
'常州心选供应链有限公司' => '3',
'常州精选供应链有限公司' => '3',
],
]);
$rows = $this->dataRows();
$rows[0][0] = '常州心选供应链有限公司';
$path = $this->writeWorkbook($rows);
try {
$result = app(InternalFlowWorkbookImporter::class)->import($path);
} finally {
@unlink($path);
}
$this->assertSame(4, $result['imported']);
$stored = collect(DB::connection('business_mirror')
->table(InternalFlowWorkbookImporter::TABLE)
->get())
->keyBy('company_name');
$this->assertSame('3', $stored['常州心选供应链有限公司']->tag);
$this->assertSame('3', $stored['常州精选供应链有限公司']->tag);
$this->assertSame(4, (int) $stored['常州精选供应链有限公司']->sort_order);
$this->assertNull($stored['常州精选供应链有限公司']->projected_sales);
}
public function testSyncConfiguredCompaniesPersistsMissingCompanyAndUsesProjection(): void
{
$path = $this->writeWorkbook($this->dataRows());
app(InternalFlowWorkbookImporter::class)->import($path);
@unlink($path);
config([
'internal_flow_report.company_tags' => [
'常州精选供应链有限公司' => '3',
],
]);
$this->artisan('internal-flow:sync-companies')
->expectsOutputToContain('新增 1 家,更新 0 家,配置共 1 家')
->assertSuccessful();
$this->artisan('internal-flow:sync-companies')
->expectsOutputToContain('新增 0 家,更新 0 家,配置共 1 家')
->assertSuccessful();
$record = DB::connection('business_mirror')
->table(InternalFlowWorkbookImporter::TABLE)
->where('company_name', '常州精选供应链有限公司')
->first();
$this->assertNotNull($record);
$this->assertSame('3', $record->tag);
$result = app(InternalFlowReportRepository::class)->paginate(
1,
50,
['company_name' => '常州精选供应链有限公司'],
null,
'asc',
[
'sales_by_company' => [
'常州精选供应链有限公司' => 2000000.0,
],
],
);
$this->assertSame(1, $result['total']);
$this->assertSame('3', $result['data'][0]['tag']);
$this->assertEqualsWithDelta(2000000.0, $result['data'][0]['projected_sales'], 0.000001);
$this->assertEqualsWithDelta(400000.0, $result['data'][0]['invoiced_to_buyer'], 0.000001);
$this->assertEqualsWithDelta(500000.0, $result['data'][0]['internal_invoiced'], 0.000001);
$this->assertEqualsWithDelta(1600000.0, $result['data'][0]['required_input_cost'], 0.000001);
$this->assertEqualsWithDelta(1600000.0, $result['data'][0]['remaining_gap'], 0.000001);
}
public function testProjectionRecalculatesAmountsAndSupplierReceiptOverrideSurvivesReimport(): void
{
$path = $this->writeWorkbook($this->dataRows());