# Architecture

## Overview

```
Browser (Vuexy Blade pages, jQuery, Select2, Quill, ApexCharts)
   │  plain forms + 3 small JSON lookups; CSRF on every write
   ▼
routes/web.php ── auth ── admin (active + has role) ── can:* / policies
   ▼
Controllers (thin)  ──►  Form Requests (validation + authorisation)
   ▼
Services:   ArticleService · MediaService · DashboardService · ActivityLogger
Queries:    ArticleFilter (filters → indexed SQL)
Support:    CappedPaginator · ContentSanitizer · SlugGenerator · Permissions
   ▼
Eloquent models ──► MySQL 8 (InnoDB)          Queue: thumbnails, scheduled publishing, bulk jobs
                                              Cache: master-data dropdowns, dashboard aggregates
```

- **Controllers** only authorise, call a service or query object, and pick a view.
- **ArticleService** owns every write to an article: one DB transaction covers the
  article, body, tags, media, SEO, revision and audit entry. Workflow columns
  (`status`, `published_at`, flags, `created_by`) are not mass-assignable, so they
  can only change through this service.
- **ArticleFilter** is the only place listing filters become SQL. The queued bulk
  job reuses it, so "apply to all matching" touches exactly the rows the list showed.

## Database

### Tables

| Table | PK type | Purpose |
|---|---|---|
| `users` | BIGINT | Login accounts (`status` = may sign in) |
| `roles`, `permissions`, `permission_role`, `role_user` | SMALLINT / composite | RBAC |
| `countries` | SMALLINT | ISO countries; `slug` used in public URLs |
| `categories` | INT | Two-level tree (`parent_id`), soft deletes |
| `authors` | INT | Bylines; optional 1:1 link to `users` |
| `tags` | INT | Tag vocabulary, soft deletes |
| `media` | BIGINT | File metadata only (disk + path), soft deletes |
| `news_articles` | BIGINT | The article record (no body), soft deletes |
| `article_contents` | BIGINT (= article id) | Article body, 1:1 |
| `article_tag` | composite (article_id, tag_id) | Tags ↔ articles |
| `article_media` | BIGINT | Gallery / inline / video / attachment media per article |
| `article_seos` | BIGINT | Optional SEO and social overrides, 1:1 |
| `article_revisions` | BIGINT | Snapshots of title, summary and body |
| `article_slug_redirects` | BIGINT | Old slugs of published articles (for 301s) |
| `activity_logs` | BIGINT | Append-only audit trail |
| `cache`, `jobs`, `failed_jobs`, `job_batches`, `sessions` | Laravel defaults | |

### Relationships

```
Country 1─* NewsArticle *─1 Category (category_id, top level)
                        *─1 Category (subcategory_id, child of category_id)
                        *─1 Author, *─1 User (created_by)
                        *─1 Media (featured_image_id)
                        1─1 ArticleContent, 1─1 ArticleSeo
                        *─* Tag     (article_tag)
                        *─* Media   (article_media, with role/sort_order/caption)
                        1─* ArticleRevision, 1─* ArticleSlugRedirect
Category 1─* Category (children)          Author 0..1─1 User
User *─* Role *─* Permission
```

### Integer sizes and why BIGINT

High-growth tables (`news_articles`, `article_contents`, `media`, `article_media`,
`article_revisions`, `article_slug_redirects`, `activity_logs`, `users`) use
`BIGINT UNSIGNED`. Articles, media and log rows can exceed INT's 4.29 billion over a
platform's lifetime, and an ID type cannot be changed cheaply on a billion-row table.

Small, bounded master tables go the other way on purpose. Their keys are copied
into every `news_articles` row and every index on it, so narrower keys keep that
hot table and its indexes smaller:

| Key | Type | Saving per article row, per index containing it |
|---|---|---|
| `country_id` | SMALLINT (max 65,535) | 6 bytes vs BIGINT |
| `category_id`, `subcategory_id`, `author_id`, `tag_id` | INT (4.29 billion) | 4 bytes vs BIGINT |
| `status`, `visibility` | TINYINT enum | vs VARCHAR status strings |

### Why the body is in its own table

InnoDB stores a `LONGTEXT` value inline in the clustered index when the row fits in
roughly half a page, and typical 2–10 KB news bodies do. With the body inline, every
listing scan, `COUNT`, dashboard aggregate and bulk `UPDATE` pulls whole articles
through the buffer pool. Moving the body to `article_contents` (1:1, PK = article id)
cut `news_articles` to **~450 bytes/row** (against ~2.8 KB bodies in the test data),
and benchmark times dropped accordingly (see below). Only the edit page, preview
page and future article page read the body.

### Status design

There is one `status` column (`App\Enums\ArticleStatus`: Draft 1, Pending 2,
Scheduled 3, Published 4, Archived 5) instead of `is_draft`/`is_published` flags,
which can contradict each other. `is_featured` and `is_breaking` stay as separate
booleans because they are editorial attributes, not workflow states.
`published_at` is when the article went live; `scheduled_at` is set only while it is scheduled.

### Index reference: `news_articles`

Every composite index starts with a foreign-key column, so it also satisfies
InnoDB's requirement that FK columns be indexed. These indexes therefore replace
the plain FK indexes rather than adding to them.

| Index | Serves |
|---|---|
| PK `id` | Default admin sort (newest first), `#id` search, keyset chunking in jobs |
| UNIQUE `slug` | Public URL lookup `/news/{country}/{slug}`; uniqueness |
| `(status, published_at)` | Latest published (home, feeds, sitemap), per-day dashboard chart, scheduler (`status = scheduled AND scheduled_at <= now` reads only the small scheduled slice) |
| `(country_id, status, published_at)` | Country pages; admin country filter |
| `(category_id, status, published_at)` | Category pages; admin category filter |
| `(subcategory_id, status, published_at)` | Subcategory pages; filter |
| `(author_id, status, published_at)` | Author pages; filter |
| `(is_breaking, status, published_at)` | Breaking ticker; admin "breaking" filter |
| `(is_featured, status, published_at)` | Featured slots; admin "featured" filter |
| `created_by` | Author role's "my articles" list; FK |
| `featured_image_id` | FK; "where is this image used" |
| `created_at` | Admin "created between" filter |
| `deleted_at` | Trash view (deleted rows are rare, so the index is tiny) |
| FULLTEXT `(title, short_description)` | Admin keyword search |

Indexes deliberately **not** added:

- Plain single-column `status`: covered by `(status, published_at)`.
- A FULLTEXT index on the body: it would be very expensive to maintain on millions of
  `LONGTEXT` rows. Body search belongs in Elasticsearch/OpenSearch (see Future work).
- `(is_breaking, …)` and `(is_featured, …)` were left out in the first design, on the
  assumption that a backward scan of `(status, published_at)` would find recent flagged
  rows quickly. The 100k benchmark showed the admin "breaking" filter taking **1.15 s**,
  because the capped count must scan the whole table when fewer rows match than the cap.
  With the indexes it takes **20 ms**.

### Other indexes

- `article_tag`: PK `(article_id, tag_id)` answers "tags of an article" and prevents
  duplicates; `(tag_id, article_id)` answers "articles with a tag" from the index alone.
- `article_media`: unique `(article_id, role, media_id)`; `(article_id, role, sort_order)` for ordered galleries; `media_id`.
- `categories`: unique `slug`; `(parent_id, status, sort_order)` for menus and children.
- `media`: `(type, id)` for type filter plus newest first; FULLTEXT `(original_name, title, alt_text)`; `deleted_at`.
- `activity_logs`: `(subject_type, subject_id, id)` for a record's history, `(user_id, id)`, `(action, id)`.
- `tags.name`, `tags.slug`, `authors.slug`, `countries.iso_code` / `iso3_code` / `slug`: unique.

### Soft deletes and unique slugs

Articles, categories, authors, tags and media use soft deletes. Unique indexes include
trashed rows, so a deleted record's slug stays reserved and **restoring can never collide**.
The UI says so, e.g. "a tag with this name already exists (it may be in the trash)".
`SlugGenerator` checks trashed rows too, and for articles also checks the redirect history.

## Scale strategies

| Concern | Approach |
|---|---|
| Pagination on millions of rows | `CappedPaginator` counts at most 10,001 matching rows (`SELECT COUNT(*) FROM (… LIMIT 10001)`), shows "10,000+", and clamps pages to the cap. This bounds both the count and the deepest `OFFSET` (page 400 at 25/page). Users narrow results with filters. |
| Filtering | Done in SQL by `ArticleFilter`; every filter maps to an index above. |
| Search | FULLTEXT boolean mode; each word is required and prefix-matched (`+budget* +india*`). Operators typed by users are stripped. `#123` jumps straight to an id. |
| N+1 queries | Listings use `forListing()`: an explicit column list plus eager loads with selected columns. `Model::preventLazyLoading()` is on outside production, and a test asserts that the listing's query count doesn't grow with the number of rows. |
| Dashboard | One `GROUP BY status` pass for all counters; `Cache::flexible` (fresh 5 min, stale-while-revalidate to 30 min); warmed by the scheduler every 5 minutes, so admin requests never pay for the aggregation. |
| Dropdowns | Countries, categories and authors are cached forever and invalidated by model events. |
| Bulk actions | Set-based `UPDATE … WHERE id IN (…)` per chunk of 1,000 ids, never a loop of saves. "All matching filters" goes to a queued job that streams ids with `chunkById` (keyset, constant memory). |
| Scheduled publishing | Queued unique job every minute; a set-based update per chunk, `published_at = scheduled_at`. |
| Image processing | Thumbnails are generated on the queue, not in the upload request. |
| Views | Only the aggregate `views_count` is stored. Per-view events should go to a separate append-only store (partitioned table, Redis counters, or an analytics pipeline) and be rolled up periodically, never one `UPDATE` per page view. |
| Audit log | Append-only, small JSON diffs only (body changes are recorded as `"content": "changed"`; the text itself goes to revisions). Ready for monthly `RANGE` partitioning on `created_at`. |

## Benchmarks (100,000 articles)

Machine: local Windows/WAMP, MySQL 8.0.31, 1 GB buffer pool. Test data: 70% of
articles in 6 launch countries, 75% published, about 3 tags per article, ids rising
with creation time. Reproduce with `php artisan news:generate-test-data 100000`
followed by `php artisan news:benchmark`. Times are medians of 3 runs and include
the capped count query.

| Query | ms | Index chosen by MySQL |
|---|---:|---|
| Listing, newest, page 1 | 33 | `deleted_at` (equivalent to a PK-ordered scan) |
| Listing, page 400 (deepest allowed) | 63 | `deleted_at` |
| Filter: country | 54 | PRIMARY |
| Filter: category + published, sort by published | 39 | `category_status_published` |
| Filter: country + status + published range | 20 | `deleted_at` (optimizer's pick at this size) |
| Filter: breaking | 21 | `breaking_status_published` |
| Filter: created range | 18 | `deleted_at` |
| Search "budget" | 359 | FULLTEXT |
| Search "election minister" | 257 | FULLTEXT |
| Search `#id` | 9 | PRIMARY |
| Public-style: latest 20 in country | 14 | `status_published` |
| Public-style: latest 20 with tag | 17 | `article_tag` reverse index |
| Dashboard full recompute (cached in normal use) | 590 | — |

Full admin page loads (HTTP, `php artisan serve`) took 0.1–0.5 s.

Search is the slowest path because the synthetic data draws from a vocabulary of
about 120 words, so a single word matches around 8% of all articles. Real text is far
more selective. At tens of millions of rows, or when body search or relevance ranking
is needed, move search to OpenSearch (see below).

## Security

- **AuthN**: session login, rate-limited to 5 attempts/min per email+IP; inactive users
  cannot sign in and are logged out mid-session (`EnsureAdminAccess`).
- **AuthZ**: route middleware `can:*` for master data; `NewsArticlePolicy` and
  `MediaPolicy` for records; Form Request `authorize()` on every write;
  `Gate::before` grants Super Admin everything. Hiding buttons is cosmetic only, and the
  tests post directly to every protected route.
- **Workflow rules**: publish/schedule actions and the featured/breaking flags require
  `news.publish`. Authors' bylines are forced server-side. Workflow columns are not fillable.
- **XSS**: article HTML is cleaned by `symfony/html-sanitizer` with an allow-list before
  storage. Iframes are allowed only from YouTube, Vimeo and Dailymotion; event
  handlers, `javascript:` URLs, `<script>` and `<style>` are removed. All other output
  is escaped by Blade, and JSON for scripts uses `@json` (HTML-escaped).
- **Uploads**: MIME type is detected from file contents; extensions are allow-listed;
  SVG is refused; size and dimension limits apply; files get ULID names in dated
  directories. The client's file name is kept only as sanitised metadata.
- **CSRF** on all web routes (verified: 419 without a token). SQL goes through the query
  builder with bindings, and filter values are type-checked before use.

## Future work this design allows

- **Public site**: `/news/{country:slug}/{article:slug}` with lookups via the unique
  `slug` index and 301s from `article_slug_redirects`. Country, category and author pages
  are covered by the composite indexes; private visibility is already modelled.
- **Search**: index articles in OpenSearch from `ArticleService` via a queued listener.
  The admin `ArticleFilter::search()` is the single swap point.
- **Multi-language**: add `language` (CHAR(5)) to `news_articles` (an INSTANT `ADD COLUMN`
  in MySQL 8) plus a `translation_group_id`, or move to per-locale article rows.
- **Analytics**: `article_view_events` (partitioned) or a stream, rolled up into `views_count`.
- **API / mobile**: reuse the services and `ArticleFilter`; add API Resources.
- **Sitemaps, RSS, Google News**: stream from `(status, published_at)` with `chunkById`.
- **Very high write volume**: replace the dashboard's full scan with a counters table
  maintained by `ArticleService` (the single write path already exists).

## Assumptions

- No Laravel project existed, only the Vuexy HTML template, so Laravel 12 was scaffolded
  (the newest version supporting the installed PHP 8.2) and the template's starter-kit
  vertical layout was converted to Blade. The original template folder is untouched;
  its assets are copied to `public/vuexy`.
- Categories are two levels (category → subcategory), matching the article's
  `category_id` / `subcategory_id` pair.
- Geography is country-level only. Regions/states were built first and then removed at
  the product owner's request (migration `2026_01_02_000100_drop_regions`); cities were never required.
- Featured image: `news_articles.featured_image_id` (denormalised, so listings show
  thumbnails without a join). Gallery, inline, video and attachments: `article_media.role`.
- The editor is Vuexy's Quill 1.3. It supports headings, lists, quotes, code,
  links, images (uploaded to the media library) and video embeds, but **not tables**.
- User management was added (not in the brief) so that Editor and Author accounts can
  be created without database access. Users are disabled rather than deleted, to keep authorship history.
