182 lines
16 KiB
PHP
182 lines
16 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
namespace app\service\group;
|
|
|
|
use app\exception\ApiError;
|
|
|
|
/** Only imports navigation metadata. Local kefu RBAC remains authoritative. */
|
|
final class KefuMenuCatalog
|
|
{
|
|
public function __construct(private readonly GroupStore $store) {}
|
|
|
|
/** Explicit group edits stay independent from source disable, even while already disabled. */
|
|
public function recordEdit(int $nodeId, array $payload): void
|
|
{
|
|
$state = $this->store->one('SELECT * FROM application_catalog_state WHERE node_id=?', [$nodeId]);
|
|
if (!$state) { return; }
|
|
$baseline = json_decode($state['baseline'], true, 32, JSON_THROW_ON_ERROR);
|
|
$overrides = json_decode($state['overrides'], true, 32, JSON_THROW_ON_ERROR);
|
|
foreach (['name','sort','pid','type','component','perms'] as $field) {
|
|
if (array_key_exists($field,$payload)) { $overrides[$field] = $payload[$field] !== ($baseline[$field] ?? null); }
|
|
}
|
|
$local = array_key_exists('disable',$payload) ? (int)$payload['disable'] : (int)$state['local_disable'];
|
|
$this->store->execute('UPDATE application_catalog_state SET overrides=?,local_disable=? WHERE node_id=?', [json_encode($overrides,JSON_THROW_ON_ERROR),$local,$nodeId]);
|
|
// Source deletion/disable cannot be bypassed by editing the local status.
|
|
if ((int)$state['source_disable'] === 1) { $this->store->execute('UPDATE company_structure_node SET disable=1 WHERE id=?',[$nodeId]); }
|
|
}
|
|
|
|
/** Runtime metadata is authoritative; static seed only supplies stable builtin page identities. */
|
|
public function sync(array $runtime, string $companyCode, int $actorId): array
|
|
{
|
|
$company = $this->store->one('SELECT * FROM company WHERE code=?',[$companyCode]);
|
|
if (!$company || (int)$company['id'] <= 1 || $actorId < 1 || !array_is_list($runtime) || count($runtime)>2000) { throw new ApiError(422,'客服目录目标无效'); }
|
|
$seed = json_decode(file_get_contents(dirname(__DIR__,4) . '/integration/kefu-menu-catalog.json'),true,64,JSON_THROW_ON_ERROR);
|
|
$permissions=[];
|
|
foreach ($runtime as $row) {
|
|
if (!is_array($row) || !is_string($row['code'] ?? null) || !preg_match('/^[a-z][a-z0-9:-]{1,80}$/D',$row['code']) || isset($permissions[$row['code']])
|
|
|| !is_string($row['name'] ?? null) || trim($row['name'])==='' || mb_strlen($row['name'])>64 || !is_string($row['group'] ?? null) || trim($row['group'])==='' || mb_strlen($row['group'])>64
|
|
|| !in_array($row['kind'] ?? null,['page','action'],true) || !is_bool($row['enabled'] ?? null) || !is_int($row['sort'] ?? null)) { throw new ApiError(422,'客服目录格式无效'); }
|
|
$permissions[$row['code']]=$row;
|
|
}
|
|
$prefix='company.'.$companyCode.'.kefu.';
|
|
$make=static fn(?string $pid,string $name,string $type,string $permission='',int $sort=0,int $disable=0):array=>['pid'=>$pid,'name'=>$name,'sort'=>$sort,'disable'=>$disable,'type'=>$type,'component'=>$type==='C'?'common/custom':'','perms'=>$permission];
|
|
$items=['root'=>$make(null,'企微客服','M')]; $legacy=$items; $covered=[];
|
|
foreach ($seed['menus'] as $menu) {
|
|
$key='page-'.$menu['key']; $groupKey='group-'.substr(hash('sha256',$menu['group']),0,16);
|
|
$legacy[$groupKey]??=$make('root',$menu['group'],'M');
|
|
$code=$menu['permissions'][0]??('page.'.$menu['key']);
|
|
$legacy[$key]=$make($groupKey,$menu['name'],'C',$prefix.$code);
|
|
foreach ($menu['permissions'] as $permissionCode) { $covered[$permissionCode]=true; }
|
|
$row=$permissions[$code]??null;
|
|
// Keep builtin route key even when a release removes its permission; it is soft-disabled.
|
|
$group=$row['group']??$menu['group']; $newGroup='group-'.substr(hash('sha256',$group),0,16);
|
|
$items[$newGroup]??=$make('root',$group,'M');
|
|
$items[$key]=$make($newGroup,$row && $row['kind']==='page'?$row['name']:$menu['name'],'C',$prefix.$code,$row['sort']??0,(!$row||!$row['enabled'])?1:0);
|
|
}
|
|
$items['actions']=$make('root','客服操作权限','M'); $legacy['actions']=$items['actions'];
|
|
foreach ($seed['permissions'] as $row) { $legacy['action-'.$row['code']]=$make('actions',$row['name'],'A',$prefix.$row['code']); }
|
|
foreach ($permissions as $code=>$row) {
|
|
if ($row['kind']==='page' && !isset($covered[$code])) {
|
|
$groupKey='group-'.substr(hash('sha256',$row['group']),0,16); $items[$groupKey]??=$make('root',$row['group'],'M');
|
|
$items['page-custom-'.substr(hash('sha256',$code),0,24)]=$make($groupKey,$row['name'],'C',$prefix.$code,$row['sort'],$row['enabled']?0:1);
|
|
}
|
|
$items['action-'.$code]=$make('actions',$row['name'],'A',$prefix.$code,$row['sort'],$row['enabled']?0:1);
|
|
}
|
|
return $this->store->write(function () use($items,$legacy,$company,$actorId):array {
|
|
$ids=[]; $created=0;$updated=0;$kept=0;$disabled=0;$now=time();$seen=[];
|
|
foreach ($items as $key=>$definition) {
|
|
$row=$this->store->one('SELECT n.* FROM application_catalog_node m JOIN company_structure_node n ON n.id=m.node_id WHERE m.client_id=? AND m.company_id=? AND m.external_key=?',['kefu',$company['id'],$key]);
|
|
$desired=$definition; $desired['pid']=$definition['pid']===null?0:($ids[$definition['pid']]??throw new ApiError(422,'客服父目录无效'));
|
|
if (!$row) {
|
|
$path='kefu-catalog/'.$key;
|
|
if ($this->store->one('SELECT id FROM company_structure_node WHERE company_id=? AND kind=? AND paths=?',[$company['id'],'menu',$path])) { throw new ApiError(409,'存在未登记的客服目录标识'); }
|
|
$this->store->execute("INSERT INTO company_structure_node(company_id,kind,pid,name,sort,disable,type,paths,component,perms,create_time,update_time) VALUES(?,'menu',?,?,?,?,?,?,?,?,?,?)",[$company['id'],$desired['pid'],$desired['name'],$desired['sort'],$desired['disable'],$desired['type'],$path,$desired['component'],$desired['perms'],$now,$now]);
|
|
$id=(int)$this->store->one('SELECT last_insert_rowid() AS id')['id'];
|
|
$this->store->execute('INSERT INTO application_catalog_node(client_id,company_id,external_key,node_id) VALUES(?,?,?,?)',['kefu',$company['id'],$key,$id]);
|
|
$this->store->execute('INSERT INTO application_catalog_state(node_id,baseline,applied,overrides,local_disable,source_disable) VALUES(?,?,?,?,0,?)',[$id,json_encode($desired,JSON_THROW_ON_ERROR),json_encode($desired,JSON_THROW_ON_ERROR),'{}',$desired['disable']]);
|
|
$created++; $ids[$key]=$id; $seen[$id]=true; continue;
|
|
}
|
|
if ((int)$row['company_id']!==(int)$company['id']||$row['kind']!=='menu') { throw new ApiError(409,'客服目录关联损坏'); }
|
|
$id=(int)$row['id'];$ids[$key]=$id;$seen[$id]=true;
|
|
$state=$this->store->one('SELECT * FROM application_catalog_state WHERE node_id=?',[$id]);
|
|
if ($state) { $applied=json_decode($state['applied'],true,32,JSON_THROW_ON_ERROR);$overrides=json_decode($state['overrides'],true,32,JSON_THROW_ON_ERROR);$local=(int)$state['local_disable']; }
|
|
else {
|
|
$applied=$legacy[$key]??$desired;
|
|
if (isset($legacy[$key])) { $applied['pid']=$applied['pid']===null?0:($ids[$applied['pid']]??(int)$row['pid']); }
|
|
$overrides=[];$local=(int)$row['disable'];
|
|
}
|
|
$next=[];
|
|
foreach (['pid','name','sort','type','component','perms'] as $field) {
|
|
$current=in_array($field,['pid','sort'],true)?(int)$row[$field]:$row[$field];
|
|
if ($current!==($applied[$field]??null)) { $overrides[$field]=true; }
|
|
$next[$field]=!empty($overrides[$field])?$current:$desired[$field];
|
|
}
|
|
if ($state && (int)$row['disable']!==(int)$applied['disable']) { $local=(int)$row['disable']; }
|
|
$next['disable']=max($local,$desired['disable']);
|
|
$changed=false;foreach($next as $field=>$value) if ((string)$row[$field] !== (string)$value) { $changed=true; }
|
|
if ($changed) {
|
|
$this->store->execute('UPDATE company_structure_node SET pid=?,name=?,sort=?,type=?,component=?,perms=?,disable=?,update_time=? WHERE id=?',[...array_values($next),$now,$id]);$updated++;
|
|
if ((int)$row['disable']===0 && $next['disable']===1) { $disabled++; }
|
|
} else { $kept++; }
|
|
$baseline=json_encode($desired,JSON_THROW_ON_ERROR);$applied=json_encode($next,JSON_THROW_ON_ERROR);$overrideJson=json_encode($overrides,JSON_THROW_ON_ERROR);
|
|
$this->store->execute('INSERT OR IGNORE INTO application_catalog_state(node_id,baseline,applied,overrides,local_disable,source_disable) VALUES(?,?,?,?,?,?)',[$id,$baseline,$applied,$overrideJson,$local,$desired['disable']]);
|
|
$this->store->execute('UPDATE application_catalog_state SET baseline=?,applied=?,overrides=?,local_disable=?,source_disable=? WHERE node_id=?',[$baseline,$applied,$overrideJson,$local,$desired['disable'],$id]);
|
|
}
|
|
foreach ($this->store->all('SELECT n.id,n.disable FROM application_catalog_node m JOIN company_structure_node n ON n.id=m.node_id WHERE m.client_id=? AND m.company_id=?',['kefu',$company['id']]) as $row) {
|
|
$id=(int)$row['id'];if(isset($seen[$id])) { continue; }
|
|
$state=$this->store->one('SELECT * FROM application_catalog_state WHERE node_id=?',[$id]);
|
|
if (!$state) { $full=$this->store->one('SELECT * FROM company_structure_node WHERE id=?',[$id]);$base=array_intersect_key($full,array_flip(['pid','name','sort','type','component','perms','disable']));$json=json_encode($base,JSON_THROW_ON_ERROR);
|
|
$this->store->execute('INSERT INTO application_catalog_state(node_id,baseline,applied,overrides,local_disable,source_disable) VALUES(?,?,?,?,?,1)',[$id,$json,$json,'{}',(int)$row['disable']]); }
|
|
$applied=$state?json_decode($state['applied'],true,32,JSON_THROW_ON_ERROR):$base;$applied['disable']=1;
|
|
$this->store->execute('UPDATE application_catalog_state SET source_disable=1,applied=? WHERE node_id=?',[json_encode($applied,JSON_THROW_ON_ERROR),$id]);
|
|
if ((int)$row['disable']===0) { $this->store->execute('UPDATE company_structure_node SET disable=1,update_time=? WHERE id=?',[$now,$id]);$disabled++; }
|
|
}
|
|
$this->store->audit($actorId,'kefu.catalog.sync',(int)$company['id']);
|
|
return ['created'=>$created,'updated'=>$updated,'kept'=>$kept,'disabled'=>$disabled,'pages'=>count(array_filter($items,static fn(array $item):bool=>$item['type']==='C')),'permissions'=>count(array_filter($items,static fn(array $item):bool=>$item['type']==='A')),'roles_changed'=>0];
|
|
});
|
|
}
|
|
|
|
public function import(array $catalog, string $companyCode, int $actorId): array
|
|
{
|
|
if (($catalog['version'] ?? null) !== 1 || ($catalog['client_id'] ?? null) !== 'kefu'
|
|
|| ($catalog['authorization_mode'] ?? null) !== 'kefu-local-roles' || $actorId < 1
|
|
|| !is_array($catalog['menus'] ?? null) || !is_array($catalog['permissions'] ?? null)
|
|
|| count($catalog['menus']) > 100 || count($catalog['permissions']) > 200) {
|
|
throw new ApiError(422, '客服菜单目录格式无效');
|
|
}
|
|
$company = $this->store->one('SELECT * FROM company WHERE code=?', [$companyCode]);
|
|
if (!$company || (int) $company['id'] <= 1) { throw new ApiError(422, '请先创建客服所属公司,不能导入医院目录'); }
|
|
$prefix = 'company.' . $companyCode . '.kefu.';
|
|
$items = ['root' => ['pid' => null, 'name' => '企微客服', 'type' => 'M', 'permission' => '', 'component' => '']];
|
|
$permissionCodes = [];
|
|
foreach ($catalog['permissions'] as $permission) {
|
|
$code = $permission['code'] ?? null;
|
|
if (!is_string($code) || !preg_match('/^[a-z][a-z0-9:-]{1,80}$/D', $code) || isset($permissionCodes[$code])) {
|
|
throw new ApiError(422, '客服权限码无效或重复');
|
|
}
|
|
$permissionCodes[$code] = true;
|
|
}
|
|
foreach ($catalog['menus'] as $menu) {
|
|
$key = $menu['key'] ?? null;
|
|
if (!is_string($key) || !preg_match('/^[A-Za-z][A-Za-z0-9_-]{0,79}$/D', $key)
|
|
|| isset($items['page-' . $key]) || !is_array($menu['permissions'] ?? null)) { throw new ApiError(422, '客服菜单标识无效'); }
|
|
$group = $menu['group'] ?? '';
|
|
$groupKey = 'group-' . substr(hash('sha256', (string) $group), 0, 16);
|
|
$items[$groupKey] ??= ['pid' => 'root', 'name' => $group, 'type' => 'M', 'permission' => '', 'component' => ''];
|
|
foreach ($menu['permissions'] as $code) if (!isset($permissionCodes[$code])) { throw new ApiError(422, '客服菜单引用了未知权限'); }
|
|
$code = $menu['permissions'][0] ?? ('page.' . $key);
|
|
$items['page-' . $key] = ['pid' => $groupKey, 'name' => $menu['name'] ?? '', 'type' => 'C', 'permission' => $prefix . $code, 'component' => 'common/custom'];
|
|
}
|
|
$items['actions'] = ['pid' => 'root', 'name' => '客服操作权限', 'type' => 'M', 'permission' => '', 'component' => ''];
|
|
foreach ($catalog['permissions'] as $permission) {
|
|
$items['action-' . $permission['code']] = ['pid' => 'actions', 'name' => $permission['name'] ?? '', 'type' => 'A',
|
|
'permission' => $prefix . $permission['code'], 'component' => ''];
|
|
}
|
|
foreach ($items as $item) {
|
|
if (!is_string($item['name']) || trim($item['name']) === '' || mb_strlen($item['name']) > 64
|
|
|| strlen($item['permission']) > 200) { throw new ApiError(422, '客服菜单名称或权限长度无效'); }
|
|
}
|
|
// The import's stable keys are independent of names and never claim existing user-created nodes.
|
|
$this->store->execute('CREATE TABLE IF NOT EXISTS application_catalog_node (client_id TEXT NOT NULL,company_id INTEGER NOT NULL REFERENCES company(id),external_key TEXT NOT NULL,node_id INTEGER NOT NULL REFERENCES company_structure_node(id) ON DELETE CASCADE,PRIMARY KEY(client_id,company_id,external_key))');
|
|
return $this->store->write(function () use ($items, $company, $actorId): array {
|
|
$ids = []; $created = 0; $kept = 0; $now = time();
|
|
foreach ($items as $key => $item) {
|
|
$path = 'kefu-catalog/' . $key;
|
|
$existing = $this->store->one('SELECT n.* FROM application_catalog_node m JOIN company_structure_node n ON n.id=m.node_id WHERE m.client_id=? AND m.company_id=? AND m.external_key=?', ['kefu', $company['id'], $key]);
|
|
if ($existing) {
|
|
if ((int) $existing['company_id'] !== (int) $company['id'] || $existing['kind'] !== 'menu') { throw new ApiError(409, '客服菜单关联已损坏,请核对后重试'); }
|
|
$ids[$key] = (int) $existing['id']; $kept++; continue;
|
|
}
|
|
if ($this->store->one('SELECT id FROM company_structure_node WHERE company_id=? AND kind=? AND paths=?', [$company['id'], 'menu', $path])) { throw new ApiError(409, '存在未登记的同标识客服菜单,请先核对'); }
|
|
$pid = $item['pid'] === null ? 0 : $ids[$item['pid']];
|
|
$this->store->execute("INSERT INTO company_structure_node(company_id,kind,pid,name,sort,disable,type,paths,component,perms,icon,is_show,is_cache,selected,params,create_time,update_time) VALUES(?,'menu',?,?,0,0,?,?,?,?, '',1,0,'','',?,?)", [$company['id'], $pid, $item['name'], $item['type'], $path, $item['component'], $item['permission'], $now, $now]);
|
|
$node = $this->store->one('SELECT id FROM company_structure_node WHERE company_id=? AND kind=? AND paths=?', [$company['id'], 'menu', $path]);
|
|
$ids[$key] = (int) $node['id'];
|
|
$this->store->execute('INSERT INTO application_catalog_node(client_id,company_id,external_key,node_id) VALUES(?,?,?,?)', ['kefu', $company['id'], $key, $ids[$key]]); $created++;
|
|
}
|
|
$this->store->audit($actorId, 'kefu.catalog.import', (int) $company['id']);
|
|
return ['company_id' => (int) $company['id'], 'created' => $created, 'kept' => $kept, 'pages' => count(array_filter($items, static fn (array $item): bool => $item['type'] === 'C')), 'permissions' => count(array_filter($items, static fn (array $item): bool => $item['type'] === 'A')), 'roles_changed' => 0];
|
|
});
|
|
}
|
|
}
|