diff --git a/docs/이벤트_추적.md b/docs/이벤트_추적.md index 2c932e7..ac1bb8e 100644 --- a/docs/이벤트_추적.md +++ b/docs/이벤트_추적.md @@ -78,7 +78,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화 - 앱도 같은 이벤트 이름·값으로 `track()`을 부른다 (`mobile/src/lib/analytics.ts`). 모든 이벤트에 `platform: 'app'`이 붙는다. - **아직 GA4로 보내지 않는다 (2026-11-04).** Firebase Analytics(`google-services.json`)를 붙이면 앱 시작 때 `setAnalyticsSender`로 보내는 함수를 단다. 그 전까지 `track()`은 아무것도 보내지 않는다. 개발 빌드(`__DEV__`)는 붙인 뒤에도 보내지 않는다. -- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`). 레벨 창·레벨업 창은 `sheet_open`(`level`·`levelUp`)으로 잡힌다. 동네 이야기: `talk_post`(`components/talk/talk.tsx` `Composer`), `like`·`report`·`block`의 `talk`(`talk/talk.tsx`), `talk_comment`(`sheets/comments.tsx`), `feed_item_view`(`app/(tabs)/index.tsx` `useSeen`, 화면에 반쯤 보일 때). 내 각: `my_gak_save`(`lib/my-gak.ts`), 만들기·상세 창은 `sheet_open`(`mix`·`myGak`). 쇼츠: `shorts_open`·`shorts_view`·`shorts_sound`(`app/shorts/[id].tsx`). 구름 합치기 게임은 앱이 웹 `/game`을 웹뷰로 띄우므로 `game_start`·`game_round`·`game_over`는 웹 페이지가 보내고 `platform: 'web'`으로 찍힌다(앱 안 게임과 웹 게임을 GA에서 나눠 볼 수 없음). +- 앱에서 부르는 곳: `sheet_open`(`components/sheets/index.tsx`), `view_gak`(`sheets/gak.tsx`), `select_content`(`sheets/article.tsx`), `login`·`sign_up`(`sheets/login.tsx`, 구글만), `region_change`(`sheets/region.tsx`·`lib/region.tsx`), `like`(`post/post-card.tsx` 글, `sheets/comments.tsx` 댓글), `comment`·`report`·`block`·`terms_agree`(`sheets/comments.tsx`), `share`(`lib/share-image.ts`), `hero_day_switch`(`today/hero.tsx`), `like`의 `hero_post`·`gak_post`(`lib/pinned-like.ts`). 레벨 창·레벨업 창은 `sheet_open`(`level`·`levelUp`)으로 잡힌다. 동네 이야기: `talk_post`(`components/talk/talk.tsx` `Composer`), `like`·`report`·`block`의 `talk`(`talk/talk.tsx`), `talk_comment`(`sheets/comments.tsx`), `feed_item_view`(`app/(tabs)/index.tsx` `useSeen`, 화면에 반쯤 보일 때). 내 각: `my_gak_save`(`lib/my-gak.ts`), 만들기·상세 창은 `sheet_open`(`mix`·`myGak`). 사주: `saju_input`(`components/saju/birth-form.tsx`), `saju_view`(`saju/reading.tsx`). 쇼츠: `shorts_open`·`shorts_view`·`shorts_sound`(`app/shorts/[id].tsx`). 구름 합치기 게임은 앱이 웹 `/game`을 웹뷰로 띄우므로 `game_start`·`game_round`·`game_over`는 웹 페이지가 보내고 `platform: 'web'`으로 찍힌다(앱 안 게임과 웹 게임을 GA에서 나눠 볼 수 없음). - 앱 `share`의 `ratio`는 `'card'` — 보이는 카드를 그대로 찍어 보내 비율을 고르지 않는다. ## GA4 설정 diff --git a/mobile/src/app/saju.tsx b/mobile/src/app/saju.tsx new file mode 100644 index 0000000..c5453d5 --- /dev/null +++ b/mobile/src/app/saju.tsx @@ -0,0 +1,63 @@ +import { useLocalSearchParams } from 'expo-router'; +import { useMemo, useRef, useState } from 'react'; +import { ScrollView, View } from 'react-native'; + +import { BirthForm } from '@/components/saju/birth-form'; +import { OpenTarget } from '@/components/saju/parts'; +import { Reading } from '@/components/saju/reading'; +import { ScreenHeader } from '@/components/screen-header'; +import { Text } from '@/components/text'; +import { useAccountBirth, useBirth } from '@/lib/saju-birth'; + +type Pos = { base: number | null; panel: number | null; done: boolean }; + +function tryScroll(p: Pos, view: ScrollView | null) { + if (p.done || p.base == null || p.panel == null || !view) return; + p.done = true; + view.scrollTo({ y: Math.max(0, p.base + p.panel - 12), animated: true }); +} + +/** 날씨 사주(/saju): 오늘 점수와 할 일, 내 기운, 레벨로 열리는 칸. ?open=saju_love 처럼 열면 그 칸으로 내려간다 (웹 SajuPage, #hash) */ +export default function SajuScreen() { + const params = useLocalSearchParams<{ open?: string }>(); + const birth = useBirth(); + const loading = useAccountBirth(); + const [editing, setEditing] = useState(false); + const scroll = useRef(null); + // 결과 묶음의 위치와 그 안에서 연 칸의 위치를 둘 다 알아야 내려갈 수 있다 (어느 쪽이 먼저 잡힐지 모른다) + const pos = useRef({ base: null, panel: null, done: false }); + const target = useMemo( + () => ({ + id: params.open, + onLayout: (y: number) => { + pos.current.panel = y; + tryScroll(pos.current, scroll.current); + }, + }), + [params.open], + ); + + return ( + + + + {loading && !birth ? ( + 내 생년월일을 불러오는 중이에요… + ) : !birth || editing ? ( + setEditing(false)} onCancel={birth ? () => setEditing(false) : undefined} /> + ) : ( + { + pos.current.base = e.nativeEvent.layout.y; + tryScroll(pos.current, scroll.current); + }} + > + + setEditing(true)} /> + + + )} + + + ); +} diff --git a/mobile/src/components/saju/birth-form.tsx b/mobile/src/components/saju/birth-form.tsx new file mode 100644 index 0000000..5f7f502 --- /dev/null +++ b/mobile/src/components/saju/birth-form.tsx @@ -0,0 +1,108 @@ +import { useState } from 'react'; +import { Pressable, View } from 'react-native'; + +import { Text } from '@/components/text'; +import { Ic } from '@/components/ui'; +import { track } from '@/lib/analytics'; +import { useAuth } from '@/lib/auth'; +import { BIRTH_PLACES, placeName, useSaveBirth, validBirth, type Birth } from '@/lib/saju-birth'; + +import { Box, ChipGrid, DatePick, Stepper, type Ymd } from './pick'; + +const HOURS: [number, string][] = [[-1, '모름'], ...Array.from({ length: 24 }, (_, i): [number, string] => [i, `${i}시`])]; +const PLACES: [string, string][] = BIRTH_PLACES.map(([k, n]) => [k, n]); + +function Label({ children }: { children: string }) { + return {children}; +} + +/** 생년월일·태어난 시각·지역 넣기 (웹 SajuPage BirthForm) */ +export function BirthForm({ initial, onDone, onCancel }: { initial: Birth | null; onDone: () => void; onCancel?: () => void }) { + const { loggedIn } = useAuth(); + const save = useSaveBirth(); + const [date, setDate] = useState({ y: initial?.y ?? null, m: initial?.m ?? null, d: initial?.d ?? null }); + const [hour, setHour] = useState(initial?.hour ?? null); + const [minute, setMinute] = useState(initial?.minute ?? 0); + const [place, setPlace] = useState(initial?.place ?? 'seoul'); + const [open, setOpen] = useState<'hour' | 'place' | null>(null); + const [error, setError] = useState(''); + const toggle = (k: 'hour' | 'place') => setOpen((o) => (o === k ? null : k)); + + const submit = () => { + const { y, m, d } = date; + if (y == null || m == null || d == null) return setError('생년월일을 모두 넣어 주세요'); + if (!validBirth(y, m, d)) return setError('없는 날짜예요. 다시 확인해 주세요'); + void save({ y, m, d, hour, minute: hour == null ? null : minute, place, gender: initial?.gender ?? null }); + track('saju_input', { with_time: hour != null }); + onDone(); + }; + + return ( + + + + {'내 사주와 오늘 날씨로\n오늘 하루를 봐요'} + + + + { + setDate(v); + setError(''); + }} + /> + + + + + toggle('hour')} /> + + + {open === 'hour' && ( + + { + setHour(h < 0 ? null : h); + setOpen(null); + }} + wide + /> + + )} + + + + toggle('place')} /> + {open === 'place' && ( + + { + setPlace(p); + setOpen(null); + }} + wide + /> + + )} + 지역마다 해가 뜨는 시각이 달라 태어난 시각을 그만큼 고쳐서 봐요. + + {!!error && {error}} + + 오늘 날씨 사주 보기 + + {!!onCancel && ( + + 취소 + + )} + {loggedIn ? '내 계정에 저장돼요. 내 정보에서 언제든 지울 수 있어요.' : '이 기기에만 저장돼요. 로그인하면 계정에 저장해 어느 기기에서든 바로 볼 수 있어요.'} + + ); +} diff --git a/mobile/src/components/saju/match.tsx b/mobile/src/components/saju/match.tsx new file mode 100644 index 0000000..9d5dce8 --- /dev/null +++ b/mobile/src/components/saju/match.tsx @@ -0,0 +1,81 @@ +import { matchMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; +import type { ResSajuMatch } from '@nalssigak/shared/api/client/types.gen'; +import { useMutation } from '@tanstack/react-query'; +import { useState } from 'react'; +import { Pressable, View } from 'react-native'; + +import { useSoft } from '@/components/sheets/parts'; +import { Text } from '@/components/text'; +import { useRegion } from '@/lib/region'; +import { toBody, validBirth, type Birth } from '@/lib/saju-birth'; + +import { dayWord, Panel } from './parts'; +import { DatePick, type Ymd } from './pick'; + +const pad = (n: number) => String(n).padStart(2, '0'); + +/** 궁합 (Lv.5): 상대 생년월일로 두 사주가 맞는 정도와 같이 나가기 좋은 날. 상대 생년월일은 저장하지 않는다 */ +export function Match({ birth }: { birth: Birth }) { + const { region } = useRegion(); + const soft = useSoft(); + const [date, setDate] = useState({ y: null, m: null, d: null }); + const [error, setError] = useState(''); + const run = useMutation({ ...matchMutation() }); + const res: ResSajuMatch | undefined = run.data?.result?.success ? run.data : undefined; + const go = () => { + const { y, m, d } = date; + if (y == null || m == null || d == null) return setError('상대 생년월일을 모두 넣어 주세요'); + if (!validBirth(y, m, d)) return setError('없는 날짜예요. 다시 확인해 주세요'); + setError(''); + run.mutate({ body: { region_code: region.code, me: toBody(birth), friend: { birth_date: `${y}-${pad(m)}-${pad(d)}`, longitude: 126.98 } } }); + }; + return ( + + {res ? ( + <> + + + 상대 {date.y}.{date.m}.{date.d}생 + + run.reset()} hitSlop={8} accessibilityRole="button"> + 다른 사람 보기 + + + + {res.title ?? ''} {res.score ?? ''}점 + + {res.lines?.map((l) => ( + + {l} + + ))} + {!!res.day && ( + + 앞으로 7일 중 같이 나가기 좋은 날: {dayWord(res.day.day, res.day.weekday)} + {res.day.word ? ` · ${res.day.word} ${res.day.temp_max ?? ''}°` : ''} + + )} + 상대 기운: {res.friend_scene ?? ''} + + ) : ( + <> + 상대 생년월일(양력)을 넣으면 두 사람 사주가 어떻게 맞는지와 앞으로 7일 중 같이 나가기 좋은 날을 봐요. + { + setDate(v); + setError(''); + }} + /> + + 보기 + + {!!error && {error}} + {(run.isError || (!!run.data && !run.data.result?.success)) && 궁합을 불러오지 못했어요. 다시 눌러 주세요.} + 상대 생년월일은 저장하지 않아요. + + )} + + ); +} diff --git a/mobile/src/components/saju/me-card.tsx b/mobile/src/components/saju/me-card.tsx new file mode 100644 index 0000000..d480e99 --- /dev/null +++ b/mobile/src/components/saju/me-card.tsx @@ -0,0 +1,139 @@ +import type { ResSaju } from '@nalssigak/shared/api/client/types.gen'; +import { Image } from 'expo-image'; +import { Pressable, View } from 'react-native'; + +import { useSoft } from '@/components/sheets/parts'; +import { Text } from '@/components/text'; + +import { EL_ART, EL_COLOR, EL_WORD, Panel } from './parts'; + +const POS_WORD: Record = { hour: '시', day: '일', month: '월', year: '연' }; +const STRENGTH_WORD: Record = { + 신강: '나를 돕는 기운이 센 사주. 태어난 달(월령)의 힘을 먼저 봐요', + 중화: '나를 돕는 기운과 다른 기운이 비슷한 사주', + 신약: '나를 돕는 기운이 약한 사주', +}; +const TEN_GOD_WORD: Record = { + 비견: '나와 같은 기운', + 겁재: '나와 같지만 겨루는 기운', + 식신: '내가 만들어 내는 기운', + 상관: '내가 드러내는 기운', + 편재: '내가 크게 굴리는 재물', + 정재: '내가 차곡차곡 모으는 재물', + 편관: '나를 세게 다잡는 기운', + 정관: '나를 바르게 이끄는 기운', + 편인: '나를 돕는 남다른 지혜', + 정인: '나를 돕는 배움·도움', +}; + +function Art({ el, size }: { el: string; size: number }) { + const src = EL_ART[el]; + return src != null ? : null; +} + +function Char({ c, ko, el, me }: { c: string; ko: string; el: string; me?: boolean }) { + const [fg, bg] = EL_COLOR[el] ?? ['#28304a', '#f3f6fb']; + return ( + + + {c} + + + {ko} + + + ); +} + +function Note({ term, word }: { term: string; word: string }) { + return ( + + {term} = {word} + + ); +} + +/** 사주 명식: 가장 센 기운, 오행 막대, 네 기둥, 용어 풀이 */ +export function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) { + const soft = useSoft(); + const me = r.me!; + const cols = [...me.pillars].reverse(); + const els = Object.entries(me.elements ?? {}); + const total = els.reduce((a, [, v]) => a + v, 0); + const gods = [...new Set(me.pillars.flatMap((p) => [p.stem_ten_god, p.branch_ten_god]).filter((g): g is string => !!g && g in TEN_GOD_WORD))]; + const strength = me.strength ?? (me.strong == null ? null : me.strong ? '신강' : '신약'); + const top = me.top_element; + return ( + + 생년월일 바꾸기 + + } + > + {!!top && !!strength && ( + + + + + {EL_WORD[top]}({top}) 기운이 가장 센 {strength} 사주 + + + 나를 돕는 기운 {Math.round((me.support ?? 0) * 100)}% · {me.scene} + + + + )} + {total > 0 && ( + <> + `${k} ${Math.round(v)}`).join(', ')}> + {els.map(([k, v]) => ( + + ))} + + + {els.map(([k, v]) => ( + + + + {k} {Math.round(v)} + + + ))} + + + )} + + {(me.hour_known ? cols : [null, ...cols]).map((p, i) => ( + + {p ? `${POS_WORD[p.position]}주` : '시주'} + {p ? ( + <> + {p.position === 'day' ? '나' : (p.stem_ten_god ?? '')} + + + {p.branch_ten_god} + {p.position === 'month' && 월령} + + ) : ( + + 시각 모름 + + )} + + ))} + + + {!!strength && } + {gods.map((g) => ( + + ))} + + + {(me.need?.length ?? 0) > 0 && 내 기운에 좋은 날씨: {me.need!.join(' · ')}} + {me.jeol_warning && 태어난 날에 절기가 바뀌어요. 태어난 시각을 넣어야 달 기둥이 정확해요.} + + ); +} diff --git a/mobile/src/components/saju/panels.tsx b/mobile/src/components/saju/panels.tsx new file mode 100644 index 0000000..b886eca --- /dev/null +++ b/mobile/src/components/saju/panels.tsx @@ -0,0 +1,171 @@ +import type { ResSaju, SajuLock } from '@nalssigak/shared/api/client/types.gen'; +import { LinearGradient } from 'expo-linear-gradient'; +import { Pressable, View } from 'react-native'; + +import { useSoft } from '@/components/sheets/parts'; +import { Text } from '@/components/text'; +import { Ic } from '@/components/ui'; +import { useAuth } from '@/lib/auth'; +import { progress, useLevel } from '@/lib/level'; +import { useSaveBirth, type Birth } from '@/lib/saju-birth'; +import { useSheet } from '@/lib/sheet'; + +import { dayWord, Panel } from './parts'; + +/** 앞으로 7일 흐름 (Lv.2) */ +export function Week({ days }: { days: NonNullable }) { + const soft = useSoft(); + return ( + + + {days.map((d) => ( + + + {dayWord(d.day, d.weekday)} + + {d.icon ? : } + + {d.temp_max != null ? `${d.temp_min}~${d.temp_max}°` : ''} + + + {d.title} + + {d.score} + + ))} + + 점수는 그날 사주와 예보로 계산해요. 주황색은 7일 중 점수가 가장 높은 날이에요. + + ); +} + +/** 금전운·일운 (Lv.3) */ +export function Money({ money, work }: { money: string[]; work: string[] }) { + const lines = [...money.map((l) => ['money_bag', l]), ...work.map((l) => ['briefcase', l])]; + return ( + + + {lines.map(([icon, l]) => ( + + + {l} + + ))} + + + ); +} + +/** 앞으로 7일 연애운 (Lv.4). 성별을 고르면 이성 인연까지 */ +export function Love({ love, birth }: { love: NonNullable; birth: Birth }) { + const soft = useSoft(); + const save = useSaveBirth(); + const pick = (g: 'M' | 'F' | null) => void save({ ...birth, gender: g }); + return ( + + {love.good ? ( + + 연애 기운이 좋은 날 + + {dayWord(love.good.day, love.good.weekday)} + {love.good.word ? ` · ${love.good.word} ${love.good.temp_max ?? ''}°` : ''} + + {love.good.body} + {love.good.why} + + ) : ( + 앞으로 7일 중엔 연애 기운이 두드러지는 날이 없어요. + )} + {!!love.caution && ( + + 조심할 날 {dayWord(love.caution.day, love.caution.weekday)}: {love.caution.body} · {love.caution.why} + + )} + {love.gender_known ? ( + + {birth.gender === 'M' ? '남성' : '여성'} 기준으로 이성 인연(재성·관성)까지 봤어요 ·{' '} + pick(null)} accessibilityRole="button" className="font-extrabold text-orange"> + 빼고 보기 + + + ) : ( + + 성별을 고르면 이성 인연(재성·관성)까지 봐요 + {( + [ + ['M', '남성'], + ['F', '여성'], + ] as const + ).map(([g, word]) => ( + pick(g)} accessibilityRole="button" className="rounded-full px-2.5 py-1" style={{ backgroundColor: soft.soft }}> + {word} + + ))} + + )} + + ); +} + +/** 이달·올해 (Lv.6·7) */ +export function Period({ id, icon, p }: { id: string; icon: string; p: NonNullable }) { + return ( + + + {p.title} ({p.ten_god}) + + {p.body} + {(p.months?.length ?? 0) > 0 && ( + + {p.label.includes('미리') ? '내 사주와 잘 맞는 달' : '남은 달 중 잘 맞는 달'}: {p.months!.map((m) => `${m}월`).join(' · ')} + + )} + {p.notes?.map((n) => ( + + {n} + + ))} + + ); +} + +/** 아직 안 열린 것: 다음에 열릴 하나를 크게, 나머지는 한 줄로. 로그인 전이면 로그인부터 */ +export function Locked({ locks }: { locks: SajuLock[] }) { + const { loggedIn } = useAuth(); + const { open } = useSheet(); + const soft = useSoft(); + const level = useLevel().data; + if (!locks.length) return null; + const [next, ...rest] = [...locks].sort((a, b) => a.level - b.level); + const close = loggedIn && !!level && level.next_points != null && level.level + 1 === next.level; + return ( + + + + + {loggedIn ? `다음은 ${next.name}` : '각을 모으면 더 볼 수 있어요'} + + {loggedIn ? (close && level ? `${level.next_points! - level.points}각 더 모으면 열려요` : `Lv.${next.level}이 되면 열려요`) : "로그인하고 출석·사주 보기·좋아요를 하면 활동 포인트 '각'이 쌓여요"} + + + open(loggedIn ? { type: 'level' } : { type: 'login', why: 'level' })} accessibilityRole="button" className="rounded-full bg-ink-btn px-3 py-1.5"> + {loggedIn ? '각 모으는 법' : '로그인'} + + + {close && !!level && ( + + + + )} + + {(loggedIn ? rest : [next, ...rest]).map((l) => ( + + + Lv.{l.level} {l.name} + + + ))} + + + ); +} diff --git a/mobile/src/components/saju/parts.tsx b/mobile/src/components/saju/parts.tsx new file mode 100644 index 0000000..6445304 --- /dev/null +++ b/mobile/src/components/saju/parts.tsx @@ -0,0 +1,38 @@ +import { createContext, use, type ReactNode } from 'react'; +import { View } from 'react-native'; + +import { Text } from '@/components/text'; +import { Ic } from '@/components/ui'; + +export const EL_COLOR: Record = { 木: ['#2f8a4c', '#e3f6ea'], 火: ['#d9442f', '#ffe6e0'], 土: ['#a8761a', '#fbf0d6'], 金: ['#6b7486', '#eef0f4'], 水: ['#2d4a8a', '#e3ebfb'] }; +export const EL_WORD: Record = { 木: '나무', 火: '불', 土: '흙', 金: '쇠', 水: '물' }; +// 오행 그림 (웹 public/saju). Metro 는 정적 require 만 묶을 수 있어 하나씩 적는다 +export const EL_ART: Record = { + 木: require('../../../../frontend/public/saju/wood.webp'), + 火: require('../../../../frontend/public/saju/fire.webp'), + 土: require('../../../../frontend/public/saju/earth.webp'), + 金: require('../../../../frontend/public/saju/metal.webp'), + 水: require('../../../../frontend/public/saju/water.webp'), +}; + +/** 2026-11-04 + 수 → 11/4(수) */ +export const dayWord = (iso: string, weekday: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}(${weekday})`; + +/** ?open= 으로 연 칸: 그 칸이 자리를 잡으면 화면이 그 위치로 내려간다 (웹 #hash 스크롤) */ +export const OpenTarget = createContext<{ id?: string; onLayout: (y: number) => void }>({ onLayout: () => {} }); + +/** 흰 판: 아이콘·제목·오른쪽 버튼 */ +export function Panel({ id, icon, title, right, children }: { id?: string; icon: string; title: string; right?: ReactNode; children: ReactNode }) { + const target = use(OpenTarget); + const mine = !!id && target.id === id; + return ( + target.onLayout(e.nativeEvent.layout.y) : undefined} className="mx-4 rounded-[22px] border-b-4 border-shade bg-card px-4 py-3.5"> + + + {title} + {right != null && {right}} + + {children} + + ); +} diff --git a/mobile/src/components/saju/pick.tsx b/mobile/src/components/saju/pick.tsx new file mode 100644 index 0000000..180c9ea --- /dev/null +++ b/mobile/src/components/saju/pick.tsx @@ -0,0 +1,131 @@ +import { useState } from 'react'; +import { Pressable, View } from 'react-native'; + +import { useSoft } from '@/components/sheets/parts'; +import { Text } from '@/components/text'; + +/** 고르는 칸: 누르면 아래에 칩이 펼쳐진다 (웹 input·select 대신. 숫자 자판 없이 눌러서 고른다) */ +export function Box({ label, value, placeholder, open, onPress, disabled, flex = 1 }: { label: string; value: string | null; placeholder: string; open: boolean; onPress: () => void; disabled?: boolean; flex?: number }) { + const soft = useSoft(); + return ( + + + {value ?? placeholder} + + {open ? '▲' : '▼'} + + ); +} + +/** 칩 여러 개 중 하나 고르기 */ +export function ChipGrid({ items, value, onPick, label, wide }: { items: [K, string][]; value: K | null; onPick: (k: K) => void; label: string; wide?: boolean }) { + const soft = useSoft(); + return ( + + {items.map(([k, word]) => { + const on = value === k; + return ( + onPick(k)} accessibilityRole="radio" accessibilityState={{ checked: on }} className={`min-h-[40px] items-center justify-center rounded-xl px-1 ${wide ? 'w-[64px]' : 'w-[44px]'} ${on ? 'bg-orange' : 'bg-card'}`}> + {word} + + ); + })} + + ); +} + +/** 연도: 먼저 10년 단위를 고르고 그 안에서 연도 */ +function YearGrid({ value, onPick, label }: { value: number | null; onPick: (y: number) => void; label: string }) { + const thisYear = new Date().getFullYear(); + const [decade, setDecade] = useState(value != null ? Math.floor(value / 10) * 10 : 1990); + const decades: [number, string][] = []; + for (let d = 1900; d <= thisYear; d += 10) decades.push([d, `${String(d).slice(2)}년대`]); + const years: [number, string][] = []; + for (let y = decade; y < decade + 10 && y <= thisYear; y++) years.push([y, String(y)]); + return ( + + + + + ); +} + +const MONTHS: [number, string][] = Array.from({ length: 12 }, (_, i) => [i + 1, `${i + 1}월`]); +const daysIn = (y: number | null, m: number | null) => (m == null ? 31 : new Date(y ?? 2000, m, 0).getDate()); + +export type Ymd = { y: number | null; m: number | null; d: number | null }; + +/** 생년월일(양력) 고르기: 연도 → 월 → 일 순서로 이어서 펼친다 */ +export function DatePick({ value, onChange, label = '' }: { value: Ymd; onChange: (v: Ymd) => void; label?: string }) { + const [open, setOpen] = useState<'y' | 'm' | 'd' | null>(null); + const toggle = (k: 'y' | 'm' | 'd') => setOpen((o) => (o === k ? null : k)); + const days: [number, string][] = Array.from({ length: daysIn(value.y, value.m) }, (_, i) => [i + 1, String(i + 1)]); + return ( + + + toggle('y')} flex={1.5} /> + toggle('m')} /> + toggle('d')} /> + + {open === 'y' ? ( + { + onChange({ ...value, y }); + setOpen(value.m == null ? 'm' : null); + }} + /> + ) : open === 'm' ? ( + { + onChange({ ...value, m }); + setOpen(value.d == null ? 'd' : null); + }} + wide + /> + ) : open === 'd' ? ( + { + onChange({ ...value, d }); + setOpen(null); + }} + /> + ) : null} + + ); +} + +/** 숫자: −/+ 버튼 (분) */ +export function Stepper({ value, onChange, min, max, label, unit, disabled }: { value: number; onChange: (v: number) => void; min: number; max: number; label: string; unit: string; disabled?: boolean }) { + const soft = useSoft(); + const set = (v: number) => onChange(Math.min(max, Math.max(min, v))); + return ( + + set(value - 1)} onLongPress={() => set(value - 10)} disabled={disabled || value <= min} hitSlop={4} accessibilityLabel={`${label} 내리기`} className="px-3.5 py-2"> + − + + + {value} + {unit} + + set(value + 1)} onLongPress={() => set(value + 10)} disabled={disabled || value >= max} hitSlop={4} accessibilityLabel={`${label} 올리기`} className="px-3.5 py-2"> + + + + + ); +} diff --git a/mobile/src/components/saju/reading.tsx b/mobile/src/components/saju/reading.tsx new file mode 100644 index 0000000..e5b9df7 --- /dev/null +++ b/mobile/src/components/saju/reading.tsx @@ -0,0 +1,172 @@ +import { myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; +import { reading } from '@nalssigak/shared/api/client/sdk.gen'; +import type { SajuCard } from '@nalssigak/shared/api/client/types.gen'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { useEffect, useRef } from 'react'; +import { Pressable, View } from 'react-native'; +import Svg, { Circle } from 'react-native-svg'; +import { useCSSVariable } from 'uniwind'; + +import { useSoft } from '@/components/sheets/parts'; +import { Text } from '@/components/text'; +import { Ic } from '@/components/ui'; +import { track } from '@/lib/analytics'; +import { useAuth } from '@/lib/auth'; +import { useLevel } from '@/lib/level'; +import { useRegion } from '@/lib/region'; +import { markSajuSeen, toBody, type Birth } from '@/lib/saju-birth'; +import { useShare } from '@/lib/share-image'; +import { SITE_URL } from '@/lib/site'; + +import { Match } from './match'; +import { MeCard } from './me-card'; +import { Locked, Love, Money, Period, Week } from './panels'; + +const CARD_ICON: Record = { when: 'alarm_clock', do: 'check_mark_button', avoid: 'warning', good: 'sparkles', wear: 'tshirt' }; + +function DecisionCard({ c }: { c: SajuCard }) { + return ( + + + + {c.kind === 'when' ? '내 기운에 맞는 시간' : c.title} + {c.kind === 'when' ? `${c.title} · ${c.sub ?? ''}` : c.body} + {(c.kind === 'when' ? c.body : c.sub) ?? ''} + + + ); +} + +const RING_R = 46; +const RING_LEN = 2 * Math.PI * RING_R; + +function ScoreRing({ score }: { score: number }) { + const soft = useSoft(); + return ( + + + + + + {score} + 오늘의 점수 + + ); +} + +function ScoreBar({ label, value, width, color, signed }: { label: string; value: number; width: number; color: string; signed?: boolean }) { + const soft = useSoft(); + return ( + + + + {label} + + + {`${signed ? (value >= 0 ? '+' : '−') : ''}${Math.abs(value)}점`} + + + + + + + ); +} + +/** 오늘 점수와 할 일, 내 기운, 레벨로 열리는 이번 주·금전·연애·궁합·이달·올해 (웹 SajuPage Reading) */ +export function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) { + const { region } = useRegion(); + const { loggedIn } = useAuth(); + const queryClient = useQueryClient(); + const soft = useSoft(); + const ink = String(useCSSVariable('--color-ink')); + const share = useShare(); + const level = useLevel().data?.level; + const body = { ...toBody(birth), region_code: region.code, gender: birth.gender === 'M' ? ('male' as const) : birth.gender === 'F' ? ('female' as const) : undefined }; + // 레벨이 오르면 키가 바뀌어 새로 열린 칸까지 다시 받는다. 사주를 보면 각이 쌓이니 레벨도 새로 받는다 + const q = useQuery({ + queryKey: ['saju', body, loggedIn, level], + staleTime: 10 * 60_000, + queryFn: async () => { + const { data } = await reading({ body }); + if (!data.result?.success) throw new Error(data.result?.desc ?? 'saju'); + if (loggedIn) void queryClient.invalidateQueries({ queryKey: myLevelQueryKey() }); + return data; + }, + }); + const shot = useRef(null); + const r = q.data; + + useEffect(() => { + if (!r?.today) return; + markSajuSeen(); + track('saju_view', { scene: r.me?.scene ?? '', score: r.today.score, strength: r.me?.strength ?? '', top_element: r.me?.top_element ?? '' }); + }, [r]); + + if (q.isPending) return 사주를 풀고 있어요…; + if (!r?.today || !r.me) + return ( + + 결과를 불러오지 못했어요. + void q.refetch()} accessibilityRole="button" className="mt-3 rounded-full bg-ink-btn px-4 py-2"> + 다시 시도 + + + ); + const t = r.today; + const matchOpen = !!r.locks?.find((l) => l.key === 'saju_match')?.unlocked; + const title = `오늘 내 날씨 사주 ${t.score}점 · ${t.title}`; + + return ( + + + + {Number(t.day.slice(5, 7))}월 {Number(t.day.slice(8, 10))}일 {t.pillar}일 · 오늘의 점수 + + + + + {t.title} + + {t.weather_points != null && = 0 ? '#1f7a4f' : '#e8663a'} signed />} + + + {(t.why?.length ?? 0) > 0 && ( + + {t.why!.map((w) => { + const down = w.startsWith('↓'); + return ( + + {w} + + ); + })} + + )} + + + + {t.cards.map((c) => ( + + ))} + + + + + {!!r.week && } + {!!r.money && } + {!!r.love && } + {matchOpen && } + {!!r.month && } + {!!r.year && } + !l.unlocked)} /> + + + 재미로 보는 날씨 사주 + void share(shot, { title, message: `${title} ${SITE_URL}/saju` })} accessibilityRole="button" className="rounded-full bg-ink-btn px-4 py-2"> + 공유 + + + + ); +} diff --git a/mobile/src/lib/saju-birth.ts b/mobile/src/lib/saju-birth.ts new file mode 100644 index 0000000..05797f7 --- /dev/null +++ b/mobile/src/lib/saju-birth.ts @@ -0,0 +1,169 @@ +import { getBirthQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; +import { deleteBirth, getBirth, putBirth } from '@nalssigak/shared/api/client/sdk.gen'; +import type { SajuSavedBirth } from '@nalssigak/shared/api/client/types.gen'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import * as SecureStore from 'expo-secure-store'; +import { useEffect, useSyncExternalStore } from 'react'; + +import { useAuth } from '@/lib/auth'; + +/** 날씨 사주에 쓰는 태어난 정보. 기기에 두고, 로그인했으면 계정에도 저장한다 (웹 sajuBirth.ts) */ +export type Birth = { y: number; m: number; d: number; hour: number | null; minute: number | null; place: string; gender: 'M' | 'F' | null }; + +// SecureStore 키는 영문·숫자·._- 만 된다 +const KEY = 'nalssigak.birth'; +const SEEN_KEY = 'nalssigak.sajuSeen'; + +/** 태어난 곳: 시각을 그곳 경도로 맞춘다 (시·도청 경도) */ +export const BIRTH_PLACES: [string, string, number][] = [ + ['seoul', '서울', 126.98], + ['busan', '부산', 129.08], + ['daegu', '대구', 128.6], + ['incheon', '인천', 126.71], + ['gwangju', '광주', 126.85], + ['daejeon', '대전', 127.38], + ['ulsan', '울산', 129.31], + ['sejong', '세종', 127.29], + ['gyeonggi', '경기', 127.01], + ['gangwon', '강원', 127.73], + ['chungbuk', '충북', 127.49], + ['chungnam', '충남', 126.67], + ['jeonbuk', '전북', 127.11], + ['jeonnam', '전남', 126.46], + ['gyeongbuk', '경북', 128.51], + ['gyeongnam', '경남', 128.69], + ['jeju', '제주', 126.5], +]; + +export const placeLon = (key: string) => BIRTH_PLACES.find(([k]) => k === key)?.[2] ?? 127; +export const placeName = (key: string) => BIRTH_PLACES.find(([k]) => k === key)?.[1] ?? key; + +const pad = (n: number) => String(n).padStart(2, '0'); + +/** 사주 풀이·궁합 요청에 넣는 생년월일 */ +export const toBody = (b: Birth) => ({ + birth_date: `${b.y}-${pad(b.m)}-${pad(b.d)}`, + birth_time: b.hour != null ? `${pad(b.hour)}:${pad(b.minute ?? 0)}` : undefined, + longitude: placeLon(b.place), +}); + +function readLocal(): Birth | null { + try { + const raw = SecureStore.getItem(KEY); + return raw ? (JSON.parse(raw) as Birth) : null; + } catch (e) { + console.warn('[saju] 기기에 저장한 생년월일을 읽지 못함', e); + return null; + } +} + +// 사주 화면과 오늘 탭이 같은 값을 보게 한 곳에 두고 바뀌면 알린다 +let birth: Birth | null | undefined; +const listeners = new Set<() => void>(); +const subscribe = (cb: () => void) => { + listeners.add(cb); + return () => listeners.delete(cb); +}; +const getBirthLocal = () => { + if (birth === undefined) birth = readLocal(); + return birth; +}; + +export function setBirth(b: Birth | null) { + birth = b; + listeners.forEach((cb) => cb()); + try { + if (b) SecureStore.setItem(KEY, JSON.stringify(b)); + else void SecureStore.deleteItemAsync(KEY); + } catch (e) { + console.warn('[saju] 기기에 저장하지 못함', e); + } +} + +export const useBirth = () => useSyncExternalStore(subscribe, getBirthLocal); + +const toSaved = (b: Birth): SajuSavedBirth => ({ + birth_date: `${b.y}-${pad(b.m)}-${pad(b.d)}`, + birth_time: b.hour != null ? `${pad(b.hour)}:${pad(b.minute ?? 0)}` : undefined, + place: b.place, + gender: b.gender === 'M' ? 'male' : b.gender === 'F' ? 'female' : undefined, +}); +const fromSaved = (s: SajuSavedBirth): Birth => { + const [y, m, d] = s.birth_date.split('-').map(Number); + const [hour, minute] = s.birth_time ? s.birth_time.split(':').map(Number) : [null, null]; + return { y, m, d, hour, minute, place: s.place ?? 'seoul', gender: s.gender === 'male' ? 'M' : s.gender === 'female' ? 'F' : null }; +}; + +/** 로그인했으면 계정의 생년월일을 기기로 가져온다. 계정엔 없고 기기에만 있으면 계정으로 올린다. 받는 중이면 true */ +export function useAccountBirth() { + const { loggedIn } = useAuth(); + const q = useQuery({ queryKey: getBirthQueryKey(), enabled: loggedIn, staleTime: Infinity, queryFn: async () => (await getBirth()).data }); + useEffect(() => { + if (!loggedIn || !q.data?.result?.success) return; + if (q.data.birth) setBirth(fromSaved(q.data.birth)); + else { + const local = getBirthLocal(); + if (local) putBirth({ body: toSaved(local) }).catch((e) => console.warn('[saju] 계정에 올리지 못함', e)); + } + }, [loggedIn, q.data]); + return loggedIn && q.isPending; +} + +/** 생년월일 저장·지우기: 기기에 두고, 로그인했으면 계정에도 */ +export function useSaveBirth() { + const { loggedIn } = useAuth(); + const queryClient = useQueryClient(); + return async (b: Birth | null) => { + setBirth(b); + if (!loggedIn) return; + try { + const { data } = b ? await putBirth({ body: toSaved(b) }) : await deleteBirth(); + if (data.result?.success) queryClient.setQueryData(getBirthQueryKey(), data); + } catch (e) { + console.warn('[saju] 계정에 저장하지 못함', e); + } + }; +} + +/** 있는 날짜이고 1900-01-01 ~ 오늘 사이인지 */ +export function validBirth(y: number, m: number, d: number) { + const at = new Date(Date.UTC(y, m - 1, d)); + const ok = at.getUTCFullYear() === y && at.getUTCMonth() === m - 1 && at.getUTCDate() === d; + return ok && y >= 1900 && at.getTime() <= Date.now(); +} + +// 오늘 사주를 본 날 (오늘 아이콘 줄의 빨간 점) +let seen: string | null | undefined; +const seenListeners = new Set<() => void>(); +const subscribeSeen = (cb: () => void) => { + seenListeners.add(cb); + return () => seenListeners.delete(cb); +}; +const getSeen = () => { + if (seen === undefined) { + try { + seen = SecureStore.getItem(SEEN_KEY); + } catch (e) { + console.warn('[saju] 본 날을 읽지 못함', e); + // 저장소를 못 쓰면 점을 보이지 않는다 + seen = new Date().toDateString(); + } + } + return seen; +}; + +/** 오늘 아이콘 줄의 빨간 점: 오늘 날씨 사주를 이미 봤는지 (웹 SajuPage sajuSeenToday) */ +export const sajuSeenToday = () => getSeen() === new Date().toDateString(); + +/** sajuSeenToday 를 화면에서 쓸 때: 사주를 보고 돌아오면 바로 점이 사라진다 */ +export const useSajuSeenToday = () => useSyncExternalStore(subscribeSeen, getSeen) === new Date().toDateString(); + +export function markSajuSeen() { + seen = new Date().toDateString(); + seenListeners.forEach((cb) => cb()); + try { + SecureStore.setItem(SEEN_KEY, seen); + } catch (e) { + console.warn('[saju] 본 날을 저장하지 못함', e); + } +}