218 lines
12 KiB
PHP
218 lines
12 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace app\common\service\assistantservice;
|
|
|
|
use think\facade\Db;
|
|
|
|
/** 读取本机企微客服归档。没有患者绑定时保留会话名,不把客户原文送进预警。 */
|
|
final class WecomArchiveSqlite
|
|
{
|
|
public static function configured(): bool
|
|
{
|
|
$path = (string) config('assistant_service.wecom_archive_sqlite', '');
|
|
return WecomArchiveScope::tenant() !== '' && $path !== '' && is_file($path);
|
|
}
|
|
|
|
/** @return array{configured:bool,items:array<int,array<string,mixed>>,next_cursor:string,has_more:bool} */
|
|
public static function page(string $cursor, int $limit): array
|
|
{
|
|
$empty = ['configured' => true, 'items' => [], 'next_cursor' => $cursor, 'has_more' => false];
|
|
$pdo = self::connection();
|
|
if (!$pdo) { return ['configured' => false, 'items' => [], 'next_cursor' => $cursor, 'has_more' => false]; }
|
|
$limit = max(1, min(200, $limit));
|
|
$cursorTime = '';
|
|
$cursorId = '';
|
|
if ($cursor !== '') {
|
|
$parts = explode('|', $cursor, 2);
|
|
if (count($parts) !== 2) { return $empty; }
|
|
[$cursorTime, $cursorId] = $parts;
|
|
}
|
|
$sql = "SELECT m.id, substr(m.content,1,8000) AS content, m.sent_at, m.sent_at_epoch,
|
|
a.external_account_id, a.display_name AS staff_name, c.name AS patient_name,
|
|
c.id AS conversation_id, c.conversation_type, c.source_account_id
|
|
FROM archive_message m
|
|
JOIN archive_conversation c ON c.id = m.conversation_id AND c.tenant_id = m.tenant_id AND c.source_account_id = m.source_account_id
|
|
JOIN archive_source_account a ON a.id = m.source_account_id AND a.tenant_id = m.tenant_id
|
|
WHERE m.tenant_id = ? AND m.direction = 'outbound' AND m.status = 'normal'
|
|
AND m.message_type IN ('text','文本') AND length(trim(m.content)) > 0
|
|
AND c.conversation_type IN ('direct_wechat','direct_wecom','group')";
|
|
$params = [WecomArchiveScope::tenant()];
|
|
if ($cursor !== '') {
|
|
$sql .= ' AND (m.sent_at, m.id) > (?, ?)';
|
|
$params[] = $cursorTime;
|
|
$params[] = $cursorId;
|
|
}
|
|
$sql .= ' ORDER BY m.sent_at, m.id LIMIT ' . ($limit + 1);
|
|
$statement = $pdo->prepare($sql);
|
|
$statement->execute($params);
|
|
$rows = $statement->fetchAll(\PDO::FETCH_ASSOC);
|
|
$hasMore = count($rows) > $limit;
|
|
if ($hasMore) { array_pop($rows); }
|
|
if (!$rows) { return $empty; }
|
|
$bindings = self::patientBindings($pdo, $rows);
|
|
foreach ($rows as &$row) {
|
|
$row += $bindings[$row['conversation_id']] ?? [];
|
|
}
|
|
unset($row);
|
|
$items = self::identify($rows);
|
|
$last = $rows[count($rows) - 1];
|
|
return ['configured' => true, 'items' => $items, 'has_more' => $hasMore,
|
|
'next_cursor' => (string) $last['sent_at'] . '|' . (string) $last['id']];
|
|
}
|
|
|
|
/** @param list<array<string,mixed>> $rows @return list<array<string,mixed>> */
|
|
public static function identify(array $rows): array
|
|
{
|
|
$staff = WecomArchiveScope::accountOwners();
|
|
$patientIds = array_values(array_filter(array_unique(array_map('intval', array_column($rows, 'patient_id')))));
|
|
$diagnoses = $patientIds ? Db::name('tcm_diagnosis')->whereNull('delete_time')->where('status', 1)
|
|
->whereIn('patient_id', $patientIds)->field('id,patient_id')->select()->toArray() : [];
|
|
$patients = [];
|
|
foreach ($diagnoses as $diagnosis) { $patients[(int) $diagnosis['patient_id']][(int) $diagnosis['id']] = true; }
|
|
$items = [];
|
|
foreach ($rows as $row) {
|
|
if (!is_array($row)) { continue; }
|
|
$staffName = trim((string) ($row['staff_name'] ?? ''));
|
|
$patientName = trim((string) ($row['patient_name'] ?? ''));
|
|
$person = $staff[(string) ($row['external_account_id'] ?? '')] ?? 0;
|
|
$patientId = (int) ($row['patient_id'] ?? 0);
|
|
$diagnosisId = (int) ($row['diagnosis_id'] ?? 0);
|
|
$items[] = [
|
|
'id' => (string) ($row['id'] ?? ''),
|
|
'sent_at' => (string) ($row['sent_at'] ?? ''),
|
|
'sent_at_epoch' => (int) ($row['sent_at_epoch'] ?? 0),
|
|
'patient_id' => isset($patients[$patientId]) ? $patientId : 0,
|
|
'diagnosis_id' => isset($patients[$patientId][$diagnosisId]) ? $diagnosisId : 0,
|
|
'zyt_user_id' => (string) $person,
|
|
'staff_name' => $staffName,
|
|
'patient_name' => $patientName,
|
|
'content' => (string) ($row['content'] ?? ''),
|
|
];
|
|
}
|
|
return $items;
|
|
}
|
|
|
|
/** 仅接受同租户单聊中唯一入站对方的唯一有效主绑定。旧库没有绑定表时保留未归属。 */
|
|
private static function patientBindings(\PDO $pdo, array $rows): array
|
|
{
|
|
$ids = [];
|
|
foreach ($rows as $row) {
|
|
if (in_array($row['conversation_type'], ['direct_wechat', 'direct_wecom'], true)) {
|
|
$ids[] = $row['conversation_id'];
|
|
}
|
|
}
|
|
if (!$ids || !$pdo->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='archive_patient_binding'")->fetchColumn()) { return []; }
|
|
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
|
$statement = $pdo->prepare("WITH peer AS (
|
|
SELECT m.tenant_id, m.conversation_id, MIN(m.sender_person_id) AS person_id
|
|
FROM archive_message m
|
|
JOIN archive_conversation c ON c.id = m.conversation_id AND c.tenant_id = m.tenant_id AND c.source_account_id = m.source_account_id
|
|
WHERE m.tenant_id = ? AND m.direction = 'inbound' AND m.conversation_id IN ($placeholders)
|
|
GROUP BY m.tenant_id, m.conversation_id
|
|
HAVING COUNT(*) = COUNT(NULLIF(m.sender_person_id, '')) AND COUNT(DISTINCT m.sender_person_id) = 1
|
|
)
|
|
SELECT peer.conversation_id, MIN(b.patient_id) AS patient_id, MIN(b.diagnosis_id) AS diagnosis_id
|
|
FROM peer
|
|
JOIN archive_person p ON p.id = peer.person_id AND p.tenant_id = peer.tenant_id
|
|
JOIN archive_patient_binding b ON b.tenant_id = peer.tenant_id AND b.person_id = peer.person_id
|
|
WHERE b.status = 'active' AND b.is_primary = 1
|
|
GROUP BY peer.conversation_id HAVING COUNT(*) = 1");
|
|
$statement->execute(array_merge([WecomArchiveScope::tenant()], $ids));
|
|
return $statement->fetchAll(\PDO::FETCH_UNIQUE | \PDO::FETCH_ASSOC);
|
|
}
|
|
|
|
/** @return list<array{external_id:string,name:string,conversations:int}> */
|
|
public static function accounts(): array
|
|
{
|
|
$pdo = self::connection();
|
|
if (!$pdo) { return []; }
|
|
$statement = $pdo->prepare("SELECT a.external_account_id, a.display_name, COUNT(c.id) AS conversations
|
|
FROM archive_source_account a
|
|
LEFT JOIN archive_conversation c ON c.source_account_id = a.id AND c.tenant_id = a.tenant_id
|
|
WHERE a.tenant_id = ?
|
|
GROUP BY a.external_account_id, a.display_name
|
|
ORDER BY conversations DESC, a.external_account_id");
|
|
$statement->execute([WecomArchiveScope::tenant()]);
|
|
$rows = $statement->fetchAll(\PDO::FETCH_ASSOC);
|
|
$accounts = [];
|
|
foreach ($rows as $row) {
|
|
$accounts[] = ['external_id' => (string) $row['external_account_id'], 'name' => trim((string) $row['display_name']),
|
|
'conversations' => (int) $row['conversations']];
|
|
}
|
|
return $accounts;
|
|
}
|
|
|
|
/** @return list<array{id:string,name:string,conversation_type:string,last_message_at:string,message_count:int,preview:string}> */
|
|
public static function conversations(string $externalId): array
|
|
{
|
|
$pdo = self::connection();
|
|
if (!$pdo || $externalId === '') { return []; }
|
|
$statement = $pdo->prepare("SELECT c.id, c.name, c.conversation_type, c.last_message_at,
|
|
(SELECT COUNT(*) FROM archive_message m WHERE m.tenant_id = c.tenant_id
|
|
AND m.conversation_id = c.id AND m.source_account_id = c.source_account_id) AS message_count,
|
|
(SELECT substr(m.content, 1, 80) FROM archive_message m WHERE m.tenant_id = c.tenant_id
|
|
AND m.conversation_id = c.id AND m.source_account_id = c.source_account_id
|
|
ORDER BY m.sent_at DESC, m.id DESC LIMIT 1) AS preview
|
|
FROM archive_conversation c
|
|
JOIN archive_source_account a ON a.id = c.source_account_id AND a.tenant_id = c.tenant_id
|
|
WHERE c.tenant_id = ? AND a.external_account_id = ?
|
|
ORDER BY c.last_message_at DESC, c.id DESC LIMIT 100");
|
|
$statement->execute([WecomArchiveScope::tenant(), $externalId]);
|
|
$rows = $statement->fetchAll(\PDO::FETCH_ASSOC);
|
|
$items = [];
|
|
foreach ($rows as $row) {
|
|
$id = (string) $row['id'];
|
|
$items[] = ['id' => $id, 'name' => self::plainText((string) $row['name']),
|
|
'conversation_type' => (string) $row['conversation_type'], 'last_message_at' => (string) $row['last_message_at'],
|
|
'message_count' => (int) $row['message_count'], 'preview' => self::plainText((string) $row['preview'])];
|
|
}
|
|
return $items;
|
|
}
|
|
|
|
/** @return array{account:string,messages:list<array{id:string,sent_at:string,direction:string,message_type:string,sender_name:string,content:string}>} */
|
|
public static function messages(string $conversationId): array
|
|
{
|
|
$pdo = self::connection();
|
|
if (!$pdo || $conversationId === '') { return ['account' => '', 'messages' => []]; }
|
|
$account = $pdo->prepare("SELECT a.external_account_id, a.id FROM archive_conversation c
|
|
JOIN archive_source_account a ON a.id = c.source_account_id AND a.tenant_id = c.tenant_id WHERE c.tenant_id = ? AND c.id = ?");
|
|
$account->execute([WecomArchiveScope::tenant(), $conversationId]);
|
|
$source = $account->fetch(\PDO::FETCH_ASSOC);
|
|
$externalId = (string) ($source['external_account_id'] ?? '');
|
|
if ($externalId === '') { return ['account' => '', 'messages' => []]; }
|
|
$statement = $pdo->prepare("SELECT m.id, m.sent_at, m.direction, m.message_type, substr(m.content, 1, 2000) AS content,
|
|
COALESCE(p.display_name, '') AS sender_name
|
|
FROM archive_message m
|
|
LEFT JOIN archive_person p ON p.id = m.sender_person_id AND p.tenant_id = m.tenant_id
|
|
WHERE m.tenant_id = ? AND m.conversation_id = ? AND m.source_account_id = ?
|
|
ORDER BY m.sent_at ASC, m.id ASC LIMIT 200");
|
|
$statement->execute([WecomArchiveScope::tenant(), $conversationId, $source['id']]);
|
|
$messages = [];
|
|
foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $row) {
|
|
$messages[] = ['id' => (string) $row['id'], 'sent_at' => (string) $row['sent_at'], 'direction' => (string) $row['direction'],
|
|
'message_type' => (string) $row['message_type'], 'sender_name' => self::plainText((string) $row['sender_name']),
|
|
'content' => self::plainText((string) $row['content'])];
|
|
}
|
|
return ['account' => $externalId, 'messages' => $messages];
|
|
}
|
|
|
|
private static function plainText(string $value): string
|
|
{
|
|
$clean = iconv('UTF-8', 'UTF-8//IGNORE', $value);
|
|
$text = is_string($clean) ? $clean : '';
|
|
return trim(str_replace("\0", '', $text));
|
|
}
|
|
|
|
private static function connection(): ?\PDO
|
|
{
|
|
$path = (string) config('assistant_service.wecom_archive_sqlite', '');
|
|
if (!self::configured()) { return null; }
|
|
return new \PDO('sqlite:' . $path, null, null, [
|
|
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
|
|
\PDO::SQLITE_ATTR_OPEN_FLAGS => \PDO::SQLITE_OPEN_READONLY,
|
|
]);
|
|
}
|
|
}
|