@langwatch/server 3.1.0-beta.1 → 3.1.0-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/langwatch/ee/admin/ImpersonationBanner.tsx +61 -0
- package/langwatch/ee/admin/ImpersonationSwitchBackMenuItem.tsx +30 -0
- package/langwatch/ee/admin/__tests__/ImpersonationBanner.integration.test.tsx +82 -0
- package/langwatch/ee/admin/__tests__/impersonation.service.unit.test.ts +231 -0
- package/langwatch/ee/admin/backoffice/BackofficeTable.tsx +200 -0
- package/langwatch/ee/admin/backoffice/__tests__/adminClient.unit.test.ts +147 -0
- package/langwatch/ee/admin/backoffice/__tests__/dateInputToISO.unit.test.ts +42 -0
- package/langwatch/ee/admin/backoffice/__tests__/userVisibility.unit.test.ts +174 -0
- package/langwatch/ee/admin/backoffice/adminClient.ts +114 -0
- package/langwatch/ee/admin/backoffice/resources/OrganizationFeaturesView.tsx +373 -0
- package/langwatch/ee/admin/backoffice/resources/OrganizationsView.tsx +677 -0
- package/langwatch/ee/admin/backoffice/resources/ProjectsView.tsx +647 -0
- package/langwatch/ee/admin/backoffice/resources/SubscriptionsView.tsx +628 -0
- package/langwatch/ee/admin/backoffice/resources/UsersView.tsx +556 -0
- package/langwatch/ee/admin/backoffice/useAdminResource.ts +104 -0
- package/langwatch/ee/admin/backoffice/userVisibility.ts +105 -0
- package/langwatch/ee/admin/impersonation.service.ts +170 -0
- package/langwatch/ee/admin/isAdmin.ts +9 -0
- package/langwatch/ee/admin/routes/admin.ts +531 -0
- package/langwatch/ee/admin/safeSelects.ts +64 -0
- package/langwatch/ee/billing/__tests__/customerService.unit.test.ts +183 -0
- package/langwatch/ee/billing/__tests__/growthSeatEvent.unit.test.ts +213 -0
- package/langwatch/ee/billing/__tests__/licensePurchaseHandler.unit.test.ts +250 -0
- package/langwatch/ee/billing/__tests__/notification.service.unit.test.ts +768 -0
- package/langwatch/ee/billing/__tests__/planLimits.unit.test.ts +19 -0
- package/langwatch/ee/billing/__tests__/planProvider.unit.test.ts +440 -0
- package/langwatch/ee/billing/__tests__/planTypes.unit.test.ts +32 -0
- package/langwatch/ee/billing/__tests__/pricing.unit.test.ts +54 -0
- package/langwatch/ee/billing/__tests__/seatEventSubscription.unit.test.ts +717 -0
- package/langwatch/ee/billing/__tests__/stripe.integration.test.ts +344 -0
- package/langwatch/ee/billing/__tests__/stripePrices.types.unit.test.ts +27 -0
- package/langwatch/ee/billing/__tests__/stripePricesLoader.unit.test.ts +72 -0
- package/langwatch/ee/billing/__tests__/subscription.service.unit.test.ts +730 -0
- package/langwatch/ee/billing/__tests__/subscriptionItemCalculator.unit.test.ts +176 -0
- package/langwatch/ee/billing/__tests__/usage-limit.service.unit.test.ts +706 -0
- package/langwatch/ee/billing/__tests__/usageReportingService.integration.test.ts +421 -0
- package/langwatch/ee/billing/__tests__/usageReportingService.unit.test.ts +515 -0
- package/langwatch/ee/billing/__tests__/webhookService.unit.test.ts +958 -0
- package/langwatch/ee/billing/currencyRouter.ts +18 -0
- package/langwatch/ee/billing/errors.ts +129 -0
- package/langwatch/ee/billing/index.ts +67 -0
- package/langwatch/ee/billing/middleware.ts +17 -0
- package/langwatch/ee/billing/notifications/notification.service.ts +651 -0
- package/langwatch/ee/billing/notifications/repositories/notification.repository.ts +51 -0
- package/langwatch/ee/billing/notifications/types.ts +9 -0
- package/langwatch/ee/billing/notifications/usage-limit.service.ts +622 -0
- package/langwatch/ee/billing/nurturing/hooks/activityTracking.ts +90 -0
- package/langwatch/ee/billing/nurturing/hooks/activityTracking.unit.test.ts +237 -0
- package/langwatch/ee/billing/nurturing/hooks/featureAdoption.ts +120 -0
- package/langwatch/ee/billing/nurturing/hooks/featureAdoption.unit.test.ts +324 -0
- package/langwatch/ee/billing/nurturing/hooks/index.ts +17 -0
- package/langwatch/ee/billing/nurturing/hooks/productInterest.ts +68 -0
- package/langwatch/ee/billing/nurturing/hooks/productInterest.unit.test.ts +138 -0
- package/langwatch/ee/billing/nurturing/hooks/promptCreation.integration.test.ts +288 -0
- package/langwatch/ee/billing/nurturing/hooks/promptCreation.ts +131 -0
- package/langwatch/ee/billing/nurturing/hooks/promptCreation.unit.test.ts +134 -0
- package/langwatch/ee/billing/nurturing/hooks/signupIdentification.ts +101 -0
- package/langwatch/ee/billing/nurturing/hooks/signupIdentification.unit.test.ts +317 -0
- package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.ts +49 -0
- package/langwatch/ee/billing/nurturing/hooks/subscriptionSync.unit.test.ts +170 -0
- package/langwatch/ee/billing/nurturing/hooks/userSync.ts +143 -0
- package/langwatch/ee/billing/nurturing/hooks/userSync.unit.test.ts +307 -0
- package/langwatch/ee/billing/nurturing/nurturing.service.ts +179 -0
- package/langwatch/ee/billing/nurturing/nurturing.service.unit.test.ts +266 -0
- package/langwatch/ee/billing/nurturing/nurturing.service.wiring.unit.test.ts +109 -0
- package/langwatch/ee/billing/nurturing/types.ts +125 -0
- package/langwatch/ee/billing/planLimits.ts +190 -0
- package/langwatch/ee/billing/planProvider.ts +119 -0
- package/langwatch/ee/billing/planTypes.ts +53 -0
- package/langwatch/ee/billing/pricing.ts +57 -0
- package/langwatch/ee/billing/services/billableEventsQuery.ts +248 -0
- package/langwatch/ee/billing/services/customerService.ts +90 -0
- package/langwatch/ee/billing/services/licensePurchaseHandler.ts +73 -0
- package/langwatch/ee/billing/services/seatEventSubscription.ts +351 -0
- package/langwatch/ee/billing/services/seatSyncService.ts +34 -0
- package/langwatch/ee/billing/services/subscription.repository.ts +203 -0
- package/langwatch/ee/billing/services/subscription.service.ts +549 -0
- package/langwatch/ee/billing/services/subscriptionItemCalculator.ts +249 -0
- package/langwatch/ee/billing/services/usageReportingService.ts +301 -0
- package/langwatch/ee/billing/services/webhookService.ts +858 -0
- package/langwatch/ee/billing/stripe/stripeCatalog.json +1781 -0
- package/langwatch/ee/billing/stripe/stripeClient.ts +13 -0
- package/langwatch/ee/billing/stripe/stripePriceCatalog.ts +70 -0
- package/langwatch/ee/billing/stripe/stripePrices.types.ts +118 -0
- package/langwatch/ee/billing/subscriptionRouter.ts +202 -0
- package/langwatch/ee/billing/types.ts +102 -0
- package/langwatch/ee/billing/utils/currency.ts +99 -0
- package/langwatch/ee/billing/utils/growthSeatEvent.ts +137 -0
- package/langwatch/ee/licensing/__tests__/constants.unit.test.ts +56 -0
- package/langwatch/ee/licensing/__tests__/defaults.unit.test.ts +192 -0
- package/langwatch/ee/licensing/__tests__/fixtures/testKeys.ts +86 -0
- package/langwatch/ee/licensing/__tests__/fixtures/testLicenses.ts +92 -0
- package/langwatch/ee/licensing/__tests__/licenseGenerationService.unit.test.ts +232 -0
- package/langwatch/ee/licensing/__tests__/licenseHandler.integration.test.ts +419 -0
- package/langwatch/ee/licensing/__tests__/planMapping.unit.test.ts +195 -0
- package/langwatch/ee/licensing/__tests__/planTemplates.unit.test.ts +193 -0
- package/langwatch/ee/licensing/__tests__/signing.unit.test.ts +164 -0
- package/langwatch/ee/licensing/__tests__/validation.unit.test.ts +281 -0
- package/langwatch/ee/licensing/client.ts +29 -0
- package/langwatch/ee/licensing/constants.ts +195 -0
- package/langwatch/ee/licensing/defaults.ts +55 -0
- package/langwatch/ee/licensing/errors.ts +11 -0
- package/langwatch/ee/licensing/index.ts +52 -0
- package/langwatch/ee/licensing/licenseGenerationService.ts +87 -0
- package/langwatch/ee/licensing/licenseHandler.ts +308 -0
- package/langwatch/ee/licensing/planInfo.ts +46 -0
- package/langwatch/ee/licensing/planMapping.ts +37 -0
- package/langwatch/ee/licensing/planTemplates.ts +109 -0
- package/langwatch/ee/licensing/server.ts +43 -0
- package/langwatch/ee/licensing/signing.ts +43 -0
- package/langwatch/ee/licensing/types.ts +156 -0
- package/langwatch/ee/licensing/validation.ts +107 -0
- package/langwatch/ee/managed-providers/ManagedModelProviderAlert.tsx +29 -0
- package/langwatch/ee/managed-providers/managedBedrockConfig.ts +226 -0
- package/langwatch/ee/saas/ExtraFooterComponents.tsx +169 -0
- package/langwatch/package.json +1 -1
- package/langwatch/pnpm-workspace.yaml +0 -1
- package/langwatch_nlp/uv.lock +179 -5
- package/mcp-server/.env.example +2 -0
- package/mcp-server/.eslintrc.cjs +36 -0
- package/mcp-server/CHANGELOG.md +165 -0
- package/mcp-server/CONTRIBUTING.md +96 -0
- package/mcp-server/README.md +172 -0
- package/mcp-server/dist/archive-scenario-WJ2A7ETN.js +19 -0
- package/mcp-server/dist/archive-suite-4JOM4SSL.js +15 -0
- package/mcp-server/dist/assign-prompt-tag-GL7EAAF3.js +19 -0
- package/mcp-server/dist/chunk-2GT7IFWK.js +40 -0
- package/mcp-server/dist/chunk-2WPLXEKF.js +127 -0
- package/mcp-server/dist/chunk-4AUB2BIA.js +71 -0
- package/mcp-server/dist/chunk-BWWY5KEF.js +71 -0
- package/mcp-server/dist/chunk-CCWCIJJ3.js +22 -0
- package/mcp-server/dist/chunk-EGH5RPXM.js +25 -0
- package/mcp-server/dist/chunk-EUQDVOSU.js +39 -0
- package/mcp-server/dist/chunk-HYMIWO3U.js +44 -0
- package/mcp-server/dist/chunk-IE4M5OGE.js +42 -0
- package/mcp-server/dist/chunk-LUMEZEHL.js +48 -0
- package/mcp-server/dist/chunk-NUFPTHKU.js +9 -0
- package/mcp-server/dist/chunk-UDHJYT6P.js +1567 -0
- package/mcp-server/dist/chunk-WQG2DFHX.js +86 -0
- package/mcp-server/dist/chunk-WVI5CJ6S.js +21 -0
- package/mcp-server/dist/chunk-ZVS4UKN2.js +35 -0
- package/mcp-server/dist/chunk-ZXKLPC2E.js +27 -0
- package/mcp-server/dist/config.d.ts +17 -0
- package/mcp-server/dist/config.js +13 -0
- package/mcp-server/dist/create-agent-MBOOT3XK.js +23 -0
- package/mcp-server/dist/create-annotation-XMV6A7ED.js +24 -0
- package/mcp-server/dist/create-dashboard-VRKLFVZJ.js +18 -0
- package/mcp-server/dist/create-dataset-7HQPZCRE.js +22 -0
- package/mcp-server/dist/create-dataset-records-2NIVFYTV.js +22 -0
- package/mcp-server/dist/create-evaluator-WYFRFLRC.js +27 -0
- package/mcp-server/dist/create-mcp-server.d.ts +8 -0
- package/mcp-server/dist/create-mcp-server.js +8 -0
- package/mcp-server/dist/create-prompt-IEN7O6JT.js +39 -0
- package/mcp-server/dist/create-prompt-tag-CAEZ45VO.js +17 -0
- package/mcp-server/dist/create-scenario-6YHSMGLP.js +26 -0
- package/mcp-server/dist/create-suite-H5XOFDE5.js +38 -0
- package/mcp-server/dist/delete-agent-JKTNBWAA.js +18 -0
- package/mcp-server/dist/delete-annotation-ACMDV6QO.js +17 -0
- package/mcp-server/dist/delete-dashboard-VJSR7CRU.js +18 -0
- package/mcp-server/dist/delete-dataset-RTTTWP4D.js +20 -0
- package/mcp-server/dist/delete-dataset-records-KNQTIPQK.js +21 -0
- package/mcp-server/dist/delete-evaluator-7FVC5WM4.js +15 -0
- package/mcp-server/dist/delete-prompt-tag-ZMZUAGFW.js +17 -0
- package/mcp-server/dist/delete-workflow-EYQ3T4RQ.js +17 -0
- package/mcp-server/dist/discover-evaluator-schema-H23XCLNE.js +1402 -0
- package/mcp-server/dist/discover-scenario-schema-MEEEVND7.js +65 -0
- package/mcp-server/dist/discover-schema-3T52ORPB.js +446 -0
- package/mcp-server/dist/get-agent-E3QSTVKG.js +28 -0
- package/mcp-server/dist/get-analytics-2OHV763I.js +72 -0
- package/mcp-server/dist/get-dashboard-PC7JDHH6.js +29 -0
- package/mcp-server/dist/get-dataset-H5IK5FVU.js +48 -0
- package/mcp-server/dist/get-evaluator-UWVUPYTM.js +47 -0
- package/mcp-server/dist/get-prompt-WZUOLLQC.js +45 -0
- package/mcp-server/dist/get-scenario-Q6LCNUYN.js +33 -0
- package/mcp-server/dist/get-simulation-run-Z2XKO256.js +56 -0
- package/mcp-server/dist/get-suite-BXK5TN7P.js +44 -0
- package/mcp-server/dist/get-trace-4EJAYVBG.js +50 -0
- package/mcp-server/dist/get-workflow-O34QJLHD.js +25 -0
- package/mcp-server/dist/http-server-RSTXN4CN.js +224 -0
- package/mcp-server/dist/index.d.ts +2 -0
- package/mcp-server/dist/index.js +67774 -0
- package/mcp-server/dist/langwatch-api-annotations-ERBG27RF.js +17 -0
- package/mcp-server/dist/langwatch-api-dashboards-G6TR7VVO.js +17 -0
- package/mcp-server/dist/langwatch-api-monitors-WSXZLS2B.js +52 -0
- package/mcp-server/dist/langwatch-api-secrets-RR5DKG2X.js +40 -0
- package/mcp-server/dist/langwatch-api-triggers-2RTNSWQY.js +30 -0
- package/mcp-server/dist/langwatch-api-workflows-VJRIIDZ7.js +15 -0
- package/mcp-server/dist/list-agents-AW3P6FJV.js +32 -0
- package/mcp-server/dist/list-annotations-QNCGWPQ3.js +33 -0
- package/mcp-server/dist/list-dashboards-R7RK2IXL.js +32 -0
- package/mcp-server/dist/list-dataset-records-WVCSQP7P.js +39 -0
- package/mcp-server/dist/list-datasets-KEXRLDEU.js +60 -0
- package/mcp-server/dist/list-evaluators-7R2LB4JH.js +34 -0
- package/mcp-server/dist/list-model-providers-OBYJCKBX.js +35 -0
- package/mcp-server/dist/list-prompt-tags-6LY3ZPYI.js +23 -0
- package/mcp-server/dist/list-prompts-VWEZ4CDE.js +32 -0
- package/mcp-server/dist/list-scenarios-TXD4W2ZJ.js +40 -0
- package/mcp-server/dist/list-simulation-runs-RHPOLMFI.js +43 -0
- package/mcp-server/dist/list-suites-FSGBX27Z.js +42 -0
- package/mcp-server/dist/list-workflows-VRGEZ3EN.js +35 -0
- package/mcp-server/dist/rename-prompt-tag-VOJJLX4M.js +18 -0
- package/mcp-server/dist/run-agent-KTCC7TB7.js +36 -0
- package/mcp-server/dist/run-evaluation-2X3V3Q6L.js +64 -0
- package/mcp-server/dist/run-suite-BTMHGI2D.js +29 -0
- package/mcp-server/dist/run-workflow-IGAYGKJL.js +36 -0
- package/mcp-server/dist/search-traces-VYFUIMXH.js +72 -0
- package/mcp-server/dist/set-model-provider-W5IUI326.js +33 -0
- package/mcp-server/dist/update-agent-4BB7EYLR.js +20 -0
- package/mcp-server/dist/update-dataset-CXBKZ4W3.js +22 -0
- package/mcp-server/dist/update-dataset-record-HOHAMHXG.js +19 -0
- package/mcp-server/dist/update-evaluator-IVOR6FTR.js +24 -0
- package/mcp-server/dist/update-prompt-OWQAKE7K.js +24 -0
- package/mcp-server/dist/update-scenario-GDFVILPN.js +27 -0
- package/mcp-server/dist/update-suite-BXYUYSPT.js +39 -0
- package/mcp-server/package.json +79 -0
- package/mcp-server/pnpm-lock.yaml +6103 -0
- package/mcp-server/pnpm-workspace.yaml +2 -0
- package/mcp-server/pyproject.toml +17 -0
- package/mcp-server/src/__tests__/all-tools.integration.test.ts +1681 -0
- package/mcp-server/src/__tests__/config.unit.test.ts +169 -0
- package/mcp-server/src/__tests__/datasets.integration.test.ts +603 -0
- package/mcp-server/src/__tests__/datasets.unit.test.ts +240 -0
- package/mcp-server/src/__tests__/date-parsing.unit.test.ts +78 -0
- package/mcp-server/src/__tests__/discover-evaluator-schema.unit.test.ts +89 -0
- package/mcp-server/src/__tests__/discover-schema.unit.test.ts +118 -0
- package/mcp-server/src/__tests__/docker.integration.test.ts +234 -0
- package/mcp-server/src/__tests__/evaluator-tools.unit.test.ts +262 -0
- package/mcp-server/src/__tests__/http-transport.integration.test.ts +397 -0
- package/mcp-server/src/__tests__/integration.integration.test.ts +288 -0
- package/mcp-server/src/__tests__/langwatch-api.unit.test.ts +455 -0
- package/mcp-server/src/__tests__/model-provider-tools.unit.test.ts +190 -0
- package/mcp-server/src/__tests__/scenario-tools.integration.test.ts +286 -0
- package/mcp-server/src/__tests__/scenario-tools.unit.test.ts +185 -0
- package/mcp-server/src/__tests__/schemas.unit.test.ts +85 -0
- package/mcp-server/src/__tests__/tools.unit.test.ts +900 -0
- package/mcp-server/src/config.d.ts +15 -0
- package/mcp-server/src/config.ts +107 -0
- package/mcp-server/src/create-mcp-server.d.ts +6 -0
- package/mcp-server/src/create-mcp-server.ts +1799 -0
- package/mcp-server/src/http-server.ts +329 -0
- package/mcp-server/src/index.ts +46 -0
- package/mcp-server/src/langwatch-api-agents.ts +108 -0
- package/mcp-server/src/langwatch-api-annotations.ts +49 -0
- package/mcp-server/src/langwatch-api-dashboards.ts +48 -0
- package/mcp-server/src/langwatch-api-datasets.ts +191 -0
- package/mcp-server/src/langwatch-api-evaluators.ts +80 -0
- package/mcp-server/src/langwatch-api-model-providers.ts +41 -0
- package/mcp-server/src/langwatch-api-monitors.ts +82 -0
- package/mcp-server/src/langwatch-api-scenarios.ts +67 -0
- package/mcp-server/src/langwatch-api-secrets.ts +48 -0
- package/mcp-server/src/langwatch-api-simulation-runs.ts +51 -0
- package/mcp-server/src/langwatch-api-suites.ts +118 -0
- package/mcp-server/src/langwatch-api-triggers.ts +48 -0
- package/mcp-server/src/langwatch-api-workflows.ts +41 -0
- package/mcp-server/src/langwatch-api.ts +299 -0
- package/mcp-server/src/schemas/analytics-groups.ts +78 -0
- package/mcp-server/src/schemas/analytics-metrics.ts +179 -0
- package/mcp-server/src/schemas/create-dataset.ts +48 -0
- package/mcp-server/src/schemas/filter-fields.ts +119 -0
- package/mcp-server/src/schemas/index.ts +4 -0
- package/mcp-server/src/tools/archive-scenario.ts +19 -0
- package/mcp-server/src/tools/archive-suite.ts +12 -0
- package/mcp-server/src/tools/assign-prompt-tag.ts +16 -0
- package/mcp-server/src/tools/create-agent.ts +15 -0
- package/mcp-server/src/tools/create-annotation.ts +18 -0
- package/mcp-server/src/tools/create-dashboard.ts +7 -0
- package/mcp-server/src/tools/create-dataset-records.ts +23 -0
- package/mcp-server/src/tools/create-dataset.ts +22 -0
- package/mcp-server/src/tools/create-evaluator.ts +33 -0
- package/mcp-server/src/tools/create-prompt-tag.ts +12 -0
- package/mcp-server/src/tools/create-prompt.ts +58 -0
- package/mcp-server/src/tools/create-scenario.ts +30 -0
- package/mcp-server/src/tools/create-suite.ts +42 -0
- package/mcp-server/src/tools/delete-agent.ts +7 -0
- package/mcp-server/src/tools/delete-annotation.ts +7 -0
- package/mcp-server/src/tools/delete-dashboard.ts +7 -0
- package/mcp-server/src/tools/delete-dataset-records.ts +22 -0
- package/mcp-server/src/tools/delete-dataset.ts +20 -0
- package/mcp-server/src/tools/delete-evaluator.ts +12 -0
- package/mcp-server/src/tools/delete-prompt-tag.ts +12 -0
- package/mcp-server/src/tools/delete-workflow.ts +7 -0
- package/mcp-server/src/tools/discover-evaluator-schema.ts +143 -0
- package/mcp-server/src/tools/discover-scenario-schema.ts +71 -0
- package/mcp-server/src/tools/discover-schema.ts +106 -0
- package/mcp-server/src/tools/format-dataset-mutation.ts +25 -0
- package/mcp-server/src/tools/get-agent.ts +21 -0
- package/mcp-server/src/tools/get-analytics.ts +98 -0
- package/mcp-server/src/tools/get-dashboard.ts +22 -0
- package/mcp-server/src/tools/get-dataset.ts +63 -0
- package/mcp-server/src/tools/get-evaluator.ts +53 -0
- package/mcp-server/src/tools/get-prompt.ts +54 -0
- package/mcp-server/src/tools/get-scenario.ts +36 -0
- package/mcp-server/src/tools/get-simulation-run.ts +60 -0
- package/mcp-server/src/tools/get-suite.ts +47 -0
- package/mcp-server/src/tools/get-trace.ts +61 -0
- package/mcp-server/src/tools/get-workflow.ts +17 -0
- package/mcp-server/src/tools/list-agents.ts +27 -0
- package/mcp-server/src/tools/list-annotations.ts +33 -0
- package/mcp-server/src/tools/list-dashboards.ts +27 -0
- package/mcp-server/src/tools/list-dataset-records.ts +46 -0
- package/mcp-server/src/tools/list-datasets.ts +80 -0
- package/mcp-server/src/tools/list-evaluators.ts +37 -0
- package/mcp-server/src/tools/list-model-providers.ts +40 -0
- package/mcp-server/src/tools/list-prompt-tags.ts +21 -0
- package/mcp-server/src/tools/list-prompts.ts +34 -0
- package/mcp-server/src/tools/list-scenarios.ts +47 -0
- package/mcp-server/src/tools/list-simulation-runs.ts +49 -0
- package/mcp-server/src/tools/list-suites.ts +43 -0
- package/mcp-server/src/tools/list-workflows.ts +31 -0
- package/mcp-server/src/tools/rename-prompt-tag.ts +14 -0
- package/mcp-server/src/tools/run-agent.ts +36 -0
- package/mcp-server/src/tools/run-evaluation.ts +87 -0
- package/mcp-server/src/tools/run-suite.ts +28 -0
- package/mcp-server/src/tools/run-workflow.ts +36 -0
- package/mcp-server/src/tools/search-traces.ts +91 -0
- package/mcp-server/src/tools/set-model-provider.ts +46 -0
- package/mcp-server/src/tools/update-agent.ts +13 -0
- package/mcp-server/src/tools/update-dataset-record.ts +21 -0
- package/mcp-server/src/tools/update-dataset.ts +23 -0
- package/mcp-server/src/tools/update-evaluator.ts +30 -0
- package/mcp-server/src/tools/update-prompt.ts +31 -0
- package/mcp-server/src/tools/update-scenario.ts +32 -0
- package/mcp-server/src/tools/update-suite.ts +44 -0
- package/mcp-server/src/utils/date-parsing.ts +31 -0
- package/mcp-server/src/utils/escape-markdown.ts +12 -0
- package/mcp-server/tsconfig.json +27 -0
- package/mcp-server/uv.lock +2731 -0
- package/package.json +2 -6
- package/packages/server/dist/cli.cjs +299 -177
- package/cmd/service/main.go +0 -68
- package/go.mod +0 -117
- package/go.sum +0 -299
- package/pkg/breaker/breaker.go +0 -157
- package/pkg/breaker/breaker_test.go +0 -131
- package/pkg/clog/LICENSE +0 -26
- package/pkg/clog/clog.go +0 -90
- package/pkg/clog/clog_test.go +0 -56
- package/pkg/clog/panic.go +0 -39
- package/pkg/config/LICENSE +0 -26
- package/pkg/config/config.go +0 -86
- package/pkg/config/config_test.go +0 -70
- package/pkg/config/otel.go +0 -50
- package/pkg/config/server.go +0 -61
- package/pkg/config/validate.go +0 -80
- package/pkg/config/validate_test.go +0 -74
- package/pkg/contexts/contexts_test.go +0 -34
- package/pkg/contexts/request_id.go +0 -1
- package/pkg/contexts/service_info.go +0 -33
- package/pkg/errfuncs/errfuncs.go +0 -9
- package/pkg/errfuncs/errfuncs_test.go +0 -28
- package/pkg/forkedcontext/forkedcontext.go +0 -57
- package/pkg/health/health.go +0 -123
- package/pkg/health/health_test.go +0 -84
- package/pkg/herr/LICENSE +0 -26
- package/pkg/herr/code.go +0 -14
- package/pkg/herr/herr.go +0 -112
- package/pkg/herr/herr_test.go +0 -78
- package/pkg/herr/http.go +0 -133
- package/pkg/herr/http_test.go +0 -103
- package/pkg/herr/validate.go +0 -72
- package/pkg/herr/validate_test.go +0 -75
- package/pkg/httpmiddleware/bearer.go +0 -47
- package/pkg/httpmiddleware/httputil_test.go +0 -167
- package/pkg/httpmiddleware/inflight.go +0 -23
- package/pkg/httpmiddleware/maxbody.go +0 -30
- package/pkg/httpmiddleware/recover.go +0 -38
- package/pkg/httpmiddleware/requestid.go +0 -40
- package/pkg/httpmiddleware/telemetry.go +0 -96
- package/pkg/httpmiddleware/version.go +0 -16
- package/pkg/jwtverify/verifier.go +0 -72
- package/pkg/jwtverify/verifier_test.go +0 -134
- package/pkg/ksuid/LICENSE +0 -26
- package/pkg/ksuid/ksuid.go +0 -157
- package/pkg/ksuid/ksuid_test.go +0 -107
- package/pkg/ksuid/resources.go +0 -13
- package/pkg/lifecycle/group.go +0 -175
- package/pkg/lifecycle/group_test.go +0 -236
- package/pkg/lifecycle/service.go +0 -112
- package/pkg/netprobe/netprobe.go +0 -89
- package/pkg/netprobe/netprobe_test.go +0 -55
- package/pkg/otelsetup/otelsetup.go +0 -226
- package/pkg/otelsetup/otelsetup_test.go +0 -130
- package/pkg/ptr/LICENSE +0 -26
- package/pkg/ptr/ptr.go +0 -34
- package/pkg/ptr/ptr_test.go +0 -66
- package/pkg/retry/bench_test.go +0 -67
- package/pkg/retry/retry.go +0 -188
- package/pkg/retry/retry_test.go +0 -222
- package/pkg/slicefuncs/LICENSE +0 -26
- package/pkg/slicefuncs/slicefuncs.go +0 -10
- package/pkg/slicefuncs/slicefuncs_test.go +0 -29
- package/pkg/stacktrace/LICENSE +0 -26
- package/pkg/stacktrace/frames.go +0 -77
- package/pkg/stacktrace/frames_test.go +0 -73
- package/services/aigateway/BENCHMARKS.md +0 -110
- package/services/aigateway/README.md +0 -156
- package/services/aigateway/adapters/authresolver/bench_test.go +0 -13
- package/services/aigateway/adapters/authresolver/redis.go +0 -61
- package/services/aigateway/adapters/authresolver/service.go +0 -442
- package/services/aigateway/adapters/authresolver/service_test.go +0 -435
- package/services/aigateway/adapters/budget/bench_test.go +0 -50
- package/services/aigateway/adapters/budget/budget.go +0 -59
- package/services/aigateway/adapters/cacherules/evaluator.go +0 -134
- package/services/aigateway/adapters/cacherules/evaluator_test.go +0 -207
- package/services/aigateway/adapters/controlplane/bench_test.go +0 -40
- package/services/aigateway/adapters/controlplane/client.go +0 -213
- package/services/aigateway/adapters/controlplane/client_test.go +0 -73
- package/services/aigateway/adapters/controlplane/config_wire.go +0 -310
- package/services/aigateway/adapters/controlplane/guardrails.go +0 -88
- package/services/aigateway/adapters/controlplane/signer.go +0 -95
- package/services/aigateway/adapters/controlplane/signer_test.go +0 -64
- package/services/aigateway/adapters/customertracebridge/context.go +0 -48
- package/services/aigateway/adapters/customertracebridge/context_test.go +0 -24
- package/services/aigateway/adapters/customertracebridge/emitter.go +0 -329
- package/services/aigateway/adapters/customertracebridge/emitter_test.go +0 -93
- package/services/aigateway/adapters/customertracebridge/registry.go +0 -82
- package/services/aigateway/adapters/customertracebridge/transport.go +0 -122
- package/services/aigateway/adapters/gatewaytracer/attrs.go +0 -28
- package/services/aigateway/adapters/gatewaytracer/attrs_genai.go +0 -24
- package/services/aigateway/adapters/gatewaytracer/headers.go +0 -8
- package/services/aigateway/adapters/gatewaytracer/tracer.go +0 -101
- package/services/aigateway/adapters/httpapi/bench_test.go +0 -83
- package/services/aigateway/adapters/httpapi/middleware.go +0 -123
- package/services/aigateway/adapters/httpapi/router.go +0 -635
- package/services/aigateway/adapters/httpapi/router_test.go +0 -633
- package/services/aigateway/adapters/modelresolver/resolver.go +0 -107
- package/services/aigateway/adapters/modelresolver/resolver_test.go +0 -140
- package/services/aigateway/adapters/policy/matcher.go +0 -250
- package/services/aigateway/adapters/policy/matcher_test.go +0 -124
- package/services/aigateway/adapters/providers/bifrost.go +0 -798
- package/services/aigateway/adapters/providers/bifrost_parser.go +0 -201
- package/services/aigateway/adapters/providers/bifrost_test.go +0 -181
- package/services/aigateway/adapters/ratelimit/limiter.go +0 -122
- package/services/aigateway/adapters/ratelimit/limiter_test.go +0 -81
- package/services/aigateway/app/app.go +0 -104
- package/services/aigateway/app/dispatch.go +0 -89
- package/services/aigateway/app/dispatch_test.go +0 -475
- package/services/aigateway/app/handlers.go +0 -79
- package/services/aigateway/app/peek_bench_test.go +0 -21
- package/services/aigateway/app/pipeline/bench_test.go +0 -34
- package/services/aigateway/app/pipeline/budget.go +0 -55
- package/services/aigateway/app/pipeline/cache.go +0 -34
- package/services/aigateway/app/pipeline/cachecontrol.go +0 -86
- package/services/aigateway/app/pipeline/cachecontrol_test.go +0 -110
- package/services/aigateway/app/pipeline/guardrail.go +0 -121
- package/services/aigateway/app/pipeline/pipeline.go +0 -159
- package/services/aigateway/app/pipeline/policy.go +0 -23
- package/services/aigateway/app/pipeline/ratelimit.go +0 -21
- package/services/aigateway/app/pipeline/rawframing_test.go +0 -67
- package/services/aigateway/app/pipeline/resolve.go +0 -44
- package/services/aigateway/app/pipeline/trace.go +0 -129
- package/services/aigateway/app/ports.go +0 -61
- package/services/aigateway/cmd/root.go +0 -42
- package/services/aigateway/config.go +0 -86
- package/services/aigateway/deps.go +0 -177
- package/services/aigateway/domain/bundle.go +0 -203
- package/services/aigateway/domain/errors.go +0 -23
- package/services/aigateway/domain/model.go +0 -24
- package/services/aigateway/domain/provider.go +0 -38
- package/services/aigateway/domain/request.go +0 -65
- package/services/aigateway/domain/response.go +0 -56
- package/services/aigateway/domain/verdict.go +0 -55
- package/services/aigateway/serve.go +0 -45
- package/services/aigateway/tests/matrix/README.md +0 -71
- package/services/aigateway/tests/matrix/anthropic_test.go +0 -61
- package/services/aigateway/tests/matrix/azure_test.go +0 -52
- package/services/aigateway/tests/matrix/bedrock_test.go +0 -69
- package/services/aigateway/tests/matrix/gemini_test.go +0 -117
- package/services/aigateway/tests/matrix/matrix_test.go +0 -601
- package/services/aigateway/tests/matrix/openai_test.go +0 -66
- package/services/aigateway/tests/matrix/vertex_test.go +0 -160
|
@@ -0,0 +1,858 @@
|
|
|
1
|
+
import { Currency, type PrismaClient } from "@prisma/client";
|
|
2
|
+
import type Stripe from "stripe";
|
|
3
|
+
import type { PostHog } from "posthog-node";
|
|
4
|
+
import { createLogger } from "../../../src/utils/logger";
|
|
5
|
+
import { getApp } from "../../../src/server/app-layer/app";
|
|
6
|
+
import type {
|
|
7
|
+
SubscriptionRepository,
|
|
8
|
+
SubscriptionWithOrg,
|
|
9
|
+
} from "../../../src/server/app-layer/subscription/subscription.repository";
|
|
10
|
+
import type { OrganizationRepository } from "../../../src/server/app-layer/organizations/repositories/organization.repository";
|
|
11
|
+
import { PrismaOrganizationRepository } from "../../../src/server/app-layer/organizations/repositories/organization.prisma.repository";
|
|
12
|
+
import { PrismaSubscriptionRepository } from "./subscription.repository";
|
|
13
|
+
import { SubscriptionStatus } from "../planTypes";
|
|
14
|
+
import type { calculateQuantityForPrice, prices } from "./subscriptionItemCalculator";
|
|
15
|
+
import { isGrowthEventsPrice, isGrowthSeatEventPlan, isGrowthSeatPrice } from "../utils/growthSeatEvent";
|
|
16
|
+
import { SubscriptionRecordNotFoundError } from "../errors";
|
|
17
|
+
import { traced } from "../../../src/server/app-layer/tracing";
|
|
18
|
+
import { fireSubscriptionSyncNurturing } from "../nurturing/hooks/subscriptionSync";
|
|
19
|
+
|
|
20
|
+
const logger = createLogger("langwatch:billing:webhookService");
|
|
21
|
+
|
|
22
|
+
const VALID_CURRENCIES_FOR_CHECKOUT = new Set<string>(Object.values(Currency));
|
|
23
|
+
const maskCustomerId = (id: string) => `${id.slice(0, 7)}...${id.slice(-4)}`;
|
|
24
|
+
|
|
25
|
+
type ItemCalculator = {
|
|
26
|
+
calculateQuantityForPrice: typeof calculateQuantityForPrice;
|
|
27
|
+
prices: typeof prices;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
type InviteApprover = {
|
|
31
|
+
approvePaymentPendingInvites(params: {
|
|
32
|
+
subscriptionId: string;
|
|
33
|
+
organizationId: string;
|
|
34
|
+
}): Promise<unknown>;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* License purchase events originate from a specific Stripe payment link and
|
|
39
|
+
* target self-hosted buyers who have no organization in the SaaS database.
|
|
40
|
+
* The webhook service routes these before any org lookup.
|
|
41
|
+
*/
|
|
42
|
+
export interface LicensePurchaseHandler {
|
|
43
|
+
handle(params: {
|
|
44
|
+
checkoutSession: Stripe.Checkout.Session;
|
|
45
|
+
stripe: Stripe;
|
|
46
|
+
privateKey: string;
|
|
47
|
+
}): Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export type HandleEventResult =
|
|
51
|
+
| { status: "ok" }
|
|
52
|
+
| { status: "error"; httpStatus: 400 | 500; message: string };
|
|
53
|
+
|
|
54
|
+
/** Stripe webhooks can arrive before subscription state is fully consistent. */
|
|
55
|
+
const STRIPE_EVENTUAL_CONSISTENCY_DELAY_MS = 2000;
|
|
56
|
+
// TECH-DEBT: This fixed delay should become a retry loop with backoff.
|
|
57
|
+
const waitForStripeConsistency = () =>
|
|
58
|
+
new Promise((resolve) => setTimeout(resolve, STRIPE_EVENTUAL_CONSISTENCY_DELAY_MS));
|
|
59
|
+
|
|
60
|
+
export type WebhookService = {
|
|
61
|
+
/**
|
|
62
|
+
* Dispatches a verified Stripe event to the right handler.
|
|
63
|
+
*
|
|
64
|
+
* Signature verification happens at the transport layer (the Hono route);
|
|
65
|
+
* this method is transport-agnostic so it can be reused from workers,
|
|
66
|
+
* replays, and tests.
|
|
67
|
+
*
|
|
68
|
+
* Retry policy:
|
|
69
|
+
* - Returns `{ status: "ok" }` for no-op events (unknown types, events we
|
|
70
|
+
* do not care about). Stripe will mark delivery successful — no retry.
|
|
71
|
+
* - Returns `{ status: "error", httpStatus: 500 }` on unexpected throws.
|
|
72
|
+
* Stripe retries with backoff — correct for transient infra failures
|
|
73
|
+
* and for bugs that will succeed after a deploy.
|
|
74
|
+
* - Every non-action branch logs at INFO/ERROR — nothing returns silently.
|
|
75
|
+
*/
|
|
76
|
+
handleEvent(event: Stripe.Event): Promise<HandleEventResult>;
|
|
77
|
+
|
|
78
|
+
handleCheckoutCompleted(params: {
|
|
79
|
+
subscriptionId: string;
|
|
80
|
+
clientReferenceId: string | null;
|
|
81
|
+
selectedCurrency?: string | null;
|
|
82
|
+
}): Promise<{ earlyReturn: boolean }>;
|
|
83
|
+
|
|
84
|
+
handleInvoicePaymentSucceeded(params: {
|
|
85
|
+
subscriptionId: string;
|
|
86
|
+
throwOnMissing?: boolean;
|
|
87
|
+
}): Promise<void>;
|
|
88
|
+
|
|
89
|
+
handleInvoicePaymentFailed(params: {
|
|
90
|
+
subscriptionId: string;
|
|
91
|
+
}): Promise<void>;
|
|
92
|
+
|
|
93
|
+
handleSubscriptionDeleted(params: {
|
|
94
|
+
stripeSubscriptionId: string;
|
|
95
|
+
}): Promise<void>;
|
|
96
|
+
|
|
97
|
+
handleSubscriptionUpdated(params: {
|
|
98
|
+
subscription: Stripe.Subscription;
|
|
99
|
+
}): Promise<void>;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
export class EEWebhookService implements WebhookService {
|
|
103
|
+
private readonly subscriptionRepository: SubscriptionRepository;
|
|
104
|
+
private readonly organizationRepository: OrganizationRepository;
|
|
105
|
+
private readonly stripe: Stripe;
|
|
106
|
+
private readonly itemCalculator: ItemCalculator;
|
|
107
|
+
private readonly inviteApprover?: InviteApprover;
|
|
108
|
+
private readonly licensePurchaseHandler?: LicensePurchaseHandler;
|
|
109
|
+
private readonly licensePaymentLinkId?: string;
|
|
110
|
+
private readonly licensePrivateKey?: string;
|
|
111
|
+
private readonly getPostHog?: () => PostHog | null;
|
|
112
|
+
|
|
113
|
+
constructor({
|
|
114
|
+
subscriptionRepository,
|
|
115
|
+
organizationRepository,
|
|
116
|
+
stripe,
|
|
117
|
+
itemCalculator,
|
|
118
|
+
inviteApprover,
|
|
119
|
+
licensePurchaseHandler,
|
|
120
|
+
licensePaymentLinkId,
|
|
121
|
+
licensePrivateKey,
|
|
122
|
+
getPostHog,
|
|
123
|
+
}: {
|
|
124
|
+
subscriptionRepository: SubscriptionRepository;
|
|
125
|
+
organizationRepository: OrganizationRepository;
|
|
126
|
+
stripe: Stripe;
|
|
127
|
+
itemCalculator: ItemCalculator;
|
|
128
|
+
inviteApprover?: InviteApprover;
|
|
129
|
+
licensePurchaseHandler?: LicensePurchaseHandler;
|
|
130
|
+
licensePaymentLinkId?: string;
|
|
131
|
+
licensePrivateKey?: string;
|
|
132
|
+
getPostHog?: () => PostHog | null;
|
|
133
|
+
}) {
|
|
134
|
+
this.subscriptionRepository = subscriptionRepository;
|
|
135
|
+
this.organizationRepository = organizationRepository;
|
|
136
|
+
this.stripe = stripe;
|
|
137
|
+
this.itemCalculator = itemCalculator;
|
|
138
|
+
this.inviteApprover = inviteApprover;
|
|
139
|
+
this.licensePurchaseHandler = licensePurchaseHandler;
|
|
140
|
+
this.licensePaymentLinkId = licensePaymentLinkId;
|
|
141
|
+
this.licensePrivateKey = licensePrivateKey;
|
|
142
|
+
this.getPostHog = getPostHog;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
static create({
|
|
146
|
+
db,
|
|
147
|
+
stripe,
|
|
148
|
+
itemCalculator,
|
|
149
|
+
inviteApprover,
|
|
150
|
+
licensePurchaseHandler,
|
|
151
|
+
licensePaymentLinkId,
|
|
152
|
+
licensePrivateKey,
|
|
153
|
+
getPostHog,
|
|
154
|
+
}: {
|
|
155
|
+
db: PrismaClient;
|
|
156
|
+
stripe: Stripe;
|
|
157
|
+
itemCalculator: ItemCalculator;
|
|
158
|
+
inviteApprover?: InviteApprover;
|
|
159
|
+
licensePurchaseHandler?: LicensePurchaseHandler;
|
|
160
|
+
licensePaymentLinkId?: string;
|
|
161
|
+
licensePrivateKey?: string;
|
|
162
|
+
getPostHog?: () => PostHog | null;
|
|
163
|
+
}): WebhookService {
|
|
164
|
+
return traced(
|
|
165
|
+
new EEWebhookService({
|
|
166
|
+
subscriptionRepository: new PrismaSubscriptionRepository(db),
|
|
167
|
+
organizationRepository: new PrismaOrganizationRepository(db),
|
|
168
|
+
stripe,
|
|
169
|
+
itemCalculator,
|
|
170
|
+
inviteApprover,
|
|
171
|
+
licensePurchaseHandler,
|
|
172
|
+
licensePaymentLinkId,
|
|
173
|
+
licensePrivateKey,
|
|
174
|
+
getPostHog,
|
|
175
|
+
}),
|
|
176
|
+
"EEWebhookService",
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async handleEvent(event: Stripe.Event): Promise<HandleEventResult> {
|
|
181
|
+
try {
|
|
182
|
+
if (event.type === "checkout.session.completed") {
|
|
183
|
+
const licenseResult = await this.tryRouteLicensePurchase(event);
|
|
184
|
+
if (licenseResult) return licenseResult;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (
|
|
188
|
+
event.type === "checkout.session.completed" ||
|
|
189
|
+
event.type === "invoice.payment_succeeded" ||
|
|
190
|
+
event.type === "invoice.payment_failed"
|
|
191
|
+
) {
|
|
192
|
+
return await this.routeCheckoutOrInvoice(event);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (
|
|
196
|
+
event.type === "customer.subscription.deleted" ||
|
|
197
|
+
event.type === "customer.subscription.updated"
|
|
198
|
+
) {
|
|
199
|
+
return await this.routeSubscriptionLifecycle(event);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
logger.info(
|
|
203
|
+
{ eventType: event.type, eventId: event.id },
|
|
204
|
+
"[stripeWebhook] Ignoring unhandled event type",
|
|
205
|
+
);
|
|
206
|
+
return { status: "ok" };
|
|
207
|
+
} catch (error) {
|
|
208
|
+
logger.error(
|
|
209
|
+
{
|
|
210
|
+
error: (error as Error).message,
|
|
211
|
+
stack: (error as Error).stack,
|
|
212
|
+
eventType: event.type,
|
|
213
|
+
eventId: event.id,
|
|
214
|
+
},
|
|
215
|
+
"[stripeWebhook] Unhandled error processing event",
|
|
216
|
+
);
|
|
217
|
+
return {
|
|
218
|
+
status: "error",
|
|
219
|
+
httpStatus: 500,
|
|
220
|
+
message: "Webhook processing error",
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Returns a result when the session is a license purchase, otherwise null
|
|
227
|
+
* so `handleEvent` falls through to the subscription flow.
|
|
228
|
+
*/
|
|
229
|
+
private async tryRouteLicensePurchase(
|
|
230
|
+
event: Stripe.Event & { type: "checkout.session.completed" },
|
|
231
|
+
): Promise<HandleEventResult | null> {
|
|
232
|
+
const checkoutSession = event.data.object as Stripe.Checkout.Session;
|
|
233
|
+
|
|
234
|
+
const paymentLinkId =
|
|
235
|
+
typeof checkoutSession.payment_link === "string"
|
|
236
|
+
? checkoutSession.payment_link
|
|
237
|
+
: checkoutSession.payment_link?.id;
|
|
238
|
+
|
|
239
|
+
if (
|
|
240
|
+
!this.licensePaymentLinkId ||
|
|
241
|
+
paymentLinkId !== this.licensePaymentLinkId
|
|
242
|
+
) {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (!this.licensePurchaseHandler) {
|
|
247
|
+
logger.error(
|
|
248
|
+
{ eventId: event.id },
|
|
249
|
+
"[stripeWebhook] License purchase handler is not configured",
|
|
250
|
+
);
|
|
251
|
+
return {
|
|
252
|
+
status: "error",
|
|
253
|
+
httpStatus: 500,
|
|
254
|
+
message: "License generation error: handler not configured",
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
if (!this.licensePrivateKey) {
|
|
259
|
+
logger.error(
|
|
260
|
+
{ eventId: event.id },
|
|
261
|
+
"[stripeWebhook] LANGWATCH_LICENSE_PRIVATE_KEY is not configured",
|
|
262
|
+
);
|
|
263
|
+
return {
|
|
264
|
+
status: "error",
|
|
265
|
+
httpStatus: 500,
|
|
266
|
+
message: "License generation error: missing private key",
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
await this.licensePurchaseHandler.handle({
|
|
271
|
+
checkoutSession,
|
|
272
|
+
stripe: this.stripe,
|
|
273
|
+
privateKey: this.licensePrivateKey,
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
return { status: "ok" };
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
private async routeCheckoutOrInvoice(
|
|
280
|
+
event: Stripe.Event & {
|
|
281
|
+
type:
|
|
282
|
+
| "checkout.session.completed"
|
|
283
|
+
| "invoice.payment_succeeded"
|
|
284
|
+
| "invoice.payment_failed";
|
|
285
|
+
},
|
|
286
|
+
): Promise<HandleEventResult> {
|
|
287
|
+
const paymentIntent = event.data.object as
|
|
288
|
+
| Stripe.Checkout.Session
|
|
289
|
+
| Stripe.Invoice;
|
|
290
|
+
|
|
291
|
+
const subscriptionId =
|
|
292
|
+
typeof paymentIntent.subscription === "string"
|
|
293
|
+
? paymentIntent.subscription
|
|
294
|
+
: paymentIntent.subscription?.id;
|
|
295
|
+
|
|
296
|
+
if (!subscriptionId) {
|
|
297
|
+
logger.info(
|
|
298
|
+
{ eventType: event.type, eventId: event.id },
|
|
299
|
+
"[stripeWebhook] Event has no subscription id — skipping",
|
|
300
|
+
);
|
|
301
|
+
return { status: "ok" };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Customer/organization lookup is best-effort for analytics only.
|
|
305
|
+
// Core handlers only need subscriptionId (+ client_reference_id for
|
|
306
|
+
// checkout) — dropping the work here would ACK the event to Stripe
|
|
307
|
+
// (no retry) while leaving the DB subscription PENDING.
|
|
308
|
+
const customerId =
|
|
309
|
+
typeof paymentIntent.customer === "string"
|
|
310
|
+
? paymentIntent.customer
|
|
311
|
+
: paymentIntent.customer?.id;
|
|
312
|
+
|
|
313
|
+
const organization = customerId
|
|
314
|
+
? await this.organizationRepository.findByStripeCustomerId(customerId)
|
|
315
|
+
: null;
|
|
316
|
+
|
|
317
|
+
if (customerId && !organization) {
|
|
318
|
+
logger.warn(
|
|
319
|
+
{
|
|
320
|
+
eventType: event.type,
|
|
321
|
+
eventId: event.id,
|
|
322
|
+
customerId: maskCustomerId(customerId),
|
|
323
|
+
},
|
|
324
|
+
"[stripeWebhook] No organization found for customer — proceeding without analytics",
|
|
325
|
+
);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
switch (event.type) {
|
|
329
|
+
case "checkout.session.completed":
|
|
330
|
+
await this.dispatchCheckoutCompleted({
|
|
331
|
+
event: event as Stripe.Event & { type: "checkout.session.completed" },
|
|
332
|
+
subscriptionId,
|
|
333
|
+
customerId,
|
|
334
|
+
organizationId: organization?.id ?? null,
|
|
335
|
+
});
|
|
336
|
+
return { status: "ok" };
|
|
337
|
+
|
|
338
|
+
case "invoice.payment_succeeded":
|
|
339
|
+
await this.handleInvoicePaymentSucceeded({ subscriptionId });
|
|
340
|
+
return { status: "ok" };
|
|
341
|
+
|
|
342
|
+
case "invoice.payment_failed":
|
|
343
|
+
await this.handleInvoicePaymentFailed({ subscriptionId });
|
|
344
|
+
return { status: "ok" };
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
private async dispatchCheckoutCompleted({
|
|
349
|
+
event,
|
|
350
|
+
subscriptionId,
|
|
351
|
+
customerId,
|
|
352
|
+
organizationId,
|
|
353
|
+
}: {
|
|
354
|
+
event: Stripe.Event & { type: "checkout.session.completed" };
|
|
355
|
+
subscriptionId: string;
|
|
356
|
+
customerId?: string;
|
|
357
|
+
organizationId: string | null;
|
|
358
|
+
}): Promise<void> {
|
|
359
|
+
const checkoutSession = event.data.object as Stripe.Checkout.Session;
|
|
360
|
+
const selectedCurrencyRaw = checkoutSession.metadata?.selectedCurrency;
|
|
361
|
+
const selectedCurrency =
|
|
362
|
+
selectedCurrencyRaw &&
|
|
363
|
+
VALID_CURRENCIES_FOR_CHECKOUT.has(selectedCurrencyRaw)
|
|
364
|
+
? selectedCurrencyRaw
|
|
365
|
+
: null;
|
|
366
|
+
|
|
367
|
+
const result = await this.handleCheckoutCompleted({
|
|
368
|
+
subscriptionId,
|
|
369
|
+
clientReferenceId: checkoutSession.client_reference_id ?? null,
|
|
370
|
+
selectedCurrency,
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
if (result.earlyReturn) {
|
|
374
|
+
logger.error(
|
|
375
|
+
{
|
|
376
|
+
eventId: event.id,
|
|
377
|
+
customerId: customerId ? maskCustomerId(customerId) : null,
|
|
378
|
+
},
|
|
379
|
+
"[stripeWebhook] No client_reference_id in checkout session",
|
|
380
|
+
);
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
if (organizationId) {
|
|
385
|
+
this.emitCheckoutAnalytics({
|
|
386
|
+
checkoutSession,
|
|
387
|
+
subscriptionId,
|
|
388
|
+
organizationId,
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
private emitCheckoutAnalytics({
|
|
394
|
+
checkoutSession,
|
|
395
|
+
subscriptionId,
|
|
396
|
+
organizationId,
|
|
397
|
+
}: {
|
|
398
|
+
checkoutSession: Stripe.Checkout.Session;
|
|
399
|
+
subscriptionId: string;
|
|
400
|
+
organizationId: string;
|
|
401
|
+
}): void {
|
|
402
|
+
const posthog = this.getPostHog?.() ?? null;
|
|
403
|
+
if (!posthog) return;
|
|
404
|
+
|
|
405
|
+
posthog.capture({
|
|
406
|
+
distinctId: organizationId,
|
|
407
|
+
event: "subscription_created",
|
|
408
|
+
properties: {
|
|
409
|
+
subscriptionId,
|
|
410
|
+
$groups: { organization: organizationId },
|
|
411
|
+
},
|
|
412
|
+
});
|
|
413
|
+
posthog.groupIdentify({
|
|
414
|
+
groupType: "organization",
|
|
415
|
+
groupKey: organizationId,
|
|
416
|
+
properties: {
|
|
417
|
+
subscriptionCreatedAt: new Date(
|
|
418
|
+
checkoutSession.created * 1000,
|
|
419
|
+
).toISOString(),
|
|
420
|
+
hasActiveSubscription: true,
|
|
421
|
+
},
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
private async routeSubscriptionLifecycle(
|
|
426
|
+
event: Stripe.Event & {
|
|
427
|
+
type: "customer.subscription.deleted" | "customer.subscription.updated";
|
|
428
|
+
},
|
|
429
|
+
): Promise<HandleEventResult> {
|
|
430
|
+
const subscription = event.data.object as Stripe.Subscription;
|
|
431
|
+
if (!subscription.id) {
|
|
432
|
+
logger.info(
|
|
433
|
+
{ eventType: event.type, eventId: event.id },
|
|
434
|
+
"[stripeWebhook] Subscription event has no id — skipping",
|
|
435
|
+
);
|
|
436
|
+
return { status: "ok" };
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
if (event.type === "customer.subscription.deleted") {
|
|
440
|
+
await this.handleSubscriptionDeleted({
|
|
441
|
+
stripeSubscriptionId: subscription.id,
|
|
442
|
+
});
|
|
443
|
+
} else {
|
|
444
|
+
await this.handleSubscriptionUpdated({ subscription });
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
return { status: "ok" };
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
async handleCheckoutCompleted({
|
|
451
|
+
subscriptionId,
|
|
452
|
+
clientReferenceId,
|
|
453
|
+
selectedCurrency,
|
|
454
|
+
}: {
|
|
455
|
+
subscriptionId: string;
|
|
456
|
+
clientReferenceId: string | null;
|
|
457
|
+
selectedCurrency?: string | null;
|
|
458
|
+
}): Promise<{ earlyReturn: boolean }> {
|
|
459
|
+
const subscriptionClientReferenceId = clientReferenceId?.replace(
|
|
460
|
+
"subscription_setup_",
|
|
461
|
+
"",
|
|
462
|
+
);
|
|
463
|
+
|
|
464
|
+
if (!subscriptionClientReferenceId) {
|
|
465
|
+
return { earlyReturn: true };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const updateResult = await this.subscriptionRepository.linkStripeId({
|
|
469
|
+
id: subscriptionClientReferenceId,
|
|
470
|
+
stripeSubscriptionId: subscriptionId,
|
|
471
|
+
});
|
|
472
|
+
|
|
473
|
+
if (updateResult.count === 0) {
|
|
474
|
+
logger.error(
|
|
475
|
+
{ subscriptionClientReferenceId },
|
|
476
|
+
"[stripeWebhook] No subscription found for checkout",
|
|
477
|
+
);
|
|
478
|
+
throw new SubscriptionRecordNotFoundError(
|
|
479
|
+
subscriptionClientReferenceId,
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
await this.syncInvoicePaymentSuccess({
|
|
484
|
+
subscriptionId,
|
|
485
|
+
throwOnMissing: true,
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
const subscriptionRecord = await this.subscriptionRepository.findByStripeId(subscriptionId);
|
|
489
|
+
|
|
490
|
+
const normalizedCurrency = this.normalizeSelectedCurrency(selectedCurrency);
|
|
491
|
+
if (normalizedCurrency && subscriptionRecord) {
|
|
492
|
+
try {
|
|
493
|
+
await this.organizationRepository.updateCurrency({
|
|
494
|
+
organizationId: subscriptionRecord.organizationId,
|
|
495
|
+
currency: normalizedCurrency,
|
|
496
|
+
});
|
|
497
|
+
} catch (err) {
|
|
498
|
+
logger.warn(
|
|
499
|
+
{ subscriptionId, selectedCurrency: normalizedCurrency, err },
|
|
500
|
+
"[stripeWebhook] Failed to persist selected currency on checkout completion",
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// Approve PAYMENT_PENDING invites linked to this subscription
|
|
506
|
+
if (this.inviteApprover && subscriptionRecord) {
|
|
507
|
+
try {
|
|
508
|
+
await this.inviteApprover.approvePaymentPendingInvites({
|
|
509
|
+
subscriptionId: subscriptionRecord.id,
|
|
510
|
+
organizationId: subscriptionRecord.organizationId,
|
|
511
|
+
});
|
|
512
|
+
} catch (err) {
|
|
513
|
+
logger.error(
|
|
514
|
+
{ subscriptionId, err },
|
|
515
|
+
"[stripeWebhook] Failed to approve PAYMENT_PENDING invites after checkout, manual resolution may be needed",
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// Cancel any active trial subscriptions for this org
|
|
521
|
+
if (subscriptionRecord) {
|
|
522
|
+
await this.subscriptionRepository.cancelTrialSubscriptions(
|
|
523
|
+
subscriptionRecord.organizationId,
|
|
524
|
+
);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
return { earlyReturn: false };
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
async handleInvoicePaymentSucceeded({
|
|
531
|
+
subscriptionId,
|
|
532
|
+
throwOnMissing,
|
|
533
|
+
}: {
|
|
534
|
+
subscriptionId: string;
|
|
535
|
+
throwOnMissing?: boolean;
|
|
536
|
+
}): Promise<void> {
|
|
537
|
+
await this.syncInvoicePaymentSuccess({ subscriptionId, throwOnMissing });
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
async handleInvoicePaymentFailed({
|
|
541
|
+
subscriptionId,
|
|
542
|
+
}: {
|
|
543
|
+
subscriptionId: string;
|
|
544
|
+
}): Promise<void> {
|
|
545
|
+
await waitForStripeConsistency();
|
|
546
|
+
|
|
547
|
+
const currentSubscription =
|
|
548
|
+
await this.subscriptionRepository.findByStripeId(subscriptionId);
|
|
549
|
+
|
|
550
|
+
if (!currentSubscription) {
|
|
551
|
+
logger.warn(
|
|
552
|
+
{ subscriptionId },
|
|
553
|
+
"[stripeWebhook] No subscription record for payment failure, skipping",
|
|
554
|
+
);
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
await this.subscriptionRepository.recordPaymentFailure({
|
|
559
|
+
id: currentSubscription.id,
|
|
560
|
+
currentStatus: currentSubscription.status,
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
async handleSubscriptionDeleted({
|
|
565
|
+
stripeSubscriptionId,
|
|
566
|
+
}: {
|
|
567
|
+
stripeSubscriptionId: string;
|
|
568
|
+
}): Promise<void> {
|
|
569
|
+
await waitForStripeConsistency();
|
|
570
|
+
|
|
571
|
+
const existingSubscription =
|
|
572
|
+
await this.subscriptionRepository.findByStripeId(stripeSubscriptionId);
|
|
573
|
+
|
|
574
|
+
if (!existingSubscription) {
|
|
575
|
+
logger.warn(
|
|
576
|
+
{ stripeSubscriptionId },
|
|
577
|
+
"[stripeWebhook] No subscription for deletion event, skipping",
|
|
578
|
+
);
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// Idempotency: if already CANCELLED (e.g., by upgrade flow), skip redundant update
|
|
583
|
+
if (existingSubscription.status === SubscriptionStatus.CANCELLED) {
|
|
584
|
+
logger.info(
|
|
585
|
+
{ stripeSubscriptionId },
|
|
586
|
+
"[stripeWebhook] Subscription already cancelled, skipping redundant update",
|
|
587
|
+
);
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
await this.subscriptionRepository.cancel({ id: existingSubscription.id });
|
|
592
|
+
|
|
593
|
+
// Send "Subscription cancelled" Slack notification
|
|
594
|
+
try {
|
|
595
|
+
const org = await this.organizationRepository.findNameById(
|
|
596
|
+
existingSubscription.organizationId,
|
|
597
|
+
);
|
|
598
|
+
await getApp().notifications.sendSlackSubscriptionEvent({
|
|
599
|
+
type: "cancelled",
|
|
600
|
+
organizationId: existingSubscription.organizationId,
|
|
601
|
+
organizationName: org?.name ?? "Unknown",
|
|
602
|
+
plan: existingSubscription.plan,
|
|
603
|
+
subscriptionId: existingSubscription.id,
|
|
604
|
+
cancellationDate: new Date(),
|
|
605
|
+
});
|
|
606
|
+
} catch (err) {
|
|
607
|
+
logger.error(
|
|
608
|
+
{ stripeSubscriptionId, err },
|
|
609
|
+
"[stripeWebhook] Failed to send cancellation notification",
|
|
610
|
+
);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
const remainingActive = await this.subscriptionRepository.findLastNonCancelled(
|
|
614
|
+
existingSubscription.organizationId,
|
|
615
|
+
);
|
|
616
|
+
fireSubscriptionSyncNurturing({
|
|
617
|
+
organizationId: existingSubscription.organizationId,
|
|
618
|
+
hasSubscription: !!remainingActive,
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
async handleSubscriptionUpdated({
|
|
623
|
+
subscription,
|
|
624
|
+
}: {
|
|
625
|
+
subscription: Stripe.Subscription;
|
|
626
|
+
}): Promise<void> {
|
|
627
|
+
await waitForStripeConsistency();
|
|
628
|
+
|
|
629
|
+
const existingSubForUpdate =
|
|
630
|
+
await this.subscriptionRepository.findByStripeId(subscription.id);
|
|
631
|
+
|
|
632
|
+
if (!existingSubForUpdate) {
|
|
633
|
+
logger.warn(
|
|
634
|
+
{ stripeSubscriptionId: subscription.id },
|
|
635
|
+
"[stripeWebhook] No subscription for update event, skipping",
|
|
636
|
+
);
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
if (
|
|
641
|
+
subscription.status !== "active" ||
|
|
642
|
+
subscription.ended_at
|
|
643
|
+
) {
|
|
644
|
+
// Truly cancelled or ended — mark as CANCELLED in DB.
|
|
645
|
+
// Note: canceled_at alone means "scheduled for cancellation at period end"
|
|
646
|
+
// — the sub is still active until then, so we don't cancel in DB yet.
|
|
647
|
+
// When the period ends, Stripe fires `customer.subscription.deleted`
|
|
648
|
+
// which is handled by handleSubscriptionDeleted.
|
|
649
|
+
await this.subscriptionRepository.cancel({ id: existingSubForUpdate.id });
|
|
650
|
+
|
|
651
|
+
const remainingActive = await this.subscriptionRepository.findLastNonCancelled(
|
|
652
|
+
existingSubForUpdate.organizationId,
|
|
653
|
+
);
|
|
654
|
+
fireSubscriptionSyncNurturing({
|
|
655
|
+
organizationId: existingSubForUpdate.organizationId,
|
|
656
|
+
hasSubscription: !!remainingActive,
|
|
657
|
+
});
|
|
658
|
+
} else if (subscription.status === "active") {
|
|
659
|
+
const shouldNotify =
|
|
660
|
+
existingSubForUpdate.status !== SubscriptionStatus.ACTIVE;
|
|
661
|
+
|
|
662
|
+
let tracesQuantity: number | null = null;
|
|
663
|
+
let usersQuantity: number | null = null;
|
|
664
|
+
|
|
665
|
+
for (const item of subscription.items.data) {
|
|
666
|
+
if (isGrowthSeatPrice(item.price.id)) {
|
|
667
|
+
usersQuantity = item.quantity ?? 0;
|
|
668
|
+
} else if (isGrowthEventsPrice(item.price.id)) {
|
|
669
|
+
// Events price exists on the subscription; traces limit comes from plan limits
|
|
670
|
+
} else if (
|
|
671
|
+
item.price.id === this.itemCalculator.prices.LAUNCH_USERS ||
|
|
672
|
+
item.price.id === this.itemCalculator.prices.ACCELERATE_USERS ||
|
|
673
|
+
item.price.id === this.itemCalculator.prices.LAUNCH_ANNUAL_USERS ||
|
|
674
|
+
item.price.id ===
|
|
675
|
+
this.itemCalculator.prices.ACCELERATE_ANNUAL_USERS
|
|
676
|
+
) {
|
|
677
|
+
const calculateQuantity =
|
|
678
|
+
this.itemCalculator.calculateQuantityForPrice({
|
|
679
|
+
priceId: item.price.id,
|
|
680
|
+
quantity: item.quantity ?? 0,
|
|
681
|
+
plan: existingSubForUpdate.plan,
|
|
682
|
+
});
|
|
683
|
+
usersQuantity = calculateQuantity;
|
|
684
|
+
} else if (
|
|
685
|
+
item.price.id ===
|
|
686
|
+
this.itemCalculator.prices.ACCELERATE_TRACES_100K ||
|
|
687
|
+
item.price.id === this.itemCalculator.prices.LAUNCH_TRACES_10K ||
|
|
688
|
+
item.price.id ===
|
|
689
|
+
this.itemCalculator.prices.LAUNCH_ANNUAL_TRACES_10K ||
|
|
690
|
+
item.price.id ===
|
|
691
|
+
this.itemCalculator.prices.ACCELERATE_ANNUAL_TRACES_100K
|
|
692
|
+
) {
|
|
693
|
+
const calculateQuantity =
|
|
694
|
+
this.itemCalculator.calculateQuantityForPrice({
|
|
695
|
+
priceId: item.price.id,
|
|
696
|
+
quantity: item.quantity ?? 0,
|
|
697
|
+
plan: existingSubForUpdate.plan,
|
|
698
|
+
});
|
|
699
|
+
tracesQuantity = calculateQuantity;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const updatedSubscription = await this.subscriptionRepository.updateQuantities({
|
|
704
|
+
id: existingSubForUpdate.id,
|
|
705
|
+
maxMembers: usersQuantity,
|
|
706
|
+
maxMessagesPerMonth: tracesQuantity,
|
|
707
|
+
});
|
|
708
|
+
|
|
709
|
+
if (!updatedSubscription) {
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
await this.clearTrialLicenseIfPresent(updatedSubscription, "subscription updated to active");
|
|
714
|
+
|
|
715
|
+
if (shouldNotify) {
|
|
716
|
+
await getApp().notifications.sendSlackSubscriptionEvent({
|
|
717
|
+
type: "confirmed",
|
|
718
|
+
organizationId: updatedSubscription.organizationId,
|
|
719
|
+
organizationName: updatedSubscription.organization.name,
|
|
720
|
+
plan: updatedSubscription.plan,
|
|
721
|
+
subscriptionId: updatedSubscription.id,
|
|
722
|
+
startDate: updatedSubscription.startDate,
|
|
723
|
+
maxMembers: updatedSubscription.maxMembers,
|
|
724
|
+
maxMessagesPerMonth: updatedSubscription.maxMessagesPerMonth,
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
// --- Private helpers ---
|
|
731
|
+
|
|
732
|
+
private async syncInvoicePaymentSuccess({
|
|
733
|
+
subscriptionId,
|
|
734
|
+
throwOnMissing = false,
|
|
735
|
+
}: {
|
|
736
|
+
subscriptionId: string;
|
|
737
|
+
throwOnMissing?: boolean;
|
|
738
|
+
}) {
|
|
739
|
+
await waitForStripeConsistency();
|
|
740
|
+
|
|
741
|
+
const previousSubscription =
|
|
742
|
+
await this.subscriptionRepository.findByStripeId(subscriptionId);
|
|
743
|
+
|
|
744
|
+
if (!previousSubscription) {
|
|
745
|
+
if (throwOnMissing) {
|
|
746
|
+
throw new SubscriptionRecordNotFoundError(subscriptionId);
|
|
747
|
+
}
|
|
748
|
+
logger.warn(
|
|
749
|
+
{ subscriptionId },
|
|
750
|
+
"[stripeWebhook] No subscription record found, skipping sync",
|
|
751
|
+
);
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// Guard: a $0 invoice generated during cancellation must not reactivate the subscription.
|
|
756
|
+
// Stripe fires invoice.payment_succeeded for $0 prorated invoices even when the subscription
|
|
757
|
+
// is being cancelled. Check the authoritative Stripe status before activating.
|
|
758
|
+
let stripeCanceled = false;
|
|
759
|
+
try {
|
|
760
|
+
const stripeSubscription =
|
|
761
|
+
await this.stripe.subscriptions.retrieve(subscriptionId);
|
|
762
|
+
stripeCanceled = stripeSubscription.status === "canceled";
|
|
763
|
+
} catch (err) {
|
|
764
|
+
logger.warn(
|
|
765
|
+
{ subscriptionId, err },
|
|
766
|
+
"[stripeWebhook] Failed to verify Stripe subscription status, proceeding with activation",
|
|
767
|
+
);
|
|
768
|
+
if (previousSubscription.status === SubscriptionStatus.CANCELLED) {
|
|
769
|
+
logger.info(
|
|
770
|
+
{ subscriptionId },
|
|
771
|
+
"[stripeWebhook] Stripe status unavailable and DB is CANCELLED, skipping activation",
|
|
772
|
+
);
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
if (stripeCanceled) {
|
|
778
|
+
logger.info(
|
|
779
|
+
{ subscriptionId },
|
|
780
|
+
"[stripeWebhook] Stripe subscription is canceled, skipping activation from $0 invoice",
|
|
781
|
+
);
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
const updatedSubscription = await this.subscriptionRepository.activate({
|
|
786
|
+
id: previousSubscription.id,
|
|
787
|
+
previousStatus: previousSubscription.status,
|
|
788
|
+
});
|
|
789
|
+
|
|
790
|
+
if (!updatedSubscription) {
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
if (previousSubscription.status !== SubscriptionStatus.ACTIVE) {
|
|
795
|
+
await this.clearTrialLicenseIfPresent(updatedSubscription, "subscription activated");
|
|
796
|
+
|
|
797
|
+
if (isGrowthSeatEventPlan(updatedSubscription.plan)) {
|
|
798
|
+
const oldSubscriptions = await this.subscriptionRepository.migrateToSeatEvent({
|
|
799
|
+
organizationId: updatedSubscription.organizationId,
|
|
800
|
+
excludeSubscriptionId: updatedSubscription.id,
|
|
801
|
+
});
|
|
802
|
+
|
|
803
|
+
// Cancel in Stripe after DB is consistent (outside transaction)
|
|
804
|
+
for (const oldSub of oldSubscriptions) {
|
|
805
|
+
if (oldSub.stripeSubscriptionId) {
|
|
806
|
+
try {
|
|
807
|
+
await this.stripe.subscriptions.cancel(oldSub.stripeSubscriptionId, {
|
|
808
|
+
prorate: true,
|
|
809
|
+
});
|
|
810
|
+
} catch (err) {
|
|
811
|
+
logger.error(
|
|
812
|
+
{ stripeSubscriptionId: oldSub.stripeSubscriptionId, err },
|
|
813
|
+
"[stripeWebhook] CRITICAL: Failed to cancel old Stripe subscription during upgrade. Manual intervention required.",
|
|
814
|
+
);
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
await getApp().notifications.sendSlackSubscriptionEvent({
|
|
821
|
+
type: "confirmed",
|
|
822
|
+
organizationId: updatedSubscription.organizationId,
|
|
823
|
+
organizationName: updatedSubscription.organization.name,
|
|
824
|
+
plan: updatedSubscription.plan,
|
|
825
|
+
subscriptionId: updatedSubscription.id,
|
|
826
|
+
startDate: updatedSubscription.startDate,
|
|
827
|
+
maxMembers: updatedSubscription.maxMembers,
|
|
828
|
+
maxMessagesPerMonth: updatedSubscription.maxMessagesPerMonth,
|
|
829
|
+
});
|
|
830
|
+
|
|
831
|
+
fireSubscriptionSyncNurturing({
|
|
832
|
+
organizationId: updatedSubscription.organizationId,
|
|
833
|
+
hasSubscription: true,
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
private async clearTrialLicenseIfPresent(
|
|
839
|
+
updatedSubscription: SubscriptionWithOrg,
|
|
840
|
+
reason: string,
|
|
841
|
+
) {
|
|
842
|
+
if (!updatedSubscription.organization.license) return;
|
|
843
|
+
logger.info(
|
|
844
|
+
{ organizationId: updatedSubscription.organizationId },
|
|
845
|
+
`[stripeWebhook] Clearing trial license — ${reason}`,
|
|
846
|
+
);
|
|
847
|
+
await this.organizationRepository.clearTrialLicense(
|
|
848
|
+
updatedSubscription.organizationId,
|
|
849
|
+
);
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
private normalizeSelectedCurrency(value?: string | null): Currency | null {
|
|
853
|
+
if (value === Currency.EUR || value === Currency.USD) {
|
|
854
|
+
return value;
|
|
855
|
+
}
|
|
856
|
+
return null;
|
|
857
|
+
}
|
|
858
|
+
}
|