322 lines
12 KiB
PHP
322 lines
12 KiB
PHP
<?php
|
||
|
||
namespace App\Business\CompanyPlan;
|
||
|
||
use PDO;
|
||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
||
use RuntimeException;
|
||
use Throwable;
|
||
|
||
/**
|
||
* 公司盘点中的公司持股关系。
|
||
*
|
||
* 数据来自资产盘点工作簿“主体明细”的“股东”列,只保留股东本身也是盘点主体的公司关系,
|
||
* 供公司盘点备注跳转到公司基础信息并按股东过滤。
|
||
*/
|
||
class CompanyPlanCompanyRepository
|
||
{
|
||
public const SUBSIDIARY_NOTE = '名下有子公司,暂不注销';
|
||
|
||
private ?PDO $pdo = null;
|
||
|
||
public function pdo(): PDO
|
||
{
|
||
if ($this->pdo instanceof PDO) {
|
||
return $this->pdo;
|
||
}
|
||
|
||
$path = (string) config('company_plan.database_path');
|
||
$directory = dirname($path);
|
||
|
||
if (! is_dir($directory) && ! mkdir($directory, 0775, true) && ! is_dir($directory)) {
|
||
throw new RuntimeException('无法创建公司盘点原型数据目录。');
|
||
}
|
||
|
||
$pdo = new PDO('sqlite:' . $path, null, null, [
|
||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||
]);
|
||
$pdo->exec('PRAGMA busy_timeout = 5000');
|
||
$pdo->exec('PRAGMA journal_mode = WAL');
|
||
$this->ensureSchema($pdo);
|
||
|
||
return $this->pdo = $pdo;
|
||
}
|
||
|
||
private function ensureSchema(PDO $pdo): void
|
||
{
|
||
$pdo->exec(<<<'SQL'
|
||
CREATE TABLE IF NOT EXISTS company_plan_company_relations (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
company_id INTEGER NOT NULL,
|
||
plan_row_id INTEGER,
|
||
shareholder_company_name TEXT NOT NULL,
|
||
related_company_name TEXT NOT NULL,
|
||
related_unified_social_credit_code TEXT,
|
||
share_ratio TEXT,
|
||
shareholders_text TEXT NOT NULL,
|
||
source_sheet TEXT,
|
||
created_at TEXT NOT NULL,
|
||
updated_at TEXT NOT NULL,
|
||
UNIQUE (company_id, shareholder_company_name, related_company_name)
|
||
)
|
||
SQL);
|
||
$pdo->exec(
|
||
'CREATE INDEX IF NOT EXISTS company_plan_company_relations_shareholder_index '
|
||
. 'ON company_plan_company_relations (company_id, shareholder_company_name)'
|
||
);
|
||
}
|
||
|
||
/**
|
||
* @return array{source_sheet:string,scanned:int,relationships:int,shareholders:int}
|
||
*/
|
||
public function importFromWorkbook(string $path, int $companyId): array
|
||
{
|
||
if (! is_file($path)) {
|
||
throw new RuntimeException('源工作簿不存在:' . $path);
|
||
}
|
||
|
||
$reader = IOFactory::createReaderForFile($path);
|
||
$reader->setReadDataOnly(true);
|
||
$book = $reader->load($path);
|
||
|
||
try {
|
||
$sheet = $book->getSheetByName('主体明细');
|
||
if (! $sheet instanceof Worksheet) {
|
||
throw new RuntimeException('源工作簿缺少“主体明细”工作表。');
|
||
}
|
||
|
||
$rows = $sheet->toArray(null, true, false, false);
|
||
[$headerRow, $headers] = $this->findHeaders($rows);
|
||
if (! isset($headers['company_name'], $headers['shareholders'])) {
|
||
throw new RuntimeException('“主体明细”缺少“公司名称”或“股东”表头。');
|
||
}
|
||
|
||
$planRows = [];
|
||
$statement = $this->pdo()->prepare(
|
||
'SELECT id, company_name FROM company_plan_rows WHERE company_id = ?'
|
||
);
|
||
$statement->execute([$companyId]);
|
||
foreach ($statement->fetchAll() as $planRow) {
|
||
$name = trim((string) $planRow['company_name']);
|
||
$planRows[self::normalizeCompanyName($name)] = [
|
||
'id' => (int) $planRow['id'],
|
||
'name' => $name,
|
||
];
|
||
}
|
||
|
||
$relations = [];
|
||
$shareholders = [];
|
||
$scanned = 0;
|
||
foreach (array_slice($rows, $headerRow + 1) as $row) {
|
||
$relatedCompany = $this->cell($row, $headers['company_name']);
|
||
$shareholderText = $this->cell($row, $headers['shareholders']);
|
||
if ($relatedCompany === '' || $shareholderText === '') {
|
||
continue;
|
||
}
|
||
$scanned++;
|
||
|
||
foreach ($this->shareholderEntries($shareholderText) as [$shareholderName, $ratio]) {
|
||
$match = $planRows[self::normalizeCompanyName($shareholderName)] ?? null;
|
||
if ($match === null) {
|
||
continue;
|
||
}
|
||
|
||
$key = $match['name'] . '|' . $relatedCompany;
|
||
$relations[$key] = [
|
||
'plan_row_id' => $match['id'],
|
||
'shareholder_company_name' => $match['name'],
|
||
'related_company_name' => $relatedCompany,
|
||
'related_unified_social_credit_code' => isset($headers['credit_code'])
|
||
? $this->nullableCell($row, $headers['credit_code'], 64)
|
||
: null,
|
||
'share_ratio' => $ratio !== '' ? $ratio : null,
|
||
'shareholders_text' => $ratio !== ''
|
||
? $match['name'] . ':' . $ratio
|
||
: $match['name'],
|
||
'source_sheet' => '主体明细',
|
||
];
|
||
$shareholders[$match['name']] = true;
|
||
}
|
||
}
|
||
|
||
$pdo = $this->pdo();
|
||
$pdo->beginTransaction();
|
||
try {
|
||
$pdo->prepare('DELETE FROM company_plan_company_relations WHERE company_id = ?')
|
||
->execute([$companyId]);
|
||
$insert = $pdo->prepare(<<<'SQL'
|
||
INSERT INTO company_plan_company_relations (
|
||
company_id, plan_row_id, shareholder_company_name, related_company_name,
|
||
related_unified_social_credit_code, share_ratio, shareholders_text,
|
||
source_sheet, created_at, updated_at
|
||
) VALUES (
|
||
:company_id, :plan_row_id, :shareholder_company_name, :related_company_name,
|
||
:related_unified_social_credit_code, :share_ratio, :shareholders_text,
|
||
:source_sheet, :created_at, :updated_at
|
||
)
|
||
SQL);
|
||
$now = now()->toDateTimeString();
|
||
foreach ($relations as $relation) {
|
||
$insert->execute([
|
||
':company_id' => $companyId,
|
||
':plan_row_id' => $relation['plan_row_id'],
|
||
':shareholder_company_name' => mb_substr($relation['shareholder_company_name'], 0, 255),
|
||
':related_company_name' => mb_substr($relation['related_company_name'], 0, 255),
|
||
':related_unified_social_credit_code' => $relation['related_unified_social_credit_code'],
|
||
':share_ratio' => $relation['share_ratio'],
|
||
':shareholders_text' => mb_substr($relation['shareholders_text'], 0, 500),
|
||
':source_sheet' => $relation['source_sheet'],
|
||
':created_at' => $now,
|
||
':updated_at' => $now,
|
||
]);
|
||
}
|
||
$pdo->commit();
|
||
} catch (Throwable $exception) {
|
||
if ($pdo->inTransaction()) {
|
||
$pdo->rollBack();
|
||
}
|
||
throw $exception;
|
||
}
|
||
|
||
return [
|
||
'source_sheet' => '主体明细',
|
||
'scanned' => $scanned,
|
||
'relationships' => count($relations),
|
||
'shareholders' => count($shareholders),
|
||
];
|
||
} finally {
|
||
$book->disconnectWorksheets();
|
||
}
|
||
}
|
||
|
||
/** @return array<string,int> 键包含原名称和归一化名称。 */
|
||
public function countsByShareholder(int $companyId): array
|
||
{
|
||
$statement = $this->pdo()->prepare(
|
||
'SELECT shareholder_company_name, COUNT(*) AS total '
|
||
. 'FROM company_plan_company_relations WHERE company_id = ? '
|
||
. 'GROUP BY shareholder_company_name'
|
||
);
|
||
$statement->execute([$companyId]);
|
||
|
||
$counts = [];
|
||
foreach ($statement->fetchAll() as $row) {
|
||
$name = (string) $row['shareholder_company_name'];
|
||
$counts[$name] = (int) $row['total'];
|
||
$counts[self::normalizeCompanyName($name)] = (int) $row['total'];
|
||
}
|
||
|
||
return $counts;
|
||
}
|
||
|
||
/**
|
||
* @return array<string,array{company_name:string,shareholders_text:string,share_ratio:?string}>
|
||
*/
|
||
public function relationsForShareholder(int $companyId, string $shareholderCompany): array
|
||
{
|
||
$statement = $this->pdo()->prepare(
|
||
'SELECT related_company_name, shareholders_text, share_ratio '
|
||
. 'FROM company_plan_company_relations '
|
||
. 'WHERE company_id = :company_id AND shareholder_company_name = :shareholder_company '
|
||
. 'ORDER BY related_company_name ASC'
|
||
);
|
||
$statement->execute([
|
||
':company_id' => $companyId,
|
||
':shareholder_company' => trim($shareholderCompany),
|
||
]);
|
||
|
||
$relations = [];
|
||
foreach ($statement->fetchAll() as $row) {
|
||
$name = trim((string) $row['related_company_name']);
|
||
$relations[self::normalizeCompanyName($name)] = [
|
||
'company_name' => $name,
|
||
'shareholders_text' => (string) $row['shareholders_text'],
|
||
'share_ratio' => $row['share_ratio'] !== null ? (string) $row['share_ratio'] : null,
|
||
];
|
||
}
|
||
|
||
return $relations;
|
||
}
|
||
|
||
public static function normalizeCompanyName(string $name): string
|
||
{
|
||
$normalized = preg_replace('/[\s\x{00A0}\x{3000}]+/u', '', trim($name)) ?? trim($name);
|
||
|
||
return mb_strtolower(str_replace(['(', ')'], ['(', ')'], $normalized));
|
||
}
|
||
|
||
/**
|
||
* @param list<array<int,mixed>> $rows
|
||
* @return array{0:int,1:array<string,int>}
|
||
*/
|
||
private function findHeaders(array $rows): array
|
||
{
|
||
$aliases = [
|
||
'公司名称' => 'company_name',
|
||
'统一社会信用代码' => 'credit_code',
|
||
'股东' => 'shareholders',
|
||
];
|
||
|
||
foreach (array_slice($rows, 0, 20, true) as $index => $row) {
|
||
$headers = [];
|
||
foreach ($row as $column => $value) {
|
||
$header = preg_replace('/\s+/u', '', trim((string) $value)) ?? '';
|
||
if (isset($aliases[$header])) {
|
||
$headers[$aliases[$header]] = $column;
|
||
}
|
||
}
|
||
if (isset($headers['company_name'], $headers['shareholders'])) {
|
||
return [$index, $headers];
|
||
}
|
||
}
|
||
|
||
throw new RuntimeException('未识别到“主体明细”的公司名称和股东表头。');
|
||
}
|
||
|
||
/**
|
||
* @param array<int,mixed> $row
|
||
* @return list<array{0:string,1:string}>
|
||
*/
|
||
private function shareholderEntries(string $text): array
|
||
{
|
||
$entries = [];
|
||
foreach (preg_split('/[|;;]/u', $text) ?: [] as $part) {
|
||
$part = trim(str_replace("\u{00A0}", ' ', $part));
|
||
if ($part === '') {
|
||
continue;
|
||
}
|
||
|
||
if (! preg_match('/^(.+?)[::]\s*(.*)$/u', $part, $matches)) {
|
||
$entries[] = [$part, ''];
|
||
continue;
|
||
}
|
||
|
||
$name = trim($matches[1]);
|
||
$ratio = trim($matches[2]);
|
||
if ($name !== '') {
|
||
$entries[] = [$name, $ratio];
|
||
}
|
||
}
|
||
|
||
return $entries;
|
||
}
|
||
|
||
/** @param array<int,mixed> $row */
|
||
private function cell(array $row, int $column): string
|
||
{
|
||
$value = $row[$column] ?? null;
|
||
|
||
return $value === null ? '' : trim(str_replace("\u{00A0}", ' ', (string) $value));
|
||
}
|
||
|
||
/** @param array<int,mixed> $row */
|
||
private function nullableCell(array $row, int $column, int $length): ?string
|
||
{
|
||
$value = $this->cell($row, $column);
|
||
|
||
return $value !== '' ? mb_substr($value, 0, $length) : null;
|
||
}
|
||
}
|