A free open source IT asset/license management system
Updated migrations and backfill for order+order items approach
snipeb23b1083a231
diff --git a/app/Models/OrderItem.php b/app/Models/OrderItem.phpindex 4e422f8508..8e2aff5fbb 100644--- a/app/Models/OrderItem.php+++ b/app/Models/OrderItem.php@@ -6,6 +6,7 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsTo;use Illuminate\Database\Eloquent\Relations\MorphTo;+use Illuminate\Database\Eloquent\SoftDeletes;/*** One line on an Order. Polymorphic to the inventory model that was@@ -17,6 +18,7 @@ use Illuminate\Database\Eloquent\Relations\MorphTo;class OrderItem extends Model{use HasFactory;+ use SoftDeletes;protected $table = 'order_items';diff --git a/database/migrations/2026_08_03_141000_create_orders_and_order_items_tables.php b/database/migrations/2026_08_03_141000_create_orders_and_order_items_tables.phpindex 2400a77e54..22a00d43cd 100644--- a/database/migrations/2026_08_03_141000_create_orders_and_order_items_tables.php+++ b/database/migrations/2026_08_03_141000_create_orders_and_order_items_tables.php@@ -71,6 +71,12 @@ return new class extends Migration// rounding drift on aggregate totals.$table->decimal('price', 20, 4)->nullable();$table->timestamps();+ // SoftDeletes so a force-delete on a referenced inventory+ // row (Accessory / Consumable / Component / Asset / License)+ // can trash the OrderItem line without losing the+ // acquisition ledger. HasOrders::bootHasOrders() wires the+ // observer that flips this flag on parent force-delete.+ $table->softDeletes();$table->index('order_id');$table->index(['item_type', 'item_id']);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.phpnew file mode 100644index 0000000000..2ed9f2011d--- /dev/null+++ b/database/migrations/2026_08_03_142000_backfill_orders_from_inventory_tables.php@@ -0,0 +1,127 @@+<?php++use Illuminate\Database\Migrations\Migration;+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, assets,+ * and licenses. One Order row is created per unique+ * (order_number, supplier_id, company_id) tuple across all five tables,+ * and each source inventory row becomes an OrderItem line under that+ * Order.+ *+ * 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 migration (`drop_order_number_from_inventory_tables`)+ * removes the source columns once this backfill has run.+ */+return new class extends Migration+{+ /**+ * Model class => source table name. Order determines the sequence+ * OrderItem rows are created in (purely cosmetic — a chronological+ * report would sort by Order.purchase_date or Order.created_at+ * anyway).+ */+ private const SOURCES = [+ \App\Models\Accessory::class => 'accessories',+ \App\Models\Consumable::class => 'consumables',+ \App\Models\Component::class => 'components',+ \App\Models\Asset::class => 'assets',+ \App\Models\License::class => 'licenses',+ ];++ public function up(): void+ {+ // Order dedupe cache: (order_number|supplier_id|company_id) => order_id.+ // Keeps us from hitting the DB with a lookup per source row.+ $orderIndex = [];++ foreach (self::SOURCES as $modelClass => $table) {+ // Defensive skip: if a source table has already had its+ // order_number column dropped (partial rerun, hand rollback,+ // schema drift), there's nothing to backfill from and the+ // migration should keep moving rather than blow up.+ if (! Schema::hasColumn($table, 'order_number')) {+ continue;+ }++ $qtyColumn = ($table === 'licenses') ? 'seats' : 'qty';+ $hasQtyColumn = Schema::hasColumn($table, $qtyColumn);++ DB::table($table)+ ->select([+ 'id',+ 'order_number',+ 'supplier_id',+ 'company_id',+ 'purchase_date',+ 'purchase_cost',+ 'created_by',+ 'created_at',+ ])+ ->whereNotNull('order_number')+ ->where('order_number', '!=', '')+ ->orderBy('id')+ ->chunkById(500, function ($rows) use ($modelClass, $table, $hasQtyColumn, $qtyColumn, &$orderIndex) {+ // Chunked pull grabs qty separately since not every+ // source table has the same qty-column name and we+ // want the primary select above to stay portable.+ $qtyMap = $hasQtyColumn+ ? DB::table($table)+ ->whereIn('id', $rows->pluck('id'))+ ->pluck($qtyColumn, 'id')+ ->all()+ : [];++ foreach ($rows as $row) {+ $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,+ '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(),+ ]);+ }++ DB::table('order_items')->insert([+ 'order_id' => $orderIndex[$key],+ 'item_type' => $modelClass,+ 'item_id' => $row->id,+ 'qty' => max(1, (int) ($qtyMap[$row->id] ?? 1)),+ 'price' => $row->purchase_cost,+ 'created_at' => $row->created_at ?? now(),+ 'updated_at' => $row->created_at ?? now(),+ ]);+ }+ });+ }+ }++ public function down(): void+ {+ // Reversible only in a coarse sense — the drop wipes every row+ // in both tables rather than trying to reconstruct the original+ // per-source-column state. Combined with the follow-up+ // drop-columns migration (which does have a real down()), a full+ // rollback restores the pre-Orders layout.+ DB::table('order_items')->delete();+ DB::table('orders')->delete();+ }+};diff --git a/database/migrations/2026_08_03_143000_drop_order_number_from_inventory_tables.php b/database/migrations/2026_08_03_143000_drop_order_number_from_inventory_tables.phpnew file mode 100644index 0000000000..e961f4f2f0--- /dev/null+++ b/database/migrations/2026_08_03_143000_drop_order_number_from_inventory_tables.php@@ -0,0 +1,60 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++/**+ * Drop the now-orphaned `order_number` string columns from the five+ * inventory tables. Runs after the `backfill_orders_from_inventory_tables`+ * migration has moved every non-null value into a real Order + OrderItem+ * pair; anything still pointing at the parent column is either null or+ * legitimately stale.+ *+ * Deliberately does not touch Asset / License business logic — those+ * models had already dropped `order_number` from their fillable /+ * searchable / validation arrays in the same PR. The DB column is the+ * last piece of the old shape.+ */+return new class extends Migration+{+ private const TABLES = [+ 'accessories',+ 'consumables',+ 'components',+ 'assets',+ 'licenses',+ ];++ public function up(): void+ {+ foreach (self::TABLES as $table) {+ if (! Schema::hasColumn($table, 'order_number')) {+ continue;+ }++ Schema::table($table, function (Blueprint $t) {+ $t->dropColumn('order_number');+ });+ }+ }++ public function down(): void+ {+ // Restore as a plain nullable string column. No data recovery —+ // callers that want the pre-Orders values back need to roll the+ // backfill migration first and then rehydrate this column from+ // the OrderItem rows themselves. Leaving that manual because+ // the rehydration is inherently lossy (many-to-one order → one+ // row here means we'd have to pick one Order per parent row).+ foreach (self::TABLES as $table) {+ if (Schema::hasColumn($table, 'order_number')) {+ continue;+ }++ Schema::table($table, function (Blueprint $t) {+ $t->string('order_number')->nullable();+ });+ }+ }+};