From e270261e328cafa91da98dcf9e9b8e6b17c6eec4 Mon Sep 17 00:00:00 2001 From: hbyang Date: Tue, 13 Oct 2026 15:36:50 +0900 Subject: [PATCH 01/63] =?UTF-8?q?feat:=20=EC=9B=8C=EC=B9=98=20=ED=8E=98?= =?UTF-8?q?=EC=9D=B4=EC=8A=A4=20=ED=91=B8=EC=8B=9C=EB=A1=9C=20=EC=95=B1=20?= =?UTF-8?q?=EC=84=A4=EC=B9=98=20=EB=95=8C=20=EB=82=A0=EC=94=A8=EA=B0=81=20?= =?UTF-8?q?=EC=8A=A4=ED=82=A8=20=EA=B0=99=EC=9D=B4=20=EC=A0=81=EC=9A=A9(We?= =?UTF-8?q?ar=20OS=206+),=20=EC=95=B1=20=EC=B2=AB=20=EC=9E=A5=EC=9D=84=20?= =?UTF-8?q?=EC=98=A4=EB=8A=98=20=EB=82=A8=EC=9D=80=20=EC=8B=9C=EA=B0=84?= =?UTF-8?q?=E2=86=92=EC=A3=BC=EB=B3=80=20=EC=B6=95=EC=A0=9C=20=EC=88=9C?= =?UTF-8?q?=EC=9C=BC=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Play 스토어 심사에 낸 1(0.1) 빌드와 같은 코드 Co-Authored-By: Claude Opus 5.5 --- watch/app/build.gradle.kts | 51 +++++++++++++- watch/app/src/main/AndroidManifest.xml | 12 +++- .../java/kr/o2o/nalssigak/MainActivity.kt | 70 +++++++++++++++++-- .../o2o/nalssigak/RainComplicationService.kt | 34 ++++++--- .../src/main/java/kr/o2o/nalssigak/Summary.kt | 2 +- watch/gradle.properties | 2 + watch/watchface/build.gradle.kts | 9 +-- watch/watchface/gen_watchface.py | 53 +++++++------- .../watchface/src/main/res/raw/watchface.xml | 57 ++++++--------- 9 files changed, 203 insertions(+), 87 deletions(-) diff --git a/watch/app/build.gradle.kts b/watch/app/build.gradle.kts index ad65748..7ceabb9 100644 --- a/watch/app/build.gradle.kts +++ b/watch/app/build.gradle.kts @@ -1,3 +1,15 @@ +import com.google.android.wearable.watchface.validator.client.DwfValidatorFactory + +// 스킨 APK 검증·토큰 발급기 (Watch Face Push). 의존성 하나가 jitpack 에만 있다 +buildscript { + repositories { + google() + mavenCentral() + maven("https://jitpack.io") { content { includeGroup("com.github.xgouchet") } } + } + dependencies { classpath("com.google.android.wearable.watchface.validator:validator-push:1.0.0-alpha09") } +} + plugins { id("com.android.application") id("org.jetbrains.kotlin.plugin.compose") @@ -9,10 +21,13 @@ android { defaultConfig { applicationId = "kr.o2o.nalssigak" - minSdk = 30 - targetSdk = 34 + // Wear OS 6+ 만. 앱 설치 때 스킨을 같이 깔고 시계 화면으로 바꾸는 Watch Face Push 가 API 36 부터다 + minSdk = 36 + targetSdk = 36 versionCode = 1 versionName = "0.1" + // 앱에 실은 스킨 버전. 워치에 깔린 스킨이 이보다 낮으면 앱이 바꿔 끼운다 (MainActivity.useSkin) + buildConfigField("int", "SKIN_VERSION", providers.gradleProperty("NALSSIGAK_SKIN_VERSION").get()) } buildTypes { // 에뮬레이터에서 본 맥의 로컬 백엔드 (compose 포트 9810) @@ -38,4 +53,36 @@ dependencies { implementation("androidx.wear.tiles:tiles:1.6.2") implementation("androidx.concurrent:concurrent-futures:1.3.0") implementation("androidx.wear.watchface:watchface-complications-data-source-ktx:1.3.0") + implementation("androidx.wear.watchfacepush:watchfacepush:1.0.0") +} + +// 앱을 깔면 스킨(:watchface)도 같이 깔리게 한다 (Wear OS 6+ 기본 워치 페이스). +// 같은 빌드 타입의 스킨 APK 를 assets/default_watchface.apk 로 싣고, 검증 토큰을 문자열 리소스로 만든다 +androidComponents.onVariants { variant -> + val name = variant.name.replaceFirstChar(Char::titlecase) + val skinApks = project(":watchface").layout.buildDirectory.dir("outputs/apk/${variant.name}") + val assetsDir = layout.buildDirectory.dir("generated/skinAssets/${variant.name}") + val resDir = layout.buildDirectory.dir("generated/skinToken/${variant.name}") + val appId = variant.applicationId + variant.sources.assets?.addStaticSourceDirectory(assetsDir.get().asFile.path) + variant.sources.res?.addStaticSourceDirectory(resDir.get().asFile.path) + val bundle = tasks.register("bundleSkin$name") { + dependsOn(":watchface:assemble$name") + inputs.dir(skinApks) + outputs.dirs(assetsDir, resDir) + doLast { + val apk = skinApks.get().asFile.listFiles { f -> f.extension == "apk" }!!.single() + // 서명 없는 스킨은 워치가 설치를 거부한다. 업로드 키 설정은 루트 build.gradle.kts 참고 + if (apk.name.endsWith("-unsigned.apk")) throw GradleException("스킨 APK 가 서명되지 않았습니다. ~/.gradle/gradle.properties 에 NALSSIGAK_STORE_* 를 넣고 다시 빌드하세요") + val result = DwfValidatorFactory.create().validate(apk, appId.get()) + if (result.failures().isNotEmpty()) throw GradleException("스킨 검증 실패: ${result.failures()}") + apk.copyTo(assetsDir.get().file("default_watchface.apk").asFile, overwrite = true) + resDir.get().file("values/skin_token.xml").asFile.apply { parentFile.mkdirs() } + .writeText( + """""" + + """${result.validationToken()}""" + "\n" + ) + } + } + afterEvaluate { tasks.named("pre${name}Build") { dependsOn(bundle) } } } diff --git a/watch/app/src/main/AndroidManifest.xml b/watch/app/src/main/AndroidManifest.xml index ec1e0a5..9873c9c 100644 --- a/watch/app/src/main/AndroidManifest.xml +++ b/watch/app/src/main/AndroidManifest.xml @@ -4,6 +4,9 @@ + + + + + + @@ -126,7 +134,7 @@ - + - + diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/MainActivity.kt b/watch/app/src/main/java/kr/o2o/nalssigak/MainActivity.kt index b48285c..27d77a2 100644 --- a/watch/app/src/main/java/kr/o2o/nalssigak/MainActivity.kt +++ b/watch/app/src/main/java/kr/o2o/nalssigak/MainActivity.kt @@ -3,6 +3,8 @@ package kr.o2o.nalssigak import android.Manifest import android.content.pm.PackageManager import android.os.Bundle +import android.os.ParcelFileDescriptor +import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts @@ -16,29 +18,85 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.lifecycle.lifecycleScope import androidx.wear.compose.foundation.pager.VerticalPager import androidx.wear.compose.foundation.pager.rememberPagerState import androidx.wear.compose.material3.MaterialTheme import androidx.wear.compose.material3.VerticalPageIndicator +import androidx.wear.watchfacepush.WatchFacePushManager +import androidx.wear.watchfacepush.WatchFacePushManagerFactory +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File import java.time.Instant import kotlin.concurrent.thread /** 컴플리케이션 탭이 실어 보내는 각 코드 */ const val EXTRA_GAK = "gak" +/** 앱과 같이 깔린 스킨을 시계 화면으로 바꾸는 권한. 사용자가 한 번 거절하면 다시 묻지 못한다 */ +private const val SET_SKIN = "com.google.wear.permission.SET_PUSHED_WATCH_FACE_AS_ACTIVE" +private const val TAG = "MainActivity" + class MainActivity : ComponentActivity() { private var summary by mutableStateOf(null) private var loading by mutableStateOf(true) - private val askLocation = registerForActivityResult(ActivityResultContracts.RequestPermission()) { load() } + private val askPermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { + load() + useSkin() + } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val opened = intent.getStringExtra(EXTRA_GAK) setContent { MaterialTheme { App(summary, loading, opened) { load(force = true) } } } - if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) load() - else askLocation.launch(Manifest.permission.ACCESS_COARSE_LOCATION) + // 위치와 스킨 적용을 한 번에 묻는다 + val missing = listOf(Manifest.permission.ACCESS_COARSE_LOCATION, SET_SKIN).filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED } + if (missing.isEmpty()) { + load() + useSkin() + } else askPermissions.launch(missing.toTypedArray()) + } + + /** + * 앱 설치 때 같이 깔린 날씨각 스킨을 챙긴다. + * 앱 업데이트로 새 스킨이 실려 왔으면 바꿔 끼우고(기본 스킨은 처음 설치 때만 깔린다), 허락받았으면 시계 화면으로 바꾼다(시스템이 앱마다 한 번만 허락한다). + */ + private fun useSkin() { + lifecycleScope.launch { + val push = WatchFacePushManagerFactory.createWatchFacePushManager(this@MainActivity) + try { + // 기본 스킨 설치가 아직 안 끝났으면 다음 실행 때 다시 본다 + val skin = push.listWatchFaces().installedWatchFaceDetails.firstOrNull() ?: return@launch + if (skin.versionCode < BuildConfig.SKIN_VERSION) updateSkin(push, skin.slotId) + if (checkSelfPermission(SET_SKIN) == PackageManager.PERMISSION_GRANTED && !push.isWatchFaceActive(skin.packageName)) { + push.setWatchFaceAsActive(skin.slotId) + } + } catch (e: WatchFacePushManager.ListWatchFacesException) { + Log.w(TAG, "스킨 목록을 못 읽음", e) + } catch (e: WatchFacePushManager.UpdateWatchFaceException) { + Log.w(TAG, "스킨을 새 버전으로 못 바꿈", e) + } catch (e: WatchFacePushManager.IsWatchFaceActiveException) { + Log.w(TAG, "스킨 사용 여부를 못 읽음", e) + } catch (e: WatchFacePushManager.SetWatchFaceAsActiveException) { + // 이미 한 번 바꾼 뒤 사용자가 다른 화면으로 옮긴 경우. 다시 바꾸지 않는다 + Log.i(TAG, "스킨을 시계 화면으로 바꾸지 않음", e) + } + } + } + + /** 앱에 실은 스킨(assets/default_watchface.apk)으로 바꿔 끼운다. 검증 토큰은 빌드가 만든 것 (build.gradle.kts) */ + private suspend fun updateSkin(push: WatchFacePushManager, slotId: String) { + val apk = File(cacheDir, "skin.apk") + try { + withContext(Dispatchers.IO) { assets.open("default_watchface.apk").use { input -> apk.outputStream().use { input.copyTo(it) } } } + ParcelFileDescriptor.open(apk, ParcelFileDescriptor.MODE_READ_ONLY).use { push.updateWatchFace(slotId, it, getString(R.string.default_wf_token)) } + } finally { + apk.delete() + } } private fun load(force: Boolean = false) { @@ -50,7 +108,7 @@ class MainActivity : ComponentActivity() { } } -private enum class Page { DETAIL, EVENTS, TOP, PICKS, SUNSET, HOURS } +private enum class Page { DETAIL, HOURS, EVENTS, TOP, PICKS, SUNSET } @Composable private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> Unit) { @@ -65,15 +123,15 @@ private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> U StatePage(loading, onRetry) return } - // 스킨 링에서 누른 각이 있으면 그 상세부터, 아니면 주변 축제부터 (축제가 없으면 오늘의 각부터) + // 스킨 링에서 누른 각이 있으면 그 상세부터, 아니면 오늘 남은 시간 → 주변 축제 → 각 순서 val detail = opened?.let { c -> (s.top + s.picks).firstOrNull { it.code == c } } val pages = buildList { if (detail != null) add(Page.DETAIL) + if (s.slots.isNotEmpty()) add(Page.HOURS) if (s.events.isNotEmpty()) add(Page.EVENTS) if (s.top.isNotEmpty()) add(Page.TOP) if (s.picks.isNotEmpty()) add(Page.PICKS) if (s.sunset != null) add(Page.SUNSET) - if (s.slots.isNotEmpty()) add(Page.HOURS) } val state = rememberPagerState { pages.size } Box(Modifier.fillMaxSize()) { diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt b/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt index 8eec0f3..e8a3e05 100644 --- a/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt +++ b/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt @@ -1,27 +1,45 @@ package kr.o2o.nalssigak +import android.app.PendingIntent +import android.content.Intent import androidx.wear.watchface.complications.data.ComplicationData import androidx.wear.watchface.complications.data.ComplicationType import androidx.wear.watchface.complications.data.PlainComplicationText -import androidx.wear.watchface.complications.data.ShortTextComplicationData +import androidx.wear.watchface.complications.data.RangedValueComplicationData import androidx.wear.watchface.complications.datasource.ComplicationRequest import androidx.wear.watchface.complications.datasource.SuspendingComplicationDataSourceService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlin.math.roundToInt -/** 워치 스킨 아래 칩: 글자 = 지금 기온, 제목 = 비 소식. 스킨은 제목("비 와요"·"곧 비"·"천둥 쳐요"·"눈 와요")을 보고 빗줄기·눈송이와 가운데 구름도 그린다. */ +/** + * 워치 스킨 날씨 칸 + 가운데 1위. 스킨 칸이 8개까지라 한 칸에 몰아 준다. + * 값 = 날씨 코드(0 맑음·1 비·2 천둥·3 눈) × 1000 + 1위 점수, 글자 = 지금 기온, 제목 = 1위 이름(없으면 빈 글자). + */ class RainComplicationService : SuspendingComplicationDataSourceService() { override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? { val s = withContext(Dispatchers.IO) { SummaryRepo.load(this@RainComplicationService) } ?: return null - return data(s.tempC?.let { "${it.roundToInt()}°" } ?: "-°", s.rainLabel) + val code = when (s.rainLabel) { + "비 와요", "곧 비" -> 1 + "천둥 쳐요" -> 2 + "눈 와요" -> 3 + else -> 0 + } + val top = s.top.firstOrNull() + return data(code, top?.score ?: 0, s.tempC?.let { "${it.roundToInt()}°" } ?: "-°", top?.name ?: "") } - override fun getPreviewData(type: ComplicationType): ComplicationData = data("20°", "비 없음") + override fun getPreviewData(type: ComplicationType): ComplicationData = data(0, 88, "20°", "산책각") - private fun data(temp: String, rain: String) = ShortTextComplicationData.Builder( - PlainComplicationText.Builder(temp).build(), - PlainComplicationText.Builder("$temp $rain").build(), - ).setTitle(PlainComplicationText.Builder(rain).build()).build() + private fun data(code: Int, score: Int, temp: String, name: String): ComplicationData { + // 가운데 구슬을 누르면 앱 첫 장 + val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + return RangedValueComplicationData.Builder(code * 1000f + score, 0f, 3100f, PlainComplicationText.Builder("$name $score, $temp").build()) + .setText(PlainComplicationText.Builder(temp).build()) + .setTitle(PlainComplicationText.Builder(name).build()) + .setTapAction(open) + .build() + } } diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt b/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt index de85967..78d0e1c 100644 --- a/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt +++ b/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt @@ -60,7 +60,7 @@ data class Summary( else -> null } - /** 스킨 칩의 비 소식. 스킨은 이 글자를 보고 가운데를 비구름·천둥 구름·눈구름으로 바꾼다 */ + /** 비 소식. 스킨 날씨 칸(RainComplicationService)이 이 글자로 날씨 코드를 정한다 */ val rainLabel: String get() = when { precip == "snow" -> "눈 와요" thunder == true -> "천둥 쳐요" diff --git a/watch/gradle.properties b/watch/gradle.properties index 660848f..66d67d8 100644 --- a/watch/gradle.properties +++ b/watch/gradle.properties @@ -1,2 +1,4 @@ org.gradle.jvmargs=-Xmx2g android.useAndroidX=true +# 워치 스킨 버전. 스킨(watchface.xml·리소스)을 바꾸면 1 올린다. 앱은 깔린 스킨이 이보다 낮으면 앱에 실은 스킨으로 바꿔 끼운다 +NALSSIGAK_SKIN_VERSION=2 diff --git a/watch/watchface/build.gradle.kts b/watch/watchface/build.gradle.kts index 85b7ff9..6c0ba39 100644 --- a/watch/watchface/build.gradle.kts +++ b/watch/watchface/build.gradle.kts @@ -9,15 +9,16 @@ android { compileSdk = 37 defaultConfig { - applicationId = "kr.o2o.nalssigak.watchface" + // 앱(:app)이 Watch Face Push 로 같이 설치하려면 "<앱 패키지>.watchfacepush.<이름>" 이어야 한다 + applicationId = "kr.o2o.nalssigak.watchfacepush.skin" // WFF 버전 2 는 Wear OS 5(API 34)부터 minSdk = 34 targetSdk = 34 - versionCode = 1 + versionCode = providers.gradleProperty("NALSSIGAK_SKIN_VERSION").get().toInt() versionName = "0.1" } - buildTypes.getByName("release") { - // 스킨 번들엔 dex 가 없어야 한다. R8 이 R 클래스까지 다 걷어내게 + // 스킨 APK 엔 dex 가 없어야 한다 (Play 번들, 앱에 싣는 Watch Face Push 둘 다). R8 이 R 클래스까지 다 걷어내게 + buildTypes.all { isMinifyEnabled = true // 스킨 XML 이 이름으로만 부르는 아이콘·글꼴을 안 쓰는 걸로 보고 지운다. 켜지 말 것 isShrinkResources = false diff --git a/watch/watchface/gen_watchface.py b/watch/watchface/gen_watchface.py index ce1c4c0..718e3e7 100644 --- a/watch/watchface/gen_watchface.py +++ b/watch/watchface/gen_watchface.py @@ -117,21 +117,19 @@ def text(x, y, w, h, family, size, color, expr, amb=False): ''' -def orb_slot(): +def orb_text(): + """해 구슬 위 1위 점수·이름. 날씨 칸 값: 값 = 날씨 코드 × 1000 + 1위 점수, 제목 = 1위 이름 (1위가 없으면 빈 제목)""" x, y = CX - ORB // 2, CY - ORB // 2 - body = text(0, int(ORB * .19), ORB, int(ORB * .45), "bagel_fat_one", 50, "#FFFFFFFF", "[COMPLICATION.TEXT]") + text(14, int(ORB * .62), ORB - 28, 28, "jua", 19, "#FFFFFFFF", "[COMPLICATION.TITLE]") - return f''' - - - + body = (text(x, y + int(ORB * .19), ORB, int(ORB * .45), "bagel_fat_one", 50, "#FFFFFFFF", f"round({VALUE} % 1000)") + + text(x + 14, y + int(ORB * .62), ORB - 28, 28, "jua", 19, "#FFFFFFFF", "[COMPLICATION.TITLE]")) + return f''' + + {body} - - - {body} - - - ''' + + ''' +VALUE = "[COMPLICATION.RANGED_VALUE_VALUE]" PROGRESS = "clamp([COMPLICATION.RANGED_VALUE_VALUE], [COMPLICATION.RANGED_VALUE_MIN], [COMPLICATION.RANGED_VALUE_MAX]) / ([COMPLICATION.RANGED_VALUE_MAX] - [COMPLICATION.RANGED_VALUE_MIN]) * 360" def icon_by_title(x, y, size): @@ -182,10 +180,11 @@ def chip(x, w, icon, expr): {text(x + 32, CHIP_Y + 5, w - 38, 30, "jua", 21, INK, expr, amb=True)}''' def precip_slot(): - """화면 전체를 덮는 숨은 칸. 날씨각 앱(RainComplicationService)이 글자 = 기온, 제목 = 비 소식을 주면 - 아래에 기온·비 칩을 그리고, 비 소식이 "비 와요"·"곧 비"면 빗줄기와 비구름, "천둥 쳐요"면 빗줄기와 번개 구름, - "눈 와요"면 눈송이와 눈구름을 가운데 해 자리에 그린다. 날씨 값은 이 칸 안에서만 읽혀서 맑을 때 해·달 구슬도 여기서 그린다. - 터치는 막지 않게 BoundingOval 을 1px 로 둔다. 주기는 60 의 약수여야 분이 바뀔 때 튀지 않는다.""" + """화면 전체를 덮는 숨은 칸. WFF 는 칸이 8개까지라 날씨와 1위를 이 칸 하나로 받는다. + 날씨각 앱(RainComplicationService)이 값 = 날씨 코드 × 1000 + 1위 점수, 글자 = 기온, 제목 = 1위 이름을 준다. + 날씨 코드 1(비·곧 비)이면 빗줄기와 비구름, 2(천둥)면 빗줄기와 번개 구름, 3(눈)이면 눈송이와 눈구름을 가운데 해 자리에 그리고, + 그 위에 1위 점수·이름, 아래에 기온 칩을 그린다. 날씨 값은 이 칸 안에서만 읽혀서 맑을 때 해·달 구슬도 여기서 그린다. + 터치는 가운데 구슬만 받는다(누르면 앱). 주기는 60 의 약수여야 분이 바뀔 때 튀지 않는다.""" import random r = random.Random(7) drops, flakes = [], [] @@ -207,15 +206,16 @@ def precip_slot(): ''') shade = lambda c: f'{AMB0}' - return f''' - - - + mode = f"floor({VALUE} / 1000)" + return f''' + + + - - - + + + @@ -235,8 +235,8 @@ def precip_slot(): {sun_or_moon()} - {chip(108, 104, "thermo", "[COMPLICATION.TEXT]")} - {chip(220, 122, "umbrella", "[COMPLICATION.TITLE]")} + {chip(CX - 52, 104, "thermo", "[COMPLICATION.TEXT]")} + {orb_text()} @@ -273,7 +273,7 @@ exprs = "\n ".join(f'\n {mode_block(v[1], v[2], v[3])}\n ' for k, v in MODES.items()) xml = f''' - @@ -293,7 +293,6 @@ xml = f''' {precip_slot()} {clock("#FFFFFFFF", ambient_visible=True)} - {orb_slot()} {"".join(ring_slot(i, a) for i, a in enumerate(ANGLES))} {event_slot()} diff --git a/watch/watchface/src/main/res/raw/watchface.xml b/watch/watchface/src/main/res/raw/watchface.xml index 2916629..bdb8454 100644 --- a/watch/watchface/src/main/res/raw/watchface.xml +++ b/watch/watchface/src/main/res/raw/watchface.xml @@ -1,5 +1,5 @@ - @@ -148,15 +148,15 @@ - - - - + + + + - - - + + + = 21]]> @@ -495,22 +495,24 @@ - + - - + + - - - - - - - + + + + + + + + + @@ -535,25 +537,6 @@ - - - - - - - - - - - - - - - - - - - From 599ef05dcf45dc8e79326340f839efd0d0c5f223 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Tue, 13 Oct 2026 17:02:41 +0900 Subject: [PATCH 02/63] =?UTF-8?q?fix:=20=EC=B2=98=EC=9D=8C=20=EC=98=A8=20?= =?UTF-8?q?=EC=A7=80=EC=97=AD=EC=9D=98=20=EA=B0=81=EC=9D=B4=20=EB=B9=84?= =?UTF-8?q?=EC=96=B4=20=EB=B3=B4=EC=9D=B4=EB=8D=98=20=EA=B2=83=20(?= =?UTF-8?q?=EC=98=88=EB=B3=B4=20=EB=B0=9B=EB=8A=94=20=EB=8F=99=EC=95=88=20?= =?UTF-8?q?3=EC=B4=88=EB=A7=8C=20=EA=B8=B0=EB=8B=A4=EB=A6=AC=EA=B3=A0=20?= =?UTF-8?q?=EB=B9=88=20=ED=94=BC=EB=93=9C=EB=A5=BC=201=EB=B6=84=20?= =?UTF-8?q?=EC=A0=80=EC=9E=A5=ED=95=98=EB=8D=98=20=EA=B2=83)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/services/feed_service.py | 3 +++ backend/services/weather_service.py | 2 +- backend/tests/test_feed.py | 5 ++--- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index 9e57a41..6f4d209 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -323,6 +323,9 @@ class FeedService: async with redis_lock("lock:feed:build", ttl_sec=20): await build_feed_day(day, self.crud, self.season_crud, self.regions) res, partial = await self._assemble(region, now, day, slot, sunset_at) + # 각을 못 낸 피드는 저장하지 않는다. 처음 온 지역은 예보를 받는 중이라 다음 요청에서 바로 채운다 + if not res.bands.top5: + return ErrorType.SUCCESS, res try: await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at)) except RedisError as e: diff --git a/backend/services/weather_service.py b/backend/services/weather_service.py index 44ec8c4..13dfc0e 100644 --- a/backend/services/weather_service.py +++ b/backend/services/weather_service.py @@ -25,7 +25,7 @@ from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestF from services.external.kma import day_start_base, fetch_mid, fetch_ultra, fetch_vilage, latest_mid_base, parse_mid, parse_ultra, parse_vilage SLOT_HOURS = range(0, 24, 3) -_WAIT_STEPS, _WAIT_SEC = 15, 0.2 +_WAIT_STEPS, _WAIT_SEC = 75, 0.2 # 처음 온 지역은 다른 요청이 예보를 받아 오는 동안 최대 15초 기다린다 # 단기예보 끝날 몇 시간만 있는 날은 하루 값을 만들지 않는다 (중기예보 값을 덮어쓰지 않게). _MIN_DAY_HOURS = 8 MID_DAYS = 11 # 중기예보가 닿는 오늘+10일까지 diff --git a/backend/tests/test_feed.py b/backend/tests/test_feed.py index 78cb188..bfba8ae 100644 --- a/backend/tests/test_feed.py +++ b/backend/tests/test_feed.py @@ -204,7 +204,7 @@ def test_gak_key_handles_sunset_window(): @pytest.mark.anyio -async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch): +async def test_feed_missing_gak_is_not_cached(offline, monkeypatch): from common.cache.redis_client import REDIS from common.enums import ErrorType from services.index_service import IndexService @@ -216,8 +216,7 @@ async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/feed", params={"region": REGION})).json() assert PostType.GAK.value not in [p["post_type"] for p in body["posts"]] - keys = [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")] - assert keys and 0 < await REDIS.conn.ttl(keys[0]) <= 60 + assert [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")] == [] def _alert_ctx(warnings=(), rain_prob=0): From b586db0de7bb7a7410a3326d2498959a201f8c24 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Wed, 14 Oct 2026 09:08:49 +0900 Subject: [PATCH 03/63] =?UTF-8?q?feat:=20=EB=B3=B4=EA=B3=A0=20=EC=9E=88?= =?UTF-8?q?=EB=8A=94=20=ED=83=AD=EC=9D=84=20=EB=8B=A4=EC=8B=9C=20=EB=88=84?= =?UTF-8?q?=EB=A5=B4=EB=A9=B4=20=EB=A7=A8=20=EC=9C=84=EB=A1=9C=20=EC=8A=A4?= =?UTF-8?q?=ED=81=AC=EB=A1=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/b/BLayout.tsx | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/frontend/src/b/BLayout.tsx b/frontend/src/b/BLayout.tsx index fca9a25..bbb3afa 100644 --- a/frontend/src/b/BLayout.tsx +++ b/frontend/src/b/BLayout.tsx @@ -48,17 +48,17 @@ function TopBar() { const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to)) return ( -
+
{tab?.title ?

{tab.title}

:

날씨각

} {mePending ? ( @@ -208,6 +208,10 @@ function Shell() { useEffect(() => { window.scrollTo({ top: 0 }) }, [pathname]) + // 지금 보고 있는 탭을 다시 누르면 맨 위로 + const toTopIfHere = (to: string) => () => { + if (pathname === to) window.scrollTo({ top: 0, behavior: 'smooth' }) + } useEffect(() => { document.querySelector('meta[name="theme-color"]')?.setAttribute('content', NOTCH_BG[kind]) }, [kind]) @@ -228,14 +232,14 @@ function Shell() { {TABS.map((t) => t.key === 'today' ? ( // 메인 탭: 막대 위로 솟은 큰 주황 동그라미 - cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive ? 'text-(--orange)' : 'text-(--ink3)')}> + cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive ? 'text-(--orange)' : 'text-(--ink3)')}> {t.label} ) : ( - cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}> + cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}> {t.label} From 0aeceac2577da46717e856d667d6bf5b588cd7d7 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Wed, 14 Oct 2026 09:08:50 +0900 Subject: [PATCH 04/63] =?UTF-8?q?feat:=20=EC=9A=B0=EC=82=B0=EB=B6=84?= =?UTF-8?q?=EC=8B=A4=EA=B0=81(=EB=B9=84=20=EA=B7=B8=EC=B9=9C=20=EB=92=A4?= =?UTF-8?q?=20=EC=9A=B0=EC=82=B0=20=EB=91=90=EA=B3=A0=20=EC=98=A4=EA=B8=B0?= =?UTF-8?q?=20=EC=89=AC=EC=9A=B4=20=EC=A0=95=EB=8F=84)=C2=B7=EA=B5=90?= =?UTF-8?q?=ED=86=B5=EC=B2=B4=EC=A6=9D=EA=B0=81(=EC=B6=9C=ED=87=B4?= =?UTF-8?q?=EA=B7=BC=EA=B8=B8=20=EB=B9=84=C2=B7=EB=88=88=C2=B7=EC=B6=94?= =?UTF-8?q?=EC=9C=84)=20=EC=B6=94=EA=B0=80,=20'=EC=95=9E=EC=84=9C=20?= =?UTF-8?q?=EB=B9=84=20=EC=98=B4'=20=EC=A1=B0=EA=B1=B4(rain=5Fbefore)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/seed/index_definition.json | 154 ++++++++++++++++++++++++++++ backend/services/calc/index_calc.py | 7 +- backend/services/index_service.py | 10 +- backend/tests/test_index_calc.py | 10 ++ frontend/seo/gak.json | 8 ++ 5 files changed, 186 insertions(+), 3 deletions(-) diff --git a/backend/seed/index_definition.json b/backend/seed/index_definition.json index a14384d..e0ee25e 100644 --- a/backend/seed/index_definition.json +++ b/backend/seed/index_definition.json @@ -3730,5 +3730,159 @@ "sort_order": 51, "priority": 3, "months": [] + }, + { + "code": "umbrella_lost", + "name": "우산분실각", + "icon": "umbrella", + "category": 4, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "오전 9시~밤 10시, 비가 그쳐서 우산을 두고 오기 쉬운 정도", + "windows": [ + { + "from": 9, + "to": 11 + }, + { + "from": 11, + "to": 13 + }, + { + "from": 13, + "to": 15 + }, + { + "from": 15, + "to": 17 + }, + { + "from": 17, + "to": 19 + }, + { + "from": 19, + "to": 22 + } + ], + "weight_temp": 0, + "weight_rain": 80, + "weight_wind": 0, + "weight_humidity": 0, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 20, + "factor_rules": { + "temp": { + "type": "range", + "lo": 0, + "hi": 40 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "ignore" + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [ + { + "field": "rain_before", + "op": "==", + "value": "no" + }, + { + "field": "rain", + "op": "==", + "value": "yes" + } + ], + "limit_description": "비가 언제 그칠지는 예보만큼만 맞아요", + "sentences": { + "0": "우산 두고 올 일 없는 날이에요.", + "30": "비가 오락가락해요. 우산 손에 꼭 쥐어요.", + "60": "비가 그쳤어요. 카페·버스에 우산 두고 오기 딱 좋아요.", + "80": "비 끝, 하늘 맑음! 일어날 때 우산부터 챙겨요 ☂️" + }, + "sort_order": 52, + "priority": 2, + "months": [] + }, + { + "code": "traffic", + "name": "교통체증각", + "icon": "drive", + "category": 4, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "출퇴근길 비·눈·추위로 차가 막히는 정도", + "windows": [ + { + "from": 7, + "to": 10 + }, + { + "from": 17, + "to": 20 + } + ], + "weight_temp": 10, + "weight_rain": 70, + "weight_wind": 0, + "weight_humidity": 0, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 20, + "factor_rules": { + "temp": { + "type": "lower", + "zero": 10, + "full": -5 + }, + "rain": { + "dir": "wet" + }, + "wind": { + "type": "ignore" + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "weekday", + "mon": 100, + "tue": 100, + "wed": 100, + "thu": 100, + "fri": 100, + "sat": 40, + "sun": 40, + "holiday": 30 + } + }, + "zero_rules": [], + "limit_description": "사고·공사·행사로 막히는 건 반영하지 못해요", + "sentences": { + "0": "길이 수월해요. 평소처럼 나가요.", + "30": "조금 더뎌 수 있어요. 10분 일찍!", + "60": "빗길에 차가 막혀요. 대중교통이 나아요.", + "80": "출퇴근길 주차장 예상! 30분 일찍 나서요 🚗" + }, + "sort_order": 53, + "priority": 2, + "months": [] } ] diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index 4dcc185..ab01444 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -56,6 +56,7 @@ class Context: lookahead_rain_prob: int moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간 sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각) + rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지' @dataclass(frozen=True) @@ -262,6 +263,8 @@ def _cond(r: dict) -> tuple[str, str, str]: return "눈 소식이 없어", "눈 소식이 없거나", "눈 소식이 없으면" if r["field"] == "rain": return "비 소식이 있어", "비 소식이 있거나", "비 소식이 있으면" + if r["field"] == "rain_before": + return "앞서 내린 비가 없어", "앞서 내린 비가 없거나", "앞서 내린 비가 없으면" base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}" return f"{base}이라", f"{base}이거나", f"{base}이면" @@ -344,6 +347,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re "gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None), "snow": "yes" if any(h.rain_type in (RainType.SNOW, RainType.SLEET) for h in hours) else "no", "rain": "yes" if raining else "no", "humidity": round(mean(h.humidity for h in hours)), + "rain_before": "yes" if any(h < hours[0].hour for h in ctx.rain_hours) else "no", } reason, cap = _zero(definition.zero_rules, agg) if reason is not None: @@ -393,7 +397,8 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context notes = {a: n for a, (_, n) in scored.items()} score = _weighted(factors, weights) # 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다 - known = {"rain_prob": max_prob, "snow": "no"} + # 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다 + known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"} reason, cap = _zero([r for r in definition.zero_rules if r["field"] in known], known) if reason is not None: score = min(score, cap) diff --git a/backend/services/index_service.py b/backend/services/index_service.py index d586207..a615e8c 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -193,6 +193,12 @@ def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]: return {k: shown[k] for k in SLOTS if k in shown} +def rain_hours(by_at: dict[datetime, WeatherHourly], day: date) -> frozenset[int]: + """그날 비·눈 오는 시각(0~23).""" + start = kst_midnight(day) + return frozenset(h for h in range(24) if (r := by_at.get(start + timedelta(hours=h))) is not None and r.rain_type != RainType.NONE.value) + + def slot_results( defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime, now: Optional[datetime] = None, @@ -388,7 +394,7 @@ class IndexService: air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None, wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []), ) - today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx) + today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), **base_ctx) sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()} @@ -419,7 +425,7 @@ class IndexService: m = night(day, float(region.lat), float(region.lon)) ctx = Context( day=day, is_holiday=day in (holidays or set()), moon=m.lit * up_ratio(m, _STARS_HOURS), moon_note=f"{m.name}, {view_line(m, None)}", - sunset_score=sunset.get(day), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, **base_ctx, + sunset_score=sunset.get(day), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, rain_hours=rain_hours(by_at, day), **base_ctx, ) for d in defs: result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om) diff --git a/backend/tests/test_index_calc.py b/backend/tests/test_index_calc.py index ff95e2f..3ea3c38 100644 --- a/backend/tests/test_index_calc.py +++ b/backend/tests/test_index_calc.py @@ -308,3 +308,13 @@ def test_humidity_cap(): def test_axis_label_can_be_overridden(): assert axis_label("temp", {"temp": {"type": "higher", "label": "덜 추움"}}) == "덜 추움" + + +def test_umbrella_lost_needs_rain_that_stopped(): + """우산분실각: 앞서 비가 왔다가 그친 시간대만 점수가 난다. 비가 안 온 날, 아직 비가 오는 시간대는 0점.""" + defn = _defn(weight_temp=0, weight_rain=80, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=20, + zero_rules=[{"field": "rain_before", "op": "==", "value": "no"}, {"field": "rain", "op": "==", "value": "yes"}]) + after_rain = replace(CTX, rain_hours=frozenset({9, 10})) + assert evaluate(defn, [[_h(13), _h(14)]], after_rain).score >= 80 + assert evaluate(defn, [[_h(13), _h(14)]], CTX).zero_reason == "앞서 내린 비가 없어 0점" + assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0 diff --git a/frontend/seo/gak.json b/frontend/seo/gak.json index 3693a79..80d9d2d 100644 --- a/frontend/seo/gak.json +++ b/frontend/seo/gak.json @@ -202,5 +202,13 @@ { "name": "싱잉인더레인각", "description": "비 오는 날 우산 쓰고 노래하며 걷기 좋은 정도" + }, + { + "name": "우산분실각", + "description": "오전 9시~밤 10시, 비가 그쳐서 우산을 두고 오기 쉬운 정도" + }, + { + "name": "교통체증각", + "description": "출퇴근길 비·눈·추위로 차가 막히는 정도" } ] From e0d2ad2c9b35554e041fdd31aca84215b10941f0 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Wed, 14 Oct 2026 09:12:45 +0900 Subject: [PATCH 05/63] =?UTF-8?q?feat:=20=EC=A7=80=EC=97=AD=EB=B3=84=20?= =?UTF-8?q?=EA=B2=80=EC=83=89=20=ED=8E=98=EC=9D=B4=EC=A7=80=20230=EC=9E=A5?= =?UTF-8?q?=20(/today/{=EC=8B=9C=EB=8F=84}/{=EC=A7=80=EC=97=AD},=20?= =?UTF-8?q?=EA=B5=AC=EB=A1=9C=20=EB=82=98=EB=89=9C=2013=EA=B0=9C=20?= =?UTF-8?q?=EC=8B=9C=EB=8A=94=20=EC=8B=9C=20=ED=8E=98=EC=9D=B4=EC=A7=80)?= =?UTF-8?q?=20+=20sitemap=20=EC=9E=90=EB=8F=99=20=EC=83=9D=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/public/sitemap.xml | 8 - frontend/seo/region.json | 3404 +++++++++++++++++++++++++++++++++++ frontend/src/App.tsx | 1 + frontend/src/b/BLayout.tsx | 2 +- frontend/src/b/region.tsx | 82 +- frontend/tsconfig.app.json | 1 + frontend/vite.config.ts | 26 +- 7 files changed, 3496 insertions(+), 28 deletions(-) delete mode 100644 frontend/public/sitemap.xml create mode 100644 frontend/seo/region.json diff --git a/frontend/public/sitemap.xml b/frontend/public/sitemap.xml deleted file mode 100644 index 87e7843..0000000 --- a/frontend/public/sitemap.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - https://weather.o2o.kr/2026-10-13 - https://weather.o2o.kr/gak2026-10-13 - https://weather.o2o.kr/sky2026-10-13 - https://weather.o2o.kr/week2026-10-13 - https://weather.o2o.kr/season2026-10-13 - diff --git a/frontend/seo/region.json b/frontend/seo/region.json new file mode 100644 index 0000000..1238af7 --- /dev/null +++ b/frontend/seo/region.json @@ -0,0 +1,3404 @@ +[ + { + "path": "seoul/jongno", + "name": "서울 종로구", + "main": "1111000000", + "regions": [ + { + "code": "1111000000", + "name": "서울 종로구", + "short_name": "종로구", + "lat": 37.57038, + "lon": 126.98164 + } + ] + }, + { + "path": "seoul/jung", + "name": "서울 중구", + "main": "1114000000", + "regions": [ + { + "code": "1114000000", + "name": "서울 중구", + "short_name": "중구", + "lat": 37.561, + "lon": 126.99964 + } + ] + }, + { + "path": "seoul/yongsan", + "name": "서울 용산구", + "main": "1117000000", + "regions": [ + { + "code": "1117000000", + "name": "서울 용산구", + "short_name": "용산구", + "lat": 37.53609, + "lon": 126.96752 + } + ] + }, + { + "path": "seoul/seongdong", + "name": "서울 성동구", + "main": "1120000000", + "regions": [ + { + "code": "1120000000", + "name": "서울 성동구", + "short_name": "성동구", + "lat": 37.56061, + "lon": 127.039 + } + ] + }, + { + "path": "seoul/gwangjin", + "name": "서울 광진구", + "main": "1121500000", + "regions": [ + { + "code": "1121500000", + "name": "서울 광진구", + "short_name": "광진구", + "lat": 37.53574, + "lon": 127.08453 + } + ] + }, + { + "path": "seoul/dongdaemun", + "name": "서울 동대문구", + "main": "1123000000", + "regions": [ + { + "code": "1123000000", + "name": "서울 동대문구", + "short_name": "동대문구", + "lat": 37.57162, + "lon": 127.04214 + } + ] + }, + { + "path": "seoul/jungnang", + "name": "서울 중랑구", + "main": "1126000000", + "regions": [ + { + "code": "1126000000", + "name": "서울 중랑구", + "short_name": "중랑구", + "lat": 37.60381, + "lon": 127.09478 + } + ] + }, + { + "path": "seoul/seongbuk", + "name": "서울 성북구", + "main": "1129000000", + "regions": [ + { + "code": "1129000000", + "name": "서울 성북구", + "short_name": "성북구", + "lat": 37.58638, + "lon": 127.02033 + } + ] + }, + { + "path": "seoul/gangbuk", + "name": "서울 강북구", + "main": "1130500000", + "regions": [ + { + "code": "1130500000", + "name": "서울 강북구", + "short_name": "강북구", + "lat": 37.63696, + "lon": 127.02772 + } + ] + }, + { + "path": "seoul/dobong", + "name": "서울 도봉구", + "main": "1132000000", + "regions": [ + { + "code": "1132000000", + "name": "서울 도봉구", + "short_name": "도봉구", + "lat": 37.66583, + "lon": 127.04952 + } + ] + }, + { + "path": "seoul/nowon", + "name": "서울 노원구", + "main": "1135000000", + "regions": [ + { + "code": "1135000000", + "name": "서울 노원구", + "short_name": "노원구", + "lat": 37.65146, + "lon": 127.05839 + } + ] + }, + { + "path": "seoul/eunpyeong", + "name": "서울 은평구", + "main": "1138000000", + "regions": [ + { + "code": "1138000000", + "name": "서울 은평구", + "short_name": "은평구", + "lat": 37.59997, + "lon": 126.93124 + } + ] + }, + { + "path": "seoul/seodaemun", + "name": "서울 서대문구", + "main": "1141000000", + "regions": [ + { + "code": "1141000000", + "name": "서울 서대문구", + "short_name": "서대문구", + "lat": 37.57637, + "lon": 126.9389 + } + ] + }, + { + "path": "seoul/mapo", + "name": "서울 마포구", + "main": "1144000000", + "regions": [ + { + "code": "1144000000", + "name": "서울 마포구", + "short_name": "마포구", + "lat": 37.56071, + "lon": 126.91053 + } + ] + }, + { + "path": "seoul/yangcheon", + "name": "서울 양천구", + "main": "1147000000", + "regions": [ + { + "code": "1147000000", + "name": "서울 양천구", + "short_name": "양천구", + "lat": 37.51423, + "lon": 126.86871 + } + ] + }, + { + "path": "seoul/gangseo", + "name": "서울 강서구", + "main": "1150000000", + "regions": [ + { + "code": "1150000000", + "name": "서울 강서구", + "short_name": "강서구", + "lat": 37.54816, + "lon": 126.85168 + } + ] + }, + { + "path": "seoul/guro", + "name": "서울 구로구", + "main": "1153000000", + "regions": [ + { + "code": "1153000000", + "name": "서울 구로구", + "short_name": "구로구", + "lat": 37.49265, + "lon": 126.8896 + } + ] + }, + { + "path": "seoul/geumcheon", + "name": "서울 금천구", + "main": "1154500000", + "regions": [ + { + "code": "1154500000", + "name": "서울 금천구", + "short_name": "금천구", + "lat": 37.44911, + "lon": 126.9042 + } + ] + }, + { + "path": "seoul/yeongdeungpo", + "name": "서울 영등포구", + "main": "1156000000", + "regions": [ + { + "code": "1156000000", + "name": "서울 영등포구", + "short_name": "영등포구", + "lat": 37.52361, + "lon": 126.89834 + } + ] + }, + { + "path": "seoul/dongjak", + "name": "서울 동작구", + "main": "1159000000", + "regions": [ + { + "code": "1159000000", + "name": "서울 동작구", + "short_name": "동작구", + "lat": 37.50966, + "lon": 126.94158 + } + ] + }, + { + "path": "seoul/gwanak", + "name": "서울 관악구", + "main": "1162000000", + "regions": [ + { + "code": "1162000000", + "name": "서울 관악구", + "short_name": "관악구", + "lat": 37.47539, + "lon": 126.95384 + } + ] + }, + { + "path": "seoul/seocho", + "name": "서울 서초구", + "main": "1165000000", + "regions": [ + { + "code": "1165000000", + "name": "서울 서초구", + "short_name": "서초구", + "lat": 37.48079, + "lon": 127.03481 + } + ] + }, + { + "path": "seoul/gangnam", + "name": "서울 강남구", + "main": "1168000000", + "regions": [ + { + "code": "1168000000", + "name": "서울 강남구", + "short_name": "강남구", + "lat": 37.51458, + "lon": 127.04956 + } + ] + }, + { + "path": "seoul/songpa", + "name": "서울 송파구", + "main": "1171000000", + "regions": [ + { + "code": "1171000000", + "name": "서울 송파구", + "short_name": "송파구", + "lat": 37.51176, + "lon": 127.10793 + } + ] + }, + { + "path": "seoul/gangdong", + "name": "서울 강동구", + "main": "1174000000", + "regions": [ + { + "code": "1174000000", + "name": "서울 강동구", + "short_name": "강동구", + "lat": 37.52737, + "lon": 127.12586 + } + ] + }, + { + "path": "jeonnam/mokpo", + "name": "전남 목포시", + "main": "1211000000", + "regions": [ + { + "code": "1211000000", + "name": "전남 목포시", + "short_name": "목포시", + "lat": 34.80879, + "lon": 126.39442 + } + ] + }, + { + "path": "jeonnam/yeosu", + "name": "전남 여수시", + "main": "1213000000", + "regions": [ + { + "code": "1213000000", + "name": "전남 여수시", + "short_name": "여수시", + "lat": 34.75731, + "lon": 127.66439 + } + ] + }, + { + "path": "jeonnam/suncheon", + "name": "전남 순천시", + "main": "1215000000", + "regions": [ + { + "code": "1215000000", + "name": "전남 순천시", + "short_name": "순천시", + "lat": 34.94761, + "lon": 127.48933 + } + ] + }, + { + "path": "jeonnam/naju", + "name": "전남 나주시", + "main": "1217000000", + "regions": [ + { + "code": "1217000000", + "name": "전남 나주시", + "short_name": "나주시", + "lat": 35.01284, + "lon": 126.71287 + } + ] + }, + { + "path": "jeonnam/gwangyang", + "name": "전남 광양시", + "main": "1219000000", + "regions": [ + { + "code": "1219000000", + "name": "전남 광양시", + "short_name": "광양시", + "lat": 34.93754, + "lon": 127.69818 + } + ] + }, + { + "path": "gwangju/dong", + "name": "광주 동구", + "main": "1221000000", + "regions": [ + { + "code": "1221000000", + "name": "광주 동구", + "short_name": "동구", + "lat": 35.1431, + "lon": 126.92518 + } + ] + }, + { + "path": "gwangju/seo", + "name": "광주 서구", + "main": "1224000000", + "regions": [ + { + "code": "1224000000", + "name": "광주 서구", + "short_name": "서구", + "lat": 35.14948, + "lon": 126.89341 + } + ] + }, + { + "path": "gwangju/nam", + "name": "광주 남구", + "main": "1227000000", + "regions": [ + { + "code": "1227000000", + "name": "광주 남구", + "short_name": "남구", + "lat": 35.11904, + "lon": 126.91014 + } + ] + }, + { + "path": "gwangju/buk", + "name": "광주 북구", + "main": "1230000000", + "regions": [ + { + "code": "1230000000", + "name": "광주 북구", + "short_name": "북구", + "lat": 35.17112, + "lon": 126.91412 + } + ] + }, + { + "path": "gwangju/gwangsan", + "name": "광주 광산구", + "main": "1233000000", + "regions": [ + { + "code": "1233000000", + "name": "광주 광산구", + "short_name": "광산구", + "lat": 35.13643, + "lon": 126.79579 + } + ] + }, + { + "path": "jeonnam/damyang", + "name": "전남 담양군", + "main": "1271000000", + "regions": [ + { + "code": "1271000000", + "name": "전남 담양군", + "short_name": "담양군", + "lat": 35.31813, + "lon": 126.99016 + } + ] + }, + { + "path": "jeonnam/gokseong", + "name": "전남 곡성군", + "main": "1272000000", + "regions": [ + { + "code": "1272000000", + "name": "전남 곡성군", + "short_name": "곡성군", + "lat": 35.27896, + "lon": 127.29411 + } + ] + }, + { + "path": "jeonnam/gurye", + "name": "전남 구례군", + "main": "1273000000", + "regions": [ + { + "code": "1273000000", + "name": "전남 구례군", + "short_name": "구례군", + "lat": 35.19946, + "lon": 127.46493 + } + ] + }, + { + "path": "jeonnam/goheung", + "name": "전남 고흥군", + "main": "1274000000", + "regions": [ + { + "code": "1274000000", + "name": "전남 고흥군", + "short_name": "고흥군", + "lat": 34.60807, + "lon": 127.28706 + } + ] + }, + { + "path": "jeonnam/boseong", + "name": "전남 보성군", + "main": "1275000000", + "regions": [ + { + "code": "1275000000", + "name": "전남 보성군", + "short_name": "보성군", + "lat": 34.76833, + "lon": 127.08209 + } + ] + }, + { + "path": "jeonnam/hwasun", + "name": "전남 화순군", + "main": "1276000000", + "regions": [ + { + "code": "1276000000", + "name": "전남 화순군", + "short_name": "화순군", + "lat": 35.06148, + "lon": 126.98857 + } + ] + }, + { + "path": "jeonnam/jangheung", + "name": "전남 장흥군", + "main": "1277000000", + "regions": [ + { + "code": "1277000000", + "name": "전남 장흥군", + "short_name": "장흥군", + "lat": 34.67853, + "lon": 126.90911 + } + ] + }, + { + "path": "jeonnam/gangjin", + "name": "전남 강진군", + "main": "1278000000", + "regions": [ + { + "code": "1278000000", + "name": "전남 강진군", + "short_name": "강진군", + "lat": 34.63891, + "lon": 126.7692 + } + ] + }, + { + "path": "jeonnam/haenam", + "name": "전남 해남군", + "main": "1279000000", + "regions": [ + { + "code": "1279000000", + "name": "전남 해남군", + "short_name": "해남군", + "lat": 34.57044, + "lon": 126.60129 + } + ] + }, + { + "path": "jeonnam/yeongam", + "name": "전남 영암군", + "main": "1280000000", + "regions": [ + { + "code": "1280000000", + "name": "전남 영암군", + "short_name": "영암군", + "lat": 34.79699, + "lon": 126.69862 + } + ] + }, + { + "path": "jeonnam/muan", + "name": "전남 무안군", + "main": "1281000000", + "regions": [ + { + "code": "1281000000", + "name": "전남 무안군", + "short_name": "무안군", + "lat": 34.98737, + "lon": 126.4837 + } + ] + }, + { + "path": "jeonnam/hampyeong", + "name": "전남 함평군", + "main": "1282000000", + "regions": [ + { + "code": "1282000000", + "name": "전남 함평군", + "short_name": "함평군", + "lat": 35.06274, + "lon": 126.51862 + } + ] + }, + { + "path": "jeonnam/yeonggwang", + "name": "전남 영광군", + "main": "1283000000", + "regions": [ + { + "code": "1283000000", + "name": "전남 영광군", + "short_name": "영광군", + "lat": 35.27417, + "lon": 126.51409 + } + ] + }, + { + "path": "jeonnam/jangseong", + "name": "전남 장성군", + "main": "1284000000", + "regions": [ + { + "code": "1284000000", + "name": "전남 장성군", + "short_name": "장성군", + "lat": 35.29881, + "lon": 126.78697 + } + ] + }, + { + "path": "jeonnam/wando", + "name": "전남 완도군", + "main": "1285000000", + "regions": [ + { + "code": "1285000000", + "name": "전남 완도군", + "short_name": "완도군", + "lat": 34.30785, + "lon": 126.7571 + } + ] + }, + { + "path": "jeonnam/jindo", + "name": "전남 진도군", + "main": "1286000000", + "regions": [ + { + "code": "1286000000", + "name": "전남 진도군", + "short_name": "진도군", + "lat": 34.48375, + "lon": 126.26554 + } + ] + }, + { + "path": "jeonnam/sinan", + "name": "전남 신안군", + "main": "1287000000", + "regions": [ + { + "code": "1287000000", + "name": "전남 신안군", + "short_name": "신안군", + "lat": 34.78981, + "lon": 126.38173 + } + ] + }, + { + "path": "busan/jung", + "name": "부산 중구", + "main": "2611000000", + "regions": [ + { + "code": "2611000000", + "name": "부산 중구", + "short_name": "중구", + "lat": 35.10322, + "lon": 129.03451 + } + ] + }, + { + "path": "busan/seo", + "name": "부산 서구", + "main": "2614000000", + "regions": [ + { + "code": "2614000000", + "name": "부산 서구", + "short_name": "서구", + "lat": 35.09484, + "lon": 129.02638 + } + ] + }, + { + "path": "busan/dong", + "name": "부산 동구", + "main": "2617000000", + "regions": [ + { + "code": "2617000000", + "name": "부산 동구", + "short_name": "동구", + "lat": 35.13589, + "lon": 129.05918 + } + ] + }, + { + "path": "busan/yeongdo", + "name": "부산 영도구", + "main": "2620000000", + "regions": [ + { + "code": "2620000000", + "name": "부산 영도구", + "short_name": "영도구", + "lat": 35.08812, + "lon": 129.07019 + } + ] + }, + { + "path": "busan/busanjin", + "name": "부산 부산진구", + "main": "2623000000", + "regions": [ + { + "code": "2623000000", + "name": "부산 부산진구", + "short_name": "부산진구", + "lat": 35.15995, + "lon": 129.05532 + } + ] + }, + { + "path": "busan/dongnae", + "name": "부산 동래구", + "main": "2626000000", + "regions": [ + { + "code": "2626000000", + "name": "부산 동래구", + "short_name": "동래구", + "lat": 35.20187, + "lon": 129.08586 + } + ] + }, + { + "path": "busan/nam", + "name": "부산 남구", + "main": "2629000000", + "regions": [ + { + "code": "2629000000", + "name": "부산 남구", + "short_name": "남구", + "lat": 35.13341, + "lon": 129.0865 + } + ] + }, + { + "path": "busan/buk", + "name": "부산 북구", + "main": "2632000000", + "regions": [ + { + "code": "2632000000", + "name": "부산 북구", + "short_name": "북구", + "lat": 35.19418, + "lon": 128.99247 + } + ] + }, + { + "path": "busan/haeundae", + "name": "부산 해운대구", + "main": "2635000000", + "regions": [ + { + "code": "2635000000", + "name": "부산 해운대구", + "short_name": "해운대구", + "lat": 35.16002, + "lon": 129.16581 + } + ] + }, + { + "path": "busan/saha", + "name": "부산 사하구", + "main": "2638000000", + "regions": [ + { + "code": "2638000000", + "name": "부산 사하구", + "short_name": "사하구", + "lat": 35.10143, + "lon": 128.97704 + } + ] + }, + { + "path": "busan/geumjeong", + "name": "부산 금정구", + "main": "2641000000", + "regions": [ + { + "code": "2641000000", + "name": "부산 금정구", + "short_name": "금정구", + "lat": 35.24008, + "lon": 129.09432 + } + ] + }, + { + "path": "busan/gangseo", + "name": "부산 강서구", + "main": "2644000000", + "regions": [ + { + "code": "2644000000", + "name": "부산 강서구", + "short_name": "강서구", + "lat": 35.20916, + "lon": 128.98291 + } + ] + }, + { + "path": "busan/yeonje", + "name": "부산 연제구", + "main": "2647000000", + "regions": [ + { + "code": "2647000000", + "name": "부산 연제구", + "short_name": "연제구", + "lat": 35.17319, + "lon": 129.08208 + } + ] + }, + { + "path": "busan/suyeong", + "name": "부산 수영구", + "main": "2650000000", + "regions": [ + { + "code": "2650000000", + "name": "부산 수영구", + "short_name": "수영구", + "lat": 35.14247, + "lon": 129.11538 + } + ] + }, + { + "path": "busan/sasang", + "name": "부산 사상구", + "main": "2653000000", + "regions": [ + { + "code": "2653000000", + "name": "부산 사상구", + "short_name": "사상구", + "lat": 35.14947, + "lon": 128.99333 + } + ] + }, + { + "path": "busan/gijang", + "name": "부산 기장군", + "main": "2671000000", + "regions": [ + { + "code": "2671000000", + "name": "부산 기장군", + "short_name": "기장군", + "lat": 35.24135, + "lon": 129.22448 + } + ] + }, + { + "path": "daegu/jung", + "name": "대구 중구", + "main": "2711000000", + "regions": [ + { + "code": "2711000000", + "name": "대구 중구", + "short_name": "중구", + "lat": 35.86629, + "lon": 128.6084 + } + ] + }, + { + "path": "daegu/dong", + "name": "대구 동구", + "main": "2714000000", + "regions": [ + { + "code": "2714000000", + "name": "대구 동구", + "short_name": "동구", + "lat": 35.88362, + "lon": 128.63771 + } + ] + }, + { + "path": "daegu/seo", + "name": "대구 서구", + "main": "2717000000", + "regions": [ + { + "code": "2717000000", + "name": "대구 서구", + "short_name": "서구", + "lat": 35.86879, + "lon": 128.56141 + } + ] + }, + { + "path": "daegu/nam", + "name": "대구 남구", + "main": "2720000000", + "regions": [ + { + "code": "2720000000", + "name": "대구 남구", + "short_name": "남구", + "lat": 35.84298, + "lon": 128.5998 + } + ] + }, + { + "path": "daegu/buk", + "name": "대구 북구", + "main": "2723000000", + "regions": [ + { + "code": "2723000000", + "name": "대구 북구", + "short_name": "북구", + "lat": 35.8827, + "lon": 128.58502 + } + ] + }, + { + "path": "daegu/suseong", + "name": "대구 수성구", + "main": "2726000000", + "regions": [ + { + "code": "2726000000", + "name": "대구 수성구", + "short_name": "수성구", + "lat": 35.85521, + "lon": 128.63287 + } + ] + }, + { + "path": "daegu/dalseo", + "name": "대구 달서구", + "main": "2729000000", + "regions": [ + { + "code": "2729000000", + "name": "대구 달서구", + "short_name": "달서구", + "lat": 35.82693, + "lon": 128.53506 + } + ] + }, + { + "path": "daegu/dalseong", + "name": "대구 달성군", + "main": "2771000000", + "regions": [ + { + "code": "2771000000", + "name": "대구 달성군", + "short_name": "달성군", + "lat": 35.77168, + "lon": 128.43327 + } + ] + }, + { + "path": "daegu/gunwi", + "name": "대구 군위군", + "main": "2772000000", + "regions": [ + { + "code": "2772000000", + "name": "대구 군위군", + "short_name": "군위군", + "lat": 36.24, + "lon": 128.57508 + } + ] + }, + { + "path": "incheon/jemulpo", + "name": "인천 제물포구", + "main": "2812500000", + "regions": [ + { + "code": "2812500000", + "name": "인천 제물포구", + "short_name": "제물포구", + "lat": 37.47093, + "lon": 126.62357 + } + ] + }, + { + "path": "incheon/yeongjong", + "name": "인천 영종구", + "main": "2815500000", + "regions": [ + { + "code": "2815500000", + "name": "인천 영종구", + "short_name": "영종구", + "lat": 37.48977, + "lon": 126.55996 + } + ] + }, + { + "path": "incheon/michuhol", + "name": "인천 미추홀구", + "main": "2817700000", + "regions": [ + { + "code": "2817700000", + "name": "인천 미추홀구", + "short_name": "미추홀구", + "lat": 37.46068, + "lon": 126.65269 + } + ] + }, + { + "path": "incheon/yeonsu", + "name": "인천 연수구", + "main": "2818500000", + "regions": [ + { + "code": "2818500000", + "name": "인천 연수구", + "short_name": "연수구", + "lat": 37.40712, + "lon": 126.68044 + } + ] + }, + { + "path": "incheon/namdong", + "name": "인천 남동구", + "main": "2820000000", + "regions": [ + { + "code": "2820000000", + "name": "인천 남동구", + "short_name": "남동구", + "lat": 37.44452, + "lon": 126.7338 + } + ] + }, + { + "path": "incheon/bupyeong", + "name": "인천 부평구", + "main": "2823700000", + "regions": [ + { + "code": "2823700000", + "name": "인천 부평구", + "short_name": "부평구", + "lat": 37.50427, + "lon": 126.7241 + } + ] + }, + { + "path": "incheon/gyeyang", + "name": "인천 계양구", + "main": "2824500000", + "regions": [ + { + "code": "2824500000", + "name": "인천 계양구", + "short_name": "계양구", + "lat": 37.53479, + "lon": 126.73975 + } + ] + }, + { + "path": "incheon/seohae", + "name": "인천 서해구", + "main": "2827500000", + "regions": [ + { + "code": "2827500000", + "name": "인천 서해구", + "short_name": "서해구", + "lat": 37.54269, + "lon": 126.6782 + } + ] + }, + { + "path": "incheon/geomdan", + "name": "인천 검단구", + "main": "2829000000", + "regions": [ + { + "code": "2829000000", + "name": "인천 검단구", + "short_name": "검단구", + "lat": 37.59153, + "lon": 126.68157 + } + ] + }, + { + "path": "incheon/ganghwa", + "name": "인천 강화군", + "main": "2871000000", + "regions": [ + { + "code": "2871000000", + "name": "인천 강화군", + "short_name": "강화군", + "lat": 37.74386, + "lon": 126.49 + } + ] + }, + { + "path": "incheon/ongjin", + "name": "인천 옹진군", + "main": "2872000000", + "regions": [ + { + "code": "2872000000", + "name": "인천 옹진군", + "short_name": "옹진군", + "lat": 37.44372, + "lon": 126.63889 + } + ] + }, + { + "path": "daejeon/dong", + "name": "대전 동구", + "main": "3011000000", + "regions": [ + { + "code": "3011000000", + "name": "대전 동구", + "short_name": "동구", + "lat": 36.32413, + "lon": 127.43485 + } + ] + }, + { + "path": "daejeon/jung", + "name": "대전 중구", + "main": "3014000000", + "regions": [ + { + "code": "3014000000", + "name": "대전 중구", + "short_name": "중구", + "lat": 36.32263, + "lon": 127.42311 + } + ] + }, + { + "path": "daejeon/seo", + "name": "대전 서구", + "main": "3017000000", + "regions": [ + { + "code": "3017000000", + "name": "대전 서구", + "short_name": "서구", + "lat": 36.35248, + "lon": 127.38577 + } + ] + }, + { + "path": "daejeon/yuseong", + "name": "대전 유성구", + "main": "3020000000", + "regions": [ + { + "code": "3020000000", + "name": "대전 유성구", + "short_name": "유성구", + "lat": 36.35937, + "lon": 127.35834 + } + ] + }, + { + "path": "daejeon/daedeok", + "name": "대전 대덕구", + "main": "3023000000", + "regions": [ + { + "code": "3023000000", + "name": "대전 대덕구", + "short_name": "대덕구", + "lat": 36.34379, + "lon": 127.41769 + } + ] + }, + { + "path": "ulsan/jung", + "name": "울산 중구", + "main": "3111000000", + "regions": [ + { + "code": "3111000000", + "name": "울산 중구", + "short_name": "중구", + "lat": 35.56634, + "lon": 129.33488 + } + ] + }, + { + "path": "ulsan/nam", + "name": "울산 남구", + "main": "3114000000", + "regions": [ + { + "code": "3114000000", + "name": "울산 남구", + "short_name": "남구", + "lat": 35.54076, + "lon": 129.33239 + } + ] + }, + { + "path": "ulsan/dong", + "name": "울산 동구", + "main": "3117000000", + "regions": [ + { + "code": "3117000000", + "name": "울산 동구", + "short_name": "동구", + "lat": 35.50189, + "lon": 129.41895 + } + ] + }, + { + "path": "ulsan/buk", + "name": "울산 북구", + "main": "3120000000", + "regions": [ + { + "code": "3120000000", + "name": "울산 북구", + "short_name": "북구", + "lat": 35.57969, + "lon": 129.36354 + } + ] + }, + { + "path": "ulsan/ulju", + "name": "울산 울주군", + "main": "3171000000", + "regions": [ + { + "code": "3171000000", + "name": "울산 울주군", + "short_name": "울주군", + "lat": 35.53074, + "lon": 129.29716 + } + ] + }, + { + "path": "sejong/sejong", + "name": "세종시", + "main": "3611000000", + "regions": [ + { + "code": "3611000000", + "name": "세종 세종특별자치시", + "short_name": "세종특별자치시", + "lat": 36.48001, + "lon": 127.28907 + } + ] + }, + { + "path": "gyeonggi/suwon", + "name": "경기 수원시", + "main": "4111500000", + "regions": [ + { + "code": "4111100000", + "name": "경기 수원시 장안구", + "short_name": "수원시 장안구", + "lat": 37.30101, + "lon": 127.01222 + }, + { + "code": "4111300000", + "name": "경기 수원시 권선구", + "short_name": "수원시 권선구", + "lat": 37.25473, + "lon": 126.97407 + }, + { + "code": "4111500000", + "name": "경기 수원시 팔달구", + "short_name": "수원시 팔달구", + "lat": 37.2831, + "lon": 127.03783 + }, + { + "code": "4111700000", + "name": "경기 수원시 영통구", + "short_name": "수원시 영통구", + "lat": 37.25631, + "lon": 127.04863 + } + ] + }, + { + "path": "gyeonggi/seongnam", + "name": "경기 성남시", + "main": "4113300000", + "regions": [ + { + "code": "4113100000", + "name": "경기 성남시 수정구", + "short_name": "성남시 수정구", + "lat": 37.44749, + "lon": 127.14772 + }, + { + "code": "4113300000", + "name": "경기 성남시 중원구", + "short_name": "성남시 중원구", + "lat": 37.42767, + "lon": 127.13942 + }, + { + "code": "4113500000", + "name": "경기 성남시 분당구", + "short_name": "성남시 분당구", + "lat": 37.37997, + "lon": 127.12102 + } + ] + }, + { + "path": "gyeonggi/uijeongbu", + "name": "경기 의정부시", + "main": "4115000000", + "regions": [ + { + "code": "4115000000", + "name": "경기 의정부시", + "short_name": "의정부시", + "lat": 37.73529, + "lon": 127.03584 + } + ] + }, + { + "path": "gyeonggi/anyang", + "name": "경기 안양시", + "main": "4117300000", + "regions": [ + { + "code": "4117100000", + "name": "경기 안양시 만안구", + "short_name": "안양시 만안구", + "lat": 37.38378, + "lon": 126.9345 + }, + { + "code": "4117300000", + "name": "경기 안양시 동안구", + "short_name": "안양시 동안구", + "lat": 37.3897, + "lon": 126.95336 + } + ] + }, + { + "path": "gyeonggi/bucheon", + "name": "경기 부천시", + "main": "4119200000", + "regions": [ + { + "code": "4119200000", + "name": "경기 부천시 원미구", + "short_name": "부천시 원미구", + "lat": 37.49659, + "lon": 126.787 + }, + { + "code": "4119400000", + "name": "경기 부천시 소사구", + "short_name": "부천시 소사구", + "lat": 37.48004, + "lon": 126.79994 + }, + { + "code": "4119600000", + "name": "경기 부천시 오정구", + "short_name": "부천시 오정구", + "lat": 37.52835, + "lon": 126.79581 + } + ] + }, + { + "path": "gyeonggi/gwangmyeong", + "name": "경기 광명시", + "main": "4121000000", + "regions": [ + { + "code": "4121000000", + "name": "경기 광명시", + "short_name": "광명시", + "lat": 37.47575, + "lon": 126.86671 + } + ] + }, + { + "path": "gyeonggi/pyeongtaek", + "name": "경기 평택시", + "main": "4122000000", + "regions": [ + { + "code": "4122000000", + "name": "경기 평택시", + "short_name": "평택시", + "lat": 36.98944, + "lon": 127.11466 + } + ] + }, + { + "path": "gyeonggi/dongducheon", + "name": "경기 동두천시", + "main": "4125000000", + "regions": [ + { + "code": "4125000000", + "name": "경기 동두천시", + "short_name": "동두천시", + "lat": 37.90092, + "lon": 127.06265 + } + ] + }, + { + "path": "gyeonggi/ansan", + "name": "경기 안산시", + "main": "4127300000", + "regions": [ + { + "code": "4127100000", + "name": "경기 안산시 상록구", + "short_name": "안산시 상록구", + "lat": 37.29852, + "lon": 126.84682 + }, + { + "code": "4127300000", + "name": "경기 안산시 단원구", + "short_name": "안산시 단원구", + "lat": 37.31673, + "lon": 126.81442 + } + ] + }, + { + "path": "gyeonggi/goyang", + "name": "경기 고양시", + "main": "4128100000", + "regions": [ + { + "code": "4128100000", + "name": "경기 고양시 덕양구", + "short_name": "고양시 덕양구", + "lat": 37.63458, + "lon": 126.8342 + }, + { + "code": "4128500000", + "name": "경기 고양시 일산동구", + "short_name": "고양시 일산동구", + "lat": 37.65591, + "lon": 126.77706 + }, + { + "code": "4128700000", + "name": "경기 고양시 일산서구", + "short_name": "고양시 일산서구", + "lat": 37.67249, + "lon": 126.75278 + } + ] + }, + { + "path": "gyeonggi/gwacheon", + "name": "경기 과천시", + "main": "4129000000", + "regions": [ + { + "code": "4129000000", + "name": "경기 과천시", + "short_name": "과천시", + "lat": 37.42637, + "lon": 126.9898 + } + ] + }, + { + "path": "gyeonggi/guri", + "name": "경기 구리시", + "main": "4131000000", + "regions": [ + { + "code": "4131000000", + "name": "경기 구리시", + "short_name": "구리시", + "lat": 37.59163, + "lon": 127.13186 + } + ] + }, + { + "path": "gyeonggi/namyangju", + "name": "경기 남양주시", + "main": "4136000000", + "regions": [ + { + "code": "4136000000", + "name": "경기 남양주시", + "short_name": "남양주시", + "lat": 37.63318, + "lon": 127.21863 + } + ] + }, + { + "path": "gyeonggi/osan", + "name": "경기 오산시", + "main": "4137000000", + "regions": [ + { + "code": "4137000000", + "name": "경기 오산시", + "short_name": "오산시", + "lat": 37.14691, + "lon": 127.07964 + } + ] + }, + { + "path": "gyeonggi/siheung", + "name": "경기 시흥시", + "main": "4139000000", + "regions": [ + { + "code": "4139000000", + "name": "경기 시흥시", + "short_name": "시흥시", + "lat": 37.37732, + "lon": 126.80508 + } + ] + }, + { + "path": "gyeonggi/gunpo", + "name": "경기 군포시", + "main": "4141000000", + "regions": [ + { + "code": "4141000000", + "name": "경기 군포시", + "short_name": "군포시", + "lat": 37.35866, + "lon": 126.9375 + } + ] + }, + { + "path": "gyeonggi/uiwang", + "name": "경기 의왕시", + "main": "4143000000", + "regions": [ + { + "code": "4143000000", + "name": "경기 의왕시", + "short_name": "의왕시", + "lat": 37.34195, + "lon": 126.97039 + } + ] + }, + { + "path": "gyeonggi/hanam", + "name": "경기 하남시", + "main": "4145000000", + "regions": [ + { + "code": "4145000000", + "name": "경기 하남시", + "short_name": "하남시", + "lat": 37.5365, + "lon": 127.217 + } + ] + }, + { + "path": "gyeonggi/yongin", + "name": "경기 용인시", + "main": "4146100000", + "regions": [ + { + "code": "4146100000", + "name": "경기 용인시 처인구", + "short_name": "용인시 처인구", + "lat": 37.23148, + "lon": 127.20384 + }, + { + "code": "4146300000", + "name": "경기 용인시 기흥구", + "short_name": "용인시 기흥구", + "lat": 37.2776, + "lon": 127.11679 + }, + { + "code": "4146500000", + "name": "경기 용인시 수지구", + "short_name": "용인시 수지구", + "lat": 37.31939, + "lon": 127.1001 + } + ] + }, + { + "path": "gyeonggi/paju", + "name": "경기 파주시", + "main": "4148000000", + "regions": [ + { + "code": "4148000000", + "name": "경기 파주시", + "short_name": "파주시", + "lat": 37.75708, + "lon": 126.78195 + } + ] + }, + { + "path": "gyeonggi/icheon", + "name": "경기 이천시", + "main": "4150000000", + "regions": [ + { + "code": "4150000000", + "name": "경기 이천시", + "short_name": "이천시", + "lat": 37.27544, + "lon": 127.44322 + } + ] + }, + { + "path": "gyeonggi/anseong", + "name": "경기 안성시", + "main": "4155000000", + "regions": [ + { + "code": "4155000000", + "name": "경기 안성시", + "short_name": "안성시", + "lat": 37.00518, + "lon": 127.28184 + } + ] + }, + { + "path": "gyeonggi/gimpo", + "name": "경기 김포시", + "main": "4157000000", + "regions": [ + { + "code": "4157000000", + "name": "경기 김포시", + "short_name": "김포시", + "lat": 37.61246, + "lon": 126.71778 + } + ] + }, + { + "path": "gyeonggi/hwaseong", + "name": "경기 화성시", + "main": "4159100000", + "regions": [ + { + "code": "4159100000", + "name": "경기 화성시 만세구", + "short_name": "화성시 만세구", + "lat": 37.1377, + "lon": 126.92566 + }, + { + "code": "4159300000", + "name": "경기 화성시 효행구", + "short_name": "화성시 효행구", + "lat": 37.20918, + "lon": 126.95915 + }, + { + "code": "4159500000", + "name": "경기 화성시 병점구", + "short_name": "화성시 병점구", + "lat": 37.20875, + "lon": 127.0359 + }, + { + "code": "4159700000", + "name": "경기 화성시 동탄구", + "short_name": "화성시 동탄구", + "lat": 37.19724, + "lon": 127.09687 + } + ] + }, + { + "path": "gyeonggi/gwangju", + "name": "경기 광주시", + "main": "4161000000", + "regions": [ + { + "code": "4161000000", + "name": "경기 광주시", + "short_name": "광주시", + "lat": 37.41451, + "lon": 127.25779 + } + ] + }, + { + "path": "gyeonggi/yangju", + "name": "경기 양주시", + "main": "4163000000", + "regions": [ + { + "code": "4163000000", + "name": "경기 양주시", + "short_name": "양주시", + "lat": 37.78245, + "lon": 127.04782 + } + ] + }, + { + "path": "gyeonggi/pocheon", + "name": "경기 포천시", + "main": "4165000000", + "regions": [ + { + "code": "4165000000", + "name": "경기 포천시", + "short_name": "포천시", + "lat": 37.89216, + "lon": 127.20242 + } + ] + }, + { + "path": "gyeonggi/yeoju", + "name": "경기 여주시", + "main": "4167000000", + "regions": [ + { + "code": "4167000000", + "name": "경기 여주시", + "short_name": "여주시", + "lat": 37.29536, + "lon": 127.63962 + } + ] + }, + { + "path": "gyeonggi/yeoncheon", + "name": "경기 연천군", + "main": "4180000000", + "regions": [ + { + "code": "4180000000", + "name": "경기 연천군", + "short_name": "연천군", + "lat": 38.09336, + "lon": 127.07707 + } + ] + }, + { + "path": "gyeonggi/gapyeong", + "name": "경기 가평군", + "main": "4182000000", + "regions": [ + { + "code": "4182000000", + "name": "경기 가평군", + "short_name": "가평군", + "lat": 37.82883, + "lon": 127.51178 + } + ] + }, + { + "path": "gyeonggi/yangpyeong", + "name": "경기 양평군", + "main": "4183000000", + "regions": [ + { + "code": "4183000000", + "name": "경기 양평군", + "short_name": "양평군", + "lat": 37.48894, + "lon": 127.48989 + } + ] + }, + { + "path": "chungbuk/cheongju", + "name": "충북 청주시", + "main": "4311100000", + "regions": [ + { + "code": "4311100000", + "name": "충북 청주시 상당구", + "short_name": "청주시 상당구", + "lat": 36.584, + "lon": 127.51173 + }, + { + "code": "4311200000", + "name": "충북 청주시 서원구", + "short_name": "청주시 서원구", + "lat": 36.63726, + "lon": 127.48329 + }, + { + "code": "4311300000", + "name": "충북 청주시 흥덕구", + "short_name": "청주시 흥덕구", + "lat": 36.6182, + "lon": 127.35942 + }, + { + "code": "4311400000", + "name": "충북 청주시 청원구", + "short_name": "청주시 청원구", + "lat": 36.64431, + "lon": 127.48766 + } + ] + }, + { + "path": "chungbuk/chungju", + "name": "충북 충주시", + "main": "4313000000", + "regions": [ + { + "code": "4313000000", + "name": "충북 충주시", + "short_name": "충주시", + "lat": 36.98818, + "lon": 127.92814 + } + ] + }, + { + "path": "chungbuk/jecheon", + "name": "충북 제천시", + "main": "4315000000", + "regions": [ + { + "code": "4315000000", + "name": "충북 제천시", + "short_name": "제천시", + "lat": 37.12977, + "lon": 128.19315 + } + ] + }, + { + "path": "chungbuk/boeun", + "name": "충북 보은군", + "main": "4372000000", + "regions": [ + { + "code": "4372000000", + "name": "충북 보은군", + "short_name": "보은군", + "lat": 36.48653, + "lon": 127.73161 + } + ] + }, + { + "path": "chungbuk/okcheon", + "name": "충북 옥천군", + "main": "4373000000", + "regions": [ + { + "code": "4373000000", + "name": "충북 옥천군", + "short_name": "옥천군", + "lat": 36.30355, + "lon": 127.57363 + } + ] + }, + { + "path": "chungbuk/yeongdong", + "name": "충북 영동군", + "main": "4374000000", + "regions": [ + { + "code": "4374000000", + "name": "충북 영동군", + "short_name": "영동군", + "lat": 36.17206, + "lon": 127.78561 + } + ] + }, + { + "path": "chungbuk/jeungpyeong", + "name": "충북 증평군", + "main": "4374500000", + "regions": [ + { + "code": "4374500000", + "name": "충북 증평군", + "short_name": "증평군", + "lat": 36.78218, + "lon": 127.58329 + } + ] + }, + { + "path": "chungbuk/jincheon", + "name": "충북 진천군", + "main": "4375000000", + "regions": [ + { + "code": "4375000000", + "name": "충북 진천군", + "short_name": "진천군", + "lat": 36.85254, + "lon": 127.43764 + } + ] + }, + { + "path": "chungbuk/goesan", + "name": "충북 괴산군", + "main": "4376000000", + "regions": [ + { + "code": "4376000000", + "name": "충북 괴산군", + "short_name": "괴산군", + "lat": 36.81243, + "lon": 127.78883 + } + ] + }, + { + "path": "chungbuk/eumseong", + "name": "충북 음성군", + "main": "4377000000", + "regions": [ + { + "code": "4377000000", + "name": "충북 음성군", + "short_name": "음성군", + "lat": 36.93741, + "lon": 127.69262 + } + ] + }, + { + "path": "chungbuk/danyang", + "name": "충북 단양군", + "main": "4380000000", + "regions": [ + { + "code": "4380000000", + "name": "충북 단양군", + "short_name": "단양군", + "lat": 36.98178, + "lon": 128.36784 + } + ] + }, + { + "path": "chungnam/cheonan", + "name": "충남 천안시", + "main": "4413300000", + "regions": [ + { + "code": "4413100000", + "name": "충남 천안시 동남구", + "short_name": "천안시 동남구", + "lat": 36.80412, + "lon": 127.15247 + }, + { + "code": "4413300000", + "name": "충남 천안시 서북구", + "short_name": "천안시 서북구", + "lat": 36.87556, + "lon": 127.1572 + } + ] + }, + { + "path": "chungnam/gongju", + "name": "충남 공주시", + "main": "4415000000", + "regions": [ + { + "code": "4415000000", + "name": "충남 공주시", + "short_name": "공주시", + "lat": 36.44361, + "lon": 127.12112 + } + ] + }, + { + "path": "chungnam/boryeong", + "name": "충남 보령시", + "main": "4418000000", + "regions": [ + { + "code": "4418000000", + "name": "충남 보령시", + "short_name": "보령시", + "lat": 36.33058, + "lon": 126.61489 + } + ] + }, + { + "path": "chungnam/asan", + "name": "충남 아산시", + "main": "4420000000", + "regions": [ + { + "code": "4420000000", + "name": "충남 아산시", + "short_name": "아산시", + "lat": 36.78711, + "lon": 127.00464 + } + ] + }, + { + "path": "chungnam/seosan", + "name": "충남 서산시", + "main": "4421000000", + "regions": [ + { + "code": "4421000000", + "name": "충남 서산시", + "short_name": "서산시", + "lat": 36.7821, + "lon": 126.45216 + } + ] + }, + { + "path": "chungnam/nonsan", + "name": "충남 논산시", + "main": "4423000000", + "regions": [ + { + "code": "4423000000", + "name": "충남 논산시", + "short_name": "논산시", + "lat": 36.1842, + "lon": 127.10091 + } + ] + }, + { + "path": "chungnam/gyeryong", + "name": "충남 계룡시", + "main": "4425000000", + "regions": [ + { + "code": "4425000000", + "name": "충남 계룡시", + "short_name": "계룡시", + "lat": 36.27184, + "lon": 127.25093 + } + ] + }, + { + "path": "chungnam/dangjin", + "name": "충남 당진시", + "main": "4427000000", + "regions": [ + { + "code": "4427000000", + "name": "충남 당진시", + "short_name": "당진시", + "lat": 36.89075, + "lon": 126.63025 + } + ] + }, + { + "path": "chungnam/geumsan", + "name": "충남 금산군", + "main": "4471000000", + "regions": [ + { + "code": "4471000000", + "name": "충남 금산군", + "short_name": "금산군", + "lat": 36.10587, + "lon": 127.49031 + } + ] + }, + { + "path": "chungnam/buyeo", + "name": "충남 부여군", + "main": "4476000000", + "regions": [ + { + "code": "4476000000", + "name": "충남 부여군", + "short_name": "부여군", + "lat": 36.27282, + "lon": 126.91186 + } + ] + }, + { + "path": "chungnam/seocheon", + "name": "충남 서천군", + "main": "4477000000", + "regions": [ + { + "code": "4477000000", + "name": "충남 서천군", + "short_name": "서천군", + "lat": 36.07741, + "lon": 126.69389 + } + ] + }, + { + "path": "chungnam/cheongyang", + "name": "충남 청양군", + "main": "4479000000", + "regions": [ + { + "code": "4479000000", + "name": "충남 청양군", + "short_name": "청양군", + "lat": 36.45627, + "lon": 126.80426 + } + ] + }, + { + "path": "chungnam/hongseong", + "name": "충남 홍성군", + "main": "4480000000", + "regions": [ + { + "code": "4480000000", + "name": "충남 홍성군", + "short_name": "홍성군", + "lat": 36.59836, + "lon": 126.66291 + } + ] + }, + { + "path": "chungnam/yesan", + "name": "충남 예산군", + "main": "4481000000", + "regions": [ + { + "code": "4481000000", + "name": "충남 예산군", + "short_name": "예산군", + "lat": 36.67981, + "lon": 126.85087 + } + ] + }, + { + "path": "chungnam/taean", + "name": "충남 태안군", + "main": "4482500000", + "regions": [ + { + "code": "4482500000", + "name": "충남 태안군", + "short_name": "태안군", + "lat": 36.74267, + "lon": 126.29998 + } + ] + }, + { + "path": "gyeongbuk/pohang", + "name": "경북 포항시", + "main": "4711100000", + "regions": [ + { + "code": "4711100000", + "name": "경북 포항시 남구", + "short_name": "포항시 남구", + "lat": 36.00569, + "lon": 129.36167 + }, + { + "code": "4711300000", + "name": "경북 포항시 북구", + "short_name": "포항시 북구", + "lat": 36.03885, + "lon": 129.36791 + } + ] + }, + { + "path": "gyeongbuk/gyeongju", + "name": "경북 경주시", + "main": "4713000000", + "regions": [ + { + "code": "4713000000", + "name": "경북 경주시", + "short_name": "경주시", + "lat": 35.85317, + "lon": 129.22702 + } + ] + }, + { + "path": "gyeongbuk/gimcheon", + "name": "경북 김천시", + "main": "4715000000", + "regions": [ + { + "code": "4715000000", + "name": "경북 김천시", + "short_name": "김천시", + "lat": 36.1369, + "lon": 128.1158 + } + ] + }, + { + "path": "gyeongbuk/andong", + "name": "경북 안동시", + "main": "4717000000", + "regions": [ + { + "code": "4717000000", + "name": "경북 안동시", + "short_name": "안동시", + "lat": 36.56546, + "lon": 128.73162 + } + ] + }, + { + "path": "gyeongbuk/gumi", + "name": "경북 구미시", + "main": "4719000000", + "regions": [ + { + "code": "4719000000", + "name": "경북 구미시", + "short_name": "구미시", + "lat": 36.11655, + "lon": 128.34678 + } + ] + }, + { + "path": "gyeongbuk/yeongju", + "name": "경북 영주시", + "main": "4721000000", + "regions": [ + { + "code": "4721000000", + "name": "경북 영주시", + "short_name": "영주시", + "lat": 36.80294, + "lon": 128.62634 + } + ] + }, + { + "path": "gyeongbuk/yeongcheon", + "name": "경북 영천시", + "main": "4723000000", + "regions": [ + { + "code": "4723000000", + "name": "경북 영천시", + "short_name": "영천시", + "lat": 35.97005, + "lon": 128.94078 + } + ] + }, + { + "path": "gyeongbuk/sangju", + "name": "경북 상주시", + "main": "4725000000", + "regions": [ + { + "code": "4725000000", + "name": "경북 상주시", + "short_name": "상주시", + "lat": 36.40797, + "lon": 128.16126 + } + ] + }, + { + "path": "gyeongbuk/mungyeong", + "name": "경북 문경시", + "main": "4728000000", + "regions": [ + { + "code": "4728000000", + "name": "경북 문경시", + "short_name": "문경시", + "lat": 36.58363, + "lon": 128.18902 + } + ] + }, + { + "path": "gyeongbuk/gyeongsan", + "name": "경북 경산시", + "main": "4729000000", + "regions": [ + { + "code": "4729000000", + "name": "경북 경산시", + "short_name": "경산시", + "lat": 35.82209, + "lon": 128.74346 + } + ] + }, + { + "path": "gyeongbuk/uiseong", + "name": "경북 의성군", + "main": "4773000000", + "regions": [ + { + "code": "4773000000", + "name": "경북 의성군", + "short_name": "의성군", + "lat": 36.34976, + "lon": 128.69936 + } + ] + }, + { + "path": "gyeongbuk/cheongsong", + "name": "경북 청송군", + "main": "4775000000", + "regions": [ + { + "code": "4775000000", + "name": "경북 청송군", + "short_name": "청송군", + "lat": 36.43329, + "lon": 129.0594 + } + ] + }, + { + "path": "gyeongbuk/yeongyang", + "name": "경북 영양군", + "main": "4776000000", + "regions": [ + { + "code": "4776000000", + "name": "경북 영양군", + "short_name": "영양군", + "lat": 36.66427, + "lon": 129.11462 + } + ] + }, + { + "path": "gyeongbuk/yeongdeok", + "name": "경북 영덕군", + "main": "4777000000", + "regions": [ + { + "code": "4777000000", + "name": "경북 영덕군", + "short_name": "영덕군", + "lat": 36.4121, + "lon": 129.36836 + } + ] + }, + { + "path": "gyeongbuk/cheongdo", + "name": "경북 청도군", + "main": "4782000000", + "regions": [ + { + "code": "4782000000", + "name": "경북 청도군", + "short_name": "청도군", + "lat": 35.64431, + "lon": 128.7362 + } + ] + }, + { + "path": "gyeongbuk/goryeong", + "name": "경북 고령군", + "main": "4783000000", + "regions": [ + { + "code": "4783000000", + "name": "경북 고령군", + "short_name": "고령군", + "lat": 35.72299, + "lon": 128.26502 + } + ] + }, + { + "path": "gyeongbuk/seongju", + "name": "경북 성주군", + "main": "4784000000", + "regions": [ + { + "code": "4784000000", + "name": "경북 성주군", + "short_name": "성주군", + "lat": 35.91915, + "lon": 128.28299 + } + ] + }, + { + "path": "gyeongbuk/chilgok", + "name": "경북 칠곡군", + "main": "4785000000", + "regions": [ + { + "code": "4785000000", + "name": "경북 칠곡군", + "short_name": "칠곡군", + "lat": 35.99255, + "lon": 128.4038 + } + ] + }, + { + "path": "gyeongbuk/yecheon", + "name": "경북 예천군", + "main": "4790000000", + "regions": [ + { + "code": "4790000000", + "name": "경북 예천군", + "short_name": "예천군", + "lat": 36.65495, + "lon": 128.45502 + } + ] + }, + { + "path": "gyeongbuk/bonghwa", + "name": "경북 봉화군", + "main": "4792000000", + "regions": [ + { + "code": "4792000000", + "name": "경북 봉화군", + "short_name": "봉화군", + "lat": 36.89026, + "lon": 128.73487 + } + ] + }, + { + "path": "gyeongbuk/uljin", + "name": "경북 울진군", + "main": "4793000000", + "regions": [ + { + "code": "4793000000", + "name": "경북 울진군", + "short_name": "울진군", + "lat": 36.99019, + "lon": 129.40279 + } + ] + }, + { + "path": "gyeongbuk/ulleung", + "name": "경북 울릉군", + "main": "4794000000", + "regions": [ + { + "code": "4794000000", + "name": "경북 울릉군", + "short_name": "울릉군", + "lat": 37.48058, + "lon": 130.90379 + } + ] + }, + { + "path": "gyeongnam/changwon", + "name": "경남 창원시", + "main": "4812100000", + "regions": [ + { + "code": "4812100000", + "name": "경남 창원시 의창구", + "short_name": "창원시 의창구", + "lat": 35.254, + "lon": 128.64015 + }, + { + "code": "4812300000", + "name": "경남 창원시 성산구", + "short_name": "창원시 성산구", + "lat": 35.19838, + "lon": 128.70294 + }, + { + "code": "4812500000", + "name": "경남 창원시 마산합포구", + "short_name": "창원시 마산합포구", + "lat": 35.19687, + "lon": 128.56786 + }, + { + "code": "4812700000", + "name": "경남 창원시 마산회원구", + "short_name": "창원시 마산회원구", + "lat": 35.22093, + "lon": 128.57971 + }, + { + "code": "4812900000", + "name": "경남 창원시 진해구", + "short_name": "창원시 진해구", + "lat": 35.13306, + "lon": 128.71008 + } + ] + }, + { + "path": "gyeongnam/jinju", + "name": "경남 진주시", + "main": "4817000000", + "regions": [ + { + "code": "4817000000", + "name": "경남 진주시", + "short_name": "진주시", + "lat": 35.17703, + "lon": 128.11 + } + ] + }, + { + "path": "gyeongnam/tongyeong", + "name": "경남 통영시", + "main": "4822000000", + "regions": [ + { + "code": "4822000000", + "name": "경남 통영시", + "short_name": "통영시", + "lat": 34.85126, + "lon": 128.43528 + } + ] + }, + { + "path": "gyeongnam/sacheon", + "name": "경남 사천시", + "main": "4824000000", + "regions": [ + { + "code": "4824000000", + "name": "경남 사천시", + "short_name": "사천시", + "lat": 35.00028, + "lon": 128.06678 + } + ] + }, + { + "path": "gyeongnam/gimhae", + "name": "경남 김해시", + "main": "4825000000", + "regions": [ + { + "code": "4825000000", + "name": "경남 김해시", + "short_name": "김해시", + "lat": 35.22551, + "lon": 128.89167 + } + ] + }, + { + "path": "gyeongnam/miryang", + "name": "경남 밀양시", + "main": "4827000000", + "regions": [ + { + "code": "4827000000", + "name": "경남 밀양시", + "short_name": "밀양시", + "lat": 35.50078, + "lon": 128.74894 + } + ] + }, + { + "path": "gyeongnam/geoje", + "name": "경남 거제시", + "main": "4831000000", + "regions": [ + { + "code": "4831000000", + "name": "경남 거제시", + "short_name": "거제시", + "lat": 34.87736, + "lon": 128.62336 + } + ] + }, + { + "path": "gyeongnam/yangsan", + "name": "경남 양산시", + "main": "4833000000", + "regions": [ + { + "code": "4833000000", + "name": "경남 양산시", + "short_name": "양산시", + "lat": 35.33193, + "lon": 129.03941 + } + ] + }, + { + "path": "gyeongnam/uiryeong", + "name": "경남 의령군", + "main": "4872000000", + "regions": [ + { + "code": "4872000000", + "name": "경남 의령군", + "short_name": "의령군", + "lat": 35.31912, + "lon": 128.26382 + } + ] + }, + { + "path": "gyeongnam/haman", + "name": "경남 함안군", + "main": "4873000000", + "regions": [ + { + "code": "4873000000", + "name": "경남 함안군", + "short_name": "함안군", + "lat": 35.26941, + "lon": 128.40871 + } + ] + }, + { + "path": "gyeongnam/changnyeong", + "name": "경남 창녕군", + "main": "4874000000", + "regions": [ + { + "code": "4874000000", + "name": "경남 창녕군", + "short_name": "창녕군", + "lat": 35.54154, + "lon": 128.49453 + } + ] + }, + { + "path": "gyeongnam/goseong", + "name": "경남 고성군", + "main": "4882000000", + "regions": [ + { + "code": "4882000000", + "name": "경남 고성군", + "short_name": "고성군", + "lat": 34.9699, + "lon": 128.32454 + } + ] + }, + { + "path": "gyeongnam/namhae", + "name": "경남 남해군", + "main": "4884000000", + "regions": [ + { + "code": "4884000000", + "name": "경남 남해군", + "short_name": "남해군", + "lat": 34.83456, + "lon": 127.89447 + } + ] + }, + { + "path": "gyeongnam/hadong", + "name": "경남 하동군", + "main": "4885000000", + "regions": [ + { + "code": "4885000000", + "name": "경남 하동군", + "short_name": "하동군", + "lat": 35.0642, + "lon": 127.75343 + } + ] + }, + { + "path": "gyeongnam/sancheong", + "name": "경남 산청군", + "main": "4886000000", + "regions": [ + { + "code": "4886000000", + "name": "경남 산청군", + "short_name": "산청군", + "lat": 35.41249, + "lon": 127.87562 + } + ] + }, + { + "path": "gyeongnam/hamyang", + "name": "경남 함양군", + "main": "4887000000", + "regions": [ + { + "code": "4887000000", + "name": "경남 함양군", + "short_name": "함양군", + "lat": 35.51747, + "lon": 127.72742 + } + ] + }, + { + "path": "gyeongnam/geochang", + "name": "경남 거창군", + "main": "4888000000", + "regions": [ + { + "code": "4888000000", + "name": "경남 거창군", + "short_name": "거창군", + "lat": 35.68362, + "lon": 127.91166 + } + ] + }, + { + "path": "gyeongnam/hapcheon", + "name": "경남 합천군", + "main": "4889000000", + "regions": [ + { + "code": "4889000000", + "name": "경남 합천군", + "short_name": "합천군", + "lat": 35.56362, + "lon": 128.16793 + } + ] + }, + { + "path": "jeju/jeju", + "name": "제주 제주시", + "main": "5011000000", + "regions": [ + { + "code": "5011000000", + "name": "제주 제주시", + "short_name": "제주시", + "lat": 33.49631, + "lon": 126.53321 + } + ] + }, + { + "path": "jeju/seogwipo", + "name": "제주 서귀포시", + "main": "5013000000", + "regions": [ + { + "code": "5013000000", + "name": "제주 서귀포시", + "short_name": "서귀포시", + "lat": 33.25406, + "lon": 126.55955 + } + ] + }, + { + "path": "gangwon/chuncheon", + "name": "강원 춘천시", + "main": "5111000000", + "regions": [ + { + "code": "5111000000", + "name": "강원 춘천시", + "short_name": "춘천시", + "lat": 37.87854, + "lon": 127.73231 + } + ] + }, + { + "path": "gangwon/wonju", + "name": "강원 원주시", + "main": "5113000000", + "regions": [ + { + "code": "5113000000", + "name": "강원 원주시", + "short_name": "원주시", + "lat": 37.33908, + "lon": 127.92206 + } + ] + }, + { + "path": "gangwon/gangneung", + "name": "강원 강릉시", + "main": "5115000000", + "regions": [ + { + "code": "5115000000", + "name": "강원 강릉시", + "short_name": "강릉시", + "lat": 37.74914, + "lon": 128.8785 + } + ] + }, + { + "path": "gangwon/donghae", + "name": "강원 동해시", + "main": "5117000000", + "regions": [ + { + "code": "5117000000", + "name": "강원 동해시", + "short_name": "동해시", + "lat": 37.52193, + "lon": 129.11663 + } + ] + }, + { + "path": "gangwon/taebaek", + "name": "강원 태백시", + "main": "5119000000", + "regions": [ + { + "code": "5119000000", + "name": "강원 태백시", + "short_name": "태백시", + "lat": 37.16123, + "lon": 128.988 + } + ] + }, + { + "path": "gangwon/sokcho", + "name": "강원 속초시", + "main": "5121000000", + "regions": [ + { + "code": "5121000000", + "name": "강원 속초시", + "short_name": "속초시", + "lat": 38.20428, + "lon": 128.59417 + } + ] + }, + { + "path": "gangwon/samcheok", + "name": "강원 삼척시", + "main": "5123000000", + "regions": [ + { + "code": "5123000000", + "name": "강원 삼척시", + "short_name": "삼척시", + "lat": 37.44709, + "lon": 129.16749 + } + ] + }, + { + "path": "gangwon/hongcheon", + "name": "강원 홍천군", + "main": "5172000000", + "regions": [ + { + "code": "5172000000", + "name": "강원 홍천군", + "short_name": "홍천군", + "lat": 37.69442, + "lon": 127.89084 + } + ] + }, + { + "path": "gangwon/hoengseong", + "name": "강원 횡성군", + "main": "5173000000", + "regions": [ + { + "code": "5173000000", + "name": "강원 횡성군", + "short_name": "횡성군", + "lat": 37.48896, + "lon": 127.98722 + } + ] + }, + { + "path": "gangwon/yeongwol", + "name": "강원 영월군", + "main": "5175000000", + "regions": [ + { + "code": "5175000000", + "name": "강원 영월군", + "short_name": "영월군", + "lat": 37.18086, + "lon": 128.46402 + } + ] + }, + { + "path": "gangwon/pyeongchang", + "name": "강원 평창군", + "main": "5176000000", + "regions": [ + { + "code": "5176000000", + "name": "강원 평창군", + "short_name": "평창군", + "lat": 37.36792, + "lon": 128.39235 + } + ] + }, + { + "path": "gangwon/jeongseon", + "name": "강원 정선군", + "main": "5177000000", + "regions": [ + { + "code": "5177000000", + "name": "강원 정선군", + "short_name": "정선군", + "lat": 37.37781, + "lon": 128.66309 + } + ] + }, + { + "path": "gangwon/cheorwon", + "name": "강원 철원군", + "main": "5178000000", + "regions": [ + { + "code": "5178000000", + "name": "강원 철원군", + "short_name": "철원군", + "lat": 38.14406, + "lon": 127.31573 + } + ] + }, + { + "path": "gangwon/hwacheon", + "name": "강원 화천군", + "main": "5179000000", + "regions": [ + { + "code": "5179000000", + "name": "강원 화천군", + "short_name": "화천군", + "lat": 38.10341, + "lon": 127.71036 + } + ] + }, + { + "path": "gangwon/yanggu", + "name": "강원 양구군", + "main": "5180000000", + "regions": [ + { + "code": "5180000000", + "name": "강원 양구군", + "short_name": "양구군", + "lat": 38.10729, + "lon": 127.99224 + } + ] + }, + { + "path": "gangwon/inje", + "name": "강원 인제군", + "main": "5181000000", + "regions": [ + { + "code": "5181000000", + "name": "강원 인제군", + "short_name": "인제군", + "lat": 38.06697, + "lon": 128.1727 + } + ] + }, + { + "path": "gangwon/goseong", + "name": "강원 고성군", + "main": "5182000000", + "regions": [ + { + "code": "5182000000", + "name": "강원 고성군", + "short_name": "고성군", + "lat": 38.37796, + "lon": 128.47016 + } + ] + }, + { + "path": "gangwon/yangyang", + "name": "강원 양양군", + "main": "5183000000", + "regions": [ + { + "code": "5183000000", + "name": "강원 양양군", + "short_name": "양양군", + "lat": 38.07283, + "lon": 128.62136 + } + ] + }, + { + "path": "jeonbuk/jeonju", + "name": "전북 전주시", + "main": "5211100000", + "regions": [ + { + "code": "5211100000", + "name": "전북 전주시 완산구", + "short_name": "전주시 완산구", + "lat": 35.80919, + "lon": 127.12192 + }, + { + "code": "5211300000", + "name": "전북 전주시 덕진구", + "short_name": "전주시 덕진구", + "lat": 35.82639, + "lon": 127.13642 + } + ] + }, + { + "path": "jeonbuk/gunsan", + "name": "전북 군산시", + "main": "5213000000", + "regions": [ + { + "code": "5213000000", + "name": "전북 군산시", + "short_name": "군산시", + "lat": 35.96464, + "lon": 126.73884 + } + ] + }, + { + "path": "jeonbuk/iksan", + "name": "전북 익산시", + "main": "5214000000", + "regions": [ + { + "code": "5214000000", + "name": "전북 익산시", + "short_name": "익산시", + "lat": 35.94527, + "lon": 126.95985 + } + ] + }, + { + "path": "jeonbuk/jeongeup", + "name": "전북 정읍시", + "main": "5218000000", + "regions": [ + { + "code": "5218000000", + "name": "전북 정읍시", + "short_name": "정읍시", + "lat": 35.56687, + "lon": 126.85811 + } + ] + }, + { + "path": "jeonbuk/namwon", + "name": "전북 남원시", + "main": "5219000000", + "regions": [ + { + "code": "5219000000", + "name": "전북 남원시", + "short_name": "남원시", + "lat": 35.41326, + "lon": 127.3925 + } + ] + }, + { + "path": "jeonbuk/gimje", + "name": "전북 김제시", + "main": "5221000000", + "regions": [ + { + "code": "5221000000", + "name": "전북 김제시", + "short_name": "김제시", + "lat": 35.80057, + "lon": 126.88275 + } + ] + }, + { + "path": "jeonbuk/wanju", + "name": "전북 완주군", + "main": "5271000000", + "regions": [ + { + "code": "5271000000", + "name": "전북 완주군", + "short_name": "완주군", + "lat": 35.84297, + "lon": 127.1496 + } + ] + }, + { + "path": "jeonbuk/jinan", + "name": "전북 진안군", + "main": "5272000000", + "regions": [ + { + "code": "5272000000", + "name": "전북 진안군", + "short_name": "진안군", + "lat": 35.78872, + "lon": 127.42697 + } + ] + }, + { + "path": "jeonbuk/muju", + "name": "전북 무주군", + "main": "5273000000", + "regions": [ + { + "code": "5273000000", + "name": "전북 무주군", + "short_name": "무주군", + "lat": 36.00383, + "lon": 127.66287 + } + ] + }, + { + "path": "jeonbuk/jangsu", + "name": "전북 장수군", + "main": "5274000000", + "regions": [ + { + "code": "5274000000", + "name": "전북 장수군", + "short_name": "장수군", + "lat": 35.6443, + "lon": 127.5233 + } + ] + }, + { + "path": "jeonbuk/imsil", + "name": "전북 임실군", + "main": "5275000000", + "regions": [ + { + "code": "5275000000", + "name": "전북 임실군", + "short_name": "임실군", + "lat": 35.60806, + "lon": 127.28475 + } + ] + }, + { + "path": "jeonbuk/sunchang", + "name": "전북 순창군", + "main": "5277000000", + "regions": [ + { + "code": "5277000000", + "name": "전북 순창군", + "short_name": "순창군", + "lat": 35.37139, + "lon": 127.13963 + } + ] + }, + { + "path": "jeonbuk/gochang", + "name": "전북 고창군", + "main": "5279000000", + "regions": [ + { + "code": "5279000000", + "name": "전북 고창군", + "short_name": "고창군", + "lat": 35.43274, + "lon": 126.70411 + } + ] + }, + { + "path": "jeonbuk/buan", + "name": "전북 부안군", + "main": "5280000000", + "regions": [ + { + "code": "5280000000", + "name": "전북 부안군", + "short_name": "부안군", + "lat": 35.72853, + "lon": 126.73568 + } + ] + } +] \ No newline at end of file diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index d241960..88502e3 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -12,6 +12,7 @@ export default function App() { }> } /> + } /> } /> } /> } /> diff --git a/frontend/src/b/BLayout.tsx b/frontend/src/b/BLayout.tsx index fca9a25..0466f0c 100644 --- a/frontend/src/b/BLayout.tsx +++ b/frontend/src/b/BLayout.tsx @@ -228,7 +228,7 @@ function Shell() { {TABS.map((t) => t.key === 'today' ? ( // 메인 탭: 막대 위로 솟은 큰 주황 동그라미 - cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive ? 'text-(--orange)' : 'text-(--ink3)')}> + cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive || pathname.startsWith('/today/') ? 'text-(--orange)' : 'text-(--ink3)')}> diff --git a/frontend/src/b/region.tsx b/frontend/src/b/region.tsx index 0a49f13..9760d06 100644 --- a/frontend/src/b/region.tsx +++ b/frontend/src/b/region.tsx @@ -1,4 +1,6 @@ -import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import { matchPath, useLocation, useNavigate } from 'react-router' +import regionPages from '../../seo/region.json' import { nearestRegion } from '../api/client/sdk.gen' import type { RegionData } from '../api/client/types.gen' import { track } from '../lib/analytics' @@ -6,6 +8,19 @@ import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContex const KEY = 'nalssigak.b.region' +type RegionPage = (typeof regionPages)[number] + +/** /today/gyeonggi/seongnam 같은 지역 페이지 주소면 그 페이지 */ +function pageOf(pathname: string): RegionPage | undefined { + const m = matchPath('/today/:sido/:place', pathname) + return m ? regionPages.find((p) => p.path === `${m.params.sido}/${m.params.place}`) : undefined +} + +/** 지역 페이지 안의 구: 구로 나뉜 시는 r 이 그 시 안이면 r, 아니면 시청이 있는 구 */ +function regionIn(page: RegionPage, r?: RegionData | null): RegionData { + return page.regions.find((g) => g.code === r?.code) ?? page.regions.find((g) => g.code === page.main)! +} + function readStored(): RegionData | null { try { const raw = localStorage.getItem(KEY) @@ -26,33 +41,45 @@ function writeStored(r: RegionData) { } export function RegionProvider({ children }: { children: ReactNode }) { + const { pathname } = useLocation() + const navigate = useNavigate() + const page = pageOf(pathname) + const pageRef = useRef(page) + useEffect(() => { + pageRef.current = page + }, [page]) const [stored] = useState(readStored) - const [region, setRegionState] = useState(stored ?? DEFAULT_REGION) + const [landing] = useState(page) + const [chosen, setRegionState] = useState(() => (page ? regionIn(page, stored) : (stored ?? DEFAULT_REGION))) + // 앱 안에서 다른 지역 페이지로 옮겨 가면 그 지역으로 + const region = page && !page.regions.some((g) => g.code === chosen.code) ? regionIn(page, stored) : chosen const canLocate = typeof navigator !== 'undefined' && 'geolocation' in navigator - const [locateStatus, setLocateStatus] = useState(!stored && canLocate ? 'locating' : 'idle') + const [locateStatus, setLocateStatus] = useState(!landing && !stored && canLocate ? 'locating' : 'idle') + // 지역 페이지에서 고르면 주소도 그 지역 페이지로 바꿔, 공유한 링크가 보던 화면과 같게 한다 const setRegion = useCallback((r: RegionData) => { setRegionState(r) writeStored(r) - }, []) + const next = regionPages.find((p) => p.regions.some((g) => g.code === r.code)) + if (pageRef.current && next && next !== pageRef.current) navigate(`/today/${next.path}`) + }, [navigate]) - const findNearest = useCallback((onFound?: () => void) => { + // quiet 면 못 찾아도 상태를 바꾸지 않는다 (사람이 누른 게 아니라 안내 문구를 띄우지 않음) + const findNearest = useCallback((apply: (r: RegionData) => void, quiet = false) => { navigator.geolocation.getCurrentPosition( (pos) => { nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } }) .then(({ data: res }) => { if (!res.region) throw new Error('가까운 구를 찾지 못함') - setRegion(res.region) setLocateStatus('idle') - track('region_change', { region_name: res.region.name, method: 'location' }) - onFound?.() + apply(res.region) }) - .catch(() => setLocateStatus('error')) + .catch(() => !quiet && setLocateStatus('error')) }, - (err) => setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'), + (err) => !quiet && setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'), { timeout: 10000, maximumAge: 600000 }, ) - }, [setRegion]) + }, []) const locate = useCallback((onFound?: () => void) => { if (!canLocate) { @@ -60,13 +87,36 @@ export function RegionProvider({ children }: { children: ReactNode }) { return } setLocateStatus('locating') - findNearest(onFound) - }, [canLocate, findNearest]) + findNearest((r) => { + setRegion(r) + track('region_change', { region_name: r.name, method: 'location' }) + onFound?.() + }) + }, [canLocate, findNearest, setRegion]) - // 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다 useEffect(() => { - if (!stored && canLocate) findNearest() - }, [stored, canLocate, findNearest]) + if (!canLocate) return + // 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다 + if (!landing) { + if (!stored) { + findNearest((r) => { + setRegion(r) + track('region_change', { region_name: r.name, method: 'location' }) + }) + } + return + } + // 지역 페이지로 들어오면 그 지역을 보여 준다. 구로 나뉜 시는 위치를 이미 허용했고 그 시 안에 있으면 지금 있는 구로 + if (landing.regions.length < 2) return + navigator.permissions?.query({ name: 'geolocation' }) + .then((s) => { + if (s.state !== 'granted') return + findNearest((r) => { + if (pageRef.current === landing && landing.regions.some((g) => g.code === r.code)) setRegionState(r) + }, true) + }) + .catch((e) => console.warn('위치 권한 상태를 읽지 못함', e)) + }, [canLocate, landing, stored, findNearest, setRegion]) const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus]) return {children} diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.json index 6830b6f..345ba12 100644 --- a/frontend/tsconfig.app.json +++ b/frontend/tsconfig.app.json @@ -6,6 +6,7 @@ "module": "esnext", "types": ["vite/client"], "allowArbitraryExtensions": true, + "resolveJsonModule": true, "skipLibCheck": true, /* Bundler mode */ diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 279fe87..382e977 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -1,13 +1,15 @@ -import { readFileSync, writeFileSync } from 'node:fs' -import { resolve } from 'node:path' +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { dirname, resolve } from 'node:path' import tailwindcss from '@tailwindcss/vite' import react from '@vitejs/plugin-react' import { defineConfig, type Plugin } from 'vite' type Gak = { name: string; description: string } +type RegionPage = { path: string; name: string; main: string; regions: { code: string; name: string }[] } const gaks: Gak[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/gak.json'), 'utf8')) const gakList = `
    ${gaks.map((g) => `
  • ${g.name}: ${g.description}
  • `).join('')}
` +const regionPages: RegionPage[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/region.json'), 'utf8')) /** 검색 로봇이 처음 받는 페이지별 HTML. 바뀌지 않는 소개 글만 넣고, 날씨 값은 앱이 뜬 뒤 불러온다 */ const PAGES: { path: string; title: string; description: string; body: string }[] = [ @@ -37,6 +39,19 @@ const PAGES: { path: string; title: string; description: string; body: string }[ }, ] +/** 지역마다 한 장: /today/gyeonggi/seongnam. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */ +for (const r of regionPages) { + const sido = r.path.split('/')[0] + const near = regionPages.filter((o) => o !== r && o.path.startsWith(`${sido}/`)) + const parts = r.regions.length > 1 ? `

${r.name}는 ${r.regions.map((g) => g.name.split(' ').at(-1)).join(', ')}별로 따로 계산해요.

` : '' + PAGES.push({ + path: `today/${r.path}`, + title: `오늘 ${r.name} 날씨, 뭐 할까? | 날씨각`, + description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`, + body: `

오늘 ${r.name} 날씨, 뭐 할까?

${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.

${parts}

세차각, 빨래각, 러닝각, 우산각처럼 ${gaks.length}가지 일을 매일 새로 계산하고, 오늘 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.

${near.length ? `

${r.name.split(' ')[0]} 다른 지역 날씨

` : ''}`, + }) +} + const attr = (s: string) => s.replace(/&/g, '&').replace(/"/g, '"') function seoPages(): Plugin { @@ -59,8 +74,13 @@ function seoPages(): Plugin { .replace(/([\s\S]*<\/main>/, `
${p.body}

날씨각 처음으로

`) - writeFileSync(resolve(outDir, `${p.path}.html`), html) + const file = resolve(outDir, `${p.path}.html`) + mkdirSync(dirname(file), { recursive: true }) + writeFileSync(file, html) } + const today = new Date().toISOString().slice(0, 10) + const urls = ['', ...PAGES.map((p) => p.path)].map((path) => ` ${site}/${path}${today}`) + writeFileSync(resolve(outDir, 'sitemap.xml'), `\n\n${urls.join('\n')}\n\n`) }, } } From 646a45c88eb51991fc97b114c932905227baa24a Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Wed, 14 Oct 2026 09:15:16 +0900 Subject: [PATCH 06/63] =?UTF-8?q?chore:=20=EC=A7=80=EC=97=AD=20=EA=B2=80?= =?UTF-8?q?=EC=83=89=20=ED=8E=98=EC=9D=B4=EC=A7=80=20=EB=AA=A9=EB=A1=9D=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20=EC=8A=A4=ED=81=AC=EB=A6=BD=ED=8A=B8,=20?= =?UTF-8?q?=EB=B3=B8=EB=AC=B8=20=EB=AC=B8=EA=B5=AC=EC=97=90=EC=84=9C=20?= =?UTF-8?q?=EA=B0=81=20=EA=B0=9C=EC=88=98=20=EB=B9=BC=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/scripts/gen_region_pages.py | 43 +++++++++++++++++++++++++++++ frontend/vite.config.ts | 2 +- 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 backend/scripts/gen_region_pages.py diff --git a/backend/scripts/gen_region_pages.py b/backend/scripts/gen_region_pages.py new file mode 100644 index 0000000..2d0f6fa --- /dev/null +++ b/backend/scripts/gen_region_pages.py @@ -0,0 +1,43 @@ +"""프론트 지역 검색 페이지 목록(frontend/seo/region.json)을 seed/region.csv 로 다시 만든다. + +region.csv 가 바뀌면 실행: python backend/scripts/gen_region_pages.py +""" + +import csv +import json +import os + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +SRC = os.path.join(ROOT, "backend", "seed", "region.csv") +OUT = os.path.join(ROOT, "frontend", "seo", "region.json") + +SIDO = dict(서울='seoul', 부산='busan', 대구='daegu', 인천='incheon', 광주='gwangju', 대전='daejeon', 울산='ulsan', 세종='sejong', 경기='gyeonggi', 강원='gangwon', 충북='chungbuk', 충남='chungnam', 전북='jeonbuk', 전남='jeonnam', 경북='gyeongbuk', 경남='gyeongnam', 제주='jeju') +R = '''종로 jongno 중 jung 용산 yongsan 성동 seongdong 광진 gwangjin 동대문 dongdaemun 중랑 jungnang 성북 seongbuk 강북 gangbuk 도봉 dobong 노원 nowon 은평 eunpyeong 서대문 seodaemun 마포 mapo 양천 yangcheon 강서 gangseo 구로 guro 금천 geumcheon 영등포 yeongdeungpo 동작 dongjak 관악 gwanak 서초 seocho 강남 gangnam 송파 songpa 강동 gangdong +목포 mokpo 여수 yeosu 순천 suncheon 나주 naju 광양 gwangyang 동 dong 서 seo 남 nam 북 buk 광산 gwangsan 담양 damyang 곡성 gokseong 구례 gurye 고흥 goheung 보성 boseong 화순 hwasun 장흥 jangheung 강진 gangjin 해남 haenam 영암 yeongam 무안 muan 함평 hampyeong 영광 yeonggwang 장성 jangseong 완도 wando 진도 jindo 신안 sinan +영도 yeongdo 부산진 busanjin 동래 dongnae 해운대 haeundae 사하 saha 금정 geumjeong 연제 yeonje 수영 suyeong 사상 sasang 기장 gijang 수성 suseong 달서 dalseo 달성 dalseong 군위 gunwi +제물포 jemulpo 영종 yeongjong 미추홀 michuhol 연수 yeonsu 남동 namdong 부평 bupyeong 계양 gyeyang 서해 seohae 검단 geomdan 강화 ganghwa 옹진 ongjin 유성 yuseong 대덕 daedeok 울주 ulju 세종특별자치 sejong +수원 suwon 성남 seongnam 의정부 uijeongbu 안양 anyang 부천 bucheon 광명 gwangmyeong 평택 pyeongtaek 동두천 dongducheon 안산 ansan 고양 goyang 과천 gwacheon 구리 guri 남양주 namyangju 오산 osan 시흥 siheung 군포 gunpo 의왕 uiwang 하남 hanam 용인 yongin 파주 paju 이천 icheon 안성 anseong 김포 gimpo 화성 hwaseong 광주 gwangju 양주 yangju 포천 pocheon 여주 yeoju 연천 yeoncheon 가평 gapyeong 양평 yangpyeong +청주 cheongju 충주 chungju 제천 jecheon 보은 boeun 옥천 okcheon 영동 yeongdong 증평 jeungpyeong 진천 jincheon 괴산 goesan 음성 eumseong 단양 danyang +천안 cheonan 공주 gongju 보령 boryeong 아산 asan 서산 seosan 논산 nonsan 계룡 gyeryong 당진 dangjin 금산 geumsan 부여 buyeo 서천 seocheon 청양 cheongyang 홍성 hongseong 예산 yesan 태안 taean +포항 pohang 경주 gyeongju 김천 gimcheon 안동 andong 구미 gumi 영주 yeongju 영천 yeongcheon 상주 sangju 문경 mungyeong 경산 gyeongsan 의성 uiseong 청송 cheongsong 영양 yeongyang 영덕 yeongdeok 청도 cheongdo 고령 goryeong 성주 seongju 칠곡 chilgok 예천 yecheon 봉화 bonghwa 울진 uljin 울릉 ulleung +창원 changwon 진주 jinju 통영 tongyeong 사천 sacheon 김해 gimhae 밀양 miryang 거제 geoje 양산 yangsan 의령 uiryeong 함안 haman 창녕 changnyeong 고성 goseong 남해 namhae 하동 hadong 산청 sancheong 함양 hamyang 거창 geochang 합천 hapcheon 제주 jeju 서귀포 seogwipo +춘천 chuncheon 원주 wonju 강릉 gangneung 동해 donghae 태백 taebaek 속초 sokcho 삼척 samcheok 홍천 hongcheon 횡성 hoengseong 영월 yeongwol 평창 pyeongchang 정선 jeongseon 철원 cheorwon 화천 hwacheon 양구 yanggu 인제 inje 양양 yangyang +전주 jeonju 군산 gunsan 익산 iksan 정읍 jeongeup 남원 namwon 김제 gimje 완주 wanju 진안 jinan 무주 muju 장수 jangsu 임실 imsil 순창 sunchang 고창 gochang 부안 buan'''.split() +ROMAN = dict(zip(R[::2], R[1::2])) +# 구로 나뉜 시는 시청이 있는 구를 먼저 보여 준다 +CITY_MAIN = {'수원시': '팔달구', '성남시': '중원구', '안양시': '동안구', '부천시': '원미구', '안산시': '단원구', '고양시': '덕양구', '용인시': '처인구', '화성시': '만세구', '청주시': '상당구', '천안시': '서북구', '포항시': '남구', '창원시': '의창구', '전주시': '완산구'} +pages = {} +for row in csv.DictReader(open(SRC, encoding='utf-8')): + sido, *rest = row['name'].split() + place = rest[0] + r = dict(code=row['code'], name=row['name'], short_name=row['short_name'], lat=float(row['lat']), lon=float(row['lon'])) + path = f"{SIDO[sido]}/{ROMAN[place[:-1]]}" + p = pages.setdefault(path, dict(path=path, name='세종시' if sido == '세종' else f'{sido} {place}', main=None, regions=[])) + p['regions'].append(r) + if len(rest) == 1 or CITY_MAIN[place] == rest[1]: + p['main'] = r['code'] +out = list(pages.values()) +assert all(p['main'] for p in out), [p['path'] for p in out if not p['main']] +assert sum(len(p['regions']) for p in out) == 256 +json.dump(out, open(OUT, 'w', encoding='utf-8'), ensure_ascii=False, indent=1) +print(len(out), 'pages', sum(len(p['regions']) > 1 for p in out), 'cities') diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 382e977..91495b8 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -48,7 +48,7 @@ for (const r of regionPages) { path: `today/${r.path}`, title: `오늘 ${r.name} 날씨, 뭐 할까? | 날씨각`, description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`, - body: `

오늘 ${r.name} 날씨, 뭐 할까?

${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.

${parts}

세차각, 빨래각, 러닝각, 우산각처럼 ${gaks.length}가지 일을 매일 새로 계산하고, 오늘 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.

${near.length ? `

${r.name.split(' ')[0]} 다른 지역 날씨

` : ''}`, + body: `

오늘 ${r.name} 날씨, 뭐 할까?

${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.

${parts}

세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.

${near.length ? `

${r.name.split(' ')[0]} 다른 지역 날씨

` : ''}`, }) } From a68268234d8f61d27324d32f7411edd88d90bd0e Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Wed, 14 Oct 2026 09:32:23 +0900 Subject: [PATCH 07/63] =?UTF-8?q?feat:=20=EC=A7=80=EC=97=AD=20=EA=B2=80?= =?UTF-8?q?=EC=83=89=20=ED=8E=98=EC=9D=B4=EC=A7=80=EC=97=90=20=EC=98=A4?= =?UTF-8?q?=EB=8A=98=20=EB=82=A0=EC=94=A8=C2=B7=EA=B0=81=EC=9D=84=20?= =?UTF-8?q?=EC=84=9C=EB=B2=84=EA=B0=80=20=EC=B1=84=EC=9B=8C=20=EC=A4=80?= =?UTF-8?q?=EB=8B=A4=20(nginx=20=E2=86=92=20/v1/seo/today,=20=EC=8B=A4?= =?UTF-8?q?=ED=8C=A8=ED=95=98=EB=A9=B4=20=EC=A0=95=EC=A0=81=20HTML)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/config/settings.py | 3 ++ backend/router/router.py | 2 + backend/router/v1/seo/__init__.py | 0 backend/router/v1/seo/seo.py | 17 +++++++ backend/services/seo_service.py | 84 +++++++++++++++++++++++++++++++ backend/tests/test_seo.py | 56 +++++++++++++++++++++ frontend/nginx.conf | 17 +++++++ frontend/vite.config.ts | 5 +- 8 files changed, 183 insertions(+), 1 deletion(-) create mode 100644 backend/router/v1/seo/__init__.py create mode 100644 backend/router/v1/seo/seo.py create mode 100644 backend/services/seo_service.py create mode 100644 backend/tests/test_seo.py diff --git a/backend/config/settings.py b/backend/config/settings.py index 1c26d87..f56e97b 100644 --- a/backend/config/settings.py +++ b/backend/config/settings.py @@ -31,6 +31,9 @@ class Settings(BaseSettings): # 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분) image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr" + # 지역 검색 페이지의 정적 HTML 을 받아 올 프론트 주소 (같은 docker 망 안) + frontend_internal_url: str = "http://frontend" + jwt_access_secret: str = "" jwt_refresh_secret: str = "" jwt_access_minutes: int = 60 diff --git a/backend/router/router.py b/backend/router/router.py index 28316de..ea6858a 100644 --- a/backend/router/router.py +++ b/backend/router/router.py @@ -14,6 +14,7 @@ from router.v1.index.index import router as index_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 +from router.v1.seo.seo import router as seo_router from router.v1.sky.sky import router as sky_router from router.v1.watch.watch import router as watch_router from router.v1.weather.weather import router as weather_router @@ -43,6 +44,7 @@ app.include_router(auth_router) app.include_router(reaction_router) app.include_router(watch_router) app.include_router(image_router) +app.include_router(seo_router) class Res_Health(Res_WebPacketProtocol): diff --git a/backend/router/v1/seo/__init__.py b/backend/router/v1/seo/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/router/v1/seo/seo.py b/backend/router/v1/seo/seo.py new file mode 100644 index 0000000..5b62d9d --- /dev/null +++ b/backend/router/v1/seo/seo.py @@ -0,0 +1,17 @@ +from fastapi import APIRouter, Depends, Path +from fastapi.responses import HTMLResponse + +from common.enums import ErrorType +from services.seo_service import SeoService + +router = APIRouter(prefix="/v1/seo", tags=["seo"]) + +_SLUG = r"^[a-z]+$" + + +@router.get("/today/{sido}/{place}", response_class=HTMLResponse, summary="지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김)") +async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse: + err, html = await service.page(f"today/{sido}/{place}") + if err is not ErrorType.SUCCESS: + return HTMLResponse("not found", status_code=404) + return HTMLResponse(html, headers={"Cache-Control": "no-cache"}) diff --git a/backend/services/seo_service.py b/backend/services/seo_service.py new file mode 100644 index 0000000..0fdcd0e --- /dev/null +++ b/backend/services/seo_service.py @@ -0,0 +1,84 @@ +import re +from datetime import datetime +from html import escape +from typing import Optional + +import httpx +from fastapi import Depends + +from common.database.db_session_manager import DB_SESSION_MNG +from common.enums import ErrorType +from common.logger import LOG +from common.utils.kma_time import KST, now_kst +from config.settings import settings +from crud.region_crud import RegionCRUD +from router.v1.feed.protocol import Res_Feed +from services.calc.day_slot import SLOT_LABEL +from services.calc.sun import sun_times +from services.feed_service import FeedService + +_CODE = re.compile(r'오늘 (.+?) 날씨") +_H1 = re.compile(r"(

[^<]*

)") + + +def _clock(at: datetime) -> str: + at = at.astimezone(KST) + h = at.hour % 12 or 12 + return f"{'오전' if at.hour < 12 else '오후'} {h}시" + (f" {at.minute}분" if at.minute else "") + + +def today_line(feed: Res_Feed, sunset_at: Optional[datetime]) -> str: + """검색 결과 요약에 보일 오늘 한 줄: 지금 기온·상태, 구간별 1위 각, 해 지는 시각.""" + parts = [] + h = feed.hero + if h and h.temp_c is not None: + status = "·".join(f"{s.label} {s.value}" for s in h.status) + parts.append(f"지금 {round(h.temp_c)}°" + (f", {status}" if status else "") + ".") + firsts = [f"{label}은 {s.name}" for slot, label in SLOT_LABEL.items() for s in feed.stories if s.slot_ranks.get(slot) == 1] + if firsts: + parts.append(", ".join(firsts) + ".") + if sunset_at: + parts.append(f"해 지는 시각 {_clock(sunset_at)}.") + return " ".join(parts) + + +def fill(template: str, feed: Res_Feed, name: str, sunset_at: Optional[datetime]) -> str: + """정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위.""" + line = today_line(feed, sunset_at) + if not line: + return template + top = feed.bands.top5 if feed.bands else [] + ranks = f"

오늘 {escape(name)} 각 순위

    {''.join(f'
  1. {escape(t.name)} {t.score}점
  2. ' for t in top)}
" if top else "" + html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template) + return _H1.sub(lambda m: f"{m.group(1)}

{escape(line)}

{ranks}", html, count=1) + + +class SeoService: + def __init__(self, feed: FeedService = Depends(FeedService), regions: RegionCRUD = Depends(RegionCRUD)) -> None: + self.feed, self.regions = feed, regions + + async def template(self, path: str) -> Optional[str]: + """프론트가 빌드한 정적 지역 페이지 (today/gyeonggi/seongnam.html).""" + try: + async with httpx.AsyncClient(timeout=5) as client: + r = await client.get(f"{settings.frontend_internal_url}/{path}.html") + except httpx.HTTPError as e: + LOG.error(f"[seo] template {path}: {e}") + return None + return r.text if r.status_code == 200 and _CODE.search(r.text) else None + + async def page(self, path: str) -> tuple[ErrorType, Optional[str]]: + template = await self.template(path) + if template is None: + return ErrorType.NOT_FOUND, None + code = _CODE.search(template).group(1) + err, feed = await self.feed.feed(code) + if err is not ErrorType.SUCCESS or feed is None: + LOG.error(f"[seo] feed {code}: {err}") + return ErrorType.SUCCESS, template + _, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code)) + sunset_at = sun_times(now_kst().date(), float(region.lat), float(region.lon)).sunset_at if region else None + name = _NAME.search(template) + return ErrorType.SUCCESS, fill(template, feed, name.group(1) if name else (feed.region_name or ""), sunset_at) diff --git a/backend/tests/test_seo.py b/backend/tests/test_seo.py new file mode 100644 index 0000000..690376c --- /dev/null +++ b/backend/tests/test_seo.py @@ -0,0 +1,56 @@ +from datetime import datetime + +import pytest +from httpx import ASGITransport, AsyncClient + +from common.utils.kma_time import KST +from router.router import app +from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex +from services.seo_service import SeoService, fill, today_line + +REGION = "1114000000" +TEMPLATE = ( + '' + f'\n

오늘 서울 중구 날씨, 뭐 할까?

소개 글

' +) + + +def _top(name: str, score: int, ranks: dict[str, int]) -> TopIndex: + return TopIndex(index_id=1, code="x", name=name, icon="x", score=score, rank=1, slot_ranks=ranks) + + +def _feed() -> Res_Feed: + stories = [_top("러닝각", 80, {"morning": 1, "day": 2}), _top("빨래각", 77, {"day": 1}), _top("별보기각", 70, {"night": 1})] + hero = Hero(now_at=datetime(2026, 10, 14, 9), sky_mode="morning", temp_c=13.4, + status=[HeroStat(icon="m", label="습도", value="보통", tone="normal"), HeroStat(icon="m", label="미세먼지", value="좋음", tone="normal")]) + return Res_Feed(hero=hero, stories=stories, bands=Bands(top5=stories[:2])) + + +def test_today_line_has_temp_status_slot_firsts_and_sunset(): + line = today_line(_feed(), datetime(2026, 10, 14, 17, 52, tzinfo=KST)) + assert line == "지금 13°, 습도 보통·미세먼지 좋음. 아침은 러닝각, 낮은 빨래각, 밤은 별보기각. 해 지는 시각 오후 5시 52분." + + +def test_fill_puts_today_into_description_and_body(): + html = fill(TEMPLATE, _feed(), "서울 중구", None) + assert html.count('content="지금 13°, 습도 보통·미세먼지 좋음.') == 2 + assert "

오늘 서울 중구 날씨, 뭐 할까?

지금 13°" in html + assert "

  • 러닝각 80점
  • 빨래각 77점
  • " in html + + +def test_fill_keeps_template_when_no_weather(): + assert fill(TEMPLATE, Res_Feed(), "서울 중구", None) == TEMPLATE + + +@pytest.mark.anyio +async def test_today_page_fills_real_feed(offline, monkeypatch): + async def template(self, path): + return TEMPLATE if path == "today/seoul/jung" else None + + monkeypatch.setattr(SeoService, "template", template) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + page = await client.get("/v1/seo/today/seoul/jung") + missing = await client.get("/v1/seo/today/seoul/nowhere") + assert page.status_code == 200 and "

    오늘 서울 중구 날씨, 뭐 할까?

    지금 20°" in page.text + assert "해 지는 시각 오후" in page.text and "

    1. " in page.text + assert missing.status_code == 404 diff --git a/frontend/nginx.conf b/frontend/nginx.conf index 3c207a6..186c17a 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -31,6 +31,23 @@ server { proxy_set_header X-Forwarded-Proto $scheme; } + # 지역 검색 페이지: 백엔드가 정적 HTML(today/…/….html)에 오늘 날씨를 채워 준다. 백엔드가 안 되면 정적 HTML 그대로 + location ~ ^/today/[a-z]+/[a-z]+$ { + resolver 127.0.0.11 valid=10s ipv6=off; + set $api http://backend:9800; + proxy_pass $api/v1/seo$uri; + proxy_set_header Host $host; + proxy_connect_timeout 3s; + proxy_read_timeout 20s; + proxy_intercept_errors on; + error_page 404 500 502 503 504 = @static; + } + + location @static { + add_header Cache-Control "no-cache"; + try_files $uri.html /index.html; + } + # SPA: /gak 처럼 빌드 때 만든 페이지별 HTML(gak.html)이 있으면 그것을, 없으면 index.html. 폴더는 안 찾는다 (/season 이 이미지 폴더 public/season 과 겹쳐 403) location / { add_header Cache-Control "no-cache"; diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 91495b8..8283b90 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -12,7 +12,7 @@ const gakList = `
        ${gaks.map((g) => `
      • ${g.name}: ${g.description} 1 ? `

        ${r.name}는 ${r.regions.map((g) => g.name.split(' ').at(-1)).join(', ')}별로 따로 계산해요.

        ` : '' PAGES.push({ path: `today/${r.path}`, + code: r.main, title: `오늘 ${r.name} 날씨, 뭐 할까? | 날씨각`, description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`, body: `

        오늘 ${r.name} 날씨, 뭐 할까?

        ${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.

        ${parts}

        세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.

        ${near.length ? `

        ${r.name.split(' ')[0]} 다른 지역 날씨

        ` : ''}`, @@ -74,6 +75,8 @@ function seoPages(): Plugin { .replace(/([\s\S]*<\/main>/, `
        ${p.body}

        날씨각 처음으로

        `) + // 서버가 오늘 날씨를 채울 때 이 페이지의 구를 알아보는 표시 + .replace('', p.code ? `\n ` : '') const file = resolve(outDir, `${p.path}.html`) mkdirSync(dirname(file), { recursive: true }) writeFileSync(file, html) From 882932a51b8890cd9a6ff92118957bc156eee5ef Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Wed, 14 Oct 2026 10:11:29 +0900 Subject: [PATCH 08/63] =?UTF-8?q?feat:=20=EC=A7=80=EC=97=AD=20=EA=B2=80?= =?UTF-8?q?=EC=83=89=20=ED=8E=98=EC=9D=B4=EC=A7=80=20=EC=A0=9C=EB=AA=A9?= =?UTF-8?q?=EC=9D=84=20'=EC=84=B1=EB=82=A8=EC=8B=9C=20=EC=98=A4=EB=8A=98?= =?UTF-8?q?=20=EB=82=A0=EC=94=A8'=EB=A1=9C=20=EC=8B=9C=EC=9E=91,=20?= =?UTF-8?q?=EC=9A=94=EC=95=BD=20=EC=95=9E=EC=97=90=20=EC=B5=9C=EC=A0=80?= =?UTF-8?q?=C2=B7=EC=B5=9C=EA=B3=A0=C2=B7=EA=B0=95=EC=88=98=ED=99=95?= =?UTF-8?q?=EB=A5=A0=C2=B7=ED=95=98=EB=8A=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/services/seo_service.py | 48 ++++++++++++++++++++++++--------- backend/tests/test_seo.py | 29 +++++++++++++------- frontend/vite.config.ts | 7 +++-- 3 files changed, 60 insertions(+), 24 deletions(-) diff --git a/backend/services/seo_service.py b/backend/services/seo_service.py index 0fdcd0e..b2c76fb 100644 --- a/backend/services/seo_service.py +++ b/backend/services/seo_service.py @@ -1,5 +1,5 @@ import re -from datetime import datetime +from datetime import datetime, timedelta from html import escape from typing import Optional @@ -7,11 +7,13 @@ import httpx from fastapi import Depends from common.database.db_session_manager import DB_SESSION_MNG -from common.enums import ErrorType +from common.database.model.models import WeatherHourly +from common.enums import ErrorType, RainType, Sky from common.logger import LOG -from common.utils.kma_time import KST, now_kst +from common.utils.kma_time import KST, kst_midnight, now_kst from config.settings import settings from crud.region_crud import RegionCRUD +from crud.weather_crud import WeatherCRUD from router.v1.feed.protocol import Res_Feed from services.calc.day_slot import SLOT_LABEL from services.calc.sun import sun_times @@ -19,7 +21,7 @@ from services.feed_service import FeedService _CODE = re.compile(r'오늘 (.+?) 날씨") +_NAME = re.compile(r"

        (.+?) 오늘 날씨") _H1 = re.compile(r"(

        [^<]*

        )") @@ -29,9 +31,24 @@ def _clock(at: datetime) -> str: return f"{'오전' if at.hour < 12 else '오후'} {h}시" + (f" {at.minute}분" if at.minute else "") -def today_line(feed: Res_Feed, sunset_at: Optional[datetime]) -> str: - """검색 결과 요약에 보일 오늘 한 줄: 지금 기온·상태, 구간별 1위 각, 해 지는 시각.""" - parts = [] +_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"} +_RAIN_WORD = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"} + + +def day_summary(rows: list[WeatherHourly]) -> str: + """오늘 하루 예보 요약: 최저·최고, 강수확률, 하늘 (비·눈이 있으면 그것).""" + if not rows: + return "" + temps = [float(r.temp_c) for r in rows] + wet = next((RainType(r.rain_type) for r in rows if r.rain_type != RainType.NONE.value), None) + day = [r for r in rows if 9 <= r.forecast_at.astimezone(KST).hour <= 18] or rows + sky = _RAIN_WORD[wet] if wet else _SKY_WORD[Sky(max({r.sky for r in day}, key=[r.sky for r in day].count))] + return f"최저 {round(min(temps))}°·최고 {round(max(temps))}°, 강수확률 {max(r.rain_prob for r in rows)}%, {sky}." + + +def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str: + """검색 결과 요약에 보일 오늘 한 줄: 하루 예보, 지금 기온·상태, 구간별 1위 각, 해 지는 시각.""" + parts = [day_summary(rows)] if rows else [] h = feed.hero if h and h.temp_c is not None: status = "·".join(f"{s.label} {s.value}" for s in h.status) @@ -44,9 +61,9 @@ def today_line(feed: Res_Feed, sunset_at: Optional[datetime]) -> str: return " ".join(parts) -def fill(template: str, feed: Res_Feed, name: str, sunset_at: Optional[datetime]) -> str: +def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str: """정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위.""" - line = today_line(feed, sunset_at) + line = today_line(feed, rows, sunset_at) if not line: return template top = feed.bands.top5 if feed.bands else [] @@ -56,8 +73,10 @@ def fill(template: str, feed: Res_Feed, name: str, sunset_at: Optional[datetime] class SeoService: - def __init__(self, feed: FeedService = Depends(FeedService), regions: RegionCRUD = Depends(RegionCRUD)) -> None: - self.feed, self.regions = feed, regions + def __init__( + self, feed: FeedService = Depends(FeedService), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD) + ) -> None: + self.feed, self.regions, self.weather = feed, regions, weather async def template(self, path: str) -> Optional[str]: """프론트가 빌드한 정적 지역 페이지 (today/gyeonggi/seongnam.html).""" @@ -79,6 +98,9 @@ class SeoService: LOG.error(f"[seo] feed {code}: {err}") return ErrorType.SUCCESS, template _, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code)) - sunset_at = sun_times(now_kst().date(), float(region.lat), float(region.lon)).sunset_at if region else None + today = now_kst().date() + sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at if region else None + start = kst_midnight(today) + _, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, code, start, start + timedelta(days=1))) name = _NAME.search(template) - return ErrorType.SUCCESS, fill(template, feed, name.group(1) if name else (feed.region_name or ""), sunset_at) + return ErrorType.SUCCESS, fill(template, feed, rows or [], name.group(1) if name else (feed.region_name or ""), sunset_at) diff --git a/backend/tests/test_seo.py b/backend/tests/test_seo.py index 690376c..0923896 100644 --- a/backend/tests/test_seo.py +++ b/backend/tests/test_seo.py @@ -4,14 +4,15 @@ import pytest from httpx import ASGITransport, AsyncClient from common.utils.kma_time import KST +from common.database.model.models import WeatherHourly from router.router import app from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex -from services.seo_service import SeoService, fill, today_line +from services.seo_service import SeoService, day_summary, fill, today_line REGION = "1114000000" TEMPLATE = ( '' - f'\n

        오늘 서울 중구 날씨, 뭐 할까?

        소개 글

        ' + f'\n

        서울 중구 오늘 날씨, 뭐 할까?

        소개 글

        ' ) @@ -26,20 +27,30 @@ def _feed() -> Res_Feed: return Res_Feed(hero=hero, stories=stories, bands=Bands(top5=stories[:2])) -def test_today_line_has_temp_status_slot_firsts_and_sunset(): - line = today_line(_feed(), datetime(2026, 10, 14, 17, 52, tzinfo=KST)) - assert line == "지금 13°, 습도 보통·미세먼지 좋음. 아침은 러닝각, 낮은 빨래각, 밤은 별보기각. 해 지는 시각 오후 5시 52분." +def _hour(h: int, temp: float, sky: int = 1, rain: int = 1, prob: int = 0) -> WeatherHourly: + return WeatherHourly(forecast_at=datetime(2026, 10, 14, h, tzinfo=KST), temp_c=temp, sky=sky, rain_type=rain, rain_prob=prob) + + +def test_day_summary_min_max_prob_and_daytime_sky(): + rows = [_hour(3, 8.6, sky=4), _hour(9, 12, sky=3), _hour(12, 19.5, sky=1, prob=10), _hour(15, 20.2, sky=1), _hour(21, 14)] + assert day_summary(rows) == "최저 9°·최고 20°, 강수확률 10%, 맑음." + assert day_summary([_hour(12, 15, rain=2, prob=70)]) == "최저 15°·최고 15°, 강수확률 70%, 비." + + +def test_today_line_has_day_now_slot_firsts_and_sunset(): + line = today_line(_feed(), [_hour(12, 19.5, prob=10)], datetime(2026, 10, 14, 17, 52, tzinfo=KST)) + assert line == "최저 20°·최고 20°, 강수확률 10%, 맑음. 지금 13°, 습도 보통·미세먼지 좋음. 아침은 러닝각, 낮은 빨래각, 밤은 별보기각. 해 지는 시각 오후 5시 52분." def test_fill_puts_today_into_description_and_body(): - html = fill(TEMPLATE, _feed(), "서울 중구", None) + html = fill(TEMPLATE, _feed(), [], "서울 중구", None) assert html.count('content="지금 13°, 습도 보통·미세먼지 좋음.') == 2 - assert "

        오늘 서울 중구 날씨, 뭐 할까?

        지금 13°" in html + assert "

        서울 중구 오늘 날씨, 뭐 할까?

        지금 13°" in html assert "

      • 러닝각 80점
      • 빨래각 77점
      • " in html def test_fill_keeps_template_when_no_weather(): - assert fill(TEMPLATE, Res_Feed(), "서울 중구", None) == TEMPLATE + assert fill(TEMPLATE, Res_Feed(), [], "서울 중구", None) == TEMPLATE @pytest.mark.anyio @@ -51,6 +62,6 @@ async def test_today_page_fills_real_feed(offline, monkeypatch): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: page = await client.get("/v1/seo/today/seoul/jung") missing = await client.get("/v1/seo/today/seoul/nowhere") - assert page.status_code == 200 and "

        오늘 서울 중구 날씨, 뭐 할까?

        지금 20°" in page.text + assert page.status_code == 200 and "

        서울 중구 오늘 날씨, 뭐 할까?

        최저 " in page.text and "지금 20°" in page.text assert "해 지는 시각 오후" in page.text and "

        1. " in page.text assert missing.status_code == 404 diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 8283b90..013550f 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -39,6 +39,9 @@ const PAGES: { path: string; title: string; description: string; body: string; c }, ] +/** 제목 앞자리: 검색어처럼 시군구 이름부터 (경기 성남시 → 성남시) */ +const headName = (name: string) => name.split(' ').at(-1)! + /** 지역마다 한 장: /today/gyeonggi/seongnam. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */ for (const r of regionPages) { const sido = r.path.split('/')[0] @@ -47,9 +50,9 @@ for (const r of regionPages) { PAGES.push({ path: `today/${r.path}`, code: r.main, - title: `오늘 ${r.name} 날씨, 뭐 할까? | 날씨각`, + title: `${headName(r.name)} 오늘 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[0]}` : ''} | 날씨각`, description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`, - body: `

          오늘 ${r.name} 날씨, 뭐 할까?

          ${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.

          ${parts}

          세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.

          ${near.length ? `

          ${r.name.split(' ')[0]} 다른 지역 날씨

          ` : ''}`, + body: `

          ${r.name} 오늘 날씨, 뭐 할까?

          ${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.

          ${parts}

          세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.

          ${near.length ? `

          ${r.name.split(' ')[0]} 다른 지역 날씨

          ` : ''}`, }) } From ba94a381a9516ac56c023015089bb9f74c5415a1 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Wed, 14 Oct 2026 10:18:17 +0900 Subject: [PATCH 09/63] =?UTF-8?q?fix:=20'=EB=82=A0=EC=94=A8=EA=B0=81'=20?= =?UTF-8?q?=EA=B2=80=EC=83=89=20=EC=9A=94=EC=95=BD=EC=97=90=20=EA=B2=8C?= =?UTF-8?q?=EC=8B=9C=EB=AC=BC=20=EA=B8=80=EC=9D=B4=20=EB=BD=91=ED=9E=88?= =?UTF-8?q?=EB=8D=98=20=EA=B2=83=20(=EA=B2=8C=EC=8B=9C=EB=AC=BC=20data-nos?= =?UTF-8?q?nippet,=20=ED=99=88=20=EC=84=A4=EB=AA=85=EC=9D=84=20'=EB=82=A0?= =?UTF-8?q?=EC=94=A8=EA=B0=81=EC=9D=80'=EC=9C=BC=EB=A1=9C=20=EC=8B=9C?= =?UTF-8?q?=EC=9E=91)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/index.html | 8 ++++---- frontend/src/b/Post.tsx | 3 ++- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/frontend/index.html b/frontend/index.html index 07663b6..644acc0 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -15,14 +15,14 @@ - + 날씨각 · 오늘 날씨 지수, 노을, 주말 행사 - + @@ -31,7 +31,7 @@ - + @@ -60,7 +60,7 @@ "@type": "WebApplication", "name": "날씨각", "url": "%VITE_SITE_URL%/", - "description": "세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요.", + "description": "날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요.", "applicationCategory": "WeatherApplication", "operatingSystem": "All", "inLanguage": "ko-KR", diff --git a/frontend/src/b/Post.tsx b/frontend/src/b/Post.tsx index 06f77fc..9143b43 100644 --- a/frontend/src/b/Post.tsx +++ b/frontend/src/b/Post.tsx @@ -269,8 +269,9 @@ function LineCard({ post }: PostProps) { } /** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요 */ +// data-nosnippet: 검색 결과 요약에 게시물 글('날씨각' + 오늘 문장)이 대신 뽑혀 나오지 않게 export function PostCard({ post }: PostProps) { - return post.size === 'line' ? : + return
          {post.size === 'line' ? : }
          } /** FullCard 와 같은 틀(머리줄·4:5 그림·버튼줄·글 한 줄)의 스켈레톤 */ From 0d6ab29552d76bf8ebcb1e8618fa32a040dc33d9 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Wed, 14 Oct 2026 10:48:49 +0900 Subject: [PATCH 10/63] =?UTF-8?q?fix:=20=EA=B2=80=EC=83=89=20=EA=B2=B0?= =?UTF-8?q?=EA=B3=BC=20=EC=9A=94=EC=95=BD=EC=97=90=20=ED=99=94=EB=A9=B4=20?= =?UTF-8?q?=EA=B8=80(=EC=8B=9C=EA=B0=84=EB=8C=80=20=EC=B9=B8=C2=B7?= =?UTF-8?q?=ED=96=89=EC=82=AC=C2=B7=EA=B2=8C=EC=8B=9C=EB=AC=BC)=EC=9D=B4?= =?UTF-8?q?=20=EB=BD=91=ED=9E=88=EB=8D=98=20=EA=B2=83=20(=EC=95=B1=20?= =?UTF-8?q?=EC=98=81=EC=97=AD=20=EC=A0=84=EC=B2=B4=20data-nosnippet,=20?= =?UTF-8?q?=EC=9A=94=EC=95=BD=EC=9D=80=20description=20=EC=9C=BC=EB=A1=9C)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/index.html | 5 +++-- frontend/src/b/Post.tsx | 3 +-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/frontend/index.html b/frontend/index.html index 644acc0..34d6bff 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -98,11 +98,12 @@ -
          +

          날씨 불러오는 중…

          -
          + +

          날씨각

          오늘 하고 싶은 일이 날씨에 맞는지 점수로 알려 드려요. 세차, 빨래, 러닝, 피크닉처럼 일상의 일을 우리 동네 날씨로 바로 확인하세요.

          diff --git a/frontend/src/b/Post.tsx b/frontend/src/b/Post.tsx index 9143b43..06f77fc 100644 --- a/frontend/src/b/Post.tsx +++ b/frontend/src/b/Post.tsx @@ -269,9 +269,8 @@ function LineCard({ post }: PostProps) { } /** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요 */ -// data-nosnippet: 검색 결과 요약에 게시물 글('날씨각' + 오늘 문장)이 대신 뽑혀 나오지 않게 export function PostCard({ post }: PostProps) { - return
          {post.size === 'line' ? : }
          + return post.size === 'line' ? : } /** FullCard 와 같은 틀(머리줄·4:5 그림·버튼줄·글 한 줄)의 스켈레톤 */ From b0cd5ef1efdee4484d43076f46010ed34d8d254c Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Wed, 14 Oct 2026 11:07:54 +0900 Subject: [PATCH 11/63] =?UTF-8?q?feat:=20=EC=A7=80=EC=97=AD=20=EA=B2=80?= =?UTF-8?q?=EC=83=89=20=ED=8E=98=EC=9D=B4=EC=A7=80=20keywords=20=EB=A5=BC?= =?UTF-8?q?=20=EC=A7=80=EC=97=AD=EB=B3=84=EB=A1=9C=20(=EC=84=B1=EB=82=A8?= =?UTF-8?q?=20=EB=82=A0=EC=94=A8=C2=B7=EC=84=B1=EB=82=A8=EC=8B=9C=20?= =?UTF-8?q?=EB=82=A0=EC=94=A8=C2=B7=EB=B6=84=EB=8B=B9=EA=B5=AC=20=EB=82=A0?= =?UTF-8?q?=EC=94=A8=E2=80=A6),=20=EB=B3=B8=EB=AC=B8=20=EC=B2=AB=20?= =?UTF-8?q?=EC=A4=84=EC=97=90=20'=EC=84=B1=EB=82=A8=20=EB=82=A0=EC=94=A8'?= =?UTF-8?q?=20=EA=BC=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/vite.config.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 013550f..028b03f 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -12,7 +12,7 @@ const gakList = `
            ${gaks.map((g) => `
          • ${g.name}: ${g.description} name.split(' ').at(-1)! +/** 검색어로 많이 치는 꼴: 성남시 → 성남. 중구처럼 두 글자는 그대로 */ +const bareName = (name: string) => (name.length > 2 ? name.slice(0, -1) : name) /** 지역마다 한 장: /today/gyeonggi/seongnam. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */ for (const r of regionPages) { const sido = r.path.split('/')[0] const near = regionPages.filter((o) => o !== r && o.path.startsWith(`${sido}/`)) const parts = r.regions.length > 1 ? `

            ${r.name}는 ${r.regions.map((g) => g.name.split(' ').at(-1)).join(', ')}별로 따로 계산해요.

            ` : '' + const head = headName(r.name) + const bare = bareName(head) + const guNames = r.regions.length > 1 ? r.regions.map((g) => g.name.split(' ').at(-1)!) : [] + const keywords = [...new Set([`${bare} 날씨`, `${head} 날씨`, `${bare} 오늘 날씨`, `${r.name} 날씨`, ...guNames.flatMap((g) => [`${g} 날씨`, `${bareName(g)} 날씨`]), '날씨각'])].join(', ') PAGES.push({ path: `today/${r.path}`, code: r.main, + keywords, title: `${headName(r.name)} 오늘 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[0]}` : ''} | 날씨각`, description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`, - body: `

            ${r.name} 오늘 날씨, 뭐 할까?

            ${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.

            ${parts}

            세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.

            ${near.length ? `

            ${r.name.split(' ')[0]} 다른 지역 날씨

            ` : ''}`, + body: `

            ${r.name} 오늘 날씨, 뭐 할까?

            ${bare} 날씨, 오늘 ${head}에서는 뭐 하기 좋을까요? ${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.

            ${parts}

            세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.

            ${near.length ? `

            ${r.name.split(' ')[0]} 다른 지역 날씨

            ` : ''}`, }) } @@ -75,6 +82,7 @@ function seoPages(): Plugin { .replace(/[^<]*<\/title>/, `<title>${p.title}`) .replace(/( (p.keywords ? `${head}${attr(p.keywords)}"` : m)) .replace(/([\s\S]*<\/main>/, `
            ${p.body}

            날씨각 처음으로

            `) From 3c9b163dd489a013cade300046ee16a5786a0f66 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Mon, 19 Oct 2026 10:54:06 +0900 Subject: [PATCH 12/63] =?UTF-8?q?feat:=20=ED=99=88=20=EC=B2=AB=20HTML?= =?UTF-8?q?=EC=97=90=20=EC=8B=9C=EB=8F=84=EB=B3=84=20=EC=A7=80=EC=97=AD=20?= =?UTF-8?q?=ED=8E=98=EC=9D=B4=EC=A7=80=20=EB=A7=81=ED=81=AC(230=EA=B0=9C)?= =?UTF-8?q?=EB=A5=BC=20=EB=84=A3=EC=96=B4=20=EA=B2=80=EC=83=89=20=EB=A1=9C?= =?UTF-8?q?=EB=B4=87=EC=9D=B4=20=ED=99=88=EC=97=90=EC=84=9C=20=EC=A7=80?= =?UTF-8?q?=EC=97=AD=20=ED=8E=98=EC=9D=B4=EC=A7=80=EB=A1=9C=20=EC=9D=B4?= =?UTF-8?q?=EC=96=B4=EC=A7=80=EA=B2=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/vite.config.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 028b03f..5914352 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -63,6 +63,12 @@ for (const r of regionPages) { }) } +/** 홈에만 넣는 시도별 지역 페이지 링크. 홈에서 지역 페이지로 바로 이어지게 한다 */ +const sidos = [...new Set(regionPages.map((r) => r.name.split(' ')[0]))] +const regionLinks = `

            지역별 오늘 날씨

            ${sidos + .map((s) => `

            ${s}

              ${regionPages.filter((r) => r.name.split(' ')[0] === s).map((r) => `
            • ${r.name}
            • `).join('')}
            `) + .join('')}` + const attr = (s: string) => s.replace(/&/g, '&').replace(/"/g, '"') function seoPages(): Plugin { @@ -92,6 +98,7 @@ function seoPages(): Plugin { mkdirSync(dirname(file), { recursive: true }) writeFileSync(file, html) } + writeFileSync(resolve(outDir, 'index.html'), base.replace('
          ', `${regionLinks}
        `)) const today = new Date().toISOString().slice(0, 10) const urls = ['', ...PAGES.map((p) => p.path)].map((path) => ` ${site}/${path}${today}`) writeFileSync(resolve(outDir, 'sitemap.xml'), `\n\n${urls.join('\n')}\n\n`) From aad8784b48d1222ac8ca0dde11022e3acd920edb Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Mon, 19 Oct 2026 14:19:31 +0900 Subject: [PATCH 13/63] =?UTF-8?q?fix:=20=ED=99=88=20=EC=B2=AB=20HTML?= =?UTF-8?q?=EC=9D=98=20=EC=88=A8=EA=B8=B4=20=EC=A7=80=EC=97=AD=20=ED=8E=98?= =?UTF-8?q?=EC=9D=B4=EC=A7=80=20=EB=A7=81=ED=81=AC=20=EC=A0=9C=EA=B1=B0=20?= =?UTF-8?q?(=EC=82=AC=EB=9E=8C=EC=97=90=EA=B2=8C=20=EC=95=88=20=EB=B3=B4?= =?UTF-8?q?=EC=9D=B4=EA=B3=A0=20=EB=A1=9C=EB=B4=87=EB=A7=8C=20=EC=9D=BD?= =?UTF-8?q?=EB=8A=94=20=EB=A7=81=ED=81=AC)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/vite.config.ts | 7 ------- 1 file changed, 7 deletions(-) diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 5914352..028b03f 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -63,12 +63,6 @@ for (const r of regionPages) { }) } -/** 홈에만 넣는 시도별 지역 페이지 링크. 홈에서 지역 페이지로 바로 이어지게 한다 */ -const sidos = [...new Set(regionPages.map((r) => r.name.split(' ')[0]))] -const regionLinks = `

        지역별 오늘 날씨

        ${sidos - .map((s) => `

        ${s}

          ${regionPages.filter((r) => r.name.split(' ')[0] === s).map((r) => `
        • ${r.name}
        • `).join('')}
        `) - .join('')}` - const attr = (s: string) => s.replace(/&/g, '&').replace(/"/g, '"') function seoPages(): Plugin { @@ -98,7 +92,6 @@ function seoPages(): Plugin { mkdirSync(dirname(file), { recursive: true }) writeFileSync(file, html) } - writeFileSync(resolve(outDir, 'index.html'), base.replace('

    ', `${regionLinks}`)) const today = new Date().toISOString().slice(0, 10) const urls = ['', ...PAGES.map((p) => p.path)].map((path) => ` ${site}/${path}${today}`) writeFileSync(resolve(outDir, 'sitemap.xml'), `\n\n${urls.join('\n')}\n\n`) From 0a16c5329d696b4fe7fae5b8564b9fceb00d472c Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Mon, 19 Oct 2026 16:25:48 +0900 Subject: [PATCH 14/63] =?UTF-8?q?feat:=20=EC=A7=80=EC=97=AD=20=EB=B0=94?= =?UTF-8?q?=EA=BE=B8=EA=B8=B0=20=EB=AA=A9=EB=A1=9D=EC=9D=84=20=EC=A7=80?= =?UTF-8?q?=EC=97=AD=20=ED=8E=98=EC=9D=B4=EC=A7=80=20=EB=A7=81=ED=81=AC(a?= =?UTF-8?q?=20href)=EB=A1=9C,=20=EC=8B=9C=ED=8A=B8=EA=B0=80=20=EB=8B=AB?= =?UTF-8?q?=ED=98=80=20=EC=9E=88=EC=96=B4=EB=8F=84=20=EC=A7=80=EC=97=AD=20?= =?UTF-8?q?=ED=8E=98=EC=9D=B4=EC=A7=80=20=EB=A7=81=ED=81=AC=EB=A5=BC=20HTM?= =?UTF-8?q?L=EC=97=90=20=EB=91=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/b/Sheets.tsx | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx index 530dd3f..71ddd00 100644 --- a/frontend/src/b/Sheets.tsx +++ b/frontend/src/b/Sheets.tsx @@ -1,5 +1,6 @@ import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query' import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react' +import regionPages from '../../seo/region.json' import { setTokens, subscribeAuth } from '../api/auth' import { SITE_URL } from '../api/setup' import { @@ -133,6 +134,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void {state.type === 'region' && } )} + {!state && } ) } @@ -987,6 +989,27 @@ function MeSheet({ onDone }: { onDone: () => void }) { /* ---------- 지역 ---------- */ const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const +/** 구 코드 → 그 구가 속한 지역 페이지 주소 */ +const pageHref = (code: string) => { + const p = regionPages.find((g) => g.regions.some((r) => r.code === code)) + return p ? `/today/${p.path}` : '/' +} + +/** 지역 바꾸기가 닫혀 있을 때도 지역 페이지 링크를 HTML에 둔다 (검색 로봇이 링크를 따라가게) */ +function RegionLinks() { + return ( + + ) +} + function RegionSheet({ onDone }: { onDone: () => void }) { const { region, setRegion, locate, locateStatus } = useRegion() const { me, logout } = useAuth() @@ -1018,10 +1041,11 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
      {regions.map((r) => (
    • - +
    • ))}
    From 96cbd19c61516dc1eb497d1282353a923981024c Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Tue, 20 Oct 2026 09:35:16 +0900 Subject: [PATCH 15/63] =?UTF-8?q?feat:=20=EA=B5=AC=EB=A1=9C=20=EB=82=98?= =?UTF-8?q?=EB=89=9C=2013=EA=B0=9C=20=EC=8B=9C=EC=9D=98=20=EA=B5=AC?= =?UTF-8?q?=EB=A7=88=EB=8B=A4=20=EC=9E=90=EA=B8=B0=20=EC=A3=BC=EC=86=8C(/t?= =?UTF-8?q?oday/gyeonggi/seongnam/bundang,=2039=EC=9E=A5),=20=EA=B5=AC?= =?UTF-8?q?=EB=A5=BC=20=EA=B3=A0=EB=A5=B4=EB=A9=B4=20=EA=B5=AC=20=EC=A3=BC?= =?UTF-8?q?=EC=86=8C=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/router/v1/seo/seo.py | 8 + backend/scripts/gen_region_pages.py | 9 +- backend/tests/test_seo.py | 11 + frontend/nginx.conf | 2 +- frontend/seo/region.json | 546 ++++++++++++++++++++++++++++ frontend/src/b/Sheets.tsx | 6 +- frontend/src/b/region.tsx | 12 +- frontend/src/b/regionContext.ts | 4 + frontend/vite.config.ts | 12 +- 9 files changed, 595 insertions(+), 15 deletions(-) diff --git a/backend/router/v1/seo/seo.py b/backend/router/v1/seo/seo.py index 5b62d9d..6062a60 100644 --- a/backend/router/v1/seo/seo.py +++ b/backend/router/v1/seo/seo.py @@ -15,3 +15,11 @@ async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path if err is not ErrorType.SUCCESS: return HTMLResponse("not found", status_code=404) return HTMLResponse(html, headers={"Cache-Control": "no-cache"}) + + +@router.get("/today/{sido}/{place}/{gu}", response_class=HTMLResponse, summary="구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)") +async def get_today_gu_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), gu: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse: + err, html = await service.page(f"today/{sido}/{place}/{gu}") + if err is not ErrorType.SUCCESS: + return HTMLResponse("not found", status_code=404) + return HTMLResponse(html, headers={"Cache-Control": "no-cache"}) diff --git a/backend/scripts/gen_region_pages.py b/backend/scripts/gen_region_pages.py index 2d0f6fa..485020f 100644 --- a/backend/scripts/gen_region_pages.py +++ b/backend/scripts/gen_region_pages.py @@ -24,6 +24,9 @@ R = '''종로 jongno 중 jung 용산 yongsan 성동 seongdong 광진 gwangjin 춘천 chuncheon 원주 wonju 강릉 gangneung 동해 donghae 태백 taebaek 속초 sokcho 삼척 samcheok 홍천 hongcheon 횡성 hoengseong 영월 yeongwol 평창 pyeongchang 정선 jeongseon 철원 cheorwon 화천 hwacheon 양구 yanggu 인제 inje 양양 yangyang 전주 jeonju 군산 gunsan 익산 iksan 정읍 jeongeup 남원 namwon 김제 gimje 완주 wanju 진안 jinan 무주 muju 장수 jangsu 임실 imsil 순창 sunchang 고창 gochang 부안 buan'''.split() ROMAN = dict(zip(R[::2], R[1::2])) +G = '''장안 jangan 권선 gwonseon 팔달 paldal 영통 yeongtong 수정 sujeong 중원 jungwon 분당 bundang 만안 manan 동안 dongan 원미 wonmi 소사 sosa 오정 ojeong 상록 sangnok 단원 danwon 덕양 deogyang 일산동 ilsandong 일산서 ilsanseo 처인 cheoin 기흥 giheung 수지 suji +만세 manse 효행 hyohaeng 병점 byeongjeom 동탄 dongtan 상당 sangdang 서원 seowon 흥덕 heungdeok 청원 cheongwon 동남 dongnam 서북 seobuk 남 nam 북 buk 의창 uichang 성산 seongsan 마산합포 masanhappo 마산회원 masanhoewon 진해 jinhae 완산 wansan 덕진 deokjin'''.split() +GU = dict(zip(G[::2], G[1::2])) # 구로 나뉜 시는 시청이 있는 구를 먼저 보여 준다 CITY_MAIN = {'수원시': '팔달구', '성남시': '중원구', '안양시': '동안구', '부천시': '원미구', '안산시': '단원구', '고양시': '덕양구', '용인시': '처인구', '화성시': '만세구', '청주시': '상당구', '천안시': '서북구', '포항시': '남구', '창원시': '의창구', '전주시': '완산구'} pages = {} @@ -36,8 +39,12 @@ for row in csv.DictReader(open(SRC, encoding='utf-8')): p['regions'].append(r) if len(rest) == 1 or CITY_MAIN[place] == rest[1]: p['main'] = r['code'] + # 구로 나뉜 시의 구도 자기 주소를 갖는다: /today/gyeonggi/seongnam/bundang + if len(rest) == 2: + gu = f"{path}/{GU[rest[1][:-1]]}" + pages[gu] = dict(path=gu, name=row['name'], main=r['code'], regions=[r]) out = list(pages.values()) assert all(p['main'] for p in out), [p['path'] for p in out if not p['main']] -assert sum(len(p['regions']) for p in out) == 256 +assert sum(len(p['regions']) for p in out if p['path'].count('/') == 1) == 256 json.dump(out, open(OUT, 'w', encoding='utf-8'), ensure_ascii=False, indent=1) print(len(out), 'pages', sum(len(p['regions']) > 1 for p in out), 'cities') diff --git a/backend/tests/test_seo.py b/backend/tests/test_seo.py index 0923896..b64ef02 100644 --- a/backend/tests/test_seo.py +++ b/backend/tests/test_seo.py @@ -65,3 +65,14 @@ async def test_today_page_fills_real_feed(offline, monkeypatch): assert page.status_code == 200 and "

    서울 중구 오늘 날씨, 뭐 할까?

    최저 " in page.text and "지금 20°" in page.text assert "해 지는 시각 오후" in page.text and "

    1. " in page.text assert missing.status_code == 404 + + +@pytest.mark.anyio +async def test_gu_page_of_city_has_its_own_address(offline, monkeypatch): + async def template(self, path): + return TEMPLATE if path == "today/gyeonggi/seongnam/bundang" else None + + monkeypatch.setattr(SeoService, "template", template) + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + page = await client.get("/v1/seo/today/gyeonggi/seongnam/bundang") + assert page.status_code == 200 and "지금 20°" in page.text diff --git a/frontend/nginx.conf b/frontend/nginx.conf index 186c17a..c5ce3d5 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -32,7 +32,7 @@ server { } # 지역 검색 페이지: 백엔드가 정적 HTML(today/…/….html)에 오늘 날씨를 채워 준다. 백엔드가 안 되면 정적 HTML 그대로 - location ~ ^/today/[a-z]+/[a-z]+$ { + location ~ ^/today/[a-z]+/[a-z]+(/[a-z]+)?$ { resolver 127.0.0.11 valid=10s ipv6=off; set $api http://backend:9800; proxy_pass $api/v1/seo$uri; diff --git a/frontend/seo/region.json b/frontend/seo/region.json index 1238af7..121335a 100644 --- a/frontend/seo/region.json +++ b/frontend/seo/region.json @@ -1420,6 +1420,62 @@ } ] }, + { + "path": "gyeonggi/suwon/jangan", + "name": "경기 수원시 장안구", + "main": "4111100000", + "regions": [ + { + "code": "4111100000", + "name": "경기 수원시 장안구", + "short_name": "수원시 장안구", + "lat": 37.30101, + "lon": 127.01222 + } + ] + }, + { + "path": "gyeonggi/suwon/gwonseon", + "name": "경기 수원시 권선구", + "main": "4111300000", + "regions": [ + { + "code": "4111300000", + "name": "경기 수원시 권선구", + "short_name": "수원시 권선구", + "lat": 37.25473, + "lon": 126.97407 + } + ] + }, + { + "path": "gyeonggi/suwon/paldal", + "name": "경기 수원시 팔달구", + "main": "4111500000", + "regions": [ + { + "code": "4111500000", + "name": "경기 수원시 팔달구", + "short_name": "수원시 팔달구", + "lat": 37.2831, + "lon": 127.03783 + } + ] + }, + { + "path": "gyeonggi/suwon/yeongtong", + "name": "경기 수원시 영통구", + "main": "4111700000", + "regions": [ + { + "code": "4111700000", + "name": "경기 수원시 영통구", + "short_name": "수원시 영통구", + "lat": 37.25631, + "lon": 127.04863 + } + ] + }, { "path": "gyeonggi/seongnam", "name": "경기 성남시", @@ -1448,6 +1504,48 @@ } ] }, + { + "path": "gyeonggi/seongnam/sujeong", + "name": "경기 성남시 수정구", + "main": "4113100000", + "regions": [ + { + "code": "4113100000", + "name": "경기 성남시 수정구", + "short_name": "성남시 수정구", + "lat": 37.44749, + "lon": 127.14772 + } + ] + }, + { + "path": "gyeonggi/seongnam/jungwon", + "name": "경기 성남시 중원구", + "main": "4113300000", + "regions": [ + { + "code": "4113300000", + "name": "경기 성남시 중원구", + "short_name": "성남시 중원구", + "lat": 37.42767, + "lon": 127.13942 + } + ] + }, + { + "path": "gyeonggi/seongnam/bundang", + "name": "경기 성남시 분당구", + "main": "4113500000", + "regions": [ + { + "code": "4113500000", + "name": "경기 성남시 분당구", + "short_name": "성남시 분당구", + "lat": 37.37997, + "lon": 127.12102 + } + ] + }, { "path": "gyeonggi/uijeongbu", "name": "경기 의정부시", @@ -1483,6 +1581,34 @@ } ] }, + { + "path": "gyeonggi/anyang/manan", + "name": "경기 안양시 만안구", + "main": "4117100000", + "regions": [ + { + "code": "4117100000", + "name": "경기 안양시 만안구", + "short_name": "안양시 만안구", + "lat": 37.38378, + "lon": 126.9345 + } + ] + }, + { + "path": "gyeonggi/anyang/dongan", + "name": "경기 안양시 동안구", + "main": "4117300000", + "regions": [ + { + "code": "4117300000", + "name": "경기 안양시 동안구", + "short_name": "안양시 동안구", + "lat": 37.3897, + "lon": 126.95336 + } + ] + }, { "path": "gyeonggi/bucheon", "name": "경기 부천시", @@ -1511,6 +1637,48 @@ } ] }, + { + "path": "gyeonggi/bucheon/wonmi", + "name": "경기 부천시 원미구", + "main": "4119200000", + "regions": [ + { + "code": "4119200000", + "name": "경기 부천시 원미구", + "short_name": "부천시 원미구", + "lat": 37.49659, + "lon": 126.787 + } + ] + }, + { + "path": "gyeonggi/bucheon/sosa", + "name": "경기 부천시 소사구", + "main": "4119400000", + "regions": [ + { + "code": "4119400000", + "name": "경기 부천시 소사구", + "short_name": "부천시 소사구", + "lat": 37.48004, + "lon": 126.79994 + } + ] + }, + { + "path": "gyeonggi/bucheon/ojeong", + "name": "경기 부천시 오정구", + "main": "4119600000", + "regions": [ + { + "code": "4119600000", + "name": "경기 부천시 오정구", + "short_name": "부천시 오정구", + "lat": 37.52835, + "lon": 126.79581 + } + ] + }, { "path": "gyeonggi/gwangmyeong", "name": "경기 광명시", @@ -1574,6 +1742,34 @@ } ] }, + { + "path": "gyeonggi/ansan/sangnok", + "name": "경기 안산시 상록구", + "main": "4127100000", + "regions": [ + { + "code": "4127100000", + "name": "경기 안산시 상록구", + "short_name": "안산시 상록구", + "lat": 37.29852, + "lon": 126.84682 + } + ] + }, + { + "path": "gyeonggi/ansan/danwon", + "name": "경기 안산시 단원구", + "main": "4127300000", + "regions": [ + { + "code": "4127300000", + "name": "경기 안산시 단원구", + "short_name": "안산시 단원구", + "lat": 37.31673, + "lon": 126.81442 + } + ] + }, { "path": "gyeonggi/goyang", "name": "경기 고양시", @@ -1602,6 +1798,48 @@ } ] }, + { + "path": "gyeonggi/goyang/deogyang", + "name": "경기 고양시 덕양구", + "main": "4128100000", + "regions": [ + { + "code": "4128100000", + "name": "경기 고양시 덕양구", + "short_name": "고양시 덕양구", + "lat": 37.63458, + "lon": 126.8342 + } + ] + }, + { + "path": "gyeonggi/goyang/ilsandong", + "name": "경기 고양시 일산동구", + "main": "4128500000", + "regions": [ + { + "code": "4128500000", + "name": "경기 고양시 일산동구", + "short_name": "고양시 일산동구", + "lat": 37.65591, + "lon": 126.77706 + } + ] + }, + { + "path": "gyeonggi/goyang/ilsanseo", + "name": "경기 고양시 일산서구", + "main": "4128700000", + "regions": [ + { + "code": "4128700000", + "name": "경기 고양시 일산서구", + "short_name": "고양시 일산서구", + "lat": 37.67249, + "lon": 126.75278 + } + ] + }, { "path": "gyeonggi/gwacheon", "name": "경기 과천시", @@ -1742,6 +1980,48 @@ } ] }, + { + "path": "gyeonggi/yongin/cheoin", + "name": "경기 용인시 처인구", + "main": "4146100000", + "regions": [ + { + "code": "4146100000", + "name": "경기 용인시 처인구", + "short_name": "용인시 처인구", + "lat": 37.23148, + "lon": 127.20384 + } + ] + }, + { + "path": "gyeonggi/yongin/giheung", + "name": "경기 용인시 기흥구", + "main": "4146300000", + "regions": [ + { + "code": "4146300000", + "name": "경기 용인시 기흥구", + "short_name": "용인시 기흥구", + "lat": 37.2776, + "lon": 127.11679 + } + ] + }, + { + "path": "gyeonggi/yongin/suji", + "name": "경기 용인시 수지구", + "main": "4146500000", + "regions": [ + { + "code": "4146500000", + "name": "경기 용인시 수지구", + "short_name": "용인시 수지구", + "lat": 37.31939, + "lon": 127.1001 + } + ] + }, { "path": "gyeonggi/paju", "name": "경기 파주시", @@ -1833,6 +2113,62 @@ } ] }, + { + "path": "gyeonggi/hwaseong/manse", + "name": "경기 화성시 만세구", + "main": "4159100000", + "regions": [ + { + "code": "4159100000", + "name": "경기 화성시 만세구", + "short_name": "화성시 만세구", + "lat": 37.1377, + "lon": 126.92566 + } + ] + }, + { + "path": "gyeonggi/hwaseong/hyohaeng", + "name": "경기 화성시 효행구", + "main": "4159300000", + "regions": [ + { + "code": "4159300000", + "name": "경기 화성시 효행구", + "short_name": "화성시 효행구", + "lat": 37.20918, + "lon": 126.95915 + } + ] + }, + { + "path": "gyeonggi/hwaseong/byeongjeom", + "name": "경기 화성시 병점구", + "main": "4159500000", + "regions": [ + { + "code": "4159500000", + "name": "경기 화성시 병점구", + "short_name": "화성시 병점구", + "lat": 37.20875, + "lon": 127.0359 + } + ] + }, + { + "path": "gyeonggi/hwaseong/dongtan", + "name": "경기 화성시 동탄구", + "main": "4159700000", + "regions": [ + { + "code": "4159700000", + "name": "경기 화성시 동탄구", + "short_name": "화성시 동탄구", + "lat": 37.19724, + "lon": 127.09687 + } + ] + }, { "path": "gyeonggi/gwangju", "name": "경기 광주시", @@ -1966,6 +2302,62 @@ } ] }, + { + "path": "chungbuk/cheongju/sangdang", + "name": "충북 청주시 상당구", + "main": "4311100000", + "regions": [ + { + "code": "4311100000", + "name": "충북 청주시 상당구", + "short_name": "청주시 상당구", + "lat": 36.584, + "lon": 127.51173 + } + ] + }, + { + "path": "chungbuk/cheongju/seowon", + "name": "충북 청주시 서원구", + "main": "4311200000", + "regions": [ + { + "code": "4311200000", + "name": "충북 청주시 서원구", + "short_name": "청주시 서원구", + "lat": 36.63726, + "lon": 127.48329 + } + ] + }, + { + "path": "chungbuk/cheongju/heungdeok", + "name": "충북 청주시 흥덕구", + "main": "4311300000", + "regions": [ + { + "code": "4311300000", + "name": "충북 청주시 흥덕구", + "short_name": "청주시 흥덕구", + "lat": 36.6182, + "lon": 127.35942 + } + ] + }, + { + "path": "chungbuk/cheongju/cheongwon", + "name": "충북 청주시 청원구", + "main": "4311400000", + "regions": [ + { + "code": "4311400000", + "name": "충북 청주시 청원구", + "short_name": "청주시 청원구", + "lat": 36.64431, + "lon": 127.48766 + } + ] + }, { "path": "chungbuk/chungju", "name": "충북 충주시", @@ -2127,6 +2519,34 @@ } ] }, + { + "path": "chungnam/cheonan/dongnam", + "name": "충남 천안시 동남구", + "main": "4413100000", + "regions": [ + { + "code": "4413100000", + "name": "충남 천안시 동남구", + "short_name": "천안시 동남구", + "lat": 36.80412, + "lon": 127.15247 + } + ] + }, + { + "path": "chungnam/cheonan/seobuk", + "name": "충남 천안시 서북구", + "main": "4413300000", + "regions": [ + { + "code": "4413300000", + "name": "충남 천안시 서북구", + "short_name": "천안시 서북구", + "lat": 36.87556, + "lon": 127.1572 + } + ] + }, { "path": "chungnam/gongju", "name": "충남 공주시", @@ -2344,6 +2764,34 @@ } ] }, + { + "path": "gyeongbuk/pohang/nam", + "name": "경북 포항시 남구", + "main": "4711100000", + "regions": [ + { + "code": "4711100000", + "name": "경북 포항시 남구", + "short_name": "포항시 남구", + "lat": 36.00569, + "lon": 129.36167 + } + ] + }, + { + "path": "gyeongbuk/pohang/buk", + "name": "경북 포항시 북구", + "main": "4711300000", + "regions": [ + { + "code": "4711300000", + "name": "경북 포항시 북구", + "short_name": "포항시 북구", + "lat": 36.03885, + "lon": 129.36791 + } + ] + }, { "path": "gyeongbuk/gyeongju", "name": "경북 경주시", @@ -2680,6 +3128,76 @@ } ] }, + { + "path": "gyeongnam/changwon/uichang", + "name": "경남 창원시 의창구", + "main": "4812100000", + "regions": [ + { + "code": "4812100000", + "name": "경남 창원시 의창구", + "short_name": "창원시 의창구", + "lat": 35.254, + "lon": 128.64015 + } + ] + }, + { + "path": "gyeongnam/changwon/seongsan", + "name": "경남 창원시 성산구", + "main": "4812300000", + "regions": [ + { + "code": "4812300000", + "name": "경남 창원시 성산구", + "short_name": "창원시 성산구", + "lat": 35.19838, + "lon": 128.70294 + } + ] + }, + { + "path": "gyeongnam/changwon/masanhappo", + "name": "경남 창원시 마산합포구", + "main": "4812500000", + "regions": [ + { + "code": "4812500000", + "name": "경남 창원시 마산합포구", + "short_name": "창원시 마산합포구", + "lat": 35.19687, + "lon": 128.56786 + } + ] + }, + { + "path": "gyeongnam/changwon/masanhoewon", + "name": "경남 창원시 마산회원구", + "main": "4812700000", + "regions": [ + { + "code": "4812700000", + "name": "경남 창원시 마산회원구", + "short_name": "창원시 마산회원구", + "lat": 35.22093, + "lon": 128.57971 + } + ] + }, + { + "path": "gyeongnam/changwon/jinhae", + "name": "경남 창원시 진해구", + "main": "4812900000", + "regions": [ + { + "code": "4812900000", + "name": "경남 창원시 진해구", + "short_name": "창원시 진해구", + "lat": 35.13306, + "lon": 128.71008 + } + ] + }, { "path": "gyeongnam/jinju", "name": "경남 진주시", @@ -3219,6 +3737,34 @@ } ] }, + { + "path": "jeonbuk/jeonju/wansan", + "name": "전북 전주시 완산구", + "main": "5211100000", + "regions": [ + { + "code": "5211100000", + "name": "전북 전주시 완산구", + "short_name": "전주시 완산구", + "lat": 35.80919, + "lon": 127.12192 + } + ] + }, + { + "path": "jeonbuk/jeonju/deokjin", + "name": "전북 전주시 덕진구", + "main": "5211300000", + "regions": [ + { + "code": "5211300000", + "name": "전북 전주시 덕진구", + "short_name": "전주시 덕진구", + "lat": 35.82639, + "lon": 127.13642 + } + ] + }, { "path": "jeonbuk/gunsan", "name": "전북 군산시", diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx index 71ddd00..4a93525 100644 --- a/frontend/src/b/Sheets.tsx +++ b/frontend/src/b/Sheets.tsx @@ -25,7 +25,7 @@ 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 { useRegion } from './regionContext' +import { ownPage, useRegion } from './regionContext' import { useSky } from './skyContext' import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage' import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext' @@ -989,9 +989,9 @@ function MeSheet({ onDone }: { onDone: () => void }) { /* ---------- 지역 ---------- */ const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const -/** 구 코드 → 그 구가 속한 지역 페이지 주소 */ +/** 구 코드 → 그 구의 지역 페이지 주소 */ const pageHref = (code: string) => { - const p = regionPages.find((g) => g.regions.some((r) => r.code === code)) + const p = ownPage(code) return p ? `/today/${p.path}` : '/' } diff --git a/frontend/src/b/region.tsx b/frontend/src/b/region.tsx index 9760d06..d5048c1 100644 --- a/frontend/src/b/region.tsx +++ b/frontend/src/b/region.tsx @@ -1,19 +1,19 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' -import { matchPath, useLocation, useNavigate } from 'react-router' +import { useLocation, useNavigate } from 'react-router' import regionPages from '../../seo/region.json' import { nearestRegion } from '../api/client/sdk.gen' import type { RegionData } from '../api/client/types.gen' import { track } from '../lib/analytics' -import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext' +import { DEFAULT_REGION, ownPage, RegionContext, type LocateStatus } from './regionContext' const KEY = 'nalssigak.b.region' type RegionPage = (typeof regionPages)[number] -/** /today/gyeonggi/seongnam 같은 지역 페이지 주소면 그 페이지 */ +/** /today/gyeonggi/seongnam, /today/gyeonggi/seongnam/bundang 같은 지역 페이지 주소면 그 페이지 */ function pageOf(pathname: string): RegionPage | undefined { - const m = matchPath('/today/:sido/:place', pathname) - return m ? regionPages.find((p) => p.path === `${m.params.sido}/${m.params.place}`) : undefined + const path = pathname.match(/^\/today\/([a-z]+\/[a-z]+(?:\/[a-z]+)?)\/?$/)?.[1] + return path ? regionPages.find((p) => p.path === path) : undefined } /** 지역 페이지 안의 구: 구로 나뉜 시는 r 이 그 시 안이면 r, 아니면 시청이 있는 구 */ @@ -60,7 +60,7 @@ export function RegionProvider({ children }: { children: ReactNode }) { const setRegion = useCallback((r: RegionData) => { setRegionState(r) writeStored(r) - const next = regionPages.find((p) => p.regions.some((g) => g.code === r.code)) + const next = ownPage(r.code) if (pageRef.current && next && next !== pageRef.current) navigate(`/today/${next.path}`) }, [navigate]) diff --git a/frontend/src/b/regionContext.ts b/frontend/src/b/regionContext.ts index 52c840b..3039bc5 100644 --- a/frontend/src/b/regionContext.ts +++ b/frontend/src/b/regionContext.ts @@ -1,4 +1,5 @@ import { createContext, use } from 'react' +import regionPages from '../../seo/region.json' import type { RegionData } from '../api/client/types.gen' export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error' @@ -7,6 +8,9 @@ export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void export const DEFAULT_REGION: RegionData = { code: '1144000000', name: '서울 마포구', short_name: '마포구', lat: 37.56071, lon: 126.91053 } +/** 구 하나만 보여 주는 지역 페이지: 일반 시군구, 또는 구로 나뉜 시의 구 페이지 */ +export const ownPage = (code: string) => regionPages.find((p) => p.regions.length === 1 && p.regions[0].code === code) + export const RegionContext = createContext(null) export function useRegion() { diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 028b03f..a92b74f 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -44,11 +44,15 @@ const headName = (name: string) => name.split(' ').at(-1)! /** 검색어로 많이 치는 꼴: 성남시 → 성남. 중구처럼 두 글자는 그대로 */ const bareName = (name: string) => (name.length > 2 ? name.slice(0, -1) : name) -/** 지역마다 한 장: /today/gyeonggi/seongnam. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */ +/** 지역마다 한 장: /today/gyeonggi/seongnam, 구로 나뉜 시의 구는 /today/gyeonggi/seongnam/bundang. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */ for (const r of regionPages) { const sido = r.path.split('/')[0] - const near = regionPages.filter((o) => o !== r && o.path.startsWith(`${sido}/`)) - const parts = r.regions.length > 1 ? `

      ${r.name}는 ${r.regions.map((g) => g.name.split(' ').at(-1)).join(', ')}별로 따로 계산해요.

      ` : '' + const city = r.path.split('/').slice(0, 2).join('/') + const isGu = r.path !== city + const gus = regionPages.filter((o) => o.path.startsWith(`${r.path}/`)) + // 시도의 다른 시군구 + 같은 시의 다른 구 + const near = regionPages.filter((o) => o !== r && o.path.startsWith(`${sido}/`) && (o.path.split('/').length === 2 || (isGu && o.path.startsWith(`${city}/`)))) + const parts = gus.length ? `

      ${r.name}는 ${gus.map((g) => `${headName(g.name)}`).join(', ')}별로 따로 계산해요.

      ` : '' const head = headName(r.name) const bare = bareName(head) const guNames = r.regions.length > 1 ? r.regions.map((g) => g.name.split(' ').at(-1)!) : [] @@ -57,7 +61,7 @@ for (const r of regionPages) { path: `today/${r.path}`, code: r.main, keywords, - title: `${headName(r.name)} 오늘 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[0]}` : ''} | 날씨각`, + title: `${headName(r.name)} 오늘 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[isGu ? 1 : 0]}` : ''} | 날씨각`, description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`, body: `

      ${r.name} 오늘 날씨, 뭐 할까?

      ${bare} 날씨, 오늘 ${head}에서는 뭐 하기 좋을까요? ${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.

      ${parts}

      세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.

      ${near.length ? `

      ${r.name.split(' ')[0]} 다른 지역 날씨

      ` : ''}`, }) From a8a126f6a5d7a99a64c29d0f490b7f4913873f0e Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Tue, 20 Oct 2026 11:37:40 +0900 Subject: [PATCH 16/63] =?UTF-8?q?feat:=20=EB=82=98=EB=A7=8C=EC=9D=98=20?= =?UTF-8?q?=EA=B0=81=201=EB=8B=A8=EA=B3=84=20=E2=80=94=20=EA=B3=B5?= =?UTF-8?q?=EC=8B=9D=20=EA=B0=81=20=EB=91=90=20=EA=B0=9C=EB=A5=BC=20?= =?UTF-8?q?=EC=84=9E=EC=96=B4=20=EB=82=B4=20=EA=B0=81=20=EB=A7=8C=EB=93=A4?= =?UTF-8?q?=EA=B8=B0(=EC=A0=90=EC=88=98=EB=8A=94=20=EB=82=AE=EC=9D=80=20?= =?UTF-8?q?=EC=AA=BD),=20=EB=A1=9C=EA=B7=B8=EC=9D=B8=20=EC=97=86=EC=9D=B4?= =?UTF-8?q?=201=EA=B0=9C=C2=B7=EB=A1=9C=EA=B7=B8=EC=9D=B8=ED=95=98?= =?UTF-8?q?=EB=A9=B4=20=EA=B3=84=EC=A0=95=20=EC=A0=80=EC=9E=A5,=20?= =?UTF-8?q?=EC=B9=9C=EA=B5=AC=EC=97=90=EA=B2=8C=20=EB=B3=B4=EB=82=B8=20?= =?UTF-8?q?=EB=A7=81=ED=81=AC=EB=A1=9C=20=EB=82=B4=20=EB=8F=99=EB=84=A4=20?= =?UTF-8?q?=EC=A0=90=EC=88=98=20=EB=B3=B4=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/common/database/model/models.py | 10 + backend/crud/my_gak_crud.py | 24 ++ backend/postgres-init/init.sql | 11 + backend/router/router.py | 2 + backend/router/v1/my_gak/__init__.py | 0 backend/router/v1/my_gak/my_gak.py | 41 +++ backend/router/v1/my_gak/protocol.py | 23 ++ backend/services/my_gak_service.py | 48 ++++ backend/tests/test_my_gak.py | 59 +++++ .../api/client/@tanstack/react-query.gen.ts | 92 ++++++- frontend/src/api/client/index.ts | 4 +- frontend/src/api/client/sdk.gen.ts | 34 ++- frontend/src/api/client/types.gen.ts | 240 ++++++++++++++++++ frontend/src/b/Sheets.tsx | 12 +- frontend/src/b/TodayPage.tsx | 13 + frontend/src/b/myGak.tsx | 135 ++++++++++ frontend/src/b/myGakState.ts | 99 ++++++++ frontend/src/b/sheetContext.ts | 1 + 18 files changed, 842 insertions(+), 6 deletions(-) create mode 100644 backend/crud/my_gak_crud.py create mode 100644 backend/router/v1/my_gak/__init__.py create mode 100644 backend/router/v1/my_gak/my_gak.py create mode 100644 backend/router/v1/my_gak/protocol.py create mode 100644 backend/services/my_gak_service.py create mode 100644 backend/tests/test_my_gak.py create mode 100644 frontend/src/b/myGak.tsx create mode 100644 frontend/src/b/myGakState.ts 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 } From 798286d975eeeeee3a4f63d4fc7050cb6b2ea316 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Tue, 20 Oct 2026 13:11:20 +0900 Subject: [PATCH 17/63] =?UTF-8?q?feat:=20=EB=8F=99=EB=84=A4=20=EC=9D=B4?= =?UTF-8?q?=EC=95=BC=EA=B8=B0=20=E2=80=94=20=EB=A1=9C=EA=B7=B8=EC=9D=B8?= =?UTF-8?q?=ED=95=98=EB=A9=B4=20100=EC=9E=90=20=EA=B8=80=20=EC=93=B0?= =?UTF-8?q?=EA=B8=B0(=EC=93=B8=20=EB=95=8C=20=EB=8F=99=EB=84=A4=20?= =?UTF-8?q?=EB=82=A0=EC=94=A8=EA=B0=80=20=EB=B6=99=EC=9D=8C,=20=EC=A0=84?= =?UTF-8?q?=EA=B5=AD=EC=97=90=20=EB=B3=B4=EC=9E=84),=20=EC=A2=8B=EC=95=84?= =?UTF-8?q?=EC=9A=94=C2=B7=EC=8B=A0=EA=B3=A0=203=EA=B1=B4=20=EC=9E=90?= =?UTF-8?q?=EB=8F=99=20=EC=88=A8=EA=B9=80=C2=B7=EC=9D=B4=20=EC=82=AC?= =?UTF-8?q?=EB=9E=8C=20=EA=B8=80=20=EC=95=88=20=EB=B3=B4=EA=B8=B0=C2=B7?= =?UTF-8?q?=EB=82=B4=20=EA=B8=80=20=EC=A7=80=EC=9A=B0=EA=B8=B0,=20?= =?UTF-8?q?=EB=A7=81=ED=81=AC=C2=B7=EC=A0=84=ED=99=94=EB=B2=88=ED=98=B8=20?= =?UTF-8?q?=EB=A7=89=EA=B8=B0=EC=99=80=20=ED=95=98=EB=A3=A8=205=EA=B0=9C?= =?UTF-8?q?=20=EC=A0=9C=ED=95=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/common/database/model/models.py | 40 ++ backend/common/enums.py | 9 + backend/crud/talk_crud.py | 65 +++ backend/postgres-init/init.sql | 39 ++ backend/router/router.py | 2 + backend/router/v1/talk/__init__.py | 0 backend/router/v1/talk/protocol.py | 45 ++ backend/router/v1/talk/talk.py | 67 +++ backend/services/talk_service.py | 129 ++++++ backend/tests/test_talk.py | 89 ++++ .../api/client/@tanstack/react-query.gen.ts | 154 ++++++- frontend/src/api/client/index.ts | 4 +- frontend/src/api/client/sdk.gen.ts | 51 ++- frontend/src/api/client/types.gen.ts | 405 ++++++++++++++++++ frontend/src/b/Sheets.tsx | 4 +- frontend/src/b/TodayPage.tsx | 2 + frontend/src/b/sheetContext.ts | 1 + frontend/src/b/talk.tsx | 256 +++++++++++ 18 files changed, 1356 insertions(+), 6 deletions(-) create mode 100644 backend/crud/talk_crud.py create mode 100644 backend/router/v1/talk/__init__.py create mode 100644 backend/router/v1/talk/protocol.py create mode 100644 backend/router/v1/talk/talk.py create mode 100644 backend/services/talk_service.py create mode 100644 backend/tests/test_talk.py create mode 100644 frontend/src/b/talk.tsx diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index 4895e83..c85de53 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -372,3 +372,43 @@ class MyGak(Base): 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()) + + +class Talk(Base): + __tablename__ = "talk" + + talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True)) + region_code: Mapped[str] = mapped_column(String(10)) + body: Mapped[str] = mapped_column(String(100)) + weather: Mapped[Optional[str]] = mapped_column(String(30), nullable=True) + like_count: Mapped[int] = mapped_column(Integer, default=0) + report_count: Mapped[int] = mapped_column(Integer, default=0) + hidden: Mapped[bool] = mapped_column(Boolean, default=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + deleted: Mapped[bool] = mapped_column(Boolean, default=False) + + +class TalkLike(Base): + __tablename__ = "talk_like" + + talk_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 TalkReport(Base): + __tablename__ = "talk_report" + + talk_id: Mapped[int] = mapped_column(BigInteger, primary_key=True) + user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) + reason: Mapped[int] = mapped_column(SmallInteger) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + + +class UserBlock(Base): + __tablename__ = "user_block" + + user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True) + blocked_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()) diff --git a/backend/common/enums.py b/backend/common/enums.py index 19d43ec..09d5a97 100644 --- a/backend/common/enums.py +++ b/backend/common/enums.py @@ -19,6 +19,8 @@ class ErrorType(Enum): EXTERNAL_API_ERROR = 2001 NOT_FOUND = 3001 INVALID_INPUT = 3002 + DAILY_LIMIT = 3003 # 하루에 쓸 수 있는 수를 넘음 + LINK_NOT_ALLOWED = 3004 # 글에 링크·전화번호 AUTH_REQUIRED = 4001 AUTH_FAILED = 4002 AUTH_DUPLICATE_ID = 4003 @@ -113,6 +115,13 @@ class IndexCategory(CodeEnum): LIFE = 4 +class TalkReport(CodeEnum): + ABUSE = 1 # 욕설·비하 + SPAM = 2 # 광고·도배 + PRIVACY = 3 # 개인정보 노출 + ETC = 4 + + class ArticleCategory(CodeEnum): SEASON = 1 TIP = 2 diff --git a/backend/crud/talk_crud.py b/backend/crud/talk_crud.py new file mode 100644 index 0000000..dc681a8 --- /dev/null +++ b/backend/crud/talk_crud.py @@ -0,0 +1,65 @@ +import uuid +from datetime import datetime +from typing import Optional + +from sqlalchemy import delete, func, select, update +from sqlalchemy.dialects.postgresql import insert +from sqlalchemy.ext.asyncio import AsyncSession + +from common.database.model.models import Region, Talk, TalkLike, TalkReport, User, UserBlock + + +class TalkCRUD: + async def page(self, s: AsyncSession, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Talk, User, Optional[str]]]: + """최신 글부터. 숨김·지운 글과 내가 안 보기로 한 사람의 글은 뺀다.""" + stmt = ( + select(Talk, User, Region.short_name) + .join(User, User.user_id == Talk.user_id) + .outerjoin(Region, Region.code == Talk.region_code) + .where(Talk.deleted.is_(False), Talk.hidden.is_(False), User.deleted.is_(False)) + ) + if viewer is not None: + stmt = stmt.where(Talk.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer))) + if cursor is not None: + stmt = stmt.where(Talk.talk_id < cursor) + return list((await s.execute(stmt.order_by(Talk.talk_id.desc()).limit(limit))).all()) + + async def liked(self, s: AsyncSession, user_id: uuid.UUID, talk_ids: list[int]) -> set[int]: + return set((await s.scalars(select(TalkLike.talk_id).where(TalkLike.user_id == user_id, TalkLike.talk_id.in_(talk_ids)))).all()) + + async def count_since(self, s: AsyncSession, user_id: uuid.UUID, since: datetime) -> int: + return await s.scalar(select(func.count()).select_from(Talk).where(Talk.user_id == user_id, Talk.created_at >= since)) + + async def add(self, s: AsyncSession, user_id: uuid.UUID, region_code: str, body: str, weather: Optional[str]) -> Talk: + t = Talk(user_id=user_id, region_code=region_code, body=body, weather=weather) + s.add(t) + await s.flush() + await s.refresh(t) + return t + + async def get(self, s: AsyncSession, talk_id: int) -> Optional[Talk]: + return await s.scalar(select(Talk).where(Talk.talk_id == talk_id, Talk.deleted.is_(False))) + + async def delete(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID) -> bool: + res = await s.execute(update(Talk).where(Talk.talk_id == talk_id, Talk.user_id == user_id, Talk.deleted.is_(False)).values(deleted=True).returning(Talk.talk_id)) + return res.first() is not None + + async def toggle_like(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID, on: bool) -> int: + """좋아요를 켜거나 끄고, 실제로 바뀌었을 때만 수를 고친다. 바뀐 뒤 좋아요 수를 돌려준다.""" + if on: + res = await s.execute(insert(TalkLike).values(talk_id=talk_id, user_id=user_id).on_conflict_do_nothing().returning(TalkLike.talk_id)) + else: + res = await s.execute(delete(TalkLike).where(TalkLike.talk_id == talk_id, TalkLike.user_id == user_id).returning(TalkLike.talk_id)) + if res.first() is not None: + await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(like_count=Talk.like_count + (1 if on else -1))) + return await s.scalar(select(Talk.like_count).where(Talk.talk_id == talk_id)) + + async def report(self, s: AsyncSession, talk_id: int, user_id: uuid.UUID, reason: int, hide_at: int) -> None: + """한 사람은 한 번만 센다. hide_at 건이 되면 숨긴다.""" + res = await s.execute(insert(TalkReport).values(talk_id=talk_id, user_id=user_id, reason=reason).on_conflict_do_nothing().returning(TalkReport.talk_id)) + if res.first() is None: + return + await s.execute(update(Talk).where(Talk.talk_id == talk_id).values(report_count=Talk.report_count + 1, hidden=Talk.report_count + 1 >= hide_at)) + + async def block(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> None: + await s.execute(insert(UserBlock).values(user_id=user_id, blocked_id=blocked_id).on_conflict_do_nothing()) diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql index 2447543..34e1094 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -259,6 +259,45 @@ CREATE TABLE IF NOT EXISTS public.my_gak ( ); CREATE UNIQUE INDEX IF NOT EXISTS uq_my_gak ON public.my_gak (user_id, index_a, index_b); +-- 동네 이야기: 사용자가 쓴 짧은 글(전국에 보임). 쓸 때의 동네 날씨를 함께 남긴다 +CREATE TABLE IF NOT EXISTS public.talk ( + talk_id BIGSERIAL PRIMARY KEY, + user_id UUID NOT NULL, + region_code VARCHAR(10) NOT NULL, + body VARCHAR(100) NOT NULL, + weather VARCHAR(30), -- 쓸 때 날씨 한 줄 (예: 18° 맑음) + like_count INTEGER NOT NULL DEFAULT 0, + report_count INTEGER NOT NULL DEFAULT 0, -- 로그인한 사람의 신고만 센다 + hidden BOOLEAN NOT NULL DEFAULT FALSE, -- 신고가 쌓이면 자동으로 숨김 + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + deleted BOOLEAN NOT NULL DEFAULT FALSE +); +CREATE INDEX IF NOT EXISTS idx_talk_list ON public.talk (talk_id DESC) WHERE deleted = FALSE AND hidden = FALSE; +CREATE INDEX IF NOT EXISTS idx_talk_user_day ON public.talk (user_id, created_at); + +CREATE TABLE IF NOT EXISTS public.talk_like ( + talk_id BIGINT NOT NULL, + user_id UUID NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (talk_id, user_id) +); + +CREATE TABLE IF NOT EXISTS public.talk_report ( + talk_id BIGINT NOT NULL, + user_id UUID NOT NULL, + reason SMALLINT NOT NULL, -- TalkReport: 1=욕설·비하 2=광고·도배 3=개인정보 노출 4=기타 + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (talk_id, user_id) +); + +-- 이 사람 글 안 보기 +CREATE TABLE IF NOT EXISTS public.user_block ( + user_id UUID NOT NULL, + blocked_id UUID NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, blocked_id) +); + -- 직접 넣는 내용 (처음 값은 저장소의 시드 파일에서 불러온다) -- 구 목록. diff --git a/backend/router/router.py b/backend/router/router.py index 644fd10..2fdf6c8 100644 --- a/backend/router/router.py +++ b/backend/router/router.py @@ -17,6 +17,7 @@ from router.v1.region.region import router as region_router from router.v1.season.season import router as season_router from router.v1.seo.seo import router as seo_router from router.v1.sky.sky import router as sky_router +from router.v1.talk.talk import router as talk_router from router.v1.watch.watch import router as watch_router from router.v1.weather.weather import router as weather_router from router.v1.week.week import router as week_router @@ -44,6 +45,7 @@ app.include_router(feed_router) app.include_router(auth_router) app.include_router(reaction_router) app.include_router(my_gak_router) +app.include_router(talk_router) app.include_router(watch_router) app.include_router(image_router) app.include_router(seo_router) diff --git a/backend/router/v1/talk/__init__.py b/backend/router/v1/talk/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/router/v1/talk/protocol.py b/backend/router/v1/talk/protocol.py new file mode 100644 index 0000000..45c5171 --- /dev/null +++ b/backend/router/v1/talk/protocol.py @@ -0,0 +1,45 @@ +from datetime import datetime +from typing import Optional + +from pydantic import Field + +from common.enums import TalkReport +from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol + + +class TalkData(WebPacketProtocol): + talk_id: int + nickname: str + character: str + color: str + mood: Optional[str] = None + region_name: Optional[str] = Field(None, description="쓴 사람이 고른 동네 (성남시 분당구)") + weather: Optional[str] = Field(None, description="쓸 때 그 동네 날씨 (18° 맑음)") + body: str + like_count: int + liked: bool + mine: bool + created_at: datetime + + +class Req_Talk(Req_WebPacketProtocol): + region_code: str = Field(min_length=10, max_length=10) + body: str = Field(min_length=1, max_length=200, description="공백을 줄인 뒤 100자까지") + + +class Req_TalkReport(Req_WebPacketProtocol): + reason: TalkReport + + +class Res_TalkList(Res_WebPacketProtocol): + talks: list[TalkData] = [] + next_cursor: Optional[int] = None + + +class Res_Talk(Res_WebPacketProtocol): + talk: Optional[TalkData] = None + + +class Res_TalkLike(Res_WebPacketProtocol): + liked: Optional[bool] = None + like_count: Optional[int] = None diff --git a/backend/router/v1/talk/talk.py b/backend/router/v1/talk/talk.py new file mode 100644 index 0000000..da5e9a7 --- /dev/null +++ b/backend/router/v1/talk/talk.py @@ -0,0 +1,67 @@ +from typing import Optional + +from fastapi import APIRouter, Depends, Path, Query + +from common.auth import current_user, optional_user +from common.database.model.models import User +from common.enums import ErrorType +from common.models.errors import error_info +from common.models.gmodel import Res_WebPacketProtocol +from common.utils.kma_time import KST +from router.v1.talk.protocol import Req_Talk, Req_TalkReport, Res_Talk, Res_TalkLike, Res_TalkList, TalkData +from services.talk_service import PAGE, TalkService, TalkView + +router = APIRouter(prefix="/v1/talk", tags=["talk"]) + + +def _data(v: TalkView) -> TalkData: + t, u = v.talk, v.author + return TalkData( + talk_id=t.talk_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, region_name=v.region_name, weather=t.weather, + body=t.body, like_count=t.like_count, liked=v.liked, mine=v.mine, created_at=t.created_at.astimezone(KST), + ) + + +@router.get("/list", response_model=Res_TalkList, response_model_exclude_none=True, summary="동네 이야기 (전국, 최신순, 로그인 없이 보기)") +async def list_talks(cursor: Optional[int] = Query(None), user: Optional[User] = Depends(optional_user), service: TalkService = Depends()) -> Res_TalkList: + err, views = await service.page(user, cursor) + if err is not ErrorType.SUCCESS: + return Res_TalkList(result=error_info(err)) + talks = [_data(v) for v in views] + return Res_TalkList(talks=talks, next_cursor=talks[-1].talk_id if len(talks) == PAGE else None) + + +@router.post("", response_model=Res_Talk, response_model_exclude_none=True, summary="동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)") +async def add_talk(req: Req_Talk, user: User = Depends(current_user), service: TalkService = Depends()) -> Res_Talk: + err, v = await service.add(user, req.region_code, req.body) + return Res_Talk(result=error_info(err)) if err is not ErrorType.SUCCESS or v is None else Res_Talk(talk=_data(v)) + + +@router.delete("/{talk_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="내 이야기 지우기") +async def delete_talk(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol: + return Res_WebPacketProtocol(result=error_info(await service.delete(user, talk_id))) + + +async def _like(talk_id: int, user: User, on: bool, service: TalkService) -> Res_TalkLike: + err, count = await service.like(user, talk_id, on) + return Res_TalkLike(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_TalkLike(liked=on, like_count=count) + + +@router.post("/{talk_id}/like", response_model=Res_TalkLike, response_model_exclude_none=True, summary="이야기 좋아요") +async def like_talk(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_TalkLike: + return await _like(talk_id, user, True, service) + + +@router.delete("/{talk_id}/like", response_model=Res_TalkLike, response_model_exclude_none=True, summary="이야기 좋아요 취소") +async def unlike_talk(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_TalkLike: + return await _like(talk_id, user, False, service) + + +@router.post("/{talk_id}/report", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이야기 신고 (서로 다른 3명이면 숨김)") +async def report_talk(req: Req_TalkReport, talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol: + return Res_WebPacketProtocol(result=error_info(await service.report(user, talk_id, req.reason))) + + +@router.post("/{talk_id}/block", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이 글 쓴 사람의 글 안 보기") +async def block_talk_author(talk_id: int = Path(...), user: User = Depends(current_user), service: TalkService = Depends()) -> Res_WebPacketProtocol: + return Res_WebPacketProtocol(result=error_info(await service.block_author(user, talk_id))) diff --git a/backend/services/talk_service.py b/backend/services/talk_service.py new file mode 100644 index 0000000..22a3051 --- /dev/null +++ b/backend/services/talk_service.py @@ -0,0 +1,129 @@ +import re +from dataclasses import dataclass +from datetime import timedelta +from typing import Optional + +from fastapi import Depends + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import Talk, User, WeatherHourly +from common.enums import ErrorType, RainType, Sky, TalkReport +from common.utils.kma_time import kst_midnight, now_kst +from crud.region_crud import RegionCRUD +from crud.talk_crud import TalkCRUD +from crud.weather_crud import WeatherCRUD + +BODY_MAX = 100 +DAILY_MAX = 5 +# 로그인한 서로 다른 사람의 신고가 이만큼 쌓이면 운영자 확인 전까지 숨긴다 +HIDE_AT = 3 +PAGE = 20 + +# 링크(http, www, 도메인 꼴)와 전화번호(010-1234-5678, 01012345678, 02-123-4567) +_LINK = re.compile(r"https?://|www\.|[a-z0-9-]+\.(?:com|net|kr|co|org|io|me|ly|gl)\b", re.I) +_PHONE = re.compile(r"0\d{1,2}[-.\s]?\d{3,4}[-.\s]?\d{4}") + +_SKY = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"} +_RAIN = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"} + + +def weather_line(row: Optional[WeatherHourly]) -> Optional[str]: + """글에 붙일 그때 날씨: 18° 맑음 / 12° 비.""" + if row is None: + return None + rain = RainType(row.rain_type) + word = _RAIN.get(rain) or _SKY.get(Sky(row.sky), "") + return f"{round(float(row.temp_c))}° {word}".strip() + + +@dataclass +class TalkView: + talk: Talk + author: User + region_name: Optional[str] + liked: bool + mine: bool + + +class TalkService: + def __init__(self, crud: TalkCRUD = Depends(TalkCRUD), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)) -> None: + self.crud, self.regions, self.weather = crud, regions, weather + + async def page(self, user: Optional[User], cursor: Optional[int]) -> tuple[ErrorType, list[TalkView]]: + viewer = user.user_id if user else None + err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.page(s, viewer, cursor, PAGE)) + if err is not ErrorType.SUCCESS: + return err, [] + liked: set[int] = set() + if user is not None and rows: + err, liked = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.liked(s, user.user_id, [t.talk_id for t, *_ in rows])) + if err is not ErrorType.SUCCESS: + return err, [] + return ErrorType.SUCCESS, [TalkView(talk=t, author=u, region_name=name, liked=t.talk_id in liked, mine=viewer == t.user_id) for t, u, name in rows] + + async def _weather_now(self, region_code: str) -> Optional[str]: + """지금 시각에 가장 가까운 예보 한 칸. 못 읽으면 날씨 없이 쓴다.""" + now = now_kst() + err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, region_code, now - timedelta(hours=1), now + timedelta(hours=2))) + if err is not ErrorType.SUCCESS or not rows: + return None + return weather_line(min(rows, key=lambda r: abs(r.forecast_at - now))) + + async def add(self, user: User, region_code: str, body: str) -> tuple[ErrorType, Optional[TalkView]]: + body = " ".join(body.split()) + if not body or len(body) > BODY_MAX: + return ErrorType.INVALID_INPUT, None + if _LINK.search(body) or _PHONE.search(body): + return ErrorType.LINK_NOT_ALLOWED, None + err, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, region_code)) + if err is not ErrorType.SUCCESS: + return err, None + if region is None: + return ErrorType.INVALID_INPUT, None + today = kst_midnight(now_kst().date()) + err, n = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.count_since(s, user.user_id, today)) + if err is not ErrorType.SUCCESS: + return err, None + if n >= DAILY_MAX: + return ErrorType.DAILY_LIMIT, None + weather = await self._weather_now(region_code) + err, t = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.add(s, user.user_id, region_code, body, weather)) + if err is not ErrorType.SUCCESS or t is None: + return err, None + return ErrorType.SUCCESS, TalkView(talk=t, author=user, region_name=region.short_name, liked=False, mine=True) + + async def delete(self, user: User, talk_id: int) -> ErrorType: + err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.delete(s, talk_id, user.user_id)) + if err is not ErrorType.SUCCESS: + return err + return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND + + async def _talk(self, talk_id: int) -> tuple[ErrorType, Optional[Talk]]: + err, t = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, talk_id)) + if err is not ErrorType.SUCCESS: + return err, None + return (ErrorType.SUCCESS, t) if t is not None else (ErrorType.NOT_FOUND, None) + + async def like(self, user: User, talk_id: int, on: bool) -> tuple[ErrorType, Optional[int]]: + err, _ = await self._talk(talk_id) + if err is not ErrorType.SUCCESS: + return err, None + return await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.toggle_like(s, talk_id, user.user_id, on)) + + async def report(self, user: User, talk_id: int, reason: TalkReport) -> ErrorType: + err, t = await self._talk(talk_id) + if err is not ErrorType.SUCCESS or t is None: + return err + if t.user_id == user.user_id: + return ErrorType.INVALID_INPUT + err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.report(s, talk_id, user.user_id, reason.value, HIDE_AT)) + return err + + async def block_author(self, user: User, talk_id: int) -> ErrorType: + err, t = await self._talk(talk_id) + if err is not ErrorType.SUCCESS or t is None: + return err + if t.user_id == user.user_id: + return ErrorType.INVALID_INPUT + err, _ = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.block(s, user.user_id, t.user_id)) + return err diff --git a/backend/tests/test_talk.py b/backend/tests/test_talk.py new file mode 100644 index 0000000..0f0e50e --- /dev/null +++ b/backend/tests/test_talk.py @@ -0,0 +1,89 @@ +import pytest +from httpx import ASGITransport, AsyncClient + +from router.router import app +from services.talk_service import DAILY_MAX, HIDE_AT, weather_line + +REGION = "1144000000" + + +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": login_id})).json() + return {"Authorization": f"Bearer {body['access_token']}"} + + +async def _write(c, h, body="망원동 하늘 진짜 맑아요"): + return (await c.post("/v1/talk", json={"region_code": REGION, "body": body}, headers=h)).json() + + +@pytest.mark.anyio +async def test_write_list_like_delete(): + async with client() as c: + assert (await c.post("/v1/talk", json={"region_code": REGION, "body": "안녕"})).status_code == 401 + h = await _login(c, "talk_01") + t = (await _write(c, h, " 바람 많이 불어요 "))["talk"] + assert t["body"] == "바람 많이 불어요" and t["mine"] is True and t["region_name"] + + anon = (await c.get("/v1/talk/list")).json()["talks"] + mine = next(x for x in anon if x["talk_id"] == t["talk_id"]) + assert mine["mine"] is False and mine["nickname"] == "talk_01" + + liked = (await c.post(f"/v1/talk/{t['talk_id']}/like", headers=h)).json() + assert liked["liked"] is True and liked["like_count"] == 1 + assert (await c.post(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()["like_count"] == 1 + assert (await c.delete(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()["like_count"] == 0 + + other = await _login(c, "talk_02") + assert (await c.delete(f"/v1/talk/{t['talk_id']}", headers=other)).json()["result"]["desc"] == "NOT_FOUND" + assert (await c.delete(f"/v1/talk/{t['talk_id']}", headers=h)).json()["result"]["success"] is True + assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]] + + +@pytest.mark.anyio +async def test_rejects_links_phone_long_and_daily_limit(): + async with client() as c: + h = await _login(c, "talk_03") + assert (await _write(c, h, "여기 보세요 https://spam.example"))["result"]["desc"] == "LINK_NOT_ALLOWED" + assert (await _write(c, h, "연락 주세요 010-1234-5678"))["result"]["desc"] == "LINK_NOT_ALLOWED" + assert (await _write(c, h, "가" * 101))["result"]["desc"] == "INVALID_INPUT" + bad_region = (await c.post("/v1/talk", json={"region_code": "0000000000", "body": "안녕"}, headers=h)).json() + assert bad_region["result"]["desc"] == "INVALID_INPUT" + for i in range(DAILY_MAX): + assert (await _write(c, h, f"오늘 {i}번째"))["talk"] + assert (await _write(c, h))["result"]["desc"] == "DAILY_LIMIT" + + +@pytest.mark.anyio +async def test_reports_hide_and_block_hides_author(): + async with client() as c: + author = await _login(c, "talk_04") + t = (await _write(c, author))["talk"] + assert (await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 1}, headers=author)).json()["result"]["desc"] == "INVALID_INPUT" + + viewer = await _login(c, "talk_05") + assert (await c.post(f"/v1/talk/{t['talk_id']}/block", headers=viewer)).json()["result"]["success"] is True + seen = [x["talk_id"] for x in (await c.get("/v1/talk/list", headers=viewer)).json()["talks"]] + assert t["talk_id"] not in seen + assert t["talk_id"] in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]] + + for i in range(HIDE_AT): + h = await _login(c, f"talk_r{i}") + await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 2}, headers=h) + await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 2}, headers=h) + assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]] + + +def test_weather_line(): + class Row: + temp_c, sky, rain_type = 18.4, 1, 1 + + class Wet: + temp_c, sky, rain_type = 11.6, 3, 2 + + assert weather_line(Row()) == "18° 맑음" + assert weather_line(Wet()) == "12° 비" + assert weather_line(None) is None diff --git a/frontend/src/api/client/@tanstack/react-query.gen.ts b/frontend/src/api/client/@tanstack/react-query.gen.ts index 962ad5a..91a5f5d 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, 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'; +import { addComment, addMyGak, addTalk, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, signup, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe } from '../sdk.gen'; +import type { AddCommentData, AddCommentError, AddCommentResponse, AddMyGakData, AddMyGakError, AddMyGakResponse, AddTalkData, AddTalkError, AddTalkResponse, BlockTalkAuthorData, BlockTalkAuthorError, BlockTalkAuthorResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, DeleteMyGakData, DeleteMyGakError, DeleteMyGakResponse, DeleteTalkData, DeleteTalkError, DeleteTalkResponse, 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, LikeTalkData, LikeTalkError, LikeTalkResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListMyGakData, ListMyGakError, ListMyGakResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, ListTalksData, ListTalksError, ListTalksResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, ReportTalkData, ReportTalkError, ReportTalkResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnlikeTalkData, UnlikeTalkError, UnlikeTalkResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen'; export type QueryKey = [ Pick & { @@ -761,6 +761,156 @@ export const deleteMyGakMutation = (options?: Partial>) return mutationOptions; }; +export const listTalksQueryKey = (options?: Options) => createQueryKey('listTalks', options); + +/** + * 동네 이야기 (전국, 최신순, 로그인 없이 보기) + */ +export const listTalksOptions = (options?: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await listTalks({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: listTalksQueryKey(options) +}); + +export const listTalksInfiniteQueryKey = (options?: Options): QueryKey> => createQueryKey('listTalks', options, true); + +/** + * 동네 이야기 (전국, 최신순, 로그인 없이 보기) + */ +export const listTalksInfiniteOptions = (options?: Options) => { + const opts = infiniteQueryOptions, QueryKey>, number | null | Pick>[0], 'body' | 'headers' | 'path' | 'query'>>( + // @ts-ignore + { + queryFn: async ({ pageParam, queryKey, signal }) => { + // @ts-ignore + const page: Pick>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : { + query: { + cursor: pageParam + } + }; + const params = createInfiniteParams(queryKey, page); + const { data } = await listTalks({ + ...options, + ...params, + signal, + throwOnError: true + }); + return data; + }, + queryKey: listTalksInfiniteQueryKey(options) + }); + return opts as Omit; +}; + +/** + * 동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개) + */ +export const addTalkMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await addTalk({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * 내 이야기 지우기 + */ +export const deleteTalkMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await deleteTalk({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * 이야기 좋아요 취소 + */ +export const unlikeTalkMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await unlikeTalk({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * 이야기 좋아요 + */ +export const likeTalkMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await likeTalk({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * 이야기 신고 (서로 다른 3명이면 숨김) + */ +export const reportTalkMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await reportTalk({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * 이 글 쓴 사람의 글 안 보기 + */ +export const blockTalkAuthorMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await blockTalkAuthor({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + export const getWatchSummaryQueryKey = (options: Options) => createQueryKey('getWatchSummary', options); /** diff --git a/frontend/src/api/client/index.ts b/frontend/src/api/client/index.ts index 3e861c9..c2dabb0 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, 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'; +export { addComment, addMyGak, addTalk, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, signup, unlikeComment, unlikePost, unlikeTalk, 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 AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, 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 DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, 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 LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, 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 ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, 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 ReportTalkData, type ReportTalkError, type ReportTalkErrors, type ReportTalkResponse, type ReportTalkResponses, type ReqComment, type ReqLogin, type ReqMyGak, type ReqRefresh, type ReqSignup, type ReqTalk, type ReqTalkReport, 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 ResTalk, type ResTalkLike, type ResTalkList, 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 TalkData, TalkReport, 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 UnlikeTalkData, type UnlikeTalkError, type UnlikeTalkErrors, type UnlikeTalkResponse, type UnlikeTalkResponses, 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 acc5525..2084bd6 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, 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'; +import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, 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, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen'; export type Options = Options2 & { /** @@ -240,6 +240,55 @@ export const addMyGak = (options: Options(options: Options): RequestResult => (options.client ?? client).delete({ url: '/v1/my-gak/{my_gak_id}', ...options }); +/** + * 동네 이야기 (전국, 최신순, 로그인 없이 보기) + */ +export const listTalks = (options?: Options): RequestResult => (options?.client ?? client).get({ url: '/v1/talk/list', ...options }); + +/** + * 동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개) + */ +export const addTalk = (options: Options): RequestResult => (options.client ?? client).post({ + url: '/v1/talk', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +/** + * 내 이야기 지우기 + */ +export const deleteTalk = (options: Options): RequestResult => (options.client ?? client).delete({ url: '/v1/talk/{talk_id}', ...options }); + +/** + * 이야기 좋아요 취소 + */ +export const unlikeTalk = (options: Options): RequestResult => (options.client ?? client).delete({ url: '/v1/talk/{talk_id}/like', ...options }); + +/** + * 이야기 좋아요 + */ +export const likeTalk = (options: Options): RequestResult => (options.client ?? client).post({ url: '/v1/talk/{talk_id}/like', ...options }); + +/** + * 이야기 신고 (서로 다른 3명이면 숨김) + */ +export const reportTalk = (options: Options): RequestResult => (options.client ?? client).post({ + url: '/v1/talk/{talk_id}/report', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +/** + * 이 글 쓴 사람의 글 안 보기 + */ +export const blockTalkAuthor = (options: Options): RequestResult => (options.client ?? client).post({ url: '/v1/talk/{talk_id}/block', ...options }); + /** * 워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표 */ diff --git a/frontend/src/api/client/types.gen.ts b/frontend/src/api/client/types.gen.ts index 794a8b2..610ac72 100644 --- a/frontend/src/api/client/types.gen.ts +++ b/frontend/src/api/client/types.gen.ts @@ -1278,6 +1278,29 @@ export type ReqSignup = { nickname: string; }; +/** + * Req_Talk + */ +export type ReqTalk = { + /** + * Region Code + */ + region_code: string; + /** + * Body + * + * 공백을 줄인 뒤 100자까지 + */ + body: string; +}; + +/** + * Req_TalkReport + */ +export type ReqTalkReport = { + reason: TalkReport; +}; + /** * Req_UpdateMe */ @@ -1826,6 +1849,56 @@ export type ResSkyRanking = { items?: Array; }; +/** + * Res_Talk + */ +export type ResTalk = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; + talk?: TalkData | null; +}; + +/** + * Res_TalkLike + */ +export type ResTalkLike = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; + /** + * Liked + */ + liked?: boolean | null; + /** + * Like Count + */ + like_count?: number | null; +}; + +/** + * Res_TalkList + */ +export type ResTalkList = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; + /** + * Talks + */ + talks?: Array; + /** + * Next Cursor + */ + next_cursor?: number | null; +}; + /** * Res_WatchSummary */ @@ -2431,6 +2504,91 @@ export type SunsetSlide = { peak_at?: string | null; }; +/** + * TalkData + */ +export type TalkData = { + /** + * Talk Id + */ + talk_id: number; + /** + * Nickname + */ + nickname: string; + /** + * Character + */ + character: string; + /** + * Color + */ + color: string; + /** + * Mood + */ + mood?: string | null; + /** + * Region Name + * + * 쓴 사람이 고른 동네 (성남시 분당구) + */ + region_name?: string | null; + /** + * Weather + * + * 쓸 때 그 동네 날씨 (18° 맑음) + */ + weather?: string | null; + /** + * Body + */ + body: string; + /** + * Like Count + */ + like_count: number; + /** + * Liked + */ + liked: boolean; + /** + * Mine + */ + mine: boolean; + /** + * Created At + */ + created_at: string; +}; + +/** + * TalkReport + */ +export const TalkReport = { + /** + * ABUSE + */ + ABUSE: 1, + /** + * SPAM + */ + SPAM: 2, + /** + * PRIVACY + */ + PRIVACY: 3, + /** + * ETC + */ + ETC: 4 +} as const; + +/** + * TalkReport + */ +export type TalkReport = typeof TalkReport[keyof typeof TalkReport]; + /** * TermData */ @@ -4123,6 +4281,253 @@ export type DeleteMyGakResponses = { export type DeleteMyGakResponse = DeleteMyGakResponses[keyof DeleteMyGakResponses]; +export type ListTalksData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: { + /** + * Cursor + */ + cursor?: number | null; + }; + url: '/v1/talk/list'; +}; + +export type ListTalksErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListTalksError = ListTalksErrors[keyof ListTalksErrors]; + +export type ListTalksResponses = { + /** + * Successful Response + */ + 200: ResTalkList; +}; + +export type ListTalksResponse = ListTalksResponses[keyof ListTalksResponses]; + +export type AddTalkData = { + body: ReqTalk; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: never; + url: '/v1/talk'; +}; + +export type AddTalkErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type AddTalkError = AddTalkErrors[keyof AddTalkErrors]; + +export type AddTalkResponses = { + /** + * Successful Response + */ + 200: ResTalk; +}; + +export type AddTalkResponse = AddTalkResponses[keyof AddTalkResponses]; + +export type DeleteTalkData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path: { + /** + * Talk Id + */ + talk_id: number; + }; + query?: never; + url: '/v1/talk/{talk_id}'; +}; + +export type DeleteTalkErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type DeleteTalkError = DeleteTalkErrors[keyof DeleteTalkErrors]; + +export type DeleteTalkResponses = { + /** + * Successful Response + */ + 200: ResWebPacketProtocol; +}; + +export type DeleteTalkResponse = DeleteTalkResponses[keyof DeleteTalkResponses]; + +export type UnlikeTalkData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path: { + /** + * Talk Id + */ + talk_id: number; + }; + query?: never; + url: '/v1/talk/{talk_id}/like'; +}; + +export type UnlikeTalkErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type UnlikeTalkError = UnlikeTalkErrors[keyof UnlikeTalkErrors]; + +export type UnlikeTalkResponses = { + /** + * Successful Response + */ + 200: ResTalkLike; +}; + +export type UnlikeTalkResponse = UnlikeTalkResponses[keyof UnlikeTalkResponses]; + +export type LikeTalkData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path: { + /** + * Talk Id + */ + talk_id: number; + }; + query?: never; + url: '/v1/talk/{talk_id}/like'; +}; + +export type LikeTalkErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type LikeTalkError = LikeTalkErrors[keyof LikeTalkErrors]; + +export type LikeTalkResponses = { + /** + * Successful Response + */ + 200: ResTalkLike; +}; + +export type LikeTalkResponse = LikeTalkResponses[keyof LikeTalkResponses]; + +export type ReportTalkData = { + body: ReqTalkReport; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path: { + /** + * Talk Id + */ + talk_id: number; + }; + query?: never; + url: '/v1/talk/{talk_id}/report'; +}; + +export type ReportTalkErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ReportTalkError = ReportTalkErrors[keyof ReportTalkErrors]; + +export type ReportTalkResponses = { + /** + * Successful Response + */ + 200: ResWebPacketProtocol; +}; + +export type ReportTalkResponse = ReportTalkResponses[keyof ReportTalkResponses]; + +export type BlockTalkAuthorData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path: { + /** + * Talk Id + */ + talk_id: number; + }; + query?: never; + url: '/v1/talk/{talk_id}/block'; +}; + +export type BlockTalkAuthorErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type BlockTalkAuthorError = BlockTalkAuthorErrors[keyof BlockTalkAuthorErrors]; + +export type BlockTalkAuthorResponses = { + /** + * Successful Response + */ + 200: ResWebPacketProtocol; +}; + +export type BlockTalkAuthorResponse = BlockTalkAuthorResponses[keyof BlockTalkAuthorResponses]; + export type GetWatchSummaryData = { body?: never; path?: never; diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx index b208dec..24c36e1 100644 --- a/frontend/src/b/Sheets.tsx +++ b/frontend/src/b/Sheets.tsx @@ -28,6 +28,7 @@ import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateR import { MixSheet } from './myGak' import { useMyGak } from './myGakState' import { ownPage, useRegion } from './regionContext' +import { TalkSheet } from './talk' import { useSky } from './skyContext' import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage' import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext' @@ -74,7 +75,7 @@ export function SheetProvider({ children }: { children: ReactNode }) { ) } -const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const +const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', talks: '동네 이야기' } as const /** 아래에서 올라오는 창: 네이티브 라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) { @@ -135,6 +136,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void {state.type === 'me' && } {state.type === 'region' && } {state.type === 'mix' && } + {state.type === 'talks' && } )} {!state && } diff --git a/frontend/src/b/TodayPage.tsx b/frontend/src/b/TodayPage.tsx index 07b2a0d..b507c0f 100644 --- a/frontend/src/b/TodayPage.tsx +++ b/frontend/src/b/TodayPage.tsx @@ -10,6 +10,7 @@ import { PostCard, PostCardSkel } from './Post' import { useRegion } from './regionContext' import { useSheet } from './sheetContext' import { useSky } from './skyContext' +import { TalkBand } from './talk' import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui' import { deg, slotAt } from './weatherText' @@ -391,6 +392,7 @@ export function TodayPage() { {/* 실패 안내는 여기 한 번만, 각 줄 스켈레톤과 같은 크기로 */} {stories.length ? : load === 'loading' ? : feed.refetch()} empty="오늘 계산된 각이 없어요." hold={} className="inset-x-3 top-3 bottom-1" />} +
      {load === 'loading' && } {/* 글이 없거나 못 받아도 스켈레톤 두 장 자리는 그대로 둔다 */} diff --git a/frontend/src/b/sheetContext.ts b/frontend/src/b/sheetContext.ts index f5e2aa9..33050d6 100644 --- a/frontend/src/b/sheetContext.ts +++ b/frontend/src/b/sheetContext.ts @@ -13,6 +13,7 @@ export type SheetState = | { type: 'me' } | { type: 'region' } | { type: 'mix'; ids?: number[]; shared?: boolean } + | { type: 'talks' } | null export type SheetApi = { open: (s: Exclude) => void; close: () => void } diff --git a/frontend/src/b/talk.tsx b/frontend/src/b/talk.tsx new file mode 100644 index 0000000..7b02a3f --- /dev/null +++ b/frontend/src/b/talk.tsx @@ -0,0 +1,256 @@ +import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useState, type FormEvent } from 'react' +import { + addTalkMutation, + blockTalkAuthorMutation, + deleteTalkMutation, + likeTalkMutation, + listTalksInfiniteOptions, + listTalksOptions, + reportTalkMutation, + unlikeTalkMutation, +} from '../api/client/@tanstack/react-query.gen' +import { TalkReport, type TalkData } from '../api/client/types.gen' +import { cx } from '../lib/utils' +import { useAuth } from './authContext' +import { ago, kst, loadOf } from './lib' +import { useRegion } from './regionContext' +import { useSheet } from './sheetContext' +import { HeartIcon } from './svg' +import { Avatar, Sec, StateBox, TAP44 } from './ui' + +const BODY_MAX = 100 +const PREVIEW = 3 + +// 서버 ErrorType 이름 → 안내 +const WRITE_ERRORS: Record = { + LINK_NOT_ALLOWED: '링크나 전화번호는 쓸 수 없어요.', + DAILY_LIMIT: '오늘은 더 쓸 수 없어요. 하루 5개까지예요.', + INVALID_INPUT: '100자 안으로 써 주세요.', +} + +const REASONS = [ + [TalkReport.ABUSE, '욕설·비하'], + [TalkReport.SPAM, '광고·도배'], + [TalkReport.PRIVACY, '개인정보 노출'], + [TalkReport.ETC, '기타'], +] as const + +/** 쓴 시각을 시간대로만: 정확한 시각은 동선이 드러나서 뭉갠다 */ +function slotWord(iso: string) { + const h = kst(iso).h + return h < 6 ? '새벽' : h < 10 ? '아침' : h < 17 ? '낮' : h < 21 ? '저녁' : '밤' +} + +function useRefreshTalks() { + const queryClient = useQueryClient() + return () => queryClient.invalidateQueries({ queryKey: [{ _id: 'listTalks' }] }) +} + +function Composer() { + const { region } = useRegion() + const { loggedIn, me } = useAuth() + const { open } = useSheet() + const refresh = useRefreshTalks() + const add = useMutation(addTalkMutation()) + const [text, setText] = useState('') + const [error, setError] = useState(null) + + const submit = (e: FormEvent) => { + e.preventDefault() + if (!loggedIn) return open({ type: 'login' }) + const body = text.trim() + if (!body || add.isPending) return + setError(null) + add.mutate( + { body: { region_code: region.code, body } }, + { + onSuccess: (res) => { + if (!res.result?.success) return setError(WRITE_ERRORS[res.result?.desc ?? ''] ?? '글을 올리지 못했어요. 다시 해 주세요.') + setText('') + refresh() + }, + onError: () => setError('글을 올리지 못했어요. 다시 해 주세요.'), + }, + ) + } + + return ( +
      +