Skip to content

A free open source IT asset/license management system

Handle importers

snipe0a1884c79cf7
diff --git a/app/Http/Traits/HandlesAdjustQuantity.php b/app/Http/Traits/HandlesAdjustQuantity.php
index da3601e4e3..e246cae9e2 100644
--- a/app/Http/Traits/HandlesAdjustQuantity.php
+++ b/app/Http/Traits/HandlesAdjustQuantity.php
@@ -5,6 +5,8 @@ namespace App\Http\Traits;
use App\Http\Controllers\Controller;
use App\Http\Requests\AdjustQuantityRequest;
use App\Http\Requests\UploadFileRequest;
+use App\Models\Order;
+use App\Models\OrderItem;
use DomainException;
use Illuminate\Database\Eloquent\Model;
@@ -12,10 +14,11 @@ use Illuminate\Database\Eloquent\Model;
* Shared body of the adjust-quantity controller action. Web and API
* controllers for Accessory / Consumable / Component all run the same
* sequence — authorize the update, save an optional receipt attachment,
- * call the AdjustsQuantity model trait, and translate a DomainException
- * (would-drop-below-in-use) into the shared error string. Each controller
- * still owns its own response shape (redirect vs JSON) around that
- * shared work.
+ * resolve or create an Order + OrderItem for the requested acquisition,
+ * call the AdjustsQuantity model trait with the Order's id, and
+ * translate a DomainException (would-drop-below-in-use) into the shared
+ * error string. Each controller still owns its own response shape
+ * (redirect vs JSON) around that shared work.
*/
trait HandlesAdjustQuantity
{
@@ -41,11 +44,14 @@ trait HandlesAdjustQuantity
);
}
+ $delta = (int) $request->input('amount');
+ $orderId = $this->resolveOrderForAdjustment($request, $model, $delta);
+
try {
$model->adjustQuantity(
- (int) $request->input('amount'),
+ $delta,
$request->input('note'),
- $request->input('order_number'),
+ $orderId,
$filename,
);
} catch (DomainException) {
@@ -54,4 +60,62 @@ trait HandlesAdjustQuantity
return null;
}
+
+ /**
+ * Find or create an Order from the request payload and append one
+ * OrderItem line for the model / delta being adjusted. Returns the
+ * Order's id (or null if the request carried no acquisition info,
+ * e.g. an audit-only zero-delta submission with no order_number
+ * given).
+ *
+ * Dedupes on (order_number, supplier_id, company_id) so multiple
+ * adjust-quantity events that share those fields all land under a
+ * single Order row. Never dedupes the OrderItem side — each
+ * adjustment is its own line, matching the "one line per
+ * acquisition event" semantic.
+ */
+ protected function resolveOrderForAdjustment(
+ AdjustQuantityRequest $request,
+ Model $model,
+ int $delta,
+ ): ?int {
+ $orderNumber = trim((string) $request->input('order_number', ''));
+ $supplierId = $request->filled('supplier_id') ? (int) $request->input('supplier_id') : null;
+ $purchaseDate = $request->filled('purchase_date') ? $request->input('purchase_date') : null;
+
+ // No acquisition context in the request means don't create an
+ // Order. Audit-only submissions (zero delta with no supplier /
+ // order number / date) fall through here so we don't accrete
+ // meaningless Order rows for pure inventory counts.
+ if ($orderNumber === '' && $supplierId === null && $purchaseDate === null) {
+ return null;
+ }
+
+ $companyId = $model->company_id ?? null;
+
+ $order = Order::firstOrCreate(
+ [
+ 'order_number' => $orderNumber !== '' ? $orderNumber : null,
+ 'supplier_id' => $supplierId,
+ 'company_id' => $companyId,
+ ],
+ [
+ 'purchase_date' => $purchaseDate,
+ 'created_by' => auth()->id(),
+ ],
+ );
+
+ OrderItem::create([
+ 'order_id' => $order->id,
+ 'item_type' => $model::class,
+ 'item_id' => $model->id,
+ // OrderItem.qty is always positive — a decrement adjustment
+ // records the absolute number of units the line represents,
+ // and the delta sign lives on the sibling action_log.
+ 'qty' => max(1, abs($delta)),
+ 'price' => null,
+ ]);
+
+ return $order->id;
+ }
}
diff --git a/app/Importer/AccessoryImporter.php b/app/Importer/AccessoryImporter.php
index 7cb1d5dc9b..49c2e95710 100644
--- a/app/Importer/AccessoryImporter.php
+++ b/app/Importer/AccessoryImporter.php
@@ -50,7 +50,9 @@ class AccessoryImporter extends ItemImporter
$this->setItemFromCsvIfPresent($row, 'name', 'item_name');
$this->setItemFromCsvIfPresent($row, 'notes');
- $this->setItemFromCsvIfPresent($row, 'order_number');
+ // order_number is not on the Accessory model any more — recorded
+ // as an Order + OrderItem via recordOrderForImportedRow() after
+ // the create-branch save below.
$this->setItemFromCsvIfPresent($row, 'purchase_cost');
$this->setItemFromCsvIfPresent($row, 'model_number');
$this->setItemFromCsvIfPresent($row, 'min_amt');
@@ -140,6 +142,7 @@ class AccessoryImporter extends ItemImporter
if ($accessory->save()) {
$this->log('Accessory '.$name.' was created');
$this->recordCreated();
+ $this->recordOrderForImportedRow($accessory, $row);
$this->maybeCheckoutAccessory($accessory);
diff --git a/app/Importer/ConsumableImporter.php b/app/Importer/ConsumableImporter.php
index a0cb87f0ca..7a591e7fcd 100644
--- a/app/Importer/ConsumableImporter.php
+++ b/app/Importer/ConsumableImporter.php
@@ -50,7 +50,9 @@ class ConsumableImporter extends ItemImporter
$this->setItemFromCsvIfPresent($row, 'name', 'item_name');
$this->setItemFromCsvIfPresent($row, 'notes');
- $this->setItemFromCsvIfPresent($row, 'order_number');
+ // order_number is not on the Consumable model any more — recorded
+ // as an Order + OrderItem via recordOrderForImportedRow() after
+ // the create-branch save below.
$this->setItemFromCsvIfPresent($row, 'purchase_cost');
$this->setItemFromCsvIfPresent($row, 'model_number');
$this->setItemFromCsvIfPresent($row, 'min_amt');
diff --git a/app/Importer/ItemImporter.php b/app/Importer/ItemImporter.php
index 1d7615e158..0ed75a1e75 100644
--- a/app/Importer/ItemImporter.php
+++ b/app/Importer/ItemImporter.php
@@ -76,7 +76,12 @@ class ItemImporter extends Importer
$this->item['name'] = $this->findCsvMatch($row, 'item_name');
$this->item['notes'] = $this->findCsvMatch($row, 'notes');
- $this->item['order_number'] = $this->findCsvMatch($row, 'order_number');
+ // order_number is no longer a column on the inventory tables —
+ // it moved to the Orders / OrderItems data model. Sub-importers
+ // call ItemImporter::recordOrderForImportedRow() after the row
+ // saves to record the acquisition. Reading the value straight
+ // off the row inside that helper (rather than staging into
+ // $this->item['order_number']) avoids a fillable-drop no-op.
$this->item['purchase_cost'] = $this->findCsvMatch($row, 'purchase_cost');
$this->item['model_number'] = trim($this->findCsvMatch($row, 'model_number'));
$this->item['min_amt'] = $this->findCsvMatch($row, 'min_amt');
@@ -170,32 +175,28 @@ class ItemImporter extends Importer
* kicks in for models that use the trait (Accessory, Consumable,
* Component). For everything else it's a plain $model->update().
*
- * order_number rides on the QuantityAdjust log when qty also changed,
- * matching the API update contract. A DomainException from
- * adjustQuantity (would drop qty below the currently-in-use count)
- * is logged and the row's non-qty updates still stick.
+ * A DomainException from adjustQuantity (would drop qty below the
+ * currently-in-use count) is logged and the row's non-qty updates
+ * still stick. The AdjustsQuantity trait's `$orderNumber` argument
+ * is passed as null here because the Orders / OrderItems data model
+ * now owns the acquisition record; wiring the importer to also
+ * create an Order for the qty delta is a separate follow-up under
+ * the adjust-quantity flow rework.
*/
protected function applyUpdateWithQtyAdjust($model, array $sanitized): void
{
$qtyRequested = null;
- $orderNumber = null;
-
- if (method_exists($model, 'adjustQuantity')) {
- if (array_key_exists('qty', $sanitized)) {
- // Empty CSV cell (present but blank) means "don't touch qty"
- // on update — not "set qty to 0". Casting '' straight to (int)
- // 0 produced a delta of -currentQty and silently drained
- // inventory on any import row that included an empty
- // quantity column.
- if ($sanitized['qty'] !== '' && $sanitized['qty'] !== null) {
- $qtyRequested = (int) $sanitized['qty'];
- }
- unset($sanitized['qty']);
- }
- if (array_key_exists('order_number', $sanitized)) {
- $orderNumber = $sanitized['order_number'];
- unset($sanitized['order_number']);
+
+ if (method_exists($model, 'adjustQuantity') && array_key_exists('qty', $sanitized)) {
+ // Empty CSV cell (present but blank) means "don't touch qty"
+ // on update — not "set qty to 0". Casting '' straight to (int)
+ // 0 produced a delta of -currentQty and silently drained
+ // inventory on any import row that included an empty
+ // quantity column.
+ if ($sanitized['qty'] !== '' && $sanitized['qty'] !== null) {
+ $qtyRequested = (int) $sanitized['qty'];
}
+ unset($sanitized['qty']);
}
$qtyBefore = $qtyRequested !== null ? (int) $model->qty : null;
@@ -210,13 +211,65 @@ class ItemImporter extends Importer
$model->adjustQuantity(
$qtyRequested - $qtyBefore,
"Import: qty updated from {$qtyBefore} to {$qtyRequested}",
- $orderNumber,
+ null,
);
} catch (\DomainException) {
$this->log('Skipping qty change for '.($model->name ?? 'row').': would drop on-hand below the currently-checked-out count.');
}
}
+ /**
+ * Record the CSV row's order_number (if any) as an Order + OrderItem
+ * pair against the freshly-saved model. Called from the CREATE
+ * branch of every sub-importer that participates in the Orders data
+ * model (Accessory, Consumable, Component, Asset, License).
+ *
+ * Dedupes on the Order side via (order_number, supplier_id, company_id)
+ * so multiple items in the same CSV that share an order_number all
+ * land under a single Order row. Never dedupes on the OrderItem
+ * side — each imported row is its own line, matching the "one line
+ * per item purchased" semantic.
+ *
+ * Deliberately does not run on UPDATE imports: importer update mode
+ * means "the CSV has a corrected version of an existing row", not
+ * "a new purchase happened". The adjust-quantity flow is the path
+ * that records replenishment events for existing rows and will
+ * grow its own Order-creation wiring when that flow is reworked.
+ */
+ protected function recordOrderForImportedRow($model, array $row): void
+ {
+ $orderNumber = trim((string) $this->findCsvMatch($row, 'order_number'));
+ if ($orderNumber === '') {
+ return;
+ }
+
+ $supplierId = $model->supplier_id ?? null;
+ $companyId = $model->company_id ?? null;
+ $purchaseDate = $model->purchase_date ?? null;
+ $purchaseCost = $model->purchase_cost ?? null;
+ $qty = (int) ($model->qty ?? 1);
+
+ $order = \App\Models\Order::firstOrCreate(
+ [
+ 'order_number' => $orderNumber,
+ 'supplier_id' => $supplierId,
+ 'company_id' => $companyId,
+ ],
+ [
+ 'purchase_date' => $purchaseDate,
+ 'created_by' => $this->created_by,
+ ],
+ );
+
+ \App\Models\OrderItem::create([
+ 'order_id' => $order->id,
+ 'item_type' => $model::class,
+ 'item_id' => $model->id,
+ 'qty' => max(1, $qty),
+ 'price' => $purchaseCost,
+ ]);
+ }
+
/**
* Determines if a field needs updating
* Follows the following rules:
diff --git a/app/Models/Traits/AdjustsQuantity.php b/app/Models/Traits/AdjustsQuantity.php
index 0a748451ed..38b5aa6599 100644
--- a/app/Models/Traits/AdjustsQuantity.php
+++ b/app/Models/Traits/AdjustsQuantity.php
@@ -20,7 +20,9 @@ use Illuminate\Support\Facades\DB;
* action_logs with:
* - quantity = signed delta (positive for replenish, negative for decrement)
* - note = the operator's reason (required by the controller)
- * - order_number = optional PO / order reference
+ * - order_id = optional FK to the Order row this replenishment
+ * belongs to. The caller creates / looks up the Order and passes
+ * the id; the trait does not touch the Orders table itself.
*
* License overrides adjustQuantity() so that adding or removing
* seats also creates or destroys the matching LicenseSeat pivot rows.
@@ -48,11 +50,14 @@ trait AdjustsQuantity
}
/**
- * Every QuantityAdjust action_log row for this model. Exposed as a
- * relation so free-text search on inventory-style models can hit
- * historical order_number values through $searchableRelations even
- * though the parent's own order_number column is gone. Also useful
- * for the history-tab display and any per-item PO lookup.
+ * Every QuantityAdjust action_log row for this model. Used by the
+ * history tab to render replenishment / decrement events in
+ * chronological order alongside the other action types.
+ *
+ * Explicitly NOT wired into $searchableRelations — free-text search
+ * on order-number strings goes through the HasOrders trait's
+ * orders() HasManyThrough into the Orders table instead, since the
+ * action_logs row no longer carries the raw order-number string.
*/
public function quantityAdjustLogs(): MorphMany
{
@@ -86,7 +91,7 @@ trait AdjustsQuantity
* (which extends RuntimeException) as a
* below-floor violation.
*/
- public function adjustQuantity(int $delta, string $note, ?string $orderNumber = null, ?string $filename = null): void
+ public function adjustQuantity(int $delta, string $note, ?int $orderId = null, ?string $filename = null): void
{
$column = $this->getAdjustableQuantityColumn();
$current = (int) ($this->{$column} ?? 0);
@@ -99,7 +104,7 @@ trait AdjustsQuantity
);
}
- DB::transaction(function () use ($delta, $column, $note, $orderNumber, $filename) {
+ DB::transaction(function () use ($delta, $column, $note, $filename) {
// Use the query builder directly (not $this->increment) so
// the model's `updated` event doesn't fire. Firing it would
// write a second "update" action_log entry (with log_meta of
@@ -123,7 +128,7 @@ trait AdjustsQuantity
$log->item_id = $this->id;
$log->created_by = auth()->id();
$log->note = $note;
- $log->order_number = $orderNumber;
+ $log->order_id = $orderId;
$log->quantity = $delta;
// Receipt/invoice attaches to the same log row rather than a
// separate 'uploaded' entry, so the history table shows one
diff --git a/app/Models/Traits/HasOrders.php b/app/Models/Traits/HasOrders.php
index 0d0f5e1bbb..b550893523 100644
--- a/app/Models/Traits/HasOrders.php
+++ b/app/Models/Traits/HasOrders.php
@@ -10,15 +10,16 @@ use Illuminate\Database\Eloquent\Relations\MorphMany;
/**
* Wires an inventory model up to the polymorphic Orders + OrderItems
* data model. Consumed by Accessory / Consumable / Component (via the
- * AdjustsQuantity flow) and by Asset / License (for historical PO
+ * AdjustsQuantity flow) and by Asset / License (for historical order
* lookups even though they don't get replenished per-event).
*
* `orderItems()` is the direct polymorphic relation — one row per line
- * on a PO that referenced this model. `orders()` is a HasManyThrough
- * convenience that surfaces the underlying Order rows so free-text
- * search on `$searchableRelations = ['orders' => ['order_number']]`
- * lands on the joined column without the caller having to walk through
- * order_items manually.
+ * on an Order that referenced this model. `orders()` is a
+ * HasManyThrough convenience that surfaces the underlying Order rows
+ * so free-text search on
+ * `$searchableRelations = ['orders' => ['order_number']]` lands on the
+ * joined column without the caller having to walk through order_items
+ * manually.
*/
trait HasOrders
{