Skip to content

feat: subscription billing — family plan, monthly analysis quota, report lock, RevenueCat (off by default) - #29

Merged
Frekion2002 merged 10 commits into
mainfrom
feat/billing-20261127
Nov 29, 2026
Merged

Frekion2002 merged 10 commits into
mainfrom
feat/billing-20261127

Conversation

@Frekion2002

Copy link
Copy Markdown
Collaborator

구독 결제(무료 / 프리미엄 월 13,000원, 가입 뒤 2주 체험)의 서버 쪽입니다. 연동은 RevenueCat 이고, 두 앱의 feat/billing-20261127 과 짝을 이룹니다.

결제는 꺼진 채로 들어갑니다. 설정 BILLING_LAUNCH_AT 이 비어 있으면 모든 사람이 프리미엄이고 잠금·분석 분량 제한이 없어 지금과 똑같이 동작합니다. 새 설정 값이 하나도 없어도 안전하게 동작합니다.

요금제 판정

  • 가족 단위입니다. 가족 중 한 명이라도 유효한 구독이 있으면 가족 모두 프리미엄입니다.
  • 체험은 가족 중 가장 먼저 가입한 사람 기준 가입(또는 결제를 켠 날) + 14일입니다. 새 사람이 들어와도 늘어나지 않습니다.
  • 만료 직후 7일 안의 자동 갱신 구독은 판정 직전에 RevenueCat 을 다시 읽습니다(갱신 웹훅을 놓쳐도 잠기지 않게).

분석 분량

  • 한국 시간 달력 월 기준 무료 40분 / 프리미엄 250분, 가족 합계입니다. 음성 인식을 돌린 통화 길이를 원장 표 analysis_usage 에 셉니다.
  • 다 쓰면 통화는 그대로 되고 분석만 하지 않습니다(ANALYSIS_QUOTA_EXCEEDED). 결제를 켜기 전 사용량과 음성 인식이 끝내 실패한 통화는 세지 않습니다.

잠금

  • 결제가 켜져 있고 가족이 무료면 리포트·신호 API 가 402 PREMIUM_REQUIRED 를 줍니다(403 공유 꺼짐과 구분).
  • 응급 안내는 요금제와 상관없이 봅니다: 무료 API GET /v1/parents/{id}/safety-notices, signals?filter=ACUTE 는 402 없음.

API

  • GET /v1/account/entitlement, POST /v1/account/entitlement/refresh(구매 직후 RevenueCat 재확인, 실패하면 502).
  • POST /v1/webhooks/revenuecat: Authorization 헤더 비교, 이벤트 ID 중복 거름, 요청 안에서 REST 로 다시 확인.
  • 계정을 삭제하면 RevenueCat 고객도 지웁니다.

운영 지표 화면

  • 계정 탭에 「결제 미리 켜기」(billing_preview): 전체에 켜기 전에 고른 계정(심사·팀)만 결제를 켜고 끝까지 시험합니다.

DB

  • 마이그레이션 0024_billing(down 0022_call_ai_usage, 0023 은 다른 브랜치가 예약): 표 analysis_usage·user_entitlements·revenuecat_events, 계정 표시에 billing_preview.

설정(compose·env 예시에 이름만 더함, 운영 값은 결제를 켤 때 넣음)
BILLING_LAUNCH_AT · REVENUECAT_SECRET_KEY · REVENUECAT_WEBHOOK_AUTH · REVENUECAT_ENTITLEMENT_ID=premium · REVENUECAT_ALLOW_SANDBOX=true · TRIAL_DAYS=14 · FREE_ANALYSIS_SECONDS=2400 · PREMIUM_ANALYSIS_SECONDS=15000

시험

  • uv run pytest 619개 통과, ruff check 통과.
  • 실제 RevenueCat 응답(비밀 키로 REST 가 200 을 주는지, Play 구독 키 모양)은 샌드박스 구매 한 번으로 결제를 켜기 전에 확인합니다.

Subscriptions are judged per family and free analysis is capped per Korean
calendar month, so the server needs its own records: a usage ledger keyed by
call (no foreign keys, so deleting a call or account never shrinks the
month's total), the RevenueCat entitlement per user, and processed webhook
event ids for deduplication.

Every billing setting defaults to empty or the contract value and none is a
production requirement: with BILLING_LAUNCH_AT empty the server behaves as
today. The migration is 0024 because 0023 is reserved by another branch.
…evenueCat sync

First billing pass from the billing contract (section 2):

- A family is premium while anyone in it has a valid subscription or the
  earliest member's trial (max(signup, launch) + TRIAL_DAYS) has not ended,
  so a new member never extends the trial.
- The pipeline checks the family's usage for the Korean month after the
  consent check and before claiming the call. A family at or over its limit
  gets ANALYSIS_EXCLUDED with ANALYSIS_QUOTA_EXCEEDED and the audio deleted,
  without calling STT or Gemini. The check stays out of processing_allowed,
  which runs again mid-analysis and would cut a call that already started.
  A call is written to the ledger once when STT starts, even with billing
  off, and a retried call already in the ledger is never cut.
- Reports and signals answer 402 PREMIUM_REQUIRED, kept apart from the 403
  for disabled sharing. Baseline and call APIs stay open for free screens.
- GET /v1/account/entitlement and POST /v1/account/entitlement/refresh
  report the family plan; refresh re-reads RevenueCat by our user id only.
- POST /v1/webhooks/revenuecat checks the static Authorization value,
  ignores repeated event ids, refreshes every related user (including
  TRANSFER targets) and only drops access when the stored expiry passes.
  It finishes inside the request and answers 503 on failure so RevenueCat
  retries instead of losing an update.
- Account deletion removes the entitlement and webhook rows and blanks the
  person's id in the usage ledger.
The production env file lives on the server and is filled by the team, so
compose falls back to empty values and contract defaults. Until
BILLING_LAUNCH_AT is set billing stays off and production is unaffected.
The paywall shows the next charge date only while the subscription renews
and offers subscription management once it is cancelled. willRenew comes
from the subscription that gives paidUntil (the latest one in the family):
true while auto-renewing, false after cancellation, null when nobody pays.
It is updated from unsubscribe_detected_at in the REST response and from
CANCELLATION and UNCANCELLATION webhooks.
…usage from launch

Review fixes before billing is turned on:

- A missed renewal webhook could lock a paying family. Before locking
  reports, excluding a call for quota or answering the entitlement, a
  subscription that expired within 7 days and was not cancelled is read
  again from RevenueCat, at most every 10 minutes per person. Failures fall
  back to stored values and never fail the request.
- Entitlements are written with INSERT ... ON CONFLICT DO UPDATE so a
  refresh racing the first purchase webhook cannot hit the primary key.
- Refresh calls RevenueCat only while billing is on and at most every 30
  seconds per user; otherwise it answers from stored values.
- Webhook authorization ignores surrounding whitespace on both sides.
- Without a secret key, events other than EXPIRATION only move the expiry
  forward and include the billing grace period, so a late retry of an old
  event cannot cut access.
- Usage recorded before BILLING_LAUNCH_AT does not count toward the month.
- A call whose STT never finished and that ends ANALYSIS_FAILED gives its
  usage back; a call that fails after the transcript was saved keeps it.
- When I pay, paidUntil and willRenew describe my own subscription.
…is deleted

Account deletion already removes our billing rows; RevenueCat still kept the
customer under the deleted user id. With billing on and a secret key, the
server now calls DELETE /v1/subscribers/{id} after the deletion commits.
RevenueCat queues the deletion and answers 404 for a customer that no
longer exists, which counts as done. Any failure is only logged so the
account deletion still completes; the store subscription itself is
untouched and must be cancelled in the store.
App Store review and the team need to walk through the paywall and a real
purchase before billing is turned on for everyone. An operator can now mark
an account with "billing preview" in the /ops accounts tab (same pattern as
the internal and cohort controls, operator code required, metrics
untouched).

If anyone in a family is marked, that family is treated as billing on even
with BILLING_LAUNCH_AT empty: entitlement says billingEnabled, reports
answer 402, the analysis quota applies and refresh calls RevenueCat. Its
billing start is the earliest member's signup, so the trial ends 14 days
after that and an old review account sees the free plan at once. The same
start is kept when billing is later on for everyone. The column is added in
0024, which has not reached production yet.
Decision 2026-11-28: emergency guidance is shown whatever the plan.
GET /parents/{id}/signals?filter=ACUTE no longer answers 402 for a free
family; ALL and PROMOTED stay locked, and the sharing check (403) still
runs first.
Decision 2026-11-28: emergency guidance is shown whatever the plan, but the
report's safetyNotices come from call extractions, not from acute signals,
and the report itself is locked on the free plan.

GET /parents/{id}/safety-notices?days=14 (1-90) returns the same items as
the report ({callId, observedAt, text}, newest call first, short excluded
calls included) for calls that ended in the last N days. It checks sharing
(403) but never the plan. The report and this API now share one function so
the two cannot drift apart.
@Frekion2002
Frekion2002 merged commit 1f20d2f into main Nov 29, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant