feat: 服务公司对账自动同步公司盘点 (#1087)

This commit is contained in:
DoDo 2026-11-11 17:05:58 +08:00
parent 868a1ec403
commit 89a7ee4d3a
9 changed files with 371 additions and 5 deletions

View File

@ -281,6 +281,37 @@ SQL);
return $statement->fetchAll();
}
/**
* 服务公司对账从公司盘点读取类型包含“服务公司”的主体。
*
* @return list<array<string,mixed>>
*/
public function serviceCompanyRows(int $companyId): array
{
$statement = $this->pdo()->prepare(<<<'SQL'
SELECT
id,
company_name,
company_type,
taxpayer_type,
business_registration_type,
unified_social_credit_code,
company_status,
sequence_no
FROM company_plan_rows
WHERE company_id = :company_id
AND company_type IS NOT NULL
AND TRIM(company_type) LIKE '%服务公司%'
ORDER BY
CASE WHEN sequence_no IS NULL THEN 1 ELSE 0 END,
sequence_no,
id
SQL);
$statement->execute([':company_id' => $companyId]);
return $statement->fetchAll();
}
public function findForCompany(int $companyId, int $id): ?array
{
$statement = $this->pdo()->prepare(

View File

@ -38,6 +38,7 @@ class ServiceCompanyReconciliationRepository
{
$companies = $this->connection->table('svc_service_companies')
->where('company_id', $tenantId)
->where('status', 'active')
->orderBy('service_type_label')
->orderBy('company_name')
->get();
@ -109,6 +110,7 @@ class ServiceCompanyReconciliationRepository
'service_type_code' => (string) $company->service_type_code,
'service_type_label' => (string) $company->service_type_label,
'taxpayer_type' => $company->taxpayer_type,
'business_registration_type' => $company->business_registration_type,
'company_status' => (string) ($company->company_status ?: '正常'),
'planning_target_amount' => $company->planning_target_amount !== null
? (float) $company->planning_target_amount
@ -149,6 +151,94 @@ class ServiceCompanyReconciliationRepository
return $row ? (array) $row : null;
}
/**
* 将公司盘点中“类型包含服务公司”的主体同步为服务公司档案。
*
* 同步只更新公司名称、类型、税务类型、信用代码和公司状态;手工维护的
* 规划量、备注和启停状态保持不变。
*
* @param list<array<string,mixed>> $rows
*/
public function syncCompanyPlanServiceCompanies(int $tenantId, array $rows): int
{
return $this->connection->transaction(function () use ($tenantId, $rows): int {
$seen = [];
$synced = 0;
$syncedAt = now();
foreach ($rows as $row) {
$typeLabel = trim((string) ($row['company_type'] ?? ''));
$companyName = trim((string) ($row['company_name'] ?? ''));
if ($companyName === '' || mb_stripos($typeLabel, '服务公司') === false) {
continue;
}
$creditCode = strtoupper(trim((string) ($row['unified_social_credit_code'] ?? '')));
$companyKey = $this->companyKey($companyName, $creditCode);
$serviceTypeCode = $this->serviceTypeCodeFromLabel($typeLabel);
$seen[$companyKey . '|' . $serviceTypeCode] = true;
$payload = [
'company_key' => $companyKey,
'company_name' => mb_substr($companyName, 0, 200),
'unified_social_credit_code' => $creditCode !== '' ? mb_substr($creditCode, 0, 64) : null,
'service_type_code' => $serviceTypeCode,
'service_type_label' => mb_substr($typeLabel, 0, 64),
'taxpayer_type' => $this->nullableText($row['taxpayer_type'] ?? null, 64),
'business_registration_type' => $this->nullableText(
$row['business_registration_type'] ?? null,
64,
),
'company_status' => $this->nullableText($row['company_status'] ?? null, 32) ?: '正常',
'source' => 'company_plan',
'source_row_id' => isset($row['id']) ? (int) $row['id'] : null,
'source_synced_at' => $syncedAt,
'updated_at' => $syncedAt,
];
$existing = $this->connection->table('svc_service_companies')
->where('company_id', $tenantId)
->where('company_key', $companyKey)
->where('service_type_code', $serviceTypeCode)
->first();
if ($existing) {
$this->connection->table('svc_service_companies')
->where('company_id', $tenantId)
->where('id', $existing->id)
->update($payload);
} else {
$this->connection->table('svc_service_companies')->insert([
...$payload,
'company_id' => $tenantId,
'status' => 'active',
'created_by' => '公司盘点同步',
'created_at' => $syncedAt,
]);
}
$synced++;
}
$imported = $this->connection->table('svc_service_companies')
->where('company_id', $tenantId)
->where('source', 'company_plan')
->get();
foreach ($imported as $company) {
$key = (string) $company->company_key . '|' . (string) $company->service_type_code;
if (! isset($seen[$key]) && (string) $company->status !== 'inactive') {
$this->connection->table('svc_service_companies')
->where('company_id', $tenantId)
->where('id', $company->id)
->update([
'status' => 'inactive',
'source_synced_at' => $syncedAt,
'updated_at' => $syncedAt,
]);
}
}
return $synced;
});
}
/** @return list<array<string,mixed>> */
public function relations(int $tenantId, int $serviceCompanyId): array
{
@ -349,6 +439,10 @@ class ServiceCompanyReconciliationRepository
'service_type_code' => $serviceTypeCode,
'service_type_label' => self::SERVICE_TYPES[$serviceTypeCode],
'taxpayer_type' => $this->nullableText($data['taxpayer_type'] ?? null, 64),
'business_registration_type' => $this->nullableText(
$data['business_registration_type'] ?? null,
64,
),
'company_status' => $this->nullableText($data['company_status'] ?? null, 32) ?: '正常',
'planning_target_amount' => isset($data['planning_target_amount'])
&& $data['planning_target_amount'] !== ''
@ -944,4 +1038,19 @@ class ServiceCompanyReconciliationRepository
return $text === '' ? null : mb_substr($text, 0, $length);
}
private function serviceTypeCodeFromLabel(string $label): string
{
if (mb_stripos($label, '客服') !== false) {
return 'customer_service';
}
if (mb_stripos($label, '仓储') !== false) {
return 'warehouse';
}
if (mb_stripos($label, '运营') !== false) {
return 'operations';
}
return 'other';
}
}

View File

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Business;
use App\Business\CompanyPlan\CompanyPlanRepository;
use App\Business\ServiceCompanyReconciliation\ServiceCompanyReconciliationRepository;
use App\Utilities\FinanceLedgerAccess;
use Carbon\CarbonImmutable;
@ -14,6 +15,7 @@ class ServiceCompanyReconciliation extends Controller
{
public function __construct(
private readonly ServiceCompanyReconciliationRepository $repository,
private readonly CompanyPlanRepository $companyPlanRepository,
) {
$this->middleware('auth');
$this->middleware('company.identify');
@ -23,6 +25,7 @@ class ServiceCompanyReconciliation extends Controller
{
$tenantId = (int) (company_id() ?: 1);
$period = $this->period($request);
$companyPlanSyncError = $this->syncCompanyPlan($tenantId);
$serviceCompanies = $this->repository->serviceCompanies($tenantId, $period);
return view('business.pages.financial-operations.service-company-reconciliation', [
@ -39,6 +42,7 @@ class ServiceCompanyReconciliation extends Controller
'serviceTypes' => ServiceCompanyReconciliationRepository::SERVICE_TYPES,
'baseMetrics' => ServiceCompanyReconciliationRepository::BASE_METRICS,
'companyDirectory' => $this->repository->companyDirectory(),
'companyPlanSyncError' => $companyPlanSyncError,
'canEdit' => FinanceLedgerAccess::canEditMapping(user()),
'summary' => [
'companies' => count($serviceCompanies),
@ -60,6 +64,7 @@ class ServiceCompanyReconciliation extends Controller
public function show(Request $request, int $serviceCompany): View
{
$tenantId = (int) (company_id() ?: 1);
$companyPlanSyncError = $this->syncCompanyPlan($tenantId);
$company = $this->repository->serviceCompany($tenantId, $serviceCompany);
abort_if($company === null, 404);
@ -90,6 +95,7 @@ class ServiceCompanyReconciliation extends Controller
'serviceTypes' => ServiceCompanyReconciliationRepository::SERVICE_TYPES,
'baseMetrics' => ServiceCompanyReconciliationRepository::BASE_METRICS,
'companyDirectory' => $this->repository->companyDirectory(),
'companyPlanSyncError' => $companyPlanSyncError,
'canEdit' => FinanceLedgerAccess::canEditMapping(user()),
'summary' => [
'people' => count($currentPersonKeys),
@ -288,6 +294,20 @@ class ServiceCompanyReconciliation extends Controller
abort_unless(FinanceLedgerAccess::canEditMapping(user()), 403, '当前账号没有维护服务公司对账的权限。');
}
private function syncCompanyPlan(int $tenantId): ?string
{
try {
$rows = $this->companyPlanRepository->serviceCompanyRows($tenantId);
$this->repository->syncCompanyPlanServiceCompanies($tenantId, $rows);
return null;
} catch (\Throwable $exception) {
report($exception);
return '公司盘点服务公司同步暂时失败,当前先显示已登记的服务公司。';
}
}
/** @return array<string,mixed> */
private function validateCompany(Request $request): array
{
@ -298,6 +318,7 @@ class ServiceCompanyReconciliation extends Controller
ServiceCompanyReconciliationRepository::SERVICE_TYPES,
))],
'taxpayer_type' => ['nullable', 'string', 'max:64'],
'business_registration_type' => ['nullable', 'string', 'max:64'],
'company_status' => ['nullable', 'in:正常,注销中,已注销'],
'planning_target_amount' => ['nullable', 'numeric', 'min:0'],
'status' => ['required', 'in:active,inactive'],

View File

@ -0,0 +1,55 @@
<?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('svc_service_companies')) {
return;
}
$schema->table('svc_service_companies', function (Blueprint $table) use ($schema): void {
if (! $schema->hasColumn('svc_service_companies', 'source')) {
$table->string('source', 32)->nullable()->after('company_status');
}
if (! $schema->hasColumn('svc_service_companies', 'source_row_id')) {
$table->unsignedBigInteger('source_row_id')->nullable()->after('source');
}
if (! $schema->hasColumn('svc_service_companies', 'source_synced_at')) {
$table->timestamp('source_synced_at')->nullable()->after('source_row_id');
}
if (! $schema->hasIndex('svc_service_companies', 'svc_service_companies_source_index')) {
$table->index(['company_id', 'source'], 'svc_service_companies_source_index');
}
});
}
public function down(): void
{
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('svc_service_companies')) {
return;
}
$schema->table('svc_service_companies', function (Blueprint $table) use ($schema): void {
if ($schema->hasIndex('svc_service_companies', 'svc_service_companies_source_index')) {
$table->dropIndex('svc_service_companies_source_index');
}
foreach (['source_synced_at', 'source_row_id', 'source'] as $column) {
if ($schema->hasColumn('svc_service_companies', $column)) {
$table->dropColumn($column);
}
}
});
}
};

View File

@ -0,0 +1,39 @@
<?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('svc_service_companies')
|| $schema->hasColumn('svc_service_companies', 'business_registration_type')) {
return;
}
$schema->table('svc_service_companies', function (Blueprint $table): void {
$table->string('business_registration_type', 64)->nullable()->after('taxpayer_type');
});
}
public function down(): void
{
$schema = Schema::connection($this->connection());
if (! $schema->hasTable('svc_service_companies')
|| ! $schema->hasColumn('svc_service_companies', 'business_registration_type')) {
return;
}
$schema->table('svc_service_companies', function (Blueprint $table): void {
$table->dropColumn('business_registration_type');
});
}
};

View File

@ -357,7 +357,9 @@
- 入口:`经营报表 → 服务公司对账`。
- 服务公司总览与独立详情页,点击公司进入详情。
- 服务公司显式登记,不再依赖上游“公司类型”文字自动猜测。
- 服务公司自动读取“公司盘点”中类型包含“服务公司”的主体;人工登记仅用于盘点外例外。
- 公司盘点的名称、类型、税务类型、工商类型、信用代码和状态自动同步;规划量、备注和启停状态不被覆盖。
- 盘点类型改成非服务公司后,自动来源记录转为停用,历史关系和结算保留。
- 店铺公司来自店铺主体生命周期,关系按生效期间保存。
- 同一店铺公司 + 同一服务类型禁止重叠服务公司。
- 关系修改递增版本,并将历史快照保存在 `svc_service_relation_versions`。

View File

@ -275,7 +275,7 @@
.svc-table {
width: 100%;
min-width: 930px;
min-width: 1080px;
border-collapse: collapse;
font-size: 12px;
}
@ -718,12 +718,15 @@
@if ($errors->any())
<div class="svc-error" role="alert">{{ $errors->first() }}</div>
@endif
@if (! empty($companyPlanSyncError))
<div class="svc-error" role="alert">{{ $companyPlanSyncError }}</div>
@endif
@if (! $isDetail)
<div class="svc-page__header">
<div>
<h2>服务公司总览</h2>
<p class="svc-page__subtitle">按服务公司查看人员、店铺公司关系和本月结算。点击公司名称进入详情。</p>
<p class="svc-page__subtitle">服务公司自动来自“公司盘点”中类型包含“服务公司”的主体;点击公司名称进入详情。</p>
</div>
<div class="svc-page__actions">
<form class="svc-page__period" method="GET" action="{{ $currentRoute }}">
@ -769,7 +772,7 @@
<header class="svc-panel__head">
<div>
<h3 id="svc-company-list-title">服务公司列表</h3>
<p>服务公司必须在这里显式登记;不会根据公司名称自动猜测。</p>
<p>来源:公司盘点 → 类型包含“服务公司”。人工补充仅用于公司盘点外的例外。</p>
</div>
</header>
@ -785,6 +788,8 @@
<tr>
<th>服务公司</th>
<th>服务类型</th>
<th>税务类型</th>
<th>工商类型</th>
<th>状态</th>
<th class="is-number">当前人数</th>
<th class="is-number">人员工资快照</th>
@ -805,6 +810,8 @@
</a>
</td>
<td>{{ $company['service_type_label'] }}</td>
<td>{{ $company['taxpayer_type'] ?: '—' }}</td>
<td>{{ $company['business_registration_type'] ?: '—' }}</td>
<td>
<span @class(['svc-badge', 'is-success' => $company['company_status'] === '正常', 'is-warning' => $company['company_status'] === '注销中', 'is-danger' => $company['company_status'] === '已注销'])>
{{ $company['company_status'] }}
@ -850,6 +857,8 @@
</div>
<p class="svc-page__subtitle">
统一社会信用代码:{{ $serviceCompany['unified_social_credit_code'] ?: '未维护' }}
· 税务类型:{{ $serviceCompany['taxpayer_type'] ?: '未维护' }}
· 工商类型:{{ $serviceCompany['business_registration_type'] ?: '未维护' }}
</p>
</div>
<div class="svc-page__actions">
@ -1268,6 +1277,10 @@
<label for="svc-company-taxpayer">税务类型</label>
<input id="svc-company-taxpayer" name="taxpayer_type" maxlength="64" data-company-taxpayer>
</div>
<div class="svc-field">
<label for="svc-company-business-type">工商类型</label>
<input id="svc-company-business-type" name="business_registration_type" maxlength="64" data-company-business-type>
</div>
<div class="svc-field">
<label for="svc-company-status">公司状态</label>
<select id="svc-company-status" name="company_status" data-company-status>
@ -1465,6 +1478,7 @@
companyForm.querySelector('[data-company-code]').value = @json($isDetail ? ($serviceCompany['unified_social_credit_code'] ?? '') : '');
companyForm.querySelector('[data-company-type]').value = @json($isDetail ? $serviceCompany['service_type_code'] : 'customer_service');
companyForm.querySelector('[data-company-taxpayer]').value = @json($isDetail ? ($serviceCompany['taxpayer_type'] ?? '') : '');
companyForm.querySelector('[data-company-business-type]').value = @json($isDetail ? ($serviceCompany['business_registration_type'] ?? '') : '');
companyForm.querySelector('[data-company-status]').value = @json($isDetail ? ($serviceCompany['company_status'] ?: '正常') : '正常');
companyForm.querySelector('[data-company-target]').value = @json($isDetail ? ($serviceCompany['planning_target_amount'] ?? '') : '');
companyForm.querySelector('[data-company-record-status]').value = @json($isDetail ? $serviceCompany['status'] : 'active');

View File

@ -67,7 +67,6 @@ class FinanceLedgerNavigationTest extends FeatureTestCase
->assertSeeText('财务经营报表')
->assertSeeText('服务公司对账')
->assertSeeText('服务公司总览')
->assertSeeText('还没有登记服务公司。')
->assertSee('prototype-tag-link is-active', false);
$this->get(route('business.pages.show', [

View File

@ -2,16 +2,111 @@
namespace Tests\Feature\Business;
use App\Business\CompanyPlan\CompanyPlanRepository;
use App\Business\ServiceCompanyReconciliation\ServiceCompanyReconciliationRepository;
use App\Models\Auth\Permission;
use App\Models\Auth\Role;
use App\Models\Auth\User;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\Feature\FeatureTestCase;
class ServiceCompanyReconciliationTest extends FeatureTestCase
{
private string $companyPlanPath;
protected function setUp(): void
{
parent::setUp();
$this->companyPlanPath = storage_path(
'framework/testing/service-company-plan-' . Str::uuid() . '.sqlite',
);
config(['company_plan.database_path' => $this->companyPlanPath]);
}
protected function tearDown(): void
{
@unlink($this->companyPlanPath);
parent::tearDown();
}
public function test_overview_imports_company_plan_rows_whose_type_contains_service_company(): void
{
$pdo = app(CompanyPlanRepository::class)->pdo();
$insert = $pdo->prepare(<<<'SQL'
INSERT INTO company_plan_rows (
company_id, sequence_no, company_name, company_type, taxpayer_type,
business_registration_type, unified_social_credit_code, company_status, created_at, updated_at
) VALUES (
:company_id, :sequence_no, :company_name, :company_type, :taxpayer_type,
:business_registration_type, :credit_code, :company_status, :created_at, :updated_at
)
SQL);
$now = now()->toDateTimeString();
foreach ([
[1, '上海测试科技有限公司', '科技有限公司', '一般纳税人', '查账征收', '91310000TESTTECH01'],
[2, '常州测试仓储服务有限公司', '仓储服务公司', '小规模纳税人', '查账征收', '91320400TESTWAREHOUSE01'],
[3, '常州测试客服服务有限公司', '客服服务公司', '小规模纳税人', '个人独资企业', '91320400TESTCUSTOMER06'],
[4, '常州测试运营服务有限公司', '运营服务公司', '小规模纳税人', '核定', '91320400TESTOPS01'],
] as [$sequence, $name, $type, $taxType, $businessType, $creditCode]) {
$insert->execute([
':company_id' => $this->company->id,
':sequence_no' => $sequence,
':company_name' => $name,
':company_type' => $type,
':taxpayer_type' => $taxType,
':business_registration_type' => $businessType,
':credit_code' => $creditCode,
':company_status' => '正常',
':created_at' => $now,
':updated_at' => $now,
]);
}
$this->loginAs()
->get(route('business.service-company-reconciliation.index'))
->assertOk()
->assertSeeText('常州测试仓储服务有限公司')
->assertSeeText('常州测试客服服务有限公司')
->assertSeeText('常州测试运营服务有限公司')
->assertSeeText('个人独资企业')
->assertSeeText('核定')
->assertDontSeeText('上海测试科技有限公司');
$types = DB::connection('business_mirror')
->table('svc_service_companies')
->where('status', 'active')
->pluck('service_type_code')
->sort()
->values()
->all();
$this->assertSame(['customer_service', 'operations', 'warehouse'], $types);
$this->assertSame(
3,
DB::connection('business_mirror')
->table('svc_service_companies')
->where('source', 'company_plan')
->count(),
);
$pdo->prepare(
"UPDATE company_plan_rows SET company_type = '科技有限公司' WHERE company_name = ?"
)->execute(['常州测试客服服务有限公司']);
$this->get(route('business.service-company-reconciliation.index'))
->assertOk()
->assertDontSeeText('常州测试客服服务有限公司');
$this->assertSame(
'inactive',
DB::connection('business_mirror')
->table('svc_service_companies')
->where('unified_social_credit_code', '91320400TESTCUSTOMER06')
->value('status'),
);
}
public function test_service_company_and_relation_can_be_configured_from_the_real_page(): void
{
$this->seedStoreMirror();
@ -27,6 +122,7 @@ class ServiceCompanyReconciliationTest extends FeatureTestCase
'unified_social_credit_code' => '91320400TESTCUSTOMER01',
'service_type_code' => 'customer_service',
'taxpayer_type' => '小规模纳税人',
'business_registration_type' => '查账征收',
'company_status' => '正常',
'planning_target_amount' => 3000000,
'status' => 'active',