102 lines
5.0 KiB
Python
102 lines
5.0 KiB
Python
from abc import ABC, abstractmethod
|
|
from datetime import datetime
|
|
from typing import Tuple
|
|
|
|
from sqlalchemy import and_, distinct, func, select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.database.model.models import places, site_page_views, sites
|
|
from common.enums import ErrorType
|
|
from common.logger import LOG
|
|
|
|
|
|
class IVisitCRUD(ABC):
|
|
@abstractmethod
|
|
async def add_view(self, cdb: AsyncSession, view: site_page_views) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def stats(self, cdb: AsyncSession, start: datetime, end: datetime, today_since: datetime, site_id,
|
|
overall: bool) -> Tuple[ErrorType, dict]:
|
|
"""기간 [start, end) 집계 + today_since 이후 고유 방문자. 키: today·summary·daily·referrers·devices + (overall) sites·service_site | (사이트) pages·utm.
|
|
|
|
site_id 를 주면 그 사이트만, 없으면 발행 사이트와 서비스 사이트 공개 화면(site_id NULL)을 합쳐 센다.
|
|
"""
|
|
pass
|
|
|
|
|
|
class VisitCRUD(IVisitCRUD):
|
|
async def add_view(self, cdb: AsyncSession, view: site_page_views) -> ErrorType:
|
|
try:
|
|
return await DB_SESSION_MNG.insert(cdb, view)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def stats(self, cdb: AsyncSession, start: datetime, end: datetime, today_since: datetime, site_id,
|
|
overall: bool) -> Tuple[ErrorType, dict]:
|
|
try:
|
|
v = site_page_views
|
|
scope = v.deleted == False # noqa: E712
|
|
if site_id is not None:
|
|
scope = and_(scope, v.site_id == site_id)
|
|
# 전체(site_id None)는 발행 사이트와 서비스 사이트를 합친다.
|
|
where = and_(scope, v.created_at >= start, v.created_at < end)
|
|
views = func.count().label("views")
|
|
visitors = func.count(distinct(v.visitor_hash)).label("visitors")
|
|
# GROUP BY 는 라벨로 — 같은 식 두 번이면 'Asia/Seoul' 바인드가 갈라져 Postgres 가 거부한다(크롤러 통계와 같은 이유).
|
|
day = func.date(func.timezone("Asia/Seoul", v.created_at)).label("day")
|
|
queries = {
|
|
# 오늘 방문자는 기간 선택과 무관하다 — "오늘 몇 명" 을 묻는 숫자다.
|
|
"today": select(func.count(distinct(v.visitor_hash)).label("n")).where(scope, v.created_at >= today_since),
|
|
"summary": select(
|
|
views, visitors, func.max(v.created_at).label("last_at"),
|
|
# 리퍼러가 빈 방문 — 직접 입력·즐겨찾기·앱·QR 이 섞여 있어 "직접" 으로 단정하지 않는다.
|
|
func.count().filter(v.referrer_domain.is_(None)).label("direct_views"),
|
|
).where(where),
|
|
"daily": select(day, views, visitors).where(where).group_by("day").order_by("day"),
|
|
"referrers": (
|
|
select(v.referrer_domain, views)
|
|
.where(where, v.referrer_domain.isnot(None))
|
|
.group_by(v.referrer_domain)
|
|
.order_by(func.count().desc())
|
|
.limit(20)
|
|
),
|
|
"devices": select(v.device, views).where(where).group_by(v.device).order_by(func.count().desc()),
|
|
}
|
|
if overall:
|
|
queries["sites"] = (
|
|
select(v.site_id, places.place_id, places.name, views, visitors)
|
|
.join(sites, sites.site_id == v.site_id)
|
|
.join(places, places.place_id == sites.place_id)
|
|
.where(where)
|
|
.group_by(v.site_id, places.place_id, places.name)
|
|
.order_by(func.count().desc())
|
|
.limit(20)
|
|
)
|
|
# 서비스 사이트는 묶을 사업장이 없어 위 조인에서 빠진다 — 따로 세서 사이트 표에 한 줄로 끼운다.
|
|
queries["service_site"] = select(views, visitors).where(where, v.site_id.is_(None))
|
|
else:
|
|
queries["pages"] = (
|
|
select(v.path, views, visitors).where(where).group_by(v.path).order_by(func.count().desc()).limit(20)
|
|
)
|
|
queries["utm"] = (
|
|
select(v.utm_source, views)
|
|
.where(where, v.utm_source.isnot(None))
|
|
.group_by(v.utm_source)
|
|
.order_by(func.count().desc())
|
|
.limit(20)
|
|
)
|
|
|
|
out: dict = {}
|
|
for key, query in queries.items():
|
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, {}
|
|
out[key] = list(rows)
|
|
return ErrorType.SUCCESS, out
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, {}
|