Skip to content

A free open source IT asset/license management system

Updated controllers with orderItem logic and hashed redirect

snipe29e01933d8ae
diff --git a/app/Models/Accessory.php b/app/Models/Accessory.php
index 94a78d53df..1feb90e895 100755
--- a/app/Models/Accessory.php
+++ b/app/Models/Accessory.php
@@ -447,10 +447,54 @@ class Accessory extends SnipeModel
$accessory_checkout->limit(1)->delete();
}
- public function totalCostSum()
+ /**
+ * 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.
+ *
+ * Falls back to `qty × parent.purchase_cost` under the system's
+ * default_currency when the item has no OrderItems yet (legacy
+ * rows uncaught by backfill, or brand-new items with a purchase
+ * cost set but no acquisitions recorded).
+ *
+ * Returns [] when both paths are empty. The info-panel skips the
+ * "Total cost" line entirely in that case rather than showing 0.
+ *
+ * @return array<string, float> currency code => sum in that currency
+ */
+ public function totalCostSumByCurrency(): array
{
+ $totals = $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;
+ }, []);
+
+ if ($totals === [] && $this->purchase_cost !== null) {
+ $default = Setting::getSettings()?->default_currency ?? '';
+ $totals[$default] = $this->qty * (float) $this->purchase_cost;
+ }
- return $this->purchase_cost !== null ? $this->qty * $this->purchase_cost : null;
+ return $totals;
+ }
+
+ /**
+ * 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;
}
/**
diff --git a/app/Models/Actionlog.php b/app/Models/Actionlog.php
index 7e0ba9ee85..e1f11236bb 100755
--- a/app/Models/Actionlog.php
+++ b/app/Models/Actionlog.php
@@ -48,7 +48,7 @@ class Actionlog extends SnipeModel
'item_id',
'action_type',
'note',
- 'order_id',
+ 'order_item_id',
'target_id',
'target_type',
'stored_eula',
@@ -92,6 +92,11 @@ class Actionlog extends SnipeModel
'location' => ['name'],
'adminuser' => ['first_name', 'last_name', 'username', 'email', 'employee_num'],
'user' => ['first_name', 'last_name', 'username', 'email', 'employee_num'],
+ // Free-text search on QuantityAdjust logs walks through the
+ // OrderItem line to its parent Order so an order-number
+ // string still finds the right log rows after the parent
+ // action_logs.order_number column moved to Orders.
+ 'orderItem.order' => ['order_number'],
'assets' => ['asset_tag', 'name', 'serial', 'notes', 'purchase_date'],
'assets.model' => ['name', 'model_number', 'eol', 'notes'],
'assets.model.category' => ['name', 'notes'],
@@ -367,6 +372,21 @@ class Actionlog extends SnipeModel
->withTrashed();
}
+ /**
+ * QuantityAdjust log rows carry the specific OrderItem line this
+ * replenishment produced via the order_item_id column. The parent
+ * Order (with order_number, purchase_order, supplier, currency,
+ * purchase_date) is reachable via `$log->orderItem->order`.
+ *
+ * Points at order_items rather than orders because a single Order
+ * deduped across staggered receipts carries multiple lines, and the
+ * log entry has to identify the exact line for its event.
+ */
+ public function orderItem()
+ {
+ return $this->belongsTo(OrderItem::class, 'order_item_id');
+ }
+
/**
* Establishes the actionlog -> user relationship
*
diff --git a/app/Models/Asset.php b/app/Models/Asset.php
index 81dec2bd83..cb6a716654 100644
--- a/app/Models/Asset.php
+++ b/app/Models/Asset.php
@@ -156,6 +156,7 @@ class Asset extends Depreciable
'asset_eol_date' => ['nullable', 'date'],
'eol_explicit' => ['nullable', 'boolean'],
'byod' => ['nullable', 'boolean'],
+ 'order_number' => ['nullable', 'string', 'max:191'],
'notes' => ['nullable', 'string', 'max:65535'],
'assigned_to' => ['nullable', 'integer', 'required_with:assigned_type'],
'assigned_type' => ['nullable', 'required_with:assigned_to', 'in:'.User::class.','.Location::class.','.Asset::class],
@@ -178,6 +179,7 @@ class Asset extends Depreciable
'model_id',
'name',
'notes',
+ 'order_number',
'purchase_cost',
'purchase_date',
'rtd_location_id',
@@ -208,6 +210,7 @@ class Asset extends Depreciable
'name',
'asset_tag',
'serial',
+ 'order_number',
'purchase_cost',
'notes',
'created_at',
@@ -236,11 +239,6 @@ class Asset extends Depreciable
'category' => ['name'],
'manufacturer' => ['name'],
'assigned_to' => ['name'],
- // Historical order_number lives on the Orders table via
- // order_items now (see HasOrders trait). Search hits it through
- // the orders() HasManyThrough so an order-number string still
- // surfaces every asset ever acquired under that order.
- 'orders' => ['order_number'],
];
/**
@@ -1953,12 +1951,7 @@ class Asset extends Depreciable
)->orWhere('assets.name', 'LIKE', '%'.$search.'%')
->orWhere('assets.asset_tag', 'LIKE', '%'.$search.'%')
->orWhere('assets.serial', 'LIKE', '%'.$search.'%')
- // Historical order_number lives on the Orders
- // table via order_items now; free-text search on
- // it goes through $searchableRelations['orders'].
- // Dropped from this raw-SQL fallback to avoid a
- // reference to the removed assets.order_number
- // column.
+ ->orWhere('assets.order_number', 'LIKE', '%'.$search.'%')
->orWhere('assets.notes', 'LIKE', '%'.$search.'%');
}
diff --git a/app/Models/Component.php b/app/Models/Component.php
index c969e50b92..327957c267 100644
--- a/app/Models/Component.php
+++ b/app/Models/Component.php
@@ -399,10 +399,54 @@ class Component extends SnipeModel
return $this->qty - $this->numCheckedOut();
}
- public function totalCostSum()
+ /**
+ * 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.
+ *
+ * Falls back to `qty × parent.purchase_cost` under the system's
+ * default_currency when the item has no OrderItems yet (legacy
+ * rows uncaught by backfill, or brand-new items with a purchase
+ * cost set but no acquisitions recorded).
+ *
+ * Returns [] when both paths are empty. The info-panel skips the
+ * "Total cost" line entirely in that case rather than showing 0.
+ *
+ * @return array<string, float> currency code => sum in that currency
+ */
+ public function totalCostSumByCurrency(): array
{
+ $totals = $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;
+ }, []);
- return $this->purchase_cost !== null ? $this->qty * $this->purchase_cost : null;
+ if ($totals === [] && $this->purchase_cost !== null) {
+ $default = Setting::getSettings()?->default_currency ?? '';
+ $totals[$default] = $this->qty * (float) $this->purchase_cost;
+ }
+
+ return $totals;
+ }
+
+ /**
+ * 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;
}
/**
* -----------------------------------------------
diff --git a/app/Models/Consumable.php b/app/Models/Consumable.php
index 1c7ec60124..e1b1bca1f0 100644
--- a/app/Models/Consumable.php
+++ b/app/Models/Consumable.php
@@ -373,10 +373,54 @@ class Consumable extends SnipeModel
return $remaining;
}
- public function totalCostSum()
+ /**
+ * 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.
+ *
+ * Falls back to `qty × parent.purchase_cost` under the system's
+ * default_currency when the item has no OrderItems yet (legacy
+ * rows uncaught by backfill, or brand-new items with a purchase
+ * cost set but no acquisitions recorded).
+ *
+ * Returns [] when both paths are empty. The info-panel skips the
+ * "Total cost" line entirely in that case rather than showing 0.
+ *
+ * @return array<string, float> currency code => sum in that currency
+ */
+ public function totalCostSumByCurrency(): array
{
+ $totals = $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;
+ }, []);
+
+ if ($totals === [] && $this->purchase_cost !== null) {
+ $default = Setting::getSettings()?->default_currency ?? '';
+ $totals[$default] = $this->qty * (float) $this->purchase_cost;
+ }
- return $this->purchase_cost !== null ? $this->qty * $this->purchase_cost : null;
+ return $totals;
+ }
+
+ /**
+ * 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;
}
/**
diff --git a/app/Models/License.php b/app/Models/License.php
index f26e43a36c..43f199e212 100755
--- a/app/Models/License.php
+++ b/app/Models/License.php
@@ -5,7 +5,6 @@ namespace App\Models;
use App\Console\Commands\SendExpiringLicenseNotifications;
use App\Helpers\Helper;
use App\Models\Traits\CompanyableTrait;
-use App\Models\Traits\HasOrders;
use App\Models\Traits\HasUploads;
use App\Models\Traits\Loggable;
use App\Models\Traits\Searchable;
@@ -29,7 +28,6 @@ class License extends Depreciable
protected $presenter = LicensePresenter::class;
use CompanyableTrait;
- use HasOrders;
use HasUploads;
use Loggable, Presentable;
use SoftDeletes;
@@ -92,6 +90,7 @@ class License extends Depreciable
'category_id',
'name',
'notes',
+ 'order_number',
'purchase_cost',
'purchase_date',
'purchase_order',
@@ -114,6 +113,7 @@ class License extends Depreciable
'name',
'serial',
'notes',
+ 'order_number',
'purchase_order',
'purchase_cost',
'purchase_date',
@@ -134,11 +134,6 @@ class License extends Depreciable
'depreciation' => ['name'],
'supplier' => ['name'],
'adminuser' => ['first_name', 'last_name', 'display_name'],
- // Historical order_number lives on the Orders table via
- // order_items now (see HasOrders trait). Search hits it through
- // the orders() HasManyThrough so an order-number string still
- // surfaces every license ever acquired under that order.
- 'orders' => ['order_number'],
];
protected $appends = ['free_seat_count'];
diff --git a/app/Observers/AssetObserver.php b/app/Observers/AssetObserver.php
index 30088adecd..8792abaef4 100644
--- a/app/Observers/AssetObserver.php
+++ b/app/Observers/AssetObserver.php
@@ -4,6 +4,8 @@ namespace App\Observers;
use App\Models\Actionlog;
use App\Models\Asset;
+use App\Models\Order;
+use App\Models\OrderItem;
use App\Models\Setting;
use Carbon\Carbon;
@@ -111,6 +113,48 @@ class AssetObserver
$logAction->setActionSource('importer');
}
$logAction->logaction('create');
+
+ // Every new asset is a transaction: supplier, price, currency,
+ // date. Record it as Order + OrderItem regardless of whether
+ // the operator typed an order_number. Only dedupe on the tuple
+ // when a real order_number label is present. A blank label is a
+ // distinct transaction each time. Skip if the AssetImporter
+ // already wrote the OrderItem for this row.
+ $existingLine = OrderItem::where('item_type', Asset::class)
+ ->where('item_id', $asset->id)
+ ->exists();
+
+ if (! $existingLine) {
+ $orderNumber = trim((string) ($asset->order_number ?? '')) ?: null;
+
+ $order = $orderNumber !== null
+ ? Order::firstOrCreate(
+ [
+ 'order_number' => $orderNumber,
+ 'supplier_id' => $asset->supplier_id,
+ 'company_id' => $asset->company_id,
+ ],
+ [
+ 'purchase_date' => $asset->purchase_date,
+ 'created_by' => auth()->id(),
+ ],
+ )
+ : Order::create([
+ 'order_number' => null,
+ 'supplier_id' => $asset->supplier_id,
+ 'company_id' => $asset->company_id,
+ 'purchase_date' => $asset->purchase_date,
+ 'created_by' => auth()->id(),
+ ]);
+
+ OrderItem::create([
+ 'order_id' => $order->id,
+ 'item_type' => Asset::class,
+ 'item_id' => $asset->id,
+ 'qty' => 1,
+ 'price' => $asset->purchase_cost,
+ ]);
+ }
}
/**