A free open source IT asset/license management system
Updated seeders with initial purchase info
snipef37e428acef9
diff --git a/app/Http/Controllers/Api/AccessoriesController.php b/app/Http/Controllers/Api/AccessoriesController.phpindex 0e9886796a..7f0c42cb97 100644--- a/app/Http/Controllers/Api/AccessoriesController.php+++ b/app/Http/Controllers/Api/AccessoriesController.php@@ -153,8 +153,20 @@ class AccessoriesController extends Controllercase 'created_by':$accessories = $accessories->OrderByCreatedByName($order);break;+ case 'purchase_cost':+ // purchase_cost lives on order_items now; sort by the+ // last acquisition's price rather than the removed+ // parent column.+ $accessories = $accessories->OrderByLastPurchaseCost($order);+ break;+ case 'purchase_date':+ $accessories = $accessories->OrderByLastPurchaseDate($order);+ break;case 'total_cost':- $accessories = $accessories->orderByRaw('COALESCE(purchase_cost, 0) * qty '.$order);+ // total_cost is the sum of qty*price across every+ // OrderItem, mirroring the info-panel's total_cost+ // display so the column header sort matches.+ $accessories = $accessories->OrderByTotalOrderCost($order);break;case 'percent_remaining':$accessories = $accessories->OrderPercentRemaining($order);diff --git a/app/Http/Controllers/Api/ComponentsController.php b/app/Http/Controllers/Api/ComponentsController.phpindex 3c90baaec6..8c0c58f6a7 100644--- a/app/Http/Controllers/Api/ComponentsController.php+++ b/app/Http/Controllers/Api/ComponentsController.php@@ -167,6 +167,18 @@ class ComponentsController extends Controllercase 'percent_remaining':$components = $components->OrderPercentRemaining($order);break;+ case 'purchase_cost':+ // See AccessoriesController for the rationale — these+ // three sorts walk order_items rather than removed+ // parent columns.+ $components = $components->OrderByLastPurchaseCost($order);+ break;+ case 'purchase_date':+ $components = $components->OrderByLastPurchaseDate($order);+ break;+ case 'total_cost':+ $components = $components->OrderByTotalOrderCost($order);+ break;default:$components = $components->orderBy($column_sort, $order);break;diff --git a/app/Http/Controllers/Api/ConsumablesController.php b/app/Http/Controllers/Api/ConsumablesController.phpindex b55794851a..e863458a3f 100644--- a/app/Http/Controllers/Api/ConsumablesController.php+++ b/app/Http/Controllers/Api/ConsumablesController.php@@ -151,6 +151,18 @@ class ConsumablesController extends Controllercase 'created_by':$consumables = $consumables->OrderByCreatedBy($order);break;+ case 'purchase_cost':+ // See AccessoriesController for the rationale — these+ // three sorts walk order_items rather than removed+ // parent columns.+ $consumables = $consumables->OrderByLastPurchaseCost($order);+ break;+ case 'purchase_date':+ $consumables = $consumables->OrderByLastPurchaseDate($order);+ break;+ case 'total_cost':+ $consumables = $consumables->OrderByTotalOrderCost($order);+ break;default:$sort = in_array($request->input('sort'), $allowed_columns) ? $request->input('sort') : 'created_at';$consumables = $consumables->orderBy($sort, $order);diff --git a/app/Models/Traits/HasOrders.php b/app/Models/Traits/HasOrders.phpindex 00c043ed9f..579f1a0944 100644--- a/app/Models/Traits/HasOrders.php+++ b/app/Models/Traits/HasOrders.php@@ -225,4 +225,62 @@ trait HasOrders->select('orders.order_number'),])->orderBy('sort_order_number', $direction);}++ /**+ * Sort by the most recent OrderItem's price. Rows with no order+ * history sort last on `asc` / first on `desc` (natural NULL sort+ * behavior on both MySQL and SQLite). Uses addSelect for the same+ * reason as scopeOrderByOrderNumber above.+ */+ public function scopeOrderByLastPurchaseCost(Builder $query, string $direction = 'asc'): Builder+ {+ $modelTable = (new static)->getTable();++ return $query->addSelect([+ 'sort_last_purchase_cost' => OrderItem::query()+ ->whereColumn('order_items.item_id', $modelTable.'.id')+ ->where('order_items.item_type', static::class)+ ->orderByDesc('order_items.id')+ ->limit(1)+ ->select('order_items.price'),+ ])->orderBy('sort_last_purchase_cost', $direction);+ }++ /**+ * Sort by the most recent Order.purchase_date across this row's+ * OrderItems. See scopeOrderByLastPurchaseCost for the null-sort+ * caveat.+ */+ public function scopeOrderByLastPurchaseDate(Builder $query, string $direction = 'asc'): Builder+ {+ $modelTable = (new static)->getTable();++ return $query->addSelect([+ 'sort_last_purchase_date' => OrderItem::query()+ ->join('orders', 'orders.id', '=', 'order_items.order_id')+ ->whereColumn('order_items.item_id', $modelTable.'.id')+ ->where('order_items.item_type', static::class)+ ->orderByDesc('order_items.id')+ ->limit(1)+ ->select('orders.purchase_date'),+ ])->orderBy('sort_last_purchase_date', $direction);+ }++ /**+ * Sort by the sum of (qty * price) across every OrderItem attached+ * to this row. Matches the info-panel's total_cost display so a+ * click on the total-cost column header lands rows in the same+ * order the panel shows them.+ */+ public function scopeOrderByTotalOrderCost(Builder $query, string $direction = 'asc'): Builder+ {+ $modelTable = (new static)->getTable();++ return $query->addSelect([+ 'sort_total_order_cost' => OrderItem::query()+ ->whereColumn('order_items.item_id', $modelTable.'.id')+ ->where('order_items.item_type', static::class)+ ->selectRaw('COALESCE(SUM(order_items.qty * order_items.price), 0)'),+ ])->orderBy('sort_total_order_cost', $direction);+ }}diff --git a/app/Presenters/AccessoryPresenter.php b/app/Presenters/AccessoryPresenter.phpindex 7baf46ed81..79b0125d2c 100644--- a/app/Presenters/AccessoryPresenter.php+++ b/app/Presenters/AccessoryPresenter.php@@ -142,19 +142,24 @@ class AccessoryPresenter extends Presenter'formatter' => 'progressBarFormatter',],[+ // "Last" prefix reflects that purchase_date now lives+ // on Orders — an accessory can have many, so displaying+ // an unqualified "Purchase Date" on the index page is+ // misleading. The API's purchase_date sort routes+ // through OrderByLastPurchaseDate accordingly.'field' => 'purchase_date','scope' => 'col',- 'searchable' => true,+ 'searchable' => false,'sortable' => true,'visible' => false,- 'title' => trans('general.purchase_date'),+ 'title' => trans('general.last_purchase_date'),'formatter' => 'dateDisplayFormatter',], ['field' => 'purchase_cost','scope' => 'col',- 'searchable' => true,+ 'searchable' => false,'sortable' => true,- 'title' => trans('general.unit_cost'),+ 'title' => trans('general.last_unit_cost'),'class' => 'text-right text-padding-number-cell',], ['field' => 'total_cost',diff --git a/app/Presenters/ComponentPresenter.php b/app/Presenters/ComponentPresenter.phpindex ed41ab2533..1100f8cbf5 100644--- a/app/Presenters/ComponentPresenter.php+++ b/app/Presenters/ComponentPresenter.php@@ -97,11 +97,14 @@ class ComponentPresenter extends Presenter'title' => trans('general.location'),'formatter' => 'locationsLinkObjFormatter',], [+ // "Last" prefix — see AccessoryPresenter for the+ // rationale on why the index page can't show a single+ // Purchase Date once Orders can carry many per item.'field' => 'purchase_date','scope' => 'col',- 'searchable' => true,+ 'searchable' => false,'sortable' => true,- 'title' => trans('general.purchase_date'),+ 'title' => trans('general.last_purchase_date'),'visible' => true,'formatter' => 'dateDisplayFormatter',], [@@ -143,9 +146,9 @@ class ComponentPresenter extends Presenter], ['field' => 'purchase_cost','scope' => 'col',- 'searchable' => true,+ 'searchable' => false,'sortable' => true,- 'title' => trans('general.unit_cost'),+ 'title' => trans('general.last_unit_cost'),'visible' => true,'class' => 'text-right','footerFormatter' => 'sumFormatter',diff --git a/app/Presenters/ConsumablePresenter.php b/app/Presenters/ConsumablePresenter.phpindex 16d30c5fdd..343c799456 100644--- a/app/Presenters/ConsumablePresenter.php+++ b/app/Presenters/ConsumablePresenter.php@@ -97,11 +97,14 @@ class ConsumablePresenter extends Presenter'visible' => false,'formatter' => 'manufacturersLinkObjFormatter',], [+ // "Last" prefix — see AccessoryPresenter for the+ // rationale on why the index page can't show a single+ // Purchase Date once Orders can carry many per item.'field' => 'purchase_date','scope' => 'col',- 'searchable' => true,+ 'searchable' => false,'sortable' => true,- 'title' => trans('general.purchase_date'),+ 'title' => trans('general.last_purchase_date'),'visible' => true,'formatter' => 'dateDisplayFormatter',], [@@ -143,9 +146,9 @@ class ConsumablePresenter extends Presenter], ['field' => 'purchase_cost','scope' => 'col',- 'searchable' => true,+ 'searchable' => false,'sortable' => true,- 'title' => trans('general.unit_cost'),+ 'title' => trans('general.last_unit_cost'),'visible' => true,'class' => 'text-right text-padding-number-cell','footerFormatter' => 'sumFormatter',diff --git a/database/seeders/AccessorySeeder.php b/database/seeders/AccessorySeeder.phpindex 7d60e2e673..8d7495f2b7 100644--- a/database/seeders/AccessorySeeder.php+++ b/database/seeders/AccessorySeeder.php@@ -7,6 +7,7 @@ use App\Models\AccessoryCheckout;use App\Models\Location;use App\Models\Supplier;use App\Models\User;+use Carbon\Carbon;use Illuminate\Database\Seeder;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Log;@@ -33,29 +34,35 @@ class AccessorySeeder extends Seeder$admin = User::where('permissions->superuser', '1')->first() ?? User::factory()->firstAdmin()->create();- Accessory::factory()->appleUsbKeyboard()->create([- 'location_id' => $locationIds->random(),- 'default_supplier_id' => $supplierIds->random(),- 'created_by' => $admin->id,- ]);-- Accessory::factory()->appleBtKeyboard()->create([- 'location_id' => $locationIds->random(),- 'default_supplier_id' => $supplierIds->random(),- 'created_by' => $admin->id,- ]);-- Accessory::factory()->appleMouse()->create([- 'location_id' => $locationIds->random(),- 'default_supplier_id' => $supplierIds->random(),- 'created_by' => $admin->id,- ]);-- Accessory::factory()->microsoftMouse()->create([- 'location_id' => $locationIds->random(),- 'default_supplier_id' => $supplierIds->random(),- 'created_by' => $admin->id,- ]);+ // Build a fresh acquisition payload per accessory so demo rows+ // don't all share the same supplier / cost / date. The seeded+ // supplier also seeds the parent's default_supplier_id template+ // so future adjust-quantity events pre-populate with it.+ //+ // withInitialAcquisition enriches the observer-written Order ++ // OrderItem with realistic acquisition metadata. The observer+ // alone leaves those fields null because form-driven creates+ // enrich them via enrichInitialOrderFromRequest, which a seeder+ // can't invoke.+ $randomAcquisition = function () use ($supplierIds) {+ $supplier = Supplier::find($supplierIds->random());+ $cost = fake()->randomFloat(2, 5, 250);+ $date = Carbon::instance(fake()->dateTimeBetween('-1 years', 'now'))->toDateString();++ return compact('supplier', 'cost', 'date');+ };++ foreach (['appleUsbKeyboard', 'appleBtKeyboard', 'appleMouse', 'microsoftMouse'] as $state) {+ $acq = $randomAcquisition();+ Accessory::factory()+ ->{$state}()+ ->withInitialAcquisition($acq['supplier'], $acq['cost'], $acq['date'])+ ->create([+ 'location_id' => $locationIds->random(),+ 'default_supplier_id' => $acq['supplier']->id,+ 'created_by' => $admin->id,+ ]);+ }// Check out a handful of each accessory to random users so the// view page doesn't render empty. Uses the AccessoryCheckoutdiff --git a/database/seeders/ComponentSeeder.php b/database/seeders/ComponentSeeder.phpindex de0f5adb59..8443fb6814 100644--- a/database/seeders/ComponentSeeder.php+++ b/database/seeders/ComponentSeeder.php@@ -6,7 +6,9 @@ use App\Models\Asset;use App\Models\Company;use App\Models\Component;use App\Models\Location;+use App\Models\Supplier;use App\Models\User;+use Carbon\Carbon;use Illuminate\Database\Seeder;use Illuminate\Support\Facades\DB;@@ -29,22 +31,31 @@ class ComponentSeeder extends Seeder$locationIds = Location::all()->pluck('id');- Component::factory()->ramCrucial4()->create([- 'company_id' => $companyIds->random(),- 'location_id' => $locationIds->random(),- ]);- Component::factory()->ramCrucial8()->create([- 'company_id' => $companyIds->random(),- 'location_id' => $locationIds->random(),- ]);- Component::factory()->ssdCrucial120()->create([- 'company_id' => $companyIds->random(),- 'location_id' => $locationIds->random(),- ]);- Component::factory()->ssdCrucial240()->create([- 'company_id' => $companyIds->random(),- 'location_id' => $locationIds->random(),- ]);+ if (! Supplier::count()) {+ $this->call(SupplierSeeder::class);+ }+ $supplierIds = Supplier::all()->pluck('id');++ // See AccessorySeeder for the withInitialAcquisition rationale.+ $randomAcquisition = function () use ($supplierIds) {+ $supplier = Supplier::find($supplierIds->random());+ $cost = fake()->randomFloat(2, 10, 500);+ $date = Carbon::instance(fake()->dateTimeBetween('-1 years', 'now'))->toDateString();++ return compact('supplier', 'cost', 'date');+ };++ foreach (['ramCrucial4', 'ramCrucial8', 'ssdCrucial120', 'ssdCrucial240'] as $state) {+ $acq = $randomAcquisition();+ Component::factory()+ ->{$state}()+ ->withInitialAcquisition($acq['supplier'], $acq['cost'], $acq['date'])+ ->create([+ 'company_id' => $companyIds->random(),+ 'location_id' => $locationIds->random(),+ 'default_supplier_id' => $acq['supplier']->id,+ ]);+ }// Check out a couple of each component to random assets so the// view page doesn't render an empty checkout list. Componentsdiff --git a/database/seeders/ConsumableSeeder.php b/database/seeders/ConsumableSeeder.phpindex f1ed929db2..ba55d626b7 100644--- a/database/seeders/ConsumableSeeder.php+++ b/database/seeders/ConsumableSeeder.php@@ -3,7 +3,9 @@namespace Database\Seeders;use App\Models\Consumable;+use App\Models\Supplier;use App\Models\User;+use Carbon\Carbon;use Illuminate\Database\Seeder;use Illuminate\Support\Facades\DB;@@ -14,11 +16,35 @@ class ConsumableSeeder extends SeederConsumable::truncate();DB::table('consumables_users')->truncate();+ if (! Supplier::count()) {+ $this->call(SupplierSeeder::class);+ }+ $supplierIds = Supplier::all()->pluck('id');+$admin = User::where('permissions->superuser', '1')->first() ?? User::factory()->firstAdmin()->create();- Consumable::factory()->count(1)->cardstock()->create(['created_by' => $admin->id]);- Consumable::factory()->count(1)->paper()->create(['created_by' => $admin->id]);- Consumable::factory()->count(1)->ink()->create(['created_by' => $admin->id]);+ // See AccessorySeeder for the withInitialAcquisition rationale —+ // fills demo Order + OrderItem rows with realistic supplier /+ // cost / date so the index page and info-panel don't render+ // empty "Last Unit Cost" / "Last Purchase Date" columns.+ $randomAcquisition = function () use ($supplierIds) {+ $supplier = Supplier::find($supplierIds->random());+ $cost = fake()->randomFloat(2, 1, 50);+ $date = Carbon::instance(fake()->dateTimeBetween('-1 years', 'now'))->toDateString();++ return compact('supplier', 'cost', 'date');+ };++ foreach (['cardstock', 'paper', 'ink'] as $state) {+ $acq = $randomAcquisition();+ Consumable::factory()+ ->{$state}()+ ->withInitialAcquisition($acq['supplier'], $acq['cost'], $acq['date'])+ ->create([+ 'default_supplier_id' => $acq['supplier']->id,+ 'created_by' => $admin->id,+ ]);+ }// Check out a couple of each consumable to random users so the// view page doesn't render as an empty checkout list.diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.phpindex 2214937d02..0e52b89c23 100644--- a/database/seeders/DatabaseSeeder.php+++ b/database/seeders/DatabaseSeeder.php@@ -60,6 +60,16 @@ class DatabaseSeeder extends Seeder$this->reportMemory('after DepreciationSeeder (2nd)');$this->call(StatuslabelSeeder::class);$this->reportMemory('after StatuslabelSeeder');++ // Wipe Orders / OrderItems before any inventory seeder runs so a+ // re-seed doesn't inherit acquisition rows from the previous+ // session. The inventory seeders (Accessory / Asset / Component /+ // Consumable) truncate their own tables but the observer-written+ // Orders / OrderItems live in a shared polymorphic pair, so we+ // clear them centrally here.+ DB::table('order_items')->truncate();+ DB::table('orders')->truncate();+$this->call(AccessorySeeder::class);$this->reportMemory('after AccessorySeeder');$this->call(AssetSeeder::class);diff --git a/resources/lang/en-US/general.php b/resources/lang/en-US/general.phpindex 80c3592aa2..c4dbaffe53 100644--- a/resources/lang/en-US/general.php+++ b/resources/lang/en-US/general.php@@ -355,6 +355,8 @@ return ['suppliers' => 'Suppliers','default_supplier' => 'Default Supplier','default_supplier_help' => 'Pre-populates the supplier on new orders for this item. Each order can override this value.',+ 'last_unit_cost' => 'Last Unit Cost',+ 'last_purchase_date' => 'Last Purchase Date','sure_to_delete' => 'Are you sure you wish to delete','sure_to_delete_var' => 'Are you sure you wish to delete :item?','delete_what' => 'Delete :item',diff --git a/resources/views/blade/info-panel/index.blade.php b/resources/views/blade/info-panel/index.blade.phpindex 53e87bc9b1..76178b8a70 100644--- a/resources/views/blade/info-panel/index.blade.php+++ b/resources/views/blade/info-panel/index.blade.php@@ -199,58 +199,61 @@{{ Helper::formatCurrencyOutput($unitCost) }}</x-copy-to-clipboard></x-info-element>+ @endif- @if (isset($infoPanelObj->qty) && method_exists($infoPanelObj, 'totalCostSumByCurrency'))- @php $totalsByCurrency = $infoPanelObj->totalCostSumByCurrency(); @endphp- @if (count($totalsByCurrency) === 1)- @php $currency = array_key_first($totalsByCurrency); @endphp- <x-info-element>- <x-icon type="cost" class="fa-fw" title="{{ trans('general.total_cost') }}"/>- {{ trans('general.total_cost') }}- <span class="pull-right">- {{ $currency !== '' ? $currency : $snipeSettings->default_currency }}- {{ Helper::formatCurrencyOutput($totalsByCurrency[$currency]) }}- </span>- </x-info-element>- @elseif (count($totalsByCurrency) > 1)- <x-info-element>- <x-icon type="cost" class="fa-fw" title="{{ trans('general.total_cost') }}"/>- {{ trans('general.total_cost') }}- {{ count($totalsByCurrency) }} {{ trans('general.currencies') }}- <a class="pull-right js-copy-link" style="font-size: 16px; margin-right: 3px;" type="button" data-toggle="collapse" data-target="#totalCostBreakdown" aria-expanded="false" aria-controls="totalCostBreakdown">- <x-icon type="plus" class="fa-fw"/>- </a>- </x-info-element>- <span class="collapse" id="totalCostBreakdown">- <x-info-element class="subitem well well-sm">- @foreach ($totalsByCurrency as $currency => $amount)- <div>- {{ $currency !== '' ? $currency : $snipeSettings->default_currency }}- {{ Helper::formatCurrencyOutput($amount) }}- </div>- @endforeach- </x-info-element>+ {{-- Total cost is independent of the Last Unit Cost row. --}}+ {{-- Historical acquisitions may have carried prices even if --}}+ {{-- the most recent one didn't, so the total_cost row shows --}}+ {{-- whenever totalCostSumByCurrency has anything to sum. --}}+ @if (isset($infoPanelObj->qty) && method_exists($infoPanelObj, 'totalCostSumByCurrency'))+ @php $totalsByCurrency = $infoPanelObj->totalCostSumByCurrency(); @endphp+ @if (count($totalsByCurrency) === 1)+ @php $currency = array_key_first($totalsByCurrency); @endphp+ <x-info-element>+ <x-icon type="cost" class="fa-fw" title="{{ trans('general.total_cost') }}"/>+ {{ trans('general.total_cost') }}+ <span class="pull-right">+ {{ $currency !== '' ? $currency : $snipeSettings->default_currency }}+ {{ Helper::formatCurrencyOutput($totalsByCurrency[$currency]) }}</span>- @endif- @endif-- {{-- Skip on Asset instances. An asset is 1:1 with a --}}- {{-- transaction, so "ordered N times" is always 1 and --}}- {{-- the Orders table IS the record of the acquisition. --}}- {{-- Applies to Accessory/Consumable/Component (multi-order --}}- {{-- inventory) and to AssetModel (asset TYPE, aggregating --}}- {{-- distinct orders across all its Asset instances). --}}- @if (method_exists($infoPanelObj, 'ordersCount') && ! ($infoPanelObj instanceof \App\Models\Asset))- @php $ordersCount = $infoPanelObj->ordersCount(); @endphp- @if ($ordersCount > 0)- <x-info-element>- <x-icon type="order" class="fa-fw" title="{{ trans('general.total_orders') }}"/>- {{ trans('general.total_orders') }}- <span class="pull-right">{{ $ordersCount }}</span>+ </x-info-element>+ @elseif (count($totalsByCurrency) > 1)+ <x-info-element>+ <x-icon type="cost" class="fa-fw" title="{{ trans('general.total_cost') }}"/>+ {{ trans('general.total_cost') }}+ {{ count($totalsByCurrency) }} {{ trans('general.currencies') }}+ <a class="pull-right js-copy-link" style="font-size: 16px; margin-right: 3px;" type="button" data-toggle="collapse" data-target="#totalCostBreakdown" aria-expanded="false" aria-controls="totalCostBreakdown">+ <x-icon type="plus" class="fa-fw"/>+ </a>+ </x-info-element>+ <span class="collapse" id="totalCostBreakdown">+ <x-info-element class="subitem well well-sm">+ @foreach ($totalsByCurrency as $currency => $amount)+ <div>+ {{ $currency !== '' ? $currency : $snipeSettings->default_currency }}+ {{ Helper::formatCurrencyOutput($amount) }}+ </div>+ @endforeach</x-info-element>- @endif+ </span>@endif+ @endif+ {{-- Skip on Asset instances. An asset is 1:1 with a --}}+ {{-- transaction, so "ordered N times" is always 1 and --}}+ {{-- the Orders table IS the record of the acquisition. --}}+ {{-- Applies to Accessory/Consumable/Component (multi-order --}}+ {{-- inventory) and to AssetModel (asset TYPE, aggregating --}}+ {{-- distinct orders across all its Asset instances). --}}+ @if (method_exists($infoPanelObj, 'ordersCount') && ! ($infoPanelObj instanceof \App\Models\Asset))+ @php $ordersCount = $infoPanelObj->ordersCount(); @endphp+ @if ($ordersCount > 0)+ <x-info-element>+ <x-icon type="order" class="fa-fw" title="{{ trans('general.total_orders') }}"/>+ {{ trans('general.total_orders') }}+ <span class="pull-right">{{ $ordersCount }}</span>+ </x-info-element>+ @endif@endif{{-- Accessory/Consumable/Component override getOrderNumberAttribute