Files
o2o-weather/backend/services/my_gak_service.py
T

78 lines
3.6 KiB
Python

import re
from typing import Optional
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import MyGak, User
from common.enums import ErrorType
from crud.my_gak_crud import MyGakCRUD
from services.calc.day_slot import SLOTS
from services.calc.my_gak_calc import MyRule, axes, definition
from services.index_service import IndexService
# 한 사람이 만들 수 있는 내 각 수
MAX_PER_USER = 20
_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b|\d{3,}", re.I)
def gak_name(name: str) -> Optional[str]:
"""앞뒤 공백을 빼고 끝에 '각'을 붙인다. 링크·긴 숫자(전화번호 등)는 받지 않는다."""
name = " ".join(name.split())
if not name or _LINK.search(name):
return None
name = name if name.endswith("각") else f"{name}각"
return name if len(name) <= 12 else None
def my_rule(rule: dict) -> MyRule:
return MyRule(
temp=tuple(rule["temp"]) if rule.get("temp") else None, rain=rule.get("rain"), wind_max=rule.get("wind_max"), air=rule.get("air"),
humidity=tuple(rule["humidity"]) if rule.get("humidity") else None, slots=tuple(s for s in SLOTS if s in (rule.get("slots") or SLOTS)),
)
class MyGakService:
def __init__(self, crud: MyGakCRUD = Depends(MyGakCRUD), index: IndexService = Depends(IndexService)) -> None:
self.crud, self.index = crud, index
async def mine(self, user: User) -> tuple[ErrorType, list[MyGak]]:
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.of_user(s, user.user_id))
return err, rows or []
async def add(self, user: User, name: str, rule: dict) -> tuple[ErrorType, Optional[MyGak]]:
name = gak_name(name)
if name is None:
return ErrorType.INVALID_INPUT, None
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count(s, user.user_id))
if err is not ErrorType.SUCCESS:
return err, None
if n >= MAX_PER_USER:
return ErrorType.INVALID_INPUT, None
return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, name, rule))
async def delete(self, user: User, my_gak_id: int) -> ErrorType:
err, found = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, user.user_id, my_gak_id))
if err is not ErrorType.SUCCESS:
return err
return ErrorType.SUCCESS if found else ErrorType.NOT_FOUND
async def score(self, region_code: str, rules: list[dict]) -> tuple[ErrorType, Optional[tuple[str, list[dict]]]]:
"""조건마다 그 동네 오늘 시간대별 점수. 지금 시간대를 골랐으면 그 점수, 아니면 고른 시간대 중 가장 좋은 점수."""
mine = [my_rule(r) for r in rules]
err, got = await self.index.custom(region_code, [definition(r) for r in mine])
if err is not ErrorType.SUCCESS or got is None:
return err, None
now_slot, parts = got
out = []
for r, p in zip(mine, parts):
picked = {k: v for k, v in p.items() if k in r.slots}
key = now_slot if now_slot in picked else max(picked, key=lambda k: picked[k].score, default=None)
res = picked.get(key) if key else None
out.append({
"score": res.score if res else None, "slot": key if res else None,
"slots": {k: v.score for k, v in picked.items()},
"reasons": [res.notes[a] for a in axes(r) if res.notes.get(a)] if res else [],
})
return ErrorType.SUCCESS, (now_slot, out)