Files
zyt/server/app/common/service/assistantservice/WecomArchiveSqlite.php
T
2026-11-12 09:07:07 +08:00

215 lines
11 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 $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];
$path = (string) config('assistant_service.wecom_archive_sqlite', '');
if ($path === '' || !is_file($path)) { 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;
}
$pdo = new \PDO('sqlite:' . $path, null, null, [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]);
$sql = "SELECT m.id, substr(m.content,1,8000) AS content, m.sent_at, m.sent_at_epoch,
a.display_name AS staff_name, c.name AS patient_name
FROM archive_message m
JOIN archive_conversation c ON c.id = m.conversation_id
JOIN archive_source_account a ON a.id = m.source_account_id
WHERE 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 = [];
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; }
$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 = self::staffByUniqueName();
$patients = self::patientByUniqueName();
$items = [];
foreach ($rows as $row) {
if (!is_array($row)) { continue; }
$staffName = trim((string) ($row['staff_name'] ?? ''));
$patientName = trim((string) ($row['patient_name'] ?? ''));
$person = $staff[$staffName] ?? 0;
$patient = $patients[$patientName] ?? ['patient_id' => 0, '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' => (int) $patient['patient_id'],
'diagnosis_id' => (int) $patient['diagnosis_id'],
'zyt_user_id' => (string) $person,
'staff_name' => $staffName,
'patient_name' => $patientName,
'content' => (string) ($row['content'] ?? ''),
];
}
return $items;
}
/** @return array<string,int> */
private static function staffByUniqueName(): array
{
$map = [];
$rows = Db::name('admin')->where('root', 0)->where('disable', 0)->whereNull('delete_time')
->field('name, MIN(id) AS id, COUNT(*) AS people')->group('name')->select()->toArray();
foreach ($rows as $row) {
$name = trim((string) ($row['name'] ?? ''));
if ($name !== '' && (int) $row['people'] === 1) { $map[$name] = (int) $row['id']; }
}
return $map;
}
/** @return array<string,array{patient_id:int,diagnosis_id:int}> */
private static function patientByUniqueName(): array
{
$map = [];
$rows = Db::name('tcm_diagnosis')->whereNull('delete_time')->where('status', 1)
->field('patient_name, MIN(patient_id) AS patient_id, MIN(id) AS diagnosis_id, COUNT(DISTINCT patient_id) AS people')
->group('patient_name')->select()->toArray();
foreach ($rows as $row) {
$name = trim((string) ($row['patient_name'] ?? ''));
if ($name !== '' && (int) $row['people'] === 1) {
$map[$name] = ['patient_id' => (int) $row['patient_id'], 'diagnosis_id' => (int) $row['diagnosis_id']];
}
}
return $map;
}
/** @return list<array{external_id:string,name:string,conversations:int}> */
public static function accounts(): array
{
$pdo = self::connection();
if (!$pdo) { return []; }
$rows = $pdo->query("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
GROUP BY a.external_account_id, a.display_name
ORDER BY conversations DESC, a.external_account_id")->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
FROM archive_conversation c
JOIN archive_source_account a ON a.id = c.source_account_id
WHERE a.external_account_id = ?
ORDER BY c.last_message_at DESC, c.id DESC LIMIT 100");
$statement->execute([$externalId]);
$rows = $statement->fetchAll(\PDO::FETCH_ASSOC);
if (!$rows) { return []; }
$ids = array_map(static fn (array $row): string => (string) $row['id'], $rows);
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$counts = $pdo->prepare("SELECT conversation_id, COUNT(*) AS message_count FROM archive_message
WHERE conversation_id IN ($placeholders) GROUP BY conversation_id");
$counts->execute($ids);
$countById = [];
foreach ($counts->fetchAll(\PDO::FETCH_ASSOC) as $row) { $countById[(string) $row['conversation_id']] = (int) $row['message_count']; }
$latest = $pdo->prepare("SELECT conversation_id, MAX(sent_at) AS sent_at FROM archive_message
WHERE conversation_id IN ($placeholders) GROUP BY conversation_id");
$latest->execute($ids);
$previewById = [];
$preview = $pdo->prepare("SELECT substr(content, 1, 80) AS preview FROM archive_message
WHERE conversation_id = ? AND sent_at = ? ORDER BY id DESC LIMIT 1");
foreach ($latest->fetchAll(\PDO::FETCH_ASSOC) as $row) {
$preview->execute([(string) $row['conversation_id'], (string) $row['sent_at']]);
$previewById[(string) $row['conversation_id']] = trim((string) ($preview->fetchColumn() ?: ''));
}
$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' => $countById[$id] ?? 0, 'preview' => self::plainText($previewById[$id] ?? '')];
}
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 FROM archive_conversation c
JOIN archive_source_account a ON a.id = c.source_account_id WHERE c.id = ?");
$account->execute([$conversationId]);
$externalId = (string) ($account->fetchColumn() ?: '');
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
WHERE m.conversation_id = ?
ORDER BY m.sent_at ASC, m.id ASC LIMIT 200");
$statement->execute([$conversationId]);
$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 ($path === '' || !is_file($path)) { return null; }
$pdo = new \PDO('sqlite:' . $path, null, null, [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]);
return $pdo;
}
}