From 00728c5212f71c5d47b4bae9db3ba4803efcb65f Mon Sep 17 00:00:00 2001 From: DoDo <1060330844@qq.com> Date: Wed, 11 Nov 2026 17:45:18 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=9B=BA=E5=AE=9A=E5=AE=A2=E6=9C=8D?= =?UTF-8?q?=E5=85=AC=E5=8F=B8=E6=98=A0=E5=B0=84=E5=B9=B6=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E5=B9=B3=E8=A1=A1=E6=9C=AA=E5=88=86=E9=85=8D=E5=BA=97=E9=93=BA?= =?UTF-8?q?=20(#1096)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 固定已有映射,收入店铺自动平衡后锁定。 --- ...CustomerServiceMappingWorkbookImporter.php | 15 +- ...ServiceCompanyReconciliationRepository.php | 241 ++++++++++++++++-- .../ImportServiceCompanyCustomerMapping.php | 21 ++ docs/服务公司对账配置方案.md | 2 + .../ServiceCompanyReconciliationTest.php | 120 +++++++++ 5 files changed, 367 insertions(+), 32 deletions(-) diff --git a/app/Business/ServiceCompanyReconciliation/CustomerServiceMappingWorkbookImporter.php b/app/Business/ServiceCompanyReconciliation/CustomerServiceMappingWorkbookImporter.php index c466a0fe..76270b0b 100644 --- a/app/Business/ServiceCompanyReconciliation/CustomerServiceMappingWorkbookImporter.php +++ b/app/Business/ServiceCompanyReconciliation/CustomerServiceMappingWorkbookImporter.php @@ -15,6 +15,7 @@ class CustomerServiceMappingWorkbookImporter * total_rows:int, * assigned_rows:int, * unassigned_rows:int, + * unassigned:list, * invalid_rows:list * } */ @@ -29,6 +30,7 @@ class CustomerServiceMappingWorkbookImporter 'total_rows' => 0, 'assigned_rows' => 0, 'unassigned_rows' => 0, + 'unassigned' => [], 'invalid_rows' => [], ]; foreach ($this->reader->rows( @@ -43,16 +45,21 @@ class CustomerServiceMappingWorkbookImporter if ($storeName === '') { continue; } - if ($serviceName === '') { - $result['unassigned_rows']++; - continue; - } $feeRate = $this->feeRate((string) ($row['结算比例'] ?? '')); if ($feeRate === null) { $result['invalid_rows'][] = "第 {$sourceRow} 行结算比例无效。"; continue; } + if ($serviceName === '') { + $result['unassigned_rows']++; + $result['unassigned'][] = [ + 'store_company_name' => $storeName, + 'fee_rate' => $feeRate, + 'source_row' => $sourceRow, + ]; + continue; + } $result['rows'][] = [ 'service_company_name' => $serviceName, diff --git a/app/Business/ServiceCompanyReconciliation/ServiceCompanyReconciliationRepository.php b/app/Business/ServiceCompanyReconciliation/ServiceCompanyReconciliationRepository.php index ac854673..3ab7c2b4 100644 --- a/app/Business/ServiceCompanyReconciliation/ServiceCompanyReconciliationRepository.php +++ b/app/Business/ServiceCompanyReconciliation/ServiceCompanyReconciliationRepository.php @@ -637,15 +637,27 @@ class ServiceCompanyReconciliationRepository * 将客服公司 Excel 中的店铺公司映射同步为结算关系。 * * @param list $rows - * @return array{created:int,updated:int,unchanged:int,inactive:int,errors:list} + * @param list $unassignedRows + * @return array{created:int,updated:int,unchanged:int,inactive:int,auto_assigned:int,errors:list,auto_errors:list,auto_totals:array} */ public function syncCustomerServiceMappings( int $tenantId, array $rows, string $effectiveFrom, string $actor, + array $unassignedRows = [], + ?string $autoAssignPeriod = null, ): array { - $result = ['created' => 0, 'updated' => 0, 'unchanged' => 0, 'inactive' => 0, 'errors' => []]; + $result = [ + 'created' => 0, + 'updated' => 0, + 'unchanged' => 0, + 'inactive' => 0, + 'auto_assigned' => 0, + 'errors' => [], + 'auto_errors' => [], + 'auto_totals' => [], + ]; if (preg_match('/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/', $effectiveFrom) !== 1) { $result['errors'][] = '生效日期格式必须是 YYYY-MM-DD。'; @@ -736,6 +748,7 @@ class ServiceCompanyReconciliationRepository 'store_company_credit_code' => $creditCode !== '' ? $creditCode : null, 'fee_rate' => $feeRate, 'effective_from' => $effectiveFrom, + 'source' => 'customer_service_mapping', ]; } @@ -743,6 +756,179 @@ class ServiceCompanyReconciliationRepository return $result; } + $supersededAutoRelationIds = []; + if ($autoAssignPeriod !== null && $autoAssignPeriod !== '') { + if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $autoAssignPeriod) !== 1) { + $result['auto_errors'][] = '自动分配月份格式必须是 YYYY-MM。'; + } else { + $paidGeneration = $this->activeGeneration('store-report.paid-sales'); + $lifecycleGeneration = $this->activeGeneration('store-report.store-lifecycles'); + if ($paidGeneration === null || $lifecycleGeneration === null) { + $result['auto_errors'][] = '业绩明细或店铺主体期间尚未完成同步,未自动补分配。'; + } else { + $periodStart = CarbonImmutable::createFromFormat('!Y-m', $autoAssignPeriod)->startOfMonth(); + $baseRows = $this->baseRowsByStoreCompany( + $paidGeneration, + $lifecycleGeneration, + $periodStart, + $periodStart->addMonth(), + ); + $existingRelations = $this->connection->table('svc_service_relations') + ->where('company_id', $tenantId) + ->where('service_type_code', 'customer_service') + ->where('status', 'active') + ->where('effective_from', '<=', $periodStart->endOfMonth()->toDateString()) + ->where(static fn ($query) => $query + ->whereNull('effective_to') + ->orWhere('effective_to', '>=', $periodStart->toDateString())) + ->get(); + $assignmentsByStoreKey = []; + foreach ($existingRelations as $existingRelation) { + $assignmentsByStoreKey[(string) $existingRelation->store_company_key] = $existingRelation; + } + foreach ($prepared as $preparedRow) { + $existingAssignment = $assignmentsByStoreKey[$preparedRow['store_company_key']] ?? null; + if ($existingAssignment + && (int) $existingAssignment->service_company_id !== $preparedRow['service_company_id']) { + if ((string) $existingAssignment->source === 'customer_service_auto_balance') { + $supersededAutoRelationIds[] = (int) $existingAssignment->id; + } else { + $result['errors'][] = sprintf( + '店铺公司 %s 已固定分配给 %s,不能自动改派到 %s。', + $preparedRow['store_company_name'], + $existingAssignment->service_company_name, + $preparedRow['service_company_name'], + ); + continue; + } + } + $assignmentsByStoreKey[$preparedRow['store_company_key']] = (object) [ + 'service_company_id' => $preparedRow['service_company_id'], + 'store_company_key' => $preparedRow['store_company_key'], + 'source' => $preparedRow['source'], + ]; + } + if ($result['errors'] !== []) { + return $result; + } + + $totalsByService = []; + $relationCounts = []; + foreach ($serviceCompanies as $serviceCompany) { + $totalsByService[(int) $serviceCompany->id] = 0.0; + $relationCounts[(int) $serviceCompany->id] = 0; + } + foreach ($assignmentsByStoreKey as $storeCompanyKey => $assignment) { + $serviceId = (int) $assignment->service_company_id; + if (! array_key_exists($serviceId, $totalsByService)) { + continue; + } + $relationCounts[$serviceId] = ($relationCounts[$serviceId] ?? 0) + 1; + $totalsByService[$serviceId] = ($totalsByService[$serviceId] ?? 0.0) + + collect($baseRows[$storeCompanyKey] ?? [])->sum('base_amount'); + } + + $candidates = []; + foreach ($unassignedRows as $index => $row) { + $sourceRow = (int) ($row['source_row'] ?? ($index + count($rows) + 2)); + $storeName = trim((string) ($row['store_company_name'] ?? '')); + $feeRate = round((float) ($row['fee_rate'] ?? 0), 6); + if ($storeName === '' || $feeRate <= 0 || $feeRate > 1) { + continue; + } + $nameKey = $this->mappingCompanyNameKey($storeName); + $storeCompany = $storesByName[$nameKey] ?? null; + $directoryCompany = $directoryByName[$nameKey] ?? null; + if (! $storeCompany && ! $directoryCompany) { + $result['auto_errors'][] = "第 {$sourceRow} 行未分配店铺公司不在公司基础信息中:{$storeName}"; + continue; + } + $canonicalStoreName = trim((string) ( + $storeCompany['name'] + ?? $directoryCompany['company_name'] + )); + $creditCode = strtoupper(trim((string) ( + $storeCompany['unified_social_credit_code'] + ?? $directoryCompany['unified_social_credit_code'] + ?? '' + ))); + $storeCompanyKey = self::companyKey($canonicalStoreName, $creditCode); + if (isset($assignmentsByStoreKey[$storeCompanyKey])) { + continue; + } + $baseAmount = collect($baseRows[$storeCompanyKey] ?? [])->sum('base_amount'); + if ((float) $baseAmount <= 0) { + continue; + } + $candidates[] = [ + 'source_row' => $sourceRow, + 'store_company_key' => $storeCompanyKey, + 'store_company_name' => $canonicalStoreName, + 'store_company_credit_code' => $creditCode !== '' ? $creditCode : null, + 'fee_rate' => $feeRate, + 'base_amount' => (float) $baseAmount, + ]; + } + + usort($candidates, static fn (array $left, array $right): int => [ + $right['base_amount'], + $left['store_company_name'], + ] <=> [ + $left['base_amount'], + $right['store_company_name'], + ]); + foreach ($candidates as $candidate) { + $target = null; + foreach ($serviceCompanies as $serviceCompany) { + $serviceId = (int) $serviceCompany->id; + $score = [ + $totalsByService[$serviceId], + $relationCounts[$serviceId], + $this->mappingCompanyNameKey((string) $serviceCompany->company_name), + ]; + if ($target === null || $score < $target['score']) { + $target = ['company' => $serviceCompany, 'score' => $score]; + } + } + if ($target === null) { + $result['auto_errors'][] = '没有可用的客服服务公司,未自动补分配。'; + break; + } + + $serviceCompany = $target['company']; + $serviceId = (int) $serviceCompany->id; + $uniqueKey = $serviceId . '|' . $candidate['store_company_key'] . '|' . $effectiveFrom; + $seen[$uniqueKey] = true; + $prepared[] = [ + 'service_company_id' => $serviceId, + 'service_company_key' => (string) $serviceCompany->company_key, + 'service_company_name' => (string) $serviceCompany->company_name, + 'store_company_key' => $candidate['store_company_key'], + 'store_company_name' => $candidate['store_company_name'], + 'store_company_credit_code' => $candidate['store_company_credit_code'], + 'fee_rate' => $candidate['fee_rate'], + 'effective_from' => $effectiveFrom, + 'source' => 'customer_service_auto_balance', + ]; + $assignmentsByStoreKey[$candidate['store_company_key']] = (object) [ + 'service_company_id' => $serviceId, + 'store_company_key' => $candidate['store_company_key'], + 'source' => 'customer_service_auto_balance', + ]; + $totalsByService[$serviceId] += $candidate['base_amount']; + $relationCounts[$serviceId]++; + $result['auto_assigned']++; + } + + foreach ($serviceCompanies as $serviceCompany) { + $result['auto_totals'][(string) $serviceCompany->company_name] = + round($totalsByService[(int) $serviceCompany->id], 2); + } + ksort($result['auto_totals']); + } + } + } + $syncedAt = now(); $this->connection->transaction(function () use ( $tenantId, @@ -750,9 +936,32 @@ class ServiceCompanyReconciliationRepository $effectiveFrom, $actor, $syncedAt, - $seen, + $supersededAutoRelationIds, &$result, ): void { + foreach (array_unique($supersededAutoRelationIds) as $relationId) { + $relation = $this->connection->table('svc_service_relations')->find($relationId); + if (! $relation + || (string) $relation->source !== 'customer_service_auto_balance' + || (string) $relation->status !== 'active') { + continue; + } + $old = (array) $relation; + $this->recordRelationVersion($tenantId, (int) $relation->id, $old, $actor); + $this->connection->table('svc_service_relations') + ->where('id', $relation->id) + ->update([ + 'status' => 'inactive', + 'rule_version' => (int) $relation->rule_version + 1, + 'source_synced_at' => $syncedAt, + 'updated_by' => $actor, + 'updated_at' => $syncedAt, + ]); + $updated = (array) $this->connection->table('svc_service_relations')->find($relation->id); + $this->recordRelationVersion($tenantId, (int) $relation->id, $updated, $actor); + $result['inactive']++; + } + foreach ($prepared as $row) { $payload = [ 'service_company_key' => $row['service_company_key'], @@ -768,7 +977,7 @@ class ServiceCompanyReconciliationRepository 'contract_no' => null, 'contract_status' => 'pending', 'status' => 'active', - 'source' => 'customer_service_mapping', + 'source' => $row['source'], 'source_synced_at' => $syncedAt, 'notes' => '来源:客服公司 Excel 店铺映射', 'updated_by' => $actor, @@ -825,30 +1034,6 @@ class ServiceCompanyReconciliationRepository $result['updated']++; } - $imported = $this->connection->table('svc_service_relations') - ->where('company_id', $tenantId) - ->where('source', 'customer_service_mapping') - ->where('status', 'active') - ->get(); - foreach ($imported as $relation) { - $key = (int) $relation->service_company_id - . '|' - . (string) $relation->store_company_key - . '|' - . (string) $relation->effective_from; - if (isset($seen[$key])) { - continue; - } - $this->connection->table('svc_service_relations') - ->where('id', $relation->id) - ->update([ - 'status' => 'inactive', - 'source_synced_at' => $syncedAt, - 'updated_by' => $actor, - 'updated_at' => $syncedAt, - ]); - $result['inactive']++; - } }); return $result; diff --git a/app/Console/Commands/ImportServiceCompanyCustomerMapping.php b/app/Console/Commands/ImportServiceCompanyCustomerMapping.php index 099fa5f8..47e0ed68 100644 --- a/app/Console/Commands/ImportServiceCompanyCustomerMapping.php +++ b/app/Console/Commands/ImportServiceCompanyCustomerMapping.php @@ -12,6 +12,7 @@ class ImportServiceCompanyCustomerMapping extends Command {file : 客服公司映射 Excel 路径} {--company-id=1 : 租户公司 ID} {--effective-from=2026-10-01 : 结算关系生效日期} + {--auto-assign-period= : 未分配店铺按该月收入自动平衡,默认上一个完整月} {--actor=客服公司映射导入 : 导入操作人} {--dry-run : 只解析和校验,不写入数据库}'; @@ -23,6 +24,10 @@ class ImportServiceCompanyCustomerMapping extends Command ): int { $companyId = (int) $this->option('company-id'); $effectiveFrom = trim((string) $this->option('effective-from')); + $autoAssignPeriod = trim((string) $this->option('auto-assign-period')); + if ($autoAssignPeriod === '') { + $autoAssignPeriod = now()->startOfMonth()->subMonthNoOverflow()->format('Y-m'); + } try { $parsed = $importer->rows((string) $this->argument('file')); } catch (\Throwable $exception) { @@ -53,6 +58,8 @@ class ImportServiceCompanyCustomerMapping extends Command $parsed['rows'], $effectiveFrom, trim((string) $this->option('actor')) ?: '客服公司映射导入', + $parsed['unassigned'], + $autoAssignPeriod, ); if ($result['errors'] !== []) { $this->error(implode(PHP_EOL, $result['errors'])); @@ -65,7 +72,21 @@ class ImportServiceCompanyCustomerMapping extends Command ['更新', $result['updated']], ['无变化', $result['unchanged']], ['停用', $result['inactive']], + ['自动补分配', $result['auto_assigned']], + ['有收入但无法分配', count($result['auto_errors'])], ]); + if ($result['auto_totals'] !== []) { + $this->table( + ['客服公司', '自动补分配后收入'], + collect($result['auto_totals']) + ->map(static fn (float $amount, string $name): array => [$name, number_format($amount, 2, '.', '')]) + ->values() + ->all(), + ); + } + if ($result['auto_errors'] !== []) { + $this->warn(implode(PHP_EOL, $result['auto_errors'])); + } $this->info("客服公司映射已同步,生效日期:{$effectiveFrom}"); return self::SUCCESS; diff --git a/docs/服务公司对账配置方案.md b/docs/服务公司对账配置方案.md index 93e1d4f0..9100d6c8 100644 --- a/docs/服务公司对账配置方案.md +++ b/docs/服务公司对账配置方案.md @@ -362,6 +362,8 @@ - 盘点类型改成非服务公司后,自动来源记录转为停用,历史关系和结算保留。 - 店铺公司来自店铺主体生命周期,关系按生效期间保存。 - 可使用 `php artisan service-company:import-customer-mapping <文件> --effective-from=YYYY-MM-DD` 导入客服公司映射;文件读取 `公司盘点` 工作表,按“公司名称、结算比例、对应客服公司”建立关系,空客服公司视为暂不分配。 +- 已有客服服务关系一经建立即固定,后续导入不会因收入变化自动改派;如文件明确给出不同客服公司、与原固定关系冲突,导入会阻断并要求人工确认,避免两家客服公司串账。 +- 从未配置过的店铺公司在自动分配月份有收入时,按收入从高到低依次分配给当前累计收入较少的客服公司;分派后立即固化为普通映射关系,后续导入不再重新平衡。 - 同一店铺公司 + 同一服务类型禁止重叠服务公司。 - 关系修改递增版本,并将历史快照保存在 `svc_service_relation_versions`。 - 人员从现有工资快照选择并归属服务公司,人员同一天只能有一个有效主归属。 diff --git a/tests/Feature/Business/ServiceCompanyReconciliationTest.php b/tests/Feature/Business/ServiceCompanyReconciliationTest.php index 90e178dc..e7387e33 100644 --- a/tests/Feature/Business/ServiceCompanyReconciliationTest.php +++ b/tests/Feature/Business/ServiceCompanyReconciliationTest.php @@ -319,6 +319,126 @@ SQL); $this->assertSame(1, DB::connection('business_mirror')->table('svc_service_relations')->count()); } + public function test_unassigned_store_with_income_is_auto_balanced_once_and_then_fixed(): void + { + $this->seedStoreMirror('2026-10'); + $this->loginAs(); + $firstServiceId = $this->createServiceCompany( + '常州测试客服甲公司', + '91320400TESTCUSTOMERA', + ); + $secondServiceId = $this->createServiceCompany( + '常州测试客服乙公司', + '91320400TESTCUSTOMERB', + ); + $mirror = DB::connection('business_mirror'); + $paidGeneration = '11111111-1111-1111-1111-111111111111'; + $lifecycleGeneration = '22222222-2222-2222-2222-222222222222'; + foreach ([ + ['上海测试店铺二公司有限公司', '91310000TESTSTORE02', true], + ['上海测试店铺三公司有限公司', '91310000TESTSTORE03', false], + ] as [$companyName, $creditCode, $hasIncome]) { + $mirror->table('store_report_lifecycle_rows')->insert([ + 'generation' => $lifecycleGeneration, + 'business_key' => hash('sha256', $companyName . '|2025-01-01'), + 'erp_store_name' => $companyName . '店铺', + 'company_name' => $companyName, + 'unified_social_credit_code' => $creditCode, + 'effective_at' => '2025-01-01 00:00:00', + 'expires_at' => null, + 'source_file' => 'test.xlsx', + 'row_hash' => hash('sha256', 'lifecycle-' . $creditCode), + 'imported_at' => now(), + ]); + if ($hasIncome) { + $mirror->table('store_report_paid_sales_rows')->insert([ + 'generation' => $paidGeneration, + 'store_name' => $companyName . '店铺', + 'occurred_on' => '2026-10-09', + 'paid_amount' => 20000, + 'settlement_income' => 20000, + 'order_count' => 1, + 'updated_at' => now(), + ]); + } + } + + $repository = app(ServiceCompanyReconciliationRepository::class); + $assigned = [[ + 'service_company_name' => '常州测试客服甲公司', + 'store_company_name' => '上海测试店铺公司有限公司', + 'fee_rate' => 0.015, + 'source_row' => 2, + ]]; + $unassigned = [ + ['store_company_name' => '上海测试店铺二公司有限公司', 'fee_rate' => 0.015, 'source_row' => 3], + ['store_company_name' => '上海测试店铺三公司有限公司', 'fee_rate' => 0.015, 'source_row' => 4], + ]; + $first = $repository->syncCustomerServiceMappings( + $this->company->id, + $assigned, + '2026-10-01', + '测试导入', + $unassigned, + '2026-10', + ); + $this->assertSame(1, $first['auto_assigned']); + $this->assertSame(125000.0, $first['auto_totals']['常州测试客服甲公司']); + $this->assertSame(20000.0, $first['auto_totals']['常州测试客服乙公司']); + $autoRelation = $mirror->table('svc_service_relations') + ->where('store_company_name', '上海测试店铺二公司有限公司') + ->first(); + $this->assertSame($secondServiceId, (int) $autoRelation->service_company_id); + $this->assertSame('customer_service_auto_balance', $autoRelation->source); + $this->assertSame( + 0, + $mirror->table('svc_service_relations') + ->where('store_company_name', '上海测试店铺三公司有限公司') + ->count(), + ); + + $second = $repository->syncCustomerServiceMappings( + $this->company->id, + $assigned, + '2026-10-01', + '再次导入', + $unassigned, + '2026-10', + ); + $this->assertSame(0, $second['auto_assigned']); + $this->assertSame( + $secondServiceId, + (int) $mirror->table('svc_service_relations') + ->where('store_company_name', '上海测试店铺二公司有限公司') + ->value('service_company_id'), + ); + $this->assertSame( + 2, + $mirror->table('svc_service_relations')->count(), + ); + + $conflict = $repository->syncCustomerServiceMappings( + $this->company->id, + [[ + 'service_company_name' => '常州测试客服乙公司', + 'store_company_name' => '上海测试店铺公司有限公司', + 'fee_rate' => 0.015, + 'source_row' => 2, + ]], + '2026-10-01', + '错误改派', + [], + '2026-10', + ); + $this->assertNotSame([], $conflict['errors']); + $this->assertSame( + $firstServiceId, + (int) $mirror->table('svc_service_relations') + ->where('store_company_name', '上海测试店铺公司有限公司') + ->value('service_company_id'), + ); + } + public function test_same_store_company_and_service_type_cannot_have_overlapping_service_companies(): void { $this->seedStoreMirror();