feat: 오늘 한 장 — 하루 한 장 날씨 카드(22장)·실제 날씨 행운·연속 도장·저녁 체크인

- 로그인 안 하면 기기에, 로그인하면 계정에 남기고 로그인할 때 기기 기록을 옮긴다 (표 fortune_draw·day_log)
- 행운 시간은 오늘 남은 구간 중 날씨 점수가 가장 높은 때, 장소는 날씨 맞춤 데이트 명소, 1위 각은 지금 순위
- 체크인은 해 지기 2시간 전부터: 기분·다녀온 곳(명소·노을 명소·지금 하는 행사에서 찾거나 직접)·카드 맞았나
- GA4 fortune_draw·day_log
This commit is contained in:
minaChoi committed 2026-10-28 13:22:55 +09:00
1 parent 52a4830b08
commit c37773f48f
43 files changed
+1567 -6

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+2
View File
@@ -23,6 +23,7 @@ import { FoliageCard } from './foliageMap'
import { InstallBanner } from './installBanner'
import { MoonArt } from './moon'
import { MyGakRow } from './myGak'
import { TodayCard } from './fortune'
import { fromShare } from './myGakState'
import { PostCard, PostCardSkel, PostFrame } from './Post'
import { usePinnedLike } from './pinnedLike'
@@ -638,6 +639,7 @@ export function TodayPage() {
// 피드 칸은 전국 공통이라 지역이 바뀌어도 글 번호가 같다. 지역마다 새로 그려 넘긴 슬라이드·펼친 상태가 남지 않게 한다
<section key={region.code} aria-label="오늘" aria-busy={load === 'loading'} className={cx('transition-opacity', feed.isPlaceholderData && 'opacity-60')}>
<Hero hero={f?.hero} post={f?.hero_post} today={today.data} ranked={stories} all={f?.stories ?? []} feedLoad={load} todayLoad={loadOf(today)} />
<TodayCard />
<ShortsRail />
<FeedComposer />
{mine.length > 0 && <TalkGroup title="오늘 내 글" talks={mine} href="/talk?mine=1" />}
+20
View File
@@ -708,3 +708,23 @@ html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot,
.b-app[data-t='night'] .b-tab-main > span {
--tw-ring-color: rgb(18 24 60 / 0.9);
}
/* 오늘 한 장: 뽑은 카드가 뒤집히며 나온다 */
.b-card-flip {
animation: b-card-flip 0.55s cubic-bezier(0.2, 0.8, 0.3, 1);
}
@keyframes b-card-flip {
0% {
opacity: 0.4;
transform: perspective(600px) rotateY(90deg);
}
100% {
opacity: 1;
transform: perspective(600px) rotateY(0);
}
}
@media (prefers-reduced-motion: reduce) {
.b-card-flip {
animation: none;
}
}
+336
View File
@@ -0,0 +1,336 @@
import { useEffect, useRef, useState, useSyncExternalStore } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { getFortuneTodayOptions, getFortuneTodayQueryKey, importFortuneMutation, searchFortunePlacesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { drawFortune, saveDayLog } from '@nalssigak/shared/api/client/sdk.gen'
import type { DayLogData, LocalDraw, LocalLog, ResFortuneToday } from '@nalssigak/shared/api/client/types.gen'
import { kst } from '@nalssigak/shared/lib'
import { track } from '../lib/analytics'
import { cx } from '../lib/utils'
import { useAuth } from './authContext'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { Ic, Sec } from './ui'
const KEY = 'nalssigak.b.fortune'
// 기기에 남기는 날 수 (서버도 이 안쪽만 받는다)
const KEEP_DAYS = 60
const MOODS = ['😆', '🙂', '😐', '😕', '😢']
const STAMPS = 7
/** 로그인하지 않았을 때 이 기기에 남기는 뽑은 카드·체크인 */
type Local = { draws: LocalDraw[]; logs: LocalLog[] }
const EMPTY: Local = { draws: [], logs: [] }
function readLocal(): Local {
try {
const raw = localStorage.getItem(KEY)
return raw ? { ...EMPTY, ...(JSON.parse(raw) as Local) } : EMPTY
} catch {
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 이번 방문엔 없는 것으로
return EMPTY
}
}
let local = readLocal()
const listeners = new Set<() => void>()
const subscribe = (cb: () => void) => {
listeners.add(cb)
return () => listeners.delete(cb)
}
function setLocal(next: Local) {
const recent = <T extends { day: string }>(rows: T[]) => [...rows].sort((a, b) => b.day.localeCompare(a.day)).slice(0, KEEP_DAYS)
local = { draws: recent(next.draws), logs: recent(next.logs) }
listeners.forEach((cb) => cb())
try {
if (local.draws.length || local.logs.length) localStorage.setItem(KEY, JSON.stringify(local))
else localStorage.removeItem(KEY)
} catch (e) {
console.warn('[fortune] 기기에 저장하지 못함', e)
}
}
const pad = (n: number) => String(n).padStart(2, '0')
function todayKst() {
const t = kst(new Date())
return `${t.y}-${pad(t.mo)}-${pad(t.d)}`
}
async function draw(regionCode: string, cardCode?: string, days: string[] = []): Promise<ResFortuneToday> {
const { data } = await drawFortune({ body: { region_code: regionCode, card_code: cardCode, days } })
if (!data.result?.success || !data.card) throw new Error(data.result?.desc ?? 'draw')
return data
}
/** 오늘 카드·행운·체크인. 로그인했으면 서버, 아니면 이 기기에 있는 오늘 카드로 행운만 서버에서 받는다 */
function useTodayCard() {
const { loggedIn } = useAuth()
const { region } = useRegion()
const queryClient = useQueryClient()
const saved = useSyncExternalStore(subscribe, () => local)
const day = todayKst()
const mine = saved.draws.find((d) => d.day === day)
const pastDays = saved.draws.filter((d) => d.day < day).map((d) => d.day)
const serverKey = getFortuneTodayQueryKey({ query: { region: region.code } })
const deviceKey = ['fortuneDevice', region.code, mine?.card_code, day]
const server = useQuery({ ...getFortuneTodayOptions({ query: { region: region.code } }), enabled: loggedIn, staleTime: 5 * 60_000 })
const device = useQuery({
queryKey: deviceKey,
enabled: !loggedIn && !!mine,
staleTime: 5 * 60_000,
queryFn: () => draw(region.code, mine?.card_code, pastDays),
})
const pick = useMutation({
mutationFn: () => draw(region.code, undefined, loggedIn ? [] : pastDays),
onSuccess: (data) => {
track('fortune_draw', { card: data.card!.code })
if (loggedIn) {
queryClient.setQueryData(serverKey, data)
return
}
setLocal({ ...local, draws: [...local.draws.filter((d) => d.day !== data.day), { day: data.day!, card_code: data.card!.code }] })
queryClient.setQueryData(['fortuneDevice', region.code, data.card!.code, data.day], data)
},
})
// 로그인하면 이 기기에 있던 기록을 계정으로 옮긴다
const { mutate: moveUp } = useMutation({ ...importFortuneMutation() })
useEffect(() => {
if (!loggedIn || (!saved.draws.length && !saved.logs.length)) return
moveUp(
{ body: { draws: saved.draws, logs: saved.logs } },
{
onSuccess: (res) => {
if (!res.result?.success) return
setLocal(EMPTY)
queryClient.invalidateQueries({ queryKey: serverKey })
},
},
)
}, [loggedIn, saved, moveUp, queryClient, serverKey])
const today = loggedIn ? server.data : device.data
const log: DayLogData | LocalLog | undefined = (loggedIn ? today?.log : saved.logs.find((g) => g.day === day)) ?? undefined
const saveLog = useMutation({
mutationFn: async (v: Omit<LocalLog, 'day' | 'region_code'>) => {
const body = { ...v, region_code: region.code }
if (!loggedIn) {
setLocal({ ...local, logs: [...local.logs.filter((g) => g.day !== day), { ...body, day }] })
return
}
const { data } = await saveDayLog({ body })
if (!data.result?.success || !data.log) throw new Error(data.result?.desc ?? 'log')
queryClient.setQueryData(serverKey, (old: ResFortuneToday | undefined) => (old ? { ...old, log: data.log } : old))
},
onSuccess: (_, v) => track('day_log', { mood: v.mood, went_out: v.went_out, card_hit: v.card_hit ?? null }),
})
const loading = loggedIn ? server.isPending : !!mine && device.isPending
return { today, log, loading, pick, saveLog, loggedIn }
}
/** 오늘 탭 '오늘 한 장': 하루 한 장 뽑는 날씨 카드, 실제 날씨로 정한 행운, 연속 도장, 저녁엔 체크인 */
export function TodayCard() {
const { today, log, loading, pick, saveLog, loggedIn } = useTodayCard()
const { open } = useSheet()
const shot = useRef<HTMLDivElement>(null)
const card = today?.card
const luck = today?.luck
const streak = today?.streak ?? 0
const filled = streak > 0 ? ((streak - 1) % STAMPS) + 1 : 0
const share = () => {
if (card && shot.current) open({ type: 'share', share: { title: `오늘 내 날씨 카드는 ${card.name}`, slides: [shot.current] } })
}
return (
<>
<Sec title="오늘 한 장" />
<div className="mx-4 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
{!card ? (
<button
type="button"
onClick={() => pick.mutate()}
disabled={loading || pick.isPending}
className="mx-auto flex w-full cursor-pointer flex-col items-center gap-2"
>
<img src="/fortune/back.webp" alt="" className={cx('aspect-[2/3] w-[150px] rounded-2xl object-cover', (loading || pick.isPending) && 'animate-pulse')} />
<span className="font-jua text-[16px] text-(--orange)">눌러서 오늘 카드 뽑기</span>
</button>
) : (
<div ref={shot} className="b-card-flip rounded-2xl bg-white">
<div className="flex gap-3">
<img src={`/fortune/${card.code}.webp`} alt={card.name} className="aspect-[2/3] w-[112px] shrink-0 rounded-xl object-cover" />
<div className="flex min-w-0 flex-col justify-center gap-1.5">
<b className="font-jua text-[22px] leading-tight font-normal">{card.name}</b>
<p className="m-0 text-[14px] leading-snug font-semibold text-(--ink2)">{card.reading}</p>
</div>
</div>
{luck && (
<dl className="m-0 mt-3 grid grid-cols-2 gap-1.5">
<Luck label="행운 시간" value={luck.time} sub="날씨가 가장 좋은 때" />
<Luck label="행운 장소" value={luck.place} />
<Luck label="행운 색" value={card.color} swatch={card.hex} />
<Luck label="오늘 1위" value={luck.top_gak} icon={luck.top_icon} />
</dl>
)}
<p className="m-0 mt-2 text-center text-[11px] font-semibold text-(--ink3)">재미로 보는 날씨 운세</p>
</div>
)}
{(streak > 0 || card) && (
<div className="mt-2.5 flex items-center gap-1.5">
{streak > 0 && (
<>
<span className="flex gap-1" aria-hidden>
{Array.from({ length: STAMPS }, (_, i) => (
<i key={i} className={cx('grid size-[18px] place-items-center rounded-full text-[10px] not-italic', i < filled ? 'bg-(--orange) text-white' : 'bg-[#ffe2cf]')}>
{i < filled ? '✓' : ''}
</i>
))}
</span>
<span className="text-xs font-bold text-(--ink2)">{streak}일째</span>
</>
)}
{card && (
<button type="button" onClick={share} className="ml-auto cursor-pointer rounded-full bg-(--ink) px-4 py-1.5 text-[13px] font-extrabold text-white">
공유
</button>
)}
</div>
)}
{card && today?.checkin_open && <CheckIn log={log} saving={saveLog.isPending} onSave={(v) => saveLog.mutate(v)} anon={!loggedIn} />}
</div>
</>
)
}
function Luck({ label, value, sub, swatch, icon }: { label: string; value?: string | null; sub?: string; swatch?: string; icon?: string | null }) {
if (!value) return null
return (
<div className="rounded-xl bg-[#fff6ef] px-2.5 py-2">
<dt className="text-[11px] font-bold text-(--ink3)">{label}</dt>
<dd className="m-0 flex items-center gap-1 text-[14px] leading-tight font-extrabold">
{swatch && <span aria-hidden className="size-3 shrink-0 rounded-[4px] border border-black/10" style={{ background: swatch }} />}
{icon && <Ic name={icon} className="size-5 shrink-0" />}
<span className="truncate">{value}</span>
</dd>
{sub && <p className="m-0 text-[10.5px] font-semibold text-(--ink3)">{sub}</p>}
</div>
)
}
type LogInput = { mood: number; went_out: boolean; place_name?: string | null; place_ref?: string | null; card_hit?: boolean | null }
/** 저녁 체크인: 기분 하나, 다녀온 곳(목록에서 찾거나 직접), 오늘 카드 맞았나 */
function CheckIn({ log, saving, onSave, anon }: { log?: LogInput; saving: boolean; onSave: (v: LogInput) => void; anon: boolean }) {
const { region } = useRegion()
const [editing, setEditing] = useState(!log)
const [mood, setMood] = useState(log?.mood ?? 0)
const [place, setPlace] = useState(log?.place_name ?? '')
const [ref, setRef] = useState<string | null>(log?.place_ref ?? null)
const [stayed, setStayed] = useState(log ? !log.went_out : false)
const [hit, setHit] = useState<boolean | null>(log?.card_hit ?? null)
const [q, setQ] = useState('')
// 글자를 멈춘 뒤에 찾는다
useEffect(() => {
const t = setTimeout(() => setQ(ref ? '' : place.trim()), 250)
return () => clearTimeout(t)
}, [place, ref])
const found = useQuery({ ...searchFortunePlacesOptions({ query: { region: region.code, q } }), enabled: q.length > 0, select: (d) => d.items ?? [] })
if (log && !editing) {
return (
<button type="button" onClick={() => setEditing(true)} className="mt-3 flex w-full cursor-pointer items-center gap-2 rounded-xl bg-[#f3f6fb] px-3 py-2.5 text-left">
<span className="text-[22px] leading-none">{MOODS[log.mood - 1]}</span>
<span className="min-w-0 flex-1">
<b className="block text-[13.5px] font-extrabold">오늘 하루를 적어 뒀어요</b>
{log.place_name && <span className="block truncate text-xs font-semibold text-(--ink2)">{log.place_name}</span>}
</span>
</button>
)
}
const ready = mood > 0 && (stayed || place.trim().length > 0)
const save = () => {
onSave({ mood, went_out: !stayed, place_name: stayed ? null : place.trim(), place_ref: stayed ? null : ref, card_hit: hit })
setEditing(false)
}
const chip = (on: boolean) => cx('cursor-pointer rounded-full px-3 py-1.5 text-[13px] font-extrabold', on ? 'bg-(--ink) text-white' : 'bg-[#f3f6fb] text-(--ink2)')
return (
<div className="mt-3 border-t border-(--line) pt-3">
<p className="m-0 font-jua text-[17px]">오늘 하루 어땠어요?</p>
<div className="mt-2 flex justify-between">
{MOODS.map((m, i) => (
<button key={m} type="button" onClick={() => setMood(i + 1)} aria-pressed={mood === i + 1} className={cx('grid size-11 cursor-pointer place-items-center rounded-full text-[24px]', mood === i + 1 ? 'bg-[#ffe2cf] ring-2 ring-(--orange)' : 'bg-[#f3f6fb]')}>
{m}
</button>
))}
</div>
<p className="m-0 mt-3.5 text-[14px] font-extrabold">어디 다녀왔어요?</p>
<div className="relative mt-1.5 flex gap-1.5">
<input
value={place}
onChange={(e) => {
setPlace(e.target.value.slice(0, 40))
setRef(null)
setStayed(false)
}}
placeholder="장소 이름"
disabled={stayed}
className="min-w-0 flex-1 rounded-xl border border-(--line) bg-white px-3 py-2 text-[14px] font-semibold disabled:opacity-50"
/>
<button
type="button"
onClick={() => {
setStayed(!stayed)
setPlace('')
setRef(null)
}}
aria-pressed={stayed}
className={chip(stayed)}
>
안 나갔어요
</button>
{!stayed && !ref && (found.data?.length ?? 0) > 0 && (
<ul className="absolute top-full right-0 left-0 z-10 m-0 mt-1 max-h-48 list-none overflow-auto rounded-xl border border-(--line) bg-white p-1 shadow-lg">
{found.data!.map((p) => (
<li key={p.ref}>
<button
type="button"
onClick={() => {
setPlace(p.name)
setRef(p.ref)
}}
className="w-full cursor-pointer rounded-lg px-2.5 py-2 text-left text-[14px] font-semibold hover:bg-[#f3f6fb]"
>
{p.name}
</button>
</li>
))}
</ul>
)}
</div>
<p className="m-0 mt-3.5 text-[14px] font-extrabold">오늘 카드, 맞았어요?</p>
<div className="mt-1.5 flex gap-1.5">
<button type="button" onClick={() => setHit(hit === true ? null : true)} aria-pressed={hit === true} className={chip(hit === true)}>
맞았어요
</button>
<button type="button" onClick={() => setHit(hit === false ? null : false)} aria-pressed={hit === false} className={chip(hit === false)}>
글쎄요
</button>
</div>
<button type="button" onClick={save} disabled={!ready || saving} className="mt-3.5 w-full cursor-pointer rounded-full bg-(--orange) py-2.5 text-[14px] font-extrabold text-white disabled:opacity-40">
적어 두기
</button>
{anon && <p className="m-0 mt-2 text-center text-[11.5px] font-semibold text-(--ink3)">이 기기에만 남아요. 로그인하면 폰을 바꿔도 남아요.</p>}
</div>
)
}
+2
View File
@@ -28,6 +28,8 @@ type Events = {
foliage_open: Record<string, never>
foliage_spot: { spot_name: string; from: 'page' | 'card' }
my_gak_save: { gak_name: string }
fortune_draw: { card: string }
day_log: { mood: number; went_out: boolean; card_hit: boolean | null }
toss_intro_start: Record<string, never>
install_banner_close: Record<string, never>
}