, * updated: int, * unchanged: int, * file_sha256: string * } */ public function importSource( string $mappingPath, string $period, ?string $sheetName = null, int $companyId = 1, bool $dryRun = false, ): array { if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) { throw new InvalidArgumentException('账期格式必须为 YYYY-MM。'); } if (! is_file($mappingPath) || ! is_readable($mappingPath)) { throw new InvalidArgumentException('物料源文件不存在或不可读:' . $mappingPath); } $connection = $this->connection(); if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_base_rows')) { throw new RuntimeException('顾家过账基础数据表尚未建立,请先执行数据库迁移。'); } $allowedStores = array_values(array_filter(array_map( static fn (mixed $store): string => trim((string) $store), (array) config('kuka_posting.stores', []), ))); if ($allowedStores === []) { throw new RuntimeException('顾家过账基础数据店铺范围未配置。'); } $sheetName = trim((string) ($sheetName ?? '')); if ($sheetName === '') { $sheetName = 'Sheet1'; } $fileHash = hash_file('sha256', $mappingPath); if (! is_string($fileHash)) { throw new RuntimeException('无法计算物料源文件摘要。'); } $sourceRows = $this->readSourceRows($mappingPath, $sheetName, $allowedStores); $validMaterials = []; foreach ($sourceRows as $row) { if ($row['material_number'] !== '') { $validMaterials[$row['material_number']] = true; } } $quotations = $this->loadQuotations( $connection, $companyId, array_keys($validMaterials), ); if ($dryRun) { $collected = $this->collectSourceTargets( $connection, $sourceRows, $quotations, $period, $companyId, false, ); $result = $collected['result']; } else { $result = []; $connection->transaction(function () use ( &$result, $connection, $sourceRows, $quotations, $period, $companyId, ): void { $targets = $this->collectSourceTargets( $connection, $sourceRows, $quotations, $period, $companyId, true, ); $result = $targets['result']; $this->applyMaterials($connection, $targets['targets'], $period, $companyId); }); } return $result + [ 'period' => $period, 'dry_run' => $dryRun, 'file_sha256' => strtolower($fileHash), ]; } /** * @return array{ * period: string, * dry_run: bool, * rows: int, * identities: int, * material_pairs: int, * stores: array, * updated: int, * unchanged: int, * abnormal_file_sha256: string, * mapping_file_sha256: string * } */ public function import( string $abnormalPath, string $mappingPath, string $period, ?string $sheetName = null, int $companyId = 1, bool $dryRun = false, ): array { if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) { throw new InvalidArgumentException('账期格式必须为 YYYY-MM。'); } foreach ([$abnormalPath, $mappingPath] as $path) { if (! is_file($path) || ! is_readable($path)) { throw new InvalidArgumentException('物料修正文件不存在或不可读:' . $path); } } $connection = $this->connection(); if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_base_rows')) { throw new RuntimeException('顾家过账基础数据表尚未建立,请先执行数据库迁移。'); } $allowedStores = array_values(array_filter(array_map( static fn (mixed $store): string => trim((string) $store), (array) config('kuka_posting.stores', []), ))); if ($allowedStores === []) { throw new RuntimeException('顾家过账基础数据店铺范围未配置。'); } $sheetName = trim((string) ($sheetName ?? '')); if ($sheetName === '') { $sheetName = 'Sheet1'; } $abnormalHash = hash_file('sha256', $abnormalPath); $mappingHash = hash_file('sha256', $mappingPath); if (! is_string($abnormalHash) || ! is_string($mappingHash)) { throw new RuntimeException('无法计算物料修正文件摘要。'); } $materials = $this->readMaterialMapping($mappingPath, $sheetName); $records = $this->readAbnormalRows( $abnormalPath, $sheetName, $materials, $allowedStores, ); $quotations = $this->loadQuotations( $connection, $companyId, array_values(array_unique(array_column($records, 'material_number'))), ); if ($dryRun) { $collected = $this->collectTargets( $connection, $records, $quotations, $period, $companyId, false, ); $result = $collected['result']; } else { $result = []; $connection->transaction(function () use ( &$result, $connection, $records, $quotations, $period, $companyId, ): void { $targets = $this->collectTargets( $connection, $records, $quotations, $period, $companyId, true, ); $result = $targets['result']; $this->applyMaterials($connection, $targets['targets'], $period, $companyId); }); } return $result + [ 'period' => $period, 'dry_run' => $dryRun, 'abnormal_file_sha256' => strtolower($abnormalHash), 'mapping_file_sha256' => strtolower($mappingHash), ]; } /** * @return array */ private function readMaterialMapping(string $path, string $sheetName): array { $materials = []; $rows = 0; foreach ($this->reader->rows( $path, array_merge(self::IDENTITY_FIELDS, [ self::MATERIAL_NUMBER_FIELD, self::MATERIAL_DESCRIPTION_SOURCE_FIELD, ]), [], $sheetName, ) as $values) { $rows++; $materialNumber = trim((string) ($values[self::MATERIAL_NUMBER_FIELD] ?? '')); $description = trim((string) ($values[self::MATERIAL_DESCRIPTION_SOURCE_FIELD] ?? '')); if ($this->isMissingMaterialValue($materialNumber) || $this->isMissingMaterialValue($description)) { throw new RuntimeException(sprintf( '表二第 %d 行的物料编号或物料描述为空。', $rows + 1, )); } $key = $this->identityKey($values); $pair = [ 'material_number' => $materialNumber, 'description' => $description, ]; if (isset($materials[$key]) && $materials[$key] !== $pair) { throw new RuntimeException(sprintf( '表二第 %d 行对应的业务记录存在多个物料编号/物料描述组合。', $rows + 1, )); } $materials[$key] = $pair; } if ($materials === []) { throw new RuntimeException('表二没有可用于匹配的物料数据。'); } return $materials; } /** * @param array $materials * @param list $allowedStores * @return list */ private function readAbnormalRows( string $path, string $sheetName, array $materials, array $allowedStores, ): array { $records = []; $excelRowNumber = 1; foreach ($this->reader->rows( $path, array_merge(self::IDENTITY_FIELDS, [ self::MATERIAL_NUMBER_FIELD, self::MATERIAL_DESCRIPTION_SOURCE_FIELD, ]), [], $sheetName, ) as $values) { $excelRowNumber++; $currentMaterial = trim((string) ($values[self::MATERIAL_NUMBER_FIELD] ?? '')); $currentDescription = trim((string) ( $values[self::MATERIAL_DESCRIPTION_SOURCE_FIELD] ?? '' )); if (! $this->isMissingMaterialValue($currentMaterial) || ! $this->isMissingMaterialValue($currentDescription)) { throw new RuntimeException(sprintf( '表一第 %d 行不是缺少物料信息的异常数据。', $excelRowNumber, )); } $store = trim((string) ($values['店铺'] ?? '')); if (! in_array($store, $allowedStores, true)) { throw new RuntimeException(sprintf( '表一第 %d 行的店铺“%s”不在顾家过账基础数据范围内。', $excelRowNumber, $store, )); } $key = $this->identityKey($values); $material = $materials[$key] ?? null; if ($material === null) { throw new RuntimeException(sprintf( '表一第 %d 行在表二中找不到唯一物料信息。', $excelRowNumber, )); } $records[] = [ 'excel_row_number' => $excelRowNumber, 'key' => $key, 'material_number' => $material['material_number'], 'description' => $material['description'], ]; } if ($records === []) { throw new RuntimeException('表一没有可修正的异常数据。'); } return $records; } /** * @param list $allowedStores * @return list */ private function readSourceRows( string $path, string $sheetName, array $allowedStores, ): array { $records = []; $excelRowNumber = 1; foreach ($this->reader->rows( $path, array_merge(self::IDENTITY_FIELDS, [ self::MATERIAL_NUMBER_FIELD, self::MATERIAL_DESCRIPTION_SOURCE_FIELD, ]), [], $sheetName, ) as $values) { $excelRowNumber++; $store = trim((string) ($values['店铺'] ?? '')); if (! in_array($store, $allowedStores, true)) { throw new RuntimeException(sprintf( '表二第 %d 行的店铺“%s”不在顾家过账基础数据范围内。', $excelRowNumber, $store, )); } $quantity = $this->normalizeDecimal($values['实发数量'] ?? ''); if ($quantity === null) { throw new RuntimeException(sprintf( '表二第 %d 行的实发数量格式无效。', $excelRowNumber, )); } if ($quantity === '') { $quantity = '0'; } $materialNumber = trim((string) ($values[self::MATERIAL_NUMBER_FIELD] ?? '')); $description = trim((string) ( $values[self::MATERIAL_DESCRIPTION_SOURCE_FIELD] ?? '' )); $materialMissing = $this->isUnmappedMaterialValue($materialNumber); $descriptionMissing = $this->isUnmappedMaterialValue($description); if ($materialMissing !== $descriptionMissing) { throw new RuntimeException(sprintf( '表二第 %d 行的物料编号和物料描述一个有效、一个无效。', $excelRowNumber, )); } if ($materialMissing) { $materialNumber = ''; $description = ''; } $records[] = [ 'excel_row_number' => $excelRowNumber, 'key' => $this->sourceIdentityKey($values, $quantity), 'quantity' => $quantity, 'material_number' => $materialNumber, 'description' => $description, ]; } if ($records === []) { throw new RuntimeException('表二没有发货明细数据。'); } return $records; } /** * @param list $sourceRows * @param array $quotations * @return array{ * result: array{ * rows: int, * valid_rows: int, * skipped_unmapped_rows: int, * materials: int, * stores: array, * updated: int, * unchanged: int * }, * targets: list> * } */ private function collectSourceTargets( ConnectionInterface $connection, array $sourceRows, array $quotations, string $period, int $companyId, bool $lockRows, ): array { $databaseRows = $this->baseRowsQuery($connection, $period, $companyId)->count(); if ($databaseRows !== count($sourceRows)) { throw new RuntimeException(sprintf( '表二有 %s 行,但共享镜像 %s 有 %s 行,行数不一致,未写入任何物料信息。', number_format(count($sourceRows)), $period, number_format($databaseRows), )); } $query = $this->baseRowsQuery($connection, $period, $companyId) ->orderBy('source_row_number'); if ($lockRows) { $query->lockForUpdate(); } $targets = []; $stores = []; $materials = []; $updated = 0; $unchanged = 0; $validRows = 0; $skippedRows = 0; $index = 0; foreach ($query->cursor() as $row) { $source = $sourceRows[$index] ?? null; if ($source === null) { throw new RuntimeException('共享镜像行数多于表二,未写入任何物料信息。'); } $values = $this->decodeSourceValues($row); $databaseQuantity = $this->normalizeDecimal($values['实发数量'] ?? ''); $databaseQuantity = $databaseQuantity === null || $databaseQuantity === '' ? '0' : $databaseQuantity; if ($this->sourceIdentityKey($values, $databaseQuantity) !== $source['key']) { throw new RuntimeException(sprintf( '表二第 %d 行与共享镜像 source_row_number=%d 的业务字段不一致,未写入任何物料信息。', $source['excel_row_number'], (int) $row->source_row_number, )); } $index++; if ($source['material_number'] === '') { $skippedRows++; continue; } $validRows++; $materials[$source['material_number']] = true; $quote = $quotations[$source['material_number']]; $expectedCost = $quote['price']; $expectedAmount = $this->multiplyDecimal($expectedCost, $source['quantity']); $currentMaterial = trim((string) ( $values[self::MATERIAL_NUMBER_FIELD] ?? '' )); $currentDescription = trim((string) ( $values[self::MATERIAL_DESCRIPTION_DATABASE_FIELD] ?? '' )); $currentCost = trim((string) ($values[self::COST_FIELD] ?? '')); $currentAmount = trim((string) ( $values[self::SHIPPING_AMOUNT_FIELD] ?? '' )); $isMarked = trim((string) ($values[self::REPAIR_MARKER_FIELD] ?? '')) === '是'; $materialMatches = $currentMaterial === $source['material_number'] && $currentDescription === $source['description']; $financialMatches = $this->decimalEquals($currentCost, $expectedCost) && $this->decimalEquals($currentAmount, $expectedAmount); $changed = ! $materialMatches || ! $isMarked || ! $financialMatches; $store = $source['material_number'] === '' ? '' : trim((string) ($values['店铺'] ?? '')); if ($store !== '') { $stores[$store] = ($stores[$store] ?? 0) + 1; } if ($changed) { $updated++; } else { $unchanged++; } $targets[] = [ 'row' => $row, 'values' => $values, 'material_number' => $source['material_number'], 'description' => $source['description'], 'cost' => $expectedCost, 'shipping_amount' => $expectedAmount, 'changed' => $changed, ]; } if ($index !== count($sourceRows)) { throw new RuntimeException('共享镜像行数少于表二,未写入任何物料信息。'); } ksort($stores); return [ 'result' => [ 'rows' => count($sourceRows), 'valid_rows' => $validRows, 'skipped_unmapped_rows' => $skippedRows, 'materials' => count($materials), 'stores' => $stores, 'updated' => $updated, 'unchanged' => $unchanged, ], 'targets' => $targets, ]; } /** * @param list $materialNumbers * @return array */ private function loadQuotations( ConnectionInterface $connection, int $companyId, array $materialNumbers, ): array { if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_quotation_rows')) { throw new RuntimeException('顾家报价单表尚未建立,无法计算成本和发货金额。'); } $quotations = []; $rows = $connection->table('kuka_posting_quotation_rows') ->where('company_id', $companyId) ->where('record_status', '生效') ->whereIn('material_number', $materialNumbers) ->orderBy('material_number') ->get(['material_number', 'material_desc', 'price_including_tax']); foreach ($rows as $row) { $materialNumber = trim((string) $row->material_number); if (isset($quotations[$materialNumber])) { throw new RuntimeException(sprintf( '物料编号 %s 存在多条生效报价,无法确定唯一成本。', $materialNumber, )); } $price = $this->normalizeDecimal($row->price_including_tax); if ($price === null) { throw new RuntimeException(sprintf( '物料编号 %s 的生效报价含税价为空或格式无效。', $materialNumber, )); } $price = $this->formatDecimal($price); $quotations[$materialNumber] = [ 'price' => $price, 'description' => trim((string) ($row->material_desc ?? '')), ]; } foreach ($materialNumbers as $materialNumber) { if (! isset($quotations[$materialNumber])) { throw new RuntimeException(sprintf( '物料编号 %s 没有生效报价,无法计算成本和发货金额。', $materialNumber, )); } } return $quotations; } /** * @param list $records * @param array $quotations * @return array{ * result: array{ * rows: int, * identities: int, * material_pairs: int, * stores: array, * updated: int, * unchanged: int * }, * targets: list> * } */ private function collectTargets( ConnectionInterface $connection, array $records, array $quotations, string $period, int $companyId, bool $lockRows, ): array { $expectedCounts = []; $expectedMaterials = []; $pairs = []; foreach ($records as $record) { $expectedCounts[$record['key']] = ($expectedCounts[$record['key']] ?? 0) + 1; $expectedMaterials[$record['key']] = [ 'material_number' => $record['material_number'], 'description' => $record['description'], ]; $pairs[$record['material_number']."\x1F".$record['description']] = true; } $foundCounts = []; $targets = []; $stores = []; $updated = 0; $unchanged = 0; $query = $this->baseRowsQuery($connection, $period, $companyId) ->orderBy('source_row_number'); if ($lockRows) { $query->lockForUpdate(); } foreach ($query->cursor() as $row) { $values = $this->decodeSourceValues($row); $key = $this->identityKey($values); if (! isset($expectedCounts[$key])) { continue; } $foundCounts[$key] = ($foundCounts[$key] ?? 0) + 1; if ($foundCounts[$key] > $expectedCounts[$key]) { throw new RuntimeException( '共享镜像中同一业务记录出现多条与异常清单不匹配的数据,未写入任何物料信息。', ); } $currentMaterial = trim((string) ($values[self::MATERIAL_NUMBER_FIELD] ?? '')); $currentDescription = trim((string) ( $values[self::MATERIAL_DESCRIPTION_DATABASE_FIELD] ?? '' )); $currentCost = trim((string) ($values[self::COST_FIELD] ?? '')); $currentAmount = trim((string) ($values[self::SHIPPING_AMOUNT_FIELD] ?? '')); $isMarked = trim((string) ($values[self::REPAIR_MARKER_FIELD] ?? '')) === '是'; $expected = $expectedMaterials[$key]; $currentIsBlank = $this->isMissingMaterialValue($currentMaterial) && $this->isMissingMaterialValue($currentDescription); $currentMatches = $currentMaterial === $expected['material_number'] && $currentDescription === $expected['description']; if (! $currentIsBlank && ! $currentMatches) { throw new RuntimeException(sprintf( '共享镜像 source_row_number=%d 已有不同物料信息,拒绝覆盖。', (int) $row->source_row_number, )); } $quotation = $quotations[$expected['material_number']]; $quantity = $this->normalizeDecimal($values['实发数量'] ?? null); if ($quantity === null) { throw new RuntimeException(sprintf( '共享镜像 source_row_number=%d 的实发数量无效,无法计算发货金额。', (int) $row->source_row_number, )); } $expectedCost = $quotation['price']; $expectedAmount = $this->multiplyDecimal($expectedCost, $quantity); $financialMatches = $this->decimalEquals($currentCost, $expectedCost) && $this->decimalEquals($currentAmount, $expectedAmount); $store = trim((string) ($values['店铺'] ?? '')); $stores[$store] = ($stores[$store] ?? 0) + 1; if ($currentMatches && $isMarked && $financialMatches) { $unchanged++; } else { $updated++; } $targets[] = [ 'row' => $row, 'values' => $values, 'material_number' => $expected['material_number'], 'description' => $expected['description'], 'cost' => $expectedCost, 'shipping_amount' => $expectedAmount, 'changed' => ! $currentMatches || ! $isMarked || ! $financialMatches, ]; } foreach ($expectedCounts as $key => $expectedCount) { if (($foundCounts[$key] ?? 0) !== $expectedCount) { throw new RuntimeException('共享镜像与表一异常数据的逐行数量不一致,未写入任何物料信息。'); } } ksort($stores); return [ 'result' => [ 'rows' => count($records), 'identities' => count($expectedCounts), 'material_pairs' => count($pairs), 'stores' => $stores, 'updated' => $updated, 'unchanged' => $unchanged, ], 'targets' => $targets, ]; } /** * @param list> $targets */ private function applyMaterials( ConnectionInterface $connection, array $targets, string $period, int $companyId, ): void { $batch = []; $flush = static function () use (&$batch, $connection): void { if ($batch === []) { return; } $connection->table('kuka_posting_base_rows')->upsert( $batch, ['company_id', 'period', 'source_row_number'], ['source_values', 'row_hash'], ); $batch = []; }; foreach ($targets as $target) { if (! $target['changed']) { continue; } $row = $target['row']; $values = $target['values']; $values[self::MATERIAL_NUMBER_FIELD] = $target['material_number']; $values[self::MATERIAL_DESCRIPTION_DATABASE_FIELD] = $target['description']; $values[self::COST_FIELD] = $target['cost']; $values[self::SHIPPING_AMOUNT_FIELD] = $target['shipping_amount']; $values[self::REPAIR_MARKER_FIELD] = '是'; $encoded = json_encode( $values, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR, ); $batch[] = [ 'company_id' => $companyId, 'period' => $period, 'source_row_number' => (int) $row->source_row_number, 'store_name' => $row->store_name, 'internal_order_no' => $row->internal_order_no, 'online_order_no' => $row->online_order_no, 'product_code' => $row->product_code, 'source_values' => $encoded, 'row_hash' => hash('sha256', $encoded), 'imported_at' => $row->imported_at, ]; if (count($batch) >= self::UPDATE_CHUNK) { $flush(); } } $flush(); } /** * @param array $values */ private function identityKey(array $values): string { $parts = []; foreach (self::IDENTITY_FIELDS as $field) { $value = trim((string) ($values[$field] ?? '')); if ($field === '发货日期') { $value = $this->normalizeDate($value); } $parts[] = $value; } return implode("\x1F", $parts); } /** * @param array $values */ private function sourceIdentityKey(array $values, string $quantity): string { $parts = []; foreach (self::IDENTITY_FIELDS as $field) { if ($field === '实发数量') { $parts[] = $quantity; continue; } $value = trim((string) ($values[$field] ?? '')); $parts[] = $field === '发货日期' ? $this->normalizeDateTime($value) : $value; } return implode("\x1F", $parts); } private function normalizeDateTime(string $value): string { if (is_numeric($value) && (float) $value > 20000 && (float) $value < 90000) { return gmdate('Y-m-d H:i:s', (int) round(((float) $value - 25569) * 86400)); } if (preg_match( '/^(\d{4})[\/-](\d{1,2})[\/-](\d{1,2})[ T](\d{1,2}):(\d{2}):(\d{2})/', $value, $matches, ) === 1) { return sprintf( '%04d-%02d-%02d %02d:%s:%s', (int) $matches[1], (int) $matches[2], (int) $matches[3], (int) $matches[4], $matches[5], $matches[6], ); } return $this->normalizeDate($value); } private function normalizeDate(string $value): string { if (is_numeric($value) && (float) $value > 20000 && (float) $value < 90000) { return gmdate('Y-m-d', (int) round(((float) $value - 25569) * 86400)); } if (preg_match('/^(\d{4})[\/-](\d{1,2})[\/-](\d{1,2})/', $value, $matches) === 1) { return sprintf( '%04d-%02d-%02d', (int) $matches[1], (int) $matches[2], (int) $matches[3], ); } return $value; } private function isMissingMaterialValue(string $value): bool { return in_array(trim($value), self::MISSING_VALUES, true); } private function isUnmappedMaterialValue(string $value): bool { return $this->isMissingMaterialValue($value) || in_array( strtoupper(trim($value)), ['#N/A', '#REF!', '#VALUE!', '#NAME?', '#NUM!'], true, ); } private function normalizeDecimal(mixed $value): ?string { $normalized = str_replace(',', '', trim((string) $value)); return $normalized !== '' && is_numeric($normalized) ? $normalized : null; } private function multiplyDecimal(string $left, string $right): string { if (function_exists('bcmul')) { return bcmul($left, $right, 4); } return number_format((float) $left * (float) $right, 4, '.', ''); } private function formatDecimal(string $value): string { if (function_exists('bcadd')) { return bcadd($value, '0', 4); } return number_format((float) $value, 4, '.', ''); } private function decimalEquals(string $left, string $right): bool { if ($left === '' || $right === '') { return false; } if (function_exists('bccomp')) { return bccomp($left, $right, 4) === 0; } return abs((float) $left - (float) $right) < 0.00005; } /** * @return array */ private function decodeSourceValues(object $row): array { $values = json_decode( (string) $row->source_values, true, 512, JSON_THROW_ON_ERROR, ); if (! is_array($values)) { throw new RuntimeException(sprintf( '共享镜像 source_row_number=%d 的源数据不是有效对象。', (int) $row->source_row_number, )); } return $values; } private function baseRowsQuery( ConnectionInterface $connection, string $period, int $companyId, ) { return $connection->table('kuka_posting_base_rows') ->where('company_id', $companyId) ->where('period', $period) ->select([ 'id', 'source_row_number', 'store_name', 'internal_order_no', 'online_order_no', 'product_code', 'source_values', 'imported_at', ]); } private function connection(): ConnectionInterface { return $this->databases->connection($this->connectionName()); } private function connectionName(): string { return (string) config('upstream_mirrors.connection', 'business_mirror'); } }