# Hot Deals — Configuration in Admin Console

How a Hot Deal is configured in the admin console (console v2), where each setting is stored, and how it reaches the member-facing booking engine (WordPress / PHP).

State as of branch `dev` @ `cebea046` (2026-10-26).

---

## 1. Big picture

There is no standalone Hot Deals screen anymore. A Hot Deal is a **Member Offer** with `offer_type = HOT_DEAL`. Everything is edited in the Member Offer editor and saved through the member-offers API.

```
Admin Console (/admin/member-offers/:offerId)
   │  Configuration tab ─┐
   │  Travel Rules tab ──┼── one PUT/POST payload
   │  Content tab ───────┘
   ▼
apps/core  /v1/admin-console/member-offers   (MemberOfferController)
   │
   ▼
Postgres
   member_offers         ← typed columns + raw_config (jsonb)
   member_offer_units    ← one row per eligible resort unit
   │
   ▼
apps/core public feeds (x-api-key = WP_HOT_DEALS_API_KEY)
   GET /v1/public/hot-deals      → booking-engine deal JSON
   GET /v1/public/travel-rules   → { resort → unit_code → Rule[] }
   │
   ▼
PHP plugin karma-club-member
   booking_engine_get_offers()           → /v1/public/hot-deals
   internal_exchange_get_travel_rules()  → /v1/public/travel-rules
   (WP transient cache, default 300 s; falls back to legacy WP option on failure)
```

### Two storage layers

| Layer | What lives there | Why |
|---|---|---|
| Typed columns on `member_offers` / `member_offer_units` | Name, type, resort, booking & travel windows, eligibility, EDMs, publish state, per-unit values | Queryable, validated, used for filtering and publish rules |
| `member_offers.raw_config` (jsonb) | Every legacy booking-engine field with no column: calculation mode, nights, occupancy, flat price, label, media, `master_info`, `roles`, and `travel_rules` | The legacy deal JSON is deeply nested and variable-shape. One jsonb column keeps a lossless round-trip with the shape PHP expects |

Migration: `apps/core/src/internal/datastore/migrations/20260721000000_add_hot_deals_raw_config.ts`.

---

## 2. Key files

**Admin console (`apps/admin-console/src`)**

| File | Role |
|---|---|
| `routes/member-offers/_client.tsx` | List page |
| `routes/member-offers/$offerId/page.tsx` | Loader: RBAC check (`member-offers`), loads offer, resorts, EDM templates, account types/statuses, clubs, eligible units. Dev instance forces read-only |
| `routes/member-offers/$offerId/_client.tsx` | Editor shell. Owns all state, builds the save payload (`buildPayload`), handles save/publish/unpublish/archive/delete |
| `routes/member-offers/_components/OfferConfigurationTab.tsx` | Configuration tab (sections 1–3, inclusions, Hot Deal Settings, publishing, eligibility) |
| `routes/member-offers/_components/OfferTravelRulesTab.tsx` | Travel Rules tab (HOT_DEAL only) |
| `routes/member-offers/_components/OfferContentTab.tsx` | Content tab (description, T&Cs, EDMs, `master_info`) |
| `lib/features/member-offers/types.ts` | `MemberOffer`, `UpsertMemberOfferInput` |
| `lib/features/hot-deals/*`, `lib/features/travel-rules/*` | Leftovers from the old standalone screens. Not used by the editor |

**Core API (`apps/core/src`)**

| File | Role |
|---|---|
| `routes/member-offers/member-offers.route.ts` | Admin routes, RBAC slug `member-offers` |
| `controllers/admin/member-offers/member-offers.controller.ts` | CRUD, publish, archive, duplicate, content-writer restriction |
| `controllers/admin/hot-deals/hot-deals.controller.ts` | Public feeds (`/v1/public/hot-deals*`, `/v1/public/travel-rules`) + `mergeRawConfigIntoDeal()` |
| `v1/services/admin/hot-deals/hot-deals.service.ts` | Legacy admin hot-deals API (`/v1/admin-console/hot-deals`) that reads/writes deals in the old JSON shape |
| `internal/queue/scheduled-offers.worker.ts` | Flips `SCHEDULED` → `PUBLISHED` (runs every 60 s from `cmd/services.ts`) |
| `cmd/import-hot-deals.ts` | One-off importer: wipes HOT_DEAL/EXCLUSIVE_DISCOVERY offers and re-seeds from `hot-deals-booking-engine.json` + `hot-deals-travel-rules.json` |

**Reference specs (shape PHP expects):** `apps/core/hot-deals-booking-engine.json`, `apps/core/hot-deals-travel-rules.json`.

---

## 3. Editor tabs and where each field is stored

Tabs: **Configuration**, **Travel Rules** (shown only when type is Hot Deal), **Content** (disabled until the offer is first saved).

All three tabs edit the same React state. One **Save Changes** sends everything in one request; there is no per-tab save.

### 3.1 Configuration tab

#### Section 1 — Offer Basics

| UI field | Stored in | Notes |
|---|---|---|
| Offer Name | `member_offers.name` | Required |
| Offer Type | `offer_type` | `HOT_DEAL` / `EXCLUSIVE_DISCOVERY`. Locked after creation |
| Target Resort | `resort_id` | Changing it clears the unit list and reloads eligible units |
| Is Active & Bookable | `is_active` | Public feeds only return `is_active = true` |
| Is Cancellable | `is_cancellable` | Stored only; not emitted to PHP |

#### Section 2 — Booking & Travel Timeline

| UI field | Stored in | Emitted to PHP as |
|---|---|---|
| Booking Window start / end | `booking_period_start` / `booking_period_end` | `starts` = `YYYY-MM-DD 00:00:00`, `expires` = `YYYY-MM-DD 23:59:59` |
| Travel Window start / end | `travel_period_start` / `travel_period_end` | `travel_between: [[start, end]]` |

All four are required on create. The UI warns (does not block) when booking ends after travel starts.

#### Section 3 — Eligible Accommodations & Offer Values

One row per resort unit. Rows come from `GET /v1/admin-console/resorts/:id/units/eligible?offerType=…`; a unit is pre-ticked when the resort unit has `eligible_for_hot_deals = true`.

| Column | Stored in `member_offer_units` |
|---|---|
| Eligible (checkbox) | Only ticked rows are saved |
| Value Type | `offer_value_type` (`PERCENTAGE` / `POINTS`) |
| Value | `offer_value` (**required on every unit to publish**) |
| Min Nights / Max Nights | `minimum_nights` / `maximum_nights_per_booking` |
| Max Units/Mbr | `maximum_units_per_membership` |

Editing any cell sets `is_admin_override = true`. On save, all unit rows for the offer are deleted and re-inserted.

The ticked units' `unit_vp_code`s become:
- the `unit_code` list in the PHP deal JSON, and
- the unit keys in the Travel Rules tab.

#### What's Included

Rich text → `member_offers.inclusions`. HTML is stripped to plain text for PHP.

#### Hot Deal Settings (HOT_DEAL only) → all in `raw_config`

| UI field | `raw_config` key | Notes |
|---|---|---|
| Calculation Mode | `calculation_mode` | `phase-3` / `standard`. UI shows `phase-3` if unset |
| Phase 3 Min / Max Nights | `phase_3_min_night` / `phase_3_max_night` | UI shows 3 / 7 if unset |
| Allow Breakdown | `allow_breakdown` | |
| Weekly | `weekly` | |
| Nights | `night` | Default stay length. Feed falls back to 7 |
| Occupancy up to | `occ_up_to` | Feed falls back to 6 |
| Flat Price | `price` | 0 for percentage deals |
| Label By | `label_by` | `pay_hot_deal` / `exclusive_offer` |
| Deal Type | `type` | Empty = standard; `exclusive_offer` |
| Min / Max Date | `min_date` / `max_date` | Open-ended nightly deals (e.g. Jimbaran / Kandara) |
| Show "New" badge | `new` | Saved as `"new"` or `""` |
| Thumbnail URL | `thumbnail` | Feed falls back to resort `cover_image` |
| Destination Profile URL | `destination_profile_url` | Feed falls back to resort `website_url` |
| Inclusions cost min nights | `inclusions_cost_min_nights` | |
| Inclusions cost at bottom | `inclusions_cost_bottom` | |
| Simple Roles | `roles` | Comma-separated strings (e.g. `type_krr, contract_kc_elite`). Complex `{and:[…]}` entries already in the array are kept |

> The UI shows a default for Calculation Mode and Phase 3 nights, but nothing is written to `raw_config` until the admin changes the field.

#### Publishing Settings

| Mode | Effect |
|---|---|
| Save as Draft | `publish_mode = DRAFT`. Hidden from feeds |
| Schedule Later | `publish_mode = SCHEDULED` + `scheduled_publish_at`. Worker publishes within ~60 s of the time |
| Publish Now | `publish_mode = PUBLISHED`, `published_at = now` |

#### Eligibility Rules

| UI field | Stored in |
|---|---|
| Blocked Account Types | `blocked_account_types` |
| Blocked Account Statuses | `blocked_account_statuses` |
| Blocked Clubs | `blocked_clubs` |
| Allowed User Types | `allowed_user_types` (`LEGAL_OWNER` / `FAMILY_MEMBER` / `GUEST`) |

Option lists come from the member DB (`member_account_types`, `member_account_statuses`, `membership_clubs`).

### 3.2 Travel Rules tab (HOT_DEAL only) → `raw_config.travel_rules`

Shape stored on the offer:

```json
{
  "travel_rules": {
    "<unit_code>": [ Rule, Rule, ... ]
  }
}
```

The resort level is not stored here. The public feed nests it under the offer's resort name, which recreates the legacy `internal_exchange_travel_rules` shape `{ resortName: { unitCode: Rule[] } }`.

The unit selector lists the ticked units from Section 3, plus any unit keys already stored (so rules for a removed unit stay reachable).

Fields per Rule:

| Group | Keys |
|---|---|
| Acceptance flags | `unit_points.accept_early_bird`, `accept_late_break`, `accept_peaks` |
| Constraints | `min_nights`, `max_nights`, `max_occ`, `confirm_from`, `confirm_to`, `hot_deal_type`, `rule_id`, `booking_caption`, `with_checkin_day`, `expose_option` |
| Roles | `roles` (strings + preserved complex conditions) |
| Dates | `travel_between: [[start, end], ...]` |
| Season point-tiers | `unit_points.<period>.<white\|blue\|red>`, where period is `daily`, `weekly`, `short_break_3/4`, `nights_1`…`nights_7` |
| Plus pay | `unit_points.plus_pay` = `{ currency, price }` or `{ currency, price: { under_ages: { adult, <age>: … } } }` |
| T&Cs | `terms_conditions` |
| Advanced (raw JSON) | Edits the whole Rule object. Use it for `override`, plus-pay peak dates, check-in days, and anything else without a field |

### 3.3 Content tab

| UI field | Stored in |
|---|---|
| Description | `member_offers.description` |
| Terms & Conditions | `terms_and_conditions` |
| Confirmation / Cancellation EDM templates | `confirmation_edm_template_ids` / `cancellation_edm_template_ids` |
| Tagline, Title, Price Label, Travel Dates Text, Booking Notes, Popup URL, Check-in, Check-out, Details bullets (HOT_DEAL only) | `raw_config.master_info.{tagline,title,price,travel,booking,popup_url,check_in,check_out,details[]}` |

---

## 4. Save, publish and workflow rules (backend)

Handled in `member-offers.controller.ts`.

**Create** (`POST /member-offers`): requires `name`, `offer_type`, `resort_id`, both booking dates and both travel dates. `raw_config` is stored as sent; there is no schema validation on it.

**Update** (`PUT /member-offers/:id`): only fields present in the body are changed; `raw_config` is replaced as a whole (the editor always sends the full object).

**Content-writer restriction:** when the caller is not a super admin, and a workflow task exists whose assignor is someone else, any change to a config field returns 403. Config fields: `offer_type`, `resort_id`, all four dates, the three blocked lists, `allowed_user_types`, both EDM lists, `is_active`, `is_cancellable`, `publish_mode`, `scheduled_publish_at`, `raw_config`, and any `unit_offers` change.

**Publish checks** (Publish Now button, or saving with mode PUBLISHED/SCHEDULED):
1. At least one unit is configured.
2. Every unit has an `offer_value`.
3. Non-super-admins: the workflow task for the offer must be `VERIFIED`.

**Other actions**
- Delete: drafts only.
- Archive: sets `ARCHIVED`. Archived offers are read-only and cannot be re-published.
- Unpublish: re-saves the current payload with `publish_mode = DRAFT`.
- Duplicate: copies columns and unit rows into a new DRAFT named `… (Copy)`.

---

## 5. How the config reaches PHP

### `GET /v1/public/hot-deals`

Returns `{ [offerId]: deal }` for every `PUBLISHED` + `is_active` offer of type HOT_DEAL or EXCLUSIVE_DISCOVERY. No date filter; PHP applies `starts` / `expires`.

Each deal is built by `mergeRawConfigIntoDeal(derived, raw_config)`:

1. **Derived defaults** from columns and the joined resort: `resort`, `starts`, `expires`, `travel_between`, `roles` (= `allowed_user_types`), `unit_code`, `night: 7`, `occ_up_to: 6`, `type`, stripped `inclusions` / `terms_conditions`, resort `thumbnail` / `destination_profile_url`, and a generated `master_info`.
2. **`raw_config` spread on top** (except `travel_rules` and `occp_price`, which are removed). Admin-entered values win.
3. **`master_info` is shallow-merged**: missing keys keep the derived value.
4. **Columns win back** for `resort`, `unit_code`, `starts`, `expires` and `travel_between` (when set), so these always follow the Configuration tab.

Precedence summary:

| Field | Source of truth |
|---|---|
| resort, unit_code, starts, expires, travel_between | Columns (Configuration tab sections 1–3) |
| roles | `raw_config.roles` if set, else `allowed_user_types` |
| night, occ_up_to, thumbnail, destination_profile_url, type | `raw_config` if set, else derived default |
| master_info.* | `raw_config.master_info.*` per key, else derived |
| Everything else in Hot Deal Settings | `raw_config` only |

### `GET /v1/public/travel-rules`

Reads `raw_config.travel_rules` from every published, active HOT_DEAL / EXCLUSIVE_DISCOVERY offer and returns `{ resortName: { unitCode: Rule[] } }`. If two offers define rules for the same resort + unit, their rule arrays are **concatenated**, not replaced.

### Other public endpoints

`/v1/public/hot-deals/list`, `/detail/:id` and `/regions` filter by today's date against the booking window (override with `test_date` / `bypass_roles=1`). They build their response from columns only and **do not read `raw_config`**.

### PHP caching

The plugin caches each feed in a WP transient (`karma_hot_deals_offers`, `karma_travel_rules`), TTL `karma_core_api_cache_ttl` (default 300 s). Console changes can take up to that long to appear. If the API call fails, PHP falls back to the legacy WP option.

---

## 6. Known gaps and risks

Found while writing this document. Not fixed.

1. **Duplicate drops `raw_config`.** `DuplicateMemberOffer` does not copy `raw_config`, so the copy loses all Hot Deal Settings, `master_info` and travel rules.
2. **Content writers cannot edit Hot Deal content.** `master_info` (Content tab) lives in `raw_config`, which is on the config-field list. A restricted content writer editing tagline or title gets a 403.
3. **Availability API does not read the DB.** `/v1/availability/units-hot-deal` and `/units/options-hot-deal` load deals from a static `hot-deals.json` file (`HOT_DEALS_PATH`, cached in memory), not from `member_offers`. Console edits do not affect it.
4. **Eligibility columns are not sent to PHP.** `blocked_account_types`, `blocked_account_statuses`, `blocked_clubs` and `is_cancellable` are stored but not included in `/v1/public/hot-deals`.
5. **`raw_config.roles` silently overrides Allowed User Types** in the feed once any simple role is entered.
6. **Publish requires `offer_value` on every unit**, even when the deal's pricing really comes from travel rules / `price`.
7. **Displayed defaults are not saved** (Calculation Mode `phase-3`, Phase 3 nights 3 / 7). PHP sees no value unless the admin touches the field.
8. **No validation of `raw_config`.** Bad JSON from the Advanced editor is caught client-side only when parsing; wrong shapes are saved and served as-is.
9. **Travel rules for Exclusive Discovery.** The tab is hidden for that type, but the feed still includes any `travel_rules` already stored (e.g. from the importer).
10. **Legacy admin API still live.** `/v1/admin-console/hot-deals` (`HotDealsService`) can still create/update offers. `createDeal` publishes immediately and guesses unit values (defaults to 75 % off, 2 units per member).
11. **`/list` and `/detail` feeds ignore `raw_config`**, so their titles and prices can differ from `/v1/public/hot-deals` for the same offer.

---

## 7. Quick checks

```bash
# Hot deal JSON as PHP receives it (core runs on PORT 9005 locally)
curl -s -H "x-api-key: $WP_HOT_DEALS_API_KEY" http://localhost:9005/v1/public/hot-deals | jq

# Travel rules feed
curl -s -H "x-api-key: $WP_HOT_DEALS_API_KEY" http://localhost:9005/v1/public/travel-rules | jq
```

Inspect what the console saved for one offer:

```sql
SELECT id, name, publish_mode, is_active, raw_config
FROM member_offers
WHERE id = '<offer-id>';
```
