# Ordering the feature-usage bars — how to put one bar before another

> **Applies to:** the subscription usage rows drawn by
> `resources/views/filament/components/subscription-usage-bars.blade.php`, on all four surfaces
> (the dashboard **My Subscriptions** widget, the **My Subscription** page grid, the admin ledger's
> **View** modal, and the **subscription detail** page), and to the **“What this plan gives”**
> benefits list, which is built from the same rows.
>
> Every claim below was read from the source on 2026-09-29. When the code and this file disagree,
> **the code wins** — see `AGENTS.md`.

---

## 1. The one-line answer

The bars are ordered by **`features.sort_order` (ascending)**, ties broken by
**`features.key` (alphabetical)**. To move a bar, change `sort_order` on the **feature**, not on
the plan, the subscription, or the Blade file.

---

## 2. Where the order actually comes from

The Blade file does **not** sort. It is a plain loop:

```blade
@foreach($rows as $row)
```

Neither does any caller. The order is decided once, in
`App\Services\FeatureEntitlement\SubscriptionUsageReport::storedKeysFor()`:

```php
return DB::table('features')
    ->whereIn('id', $ids)
    ->where('is_active', true)
    ->orderBy('sort_order')   // ← the bar order
    ->orderBy('key')          // ← the tie-break when two features share a sort_order
    ->pluck('key')
    ->all();
```

That key list is handed to `forKeys()`, which builds one row per key **in the order it was given**,
and `forSubscription()` is just `forKeys($subscription, storedKeysFor($subscription))`. So:

```
features.sort_order  →  storedKeysFor()  →  forKeys()  →  $rows  →  @foreach  →  the bars
```

**Consequences worth knowing:**

- The order is **global** — it belongs to the feature row, not to a plan, a subscription or a
  surface. Two plans cannot order the same feature differently, and the four surfaces cannot
  disagree (they render the same rows; that is asserted by
  `tests/Feature/Plans/SubscriptionUsageBarsParityTest.php`).
- A feature whose `sort_order` is **equal** to another's falls back to alphabetical `key` order.
- A feature that is not `is_active` does not appear **at all**, so its `sort_order` is irrelevant.
- Only features the subscription actually holds appear, so **gaps in the numbering are harmless**.
  The shipped catalogue numbers in tens (`10, 20, 30, …`) precisely so a new feature can be inserted
  between two existing ones without renumbering.
- The “What this plan gives” list follows the **same** order (its rows are filtered from the same
  array, preserving it), so a bar moved here moves there too.

---

## 3. Worked example — “Eligible Teachers per Marathon” before “Competitions per Marathon”

Today, in `database/data/feature-catalogue.php`:

| Feature | `key` | `sort_order` |
|---|---|---|
| Competitions per Marathon | `no_of_competition_per_marathon` | **110** |
| Eligible Teachers per Marathon | `no_of_eligible_teachers_marathon` | **120** |

So **Competitions** renders first. To swap them, give the eligible-teachers feature a **lower**
number — anything below `110` and above the feature that must stay above it:

```php
'no_of_eligible_teachers_marathon' => [
    'key' => 'no_of_eligible_teachers_marathon',
    'name' => ['ar' => 'المدربون المؤهلون للماراثون', 'en' => 'Eligible Teachers per Marathon'],
    // ...
    'sort_order' => 105,        // was 120 — now ahead of `no_of_competition_per_marathon` (110)
],
```

You do not have to renumber anything else: the two rows simply sort `105` before `110`.

---

## 4. How to apply it — two ways, and which one to use

### (a) Admin UI — immediate, no deploy

The feature catalogue is a Filament resource (`App\Filament\Resources\FeatureResource`, the
**Feature catalogue** page) with a **`sort_order`** field on the form, and its list is already
sorted by that column (`->defaultSort('sort_order')`). Edit the number on the feature row and save —
or, since 2026-09-29, **turn on the reorder toggle and drag the rows** (see **§4(c)** below).

This is the right way to change **a live database**.

### (b) The shipped catalogue file — for new installs and new features

`database/data/feature-catalogue.php` is what the catalogue bootstrap reads
(`FeatureCatalogueBootstrap::attributesFor()` maps each definition's `sort_order` into the row).
Edit it so a **fresh** install comes up in the order you want.

### ⚠️ The two are not automatically kept in step — read this before relying on (b)

`features:sync-catalogue` **only creates MISSING rows; it never overwrites an existing feature**
(the command says so in its own description, and `bootstrap()` skips any row that already exists —
*“an existing catalogue row is authoritative”*). And `sort_order` is **not** in
`FeatureCatalogueBootstrap::CORRECTABLE_COLUMNS` (`decrement_on_delete`, `default_value`,
`usage_tracking`), so `features:apply-reviewed-catalogue` will **not** write it either.

So on a database that already has the row:

- editing only the **data file** changes **nothing**;
- editing only the **UI** changes the live row but is **not** in the repository, so the next fresh
  install (or a re-seeded database) comes up with the file's order.

**Do both**: change the file (the durable, reviewable record) *and* apply the same number in the UI
(or with a one-off SQL/`tinker` update) on each live environment.

### (c) Drag and drop on the catalogue list — added 2026-09-29

The list page has the reorder toggle (`FeatureResource::table()`: `->reorderable('sort_order')`).
Once it is on, a row can be dragged and the new order is written to `features.sort_order`
immediately.

The list is **tabbed** (one tab per plan tier — `program` / `teacher` / `student` — plus an `all`
tab it opens on), and **a drag inside a tab is still a global reorder**: the rows you dragged take
new positions *among the slots those same rows already occupied in the whole catalogue*, and every
row outside the tab keeps its position relative to the others. So dragging inside the `teacher` tab
reorders the teacher features for the usage bars too, without teleporting them above the program
features. (`ListFeatures::reorderTable()` builds the sequence globally; Filament's own handler would
renumber just the visible rows to `1..N`, which ties them against the rows the tab hides.)

Two consequences:

- **Any drag renumbers the WHOLE column to `1..N`.** The tens convention of the shipped file (§2) is
a property of the seed data, not a guarantee; after a drag the numbers are contiguous. That is
harmless — the order is what matters — but it does mean the live numbers will no longer match
`database/data/feature-catalogue.php`. Re-run the drag (or the UI form) after a re-seed.
- The `all` tab is the cleanest place for a **whole-catalogue** reorder: nothing is hidden, so the
drag is exactly the resulting order.

## 5. Verifying the order

Read the order straight from the database — this is exactly what the report will produce:

```bash
php artisan tinker --execute="
  DB::table('features')->where('is_active', 1)
    ->orderBy('sort_order')->orderBy('key')
    ->get(['sort_order', 'key'])
    ->each(fn(\$f) => print(\$f->sort_order . '  ' . \$f->key . PHP_EOL));
"
```

A subscription's own row order (only the features it holds, in rendering order) is:

```php
app(\App\Services\FeatureEntitlement\SubscriptionUsageReport::class)
    ->storedKeysFor($subscription);
```

Then open any surface — the dashboard widget, My Subscription, the ledger's View modal, or the
detail page — and the bars are in that order.

---

## 6. What is NOT supported (so you do not go looking)

| You want | Status |
|---|---|
| A **different** order per surface (widget one way, modal another) | **Not supported.** One renderer, one order — that is the point of the shared partial (D-24/D-29). A per-surface order would also break the widget/modal parity test. |
| A different order **per plan tier** (e.g. teacher plans list seats first) | **Not supported.** `sort_order` is a column on the feature, not on `plan_feature_values`. The catalogue's tier tabs are a FILTER over that one order, not a per-tier order: a drag inside the `teacher` tab moves those rows in the shared column (they keep the slots they already held against the rows the tab hides). |
| Ordering by **usage**, or by “closest to its limit”, or by anything dynamic | **Not supported.** The order is a stored integer, and it is read before any usage number is computed. |
| Reordering from the **usage screen** itself | **Not supported** there — the catalogue screen owns the number. Reorder by dragging on the **Feature catalogue** list, or by editing the `sort_order` field on a feature's form. |
| Grouping the bars by `feature_group` | **Not done.** `storedKeysFor()` orders by `sort_order` and `key` only; `feature_group` plays no part in the order. |

---

## 7. Cross-references

- `app/Services/FeatureEntitlement/SubscriptionUsageReport.php` — `storedKeysFor()`,
  `forSubscription()`, `forKeys()`, `benefitRows()`.
- `resources/views/filament/components/subscription-usage-bars.blade.php` — the one renderer.
- `database/data/feature-catalogue.php` — every feature's `sort_order`.
- `app/Services/FeatureEntitlement/FeatureCatalogueBootstrap.php` — how that file becomes rows.
- `app/Filament/Resources/FeatureResource.php` — the admin editor for `sort_order`, and
  `->reorderable('sort_order')`.
- `app/Filament/Resources/FeatureResource/Pages/ListFeatures.php` — the tier tabs and
  `reorderTable()` (why a drag is persisted globally rather than per tab).
- `PROJECT_DOCUMENTATION.md` §20.2 (the display contract), D-24/D-29 (why there is one renderer)
  and D-32 (the catalogue tabs + the drag).
