From b6e90b6803911fdd36a032d7fbb3f817c3ba3dbc Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Thu, 19 Nov 2026 17:10:23 +0100 Subject: [PATCH] feat: add an in-app store to buy and renew domains and Google Workspace or Microsoft 365 mailboxes through GraphKit with a one-screen checkout, automatic DNS, tracking, forwarding, photo and signature setup, a shared prepaid balance with a $10 minimum, $100 default and auto top-up, bundled monthly mailbox billing charged before fulfilment, a plan gate that keeps purchased mailboxes readable but stops sending and warmup when the plan lapses, AI overage opt-in, admin, API, CLI, MCP, agency and partner add-on coverage, and a locked store for self-hosts until a GraphKit API key is set --- Makefile | 5 + admin/src/app/dashboard/HealthPage.tsx | 19 +- .../app/dashboard/OrganizationDetailPage.tsx | 5 + .../dashboard/configuration/SettingsTab.tsx | 219 +++ .../dashboard/health/IntegrationsTab.test.tsx | 75 + .../app/dashboard/health/IntegrationsTab.tsx | 342 +++++ .../dashboard/partners/PartnerDetailPage.tsx | 453 ++++++ .../dashboard/partners/PartnerStatements.tsx | 78 + .../app/dashboard/partners/PartnersPage.tsx | 164 ++ .../src/app/dashboard/store/EconomicsTab.tsx | 135 ++ admin/src/app/dashboard/store/HealthTab.tsx | 220 +++ .../src/app/dashboard/store/RefundDialog.tsx | 201 +++ .../src/app/dashboard/store/StoreDrawers.tsx | 546 +++++++ admin/src/app/dashboard/store/StoreLists.tsx | 335 +++++ admin/src/app/dashboard/store/StorePage.tsx | 61 + .../dashboard/store/StoreWorkspacePage.tsx | 151 ++ admin/src/app/dashboard/store/columns.tsx | 210 +++ admin/src/app/dashboard/store/format.ts | 102 ++ admin/src/app/dashboard/store/store.test.tsx | 141 ++ .../src/app/dashboard/store/useStoreAction.ts | 47 + .../src/app/dashboard/store/useStoreHealth.ts | 7 + admin/src/components/layout/nav.ts | 7 + admin/src/lib/api/client/admin/instance.ts | 16 + admin/src/lib/api/client/admin/partners.ts | 144 ++ admin/src/lib/api/client/admin/store.ts | 363 +++++ admin/src/main.tsx | 8 + cmd/backend/main.go | 140 +- cmd/cli/cli_test.go | 12 +- cmd/cli/factory.go | 10 +- cmd/cli/resources.go | 54 + cmd/cli/specs.go | 292 +++- cmd/cli/store.go | 695 +++++++++ cmd/cli/store_test.go | 372 +++++ cmd/consumer/main.go | 5 +- cmd/warmblyctl/main.go | 5 + cmd/warmblyctl/partner.go | 156 ++ cmd/warmblyctl/remote_admin.go | 18 +- cmd/warmblyctl/remote_catalog.go | 27 + docs/content/docs/api/authentication.mdx | 4 + docs/content/docs/api/cli.mdx | 50 + docs/content/docs/api/endpoints.mdx | 127 +- docs/content/docs/api/error-codes.mdx | 105 +- docs/content/docs/api/mcp.mdx | 10 + docs/content/docs/api/permissions.mdx | 56 +- .../docs/api/reference/account-org.mdx | 29 +- docs/content/docs/development/admin-panel.mdx | 37 +- .../docs/development/configuration.mdx | 78 +- .../content/docs/development/data-control.mdx | 40 + docs/content/docs/development/meta.json | 1 + .../development/operator-notifications.mdx | 1 + docs/content/docs/development/partners.mdx | 156 ++ docs/content/docs/development/warmblyctl.mdx | 21 + docs/content/docs/guides/ai-credits.mdx | 42 +- docs/content/docs/guides/buy-mailboxes.mdx | 496 ++++++ docs/content/docs/guides/mailboxes.mdx | 12 + docs/content/docs/guides/meta.json | 1 + .../docs/guides/workspace-export-import.mdx | 4 + internal/api/card_setup_route_test.go | 67 + internal/api/fresh_auth_routes_test.go | 55 +- internal/api/handler/admin_partners.go | 278 ++++ internal/api/handler/admin_store.go | 361 +++++ .../api/handler/admin_store_connection.go | 110 ++ internal/api/handler/ai_reply.go | 3 +- internal/api/handler/auth.go | 2 + internal/api/handler/balance_burn_test.go | 58 + internal/api/handler/card_setup_test.go | 92 ++ internal/api/handler/credits.go | 166 +- internal/api/handler/email.go | 3 + internal/api/handler/email_bulk.go | 3 + internal/api/handler/email_onboarding.go | 9 + internal/api/handler/generation.go | 4 +- internal/api/handler/handler.go | 10 +- internal/api/handler/identity.go | 2 +- internal/api/handler/mailbox_lock.go | 66 + internal/api/handler/mailbox_lock_test.go | 159 ++ internal/api/handler/mcp_agency_test.go | 3 + .../api/handler/mcp_partner_paused_test.go | 69 + internal/api/handler/mcp_server.go | 10 +- internal/api/handler/organization.go | 5 + internal/api/handler/partner_api.go | 334 ++++ .../api/handler/partner_contact_email_test.go | 109 ++ internal/api/handler/partner_gates.go | 131 ++ internal/api/handler/partner_mailboxes_api.go | 188 +++ internal/api/handler/store.go | 790 ++++++++++ internal/api/handler/store_connection_test.go | 172 +++ internal/api/handler/store_patch_test.go | 65 + internal/api/handler/store_photo_test.go | 105 ++ internal/api/middleware/idempotency.go | 4 +- internal/api/middleware/idempotency_test.go | 19 + internal/api/middleware/store_access_test.go | 100 ++ internal/api/partner_bound_routes_test.go | 58 + internal/api/routes.go | 123 +- internal/api/store_routes_test.go | 169 +++ internal/app/agencyhome/service.go | 15 + internal/app/aiagent/service.go | 13 +- internal/app/aitools/tools.go | 2 + .../app/aitools/tools_mailbox_lock_test.go | 44 + internal/app/aitools/tools_mailboxes.go | 5 + internal/app/aitools/tools_store.go | 373 +++++ internal/app/aitools/tools_store_test.go | 124 ++ internal/app/auth/external_idtoken.go | 5 + internal/app/auth/sso_link_test.go | 17 + internal/app/balance/service.go | 116 +- internal/app/balance/service_test.go | 125 ++ internal/app/brandkit/resolver.go | 48 +- internal/app/cliauth/service.go | 2 +- internal/app/connectlink/oauth.go | 7 + internal/app/connectlink/partner.go | 101 ++ internal/app/connectlink/partner_test.go | 119 ++ internal/app/connectlink/service.go | 8 +- internal/app/credits/overage_test.go | 117 ++ internal/app/credits/service.go | 195 ++- internal/app/delegation/purchased.go | 254 ++++ internal/app/delegation/purchased_test.go | 253 ++++ internal/app/delegation/service.go | 55 +- internal/app/delegation/service_test.go | 26 +- internal/app/delegation/signature.go | 82 + internal/app/delegation/signature_test.go | 59 + internal/app/email/existing.go | 9 +- internal/app/email/handler.go | 3 +- internal/app/email/onboarding.go | 9 +- internal/app/feature/gate.go | 44 +- internal/app/feature/mailbox_hold_test.go | 51 + internal/app/feature/partner_hold.go | 77 + internal/app/feature/partner_hold_test.go | 37 + internal/app/instancecheck/checks_store.go | 34 + .../app/instancecheck/checks_store_test.go | 26 + internal/app/instancecheck/instancecheck.go | 8 + internal/app/instanceconfig/entries.go | 24 + internal/app/instancesettings/document.go | 32 + internal/app/instancesettings/service.go | 8 + internal/app/instancesettings/store_retail.go | 96 ++ internal/app/keystatus/keystatus.go | 3 + internal/app/keystatus/keystatus_test.go | 3 + internal/app/leadfinder/service.go | 3 + internal/app/mailboxavatar/service.go | 6 +- internal/app/opsnotify/events.go | 10 +- internal/app/opsnotify/signin.go | 2 + internal/app/organization/service.go | 10 +- internal/app/orgtransfer/spec.go | 11 + internal/app/partner/apikeys.go | 145 ++ internal/app/partner/connect.go | 202 +++ internal/app/partner/events.go | 186 +++ internal/app/partner/groups.go | 184 +++ internal/app/partner/hold.go | 144 ++ internal/app/partner/hold_test.go | 83 + internal/app/partner/idempotency.go | 129 ++ internal/app/partner/keys.go | 62 + internal/app/partner/keys_test.go | 116 ++ internal/app/partner/mailbox_lock_test.go | 35 + internal/app/partner/mailboxes.go | 806 ++++++++++ internal/app/partner/mailboxes_live_test.go | 203 +++ internal/app/partner/mailboxes_test.go | 107 ++ internal/app/partner/orgs.go | 597 ++++++++ internal/app/partner/partner_live_test.go | 642 ++++++++ internal/app/partner/people.go | 394 +++++ internal/app/partner/people_test.go | 27 + internal/app/partner/service.go | 490 ++++++ internal/app/partner/sweep.go | 146 ++ internal/app/partner/tokens.go | 72 + internal/app/partner/usage.go | 345 +++++ internal/app/placement/service.go | 3 + internal/app/research/service.go | 3 + internal/app/sendingdomain/vendors.go | 60 + internal/app/slackapp/agent.go | 5 +- internal/app/slackapp/links.go | 4 +- internal/app/store/adapters.go | 71 + internal/app/store/admin.go | 990 ++++++++++++ internal/app/store/admin_test.go | 338 +++++ internal/app/store/agency.go | 175 +++ internal/app/store/autocharge_test.go | 212 +++ internal/app/store/billing.go | 409 +++++ internal/app/store/bundle_test.go | 292 ++++ internal/app/store/checkout.go | 777 ++++++++++ internal/app/store/connect.go | 204 +++ internal/app/store/connection.go | 206 +++ internal/app/store/connection_settings.go | 401 +++++ internal/app/store/connection_test.go | 418 +++++ internal/app/store/contact_error_test.go | 86 ++ internal/app/store/domains.go | 662 ++++++++ internal/app/store/errors.go | 306 ++++ internal/app/store/forward.go | 57 + internal/app/store/inventory.go | 408 +++++ internal/app/store/lifecycle.go | 78 + internal/app/store/lifecycle_test.go | 217 +++ internal/app/store/mailbox_billing.go | 587 ++++++++ internal/app/store/memphotos_test.go | 155 ++ internal/app/store/memrepo_test.go | 1338 +++++++++++++++++ internal/app/store/memsignatures_test.go | 95 ++ internal/app/store/money_test.go | 758 ++++++++++ internal/app/store/photos.go | 412 +++++ internal/app/store/photos_test.go | 456 ++++++ internal/app/store/pricing.go | 49 + internal/app/store/pricing_test.go | 121 ++ internal/app/store/registrant.go | 175 +++ internal/app/store/reload.go | 194 +++ internal/app/store/rev2_test.go | 374 +++++ internal/app/store/service.go | 654 ++++++++ internal/app/store/signature.go | 165 ++ internal/app/store/signature_test.go | 167 ++ internal/app/store/store_test.go | 644 ++++++++ internal/app/store/sync.go | 432 ++++++ internal/app/store/types.go | 435 ++++++ internal/app/store/upkeep.go | 90 ++ internal/app/store/upkeep_test.go | 30 + internal/app/store/vendor.go | 127 ++ internal/app/stripe/balance.go | 146 ++ internal/app/stripe/card_setup_test.go | 145 ++ internal/app/stripe/disabled.go | 10 + internal/app/stripe/service.go | 20 + internal/app/token/config.go | 4 + internal/app/token/purpose_test.go | 1 + internal/cli/output/output.go | 18 +- internal/cli/output/output_test.go | 8 + internal/config/admin_url.go | 24 + internal/config/admin_url_test.go | 19 + internal/config/graphkit.go | 48 + internal/errx/canceled_test.go | 34 + internal/errx/errx.go | 9 + internal/errx/status.go | 12 + .../db/migrations/000403_store.down.sql | 28 + .../db/migrations/000403_store.up.sql | 175 +++ .../db/migrations/000404_partners.down.sql | 10 + .../db/migrations/000404_partners.up.sql | 158 ++ .../000405_partner_mailboxes.down.sql | 6 + .../000405_partner_mailboxes.up.sql | 117 ++ .../db/migrations/000406_ai_overage.down.sql | 3 + .../db/migrations/000406_ai_overage.up.sql | 7 + .../migrations/000407_store_photos.down.sql | 7 + .../db/migrations/000407_store_photos.up.sql | 24 + .../000408_store_signatures.down.sql | 8 + .../migrations/000408_store_signatures.up.sql | 12 + .../000409_store_graphkit_connection.down.sql | 1 + .../000409_store_graphkit_connection.up.sql | 13 + .../000410_store_billing_keys.down.sql | 9 + .../000410_store_billing_keys.up.sql | 25 + internal/infrastructure/pubsub/events.go | 35 + internal/models/api_permission.go | 18 +- internal/models/audit.go | 12 +- internal/models/credits.go | 27 +- internal/models/email.go | 8 + internal/models/mailbox_import.go | 2 + internal/models/organization.go | 2 + internal/models/partner.go | 171 +++ internal/models/partner_mailbox.go | 136 ++ internal/models/store.go | 254 ++++ internal/models/user.go | 43 +- internal/notify/factory.go | 15 +- internal/notify/undeliverable.go | 42 + internal/notify/undeliverable_test.go | 32 + internal/pkg/graphkit/client.go | 631 ++++++++ internal/pkg/graphkit/client_test.go | 144 ++ internal/pkg/graphkit/errors.go | 172 +++ internal/pkg/graphkit/fake.go | 582 +++++++ internal/pkg/graphkit/fake_domains.go | 645 ++++++++ internal/pkg/graphkit/fake_orders.go | 646 ++++++++ internal/pkg/graphkit/fake_partner.go | 485 ++++++ internal/pkg/graphkit/fake_test.go | 397 +++++ internal/pkg/graphkit/types.go | 607 ++++++++ internal/pkg/graphkit/webhook.go | 99 ++ internal/pkg/graphkit/webhook_test.go | 61 + .../repository/credit_purchased_live_test.go | 203 +++ .../repository/partner_mailbox_live_test.go | 271 ++++ internal/repository/partner_send_gate.go | 90 ++ internal/repository/pg_agency.go | 7 +- internal/repository/pg_ai_settings.go | 21 +- internal/repository/pg_audit.go | 19 +- internal/repository/pg_credit.go | 218 ++- internal/repository/pg_email.go | 28 +- internal/repository/pg_mailbox_sources.go | 12 +- internal/repository/pg_oauth.go | 8 +- internal/repository/pg_org_risk.go | 7 +- internal/repository/pg_organization.go | 6 +- internal/repository/pg_partner.go | 747 +++++++++ internal/repository/pg_partner_mailbox.go | 698 +++++++++ internal/repository/pg_saved_card_charge.go | 20 +- internal/repository/pg_send_recovery.go | 9 + internal/repository/pg_slack.go | 11 +- internal/repository/pg_store.go | 1194 +++++++++++++++ internal/repository/pg_store_admin.go | 343 +++++ internal/repository/pg_store_connection.go | 121 ++ internal/repository/pg_team.go | 12 +- internal/repository/pg_user.go | 4 +- internal/repository/send_admission.go | 5 +- .../store_email_purchased_live_test.go | 64 + internal/repository/store_live_test.go | 178 +++ .../repository/store_mailbox_end_live_test.go | 80 + internal/repository/store_money_live_test.go | 414 +++++ internal/repository/store_rev2_live_test.go | 98 ++ internal/scheduler/campaign_sender.go | 17 + internal/tasks/email_task.go | 5 +- internal/tasks/warmup_pool_reconcile.go | 8 + internal/tasks/warmup_reconciler.go | 3 +- qa/flows/admin-graphkit.flow.ts | 16 + qa/flows/admin-store-partners.flow.ts | 50 + qa/flows/balance.flow.ts | 50 +- qa/flows/buy-mailboxes.flow.ts | 150 ++ qa/flows/manage-purchases.flow.ts | 54 + qa/flows/partner-managed.flow.ts | 49 + qa/flows/store-locked.flow.ts | 27 + .../lib/realtime_web/channels/org_channel.ex | 4 + skills/warmbly-api/SKILL.md | 38 +- skills/warmbly-cli/SKILL.md | 50 +- skills/warmbly-ops/SKILL.md | 18 + web/package.json | 1 + web/pnpm-lock.yaml | 9 + web/securityHeaders.ts | 11 +- web/src/app/app/agency/api-keys/page.tsx | 5 +- web/src/app/app/agency/store/page.tsx | 320 ++++ .../api-keys/_components/CreateKeyModal.tsx | 11 +- .../api-keys/_components/KeyDetailDrawer.tsx | 3 +- web/src/app/app/automations/page.tsx | 3 +- web/src/app/app/campaigns/[id]/layout.tsx | 6 +- web/src/app/app/campaigns/page.tsx | 2 + web/src/app/app/emails/buy/locked.test.tsx | 76 + web/src/app/app/emails/buy/orders/page.tsx | 206 +++ web/src/app/app/emails/buy/page.tsx | 264 ++++ .../emails/domains/browsePersistence.test.tsx | 11 + web/src/app/app/emails/domains/page.tsx | 62 +- .../emails/domains/purchasedPaused.test.tsx | 66 + web/src/app/app/emails/page.tsx | 98 +- .../app/app/settings/billing/AIUsageCard.tsx | 103 ++ .../settings/billing/AutoReloadSection.tsx | 294 ---- .../settings/billing/BalanceActivity.test.tsx | 61 + .../app/settings/billing/BalanceActivity.tsx | 141 +- .../app/settings/billing/BalanceTab.test.tsx | 187 +++ .../app/app/settings/billing/BalanceTab.tsx | 223 +-- web/src/app/app/settings/billing/page.tsx | 26 +- web/src/app/app/settings/danger/page.tsx | 14 +- web/src/app/app/settings/layout.tsx | 19 +- web/src/app/app/settings/members/page.tsx | 5 +- .../settings/oauth-apps/RegisterAppDialog.tsx | 11 +- web/src/app/app/settings/oauth-apps/page.tsx | 7 +- web/src/app/app/settings/profile/page.tsx | 12 +- web/src/app/app/settings/security/page.tsx | 20 +- web/src/app/auth/partner/page.tsx | 87 ++ web/src/app/select-org/page.tsx | 3 +- .../components/app/billing/AddFundsDialog.tsx | 667 ++++++++ .../components/app/billing/BalanceBanner.tsx | 5 +- .../app/billing/BalanceOverview.tsx | 225 +++ web/src/components/app/billing/TopUpPanel.tsx | 150 -- web/src/components/app/billing/funds.test.ts | 50 + web/src/components/app/billing/funds.ts | 73 + .../components/app/contacts/ContactsTable.tsx | 12 + .../app/emails/BulkSignatureDialog.tsx | 19 +- .../components/app/emails/CloudPathsPanel.tsx | 39 +- .../components/app/emails/InboxDetails.tsx | 89 +- .../app/emails/MailboxSourceChip.tsx | 11 +- .../app/emails/PartnerEnablement.tsx | 63 + .../app/emails/UnknownPlaceholders.tsx | 15 + .../app/modals/PermissionDeniedModal.tsx | 2 + .../components/app/store/BulkPhotoButton.tsx | 42 + web/src/components/app/store/BuyEntry.tsx | 96 ++ web/src/components/app/store/CardField.tsx | 124 ++ .../components/app/store/ConnectionGuide.tsx | 278 ++++ web/src/components/app/store/Controls.tsx | 149 ++ web/src/components/app/store/CopyButton.tsx | 39 + web/src/components/app/store/DnsRecords.tsx | 338 +++++ web/src/components/app/store/DomainSearch.tsx | 297 ++++ .../components/app/store/Illustrations.tsx | 183 +++ web/src/components/app/store/OrderList.tsx | 547 +++++++ web/src/components/app/store/OrderSummary.tsx | 588 ++++++++ .../components/app/store/OwnDomainPanel.tsx | 337 +++++ .../components/app/store/PatternPicker.tsx | 188 +++ web/src/components/app/store/PhotoPicker.tsx | 318 ++++ web/src/components/app/store/PlanUpsell.tsx | 46 + web/src/components/app/store/Press.tsx | 42 + .../components/app/store/PurchasedDomains.tsx | 668 ++++++++ web/src/components/app/store/Senders.tsx | 427 ++++++ web/src/components/app/store/SetupTrack.tsx | 464 ++++++ web/src/components/app/store/SignInDialog.tsx | 121 ++ web/src/components/app/store/StoreLinks.tsx | 57 + web/src/components/app/store/StoreLocked.tsx | 124 ++ web/src/components/app/store/StorePaused.tsx | 34 + .../components/app/store/StoreSignature.tsx | 154 ++ .../components/app/store/SubscriptionCard.tsx | 184 +++ .../app/store/addMailboxesCopy.test.ts | 28 + .../components/app/store/addMailboxesCopy.ts | 35 + web/src/components/app/store/cardSave.test.ts | 57 + web/src/components/app/store/cardSave.ts | 49 + .../app/store/purchasedDomainsPaused.test.tsx | 135 ++ web/src/components/app/store/senders.test.tsx | 152 ++ .../components/app/store/setupTrack.test.tsx | 30 + .../components/app/store/storeLocked.test.tsx | 149 ++ web/src/components/app/store/useCheckout.ts | 419 ++++++ .../app/store/usePurchasedMailbox.ts | 42 + .../app/unibox/compose/ComposeButton.tsx | 17 +- web/src/components/layout/AppHeader.tsx | 5 +- web/src/components/layout/AppShell.tsx | 9 +- web/src/components/layout/Page.tsx | 47 +- .../components/layout/PartnerPausedBar.tsx | 20 + web/src/components/layout/UserNav.tsx | 24 +- .../components/layout/agency/AgencyHeader.tsx | 7 +- .../components/layout/agency/AgencyNav.tsx | 11 +- web/src/components/shared/CommandPalette.tsx | 5 +- web/src/components/ui/PermissionButton.tsx | 14 +- web/src/csp.test.ts | 16 +- web/src/hooks/useFeatureAccess.ts | 9 +- web/src/hooks/useHeaderBreadcrumbs.ts | 1 + web/src/hooks/useKeyboardShortcuts.ts | 3 + web/src/hooks/usePartnerManaged.ts | 7 + web/src/hooks/usePermission.ts | 30 +- web/src/hooks/useRealtimeEvents.ts | 29 + web/src/hooks/useWorkspaceWritable.test.tsx | 61 + web/src/hooks/useWorkspaceWritable.ts | 34 + web/src/lib/api/client/Request.ts | 13 + .../lib/api/client/app/agency/agencyStore.ts | 5 + .../client/app/emails/getPartnerMailboxes.ts | 10 + web/src/lib/api/client/app/store/store.ts | 171 +++ .../api/client/app/subscription/balance.ts | 15 + .../app/subscription/getCreditTransactions.ts | 5 + .../app/subscription/updateCreditSettings.ts | 2 +- .../api/client/auth/exchangePartnerLogin.ts | 12 + web/src/lib/api/client/normalizeError.ts | 6 + .../lib/api/hooks/app/agency/useAgencyHome.ts | 2 + .../api/hooks/app/agency/useAgencyStore.ts | 28 + .../hooks/app/emails/usePartnerMailboxes.ts | 20 + web/src/lib/api/hooks/app/store/useStore.ts | 506 +++++++ .../api/hooks/app/subscription/useBalance.ts | 13 + .../app/subscription/useCreditTransactions.ts | 9 +- .../lib/api/models/app/agency/AgencyStore.ts | 43 + web/src/lib/api/models/app/apikeys/APIKey.ts | 6 +- web/src/lib/api/models/app/emails/Inbox.ts | 4 + .../api/models/app/emails/PartnerMailbox.ts | 9 + .../models/app/organizations/Organization.ts | 11 + web/src/lib/api/models/app/store/Store.ts | 331 ++++ .../api/models/app/subscription/Credits.ts | 22 + web/src/lib/api/models/auth/User.ts | 2 + web/src/lib/bitmask.test.ts | 48 + web/src/lib/bitmask.ts | 34 + web/src/lib/browse-accounts-analytics.ts | 2 +- web/src/lib/buy/addresses.test.ts | 52 + web/src/lib/buy/addresses.ts | 126 ++ web/src/lib/buy/cart.test.ts | 525 +++++++ web/src/lib/buy/cart.ts | 789 ++++++++++ web/src/lib/buy/checkout.test.ts | 89 ++ web/src/lib/buy/checkout.ts | 146 ++ web/src/lib/buy/connection.test.ts | 77 + web/src/lib/buy/connection.ts | 54 + web/src/lib/buy/errors.test.ts | 82 + web/src/lib/buy/errors.ts | 132 ++ web/src/lib/buy/money.test.ts | 28 + web/src/lib/buy/money.ts | 38 + web/src/lib/buy/motion.ts | 13 + web/src/lib/buy/patterns.test.ts | 98 ++ web/src/lib/buy/patterns.ts | 134 ++ web/src/lib/buy/photo.test.ts | 38 + web/src/lib/buy/photo.ts | 69 + web/src/lib/buy/purchased.test.ts | 25 + web/src/lib/buy/purchased.ts | 26 + web/src/lib/buy/registrant.test.ts | 43 + web/src/lib/buy/registrant.ts | 81 + web/src/lib/buy/resume.test.ts | 45 + web/src/lib/buy/resume.ts | 61 + web/src/lib/buy/stripe.ts | 24 + web/src/lib/buy/track.test.ts | 131 ++ web/src/lib/buy/track.ts | 246 +++ web/src/lib/email/signaturePlaceholders.ts | 14 + web/src/lib/mailboxSource.test.ts | 13 + web/src/lib/mailboxSource.ts | 11 +- web/src/lib/money.ts | 7 +- web/src/lib/partnerPause.ts | 39 + web/src/lib/plans.ts | 2 + web/src/lib/userDisplay.ts | 17 + web/src/routeLoaders.ts | 19 +- web/src/router.test.ts | 17 + web/src/router.tsx | 21 +- 467 files changed, 59065 insertions(+), 1105 deletions(-) create mode 100644 admin/src/app/dashboard/health/IntegrationsTab.test.tsx create mode 100644 admin/src/app/dashboard/health/IntegrationsTab.tsx create mode 100644 admin/src/app/dashboard/partners/PartnerDetailPage.tsx create mode 100644 admin/src/app/dashboard/partners/PartnerStatements.tsx create mode 100644 admin/src/app/dashboard/partners/PartnersPage.tsx create mode 100644 admin/src/app/dashboard/store/EconomicsTab.tsx create mode 100644 admin/src/app/dashboard/store/HealthTab.tsx create mode 100644 admin/src/app/dashboard/store/RefundDialog.tsx create mode 100644 admin/src/app/dashboard/store/StoreDrawers.tsx create mode 100644 admin/src/app/dashboard/store/StoreLists.tsx create mode 100644 admin/src/app/dashboard/store/StorePage.tsx create mode 100644 admin/src/app/dashboard/store/StoreWorkspacePage.tsx create mode 100644 admin/src/app/dashboard/store/columns.tsx create mode 100644 admin/src/app/dashboard/store/format.ts create mode 100644 admin/src/app/dashboard/store/store.test.tsx create mode 100644 admin/src/app/dashboard/store/useStoreAction.ts create mode 100644 admin/src/app/dashboard/store/useStoreHealth.ts create mode 100644 admin/src/lib/api/client/admin/partners.ts create mode 100644 admin/src/lib/api/client/admin/store.ts create mode 100644 cmd/cli/store.go create mode 100644 cmd/cli/store_test.go create mode 100644 cmd/warmblyctl/partner.go create mode 100644 docs/content/docs/development/partners.mdx create mode 100644 docs/content/docs/guides/buy-mailboxes.mdx create mode 100644 internal/api/card_setup_route_test.go create mode 100644 internal/api/handler/admin_partners.go create mode 100644 internal/api/handler/admin_store.go create mode 100644 internal/api/handler/admin_store_connection.go create mode 100644 internal/api/handler/balance_burn_test.go create mode 100644 internal/api/handler/card_setup_test.go create mode 100644 internal/api/handler/mailbox_lock.go create mode 100644 internal/api/handler/mailbox_lock_test.go create mode 100644 internal/api/handler/mcp_partner_paused_test.go create mode 100644 internal/api/handler/partner_api.go create mode 100644 internal/api/handler/partner_contact_email_test.go create mode 100644 internal/api/handler/partner_gates.go create mode 100644 internal/api/handler/partner_mailboxes_api.go create mode 100644 internal/api/handler/store.go create mode 100644 internal/api/handler/store_connection_test.go create mode 100644 internal/api/handler/store_patch_test.go create mode 100644 internal/api/handler/store_photo_test.go create mode 100644 internal/api/middleware/store_access_test.go create mode 100644 internal/api/partner_bound_routes_test.go create mode 100644 internal/api/store_routes_test.go create mode 100644 internal/app/aitools/tools_mailbox_lock_test.go create mode 100644 internal/app/aitools/tools_store.go create mode 100644 internal/app/aitools/tools_store_test.go create mode 100644 internal/app/connectlink/partner.go create mode 100644 internal/app/connectlink/partner_test.go create mode 100644 internal/app/credits/overage_test.go create mode 100644 internal/app/delegation/purchased.go create mode 100644 internal/app/delegation/purchased_test.go create mode 100644 internal/app/delegation/signature.go create mode 100644 internal/app/delegation/signature_test.go create mode 100644 internal/app/feature/mailbox_hold_test.go create mode 100644 internal/app/feature/partner_hold.go create mode 100644 internal/app/feature/partner_hold_test.go create mode 100644 internal/app/instancecheck/checks_store.go create mode 100644 internal/app/instancecheck/checks_store_test.go create mode 100644 internal/app/instancesettings/store_retail.go create mode 100644 internal/app/partner/apikeys.go create mode 100644 internal/app/partner/connect.go create mode 100644 internal/app/partner/events.go create mode 100644 internal/app/partner/groups.go create mode 100644 internal/app/partner/hold.go create mode 100644 internal/app/partner/hold_test.go create mode 100644 internal/app/partner/idempotency.go create mode 100644 internal/app/partner/keys.go create mode 100644 internal/app/partner/keys_test.go create mode 100644 internal/app/partner/mailbox_lock_test.go create mode 100644 internal/app/partner/mailboxes.go create mode 100644 internal/app/partner/mailboxes_live_test.go create mode 100644 internal/app/partner/mailboxes_test.go create mode 100644 internal/app/partner/orgs.go create mode 100644 internal/app/partner/partner_live_test.go create mode 100644 internal/app/partner/people.go create mode 100644 internal/app/partner/people_test.go create mode 100644 internal/app/partner/service.go create mode 100644 internal/app/partner/sweep.go create mode 100644 internal/app/partner/tokens.go create mode 100644 internal/app/partner/usage.go create mode 100644 internal/app/sendingdomain/vendors.go create mode 100644 internal/app/store/adapters.go create mode 100644 internal/app/store/admin.go create mode 100644 internal/app/store/admin_test.go create mode 100644 internal/app/store/agency.go create mode 100644 internal/app/store/autocharge_test.go create mode 100644 internal/app/store/billing.go create mode 100644 internal/app/store/bundle_test.go create mode 100644 internal/app/store/checkout.go create mode 100644 internal/app/store/connect.go create mode 100644 internal/app/store/connection.go create mode 100644 internal/app/store/connection_settings.go create mode 100644 internal/app/store/connection_test.go create mode 100644 internal/app/store/contact_error_test.go create mode 100644 internal/app/store/domains.go create mode 100644 internal/app/store/errors.go create mode 100644 internal/app/store/forward.go create mode 100644 internal/app/store/inventory.go create mode 100644 internal/app/store/lifecycle.go create mode 100644 internal/app/store/lifecycle_test.go create mode 100644 internal/app/store/mailbox_billing.go create mode 100644 internal/app/store/memphotos_test.go create mode 100644 internal/app/store/memrepo_test.go create mode 100644 internal/app/store/memsignatures_test.go create mode 100644 internal/app/store/money_test.go create mode 100644 internal/app/store/photos.go create mode 100644 internal/app/store/photos_test.go create mode 100644 internal/app/store/pricing.go create mode 100644 internal/app/store/pricing_test.go create mode 100644 internal/app/store/registrant.go create mode 100644 internal/app/store/reload.go create mode 100644 internal/app/store/rev2_test.go create mode 100644 internal/app/store/service.go create mode 100644 internal/app/store/signature.go create mode 100644 internal/app/store/signature_test.go create mode 100644 internal/app/store/store_test.go create mode 100644 internal/app/store/sync.go create mode 100644 internal/app/store/types.go create mode 100644 internal/app/store/upkeep.go create mode 100644 internal/app/store/upkeep_test.go create mode 100644 internal/app/store/vendor.go create mode 100644 internal/app/stripe/card_setup_test.go create mode 100644 internal/config/admin_url.go create mode 100644 internal/config/admin_url_test.go create mode 100644 internal/config/graphkit.go create mode 100644 internal/errx/canceled_test.go create mode 100644 internal/errx/status.go create mode 100644 internal/infrastructure/db/migrations/000403_store.down.sql create mode 100644 internal/infrastructure/db/migrations/000403_store.up.sql create mode 100644 internal/infrastructure/db/migrations/000404_partners.down.sql create mode 100644 internal/infrastructure/db/migrations/000404_partners.up.sql create mode 100644 internal/infrastructure/db/migrations/000405_partner_mailboxes.down.sql create mode 100644 internal/infrastructure/db/migrations/000405_partner_mailboxes.up.sql create mode 100644 internal/infrastructure/db/migrations/000406_ai_overage.down.sql create mode 100644 internal/infrastructure/db/migrations/000406_ai_overage.up.sql create mode 100644 internal/infrastructure/db/migrations/000407_store_photos.down.sql create mode 100644 internal/infrastructure/db/migrations/000407_store_photos.up.sql create mode 100644 internal/infrastructure/db/migrations/000408_store_signatures.down.sql create mode 100644 internal/infrastructure/db/migrations/000408_store_signatures.up.sql create mode 100644 internal/infrastructure/db/migrations/000409_store_graphkit_connection.down.sql create mode 100644 internal/infrastructure/db/migrations/000409_store_graphkit_connection.up.sql create mode 100644 internal/infrastructure/db/migrations/000410_store_billing_keys.down.sql create mode 100644 internal/infrastructure/db/migrations/000410_store_billing_keys.up.sql create mode 100644 internal/models/partner.go create mode 100644 internal/models/partner_mailbox.go create mode 100644 internal/models/store.go create mode 100644 internal/notify/undeliverable.go create mode 100644 internal/notify/undeliverable_test.go create mode 100644 internal/pkg/graphkit/client.go create mode 100644 internal/pkg/graphkit/client_test.go create mode 100644 internal/pkg/graphkit/errors.go create mode 100644 internal/pkg/graphkit/fake.go create mode 100644 internal/pkg/graphkit/fake_domains.go create mode 100644 internal/pkg/graphkit/fake_orders.go create mode 100644 internal/pkg/graphkit/fake_partner.go create mode 100644 internal/pkg/graphkit/fake_test.go create mode 100644 internal/pkg/graphkit/types.go create mode 100644 internal/pkg/graphkit/webhook.go create mode 100644 internal/pkg/graphkit/webhook_test.go create mode 100644 internal/repository/credit_purchased_live_test.go create mode 100644 internal/repository/partner_mailbox_live_test.go create mode 100644 internal/repository/partner_send_gate.go create mode 100644 internal/repository/pg_partner.go create mode 100644 internal/repository/pg_partner_mailbox.go create mode 100644 internal/repository/pg_store.go create mode 100644 internal/repository/pg_store_admin.go create mode 100644 internal/repository/pg_store_connection.go create mode 100644 internal/repository/store_email_purchased_live_test.go create mode 100644 internal/repository/store_live_test.go create mode 100644 internal/repository/store_mailbox_end_live_test.go create mode 100644 internal/repository/store_money_live_test.go create mode 100644 internal/repository/store_rev2_live_test.go create mode 100644 qa/flows/admin-graphkit.flow.ts create mode 100644 qa/flows/admin-store-partners.flow.ts create mode 100644 qa/flows/buy-mailboxes.flow.ts create mode 100644 qa/flows/manage-purchases.flow.ts create mode 100644 qa/flows/partner-managed.flow.ts create mode 100644 qa/flows/store-locked.flow.ts create mode 100644 web/src/app/app/agency/store/page.tsx create mode 100644 web/src/app/app/emails/buy/locked.test.tsx create mode 100644 web/src/app/app/emails/buy/orders/page.tsx create mode 100644 web/src/app/app/emails/buy/page.tsx create mode 100644 web/src/app/app/emails/domains/purchasedPaused.test.tsx delete mode 100644 web/src/app/app/settings/billing/AutoReloadSection.tsx create mode 100644 web/src/app/app/settings/billing/BalanceActivity.test.tsx create mode 100644 web/src/app/app/settings/billing/BalanceTab.test.tsx create mode 100644 web/src/app/auth/partner/page.tsx create mode 100644 web/src/components/app/billing/AddFundsDialog.tsx create mode 100644 web/src/components/app/billing/BalanceOverview.tsx delete mode 100644 web/src/components/app/billing/TopUpPanel.tsx create mode 100644 web/src/components/app/billing/funds.test.ts create mode 100644 web/src/components/app/billing/funds.ts create mode 100644 web/src/components/app/emails/PartnerEnablement.tsx create mode 100644 web/src/components/app/emails/UnknownPlaceholders.tsx create mode 100644 web/src/components/app/store/BulkPhotoButton.tsx create mode 100644 web/src/components/app/store/BuyEntry.tsx create mode 100644 web/src/components/app/store/CardField.tsx create mode 100644 web/src/components/app/store/ConnectionGuide.tsx create mode 100644 web/src/components/app/store/Controls.tsx create mode 100644 web/src/components/app/store/CopyButton.tsx create mode 100644 web/src/components/app/store/DnsRecords.tsx create mode 100644 web/src/components/app/store/DomainSearch.tsx create mode 100644 web/src/components/app/store/Illustrations.tsx create mode 100644 web/src/components/app/store/OrderList.tsx create mode 100644 web/src/components/app/store/OrderSummary.tsx create mode 100644 web/src/components/app/store/OwnDomainPanel.tsx create mode 100644 web/src/components/app/store/PatternPicker.tsx create mode 100644 web/src/components/app/store/PhotoPicker.tsx create mode 100644 web/src/components/app/store/PlanUpsell.tsx create mode 100644 web/src/components/app/store/Press.tsx create mode 100644 web/src/components/app/store/PurchasedDomains.tsx create mode 100644 web/src/components/app/store/Senders.tsx create mode 100644 web/src/components/app/store/SetupTrack.tsx create mode 100644 web/src/components/app/store/SignInDialog.tsx create mode 100644 web/src/components/app/store/StoreLinks.tsx create mode 100644 web/src/components/app/store/StoreLocked.tsx create mode 100644 web/src/components/app/store/StorePaused.tsx create mode 100644 web/src/components/app/store/StoreSignature.tsx create mode 100644 web/src/components/app/store/SubscriptionCard.tsx create mode 100644 web/src/components/app/store/addMailboxesCopy.test.ts create mode 100644 web/src/components/app/store/addMailboxesCopy.ts create mode 100644 web/src/components/app/store/cardSave.test.ts create mode 100644 web/src/components/app/store/cardSave.ts create mode 100644 web/src/components/app/store/purchasedDomainsPaused.test.tsx create mode 100644 web/src/components/app/store/senders.test.tsx create mode 100644 web/src/components/app/store/setupTrack.test.tsx create mode 100644 web/src/components/app/store/storeLocked.test.tsx create mode 100644 web/src/components/app/store/useCheckout.ts create mode 100644 web/src/components/app/store/usePurchasedMailbox.ts create mode 100644 web/src/components/layout/PartnerPausedBar.tsx create mode 100644 web/src/hooks/usePartnerManaged.ts create mode 100644 web/src/hooks/useWorkspaceWritable.test.tsx create mode 100644 web/src/hooks/useWorkspaceWritable.ts create mode 100644 web/src/lib/api/client/app/agency/agencyStore.ts create mode 100644 web/src/lib/api/client/app/emails/getPartnerMailboxes.ts create mode 100644 web/src/lib/api/client/app/store/store.ts create mode 100644 web/src/lib/api/client/auth/exchangePartnerLogin.ts create mode 100644 web/src/lib/api/hooks/app/agency/useAgencyStore.ts create mode 100644 web/src/lib/api/hooks/app/emails/usePartnerMailboxes.ts create mode 100644 web/src/lib/api/hooks/app/store/useStore.ts create mode 100644 web/src/lib/api/models/app/agency/AgencyStore.ts create mode 100644 web/src/lib/api/models/app/emails/PartnerMailbox.ts create mode 100644 web/src/lib/api/models/app/store/Store.ts create mode 100644 web/src/lib/bitmask.test.ts create mode 100644 web/src/lib/bitmask.ts create mode 100644 web/src/lib/buy/addresses.test.ts create mode 100644 web/src/lib/buy/addresses.ts create mode 100644 web/src/lib/buy/cart.test.ts create mode 100644 web/src/lib/buy/cart.ts create mode 100644 web/src/lib/buy/checkout.test.ts create mode 100644 web/src/lib/buy/checkout.ts create mode 100644 web/src/lib/buy/connection.test.ts create mode 100644 web/src/lib/buy/connection.ts create mode 100644 web/src/lib/buy/errors.test.ts create mode 100644 web/src/lib/buy/errors.ts create mode 100644 web/src/lib/buy/money.test.ts create mode 100644 web/src/lib/buy/money.ts create mode 100644 web/src/lib/buy/motion.ts create mode 100644 web/src/lib/buy/patterns.test.ts create mode 100644 web/src/lib/buy/patterns.ts create mode 100644 web/src/lib/buy/photo.test.ts create mode 100644 web/src/lib/buy/photo.ts create mode 100644 web/src/lib/buy/purchased.test.ts create mode 100644 web/src/lib/buy/purchased.ts create mode 100644 web/src/lib/buy/registrant.test.ts create mode 100644 web/src/lib/buy/registrant.ts create mode 100644 web/src/lib/buy/resume.test.ts create mode 100644 web/src/lib/buy/resume.ts create mode 100644 web/src/lib/buy/stripe.ts create mode 100644 web/src/lib/buy/track.test.ts create mode 100644 web/src/lib/buy/track.ts create mode 100644 web/src/lib/mailboxSource.test.ts create mode 100644 web/src/lib/partnerPause.ts create mode 100644 web/src/lib/userDisplay.ts diff --git a/Makefile b/Makefile index 31ab44683..c31613303 100644 --- a/Makefile +++ b/Makefile @@ -637,10 +637,15 @@ WORKER_DEV_ENV := \ # the docker postgres. # The sandbox's mock inbox vendor API; empty keeps the real vendors. MAILVENDOR_SANDBOX_URL ?= +# The store runs against the in-process GraphKit simulator in dev; set both to use a sandbox key. +GRAPHKIT_API_URL ?= fake +GRAPHKIT_API_KEY ?= backend: $(GO_DEV_ENV) \ $(AI_DEV_ENV) \ MAILVENDOR_SANDBOX_URL=$(MAILVENDOR_SANDBOX_URL) \ + GRAPHKIT_API_URL=$(GRAPHKIT_API_URL) \ + GRAPHKIT_API_KEY=$(GRAPHKIT_API_KEY) \ API_HOST=0.0.0.0:8080 \ FORMS_DOMAIN=localhost:$(FORMS_PORT) \ PORTAL_DOMAIN=localhost:$(PORTAL_PORT) \ diff --git a/admin/src/app/dashboard/HealthPage.tsx b/admin/src/app/dashboard/HealthPage.tsx index d123f6a87..c75df920e 100644 --- a/admin/src/app/dashboard/HealthPage.tsx +++ b/admin/src/app/dashboard/HealthPage.tsx @@ -1,16 +1,17 @@ import { Link, useSearchParams } from "react-router-dom"; -import { Activity, ListChecks } from "lucide-react"; +import { Activity, ListChecks, Plug } from "lucide-react"; import { PageHeader } from "@/components/layout/PageHeader"; import { PageTabs } from "@/components/layout/PageTabs"; import { Button } from "@/components/ui/button"; import { useInstanceHealth } from "@/hooks/useInstanceHealth"; import { FindingsTab } from "./health/FindingsTab"; import { ServicesTab } from "./health/ServicesTab"; +import { IntegrationsTab } from "./health/IntegrationsTab"; import { InstanceMonitoringPanel } from "./InstanceMonitoringPanel"; import { useAdminPerm } from "@/hooks/useAdminPerm"; import { AdminPerm } from "@/lib/auth/permissions"; -const TAB_IDS = ["findings", "services", "operations"] as const; +const TAB_IDS = ["findings", "services", "operations", "integrations"] as const; type TabId = (typeof TAB_IDS)[number]; function isTabId(v: string | null): v is TabId { @@ -21,7 +22,8 @@ export default function HealthPage() { const canConfigure = useAdminPerm(AdminPerm.ManageSettings); const [params, setParams] = useSearchParams(); const raw = params.get("tab"); - const tab: TabId = isTabId(raw) ? raw : "findings"; + // Integrations hold write-only credentials, so the tab exists only for manage-settings. + const tab: TabId = isTabId(raw) && (raw !== "integrations" || canConfigure) ? raw : "findings"; // The findings count comes from the shared cache the sidebar badge reads, // so the tab badge and the nav badge never disagree. @@ -61,12 +63,21 @@ export default function HealthPage() { }, { id: "services", label: "Services", icon: Activity }, { id: "operations", label: "Operations", icon: Activity }, + ...(canConfigure ? [{ id: "integrations", label: "Integrations", icon: Plug }] : []), ]} value={tab} onChange={setTab} /> - {tab === "findings" ? : tab === "services" ? : } + {tab === "findings" ? ( + + ) : tab === "services" ? ( + + ) : tab === "integrations" ? ( + + ) : ( + + )} ); } diff --git a/admin/src/app/dashboard/OrganizationDetailPage.tsx b/admin/src/app/dashboard/OrganizationDetailPage.tsx index e1c3525d4..21c55ee33 100644 --- a/admin/src/app/dashboard/OrganizationDetailPage.tsx +++ b/admin/src/app/dashboard/OrganizationDetailPage.tsx @@ -278,6 +278,11 @@ function OrgProperties({ org }: { org: AdminOrgDetail }) { )} + + + Domains, mailboxes, orders + +
Lifecycle
diff --git a/admin/src/app/dashboard/configuration/SettingsTab.tsx b/admin/src/app/dashboard/configuration/SettingsTab.tsx index 995af3b8b..9e0d337bc 100644 --- a/admin/src/app/dashboard/configuration/SettingsTab.tsx +++ b/admin/src/app/dashboard/configuration/SettingsTab.tsx @@ -18,11 +18,14 @@ import { getInstanceSettings, putInstanceSettings, type InstanceSettings, + type StoreSettings, type UsageSettings, } from "@/lib/api/client/admin/instance"; +import { getStorePricing } from "@/lib/api/client/admin/store"; import { RangeHint, SettingsGroup, SettingsRow } from "./SettingsLayout"; const SETTINGS_KEY = ["admin", "instance", "settings"]; +const STORE_PRICING_KEY = ["admin", "store", "pricing"]; // The backend clamps to the same band; matching it here keeps the operator // from spending a round-trip to learn the range. @@ -430,6 +433,90 @@ function formatUSD(n: number): string { return `$${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 4 })}`; } +// Store retail pricing, mirroring the store section of internal/app/instancesettings. +const MICROS_PER_USD = 1_000_000; +const MICROS_PER_CENT = 10_000; +const STORE_USD_MAX = 100; +const STORE_PERCENT_MAX = 500; +// The preview prices this extension from the live wholesale list. +const STORE_PREVIEW_TLD = "com"; + +const STORE_LEAD_MIN = 2; +const STORE_LEAD_MAX = 10; +const STORE_MIN_CARD_FLOOR = 0.5; + +const STORE_DEFAULTS: StoreSettings = { + mailbox_monthly_micros: 3_000_000, + domain_markup_percent: 0, + domain_markup_fixed_micros: 0, + mailbox_bill_lead_days: 5, + min_card_charge_micros: 10_000_000, +}; + +interface StoreForm { + mailboxMonthly: string; + markupPercent: string; + markupFixed: string; + billLead: string; + minCard: string; +} + +function microsToDollars(micros: number): string { + const usd = micros / MICROS_PER_USD; + return micros % MICROS_PER_CENT === 0 ? usd.toFixed(2) : String(usd); +} + +function dollarsToMicros(raw: string): number { + return Math.round(Number(raw) * MICROS_PER_USD); +} + +function toStoreForm(s: StoreSettings | undefined): StoreForm { + const store = { ...STORE_DEFAULTS, ...s }; + return { + mailboxMonthly: microsToDollars(store.mailbox_monthly_micros), + markupPercent: String(store.domain_markup_percent), + markupFixed: microsToDollars(store.domain_markup_fixed_micros), + billLead: String(store.mailbox_bill_lead_days ?? 5), + minCard: microsToDollars(store.min_card_charge_micros ?? 10_000_000), + }; +} + +// Dollars to at most micro-dollar precision, between zero and max. +function dollarsValid(raw: string, max: number): boolean { + return /^\d+(\.\d{1,6})?$/.test(raw.trim()) && Number(raw) <= max; +} + +function storeFormValid(f: StoreForm): boolean { + return ( + dollarsValid(f.mailboxMonthly, STORE_USD_MAX) && + syncFieldValid(f.markupPercent, 0, STORE_PERCENT_MAX) && + dollarsValid(f.markupFixed, STORE_USD_MAX) && + syncFieldValid(f.billLead, STORE_LEAD_MIN, STORE_LEAD_MAX) && + dollarsValid(f.minCard, STORE_USD_MAX) && + Number(f.minCard) >= STORE_MIN_CARD_FLOOR + ); +} + +// Retail domain price: wholesale plus the percent plus the fixed amount, rounded up to the cent. +function retailDomainMicros(wholesale: number, percent: number, fixed: number): number { + const exact = wholesale * (100 + percent) + fixed * 100; + return Math.ceil(exact / (100 * MICROS_PER_CENT)) * MICROS_PER_CENT; +} + +function mailboxPreview(f: StoreForm): string { + return `Customers pay ${formatUSD(dollarsToMicros(f.mailboxMonthly) / MICROS_PER_USD)} per mailbox per month`; +} + +// What a .com sells for at the form's markup, from the live wholesale price. +function domainPreview(f: StoreForm, wholesaleMicros: number): string { + const percent = Number(f.markupPercent); + const fixed = dollarsToMicros(f.markupFixed); + const wholesale = formatUSD(wholesaleMicros / MICROS_PER_USD); + if (percent === 0 && fixed === 0) return `a .${STORE_PREVIEW_TLD} costs ${wholesale} at cost`; + const retail = formatUSD(retailDomainMicros(wholesaleMicros, percent, fixed) / MICROS_PER_USD); + return `a .${STORE_PREVIEW_TLD} that costs ${wholesale} wholesale sells for ${retail}`; +} + interface FormState { linksEnabled: boolean; ttlHours: string; @@ -442,6 +529,7 @@ interface FormState { authGraceHours: string; autoVendorReconnect: boolean; usage: UsageForm; + store: StoreForm; } function toForm(s: InstanceSettings): FormState { @@ -485,6 +573,7 @@ function toForm(s: InstanceSettings): FormState { authGraceHours: String(s.deliverability.auth_grace_hours), autoVendorReconnect: s.mailbox_signin?.auto_vendor_reconnect ?? true, usage: toUsageForm(s.usage), + store: toStoreForm(s.store), }; } @@ -550,6 +639,10 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) { ); const usageDirty = !!server && !!form && usageSignature(form.usage) !== usageSignature(toUsageForm(server.usage)); + const storeDirty = + !!server && + !!form && + JSON.stringify(form.store) !== JSON.stringify(toStoreForm(server.store)); const dirty = !!server && !!form && @@ -563,6 +656,7 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) { trackingDirty || placementDirty || usageDirty || + storeDirty || syncDirty); useEffect(() => { @@ -592,6 +686,8 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) { ) && Object.values(form.usage.units).every(priceValid); + const storeValid = form !== null && storeFormValid(form.store); + const authGrace = form ? Number(form.authGraceHours) : NaN; const authGraceValid = form !== null && @@ -642,6 +738,12 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) { ); return; } + if (!storeValid) { + toast.error( + `The mailbox price and the fixed domain markup must be dollar amounts from $0 to $${STORE_USD_MAX}, and the domain markup a whole percent from 0 to ${STORE_PERCENT_MAX}`, + ); + return; + } if (!authGraceValid) { toast.error( `The authentication grace period must be a whole number of hours between ${AUTH_GRACE_MIN_HOURS} and ${AUTH_GRACE_MAX_HOURS}`, @@ -698,6 +800,13 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) { Object.entries(form.usage.units).map(([k, v]) => [k, Number(v)]), ), }, + store: { + mailbox_monthly_micros: dollarsToMicros(form.store.mailboxMonthly), + domain_markup_percent: Number(form.store.markupPercent), + domain_markup_fixed_micros: dollarsToMicros(form.store.markupFixed), + mailbox_bill_lead_days: Number(form.store.billLead), + min_card_charge_micros: dollarsToMicros(form.store.minCard), + }, }); } @@ -923,6 +1032,11 @@ export function SettingsTab({ onDirtyChange, onSwitchTab }: SettingsTabProps) { onChange={(usage) => setForm({ ...form, usage })} /> + setForm({ ...form, store })} + /> + void; +}) { + const pricingQ = useQuery({ + queryKey: STORE_PRICING_KEY, + queryFn: getStorePricing, + retry: false, + staleTime: 5 * 60_000, + }); + const comWholesale = pricingQ.data?.domains.find((d) => d.tld === STORE_PREVIEW_TLD)?.register_micros; + const valid = storeFormValid(store); + return ( + + What a workspace pays for the domains and mailboxes it buys under Buy mailboxes, + charged from its balance. Only used when the store is configured with{" "} + GRAPHKIT_API_KEY. A change applies + to quotes made after it; a mailbox already bought keeps the monthly price it was + bought at. A self-hosted instance with billing off charges workspaces nothing and + its partner account pays, so these prices do nothing there. + + } + > + onChange({ ...store, mailboxMonthly: v })} + valid={dollarsValid(store.mailboxMonthly, STORE_USD_MAX)} + error={`Enter a dollar amount between 0 and ${STORE_USD_MAX}.`} + inputMode="decimal" + /> + onChange({ ...store, markupPercent: v })} + valid={syncFieldValid(store.markupPercent, 0, STORE_PERCENT_MAX)} + error={`Enter a whole number between 0 and ${STORE_PERCENT_MAX}.`} + /> + onChange({ ...store, markupFixed: v })} + valid={dollarsValid(store.markupFixed, STORE_USD_MAX)} + error={`Enter a dollar amount between 0 and ${STORE_USD_MAX}.`} + inputMode="decimal" + /> + onChange({ ...store, billLead: v })} + valid={syncFieldValid(store.billLead, STORE_LEAD_MIN, STORE_LEAD_MAX)} + error={`Enter a whole number between ${STORE_LEAD_MIN} and ${STORE_LEAD_MAX}.`} + /> + onChange({ ...store, minCard: v })} + valid={dollarsValid(store.minCard, STORE_USD_MAX) && Number(store.minCard) >= STORE_MIN_CARD_FLOOR} + error={`Enter a dollar amount between ${STORE_MIN_CARD_FLOOR.toFixed(2)} and ${STORE_USD_MAX}.`} + inputMode="decimal" + /> +
+ {!valid ? ( + "Fix the values above to see what customers pay." + ) : pricingQ.isLoading ? ( +
+ {mailboxPreview(store)}; + + loading the live .{STORE_PREVIEW_TLD} price +
+ ) : comWholesale === undefined ? ( + <> + {mailboxPreview(store)}.{" "} + Live price unavailable + + ) : ( + `${mailboxPreview(store)}; ${domainPreview(store, comWholesale)}.` + )} +
+
+ ); +} + // One numeric setting: the field sits on the right, the range under the help. function NumberRow({ id, diff --git a/admin/src/app/dashboard/health/IntegrationsTab.test.tsx b/admin/src/app/dashboard/health/IntegrationsTab.test.tsx new file mode 100644 index 000000000..8737c184b --- /dev/null +++ b/admin/src/app/dashboard/health/IntegrationsTab.test.tsx @@ -0,0 +1,75 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { StoreConnection } from "@/lib/api/client/admin/store"; +import { StoreConnectionCard } from "./IntegrationsTab"; + +const state = vi.hoisted(() => ({ conn: undefined as StoreConnection | undefined })); +vi.mock("@tanstack/react-query", () => ({ + useQuery: () => ({ data: state.conn, isLoading: false, isError: false, refetch: vi.fn() }), + useMutation: () => ({ mutate: vi.fn(), isPending: false }), + useQueryClient: () => ({}), +})); +vi.mock("@/components/ConfirmDialog", () => ({ useConfirm: () => vi.fn() })); +vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } })); + +function conn(over: Partial = {}): StoreConnection { + return { + source: "settings", + configured: true, + mode: "live", + api_url: "https://gk.example/v1/infrastructure", + default_api_url: "https://api.graphkit.com/v1/infrastructure", + api_key_set: true, + webhook_secret_set: false, + webhook_url: "https://api.example/v1/webhooks/graphkit", + sealing_available: true, + updated_at: "2026-11-01T00:00:00Z", + updated_by: "user-1", + purchases_without_connection: null, + ...over, + }; +} + +function render() { + const html = renderToStaticMarkup(); + return new DOMParser().parseFromString(html, "text/html"); +} + +const buttons = (doc: Document) => [...doc.querySelectorAll("button")].map((b) => b.textContent?.trim()); + +beforeEach(() => { + state.conn = conn(); +}); + +describe("GraphKit connection card", () => { + it("renders an environment connection read-only", () => { + state.conn = conn({ source: "environment" }); + const doc = render(); + expect(doc.body.textContent).toContain("Configured by the environment"); + expect(doc.body.textContent).toContain("https://gk.example/v1/infrastructure"); + expect(doc.querySelector("input[type=password]")).toBeNull(); + expect(doc.querySelector("#graphkit-url")).toBeNull(); + expect(buttons(doc)).not.toContain("Save"); + expect(buttons(doc)).not.toContain("Disconnect"); + }); + + it("offers Disconnect for stored settings and starts secrets empty", () => { + const doc = render(); + expect(buttons(doc)).toContain("Disconnect"); + const secrets = [...doc.querySelectorAll("input[type=password]")]; + expect(secrets).toHaveLength(2); + for (const s of secrets) expect(s.value).toBe(""); + expect(doc.querySelector("#graphkit-url")?.value).toBe("https://gk.example/v1/infrastructure"); + expect(doc.body.textContent).toContain("Not set"); + }); + + it("blocks saving without the credentials key and reports unconnected purchases", () => { + state.conn = conn({ source: "none", configured: false, api_key_set: false, sealing_available: false, purchases_without_connection: { mailboxes: 3, domains: 1 } }); + const doc = render(); + expect(doc.body.textContent).toContain("CREDENTIALS_ENCRYPTION_KEY must be set"); + expect(doc.body.textContent).toContain("3 mailboxes and 1 domain were bought here"); + const save = [...doc.querySelectorAll("button")].find((b) => b.textContent?.includes("Save")); + expect(save?.hasAttribute("disabled")).toBe(true); + expect(buttons(doc)).not.toContain("Disconnect"); + }); +}); diff --git a/admin/src/app/dashboard/health/IntegrationsTab.tsx b/admin/src/app/dashboard/health/IntegrationsTab.tsx new file mode 100644 index 000000000..a74574d04 --- /dev/null +++ b/admin/src/app/dashboard/health/IntegrationsTab.tsx @@ -0,0 +1,342 @@ +// Integrations tab of Setup and health: the GraphKit connection behind the domain and mailbox store. + +import { useState, type FormEvent } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { AlertTriangle, Check, Copy, FlaskConical, Save, Unplug } from "lucide-react"; +import { useConfirm } from "@/components/ConfirmDialog"; +import { ErrorState } from "@/components/ErrorState"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Callout, Panel, StatusBadge } from "@/components/ui/kit"; +import { Skeleton } from "@/components/ui/skeleton"; +import { INSTANCE_HEALTH_KEY } from "@/hooks/useInstanceHealth"; +import { APIError, ReauthCancelledError } from "@/lib/api/client"; +import { + deleteStoreConnection, + getStoreConnection, + saveStoreConnection, + STORE_CONNECTION_KEY, + testStoreConnection, + type StoreConnection, + type StoreConnectionInput, + type StoreConnectionTest, +} from "@/lib/api/client/admin/store"; +import { MODE_TONE } from "../store/format"; + +export function IntegrationsTab() { + return ( +
+ +
+ ); +} + +const ERROR_TEXT: Record = { + store_configured_by_environment: "GRAPHKIT_* environment variables configure the store, so it cannot be changed here.", + store_sealing_unavailable: "Set CREDENTIALS_ENCRYPTION_KEY before saving a GraphKit API key here.", + graphkit_url_invalid: "The API URL is not a valid GraphKit URL.", + graphkit_key_required: "Enter an API key. None is stored yet.", + graphkit_key_reentry_required: "Enter the API key again to use a different API URL.", + graphkit_key_rejected: "GraphKit rejected this API key.", + graphkit_unreachable: "GraphKit could not be reached at this URL.", +}; + +function errorText(e: unknown): string { + if (e instanceof APIError && e.code && ERROR_TEXT[e.code]) return ERROR_TEXT[e.code]; + return e instanceof Error && e.message ? e.message : "The request failed"; +} + +function trimSlash(u: string): string { + return u.replace(/\/+$/, ""); +} + +function money(micros: number, currency: string): string { + try { + return new Intl.NumberFormat("en-US", { style: "currency", currency: currency || "USD" }).format(micros / 1_000_000); + } catch { + return `${(micros / 1_000_000).toFixed(2)} ${currency}`; + } +} + +const MODE_LABEL: Record = { + live: "Live", + sandbox: "Sandbox", + simulator: "Simulator", + off: "Off", +}; + +export function StoreConnectionCard() { + const q = useQuery({ queryKey: STORE_CONNECTION_KEY, queryFn: getStoreConnection, retry: false }); + return ( + {MODE_LABEL[q.data.mode] ?? q.data.mode}} + > + {q.isLoading ? ( +
+ + + +
+ ) : q.isError || !q.data ? ( + void q.refetch()} /> + ) : ( + // Remount on every server change so the form starts from what is stored. + + )} +
+ ); +} + +function SecretStatus({ set }: { set: boolean }) { + return {set ? "Set" : "Not set"}; +} + +function ConnectionForm({ conn }: { conn: StoreConnection }) { + const qc = useQueryClient(); + const confirm = useConfirm(); + const fromEnv = conn.source === "environment"; + const [apiUrl, setApiUrl] = useState(conn.api_url); + const [apiKey, setApiKey] = useState(""); + const [secret, setSecret] = useState(""); + const [result, setResult] = useState<{ ok: StoreConnectionTest } | { error: string } | null>(null); + + const input = (): StoreConnectionInput => ({ + api_url: apiUrl.trim() || conn.default_api_url, + api_key: apiKey.trim() || undefined, + webhook_secret: secret.trim() || undefined, + }); + + async function refresh(next: StoreConnection) { + qc.setQueryData(STORE_CONNECTION_KEY, next); + await Promise.all([ + qc.invalidateQueries({ queryKey: ["admin", "store"] }), + qc.invalidateQueries({ queryKey: INSTANCE_HEALTH_KEY }), + ]); + } + + const testMut = useMutation({ + mutationFn: testStoreConnection, + onSuccess: (ok) => setResult({ ok }), + onError: (e) => { + if (!(e instanceof ReauthCancelledError)) setResult({ error: errorText(e) }); + }, + }); + const saveMut = useMutation({ + mutationFn: saveStoreConnection, + onSuccess: async (next) => { + toast.success("GraphKit API key saved"); + await refresh(next); + }, + onError: (e) => { + if (!(e instanceof ReauthCancelledError)) toast.error(errorText(e)); + }, + }); + const deleteMut = useMutation({ + mutationFn: deleteStoreConnection, + onSuccess: async (next) => { + toast.success("GraphKit disconnected"); + await refresh(next); + }, + onError: (e) => { + if (!(e instanceof ReauthCancelledError)) toast.error(errorText(e)); + }, + }); + + const busy = testMut.isPending || saveMut.isPending || deleteMut.isPending; + // The stored key is only sent to the URL it was saved with. + const urlChanged = conn.api_key_set && trimSlash(apiUrl.trim() || conn.default_api_url) !== trimSlash(conn.api_url); + const keyMissing = (!conn.api_key_set || urlChanged) && !apiKey.trim(); + const saveBlocked = !conn.sealing_available + ? "Set CREDENTIALS_ENCRYPTION_KEY to save a GraphKit API key here." + : keyMissing + ? urlChanged + ? "Enter the API key again to use a different API URL." + : "Enter an API key to save. None is stored yet." + : null; + + function edit(set: (v: string) => void) { + return (v: string) => { + set(v); + setResult(null); + }; + } + + function onSubmit(e: FormEvent) { + e.preventDefault(); + if (fromEnv || saveBlocked || busy) return; + saveMut.mutate(input()); + } + + async function disconnect() { + const ok = await confirm({ + title: "Disconnect GraphKit?", + description: + "The store stops now. New purchases, renewals, monthly billing and Google mailbox connections pause until an API key is added again. The stored API key and webhook secret are deleted.", + confirmLabel: "Disconnect", + destructive: true, + }); + if (ok) deleteMut.mutate(); + } + + const pending = conn.purchases_without_connection; + + return ( +
+ {pending && ( + + {pending.mailboxes} {pending.mailboxes === 1 ? "mailbox" : "mailboxes"} and {pending.domains}{" "} + {pending.domains === 1 ? "domain" : "domains"} were bought here. Renewals, monthly billing and Google + mailbox connections are paused until GraphKit is configured. + + )} + + {fromEnv ? ( +
+ Configured by the environment + GRAPHKIT_* environment variables win over these settings. +
+ ) : ( + !conn.sealing_available && ( + + CREDENTIALS_ENCRYPTION_KEY must be set before GraphKit can be saved here, because the API key and + webhook secret are stored encrypted with it. + + ) + )} + +
+
+ + {fromEnv ? ( +
{conn.api_url}
+ ) : ( + edit(setApiUrl)(e.target.value)} + autoComplete="off" + spellCheck={false} + /> + )} +
+
+ + {!fromEnv && ( + edit(setApiKey)(e.target.value)} + autoComplete="new-password" + placeholder={conn.api_key_set && !urlChanged ? "Leave blank to keep the stored key" : "Required"} + /> + )} +
+
+ + {!fromEnv && ( + edit(setSecret)(e.target.value)} + autoComplete="new-password" + placeholder={conn.webhook_secret_set ? "Leave blank to keep the stored secret" : "From GraphKit"} + /> + )} +
+
+ {!fromEnv && ( +

+ Secrets are never shown again once saved. Leave a field blank to keep the stored value. +

+ )} + +
+ +
+ e.target.select()} /> + +
+

+ In GraphKit, register this URL as your webhook endpoint and paste the signing secret it gives you above. +

+
+ + {result && } + + {!fromEnv && ( +
+ + + {conn.source === "settings" && ( + + )} + {saveBlocked && {saveBlocked}} + {!saveBlocked && conn.updated_at && ( + Saved {new Date(conn.updated_at).toLocaleString()} + )} +
+ )} + + ); +} + +function TestResult({ result }: { result: { ok: StoreConnectionTest } | { error: string } }) { + if ("error" in result) { + return {result.error}; + } + const t = result.ok; + const com = + t.com_register_micros != null + ? `.com ${money(t.com_register_micros, t.currency)} to register${t.com_renew_micros != null ? `, ${money(t.com_renew_micros, t.currency)} to renew` : ""}` + : null; + return ( + + Balance {money(t.balance_micros, t.currency)} + {com && `. ${com}`} + + ); +} + +function CopyButton({ value }: { value: string }) { + const [copied, setCopied] = useState(false); + return ( + + ); +} diff --git a/admin/src/app/dashboard/partners/PartnerDetailPage.tsx b/admin/src/app/dashboard/partners/PartnerDetailPage.tsx new file mode 100644 index 000000000..fbb253aa6 --- /dev/null +++ b/admin/src/app/dashboard/partners/PartnerDetailPage.tsx @@ -0,0 +1,453 @@ +// One partner: its settings, keys, webhook and callback secrets, and the workspaces it manages. +// Reading needs view_organizations; every change needs manage_organizations and a fresh confirmation. + +import { useState, type FormEvent } from "react"; +import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Link, useParams } from "react-router-dom"; +import { Copy, KeyRound, Plus } from "lucide-react"; +import { toast } from "sonner"; +import { PageHeader } from "@/components/layout/PageHeader"; +import { Panel, Property, PropertyList, StatusBadge } from "@/components/ui/kit"; +import { ErrorState } from "@/components/ErrorState"; +import { DataTable, type Column } from "@/components/data/DataTable"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { useConfirm } from "@/components/ConfirmDialog"; +import { useAdminPerm } from "@/hooks/useAdminPerm"; +import { AdminPerm } from "@/lib/auth/permissions"; +import { PartnerStatements } from "./PartnerStatements"; +import { + createPartnerKey, + getPartner, + listPartnerOrganizations, + revokePartnerKey, + rotatePartnerWebhookSecret, + setPartnerCallbackKey, + updatePartner, + type AdminPartnerDetail, + type AdminPartnerKey, + type AdminPartnerOrganization, + type AdminPartnerUpdate, + type PartnerMode, +} from "@/lib/api/client/admin/partners"; + +const FIELD_LABEL = "text-xs font-medium text-muted-foreground"; +const MICROS = 1_000_000; + +function usdFromMicros(m: number): string { + return (m / MICROS).toLocaleString(undefined, { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 6 }); +} + +const STATE_TONE = { active: "success", suspended: "warning", cancelled: "danger" } as const; + +const ORG_COLUMNS: Column[] = [ + { + id: "name", + header: "Workspace", + cell: (o) => + o.organization_id ? ( + + {o.organization_name || o.organization_id} + + ) : ( + Deleted + ), + csv: (o) => o.organization_name ?? "", + }, + { id: "external", header: "Partner's id", cell: (o) => {o.external_id}, csv: (o) => o.external_id }, + { id: "mode", header: "Mode", cell: (o) => {o.mode}, csv: (o) => o.mode }, + { + id: "state", + header: "State", + cell: (o) => ( + + {o.state} + + ), + csv: (o) => o.state, + }, + { id: "group", header: "Group", cell: (o) => o.group_name || o.group_external_id || "None", csv: (o) => o.group_external_id ?? "" }, + { id: "cap", header: "Sends / mailbox / day", align: "right", cell: (o) => o.campaign_sends_per_mailbox_per_day, csv: (o) => o.campaign_sends_per_mailbox_per_day }, + { + id: "deletes", + header: "Deletes", + cell: (o) => (o.deletes_at ? new Date(o.deletes_at).toLocaleDateString() : ""), + csv: (o) => o.deletes_at ?? "", + }, +]; + +export default function PartnerDetailPage() { + const { id = "" } = useParams(); + const q = useQuery({ queryKey: ["admin", "partners", id], queryFn: () => getPartner(id), enabled: !!id }); + const p = q.data; + + if (q.error) { + return ( + <> + + void q.refetch()} /> + + ); + } + + return ( + <> + {p.status} : undefined} + /> + {p && ( +
+ + + + + + +
+ )} + + ); +} + +function usePartnerWrite(id: string, fn: (v: T) => Promise, done: string) { + const qc = useQueryClient(); + return useMutation({ + mutationFn: fn, + onSuccess: (res) => { + if (res && typeof res === "object" && "keys" in res) qc.setQueryData(["admin", "partners", id], res as AdminPartnerDetail); + void qc.invalidateQueries({ queryKey: ["admin", "partners"] }); + toast.success(done); + }, + onError: (e: Error) => toast.error(e.message || "That change did not save."), + }); +} + +function PartnerStatusCard({ partner: p }: { partner: AdminPartnerDetail }) { + const confirm = useConfirm(); + const canManage = useAdminPerm(AdminPerm.ManageOrganizations); + const suspended = p.status === "suspended"; + const toggle = usePartnerWrite(p.id, () => updatePartner(p.id, { status: suspended ? "active" : "suspended" }), suspended ? "Partner resumed" : "Partner suspended"); + + async function run() { + const ok = await confirm({ + title: suspended ? `Resume ${p.name}?` : `Suspend ${p.name}?`, + description: suspended + ? "Its keys work again. Workspaces it manages keep their own state." + : "Every one of its keys answers partner_suspended until it is resumed. Workspaces it manages keep running as they are.", + confirmLabel: suspended ? "Resume" : "Suspend", + destructive: !suspended, + }); + if (ok) await toggle.mutateAsync(undefined).catch(() => undefined); + } + + return ( + + + {p.slug} + + Billed through {p.display_name} + {p.allowed_plans.join(", ") || "None"} + + + {p.status} + {canManage && ( + + )} + + + + ); +} + +function PartnerSettingsCard({ partner: p }: { partner: AdminPartnerDetail }) { + const canManage = useAdminPerm(AdminPerm.ManageOrganizations); + const [form, setForm] = useState(() => ({ + name: p.name, + display_name: p.display_name, + allowed_hosts: p.allowed_hosts.join(", "), + delegation_domains: (p.delegation_domains ?? []).join(", "), + webhook_url: p.webhook_url ?? "", + callback_base_url: p.callback_base_url ?? "", + sending: String(p.wholesale_sending_warmup_day_micros / MICROS), + warmup: String(p.wholesale_warmup_only_day_micros / MICROS), + rate: String(p.rate_limit_per_second), + })); + const set = (k: keyof typeof form) => (e: { target: { value: string } }) => setForm((f) => ({ ...f, [k]: e.target.value })); + const save = usePartnerWrite(p.id, (body: AdminPartnerUpdate) => updatePartner(p.id, body), "Partner saved"); + + function submit(e: FormEvent) { + e.preventDefault(); + const toMicros = (v: string) => Math.round(Number(v || "0") * MICROS); + save.mutate({ + name: form.name.trim(), + display_name: form.display_name.trim(), + allowed_hosts: form.allowed_hosts.split(/[\s,]+/).filter(Boolean), + delegation_domains: form.delegation_domains.split(/[\s,]+/).filter(Boolean), + webhook_url: form.webhook_url.trim(), + callback_base_url: form.callback_base_url.trim(), + wholesale_sending_warmup_day_micros: toMicros(form.sending), + wholesale_warmup_only_day_micros: toMicros(form.warmup), + rate_limit_per_second: Number(form.rate), + }); + } + + const field = (id: keyof typeof form, label: string, hint?: string, placeholder?: string) => ( +
+ + + {hint &&

{hint}

} +
+ ); + + return ( + +
+ {field("name", "Name")} + {field("display_name", "Display name", 'Members read "Billed through" this name.')} + {field("allowed_hosts", "Allowed hosts", "Hosts a return URL the partner sends may point at, separated by commas.", "app.example.com")} + {field("rate", "Requests per second", "20 to 1000, across all of the partner's keys.")} + {field( + "delegation_domains", + "Delegation domains", + "Domains you have confirmed the partner controls, separated by commas. A mailbox the partner attaches by delegation connects only on one of these, or on a domain its workspace verified.", + "mail.example.com", + )} + {field("webhook_url", "Webhook URL", "HTTPS. Events are signed with the webhook secret below.", "https://api.example.com/webhooks/warmbly")} + {field("callback_base_url", "Token callback base", "Where per-mailbox access tokens are requested.", "https://api.example.com/v1/warmbly")} + {field("sending", "Wholesale, sending and warmup (USD per mailbox-day)", `Now ${usdFromMicros(p.wholesale_sending_warmup_day_micros)}.`)} + {field("warmup", "Wholesale, warmup only (USD per mailbox-day)", `Now ${usdFromMicros(p.wholesale_warmup_only_day_micros)}.`)} + {canManage && ( +
+ +
+ )} +
+
+ ); +} + +function SecretOnce({ secret, onClose, title, hint }: { secret: string | null; onClose: () => void; title: string; hint: string }) { + return ( + !v && onClose()}> + + + {title} + {hint} + +
+ e.target.select()} /> + +
+ + + +
+
+ ); +} + +function PartnerKeysCard({ partner: p }: { partner: AdminPartnerDetail }) { + const confirm = useConfirm(); + const canManage = useAdminPerm(AdminPerm.ManageOrganizations); + const [secret, setSecret] = useState(null); + const create = usePartnerWrite(p.id, async (mode: PartnerMode) => { + const k = await createPartnerKey(p.id, { mode }); + setSecret(k.secret); + return k; + }, "Key created"); + const revoke = usePartnerWrite(p.id, (keyId: string) => revokePartnerKey(p.id, keyId), "Key revoked"); + + async function askRevoke(k: AdminPartnerKey) { + const ok = await confirm({ + title: `Revoke ${k.key_prefix}…${k.key_suffix}?`, + description: "Anything using this key stops working at once.", + confirmLabel: "Revoke", + destructive: true, + }); + if (ok) await revoke.mutateAsync(k.id).catch(() => undefined); + } + + return ( + + + + + ) + } + bodyClassName="p-0" + > + {p.keys.length === 0 ? ( +

No keys yet.

+ ) : ( +
    + {p.keys.map((k) => ( +
  • + + + {k.key_prefix}…{k.key_suffix} + + {k.mode} + + {k.revoked_at + ? `Revoked ${new Date(k.revoked_at).toLocaleDateString()}` + : k.last_used_at + ? `Used ${new Date(k.last_used_at).toLocaleString()}` + : "Never used"} + + {canManage && !k.revoked_at && ( + + )} +
  • + ))} +
+ )} + setSecret(null)} + title="Copy the key now" + hint="This is the only time the key is shown. Give it to the partner over a secure channel." + /> +
+ ); +} + +function PartnerSecretsCard({ partner: p }: { partner: AdminPartnerDetail }) { + const confirm = useConfirm(); + const canManage = useAdminPerm(AdminPerm.ManageOrganizations); + const [secret, setSecret] = useState(null); + const [callbackKey, setCallbackKey] = useState(""); + const rotate = usePartnerWrite(p.id, async () => { + const r = await rotatePartnerWebhookSecret(p.id); + setSecret(r.secret); + return r; + }, "Webhook secret rotated"); + const saveCallback = usePartnerWrite(p.id, (key: string) => setPartnerCallbackKey(p.id, key), "Callback key saved"); + + async function askRotate() { + if (p.webhook_secret_set) { + const ok = await confirm({ + title: "Rotate the webhook secret?", + description: "Events are signed with both the new and the old secret for a day, then with the new one only.", + confirmLabel: "Rotate", + }); + if (!ok) return; + } + await rotate.mutateAsync(undefined).catch(() => undefined); + } + + return ( + +
+
+
Webhook signing secret
+
+ {p.webhook_secret_set + ? `Set${p.webhook_secret_rotated_at ? `, rotated ${new Date(p.webhook_secret_rotated_at).toLocaleString()}` : ""}` + : "Not set: no events are delivered until it is."} +
+ {canManage && ( + + )} +
+
{ + e.preventDefault(); + saveCallback.mutate(callbackKey.trim(), { onSuccess: () => setCallbackKey("") }); + }} + > + +
+ setCallbackKey(e.target.value)} + disabled={!canManage} + /> + {canManage && ( + + )} +
+
+
+ setSecret(null)} + title="Copy the webhook secret now" + hint="The partner verifies every event with it. This is the only time it is shown." + /> +
+ ); +} + +function PartnerOrganizations({ partnerId }: { partnerId: string }) { + const q = useInfiniteQuery({ + queryKey: ["admin", "partners", partnerId, "organizations"], + queryFn: ({ pageParam }) => listPartnerOrganizations(partnerId, pageParam || undefined), + initialPageParam: "", + getNextPageParam: (last) => (last.pagination.has_more ? (last.pagination.next_cursor ?? undefined) : undefined), + }); + const rows = q.data?.pages.flatMap((p) => p.data) ?? []; + return ( + + o.id} + loading={q.isLoading} + error={q.error} + onRetry={() => void q.refetch()} + emptyTitle="No workspaces" + emptyHint="The partner creates them through its API." + csvName="partner-workspaces" + noun="workspaces" + /> + {q.hasNextPage && ( +
+ +
+ )} +
+ ); +} diff --git a/admin/src/app/dashboard/partners/PartnerStatements.tsx b/admin/src/app/dashboard/partners/PartnerStatements.tsx new file mode 100644 index 000000000..ef49b4baa --- /dev/null +++ b/admin/src/app/dashboard/partners/PartnerStatements.tsx @@ -0,0 +1,78 @@ +// A partner's monthly statement: enabled mailbox-days per workspace at its wholesale rates. Closed months are final. + +import { useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { Panel, Property, PropertyList, StatusBadge } from "@/components/ui/kit"; +import { DataTable, type Column } from "@/components/data/DataTable"; +import { getPartnerStatement, listPartnerStatements, type AdminPartnerStatementLine } from "@/lib/api/client/admin/partners"; + +function usd(m: number): string { + return (m / 1_000_000).toLocaleString(undefined, { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 6 }); +} + +function thisMonth(): string { + return new Date().toISOString().slice(0, 7); +} + +const LINE_COLUMNS: Column[] = [ + { id: "external", header: "Partner's workspace id", cell: (l) => {l.external_id}, csv: (l) => l.external_id }, + { id: "sw", header: "Sending & warmup days", align: "right", cell: (l) => l.sending_warmup_days, csv: (l) => l.sending_warmup_days }, + { id: "wo", header: "Warmup only days", align: "right", cell: (l) => l.warmup_only_days, csv: (l) => l.warmup_only_days }, + { id: "amount", header: "Amount", align: "right", cell: (l) => usd(l.amount_micros), csv: (l) => l.amount_micros / 1_000_000 }, +]; + +export function PartnerStatements({ partnerId }: { partnerId: string }) { + const [month, setMonth] = useState(thisMonth); + const closed = useQuery({ queryKey: ["admin", "partners", partnerId, "statements"], queryFn: () => listPartnerStatements(partnerId) }); + const st = useQuery({ queryKey: ["admin", "partners", partnerId, "statements", month], queryFn: () => getPartnerStatement(partnerId, month) }); + const months = Array.from(new Set([thisMonth(), ...(closed.data?.data ?? []).map((s) => s.month)])); + const s = st.data; + return ( + setMonth(e.target.value)} + className="h-8 rounded-md border border-input bg-background px-2 text-sm" + > + {months.map((m) => ( + + ))} + + } + bodyClassName="p-0" + > + {s && ( + + + {s.closed_at ? "Closed" : "Running"} + + + {s.sending_warmup_days} days at {usd(s.sending_warmup_day_micros)} + + + {s.warmup_only_days} days at {usd(s.warmup_only_day_micros)} + + {usd(s.amount_micros)} + + )} + l.external_id} + loading={st.isLoading} + error={st.error} + onRetry={() => void st.refetch()} + emptyTitle="No enabled mailboxes" + emptyHint="Days count once the partner turns a mailbox on." + csvName={`partner-statement-${month}`} + noun="workspaces" + /> + + ); +} diff --git a/admin/src/app/dashboard/partners/PartnersPage.tsx b/admin/src/app/dashboard/partners/PartnersPage.tsx new file mode 100644 index 000000000..78d64e16a --- /dev/null +++ b/admin/src/app/dashboard/partners/PartnersPage.tsx @@ -0,0 +1,164 @@ +// Partners: resellers that create and run workspaces through /v1/partner. The partner API answers +// nothing until one exists here (or from `warmblyctl partner create`). + +import { useState, type FormEvent } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useNavigate } from "react-router-dom"; +import { Plus } from "lucide-react"; +import { toast } from "sonner"; +import { PageHeader } from "@/components/layout/PageHeader"; +import { DataTable, type Column } from "@/components/data/DataTable"; +import { StatusBadge } from "@/components/ui/kit"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { useAdminPerm } from "@/hooks/useAdminPerm"; +import { AdminPerm } from "@/lib/auth/permissions"; +import { createPartner, listPartners, type AdminPartner } from "@/lib/api/client/admin/partners"; + +const FIELD_LABEL = "text-xs font-medium text-muted-foreground"; + +const COLUMNS: Column[] = [ + { id: "name", header: "Partner", cell: (p) => {p.name}, csv: (p) => p.name }, + { id: "slug", header: "Slug", cell: (p) => {p.slug}, csv: (p) => p.slug }, + { id: "display", header: "Members see", cell: (p) => `Billed through ${p.display_name}`, csv: (p) => p.display_name }, + { + id: "status", + header: "Status", + cell: (p) => {p.status}, + csv: (p) => p.status, + }, + { id: "webhook", header: "Webhook", cell: (p) => (p.webhook_url && p.webhook_secret_set ? "Set" : "Not set"), csv: (p) => p.webhook_url ?? "" }, +]; + +export default function PartnersPage() { + const nav = useNavigate(); + const canManage = useAdminPerm(AdminPerm.ManageOrganizations); + const [creating, setCreating] = useState(false); + const q = useQuery({ queryKey: ["admin", "partners"], queryFn: listPartners }); + const rows = q.data?.data ?? []; + + return ( + <> + + {canManage && ( + + )} + + + p.id} + loading={q.isLoading} + error={q.error} + onRetry={() => void q.refetch()} + onRowClick={(p) => nav(`/partners/${p.id}`)} + emptyTitle="No partners" + emptyHint="The partner API is off on this instance until a partner exists. Add one only for a reseller you have an agreement with." + csvName="partners" + noun="partners" + /> + + ); +} + +function NewPartnerDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (v: boolean) => void }) { + return ( + + + + New partner + + Adds a reseller with no keys yet. Issue a test key on the next page, then a live one when it is ready. + + + onOpenChange(false)} /> + + + ); +} + +function NewPartnerForm({ onClose }: { onClose: () => void }) { + const nav = useNavigate(); + const qc = useQueryClient(); + const [slug, setSlug] = useState(""); + const [name, setName] = useState(""); + const [display, setDisplay] = useState(""); + const [hosts, setHosts] = useState(""); + const ready = /^[a-z0-9][a-z0-9-]{1,39}$/.test(slug.trim()) && !!name.trim(); + + const create = useMutation({ + mutationFn: () => + createPartner({ + slug: slug.trim(), + name: name.trim(), + display_name: display.trim() || undefined, + allowed_hosts: hosts.split(/[\s,]+/).filter(Boolean), + }), + onSuccess: (p) => { + qc.setQueryData(["admin", "partners", p.id], p); + void qc.invalidateQueries({ queryKey: ["admin", "partners"], exact: true }); + toast.success("Partner created"); + onClose(); + nav(`/partners/${p.id}`); + }, + }); + + function submit(e: FormEvent) { + e.preventDefault(); + if (ready && !create.isPending) create.mutate(); + } + + return ( +
+
+ + setSlug(e.target.value.toLowerCase())} autoFocus /> +

Lowercase letters, digits and dashes. It cannot be changed later.

+
+
+ + setName(e.target.value)} /> +
+
+ + setDisplay(e.target.value)} /> +

Members of its workspaces read "Billed through {display || name || "…"}".

+
+
+ + setHosts(e.target.value)} /> +

Hosts a return URL the partner sends may point at, separated by commas.

+
+ {create.error && ( +

+ {create.error.message || "Failed to create the partner."} +

+ )} + + + + +
+ ); +} diff --git a/admin/src/app/dashboard/store/EconomicsTab.tsx b/admin/src/app/dashboard/store/EconomicsTab.tsx new file mode 100644 index 000000000..d840c7102 --- /dev/null +++ b/admin/src/app/dashboard/store/EconomicsTab.tsx @@ -0,0 +1,135 @@ +// Store economics: GraphKit's wholesale price against the retail price this +// instance charges, per mailbox provider and per domain TLD, and the month's totals. + +import { useQuery } from "@tanstack/react-query"; +import { Wallet } from "lucide-react"; +import { EmptyState, Section, Stat, StatGrid } from "@/components/ui/kit"; +import { Skeleton } from "@/components/ui/skeleton"; +import { ErrorState } from "@/components/ErrorState"; +import { APIError } from "@/lib/api/client"; +import { getStoreEconomics } from "@/lib/api/client/admin/store"; +import { relative } from "@/app/dashboard/jobs/format"; +import { TONE_TEXT } from "@/lib/tones"; +import { cn } from "@/lib/utils"; +import { providerLabel, usd } from "./format"; + +const TH = "h-9 px-3 text-left text-xs font-medium text-muted-foreground whitespace-nowrap"; +const TD = "px-3 py-2 tabular-nums whitespace-nowrap"; + +function marginPct(retail: number, wholesale: number): string { + if (retail <= 0) return "—"; + return `${Math.round(((retail - wholesale) / retail) * 100)}%`; +} + +function Margin({ micros }: { micros: number }) { + return {usd(micros)}; +} + +export function EconomicsTab() { + const q = useQuery({ queryKey: ["admin", "store", "economics"], queryFn: getStoreEconomics, staleTime: 5 * 60_000, retry: false }); + if (q.isLoading) return ; + if (q.error instanceof APIError && q.error.code === "store_disabled") { + return ; + } + if (q.error || !q.data) return q.refetch()} />; + const e = q.data; + + return ( +
+ + + + + + +

+ Prices in {e.currency.toUpperCase()}, read from GraphKit {relative(e.updated_at)}. Mailbox totals only; domain income lands once a year per domain. +

+ +
+
+ + + + + + + + + + + + + + + {e.mailboxes.map((m) => ( + + + + + + + + + + + ))} + {e.mailboxes.length === 0 && ( + + + + )} + +
ProviderWholesaleRetailMarginMargin %Scheduled changeLiveMonthly margin
{providerLabel(m.provider)}{usd(m.wholesale_monthly_micros)}{usd(m.retail_monthly_micros)}{marginPct(m.retail_monthly_micros, m.wholesale_monthly_micros)} + {m.scheduled_wholesale_monthly_micros != null ? ( + m.retail_monthly_micros && TONE_TEXT.danger)}> + {usd(m.scheduled_wholesale_monthly_micros)} + {m.scheduled_from && from {new Date(m.scheduled_from).toLocaleDateString()}} + + ) : ( + None + )} + {m.live_count.toLocaleString()}
No mailbox prices
+
+
+ +
+
+ + + + + + + + + + + + + + + {e.domains.map((d) => ( + + + + + + + + + + + ))} + {e.domains.length === 0 && ( + + + + )} + +
TLDMin yearsRegister wholesaleRegister retailRegister marginRenew wholesaleRenew retailRenew margin
.{d.tld.replace(/^\./, "")}{d.min_years}{usd(d.wholesale_register_micros)}{usd(d.retail_register_micros)}{usd(d.wholesale_renew_micros)}{usd(d.retail_renew_micros)}
No domain prices
+
+
+
+ ); +} diff --git a/admin/src/app/dashboard/store/HealthTab.tsx b/admin/src/app/dashboard/store/HealthTab.tsx new file mode 100644 index 000000000..ee716e071 --- /dev/null +++ b/admin/src/app/dashboard/store/HealthTab.tsx @@ -0,0 +1,220 @@ +// Store health: which GraphKit environment the store talks to, the partner +// balance that pays for every order, whether webhooks and the two loops are +// keeping up, and the counts an operator acts on, each linking to its list. + +import { Link } from "react-router-dom"; +import { AlertTriangle, Bell, Wallet } from "lucide-react"; +import { Callout, EmptyState, Panel, Property, PropertyList, Section, StatusBadge } from "@/components/ui/kit"; +import { Skeleton } from "@/components/ui/skeleton"; +import { ErrorState } from "@/components/ErrorState"; +import type { StoreHealth, StoreLoopStatus } from "@/lib/api/client/admin/store"; +import { absolute, humanSeconds, relative } from "@/app/dashboard/jobs/format"; +import { TONE_TEXT, type Tone } from "@/lib/tones"; +import { cn } from "@/lib/utils"; +import { MODE_TONE, storeLink, usd } from "./format"; +import { useStoreHealth } from "./useStoreHealth"; + +// Webhooks only arrive on change, so a quiet day is normal; past this the reconciler is the only source. +const WEBHOOK_STALE_MS = 24 * 60 * 60 * 1000; +// A loop this far behind has stopped keeping the store current. +const LOOP_LAG_WARN_SECONDS = 60 * 60; + +export function HealthTab() { + const q = useStoreHealth(); + if (q.isLoading) return ; + if (q.error || !q.data) return q.refetch()} />; + const h = q.data; + if (!h.enabled || h.mode === "off") { + return ( + + ); + } + return ( +
+
+ + {h.mode} + + {h.metered ? "charges workspaces" : "unmetered: charges nothing"} +
+ +
+ + + + +
+ +
+ +
+ +
+ {(h.uncollected ?? []).length === 0 ? ( +
+ Every mailbox period was paid before it started +
+ ) : ( +
    + {(h.uncollected ?? []).map((m) => ( +
  • + + {m.email} + + GraphKit to {absolute(m.period_end)}, paid to {absolute(m.paid_through)} + +
  • + ))} +
+ )} +
+ +
+ {h.alerts.length === 0 ? ( +
No recent alerts
+ ) : ( +
    + {h.alerts.map((a, i) => ( +
  • + + {a.title} + {a.code} + + {relative(a.at)} + +
  • + ))} +
+ )} +
+
+ ); +} + +function BalancePanel({ h }: { h: StoreHealth }) { + const b = h.partner_balance; + const low = !!b && b.balance_micros <= b.low_threshold_micros; + return ( + + {!b ? ( + + {h.partner_balance_error === "store_unavailable" ? "GraphKit did not answer the balance read." : "No balance reported."} + + ) : ( + <> +
+ {usd(b.balance_micros)} + {b.currency.toUpperCase()} +
+
+ Low below {usd(b.low_threshold_micros)} + {!b.livemode && ", sandbox funds"} +
+ {low && ( + + Top up the partner account before orders and renewals start failing. + + )} + + )} +
+ ); +} + +function WebhookPanel({ h }: { h: StoreHealth }) { + const stale = !h.last_webhook_at || Date.now() - new Date(h.last_webhook_at).getTime() > WEBHOOK_STALE_MS; + return ( + + + + + {stale && } + {relative(h.last_webhook_at)} + + + {h.events_cursor_set ? "Set" : Not set} + + {stale &&

Nothing in the last day. The reconciler still catches changes, more slowly.

} +
+ ); +} + +function loopTone(loop: StoreLoopStatus): Tone { + const s = loop.last_status.toLowerCase(); + if (s === "error" || s === "failed") return "danger"; + if (loop.lag_seconds > LOOP_LAG_WARN_SECONDS) return "warning"; + return "success"; +} + +function LoopPanel({ title, hint, loop }: { title: string; hint: string; loop: StoreLoopStatus | null }) { + if (!loop) { + return ( + +

Has not run yet on this instance.

+
+ ); + } + const tone = loopTone(loop); + return ( + + {loop.last_status || "unknown"} + + } + > + + + {humanSeconds(loop.lag_seconds)} + + + {relative(loop.last_finished_at)} + + + {relative(loop.last_started_at)} + + {loop.last_error && ( + + {loop.last_error} + + )} + + + ); +} + +function CountGrid({ h }: { h: StoreHealth }) { + const c = h.counts; + const items: { label: string; value: number; to: string; tone: Tone }[] = [ + { label: "Open orders", value: c.orders_open, to: storeLink("orders", { status: "open" }), tone: "info" }, + { label: "Stuck orders", value: c.orders_stuck, to: storeLink("orders", { stuck: "true" }), tone: "danger" }, + { label: "Failed orders, 7 days", value: c.orders_failed_7d, to: storeLink("orders", { status: "failed" }), tone: "danger" }, + { label: "Failed connects", value: c.connects_failed, to: storeLink("mailboxes", { connect_state: "failed" }), tone: "danger" }, + { label: "Billing failures", value: c.mailboxes_billing_failed, to: storeLink("mailboxes", { billing_failed: "true" }), tone: "danger" }, + { label: "Renewal failures", value: c.domains_renewal_failed, to: storeLink("domains", { renewal_failed: "true" }), tone: "danger" }, + { label: "Expiring in 30 days", value: c.domains_expiring_30d, to: storeLink("domains", { expiring_days: "30" }), tone: "warning" }, + { label: "Live mailboxes", value: c.mailboxes_live, to: storeLink("mailboxes", { status: "active" }), tone: "neutral" }, + { label: "Live domains", value: c.domains_live, to: storeLink("domains", { status: "active" }), tone: "neutral" }, + ]; + return ( +
+ {items.map((it) => ( + +
{it.label}
+
0 && it.tone !== "neutral" ? TONE_TEXT[it.tone] : "text-foreground")}> + {it.value.toLocaleString()} +
+ + ))} +
+ ); +} diff --git a/admin/src/app/dashboard/store/RefundDialog.tsx b/admin/src/app/dashboard/store/RefundDialog.tsx new file mode 100644 index 000000000..7fc19d338 --- /dev/null +++ b/admin/src/app/dashboard/store/RefundDialog.tsx @@ -0,0 +1,201 @@ +// Refunds a store order to the workspace balance: one quote line's charge, or +// an amount with a reason, capped at what was charged and not yet refunded. +// The idempotency key belongs to the request body, so a retried click after a +// timeout reuses it and the server never pays twice. + +import { useRef, useState } from "react"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Textarea } from "@/components/ui/textarea"; +import { Segmented } from "@/components/ui/kit"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { ReauthCancelledError } from "@/lib/api/client"; +import { refundStoreOrder, type AdminStoreOrder, type StoreRefund } from "@/lib/api/client/admin/store"; +import { cn } from "@/lib/utils"; +import { dollarsToMicros, newIdempotencyKey, refundableMicros, usd } from "./format"; +import { storeErrorText } from "./useStoreAction"; + +type Mode = "line" | "amount"; + +export function RefundDialog({ + order, + open, + onOpenChange, + onRefunded, +}: { + order: AdminStoreOrder; + open: boolean; + onOpenChange: (open: boolean) => void; + onRefunded: (order: AdminStoreOrder) => void; +}) { + return ( + + + {open && onOpenChange(false)} />} + + + ); +} + +function RefundForm({ + order, + onDone, + onCancel, +}: { + order: AdminStoreOrder; + onDone: (order: AdminStoreOrder) => void; + onCancel: () => void; +}) { + const qc = useQueryClient(); + const cap = refundableMicros(order); + const refunded = new Set(order.refunded_lines ?? []); + const openLines = order.lines.map((l, i) => ({ line: l, index: i })).filter((x) => !refunded.has(x.index) && x.line.amount_micros > 0); + const [mode, setMode] = useState(openLines.length > 0 ? "line" : "amount"); + const [line, setLine] = useState(openLines[0]?.index ?? null); + const [amount, setAmount] = useState(""); + const [reason, setReason] = useState(""); + const keyFor = useRef<{ body: string; key: string } | null>(null); + + const micros = dollarsToMicros(amount); + const amountError = + mode !== "amount" || micros === null + ? null + : Number.isNaN(micros) || micros <= 0 + ? "Enter an amount in dollars, like 12.50" + : micros > cap + ? `At most ${usd(cap)} is left to refund` + : null; + + const body: StoreRefund | null = + mode === "line" + ? line === null + ? null + : { line } + : micros && !amountError && reason.trim() + ? { amount_micros: micros, reason: reason.trim() } + : null; + + const refund = useMutation({ + mutationFn: (req: { body: StoreRefund; key: string }) => refundStoreOrder(order.id, req.body, req.key), + onSuccess: (res) => { + toast.success(res.refunded_micros > 0 ? `Refunded ${usd(res.refunded_micros)} to the workspace balance` : "Already refunded; nothing more was paid"); + qc.invalidateQueries({ queryKey: ["admin", "store"] }); + onDone(res.order); + }, + onError: (e) => { + if (!(e instanceof ReauthCancelledError)) toast.error(storeErrorText(e)); + }, + }); + + function submit() { + if (!body) return; + const sig = JSON.stringify(body); + if (keyFor.current?.body !== sig) keyFor.current = { body: sig, key: newIdempotencyKey() }; + refund.mutate({ body, key: keyFor.current.key }); + } + + const lineAmount = line !== null ? order.lines[line]?.amount_micros : undefined; + const total = mode === "line" ? lineAmount : micros && !Number.isNaN(micros) ? micros : undefined; + + return ( + <> + + Refund to the workspace balance + + {order.organization_name} was charged {usd(order.charged_micros)} and has had {usd(order.refunded_micros)} back. + Up to {usd(cap)} can still be refunded. The money goes to the workspace's balance, not the card. + + + +
+ + + {mode === "line" ? ( + openLines.length === 0 ? ( +

Every line with a charge has been refunded.

+ ) : ( +
+ {openLines.map(({ line: l, index }) => ( + + ))} +
+ ) + ) : ( + <> +
+ + setAmount(e.target.value)} + aria-invalid={!!amountError} + /> + {amountError &&

{amountError}

} +
+
+ +