diff --git a/cmd/backend/main.go b/cmd/backend/main.go index 20ccea198..baa9d1a7b 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -884,7 +884,7 @@ func main() { // Initialize new services for trial, feature gates, and worker assignment. // The trial service seeds the free plan's monthly AI-credit allowance at // trial start (planRepo + creditService, both already constructed above). - trialService = trial.NewService(subscriptionRepository, userRepostory, planRepository, creditService) + trialService = trial.NewService(subscriptionRepository, planRepository, creditService) featureGateService = feature.NewService(subscriptionRepository, planRepository) // An approved daily-send increase must raise what is enforced, not // only what the dashboard shows. diff --git a/cmd/warmblyctl/client.go b/cmd/warmblyctl/client.go index 2baa6cb55..9c532b875 100644 --- a/cmd/warmblyctl/client.go +++ b/cmd/warmblyctl/client.go @@ -126,7 +126,6 @@ func (c *conn) trialService() trial.TrialService { ) return trial.NewService( repository.NewSubscriptionRepository(c.db.Pool), - c.users, repository.NewPlanRepository(c.db.Pool), creditSvc, ) diff --git a/docs/content/docs/api/error-codes.mdx b/docs/content/docs/api/error-codes.mdx index ecff97f5a..5693c016c 100644 --- a/docs/content/docs/api/error-codes.mdx +++ b/docs/content/docs/api/error-codes.mdx @@ -1080,7 +1080,7 @@ Those request URLs answer `401` `unauthorized` to a request whose Slack signatur #### `mailbox_allowance_reached` -A `403` whose `code` is `mailbox_allowance_reached` comes from every path that connects a mailbox: `POST /emails/onboarding/oauth/start`, `POST /emails/onboarding/oauth/finish`, `POST /emails/onboarding/smtp-imap`, and per row inside `POST /emails/onboarding/smtp-imap/bulk`. A [mailbox import](/guides/mailbox-import/) does not answer it over HTTP: the rows past the allowance fail with the `cause` `allowance_reached` and can be retried once it is raised. It is not a permission problem: the workspace holds its whole [mailbox allowance](/guides/mailboxes/#mailbox-allowance), which on a paid plan is one mailbox for every send a day the plan includes, `0` on a workspace without a paid plan, and `10` on a workspace that kept the earlier free plan. On a workspace without a plan the message says a plan is needed to connect mailboxes. Nothing was connected. +A `403` whose `code` is `mailbox_allowance_reached` comes from every path that connects a mailbox: `POST /emails/onboarding/oauth/start`, `POST /emails/onboarding/oauth/finish`, `POST /emails/onboarding/smtp-imap`, and per row inside `POST /emails/onboarding/smtp-imap/bulk`. A [mailbox import](/guides/mailbox-import/) does not answer it over HTTP: the rows past the allowance fail with the `cause` `allowance_reached` and can be retried once it is raised. It is not a permission problem: the workspace holds its whole [mailbox allowance](/guides/mailboxes/#mailbox-allowance), which on a paid plan is one mailbox for every send a day the plan includes, `2` during a workspace's free trial, `0` on a workspace without a paid plan after it, and `10` on a workspace that kept the earlier free plan. On a workspace without a plan the message says a plan is needed to connect mailboxes. Nothing was connected. ```json { diff --git a/docs/content/docs/guides/billing.mdx b/docs/content/docs/guides/billing.mdx index d40b4a7bc..ac74d7d88 100644 --- a/docs/content/docs/guides/billing.mdx +++ b/docs/content/docs/guides/billing.mdx @@ -3,7 +3,7 @@ title: Plans and billing description: How plans unlock features, how to upgrade from anywhere in the dashboard, and what changes when you switch. --- -Signing up for a hosted workspace is free, and so is looking around the dashboard. Connecting and warming mailboxes needs a paid plan, which also turns on sending from Warmbly Cloud, the unified inbox, contacts, the CRM, automations and integrations. +Each owner's first hosted workspace starts with a 14-day [free trial](#the-free-trial), no card needed: two mailboxes warming, `20` sends a day, the unified inbox, contacts and campaigns. After the trial, connecting and warming mailboxes needs a paid plan, and the plan decides what else is on: sending from Warmbly Cloud, the unified inbox, contacts, the CRM, automations and integrations come with the plans compared [below](#plans). ![Settings > Billing: the plan card, usage against limits, and the subscription actions](/guides/billing.webp) @@ -33,7 +33,8 @@ With no subscription yet, finish in Stripe Checkout. An existing subscription sw ## Good to know -- A new workspace without a paid plan cannot connect or warm mailboxes. Paid plans start at $29 a month with unlimited mailboxes and unlimited warmup in the premium pool. +- A new workspace gets a 14-day free trial with up to 2 mailboxes, once per owner. Every other workspace that owner creates starts without one. +- After the trial, a workspace without a paid plan cannot connect or warm mailboxes. Paid plans start at $29 a month with unlimited mailboxes and unlimited warmup in the premium pool. - A workspace that already had the free plan keeps it: up to 10 mailboxes warming in the free pool, no card and no time limit. - Annual billing is 20% off the monthly price. - Only the workspace owner can change the plan. @@ -43,9 +44,30 @@ With no subscription yet, finish in Stripe Checkout. An existing subscription sw +## The free trial + +An owner's first hosted workspace starts on a 14-day free trial the moment it is created. No card is asked for, and nothing is charged when it ends. + +| During the trial | | +| --- | --- | +| Mailboxes | Up to `2`, warming in the free pool | +| Campaign sends | `20` a day across the workspace | +| Unified inbox, contacts, campaigns | Included, within the trial limits shown under **Settings > Billing** | +| AI features and integrations | Need a paid plan | + +Each owner gets one trial. It goes to the first workspace they create, whether at sign-up or later from the workspace switcher, and every workspace after that starts without one and needs a plan to connect mailboxes. Joining someone else's workspace as a member does not use it. + +The dashboard counts the days down in a bar across the top and on **Settings > Billing**. Pick a plan at any point and the trial ends there: the plan takes over at once and every mailbox moves to the premium pool. + +**When the trial ends without a plan**, nothing is deleted. Active campaigns are paused as **paused, trial expired**, warmup stops and the mailboxes leave the free pool, and members with billing access get a notice. Warmup is paused rather than switched off, so choosing a plan resumes it on its own, with the ramp where it stopped; resume the paused campaigns from their pages. + + + + + ## Without a paid plan -Warmbly Cloud has no free plan for new workspaces. Anyone can sign up and explore the dashboard, but a workspace without a paid plan has a [mailbox allowance](/guides/mailboxes/#mailbox-allowance) of `0`: connecting a mailbox is refused with [`mailbox_allowance_reached`](/api/error-codes/#mailbox_allowance_reached), and no warmup is scheduled. Choosing any plan lifts both. +Warmbly Cloud has no free plan for new workspaces. After its trial, or from the start on a workspace that owner created after their trial, a workspace without a paid plan has a [mailbox allowance](/guides/mailboxes/#mailbox-allowance) of `0`: connecting a mailbox is refused with [`mailbox_allowance_reached`](/api/error-codes/#mailbox_allowance_reached), and no warmup is scheduled. Choosing any plan lifts both. Workspaces that had the free plan before it closed to new workspaces keep it, unchanged, for as long as they like: up to 10 mailboxes connected on the cloud, warming in the free pool, with no card. Subscribing moves those mailboxes to the premium pool with no cap. Warmbly Cloud no longer links new self-hosted instances on any plan; a free workspace [linked earlier](/guides/warmbly-cloud/#free-workspaces-linked-earlier) keeps what it already enrolled but adds no new mailboxes until it picks a plan. Sending from Warmbly Cloud, the unified inbox, contacts, the CRM, automations and integrations turn on with a paid plan. @@ -112,8 +134,8 @@ Only the workspace owner can change the plan. Other members see the same compari - The plan card shows the plan, its status, the price (per year on a yearly subscription), and the renewal or end date. Change plan opens the same chooser the locked features use. - Cancel plan schedules the cancellation for the end of the paid period. The plan stays fully active until then, and Resume clears it with one click. Nothing is deleted either way: the workspace keeps its mailboxes and settings, and warmup stops until it picks a plan again (a workspace that kept the earlier free plan returns to it). -- Usage and limits shows live counts against the limits the server actually enforces, for mailboxes, sends today (the cap the sender applies, or unlimited on a plan without one), contacts, campaigns, team members, attachment storage, sends this period, and API calls. A meter turns amber past 70% and red past 90%. A meter with no cap means that limit is unmetered on your plan. A workspace that does not send (free, or on the Warmup or Partnership plan) sees only the mailbox meter, because none of the others applies to it. The mailbox meter says where its number comes from (fair use, an approved request, or the free allowance, which is `0` for a new workspace without a plan), and the storage meter says so when a plan change left the workspace over its quota: existing attachments keep sending, and new uploads wait until you are back under. -- Banners appear only when something needs a decision: a failed payment, a scheduled cancellation, or a trial about to end. +- Usage and limits shows live counts against the limits the server actually enforces, for mailboxes, sends today (the cap the sender applies, or unlimited on a plan without one), contacts, campaigns, team members, attachment storage, sends this period, and API calls. A meter turns amber past 70% and red past 90%. A meter with no cap means that limit is unmetered on your plan. A workspace that does not send (free, or on the Warmup or Partnership plan) sees only the mailbox meter, because none of the others applies to it. The mailbox meter says where its number comes from (fair use, an approved request, or the free allowance: `2` during the free trial, `0` after it on a workspace without a plan), and the storage meter says so when a plan change left the workspace over its quota: existing attachments keep sending, and new uploads wait until you are back under. +- Banners appear only when something needs a decision: a failed payment, a scheduled cancellation, or the days left in a free trial. Need a single limit raised without moving plan? Request an increase from **Settings > Limits**, linked from the usage section, or straight from the connect dialog when it is mailboxes you need. An operator reviews it and the approved limit takes effect on the workspace, including the daily send allowance the sender enforces. The page shows how much of each limit the workspace uses, and a limit your plan leaves unlimited (mailboxes, on a plan whose daily sends are uncapped) is not offered, because there is nothing to raise. A workspace that does not send can only ask for more mailboxes. diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index 151003bc9..3d963fc8c 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -243,6 +243,7 @@ Mailboxes are unlimited on every paid plan. What keeps that honest is a fair-use | Plan | Sends per day | Mailboxes | | --- | --- | --- | +| Free trial (14 days) | `20` | `2` | | No paid plan | none | `0` | | Free plan kept from before | none | `10` | | Starter | `150` | `150` | @@ -252,7 +253,7 @@ Mailboxes are unlimited on every paid plan. What keeps that honest is a fair-use That is deliberately far more than safe sending ever needs: at the recommended `30` to `50` sends a day per mailbox, a Business workspace fills its volume with a few hundred mailboxes and still has room for tens of thousands. The allowance exists so that it is never the reason to run a mailbox hotter. A plan whose daily sends are uncapped holds unlimited mailboxes, and a self-hosted instance without billing never counts. -**Without a paid plan.** A new workspace connects no mailboxes until it picks a plan; the connect is refused with [`mailbox_allowance_reached`](/api/error-codes/#mailbox_allowance_reached). A workspace that had the free plan before it closed to new workspaces keeps `10` mailboxes warming in the free pool; subscribe to any plan to hold more. A [self-hosted instance](/development/install/) has no mailbox cap, but its warmup only pairs its own mailboxes, with no shared pool, so it does far less for deliverability. Warmbly Cloud no longer links new instances, so the hosted pool is only reached from a hosted workspace. +**Without a paid plan.** A new workspace holds `2` mailboxes, warming in the free pool, for its 14-day [free trial](/guides/billing/#the-free-trial). After the trial, or on a later workspace from an owner who already had one, it connects no mailboxes until it picks a plan; the connect is refused with [`mailbox_allowance_reached`](/api/error-codes/#mailbox_allowance_reached). Mailboxes connected during the trial stay connected and stop warming. A workspace that had the free plan before it closed to new workspaces keeps `10` mailboxes warming in the free pool; subscribe to any plan to hold more. A [self-hosted instance](/development/install/) has no mailbox cap, but its warmup only pairs its own mailboxes, with no shared pool, so it does far less for deliverability. Warmbly Cloud no longer links new instances, so the hosted pool is only reached from a hosted workspace. The connect dialog shows the allowance up front: a quiet count while there is room, a warning near the cap, and a clear full state that leads to the request flow instead of letting you type credentials that would be refused. When a connect is refused the answer is the same dialog, not an error toast. @@ -528,7 +529,7 @@ Keep warmup running after campaigns begin rather than switching it off once a ma A mailbox marked as a [placement seed inbox](/guides/placement-tests/#your-own-seed-inboxes) is the exception: it never warms up (starting warmup on it is refused until it is unmarked) and never sends campaign mail, because a test inbox has to stay a stranger to your senders. - On Warmbly Cloud every paid plan warms in the premium pool. Only a workspace that had the free plan before it closed to new workspaces warms without one, up to `10` mailboxes in the free pool. + On Warmbly Cloud every paid plan warms in the premium pool. Without one, a workspace warms in the free pool during its 14-day free trial (up to `2` mailboxes), or if it had the free plan before it closed to new workspaces (up to `10`). diff --git a/docs/content/docs/guides/warmup.mdx b/docs/content/docs/guides/warmup.mdx index fb74023b1..dcc134a83 100644 --- a/docs/content/docs/guides/warmup.mdx +++ b/docs/content/docs/guides/warmup.mdx @@ -39,7 +39,7 @@ Pause to stop both sending and receiving warmup mail, or Stop to also turn diagn ## Good to know -- On Warmbly Cloud, warmup needs a paid plan, and every paid plan warms unlimited mailboxes in the premium pool. A workspace that had the free plan before it closed to new workspaces keeps warming up to 10 mailboxes in the free pool. +- On Warmbly Cloud, every paid plan warms unlimited mailboxes in the premium pool. A new workspace warms up to 2 mailboxes in the free pool during its 14-day [free trial](/guides/billing/#the-free-trial), and a workspace that had the free plan before it closed to new workspaces keeps warming up to 10 there. Otherwise warmup needs a paid plan. - A self-hosted instance warms every mailbox, but only against the other mailboxes on that instance, with no shared pool. - New mailboxes start with warmup off. Once on, it starts at `10` emails a day by default and climbs by `+1` a day to a ceiling of `40`. - Keep warmup on after campaigns start. A mailbox backing a live campaign drops to at most five warmup messages a day, and the pool replies to more of them. @@ -53,7 +53,7 @@ Pause to stop both sending and receiving warmup mail, or Stop to also turn diagn Warmup sends natural plain-text threads between participating mailboxes. It measures observed placement and bounded actual-message DKIM evidence. It does not establish organic engagement or guarantee reputation improvement or inbox placement. - On Warmbly Cloud a workspace without a paid plan cannot connect mailboxes, and no warmup traffic is scheduled for it; pending warmup activity is skipped rather than sent. A workspace that had the free plan before it closed to new workspaces keeps warming up to 10 mailboxes in the free pool. See [billing](/guides/billing/#without-a-paid-plan). + On Warmbly Cloud a workspace with no paid plan, no free trial and no free plan kept from before cannot connect mailboxes, and no warmup traffic is scheduled for it; pending warmup activity is skipped rather than sent. During the 14-day free trial a new workspace warms up to 2 mailboxes in the free pool; when the trial ends, warmup is paused, and choosing a plan resumes it with the ramp where it stopped. A workspace that had the free plan before it closed to new workspaces keeps warming up to 10 mailboxes in the free pool. See [billing](/guides/billing/#without-a-paid-plan). @@ -125,7 +125,7 @@ A pool is the set of mailboxes that warm each other. Your mailbox exchanges warm | Pool | Who is in it | |------|--------------| | `premium` | Paid organizations' mailboxes. The default for paid accounts, isolated from lower-trust traffic. | -| `free` | Mailboxes of workspaces that kept the earlier free plan, and lower-trust mailboxes, kept separate so free traffic does not mix into premium reputation. New workspaces do not join it without a plan. | +| `free` | Mailboxes of workspaces in their free trial or that kept the earlier free plan, and lower-trust mailboxes, kept separate so free traffic does not mix into premium reputation. Other workspaces without a plan do not join it. | A mailbox belongs to exactly one pool at a time. When its plan changes the mailbox moves between pools rather than joining a second one, and it takes its warmup standing with it, so a quarantine or block is not cleared by changing tier. diff --git a/internal/api/handler/organization.go b/internal/api/handler/organization.go index be0e553cc..cdf03a78b 100644 --- a/internal/api/handler/organization.go +++ b/internal/api/handler/organization.go @@ -15,6 +15,7 @@ import ( "github.com/warmbly/warmbly/internal/errx" "github.com/warmbly/warmbly/internal/models" "github.com/warmbly/warmbly/internal/notify/templates" + "github.com/warmbly/warmbly/internal/observability/errs" "github.com/warmbly/warmbly/internal/pkg/displayname" ) @@ -40,6 +41,13 @@ func (h *Handler) CreateOrganization(c *gin.Context) { h.auditOrg(c, models.AuditActionCreate, models.AuditEntityOrganization, &org.ID, nil, map[string]string{"name": org.Name}) + // An owner who has never had a trial gets it here; every later workspace starts unpaid. + if h.TrialService != nil { + if terr := h.TrialService.StartFreeTrialWithOrg(c.Request.Context(), userID, org.ID); terr != nil { + errs.CaptureException(terr) + } + } + c.JSON(http.StatusCreated, org) } diff --git a/internal/app/feature/gate_warmup_plan_test.go b/internal/app/feature/gate_warmup_plan_test.go index 6a6e9de3e..0341e666d 100644 --- a/internal/app/feature/gate_warmup_plan_test.go +++ b/internal/app/feature/gate_warmup_plan_test.go @@ -168,3 +168,29 @@ func TestFreeWarmupFollowsTheKeptAllowance(t *testing.T) { t.Error("a workspace with no subscription row must not warm or connect mailboxes") } } + +// A trial warms in the free pool and holds TrialMailboxLimit mailboxes; once it ends, both stop. +func TestTrialWarmsTwoMailboxesUntilItEnds(t *testing.T) { + ctx := context.Background() + org := uuid.New() + must := noError(t) + + trial := &featureGateService{subRepo: stubSubs{sub: trialSub()}} + if !must(trial.CanUseWarmup(ctx, org)) { + t.Error("a workspace in its trial must warm") + } + if must(trial.HasPremiumWarmup(ctx, org)) { + t.Error("a trial warms in the free pool, not the premium one") + } + if !must(trial.CanAddInbox(ctx, org, models.TrialMailboxLimit-1)) || must(trial.CanAddInbox(ctx, org, models.TrialMailboxLimit)) { + t.Errorf("a trial must hold exactly %d mailboxes", models.TrialMailboxLimit) + } + + past := time.Now().Add(-time.Hour) + ended := trialSub() + ended.FreeTrialEndsAt = &past + over := &featureGateService{subRepo: stubSubs{sub: ended}} + if must(over.CanUseWarmup(ctx, org)) || must(over.CanAddInbox(ctx, org, 0)) { + t.Error("an ended trial must neither warm nor connect mailboxes") + } +} diff --git a/internal/app/organization/service.go b/internal/app/organization/service.go index 7f5991bd5..e2e2d7536 100644 --- a/internal/app/organization/service.go +++ b/internal/app/organization/service.go @@ -2140,6 +2140,9 @@ func (s *organizationService) GrantManagedPlan(ctx context.Context, orgID, planI errs.CaptureException(err) return nil, errx.New(errx.Internal, "failed to grant the plan") } + if err := s.subRepo.ResumeTrialWarmup(ctx, orgID); err != nil { + errs.CaptureException(err) + } return s.GetManagedPlan(ctx, orgID) } diff --git a/internal/app/stripe/service.go b/internal/app/stripe/service.go index 97c55f867..aaae4b19a 100644 --- a/internal/app/stripe/service.go +++ b/internal/app/stripe/service.go @@ -1304,6 +1304,11 @@ func (s *stripeService) handleSubscriptionUpdated(ctx context.Context, event *st return errx.New(errx.Internal, "failed to update mailbox warmup tier") } } + if sub.HasPaidSubscription() && sub.FreeTrialEndsAt != nil { + if err := s.subRepo.ResumeTrialWarmup(ctx, sub.OrganizationID); err != nil { + return errx.New(errx.Internal, "failed to resume trial warmup") + } + } // The workspace has started paying. Reported after the write, so a failed // update never counts as a start, and keyed off the same transition the diff --git a/internal/app/trial/service.go b/internal/app/trial/service.go index 788541d0b..389438784 100644 --- a/internal/app/trial/service.go +++ b/internal/app/trial/service.go @@ -2,6 +2,7 @@ package trial import ( "context" + "math" "time" "github.com/google/uuid" @@ -43,7 +44,6 @@ type CreditGranter interface { type trialService struct { subRepo repository.SubscriptionRepository - userRepo repository.UserRepository planRepo repository.PlanRepository credits CreditGranter } @@ -51,27 +51,18 @@ type trialService struct { // NewService constructs the trial service. planRepo and credits are optional // (nil-safe): when both are set, StartFreeTrialWithOrg seeds the free plan's // monthly AI-credit allowance so trial orgs can try AI features. -func NewService(subRepo repository.SubscriptionRepository, userRepo repository.UserRepository, planRepo repository.PlanRepository, credits CreditGranter) TrialService { +func NewService(subRepo repository.SubscriptionRepository, planRepo repository.PlanRepository, credits CreditGranter) TrialService { return &trialService{ subRepo: subRepo, - userRepo: userRepo, planRepo: planRepo, credits: credits, } } -// StartFreeTrialWithOrg creates a new free trial subscription linked to an organization +// StartFreeTrialWithOrg gives the workspace a TrialDuration trial on the free +// plan, once per user: a workspace created after the user's trial is claimed +// has no subscription until it pays. func (s *trialService) StartFreeTrialWithOrg(ctx context.Context, userID uuid.UUID, orgID uuid.UUID) error { - // Check if user already used their free trial - user, err := s.userRepo.GetUser(ctx, userID) - if err != nil { - return err - } - if user != nil && user.FreeTrialUsed { - return nil // No-op: user already used their free trial - } - - // Check if org already has a subscription existing, err := s.subRepo.GetByOrganizationID(ctx, orgID) if err != nil { return err @@ -80,21 +71,24 @@ func (s *trialService) StartFreeTrialWithOrg(ctx context.Context, userID uuid.UU return nil } - // A new workspace starts on the free plan with no trial: mailboxes and - // warmup (up to the free allowance) work, everything else waits for a - // subscription. freePlanUUID, _ := uuid.Parse(FreePlanID) + startedAt := time.Now() + endsAt := startedAt.Add(TrialDuration) sub := &models.Subscription{ - ID: uuid.New(), - UserID: userID, - OrganizationID: orgID, - PlanID: freePlanUUID, - StripeCustomerID: "", // Will be set when user subscribes - Status: models.SubscriptionStatusIncomplete, + ID: uuid.New(), + UserID: userID, + OrganizationID: orgID, + PlanID: freePlanUUID, + StripeCustomerID: "", // Will be set when user subscribes + Status: models.SubscriptionStatusIncomplete, + FreeTrialStartedAt: &startedAt, + FreeTrialEndsAt: &endsAt, } - if err := s.subRepo.Create(ctx, sub); err != nil { + // The claim and the row are one write: a failure keeps the trial, and a second workspace cannot also take it. + created, err := s.subRepo.CreateTrial(ctx, sub) + if err != nil || !created { return err } @@ -108,12 +102,6 @@ func (s *trialService) StartFreeTrialWithOrg(ctx context.Context, userID uuid.UU } } - // Mark the user's free trial as used - if err := s.userRepo.SetFreeTrialUsed(ctx, userID); err != nil { - // Log but don't fail - the subscription was created successfully - return nil - } - return nil } @@ -150,11 +138,8 @@ func (s *trialService) GetTrialStatus(ctx context.Context, orgID uuid.UUID) (*Tr status.IsExpired = sub.IsFreeTrialExpired() if status.IsInTrial { - remaining := time.Until(*sub.FreeTrialEndsAt) - status.DaysRemaining = int(remaining.Hours() / 24) - if remaining > 0 && status.DaysRemaining == 0 { - status.DaysRemaining = 1 // At least 1 day remaining if not expired - } + // Rounded up, as the dashboard's trial bar does, so both show the same count. + status.DaysRemaining = int(math.Ceil(time.Until(*sub.FreeTrialEndsAt).Hours() / 24)) } } diff --git a/internal/app/trial/service_test.go b/internal/app/trial/service_test.go new file mode 100644 index 000000000..2ef84e01f --- /dev/null +++ b/internal/app/trial/service_test.go @@ -0,0 +1,96 @@ +package trial + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/repository" +) + +// memSubs models CreateTrial's single statement: the owner's claim and the row commit together or not at all. +type memSubs struct { + repository.SubscriptionRepository + mu sync.Mutex + byOrg map[uuid.UUID]*models.Subscription + used map[uuid.UUID]bool + failing bool +} + +func newMemSubs() *memSubs { + return &memSubs{byOrg: map[uuid.UUID]*models.Subscription{}, used: map[uuid.UUID]bool{}} +} + +func (m *memSubs) GetByOrganizationID(_ context.Context, orgID uuid.UUID) (*models.Subscription, error) { + m.mu.Lock() + defer m.mu.Unlock() + return m.byOrg[orgID], nil +} + +func (m *memSubs) CreateTrial(_ context.Context, sub *models.Subscription) (bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.failing { + return false, errors.New("write failed") + } + if m.used[sub.UserID] { + return false, nil + } + m.used[sub.UserID] = true + m.byOrg[sub.OrganizationID] = sub + return true, nil +} + +// An owner's first workspace gets the trial; every later one starts with no subscription. +func TestOneTrialPerOwner(t *testing.T) { + ctx := context.Background() + subs := newMemSubs() + svc := NewService(subs, nil, nil) + owner, first, second := uuid.New(), uuid.New(), uuid.New() + + if err := svc.StartFreeTrialWithOrg(ctx, owner, first); err != nil { + t.Fatal(err) + } + sub := subs.byOrg[first] + if sub == nil || !sub.IsInFreeTrial() { + t.Fatal("the first workspace must start in its trial") + } + if left := time.Until(*sub.FreeTrialEndsAt); left < TrialDuration-time.Minute || left > TrialDuration { + t.Errorf("trial ends in %v, want %v", left, TrialDuration) + } + + if err := svc.StartFreeTrialWithOrg(ctx, owner, second); err != nil { + t.Fatal(err) + } + if subs.byOrg[second] != nil { + t.Error("a second workspace for the same owner must not get a trial") + } + + if err := svc.StartFreeTrialWithOrg(ctx, owner, first); err != nil || subs.byOrg[first] != sub { + t.Error("starting again on a workspace with a subscription must change nothing") + } +} + +// A trial whose write failed was never claimed, so the owner's next workspace still gets it. +func TestFailedTrialKeepsTheClaim(t *testing.T) { + ctx := context.Background() + subs := newMemSubs() + subs.failing = true + svc := NewService(subs, nil, nil) + owner, broken, next := uuid.New(), uuid.New(), uuid.New() + + if err := svc.StartFreeTrialWithOrg(ctx, owner, broken); err == nil { + t.Fatal("a failed subscription write must be reported") + } + subs.failing = false + if err := svc.StartFreeTrialWithOrg(ctx, owner, next); err != nil { + t.Fatal(err) + } + if sub := subs.byOrg[next]; sub == nil || !sub.IsInFreeTrial() { + t.Error("the owner's next workspace must get the trial the failed one never received") + } +} diff --git a/internal/jobs/trial_expiration.go b/internal/jobs/trial_expiration.go index e90811a96..a81777e63 100644 --- a/internal/jobs/trial_expiration.go +++ b/internal/jobs/trial_expiration.go @@ -84,10 +84,13 @@ func (j *TrialExpirationJob) Run(ctx context.Context) error { // Continue processing other organizations } - // Disable warmup on all email accounts (they're already blocked, but clean up) - if err := repository.DisableWarmupByOrganizationID(ctx, j.db, sub.OrganizationID); err != nil { - errs.CaptureException(err) - // Continue processing other organizations + // Paused, not cleared, so a plan resumes warmup with its ramp where it stopped. + // A failed pause leaves the trial unexpired so the next run retries it. + if sub.FreeTrialEndsAt != nil { + if err := repository.PauseTrialWarmup(ctx, j.db, sub.OrganizationID, *sub.FreeTrialEndsAt); err != nil { + errs.CaptureException(err) + continue + } } // Mark subscription as expired @@ -103,8 +106,8 @@ func (j *TrialExpirationJob) Run(ctx context.Context) error { if j.notifier != nil && sub.OrganizationID != uuid.Nil { j.notifier.NotifyOrg(ctx, sub.OrganizationID, models.PermManageBilling, uuid.Nil, models.NotifBillingAlert, - "Your Warmbly trial has expired", - "Campaigns are paused and warmup is disabled until you upgrade.", + "Your Warmbly trial has ended", + "Sending and warmup are paused. Your mailboxes, contacts and campaigns are kept, and warmup picks up where it stopped when you choose a plan.", "/app/settings/billing", nil, "trial_expired:"+sub.OrganizationID.String()) continue @@ -125,7 +128,7 @@ func (j *TrialExpirationJob) notifyTrialExpired(ctx context.Context, userID inte return } - subject := "Your Warmbly trial has expired" + subject := "Your Warmbly trial has ended" body, err := templates.GenerateTrialExpiredHTML() if err != nil { // GenerateTrialExpiredHTML already reported it. diff --git a/internal/models/subscriptions.go b/internal/models/subscriptions.go index ebaef1f13..05e0a2c6a 100644 --- a/internal/models/subscriptions.go +++ b/internal/models/subscriptions.go @@ -279,16 +279,22 @@ func (s *Subscription) CanSendEmails() bool { return false } -// CanUseWarmup: a paid plan, or a workspace that kept the free allowance -// (the free pool, up to FreeWorkspaceMailboxLimit connected mailboxes). +// CanUseWarmup: a paid plan, a free trial in progress, or a workspace that +// kept the free allowance. Unpaid ones warm in the free pool. func (s *Subscription) CanUseWarmup() bool { - return s.HasPaidSubscription() || s.KeepsFreeWarmup + return s.HasPaidSubscription() || s.KeepsFreeWarmup || s.IsInFreeTrial() } -// FreeMailboxLimit is the mailboxes an unsubscribed workspace may hold: none unless it kept the free allowance. +// FreeMailboxLimit is the mailboxes an unsubscribed workspace may hold: the +// kept free allowance, TrialMailboxLimit during a trial, otherwise none. func (s *Subscription) FreeMailboxLimit() int { - if s != nil && s.KeepsFreeWarmup { + switch { + case s == nil: + return 0 + case s.KeepsFreeWarmup: return FreeWorkspaceMailboxLimit + case s.IsInFreeTrial(): + return TrialMailboxLimit } return 0 } @@ -304,6 +310,9 @@ func (s *Subscription) CanUseUnibox() bool { // hold, connected directly or through a linked self-hosted instance. const FreeWorkspaceMailboxLimit = 10 +// TrialMailboxLimit caps the mailboxes a workspace may hold during its free trial. +const TrialMailboxLimit = 2 + // SubscriptionWithLimits includes rate limits for the subscription type SubscriptionWithLimits struct { Subscription diff --git a/internal/notify/templates/trial_expired.go b/internal/notify/templates/trial_expired.go index 6acb3c592..2913a74bf 100644 --- a/internal/notify/templates/trial_expired.go +++ b/internal/notify/templates/trial_expired.go @@ -19,7 +19,7 @@ Subscription Your free trial has ended

-Thanks for trying {{.Brand}}. Your trial has now ended, so we've paused your campaigns and turned off warmup to avoid any unexpected sending. +Thanks for trying {{.Brand}}. Your trial has now ended, so sending and warmup are paused. Your mailboxes keep their warmup settings, and warmup picks up where it stopped when you choose a plan.

@@ -35,7 +35,7 @@ Thanks for trying {{.Brand}}. Your trial has now ended, so we've paused your cam

-Upgrade to a paid plan to switch everything back on: +Choose a plan to switch everything back on:

diff --git a/internal/repository/pg_subscription.go b/internal/repository/pg_subscription.go index 849989d0c..815710c57 100644 --- a/internal/repository/pg_subscription.go +++ b/internal/repository/pg_subscription.go @@ -21,6 +21,8 @@ const subscriptionColumns = `id, user_id, organization_id, plan_id, stripe_custo type SubscriptionRepository interface { Create(ctx context.Context, sub *models.Subscription) error + // CreateTrial writes a trial subscription only if it also claims the owner's one free trial, in one statement. + CreateTrial(ctx context.Context, sub *models.Subscription) (bool, error) Update(ctx context.Context, sub *models.Subscription) error GetByID(ctx context.Context, id uuid.UUID) (*models.Subscription, error) GetByUserID(ctx context.Context, userID uuid.UUID) (*models.Subscription, error) @@ -39,6 +41,9 @@ type SubscriptionRepository interface { // Enterprise SetEnterprise(ctx context.Context, orgID uuid.UUID, isEnterprise bool) error + // ResumeTrialWarmup resumes the mailboxes the trial expiry paused, keeping their ramp where it stopped. + ResumeTrialWarmup(ctx context.Context, orgID uuid.UUID) error + // Webhook idempotency WebhookEventExists(ctx context.Context, eventID string) (bool, error) RecordWebhookEvent(ctx context.Context, event *models.StripeWebhookEvent) error @@ -76,6 +81,27 @@ func (r *subscriptionRepository) Create(ctx context.Context, sub *models.Subscri return err } +func (r *subscriptionRepository) CreateTrial(ctx context.Context, sub *models.Subscription) (bool, error) { + // One statement, so the claim and the row commit or fail together. + const q = ` + WITH claim AS ( + UPDATE users SET free_trial_used = TRUE, updated_at = now() + WHERE id = $2 AND NOT free_trial_used + RETURNING id + ) + INSERT INTO subscriptions ( + id, user_id, organization_id, plan_id, stripe_customer_id, status, + free_trial_started_at, free_trial_ends_at + ) + SELECT $1, claim.id, $3, $4, '', $5, $6, $7 FROM claim` + tag, err := r.db.Exec(ctx, q, sub.ID, sub.UserID, sub.OrganizationID, sub.PlanID, sub.Status, + sub.FreeTrialStartedAt, sub.FreeTrialEndsAt) + if err != nil { + return false, err + } + return tag.RowsAffected() == 1, nil +} + func (r *subscriptionRepository) Update(ctx context.Context, sub *models.Subscription) error { query := ` UPDATE subscriptions SET @@ -200,6 +226,17 @@ func (r *subscriptionRepository) SetEnterprise(ctx context.Context, orgID uuid.U return err } +func (r *subscriptionRepository) ResumeTrialWarmup(ctx context.Context, orgID uuid.UUID) error { + // The expiry stamps the trial end as the pause time, which no manual pause carries. + const q = `UPDATE email_accounts ea + SET warmup = ea.warmup + (now() - ea.warmup_paused_at), warmup_paused_at = NULL, updated_at = now() + FROM subscriptions s + WHERE s.organization_id = $1 AND ea.organization_id = $1 + AND ea.warmup IS NOT NULL AND ea.warmup_paused_at = s.free_trial_ends_at` + _, err := r.db.Exec(ctx, q, orgID) + return err +} + func (r *subscriptionRepository) WebhookEventExists(ctx context.Context, eventID string) (bool, error) { var exists bool err := r.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM stripe_webhook_events WHERE id = $1)`, eventID).Scan(&exists) diff --git a/internal/repository/pg_user.go b/internal/repository/pg_user.go index ddad7a5d3..f93415220 100644 --- a/internal/repository/pg_user.go +++ b/internal/repository/pg_user.go @@ -62,7 +62,6 @@ type UserRepository interface { // exempt AND belongs to no organization, which a real user never is. DeleteOrphanExemptUser(ctx context.Context, id uuid.UUID) error GetUserByEmail(ctx context.Context, email string) (*models.User, error) - SetFreeTrialUsed(ctx context.Context, userID uuid.UUID) error UpdateOnboarding(ctx context.Context, userID uuid.UUID, firstName, lastName, referralSource, role, teamSize string) error MarkOnboarded(ctx context.Context, userID uuid.UUID) (time.Time, error) MarkProductTourCompleted(ctx context.Context, userID uuid.UUID) (time.Time, error) @@ -233,12 +232,6 @@ func (r *userRepository) GetUserByEmail(ctx context.Context, email string) (*mod return r.getUser(ctx, "email", normalizeUserEmail(email)) } -func (r *userRepository) SetFreeTrialUsed(ctx context.Context, userID uuid.UUID) error { - const q = `UPDATE users SET free_trial_used = TRUE, updated_at = NOW() WHERE id = $1` - _, err := r.DB.Exec(ctx, q, userID) - return err -} - func (r *userRepository) UpdateOnboarding(ctx context.Context, userID uuid.UUID, firstName, lastName, referralSource, role, teamSize string) error { const q = `UPDATE users SET first_name=$2, last_name=$3, referral_source=$4, job_role=NULLIF($5,''), team_size=NULLIF($6,''), onboarding_completed_at=NOW(), updated_at=NOW() WHERE id=$1` _, err := r.DB.Exec(ctx, q, userID, firstName, lastName, referralSource, role, teamSize) diff --git a/internal/repository/pg_worker.go b/internal/repository/pg_worker.go index cad8084ee..c7fb3fc25 100644 --- a/internal/repository/pg_worker.go +++ b/internal/repository/pg_worker.go @@ -608,6 +608,8 @@ func GetExpiredTrialsWithoutPayment(ctx context.Context, db *pgxpool.Pool) ([]mo WHERE s.free_trial_ends_at IS NOT NULL AND s.free_trial_ends_at < NOW() AND s.stripe_subscription_id IS NULL + -- An operator-granted plan in force is paid without Stripe; its trial has nothing to expire. + AND NOT (s.managed_at IS NOT NULL AND (s.managed_until IS NULL OR s.managed_until > NOW())) AND s.status NOT IN ('canceled', 'incomplete_expired') ` @@ -642,10 +644,10 @@ func PauseCampaignsByOrganizationID(ctx context.Context, db *pgxpool.Pool, orgID return err } -// DisableWarmupByOrganizationID disables warmup for all email accounts belonging to an organization -func DisableWarmupByOrganizationID(ctx context.Context, db *pgxpool.Pool, orgID uuid.UUID) error { - query := `UPDATE email_accounts SET warmup = NULL, updated_at = NOW() WHERE organization_id = $1` - _, err := db.Exec(ctx, query, orgID) +// PauseTrialWarmup pauses the organization's warming mailboxes at the trial end, which ResumeTrialWarmup matches on. +func PauseTrialWarmup(ctx context.Context, db *pgxpool.Pool, orgID uuid.UUID, trialEndsAt time.Time) error { + query := `UPDATE email_accounts SET warmup_paused_at = $2, updated_at = NOW() WHERE organization_id = $1 AND warmup IS NOT NULL AND warmup_paused_at IS NULL` + _, err := db.Exec(ctx, query, orgID, trialEndsAt) return err } diff --git a/site/src/components/CTA.astro b/site/src/components/CTA.astro index 384a3eb29..c396c05fb 100644 --- a/site/src/components/CTA.astro +++ b/site/src/components/CTA.astro @@ -17,7 +17,7 @@ interface Props { } const { title = 'Start sending cold email that lands.', - description = 'Pick a plan, connect your mailboxes and start warming them today. Unlimited mailboxes and warmup on every paid plan.', + description = 'Start a 14-day free trial, no card needed, and warm your first mailboxes today. Unlimited mailboxes and warmup on every paid plan.', primaryLabel = 'Get started', primaryHref = 'https://app.warmbly.com/auth/register', secondaryLabel = 'See pricing', diff --git a/site/src/components/WarmupPoolNotice.astro b/site/src/components/WarmupPoolNotice.astro index d369644ad..248f2e71b 100644 --- a/site/src/components/WarmupPoolNotice.astro +++ b/site/src/components/WarmupPoolNotice.astro @@ -19,7 +19,7 @@ const { class: className = '', showWaitlist = true } = Astro.props; The shared warmup pool runs on Warmbly Cloud, because a pool only works once enough vetted mailboxes are writing to each other. A self-hosted instance warms only between its own mailboxes, with no shared pool, so it does far less for deliverability. If deliverability is the goal, Warmbly Cloud is the better choice.

- Self-hosting is free and fully functional on its own, for experienced operators who want to own the whole stack, and supported by the community on Discord rather than by Warmbly. Self-hosted instances do not link to the pool. To warm your mailboxes in it, connect them to a hosted workspace on a paid plan at app.warmbly.com. + Self-hosting is free and fully functional on its own, for experienced operators who want to own the whole stack, and supported by the community on Discord rather than by Warmbly. Self-hosted instances do not link to the pool. To warm your mailboxes in it, connect them to a hosted workspace at app.warmbly.com: an owner's first workspace warms two mailboxes free for 14 days, and a paid plan warms every mailbox within its fair-use allowance.

{showWaitlist && ( diff --git a/site/src/pages/faq.astro b/site/src/pages/faq.astro index 07d8773e6..9350bf499 100644 --- a/site/src/pages/faq.astro +++ b/site/src/pages/faq.astro @@ -13,7 +13,7 @@ const groups = [ ['How long does warmup take?', 'Most new mailboxes need three to six weeks. Warmup starts at 10 emails a day and adds one a day up to 40, and inbox placement usually settles over the same stretch.'], ['Should warmup keep running once I start sending campaigns?', 'Yes. Warmup runs alongside cold sending, so a dip in reputation shows up and gets corrected before your campaigns feel it.'], ['What takes a mailbox out of the warmup pool?', 'A complaint rate of 0.10% or more, a bounce rate of 5% or more, or deleting and junking warmup mail it received. Landing in spam alone only slows warmup down until placement recovers.'], - ['Do the free and premium pools mix?', 'Only on proven terms. The free pool holds the mailboxes of workspaces that kept the free plan after it closed to new workspaces. A paying mailbox can borrow those that have been healthy members for at least three days, and a free mailbox only writes back to a paying inbox that wrote to it first.'], + ['Do the free and premium pools mix?', 'Only on proven terms. The free pool holds the mailboxes of workspaces in their free trial and of workspaces that kept the free plan after it closed to new workspaces. A paying mailbox can borrow those that have been healthy members for at least three days, and a free mailbox only writes back to a paying inbox that wrote to it first.'], ['Is self-hosting free?', 'Yes. Warmbly is Apache 2.0 and free to run, with unlimited mailboxes. Its warmup only pairs the mailboxes on your instance, with no shared pool, so it does far less for deliverability; self-hosted instances do not link to the Warmbly Cloud pool. If deliverability is what you need, use Warmbly Cloud. Self-hosting suits teams that want to own the whole stack. Warmbly does not support self-hosted instances; the community helps on Discord.'], ], }, @@ -46,7 +46,7 @@ const groups = [ { id: 'billing', title: 'Billing', items: [ - ['Is there a free plan?', 'Not for new workspaces. Signing up and looking around is free, and connecting and warming mailboxes needs a paid plan, from $29 a month with unlimited mailboxes and warmup. Workspaces that already had the free plan keep it.'], + ['Is there a free trial?', 'Yes. The first workspace an owner creates gets 14 days free with no card: two mailboxes warming, 20 cold emails a day and the unified inbox. After it, mailboxes and warmup need a paid plan, from $29 a month with unlimited mailboxes and warmup. Workspaces that already had the free plan keep it.'], ['Do you charge per email?', 'No. Each plan includes a daily send budget. Unused volume doesn’t carry over.'], ['What is your refund policy?', 'A full refund within 14 days of a paid purchase if Warmbly didn’t work for you.'], ['Do you have startup pricing?', '50% off Grow for a year for pre-seed and seed companies from YC, Antler, EF, Techstars and similar programmes.'], diff --git a/site/src/pages/index.astro b/site/src/pages/index.astro index c6b6a8592..b7bd4bd84 100644 --- a/site/src/pages/index.astro +++ b/site/src/pages/index.astro @@ -163,7 +163,7 @@ const softwareJsonLd = { Star on GitHub -

Plans from $29 a month · Unlimited mailboxes and warmup · Free to self-host

+

14-day free trial · No credit card · Plans from $29 a month

diff --git a/site/src/pages/pricing.astro b/site/src/pages/pricing.astro index 5e4171062..5d11238cf 100644 --- a/site/src/pages/pricing.astro +++ b/site/src/pages/pricing.astro @@ -77,7 +77,7 @@ const faq: [string, string][] = [ ['Do you charge per email sent?', 'No. Each plan includes a daily send budget. Unused volume doesn’t carry over to the next day.'], ['Is warmup charged separately?', 'No. Warmup is unlimited on every paid plan and runs in the premium pool.'], ['Is there really no mailbox limit?', 'Mailboxes are unlimited on every paid plan under fair use: one mailbox for every email a day your plan includes, so Grow holds 3,000 and Business 15,000. If you need more, ask from the connect dialog and we usually answer within a business day.'], - ['Is there a free plan?', 'Not for new workspaces. Signing up and looking around the dashboard is free, and connecting and warming mailboxes needs a paid plan, from $29 a month. Workspaces that already had the free plan keep it: up to 10 mailboxes warming in the free pool, no card and no time limit.'], + ['Is there a free trial?', 'Yes. A new workspace gets 14 days free with no card: two mailboxes warming in the free pool, 20 cold emails a day, the unified inbox and campaigns. Each owner gets one trial, on their first workspace. After it, connecting and warming mailboxes needs a paid plan, from $29 a month, and nothing you set up is deleted. Workspaces that already had the free plan keep it.'], ['Can I pay for warmup only?', 'Not any more. The Warmup plan is no longer sold, and workspaces already on it keep it while they stay subscribed. Every paid plan includes unlimited warmup in the premium pool.'], ['What does self-hosting cost?', 'Nothing. Warmbly is Apache 2.0, free to run on your own servers and fully functional on its own. Its warmup only pairs the mailboxes on your own instance, with no shared pool, and self-hosted instances do not link to the Warmbly Cloud pool. If deliverability is what you need, Warmbly Cloud is the better choice. Self-hosting suits experienced operators who want to own the whole stack: Warmbly does not support self-hosted instances, and help comes from the community on Discord.'], ['Is there a charge per seat?', 'No. Add as many teammates as you like. Roles and the audit log come with Business.'], @@ -100,7 +100,7 @@ const faq: [string, string][] = [ Pay for the email you send.

- Every paid plan has unlimited mailboxes and unlimited warmup. Plans differ in how much cold email you can send a day, and in what your team needs around it. + Start with a 14-day free trial, no card needed. Every paid plan has unlimited mailboxes and unlimited warmup, and plans differ in how much cold email you can send a day and in what your team needs around it.

@@ -290,7 +290,7 @@ const faq: [string, string][] = [

Something else? Email team@warmbly.com.

- +