Files
zyt/identity-admin/server/app/service/group/KefuApplicationService.php
T
2026-11-11 13:53:14 +08:00

136 lines
8.2 KiB
PHP

<?php
declare(strict_types=1);
namespace app\service\group;
use app\exception\ApiError;
use app\service\Input;
use app\service\shared\SourceApiClient;
/** Separate read model; never enriches the authenticated actor with remote authorization. */
final class KefuApplicationService
{
public function __construct(private readonly GroupStore $store, private readonly SourceApiClient $source,
private readonly ?KefuMetadataClient $client = null, private readonly ?KefuAuthorizationClient $authorization = null) {}
private function company(): ?array
{
$code=KefuClient::companyCode();
return $code===''?null:$this->store->one('SELECT * FROM company WHERE code=? AND id>1',[$code]);
}
private function available(?array $company): bool { return $company !== null && ($this->client !== null || KefuMetadataClient::configured()); }
private function client(): KefuMetadataClient { return $this->client ?? new KefuMetadataClient(); }
public function access(array $query, string $sourceToken): array
{
Input::only($query,['client_id','source_admin_id']);
if (($query['client_id']??null)!=='kefu') { throw new ApiError(422,'应用未注册'); }
$id=Input::integer($query['source_admin_id']??null,'员工');
$target=$this->source->request('GET','auth.admin/detail',['id'=>$id],$sourceToken);
if ((int)($target['id']??0)!==$id) { throw new ApiError(404,'员工不存在'); }
// Existing GID only. Metadata reads must never enroll or join on an account name.
$identity=$this->store->one('SELECT gid FROM subject WHERE source_id=?',[$id]);
$company=$this->company();
$dto=['client_id'=>'kefu','application_name'=>'企微客服','company_id'=>(int)($company['id']??0),
'source_admin_id'=>$id,'gid'=>$identity['gid']??null,'status'=>'not_configured','synced_at'=>null,'user'=>null,'permission_details'=>[]];
if (!$this->available($company)) { return $dto; }
if (!$identity) { $dto['status']='not_enrolled';return $dto; }
$snapshot=$this->client()->snapshot([$identity['gid']],true);$subject=$snapshot['subjects'][0];
$dto['synced_at']=time();
if (!$subject['found']) { $dto['status']='not_enrolled';return $dto; }
if ($subject['gid']!==$identity['gid'] || $subject['source_admin_id']!==$id || $subject['company_id']!==(int)$company['id']) {
throw new ApiError(503,'客服身份信息不一致,请联系管理员核对');
}
$dto['status']='ok';$dto['user']=$subject['user'];
$dto['permission_details']=array_values(array_filter($snapshot['catalog']['permissions'],static fn(array $row):bool=>in_array($row['code'],$subject['user']['permissions'],true)));
return $dto;
}
public function accessOptions(array $query, string $sourceToken): array
{
Input::only($query,['client_id','source_admin_id']);
if (($query['client_id']??null)!=='kefu') { throw new ApiError(422,'应用未注册'); }
$id=Input::integer($query['source_admin_id']??null,'员工');
[$gid,$companyId]=$this->authorizationTarget($id,$sourceToken);
$snapshot=($this->authorization??new KefuAuthorizationClient())->options($gid,$id,$companyId);
return $this->editDto($snapshot);
}
public function accessUpdate(array $data, string $sourceToken, int $actorId): array
{
$expected=['client_id','source_admin_id','expected_revision','role_code','permissions'];
Input::only($data,$expected);
if (array_diff($expected,array_keys($data))!==[] || ($data['client_id']??null)!=='kefu'
|| !is_int($data['source_admin_id']??null)) { throw new ApiError(422,'客服授权参数无效'); }
$id=Input::integer($data['source_admin_id'],'员工');
KefuAuthorizationClient::validateChange($data['expected_revision'],$data['role_code'],$data['permissions']);
[$gid,$companyId]=$this->authorizationTarget($id,$sourceToken);
$snapshot=($this->authorization??new KefuAuthorizationClient())->update($gid,$id,$companyId,$actorId,
$data['expected_revision'],$data['role_code'],$data['permissions']);
// KF has committed before its verified response. Never report a local optimistic save.
try { $this->store->audit($actorId,'kefu.access.update',$companyId,$id); }
catch (\Throwable $error) { throw new ApiError(503,'客服已处理,但集团审计记录失败,请刷新核对'); }
return $this->editDto($snapshot);
}
private function authorizationTarget(int $id, string $sourceToken): array
{
$target=$this->source->request('GET','auth.admin/detail',['id'=>$id],$sourceToken);
try { $targetId=Input::integer($target['id']??null,'员工'); }
catch (ApiError $error) { throw new ApiError(404,'员工不存在'); }
if ($targetId!==$id) { throw new ApiError(404,'员工不存在'); }
$identity=$this->store->one('SELECT gid FROM subject WHERE source_id=?',[$id]);
$company=$this->company();
if (!$company) { throw new ApiError(503,'客服应用尚未登记'); }
if (!$identity) { throw new ApiError(404,'员工尚未绑定客服身份'); }
if (!is_string($identity['gid']) || !preg_match('/^gid_[a-f0-9]{32}$/D',$identity['gid'])) { throw new ApiError(503,'客服身份信息无效'); }
return [$identity['gid'],(int)$company['id']];
}
private function editDto(array $snapshot): array
{
$subject=$snapshot['subject'];$catalog=$snapshot['catalog']['permissions'];
return ['client_id'=>'kefu','application_name'=>'企微客服','company_id'=>$subject['company_id'],
'source_admin_id'=>$subject['source_admin_id'],'gid'=>$subject['gid'],'status'=>'ok','synced_at'=>$snapshot['generated_at'],
'user'=>$subject['user'],'permission_details'=>array_values(array_filter($catalog,
static fn(array $row):bool=>in_array($row['code'],$subject['user']['permissions'],true))),
'revision'=>$snapshot['revision'],'roles'=>$snapshot['roles'],'catalog'=>$catalog];
}
public function sync(array $data, int $actorId): array
{
Input::only($data,['client_id']);
if (($data['client_id']??null)!=='kefu') { throw new ApiError(422,'应用未注册'); }
$company=$this->company();
$dto=['client_id'=>'kefu','company_id'=>(int)($company['id']??0),'status'=>'not_configured','synced_at'=>null,
'created'=>0,'updated'=>0,'kept'=>0,'disabled'=>0,'pages'=>0,'permissions'=>0,'roles_changed'=>0];
if (!$this->available($company)) { return $dto; }
$snapshot=$this->client()->snapshot([],true);
$result=(new KefuMenuCatalog($this->store))->sync($snapshot['catalog']['permissions'],$company['code'],$actorId);
$now=time();
$name='kefu.catalog.synced.'.$company['id'];
$this->store->write(function()use($name,$now):void {
$this->store->execute('INSERT OR IGNORE INTO group_meta(name,value) VALUES(?,?)',[$name,(string)$now]);
$this->store->execute('UPDATE group_meta SET value=? WHERE name=?',[(string)$now,$name]);
});
return array_replace($dto,$result,['status'=>'ok','synced_at'=>$now]);
}
/** Best effort, bounded to one attempt per company/minute, including failures. */
public function refreshIfDue(int $companyId, int $actorId): void
{
try {
$company=$this->company();if (!$company || (int)$company['id']!==$companyId || !$this->available($company)) { return; }
$name='kefu.catalog.attempt.'.$companyId;$now=time();
$due=$this->store->write(function()use($name,$now):bool {
$last=$this->store->one('SELECT value FROM group_meta WHERE name=?',[$name]);
if ($last && $now-(int)$last['value']<60) { return false; }
$this->store->execute('INSERT OR IGNORE INTO group_meta(name,value) VALUES(?,?)',[$name,(string)$now]);
$this->store->execute('UPDATE group_meta SET value=? WHERE name=?',[(string)$now,$name]);return true;
});
if (!$due) { return; }
$this->sync(['client_id'=>'kefu'],$actorId);
} catch (\Throwable $error) { /* Keep the last usable directory, including when the attempt claim fails. */ }
}
}