Skip to content

[Billing] Support plan change for JPY subscribers and fix currency copy (#23584) - #23592

Closed
PINYOPATTANAWASANPORN wants to merge 1 commit into
BasedHardware:mainfrom
PINYOPATTANAWASANPORN:fix/jpy-plan-change-and-currency-copy-23584
Closed

PINYOPATTANAWASANPORN wants to merge 1 commit into
BasedHardware:mainfrom
PINYOPATTANAWASANPORN:fix/jpy-plan-change-and-currency-copy-23584

Conversation

@PINYOPATTANAWASANPORN

@PINYOPATTANAWASANPORN PINYOPATTANAWASANPORN commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary of Changes

  • Resolves bug(billing): JPY subscribers cannot change plans in the iOS sheet #23584 by supporting in-sheet plan upgrades and changes for JPY subscribers and fixing currency copy across backend and mobile client.
  • In get_available_plans_endpoint:
    • Detects active subscriber currency (sub_currency).
    • For JPY subscribers, maps Plus and Unlimited tiers to active JPY price IDs (price_1ULq6b1F8wnoWYvwtchjjNqq, price_1ULq7H1F8wnoWYvwC1poOtd5, price_1ULq501F8wnoWYvwwN56CHzO, price_1ULq5e1F8wnoWYvwQT8XQ4Uw) and filters out USD-only tiers.
    • Formats zero-decimal JPY amounts using ¥{amount:,}/mo instead of dividing whole yen by 100.
  • In upgrade_subscription_endpoint:
    • Validates that the target price's currency matches the existing Stripe subscription currency before calling Subscription.modify.
    • Rejects cross-currency plan changes with HTTP 400 (The price specified supports currency ..., which does not match your current subscription currency (...)), preventing Stripe card processing failures.
  • In plans_sheet.dart:
    • Respects JPY formatting in annualBillingSummary when price_string starts with ¥, displaying ¥$unitAmount instead of dividing by 100.
  • Adds comprehensive unit tests in test_jpy_price_recognition.py verifying JPY catalog resolution, active plan identification, and cross-currency rejection.

Root Cause / Technical Context

  1. get_available_plans_endpoint retrieved price IDs solely from USD environment variables and formatted prices assuming 2 decimal places ($unit / 100). JPY subscribers were therefore shown USD prices with $ currency signs, which failed when sent to Stripe's subscription modification endpoint due to currency mismatch.
  2. upgrade_subscription_endpoint did not check stripe_sub['currency'] == target_price.currency prior to updating the subscription item, allowing mismatched currency payloads to fail downstream in Stripe.
  3. In Flutter, plans_sheet.dart divided unitAmount / 100 unconditionally for annual summary subtitles, turning whole yen amounts (e.g. 48,000 JPY) into incorrect fractions ($480).

Verification & Testing

  • Simulated pricing catalog formatting and boundary conditions locally:
    • Verified USD: $19.99/mo, annual $16/mo.
    • Verified JPY: ¥4,800/mo, annual ¥4,000/mo (zero decimal whole yen).
  • Unit tests added to backend/tests/unit/test_jpy_price_recognition.py:
    • test_jpy_available_plans_endpoint_returns_jpy_catalog
    • test_upgrade_subscription_rejects_currency_mismatch
  • Verified clean minimal diff (232 lines across 3 files) and verified branch SHA a69290b9f1c74ec613a0f5898b3fced1d87d1d25.

Impact & Compatibility

  • Breaking changes: None. USD subscribers and default behavior are 100% unchanged.

UI-Evidence: none -- bugfix on existing plans sheet subtitle string and backend currency routing without new screen or layout addition
Failure-Class: none

…py (BasedHardware#23584)

- Detect subscriber currency in `get_available_plans_endpoint` and serve matching JPY price catalog for JPY subscribers.
- Format JPY prices in `available-plans` with whole-yen strings (`¥{amount:,}/mo`).
- Validate subscription currency vs target price currency in `upgrade_subscription_endpoint` to prevent cross-currency Stripe invoice failures.
- Update `plans_sheet.dart` to respect JPY zero-decimal formatting in annual billing summary.
- Add unit tests verifying JPY catalog return and currency mismatch rejection.

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on #23584. Selecting JPY offers and checking currency before Stripe mutations address real parts of the failure. I reviewed this head and ran its JPY and existing pricing regressions in an isolated source snapshot.

There are still customer-flow blockers below: new/free buyers receive 500s, the advertised JPY targets remain rejected by upgrade admission, and the mobile confirmation looks up the selected ID in a different USD catalog. The new JPY test file passes (15 tests), but three existing available-plans resilience tests fail with the unbound stripe_sub error.

I’m consolidating the end-to-end implementation in draft #23591 so we maintain one currency-management contract rather than parallel hardcoded catalogs. These useful behaviors are already covered there, including the mobile flow and real Stripe sandbox cases; no commits have been imported from this PR. Any useful code we subsequently port will retain its author and source attribution. This PR remains open while the consolidated fix is verified; its eventual disposition will link the exact work incorporated or superseded.

current_plan = valid_subscription.plan if valid_subscription else PlanType.basic

# Detect subscriber currency so JPY subscribers see matching JPY upgrade/switch prices
sub_currency = (stripe_sub.get('currency') or 'usd').lower() if stripe_sub else 'usd'

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Preserve the free/new-buyer catalog path. stripe_sub is assigned only inside the active paid-subscription branch. A free user, cancelled subscriber, or failed subscription retrieval reaches this expression without that local being set, so the outer handler returns 500. I reproduced three failures in test_available_plans_resilience.py, including test_new_buyer_explicit_platforms_get_single_plan_catalog, with cannot access local variable 'stripe_sub'. Currency resolution must distinguish a new buyer from an unverified existing paid subscription.

if sub_currency == 'jpy':
if plan_id not in jpy_price_catalog:
continue
monthly_price_id = jpy_price_catalog[plan_id]['month']

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Admit the advertised JPY targets at the existing-subscription boundary. These IDs are retained recognition prices, while upgrade_subscription_endpoint still unconditionally calls the unchanged _validate_price_id(request.price_id). A direct request for price_1ULq501F8wnoWYvwwN56CHzO returns 400 Unknown price_id before even looking up the subscriber, so the newly displayed option cannot be purchased. The added mismatch test patches _validate_price_id out and misses this. Keep fresh Checkout closed, add scoped admission for an existing same-currency subscription, and exercise a successful catalog-to-upgrade request.

subtitle: interval == 'year' ? l10n.annualBillingSummary(12, '\$${unitAmount / 100}') : null,
subtitle: interval == 'year'
? ((planData['price_string'] as String? ?? '').startsWith('¥')
? l10n.annualBillingSummary(12, '¥$unitAmount')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Carry the selected JPY offer through confirmation. This fixes the subtitle, but _handleUpgrade still searches provider.subscription.availablePlans from /v1/users/me/subscription, whose prices remain the configured USD IDs. The JPY ID selected from /payments/available-plans is absent there, so selectedPrice == null surfaces selectedPlanNotAvailable before calling the backend. Confirmation needs the exact fresh offer the user selected, with its currency-safe total. Also gate new non-USD offers for installed clients that still have the old USD-only rendering.

aryanorastar added a commit that referenced this pull request Oct 25, 2026
## What changed

An existing JPY subscriber selecting Unlimited in the mobile sheet
received a USD price that Stripe rejected. #20804 recognized JPY prices
for entitlements but explicitly excluded in-app plan changes. The sheet
now shows the approved JPY offer, preserves its formatted total through
the generated DTO, and confirms the exact displayed price instead of
looking it up in a separate USD catalog.

The canonical catalog explicitly admits the four existing JPY
Plus/Unlimited IDs for managing an existing JPY subscription. Resolution
checks currency, active state, interval, mode and entitlement version.
Stale USD, retired/unbound and nonrecurring targets are rejected before
releasing schedules or changing entitlements. Retained prices cannot
open new Checkout; the exact current JPY price can reactivate its own
pending cancellation, after promotion-code validation. Existing
cancellation indicators and desktop/legacy/ladder boundaries remain
guarded. No amounts are imported and no production Stripe prices are
created or changed.

Old sheets must update before receiving non-USD offers because their
annual summary hardcodes USD. The currency capability header and
additive response fields are reflected in the generated Dart, Swift and
TypeScript clients.

Closes #23584. Related recognition-only work: #20804. Parallel
submissions #23592 (@PINYOPATTANAWASANPORN) and #23597 (@khoap1220-hue)
were reviewed for consolidation; their useful boundary behaviors are
already covered here. No commits were imported from either submission.
[Coordination and attribution
record](#23584 (comment)).

## Product invariants affected

none

## How it was verified

- **524 backend tests passed in 12 isolated files**, using
`BACKEND_UNIT_TEST_FILE_LIST` with `backend/test.sh`: currency
management, JPY recognition, catalog/compiler and immutable
entitlements, pricing resilience,
proration/decline/cancellation/promotion guards, subscription ingestion,
BYOK payment access and v1 storefront-flag independence.
- **Six real Stripe sandbox flows passed**: catalog → paid immediate JPY
upgrade; JPY annual schedule plus stale-USD rejection preserving it;
declined payment preserves the paid plan; reactivation leaves exactly
one subscription; a real one-time JPY price is excluded/rejected; an
invalid promotion leaves cancellation unchanged. Only synthetic identity
bindings and DB/cache seams are substituted, not Stripe requests. Opt-in
command from `backend/`: `python -m pytest
--confcutdir=tests/integration/billing
tests/integration/billing/test_jpy_plan_changes_stripe.py -v` with an
explicitly supplied standard test key.
- **36 focused Flutter tests**, **23 mobile-verify checks**, targeted
analysis and the three-run mobile performance gate passed.
- **CI follow-up:** refreshed 52 backend/mobile storefront goldens and
the mobile revision assertion for catalog revision 11. Reviewed every
fixture diff: the revision is the only changed field. The formerly
failing storefront file now passes **343 backend tests** with the normal
timing guard; **70 mobile fixture-consumer tests** also pass. Existing
simulator and Stripe evidence remains applicable because this follow-up
changes only test metadata.
- **Fresh iPhone 16 Pro / iOS 26.5 simulator**, Flutter 3.44.5, Japanese
Flutter locale: selected Unlimited and Monthly, verified the exact JPY
confirmation, then cancelled back to the sheet through agent-flutter.
This tests the production PlansSheet and generated DTO with synthetic
offers; payment mutations are exercised separately by the real sandbox
route tests. Replay fixture and commands accompany the screenshots.
- Repository preflight and the final bounded push gate passed, including
full backend type checking, OpenAPI compatibility, all generated
clients, desktop Swift compilation and formatting. Current-head CI is
green at `a37882a71bc9e40e4e7c025bf6f8744a5211b25e` (41 passed, 23
skipped, no pending or failed checks). Aryan supplied a final review
finding no merge-blocking code issues at this head and reported another
371 backend tests and 29 Flutter tests passing; those reruns were
reported by the reviewer rather than repeated by this implementation
session.

## UI evidence

![Japanese annual JPY
offers](https://raw.githubusercontent.com/BasedHardware/omi/36e6d50bc6b9bf48680f1a9d78ce26db13f07840/.agent-artifacts/ui-evidence/fix-jpy-plan-change-currency/001-mobile-ios-jpy-annual-offers.png)

![Monthly Unlimited
selection](https://raw.githubusercontent.com/BasedHardware/omi/36e6d50bc6b9bf48680f1a9d78ce26db13f07840/.agent-artifacts/ui-evidence/fix-jpy-plan-change-currency/002-mobile-ios-jpy-monthly-selection.png)

![Exact JPY confirmation before
payment](https://raw.githubusercontent.com/BasedHardware/omi/36e6d50bc6b9bf48680f1a9d78ce26db13f07840/.agent-artifacts/ui-evidence/fix-jpy-plan-change-currency/003-mobile-ios-jpy-plan-confirmation.png)

## Release and remaining verification

Current-head CI and the supplied final code review have passed. Before
production release, an Omi Stripe owner must verify the production JPY
prices are active with the expected currency, recurrence, mode and
entitlement bindings; personal-sandbox results do not establish the
production catalog or this customer's account state. Merge and deploy
the backend before releasing the currency-aware mobile app. No
production subscriptions/customer data, deployment or app release were
changed by this work. Keep the support case open until the customer
verifies the displayed JPY price and successful plan change on the
released build.

Failure-Class: none

Line-Count-Exception: backend/routers/payment.py | 1846 -> 1934 | Keep
currency admission beside existing authenticated subscription and
schedule mutations; reusable currency resolution is extracted to
utils/billing_currency.py. A broader payment-router split is outside
this safety fix and the exception needs maintainer review.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: this needs work before merge — the JPY catalog direction is right, but this head breaks the plans endpoint for every user without an active paid subscription, and the JPY prices it advertises are then rejected by upgrade admission, so the end-to-end JPY switch still cannot complete.

Verified on the current head:

  1. backend/routers/payment.py:525 — stripe_sub is only assigned inside the active-paid-subscription branch (line 465). For any user without one, referencing it raises NameError, which the handler at line 611 turns into HTTP 500 "Failed to fetch available plans". This is exactly the three assert 500 == 200 failures in tests/unit/test_available_plans_resilience.py. If merged as-is, every free/new user loses the plans sheet.

  2. backend/routers/payment.py:842 — target_price.currency is read unconditionally; the AttributeError there ('SimpleNamespace' object has no attribute 'currency') is what fails the six tests in test_payment_declined_proration.py and test_subscription_ingestion_characterization.py with 500s. Real Stripe prices always carry currency, but the read should be attribute-safe (getattr(target_price, 'currency', None)).

  3. The hardcoded jpy_price_catalog (payment.py:526-535) is not part of the configured catalog that is_purchasable_price_id (backend/utils/subscription.py:919) enforces, so upgrade_subscription_endpoint rejects exactly the JPY price IDs this PR advertises ("Unknown price_id"). Routing the JPY IDs through the same definitions/config as the USD ones would also fix the mobile side: the checkout confirmation guard (app/lib/pages/settings/widgets/plans_sheet.dart:366-370) cross-checks the selected id/amountMinor against the storefront catalog, which does not carry these IDs.

  4. plans_sheet.dart:1275-1277 — the yen copy fix itself is correct (zero-decimal currency, no /100); fine once the catalog issue above is resolved.

  5. backend/tests/unit/test_jpy_price_recognition.py — the new tests monkeypatch payment._validate_price_id and stripe.Price.retrieve, which is why issue 3 wasn't caught; please add an admission-path test that does not patch the validator.

Security/blast radius: payment surface with hardcoded Stripe price IDs outside configuration — a billing-integrity concern if admitted as-is. Affected if wrong: all non-subscribers (plans endpoint) and all JPY subscribers (switch flow).
USER IMPACT: as written, JPY subscribers still could not complete a plan change, and anyone without an active paid subscription would fail to load the plans screen at all.

Still wanted as action items: bind sub_currency safely for users without a subscription, make the currency read attribute-safe, route JPY price IDs through the purchasable catalog so admission/startup validation/mobile storefront all agree, and add an unpatched admission-path test.

This aligns with the maintainer change request already on this head; the currency-catalog contract decision (including the #23591 consolidation) stays with the maintainer.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added security-review Touches auth, provider routing, secrets, or security-sensitive surfaces needs-tests PR introduces logic that should be covered by tests backend Backend Task (python) labels Oct 25, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks for this contribution! Our review requested some changes (see above) and we haven't heard back in a while. If you're still working on it, just push a commit or leave a comment within the next 7 days. To keep the queue healthy we'll close this PR in 14 days if it stays inactive — and it can always be reopened once updates land. Happy to re-review!

@Git-on-my-level Git-on-my-level added the stale-candidate Candidate for kind stale follow-up label Nov 2, 2026
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Hey @PINYOPATTANAWASANPORN 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-tests PR introduces logic that should be covered by tests security-review Touches auth, provider routing, secrets, or security-sensitive surfaces stale-candidate Candidate for kind stale follow-up

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(billing): JPY subscribers cannot change plans in the iOS sheet

3 participants