# Creative Library (Manage · `Src\Marketing` — creatives)

**Context:** Manage portal · **Routes:** `manage.marketing.creatives.*` (`/manage/marketing/creatives`, `/creatives/angles`, `/creatives/settings`) · **Permissions:** `view-marketing` reads every tab **and** edits creatives, tags, matches and hook ideas (owner decision 2026-11-02, "everyone"); `manage-marketing` adds **Run now**, the market targets, the campaign exclude list and the name rules · **Nav:** its own **Creative Library** entry in *Sales & Marketing* (beside Traffics), with the `creative-library` SectionTabs strip: Creatives · Angles & hooks · Sync & settings. Audience insights joins as a fourth tab in phase 2.

Built 2026-11-02 (phase 1 of 6: Meta ads). It **replaces the team's separate "Hook Library"** page.

## What it does

One place to see every **video creative** — the same cut however many ads, re-uploads and (later) organic posts it ran as — with:

- every **ad id / post id** it ran as, each copyable;
- its **video numbers** for any date range, summed across those ads: hook rate, hold rate, 15-second hold, average play time, video plays, retention (p25 → p100);
- its **result line** — spend, Meta results and cost per result, our real sign-ups and cost per sign-up — and a **verdict pair per market** (Meta-based and sign-up-based, both shown: owner decision 2026-11-02);
- the **targeting** each of its ad sets ran with *during* the range (history, not today's settings);
- **tags** (angle, hook type, value prop, format, presenter, offer), notes and hook ideas.

**Angles & hooks** is the Hook Library's replacement: pick an angle → the creatives tried for it with their numbers → its untried hook ideas with a status. Two books, as the Hook Library had them: **MY** (the AI 买房 webinar — Malaysia *and* Singapore, same target) and **HK** (數據買房).

**Sync & settings** shows each source's last run and errors (credentials stripped before they are stored — a cURL timeout message ends with the full Graph URL, `access_token` and all; `Src\Marketing\Support\SecretRedactor`, applied in `FacebookAdsService`'s catch blocks and again in `MarketingSyncRunRepository::finish()`), Meta token health, **Run now**, the name rules, the RM target per market and the campaign exclude list, and the tag editor.

## How it works

- **No second Meta integration.** The numbers come from the two stores the Traffics page already reads — `meta_ad_insights` (one row per ad per day, hourly) and `meta_ad_settings` (creative, targeting; every 4 h) — see the [Marketing doc](/docs/modules_handbook/manage/meta-ads/marketing/readMe.md). Phase 1 **added the video columns to `meta_ad_insights`** rather than a parallel table, so Traffics and this page can never disagree about an ad's spend.
- **`creatives:sync`** ([`SyncCreativeLibrary`](/app/Console/Commands/Marketing/SyncCreativeLibrary.php) → [`CreativeLibrarySync`](/app/Services/Marketing/CreativeLibrarySync.php)) runs hourly at :30 and inside the shared "Sync now / Run now" job. It makes **no Graph call** — it derives three things from `meta_ad_settings`, each pass fail-soft:
  1. **targeting snapshots** — a new `ad_targeting_snapshots` row only when an ad set's *parsed* targeting changes (fingerprint: `TargetingParser::hash`); the previous row gets `valid_to`. An ad set's **first** snapshot is dated from Meta's own `updated_time` (any edit moves it, so the targeting held since then); before that the targeting is **unknown** and the drawer says so;
  2. **placements** — every ad whose creative has a `video_id` becomes a `creative_placements` row (image / carousel ads are left out). Its **market** is the one country of ours its ad set targets — countries ∪ the country on each region and city, because most of these ad sets target *cities only* — else null; the HK landing domain (`propertylabglobal.com`) is the fallback;
  3. **auto-matching** — an unmatched placement joins a creative when its **video id** already belongs to exactly one creative (a re-used upload IS the same creative), else when an active **name rule** claims it. New placements otherwise land in the **Untagged** inbox.
  4. **video lengths** — `GET /{video-id}?fields=length` for each video a creative owns or that delivered in the last 30 days, stored as `creative_placements.video_length_secs` (rounded). **One video per call, trying every token** (`FacebookAdsService::videoLength`): most of our videos are owned by the Facebook Page, not the ad account, and Graph's `?ids=` batch fails whole (code 10) on the first one a token cannot see — probed 2026-11-03, the first token refused 7 of 12, the three tokens together read all 41 recently delivered videos. A video **every** token is refused (code 10 / 100 / 200) is cached as a miss for 7 days (`creatives:video-length-miss:{id}`); a timeout or 5xx is NOT cached, it is simply asked again next run. A **rate limit** (`FacebookAdsService::RATE_LIMIT_CODES`) stops the pass for that run and nothing is cached. **25 videos per run** at most (was 100 until 2026-11-10: each video can cost one call per token, and they share the tokens' quota with the hourly insights sync, so the first-run backlog now drains over a few hours instead of in one burst). The only pass that calls Meta.
  5. **blanks** — a creative with no `language` or `length_seconds` gets one: length = its videos' most common length; language = [`LanguageGuesser`](/src/Marketing/Support/LanguageGuesser.php) over its ads' captions, headlines and names (a Cantonese-only character such as 唔 / 嘅 / 喺 → Cantonese; else Simplified vs Traditional characters, Traditional → Cantonese; no Chinese → English; undecided → the market's language). Only blanks are filled, so a person's choice is never overwritten — but a field cleared by hand is refilled on the next run. It is the **written** language: an ad captioned in Simplified Chinese may still be spoken in Cantonese, so it stays editable. The Untagged rows carry the same guess + length, and *New creative from this video* pre-fills both.
  - The **video opening** is not detected yet: it needs the video file, and `source` is withheld for Page-owned videos with the ads token (only 5 of 954 of our videos are ad-account uploads). Reading it with the stored Page token, then Gemini on the first seconds (spoken + on-screen text), is a Phase 6 candidate.
- **Name rules** ([`CreativeMatchRule::nameMatches`](/src/Marketing/CreativeMatchRule.php)): case- and spacing-insensitive "contains", and a pattern ending in a digit may not run on into another digit — "vid 4" matches "vid 4 - 假offer", never "vid 40". Optional campaign-name pattern.
- **The read side** is [`CreativeLibraryService`](/app/Services/Marketing/CreativeLibraryService.php): `cards()`, `untagged()`, `detail()`, `untaggedDetail()`, `angles()`. `detail()` and `untaggedDetail()` share one `placementsDetail()` (ads with their numbers, copy, audience, trend), and cards and inbox rows share one `verdicts()`, so a video reads the same before and after it becomes a creative. Every figure is **summed raw counts → rate** through [`CreativeMetrics`](/src/Marketing/Support/CreativeMetrics.php) — a card is the sum of its placements, never an average of their rates.
- **Real sign-ups / buyers / revenue** per ad come from Traffics' own attribution, untouched: `AdPerformanceService::rollup('ad', …)` (sign-ups carrying the ad id; first-touch new-lead cohort for buyers and revenue). Nothing of ours is stored per placement — cohort revenue keeps rising, a stored copy would go stale.
- **Exclusions** are applied at READ time (case-insensitive "contains" on the campaign name), so changing the list on Sync & settings takes effect at once. Default: `新盘Summary`, `Webinar新盘Summary`, `Post - Engagement`.
- **Filters and sort** on the Creatives tab run client-side over the cards (a few hundred at most) and are mirrored into the URL; only the date range goes back to the server.
  - **Search** (`?q=`) matches ad / post IDs, video IDs, ad names, the creative key ("creative ID", e.g. `MY-vid-4`), title, copy and tag names, case-insensitively. It sits above both views and filters the Untagged inbox too, so an ad no creative owns yet is still found; when the Creatives view has no match but Untagged does, it offers the jump. The inbox only carries its top 150 videos by spend, so a search there covers those.
  - **An Untagged video opens the same drawer** as a creative (`GET creatives/untagged/{key}`, the key being the video id or `ad:{ad id}`): the same five sections, with verdicts on the inbox row too. Its toolbar swaps Edit / Delete for *New creative from this video* / *Link to a creative* (`Partials/UntaggedActions.vue`, shared with the inbox row); *Video & copy* has no opening / hook line yet and *Tags, notes & ideas* waits until it is a creative. Linking it closes the drawer — the video has left the inbox. 404 once linked.
  - **Bulk edit** — every card and inbox row has a tick box; ticking one shows a bar pinned to the bottom of the screen (`Partials/BulkBar.vue`) with *Select all N shown* / *Clear*. **Creatives:** *Edit N creatives* opens `Partials/CreativeBulkModal.vue` — status, market and language start at "Leave as is" and only what is changed is sent; tags are **added or removed, never replaced** (`PUT creatives/bulk` → `CreativeRepository::updateMany()`, which uses `syncWithoutDetaching` / `detach` — `update()` replaces the whole tag set and would wipe tags the edit never mentioned). The remove list shows only tags on the selection, with how many of them carry each. **Untagged:** *New creative from these videos* opens the usual create form with every ad of every ticked video (market, language and length pre-filled only when all the videos agree), or *Link all to a creative…* posts them to `placements/assign` in one go. A selection survives filtering; anything that leaves the page after a write (a linked video) drops out of it.
  - **Tagging in the create / edit modal** (`Partials/CreativeForm.vue`) lists **every** tag type, each with its own **+ Add**, even when the vocabulary has none for it yet. Angles belong to a market (MY angles also serve SG), so the picker shows only the creative's market's angles — plus any tag already on the creative. Angles from **other** markets are not chips, but **Use an existing angle…** (a picker beside *+ Add*) ticks one, so an HK creative can reuse an MY angle instead of retyping it; once ticked it shows as a chip. *+ Add* posts to `creatives/tags` (an angle takes the creative's market; every other type is shared, market NULL) and ticks the new tag; a name that already exists is just ticked. ⚠️ The block used to hide itself when nothing matched, so an HK creative — with only MY angles in the library — could not be tagged at all (fixed 2026-11-03).
  - **Watch the ad** — every placement keeps a `permalink` (the Instagram post when Meta gives one, else the ad's Facebook preview link). *Video & copy* links the first; *Where it ran* links each ad.
  - **Sorts**, best first: Spend, Hook (3s), Hold, Results, Sign-ups, Cost per result (low first), Cost per real sign-up (low first), Newest. Cards and Untagged rows show cost per Meta result and cost per real sign-up side by side. A rate that is n/a sinks to the bottom instead of ranking as 0. Rates on tiny samples rank high, so pair a rate sort with *Min impressions*.

### The metric definitions (Meta, Graph v25.0 — checked live 2026-11-02)

| Figure | Formula | Meta source |
|---|---|---|
| Hook rate (3s) | % of video plays still watching at second 3, whole percents (a range: Σ(curve point × plays) ÷ Σ plays, rounded) | Ads Manager's own figure. `video_play_curve_actions[3]`, stored per ad-day as `video_curve_3s_pct` |
| Hold rate | plays to 100% ÷ (video plays × hook rate) | Ads Manager's own figure. `video_p100_watched_actions` over the same days |
| 3s ÷ impressions | 3-second plays ÷ impressions | `actions[video_view]` — no separate 3-second field. The old Hook Library's "hook rate"; drawer |
| 15s hold | ThruPlays ÷ impressions | (the Hook Library's figure; drawer) |
| Avg play | Σ(avg × video plays) ÷ Σ video plays | `video_avg_time_watched_actions` — **whole seconds per day**, so a summed figure matches Ads Manager to about a second |
| Video plays | sum | `video_play_actions` (every start) |
| Retention pX | pX plays ÷ 3-second plays | `video_pXX_watched_actions` (can exceed 100 % for a video under 12 s) |
| Cost per result | spend ÷ Meta results | `meta_leads` — Ads Manager's "Results" |
| Cost per sign-up | spend ÷ our landing sign-ups with the ad id | `LandingSignups::countBy('ad_id')` |

- ⚠️ **"n/a", never 0.** A rate is `null` when its count is missing (an image ad, a platform without the count — Instagram has no 3-second plays) or there is nothing to divide by. Every video column on `meta_ad_insights` is nullable for exactly this; the sync stores NULL when Graph returned **no** video field for the ad-day, and 0 for the missing ones when it returned at least one.
- ⚠️ **Hook and Hold are Ads Manager's, not the formulas you find online (2026-11-04).** Meta's Video performance panel shows both but Graph has no such fields (`hook_rate` is refused), so they are rebuilt. The formulas were worked out from one ad's panel (120250534394440194, 6 Oct – 4 Nov: 48% and 10.79%, reproduced exactly); this page first used 3-second plays ÷ impressions and ThruPlays ÷ 3-second plays, which read 44.6% and 51.6% for that ad.
- ⚠️ **Hook can sit 1 point from Ads Manager on a multi-day range.** Meta gives the curve only as whole percents, and we store days, so a range is a plays-weighted mean of rounded points: 36 of 42 ads matched Meta's range figure exactly, 6 were 1 point off (2026-11-04); Hold follows it. A single day is exact. **A creative with several ads has no one Ads Manager figure to compare** — compare the per-ad rows under *Where it ran*.
- ⚠️ **After deploying the curve column, re-sync history** (`php artisan meta:sync-ad-insights --since=2026-03-03`): days without a curve read n/a for Hook and Hold.
- ⚠️ **`view_rate` / `hold15`'s denominator is `video_impressions`** — impressions on ad-days that carry video figures. Days stored before the video columns existed would otherwise sit in the denominator with no plays and drag the rate down. Re-sync history with `--since` to fill them.
- **Hook windows never mix.** Meta counts 3-second plays, TikTok 2-second (`CreativePlacement::PLATFORMS[*]['hook_window']`); every hook-rate label carries its window. Phase 1 has only Meta.
- **Rankings** (`quality_ranking`, `engagement_rate_ranking`, `conversion_rate_ranking`) are labels, stored per day and never summed; the drawer shows each ad's latest non-null one in the range. `UNKNOWN` (under ~500 impressions) is stored as null.

### Verdict

Per creative **per market** (each market has its own target; a cheap HK result must not rescue a dear MY one), twice — on Meta results and on real sign-ups:

`spend < 3 × target` → **Too early** · cost ≤ target → **Beats target** · cost ≤ 1.5 × target → **Near target** · otherwise, or nothing back at all → **Misses target**.

Targets default to MY RM40, SG RM40 (same AI 买房 webinar), HK RM100 (`Creative::DEFAULT_TARGETS`), editable on Sync & settings (`settings` key `creatives.market_targets`). The ad account bills in MYR, HK ads included, so the RM targets compare directly.

### Sync resilience (2026-11-02)

Adding the video fields made Meta slow enough to refuse some ad-level windows with code 1 ("An unknown error occurred") or 2 ("Service temporarily unavailable") — 8 of 16 weekly slices on the first backfill. `meta:sync-ad-insights` now **retries** a transient refusal twice with a back-off, then **splits the window in half** (down to single days), and the page size dropped from 500 to 200. The re-run backfill split 10 of 16 weekly windows and every half succeeded (1,019 ad-days, 0 failures), so `SLICE_DAYS` dropped from 7 to **3** — the hourly run asks for a size that works first time instead of burning three slow refusals per window. Non-transient errors (a bad token) fail at once as before. **Rate limits are not transient** (2026-11-10): codes 4 / 17 / 32 / 613 / 80000 / 80004 are neither retried nor split — that multiplied the very calls Meta was refusing — and the throttled account's remaining windows wait for the next hourly run. See the [Marketing doc](/docs/modules_handbook/manage/meta-ads/marketing/readMe.md#scheduling).

## The Hook Library import

`php artisan creatives:import-hook-library {file} [--dry-run]` ([`HookLibraryImporter`](/app/Services/Marketing/HookLibraryImporter.php)). The file is the Hook Library page's own database: `angles`, `hooks` (kind `tried` / `idea`) and `meta` (`targets`), as objects keyed by id or lists of `{id, …}`. It refreshes placements first, imports, then re-runs auto-matching; `--dry-run` rolls everything back and prints the report.

- angle → an **Angle tag** in its market; tried hook → a **creative** keyed `{market}-{video slug}` (a short hash of the full name is appended when the name has non-ASCII text — "vid 2 - 设施迷思" and "vid 2 - 无本生利" would otherwise share `MY-vid-2`), keeping `videoOpening` → video opening, `captionHook` → hook line, `videoLen`, `note`; idea → a **hook idea** (status words mapped, `addedBy: "AI"` → `is_ai`).
- **Linking ads:** exact ad name first; a looser "contains" match only when it points at ONE distinct ad name — otherwise it is **reported, not guessed**. A name rule is saved for future ads.
- The Hook Library's own numbers (`m`, `adsets`) are **not** imported; they are recomputed.
- Its targets are carried over only when none are saved yet. Idempotent: a second run creates nothing.

## Tables

All machine-owned stores are plain models (no uuid / blame / soft delete); the person-authored ones carry them. No schema-level FKs.

| Table | One row per | Notes |
|---|---|---|
| `creatives` | creative | uuid + blame + soft delete. `creative_key` unique (team-set, e.g. `MY-vid4-v2`), `market` MY/SG/HK, `language`, `length_seconds`, `hook_line`, `video_opening`, `status` (Live / Paused / Retired), `notes`, optional `thumbnail_url` override (else the latest placement's — an expiring CDN link refreshed every settings sync). Deleting one sends its placements back to Untagged, drops its name rules and unpins its ideas. |
| `creative_placements` | ad / post on a platform | unique `(platform, object_id)`. `creative_id` NULL = Untagged. Denormalised `campaign_*`, `group_*` (ad set), `name`, `caption`, `headline`, `cta`, `landing_url`, `permalink`, `thumbnail_url`, `market` — refreshed every sync, never `creative_id` / `matched_*`. `matched_by`: video id / name rule / by hand / import. `video_length_secs` (pass 4; NULL = unknown) is not a SYNCED column, so the upsert never clears it. |
| `ad_targeting_snapshots` | period of one ad set's targeting | `valid_from` / `valid_to` (NULL = current), `targeting_hash`, `raw`, parsed `countries`, `locations`, `age_min/max`, `genders`, `languages`, `interests`, audiences in/out, `advantage_audience`, one-line `summary`. |
| `creative_tags` + `creative_tag_links` | tag / creative↔tag | `type` (Angle, Hook type, Value prop, Format, Presenter, Offer). Angles carry `market`, `name_en`, `description`, `why`, `sort_order`. Deleting an angle soft-deletes its ideas. |
| `hook_ideas` | idea | uuid + blame + soft delete. `angle_tag_id`, `hook_line`, `why`, `status` (Idea → Dropped), `is_ai`, `linked_creative_id`. |
| `creative_match_rules` | rule | `name_pattern`, optional `campaign_pattern`, `is_active`. |
| `marketing_sync_runs` | run of a sync source | `source` (Meta insights / Meta settings / Creative Library), `status` (Running / OK / Partly failed / Failed), rows, failures, up to 20 `errors`. Written by the three commands through the `RecordsSyncRun` trait — bookkeeping never fails a sync. |
| `meta_ad_insights` (+14 columns) | ad per day | `video_3s_plays`, `video_plays`, `thruplays`, `video_p25…p100`, `video_avg_watch_secs`, `video_curve_3s_pct`, `landing_page_views`, three rankings — all nullable. |

## Later phases

2 Audience insights (heatmap + delivered breakdowns by age / gender / region / placement, `audience_segments`) · 3 Facebook Page & Instagram organic (needs `read_insights`, `instagram_basic`, `instagram_manage_insights`, `pages_read_user_content` — not in today's OAuth scopes) · 4 TikTok ads (a new TikTok connection module — none exists) · 5 TikTok organic · 6 AI helpers ("Generate 5 hooks" via `AiClient`).

## Related files

**Backend**
- Models: [`src/Marketing/Creative.php`](/src/Marketing/Creative.php) (`STATUSES`, `MARKETS`, `DEFAULT_TARGETS`, `LANGUAGES`, `targets()`, `targetFor()`, `suggestKey()`) · [`CreativePlacement.php`](/src/Marketing/CreativePlacement.php) (`PLATFORMS` with hook windows, `MATCHES`) · [`CreativeTag.php`](/src/Marketing/CreativeTag.php) · [`HookIdea.php`](/src/Marketing/HookIdea.php) · [`CreativeMatchRule.php`](/src/Marketing/CreativeMatchRule.php) (`nameMatches()`, `claims()`) · [`AdTargetingSnapshot.php`](/src/Marketing/AdTargetingSnapshot.php) · [`MarketingSyncRun.php`](/src/Marketing/MarketingSyncRun.php)
- Pure helpers: [`src/Marketing/Support/CreativeMetrics.php`](/src/Marketing/Support/CreativeMetrics.php) · [`TargetingParser.php`](/src/Marketing/Support/TargetingParser.php) · [`LanguageGuesser.php`](/src/Marketing/Support/LanguageGuesser.php)
- Repositories + facades (`src/Marketing/Repositories`, `src/Marketing/Facades`): `CreativeRepository`, `CreativePlacementRepository`, `AdTargetingSnapshotRepository`, `CreativeTagRepository`, `HookIdeaRepository`, `CreativeMatchRuleRepository`, `MarketingSyncRunRepository`
- Services: [`app/Services/Marketing/CreativeLibrarySync.php`](/app/Services/Marketing/CreativeLibrarySync.php) · [`CreativeLibraryService.php`](/app/Services/Marketing/CreativeLibraryService.php) · [`HookLibraryImporter.php`](/app/Services/Marketing/HookLibraryImporter.php)
- Commands: [`SyncCreativeLibrary`](/app/Console/Commands/Marketing/SyncCreativeLibrary.php) (`creatives:sync`, Kernel hourly at :30) · [`ImportHookLibrary`](/app/Console/Commands/Marketing/ImportHookLibrary.php) · trait [`Concerns/RecordsSyncRun`](/app/Console/Commands/Marketing/Concerns/RecordsSyncRun.php) (also used by `meta:sync-ad-insights` / `meta:sync-ad-settings`)
- Controllers (`app/Http/Controllers/Manage/Marketing`): `CreativesController` (index, show = drawer JSON, showUntagged = the same for an inbox video, store, update, destroy, assign) · `CreativeAnglesController` · `CreativeIdeasController` · `CreativeTagsController` · `CreativeSettingsController` (index, update, sync, storeRule, destroyRule) · trait `Concerns/CreativeLibraryProps` (vocabulary from the model constants, tag + creative options) · shared [`app/Http/Controllers/Concerns/ResolvesDateWindow.php`](/app/Http/Controllers/Concerns/ResolvesDateWindow.php) (`?from=&to=` + rolling fallback; Traffics uses it too)
- Form requests: `app/Http/Requests/Manage/Marketing/Creatives/` — `StoreRequest`, `UpdateRequest`, `AssignRequest`, `RuleRequest`, `TagRequest`, `IdeaRequest`, `SettingsRequest`
- Settings keys: `Setting::CREATIVE_MARKET_TARGETS`, `Setting::CREATIVE_EXCLUDED_CAMPAIGNS`

**Frontend**
- Pages: `resources/js/Pages/Manage/Marketing/Creatives/Index.vue` · `Angles.vue` · `Settings.vue`
- Partials (`…/Creatives/Partials/`): `CreativeCard`, `CreativeDrawer` (5 sections), `CreativeForm` + `CreativeFormModal`, `UntaggedInbox` + `UntaggedActions`, `IdStrip`, `VerdictChip`, `RangeBar`
- `resources/js/utils/creativeFormat.js` (rates as fractions → "42.1%" / "n/a") · `Components/SectionTabs.vue` (`creative-library`) · `Layouts/ManageLayout.vue` (nav entry)

**Migrations** — `2026_11_02_100001_add_video_metrics_to_meta_ad_insights` · `2026_11_02_100002_create_creative_library_tables` · `2026_11_02_100003_create_ad_targeting_snapshots_table` · `2026_11_02_100004_create_marketing_sync_runs_table`

**Routes** — `routes/web.php`, the `creatives.` group inside `manage.marketing.` (literal GETs before `{id}`).

**Tests** — `tests/Unit/Marketing/CreativeMetricsTest.php` · `TargetingParserTest.php` · `LanguageGuesserTest.php` · `tests/Feature/Marketing/CreativeLibraryTest.php` (placements + market, auto-match incl. "vid 4" ≠ "vid 40", snapshot only on change, card = sum of placements + per-market verdict + exclusions, import twice, page, video length read once + blanks-only fill, a rate limit stops the length pass without caching a miss, a sync run never stores an access token, untagged drawer) · `SyncMetaAdInsightsTest.php` (video counts from a recorded Graph row, image ad stays n/a, transient refusal retried then split, rate limit neither retried nor split) · `resources/js/Pages/Manage/Marketing/Creatives/Partials/CreativeForm.test.js` (a market with no angles can still add one, or reuse another market's) · `CreativeLibraryTest::test_a_bulk_edit_sets_only_the_chosen_fields_and_adds_or_removes_tags`.
