Repository navigation
feat(affiliates): native Telemetry Tracker affiliate program (remove Rewardful) - #737
Merged
Merged
Conversation
…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
marked this pull request as ready for review
October 5, 2026 16:15
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]>
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]>
This was referenced Oct 5, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
4b242cc1fdb70c0e8ca692b8529793373c020c52A — Migration strategy (CRITICAL)
Production API 1.17.27 already applied
20261004180000_add_affiliate_tableson boot viamigrateDeployBeforeListen. That SQL is the Rewardful-shaped original (rewardful_*columns; noAffiliate.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.apps/api/prisma/migrations/20261004180000_add_affiliate_tables/migration.sqlis restored byte-for-byte tomain.20261005180000_affiliate_rewardful_to_nativeconverts Rewardful-shaped tables → native TT schema (ALTER / ADD COLUMN / backfill / DROP / NOT NULL). Production tables are expected empty (flags never enabled; Rewardful unused).Local/CI checksum: any database that already applied the edited (native) checksum of
20261004180000will fail Prisma’s checksum check against the restored original. Useprisma migrate resetorprisma migrate resolveas appropriate. Fresh databases apply original20261004180000then the forward migration.B — First commission lost if
invoice.paidraces beforeplan_tierupgraderecordCommissionFromInvoiceused to skip whenorg.plan_tierwas still FREE (checkout.session.completedhad not written it yet) and mark the webhook processed (no retry).parent.subscription_details.metadata/subscription_details.metadatawritten at checkout).invoicePayments.listfails, the webhook errors for retry instead of saving a commission with no payment ids.Earlier blocker fixes (still in this PR)
invoice.paidstoresstripe_payment_intent_idfrom InvoicePayment (invoice.payments/invoicePayments.list). Refunds and disputes match oncharge.payment_intent, with legacycharge.invoice/invoice.chargefallbacks. Unmatched refunds/disputes on a referred org log a warning, setneeds_attention(commission_not_found_refund_or_dispute), and write an audit row. Pin the Stripe Dashboard webhook endpoint to API version2025-03-31.basilor later (basil or dahlia). The API constructsnew Stripe(key)with noapiVersionpin, so outbound calls use stripe v22’s SDK default (dahlia). Required events:invoice.paid,charge.refunded,charge.dispute.created|updated|closed.max(0, remaining_cents_at_payout − desired remaining) − sum(all prior clawbacks, settled or open).SELECT … FROM "Affiliate" … FOR UPDATE, re-read the commission inside the lock, and apply state-aware updates.Ledger model
remaining_cents/ voided). No openAffiliateAdjustmentrows for pre-payout events.AffiliateAdjustment: reserved for post-payout clawbacks.sum(payable commissions' remaining_cents) + sum(open post-payout adjustments).amountCentsmust equal selected remaining + those clawbacks. Concurrent second submit without an idempotency key returnsalready_paid.sessionStoragereferral into the 60-day cookie even when?ref=is no longer in the URL.KEEP / MODIFY / REMOVE audit (PR #732 /
0f96e61)AFFILIATES_ENABLED/NEXT_PUBLIC_AFFILIATES_ENABLEDSTRIPE_SECRET_KEY.UserReferral+ first-org lockattributed_organization_idclaimed once.>not>=). Day 60 valid, day 61 expired.googlemail+tag/dot rules; googlemail now aliases to gmail.isPayoutHold/ founder resolveaffiliate_id.tt_*stripe_customer_id.tt_org_id/tt_affiliate_idonly when ACTIVE and not held.WebhookEvent)AFFILIATE_ADMIN_EMAILS. Routes 404 when the flag is OFF.Affiliatetablecode(case-insensitive). No Rewardful IDs.OrganizationReferralreferral_codeinstead of Rewardful UUID / via token.AffiliateCommissionstripe_payment_intent_idfor basil linking.AffiliateAdjustment/AffiliatePayout20261005180000_affiliate_rewardful_to_nativeafter production’s Rewardful-shaped20261004180000.user-referral-capture/affiliate-resolution?ref=/?via=codes locally. No UUID-only UNRESOLVED webhook path.invoice.paid/ refunds / disputesstripe-webhook.ts.ReferralCapture+ sessionStorage; optional consent cookie.r.wdfl.co),RewardfulLoaderREWARDFUL_*env,/webhooks/rewardfulmetadata.referralinvoice.paid.Native V1 flow
?ref=<code>→ last-touch (sessionStorage always; 60-day cookie after marketing consent) → signup lock → first org attributed → later Pro/Businessinvoice.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
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.listfailure 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)
AFFILIATES_ENABLED/NEXT_PUBLIC_AFFILIATES_ENABLEDunset in every env.20261005180000_affiliate_rewardful_to_native(20261004180000is already applied).POST /api/meta/affiliates, sharehttps://telemetry-tracker.com/?ref=<code>.Checklist
RUN_DB_INTEGRATION_TESTS=true)docs/AFFILIATES.md+docs/BILLING.mdmain/ no production migrate / flags remain OFF20261004180000matchesmainexactly