# Changelog

## cPanel Git deployment verified and ready (2026-10-14)

- The pipeline from commit 5d34ac1 was reviewed end-to-end and is ready to use: `.cpanel.yml` → `scripts/cpanel-deploy.sh` → rsync (never touches `.env`, `storage/`, uploads or backups) → `composer install --no-dev` → maintenance mode → migrate → re-cache → back online, with the trap guaranteeing recovery even when a step fails.
- Deploy safety verified: refuses to overwrite a folder that isn't BeAuthentic, root `.htaccess` blocks dotfiles and sensitive files when the app lives inside `public_html`, and a failed maintenance test can no longer leave the down file behind.
- Phase 8 test count in the README refreshed (257).

## Admins stay signed in during maintenance mode (2026-10-14)

- **Root cause:** Laravel's maintenance middleware runs in the global stack, *before* the session starts, so `down` had no way to check who was asking — every URL, including `/admin/*` and Livewire's update endpoint, returned the prerendered "Back in a moment" page unless the browser held the secret bypass cookie. The admin who enabled maintenance from the UI (and never visited the bypass link) was locked out mid-task and looked "logged out": the database session survived, the middleware simply never consulted it.
- **Fix:** maintenance mode now whitelists the paths that guard themselves — `login`/`logout`, `admin/*` (still behind auth + the admin gate), Livewire's update/upload endpoints (CSRF + signed snapshots), `/up` (health probe) and `webhooks/*` (signature-verified, so payments keep confirming while the storefront is closed). Everything else — the whole storefront — still gets the branded 503, and the secret bypass link keeps working for staff on devices without a session.
- Admin → System copy updated: staff keep access automatically; the bypass link is for other devices.

## De-flaked the Wall colour-filter test (2026-10-14)

- **Root cause:** the colour factory generated `tagline` from a *random* faker colour name even when the test overrode `name`, so roughly 1 in 15 test colours carried the tagline "Your Blue era." — and the product page embeds each variant's colour tagline in its Alpine JSON. On an unlucky run, the pink product page legitimately contained the substring "Blue era" and the test's `assertDontSee` failed. Not a product bug — a test-data collision with brand copy.
- **Fixes:** the factory now derives the tagline from the final name (a colour named Blue carries "Your Blue era." — the copy also matches in seeded/test data), and the Wall test asserts post identity via each post's uuid (rendered in the card's link) instead of caption substrings, so no future copy can collide with it.
- Full suite: 256 passed.

## Late-payment regression test (2026-10-14)

- New test: a Paystack webhook arriving after the order was cancelled holds for review when the stock is gone — the order stays cancelled, the payment is marked successful for manual refund, stock is not deducted and no `OrderPaid` side effects (points, emails) fire. The reinstatement path (stock still available → order revived and paid) was already covered.
- 1 new test (256 total).

## Race-proof coupon limits (2026-10-14)

- Coupon usage limits are now enforced **atomically when the payment is confirmed**, not only when the cart is evaluated:
  - The coupon row is locked during confirmation, so confirmations for the same coupon serialise (callback + webhook races already covered).
  - `times_used` can never exceed `usage_limit` — the increment is conditional.
  - Per-customer limits are counted under the same lock.
  - A payment that still slips through (parallel checkouts on the last permitted use, or an admin lowering a limit while orders await payment) keeps its money and stays paid, but is flagged with a staff note and a log warning instead of silently over-redeeming.
- `CouponValidator`'s checks remain as a fast pre-filter so customers hear "fully used" before paying.
- 2 new tests (255 total).

## cPanel Git deployment (2026-10-14)

- **`.cpanel.yml` + `scripts/cpanel-deploy.sh`:** deploy from GitHub with cPanel → Git™ Version Control → *Deploy HEAD Commit*.
  - Copies the code (keeps `.env`, `storage/`, uploads, backups).
  - Runs `composer install --no-dev` with PHP 8.3+, downloading Composer if missing.
  - On installed stores: maintenance mode → migrate → re-cache → live (online again even on failure).
  - First deploy: hands over to the `/install` wizard.
  - Refuses to overwrite a folder that isn't a BeAuthentic install.
- DEPLOYMENT.md: deploy-key setup, cloning, choosing the app folder (including `public_html`), and the update and rollback routine.

## Admin AI keys & mobile colours (2026-10-14)

- **Admin → AI Try-On → Provider & API keys:**
  - Choose the OpenAI model (`gpt-image-1`, `gpt-image-1-mini`, `dall-e-2` or custom) and paste the API key.
  - The key is stored encrypted, shown only masked, overrides `.env`, and is audited without its value.
  - "Test connection" checks the key and model with no image generated and no charge.
  - Replicate token, model and webhook secret work the same way.
- **Fix:** the blank `AI_PROVIDER_BASE_URL=` line shipped in `.env.example` erased the default API address, so real OpenAI/Replicate requests would have failed. Blank lines now fall back to the defaults.
- **Fix:** the AI dashboard's "failure reasons" list and the form-error bag shared a variable name.
- **Fix:** "What colour are you today?" on phones is now a swipeable row of colour cards; previously the labels were clipped and covered by the pots. Tablet and desktop are unchanged.
- Fix: large product photos (up to 6000×6000) could exceed the common 128 MB cPanel PHP memory limit during processing; image work now raises the limit for that request only.
- 8 new tests (253 total).

## Installation wizard (2026-10-13)

- `/install` web wizard for cPanel with no terminal. Steps:
  - **Requirements:** PHP, extensions, permissions, HTTPS, and a check that private files can't be downloaded.
  - **Site & database:** the MySQL connection and table privileges are tested before saving; `.env` is written for production, safely escaped.
  - **Create tables.**
  - **Admin account:** optional starter catalogue.
  - **Email:** a real test send before saving.
  - **Paystack:** secret key checked with Paystack; Cloudflare option; backup encryption password.
  - **Finish:** storage link, optimise, then the installer locks itself and shows the cron line and webhook URL.
- **Security:** only someone who can read the one-time setup key from the server (File Manager) can install. The browser token cookie is HttpOnly and SameSite=Strict, and every form needs a matching token. Every installer URL returns 404 once installed, and existing manual installs are never affected.
- **Robust before SSL:** the wizard runs without sessions, cache or database. Its redirects are relative, so it works before HTTPS is set up.
- **Packaging:** `scripts/package-release.sh` builds an upload-ready zip (production Composer dependencies, built assets, empty storage, no `.env`). A root `.htaccess` makes extracting straight into `public_html` safe.
- 6 new tests (245 total).

## Phase 8 — Performance, security audit, cPanel hardening (2026-10-12)

**Security audit** (see SECURITY.md): dependencies clean; raw SQL and unescaped output reviewed; automated route/permission sweep for every page × role. Fixed: two admin actions without action-level checks; votes unthrottled; `.env.example` shipping insecure cookies; `env()` outside config breaking proxies and seeding after `optimize`; a migration whose `down()` failed on SQLite.

**Hardening**
- HTTPS redirect, trusted proxies via config, secure cookies by default in production, baseline CSP, HSTS.
- Throttled sign-up, reset and verification pages.
- Secret-masking log tap; `.htaccess` blocks dotfiles and adds compression and asset caching.

**Errors**
- Branded standalone error pages (404/403/419/429/500/503).
- Livewire failures become friendly toasts in production ("Something went wrong. Try again.", session-expired auto-refresh).
- Admin → System → Recent errors (redacted).

**Operations**
- Admin → System: health checks, scheduled-task last runs and overdue warnings, failed jobs (retry/delete), recent errors, backups, maintenance mode with bypass link.
- `php artisan beauthentic:doctor` for deploy verification.
- Cron heartbeat and per-task tracking.

**Backups**
- `backup:run` nightly: portable SQL dump (no mysqldump) plus media, optional AES-256 encryption (adds `.env`), off-site copy to S3/R2/B2/Wasabi (S3 adapter installed), retention, admin download (audited).
- AI previews are excluded by design.
- The restore path is tested (dump round-trip) and documented.

**Scheduler duties from the spec**
- Abandoned bags → new "Bag left behind" campaign trigger and `cart.abandoned` CRM event; old guest bags pruned.
- Nightly analytics rollups (`daily_metrics`).
- Campaign housekeeping.

**Performance**
- Indexes on hot paths (`orders.paid_at`, `orders(email, paid_at)`, `order_items.order_id`…).
- Versioned catalogue cache: IDs only, so prices and stock stay live.
- 480/960px WebP renditions with `srcset`.
- Query budgets per key page enforced by tests.

**Deployment**
- Complete cPanel guide: with and without SSH, exact cron line, queue strategy, SSL/Cloudflare, Paystack/SMTP/AI/CRM setup, backups & recovery, updating, rollback, production checklist.
- Every migration verified to roll back.

**Tests:** 26 new (239 total).

## Phase 7 — Campaign engine, CRM, email, analytics (2026-10-11)

- **Campaign engine** (Admin → Campaigns): WHEN one of 18 triggers (sign-up, order paid, first purchase, product purchased, refund, points, rewards, referrals, quiz, Wall posts, challenges, creators, AI try-on…) IF conditions (order total, lifetime spend, order count, product, colour, state, coupon, level, tags, audiences, marketing consent, creator sales) THEN actions in order: award points, create a personal coupon, unlock a reward free, tag, send email (merge fields, marketing vs service), on-site message, add to audience, set creator commission, send signed webhook. Runs once per campaign/event/customer (unique run key), per-customer caps, schedules, loop guard, failures logged without touching commerce, run log, condition tester. Registry in `config/campaigns.php`.
- **CRM layer**: every domain event → durable outbox → `outbox:dispatch` (cron, every minute) with exponential backoff and 8 attempts. Drivers: none, signed webhook, FluentCRM (contact upsert + event tags, consent-aware status). Inbound `POST /webhooks/crm` (HMAC + 5-min window, idempotent): unsubscribe/subscribe/tag/untag. Admin → Integrations: status, outbox with retry, test event, email log, incoming webhook log.
- **Email**: branded mail theme (wordmark header, black uppercase buttons); new welcome, reward-code, referral-reward and "your look is ready" (slow previews only) emails, each switchable in Settings → Emails; campaign emails with one-click unsubscribe (`List-Unsubscribe`, signed link, POST-only change); email log of every send/failure (no content stored).
- **Analytics** (Admin → Analytics): 7/30/90 days, 12 months, custom; vs previous period. Revenue (net of refunds), orders, AOV, units, checkout and bag conversion, discounts, refunds, revenue chart; customers (new accounts, first-time, repeat purchase rate, acquisition source); product, colour, creator, referral, AI, loyalty/community and campaign performance; CSV export (formula-safe).
- Customer tags (admin, campaigns, CRM) with list filter; on-site campaign messages banner.
- New events `ReferralCreated`, `CustomerUpdated`; `RedeemReward` gained a free (campaign) mode.
- Fixes found while testing: first-time-buyer counting when two orders are paid in the same second; `CRM_DRIVER=null` being read as PHP null.
- 24 new tests (213 total).

## Phase 6 — Creator programme (2026-10-10)

- Applications (`/creators/apply`): handles, audience band, city, pitch, terms; one pending at a time, re-apply 30 days after a rejection, programme can be closed in Settings.
- Approval creates a creator profile, a personal **creator code** (a coupon giving the audience a configurable discount — 0% for tracking-only), a default trackable link, a public profile page (`/creators/{slug}`) and an approval email. Rejection emails the reason.
- Attribution, server-side: `/go/{token}` records the click (session, account, hashed IP) and redirects to internal pages only; checkout stores the last valid click in `orders.attribution`. Session → account → cookie fallback, configurable window (30 days). A creator code at checkout beats any link.
- Commission ledger: one conversion per paid order (unique), commission on merchandise after discounts (never delivery), per-creator rate or programme default, campaign boosts. Pending until the hold period passes (`creators:approve-commissions`, daily), then payable. Partial refunds reduce it, full refunds/cancellations reverse it, refunds after payout create clawbacks netted from the next payout.
- Self-referral blocked (own account, email or phone; own code rejected at checkout; own clicks ignored). Suspended creators' codes and links stop earning.
- Payouts: bank details (account number encrypted, masked everywhere, reveal is audited), minimum payout, create → mark paid with transfer reference → creator email; cancel releases commissions.
- Creator dashboard (`/creator`): code, ranking this month, clicks/orders/sales/earnings by period, return-window / payable / paid balances, links with page picker, earnings ledger (no customer details), payouts, profile, campaign briefs.
- Admin → Creators: ranked creators, applications (approve with custom rate / reject with note), payouts, campaigns (brief + optional boosted rate, per product or whole order); creator page with ledger, links, rates (audited), suspend/reactivate, payout creation. Creator revenue on the dashboard; creator badge on customer records.
- Wall posts by creators are linked to their profile (`ugc_posts.creator_id`).
- Events `CreatorApproved`, `CreatorSaleRecorded`; API `GET /creator/dashboard`.
- 22 new tests (189 total).

## Phase 5 — The BeAuthentic Wall & challenges (2026-10-09)

- Wall posts (`ugc_posts`): after photo + optional before, colour/variant, caption, social handle, consent; statuses pending → approved / featured / rejected. Linked to customer, product, variant, challenge (and `creator_id`, ready for Phase 6).
- Photos re-encoded (EXIF/GPS stripped) onto the private disk; served only once approved, otherwise to the author or moderators.
- Storefront: `/community` Wall (featured first, colour filter, before/after flip), post pages with a before/after slider and "Get this look", `/community/share`, `/account/posts` (status, rejection reason, delete). "As seen on you" on product pages and a Wall section on the homepage — shown only when real approved posts exist.
- Challenges (all data): dates, hashtag, prize, entry requirements, required product (optionally purchase-gated), colour theme, entries per customer, voting with its own close time, winner bonus points. Join, enter (an entry is a moderated Wall post), vote/unvote, winner announcement.
- Points: approved post (`points.ugc`), first approved entry per challenge (`points.challenge`), winner bonus; each paid once and reversed if a moderator removes the post.
- Admin: UGC moderation (approve / reject with reason / feature / delete, bulk approve, search, challenge filter), challenge editor and entries/winner page, Settings → Community, dashboard community panel. All moderation is audited.
- Events: `UGCSubmitted`, `UGCApproved`, `ChallengeJoined`.
- API: `GET /ugc`, `GET /challenges`, `POST /ugc`, `GET /ugc/mine`; also the Phase 4 app endpoints `POST /ai/try-on`, `GET /ai/try-ons`, `GET /ai/try-ons/{id}`.
- Seed: one challenge (draft in production); local-only demo posts with generated illustrations stamped "DEMO".
- 23 new tests (167 total).

## Phase 4 — AI try-on (2026-10-08)

- Provider abstraction (`AIImageProviderInterface`) with OpenAI (`images/edits`) and Replicate (async + signed webhook) integrations, and a development-only provider that refuses to run in production. `AI_PROVIDER=disabled` shows a proper "not set up" state.
- Try-on page (upload or camera, consent, colour picker, live progress, before/after, Get this look → exact variant, share, save, try another colour on the same photo) and colour board (every colour from one photo).
- Saved looks in the account; public share pages expose the result only.
- Privacy: private disk, signed + ownership-checked image URLs, EXIF stripped, originals deleted after 60 min and unsaved results after 24 h (`ai:cleanup`, every 15 min), admins see results only.
- Cost control: guest / user / customer daily limits (failures not counted), per-IP hourly limit, per-generation cost tracking, monthly budget cap.
- Analytics: `ai_events`, purchase attribution through `orders.attribution`, admin AI dashboard (KPIs, ROI, per-colour, errors, recent results) with settings; AI revenue on the main dashboard.
- Guest previews follow the customer into their account on sign-in.
- 20 new tests (144 total).

## Phase 3 — Loyalty, rewards, referrals, colour quiz (2026-10-07)

- Points ledger (`point_accounts`, `point_transactions`): earn / spend / reverse / expire / adjust, idempotency keys, row locks, FIFO consumption, expiry after N months (scheduled `loyalty:expire`).
- Earning rules (all in Settings → Points): per ₦1,000 spent, sign-up, first order, review, UGC, challenge. Tiers (Newbie → Explorer → Trendsetter → Icon) with purchase multipliers.
- Points awarded when an order is paid; full refunds reverse them (incl. first-order bonus), partial refunds reverse a proportional share. Points shown in bag, drawer and checkout.
- Rewards catalogue: fixed / % / free delivery / free product / special product / campaign, with stock, total and per-customer limits, minimum tier, date window. Redeeming issues a personal single-use code; codes expire; marked used when the order is paid.
- Referrals: `/ref/{CODE}` landing (visits stored server-side), friend gets a personal ₦1,000-off first-order code on sign-up, referrer earns points on the friend's first paid order ≥ minimum within the window. Blocks self-referral (email/phone), repeat orders; guest checkouts attributed via `orders.attribution`; refunds and admin rejection claw points back.
- Colour quiz engine: quizzes, questions, answers, per-colour weights, outcomes with recommended product, optional contact capture; big colour reveal + share. Admin quiz builder.
- Admin: rewards (catalogue + redemptions), referrals (KPIs, reject), quiz builder, customer points & manual adjustments (admin-only, audited), Settings → Points/Referral, dashboard marketing & loyalty panel.
- API (Sanctum tokens): `POST/DELETE /auth/token`, `GET /me`, `GET /orders`, `GET /rewards`, `POST /rewards/{id}/redeem`, `GET /referrals`, `GET /quiz/{slug}`, `POST /quiz/{slug}/submit`.
- 36 new tests (124 total).

## Phase 2 — Cart, checkout, Paystack, orders (2026-10-06)

- Cart: guest carts (encrypted cookie) and account carts, merged on login; stock-capped quantities; coupons; live server-side pricing; free-delivery progress.
- Slide-out bag drawer, full cart page with recommendations, add-to-bag with sticky mobile bar.
- One-page checkout: contact, saved/new address (Nigerian states), delivery options by state, discount codes, order summary; distraction-free layout.
- `PlaceOrder`: idempotent (checkout token), recalculates totals, snapshots prices/items/address, reserves stock for the payment window.
- Paystack: initialize, server-side verify on callback, signed + idempotent webhook (`/webhooks/paystack`), amount/currency/reference checks, refunds API. No keys → honest "not configured" state.
- `PaymentConfirmation`: the only path to "paid"; row-locked and idempotent; commits stock, counts coupon use, bumps sales counts, clears the cart, fires `OrderPaid`. Late payments after expiry are reinstated if stock allows, otherwise held for review.
- Orders: `BA-YYYYMMDD-0001` numbers, status machine, timeline, notes; fulfilment (processing/shipped/delivered), cancel (releases or refunds+restocks), full/partial refunds via Paystack; scheduled expiry of unpaid orders (re-checks Paystack first).
- Emails (queued, never blocking): order confirmed, shipped, delivered, refunded — with a signed order link.
- Customer: order history, order detail/tracking page (owner or signed link).
- Admin: orders list + detail, customers list + detail (suspend/reactivate), delivery options, live sales dashboard (today / this month / 30-day revenue / colours / top products).
- API: `GET /api/v1/products`, `GET /api/v1/products/{slug}`.
- 33 new tests (88 total).

## Design v2 — retail direction (2026-10-05)

- Storefront restyled to a clean white retail look: Figtree (self-hosted) for all type, bold uppercase headings, centred letter-spaced wordmark, promo bar + two-row header, full-bleed colour-block hero, horizontal product rails, expanding colour panels with vertical titles, grey product wells, small black rectangular buttons, light four-column footer.
- Archivo / Instrument Sans removed. Hair colours still drive the accent tokens.
- Note: `design/` (the earlier canvas source) reflects the v1 editorial direction and is now superseded by `resources/css/beauthentic.css`.

## Phase 1 — Foundation (2026-10-05)

- Laravel 13, Livewire 4, Tailwind 4, Fortify. Database session/cache/queue. Private media disk.
- BeAuthentic design system ported from `design/ba.css`; fonts self-hosted at build time.
- Auth: register, login, logout, remember me, password reset, email verification, profile, password change, address book (Nigerian states).
- Roles + gates + policies; admin 404s for non-staff; suspended-account guard; security headers.
- Catalogue: colours (with accent tokens), categories, collections, products, variants, bundles, images (WebP), specs/sections, SEO fields.
- Inventory engine: ledger, reservations, commit/release/restore, bundle expansion, row locking.
- Pricing engine: base/sale price, scheduled sales and campaign rules (variant/product/colour), coupons, price history.
- Admin: dashboard (live catalogue/inventory data), products list + editor, categories/collections/colours, content pages, inventory (adjust + history), pricing (calendar, base prices, sales, coupons, history), settings, audit log.
- Storefront: home (colour-switching hero), shop (search/filters/sort in URL), collection & category pages, product page (gallery, colour selector, stock state, accordions, JSON-LD), content pages, sitemap, robots.
- Seed data: admin/staff/customer, 5 colours, 5 products, 3 bundles, Pink Week sale, welcome coupon, pages.
- 55 automated tests.
