# Database: what we have and what we need to do

Source: `stimberc_live_production_BK21072026-PART-1.sql.gz` + `PART-2.sql.gz` (phpMyAdmin export,
MySQL 5.7.44, taken 21/07/2026 08:01). **Both parts are one database.** Part 1 has 141 tables,
part 2 has the 4 biggest order tables (`orders`, `order_details`, `order_details_more`,
`orders_abandoned_cart`). Locally both are loaded into the `st_legacy` database (see README).

The new Laravel schema lives in a separate `st_manager` database. The old database is never
changed. Data is copied across by importers (`php artisan legacy:import`, built module by module).

---

## 1. What we have

### 1.1 The big picture

- **145 tables** in total, ~42 of them empty or unused (webmail, old backups, temp tables).
- Old CodeIgniter app. Mix of **InnoDB and MyISAM**, mostly **latin1** charset.
- **No foreign keys** between business tables (the only 11 FKs are on the unused `webmail_*` tables).
  Every link is a plain `int` column, e.g. `orders.users_id`, `order_details.orders_id`.
- Many "list" columns are **comma-separated ids** or **PHP-serialized arrays** inside text columns
  (`permissions.data`, `promotions.category_id`, `blogs_data.products_id`, `orders.cart`,
  `quotes.cart_contents`, `tbl_gallery.gallery_category_id`, `micro_site_*_status`, ...).
- Same data repeated in several places: e.g. an order's address is in `orders`, `orders_address`
  and `order_confirmation`; order lines are in `order_details`, `order_details_more`, the serialized
  `orders.cart` and as rendered HTML in `order_view_admin`.
- **6 websites** share the one database (`websites`): southgatetimber.co.uk (1), ipedeckingsuppliers (2),
  larchcladdingsuppliers (3), balaudeckingsuppliers (4), cedarcladdingsuppliers (5), thisisourtradesite (6).
  Most tables have a `websites_id`, `micro_site_id` or `micro_site_*_status` column.

### 1.2 Tables by area (rows ≈ count in the backup)

| Area | Tables (rows) | Admin module |
|---|---|---|
| **Staff / login** | `user_sub_admin` (12), `user_sub_admin_positions` (6), `roles` (3), `permissions` (2), `manage_logincodes` (6,440), `login_attempts` (0), `ci_sessions` (3,766), `user_autologin` (28) | Users, Roles |
| **Customers** | `users` (169,172: 49,130 registered + 120,041 guest + 1 master admin), `users_address` (68,761), `user_profile` (191,751), `addresses` (0), `customer_notes` (0), `cards` (105), `mailing_list` (3,658), `users_lastviewed_pro` (644), `products_saved_for_later` (656) | Customers |
| **Orders** | `orders` (75,074), `order_details` (188,038), `order_details_more` (158,202), `orders_address` (55,671), `order_confirmation` (1), `order_view_admin` (29,004), `orders_complete` (95,542), `quotes_orders_vertual_pro` (271) | Orders |
| **Payments** | `orders_sagepay_response` (114,677), `paysmart_mwbnmi_res` (637), `tblorders` (0), `trade_orders_manage_payment` (38) | Orders → payment tab |
| **Carts** | `orders_abandoned_cart` (34,907), `unused_cart_details` (77,520) | Orders → Abandoned / Unused carts |
| **Stock sync** | `orders_stock_api_result` (864,614), `orders_stock_cron_result` (80,112), `orders_stock_cron_lstord` (1), `product_stocklevel` (3) | Stock (logs only) |
| **Quotes** | `quotes` (21,853; 11,429 archived), `cron_quote_archived` (11,434), `quotes_config` (1), `quotes_BK02032026` (20,056, backup) | Quotes |
| **Collections** | `collection_bookings` (10,045, 2020 → 08/2026), `collection_bookings_config` (2), `collection_bookings_config_day` (21), `collection_book_disable_date` (103), `collection_book_disable_slots` (724) | Collections |
| **Catalogue** | `categories` (107; 83 enabled), `products` (559; 375 enabled), `products_has_categories` (840), `products_has_categories_parent` (1,362), `sizes` (505), `products_has_sizes` (4,948), `products_colors` (1,113), `products_colors_images` (2,921), `products_has_styles` (88), `styles` (17), `brand` (3), `product_types` (17), `properties` (3), `products_profile` (26), `alternate_products` (944), `categories_variations` (4), `product_variation_price` (142), `products_text` (3), `product_email_promo` (1) | Categories / Products |
| **Per-site product data** | `micro_website_products_description` (1,721), `micro_website_products_price` (1,229), `micro_website_products_colors_images` (23), `websites_has_*` (mostly empty) | Products → per-site tab |
| **Delivery** | `delivery` (5 methods: Courier, Lorry, Owatrol Treatment, Cedral x2), `delivery_rules` (79), `countries_has_delivery` (2), `websites_has_delivery` (9), `postcodes` (2,872 outcodes), `couriers` (0) | Delivery Pricing, Couriers |
| **Trade / loyalty** | `trading_detail_tbl` (658 accounts: 645 live, 11 suspended), `trade_applications` (698: 602 accepted, 85 declined, 3 processing), `trade_appli_invite_upload` (919), `trade_notes` (628), `trade_notes_comments` (3), `trade_applications_notes` (10), `trade_discount` (626), `special_trade_discount` (153) | Loyalty |
| **Discounts** | `discounts` (4), `discount_specialday` (1), `promotions` (14), `promotions_detail` (0), `product_discounts_audit_trails` (10,767), `websites_has_discounts` (6), `websites_has_promotions` (3) | Discounts, Promo Codes |
| **Content** | `cms` (8), `blogs_data` (134; 127 published), `faq_question` (25), `tbl_gallery` (443), `tbl_gallery_category` (22), `tbl_gallery_video*` (0/1), `z_system_images` (315: banners, swatches, sliders), `sgt_banner_config` (5), `balck_bar_details_tbl` (7), `news` (0), `reviews` (0) | Website CMS, Blogs, Gallery, Image Library |
| **Tasks** | `task_management` (12), `task_management_history` (405), `task_management_notes` (43) | Tasks |
| **Messages** | `message_sms` (0), `enquiry_emails_cus` (148: 80 imported, 68 had "0" as the email) | SMS, Email |
| **Settings** | `z_system_codes` (1), `order_limit` (1), `order_countdown` (1), `order_con_dropdown_list` (11), `currency` (3), `countries` (253), `jos_vm_country` (244), `websites` (6), `new_websites` (1) | Config |
| **Reports cache** | `admin_pro_lendboard` (15), `admin_sitevisits_data` (5) | Reports (rebuild, do not import) |

### 1.3 Tables we will NOT migrate

| Tables | Why |
|---|---|
| `categories_BK29062026`, `delivery_rules_BK11062024`, `delivery_rules_BK01042025`, `delivery_rules-BK2_01042025`, `quotes_BK02032026`, `products_local_7`, `products_new` | Backup / old copies of live tables |
| `webmail_*` (12 tables), `session`, `ci_sessions`, `user_autologin`, `user_temp`, `login_attempts` | Old webmail and session data; Laravel has its own sessions |
| `tblorders`, `addresses`, `customer_notes`, `news`, `reviews`, `couriers`, `message_sms`, `product_sizes*`, `products_colors_sizes_stock`, `products_sizes_properties`, `promotions_detail`, `websites_has_products/categories/reviews` | Empty (0 rows) |
| `order_view_admin` | Rendered HTML of each order; rebuild from order lines instead |
| `admin_pro_lendboard`, `admin_sitevisits_data` | Cached report numbers; recalculate |
| `orders_stock_api_result`, `orders_stock_cron_result`, `orders_complete` | Raw API / cron logs (1M+ rows). Keep in `st_legacy` for lookups, do not copy |
| `manage_logincodes` | Old one-time login codes; expired |
| `cards`, card columns in `orders` | Card data must not be kept (see 3.1) |

---

## 2. Problems found in the data

| # | Problem | Detail | What we do |
|---|---|---|---|
| 1 | **Weak staff passwords** | `user_sub_admin.user_passwd` is a 32-char unsalted MD5 for all 12 staff | Do not import. Staff get new accounts and set a password by email link |
| 2 | **Plain-text trade passwords** | `trading_detail_tbl.password` (652 rows, 4–17 chars) and `site_password1..10` / `branch_password1` are stored as plain text | Do not import the values. Trade users reset their password. **The live site should be fixed now as well.** |
| 3 | **Old customer passwords** | `users.password` is 32 or 65 chars (MD5 / salted hash), not bcrypt | Copy the hash to `legacy_password` and re-hash with bcrypt on the customer's first successful login (or force a reset) |
| 4 | Card columns | `cards.number`, `orders.card_number` and `orders.card_code` are empty in every row (checked) | Never import card columns |
| 5 | Duplicate customers | 16,333 email addresses appear on more than one `users` row (mainly guest checkouts) | One customer per email in the new `customers` table, orders linked to it. Guests kept as `is_guest` |
| 6 | No foreign keys | Orphan rows are likely (order lines without an order, etc.) | Importer skips orphans and logs a count |
| 7 | Repeated / wide tables | `trading_detail_tbl` has 300+ columns (10 sites x 13 fields, 5 extra contacts, 4 quantity discounts). `products` has 180 columns, including 12 `prod_discountN` and 15 `chk_*` feature pairs | Normalise: `trade_accounts` + `trade_contacts` + `trade_sites`; `products` + `product_features` + `product_discounts` |
| 8 | Serialized PHP in columns | `permissions.data`, `orders.cart`, `quotes.cart_contents`, `unused_cart_details.cart_contents` | Unserialize in the importer into proper rows (`quote_items`, `cart_items`) |
| 9 | CSV id lists | `promotions.category_id/product_id`, `blogs_data.products_id/websites_id`, `faq_question.pro_ids_prodetail`, `task_management.associates`, `tbl_gallery.gallery_category_id` | Pivot tables |
| 10 | Zero / bad dates | MySQL 5.7 dump allows `0000-00-00` | Importer turns zero and pre-1990 dates into NULL |
| 11 | Text encoding | latin1 tables holding UTF-8 / HTML-entity text (`&amp;`, `&pound;`) | Decode entities, store utf8mb4 |
| 12 | Typos in names | `date_uppdated`, `balck_bar_details_tbl`, `admi_id`, `sud_admin`, `mendrill_mail_id`, `vertual` | Clean names in the new schema |
| 13 | Status is free text | `orders.status` + `status2`, `quotes.status` (NULL or "Authorised BT"), `trading_detail_tbl.status` ("live", "suspend", "invite email", blank) | String-backed PHP enums with a `fromLegacy()` mapping |

---

## 3. What we need to do

### 3.1 Before anything else (security)

1. **Do not commit or share the `.sql.gz` files.** They contain personal data for ~170k customers.
   Keep them outside the Laravel folder (they are in `../`) and out of git.
2. Trade passwords in plain text (problem 2) are a risk **on the live site today**. Hash them there,
   or force a reset for all trade users.
3. Staff passwords are unsalted MD5 (problem 1). Staff should change their live passwords once the new
   admin is live, and the old `user_sub_admin` login should be switched off.
4. No card numbers are stored (checked), so nothing to clean up there.
5. **The Paysmart gateway secret is stored in the database.** Every row of `paysmart_mwbnmi_res.postdata`
   holds the full request sent to the gateway, including `security_key` (the merchant API key) and the
   payment token. Anyone with the database or a backup can use that key. Rotate the Paysmart key, stop
   logging `postdata`, and blank the column on the live site. The new admin never imports it.

### 3.2 New schema (Laravel migrations, one file per area)

| New table(s) | From | Notes |
|---|---|---|
| `roles`, `role_permissions`, `users` | `user_sub_admin`, `users` (role 2), `roles`, `permissions` | **Imported** (`legacy:import --only=staff`): 12 staff + 1 master admin. Role from the old job title: Sales Executive / Sales Team → Counter staff, Sales Manager → Manager, Marketing Manager / Executive → Marketing, Web Development and the master admin → Administrator. `micro_site_status` → `sites`. Last login from `manage_logincodes`. Passwords NOT imported: status "invited" until the person sets one from the welcome link. Old `permissions.data` (serialized) not used: the new roles replace it |
| `login_codes` | `manage_logincodes` | New table; old codes not imported (expired). Only a hash of each code is stored |
| `sites` | `websites` | 6 sites; everything per-site gets `site_id` or a `site_*` pivot |
| `customers`, `customer_addresses`, `customer_notes`, `mailing_list`, `countries` | `users` (role 1), `users_address`, `orders`, `trading_detail_tbl`, `mailing_list`, `countries` | **Imported** (`legacy:import --only=customers`, after orders). **One customer per email** (lower-cased): 71,917 from accounts + 115 who only exist on guest orders = 72,032. 38,978 duplicate rows merged (registered beats guest, trade beats plain, newest wins); 8,785 guest rows with no orders and 1,065 bad emails skipped; 48,426 old rows have no email at all. Type: `trade_id` → Trade (credit limit or "Full Trade", 24) or Loyalty (discount only, 626), else Retail. Old password hash kept in `legacy_password` (registered only) for re-hashing when the customer portal is built. Addresses: account billing + delivery, `users_address`, and the latest order for guest-only customers (deduplicated). `orders.customer_id` filled by email: 73,898 of 75,074 (the rest have no email) |
| `categories`, `category_site` | `categories`, `micro_site_cat_status` | Tree via `parent_id` |
| `products`, `product_category`, `product_variants` (size/length), `product_colours`, `product_images`, `product_features`, `product_site` (per-site price/description) | `products`, `products_has_categories*`, `sizes`, `products_has_sizes`, `products_colors*`, `micro_website_products_*` | Money `decimal(15,2)` |
| `orders`, `order_items` | `orders`, `order_details`, `collection_bookings` | **Imported** (`legacy:import --only=orders`). `id` = old order number. Status → `payment_status` + `fulfilment_status` (§4.1). Abandoned carts stay in `orders` with `payment_status = abandoned`; "Deleted" orders are soft-deleted. Addresses kept as a snapshot on the order. `encore_ref` → `external_ref`, `encore_ref_note` → `staff_initials`, `ord_traking_notes` → `notes`, `order_review` / `google_review` / `is_no_review` → `review_*`, `delivery` (incl. VAT) → `delivery_charge`, `cart_total_amount` → `total` |
| `order_payments` | `paysmart_mwbnmi_res`, `orders_sagepay_response` | **Imported.** Paysmart: 634 rows, reply JSON reduced to response, responsetext, authcode, transactionid, avsresponse, cvvresponse, response_code, type. Sage Pay: 62,223 result calls (transactions, 3DS, checks, declines) of 114,677 rows; session-key calls skipped. `postdata` (gateway secret + token) is never read |
| `activities` | – | New: order notes and journal (no old data; `order_details_more` not needed) |
| `unused_carts` | `unused_cart_details` | **Imported.** Cart JSON reduced to product id, name, choice, qty, price. 13,122 empty carts skipped |
| `quotes`, `quote_items`, `quote_emails` | `quotes` (`cart_contents` JSON, `cart_products` JSON, `quote_special_products` JSON), `cron_quote_archived` | **Imported** (`legacy:import --only=quotes`, after staff / customers / orders): 21,853 quotes, 56,478 lines, 20,608 emails. **Status:** became an order (`orders.quote_ref_id`) → accepted (9,951); archived or past 30 days (`quotes_config.lead_days`) → expired; emailed (`is_mail_sent`) → sent; else draft. "Overdue" is worked out: sent and not chased for 7 days. **Lines:** `cart_contents` items (price inc. VAT, choice = length) + `quote_special_products` (bespoke lines; prices there are ex VAT, total inc. VAT – converted to inc. VAT). **Totals:** `cart_total_amount` is the real total. The line prices are before quantity discounts, so the difference is stored as the quote discount (and as a %, so edits keep it); older quotes did not save delivery in `cart_products`, so a shortfall is stored as delivery. Every quote balances (lines − discount + delivery = total). Owner from `added_by_id` (staff), customer by email. `quote_emails` from `is_mail_sent` / `is_mail_success` / `mendrill_mail_id`. `quotes_orders_vertual_pro` (271 order adjustments) not imported |
| (catalogue prices) | `products_has_sizes` | `price` = ex-VAT price per length; `sale_price` there actually holds the **weight** per length (→ `product_variants.weight_kg`) |
| `collection_slots`, `collection_bookings`, `collection_blocks` | `collection_*` | **Imported** (`legacy:import --only=collections`, after orders). `collection_bookings_config` → one weekday slot per open day (Mon–Fri 09:00–17:00, 3 an hour, 24 h lead time); `collection_bookings_config_day` → 21 dated slots (day overrides); `collection_book_disable_date` / `_slots` → 825 blocks (whole day or one hour). 10,045 bookings: status from the linked order (complete 7,510, confirmed 2,462, cancelled 52, pending 21); order only linked when the booking is dated from the day before the order to 180 days after (535 left unlinked, see §4) |
| `delivery_methods`, `delivery_rates`, `delivery_postcodes` | `delivery`, `delivery_rules`, `postcodes` | **Imported** (`legacy:import --only=delivery`): 5 methods (Courier £11.95 base, Lorry, Owatrol Treatment, Cedral Lap Weatherboard off, Cedral Samples off), 69 rates (6 parcel, 5 courier, 55 lorry, 3 other). Only rules of a method that still exists are kept (10 rules of deleted methods / test rows dropped). **Service** from the name: "Parcel …" → parcel, "Lorry …" → lorry, "Courier …" → courier, else other. `delivery_effect` + `_amount` = weight condition (under / over kg), `delivery_effect_length` + `_length_amount` = longest-item condition (feet); `percentage_premium` = % added when the longest item is over 9.81 ft; `cost_per_kilo` = £/kg above 15 kg. Amount 0 with estimate "P.O.A." → price null (P.O.A.). `delivery_country` ids → region names. `postcodes` (2,872) is the list of every UK outcode, not a delivery area: the calculator uses it to flag a mistyped postcode. Over-only rates (lorry) apply when either limit is passed; others need every condition. `countries_has_delivery` / `websites_has_delivery` not needed (one site, UK only) |
| `couriers` | `couriers` (0 rows) | **Nothing to import**: the old couriers table is empty and every `orders.courier_id` is 0. `orders.tracking_code` was used as a free-text staff note ("Despatched 20/10/2017 STC2294"), so it is kept as text. Couriers are entered in the new system and set on an order when it is despatched. Fleet / vehicles / drivers are **new** (prototype only) |
| `trade_accounts`, `trade_contacts`, `trade_sites`, `trade_applications`, `trade_notes`, `trade_prices` | `trading_detail_tbl`, `trade_applications`, `trade_notes*`, `trade_discount`, `special_trade_discount` | **Imported** (`legacy:import --only=trade`, after staff and customers). `trading_detail_tbl` (658) → `trade_accounts` (status live / suspended / invited, discount type "Trade Discount" = loyalty, "Full Trade" or a credit limit = trade, `qty_dis_amount/per1..4` → `quantity_discounts`, `message` → personal welcome message) + the main contact → `trade_contacts` (**passwords not imported**). 650 accounts linked to their customer (`customers.legacy_trade_id`), 1,731 orders linked (`orders.trade_account_id`). `trade_notes` (627 with text) → activities on the account (staff author mapped). `trade_applications` (698: 602 accepted, 85 declined, 11 pending incl. 8 with no status) → `trade_applications`, linked to the account via `trd_details_id`; `trade_applications_notes` (1 with text). `trade_appli_invite_upload` (919: 118 completed) → `trade_invites` (new table). **Trade prices** (after the catalogue): `trade_discount` (626 product lists → 611 rows with no price = the product's trade price), `special_trade_discount` (153 → 59; 10 with a special price, 3 with a price per m²; every row names a product, rows for deleted products skipped), `products.is_trade_special` + `assign_trade_id` (4 clearance products × accounts → 57 rows at the product's trade price) → `trade_prices`, 727 rows for 25 accounts. Not yet: the 10 site logins and 5 extra contacts per account (`site_*1..10`, `addi_cont_*`) |
| `discounts`, `promo_codes` | `discounts`, `discount_specialday`, `promotions`, `websites_has_discounts`, `websites_has_promotions` | **Imported** (`legacy:import --only=discounts`). `discounts` (4 site-wide discounts from 2010, all off; one of them 1221% – kept as it was, disabled). `promotions` (14) → `promo_codes`: `name` = the code, "Percentage" / "Fixed", `is_only_sample_free` → type free_samples, `category_id` / `product_id` (comma lists) → `discountables` rows for the imported categories / products (17 links; `2026_11_12_000002` moved the earlier JSON lists there and dropped the columns), `add_cat_count` → min categories, `micro_site_status` / `websites_has_promotions` → sites, uses counted from `orders.promo_code` (any case; "0" is not a code). `discount_specialday` (1 row, no %), `promotions_detail` (empty) not needed. Product sale prices (`products.prod_discountN`, `product_discounts_audit_trails` 10,767) come with the catalogue |
| `pages`, `blog_posts`, `faqs`, `gallery_albums`, `gallery_items`, `media` | `cms`, `blogs_data`, `faq_question`, `tbl_gallery*`, `z_system_images` | **cms / faq_question / sgt_banner_config imported** (`--only=cms`): 8 pages (url kept as the address, page_text as the body, enable → published / draft), 25 FAQs (none was flagged for a page; 4 linked to products), seasonal theme list + active one (Normal) → settings website.theme. **tbl_gallery_category / tbl_gallery imported** (`--only=gallery`): 22 albums (meta_url kept as the live address), 443 photos → 536 album entries (a photo listed under several categories gets one entry per album; 1 link to a deleted category dropped), files stay on the old server (`LEGACY_GALLERY_IMAGE_URL`), pro_id / pro_link kept for the product link. **blogs_data imported** (`--only=blogs`): 134 posts, `blog_url` kept as the slug exactly (live addresses, some with ":" and a trailing "-"), category (old id or "general") → category_legacy_id + name, `products_id` → product_ids, `websites_id` → sites, `is_publish` → status, body HTML kept as it was (shown through a sanitizer, cleaned when saved). Blog images stay on the old server (`LEGACY_BLOG_IMAGE_URL`). The rest: image files must be copied from the live server |
| `tasks`, `task_user`, activities | `task_management*` | **Imported** (`--only=tasks`): 12 tasks (owner list → first staff member assigned, the others watchers; status completed / ongoing / waiting / blank, priority high / medium), 40 notes with text → activities; task_management_history (status / view log) not copied. Polymorphic `taskable_*` so tasks link to orders / quotes / customers |
| `settings` | `z_system_codes`, `order_limit`, `order_countdown`, `quotes_config`, `collection_bookings_config` | **Imported** (`--only=config`): `order_countdown` → lead times (courier 5/3/2, lorry 5/3/2, sample 5/3/1, shop 3/2/1 days), `order_limit` → order limit / minimum order (both off), `quotes_config.lead_days` → quote validity 30 days. One row per Config section (group "config"); `z_system_codes` (1 row) not needed |
| `sms_messages`, `emails` | `message_sms`, `enquiry_emails_cus` | |

**Catalogue imported** (`legacy:import --only=catalogue`, after orders): 17 brands (`product_types`), 107 categories (two levels, `parent_id`; `category_url` kept as the address, 23 without one get one from the name; `micro_site_cat_status` → `category_site`; tile `image`), 559 products (`product_url` kept exactly; prices ex VAT; `prod_weight_in_grams` is kg per unit → `weight_kg`; a `stock_level` of 900,000+ is the old "not counted" value, 999,999 less sales → null (80 products have a real count); `prod_discount1..12` / `wholesale_price_*` → `quantity_discounts`; offer fields → `offer`; pdf_1..4 → `documents`), 2,200 feature rows (`chk_*` + value pairs that are switched on), 839 extra category links, 4,391 variants from `products_has_sizes` (group = the parent size: Board Length 3,236, Size 580, Finish 568, Storage 7; 557 rows pointing at deleted sizes dropped; `out_of_stock` is a level 0–40, not a flag → `out_of_stock_below`; `sale_price` is the weight → `weight_kg`), 552 named colours, 2,329 published photos (`products_colors_images` via the colour rows; 61 YouTube links → the product video; files stay on the old server, `LEGACY_PRODUCT_IMAGE_URL`), 1,322 product–website rows with the microsite price / text overrides, 939 cross-sell links (`alternate_products`), 10,767 price changes (`product_discounts_audit_trails`). Then `order_items.product_id` is set from `legacy_product_id` (181,123 of 181,136 lines; the other 13 point at products that no longer exist). Not imported: `products_has_categories_parent` (derivable), `products_has_styles` / `styles`, `products_profile`, `product_variation_price`, `orders_stock_*` (old stock API log).

**Stock control** (`2026_11_12_000001`, new, no old data): the accounts `suppliers` table gains contact name, lead days, account ref, notes, active; `products.supplier_id` + `reorder_qty`, `product_variants.reorder_qty` (the reorder point is the existing `stock_warning_level`, shown as "Reorder at"); `purchase_orders` (ref PO-0001, supplier, status draft / sent / part_received / received / cancelled, expected date, total at cost) and `purchase_order_lines` (product / length or free text, qty, received qty, unit cost); `stock_movements.purchase_order_id` for goods booked in. Old `cost_price` values were all 0.00 → imported as null (not entered). A length with 0 in stock now counts as out of stock (1,748 of 2,942 counted lines are at 0 in the old data).

**Content linked to the catalogue** (`2026_11_12_000003`): `blog_posts.category_id` from the old category (87 posts; `category_legacy_id` dropped, `category_name` kept for display), `blog_posts.product_ids` (22 posts) and `faqs.product_ids` (4) hold new product ids, `gallery_items.product_id` set from `product_legacy_id` (85 photos); the blog, CMS and gallery importers now write new ids (they run after the catalogue). After `--only=catalogue --fresh`, re-run `--only=trade,discounts,blogs,gallery,cms` so their links point at the new rows.

Reports have no tables of their own: they read `orders` (revenue = paid statuses, by `ordered_at`; despatch by `despatched_on`), `order_items`, `quotes` (by `added_at`), `collection_bookings`, `delivery_runs` / `delivery_run_stops` and `sms_messages`, using the existing indexes (12 months of orders: about 0.6 s for every figure).

Every table that receives old data gets `legacy_id` (+ `legacy_source` where several old tables
merge into one), unique together, so the import can be re-run safely.

### 3.3 Importer (`php artisan legacy:import {--fresh} {--only=}`)

- One importer class per area in `app/Services/LegacyImport/`, shared `IdMap` (old id → new id).
- Cleaners: decode HTML entities, empty/"undefined"/"null" → NULL, zero dates → NULL, CSV/serialized → arrays.
- Runs in a transaction with FK checks off; skips orphans and prints counts per table.
- Order of import: sites → staff → customers → catalogue → delivery → orders → quotes → collections →
  trade → discounts → content → tasks → settings.
- Re-runnable: `--fresh` truncates the new tables first.

### 3.4 Files to copy from the live server (not in the SQL)

Product images, colour swatches, banners (`z_system_images`), gallery pictures, blog images,
PDFs (`products.pdf_1..4`), trade application uploads, staff photos (`user_sub_admin.user_photo_path`).

### 3.5 New data the prototype needs (no old data)

Fleet (vehicles, drivers, runs), delivery routes/planner, accounts (nominal / sales / purchase
ledgers, VAT, P&L), image library folders, buying guides, email inbox, AI task suggestions,
roles manager screen, user MFA settings. These start empty.

---

## 4. Orders: checked after the full load

- **75,074 orders** from 08/03/2016 to 21/07/2026. By site: southgatetimber 72,991, larch 502,
  ipe 382, balau 613, cedar 575, trade site 11.
- **Card data:** `orders.card_number` and `card_code` are empty in every row, and `cards.number` is
  empty in all 105 rows. No card data to clean up. The columns are still dropped in the new schema.
- **Order value:** use `cart_total_amount` (what the customer paid, incl. VAT and delivery; never 0).
  `grand_total` and `total` are 0 on ~700 orders this year (samples, quote orders) and differ from the paid amount.
- `payment_method` is "Debit card" on every row (meaningless). The real payment type is in the
  status text ("Authorised BT" = bank transfer, "Authorised Card", "Authorised Cash", "Authorised FOC").
- **Orphans:** 6,902 `order_details` rows point to an order that does not exist; 1,135 orders point to
  a `users` row that does not exist. Orphan lines are skipped. Orphan orders are kept and linked to a
  customer by email.
- **Collection bookings:** 527 bookings are dated before their own order and 8 more than 180 days after,
  so they point at the wrong order. 1,069 point at no order. The importer only links a booking dated
  from the day before the order to 180 days after it.
- `countdown_days` (delivery days) holds junk on some rows (values over 365); imported as empty.
- **Line prices include VAT:** `order_details.unit_price` and `row_total` are inc. VAT (row_total = unit × qty,
  before the basket discount). The board length is in `choices` ("Board Length - 3.05m (10ft)").
- **Product weight:** `products.prod_weight_in_grams` is really **kg per metre** for timber sold by length
  (`measurment_type = 'm'`), kg per unit otherwise. Line weight = kg/m × board length × qty.
- 54,155 distinct customers have orders. The other ~115k `users` rows (mostly guests) have no orders
  and need not be imported.

### 4.1 `orders.status` → new `OrderStatus` + `PaymentStatus` (to confirm with Southgate)

`status` is a mix of payment and fulfilment state; `status2` holds the despatch method.

| Old `status` | Count | New payment status | New order status |
|---|---|---|---|
| Authorised | 53,913 | paid (card) | from `status2` (see below), else `processing` |
| Authorised BT | 1,452 | paid (bank transfer) | same |
| Authorised Card | 596 | paid (card, by phone) | same |
| Authorised Cash | 35 | paid (cash) | same |
| Authorised FOC | 141 | free of charge | same |
| Account | 3 | on account (trade) | same |
| Pending | 1,199 | pending | `pending` |
| Shipped | 2,202 | paid | `despatched` |
| Despatched Lorry / Courier / Sample / Treatment | 101 / 92 / 45 / 7 | paid | `despatched` (+ method) |
| Collected | 165 | paid | `collected` |
| Part Processed | 2 | paid | `part_despatched` |
| Refund Issued | 254 | refunded | `refunded` |
| Declined | 660 | failed | `failed` |
| Cancelled / Cancelled by Customer | 372 / 440 | – | `cancelled` |
| Abandoned Cart | 6,755 | – | not an order: import into `carts` |
| Deleted | 6,625 | – | soft-deleted order |
| Invalid / Rejected | 14 / 1 | failed | `failed` |

`status2` values: NULL 31,250, Despatched Lorry 17,141, Despatched Courier 10,667, Collected 7,809,
Despatched Sample 7,687, Despatched Treatment 361, Part Refund 95, Despatched External Haulage 63,
Changed Order 1 → order status `despatched` / `collected` + `despatch_method`.
