444 lines
16 KiB
PHP
444 lines
16 KiB
PHP
<?php
|
||
|
||
namespace App\Business\CompanyPlan;
|
||
|
||
use PDO;
|
||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
|
||
use RuntimeException;
|
||
use Throwable;
|
||
|
||
/**
|
||
* 主体关联的「未完结店铺」数据层。
|
||
*
|
||
* 数据来自资产盘点工作簿里两张未完结店铺明细表(Sheet3 / Sheet6),
|
||
* 按公司名称与 company_plan_rows 关联,供公司盘点页面展示与跳转。
|
||
*/
|
||
class CompanyPlanShopRepository
|
||
{
|
||
/** 页面展示的字段顺序。 */
|
||
public const FIELDS = [
|
||
['name' => 'shop_name', 'label' => '店铺名称'],
|
||
['name' => 'company_name', 'label' => '所属主体'],
|
||
['name' => 'shop_status', 'label' => '店铺状态'],
|
||
['name' => 'profit_center', 'label' => '利润中心'],
|
||
['name' => 'owner', 'label' => '店铺负责人'],
|
||
['name' => 'opened_on', 'label' => '开店时间'],
|
||
['name' => 'successor', 'label' => '接替主体'],
|
||
['name' => 'source_sheet', 'label' => '来源'],
|
||
];
|
||
|
||
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_shops (
|
||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
company_id INTEGER NOT NULL,
|
||
plan_row_id INTEGER,
|
||
company_name TEXT NOT NULL,
|
||
shop_name TEXT NOT NULL,
|
||
shop_status TEXT,
|
||
profit_center TEXT,
|
||
owner TEXT,
|
||
opened_on TEXT,
|
||
successor TEXT,
|
||
source_sheet TEXT,
|
||
created_at TEXT NOT NULL,
|
||
updated_at TEXT NOT NULL,
|
||
UNIQUE (company_id, shop_name)
|
||
)
|
||
SQL);
|
||
$pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_shops_company_index ON company_plan_shops (company_id, company_name)');
|
||
$pdo->exec('CREATE INDEX IF NOT EXISTS company_plan_shops_status_index ON company_plan_shops (company_id, shop_status)');
|
||
|
||
// 备注口径归一:有未完结店铺的规划注销主体统一显示“关联店铺未办结”,幂等执行。
|
||
$pdo->exec(
|
||
"UPDATE company_plan_rows SET notes = '关联店铺未办结' "
|
||
. "WHERE TRIM(COALESCE(plan, '')) = '注销' "
|
||
. "AND TRIM(COALESCE(company_status, '')) = '正常' "
|
||
. "AND notes LIKE '存在未完结店铺%' "
|
||
. "AND EXISTS ("
|
||
. "SELECT 1 FROM company_plan_shops AS shops "
|
||
. "WHERE shops.company_id = company_plan_rows.company_id "
|
||
. "AND shops.company_name = company_plan_rows.company_name"
|
||
. ")"
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 从资产盘点工作簿导入未完结店铺。
|
||
*
|
||
* @return array{sheets:array<string,int>,imported:int,linked:int,skipped: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);
|
||
|
||
$shops = [];
|
||
$sheetStats = [];
|
||
|
||
// 未完结店铺明细固定在工作簿的 Sheet3 与 Sheet6;
|
||
// 「店铺基础资料」等表结构相近但口径不同,不能混入。
|
||
$sheets = array_values(array_filter(
|
||
$book->getAllSheets(),
|
||
static fn ($sheet): bool => preg_match('/^sheet\s*[36]$/i', trim((string) $sheet->getTitle())) === 1,
|
||
));
|
||
if ($sheets === []) {
|
||
$sheets = $book->getAllSheets();
|
||
}
|
||
|
||
foreach ($sheets as $sheet) {
|
||
$rows = $sheet->toArray(null, true, false, false);
|
||
$layout = $this->detectLayout($rows);
|
||
|
||
if ($layout === null) {
|
||
continue;
|
||
}
|
||
|
||
$count = 0;
|
||
foreach (array_slice($rows, $layout['header_row'] + 1) as $row) {
|
||
$shop = $this->cell($row, $layout['columns']['shop']);
|
||
if ($shop === '') {
|
||
continue;
|
||
}
|
||
|
||
$company = $this->cell($row, $layout['columns']['company']);
|
||
$key = $this->normalizeName($company) . '|' . $shop;
|
||
$shops[$key] = [
|
||
'shop_name' => $shop,
|
||
'company_name' => $company,
|
||
'shop_status' => $this->cell($row, $layout['columns']['status']),
|
||
'profit_center' => $this->cell($row, $layout['columns']['center']),
|
||
'owner' => $this->cell($row, $layout['columns']['owner']),
|
||
'opened_on' => $this->dateCell($row, $layout['columns']['opened']),
|
||
'successor' => $this->cell($row, $layout['columns']['successor']),
|
||
'source_sheet' => $sheet->getTitle(),
|
||
];
|
||
$count++;
|
||
}
|
||
|
||
if ($count > 0) {
|
||
$sheetStats[$sheet->getTitle()] = $count;
|
||
}
|
||
}
|
||
|
||
$planRows = [];
|
||
$statement = $this->pdo()->prepare('SELECT id, company_name FROM company_plan_rows WHERE company_id = ?');
|
||
$statement->execute([$companyId]);
|
||
foreach ($statement->fetchAll() as $row) {
|
||
$planRows[$this->normalizeName((string) $row['company_name'])] = [
|
||
'id' => (int) $row['id'],
|
||
'name' => (string) $row['company_name'],
|
||
];
|
||
}
|
||
|
||
$pdo = $this->pdo();
|
||
$pdo->beginTransaction();
|
||
|
||
try {
|
||
$delete = $pdo->prepare('DELETE FROM company_plan_shops WHERE company_id = ?');
|
||
$delete->execute([$companyId]);
|
||
|
||
$insert = $pdo->prepare(<<<'SQL'
|
||
INSERT INTO company_plan_shops
|
||
(company_id, plan_row_id, company_name, shop_name, shop_status, profit_center, owner, opened_on, successor, source_sheet, created_at, updated_at)
|
||
VALUES
|
||
(:company_id, :plan_row_id, :company_name, :shop_name, :shop_status, :profit_center, :owner, :opened_on, :successor, :source_sheet, :created_at, :updated_at)
|
||
SQL);
|
||
|
||
$imported = 0;
|
||
$linked = 0;
|
||
$now = now()->toDateTimeString();
|
||
|
||
foreach ($shops as $shop) {
|
||
$match = $planRows[$this->normalizeName($shop['company_name'])] ?? null;
|
||
if ($match !== null) {
|
||
$linked++;
|
||
}
|
||
$insert->execute([
|
||
':company_id' => $companyId,
|
||
':plan_row_id' => $match['id'] ?? null,
|
||
':company_name' => $match['name'] ?? $shop['company_name'],
|
||
':shop_name' => mb_substr($shop['shop_name'], 0, 255),
|
||
':shop_status' => $shop['shop_status'] !== '' ? mb_substr($shop['shop_status'], 0, 64) : null,
|
||
':profit_center' => $shop['profit_center'] !== '' ? mb_substr($shop['profit_center'], 0, 128) : null,
|
||
':owner' => $shop['owner'] !== '' ? mb_substr($shop['owner'], 0, 128) : null,
|
||
':opened_on' => $shop['opened_on'],
|
||
':successor' => $shop['successor'] !== '' ? mb_substr($shop['successor'], 0, 255) : null,
|
||
':source_sheet' => $shop['source_sheet'],
|
||
':created_at' => $now,
|
||
':updated_at' => $now,
|
||
]);
|
||
$imported++;
|
||
}
|
||
|
||
$pdo->commit();
|
||
|
||
return [
|
||
'sheets' => $sheetStats,
|
||
'imported' => $imported,
|
||
'linked' => $linked,
|
||
'skipped' => count($shops) - $imported,
|
||
];
|
||
} catch (Throwable $exception) {
|
||
$pdo->rollBack();
|
||
throw $exception;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 通过表头识别未完结店铺明细表,返回表头行号与列映射。
|
||
*
|
||
* @param list<array<int,mixed>> $rows
|
||
* @return array{header_row:int,columns:array<string,int>}|null
|
||
*/
|
||
private function detectLayout(array $rows): ?array
|
||
{
|
||
foreach (array_slice($rows, 0, 6, true) as $index => $row) {
|
||
$labels = [];
|
||
foreach ($row as $column => $value) {
|
||
$label = preg_replace('/\s+/u', '', (string) $value);
|
||
if ($label !== '') {
|
||
// 同名表头取后出现的列(Sheet3 的“状态”第二次出现才是店铺状态)。
|
||
$labels[$label] = $column;
|
||
}
|
||
}
|
||
|
||
$shop = $labels['ERP系统店铺名称'] ?? $labels['店铺名称'] ?? null;
|
||
$company = $labels['主体'] ?? $labels['公司名称'] ?? null;
|
||
if ($shop === null || $company === null) {
|
||
continue;
|
||
}
|
||
|
||
return [
|
||
'header_row' => $index,
|
||
'columns' => [
|
||
'shop' => $shop,
|
||
'company' => $company,
|
||
'status' => $labels['店铺状态'] ?? $labels['状态'] ?? $shop,
|
||
'center' => $labels['利润中心'] ?? $labels['店铺所属利润中心'] ?? $shop,
|
||
'owner' => $labels['店铺负责人'] ?? $labels['负责人'] ?? $shop,
|
||
'opened' => $labels['开店时间'] ?? $shop,
|
||
'successor' => $labels['新主体'] ?? $labels['接替主体'] ?? $shop,
|
||
],
|
||
];
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/** @param array<int,mixed> $row */
|
||
private function cell(array $row, int $column): string
|
||
{
|
||
$value = $row[$column] ?? null;
|
||
if ($value === null) {
|
||
return '';
|
||
}
|
||
|
||
return trim(str_replace("\u{00A0}", ' ', (string) $value));
|
||
}
|
||
|
||
/** @param array<int,mixed> $row */
|
||
private function dateCell(array $row, int $column): ?string
|
||
{
|
||
$value = $row[$column] ?? null;
|
||
if ($value === null || $value === '') {
|
||
return null;
|
||
}
|
||
|
||
if (is_numeric($value)) {
|
||
try {
|
||
return ExcelDate::excelToDateTimeObject((float) $value)->format('Y-m-d');
|
||
} catch (Throwable $exception) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
$text = trim((string) $value);
|
||
|
||
return $text === '' ? null : mb_substr($text, 0, 32);
|
||
}
|
||
|
||
private function normalizeName(string $name): string
|
||
{
|
||
$normalized = preg_replace('/[\s\x{00A0}\x{3000}]+/u', '', $name) ?? $name;
|
||
|
||
return str_replace(['(', ')'], ['(', ')'], $normalized);
|
||
}
|
||
|
||
/**
|
||
* @param array{shop_keyword?:string,shop_status?:string,shop_company?:string} $filters
|
||
* @return array{rows:list<array<string,mixed>>,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);
|
||
$pdo = $this->pdo();
|
||
|
||
$countStatement = $pdo->prepare("SELECT COUNT(*) FROM company_plan_shops {$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;
|
||
|
||
$statement = $pdo->prepare(
|
||
"SELECT * FROM company_plan_shops {$whereSql} "
|
||
. 'ORDER BY company_name ASC, shop_name ASC LIMIT :limit OFFSET :offset'
|
||
);
|
||
foreach ($params as $key => $value) {
|
||
$statement->bindValue($key, $value);
|
||
}
|
||
$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{shop_keyword?:string,shop_status?:string,shop_company?:string} $filters
|
||
* @return array{0:string,1:array<string,mixed>}
|
||
*/
|
||
private function where(int $companyId, array $filters): array
|
||
{
|
||
$clauses = ['company_id = :company_id'];
|
||
$params = [':company_id' => $companyId];
|
||
|
||
$status = trim((string) ($filters['shop_status'] ?? ''));
|
||
if ($status !== '') {
|
||
$clauses[] = 'shop_status = :shop_status';
|
||
$params[':shop_status'] = $status;
|
||
}
|
||
|
||
$company = trim((string) ($filters['shop_company'] ?? ''));
|
||
if ($company !== '') {
|
||
$clauses[] = "REPLACE(REPLACE(company_name, '(', '('), ')', ')') = :shop_company";
|
||
$params[':shop_company'] = str_replace(['(', ')'], ['(', ')'], $company);
|
||
}
|
||
|
||
$keyword = trim((string) ($filters['shop_keyword'] ?? ''));
|
||
if ($keyword !== '') {
|
||
$clauses[] = '(shop_name LIKE :shop_keyword_shop OR company_name LIKE :shop_keyword_company)';
|
||
$params[':shop_keyword_shop'] = '%' . $keyword . '%';
|
||
$params[':shop_keyword_company'] = '%' . $keyword . '%';
|
||
}
|
||
|
||
return ['WHERE ' . implode(' AND ', $clauses), $params];
|
||
}
|
||
|
||
/**
|
||
* @param array{shop_keyword?:string,shop_status?:string,shop_company?:string} $filters
|
||
* @return array{total:int,companies:int,statuses:array<string,int>}
|
||
*/
|
||
public function summary(int $companyId, array $filters = []): array
|
||
{
|
||
[$whereSql, $params] = $this->where($companyId, $filters);
|
||
$pdo = $this->pdo();
|
||
|
||
$statement = $pdo->prepare("SELECT COUNT(*) AS total, COUNT(DISTINCT company_name) AS companies FROM company_plan_shops {$whereSql}");
|
||
$statement->execute($params);
|
||
$row = $statement->fetch() ?: [];
|
||
|
||
$statuses = [];
|
||
$statusStatement = $pdo->prepare(
|
||
"SELECT COALESCE(NULLIF(TRIM(shop_status), ''), '未标注') AS status, COUNT(*) AS n "
|
||
. "FROM company_plan_shops {$whereSql} GROUP BY status ORDER BY n DESC"
|
||
);
|
||
$statusStatement->execute($params);
|
||
foreach ($statusStatement->fetchAll() as $statusRow) {
|
||
$statuses[(string) $statusRow['status']] = (int) $statusRow['n'];
|
||
}
|
||
|
||
return [
|
||
'total' => (int) ($row['total'] ?? 0),
|
||
'companies' => (int) ($row['companies'] ?? 0),
|
||
'statuses' => $statuses,
|
||
];
|
||
}
|
||
|
||
/** @return list<array<string,mixed>> */
|
||
public function allShopReferences(int $companyId): array
|
||
{
|
||
$statement = $this->pdo()->prepare(
|
||
'SELECT shop_name, company_name, successor '
|
||
. 'FROM company_plan_shops WHERE company_id = :company_id ORDER BY id'
|
||
);
|
||
$statement->execute([':company_id' => $companyId]);
|
||
|
||
return $statement->fetchAll();
|
||
}
|
||
|
||
/**
|
||
* 每个主体下的未完结店铺数量,用于主表徽章与跳转。
|
||
*
|
||
* @return array<string,int> 键为归一化后的公司名称
|
||
*/
|
||
public function countsByCompany(int $companyId): array
|
||
{
|
||
$statement = $this->pdo()->prepare(
|
||
'SELECT company_name, COUNT(*) AS n FROM company_plan_shops WHERE company_id = ? GROUP BY company_name'
|
||
);
|
||
$statement->execute([$companyId]);
|
||
|
||
$counts = [];
|
||
foreach ($statement->fetchAll() as $row) {
|
||
$name = (string) $row['company_name'];
|
||
$counts[$name] = (int) $row['n'];
|
||
$counts[$this->normalizeName($name)] = (int) $row['n'];
|
||
}
|
||
|
||
return $counts;
|
||
}
|
||
|
||
/** @return list<string> */
|
||
public function statusOptions(int $companyId): array
|
||
{
|
||
$statement = $this->pdo()->prepare(
|
||
"SELECT DISTINCT TRIM(shop_status) AS status FROM company_plan_shops "
|
||
. "WHERE company_id = ? AND TRIM(COALESCE(shop_status, '')) <> '' ORDER BY status"
|
||
);
|
||
$statement->execute([$companyId]);
|
||
|
||
return array_values(array_map(static fn (array $row): string => (string) $row['status'], $statement->fetchAll()));
|
||
}
|
||
}
|