feat: 落地服务公司对账配置与月度预览 #1085

Merged
DoDo merged 1 commits from feature/dodo-service-company-reconciliation-mvp into main 2026-11-11 16:34:27 +08:00
8 changed files with 3484 additions and 1 deletions

View File

@ -0,0 +1,947 @@
<?php
namespace App\Business\ServiceCompanyReconciliation;
use Carbon\CarbonImmutable;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use RuntimeException;
class ServiceCompanyReconciliationRepository
{
public const SERVICE_TYPES = [
'customer_service' => '客服服务公司',
'operations' => '运营服务公司',
'warehouse' => '仓储服务公司',
'other' => '其他服务公司',
];
public const BASE_METRICS = [
'settlement_income' => '业绩明细收入(不减退款)',
];
private readonly ConnectionInterface $connection;
public function __construct(DatabaseManager $database)
{
$this->connection = $database->connection(
(string) config('upstream_mirrors.connection', 'business_mirror'),
);
}
/** @return list<array<string,mixed>> */
public function serviceCompanies(int $tenantId, string $period): array
{
$companies = $this->connection->table('svc_service_companies')
->where('company_id', $tenantId)
->orderBy('service_type_label')
->orderBy('company_name')
->get();
if ($companies->isEmpty()) {
return [];
}
$serviceCompanyIds = $companies->pluck('id')->map(static fn ($id): int => (int) $id)->all();
$today = CarbonImmutable::today()->toDateString();
$periodStart = CarbonImmutable::createFromFormat('!Y-m', $period)->startOfMonth();
$periodEnd = $periodStart->endOfMonth();
$assignments = $this->connection->table('svc_service_people')
->where('company_id', $tenantId)
->whereIn('service_company_id', $serviceCompanyIds)
->where('status', 'active')
->where('effective_from', '<=', $today)
->where(static fn ($query) => $query
->whereNull('effective_to')
->orWhere('effective_to', '>=', $today))
->get()
->groupBy(static fn ($row): int => (int) $row->service_company_id);
$relations = $this->connection->table('svc_service_relations')
->where('company_id', $tenantId)
->whereIn('service_company_id', $serviceCompanyIds)
->where('status', 'active')
->where('effective_from', '<=', $periodEnd->toDateString())
->where(static fn ($query) => $query
->whereNull('effective_to')
->orWhere('effective_to', '>=', $periodStart->toDateString()))
->get()
->groupBy(static fn ($row): int => (int) $row->service_company_id);
$settlements = $this->connection->table('svc_service_settlements')
->where('company_id', $tenantId)
->where('period', $period)
->whereIn('service_company_id', $serviceCompanyIds)
->get()
->groupBy(static fn ($row): int => (int) $row->service_company_id);
$salaryByPerson = collect($this->availablePeople($tenantId))->keyBy('person_key');
return $companies->map(function ($company) use ($assignments, $relations, $settlements, $salaryByPerson): array {
$serviceCompanyId = (int) $company->id;
$companyAssignments = $assignments->get($serviceCompanyId, collect());
$companyRelations = $relations->get($serviceCompanyId, collect());
$companySettlements = $settlements->get($serviceCompanyId, collect());
$laborCost = $companyAssignments->sum(
static fn ($assignment): float => (float) ($salaryByPerson->get($assignment->person_key)['salary'] ?? 0),
);
$settlementAmount = (float) $companySettlements->sum('service_fee');
$confirmedAmount = (float) $companySettlements
->where('status', 'confirmed')
->sum('service_fee');
$invoiceAmount = (float) $companySettlements->sum('invoice_amount');
$paidAmount = (float) $companySettlements->sum('paid_amount');
$hasOpenInvoice = $companySettlements->contains(
static fn ($row): bool => ! in_array((string) $row->invoice_status, ['invoiced', 'waived'], true),
);
$hasOpenPayment = $companySettlements->contains(
static fn ($row): bool => (string) $row->payment_status !== 'paid',
);
$hasUnconfirmed = $companySettlements->contains(
static fn ($row): bool => (string) $row->status !== 'confirmed',
);
return [
'id' => $serviceCompanyId,
'company_key' => (string) $company->company_key,
'company_name' => (string) $company->company_name,
'unified_social_credit_code' => $company->unified_social_credit_code,
'service_type_code' => (string) $company->service_type_code,
'service_type_label' => (string) $company->service_type_label,
'taxpayer_type' => $company->taxpayer_type,
'company_status' => (string) ($company->company_status ?: '正常'),
'planning_target_amount' => $company->planning_target_amount !== null
? (float) $company->planning_target_amount
: null,
'status' => (string) $company->status,
'people_count' => $companyAssignments->count(),
'labor_cost' => $laborCost,
'relation_count' => $companyRelations->count(),
'base_amount' => (float) $companySettlements->sum('base_amount'),
'settlement_amount' => $settlementAmount,
'confirmed_amount' => $confirmedAmount,
'invoice_amount' => $invoiceAmount,
'paid_amount' => $paidAmount,
'settlement_count' => $companySettlements->count(),
'invoice_label' => $companySettlements->isEmpty()
? '尚未生成'
: ($hasOpenInvoice ? '开票待处理' : '已开票'),
'payment_label' => $companySettlements->isEmpty()
? '尚未生成'
: ($hasOpenPayment ? '到账待确认' : '已到账'),
'reconciliation_status' => $companyRelations->isEmpty()
? '未配置'
: ($companySettlements->isEmpty()
? '待生成'
: ($hasUnconfirmed ? '待确认' : '已确认')),
];
})->all();
}
/** @return array<string,mixed>|null */
public function serviceCompany(int $tenantId, int $serviceCompanyId): ?array
{
$row = $this->connection->table('svc_service_companies')
->where('company_id', $tenantId)
->where('id', $serviceCompanyId)
->first();
return $row ? (array) $row : null;
}
/** @return list<array<string,mixed>> */
public function relations(int $tenantId, int $serviceCompanyId): array
{
return $this->connection->table('svc_service_relations')
->where('company_id', $tenantId)
->where('service_company_id', $serviceCompanyId)
->orderByDesc('effective_from')
->orderByDesc('id')
->get()
->map(static fn ($row): array => (array) $row)
->all();
}
/** @return list<array<string,mixed>> */
public function settlements(int $tenantId, int $serviceCompanyId, string $period): array
{
$settlements = $this->connection->table('svc_service_settlements')
->where('company_id', $tenantId)
->where('service_company_id', $serviceCompanyId)
->where('period', $period)
->orderBy('store_company_name')
->get();
if ($settlements->isEmpty()) {
return [];
}
$details = $this->connection->table('svc_service_settlement_details')
->whereIn('settlement_id', $settlements->pluck('id')->all())
->orderBy('entity_period_from')
->orderBy('erp_store_name')
->get()
->groupBy(static fn ($row): int => (int) $row->settlement_id);
return $settlements->map(static function ($row) use ($details): array {
$data = (array) $row;
$data['details'] = $details->get((int) $row->id, collect())
->map(static fn ($detail): array => (array) $detail)
->values()
->all();
return $data;
})->all();
}
/** @return list<array<string,mixed>> */
public function assignedPeople(int $tenantId, int $serviceCompanyId): array
{
$salaryByPerson = collect($this->availablePeople($tenantId))->keyBy('person_key');
$today = CarbonImmutable::today()->toDateString();
return $this->connection->table('svc_service_people')
->where('company_id', $tenantId)
->where('service_company_id', $serviceCompanyId)
->orderByDesc('effective_from')
->orderByDesc('id')
->get()
->map(static function ($row) use ($salaryByPerson, $today): array {
$data = (array) $row;
$data['salary'] = (float) ($salaryByPerson->get($row->person_key)['salary'] ?? 0);
$data['is_current'] = $row->status === 'active'
&& $row->effective_from <= $today
&& ($row->effective_to === null || $row->effective_to >= $today);
return $data;
})->all();
}
/** @return array<string,array<string,mixed>> */
public function availablePeople(int $tenantId): array
{
$snapshot = DB::table('business_labor_expense_snapshots')
->where('company_id', $tenantId)
->first();
if (! $snapshot) {
return [];
}
$snapshotRows = is_array($snapshot->rows)
? $snapshot->rows
: json_decode((string) $snapshot->rows, true);
if (! is_array($snapshotRows)) {
return [];
}
$people = [];
foreach ($snapshotRows as $row) {
if (! is_array($row)) {
continue;
}
$name = trim((string) ($row['C'] ?? ''));
if ($name === '') {
continue;
}
$alias = trim((string) ($row['B'] ?? ''));
$department = trim((string) ($row['D'] ?? ''));
$position = trim((string) ($row['E'] ?? ''));
$personKey = $this->personKey($name, $alias, $department);
$salaryText = str_replace([',', ',', '¥', '¥'], '', trim((string) ($row['F'] ?? '0')));
$people[$personKey] = [
'person_key' => $personKey,
'employee_name' => $name,
'alias' => $alias,
'department' => $department,
'position' => $position,
'salary' => is_numeric($salaryText) ? (float) $salaryText : 0.0,
];
}
return $people;
}
/** @return list<array<string,mixed>> */
public function storeCompanies(int $tenantId): array
{
$lifecycleGeneration = $this->activeGeneration('store-report.store-lifecycles');
if ($lifecycleGeneration === null) {
return [];
}
$rows = $this->connection->table('store_report_lifecycle_rows')
->where('generation', $lifecycleGeneration)
->whereNotNull('company_name')
->where('company_name', '<>', '')
->select(['company_name', 'unified_social_credit_code'])
->distinct()
->get();
return $rows
->map(function ($row): array {
$name = trim((string) $row->company_name);
$creditCode = trim((string) ($row->unified_social_credit_code ?? ''));
return [
'key' => $this->companyKey($name, $creditCode),
'name' => $name,
'unified_social_credit_code' => $creditCode !== '' ? $creditCode : null,
];
})
->filter(static fn (array $row): bool => $row['name'] !== '')
->unique('key')
->sortBy('name')
->values()
->all();
}
/** @return list<array<string,mixed>> */
public function companyDirectory(): array
{
try {
return $this->connection->table('ops_fys_company_info')
->whereNotNull('businessLicenseName')
->where('businessLicenseName', '<>', '')
->select([
'businessLicenseName AS company_name',
'unifiedSocialCreditCode AS unified_social_credit_code',
'businessLicenseType AS company_type',
'taxCategoryAndType AS taxpayer_type',
'companyStatus AS company_status',
])
->orderBy('businessLicenseName')
->get()
->map(static fn ($row): array => (array) $row)
->unique(static fn (array $row): string => self::companyKey(
(string) $row['company_name'],
(string) ($row['unified_social_credit_code'] ?? ''),
))
->values()
->all();
} catch (\Throwable) {
return [];
}
}
/**
* @param array<string,mixed> $data
* @return array<string,mixed>
*/
public function saveServiceCompany(int $tenantId, array $data, string $actor, ?int $id = null): array
{
$serviceTypeCode = (string) ($data['service_type_code'] ?? '');
if (! isset(self::SERVICE_TYPES[$serviceTypeCode])) {
throw ValidationException::withMessages(['service_type_code' => '服务类型无效。']);
}
$companyName = trim((string) ($data['company_name'] ?? ''));
$creditCode = strtoupper(trim((string) ($data['unified_social_credit_code'] ?? '')));
if ($companyName === '') {
throw ValidationException::withMessages(['company_name' => '请填写服务公司名称。']);
}
$companyKey = $this->companyKey($companyName, $creditCode);
$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' => self::SERVICE_TYPES[$serviceTypeCode],
'taxpayer_type' => $this->nullableText($data['taxpayer_type'] ?? null, 64),
'company_status' => $this->nullableText($data['company_status'] ?? null, 32) ?: '正常',
'planning_target_amount' => isset($data['planning_target_amount'])
&& $data['planning_target_amount'] !== ''
? (float) $data['planning_target_amount']
: null,
'status' => in_array($data['status'] ?? 'active', ['active', 'inactive'], true)
? $data['status']
: 'active',
'notes' => $this->nullableText($data['notes'] ?? null, 500),
'updated_by' => $actor,
];
return $this->connection->transaction(function () use ($tenantId, $id, $payload, $actor): array {
if ($id !== null) {
$existing = $this->serviceCompany($tenantId, $id);
if ($existing === null) {
throw ValidationException::withMessages(['company_name' => '服务公司不存在。']);
}
$duplicate = $this->connection->table('svc_service_companies')
->where('company_id', $tenantId)
->where('company_key', $payload['company_key'])
->where('service_type_code', $payload['service_type_code'])
->where('id', '<>', $id)
->exists();
if ($duplicate) {
throw ValidationException::withMessages(['company_name' => '该公司的服务类型已经登记。']);
}
$payload['updated_at'] = now();
$this->connection->table('svc_service_companies')
->where('company_id', $tenantId)
->where('id', $id)
->update($payload);
return $this->serviceCompany($tenantId, $id) ?? [];
}
$payload['company_id'] = $tenantId;
$payload['created_by'] = $actor;
$payload['created_at'] = now();
$payload['updated_at'] = now();
$newId = (int) $this->connection->table('svc_service_companies')->insertGetId($payload);
return $this->serviceCompany($tenantId, $newId) ?? [];
});
}
/**
* @param array<string,mixed> $data
* @return array<string,mixed>
*/
public function saveRelation(
int $tenantId,
int $serviceCompanyId,
array $data,
string $actor,
?int $relationId = null,
): array {
$company = $this->serviceCompany($tenantId, $serviceCompanyId);
if ($company === null) {
throw ValidationException::withMessages(['store_company_key' => '服务公司不存在。']);
}
$storeCompany = collect($this->storeCompanies($tenantId))
->firstWhere('key', (string) ($data['store_company_key'] ?? ''));
if (! $storeCompany) {
throw ValidationException::withMessages(['store_company_key' => '请选择有效的店铺公司。']);
}
$effectiveFrom = trim((string) ($data['effective_from'] ?? ''));
$effectiveTo = trim((string) ($data['effective_to'] ?? ''));
if ($effectiveFrom === '') {
throw ValidationException::withMessages(['effective_from' => '请选择生效日期。']);
}
$feeRatePercent = (float) ($data['fee_rate_percent'] ?? 1.5);
if ($feeRatePercent < 0 || $feeRatePercent > 100) {
throw ValidationException::withMessages(['fee_rate_percent' => '结算比例必须在 0% 到 100% 之间。']);
}
$payload = [
'service_company_key' => (string) $company['company_key'],
'service_company_name' => (string) $company['company_name'],
'store_company_key' => $storeCompany['key'],
'store_company_name' => $storeCompany['name'],
'store_company_credit_code' => $storeCompany['unified_social_credit_code'],
'service_type_code' => (string) $company['service_type_code'],
'base_metric' => array_key_exists((string) ($data['base_metric'] ?? ''), self::BASE_METRICS)
? (string) $data['base_metric']
: 'settlement_income',
'fee_rate' => round($feeRatePercent / 100, 6),
'effective_from' => $effectiveFrom,
'effective_to' => $effectiveTo !== '' ? $effectiveTo : null,
'contract_no' => $this->nullableText($data['contract_no'] ?? null, 64),
'contract_status' => in_array($data['contract_status'] ?? 'pending', ['pending', 'stamped', 'waived'], true)
? $data['contract_status']
: 'pending',
'status' => in_array($data['status'] ?? 'active', ['active', 'inactive'], true)
? $data['status']
: 'active',
'notes' => $this->nullableText($data['notes'] ?? null, 500),
'updated_by' => $actor,
];
return $this->connection->transaction(function () use (
$tenantId,
$serviceCompanyId,
$relationId,
$payload,
$actor,
): array {
if ($payload['status'] === 'active' && $this->relationOverlaps($tenantId, $payload, $relationId)) {
throw ValidationException::withMessages([
'effective_from' => '同一店铺公司和服务类型在生效期间内已存在服务公司,不能重叠。',
]);
}
if ($relationId !== null) {
$existing = $this->connection->table('svc_service_relations')
->where('company_id', $tenantId)
->where('service_company_id', $serviceCompanyId)
->where('id', $relationId)
->first();
if (! $existing) {
throw ValidationException::withMessages(['effective_from' => '结算关系不存在。']);
}
$payload['rule_version'] = (int) $existing->rule_version + 1;
$payload['updated_at'] = now();
$this->connection->table('svc_service_relations')
->where('company_id', $tenantId)
->where('service_company_id', $serviceCompanyId)
->where('id', $relationId)
->update($payload);
$this->recordRelationVersion($tenantId, $relationId, (array) $existing, $actor);
$updated = (array) $this->connection->table('svc_service_relations')->find($relationId);
$this->recordRelationVersion($tenantId, $relationId, $updated, $actor);
return $updated;
}
$payload['company_id'] = $tenantId;
$payload['service_company_id'] = $serviceCompanyId;
$payload['rule_version'] = 1;
$payload['created_by'] = $actor;
$payload['created_at'] = now();
$payload['updated_at'] = now();
$newId = (int) $this->connection->table('svc_service_relations')->insertGetId($payload);
$created = (array) $this->connection->table('svc_service_relations')->find($newId);
$this->recordRelationVersion($tenantId, $newId, $created, $actor);
return $created;
});
}
public function assignPerson(
int $tenantId,
int $serviceCompanyId,
string $personKey,
string $effectiveFrom,
string $actor,
): array {
if ($this->serviceCompany($tenantId, $serviceCompanyId) === null) {
throw ValidationException::withMessages(['person_key' => '服务公司不存在。']);
}
$person = $this->availablePeople($tenantId)[$personKey] ?? null;
if (! $person) {
throw ValidationException::withMessages(['person_key' => '请选择有效人员。']);
}
return $this->connection->transaction(function () use (
$tenantId,
$serviceCompanyId,
$personKey,
$person,
$effectiveFrom,
$actor,
): array {
$overlap = $this->connection->table('svc_service_people')
->where('company_id', $tenantId)
->where('person_key', $personKey)
->where('status', 'active')
->where('effective_from', '<=', '9999-12-31')
->where(static fn ($query) => $query
->whereNull('effective_to')
->orWhere('effective_to', '>=', $effectiveFrom))
->exists();
if ($overlap) {
throw ValidationException::withMessages([
'person_key' => '该人员在此日期已有有效服务公司归属。',
]);
}
$payload = [
'company_id' => $tenantId,
'service_company_id' => $serviceCompanyId,
'person_key' => $personKey,
'employee_name' => $person['employee_name'],
'alias' => $person['alias'] ?: null,
'department' => $person['department'] ?: null,
'position' => $person['position'] ?: null,
'effective_from' => $effectiveFrom,
'effective_to' => null,
'status' => 'active',
'source' => 'labor_snapshot',
'created_at' => now(),
'updated_at' => now(),
];
$newId = (int) $this->connection->table('svc_service_people')->insertGetId($payload);
return (array) $this->connection->table('svc_service_people')->find($newId);
});
}
public function endPersonAssignment(
int $tenantId,
int $serviceCompanyId,
int $assignmentId,
string $effectiveTo,
): void {
$updated = $this->connection->table('svc_service_people')
->where('company_id', $tenantId)
->where('service_company_id', $serviceCompanyId)
->where('id', $assignmentId)
->update([
'effective_to' => $effectiveTo,
'status' => $effectiveTo <= CarbonImmutable::today()->toDateString() ? 'inactive' : 'active',
'updated_at' => now(),
]);
if ($updated !== 1) {
throw ValidationException::withMessages(['assignment' => '人员归属记录不存在。']);
}
}
/**
* @return array{generated:int,errors:list<string>,source_generation:string}
*/
public function generateSettlements(
int $tenantId,
int $serviceCompanyId,
string $period,
string $actor,
): array {
$relations = $this->connection->table('svc_service_relations')
->where('company_id', $tenantId)
->where('service_company_id', $serviceCompanyId)
->where('status', 'active')
->orderBy('id')
->get();
if ($relations->isEmpty()) {
throw ValidationException::withMessages(['period' => '请先配置至少一条店铺公司结算关系。']);
}
$paidGeneration = $this->activeGeneration('store-report.paid-sales');
$lifecycleGeneration = $this->activeGeneration('store-report.store-lifecycles');
if ($paidGeneration === null || $lifecycleGeneration === null) {
throw ValidationException::withMessages(['period' => '业绩明细或店铺主体期间尚未完成同步。']);
}
$periodStart = CarbonImmutable::createFromFormat('!Y-m', $period)->startOfMonth();
$periodEnd = $periodStart->addMonth();
$baseRows = $this->baseRowsByStoreCompany(
$paidGeneration,
$lifecycleGeneration,
$periodStart,
$periodEnd,
);
$sourceGeneration = mb_substr(
'paid:' . $paidGeneration . '|life:' . $lifecycleGeneration,
0,
191,
);
return $this->connection->transaction(function () use (
$tenantId,
$serviceCompanyId,
$period,
$periodStart,
$periodEnd,
$relations,
$baseRows,
$sourceGeneration,
$actor,
): array {
$generated = 0;
$errors = [];
foreach ($relations as $relation) {
$relationEnd = $relation->effective_to ?: '2999-12-31';
if ($relation->effective_from > $periodStart->toDateString()
|| $relationEnd < $periodEnd->subDay()->toDateString()) {
$errors[] = $relation->store_company_name . ':结算关系未覆盖整个月份。';
continue;
}
if ((string) $relation->base_metric !== 'settlement_income') {
$errors[] = $relation->store_company_name . ':当前尚不支持该收入口径。';
continue;
}
$unique = [
'company_id' => $tenantId,
'period' => $period,
'service_company_id' => $serviceCompanyId,
'store_company_key' => $relation->store_company_key,
'service_type_code' => $relation->service_type_code,
];
$existing = $this->connection->table('svc_service_settlements')
->where($unique)
->first();
if ($existing && (string) $existing->status === 'confirmed') {
$errors[] = $relation->store_company_name . ':已确认结算不可覆盖。';
continue;
}
$rows = collect($baseRows[$relation->store_company_key] ?? []);
$baseAmount = round((float) $rows->sum('base_amount'), 4);
$serviceFee = round((float) $rows->sum('base_amount') * (float) $relation->fee_rate, 2);
$payload = [
...$unique,
'relation_id' => (int) $relation->id,
'store_company_name' => (string) $relation->store_company_name,
'rule_version' => (int) $relation->rule_version,
'base_metric' => (string) $relation->base_metric,
'base_amount' => $baseAmount,
'fee_rate' => (float) $relation->fee_rate,
'service_fee' => $serviceFee,
'invoice_status' => 'pending',
'invoice_amount' => 0,
'payment_status' => 'pending',
'paid_amount' => 0,
'status' => 'draft',
'source_generation' => $sourceGeneration,
'generated_by' => $actor,
'generated_at' => now(),
'confirmed_by' => null,
'confirmed_at' => null,
'updated_at' => now(),
];
if ($existing) {
$settlementId = (int) $existing->id;
$this->connection->table('svc_service_settlements')
->where('id', $settlementId)
->update($payload);
} else {
$payload['created_at'] = now();
$settlementId = (int) $this->connection->table('svc_service_settlements')->insertGetId($payload);
}
$this->connection->table('svc_service_settlement_details')
->where('settlement_id', $settlementId)
->delete();
foreach ($rows as $row) {
$this->connection->table('svc_service_settlement_details')->insert([
'settlement_id' => $settlementId,
'erp_store_name' => $row['erp_store_name'],
'entity_period_from' => $row['entity_period_from'],
'entity_period_to' => $row['entity_period_to'],
'base_amount' => $row['base_amount'],
'service_fee' => round((float) $row['base_amount'] * (float) $relation->fee_rate, 2),
'source_generation' => $sourceGeneration,
'created_at' => now(),
'updated_at' => now(),
]);
}
$generated++;
}
return [
'generated' => $generated,
'errors' => $errors,
'source_generation' => $sourceGeneration,
];
});
}
/** @param array<string,mixed> $data */
public function updateSettlement(
int $tenantId,
int $serviceCompanyId,
int $settlementId,
array $data,
string $actor,
): void {
$settlement = $this->connection->table('svc_service_settlements')
->where('company_id', $tenantId)
->where('service_company_id', $serviceCompanyId)
->where('id', $settlementId)
->first();
if (! $settlement) {
throw ValidationException::withMessages(['settlement' => '结算记录不存在。']);
}
$payload = [
'invoice_status' => in_array($data['invoice_status'] ?? $settlement->invoice_status, [
'pending', 'partial', 'invoiced', 'waived',
], true) ? $data['invoice_status'] : $settlement->invoice_status,
'invoice_amount' => max(0, (float) ($data['invoice_amount'] ?? $settlement->invoice_amount)),
'payment_status' => in_array($data['payment_status'] ?? $settlement->payment_status, [
'pending', 'partial', 'paid',
], true) ? $data['payment_status'] : $settlement->payment_status,
'paid_amount' => max(0, (float) ($data['paid_amount'] ?? $settlement->paid_amount)),
'notes' => $this->nullableText($data['notes'] ?? $settlement->notes, 1000),
'updated_at' => now(),
];
$serviceFee = (float) $settlement->service_fee;
if ((float) $payload['invoice_amount'] > $serviceFee
|| (float) $payload['paid_amount'] > $serviceFee) {
throw ValidationException::withMessages([
'invoice_amount' => '开票金额和到账金额不能超过当前结算金额。',
]);
}
if (($data['action'] ?? '') === 'confirm') {
if ((string) $settlement->status === 'confirmed') {
return;
}
$payload['status'] = 'confirmed';
$payload['confirmed_by'] = $actor;
$payload['confirmed_at'] = now();
}
$this->connection->table('svc_service_settlements')
->where('company_id', $tenantId)
->where('service_company_id', $serviceCompanyId)
->where('id', $settlementId)
->update($payload);
}
public static function companyKey(string $companyName, ?string $creditCode = null): string
{
$creditCode = strtoupper((string) preg_replace('/\s+/u', '', trim((string) $creditCode)));
if ($creditCode !== '') {
return 'code:' . $creditCode;
}
$normalized = mb_strtolower((string) preg_replace('/\s+/u', '', trim($companyName)));
return 'name:' . $normalized;
}
public static function personKey(string $name, string $alias = '', string $department = ''): string
{
$normalized = mb_strtolower(trim($name))
. '|' . mb_strtolower(trim($alias))
. '|' . mb_strtolower(trim($department));
return 'labor:' . hash('sha256', $normalized);
}
/** @return array<string,list<array<string,mixed>>> */
private function baseRowsByStoreCompany(
string $paidGeneration,
string $lifecycleGeneration,
CarbonImmutable $periodStart,
CarbonImmutable $periodEnd,
): array {
$periodEndDate = $periodEnd->subDay()->toDateString();
$prefix = $this->connection->getTablePrefix();
$salesAlias = $prefix . 'sales';
$lifecycleAlias = $prefix . 'lifecycle';
$rows = $this->connection->table('store_report_paid_sales_rows AS sales')
->join('store_report_lifecycle_rows AS lifecycle', function (JoinClause $join) use (
$salesAlias,
$lifecycleAlias,
): void {
$join->on('lifecycle.erp_store_name', '=', 'sales.store_name')
->whereRaw(
"DATE({$lifecycleAlias}.effective_at) <= DATE({$salesAlias}.occurred_on)",
)
->whereRaw(
"({$lifecycleAlias}.expires_at IS NULL "
. "OR DATE({$lifecycleAlias}.expires_at) >= DATE({$salesAlias}.occurred_on))",
);
})
->where('sales.generation', $paidGeneration)
->where('lifecycle.generation', $lifecycleGeneration)
->where('sales.occurred_on', '>=', $periodStart->toDateString())
->where('sales.occurred_on', '<', $periodEnd->toDateString())
->whereNotNull('lifecycle.company_name')
->where('lifecycle.company_name', '<>', '')
->select([
'lifecycle.company_name',
'lifecycle.unified_social_credit_code',
'sales.store_name',
$this->connection->raw(
"MIN(DATE({$lifecycleAlias}.effective_at)) AS entity_period_from",
),
$this->connection->raw(
"MAX(COALESCE(DATE({$lifecycleAlias}.expires_at), '{$periodEndDate}')) "
. 'AS entity_period_to',
),
$this->connection->raw("SUM({$salesAlias}.settlement_income) AS base_amount"),
])
->groupBy(
'lifecycle.company_name',
'lifecycle.unified_social_credit_code',
'sales.store_name',
)
->orderBy('lifecycle.company_name')
->orderBy('sales.store_name')
->get();
$grouped = [];
foreach ($rows as $row) {
$key = self::companyKey(
(string) $row->company_name,
(string) ($row->unified_social_credit_code ?? ''),
);
$grouped[$key][] = [
'company_name' => (string) $row->company_name,
'unified_social_credit_code' => $row->unified_social_credit_code,
'erp_store_name' => (string) $row->store_name,
'entity_period_from' => $row->entity_period_from,
'entity_period_to' => $row->entity_period_to,
'base_amount' => (float) $row->base_amount,
];
}
return $grouped;
}
private function relationOverlaps(int $tenantId, array $payload, ?int $ignoreId): bool
{
$query = $this->connection->table('svc_service_relations')
->where('company_id', $tenantId)
->where('store_company_key', $payload['store_company_key'])
->where('service_type_code', $payload['service_type_code'])
->where('status', 'active')
->where('effective_from', '<=', $payload['effective_to'] ?: '2999-12-31')
->where(static fn ($builder) => $builder
->whereNull('effective_to')
->orWhere('effective_to', '>=', $payload['effective_from']));
if ($ignoreId !== null) {
$query->where('id', '<>', $ignoreId);
}
return $query->lockForUpdate()->exists();
}
private function activeGeneration(string $datasetKey): ?string
{
$state = $this->connection->table('store_report_import_states')
->where('dataset_key', $datasetKey)
->first();
$generation = trim((string) ($state->active_generation ?? ''));
return $generation !== '' ? $generation : null;
}
/** @param array<string,mixed> $relation */
private function recordRelationVersion(
int $tenantId,
int $relationId,
array $relation,
string $actor,
): void {
$version = (int) ($relation['rule_version'] ?? 0);
if ($version < 1
|| $this->connection->table('svc_service_relation_versions')
->where('relation_id', $relationId)
->where('rule_version', $version)
->exists()) {
return;
}
$this->connection->table('svc_service_relation_versions')->insert([
'company_id' => $tenantId,
'relation_id' => $relationId,
'service_company_id' => (int) ($relation['service_company_id'] ?? 0),
'store_company_key' => (string) ($relation['store_company_key'] ?? ''),
'store_company_name' => (string) ($relation['store_company_name'] ?? ''),
'service_type_code' => (string) ($relation['service_type_code'] ?? ''),
'base_metric' => (string) ($relation['base_metric'] ?? 'settlement_income'),
'fee_rate' => (float) ($relation['fee_rate'] ?? 0),
'effective_from' => (string) ($relation['effective_from'] ?? ''),
'effective_to' => $relation['effective_to'] ?? null,
'contract_no' => $relation['contract_no'] ?? null,
'contract_status' => (string) ($relation['contract_status'] ?? 'pending'),
'status' => (string) ($relation['status'] ?? 'active'),
'rule_version' => $version,
'notes' => $relation['notes'] ?? null,
'changed_by' => $actor,
'created_at' => now(),
]);
}
private function nullableText(mixed $value, int $length): ?string
{
$text = trim((string) ($value ?? ''));
return $text === '' ? null : mb_substr($text, 0, $length);
}
}

View File

@ -0,0 +1,325 @@
<?php
namespace App\Http\Controllers\Business;
use App\Business\ServiceCompanyReconciliation\ServiceCompanyReconciliationRepository;
use App\Utilities\FinanceLedgerAccess;
use Carbon\CarbonImmutable;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\View\View;
class ServiceCompanyReconciliation extends Controller
{
public function __construct(
private readonly ServiceCompanyReconciliationRepository $repository,
) {
$this->middleware('auth');
$this->middleware('company.identify');
}
public function index(Request $request): View
{
$tenantId = (int) (company_id() ?: 1);
$period = $this->period($request);
$serviceCompanies = $this->repository->serviceCompanies($tenantId, $period);
return view('business.pages.financial-operations.service-company-reconciliation', [
'isDetail' => false,
'period' => $period,
'periodOptions' => $this->periodOptions(),
'serviceCompanies' => $serviceCompanies,
'serviceCompany' => null,
'relations' => [],
'settlements' => [],
'assignedPeople' => [],
'availablePeople' => [],
'storeCompanies' => [],
'serviceTypes' => ServiceCompanyReconciliationRepository::SERVICE_TYPES,
'baseMetrics' => ServiceCompanyReconciliationRepository::BASE_METRICS,
'companyDirectory' => $this->repository->companyDirectory(),
'canEdit' => FinanceLedgerAccess::canEditMapping(user()),
'summary' => [
'companies' => count($serviceCompanies),
'people' => array_sum(array_column($serviceCompanies, 'people_count')),
'labor_cost' => array_sum(array_column($serviceCompanies, 'labor_cost')),
'settlement_amount' => array_sum(array_column($serviceCompanies, 'settlement_amount')),
'pending' => count(array_filter(
$serviceCompanies,
static fn (array $row): bool => in_array(
$row['reconciliation_status'],
['待生成', '待确认', '未配置'],
true,
),
)),
],
]);
}
public function show(Request $request, int $serviceCompany): View
{
$tenantId = (int) (company_id() ?: 1);
$company = $this->repository->serviceCompany($tenantId, $serviceCompany);
abort_if($company === null, 404);
$period = $this->period($request);
$relations = $this->repository->relations($tenantId, $serviceCompany);
$settlements = $this->repository->settlements($tenantId, $serviceCompany, $period);
$assignedPeople = $this->repository->assignedPeople($tenantId, $serviceCompany);
$availablePeople = array_values($this->repository->availablePeople($tenantId));
$periodStart = CarbonImmutable::createFromFormat('!Y-m', $period)->startOfMonth();
$periodEnd = $periodStart->endOfMonth();
$currentPersonKeys = array_column(
array_filter($assignedPeople, static fn (array $row): bool => $row['is_current']),
'person_key',
);
return view('business.pages.financial-operations.service-company-reconciliation', [
'isDetail' => true,
'period' => $period,
'periodOptions' => $this->periodOptions(),
'serviceCompanies' => [],
'serviceCompany' => $company,
'relations' => $relations,
'settlements' => $settlements,
'assignedPeople' => $assignedPeople,
'availablePeople' => $availablePeople,
'currentPersonKeys' => array_flip($currentPersonKeys),
'storeCompanies' => $this->repository->storeCompanies($tenantId),
'serviceTypes' => ServiceCompanyReconciliationRepository::SERVICE_TYPES,
'baseMetrics' => ServiceCompanyReconciliationRepository::BASE_METRICS,
'companyDirectory' => $this->repository->companyDirectory(),
'canEdit' => FinanceLedgerAccess::canEditMapping(user()),
'summary' => [
'people' => count($currentPersonKeys),
'labor_cost' => array_sum(array_column(
array_filter($assignedPeople, static fn (array $row): bool => $row['is_current']),
'salary',
)),
'stores' => count(array_filter(
$relations,
static fn (array $row): bool => $row['status'] === 'active'
&& $row['effective_from'] <= $periodEnd->toDateString()
&& ($row['effective_to'] === null
|| $row['effective_to'] >= $periodStart->toDateString()),
)),
'settlement_amount' => array_sum(array_column($settlements, 'service_fee')),
],
]);
}
public function storeCompany(Request $request): RedirectResponse
{
$this->authorizeEdit();
$validated = $this->validateCompany($request);
$company = $this->repository->saveServiceCompany(
(int) (company_id() ?: 1),
$validated,
(string) user()->name,
);
return redirect()
->route('business.service-company-reconciliation.show', [
'serviceCompany' => $company['id'],
])
->with('success', '服务公司已登记。');
}
public function updateCompany(Request $request, int $serviceCompany): RedirectResponse
{
$this->authorizeEdit();
$validated = $this->validateCompany($request);
$this->repository->saveServiceCompany(
(int) (company_id() ?: 1),
$validated,
(string) user()->name,
$serviceCompany,
);
return back()->with('success', '服务公司信息已更新。');
}
public function storeRelation(Request $request, int $serviceCompany): RedirectResponse
{
$this->authorizeEdit();
$validated = $this->validateRelation($request);
$this->repository->saveRelation(
(int) (company_id() ?: 1),
$serviceCompany,
$validated,
(string) user()->name,
);
return back()->with('success', '店铺公司结算关系已保存。');
}
public function updateRelation(
Request $request,
int $serviceCompany,
int $relation,
): RedirectResponse {
$this->authorizeEdit();
$validated = $this->validateRelation($request);
$this->repository->saveRelation(
(int) (company_id() ?: 1),
$serviceCompany,
$validated,
(string) user()->name,
$relation,
);
return back()->with('success', '店铺公司结算关系已更新并生成新版本。');
}
public function assignPerson(Request $request, int $serviceCompany): RedirectResponse
{
$this->authorizeEdit();
$validated = $request->validate([
'person_key' => ['required', 'string', 'max:191'],
'effective_from' => ['required', 'date_format:Y-m-d'],
]);
$this->repository->assignPerson(
(int) (company_id() ?: 1),
$serviceCompany,
$validated['person_key'],
$validated['effective_from'],
(string) user()->name,
);
return back()->with('success', '人员归属已保存。');
}
public function endPerson(Request $request, int $serviceCompany, int $assignment): RedirectResponse
{
$this->authorizeEdit();
$validated = $request->validate([
'effective_to' => ['required', 'date_format:Y-m-d'],
]);
$this->repository->endPersonAssignment(
(int) (company_id() ?: 1),
$serviceCompany,
$assignment,
$validated['effective_to'],
);
return back()->with('success', '人员归属已结束。');
}
public function generateSettlements(Request $request, int $serviceCompany): RedirectResponse
{
$this->authorizeEdit();
$validated = $request->validate([
'period' => ['required', 'date_format:Y-m'],
]);
$result = $this->repository->generateSettlements(
(int) (company_id() ?: 1),
$serviceCompany,
$validated['period'],
(string) user()->name,
);
$message = "已生成 {$result['generated']} 条月度对账预览。";
if ($result['errors'] !== []) {
$message .= ' 未生成:' . implode(';', array_slice($result['errors'], 0, 5));
}
return redirect()
->route('business.service-company-reconciliation.show', [
'serviceCompany' => $serviceCompany,
'period' => $validated['period'],
'tab' => 'reconciliation',
])
->with($result['generated'] > 0 ? 'success' : 'error', $message);
}
public function updateSettlement(
Request $request,
int $serviceCompany,
int $settlement,
): RedirectResponse {
$this->authorizeEdit();
$validated = $request->validate([
'action' => ['nullable', 'in:confirm,save'],
'invoice_status' => ['nullable', 'in:pending,partial,invoiced,waived'],
'invoice_amount' => ['nullable', 'numeric', 'min:0'],
'payment_status' => ['nullable', 'in:pending,partial,paid'],
'paid_amount' => ['nullable', 'numeric', 'min:0'],
'notes' => ['nullable', 'string', 'max:1000'],
]);
$this->repository->updateSettlement(
(int) (company_id() ?: 1),
$serviceCompany,
$settlement,
$validated,
(string) user()->name,
);
return back()->with('success', '开票与到账状态已更新。');
}
private function period(Request $request): string
{
$period = trim((string) $request->query('period', ''));
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1) {
return $period;
}
return CarbonImmutable::now()->subMonthNoOverflow()->format('Y-m');
}
/** @return list<array{value:string,label:string}> */
private function periodOptions(): array
{
$current = CarbonImmutable::now()->startOfMonth();
return collect(range(0, 11))->map(static function (int $monthsAgo) use ($current): array {
$month = $current->subMonthsNoOverflow($monthsAgo);
return [
'value' => $month->format('Y-m'),
'label' => $month->format('Y年n月'),
];
})->all();
}
private function authorizeEdit(): void
{
abort_unless(FinanceLedgerAccess::canEditMapping(user()), 403, '当前账号没有维护服务公司对账的权限。');
}
/** @return array<string,mixed> */
private function validateCompany(Request $request): array
{
return $request->validate([
'company_name' => ['required', 'string', 'max:200'],
'unified_social_credit_code' => ['nullable', 'string', 'max:64'],
'service_type_code' => ['required', 'in:' . implode(',', array_keys(
ServiceCompanyReconciliationRepository::SERVICE_TYPES,
))],
'taxpayer_type' => ['nullable', 'string', 'max:64'],
'company_status' => ['nullable', 'in:正常,注销中,已注销'],
'planning_target_amount' => ['nullable', 'numeric', 'min:0'],
'status' => ['required', 'in:active,inactive'],
'notes' => ['nullable', 'string', 'max:500'],
]);
}
/** @return array<string,mixed> */
private function validateRelation(Request $request): array
{
return $request->validate([
'store_company_key' => ['required', 'string', 'max:191'],
'base_metric' => ['required', 'in:' . implode(',', array_keys(
ServiceCompanyReconciliationRepository::BASE_METRICS,
))],
'fee_rate_percent' => ['required', 'numeric', 'min:0', 'max:100'],
'effective_from' => ['required', 'date_format:Y-m-d'],
'effective_to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:effective_from'],
'contract_no' => ['nullable', 'string', 'max:64'],
'contract_status' => ['required', 'in:pending,stamped,waived'],
'status' => ['required', 'in:active,inactive'],
'notes' => ['nullable', 'string', 'max:500'],
]);
}
}

View File

@ -0,0 +1,244 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* 服务公司对账:系统维护的服务公司、店铺公司关系、人员归属和月度结算。
*
* 这些是财务系统自己的业务配置与派生数据,不是上游镜像,统一落在
* caiwu_business_mirror;上游数据库保持只读。
*/
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->create('svc_service_companies', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedInteger('company_id');
$table->string('company_key', 191);
$table->string('company_name', 200);
$table->string('unified_social_credit_code', 64)->nullable();
$table->string('service_type_code', 32)->default('customer_service');
$table->string('service_type_label', 64);
$table->string('taxpayer_type', 64)->nullable();
$table->string('company_status', 32)->nullable();
$table->decimal('planning_target_amount', 18, 2)->nullable();
$table->string('status', 20)->default('active');
$table->text('notes')->nullable();
$table->string('created_by', 100)->nullable();
$table->string('updated_by', 100)->nullable();
$table->timestamps();
$table->unique(
['company_id', 'company_key', 'service_type_code'],
'svc_service_companies_key_type_unique',
);
$table->index(['company_id', 'status'], 'svc_service_companies_tenant_status_index');
$table->index(['company_id', 'service_type_code'], 'svc_service_companies_tenant_type_index');
});
}
if (! $schema->hasTable('svc_service_relations')) {
$schema->create('svc_service_relations', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedInteger('company_id');
$table->unsignedBigInteger('service_company_id');
$table->string('service_company_key', 191);
$table->string('service_company_name', 200);
$table->string('store_company_key', 191);
$table->string('store_company_name', 200);
$table->string('store_company_credit_code', 64)->nullable();
$table->string('service_type_code', 32);
$table->string('base_metric', 32)->default('settlement_income');
$table->decimal('fee_rate', 9, 6)->default(0.015000);
$table->date('effective_from');
$table->date('effective_to')->nullable();
$table->string('contract_no', 64)->nullable();
$table->string('contract_status', 20)->default('pending');
$table->string('status', 20)->default('active');
$table->unsignedInteger('rule_version')->default(1);
$table->text('notes')->nullable();
$table->string('created_by', 100)->nullable();
$table->string('updated_by', 100)->nullable();
$table->timestamps();
$table->unique(
[
'company_id',
'service_company_id',
'store_company_key',
'service_type_code',
'effective_from',
],
'svc_service_relations_version_unique',
);
$table->index(
['company_id', 'service_company_id', 'status'],
'svc_service_relations_company_status_index',
);
$table->index(
['company_id', 'store_company_key', 'service_type_code', 'effective_from'],
'svc_service_relations_store_type_time_index',
);
});
}
if (! $schema->hasTable('svc_service_people')) {
$schema->create('svc_service_people', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedInteger('company_id');
$table->unsignedBigInteger('service_company_id');
$table->string('person_key', 191);
$table->string('employee_name', 100);
$table->string('alias', 100)->nullable();
$table->string('department', 100)->nullable();
$table->string('position', 100)->nullable();
$table->date('effective_from');
$table->date('effective_to')->nullable();
$table->string('status', 20)->default('active');
$table->string('source', 32)->default('labor_snapshot');
$table->timestamps();
$table->unique(
['company_id', 'service_company_id', 'person_key', 'effective_from'],
'svc_service_people_assignment_unique',
);
$table->index(
['company_id', 'service_company_id', 'status'],
'svc_service_people_company_status_index',
);
$table->index(
['company_id', 'person_key', 'effective_from'],
'svc_service_people_person_time_index',
);
});
}
if (! $schema->hasTable('svc_service_relation_versions')) {
$schema->create('svc_service_relation_versions', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedInteger('company_id');
$table->unsignedBigInteger('relation_id');
$table->unsignedBigInteger('service_company_id');
$table->string('store_company_key', 191);
$table->string('store_company_name', 200);
$table->string('service_type_code', 32);
$table->string('base_metric', 32);
$table->decimal('fee_rate', 9, 6);
$table->date('effective_from');
$table->date('effective_to')->nullable();
$table->string('contract_no', 64)->nullable();
$table->string('contract_status', 20);
$table->string('status', 20);
$table->unsignedInteger('rule_version');
$table->text('notes')->nullable();
$table->string('changed_by', 100)->nullable();
$table->timestamp('created_at')->nullable();
$table->unique(
['relation_id', 'rule_version'],
'svc_relation_versions_relation_version_unique',
);
$table->index(
['company_id', 'service_company_id', 'store_company_key'],
'svc_relation_versions_company_store_index',
);
});
}
if (! $schema->hasTable('svc_service_settlements')) {
$schema->create('svc_service_settlements', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedInteger('company_id');
$table->char('period', 7);
$table->unsignedBigInteger('service_company_id');
$table->unsignedBigInteger('relation_id');
$table->string('store_company_key', 191);
$table->string('store_company_name', 200);
$table->string('service_type_code', 32);
$table->unsignedInteger('rule_version')->default(1);
$table->string('base_metric', 32)->default('settlement_income');
$table->decimal('base_amount', 20, 4)->default(0);
$table->decimal('fee_rate', 9, 6)->default(0.015000);
$table->decimal('service_fee', 18, 2)->default(0);
$table->string('invoice_status', 20)->default('pending');
$table->decimal('invoice_amount', 18, 2)->default(0);
$table->string('payment_status', 20)->default('pending');
$table->decimal('paid_amount', 18, 2)->default(0);
$table->string('status', 20)->default('draft');
$table->string('source_generation', 191)->nullable();
$table->string('generated_by', 100)->nullable();
$table->timestamp('generated_at')->nullable();
$table->string('confirmed_by', 100)->nullable();
$table->timestamp('confirmed_at')->nullable();
$table->text('notes')->nullable();
$table->timestamps();
$table->unique(
[
'company_id',
'period',
'service_company_id',
'store_company_key',
'service_type_code',
],
'svc_service_settlements_period_relation_unique',
);
$table->index(
['company_id', 'period', 'service_company_id'],
'svc_service_settlements_period_company_index',
);
$table->index(
['company_id', 'service_company_id', 'status'],
'svc_service_settlements_company_status_index',
);
});
}
if (! $schema->hasTable('svc_service_settlement_details')) {
$schema->create('svc_service_settlement_details', function (Blueprint $table): void {
$table->bigIncrements('id');
$table->unsignedBigInteger('settlement_id');
$table->string('erp_store_name', 191);
$table->date('entity_period_from')->nullable();
$table->date('entity_period_to')->nullable();
$table->decimal('base_amount', 20, 4)->default(0);
$table->decimal('service_fee', 18, 2)->default(0);
$table->string('source_generation', 191)->nullable();
$table->timestamps();
$table->unique(
['settlement_id', 'erp_store_name', 'entity_period_from', 'entity_period_to'],
'svc_settlement_details_store_period_unique',
);
$table->index(['settlement_id'], 'svc_settlement_details_settlement_index');
});
}
}
public function down(): void
{
$schema = Schema::connection($this->connection());
foreach ([
'svc_service_settlement_details',
'svc_service_settlements',
'svc_service_relation_versions',
'svc_service_people',
'svc_service_relations',
'svc_service_companies',
] as $table) {
$schema->dropIfExists($table);
}
}
};

View File

@ -350,3 +350,27 @@
8. 合同签署、盖章和生效是否作为生成正式结算的前置条件。
9. 残保金人数口径和成立年度计算方式需向税务确认,本模块暂不自动计算。
10. 园区挂靠地址无法取得房租水电发票的问题由税务顾问确认;系统仅展示凭证缺失和状态。
## 10. 一期落地状态
当前已实现:
- 入口:`经营报表 → 服务公司对账`。
- 服务公司总览与独立详情页,点击公司进入详情。
- 服务公司显式登记,不再依赖上游“公司类型”文字自动猜测。
- 店铺公司来自店铺主体生命周期,关系按生效期间保存。
- 同一店铺公司 + 同一服务类型禁止重叠服务公司。
- 关系修改递增版本,并将历史快照保存在 `svc_service_relation_versions`。
- 人员从现有工资快照选择并归属服务公司,人员同一天只能有一个有效主归属。
- 月度预览按业绩明细 `settlement_income` 汇总,默认用 1.5% 计算服务费。
- 已确认结算不会被重新生成覆盖。
- 开票、到账和结算确认状态可人工维护,为后续票据系统、银行接口预留。
一期暂不包含:
- 自动开票、自动找票或任何税务筹划判断。
- 社保、公积金单位部分、房租水电、报销的完整人工成本汇总。
- 银行接口自动到账匹配。
- 合同批量生成和电子签章。
当前成本页只汇总工资快照的“应发工资”F 列,不能把这部分金额表述为完整人工成本。

View File

@ -13,6 +13,7 @@ use App\Http\Controllers\Business\CourierSurchargeQuotes;
use App\Http\Controllers\Business\CourierSurchargeTypes;
use App\Http\Controllers\Business\InternalFlowReportActions;
use App\Http\Controllers\Business\ProductPrices;
use App\Http\Controllers\Business\ServiceCompanyReconciliation as ServiceCompanyReconciliationController;
use App\Http\Controllers\Business\SupplierPayableActions;
use App\Http\Controllers\Business\SupplierNegativeAlertDingTalkActions;
use App\Http\Controllers\Business\PayablesFinalActions;
@ -653,6 +654,59 @@ Route::get('workspace/financial-operations/installation-details/details/{guid}',
Route::get('workspace/financial-operations/installation-details/export', 'Business\Pages@exportInstallationDetails')
->name('business.installation-details.export');
Route::prefix('workspace/financial-operations/service-company-reconciliation')
->name('business.service-company-reconciliation.')
->middleware('business.page:financial-operations,service-company-reconciliation')
->group(function (): void {
Route::get('/', [ServiceCompanyReconciliationController::class, 'index'])
->defaults('section', 'financial-operations')
->defaults('page', 'service-company-reconciliation')
->name('index');
Route::post('companies', [ServiceCompanyReconciliationController::class, 'storeCompany'])
->name('companies.store');
Route::patch('companies/{serviceCompany}', [ServiceCompanyReconciliationController::class, 'updateCompany'])
->whereNumber('serviceCompany')
->name('companies.update');
Route::post('{serviceCompany}/relations', [ServiceCompanyReconciliationController::class, 'storeRelation'])
->whereNumber('serviceCompany')
->name('relations.store');
Route::patch(
'{serviceCompany}/relations/{relation}',
[ServiceCompanyReconciliationController::class, 'updateRelation'],
)
->whereNumber('serviceCompany')
->whereNumber('relation')
->name('relations.update');
Route::post('{serviceCompany}/people', [ServiceCompanyReconciliationController::class, 'assignPerson'])
->whereNumber('serviceCompany')
->name('people.store');
Route::post(
'{serviceCompany}/people/{assignment}/end',
[ServiceCompanyReconciliationController::class, 'endPerson'],
)
->whereNumber('serviceCompany')
->whereNumber('assignment')
->name('people.end');
Route::post(
'{serviceCompany}/settlements/generate',
[ServiceCompanyReconciliationController::class, 'generateSettlements'],
)
->whereNumber('serviceCompany')
->name('settlements.generate');
Route::patch(
'{serviceCompany}/settlements/{settlement}',
[ServiceCompanyReconciliationController::class, 'updateSettlement'],
)
->whereNumber('serviceCompany')
->whereNumber('settlement')
->name('settlements.update');
Route::get('{serviceCompany}', [ServiceCompanyReconciliationController::class, 'show'])
->whereNumber('serviceCompany')
->defaults('section', 'financial-operations')
->defaults('page', 'service-company-reconciliation')
->name('show');
});
Route::get('workspace/trademark-management/store-report-data-logic/edit', 'Business\Pages@editStoreReportLogic')
->middleware('business.page:trademark-management,store-report-data-logic')
->name('business.store-report-logic.edit');

View File

@ -66,7 +66,9 @@ class FinanceLedgerNavigationTest extends FeatureTestCase
->assertOk()
->assertSeeText('财务经营报表')
->assertSeeText('服务公司对账')
->assertSeeText('该页面暂未配置数据表,敬请期待。');
->assertSeeText('服务公司总览')
->assertSeeText('还没有登记服务公司。')
->assertSee('prototype-tag-link is-active', false);
$this->get(route('business.pages.show', [
'section' => 'financial-operations',

View File

@ -0,0 +1,364 @@
<?php
namespace Tests\Feature\Business;
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 Tests\Feature\FeatureTestCase;
class ServiceCompanyReconciliationTest extends FeatureTestCase
{
public function test_service_company_and_relation_can_be_configured_from_the_real_page(): void
{
$this->seedStoreMirror();
$this->loginAs();
$this->get(route('business.service-company-reconciliation.index'))
->assertOk()
->assertSeeText('服务公司总览')
->assertSeeText('新增服务公司');
$response = $this->post(route('business.service-company-reconciliation.companies.store'), [
'company_name' => '常州测试客服服务有限公司',
'unified_social_credit_code' => '91320400TESTCUSTOMER01',
'service_type_code' => 'customer_service',
'taxpayer_type' => '小规模纳税人',
'company_status' => '正常',
'planning_target_amount' => 3000000,
'status' => 'active',
'notes' => '测试服务公司',
]);
$serviceCompanyId = (int) DB::connection('business_mirror')
->table('svc_service_companies')
->value('id');
$response->assertRedirect(route('business.service-company-reconciliation.show', [
'serviceCompany' => $serviceCompanyId,
]));
$storeCompanyKey = ServiceCompanyReconciliationRepository::companyKey(
'上海测试店铺公司有限公司',
'91310000TESTSTORE01',
);
$this->post(route('business.service-company-reconciliation.relations.store', [
'serviceCompany' => $serviceCompanyId,
]), [
'store_company_key' => $storeCompanyKey,
'base_metric' => 'settlement_income',
'fee_rate_percent' => 1.5,
'effective_from' => '2025-01-01',
'effective_to' => '',
'contract_no' => 'HT-TEST-001',
'contract_status' => 'stamped',
'status' => 'active',
])->assertSessionHasNoErrors();
$relationId = (int) DB::connection('business_mirror')
->table('svc_service_relations')
->value('id');
$this->patch(route('business.service-company-reconciliation.relations.update', [
'serviceCompany' => $serviceCompanyId,
'relation' => $relationId,
]), [
'store_company_key' => $storeCompanyKey,
'base_metric' => 'settlement_income',
'fee_rate_percent' => 2,
'effective_from' => '2025-01-01',
'effective_to' => '',
'contract_no' => 'HT-TEST-001',
'contract_status' => 'stamped',
'status' => 'active',
])->assertSessionHasNoErrors();
$this->assertSame(
2,
(int) DB::connection('business_mirror')
->table('svc_service_relations')
->where('id', $relationId)
->value('rule_version'),
);
$this->assertSame(
2,
DB::connection('business_mirror')
->table('svc_service_relation_versions')
->where('relation_id', $relationId)
->count(),
);
$this->get(route('business.service-company-reconciliation.show', [
'serviceCompany' => $serviceCompanyId,
'tab' => 'relations',
]))
->assertOk()
->assertSeeText('常州测试客服服务有限公司')
->assertSeeText('上海测试店铺公司有限公司')
->assertSeeText('HT-TEST-001')
->assertSeeText('2.0000%')
->assertSeeText('同一店铺公司 + 同一服务类型');
}
public function test_same_store_company_and_service_type_cannot_have_overlapping_service_companies(): void
{
$this->seedStoreMirror();
$this->loginAs();
$firstId = $this->createServiceCompany('第一测试客服有限公司', '91320400TESTCUSTOMER02');
$secondId = $this->createServiceCompany('第二测试客服有限公司', '91320400TESTCUSTOMER03');
$storeKey = ServiceCompanyReconciliationRepository::companyKey(
'上海测试店铺公司有限公司',
'91310000TESTSTORE01',
);
$payload = [
'store_company_key' => $storeKey,
'base_metric' => 'settlement_income',
'fee_rate_percent' => 1.5,
'effective_from' => '2026-01-01',
'effective_to' => '2026-12-31',
'contract_no' => 'HT-TEST-002',
'contract_status' => 'stamped',
'status' => 'active',
];
$this->post(route('business.service-company-reconciliation.relations.store', [
'serviceCompany' => $firstId,
]), $payload)->assertSessionHasNoErrors();
$this->withExceptionHandling()
->post(route('business.service-company-reconciliation.relations.store', [
'serviceCompany' => $secondId,
]), $payload)
->assertSessionHasErrors('effective_from');
$this->assertSame(
1,
DB::connection('business_mirror')->table('svc_service_relations')->count(),
);
}
public function test_monthly_preview_uses_income_amount_and_prevents_confirmed_overwrite(): void
{
$period = CarbonImmutable::now()->subMonthNoOverflow()->format('Y-m');
$this->seedStoreMirror($period);
$this->loginAs();
$serviceCompanyId = $this->createServiceCompany(
'常州测试客服服务有限公司',
'91320400TESTCUSTOMER04',
);
$storeKey = ServiceCompanyReconciliationRepository::companyKey(
'上海测试店铺公司有限公司',
'91310000TESTSTORE01',
);
$this->post(route('business.service-company-reconciliation.relations.store', [
'serviceCompany' => $serviceCompanyId,
]), [
'store_company_key' => $storeKey,
'base_metric' => 'settlement_income',
'fee_rate_percent' => 1.5,
'effective_from' => '2025-01-01',
'effective_to' => '',
'contract_no' => 'HT-TEST-003',
'contract_status' => 'stamped',
'status' => 'active',
])->assertSessionHasNoErrors();
$this->post(route('business.service-company-reconciliation.settlements.generate', [
'serviceCompany' => $serviceCompanyId,
]), ['period' => $period])->assertRedirect();
$settlement = DB::connection('business_mirror')
->table('svc_service_settlements')
->where('period', $period)
->first();
$this->assertNotNull($settlement);
$this->assertSame(125000.0, (float) $settlement->base_amount);
$this->assertSame(1875.0, (float) $settlement->service_fee);
$this->assertSame(
2,
DB::connection('business_mirror')->table('svc_service_settlement_details')->count(),
);
$this->patch(route('business.service-company-reconciliation.settlements.update', [
'serviceCompany' => $serviceCompanyId,
'settlement' => $settlement->id,
]), [
'action' => 'confirm',
'invoice_status' => 'invoiced',
'invoice_amount' => 1875,
'payment_status' => 'paid',
'paid_amount' => 1875,
])->assertSessionHasNoErrors();
$this->assertSame(
'confirmed',
DB::connection('business_mirror')
->table('svc_service_settlements')
->where('id', $settlement->id)
->value('status'),
);
$this->post(route('business.service-company-reconciliation.settlements.generate', [
'serviceCompany' => $serviceCompanyId,
]), ['period' => $period])
->assertRedirect()
->assertSessionHas('error');
$this->assertSame(
1875.0,
(float) DB::connection('business_mirror')
->table('svc_service_settlements')
->where('id', $settlement->id)
->value('service_fee'),
);
}
public function test_people_can_be_assigned_from_the_labor_snapshot(): void
{
$this->seedStoreMirror();
$this->loginAs();
$serviceCompanyId = $this->createServiceCompany(
'常州测试客服服务有限公司',
'91320400TESTCUSTOMER05',
);
DB::table('business_labor_expense_snapshots')->insert([
'company_id' => $this->company->id,
'source_name' => '测试工资.xlsx',
'rows' => json_encode([[
'B' => '小测',
'C' => '测试员工',
'D' => '客服一组',
'E' => '客服',
'F' => '8000',
]], JSON_UNESCAPED_UNICODE),
'row_count' => 1,
'created_at' => now(),
'updated_at' => now(),
]);
$personKey = ServiceCompanyReconciliationRepository::personKey('测试员工', '小测', '客服一组');
$this->post(route('business.service-company-reconciliation.people.store', [
'serviceCompany' => $serviceCompanyId,
]), [
'person_key' => $personKey,
'effective_from' => now()->toDateString(),
])->assertSessionHasNoErrors();
$this->get(route('business.service-company-reconciliation.show', [
'serviceCompany' => $serviceCompanyId,
'tab' => 'people',
]))
->assertOk()
->assertSeeText('测试员工')
->assertSeeText('客服一组')
->assertSeeText('¥8,000.00');
}
public function test_finance_ledger_viewer_can_read_but_cannot_change_configuration(): void
{
$viewer = User::create([
'name' => 'fixture-service-company-viewer',
'email' => 'fixture-service-company-viewer@example.test',
'password' => 'fixture-unused-password',
'enabled' => true,
'locale' => 'zh-CN',
'landing_page' => 'dashboard',
]);
$viewer->roles()->attach(Role::where('name', 'user')->firstOrFail()->id);
$viewer->permissions()->attach(Permission::where('name', 'read-admin-panel')->firstOrFail()->id);
$viewer->companies()->attach($this->company->id);
$subject = 'user_' . $viewer->id;
setting()->set('system.sidebar_permissions', [
'configured' => [$subject],
'subjects' => [$subject => ['financial-operations/ledger']],
]);
$this->loginAs($viewer)
->get(route('business.service-company-reconciliation.index'))
->assertOk()
->assertSeeText('服务公司总览')
->assertDontSee('data-company-create>', false);
$this->withExceptionHandling()
->post(route('business.service-company-reconciliation.companies.store'), [
'company_name' => '不应创建的客服公司',
'service_type_code' => 'customer_service',
'company_status' => '正常',
'status' => 'active',
])
->assertForbidden();
}
private function createServiceCompany(string $name, string $code): int
{
$this->post(route('business.service-company-reconciliation.companies.store'), [
'company_name' => $name,
'unified_social_credit_code' => $code,
'service_type_code' => 'customer_service',
'taxpayer_type' => '小规模纳税人',
'company_status' => '正常',
'planning_target_amount' => 3000000,
'status' => 'active',
])->assertSessionHasNoErrors();
return (int) DB::connection('business_mirror')
->table('svc_service_companies')
->where('unified_social_credit_code', $code)
->value('id');
}
private function seedStoreMirror(?string $period = null): void
{
$period = $period ?: CarbonImmutable::now()->format('Y-m');
$periodStart = CarbonImmutable::createFromFormat('!Y-m', $period)->startOfMonth();
$mirror = DB::connection('business_mirror');
$paidGeneration = '11111111-1111-1111-1111-111111111111';
$lifecycleGeneration = '22222222-2222-2222-2222-222222222222';
$mirror->table('store_report_import_states')->insert([
[
'dataset_key' => 'store-report.paid-sales',
'status' => 'succeeded',
'active_generation' => $paidGeneration,
'row_count' => 2,
'created_at' => now(),
'updated_at' => now(),
],
[
'dataset_key' => 'store-report.store-lifecycles',
'status' => 'succeeded',
'active_generation' => $lifecycleGeneration,
'row_count' => 1,
'created_at' => now(),
'updated_at' => now(),
],
]);
foreach (['测试店铺A', '测试店铺B'] as $storeName) {
$mirror->table('store_report_lifecycle_rows')->insert([
'generation' => $lifecycleGeneration,
'business_key' => hash('sha256', '上海测试店铺公司有限公司|' . $storeName . '|2025-01-01'),
'erp_store_name' => $storeName,
'company_name' => '上海测试店铺公司有限公司',
'unified_social_credit_code' => '91310000TESTSTORE01',
'effective_at' => '2025-01-01 00:00:00',
'expires_at' => null,
'source_file' => 'test.xlsx',
'row_hash' => hash('sha256', 'lifecycle-row-' . $storeName),
'imported_at' => now(),
]);
}
foreach ([['测试店铺A', 100000], ['测试店铺B', 25000]] as [$storeName, $amount]) {
$mirror->table('store_report_paid_sales_rows')->insert([
'generation' => $paidGeneration,
'store_name' => $storeName,
'occurred_on' => $periodStart->addDays(8)->toDateString(),
'paid_amount' => $amount,
'settlement_income' => $amount,
'order_count' => 1,
'updated_at' => now(),
]);
}
}
}