Skip to content

feat(affiliates): native Telemetry Tracker affiliate program (remove Rewardful) - #737

Merged
unjica merged 8 commits into
developfrom
cursor/native-affiliates-aafa
Oct 5, 2026
Merged

unjica merged 8 commits into
developfrom
cursor/native-affiliates-aafa

Conversation

@unjica

@unjica unjica commented Oct 5, 2026 •

Copy link
Copy Markdown
Collaborator

Why

The founder is not using Rewardful ($49/mo). Product rules stay the same: TT owns attribution and 30% lifetime recurring commissions on hosted Pro/Business. Stripe remains the payment source of truth. Feature flags stay OFF. This PR does not deploy, enable flags, or run production migrations.

Blocker fixes (this revision)

HEAD: 4b242cc1fdb70c0e8ca692b8529793373c020c52

A — Migration strategy (CRITICAL)

Production API 1.17.27 already applied 20261004180000_add_affiliate_tables on boot via migrateDeployBeforeListen. That SQL is the Rewardful-shaped original (rewardful_* columns; no Affiliate.code / AffiliatePayout / AffiliateAdjustment / stripe_payment_intent_id). This PR had rewritten that same file in place to the native schema — that is wrong for production checksums and is undone.

  1. apps/api/prisma/migrations/20261004180000_add_affiliate_tables/migration.sql is restored byte-for-byte to main.
  2. New forward migration 20261005180000_affiliate_rewardful_to_native converts Rewardful-shaped tables → native TT schema (ALTER / ADD COLUMN / backfill / DROP / NOT NULL). Production tables are expected empty (flags never enabled; Rewardful unused).
  3. Docs/CHANGELOG no longer claim this migration was never run in production.

Local/CI checksum: any database that already applied the edited (native) checksum of 20261004180000 will fail Prisma’s checksum check against the restored original. Use prisma migrate reset or prisma migrate resolve as appropriate. Fresh databases apply original 20261004180000 then the forward migration.

B — First commission lost if invoice.paid races before plan_tier upgrade

recordCommissionFromInvoice used to skip when org.plan_tier was still FREE (checkout.session.completed had not written it yet) and mark the webhook processed (no retry).

  1. Hosted Pro/Business is also accepted from invoice/subscription metadata Stripe already carries (parent.subscription_details.metadata / subscription_details.metadata written at checkout).
  2. If the invoice is a paid hosted subscription but the org is still FREE and that metadata is missing/ambiguous, the webhook throws so Stripe retries. It is not marked processed and skipped forever.
  3. Self-hosted, explicit FREE metadata, and zero-eligible invoices are never commissioned.
  4. If invoicePayments.list fails, the webhook errors for retry instead of saving a commission with no payment ids.

Earlier blocker fixes (still in this PR)

  1. Stripe basil charge↔invoice linking — invoice.paid stores stripe_payment_intent_id from InvoicePayment (invoice.payments / invoicePayments.list). Refunds and disputes match on charge.payment_intent, with legacy charge.invoice / invoice.charge fallbacks. Unmatched refunds/disputes on a referred org log a warning, set needs_attention (commission_not_found_refund_or_dispute), and write an audit row. Pin the Stripe Dashboard webhook endpoint to API version 2025-03-31.basil or later (basil or dahlia). The API constructs new Stripe(key) with no apiVersion pin, so outbound calls use stripe v22’s SDK default (dahlia). Required events: invoice.paid, charge.refunded, charge.dispute.created|updated|closed.
  2. Post-payout clawback cap — clawback = max(0, remaining_cents_at_payout − desired remaining) − sum(all prior clawbacks, settled or open).
  3. Refund/dispute vs mark-as-paid race — both paths take SELECT … FROM "Affiliate" … FOR UPDATE, re-read the commission inside the lock, and apply state-aware updates.

Ledger model

  1. Pre-payout refunds / lost disputes: only mutate the commission row (remaining_cents / voided). No open AffiliateAdjustment rows for pre-payout events.
  2. AffiliateAdjustment: reserved for post-payout clawbacks.
  3. Payable balance: sum(payable commissions' remaining_cents) + sum(open post-payout adjustments).
  4. Mark as paid: auto-includes every unsettled clawback. amountCents must equal selected remaining + those clawbacks. Concurrent second submit without an idempotency key returns already_paid.
  5. Consent: after marketing consent, promote a remembered sessionStorage referral into the 60-day cookie even when ?ref= is no longer in the URL.

KEEP / MODIFY / REMOVE audit (PR #732 / 0f96e61)

Piece Decision Notes
AFFILIATES_ENABLED / NEXT_PUBLIC_AFFILIATES_ENABLED KEEP Still OFF by default. Effective ON only with STRIPE_SECRET_KEY.
UserReferral + first-org lock KEEP Canonical user capture; attributed_organization_id claimed once.
60-day last-touch window KEEP Evaluated at signup (> not >=). Day 60 valid, day 61 expired.
Self-referral + email normalize KEEP Gmail/googlemail +tag/dot rules; googlemail now aliases to gmail.
isPayoutHold / founder resolve KEEP Hold for self-referral-risk reasons; founder-only audited resolve. Never rewrite affiliate_id.
Stripe Customer reuse + tt_* KEEP Checkout reuses stripe_customer_id. tt_org_id / tt_affiliate_id only when ACTIVE and not held.
Stripe webhook dedupe (WebhookEvent) KEEP Stripe only; still gated on the affiliate flag.
Founder admin allowlist KEEP AFFILIATE_ADMIN_EMAILS. Routes 404 when the flag is OFF.
Relevant attribution / billing / dedupe tests KEEP (adapted) Rewardful-specific cases rewritten for native invoices/refunds/payouts.
Affiliate table MODIFY Founder-created. Public code (case-insensitive). No Rewardful IDs.
OrganizationReferral MODIFY Stores referral_code instead of Rewardful UUID / via token.
AffiliateCommission MODIFY Native ledger: one row per Stripe invoice. pending → payable → paid / voided. stripe_payment_intent_id for basil linking.
AffiliateAdjustment / AffiliatePayout MODIFY Added by forward migration 20261005180000_affiliate_rewardful_to_native after production’s Rewardful-shaped 20261004180000.
user-referral-capture / affiliate-resolution MODIFY Resolve ?ref= / ?via= codes locally. No UUID-only UNRESOLVED webhook path.
Stripe invoice.paid / refunds / disputes MODIFY Native commission engine in stripe-webhook.ts.
Founder admin routes MODIFY Create/disable/inspect affiliates + mark payout paid. Resolve-needs-attention kept.
Dashboard capture MODIFY First-party ReferralCapture + sessionStorage; optional consent cookie.
Rewardful JS (r.wdfl.co), RewardfulLoader REMOVE
REWARDFUL_* env, /webhooks/rewardful REMOVE
Stripe metadata.referral REMOVE Commissions come from TT attribution + invoice.paid.
Rewardful webhook / commission-mirror tests REMOVE

Native V1 flow

?ref=<code> → last-touch (sessionStorage always; 60-day cookie after marketing consent) → signup lock → first org attributed → later Pro/Business invoice.paid → 30% commission → 30-day hold → payable ≥ €50 → founder Mark as paid.

Refunds/disputes adjust the ledger (void/reduce before payout; negative adjustment after). No automated money movement. Self-hosted invoices are excluded.

How to test

pnpm lint && pnpm test && pnpm build
cd apps/api && RUN_DB_INTEGRATION_TESTS=true pnpm test

Covered in addition to prior cases: FREE org + Pro/Business subscription metadata → commission; ambiguous FREE + paid hosted invoice is retryable (webhook failed, not processed); invoicePayments.list failure does not save a commission without payment ids.

Security / privacy

Founder-only admin allowlist. No new third-party scripts or secrets. Optional referral cookie only after consent; same-session attribution still works if optional cookies are declined. No fingerprinting.

Founder enablement (not in this PR)

  • Leave AFFILIATES_ENABLED / NEXT_PUBLIC_AFFILIATES_ENABLED unset in every env.
  • Do not deploy from this branch to production.
  • Do not run production migrations until you explicitly enable the program. When this PR ships, production will apply only the new forward migration 20261005180000_affiliate_rewardful_to_native (20261004180000 is already applied).
  • When ready: set both flags, apply the forward migration via normal API boot migrate, create affiliates via POST /api/meta/affiliates, share https://telemetry-tracker.com/?ref=<code>.

Checklist

  • Tests pass (RUN_DB_INTEGRATION_TESTS=true)
  • Lint + build
  • CHANGELOG + docs/AFFILIATES.md + docs/BILLING.md
  • No main / no production migrate / flags remain OFF
  • 20261004180000 matches main exactly
Open in Web Open in Cursor 

cursoragent and others added 3 commits October 5, 2026 16:02
…mmissions

TT now owns last-touch referral capture, locked org attribution, and 30%
recurring commissions from Stripe invoice.paid. Rewardful JS, webhooks,
secrets, and schema columns are removed. Feature flags stay off by default.

Co-authored-by: Sanja Malovic <[email protected]>
…k-paid tests

Map googlemail.com onto gmail.com for self-referral checks, and use a
payable commission at the €50 threshold when testing refund-after-payout.

Co-authored-by: Sanja Malovic <[email protected]>
@unjica
unjica marked this pull request as ready for review October 5, 2026 16:15
cursoragent and others added 5 commits October 5, 2026 16:31
Pre-payout refunds and lost disputes now only mutate the commission row.
AffiliateAdjustment is reserved for post-payout clawbacks. Mark as paid
auto-includes unsettled clawbacks, refuses amount_mismatch/overpay, and
serializes concurrent submits. Consent promotes a remembered referral
cookie even when ?ref= is gone.

Co-authored-by: Sanja Malovic <[email protected]>
Store PaymentIntent ids from InvoicePayment so refunds/disputes match after
Stripe basil removed Invoice.charge and Charge.invoice. Cap post-payout
clawbacks to amount actually paid net of all prior clawbacks. Serialize
refunds/disputes with the mark-as-paid Affiliate FOR UPDATE lock.

Co-authored-by: Sanja Malovic <[email protected]>
… race

Restore 20261004180000 to the Rewardful-shaped SQL already applied on
production 1.17.27, and add a forward migration to the native schema.
Treat invoice/subscription plan_tier metadata as hosted Pro/Business
when org.plan_tier is still FREE, and fail the webhook for retry when
that metadata is missing instead of skipping forever.

Co-authored-by: Sanja Malovic <[email protected]>
@unjica
unjica merged commit 58094bf into develop Oct 5, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants