Skip to content

A free open source IT asset/license management system

A few more importer fixes

snipe486316c3fb99
diff --git a/app/Http/Controllers/Api/OrderItemsController.php b/app/Http/Controllers/Api/OrderItemsController.php
index fb0750a9bc..0008a6c92a 100644
--- a/app/Http/Controllers/Api/OrderItemsController.php
+++ b/app/Http/Controllers/Api/OrderItemsController.php
@@ -7,6 +7,7 @@ use App\Http\Transformers\OrderItemsTransformer;
use App\Models\Asset;
use App\Models\AssetModel;
use App\Models\OrderItem;
+use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
@@ -28,108 +29,151 @@ use Illuminate\Http\Request;
*/
class OrderItemsController extends Controller
{
+ /**
+ * Sortable columns that live on joined tables (orders / suppliers).
+ * Keys are the API `sort` values; values are the qualified column
+ * name the ORDER BY uses. Non-mapped values fall back to `id DESC`.
+ */
+ private const SORT_COLUMN_MAP = [
+ 'order_number' => 'orders.order_number',
+ 'purchase_date' => 'orders.purchase_date',
+ 'currency' => 'orders.currency',
+ 'supplier' => 'suppliers.name',
+ 'qty' => 'order_items.qty',
+ 'unit_cost' => 'order_items.price',
+ 'created_at' => 'order_items.created_at',
+ 'created_by' => 'order_items.created_by',
+ ];
+
public function index(Request $request): JsonResponse
{
- // Authorization: if the request narrows to a specific parent,
- // require view permission on THAT parent. Otherwise fall back
- // to the OrderItem-level policy so a global listing is gated
- // to superusers or the equivalent.
+ $this->authorizeOrderItemsRequest($request);
+
+ $query = $this->baseOrderItemsQuery();
+ $this->applyScopeFilters($query, $request);
+ $this->applyJoinsAndSearch($query, $request);
+ $this->applySort($query, $request);
+
+ $total = (clone $query)->count();
+ $offset = ($request->input('offset') > $total) ? $total : app('api_offset_value');
+ $limit = app('api_limit_value');
+ $lines = (clone $query)->skip($offset)->take($limit)->get();
+
+ return response()->json(
+ (new OrderItemsTransformer)->transformOrderItems($lines, $total),
+ 200,
+ ['Content-Type' => 'application/json;charset=utf8'],
+ JSON_UNESCAPED_UNICODE,
+ );
+ }
+
+ /**
+ * Authorization: if the request narrows to a specific parent,
+ * require view permission on THAT parent. Otherwise fall back to
+ * requiring superuser — unfiltered "list every OrderItem" is a
+ * superuser-only capability until an OrderPolicy exists.
+ */
+ private function authorizeOrderItemsRequest(Request $request): void
+ {
+ $assetModelId = $request->input('asset_model_id');
$itemType = $request->input('item_type');
$itemId = $request->input('item_id');
- $assetModelId = $request->input('asset_model_id');
if ($assetModelId) {
$this->authorize('view', AssetModel::findOrFail($assetModelId));
- } elseif ($itemType && $itemId && class_exists($itemType)) {
+
+ return;
+ }
+
+ if ($itemType && $itemId && class_exists($itemType)) {
$this->authorize('view', $itemType::findOrFail($itemId));
- } elseif (! auth()->user()?->isSuperUser()) {
- // Unfiltered "list every OrderItem" is a superuser-only
- // capability until an OrderPolicy exists.
+
+ return;
+ }
+
+ if (! auth()->user()?->isSuperUser()) {
abort(403);
}
+ }
- $query = OrderItem::query()
+ private function baseOrderItemsQuery(): Builder
+ {
+ return OrderItem::query()
->with([
'admin:id,first_name,last_name,username',
'order:id,order_number,supplier_id,currency,purchase_date,created_by',
'order.supplier:id,name',
'order.admin:id,first_name,last_name,username',
- ]);
+ ])
+ // Orders tab shows purchases only. Corrections / consumption
+ // events (zero or negative-qty OrderItems) belong in the
+ // item's history tab, not on the "Orders" list.
+ ->where('order_items.qty', '>', 0);
+ }
+
+ private function applyScopeFilters(Builder $query, Request $request): void
+ {
+ $assetModelId = $request->input('asset_model_id');
+ $itemType = $request->input('item_type');
+ $itemId = $request->input('item_id');
if ($assetModelId) {
$query->where('order_items.item_type', Asset::class)
->whereIn('order_items.item_id', Asset::where('model_id', $assetModelId)->select('id'));
- } elseif ($itemType && $itemId) {
+
+ return;
+ }
+
+ if ($itemType && $itemId) {
$query->where('order_items.item_type', $itemType)
->where('order_items.item_id', $itemId);
}
+ }
- // Orders tab shows purchases only. Corrections / consumption
- // events (zero or negative-qty OrderItems) belong in the item's
- // history tab, not on the "Orders" list — they aren't purchases.
- $query->where('order_items.qty', '>', 0);
-
- // leftJoin onto orders + suppliers so cross-table sort / search
- // can hit those columns. Select order_items.* so the model
- // hydrates cleanly and the joined columns don't leak into the
- // OrderItem attributes.
+ /**
+ * leftJoin onto orders + suppliers so cross-table sort / search
+ * can hit those columns. Select order_items.* so the model hydrates
+ * cleanly and the joined columns don't leak into the OrderItem
+ * attributes. Search covers order_number, supplier name, and the
+ * order notes field.
+ */
+ private function applyJoinsAndSearch(Builder $query, Request $request): void
+ {
$query->leftJoin('orders', 'orders.id', '=', 'order_items.order_id')
->leftJoin('suppliers', 'suppliers.id', '=', 'orders.supplier_id')
->select('order_items.*');
- if ($request->filled('search')) {
- $needle = '%'.$request->input('search').'%';
- $query->where(function ($q) use ($needle) {
- $q->where('orders.order_number', 'like', $needle)
- ->orWhere('suppliers.name', 'like', $needle)
- ->orWhere('orders.notes', 'like', $needle);
- });
+ if (! $request->filled('search')) {
+ return;
}
+ $needle = '%'.$request->input('search').'%';
+ $query->where(function ($q) use ($needle) {
+ $q->where('orders.order_number', 'like', $needle)
+ ->orWhere('suppliers.name', 'like', $needle)
+ ->orWhere('orders.notes', 'like', $needle);
+ });
+ }
+
+ private function applySort(Builder $query, Request $request): void
+ {
$order = $request->input('order') === 'asc' ? 'asc' : 'desc';
- switch ($request->input('sort')) {
- case 'order_number':
- $query->orderBy('orders.order_number', $order);
- break;
- case 'purchase_date':
- $query->orderBy('orders.purchase_date', $order);
- break;
- case 'currency':
- $query->orderBy('orders.currency', $order);
- break;
- case 'supplier':
- $query->orderBy('suppliers.name', $order);
- break;
- case 'qty':
- $query->orderBy('order_items.qty', $order);
- break;
- case 'unit_cost':
- $query->orderBy('order_items.price', $order);
- break;
- case 'total_cost':
- // qty * price sort is computed rather than a stored column.
- $query->orderByRaw('(order_items.qty * COALESCE(order_items.price, 0)) '.$order);
- break;
- case 'created_at':
- $query->orderBy('order_items.created_at', $order);
- break;
- case 'created_by':
- $query->orderBy('order_items.created_by', $order);
- break;
- default:
- $query->orderBy('order_items.id', 'desc');
+ $sort = $request->input('sort');
+
+ if ($sort === 'total_cost') {
+ // qty * price sort is computed rather than a stored column.
+ $query->orderByRaw('(order_items.qty * COALESCE(order_items.price, 0)) '.$order);
+
+ return;
}
- $total = (clone $query)->count();
- $offset = ($request->input('offset') > $total) ? $total : app('api_offset_value');
- $limit = app('api_limit_value');
- $lines = (clone $query)->skip($offset)->take($limit)->get();
+ $column = self::SORT_COLUMN_MAP[$sort] ?? null;
+ if ($column === null) {
+ $query->orderBy('order_items.id', 'desc');
- return response()->json(
- (new OrderItemsTransformer)->transformOrderItems($lines, $total),
- 200,
- ['Content-Type' => 'application/json;charset=utf8'],
- JSON_UNESCAPED_UNICODE,
- );
+ return;
+ }
+
+ $query->orderBy($column, $order);
}
}
diff --git a/app/Http/Traits/HandlesAdjustQuantity.php b/app/Http/Traits/HandlesAdjustQuantity.php
index bb566502f4..737144c945 100644
--- a/app/Http/Traits/HandlesAdjustQuantity.php
+++ b/app/Http/Traits/HandlesAdjustQuantity.php
@@ -105,35 +105,7 @@ trait HandlesAdjustQuantity
// 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.
- if ($payload['order_number'] !== null) {
- $order = Order::firstOrNew(
- [
- 'order_number' => $payload['order_number'],
- 'supplier_id' => $payload['supplier_id'],
- 'company_id' => $model->company_id ?? null,
- 'purchase_date' => $payload['purchase_date'],
- ],
- [
- 'currency' => $payload['currency'],
- 'notes' => $payload['notes'],
- ],
- );
- if (! $order->exists) {
- $order->created_by = auth()->id();
- $order->save();
- }
- } else {
- $order = new Order([
- 'order_number' => null,
- 'supplier_id' => $payload['supplier_id'],
- 'company_id' => $model->company_id ?? null,
- 'purchase_date' => $payload['purchase_date'],
- 'currency' => $payload['currency'],
- 'notes' => $payload['notes'],
- ]);
- $order->created_by = auth()->id();
- $order->save();
- }
+ $order = $this->findOrCreateOrderForPayload($payload, $model);
$orderItem = new OrderItem([
'order_id' => $order->id,
@@ -150,6 +122,62 @@ trait HandlesAdjustQuantity
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_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();
+ }
+
+ return $order;
+ }
+
+ /**
+ * 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'],
+ ]);
+ $order->created_by = auth()->id();
+ $order->save();
+
+ return $order;
+ }
+
/**
* Update the observer-created initial Order + OrderItem for a
* freshly-saved inventory item with the form-supplied transaction
@@ -165,47 +193,21 @@ trait HandlesAdjustQuantity
*/
protected function enrichInitialOrderFromRequest(Request $request, Model $item): void
{
- $orderNumber = trim((string) $request->input('order_number', ''));
- $currency = trim((string) $request->input('currency', ''));
- $supplierId = $request->filled('supplier_id') ? (int) $request->input('supplier_id') : null;
- $purchaseDate = $request->filled('purchase_date') ? $request->input('purchase_date') : null;
- $purchaseCost = $request->filled('purchase_cost') ? (float) $request->input('purchase_cost') : null;
- // The create form doesn't have a per-order note field yet, but
- // accept `notes` if the caller (importer / API) passes one so the
- // initial Order carries acquisition context matching the modal.
- $notes = $request->filled('notes') ? trim((string) $request->input('notes')) : null;
-
- if ($orderNumber === '' && $currency === '' && $supplierId === null && $purchaseDate === null && $purchaseCost === null && $notes === null) {
+ $orderInputs = $this->extractOrderEnrichmentInputs($request);
+ $purchaseCost = $orderInputs['purchase_cost'];
+
+ if ($this->initialOrderEnrichmentIsEmpty($orderInputs, $purchaseCost)) {
return;
}
$initialLine = $item->orderItems()->latest('id')->first();
- if (! $initialLine) {
- return;
- }
- $initialOrder = $initialLine->order;
- if (! $initialOrder) {
+ if (! $initialLine || ! $initialLine->order) {
return;
}
- $orderUpdates = [];
- if ($orderNumber !== '' && $initialOrder->order_number !== $orderNumber) {
- $orderUpdates['order_number'] = $orderNumber;
- }
- if ($currency !== '' && $initialOrder->currency !== $currency) {
- $orderUpdates['currency'] = $currency;
- }
- if ($supplierId !== null && (int) $initialOrder->supplier_id !== $supplierId) {
- $orderUpdates['supplier_id'] = $supplierId;
- }
- if ($purchaseDate !== null && optional($initialOrder->purchase_date)->toDateString() !== $purchaseDate) {
- $orderUpdates['purchase_date'] = $purchaseDate;
- }
- if ($notes !== null && $initialOrder->notes !== $notes) {
- $orderUpdates['notes'] = $notes;
- }
+ $orderUpdates = $this->diffInitialOrder($initialLine->order, $orderInputs);
if ($orderUpdates !== []) {
- $initialOrder->update($orderUpdates);
+ $initialLine->order->update($orderUpdates);
}
if ($purchaseCost !== null && (float) $initialLine->price !== $purchaseCost) {
@@ -213,6 +215,74 @@ 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) {
+ return null;
+ }
+ $trimmed = trim((string) $raw);
+
+ return $trimmed === '' ? null : $trimmed;
+ }
+
+ private function initialOrderEnrichmentIsEmpty(array $inputs, ?float $purchaseCost): bool
+ {
+ return $inputs['order_number'] === null
+ && $inputs['currency'] === null
+ && $inputs['supplier_id'] === null
+ && $inputs['purchase_date'] === null
+ && $inputs['notes'] === null
+ && $purchaseCost === null;
+ }
+
+ /**
+ * Build the Order-column diff between what the request wants and
+ * what the observer wrote. Only differing fields are returned so
+ * the update() runs the smallest possible set of column writes.
+ */
+ private function diffInitialOrder(Order $initialOrder, array $inputs): array
+ {
+ $candidates = [
+ 'order_number' => $inputs['order_number'],
+ 'currency' => $inputs['currency'],
+ 'supplier_id' => $inputs['supplier_id'],
+ 'notes' => $inputs['notes'],
+ ];
+
+ $updates = [];
+ foreach ($candidates as $column => $incoming) {
+ if ($incoming !== null && $initialOrder->getAttribute($column) != $incoming) {
+ $updates[$column] = $incoming;
+ }
+ }
+
+ if ($inputs['purchase_date'] !== null
+ && optional($initialOrder->purchase_date)->toDateString() !== $inputs['purchase_date']
+ ) {
+ $updates['purchase_date'] = $inputs['purchase_date'];
+ }
+
+ return $updates;
+ }
+
/**
* Pull the acquisition-metadata fields off the request and
* normalize each into the shape Order needs.
diff --git a/app/Importer/ItemImporter.php b/app/Importer/ItemImporter.php
index b3547fd136..43b7f73582 100644
--- a/app/Importer/ItemImporter.php
+++ b/app/Importer/ItemImporter.php
@@ -8,6 +8,7 @@ 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,21 +239,9 @@ class ItemImporter extends Importer
*/
protected function recordOrderForImportedRow($model, array $row): void
{
- $orderNumber = trim((string) $this->findCsvMatch($row, 'order_number'));
- $currency = trim((string) $this->findCsvMatch($row, 'currency'));
- // Supplier / purchase_date / purchase_cost live on the Order
- // and OrderItem now — the parent inventory row no longer holds
- // them. Pull them off the sub-importer's already-normalized
- // $this->item so createOrFetchSupplier / parseOrNullDate work
- // just like they used to when the values were being written
- // straight onto the parent.
- $supplierId = $this->item['supplier_id'] ?? null;
- $purchaseDate = $this->item['purchase_date'] ?? null;
- $purchaseCost = array_key_exists('purchase_cost', $this->item) && $this->item['purchase_cost'] !== '' && $this->item['purchase_cost'] !== null
- ? (float) $this->item['purchase_cost']
- : null;
+ $payload = $this->buildOrderEnrichmentPayload($row);
- if ($orderNumber === '' && $currency === '' && $supplierId === null && $purchaseDate === null && $purchaseCost === null) {
+ if ($payload === null) {
return;
}
@@ -262,35 +251,78 @@ class ItemImporter extends Importer
// 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) {
+ if (! $initialLine || ! $initialLine->order) {
return;
}
- $initialOrder = $initialLine->order;
- if (! $initialOrder) {
- return;
+
+ $updates = $this->diffOrderAgainstPayload($initialLine->order, $payload);
+ if ($updates !== []) {
+ $initialLine->order->update($updates);
}
- $updates = [];
- if ($orderNumber !== '' && $initialOrder->order_number !== $orderNumber) {
- $updates['order_number'] = $orderNumber;
+ $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'));
+ $supplierId = $this->item['supplier_id'] ?? null;
+ $purchaseDate = $this->item['purchase_date'] ?? null;
+ $rawCost = $this->item['purchase_cost'] ?? null;
+ $purchaseCost = ($rawCost !== null && $rawCost !== '') ? (float) $rawCost : null;
+
+ $isEmpty = $orderNumber === ''
+ && $currency === ''
+ && $supplierId === null
+ && $purchaseDate === null
+ && $purchaseCost === null;
+
+ if ($isEmpty) {
+ return null;
}
- if ($currency !== '' && $initialOrder->currency !== $currency) {
- $updates['currency'] = $currency;
+
+ return [
+ 'order_number' => $orderNumber,
+ 'currency' => $currency,
+ 'supplier_id' => $supplierId,
+ 'purchase_date' => $purchaseDate,
+ 'purchase_cost' => $purchaseCost,
+ ];
+ }
+
+ /**
+ * 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
+ {
+ $updates = [];
+
+ if ($payload['order_number'] !== '' && $order->order_number !== $payload['order_number']) {
+ $updates['order_number'] = $payload['order_number'];
}
- if ($supplierId !== null && (int) $initialOrder->supplier_id !== (int) $supplierId) {
- $updates['supplier_id'] = (int) $supplierId;
+ if ($payload['currency'] !== '' && $order->currency !== $payload['currency']) {
+ $updates['currency'] = $payload['currency'];
}
- if ($purchaseDate !== null && optional($initialOrder->purchase_date)->toDateString() !== (string) $purchaseDate) {
- $updates['purchase_date'] = $purchaseDate;
+ if ($payload['supplier_id'] !== null && (int) $order->supplier_id !== (int) $payload['supplier_id']) {
+ $updates['supplier_id'] = (int) $payload['supplier_id'];
}
-
- if ($updates !== []) {
- $initialOrder->update($updates);
+ if ($payload['purchase_date'] !== null && optional($order->purchase_date)->toDateString() !== (string) $payload['purchase_date']) {
+ $updates['purchase_date'] = $payload['purchase_date'];
}
- if ($purchaseCost !== null && (float) $initialLine->price !== $purchaseCost) {
- $initialLine->update(['price' => $purchaseCost]);
- }
+ return $updates;
}
/**
diff --git a/app/Models/Traits/HasOrders.php b/app/Models/Traits/HasOrders.php
index 6c35a858ea..00c043ed9f 100644
--- a/app/Models/Traits/HasOrders.php
+++ b/app/Models/Traits/HasOrders.php
@@ -152,26 +152,50 @@ trait HasOrders
*/
public function lastAcquisitionSupplier(): ?Supplier
{
- if ($this->relationLoaded('orderItems')) {
- $line = $this->orderItems->sortByDesc('id')->first();
- $order = $line?->order;
- if ($order && $order->relationLoaded('supplier') && $order->supplier) {
- return $order->supplier;
- }
- $supplierId = $order?->supplier_id;
- } else {
- $line = $this->orderItems()
- ->with('order:id,supplier_id')
- ->latest('id')
- ->first();
- $supplierId = $line?->order?->supplier_id;
+ $cachedSupplier = $this->cachedLastOrderSupplier();
+ if ($cachedSupplier !== null) {
+ return $cachedSupplier;
}
- $supplierId = $supplierId ?? $this->getAttribute('default_supplier_id');
+ $supplierId = $this->lastOrderSupplierId() ?? $this->getAttribute('default_supplier_id');
return $supplierId ? Supplier::find($supplierId) : null;
}
+ /**
+ * Fast-path: return the eager-loaded Supplier from the
+ * `orderItems.order.supplier` chain if the caller pre-loaded it.
+ * Callers rendering a list should eager-load this chain to avoid
+ * an N+1 through Supplier::find below.
+ */
+ private function cachedLastOrderSupplier(): ?Supplier
+ {
+ if (! $this->relationLoaded('orderItems')) {
+ return null;
+ }
+
+ $order = $this->orderItems->sortByDesc('id')->first()?->order;
+
+ if ($order?->relationLoaded('supplier') && $order->supplier) {
+ return $order->supplier;
+ }
+
+ return null;
+ }
+
+ /**
+ * Slow-path: read the latest OrderItem's Order.supplier_id via a
+ * fresh query. Called only when the eager-loaded fast-path missed.
+ */
+ private function lastOrderSupplierId(): ?int
+ {
+ if ($this->relationLoaded('orderItems')) {
+ return $this->orderItems->sortByDesc('id')->first()?->order?->supplier_id;
+ }
+
+ return $this->orderItems()->with('order:id,supplier_id')->latest('id')->first()?->order?->supplier_id;
+ }
+
/**
* Sort scope that lets the bootstrap-table sortable header for an
* order-number column keep working after the parent order_number
diff --git a/app/Presenters/OrderItemsPresenter.php b/app/Presenters/OrderItemsPresenter.php
index 6cb90f1865..09d5d4eeb9 100644
--- a/app/Presenters/OrderItemsPresenter.php
+++ b/app/Presenters/OrderItemsPresenter.php
@@ -11,7 +11,22 @@ class OrderItemsPresenter
{
public static function dataTableLayout(): string
{
- return json_encode([
+ return json_encode(array_merge(
+ self::metadataColumns(),
+ self::acquisitionColumns(),
+ self::amountColumns(),
+ self::notesColumns(),
+ ));
+ }
+
+ /**
+ * Created-at + who-recorded-it columns rendered at the head of the
+ * table. Kept separate from acquisition metadata so the "when +
+ * who" audit stays visually distinct from the "what" record.
+ */
+ private static function metadataColumns(): array
+ {
+ return [
[
'field' => 'created_at',
'scope' => 'col',
@@ -32,6 +47,16 @@ class OrderItemsPresenter
'visible' => true,
'formatter' => 'usersLinkObjFormatter',
],
+ ];
+ }
+
+ /**
+ * purchase_date / order_number / supplier: the "what did we buy"
+ * columns that identify the acquisition event itself.
+ */
+ private static function acquisitionColumns(): array
+ {
+ return [
[
'field' => 'purchase_date',
'scope' => 'col',
@@ -61,6 +86,16 @@ class OrderItemsPresenter
'visible' => true,
'formatter' => 'suppliersLinkObjFormatter',
],
+ ];
+ }
+
+ /**
+ * qty / unit_cost / currency / total_cost: the "how much" columns.
+ * All three numeric fields use sumFormatter for the footer roll-up.
+ */
+ private static function amountColumns(): array
+ {
+ return [
[
'field' => 'qty',
'scope' => 'col',
@@ -103,6 +138,12 @@ class OrderItemsPresenter
'footerFormatter' => 'sumFormatter',
'class' => 'text-right text-padding-number-cell',
],
+ ];
+ }
+
+ private static function notesColumns(): array
+ {
+ return [
[
'field' => 'notes',
'scope' => 'col',
@@ -112,6 +153,6 @@ class OrderItemsPresenter
'title' => trans('general.notes'),
'visible' => true,
],
- ]);
+ ];
}
}