*/ public const FIELDS = [ ['name' => 'sequence_no', 'label' => '序号', 'type' => 'integer'], ['name' => 'company_name', 'label' => '公司名称', 'type' => 'text'], ['name' => 'company_type', 'label' => '类型', 'type' => 'text'], ['name' => 'taxpayer_type', 'label' => '税务类型', 'type' => 'text'], ['name' => 'registered_at', 'label' => '注册时间', 'type' => 'date'], ['name' => 'business_registration_type', 'label' => '工商类型', 'type' => 'text'], ['name' => 'unified_social_credit_code', 'label' => '统一社会信用代码', 'type' => 'text'], ['name' => 'plan', 'label' => '规划', 'type' => 'text'], ['name' => 'company_status', 'label' => '公司状态', 'type' => 'text'], ['name' => 'tax_cancellation', 'label' => '注销-税务', 'type' => 'text'], ['name' => 'business_cancellation', 'label' => '注销-工商', 'type' => 'text'], ['name' => 'bank_cancellation', 'label' => '注销-银行', 'type' => 'text'], ['name' => 'notes', 'label' => '备注', 'type' => 'text'], ]; /** @var list */ public const MUTABLE_FIELDS = [ 'sequence_no', 'company_name', 'company_type', 'taxpayer_type', 'registered_at', 'business_registration_type', 'unified_social_credit_code', 'plan', 'company_status', 'tax_cancellation', 'business_cancellation', 'bank_cancellation', 'notes', ]; /** * 类型口径归一:历史数据中的“个体户”统一视为“个体工商户”。 * * @var array */ private const COMPANY_TYPE_ALIASES = [ '个体户' => '个体工商户', ]; /** * 公司状态口径归一:历史数据中的“注销”统一视为“已注销”。 * * @var array */ private const COMPANY_STATUS_ALIASES = [ '注销' => '已注销', ]; /** * 写入与查询选项共用的口径归一映射,键为字段名。 * * @var array> */ private const FIELD_ALIASES = [ 'company_type' => self::COMPANY_TYPE_ALIASES, 'company_status' => self::COMPANY_STATUS_ALIASES, ]; 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; } /** * @param array $filters * @return array{rows:list>,total:int,page:int,per_page:int,last_page:int} */ public function paginate(int $companyId, array $filters, int $page, int $perPage): array { [$whereSql, $params] = $this->where($companyId, $filters); $sort = $this->safeSort((string) ($filters['sort'] ?? 'sequence_no')); $direction = (($filters['direction'] ?? 'asc') === 'desc') ? 'DESC' : 'ASC'; $pdo = $this->pdo(); $countStatement = $pdo->prepare("SELECT COUNT(*) FROM company_plan_rows {$whereSql}"); $countStatement->execute($params); $total = (int) $countStatement->fetchColumn(); $lastPage = max(1, (int) ceil($total / max($perPage, 1))); $page = min(max($page, 1), $lastPage); $offset = ($page - 1) * $perPage; $orderSql = "CASE WHEN {$sort} IS NULL OR TRIM(CAST({$sort} AS TEXT)) = '' THEN 1 ELSE 0 END ASC, " . "{$sort} {$direction}, id ASC"; $statement = $pdo->prepare( "SELECT * FROM company_plan_rows {$whereSql} ORDER BY {$orderSql} LIMIT :limit OFFSET :offset" ); foreach ($params as $key => $value) { $statement->bindValue($key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR); } $statement->bindValue(':limit', $perPage, PDO::PARAM_INT); $statement->bindValue(':offset', $offset, PDO::PARAM_INT); $statement->execute(); return [ 'rows' => $statement->fetchAll(), 'total' => $total, 'page' => $page, 'per_page' => $perPage, 'last_page' => $lastPage, ]; } /** * @param array $filters * @return list> */ public function exportRows(int $companyId, array $filters): array { [$whereSql, $params] = $this->where($companyId, $filters); $sort = $this->safeSort((string) ($filters['sort'] ?? 'sequence_no')); $direction = (($filters['direction'] ?? 'asc') === 'desc') ? 'DESC' : 'ASC'; $statement = $this->pdo()->prepare( "SELECT * FROM company_plan_rows {$whereSql} " . "ORDER BY CASE WHEN {$sort} IS NULL OR TRIM(CAST({$sort} AS TEXT)) = '' THEN 1 ELSE 0 END ASC, " . "{$sort} {$direction}, id ASC" ); $statement->execute($params); return $statement->fetchAll(); } /** @return array{total:int,retained:int,cancelled_done:int,cancelling:int,plan_cancelled_pending:int} */ public function summary(int $companyId): array { $statement = $this->pdo()->prepare(<<<'SQL' SELECT COUNT(*) AS total, COALESCE(SUM(CASE WHEN TRIM(COALESCE(plan, '')) = '保留' THEN 1 ELSE 0 END), 0) AS retained, COALESCE(SUM(CASE WHEN TRIM(COALESCE(company_status, '')) = '已注销' THEN 1 ELSE 0 END), 0) AS cancelled_done, COALESCE(SUM(CASE WHEN TRIM(COALESCE(company_status, '')) = '注销中' THEN 1 ELSE 0 END), 0) AS cancelling, COALESCE(SUM(CASE WHEN TRIM(COALESCE(plan, '')) = '注销' AND TRIM(COALESCE(company_status, '')) = '正常' THEN 1 ELSE 0 END), 0) AS plan_cancelled_pending FROM company_plan_rows WHERE company_id = :company_id SQL); $statement->execute([':company_id' => $companyId]); $row = $statement->fetch() ?: []; return [ 'total' => (int) ($row['total'] ?? 0), 'retained' => (int) ($row['retained'] ?? 0), 'cancelled_done' => (int) ($row['cancelled_done'] ?? 0), 'cancelling' => (int) ($row['cancelling'] ?? 0), 'plan_cancelled_pending' => (int) ($row['plan_cancelled_pending'] ?? 0), ]; } /** @return array> */ public function filterOptions(int $companyId): array { return [ 'plan' => $this->distinctValues($companyId, 'plan'), 'company_status' => $this->distinctValues($companyId, 'company_status'), 'company_type' => $this->distinctValues($companyId, 'company_type'), 'taxpayer_type' => $this->distinctValues($companyId, 'taxpayer_type'), 'business_registration_type' => $this->distinctValues($companyId, 'business_registration_type'), ]; } /** @return array{taxpayer_type:list,business_registration_type:list} */ public function classificationFilterOptions(int $companyId): array { return [ 'taxpayer_type' => $this->distinctValues($companyId, 'taxpayer_type'), 'business_registration_type' => $this->distinctValues($companyId, 'business_registration_type'), ]; } /** @return array */ public function companyNames(int $companyId): array { $statement = $this->pdo()->prepare( 'SELECT company_name FROM company_plan_rows WHERE company_id = :company_id' ); $statement->execute([':company_id' => $companyId]); $names = []; foreach ($statement->fetchAll(PDO::FETCH_COLUMN) as $name) { $normalized = $this->normalizeCompanyName((string) $name); if ($normalized !== '') { $names[$normalized] = true; } } return $names; } /** * 公司基础信息页按当前页公司读取盘点中的税务、工商类型。 * * @param list $companyNames * @param list $creditCodes * @return list> */ public function classificationReferencesForCompanies( int $companyId, array $companyNames, array $creditCodes = [], ): array { $conditions = []; $params = [':company_id' => $companyId]; foreach (array_values(array_unique(array_filter(array_map('trim', $companyNames)))) as $index => $name) { $key = ':company_name_' . $index; $conditions[] = "REPLACE(LOWER(TRIM(COALESCE(company_name, ''))), ' ', '') = {$key}"; $params[$key] = mb_strtolower(preg_replace('/\s+/u', '', $name) ?? $name); } foreach (array_values(array_unique(array_filter(array_map('trim', $creditCodes)))) as $index => $code) { $key = ':credit_code_' . $index; $conditions[] = "REPLACE(UPPER(TRIM(COALESCE(unified_social_credit_code, ''))), ' ', '') = {$key}"; $params[$key] = mb_strtoupper(preg_replace('/\s+/u', '', $code) ?? $code); } if ($conditions === []) { return []; } $statement = $this->pdo()->prepare( 'SELECT company_name, unified_social_credit_code, taxpayer_type, business_registration_type ' . 'FROM company_plan_rows WHERE company_id = :company_id AND (' . implode(' OR ', $conditions) . ') ' . 'ORDER BY CASE WHEN sequence_no IS NULL OR TRIM(CAST(sequence_no AS TEXT)) = \'\' THEN 1 ELSE 0 END, ' . 'sequence_no, id' ); $statement->execute($params); return $statement->fetchAll(); } /** * 按盘点口径筛选或排序时读取当前公司的全部类型资料。 * * @return list> */ public function allClassificationReferences(int $companyId): array { $statement = $this->pdo()->prepare( 'SELECT company_name, unified_social_credit_code, taxpayer_type, business_registration_type ' . 'FROM company_plan_rows WHERE company_id = :company_id ' . 'ORDER BY CASE WHEN sequence_no IS NULL OR TRIM(CAST(sequence_no AS TEXT)) = \'\' THEN 1 ELSE 0 END, ' . 'sequence_no, id' ); $statement->execute([':company_id' => $companyId]); return $statement->fetchAll(); } /** @return list> */ public function allSubjectReferences(int $companyId): array { $statement = $this->pdo()->prepare( 'SELECT company_name, taxpayer_type, business_registration_type, company_status ' . 'FROM company_plan_rows ' . 'WHERE company_id = :company_id ORDER BY id' ); $statement->execute([':company_id' => $companyId]); return $statement->fetchAll(); } /** * 服务公司对账从公司盘点读取类型包含“服务公司”的主体。 * * @return list> */ 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( 'SELECT * FROM company_plan_rows WHERE company_id = :company_id AND id = :id LIMIT 1' ); $statement->execute([':company_id' => $companyId, ':id' => $id]); $row = $statement->fetch(); return $row === false ? null : $row; } public function companyNameExists(int $companyId, string $companyName, ?int $exceptId = null): bool { $sql = 'SELECT COUNT(*) FROM company_plan_rows WHERE company_id = :company_id AND company_name = :company_name'; $params = [':company_id' => $companyId, ':company_name' => trim($companyName)]; if ($exceptId !== null) { $sql .= ' AND id <> :id'; $params[':id'] = $exceptId; } $statement = $this->pdo()->prepare($sql); $statement->execute($params); return (int) $statement->fetchColumn() > 0; } /** * @param array $data */ public function update(int $companyId, int $id, array $data, ?int $userId): void { $values = $this->normalizeMutableData($data); $assignments = []; $params = [ ':company_id' => $companyId, ':id' => $id, ':updated_by' => $userId, ':updated_at' => now()->format('Y-m-d H:i:s'), ]; foreach ($values as $field => $value) { $assignments[] = "{$field} = :{$field}"; $params[':' . $field] = $value; } $assignments[] = 'updated_by = :updated_by'; $assignments[] = 'updated_at = :updated_at'; $statement = $this->pdo()->prepare( 'UPDATE company_plan_rows SET ' . implode(', ', $assignments) . ' WHERE company_id = :company_id AND id = :id' ); $statement->execute($params); } /** * @param list> $rows * @return array{created:int,updated:int,skipped:int} */ public function importRows(int $companyId, array $rows, string $duplicateMode, ?int $userId): array { $pdo = $this->pdo(); $pdo->beginTransaction(); $created = 0; $updated = 0; $skipped = 0; try { $lookup = $pdo->prepare( 'SELECT id FROM company_plan_rows WHERE company_id = :company_id AND company_name = :company_name LIMIT 1' ); $insert = $pdo->prepare(<<<'SQL' INSERT INTO company_plan_rows ( company_id, sequence_no, company_name, company_type, taxpayer_type, registered_at, business_registration_type, unified_social_credit_code, plan, company_status, tax_cancellation, business_cancellation, bank_cancellation, notes, created_by, updated_by, created_at, updated_at ) VALUES ( :company_id, :sequence_no, :company_name, :company_type, :taxpayer_type, :registered_at, :business_registration_type, :unified_social_credit_code, :plan, :company_status, :tax_cancellation, :business_cancellation, :bank_cancellation, :notes, :created_by, :updated_by, :created_at, :updated_at ) SQL); $update = $pdo->prepare(<<<'SQL' UPDATE company_plan_rows SET sequence_no = :sequence_no, company_name = :company_name, company_type = :company_type, taxpayer_type = :taxpayer_type, registered_at = :registered_at, business_registration_type = :business_registration_type, unified_social_credit_code = :unified_social_credit_code, plan = :plan, company_status = :company_status, tax_cancellation = :tax_cancellation, business_cancellation = :business_cancellation, bank_cancellation = :bank_cancellation, notes = :notes, updated_by = :updated_by, updated_at = :updated_at WHERE company_id = :company_id AND id = :id SQL); $now = now()->format('Y-m-d H:i:s'); foreach ($rows as $row) { $companyName = trim((string) ($row['company_name'] ?? '')); if ($companyName === '') { $skipped++; continue; } $values = $this->normalizeMutableData($row); $lookup->execute([':company_id' => $companyId, ':company_name' => $companyName]); $existingId = $lookup->fetchColumn(); if ($existingId !== false) { if ($duplicateMode === 'skip') { $skipped++; continue; } $update->execute([ ':company_id' => $companyId, ':id' => (int) $existingId, ...$this->importBindingParams($values), ':updated_by' => $userId, ':updated_at' => $now, ]); $updated++; continue; } $insert->execute([ ':company_id' => $companyId, ...$this->importBindingParams($values), ':created_by' => $userId, ':updated_by' => $userId, ':created_at' => $now, ':updated_at' => $now, ]); $created++; } $pdo->commit(); } catch (\Throwable $exception) { if ($pdo->inTransaction()) { $pdo->rollBack(); } throw $exception; } return compact('created', 'updated', 'skipped'); } public function normalizeCompanyName(string $name): string { return mb_strtolower(preg_replace('/\s+/u', '', trim($name)) ?? trim($name)); } private function ensureSchema(PDO $pdo): void { $pdo->exec(<<<'SQL' CREATE TABLE IF NOT EXISTS company_plan_rows ( id INTEGER PRIMARY KEY AUTOINCREMENT, company_id INTEGER NOT NULL, sequence_no INTEGER, company_name TEXT NOT NULL, company_type TEXT, taxpayer_type TEXT, registered_at TEXT, business_registration_type TEXT, unified_social_credit_code TEXT, plan TEXT, company_status TEXT, tax_cancellation TEXT, business_cancellation TEXT, bank_cancellation TEXT, notes TEXT, created_by INTEGER, updated_by INTEGER, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, UNIQUE (company_id, company_name) ) SQL); $pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_rows_company_plan_index ON company_plan_rows (company_id, plan)'); $pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_rows_company_status_index ON company_plan_rows (company_id, company_status)'); $pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_rows_company_type_index ON company_plan_rows (company_id, company_type)'); $pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_rows_company_tax_index ON company_plan_rows (company_id, taxpayer_type)'); $pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_rows_company_sequence_index ON company_plan_rows (company_id, sequence_no)'); // 类型口径归一:把存量“个体户”改写为“个体工商户”,幂等执行。 $pdo->exec( "UPDATE company_plan_rows SET company_type = '个体工商户' " . "WHERE company_type IS NOT NULL AND TRIM(COALESCE(company_type, '')) = '个体户'" ); // 公司状态口径归一:把存量“注销”改写为“已注销”,幂等执行。 $pdo->exec( "UPDATE company_plan_rows SET company_status = '已注销' " . "WHERE company_status IS NOT NULL AND TRIM(COALESCE(company_status, '')) = '注销'" ); } /** * @param array $filters * @return array{0:string,1:array} */ private function where(int $companyId, array $filters): array { $where = ['company_id = :company_id']; $params = [':company_id' => $companyId]; $keyword = trim((string) ($filters['keyword'] ?? '')); if ($keyword !== '') { $where[] = "(company_name LIKE :keyword ESCAPE '!' OR unified_social_credit_code LIKE :keyword ESCAPE '!')"; $params[':keyword'] = '%' . $this->escapeLike($keyword) . '%'; } foreach (['plan', 'company_status', 'company_type', 'taxpayer_type', 'business_registration_type'] as $field) { $value = trim((string) ($filters[$field] ?? '')); if ($value !== '') { $where[] = "{$field} = :{$field}"; $params[':' . $field] = $value; } } $remarkKeyword = trim((string) ($filters['remark_keyword'] ?? '')); if ($remarkKeyword !== '') { $where[] = "COALESCE(notes, '') LIKE :remark_keyword ESCAPE '!'"; $params[':remark_keyword'] = '%' . $this->escapeLike($remarkKeyword) . '%'; } $remarkState = (string) ($filters['remark_state'] ?? ''); if ($remarkState === 'filled') { $where[] = "TRIM(COALESCE(notes, '')) <> ''"; } elseif ($remarkState === 'empty') { $where[] = "TRIM(COALESCE(notes, '')) = ''"; } return ['WHERE ' . implode(' AND ', $where), $params]; } private function escapeLike(string $value): string { return str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $value); } private function safeSort(string $sort): string { return in_array($sort, self::MUTABLE_FIELDS, true) ? $sort : 'sequence_no'; } /** @return list */ private function distinctValues(int $companyId, string $field): array { if (! in_array($field, self::MUTABLE_FIELDS, true)) { return []; } $statement = $this->pdo()->prepare( "SELECT DISTINCT TRIM({$field}) AS value FROM company_plan_rows " . "WHERE company_id = :company_id AND {$field} IS NOT NULL AND TRIM({$field}) <> '' " . "ORDER BY value COLLATE NOCASE" ); $statement->execute([':company_id' => $companyId]); $values = array_values(array_filter(array_map( static fn (mixed $value): string => trim((string) $value), $statement->fetchAll(PDO::FETCH_COLUMN) ), static fn (string $value): bool => $value !== '')); if ($field === 'company_type') { $values = array_values(array_unique(array_map( static fn (string $value): string => self::COMPANY_TYPE_ALIASES[$value] ?? $value, $values ))); } if (isset(self::FIELD_ALIASES[$field])) { $aliases = self::FIELD_ALIASES[$field]; $values = array_values(array_unique(array_map( static fn (string $value): string => $aliases[$value] ?? $value, $values ))); } return $values; } /** * @param array $data * @return array */ private function normalizeMutableData(array $data): array { $values = []; foreach (self::MUTABLE_FIELDS as $field) { $value = $data[$field] ?? null; if (is_string($value)) { $value = trim($value); } $values[$field] = $value === '' ? null : $value; } if (isset($values['sequence_no']) && is_numeric($values['sequence_no'])) { $values['sequence_no'] = (int) $values['sequence_no']; } if (isset($values['company_type']) && is_string($values['company_type'])) { $values['company_type'] = self::COMPANY_TYPE_ALIASES[$values['company_type']] ?? $values['company_type']; } if (isset($values['company_status']) && is_string($values['company_status'])) { $values['company_status'] = self::COMPANY_STATUS_ALIASES[$values['company_status']] ?? $values['company_status']; } return $values; } /** * @param array $values * @return array */ private function importBindingParams(array $values): array { $params = []; foreach (self::MUTABLE_FIELDS as $field) { $params[':' . $field] = $values[$field] ?? null; } return $params; } }