You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.5 KiB
Python
46 lines
1.5 KiB
Python
# backend/app/connectors/chat/normalize.py — 메신저 메시지 → chat_message 정규화 + upsert
|
|
import uuid
|
|
|
|
from sqlmodel import Session, select
|
|
|
|
from ...models import ChatMessage, ExternalLink
|
|
from ..base import NormalizedRecord, RawRecord
|
|
|
|
|
|
def normalize_chat(account, raw: RawRecord) -> NormalizedRecord:
|
|
p = raw.payload
|
|
fields = {
|
|
"account_id": account.id,
|
|
"sender": p.get("sender", p.get("from", "")),
|
|
"text": p.get("text", p.get("message", "")),
|
|
"channel": p.get("channel", ""),
|
|
"at": p.get("at", p.get("ts", "방금")),
|
|
}
|
|
return NormalizedRecord(
|
|
entity_type="chat_message",
|
|
external_id=raw.external_id,
|
|
fields=fields,
|
|
etag=raw.etag,
|
|
external_updated_at=raw.external_updated_at,
|
|
)
|
|
|
|
|
|
def upsert_chat(session: Session, norm: NormalizedRecord) -> tuple[str, bool]:
|
|
link = session.exec(
|
|
select(ExternalLink).where(
|
|
ExternalLink.external_id == norm.external_id,
|
|
ExternalLink.entity_type == "chat_message",
|
|
)
|
|
).first()
|
|
if link:
|
|
cm = session.get(ChatMessage, link.entity_id)
|
|
if cm:
|
|
for k, v in norm.fields.items():
|
|
if v is not None and hasattr(cm, k):
|
|
setattr(cm, k, v)
|
|
session.add(cm)
|
|
return cm.id, False
|
|
cid = "cm-" + uuid.uuid4().hex[:8]
|
|
session.add(ChatMessage(id=cid, **{k: v for k, v in norm.fields.items() if v is not None}))
|
|
return cid, True
|