Skip to content

A free open source IT asset/license management system

Additional floor migration

snipec88b57e67494
diff --git a/database/migrations/2026_08_03_142000_backfill_orders_from_inventory_tables.php b/database/migrations/2026_08_03_142000_backfill_orders_from_inventory_tables.php
index 00d41bbae9..f631f06e11 100644
--- a/database/migrations/2026_08_03_142000_backfill_orders_from_inventory_tables.php
+++ b/database/migrations/2026_08_03_142000_backfill_orders_from_inventory_tables.php
@@ -7,25 +7,29 @@ use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
- * Backfill the Orders / OrderItems tables from the pre-existing
- * order_number columns on accessories, consumables, components, and
- * assets. One Order row is created per unique (order_number,
- * supplier_id, company_id) tuple across all four tables, and each
- * source inventory row becomes an OrderItem line under that Order.
+ * Backfill the Orders / OrderItems tables from every pre-existing
+ * inventory row on accessories, consumables, components, and assets.
+ * Every source row becomes an OrderItem so the polymorphic ledger is
+ * complete after the migration runs — the reconcile migration
+ * (`2026_08_03_144000_...`) relies on every row having at least one
+ * OrderItem to represent its starting qty.
+ *
+ * Rows with a non-null order_number dedupe on
+ * (order_number, supplier_id, company_id) so multiple inventory lines
+ * placed against the same PO collapse under one shared Order. A raw
+ * string like "PO-42" can legitimately recur across different suppliers
+ * or across companies in FMCS installs, so the supplier and company
+ * are part of the dedupe key.
+ *
+ * Rows with a null / empty order_number get a fresh Order per row (no
+ * dedupe). Blank order_number is a distinct transaction each time, not
+ * a bucket to pool anonymous acquisitions into — same convention as
+ * HandlesAdjustQuantity::resolveOrderForAdjustment at runtime.
*
* Licenses are intentionally out of scope. Per-seat product-key
* semantics need their own design pass before License can join the
* Orders flow cleanly.
*
- * The dedupe key is intentionally (order_number, supplier_id, company_id)
- * rather than just order_number: a raw string like "PO-42" can legitimately
- * recur across different suppliers or across companies in FMCS installs,
- * and collapsing them would rewrite history.
- *
- * Rows with a null / empty order_number are skipped: they represent
- * inventory rows never associated with any order, and there's nothing
- * for the Orders table to record.
- *
* The follow-up rename migration (`2026_08_03_143000_...`) renames the
* source columns to `legacy_*` names once this backfill has run.
*/
@@ -79,8 +83,6 @@ return new class extends Migration
'created_by',
'created_at',
])
- ->whereNotNull('order_number')
- ->where('order_number', '!=', '')
->orderBy('id')
->chunkById(500, function ($rows) use ($modelClass, $table, $hasQtyColumn, &$orderIndex) {
// Chunked pull grabs qty separately since assets
@@ -95,13 +97,31 @@ return new class extends Migration
: [];
foreach ($rows as $row) {
- $key = ($row->order_number ?? '')
- .'|'.($row->supplier_id ?? '')
- .'|'.($row->company_id ?? '');
+ $hasOrderNumber = $row->order_number !== null && $row->order_number !== '';
+
+ if ($hasOrderNumber) {
+ $key = $row->order_number
+ .'|'.($row->supplier_id ?? '')
+ .'|'.($row->company_id ?? '');
- if (! array_key_exists($key, $orderIndex)) {
- $orderIndex[$key] = DB::table('orders')->insertGetId([
- 'order_number' => $row->order_number,
+ if (! array_key_exists($key, $orderIndex)) {
+ $orderIndex[$key] = DB::table('orders')->insertGetId([
+ 'order_number' => $row->order_number,
+ 'supplier_id' => $row->supplier_id,
+ 'company_id' => $row->company_id,
+ 'purchase_date' => $row->purchase_date,
+ 'created_by' => $row->created_by,
+ 'created_at' => $row->created_at ?? now(),
+ 'updated_at' => $row->created_at ?? now(),
+ ]);
+ }
+ $orderId = $orderIndex[$key];
+ } else {
+ // No order_number → fresh Order per row.
+ // Matches the runtime convention in
+ // HandlesAdjustQuantity::resolveOrderForAdjustment.
+ $orderId = DB::table('orders')->insertGetId([
+ 'order_number' => null,
'supplier_id' => $row->supplier_id,
'company_id' => $row->company_id,
'purchase_date' => $row->purchase_date,
@@ -112,7 +132,7 @@ return new class extends Migration
}
DB::table('order_items')->insert([
- 'order_id' => $orderIndex[$key],
+ 'order_id' => $orderId,
'item_type' => $modelClass,
'item_id' => $row->id,
'qty' => max(1, (int) ($qtyMap[$row->id] ?? 1)),
diff --git a/database/migrations/2026_08_03_144000_reconcile_inventory_qty_from_action_logs.php b/database/migrations/2026_08_03_144000_reconcile_inventory_qty_from_action_logs.php
index 350e85726f..ea62974bf2 100644
--- a/database/migrations/2026_08_03_144000_reconcile_inventory_qty_from_action_logs.php
+++ b/database/migrations/2026_08_03_144000_reconcile_inventory_qty_from_action_logs.php
@@ -68,6 +68,35 @@ return new class extends Migration
continue;
}
+ // Legacy-data safety: pre-replenish deployments never
+ // populated action_logs.quantity for `create` events
+ // (the `qty_adjust` action_type didn't exist), so the
+ // ledger sum comes out at 0 or a stray small value on
+ // every legacy row. Overwriting the real qty with that
+ // stray value drives it below the currently-in-use
+ // count and renders "-N Remaining" in the UI. Skip
+ // when the ledger has no meaningful entries or when
+ // the sum would push qty below in-use.
+ if ($expected === 0 && $actual > 0) {
+ continue;
+ }
+
+ $inUse = method_exists($model, 'currentlyInUseCount')
+ ? (int) $model->currentlyInUseCount()
+ : 0;
+
+ if ($expected < $inUse) {
+ Log::info(sprintf(
+ 'Skipping reconcile of %s#%d: ledger sum %d < in-use count %d (probably stale pre-replenish action_logs)',
+ $modelClass,
+ $model->id,
+ $expected,
+ $inUse,
+ ));
+
+ continue;
+ }
+
Log::info(sprintf(
'Reconciling %s#%d qty: %d -> %d (ledger sum)',
$modelClass,
diff --git a/database/migrations/2026_08_03_148000_repair_inventory_qty_below_in_use.php b/database/migrations/2026_08_03_148000_repair_inventory_qty_below_in_use.php
new file mode 100644
index 0000000000..e6715f44f6
--- /dev/null
+++ b/database/migrations/2026_08_03_148000_repair_inventory_qty_below_in_use.php
@@ -0,0 +1,92 @@
+<?php
+
+use App\Models\Accessory;
+use App\Models\Component;
+use App\Models\Consumable;
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+
+/**
+ * Data-repair pass for installs that already ran the pre-fix version
+ * of `2026_08_03_144000_reconcile_inventory_qty_from_action_logs.php`.
+ *
+ * The pre-fix reconcile migration overwrote `qty` on legacy
+ * accessories / consumables / components with `SUM(action_logs.quantity)`
+ * for `create` + `qty_adjust` events. Pre-replenish deployments never
+ * populated that column for `create` events, so the sum came out at 0
+ * or a stray small value, and the migration blindly wrote it. Rows
+ * with existing checkouts got dragged below the in-use count and
+ * rendered as "-N Remaining" in the UI (issue observed on the
+ * grokability.com production instance post-upgrade).
+ *
+ * This migration is a floor-restorer. For every accessory / consumable
+ * / component where the current `qty` is below the count of units
+ * currently in use, `qty` is bumped up to that in-use count so the UI
+ * stops rendering negative remaining. This does not recover the true
+ * pre-upgrade qty — that data was overwritten and there's no ledger
+ * to reconstruct from — the admin still needs to run adjust-quantity
+ * per item to re-establish an accurate count.
+ *
+ * The repair is idempotent: on installs where the fixed reconcile
+ * migration has run and no drift exists, every row has qty >= in-use
+ * and this is a no-op.
+ *
+ * License is deliberately excluded, matching the scope of the
+ * reconcile migration that caused the damage.
+ */
+return new class extends Migration
+{
+ private const REPAIR_MODELS = [
+ Accessory::class,
+ Consumable::class,
+ Component::class,
+ ];
+
+ public function up(): void
+ {
+ foreach (self::REPAIR_MODELS as $modelClass) {
+ $this->repairFor($modelClass);
+ }
+ }
+
+ public function down(): void
+ {
+ // No-op. Reversing the repair would set qty back to a value
+ // that renders as negative remaining, which is the bug this
+ // migration exists to fix.
+ }
+
+ private function repairFor(string $modelClass): void
+ {
+ $modelClass::query()->chunkById(500, function ($rows) use ($modelClass) {
+ foreach ($rows as $model) {
+ $inUse = method_exists($model, 'currentlyInUseCount')
+ ? (int) $model->currentlyInUseCount()
+ : 0;
+
+ $actual = (int) $model->qty;
+
+ if ($actual >= $inUse) {
+ continue;
+ }
+
+ Log::info(sprintf(
+ 'Repairing %s#%d qty: %d -> %d (below in-use count)',
+ $modelClass,
+ $model->id,
+ $actual,
+ $inUse,
+ ));
+
+ // Direct DB update, same rationale as the reconcile
+ // migration: bypass the AdjustsQuantity trait so no
+ // spurious `qty_adjust` action_log is written for a
+ // data-integrity repair the admin didn't request.
+ DB::table((new $modelClass)->getTable())
+ ->where('id', $model->id)
+ ->update(['qty' => $inUse]);
+ }
+ });
+ }
+};