:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): let customers request a higher email sending tier (#122222)
Luke Beltondded985c5117
diff --git a/docs/internal/workflows-email-sending-tiers.md b/docs/internal/workflows-email-sending-tiers.mdindex 73e358d91950..03ea64a7289d 100644--- a/docs/internal/workflows-email-sending-tiers.md+++ b/docs/internal/workflows-email-sending-tiers.md@@ -14,6 +14,10 @@ Only workflows that send email are subject to the tiers; SMS, push, and webhook- Staff controls: the team's Django admin page (view state, set/pin a tier, recompute now).- Audit trail: every tier or pin change writes an `email_sending_tier_changed` row to the team's activity log, with the before and after values and the decision reason (`staff_set` for a tier staff set by hand). Staff rows name the acting user. Sweep and backfill rows carry a trigger with the job type and a per-run id. The rows are staff-only in the activity log (`products/workflows/backend/services/email_sending_tier_audit.py`).- Customer surface: the Reputation tab's sending allowance card, shown only while the team is enforced.+- Raise requests: the card's "Request a higher allowance" link opens a support ticket whose hidden context starts with `Email sending tier increase request`, followed by the project ID, tier, usage, and 30-day rates.+ Search tickets for that line to find these requests.+ The `workflows-sending-tier-requests` feature flag gates the link.+ The link shows only to accounts that can file a support ticket: a paid or custom plan, an active support trial, or an organization in its first 3 months.## Configurationdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2d2585c07dcb..018b57363256 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8533,25 +8533,25 @@ snapshots:products-workflows-editor-tree--support-sla-routing--light:hash: v1.k794b7964.1990086cf1765af4b068774f55ecf7532c624ebfbb9254ed705a5fad862b939f.RrB4yXhFhYTE3dCOFGhPMc99b7c97wHdADkxHmAhw90products-workflows-reputation--domain-withheld-from-caller--dark:- hash: v1.k794b7964.c2e39d5fe9b32f1b638e90e39ce2cce629ade26846acc2d2530fa8c89986d4ec.un8cpP-nRmKMMaLVxSAP7vc-2PZ1zELYwqHEgXQ33L8+ hash: v1.k794b7964.4c8ae4bd60867d552c0b0499308c93dbb6a9e6da74929a97ddbedd39f992599b.bwSgpaQEan0zikdVKGPrgdoZQY5PMjSXnsfOVCyrrVcproducts-workflows-reputation--domain-withheld-from-caller--light:- hash: v1.k794b7964.2a42eb93e07102fdaa2be66c61d24ec24d3824584a7fd8282086f5951be7cd60.1ZnyCHFAjY3SrKADM8oOrlMPLkBx7A3uERarZ6QX9JU+ hash: v1.k794b7964.147be54ef11f884bd92df02007bd66822377032ba8071d828df3f94cf7a99f84.k0-DsLWiwxjImrUNIp6nmGzckC9i8zgG5syjjW6BmUgproducts-workflows-reputation--no-provider-data--dark:- hash: v1.k794b7964.d5868f04ec995d95b42c5da29d86be9fe0180177c928c3aca9b178bb2b708dad.KEMPcrEoivqZ9ih7hmlXKz_OGmpe4SrDoi9B1wiMVms+ hash: v1.k794b7964.5b437cfe30305fcb667b209851f1356a4cc10702438516128c4884809094a31c.SlR1rH9HLvxf1-vLydVP3VX55FWrTQaTsOERMs6J6Acproducts-workflows-reputation--no-provider-data--light:- hash: v1.k794b7964.6b6d7a5158358a4110345590bd8d6f3b8be4b82a4126b14d3e7099850d068860.__4p80UwBytU6XA20QHzeFY876nKh8iLH_V3MUyOjMw+ hash: v1.k794b7964.1d1e5429cc3922b93b9452c8d0204fd2f4f8b776f806a0f4b7f1cd40baf73ae7.sbnZcNLID6RiaQvAvEgFsse3O7oDWAD785JScfbnZBIproducts-workflows-reputation--one-provider-filtering--dark:- hash: v1.k794b7964.33708acd8756fdd8a94edb5fbc42fec36c0e3b80fea591f7c921989c2b9b1d3d.Jr3pkLgeWS_NzZGXi_S5jbtgZf6fCWCFFqQTPwk812M+ hash: v1.k794b7964.c903e5bcfbad8781cc5dd80b7818e413ed9b11e69d8186502221199d1a1dfae0.LYWxf9d9Xjg5HZlNKrdOrt1sXMwtbecPpVzNhJOuWiEproducts-workflows-reputation--one-provider-filtering--light:- hash: v1.k794b7964.a5fc256d47dd4b41c414dff7e52bd662ed291e83dad328b4d60a03c4d8116325.weiQmgMwlgNFnsFBxyzt1PVo6uIVmBIcHpJYGyiUxJ0+ hash: v1.k794b7964.f5d9f9e0c0117059d3362bfc84a42e10076f27585acf75aeeafc2d000e62e028.V2RMl0YHbLFf654ctsE8yLgeCoRMPOXM_pPlideqrioproducts-workflows-reputation--provider-data-without-workflow-rates--dark:- hash: v1.k794b7964.307e7b4c2f84ce71b05b3b8f43dd85df28bda0f502c273dbd44f5beb9ad1d97e.qv6hpPIEVH6U-pcYaYXYt2bIKb0J9AceIgTS2ut66yQ+ hash: v1.k794b7964.9f3f4aa8a8dbc982d909a6570ed3247f7b9cf541dc7de06af7001bdb7d03d8bc.S9PFsharMlX3fTlNYtcVJXaH-_kuiPglS-CEcsJJDHYproducts-workflows-reputation--provider-data-without-workflow-rates--light:- hash: v1.k794b7964.09b8db29359499827a5ee3a6cd0b533eb9fb403a07349d6be22ab4148ee91bee.9ZFcUpOKTNhLNb1OesXvLQMOFEjnWiLDiN6dvtVzRWU+ hash: v1.k794b7964.b93a6572a6999592d2daef92c38b576457067ac50f9a5419b3bc080e676668fa.3dfOSKmnjzpqrCoPFuFEh_6bXkrktysPL7_cnF7gKvsproducts-workflows-reputation--shared-sending-domain--dark:- hash: v1.k794b7964.5cf1b5557a39a1c56f57778a8f93fae97a2369d6a0d9debeaf9a32888867e76f.YVfscq34vkHHNa-V3zETBCtGV5g2HUXGoUCZTtdwwTg+ hash: v1.k794b7964.cdce03b8be8c4ffeef15eb0a6bcab206c7eb5b1cd8b8852b1aca0de497732226.6biyQXJiwnyQcZZtOgCOVH3hpDAfJp6K_L06WtP_aW8products-workflows-reputation--shared-sending-domain--light:- hash: v1.k794b7964.d2f19057ecd63916468e49499852f4b90854405ad3d4f8bbb04e766a6180a0bf.SIZeFe7wNudMSeL2euN2W8tSq5ATz9vp6KGnFbgeUmw+ hash: v1.k794b7964.e029f36f5a4cf022e888be7cfa04b7ef2741414b6205173b0d879b037b3663df.FJeja9fI99Dhe5aX-g4hQp6P3oGBNjviDjw14YhV0cYproducts-workflows-send-calendar--busy-week--dark:hash: v1.k794b7964.1edf0999ab5e390b86d0a8d48ab5821c5cb291b35eba58eb4000587652ba79af.4plcEAYl06VvPXCtAKWYvMcbQLWV-U1_khdj3SHu5Hoproducts-workflows-send-calendar--busy-week--light:diff --git a/frontend/src/lib/components/Support/supportLogic.test.ts b/frontend/src/lib/components/Support/supportLogic.test.tsindex 05c6e28372ec..10c7651ec7f5 100644--- a/frontend/src/lib/components/Support/supportLogic.test.ts+++ b/frontend/src/lib/components/Support/supportLogic.test.ts@@ -183,17 +183,21 @@ describe('supportLogic', () => {expect(logic.values.lastSubmittedTicketId).toBe('t1')})- it('appends exception context to the message so it survives on the ticket', async () => {+ it.each([+ ['exception', { exception_event: { uuid: 'exc-1', event: '$exception' } }, 'Exception:'],+ [+ 'ticket',+ { ticket_context: 'Email sending tier increase request' },+ 'Email sending tier increase request',+ ],+ ])('appends %s context to the message so it survives on the ticket', async (_name, extra, expected) => {const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })conversationsMock(sendMessage)- await logic.asyncActions.submitSupportTicket({- ...FORM_FIELDS,- exception_event: { uuid: 'exc-1', event: '$exception' },- })+ await logic.asyncActions.submitSupportTicket({ ...FORM_FIELDS, ...extra })expect(sendMessage.mock.calls[0][0]).toContain('Help!')- expect(sendMessage.mock.calls[0][0]).toContain('Exception:')+ expect(sendMessage.mock.calls[0][0]).toContain(expected)})it('accepts a submission with no topic or severity, since the form no longer collects them', async () => {diff --git a/frontend/src/lib/components/Support/supportLogic.ts b/frontend/src/lib/components/Support/supportLogic.tsindex af45b34b1e30..c04bef01c647 100644--- a/frontend/src/lib/components/Support/supportLogic.ts+++ b/frontend/src/lib/components/Support/supportLogic.ts@@ -187,6 +187,14 @@ export function appendExceptionToMessage(message: string, exception_event?: Suppreturn message ? `${message}\n\n-----\n${exception}` : exception}+// Kept out of the editable draft and appended on send, so the customer can't edit it away+export function appendTicketContext(message: string, ticket_context?: string | null): string {+ if (!ticket_context) {+ return message+ }+ return message ? `${message}\n\n-----\n${ticket_context}` : ticket_context+}+export const SUPPORT_KIND_TO_SUBJECT = {bug: 'Bug Report',feedback: 'Feedback',@@ -221,6 +229,7 @@ export type SupportFormFields = {*/billing_issue?: booleanexception_event?: SupportTicketExceptionEvent+ ticket_context?: stringisEmailFormOpen?: boolean | 'true' | 'false'// Set when the ticket originates from a PostHog AI (/ticket, feedback) handover, so the created// ticket can be attributed back to the conversation regardless of which submit path files it.@@ -475,6 +484,7 @@ export const supportLogic = kea<supportLogicType>([kind,message,exception_event,+ ticket_context,billing_issue,target,ai_conversation_id,@@ -488,6 +498,7 @@ export const supportLogic = kea<supportLogicType>([kind,message: message ?? values.sendSupportRequest.message ?? '',exception_event,+ ticket_context,billing_issue: billing_issue ?? false,// Carried through so a PostHog AI handover still attributes the ticket it files.ai_conversation_id,@@ -511,7 +522,7 @@ export const supportLogic = kea<supportLogicType>([actions.updateUrlParams()},submitSupportTicket: async (formValues: SupportFormFields) => {- const { name, kind, message, exception_event } = formValues+ const { name, kind, message, exception_event, ticket_context } = formValues// Trimmed before validating and sending: restore-by-email matches the stored trait// exactly, so stray whitespace would make the ticket unrecoverableconst email = formValues.email.trim()@@ -564,9 +575,12 @@ export const supportLogic = kea<supportLogicType>([return}- // Measure the full outgoing payload (message plus any appended exception) so the guard+ // Measure the full outgoing payload (message plus any appended exception and ticket context) so the guard// matches what the widget endpoint actually receives and rejects- const outgoingMessage = appendExceptionToMessage(message, exception_event)+ const outgoingMessage = appendTicketContext(+ appendExceptionToMessage(message, exception_event),+ ticket_context+ )if (warnIfMessageTooLong(outgoingMessage)) {captureSupportTicketBlocked({surface: 'support_form',diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 4977094a2398..202f5bc17fc1 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -622,6 +622,7 @@ export const FEATURE_FLAGS = {WORKFLOWS_INTERNAL_EVENT_FILTERS: 'workflows-internal-event-filters', // owner: @haven #team-workflowsWORKFLOWS_LINEAR_VIEW: 'workflows-linear-view', // owner: #team-workflowsWORKFLOWS_PUSH_NOTIFICATIONS: 'workflows-push-notifications', // owner: #team-workflows+ WORKFLOWS_SENDING_TIER_REQUESTS: 'workflows-sending-tier-requests', // owner: @luke-belton #team-workflows, lets customers request a higher email sending tierWORKFLOWS_TILE_CANVAS: 'workflows-tile-canvas', // owner: #team-workflowsWORKFLOWS_TRANSACTIONAL_EMAIL_API: 'workflows-transactional-email-api', // owner: @mayteio #team-workflowsXAA_AUTHENTICATION: 'xaa-authentication', // owner: @reecejones #team-platform-featuresdiff --git a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.tsindex 67e7859cd262..d00a98272d7b 100644--- a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts+++ b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.test.ts@@ -70,6 +70,7 @@ describe('sidepanelTicketsLogic', () => {kind: 'bug',isEmailFormOpen: true,message: 'It broke',+ ticket_context: 'Project ID: 997',target: 'sidePanel',})@@ -81,9 +82,19 @@ describe('sidepanelTicketsLogic', () => {expect(JSON.stringify(logic.values.newTicketDraft)).toContain('It broke')expect(supportLogic.values.isEmailFormOpen).toBe(false)+ await expectLogic(logic, () => {+ logic.actions.sendMessage('It broke badly', jest.fn())+ }).toFinishAllListeners()+ expect((posthog as any).conversations.sendMessage).toHaveBeenCalledWith(+ 'It broke badly\n\n-----\nProject ID: 997',+ {},+ true+ )+// Leaving the composer clears the prefill so a later blank "New ticket" starts emptylogic.actions.setView('list')expect(logic.values.newTicketDraft).toBeNull()+ expect(logic.values.newTicketContext).toBeNull()})it('switches to the composer when the support form opens while already mounted', async () => {diff --git a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.tsindex 83d56c31d800..809e7452f15f 100644--- a/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts+++ b/products/conversations/frontend/components/SidePanel/sidepanelTicketsLogic.ts@@ -17,6 +17,7 @@ import posthog from 'posthog-js'import {appendExceptionToMessage,+ appendTicketContext,captureSupportTicketBlocked,captureSupportWidgetLoadFailed,SUPPORT_WIDGET_UNAVAILABLE_MESSAGE,@@ -126,6 +127,7 @@ export interface sidepanelTicketsLogicValues {messageSending: booleanmessages: ChatMessage[]messagesLoading: boolean+ newTicketContext: string | nullnewTicketDraft: JSONContent | nullnewTicketDraftRevision: numberpendingTicketId: string | null@@ -208,6 +210,9 @@ export interface sidepanelTicketsLogicActions {setMessagesLoading: (loading: boolean) => {loading: boolean}+ setNewTicketContext: (context: string | null) => {+ context: string | null+ }setNewTicketDraft: (content: JSONContent | null) => {content: JSONContent | null}@@ -315,6 +320,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([setView: (view: SidePanelViewState) => ({ view }),setCurrentTicket: (ticket: ConversationTicket) => ({ ticket }),setNewTicketDraft: (content: JSONContent | null) => ({ content }),+ setNewTicketContext: (context: string | null) => ({ context }),startTicketFromSupportForm: true,openPendingTicket: true,sendMessage: (content: string, onSuccess: () => void) => ({ content, onSuccess }),@@ -379,6 +385,14 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([setView: (state, { view }) => (view === 'new' ? state : null),},],+ // Cleared with the draft, so a later blank "New ticket" doesn't carry it+ newTicketContext: [+ null as string | null,+ {+ setNewTicketContext: (_, { context }) => context,+ setView: (state, { view }) => (view === 'new' ? state : null),+ },+ ],// Bumped only when a draft is injected via setNewTicketDraft (a prefilled CTA), so NewTicket// remounts to pick up the seeded content. Plain typing never calls this, so it doesn't remount.newTicketDraftRevision: [@@ -739,10 +753,11 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([actions.setMessagesLoading(false)}},- sendMessage: async ({ content, onSuccess }) => {- if (!content.trim() || values.messageSending) {+ sendMessage: async ({ content: typed, onSuccess }) => {+ if (!typed.trim() || values.messageSending) {return}+ const content = values.view === 'new' ? appendTicketContext(typed, values.newTicketContext) : typed// Bailing quietly here left the button un-loaded and the typed message sitting in the box// with no explanation, which is the worst version of this now conversations is the only channelif (!posthog.conversations) {@@ -912,6 +927,7 @@ export const sidepanelTicketsLogic = kea<sidepanelTicketsLogicType>([if (draft) {actions.setNewTicketDraft(messageToRichContent(draft))}+ actions.setNewTicketContext(request?.ticket_context || null)actions.setView('new')// Consume the support-form intent fully (or supportRouterLogic keeps treating the form as// open and ignores future URL-driven opens), and reset so a stale message can't resurfacediff --git a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.stories.tsx b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.stories.tsxindex 67be9eb0521c..f21b073f9315 100644--- a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.stories.tsx+++ b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.stories.tsx@@ -1,5 +1,7 @@import { Meta, StoryFn } from '@storybook/react'+import { FEATURE_FLAGS } from 'lib/constants'+import { useStorybookMocks } from '~/mocks/browser'import type { TeamEmailReputationResponseApi } from 'products/workflows/frontend/generated/api.schemas'@@ -112,6 +114,7 @@ const meta: Meta<typeof WorkflowsReputation> = {parameters: {layout: 'padded',testOptions: { waitForLoadersToDisappear: true },+ featureFlags: [FEATURE_FLAGS.WORKFLOWS_SENDING_TIER_REQUESTS],},}export default metadiff --git a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsxindex 7634cf5c4e0b..2ccee0be4504 100644--- a/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx+++ b/products/workflows/frontend/Workflows/Reputation/WorkflowsReputation.tsx@@ -375,6 +375,8 @@ function TeamRatesCard({}function SendingAllowanceCard({ allowance }: { allowance: EmailSendingAllowanceApi }): JSX.Element {+ const { canRequestSendingTierIncrease } = useValues(workflowsReputationLogic)+ const { requestSendingTierIncrease } = useActions(workflowsReputationLogic)const hourlyPercent = Math.min(100, (allowance.emails_sent_last_hour / allowance.emails_per_hour) * 100)const dailyPercent = Math.min(100, (allowance.emails_sent_last_day / allowance.emails_per_day) * 100)return (@@ -390,6 +392,18 @@ function SendingAllowanceCard({ allowance }: { allowance: EmailSendingAllowanceA<p className="text-secondary mt-2 mb-0">Your allowance grows as your workflows keep sending with low bounce and spam complaint rates. Emailsabove the allowance are not dropped, they are sent later.+ {canRequestSendingTierIncrease && (+ <>+ {' '}+ Need more sooner?{' '}+ <Link+ onClick={() => requestSendingTierIncrease(allowance)}+ data-attr="workflows-request-sending-tier-increase"+ >+ Request a higher allowance+ </Link>+ </>+ )}</p><div className="flex flex-wrap gap-8 mt-3"><div className="min-w-48">diff --git a/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.test.ts b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.test.tsnew file mode 100644index 000000000000..2cf68f9247e4--- /dev/null+++ b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.test.ts@@ -0,0 +1,58 @@+import { expectLogic } from 'kea-test-utils'++import { supportLogic } from 'lib/components/Support/supportLogic'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { billingLogic } from 'scenes/billing/billingLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import type { BillingType } from '~/types'++import type { EmailSendingAllowanceApi } from 'products/workflows/frontend/generated/api.schemas'++import { workflowsReputationLogic } from './workflowsReputationLogic'++const allowance: EmailSendingAllowanceApi = {+ tier: 2,+ max_tier: 4,+ emails_per_hour: 5000,+ emails_per_day: 50000,+ max_batch_audience: 25000,+ emails_sent_last_hour: 1200,+ emails_sent_last_day: 18400,+ enforced: true,+}++describe('workflowsReputationLogic', () => {+ beforeEach(() => {+ useMocks({ get: { '/api/projects/:team_id/hog_flows/reputation': { workflows: [], isps: [] } } })+ initKeaTests()+ })++ it.each([+ ['shows the request on a paid plan with the flag on', true, true],+ ['hides the request when the flag is off', false, false],+ ])('%s', async (_name, flagOn, expected) => {+ const logic = workflowsReputationLogic()+ logic.mount()+ billingLogic.actions.loadBillingSuccess({ subscription_level: 'paid' } as BillingType)+ const flag = FEATURE_FLAGS.WORKFLOWS_SENDING_TIER_REQUESTS+ featureFlagLogic.actions.setFeatureFlags(flagOn ? [flag] : [], { [flag]: flagOn })++ expect(logic.values.canRequestSendingTierIncrease).toBe(expected)+ })++ it('opens the support composer with the tier request details attached', async () => {+ const logic = workflowsReputationLogic()+ logic.mount()++ await expectLogic(logic, () => logic.actions.requestSendingTierIncrease(allowance)).toFinishAllListeners()++ expect(supportLogic.values.isEmailFormOpen).toBe(true)+ expect(supportLogic.values.sendSupportRequest).toMatchObject({ kind: 'support' })+ const context = supportLogic.values.sendSupportRequest.ticket_context ?? ''+ expect(context.split('\n')[0]).toBe('Email sending tier increase request')+ expect(context).toContain('Current tier: 2 of 4')+ })+})diff --git a/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.tsindex 31fae1f7b253..220ac4006c28 100644--- a/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts+++ b/products/workflows/frontend/Workflows/Reputation/workflowsReputationLogic.ts@@ -1,8 +1,18 @@import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'+import { type SupportFormFields, supportLogic } from 'lib/components/Support/supportLogic'+import { FEATURE_FLAGS } from 'lib/constants'+import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'+import { billingLogic } from 'scenes/billing/billingLogic'+import { canCreateSupportTicket } from 'scenes/max/ticketUtils'+import { organizationLogic } from 'scenes/organizationLogic'import { projectLogic } from 'scenes/projectLogic'+import type { BillingType } from '~/types'+import { hogFlowsReputationRetrieve } from 'products/workflows/frontend/generated/api'import type {AwsTenantReputationApi,@@ -13,10 +23,46 @@ import type {WorkflowEmailSendingRatesApi,} from 'products/workflows/frontend/generated/api.schemas'+// The first line of every tier increase ticket. Support searches tickets on this exact text, so keep it stable.+const SENDING_TIER_INCREASE_TICKET_MARKER = 'Email sending tier increase request'++const SENDING_TIER_INCREASE_PROMPT = [+ 'How many emails do you need to send per day?',+ '',+ '',+ "What supports the increase? For example, if you're moving from another email provider, tell us which one, roughly how many emails you sent there each month, and your bounce and spam complaint rates there.",+ '',+ "If you're able to, please upload screenshots of any supporting evidence.",+].join('\n')++function sendingTierIncreaseContext(+ projectId: number | null,+ allowance: EmailSendingAllowanceApi,+ rates: EmailSendingRatesApi | null+): string {+ return [+ SENDING_TIER_INCREASE_TICKET_MARKER,+ `Project ID: ${projectId ?? 'unknown'}`,+ `Current tier: ${allowance.tier} of ${allowance.max_tier}`,+ `Emails today: ${humanFriendlyNumber(allowance.emails_sent_last_day)} of ${humanFriendlyNumber(allowance.emails_per_day)}`,+ `Emails this hour: ${humanFriendlyNumber(allowance.emails_sent_last_hour)} of ${humanFriendlyNumber(allowance.emails_per_hour)}`,+ ...(rates+ ? [+ `Bounce rate (last 30 days): ${percentage(rates.bounce_rate, 2, true)}`,+ `Spam complaint rate (last 30 days): ${percentage(rates.complaint_rate, 2, true)}`,+ ]+ : []),+ ].join('\n')+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowsReputationLogicValues {+ billing: BillingType | null // billingLogic+ featureFlags: FeatureFlagsSet // featureFlagLogic+ isCurrentOrganizationNew: boolean // organizationLogiccurrentProjectId: number | null // projectLogicawsReputation: AwsTenantReputationApi | null+ canRequestSendingTierIncrease: booleanispSendingHealth: readonly IspSendingHealthApi[]ispSharedDomains: readonly string[]ispWithheldDomains: readonly string[]@@ -30,6 +76,13 @@ export interface workflowsReputationLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowsReputationLogicActions {+ openSupportForm: (+ values: Partial<SupportFormFields> & {+ target?: 'modal' | 'sidePanel'+ }+ ) => Partial<SupportFormFields> & {+ target?: 'modal' | 'sidePanel' | undefined+ } // supportLogicloadReputation: () => {value: true}@@ -51,6 +104,9 @@ export interface workflowsReputationLogicActions {value: true}}+ requestSendingTierIncrease: (allowance: EmailSendingAllowanceApi) => {+ allowance: EmailSendingAllowanceApi+ }setSearch: (search: string) => {search: string}@@ -59,6 +115,11 @@ export interface workflowsReputationLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface workflowsReputationLogicMeta {__keaTypeGenInternalSelectorTypes: {+ canRequestSendingTierIncrease: (+ featureFlags: FeatureFlagsSet,+ billing: BillingType | null,+ isCurrentOrganizationNew: boolean+ ) => booleanawsReputation: (reputationResponse: TeamEmailReputationResponseApi | null) => AwsTenantReputationApi | nullsendingAllowance: (reputationResponse: TeamEmailReputationResponseApi | null) => EmailSendingAllowanceApi | nullteamReputation: (reputationResponse: TeamEmailReputationResponseApi | null) => EmailSendingRatesApi | null@@ -81,13 +142,24 @@ export type workflowsReputationLogicType = MakeLogicType<export const workflowsReputationLogic = kea<workflowsReputationLogicType>([path(['products', 'workflows', 'frontend', 'Workflows', 'Reputation', 'workflowsReputationLogic']),connect(() => ({- values: [projectLogic, ['currentProjectId']],+ values: [+ featureFlagLogic,+ ['featureFlags'],+ billingLogic,+ ['billing'],+ organizationLogic,+ ['isCurrentOrganizationNew'],+ projectLogic,+ ['currentProjectId'],+ ],+ actions: [supportLogic, ['openSupportForm']],})),actions({// Declared here (as well as auto-created by the loader) so kea-typegen sees a payload-less// action; without this, TS types the first loader arg as required and callers fail typecheck.loadReputation: true,setSearch: (search: string) => ({ search }),+ requestSendingTierIncrease: (allowance: EmailSendingAllowanceApi) => ({ allowance }),}),reducers({search: [@@ -116,15 +188,37 @@ export const workflowsReputationLogic = kea<workflowsReputationLogicType>([},],})),- listeners(({ actions }) => ({+ listeners(({ actions, values }) => ({// Search filters server-side (the response is capped to the worst 50 workflows), so each// keystroke needs a reload — debounced via the loader's own breakpoint on rapid typing.setSearch: async (_, breakpoint) => {await breakpoint(250)actions.loadReputation()},+ requestSendingTierIncrease: ({ allowance }) => {+ posthog.capture('email sending tier increase requested', {+ tier: allowance.tier,+ max_tier: allowance.max_tier,+ emails_sent_last_day: allowance.emails_sent_last_day,+ emails_per_day: allowance.emails_per_day,+ })+ // Without isEmailFormOpen the support side panel shows the ticket list and drops the draft+ actions.openSupportForm({+ kind: 'support',+ isEmailFormOpen: true,+ message: SENDING_TIER_INCREASE_PROMPT,+ ticket_context: sendingTierIncreaseContext(values.currentProjectId, allowance, values.teamReputation),+ })+ },})),selectors({+ // A free plan past its first 3 months would not get a higher tier, so it is not invited to ask+ canRequestSendingTierIncrease: [+ (s) => [s.featureFlags, s.billing, s.isCurrentOrganizationNew],+ (featureFlags: FeatureFlagsSet, billing: BillingType | null, isCurrentOrganizationNew: boolean): boolean =>+ !!featureFlags[FEATURE_FLAGS.WORKFLOWS_SENDING_TIER_REQUESTS] &&+ canCreateSupportTicket(billing, isCurrentOrganizationNew),+ ],awsReputation: [(s) => [s.reputationResponse],(response: TeamEmailReputationResponseApi | null): AwsTenantReputationApi | null => response?.aws ?? null,