- Change RawOpdCheckpoint model to RawWaitingTime - Update schema from FeedCheckpointIn to FeedWaitingTimeIn - Switch to rawdata.raw_waiting_time table - Keep existing /feed/checkpoint endpoint - Add new fields: vn, txn, name, doctor_code, doctor_name, location_code, location_name, step_name, time - Update permission to feed.waiting-time:write
75 lines
2.3 KiB
Python
75 lines
2.3 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import Annotated
|
|
from datetime import datetime
|
|
from zoneinfo import ZoneInfo
|
|
|
|
from fastapi import APIRouter, Depends
|
|
from sqlalchemy.dialects.postgresql import insert
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.api.v1.schemas import FeedWaitingTimeIn
|
|
from app.core.config import settings
|
|
from app.db.models import RawWaitingTime
|
|
from app.security.dependencies import get_db, require_permission
|
|
|
|
|
|
router = APIRouter(prefix="/api/v1")
|
|
|
|
PERM_FEED_WAITING_TIME_WRITE = "feed.waiting-time:write"
|
|
|
|
|
|
def _to_tz(dt):
|
|
if dt is None:
|
|
return None
|
|
if dt.tzinfo is None:
|
|
return dt.replace(tzinfo=ZoneInfo(settings.TIMEZONE))
|
|
return dt.astimezone(ZoneInfo(settings.TIMEZONE))
|
|
|
|
|
|
@router.post("/feed/checkpoint")
|
|
def upsert_feed_checkpoint(
|
|
payload: list[FeedWaitingTimeIn],
|
|
_: Annotated[object, Depends(require_permission(PERM_FEED_WAITING_TIME_WRITE))],
|
|
db: Annotated[Session, Depends(get_db)],
|
|
):
|
|
rows = []
|
|
for item in payload:
|
|
rows.append(
|
|
{
|
|
"id": item.id,
|
|
"vn": item.vn,
|
|
"txn": item.txn,
|
|
"hn": item.hn,
|
|
"name": item.name,
|
|
"doctor_code": item.doctor_code,
|
|
"doctor_name": item.doctor_name,
|
|
"location_code": item.location_code,
|
|
"location_name": item.location_name,
|
|
"step_name": item.step_name,
|
|
"time": _to_tz(item.time),
|
|
"updated_at": datetime.now(ZoneInfo(settings.TIMEZONE)),
|
|
}
|
|
)
|
|
|
|
stmt = insert(RawWaitingTime).values(rows)
|
|
update_cols = {
|
|
"vn": stmt.excluded.vn,
|
|
"txn": stmt.excluded.txn,
|
|
"hn": stmt.excluded.hn,
|
|
"name": stmt.excluded.name,
|
|
"doctor_code": stmt.excluded.doctor_code,
|
|
"doctor_name": stmt.excluded.doctor_name,
|
|
"location_code": stmt.excluded.location_code,
|
|
"location_name": stmt.excluded.location_name,
|
|
"step_name": stmt.excluded.step_name,
|
|
"time": stmt.excluded.time,
|
|
"updated_at": stmt.excluded.updated_at,
|
|
}
|
|
|
|
stmt = stmt.on_conflict_do_update(index_elements=[RawWaitingTime.id], set_=update_cols)
|
|
result = db.execute(stmt)
|
|
db.commit()
|
|
|
|
return {"upserted": len(rows), "rowcount": result.rowcount}
|