feat(V2-6/V2-7/V2-8): Mobile MVP + Teams + Billing 스캐폴딩

V2-6 — Mobile (Expo) MVP
- apps/mobile/ 신규, npm workspace에서 제외 (Expo deps 부담 회피)
- Expo SDK 51 + Expo Router + AsyncStorage Supabase 클라이언트
- 화면: index/login/(tabs)/{meetings,record,profile}
- expo-av로 녹음 → Edge Function stt-proxy 호출
- expo-web-browser + expo-linking으로 OAuth 콜백 처리
- README에 setup/EAS build 가이드
- 루트 package.json workspaces를 명시 나열로 변경 (apps/mobile 제외)

V2-7 — 팀 기능 (Web)
- apps/web/src/app/teams/page.tsx — 가입한 팀 카드 그리드
- apps/web/src/app/teams/[id]/page.tsx — 멤버 + 공유 회의
- components/teams/create-team-form.tsx — 팀 생성 + owner 자동 team_members
- components/teams/invite-member-form.tsx — user_id 직접 초대 (V2-7b에서 invite flow)
- Sidebar에 Teams/Billing 메뉴 + 아이콘
- ko.json에 nav.teams/nav.billing 키 추가
- V2-2 teams/team_members RLS 활용

V2-8 — 결제 스캐폴딩
- apps/web/src/app/billing/page.tsx — Free/Pro/Team 가격표 + 현재 구독
- components/billing/checkout-button.tsx — Edge Function 호출 후 redirect
- server/supabase/functions/stripe-checkout/index.ts:
  - JWT 인증 -> 기존 customer 조회/생성 -> Checkout Session 생성
  - subscriptions 테이블에 customer_id upsert
- server/supabase/functions/stripe-webhook/index.ts:
  - checkout.session.completed -> subscriptions tier=pro/team active
  - customer.subscription.updated/created -> status/period 업데이트
  - customer.subscription.deleted -> tier=free, status=canceled
  - signature 검증은 placeholder (V2-8b에서 정식)
- server/supabase/config.toml에 두 함수 등록 (webhook verify_jwt=false)

검증:
- desktop typecheck OK (회귀 없음)
- web typecheck OK
- web next build OK (11 라우트)
- mobile은 별도 install 필요 (workspace 제외)

memory/project_status.md 갱신 — V2 마스터 플랜 전 페이즈 로컬 완료
This commit is contained in:
yunchan8804 2026-04-09 16:39:54 +09:00
parent 5c0f4a2b98
commit 61a96b3e9b
136 changed files with 2641 additions and 251 deletions

View file

@ -84,5 +84,11 @@ verify_jwt = true
[functions.llm-proxy]
verify_jwt = true
[functions.stripe-checkout]
verify_jwt = true
[functions.stripe-webhook]
verify_jwt = false
[analytics]
enabled = false

View file

@ -0,0 +1,137 @@
// server/supabase/functions/stripe-checkout/index.ts
// Stripe Checkout Session 생성 — 사용자가 업그레이드 버튼 클릭 시 호출.
// 응답: { url: 'https://checkout.stripe.com/...' } → 클라이언트가 redirect.
import { corsHeaders, handleCorsPreflightRequest } from '../_shared/cors.ts'
import { requireUser, authErrorResponse, type AuthError } from '../_shared/auth.ts'
import { createServiceRoleClient } from '../_shared/quota.ts'
interface CheckoutRequest {
tier: 'pro' | 'team'
success_url: string
cancel_url: string
}
// Stripe Price ID는 환경변수로 주입 (대시보드에서 생성한 product의 price ID)
// 실제 운영 시:
// supabase secrets set STRIPE_PRICE_PRO=price_xxx
// supabase secrets set STRIPE_PRICE_TEAM=price_yyy
// supabase secrets set STRIPE_SECRET_KEY=sk_live_xxx
// @ts-expect-error — Deno 런타임 전역
Deno.serve(async (req: Request) => {
const preflight = handleCorsPreflightRequest(req)
if (preflight) return preflight
if (req.method !== 'POST') {
return new Response(JSON.stringify({ error: 'Method not allowed' }), {
status: 405,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
})
}
try {
const user = await requireUser(req)
const body = (await req.json()) as CheckoutRequest
// @ts-expect-error — Deno.env
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY') ?? ''
// @ts-expect-error — Deno.env
const priceMap: Record<string, string> = {
pro: Deno.env.get('STRIPE_PRICE_PRO') ?? '',
team: Deno.env.get('STRIPE_PRICE_TEAM') ?? ''
}
const priceId = priceMap[body.tier]
if (!stripeKey || !priceId) {
return new Response(
JSON.stringify({
error: 'stripe_not_configured',
message: 'STRIPE_SECRET_KEY 또는 STRIPE_PRICE_* 환경변수가 설정되지 않았습니다.'
}),
{
status: 503,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
}
)
}
// 기존 customer_id 조회 (subscriptions 테이블에서)
const serviceClient = createServiceRoleClient()
const { data: sub } = await serviceClient
.from('subscriptions')
.select('stripe_customer_id')
.eq('user_id', user.id)
.maybeSingle()
let customerId = (sub?.stripe_customer_id as string | null | undefined) ?? null
// 없으면 새 customer 생성
if (!customerId) {
const customerResp = await fetch('https://api.stripe.com/v1/customers', {
method: 'POST',
headers: {
Authorization: `Bearer ${stripeKey}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
email: user.email ?? '',
'metadata[user_id]': user.id
})
})
if (!customerResp.ok) {
const errText = await customerResp.text()
throw new Error(`Stripe customer 생성 실패: ${errText}`)
}
const customerData = (await customerResp.json()) as { id: string }
customerId = customerData.id
// subscriptions에 저장
await serviceClient
.from('subscriptions')
.upsert({ user_id: user.id, stripe_customer_id: customerId, tier: 'free' })
}
// Checkout session 생성
const sessionResp = await fetch('https://api.stripe.com/v1/checkout/sessions', {
method: 'POST',
headers: {
Authorization: `Bearer ${stripeKey}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
customer: customerId,
mode: 'subscription',
'line_items[0][price]': priceId,
'line_items[0][quantity]': '1',
success_url: body.success_url,
cancel_url: body.cancel_url,
'metadata[user_id]': user.id,
'metadata[tier]': body.tier
})
})
if (!sessionResp.ok) {
const errText = await sessionResp.text()
throw new Error(`Stripe checkout 생성 실패: ${errText}`)
}
const sessionData = (await sessionResp.json()) as { url: string }
return new Response(JSON.stringify({ url: sessionData.url }), {
status: 200,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
})
} catch (err) {
if (err && typeof err === 'object' && 'status' in err && 'message' in err) {
return authErrorResponse(err as AuthError, corsHeaders)
}
const message = err instanceof Error ? err.message : 'Unknown error'
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
})
}
})

View file

@ -0,0 +1,130 @@
// server/supabase/functions/stripe-webhook/index.ts
// Stripe Webhook 핸들러 — checkout 완료, 구독 갱신/취소 등 이벤트 처리.
// Supabase 대시보드 → Functions → stripe-webhook 의 verify_jwt를 false로 설정해야 함
// (Stripe는 JWT 없이 호출, 대신 signature로 검증).
//
// 환경변수:
// STRIPE_SECRET_KEY
// STRIPE_WEBHOOK_SECRET (Stripe 대시보드에서 발급)
import { createServiceRoleClient } from '../_shared/quota.ts'
interface StripeEvent {
id: string
type: string
data: {
object: Record<string, unknown>
}
}
async function verifyStripeSignature(payload: string, signature: string, secret: string): Promise<boolean> {
// 단순화: 본 스캐폴딩에서는 signature 검증 logic placeholder.
// 정식 구현은 Stripe SDK의 stripe.webhooks.constructEvent 사용 또는
// HMAC-SHA256으로 직접 검증.
// https://stripe.com/docs/webhooks/signatures
return Boolean(signature && secret && payload)
}
// @ts-expect-error — Deno 런타임 전역
Deno.serve(async (req: Request) => {
if (req.method !== 'POST') {
return new Response('Method not allowed', { status: 405 })
}
// @ts-expect-error — Deno.env
const webhookSecret = Deno.env.get('STRIPE_WEBHOOK_SECRET') ?? ''
if (!webhookSecret) {
return new Response('Webhook secret not configured', { status: 503 })
}
const signature = req.headers.get('stripe-signature') ?? ''
const payload = await req.text()
const valid = await verifyStripeSignature(payload, signature, webhookSecret)
if (!valid) {
return new Response('Invalid signature', { status: 400 })
}
let event: StripeEvent
try {
event = JSON.parse(payload) as StripeEvent
} catch {
return new Response('Invalid JSON', { status: 400 })
}
const serviceClient = createServiceRoleClient()
try {
switch (event.type) {
case 'checkout.session.completed': {
const session = event.data.object as {
customer: string
subscription: string
metadata?: { user_id?: string; tier?: string }
}
const userId = session.metadata?.user_id
const tier = session.metadata?.tier
if (userId && tier) {
await serviceClient.from('subscriptions').upsert({
user_id: userId,
stripe_customer_id: session.customer,
stripe_subscription_id: session.subscription,
tier,
status: 'active'
})
}
break
}
case 'customer.subscription.updated':
case 'customer.subscription.created': {
const sub = event.data.object as {
id: string
customer: string
status: string
current_period_start?: number
current_period_end?: number
cancel_at?: number | null
}
await serviceClient
.from('subscriptions')
.update({
status: sub.status,
current_period_start: sub.current_period_start
? new Date(sub.current_period_start * 1000).toISOString()
: null,
current_period_end: sub.current_period_end
? new Date(sub.current_period_end * 1000).toISOString()
: null,
cancel_at: sub.cancel_at ? new Date(sub.cancel_at * 1000).toISOString() : null
})
.eq('stripe_subscription_id', sub.id)
break
}
case 'customer.subscription.deleted': {
const sub = event.data.object as { id: string }
await serviceClient
.from('subscriptions')
.update({ tier: 'free', status: 'canceled' })
.eq('stripe_subscription_id', sub.id)
break
}
default:
// 기타 이벤트는 무시
break
}
return new Response(JSON.stringify({ received: true }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
} catch (err) {
const message = err instanceof Error ? err.message : 'Unknown error'
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
})
}
})