A free open source IT asset/license management system
Refactored to move initial create order logic into the trait
snipe037f50b1a552
diff --git a/app/Http/Traits/HandlesAdjustQuantity.php b/app/Http/Traits/HandlesAdjustQuantity.phpindex 10969b4826..ef3df58f09 100644--- a/app/Http/Traits/HandlesAdjustQuantity.php+++ b/app/Http/Traits/HandlesAdjustQuantity.php@@ -105,7 +105,7 @@ trait HandlesAdjustQuantity): ?int {// Orders / OrderItems record purchases only. A negative delta is// a correction / consumption / loss and a zero delta is a- // physical-count audit — neither is a purchase, so neither+ // physical-count audit, neither is a purchase, so neither// writes to the Orders ledger. Both still write an action_log// entry (that's the QuantityAdjust source of truth), just// without an order_item_id link.@@ -113,7 +113,18 @@ trait HandlesAdjustQuantityreturn null;}- $payload = $this->extractOrderPayloadFromRequest($request);+ $orderNumberRaw = trim((string) $request->input('order_number', ''));+ $currencyRaw = $request->filled('currency') ? trim((string) $request->input('currency')) : null;+ $noteRaw = $request->filled('note') ? trim((string) $request->input('note')) : null;++ $payload = [+ 'order_number' => $orderNumberRaw !== '' ? $orderNumberRaw : null,+ 'supplier_id' => $request->filled('supplier_id') ? (int) $request->input('supplier_id') : null,+ 'purchase_date' => $request->filled('purchase_date') ? $request->input('purchase_date') : null,+ 'unit_cost' => $request->filled('unit_cost') ? (float) $request->input('unit_cost') : null,+ 'currency' => ($currencyRaw !== null && $currencyRaw !== '') ? $currencyRaw : null,+ 'notes' => ($noteRaw !== null && $noteRaw !== '') ? $noteRaw : null,+ ];if ($this->orderPayloadIsEmpty($payload)) {return null;@@ -123,83 +134,58 @@ trait HandlesAdjustQuantity// on. A blank order_number is a distinct transaction each time// (own timestamp, supplier, cost, currency), not a bucket to// pool anonymous acquisitions into. purchase_date is part of- // the dedup key because Snipe-IT has no partial-receipt concept- // — every Order is a completed receipt-in-hand, so "same+ // the dedup key because Snipe-IT has no partial-receipt concept,+ // every Order is a completed receipt-in-hand, so "same// order_number on a different receipt date" is a distinct// event, not a staggered delivery of one order. created_by is// set via property assignment rather than mass-fill because// it's guarded on both Order and OrderItem to prevent forgery.- $order = $this->findOrCreateOrderForPayload($payload, $model);-- $orderItem = new OrderItem([- 'order_id' => $order->id,- 'item_type' => $model::class,- 'item_id' => $model->id,- // OrderItem.qty is always positive. The delta sign lives on- // the sibling action_log.- 'qty' => max(1, abs($delta)),- 'price' => $payload['unit_cost'],- ]);- $orderItem->created_by = auth()->id();- $orderItem->save();-- return $orderItem->id;- }-- /**- * Resolve the Order the OrderItem line will hang off of.- * Non-blank order_number dedupes on (order_number, supplier_id,- * company_id, purchase_date); blank order_number always mints a- * fresh row.- */- private function findOrCreateOrderForPayload(array $payload, Model $model): Order- {$companyId = $model->company_id ?? null;if ($payload['order_number'] === null) {- return $this->createOrder($payload, $companyId);- }-- $order = Order::firstOrNew(- [+ $order = new Order(['order_number' => $payload['order_number'],'supplier_id' => $payload['supplier_id'],'company_id' => $companyId,'purchase_date' => $payload['purchase_date'],- ],- ['currency' => $payload['currency'],'notes' => $payload['notes'],- ],- );-- if (! $order->exists) {+ ]);$order->created_by = auth()->id();$order->save();- }+ } else {+ $order = Order::firstOrNew(+ [+ 'order_number' => $payload['order_number'],+ 'supplier_id' => $payload['supplier_id'],+ 'company_id' => $companyId,+ 'purchase_date' => $payload['purchase_date'],+ ],+ [+ 'currency' => $payload['currency'],+ 'notes' => $payload['notes'],+ ],+ );- return $order;- }+ if (! $order->exists) {+ $order->created_by = auth()->id();+ $order->save();+ }+ }- /**- * Persist a new Order with the given payload. created_by is set via- * property assignment because it's guarded on the model to prevent- * caller-supplied user_id forgery via mass-assignment.- */- private function createOrder(array $payload, ?int $companyId): Order- {- $order = new Order([- 'order_number' => $payload['order_number'],- 'supplier_id' => $payload['supplier_id'],- 'company_id' => $companyId,- 'purchase_date' => $payload['purchase_date'],- 'currency' => $payload['currency'],- 'notes' => $payload['notes'],+ $orderItem = new OrderItem([+ 'order_id' => $order->id,+ 'item_type' => $model::class,+ 'item_id' => $model->id,+ // OrderItem.qty is always positive. The delta sign lives on+ // the sibling action_log.+ 'qty' => max(1, abs($delta)),+ 'price' => $payload['unit_cost'],]);- $order->created_by = auth()->id();- $order->save();+ $orderItem->created_by = auth()->id();+ $orderItem->save();- return $order;+ return $orderItem->id;}/**@@ -217,7 +203,14 @@ trait HandlesAdjustQuantity*/protected function enrichInitialOrderFromRequest(Request $request, Model $item): void{- $orderInputs = $this->extractOrderEnrichmentInputs($request);+ $orderInputs = [+ 'order_number' => $this->trimmedOrNull($request->input('order_number')),+ 'currency' => $this->trimmedOrNull($request->input('currency')),+ 'supplier_id' => $request->filled('supplier_id') ? (int) $request->input('supplier_id') : null,+ 'purchase_date' => $request->filled('purchase_date') ? $request->input('purchase_date') : null,+ 'purchase_cost' => $request->filled('purchase_cost') ? (float) $request->input('purchase_cost') : null,+ 'notes' => $this->trimmedOrNull($request->input('notes')),+ ];$purchaseCost = $orderInputs['purchase_cost'];if ($this->initialOrderEnrichmentIsEmpty($orderInputs, $purchaseCost)) {@@ -239,24 +232,6 @@ trait HandlesAdjustQuantity}}- /**- * Normalize request inputs into the shape the initial-Order- * enrichment compares against. Empty strings on the free-text- * columns collapse to null so the diff step treats "field was blank- * on the form" as "no change requested," not "clear the DB value."- */- private function extractOrderEnrichmentInputs(Request $request): array- {- return [- 'order_number' => $this->trimmedOrNull($request->input('order_number')),- 'currency' => $this->trimmedOrNull($request->input('currency')),- 'supplier_id' => $request->filled('supplier_id') ? (int) $request->input('supplier_id') : null,- 'purchase_date' => $request->filled('purchase_date') ? $request->input('purchase_date') : null,- 'purchase_cost' => $request->filled('purchase_cost') ? (float) $request->input('purchase_cost') : null,- 'notes' => $this->trimmedOrNull($request->input('notes')),- ];- }-private function trimmedOrNull(mixed $raw): ?string{if ($raw === null) {@@ -307,28 +282,6 @@ trait HandlesAdjustQuantityreturn $updates;}- /**- * Pull the acquisition-metadata fields off the request and- * normalize each into the shape Order needs.- *- * @return array{order_number: ?string, supplier_id: ?int, purchase_date: ?string, unit_cost: ?float, currency: ?string}- */- private function extractOrderPayloadFromRequest(Request $request): array- {- $orderNumberRaw = trim((string) $request->input('order_number', ''));- $currencyRaw = $request->filled('currency') ? trim((string) $request->input('currency')) : null;- $noteRaw = $request->filled('note') ? trim((string) $request->input('note')) : null;-- return [- 'order_number' => $orderNumberRaw !== '' ? $orderNumberRaw : null,- 'supplier_id' => $request->filled('supplier_id') ? (int) $request->input('supplier_id') : null,- 'purchase_date' => $request->filled('purchase_date') ? $request->input('purchase_date') : null,- 'unit_cost' => $request->filled('unit_cost') ? (float) $request->input('unit_cost') : null,- 'currency' => ($currencyRaw !== null && $currencyRaw !== '') ? $currencyRaw : null,- 'notes' => ($noteRaw !== null && $noteRaw !== '') ? $noteRaw : null,- ];- }-/*** True when the request carried no acquisition context. Audit-only* zero-delta submissions with no order metadata fall through herediff --git a/app/Importer/ItemImporter.php b/app/Importer/ItemImporter.phpindex 43b7f73582..069f153170 100644--- a/app/Importer/ItemImporter.php+++ b/app/Importer/ItemImporter.php@@ -8,7 +8,6 @@ use App\Models\Company;use App\Models\CompanyableScope;use App\Models\Location;use App\Models\Manufacturer;-use App\Models\Order;use App\Models\Statuslabel;use App\Models\Supplier;use App\Models\User;@@ -238,41 +237,6 @@ class ItemImporter extends Importer* grow its own Order-creation wiring when that flow is reworked.*/protected function recordOrderForImportedRow($model, array $row): void- {- $payload = $this->buildOrderEnrichmentPayload($row);-- if ($payload === null) {- return;- }-- // Every accessory / consumable / component / asset create fires- // its observer which writes an initial Order + OrderItem from- // parent attributes (with null acquisition metadata — parents- // don't carry those columns any more). The importer's job here- // is to enrich the observer-created rows with the CSV's values.- $initialLine = $model->orderItems()->latest('id')->first();- if (! $initialLine || ! $initialLine->order) {- return;- }-- $updates = $this->diffOrderAgainstPayload($initialLine->order, $payload);- if ($updates !== []) {- $initialLine->order->update($updates);- }-- $purchaseCost = $payload['purchase_cost'];- if ($purchaseCost !== null && (float) $initialLine->price !== $purchaseCost) {- $initialLine->update(['price' => $purchaseCost]);- }- }-- /**- * Assemble the enrichment payload from the CSV row and the- * sub-importer's already-normalized $this->item. Returns null when- * the row carried no acquisition metadata at all, so the caller- * can short-circuit before pulling the initial Order off the DB.- */- private function buildOrderEnrichmentPayload(array $row): ?array{$orderNumber = trim((string) $this->findCsvMatch($row, 'order_number'));$currency = trim((string) $this->findCsvMatch($row, 'currency'));@@ -281,48 +245,48 @@ class ItemImporter extends Importer$rawCost = $this->item['purchase_cost'] ?? null;$purchaseCost = ($rawCost !== null && $rawCost !== '') ? (float) $rawCost : null;- $isEmpty = $orderNumber === ''+ if ($orderNumber === ''&& $currency === ''&& $supplierId === null&& $purchaseDate === null- && $purchaseCost === null;-- if ($isEmpty) {- return null;+ && $purchaseCost === null+ ) {+ return;}- return [- 'order_number' => $orderNumber,- 'currency' => $currency,- 'supplier_id' => $supplierId,- 'purchase_date' => $purchaseDate,- 'purchase_cost' => $purchaseCost,- ];- }+ // Every accessory / consumable / component / asset create fires+ // its observer which writes an initial Order + OrderItem from+ // parent attributes (with null acquisition metadata, parents+ // don't carry those columns any more). The importer's job here+ // is to enrich the observer-created rows with the CSV's values.+ $initialLine = $model->orderItems()->latest('id')->first();+ if (! $initialLine || ! $initialLine->order) {+ return;+ }- /**- * Compute the field-level diff between the payload and the- * observer-written Order. Only changed columns are returned so the- * subsequent update() writes the minimum set.- */- private function diffOrderAgainstPayload(Order $order, array $payload): array- {+ $order = $initialLine->order;$updates = [];- if ($payload['order_number'] !== '' && $order->order_number !== $payload['order_number']) {- $updates['order_number'] = $payload['order_number'];+ if ($orderNumber !== '' && $order->order_number !== $orderNumber) {+ $updates['order_number'] = $orderNumber;}- if ($payload['currency'] !== '' && $order->currency !== $payload['currency']) {- $updates['currency'] = $payload['currency'];+ if ($currency !== '' && $order->currency !== $currency) {+ $updates['currency'] = $currency;}- if ($payload['supplier_id'] !== null && (int) $order->supplier_id !== (int) $payload['supplier_id']) {- $updates['supplier_id'] = (int) $payload['supplier_id'];+ if ($supplierId !== null && (int) $order->supplier_id !== (int) $supplierId) {+ $updates['supplier_id'] = (int) $supplierId;}- if ($payload['purchase_date'] !== null && optional($order->purchase_date)->toDateString() !== (string) $payload['purchase_date']) {- $updates['purchase_date'] = $payload['purchase_date'];+ if ($purchaseDate !== null && optional($order->purchase_date)->toDateString() !== (string) $purchaseDate) {+ $updates['purchase_date'] = $purchaseDate;}- return $updates;+ if ($updates !== []) {+ $order->update($updates);+ }++ if ($purchaseCost !== null && (float) $initialLine->price !== $purchaseCost) {+ $initialLine->update(['price' => $purchaseCost]);+ }}/**diff --git a/app/Models/Traits/HasOrders.php b/app/Models/Traits/HasOrders.phpindex 579f1a0944..9983408e89 100644--- a/app/Models/Traits/HasOrders.php+++ b/app/Models/Traits/HasOrders.php@@ -2,8 +2,10 @@namespace App\Models\Traits;+use App\Models\Actionlog;use App\Models\Order;use App\Models\OrderItem;+use App\Models\Setting;use App\Models\Supplier;use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Relations\HasManyThrough;@@ -122,8 +124,8 @@ trait HasOrders];}- $defaultSupplier = $this->getAttribute('default_supplier_id');- $defaultCost = $this->getAttribute('default_purchase_cost');+ $defaultSupplier = $this->default_supplier_id;+ $defaultCost = $this->default_purchase_cost;if ($defaultSupplier === null && $defaultCost === null) {return null;@@ -157,7 +159,7 @@ trait HasOrdersreturn $cachedSupplier;}- $supplierId = $this->lastOrderSupplierId() ?? $this->getAttribute('default_supplier_id');+ $supplierId = $this->lastOrderSupplierId() ?? $this->default_supplier_id;return $supplierId ? Supplier::find($supplierId) : null;}@@ -283,4 +285,135 @@ trait HasOrders->selectRaw('COALESCE(SUM(order_items.qty * order_items.price), 0)'),])->orderBy('sort_total_order_cost', $direction);}++ /**+ * Sum every OrderItem's line total (qty × price) grouped by the+ * parent Order's currency, so mixed-currency acquisitions render+ * as a per-currency breakdown instead of a single misleading total.+ *+ * Returns [] when the item has no OrderItems yet or every line has+ * a null price. The info-panel skips the "Total cost" line entirely+ * in that case rather than showing 0. Orders / OrderItems is the+ * single source of truth for acquisition cost, no fallback to+ * legacy_* columns (those will be dropped in a later version).+ *+ * @return array<string, float> currency code => sum in that currency+ */+ public function totalCostSumByCurrency(): array+ {+ return $this->orderItems()+ ->with('order:id,currency')+ ->get()+ ->reduce(function (array $carry, OrderItem $line) {+ if ($line->price === null) {+ return $carry;+ }+ $currency = $line->order?->currency+ ?? Setting::getSettings()?->default_currency+ ?? '';+ $carry[$currency] = ($carry[$currency] ?? 0) + ($line->qty * (float) $line->price);++ return $carry;+ }, []);+ }++ /**+ * Naive cross-currency sum, kept for backwards compatibility with+ * external callers. New code should prefer totalCostSumByCurrency()+ * so mixed-currency totals stay disambiguated.+ */+ public function totalCostSum()+ {+ return array_sum($this->totalCostSumByCurrency()) ?: null;+ }++ /**+ * True when every recorded acquisition for this item came from the+ * same supplier. Info-panel supplier row hides when false so a+ * single supplier name doesn't misrepresent multi-supplier history.+ */+ public function hasConsistentSupplier(): bool+ {+ return $this->orderItems()+ ->with('order:id,supplier_id')+ ->get()+ ->map(fn (OrderItem $line) => $line->order?->supplier_id)+ ->filter()+ ->unique()+ ->count() <= 1;+ }++ /**+ * Called from the inventory observer's `created` event. When the row+ * lands with qty > 0, write a placeholder Order + OrderItem to+ * represent the initial acquisition. Transaction metadata+ * (supplier_id, purchase_date, purchase_cost, currency, order_number)+ * only lives on Orders / OrderItems now, form-driven creates enrich+ * the placeholder via the controller's enrichInitialOrderFromRequest,+ * and factory / seeder paths fill it via an afterCreating hook.+ *+ * qty=0/null is container-only: a bare inventory row with no initial+ * acquisition. The Order + OrderItem write is skipped entirely,+ * later adjust-quantity events write their own when stock actually+ * arrives.+ *+ * The create action_log always writes, linked to the OrderItem when+ * one exists and unlinked (order_item_id = null) for container-only+ * creates. quantity captures the initial on-hand count so auditors+ * get a "started with N units" anchor, subsequent QuantityAdjust+ * logs record deltas rather than running totals.+ */+ public function writeInitialInventoryCreate(): void+ {+ $initialQty = (int) ($this->getAttributes()['qty'] ?? 0);+ $orderItem = $this->writeInitialOrderIfStocked($initialQty);++ $log = new Actionlog;+ $log->item_type = static::class;+ $log->item_id = $this->id;+ $log->created_at = date('Y-m-d H:i:s');+ // See AssetModelObserver::created for the seeder-friendly+ // auth fallback rationale.+ $log->created_by = auth()->id() ?? $this->created_by;+ $log->quantity = $initialQty;+ $log->order_item_id = $orderItem?->id;+ if ($this->imported) {+ $log->setActionSource('importer');+ }+ $log->logaction('create');+ }++ private function writeInitialOrderIfStocked(int $initialQty): ?OrderItem+ {+ if ($initialQty <= 0) {+ return null;+ }++ $locationCurrency = $this->location?->currency;+ $currency = ($locationCurrency !== '' && $locationCurrency !== null)+ ? $locationCurrency+ : Setting::getSettings()?->default_currency;++ $order = new Order([+ 'order_number' => null,+ 'supplier_id' => null,+ 'company_id' => $this->company_id,+ 'purchase_date' => null,+ 'currency' => $currency,+ ]);+ $order->created_by = $this->created_by ?? auth()->id();+ $order->save();++ $orderItem = new OrderItem([+ 'order_id' => $order->id,+ 'item_type' => static::class,+ 'item_id' => $this->id,+ 'qty' => $initialQty,+ 'price' => null,+ ]);+ $orderItem->created_by = $this->created_by ?? auth()->id();+ $orderItem->save();++ return $orderItem;+ }}diff --git a/app/Observers/AccessoryObserver.php b/app/Observers/AccessoryObserver.phpindex 1aa34481e9..5440305632 100644--- a/app/Observers/AccessoryObserver.php+++ b/app/Observers/AccessoryObserver.php@@ -4,12 +4,10 @@ namespace App\Observers;use App\Models\Accessory;use App\Models\Actionlog;-use App\Models\Order;-use App\Models\OrderItem;-use App\Models\Setting;class AccessoryObserver{+/*** Listen to the User created event.*@@ -35,8 +33,6 @@ class AccessoryObserver$logAction->item_id = $accessory->id;$logAction->created_at = date('Y-m-d H:i:s');$logAction->created_by = auth()->id();- // order_number moved off Accessory to the Orders / OrderItems- // data model — nothing to capture on the update log anymore.$logAction->log_meta = json_encode($changed);$logAction->logaction('update');}@@ -50,67 +46,7 @@ class AccessoryObserver*/public function created(Accessory $accessory){- $attrs = $accessory->getAttributes();- $initialQty = (int) ($attrs['qty'] ?? 0);-- // Only write an Order + OrderItem when the create carried real- // stock (qty > 0). qty=0/null means "container-only" — a bare- // accessory row without an initial acquisition — and there's no- // transaction to record. Later adjust-quantity events write- // their own Order + OrderItem when stock actually arrives.- //- // For qty > 0, the Order + OrderItem written here are- // placeholders. Transaction metadata (supplier_id, purchase_date,- // purchase_cost, currency, order_number) only lives on Orders /- // OrderItems now — form-driven creates enrich it via the- // controller's enrichInitialOrderFromRequest(), and factory /- // seeder paths fill it via an afterCreating hook.- $orderItem = null;- if ($initialQty > 0) {- $currency = ($accessory->location && $accessory->location->currency !== '' && $accessory->location->currency !== null)- ? $accessory->location->currency- : Setting::getSettings()?->default_currency;-- $order = new Order([- 'order_number' => null,- 'supplier_id' => null,- 'company_id' => $accessory->company_id,- 'purchase_date' => null,- 'currency' => $currency,- ]);- $order->created_by = $accessory->created_by ?? auth()->id();- $order->save();-- $orderItem = new OrderItem([- 'order_id' => $order->id,- 'item_type' => Accessory::class,- 'item_id' => $accessory->id,- 'qty' => $initialQty,- 'price' => null,- ]);- $orderItem->created_by = $accessory->created_by ?? auth()->id();- $orderItem->save();- }-- $logAction = new Actionlog;- $logAction->item_type = Accessory::class;- $logAction->item_id = $accessory->id;- $logAction->created_at = date('Y-m-d H:i:s');- // See AssetModelObserver::created for the seeder-friendly- // auth fallback rationale.- $logAction->created_by = auth()->id() ?? $accessory->created_by;- // Capture the initial on-hand qty so the create log gives auditors- // a "started with N units" anchor point. Subsequent QuantityAdjust- // logs record deltas, not running totals.- $logAction->quantity = $initialQty;- // Link the create log to the OrderItem when one exists. For- // container-only creates (qty=0) the log has no OrderItem to- // point at.- $logAction->order_item_id = $orderItem?->id;- if ($accessory->imported) {- $logAction->setActionSource('importer');- }- $logAction->logaction('create');+ $accessory->writeInitialInventoryCreate();}/**diff --git a/app/Observers/ComponentObserver.php b/app/Observers/ComponentObserver.phpindex 13c93d6b45..0070f27cc1 100644--- a/app/Observers/ComponentObserver.php+++ b/app/Observers/ComponentObserver.php@@ -4,12 +4,10 @@ namespace App\Observers;use App\Models\Actionlog;use App\Models\Component;-use App\Models\Order;-use App\Models\OrderItem;-use App\Models\Setting;class ComponentObserver{+/*** Listen to the User created event.*@@ -35,8 +33,6 @@ class ComponentObserver$logAction->created_at = date('Y-m-d H:i:s');$logAction->action_date = date('Y-m-d H:i:s');$logAction->created_by = auth()->id();- // order_number moved off Component to the Orders / OrderItems- // data model — nothing to capture on the update log anymore.$logAction->log_meta = json_encode($changed);if ($component->imported) {$logAction->setActionSource('importer');@@ -54,52 +50,7 @@ class ComponentObserver*/public function created(Component $component){- $attrs = $component->getAttributes();- $initialQty = (int) ($attrs['qty'] ?? 0);-- // Skip Order + OrderItem when qty=0/null (container-only).- // See AccessoryObserver::created for the full rationale.- $orderItem = null;- if ($initialQty > 0) {- $currency = ($component->location && $component->location->currency !== '' && $component->location->currency !== null)- ? $component->location->currency- : Setting::getSettings()?->default_currency;-- $order = new Order([- 'order_number' => null,- 'supplier_id' => null,- 'company_id' => $component->company_id,- 'purchase_date' => null,- 'currency' => $currency,- ]);- $order->created_by = $component->created_by ?? auth()->id();- $order->save();-- $orderItem = new OrderItem([- 'order_id' => $order->id,- 'item_type' => Component::class,- 'item_id' => $component->id,- 'qty' => $initialQty,- 'price' => null,- ]);- $orderItem->created_by = $component->created_by ?? auth()->id();- $orderItem->save();- }-- $logAction = new Actionlog;- $logAction->item_type = Component::class;- $logAction->item_id = $component->id;- $logAction->created_at = date('Y-m-d H:i:s');- $logAction->action_date = date('Y-m-d H:i:s');- // See AssetModelObserver::created for the seeder-friendly- // auth fallback rationale.- $logAction->created_by = auth()->id() ?? $component->created_by;- $logAction->quantity = $initialQty;- $logAction->order_item_id = $orderItem?->id;- if ($component->imported) {- $logAction->setActionSource('importer');- }- $logAction->logaction('create');+ $component->writeInitialInventoryCreate();}/**diff --git a/app/Observers/ConsumableObserver.php b/app/Observers/ConsumableObserver.phpindex f4343a0894..ba7b36c716 100644--- a/app/Observers/ConsumableObserver.php+++ b/app/Observers/ConsumableObserver.php@@ -4,14 +4,12 @@ namespace App\Observers;use App\Models\Actionlog;use App\Models\Consumable;-use App\Models\Order;-use App\Models\OrderItem;-use App\Models\Setting;use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Storage;class ConsumableObserver{+/*** Listen to the User created event.*@@ -36,8 +34,6 @@ class ConsumableObserver$logAction->item_id = $consumable->id;$logAction->created_at = date('Y-m-d H:i:s');$logAction->created_by = auth()->id();- // order_number moved off Consumable to the Orders / OrderItems- // data model — nothing to capture on the update log anymore.$logAction->log_meta = json_encode($changed);$logAction->logaction('update');}@@ -51,51 +47,7 @@ class ConsumableObserver*/public function created(Consumable $consumable){- $attrs = $consumable->getAttributes();- $initialQty = (int) ($attrs['qty'] ?? 0);-- // Skip Order + OrderItem when qty=0/null (container-only).- // See AccessoryObserver::created for the full rationale.- $orderItem = null;- if ($initialQty > 0) {- $currency = ($consumable->location && $consumable->location->currency !== '' && $consumable->location->currency !== null)- ? $consumable->location->currency- : Setting::getSettings()?->default_currency;-- $order = new Order([- 'order_number' => null,- 'supplier_id' => null,- 'company_id' => $consumable->company_id,- 'purchase_date' => null,- 'currency' => $currency,- ]);- $order->created_by = $consumable->created_by ?? auth()->id();- $order->save();-- $orderItem = new OrderItem([- 'order_id' => $order->id,- 'item_type' => Consumable::class,- 'item_id' => $consumable->id,- 'qty' => $initialQty,- 'price' => null,- ]);- $orderItem->created_by = $consumable->created_by ?? auth()->id();- $orderItem->save();- }-- $logAction = new Actionlog;- $logAction->item_type = Consumable::class;- $logAction->item_id = $consumable->id;- $logAction->created_at = date('Y-m-d H:i:s');- // See AssetModelObserver::created for the seeder-friendly- // auth fallback rationale.- $logAction->created_by = auth()->id() ?? $consumable->created_by;- $logAction->quantity = $initialQty;- $logAction->order_item_id = $orderItem?->id;- if ($consumable->imported) {- $logAction->setActionSource('importer');- }- $logAction->logaction('create');+ $consumable->writeInitialInventoryCreate();}/**