feat(shopro_huifu): 添加全国联行号导入功能 新增全国联行号导入命令行工具,支持从多种数据源导入银行支行信息: - 支持导入内置种子数据(约120条主要城市数据) - 支持自动下载全国CSV文件(约20MB,来自gweesin/CNAPS) - 支持手动指定文件导入 - 提供多种操作选项:清空重导、批量导入、试运行等 更新README文档,详细说明联行号导入的使用方法和操作步骤, 包括命令示例和参数说明。 扩展bank_branches.json数据文件,添加全国主要城市的银行支行信息, 涵盖工农中建交招等主要银行在各省会城市的分支机构。 添加.gitignore规则,忽略CSV数据文件的版本控制。 ```
493 行
16 KiB
PHP
493 行
16 KiB
PHP
<?php
|
|
|
|
namespace addons\shopro_huifu\library\onboard;
|
|
|
|
use think\Db;
|
|
|
|
class HuifuOnboardBankBranchImporter
|
|
{
|
|
protected static $areaNameMap;
|
|
|
|
/**
|
|
* @return array{inserted:int,updated:int,skipped:int,total:int}
|
|
*/
|
|
public static function importFile($file, array $options = [])
|
|
{
|
|
$file = (string) $file;
|
|
if (!is_file($file)) {
|
|
throw new \InvalidArgumentException('文件不存在: ' . $file);
|
|
}
|
|
|
|
$format = strtolower((string) ($options['format'] ?? 'auto'));
|
|
if ($format === 'auto') {
|
|
$format = self::detectFormat($file);
|
|
}
|
|
|
|
$limit = max(0, (int) ($options['limit'] ?? 0));
|
|
$batch = max(50, min(2000, (int) ($options['batch'] ?? 500)));
|
|
$dryRun = !empty($options['dry_run']);
|
|
$truncate = !empty($options['truncate']);
|
|
|
|
if ($truncate && !$dryRun) {
|
|
Db::name('shopro_huifu_bank_branch')->where('id', '>', 0)->delete();
|
|
}
|
|
|
|
$rows = $format === 'json'
|
|
? self::parseJsonFile($file, $limit)
|
|
: self::parseCsvFile($file, $limit);
|
|
|
|
$inserted = 0;
|
|
$updated = 0;
|
|
$skipped = 0;
|
|
$buffer = [];
|
|
|
|
foreach ($rows as $row) {
|
|
$normalized = self::normalizeRow($row);
|
|
if (!$normalized) {
|
|
$skipped++;
|
|
continue;
|
|
}
|
|
$buffer[] = $normalized;
|
|
if (count($buffer) >= $batch) {
|
|
$stats = self::flushBuffer($buffer, $dryRun);
|
|
$inserted += $stats['inserted'];
|
|
$updated += $stats['updated'];
|
|
$buffer = [];
|
|
}
|
|
}
|
|
|
|
if ($buffer) {
|
|
$stats = self::flushBuffer($buffer, $dryRun);
|
|
$inserted += $stats['inserted'];
|
|
$updated += $stats['updated'];
|
|
}
|
|
|
|
return [
|
|
'inserted' => $inserted,
|
|
'updated' => $updated,
|
|
'skipped' => $skipped,
|
|
'total' => $inserted + $updated,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @return array{inserted:int,updated:int,skipped:int,total:int}
|
|
*/
|
|
public static function importSeedJson($jsonFile = null, array $options = [])
|
|
{
|
|
$jsonFile = $jsonFile ?: (ADDON_PATH . 'shopro_huifu/data/bank_branches.json');
|
|
return self::importFile($jsonFile, array_merge(['format' => 'json'], $options));
|
|
}
|
|
|
|
public static function downloadCnapsCsv($dest = null)
|
|
{
|
|
$dest = $dest ?: (ADDON_PATH . 'shopro_huifu/data/cnaps.csv');
|
|
$dir = dirname($dest);
|
|
if (!is_dir($dir)) {
|
|
mkdir($dir, 0755, true);
|
|
}
|
|
|
|
$urls = [
|
|
'https://hf-mirror.com/datasets/gweesin/CNAPS/resolve/main/cnaps.csv',
|
|
'https://huggingface.co/datasets/gweesin/CNAPS/resolve/main/cnaps.csv',
|
|
];
|
|
|
|
$lastError = '';
|
|
foreach ($urls as $url) {
|
|
try {
|
|
self::downloadToFile($url, $dest);
|
|
if (is_file($dest) && filesize($dest) > 1024) {
|
|
return $dest;
|
|
}
|
|
} catch (\Throwable $e) {
|
|
$lastError = $e->getMessage();
|
|
}
|
|
}
|
|
|
|
throw new \RuntimeException('下载全国联行号 CSV 失败,请手动下载后指定 --file。' . ($lastError ? ' ' . $lastError : ''));
|
|
}
|
|
|
|
public static function exportJson($dest, $limit = 0)
|
|
{
|
|
$dest = (string) $dest;
|
|
$limit = max(0, (int) $limit);
|
|
$query = Db::name('shopro_huifu_bank_branch')->where('status', 1)->order('id', 'asc');
|
|
if ($limit > 0) {
|
|
$query->limit($limit);
|
|
}
|
|
$list = $query->select();
|
|
$rows = [];
|
|
foreach ($list ?: [] as $item) {
|
|
$row = [
|
|
'branch_code' => (string) $item['branch_code'],
|
|
'branch_name' => (string) $item['branch_name'],
|
|
];
|
|
if (!empty($item['bank_name'])) {
|
|
$row['bank_name'] = (string) $item['bank_name'];
|
|
}
|
|
if (!empty($item['prov_id'])) {
|
|
$row['prov_id'] = (string) $item['prov_id'];
|
|
}
|
|
if (!empty($item['area_id'])) {
|
|
$row['area_id'] = (string) $item['area_id'];
|
|
}
|
|
$rows[] = $row;
|
|
}
|
|
|
|
$json = json_encode($rows, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
|
if ($json === false) {
|
|
throw new \RuntimeException('导出 JSON 失败');
|
|
}
|
|
file_put_contents($dest, $json . "\n");
|
|
return count($rows);
|
|
}
|
|
|
|
protected static function detectFormat($file)
|
|
{
|
|
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
|
|
if ($ext === 'json') {
|
|
return 'json';
|
|
}
|
|
return 'csv';
|
|
}
|
|
|
|
protected static function parseJsonFile($file, $limit = 0)
|
|
{
|
|
$decoded = json_decode(file_get_contents($file), true);
|
|
if (!is_array($decoded)) {
|
|
throw new \InvalidArgumentException('JSON 格式无效: ' . $file);
|
|
}
|
|
if ($limit > 0) {
|
|
return array_slice($decoded, 0, $limit);
|
|
}
|
|
return $decoded;
|
|
}
|
|
|
|
protected static function parseCsvFile($file, $limit = 0)
|
|
{
|
|
$handle = fopen($file, 'rb');
|
|
if (!$handle) {
|
|
throw new \RuntimeException('无法读取 CSV: ' . $file);
|
|
}
|
|
|
|
$header = null;
|
|
$rows = [];
|
|
while (($line = fgetcsv($handle)) !== false) {
|
|
if (!$line || self::isEmptyCsvLine($line)) {
|
|
continue;
|
|
}
|
|
if ($header === null) {
|
|
$header = self::normalizeHeader($line);
|
|
continue;
|
|
}
|
|
$assoc = self::mapCsvLine($header, $line);
|
|
if ($assoc) {
|
|
$rows[] = $assoc;
|
|
}
|
|
if ($limit > 0 && count($rows) >= $limit) {
|
|
break;
|
|
}
|
|
}
|
|
fclose($handle);
|
|
return $rows;
|
|
}
|
|
|
|
protected static function normalizeHeader(array $header)
|
|
{
|
|
$map = [];
|
|
foreach ($header as $idx => $name) {
|
|
$key = self::normalizeHeaderKey($name);
|
|
if ($key !== '') {
|
|
$map[$idx] = $key;
|
|
}
|
|
}
|
|
return $map;
|
|
}
|
|
|
|
protected static function normalizeHeaderKey($name)
|
|
{
|
|
$name = trim((string) $name);
|
|
if ($name === '') {
|
|
return '';
|
|
}
|
|
$lower = strtolower($name);
|
|
$aliases = [
|
|
'branch_code' => ['branch_code', 'bankid', 'cnaps', 'cnapscode', '联行号', '行号', '开户行联行号', '大额支付行号'],
|
|
'branch_name' => ['branch_name', 'lname', 'banknamebranch', '支行名称', '开户行', '开户行支行名称', '支行全称', '网点名称'],
|
|
'bank_name' => ['bank_name', 'bankname', 'banknamemain', '银行', '银行名称', '银行简称', '总行名称'],
|
|
'province' => ['province', 'provincename', 'areaprovince', '省份', '省'],
|
|
'city' => ['city', 'cityname', 'areacity', '城市', '市', '地区'],
|
|
'prov_id' => ['prov_id', 'provincecode', '省码'],
|
|
'area_id' => ['area_id', 'citycode', '市码'],
|
|
];
|
|
foreach ($aliases as $canonical => $list) {
|
|
if (in_array($lower, $list, true) || in_array($name, $list, true)) {
|
|
return $canonical;
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
protected static function mapCsvLine(array $header, array $line)
|
|
{
|
|
$row = [];
|
|
foreach ($header as $idx => $key) {
|
|
if (!array_key_exists($idx, $line)) {
|
|
continue;
|
|
}
|
|
$row[$key] = trim((string) $line[$idx]);
|
|
}
|
|
return $row;
|
|
}
|
|
|
|
protected static function isEmptyCsvLine(array $line)
|
|
{
|
|
foreach ($line as $cell) {
|
|
if (trim((string) $cell) !== '') {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
protected static function normalizeRow(array $row)
|
|
{
|
|
$branchCode = self::normalizeBranchCode(
|
|
$row['branch_code'] ?? ($row['BankId'] ?? ($row['cnapsCode'] ?? ''))
|
|
);
|
|
$branchName = trim((string) ($row['branch_name'] ?? ($row['LName'] ?? '')));
|
|
if ($branchCode === '' || $branchName === '') {
|
|
return null;
|
|
}
|
|
|
|
$bankName = trim((string) ($row['bank_name'] ?? ($row['BankName'] ?? '')));
|
|
if ($bankName === '') {
|
|
$bankName = self::guessBankName($branchName);
|
|
}
|
|
|
|
$provId = HuifuOnboardAreaHelper::toCode($row['prov_id'] ?? '');
|
|
$areaId = HuifuOnboardAreaHelper::toCode($row['area_id'] ?? '');
|
|
|
|
$province = trim((string) ($row['province'] ?? ($row['ProvinceName'] ?? '')));
|
|
$city = trim((string) ($row['city'] ?? ($row['CityName'] ?? '')));
|
|
|
|
if ($provId === '' && !empty($row['ProvinceCode'])) {
|
|
$provId = self::provinceCodeToAdmin((string) $row['ProvinceCode']);
|
|
}
|
|
|
|
if ($provId === '' && $province !== '') {
|
|
$provId = self::lookupAreaId($province, 1);
|
|
}
|
|
if ($areaId === '' && $city !== '') {
|
|
$areaId = self::lookupAreaId($city, 2, $provId);
|
|
}
|
|
if ($provId === '' && $areaId !== '') {
|
|
$provId = substr($areaId, 0, 2) . '0000';
|
|
}
|
|
|
|
return [
|
|
'branch_code' => $branchCode,
|
|
'branch_name' => $branchName,
|
|
'bank_name' => $bankName,
|
|
'prov_id' => $provId,
|
|
'area_id' => $areaId,
|
|
'status' => 1,
|
|
];
|
|
}
|
|
|
|
protected static function normalizeBranchCode($code)
|
|
{
|
|
$code = preg_replace('/\D+/', '', (string) $code);
|
|
if ($code === '') {
|
|
return '';
|
|
}
|
|
if (strlen($code) < 8 || strlen($code) > 20) {
|
|
return '';
|
|
}
|
|
if (strlen($code) < 12) {
|
|
$code = str_pad($code, 12, '0', STR_PAD_LEFT);
|
|
}
|
|
return $code;
|
|
}
|
|
|
|
protected static function provinceCodeToAdmin($code)
|
|
{
|
|
$code = preg_replace('/\D+/', '', (string) $code);
|
|
if ($code === '') {
|
|
return '';
|
|
}
|
|
if (strlen($code) >= 6) {
|
|
return substr($code, 0, 2) . '0000';
|
|
}
|
|
return str_pad($code, 2, '0', STR_PAD_LEFT) . '0000';
|
|
}
|
|
|
|
protected static function guessBankName($branchName)
|
|
{
|
|
$rules = [
|
|
'工商银行' => '工商银行',
|
|
'农业银行' => '农业银行',
|
|
'中国银行' => '中国银行',
|
|
'建设银行' => '建设银行',
|
|
'交通银行' => '交通银行',
|
|
'招商银行' => '招商银行',
|
|
'浦发银行' => '浦发银行',
|
|
'民生银行' => '民生银行',
|
|
'光大银行' => '光大银行',
|
|
'兴业银行' => '兴业银行',
|
|
'平安银行' => '平安银行',
|
|
'中信银行' => '中信银行',
|
|
'华夏银行' => '华夏银行',
|
|
'广发银行' => '广发银行',
|
|
'邮储银行' => '邮储银行',
|
|
'邮政储蓄' => '邮储银行',
|
|
];
|
|
foreach ($rules as $needle => $short) {
|
|
if (mb_strpos($branchName, $needle, 0, 'UTF-8') !== false) {
|
|
return $short;
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
protected static function lookupAreaId($name, $level, $provId = '')
|
|
{
|
|
self::loadAreaNameMap();
|
|
$key = self::areaCacheKey($name, $level, $provId);
|
|
if (isset(self::$areaNameMap[$key])) {
|
|
return (string) self::$areaNameMap[$key];
|
|
}
|
|
|
|
$candidates = self::areaNameCandidates($name);
|
|
foreach ($candidates as $candidate) {
|
|
$tryKey = self::areaCacheKey($candidate, $level, $provId);
|
|
if (isset(self::$areaNameMap[$tryKey])) {
|
|
return (string) self::$areaNameMap[$tryKey];
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
protected static function loadAreaNameMap()
|
|
{
|
|
if (self::$areaNameMap !== null) {
|
|
return;
|
|
}
|
|
self::$areaNameMap = [];
|
|
try {
|
|
$rows = Db::name('shopro_area')->where('level', 'in', [1, 2])->field('id,name,pid,level')->select();
|
|
} catch (\Throwable $e) {
|
|
return;
|
|
}
|
|
foreach ($rows ?: [] as $row) {
|
|
$id = (string) $row['id'];
|
|
$level = (int) $row['level'];
|
|
$pid = (string) ($row['pid'] ?? '');
|
|
$provId = $level === 2 ? (substr($id, 0, 2) . '0000') : '';
|
|
foreach (self::areaNameCandidates($row['name']) as $candidate) {
|
|
$key = self::areaCacheKey($candidate, $level, $level === 2 ? $provId : '');
|
|
if (!isset(self::$areaNameMap[$key])) {
|
|
self::$areaNameMap[$key] = $id;
|
|
}
|
|
if ($level === 2 && $pid !== '' && $pid !== '0') {
|
|
$parentKey = self::areaCacheKey($candidate, $level, (string) $pid);
|
|
if (!isset(self::$areaNameMap[$parentKey])) {
|
|
self::$areaNameMap[$parentKey] = $id;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
protected static function areaNameCandidates($name)
|
|
{
|
|
$name = trim((string) $name);
|
|
if ($name === '') {
|
|
return [];
|
|
}
|
|
$list = [$name];
|
|
$stripped = preg_replace('/(省|市|自治区|壮族|回族|维吾尔|特别行政区)$/u', '', $name);
|
|
if ($stripped && $stripped !== $name) {
|
|
$list[] = $stripped;
|
|
}
|
|
return array_values(array_unique($list));
|
|
}
|
|
|
|
protected static function areaCacheKey($name, $level, $provId = '')
|
|
{
|
|
return strtolower($level . '|' . HuifuOnboardAreaHelper::toCode($provId) . '|' . $name);
|
|
}
|
|
|
|
/**
|
|
* @param array<int, array<string, mixed>> $rows
|
|
* @return array{inserted:int,updated:int}
|
|
*/
|
|
protected static function flushBuffer(array $rows, $dryRun = false)
|
|
{
|
|
$inserted = 0;
|
|
$updated = 0;
|
|
if ($dryRun) {
|
|
return ['inserted' => count($rows), 'updated' => 0];
|
|
}
|
|
|
|
foreach ($rows as $row) {
|
|
$exists = Db::name('shopro_huifu_bank_branch')->where('branch_code', $row['branch_code'])->find();
|
|
if ($exists) {
|
|
Db::name('shopro_huifu_bank_branch')->where('id', $exists['id'])->update([
|
|
'branch_name' => $row['branch_name'],
|
|
'bank_name' => $row['bank_name'],
|
|
'prov_id' => $row['prov_id'],
|
|
'area_id' => $row['area_id'],
|
|
'status' => 1,
|
|
]);
|
|
$updated++;
|
|
continue;
|
|
}
|
|
Db::name('shopro_huifu_bank_branch')->insert($row);
|
|
$inserted++;
|
|
}
|
|
|
|
return ['inserted' => $inserted, 'updated' => $updated];
|
|
}
|
|
|
|
protected static function downloadToFile($url, $dest)
|
|
{
|
|
if (function_exists('curl_init')) {
|
|
$fp = fopen($dest, 'wb');
|
|
if (!$fp) {
|
|
throw new \RuntimeException('无法写入: ' . $dest);
|
|
}
|
|
$ch = curl_init($url);
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_FILE => $fp,
|
|
CURLOPT_FOLLOWLOCATION => true,
|
|
CURLOPT_TIMEOUT => 600,
|
|
CURLOPT_SSL_VERIFYPEER => true,
|
|
CURLOPT_USERAGENT => 'shopro_huifu-importer/1.0',
|
|
]);
|
|
$ok = curl_exec($ch);
|
|
$err = curl_error($ch);
|
|
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
curl_close($ch);
|
|
fclose($fp);
|
|
if (!$ok || $code >= 400) {
|
|
@unlink($dest);
|
|
throw new \RuntimeException('HTTP ' . $code . ($err ? ': ' . $err : ''));
|
|
}
|
|
return;
|
|
}
|
|
|
|
$ctx = stream_context_create([
|
|
'http' => [
|
|
'timeout' => 600,
|
|
'header' => "User-Agent: shopro_huifu-importer/1.0\r\n",
|
|
],
|
|
]);
|
|
$content = @file_get_contents($url, false, $ctx);
|
|
if ($content === false || $content === '') {
|
|
throw new \RuntimeException('下载失败: ' . $url);
|
|
}
|
|
file_put_contents($dest, $content);
|
|
}
|
|
}
|