diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index 3e2bca0..4895e83 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -362,3 +362,13 @@ class CommentLike(Base): comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True) user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + + +class MyGak(Base): + __tablename__ = "my_gak" + + my_gak_id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True)) + index_a: Mapped[int] = mapped_column(SmallInteger) + index_b: Mapped[int] = mapped_column(SmallInteger) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) diff --git a/backend/crud/my_gak_crud.py b/backend/crud/my_gak_crud.py new file mode 100644 index 0000000..ab4f117 --- /dev/null +++ b/backend/crud/my_gak_crud.py @@ -0,0 +1,24 @@ +import uuid + +from sqlalchemy import delete, func, select +from sqlalchemy.dialects.postgresql import insert +from sqlalchemy.ext.asyncio import AsyncSession + +from common.database.model.models import MyGak + + +class MyGakCRUD: + async def of_user(self, s: AsyncSession, user_id: uuid.UUID) -> list[MyGak]: + return list((await s.scalars(select(MyGak).where(MyGak.user_id == user_id).order_by(MyGak.my_gak_id))).all()) + + async def count(self, s: AsyncSession, user_id: uuid.UUID) -> int: + return await s.scalar(select(func.count()).select_from(MyGak).where(MyGak.user_id == user_id)) + + async def add(self, s: AsyncSession, user_id: uuid.UUID, a: int, b: int) -> MyGak: + """같은 조합이 이미 있으면 그것을 돌려준다.""" + await s.execute(insert(MyGak).values(user_id=user_id, index_a=a, index_b=b).on_conflict_do_nothing()) + return await s.scalar(select(MyGak).where(MyGak.user_id == user_id, MyGak.index_a == a, MyGak.index_b == b)) + + async def delete(self, s: AsyncSession, user_id: uuid.UUID, my_gak_id: int) -> bool: + res = await s.execute(delete(MyGak).where(MyGak.my_gak_id == my_gak_id, MyGak.user_id == user_id).returning(MyGak.my_gak_id)) + return res.first() is not None diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql index 14452c1..2447543 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -248,6 +248,17 @@ CREATE TABLE IF NOT EXISTS public.comment_like ( PRIMARY KEY (comment_id, user_id) ); +-- 나만의 각: 공식 각 두 개를 섞은 조합. 점수는 저장하지 않고 두 각의 오늘 점수 중 낮은 쪽을 그때 쓴다 +CREATE TABLE IF NOT EXISTS public.my_gak ( + my_gak_id BIGSERIAL PRIMARY KEY, + user_id UUID NOT NULL, + index_a SMALLINT NOT NULL, -- 같은 조합은 하나로: 작은 index_id 가 a + index_b SMALLINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (index_a < index_b) +); +CREATE UNIQUE INDEX IF NOT EXISTS uq_my_gak ON public.my_gak (user_id, index_a, index_b); + -- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다) -- 구 목록. diff --git a/backend/router/router.py b/backend/router/router.py index ea6858a..644fd10 100644 --- a/backend/router/router.py +++ b/backend/router/router.py @@ -11,6 +11,7 @@ from router.v1.auth.account import router as auth_router from router.v1.feed.feed import router as feed_router from router.v1.image.image import router as image_router from router.v1.index.index import router as index_router +from router.v1.my_gak.my_gak import router as my_gak_router from router.v1.reaction.reaction import router as reaction_router from router.v1.region.region import router as region_router from router.v1.season.season import router as season_router @@ -42,6 +43,7 @@ app.include_router(season_router) app.include_router(feed_router) app.include_router(auth_router) app.include_router(reaction_router) +app.include_router(my_gak_router) app.include_router(watch_router) app.include_router(image_router) app.include_router(seo_router) diff --git a/backend/router/v1/my_gak/__init__.py b/backend/router/v1/my_gak/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/router/v1/my_gak/my_gak.py b/backend/router/v1/my_gak/my_gak.py new file mode 100644 index 0000000..87e29e8 --- /dev/null +++ b/backend/router/v1/my_gak/my_gak.py @@ -0,0 +1,41 @@ +from typing import Optional + +from fastapi import APIRouter, Depends, Path + +from common.auth import current_user, optional_user +from common.database.model.models import MyGak, User +from common.enums import ErrorType +from common.models.errors import error_info +from common.models.gmodel import Res_WebPacketProtocol +from router.v1.my_gak.protocol import MyGakData, Req_MyGak, Res_MyGak, Res_MyGakList +from services.my_gak_service import MyGakService + +router = APIRouter(prefix="/v1/my-gak", tags=["my-gak"]) + + +def _data(g: MyGak) -> MyGakData: + return MyGakData(my_gak_id=g.my_gak_id, index_ids=[g.index_a, g.index_b]) + + +@router.get("", response_model=Res_MyGakList, response_model_exclude_none=True, summary="내 각과 섞을 수 있는 공식 각 (로그인 없이도 섞을 수 있는 목록은 보임)") +async def list_my_gak(user: Optional[User] = Depends(optional_user), service: MyGakService = Depends()) -> Res_MyGakList: + err, mixable = await service.mixable() + if err is not ErrorType.SUCCESS: + return Res_MyGakList(result=error_info(err)) + if user is None: + return Res_MyGakList(mixable=mixable) + err, rows = await service.mine(user) + if err is not ErrorType.SUCCESS: + return Res_MyGakList(result=error_info(err)) + return Res_MyGakList(mixable=mixable, items=[_data(g) for g in rows]) + + +@router.post("", response_model=Res_MyGak, response_model_exclude_none=True, summary="공식 각 두 개를 섞어 내 각 만들기 (같은 조합이면 있는 것을 돌려줌)") +async def add_my_gak(req: Req_MyGak, user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_MyGak: + err, g = await service.add(user, req.index_ids) + return Res_MyGak(result=error_info(err)) if err is not ErrorType.SUCCESS or g is None else Res_MyGak(item=_data(g)) + + +@router.delete("/{my_gak_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 각 지우기") +async def delete_my_gak(my_gak_id: int = Path(...), user: User = Depends(current_user), service: MyGakService = Depends()) -> Res_WebPacketProtocol: + return Res_WebPacketProtocol(result=error_info(await service.delete(user, my_gak_id))) diff --git a/backend/router/v1/my_gak/protocol.py b/backend/router/v1/my_gak/protocol.py new file mode 100644 index 0000000..eba7cf3 --- /dev/null +++ b/backend/router/v1/my_gak/protocol.py @@ -0,0 +1,23 @@ +from typing import Optional + +from pydantic import Field + +from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol + + +class MyGakData(WebPacketProtocol): + my_gak_id: int + index_ids: list[int] = Field(description="섞은 공식 각 두 개. 점수는 두 각의 오늘 점수 중 낮은 쪽") + + +class Req_MyGak(Req_WebPacketProtocol): + index_ids: list[int] = Field(min_length=2, max_length=2, description="섞을 공식 각 두 개") + + +class Res_MyGakList(Res_WebPacketProtocol): + mixable: list[int] = Field(default=[], description="섞을 수 있는 공식 각 index_id") + items: list[MyGakData] = Field(default=[], description="내 각. 로그인하지 않았으면 비어 있음") + + +class Res_MyGak(Res_WebPacketProtocol): + item: Optional[MyGakData] = None diff --git a/backend/services/my_gak_service.py b/backend/services/my_gak_service.py new file mode 100644 index 0000000..ee91f23 --- /dev/null +++ b/backend/services/my_gak_service.py @@ -0,0 +1,48 @@ +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, IndexCategory +from crud.index_crud import IndexCRUD +from crud.my_gak_crud import MyGakCRUD + +# 한 사람이 만들 수 있는 조합 수 +MAX_PER_USER = 20 + + +class MyGakService: + def __init__(self, crud: MyGakCRUD = Depends(MyGakCRUD), index: IndexCRUD = Depends(IndexCRUD)) -> None: + self.crud, self.index = crud, index + + async def mixable(self) -> tuple[ErrorType, list[int]]: + """섞을 수 있는 공식 각. 생활 고민(우산·교통체증처럼 불편한 날을 알리는 각)은 좋은 날 각과 섞으면 뜻이 뒤집혀 뺀다.""" + err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.index.definitions(s)) + if err is not ErrorType.SUCCESS: + return err, [] + return ErrorType.SUCCESS, [d.index_id for d in defs if d.category != IndexCategory.LIFE.value] + + 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, index_ids: list[int]) -> tuple[ErrorType, Optional[MyGak]]: + a, b = sorted(index_ids) + err, ok = await self.mixable() + if err is not ErrorType.SUCCESS: + return err, None + if a == b or a not in ok or b not in ok: + 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, a, b)) + + 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 diff --git a/backend/tests/test_my_gak.py b/backend/tests/test_my_gak.py new file mode 100644 index 0000000..998e2f7 --- /dev/null +++ b/backend/tests/test_my_gak.py @@ -0,0 +1,59 @@ +import pytest +from httpx import ASGITransport, AsyncClient + +from common.database.db_session_manager import DB_SESSION_MNG +from crud.index_crud import IndexCRUD +from router.router import app +from services.my_gak_service import MAX_PER_USER + + +def client(): + return AsyncClient(transport=ASGITransport(app=app), base_url="http://test") + + +async def _login(c, login_id: str) -> dict: + body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": "섞기토끼"})).json() + return {"Authorization": f"Bearer {body['access_token']}"} + + +@pytest.mark.anyio +async def test_mixable_without_login_excludes_life_gak(): + async with client() as c: + body = (await c.get("/v1/my-gak")).json() + _, defs = await DB_SESSION_MNG.execute_lambda(lambda s: IndexCRUD().definitions(s)) + ids = {d.name: d.index_id for d in defs} + assert body["items"] == [] + mixable = set(body["mixable"]) + assert {ids["러닝각"], ids["치맥각"]} <= mixable + assert not {ids["우산각"], ids["교통체증각"]} & mixable + + +@pytest.mark.anyio +async def test_add_list_delete_and_same_pair_is_one(): + async with client() as c: + assert (await c.post("/v1/my-gak", json={"index_ids": [1, 2]})).status_code == 401 + h = await _login(c, "mix_01") + a, b = sorted((await c.get("/v1/my-gak")).json()["mixable"])[:2] + first = (await c.post("/v1/my-gak", json={"index_ids": [b, a]}, headers=h)).json()["item"] + assert first["index_ids"] == [a, b] + again = (await c.post("/v1/my-gak", json={"index_ids": [a, b]}, headers=h)).json()["item"] + assert again["my_gak_id"] == first["my_gak_id"] + assert [g["my_gak_id"] for g in (await c.get("/v1/my-gak", headers=h)).json()["items"]] == [first["my_gak_id"]] + assert (await c.delete(f"/v1/my-gak/{first['my_gak_id']}", headers=h)).json()["result"]["success"] is True + assert (await c.get("/v1/my-gak", headers=h)).json()["items"] == [] + assert (await c.delete(f"/v1/my-gak/{first['my_gak_id']}", headers=h)).json()["result"]["desc"] == "NOT_FOUND" + + +@pytest.mark.anyio +async def test_rejects_same_gak_unmixable_and_over_limit(): + async with client() as c: + h = await _login(c, "mix_02") + mixable = sorted((await c.get("/v1/my-gak")).json()["mixable"]) + bad = lambda ids: c.post("/v1/my-gak", json={"index_ids": ids}, headers=h) # noqa: E731 + assert (await bad([mixable[0], mixable[0]])).json()["result"]["desc"] == "INVALID_INPUT" + assert (await bad([mixable[0], 9999])).json()["result"]["desc"] == "INVALID_INPUT" + assert (await bad([mixable[0]])).status_code == 422 + pairs = [(mixable[0], x) for x in mixable[1 : MAX_PER_USER + 1]] + for p in pairs: + assert (await bad(list(p))).json()["item"] + assert (await bad([mixable[1], mixable[2]])).json()["result"]["desc"] == "INVALID_INPUT" diff --git a/frontend/src/api/client/@tanstack/react-query.gen.ts b/frontend/src/api/client/@tanstack/react-query.gen.ts index 1cb695b..962ad5a 100644 --- a/frontend/src/api/client/@tanstack/react-query.gen.ts +++ b/frontend/src/api/client/@tanstack/react-query.gen.ts @@ -3,8 +3,8 @@ import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; -import { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen'; -import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen'; +import { addComment, addMyGak, deleteComment, deleteMyGak, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen'; +import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTodayGuPageData, GetTodayGuPageError, GetTodayGuPageResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen'; export type QueryKey = [ Pick & { @@ -709,6 +709,58 @@ export const likeCommentMutation = (options?: Partial>) return mutationOptions; }; +export const listMyGakQueryKey = (options?: Options) => createQueryKey('listMyGak', options); + +/** + * 내 각과 섞을 수 있는 공식 각 (로그인 없이도 섞을 수 있는 목록은 보임) + */ +export const listMyGakOptions = (options?: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await listMyGak({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: listMyGakQueryKey(options) +}); + +/** + * 공식 각 두 개를 섞어 내 각 만들기 (같은 조합이면 있는 것을 돌려줌) + */ +export const addMyGakMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await addMyGak({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * 내 각 지우기 + */ +export const deleteMyGakMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteMyGak({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + export const getWatchSummaryQueryKey = (options: Options) => createQueryKey('getWatchSummary', options); /** @@ -745,6 +797,42 @@ export const getImageOptions = (options: Options) => queryOptions< queryKey: getImageQueryKey(options) }); +export const getTodayPageQueryKey = (options: Options) => createQueryKey('getTodayPage', options); + +/** + * 지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김) + */ +export const getTodayPageOptions = (options: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await getTodayPage({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: getTodayPageQueryKey(options) +}); + +export const getTodayGuPageQueryKey = (options: Options) => createQueryKey('getTodayGuPage', options); + +/** + * 구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang) + */ +export const getTodayGuPageOptions = (options: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await getTodayGuPage({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: getTodayGuPageQueryKey(options) +}); + export const healthzHealthzGetQueryKey = (options?: Options) => createQueryKey('healthzHealthzGet', options); /** diff --git a/frontend/src/api/client/index.ts b/frontend/src/api/client/index.ts index bb70c7a..3e861c9 100644 --- a/frontend/src/api/client/index.ts +++ b/frontend/src/api/client/index.ts @@ -1,4 +1,4 @@ // This file is auto-generated by @hey-api/openapi-ts -export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen'; -export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide } from './types.gen'; +export { addComment, addMyGak, deleteComment, deleteMyGak, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen'; +export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type MyGakData, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqMyGak, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResMyGak, type ResMyGakList, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide } from './types.gen'; diff --git a/frontend/src/api/client/sdk.gen.ts b/frontend/src/api/client/sdk.gen.ts index 3e6ebe7..acc5525 100644 --- a/frontend/src/api/client/sdk.gen.ts +++ b/frontend/src/api/client/sdk.gen.ts @@ -2,7 +2,7 @@ import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client'; import { client } from './client.gen'; -import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen'; +import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen'; export type Options = Options2 & { /** @@ -218,6 +218,28 @@ export const unlikeComment = (options: Opti */ export const likeComment = (options: Options): RequestResult => (options.client ?? client).post({ url: '/v1/reaction/comment/{comment_id}/like', ...options }); +/** + * 내 각과 섞을 수 있는 공식 각 (로그인 없이도 섞을 수 있는 목록은 보임) + */ +export const listMyGak = (options?: Options): RequestResult => (options?.client ?? client).get({ url: '/v1/my-gak', ...options }); + +/** + * 공식 각 두 개를 섞어 내 각 만들기 (같은 조합이면 있는 것을 돌려줌) + */ +export const addMyGak = (options: Options): RequestResult => (options.client ?? client).post({ + url: '/v1/my-gak', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +/** + * 내 각 지우기 + */ +export const deleteMyGak = (options: Options): RequestResult => (options.client ?? client).delete({ url: '/v1/my-gak/{my_gak_id}', ...options }); + /** * 워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표 */ @@ -228,6 +250,16 @@ export const getWatchSummary = (options: Op */ export const getImage = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/image', ...options }); +/** + * 지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김) + */ +export const getTodayPage = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/seo/today/{sido}/{place}', ...options }); + +/** + * 구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang) + */ +export const getTodayGuPage = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/seo/today/{sido}/{place}/{gu}', ...options }); + /** * 헬스체크 */ diff --git a/frontend/src/api/client/types.gen.ts b/frontend/src/api/client/types.gen.ts index 17f3389..794a8b2 100644 --- a/frontend/src/api/client/types.gen.ts +++ b/frontend/src/api/client/types.gen.ts @@ -830,6 +830,22 @@ export type Me = { provider: AuthProvider; }; +/** + * MyGakData + */ +export type MyGakData = { + /** + * My Gak Id + */ + my_gak_id: number; + /** + * Index Ids + * + * 섞은 공식 각 두 개. 점수는 두 각의 오늘 점수 중 낮은 쪽 + */ + index_ids: Array; +}; + /** * PlaceData */ @@ -1219,6 +1235,21 @@ export type ReqLogin = { password: string; }; +/** + * Req_MyGak + */ +export type ReqMyGak = { + /** + * Index Ids + * + * 섞을 공식 각 두 개 + */ + index_ids: [ + number, + number + ]; +}; + /** * Req_Refresh */ @@ -1535,6 +1566,41 @@ export type ResMe = { me?: Me | null; }; +/** + * Res_MyGak + */ +export type ResMyGak = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; + item?: MyGakData | null; +}; + +/** + * Res_MyGakList + */ +export type ResMyGakList = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; + /** + * Mixable + * + * 섞을 수 있는 공식 각 index_id + */ + mixable?: Array; + /** + * Items + * + * 내 각. 로그인하지 않았으면 비어 있음 + */ + items?: Array; +}; + /** * Res_PlaceList */ @@ -2635,6 +2701,10 @@ export type WatchNow = { * Rain 2H */ rain_2h?: boolean | null; + /** + * Thunder + */ + thunder?: boolean | null; /** * Text */ @@ -3955,6 +4025,104 @@ export type LikeCommentResponses = { export type LikeCommentResponse = LikeCommentResponses[keyof LikeCommentResponses]; +export type ListMyGakData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: never; + url: '/v1/my-gak'; +}; + +export type ListMyGakErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListMyGakError = ListMyGakErrors[keyof ListMyGakErrors]; + +export type ListMyGakResponses = { + /** + * Successful Response + */ + 200: ResMyGakList; +}; + +export type ListMyGakResponse = ListMyGakResponses[keyof ListMyGakResponses]; + +export type AddMyGakData = { + body: ReqMyGak; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: never; + url: '/v1/my-gak'; +}; + +export type AddMyGakErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type AddMyGakError = AddMyGakErrors[keyof AddMyGakErrors]; + +export type AddMyGakResponses = { + /** + * Successful Response + */ + 200: ResMyGak; +}; + +export type AddMyGakResponse = AddMyGakResponses[keyof AddMyGakResponses]; + +export type DeleteMyGakData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path: { + /** + * My Gak Id + */ + my_gak_id: number; + }; + query?: never; + url: '/v1/my-gak/{my_gak_id}'; +}; + +export type DeleteMyGakErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type DeleteMyGakError = DeleteMyGakErrors[keyof DeleteMyGakErrors]; + +export type DeleteMyGakResponses = { + /** + * Successful Response + */ + 200: ResWebPacketProtocol; +}; + +export type DeleteMyGakResponse = DeleteMyGakResponses[keyof DeleteMyGakResponses]; + export type GetWatchSummaryData = { body?: never; path?: never; @@ -4031,6 +4199,78 @@ export type GetImageResponses = { 200: unknown; }; +export type GetTodayPageData = { + body?: never; + path: { + /** + * Sido + */ + sido: string; + /** + * Place + */ + place: string; + }; + query?: never; + url: '/v1/seo/today/{sido}/{place}'; +}; + +export type GetTodayPageErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type GetTodayPageError = GetTodayPageErrors[keyof GetTodayPageErrors]; + +export type GetTodayPageResponses = { + /** + * Successful Response + */ + 200: string; +}; + +export type GetTodayPageResponse = GetTodayPageResponses[keyof GetTodayPageResponses]; + +export type GetTodayGuPageData = { + body?: never; + path: { + /** + * Sido + */ + sido: string; + /** + * Place + */ + place: string; + /** + * Gu + */ + gu: string; + }; + query?: never; + url: '/v1/seo/today/{sido}/{place}/{gu}'; +}; + +export type GetTodayGuPageErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type GetTodayGuPageError = GetTodayGuPageErrors[keyof GetTodayGuPageErrors]; + +export type GetTodayGuPageResponses = { + /** + * Successful Response + */ + 200: string; +}; + +export type GetTodayGuPageResponse = GetTodayGuPageResponses[keyof GetTodayGuPageResponses]; + export type HealthzHealthzGetData = { body?: never; path?: never; diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx index 4a93525..b208dec 100644 --- a/frontend/src/b/Sheets.tsx +++ b/frontend/src/b/Sheets.tsx @@ -25,6 +25,8 @@ import { track } from '../lib/analytics' import { cx } from '../lib/utils' import { useAuth } from './authContext' import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib' +import { MixSheet } from './myGak' +import { useMyGak } from './myGakState' import { ownPage, useRegion } from './regionContext' import { useSky } from './skyContext' import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage' @@ -102,7 +104,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }, [isOpen]) const then = state?.type === 'login' ? state.then : undefined - const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type] + const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type] return ( void {state.type === 'login' && open(then) : onClose} />} {state.type === 'me' && } {state.type === 'region' && } + {state.type === 'mix' && } )} {!state && } @@ -323,6 +326,8 @@ function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[]; function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string) => void }) { const { region } = useRegion() + const { open } = useSheet() + const { mixable } = useMyGak() const q = useQuery(getIndexOptions({ path: { index_id: indexId }, query: { region: region.code } })) const d: ResIndexDetail | undefined = q.data const g = d?.index @@ -355,6 +360,11 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string) {g.score} {!g.active &&

지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.

} + {mixable.has(g.index_id) && ( + + )} {now && (

{now.low}~{now.high}점 diff --git a/frontend/src/b/TodayPage.tsx b/frontend/src/b/TodayPage.tsx index 3be96ae..07b2a0d 100644 --- a/frontend/src/b/TodayPage.tsx +++ b/frontend/src/b/TodayPage.tsx @@ -5,6 +5,7 @@ import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/ import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TopIndex, type WeatherSlot } from '../api/client/types.gen' import { cx } from '../lib/utils' import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib' +import { MyGakRow } from './myGak' import { PostCard, PostCardSkel } from './Post' import { useRegion } from './regionContext' import { useSheet } from './sheetContext' @@ -352,6 +353,7 @@ export function TodayPage() { const feed = useQuery(getFeedOptions({ query: { region: region.code } })) const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } })) const { preview } = useSky() + const { open } = useSheet() const f = feed.data const posts = f?.posts ?? [] const stories = atSlot(f?.stories ?? [], preview) @@ -364,6 +366,16 @@ export function TodayPage() { window.scrollTo({ top: 0 }) }, [region.code]) + // 친구가 보낸 섞은 각 링크(/?mix=3,8)로 들어오면 내 동네 기준으로 보여 준다 + useEffect(() => { + const url = new URL(window.location.href) + const ids = url.searchParams.get('mix')?.split(',').map(Number).filter(Number.isInteger) + if (!ids || ids.length !== 2) return + url.searchParams.delete('mix') + window.history.replaceState(window.history.state, '', url) + open({ type: 'mix', ids, shared: true }) + }, [open]) + // 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다 const bandAt: [number, ReactNode][] = [ [3, bands?.events?.length ? : null], @@ -375,6 +387,7 @@ export function TodayPage() { // 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다

+ {/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */} {stories.length ? : load === 'loading' ? : feed.refetch()} empty="오늘 계산된 각이 없어요." hold={} className="inset-x-3 top-3 bottom-1" />} diff --git a/frontend/src/b/myGak.tsx b/frontend/src/b/myGak.tsx new file mode 100644 index 0000000..7e0c661 --- /dev/null +++ b/frontend/src/b/myGak.tsx @@ -0,0 +1,135 @@ +import { useQuery } from '@tanstack/react-query' +import { useState } from 'react' +import { getFeedOptions } from '../api/client/@tanstack/react-query.gen' +import type { TopIndex } from '../api/client/types.gen' +import { cx } from '../lib/utils' +import { mix, shareUrl, useMyGak } from './myGakState' +import { useRegion } from './regionContext' +import { useSheet } from './sheetContext' +import { Ic, Sec } from './ui' + +function Bar({ g, low }: { g: TopIndex; low: boolean }) { + return ( + + {g.name} + {g.score} + + + + + ) +} + +/** 오늘 탭의 내 각 줄: 섞은 각 카드들과 새로 섞기 */ +export function MyGakRow({ stories }: { stories: TopIndex[] }) { + const { open } = useSheet() + const { pairs, remove } = useMyGak() + const [copied, setCopied] = useState(null) + const send = (ids: number[], name: string) => { + const url = shareUrl(ids) + if (navigator.share) { + navigator.share({ title: `${name} · 날씨각`, url }).catch((e: unknown) => { + if (!(e instanceof DOMException && e.name === 'AbortError')) console.error('[myGak] share', e) + }) + return + } + navigator.clipboard.writeText(url).then( + () => setCopied(ids.join()), + (e: unknown) => console.error('[myGak] copy', e), + ) + } + if (!stories.length) return null + return ( + <> + +
+ {pairs.map((p) => { + const m = mix(stories, p.ids) + if (!m) return null + return ( +
+
+ + + {m.name} + {m.score} +
+ + +
+ + +
+
+ ) + })} + +
+ + ) +} + +/** 섞을 각 고르기와 미리보기. ids 가 둘이면(받은 링크) 바로 미리보기 */ +export function MixSheet({ ids: start = [], shared = false, onDone }: { ids?: number[]; shared?: boolean; onDone: () => void }) { + const { region } = useRegion() + const stories = useQuery(getFeedOptions({ query: { region: region.code } })).data?.stories ?? [] + const { mixable, has, create, pending } = useMyGak() + const [ids, setIds] = useState(start.slice(0, 2)) + const choices = stories.filter((g) => mixable.has(g.index_id)) + const m = ids.length === 2 ? mix(stories, ids) : null + const owned = ids.length === 2 && has(ids) + const toggle = (id: number) => setIds((now) => (now.includes(id) ? now.filter((x) => x !== id) : now.length < 2 ? [...now, id] : [now[0], id])) + + return ( +
+ {!shared && ( + <> +

{ids.length === 2 ? '이 둘을 섞어요' : ids.length ? '하나 더 골라요' : '섞을 각 두 개를 골라요'}

+

함께 할 일끼리 골라요. 점수는 둘 중 낮은 쪽이에요

+
+ {choices.map((g) => { + const on = ids.includes(g.index_id) + return ( + + ) + })} +
+ + )} + {m && ( +
+ {shared &&

친구가 보낸 각이에요. {region.name} 기준 점수예요

} +
+ + + {m.name} + {m.score} +
+ + +

+ {m.a.score === m.b.score ? '두 각 점수가 같아요' : `오늘은 ${m.low.name} 점수를 따라가요`} +

+
+ )} + +
+ ) +} diff --git a/frontend/src/b/myGakState.ts b/frontend/src/b/myGakState.ts new file mode 100644 index 0000000..66968d5 --- /dev/null +++ b/frontend/src/b/myGakState.ts @@ -0,0 +1,99 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useEffect, useSyncExternalStore } from 'react' +import { SITE_URL } from '../api/setup' +import { addMyGakMutation, deleteMyGakMutation, listMyGakOptions, listMyGakQueryKey } from '../api/client/@tanstack/react-query.gen' +import type { TopIndex } from '../api/client/types.gen' +import { useAuth } from './authContext' +import { useSheet } from './sheetContext' + +const KEY = 'nalssigak.b.myGak' + +/** 로그인하지 않으면 이 기기에 하나만 */ +export type Pair = { id?: number; ids: [number, number] } + +const sameIds = (a: number[], b: number[]) => a.length === 2 && b.length === 2 && a[0] === b[0] && a[1] === b[1] +const sorted = (ids: number[]) => [...ids].sort((x, y) => x - y) as [number, number] + +function readLocal(): [number, number] | null { + try { + const raw = localStorage.getItem(KEY) + return raw ? sorted(JSON.parse(raw) as number[]) : null + } catch { + // 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로 + return null + } +} + +// 시트와 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다 +let local = readLocal() +const listeners = new Set<() => void>() +const subscribe = (cb: () => void) => { + listeners.add(cb) + return () => listeners.delete(cb) +} + +function setLocal(ids: [number, number] | null) { + local = ids + listeners.forEach((cb) => cb()) + try { + if (ids) localStorage.setItem(KEY, JSON.stringify(ids)) + else localStorage.removeItem(KEY) + } catch (e) { + console.warn('[myGak] 기기에 저장하지 못함', e) + } +} + +/** 두 각 이름을 이어 붙인 이름: 러닝각 + 치맥각 → 러닝·치맥각 */ +const pairName = (a: TopIndex, b: TopIndex) => `${a.name.replace(/각$/, '')}·${b.name}` + +/** 섞은 각 점수: 둘 다 좋아야 좋은 날이라 낮은 쪽 */ +export function mix(stories: TopIndex[], ids: number[]) { + const a = stories.find((g) => g.index_id === ids[0]) + const b = stories.find((g) => g.index_id === ids[1]) + if (!a || !b) return null + return { a, b, name: pairName(a, b), score: Math.min(a.score, b.score), low: a.score <= b.score ? a : b } +} + +export const shareUrl = (ids: number[]) => `${SITE_URL}/?mix=${ids.join(',')}` + +export function useMyGak() { + const { loggedIn } = useAuth() + const { open } = useSheet() + const queryClient = useQueryClient() + const q = useQuery(listMyGakOptions()) + const saved = useSyncExternalStore(subscribe, () => local) + const add = useMutation({ ...addMyGakMutation(), onSuccess: () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() }) }) + const del = useMutation({ ...deleteMyGakMutation(), onSuccess: () => queryClient.invalidateQueries({ queryKey: listMyGakQueryKey() }) }) + + // 로그인하면 이 기기에 만들어 둔 각을 계정으로 옮긴다 + const { mutate } = add + useEffect(() => { + if (!loggedIn || !saved) return + mutate({ body: { index_ids: saved } }, { onSuccess: () => setLocal(null) }) + }, [loggedIn, saved, mutate]) + + const pairs: Pair[] = loggedIn ? (q.data?.items ?? []).map((g) => ({ id: g.my_gak_id, ids: sorted(g.index_ids) })) : saved ? [{ ids: saved }] : [] + const has = (ids: number[]) => pairs.some((p) => sameIds(p.ids, sorted(ids))) + + /** 로그인 없이 두 번째를 만들려 하면 로그인 창을 띄운다 */ + const create = (ids: number[], onDone?: () => void) => { + const two = sorted(ids) + if (loggedIn) { + add.mutate({ body: { index_ids: two } }, { onSuccess: onDone }) + return + } + if (saved && !sameIds(saved, two)) { + open({ type: 'login' }) + return + } + setLocal(two) + onDone?.() + } + + const remove = (p: Pair) => { + if (p.id != null) return del.mutate({ path: { my_gak_id: p.id } }) + setLocal(null) + } + + return { mixable: new Set(q.data?.mixable ?? []), pairs, has, create, remove, pending: add.isPending } +} diff --git a/frontend/src/b/sheetContext.ts b/frontend/src/b/sheetContext.ts index 25b5977..f5e2aa9 100644 --- a/frontend/src/b/sheetContext.ts +++ b/frontend/src/b/sheetContext.ts @@ -12,6 +12,7 @@ export type SheetState = | { type: 'login'; then?: CommentsState } | { type: 'me' } | { type: 'region' } + | { type: 'mix'; ids?: number[]; shared?: boolean } | null export type SheetApi = { open: (s: Exclude) => void; close: () => void }