# Task: let this app's users join its affiliate program in one tap and see their earnings in the app

You are working in the app's codebase. The affiliate program runs on Anderro.
Work through everything below on your own, from start to finish, then report back once.

## How to work (no check-ins)
- Do not stop to show me a plan, ask for a go-ahead, or confirm a choice. Where this
  prompt gives a default, use it. Where it does not, pick what fits the codebase best.
  Write each choice and why under "Decisions I made" in your report.
- Stop and ask me only if one of these is true:
  1. The app has no signed-in users, or you cannot read the user's email on the server.
  2. The key reaches more than one Anderro product and nothing in the codebase says which.
  3. Finishing would mean something on the "Never do" list below.
- A missing ANDERRO_SECRET_KEY is not a reason to stop: build and test without it (see
  "Secret key") and put it in the "What you need to do" list.
- If this is a git repository, work on a new branch named referral-program and commit as
  you go. Never do: push, deploy, run migrations against production, send an email to a
  real user, edit the published terms or privacy pages, or create affiliates on Anderro
  with made-up emails. List any of these that are needed for me to do.

## Facts (from Anderro; do not change them or invent others)
- Program name, commission, cookie window and link format: read them from GET https://anderro.com/api/v1/products
  (the `program` object; read-only and safe to call) with the key below. Put them in one
  config module that the pages read. If the key is not set yet, put clearly marked
  placeholders there and list them in "What you need to do".
- Affiliate terms: program.programPageUrl from GET https://anderro.com/api/v1/products. If that is null, use this app's own terms page, and if there is none, a marked placeholder listed in "What you need to do".
- API: https://anderro.com/api/v1. Header on every call: x-api-key: <value of ANDERRO_SECRET_KEY>.
  Also send a User-Agent naming this app (Anderro's firewall refuses some default ones).
  A product key (sk_...) needs nothing else; an organization or account key also needs
  X-Anderro-Product: <product id>.
- GET responses are wrapped in {"data": ...} with snake_case keys. POST /affiliates
  answers with camelCase keys and no wrapper. Read both.

## Before you start
- Find: the user model and how the signed-in user is read on the server, how database
  fields are added, the email system, feature flags, analytics, and the billing state
  (who is a paying customer). Keep notes for the report; do not wait for a reply.
- Stack: Something else. Use whatever this codebase already uses for server routes, the signed-in user, database fields and HTTP calls.
- Reuse the codebase's own components, styles, HTTP client and patterns. Do not add a
  dependency when one already in the app does the job.
- Put everything behind one flag, REFERRAL_PROGRAM_ENABLED, off by default, using the
  app's feature-flag system if it has one, else an environment variable. Make it possible
  to turn it on for one account (an allow-list of user ids or emails is enough).

## 1. Server: two routes, signed-in users only
Add to the user: anderro_partnership_id, anderro_affiliate_id, referral_code,
referral_link, affiliate_joined_at, referral_prompt_dismissed_at (all nullable).

POST /affiliate/enroll  body {placement}  (placement = where the tap happened,
for example "refer-page" or "checkout-success")
1. Refuse without an email. Already enrolled (anderro_partnership_id set): return the
   stored link, change nothing. Key not set: answer 503 {code: "not_configured"} and
   call nothing.
2. Every signed-in user may join.
3. POST https://anderro.com/api/v1/affiliates
   {"email": "<lower-cased email>", "name": "<name>", "source": "in_app", "placement": "<placement>"}
   - 201 (new) or 200 (already joined from this app, or re-added): store
     partnership.id, partnership.referralCode and partnership.referralLink. Then call
     GET https://anderro.com/api/v1/affiliates/{partnership.id} once and store data.affiliate.id as
     anderro_affiliate_id: the commissions and payouts filters take that id, not the
     affiliate.id in the POST answer.
   - 409 with code "joined_on_anderro": this person already joined the program on Anderro
     itself. Store nothing; tell them their link is in Anderro and link to
     https://anderro.com/affiliate/links.
   - 409 "Referral code is already in use" only happens if you send referralCode: retry
     once without it.
   - Any other error: change nothing, return an error the button can show; a retry is safe.
4. Set affiliate_joined_at, record an analytics event affiliate_joined {placement}, and
   return {url: referral_link}.

GET /affiliate/me → {joined, url, stats, commissions, payouts} for the signed-in user.
Not joined: {joined: false} with no Anderro call. Joined: cache the answer 10 minutes per
user; a refresh parameter skips the cache. Calls (id = anderro_partnership_id,
affiliate id = anderro_affiliate_id):
- GET https://anderro.com/api/v1/affiliates/{id}/stats?period=30d → clicks, signups, conversions,
  revenue_cents, commissions_cents, previous_period {...}
- GET https://anderro.com/api/v1/affiliates/{id}/stats/timeseries?period=30d → one row per day: date
  (YYYY-MM-DD), clicks, signups, conversions, revenue_cents, commissions_cents
- GET https://anderro.com/api/v1/affiliates/{id} → commissions.pending_amount_cents, approved_amount_cents
- GET https://anderro.com/api/v1/commissions?affiliate_id={affiliate id}&limit=20 → created_at,
  payment_amount_cents, amount_cents, status (pending, approved, paid, refunded, rejected)
- GET https://anderro.com/api/v1/payouts?affiliate_id={affiliate id}&limit=10 → amount_cents, status, paid_at
Never send customer_email (or any customer detail) to the browser: the user sees dates,
amounts and statuses only.

## 2. Copy my link: one shared component
Every surface uses the same component. States:
- Joined: the stored link and a Copy button. A tap only copies.
- Not joined: a greyed, unselectable preview, a "Copy my link" button, and under it,
  word for word: "By copying you join the <App name> affiliate program on Anderro. Terms"
  (Terms opens the affiliate terms in a new tab). One tap joins AND copies.
- Working: "Getting your link…", button disabled. Done: "Copied" for 2 seconds.
- Copy blocked by the browser: they are joined anyway; show the link selectable with
  "Copy again".
- Not allowed to join (subscription_required): "Referral links are for paying
  <App name> customers" and a link to the plans page.
- Error: "Something went wrong getting your link. Try again".
Safari only allows a copy inside the click handler. Start the enroll request, and in the
same handler call navigator.clipboard.write([new ClipboardItem({"text/plain": promise})])
where promise resolves to a Blob of the link. Do not await the request before that call.
Fall back to navigator.clipboard.writeText after the request, then to showing the link.
Never join anyone from a page load, a GET request, an email link or a background job.
Real <button>s, visible focus, and the state announced to screen readers.

## 3. Refer & earn page (in the signed-in navigation)
- Top: "Earn <commission>" in one line, then the Copy my link component.
- Not joined: three steps (copy your link, share it, get paid) and two answers:
  "Do I need another account? Not to share. To get paid, sign up on Anderro with the
  email you use for <App name>." and what counts as a referral (from the facts above).
- Joined: four numbers for the last 30 days with the change against the previous 30
  (clicks, sign-ups, paying customers, earned), a daily clicks chart, the commissions
  table, the payouts list, and an "Updated N min ago · Refresh" line.
- A "Get paid" box: "Payouts are made through Anderro. Add PayPal or Wise there. The first
  time, sign up with <their email>, the email you use for <App name>." Button: Add payout
  details → https://anderro.com/affiliate/settings/payouts (new tab).
- Empty state when every number is 0: where people usually share the link.

## 4. Prompts at good moments (no Anderro calls)
- Pick 1 to 3 moments yourself when the user just got value, in this order of preference:
  a successful payment or upgrade, the first time they finish the app's core action, a
  milestone (a count, a streak, a result they share). Write the ones you chose, and
  where, under "Decisions I made". If none fit, skip the banners and say so.
- Show a dismissible banner there with the Copy my link component and the one-line offer.
- At most once per moment per user and at most one banner a week (store the time it was
  shown and referral_prompt_dismissed_at). Never on sign-up, onboarding, billing or
  error pages. Hidden when the user may not join.
- Once joined, do not ask again; if they have earned something, a quiet "You've earned
  $X so far" link to the page is fine.
- Analytics: referral_prompt_shown and referral_prompt_copied with {placement}.

## 5. One referral email (this app's own email system)
- Once per user, 14 days after their first good moment, only with marketing consent.
- Unsubscribe link, the app's frequency cap, and its own kill switch (off by default).
- Links to the Refer & earn page, never to a preview link.
- Test it with the app's email preview or test mode; never send it to a real user.

## 6. Terms and privacy wording (a draft file for me to review)
- Write the wording into REFERRAL_LEGAL_DRAFT.md at the repository root, next to where
  each line belongs in the app's current terms and privacy policy. Do not edit the
  published pages.
- Terms: users may join the <App name> affiliate program, run on Anderro, under the
  affiliate terms at the affiliate terms URL from the Facts section.
- Privacy policy: when a user joins, their email and name are shared with Anderro to run
  the program and pay them.
- Account deletion (build this in code, not just the draft): when a joined user deletes
  their account, also call POST https://anderro.com/api/v1/affiliates/remove {"email": ...}.
- Use only the facts above; do not invent rates, payout rules or dates.

## 7. Secret key: I add it myself, you never see it
- Read it only on the server, only from the environment variable ANDERRO_SECRET_KEY.
  If tracking is already set up, the same variable is already there.
- Do not ask me to paste the key into this chat. Do not print, log or echo its value.
- Do not write the key into any file. In .env.example, add the name with an empty value.
- Check whether it is already set by name only, never by printing a value: in the local
  environment (test -n "$ANDERRO_SECRET_KEY"), in .env files (match the name, not the
  line), and in the hosting provider's config if its CLI can list names without values.
- Not set: carry on. The routes answer 503 not_configured, the tests use a fake value, and
  "What you need to do" says to add it in the hosting provider's environment settings,
  copied from the product's API tab in Anderro.
- Never use it in browser code or in anything shipped to the browser.

## Check it yourself
- Add automated tests with the Anderro API mocked (never the real one) for:
  - enroll: 201 stores the ids and calls GET /affiliates/{id} once; a second tap calls
    nothing; 200 is handled like 201; 409 joined_on_anderro stores nothing; any other
    error stores nothing; no email is refused; no key gives 503 not_configured;
    every signed-in user may join; signed-out gets 401.
  - me: not joined makes no Anderro call; joined is cached; no customer_email or other
    customer detail is in the response.
  - the flag: off means no route, page, banner or email exists for that user.
- Run the app's own tests, type check, linter and build. Fix anything you broke.
- If ANDERRO_SECRET_KEY is set where you run, make one read-only call,
  GET https://anderro.com/api/v1/products, and check the program facts match the Facts section. Print the
  status and the program fields only, never the request headers.
- If you can run the app and open a browser, sign in as a test user with the flag on and
  check the page and a banner in the not-joined state, on a phone-width
  screen too. Do not tap Copy my link: that creates a real affiliate.

## Done when
- Everything is behind REFERRAL_PROGRAM_ENABLED, off by default.
- The tests above pass, along with the app's existing tests, type check and build.
- No customer email or other customer detail reaches the browser.
- No secret value appears in the code, the commit, or this conversation.
- You have sent one report with these four headings:
  1. What I built: the files, one line each.
  2. Decisions I made: each choice and why.
  3. Checks I ran: each command or test and its result, including anything that failed.
  4. What you need to do: only what you could not do yourself, numbered, shortest first.
     Usually: add ANDERRO_SECRET_KEY if it was missing; replace any placeholders;
     review REFERRAL_LEGAL_DRAFT.md and publish it; deploy; turn REFERRAL_PROGRAM_ENABLED on for your own
     account and tap Copy my link once (Anderro then shows
     "Joined from inside your app" on the In your app tab); then turn it on for everyone.
