fix(财务导入): 兼容Excel金额浮点尾差 #1698

Closed
limeng wants to merge 1 commits from fix/limeng-bookkeeping-float-tails into main
5 changed files with 139 additions and 2 deletions

View File

@ -7,6 +7,34 @@ use Illuminate\Validation\ValidationException;
/** 按字段定义校验并整理按表维护/导入的字段值。 */
class PayablesFieldNormalizer
{
/** 导入允许清除 Excel 的微小十进制尾差,手工编辑仍执行严格精度校验。 */
public function normalizeImport(array $fields, array $input): array
{
foreach ($fields as $field => $definition) {
if ($definition['type'] !== 'number' || ! isset($input[$field])) {
continue;
}
$number = str_replace([',', ',', '¥', '¥'], '', trim((string) $input[$field]));
if (preg_match('/^-?(?:\d+)?\.\d{5,}$/', $number) !== 1) {
continue;
}
// 全程十进制运算,不把金额或大整数转成 float。
$magnitude = ltrim($number, '-');
$scale = strlen(explode('.', $number, 2)[1]);
$rounded = bcadd($magnitude, '0.00005', 4);
$difference = ltrim(bcsub($magnitude, $rounded, $scale), '-');
if (bccomp($difference, '0.000000000001', max(12, $scale)) <= 0) {
$input[$field] = str_starts_with($number, '-') && bccomp($rounded, '0', 4) !== 0
? '-' . $rounded
: $rounded;
}
}
return $this->normalize($fields, $input);
}
/** @param array<string,array{label:string,type:string}> $fields */
public function normalize(array $fields, array $input): array
{

View File

@ -212,7 +212,7 @@ class PayablesFinalImportRunner
unset($values['_action_key'], $values['__import_row_key']);
try {
$normalized = $this->normalizer->normalize($fields, $values);
$normalized = $this->normalizer->normalizeImport($fields, $values);
} catch (ValidationException $exception) {
$this->fail($meta, $line - 1, $created, $updated, $this->rowMessage($firstRow, $line, $exception));
throw ValidationException::withMessages([

View File

@ -99,7 +99,7 @@ class PayablesFinalImporter
}
try {
$values = $this->normalizer->normalize($fields, $rawValues);
$values = $this->normalizer->normalizeImport($fields, $rawValues);
} catch (ValidationException $exception) {
throw ValidationException::withMessages([
'import' => "第 {$line} 行:" . collect($exception->errors())->flatten()->first(),

View File

@ -46,6 +46,34 @@ class PayablesFinalImportRunnerTest extends FeatureTestCase
}
}
public function test_courier_import_removes_excel_tails_without_changing_record_keys(): void
{
$path = $this->makeXlsxFile([
['记录标识', '月份', '物流单号', '结算运费'],
['tail:1', '2026-10', 'SF-TAIL-1', '9.220000000000001'],
['tail:2', '2026-10', 'SF-TAIL-2', '-9.699999999999999'],
]);
try {
$fields = app(PayablesFinalRegistry::class)->fields('courier-payables-final', 'bookkeeping-details');
$dataset = 'final:courier:bookkeeping-details';
$file = new UploadedFile($path, 'tails.xlsx', null, null, true);
$runner = app(PayablesFinalImportRunner::class);
$prepared = $runner->prepare($file, $fields, $dataset, $this->company->id, $this->user->id);
$progress = $runner->process($prepared['token'], 0, 10);
$this->assertTrue($progress['done']);
$this->assertSame(2, $progress['created']);
$store = app(SupplierPayableOverrideStore::class);
$this->assertSame('9.2200', $store->findRow($dataset, 'tail:1', $this->company->id)['settle_freight']);
$this->assertSame('-9.7000', $store->findRow($dataset, 'tail:2', $this->company->id)['settle_freight']);
$legacy = app(\Modules\EcommerceFinance\Services\PayablesFinalImporter::class)
->import($fields, $dataset, $file, $this->company->id, $this->user->id);
$this->assertSame(0, $legacy['created']);
$this->assertSame(2, $legacy['updated']);
} finally {
@unlink($path);
}
}
public function test_stream_reader_keeps_the_first_data_row_after_skipping_the_header(): void
{
$path = $this->makeXlsxFile([

View File

@ -0,0 +1,81 @@
<?php
namespace Tests\Unit;
use Illuminate\Container\Container;
use Illuminate\Support\Facades\Facade;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Factory;
use Illuminate\Validation\ValidationException;
use Modules\EcommerceFinance\Services\PayablesFieldNormalizer;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class PayablesFieldNormalizerTest extends TestCase
{
private $previousApp;
private const FIELDS = ['amount' => ['label' => '金额', 'type' => 'number']];
protected function setUp(): void
{
$this->previousApp = Facade::getFacadeApplication();
$app = new Container;
$app->instance('validator', new Factory(new Translator(new ArrayLoader, 'zh_CN'), $app));
Facade::clearResolvedInstances();
Facade::setFacadeApplication($app);
}
protected function tearDown(): void
{
Facade::clearResolvedInstances();
Facade::setFacadeApplication($this->previousApp);
parent::tearDown();
}
public static function tailValues(): array
{
return [
['9.220000000000001', '9.2200'],
['9.699999999999999', '9.7000'],
['-75.70999999999999', '-75.7100'],
['1.234500000000001', '1.2345'],
['9.220000000001', '9.2200'],
['.09999999999999999', '0.1000'],
['0.000000000000001', '0.0000'],
['-0.000000000000001', '0.0000'],
['9999999999999999.999900000000001', '9999999999999999.9999'],
['12.34000', '12.3400'],
];
}
#[DataProvider('tailValues')]
public function test_import_removes_only_micro_decimal_tails(string $input, string $expected): void
{
$this->assertSame(['amount' => $expected], (new PayablesFieldNormalizer)->normalizeImport(self::FIELDS, ['amount' => $input]));
}
public static function invalidValues(): array
{
return array_map(fn ($value) => [$value], ['9.22001', '9.220000000002', '0.000000001', '1.23456',
'9999999999999999.99999', '10000000000000000.00000', 'NaN', 'INF', '1e-5', '=1+2']);
}
#[DataProvider('invalidValues')]
public function test_import_still_rejects_real_excess_precision_and_invalid_amounts(string $value): void
{
$this->expectException(ValidationException::class);
(new PayablesFieldNormalizer)->normalizeImport(self::FIELDS, ['amount' => $value]);
}
public function test_manual_edit_stays_strict_and_import_preserves_text_and_blank_zero(): void
{
$normalizer = new PayablesFieldNormalizer;
$fields = self::FIELDS + ['code' => ['label' => '编码', 'type' => 'text']];
$this->assertSame(['amount' => '0', 'code' => '00123456789012345678'],
$normalizer->normalizeImport($fields, ['amount' => '0', 'code' => '00123456789012345678']));
$this->assertSame(['amount' => null], $normalizer->normalizeImport(self::FIELDS, ['amount' => '']));
$this->expectException(ValidationException::class);
$normalizer->normalize(self::FIELDS, ['amount' => '9.220000000000001']);
}
}