@rytass/wms-module-core 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs.js CHANGED
@@ -587,6 +587,53 @@ exports.SequenceEntityClass = tslib.__decorate([
587
587
 
588
588
  const WMS_CORE_MODULE_OPTIONS = Symbol('WMS_CORE_MODULE_OPTIONS');
589
589
 
590
+ /**
591
+ * Columns `LoaderService.findManyLoaders` can sort by. Values are part of the
592
+ * public GraphQL schema (`LoaderSortField`): add freely, never rename or remove.
593
+ */
594
+ exports.LoaderSortField = void 0;
595
+ (function (LoaderSortField) {
596
+ LoaderSortField["SERIAL_ID"] = "SERIAL_ID";
597
+ /** The loader type's `description`. */
598
+ LoaderSortField["TYPE_DESCRIPTION"] = "TYPE_DESCRIPTION";
599
+ /** The location's `key`. */
600
+ LoaderSortField["LOCATION_KEY"] = "LOCATION_KEY";
601
+ LoaderSortField["LENGTH"] = "LENGTH";
602
+ LoaderSortField["WIDTH"] = "WIDTH";
603
+ LoaderSortField["HEIGHT"] = "HEIGHT";
604
+ LoaderSortField["SIZE_UNIT"] = "SIZE_UNIT";
605
+ LoaderSortField["VOLUME"] = "VOLUME";
606
+ LoaderSortField["VOLUME_UNIT"] = "VOLUME_UNIT";
607
+ LoaderSortField["NOTE"] = "NOTE";
608
+ LoaderSortField["IS_ACTIVE"] = "IS_ACTIVE";
609
+ LoaderSortField["CREATED_AT"] = "CREATED_AT";
610
+ })(exports.LoaderSortField || (exports.LoaderSortField = {}));
611
+ /**
612
+ * Columns `LoaderService.findManyLoaderTypes` can sort by (`LoaderTypeSortField`).
613
+ */
614
+ exports.LoaderTypeSortField = void 0;
615
+ (function (LoaderTypeSortField) {
616
+ LoaderTypeSortField["KEY"] = "KEY";
617
+ LoaderTypeSortField["DESCRIPTION"] = "DESCRIPTION";
618
+ LoaderTypeSortField["IS_ACTIVE"] = "IS_ACTIVE";
619
+ LoaderTypeSortField["CREATED_AT"] = "CREATED_AT";
620
+ })(exports.LoaderTypeSortField || (exports.LoaderTypeSortField = {}));
621
+
622
+ /**
623
+ * Columns `MaterialService.findMany` can sort by. Values are part of the public
624
+ * GraphQL schema (`MaterialSortField`): adding one is a minor change, renaming
625
+ * or removing one is breaking.
626
+ */
627
+ exports.MaterialSortField = void 0;
628
+ (function (MaterialSortField) {
629
+ MaterialSortField["KEY"] = "KEY";
630
+ MaterialSortField["DESCRIPTION"] = "DESCRIPTION";
631
+ /** The base unit's `key` (the column stores the unit's id). */
632
+ MaterialSortField["BASE_UNIT"] = "BASE_UNIT";
633
+ MaterialSortField["IS_ACTIVE"] = "IS_ACTIVE";
634
+ MaterialSortField["CREATED_AT"] = "CREATED_AT";
635
+ })(exports.MaterialSortField || (exports.MaterialSortField = {}));
636
+
590
637
  exports.ReceiveInventoryOrderStatus = void 0;
591
638
  (function (ReceiveInventoryOrderStatus) {
592
639
  ReceiveInventoryOrderStatus["PENDING"] = "PENDING";
@@ -594,6 +641,24 @@ exports.ReceiveInventoryOrderStatus = void 0;
594
641
  ReceiveInventoryOrderStatus["REMOVED"] = "REMOVED";
595
642
  ReceiveInventoryOrderStatus["PARTIAL_RECEIVED"] = "PARTIAL_RECEIVED";
596
643
  })(exports.ReceiveInventoryOrderStatus || (exports.ReceiveInventoryOrderStatus = {}));
644
+ /**
645
+ * Columns `ReceiveInventoryOrderService.findMany` can sort by. Values are part
646
+ * of the public GraphQL schema (`ReceiveInventoryOrderSortField`): add freely, never rename or
647
+ * remove. Per-item columns (material, batch, location, loader) are left out:
648
+ * an order has many items, so they have no single value to sort by.
649
+ */
650
+ exports.ReceiveInventoryOrderSortField = void 0;
651
+ (function (ReceiveInventoryOrderSortField) {
652
+ /**
653
+ * The computed status, in lifecycle order: pending → partially received →
654
+ * received → removed.
655
+ */
656
+ ReceiveInventoryOrderSortField["STATUS"] = "STATUS";
657
+ ReceiveInventoryOrderSortField["KEY"] = "KEY";
658
+ ReceiveInventoryOrderSortField["CREATED_BY"] = "CREATED_BY";
659
+ ReceiveInventoryOrderSortField["CREATED_AT"] = "CREATED_AT";
660
+ ReceiveInventoryOrderSortField["DESCRIPTION"] = "DESCRIPTION";
661
+ })(exports.ReceiveInventoryOrderSortField || (exports.ReceiveInventoryOrderSortField = {}));
597
662
 
598
663
  exports.ShipInventoryOrderStatus = void 0;
599
664
  (function (ShipInventoryOrderStatus) {
@@ -602,6 +667,180 @@ exports.ShipInventoryOrderStatus = void 0;
602
667
  ShipInventoryOrderStatus["REMOVED"] = "REMOVED";
603
668
  ShipInventoryOrderStatus["PARTIAL_SHIPPED"] = "PARTIAL_SHIPPED";
604
669
  })(exports.ShipInventoryOrderStatus || (exports.ShipInventoryOrderStatus = {}));
670
+ /**
671
+ * Columns `ShipInventoryOrderService.findMany` can sort by. Values are part
672
+ * of the public GraphQL schema (`ShipInventoryOrderSortField`): add freely, never rename or
673
+ * remove. Per-item columns (material, batch, location, loader) are left out:
674
+ * an order has many items, so they have no single value to sort by.
675
+ */
676
+ exports.ShipInventoryOrderSortField = void 0;
677
+ (function (ShipInventoryOrderSortField) {
678
+ /**
679
+ * The computed status, in lifecycle order: pending → partially shipped →
680
+ * shipped → removed.
681
+ */
682
+ ShipInventoryOrderSortField["STATUS"] = "STATUS";
683
+ ShipInventoryOrderSortField["KEY"] = "KEY";
684
+ ShipInventoryOrderSortField["CREATED_BY"] = "CREATED_BY";
685
+ ShipInventoryOrderSortField["CREATED_AT"] = "CREATED_AT";
686
+ ShipInventoryOrderSortField["DESCRIPTION"] = "DESCRIPTION";
687
+ })(exports.ShipInventoryOrderSortField || (exports.ShipInventoryOrderSortField = {}));
688
+
689
+ /**
690
+ * Columns `StockService.findChangeLogs` can sort by. Values are part of the
691
+ * public GraphQL schema (`ChangeLogSortField`): add freely, never rename or
692
+ * remove.
693
+ */
694
+ exports.ChangeLogSortField = void 0;
695
+ (function (ChangeLogSortField) {
696
+ /** The computed change type, in `ChangeType` declaration order. */
697
+ ChangeLogSortField["CHANGE_TYPE"] = "CHANGE_TYPE";
698
+ ChangeLogSortField["MATERIAL_KEY"] = "MATERIAL_KEY";
699
+ ChangeLogSortField["MATERIAL_DESCRIPTION"] = "MATERIAL_DESCRIPTION";
700
+ ChangeLogSortField["BATCH_KEY"] = "BATCH_KEY";
701
+ ChangeLogSortField["LOCATION_KEY"] = "LOCATION_KEY";
702
+ /** The quantity's magnitude, as `changeLogs` returns it. */
703
+ ChangeLogSortField["QUANTITY"] = "QUANTITY";
704
+ /** The material's base unit `key`. */
705
+ ChangeLogSortField["BASE_UNIT"] = "BASE_UNIT";
706
+ ChangeLogSortField["CREATED_AT"] = "CREATED_AT";
707
+ })(exports.ChangeLogSortField || (exports.ChangeLogSortField = {}));
708
+
709
+ /**
710
+ * Columns `ConsumptionOrderService.findMany` can sort by. Values are part of
711
+ * the public GraphQL schema (`ConsumptionOrderSortField`): add freely, never
712
+ * rename or remove. Item-derived columns (sources, targets, item count,
713
+ * issued/outstanding/settled totals) are left out: they aggregate many lines
714
+ * and have no column to order by.
715
+ */
716
+ exports.ConsumptionOrderSortField = void 0;
717
+ (function (ConsumptionOrderSortField) {
718
+ ConsumptionOrderSortField["KEY"] = "KEY";
719
+ ConsumptionOrderSortField["DESCRIPTION"] = "DESCRIPTION";
720
+ ConsumptionOrderSortField["CREATED_AT"] = "CREATED_AT";
721
+ })(exports.ConsumptionOrderSortField || (exports.ConsumptionOrderSortField = {}));
722
+
723
+ /**
724
+ * Columns `InventoryCountOrderService.findMany` can sort by. Values are part of
725
+ * the public GraphQL schema (`InventoryCountOrderSortField`): add freely, never
726
+ * rename or remove. The scope (盤點範圍) is left out: a count covers many
727
+ * locations, so it has no single value to sort by.
728
+ */
729
+ exports.InventoryCountOrderSortField = void 0;
730
+ (function (InventoryCountOrderSortField) {
731
+ InventoryCountOrderSortField["NAME"] = "NAME";
732
+ /** The PostgreSQL enum's declaration order: pending → counting → completed → cancelled. */
733
+ InventoryCountOrderSortField["STATUS"] = "STATUS";
734
+ InventoryCountOrderSortField["COUNT_DATE"] = "COUNT_DATE";
735
+ InventoryCountOrderSortField["CREATED_BY"] = "CREATED_BY";
736
+ InventoryCountOrderSortField["CREATED_AT"] = "CREATED_AT";
737
+ })(exports.InventoryCountOrderSortField || (exports.InventoryCountOrderSortField = {}));
738
+ /**
739
+ * Columns `InventoryCountOrderService.findItems` (the count sheet) can sort by
740
+ * (`InventoryCountOrderItemSortField`). The quantity columns are left out: the
741
+ * sheet shows them in the line's selected unit, which the operator can change
742
+ * locally before saving, so no server order could match what is on screen.
743
+ */
744
+ exports.InventoryCountOrderItemSortField = void 0;
745
+ (function (InventoryCountOrderItemSortField) {
746
+ InventoryCountOrderItemSortField["MATERIAL_KEY"] = "MATERIAL_KEY";
747
+ InventoryCountOrderItemSortField["MATERIAL_DESCRIPTION"] = "MATERIAL_DESCRIPTION";
748
+ InventoryCountOrderItemSortField["BATCH_KEY"] = "BATCH_KEY";
749
+ InventoryCountOrderItemSortField["LOCATION_KEY"] = "LOCATION_KEY";
750
+ InventoryCountOrderItemSortField["LOADER_SERIAL_ID"] = "LOADER_SERIAL_ID";
751
+ InventoryCountOrderItemSortField["VENDOR_ID"] = "VENDOR_ID";
752
+ InventoryCountOrderItemSortField["CUSTOMER_ID"] = "CUSTOMER_ID";
753
+ InventoryCountOrderItemSortField["SALE_ID"] = "SALE_ID";
754
+ InventoryCountOrderItemSortField["SALE_SERIAL_ID"] = "SALE_SERIAL_ID";
755
+ /** Lines the operator added during the count. */
756
+ InventoryCountOrderItemSortField["IS_ADDITION"] = "IS_ADDITION";
757
+ /** The 凍結 icon: `held`, a NULL snapshot read as not held. */
758
+ InventoryCountOrderItemSortField["HELD"] = "HELD";
759
+ /** The 調撥 icon: the line had a `transferId`. */
760
+ InventoryCountOrderItemSortField["IN_TRANSFER"] = "IN_TRANSFER";
761
+ /**
762
+ * The 待檢驗 icon, ranked: no mark (0) < failed inspection (1) < awaiting
763
+ * inspection (2, `requiresInspection` and no result yet).
764
+ */
765
+ InventoryCountOrderItemSortField["INSPECTION"] = "INSPECTION";
766
+ })(exports.InventoryCountOrderItemSortField || (exports.InventoryCountOrderItemSortField = {}));
767
+
768
+ /**
769
+ * Columns `LocationService.findMany` can sort by. Values are part of the public
770
+ * GraphQL schema (`LocationSortField`): add freely, never rename or remove.
771
+ */
772
+ exports.LocationSortField = void 0;
773
+ (function (LocationSortField) {
774
+ LocationSortField["KEY"] = "KEY";
775
+ LocationSortField["DESCRIPTION"] = "DESCRIPTION";
776
+ LocationSortField["IS_ACTIVE"] = "IS_ACTIVE";
777
+ LocationSortField["CREATED_AT"] = "CREATED_AT";
778
+ })(exports.LocationSortField || (exports.LocationSortField = {}));
779
+
780
+ /**
781
+ * Columns `TransferOrderService.findMany` can sort by. Values are part of the
782
+ * public GraphQL schema (`TransferOrderSortField`): add freely, never rename or
783
+ * remove. Per-item columns (material, batch, locations, loaders) are left out:
784
+ * an order has many items, so they have no single value to sort by.
785
+ */
786
+ exports.TransferOrderSortField = void 0;
787
+ (function (TransferOrderSortField) {
788
+ TransferOrderSortField["KEY"] = "KEY";
789
+ TransferOrderSortField["RECEIVER"] = "RECEIVER";
790
+ TransferOrderSortField["DESCRIPTION"] = "DESCRIPTION";
791
+ TransferOrderSortField["CREATED_BY"] = "CREATED_BY";
792
+ TransferOrderSortField["CREATED_AT"] = "CREATED_AT";
793
+ })(exports.TransferOrderSortField || (exports.TransferOrderSortField = {}));
794
+
795
+ /**
796
+ * Direction of a list sort. Exposed through GraphQL as the `SortOrder` enum.
797
+ */
798
+ exports.SortOrder = void 0;
799
+ (function (SortOrder) {
800
+ SortOrder["ASC"] = "ASC";
801
+ SortOrder["DESC"] = "DESC";
802
+ })(exports.SortOrder || (exports.SortOrder = {}));
803
+
804
+ /**
805
+ * Columns `StockService.findAggregatedStocks` can sort by. Values are part of
806
+ * the public GraphQL schema (`AggregatedStockSortField`): adding one is a minor
807
+ * change, renaming or removing one is breaking.
808
+ *
809
+ * Every one is single-valued per aggregated row: a row is one (material, batch,
810
+ * location, loader, status) position, and each joined key is one-to-one with
811
+ * its id.
812
+ */
813
+ exports.AggregatedStockSortField = void 0;
814
+ (function (AggregatedStockSortField) {
815
+ /** The derived status code (`FREE`, `HELD`, …), compared as text. */
816
+ AggregatedStockSortField["STATUS"] = "STATUS";
817
+ AggregatedStockSortField["MATERIAL_KEY"] = "MATERIAL_KEY";
818
+ AggregatedStockSortField["MATERIAL_DESCRIPTION"] = "MATERIAL_DESCRIPTION";
819
+ /** The batch *group*'s key — what the `batch { key }` field shows. */
820
+ AggregatedStockSortField["BATCH_KEY"] = "BATCH_KEY";
821
+ AggregatedStockSortField["LOCATION_KEY"] = "LOCATION_KEY";
822
+ AggregatedStockSortField["LOADER_SERIAL_ID"] = "LOADER_SERIAL_ID";
823
+ AggregatedStockSortField["QUANTITY"] = "QUANTITY";
824
+ /** The material's base unit `key`. */
825
+ AggregatedStockSortField["BASE_UNIT"] = "BASE_UNIT";
826
+ AggregatedStockSortField["VENDOR_ID"] = "VENDOR_ID";
827
+ AggregatedStockSortField["CUSTOMER_ID"] = "CUSTOMER_ID";
828
+ AggregatedStockSortField["SALE_ID"] = "SALE_ID";
829
+ AggregatedStockSortField["SALE_SERIAL_ID"] = "SALE_SERIAL_ID";
830
+ })(exports.AggregatedStockSortField || (exports.AggregatedStockSortField = {}));
831
+ /**
832
+ * Columns `StockService.findManyGroupedByMaterialId` can sort by. Values are
833
+ * part of the public GraphQL schema (`StockGroupedByMaterialSortField`).
834
+ */
835
+ exports.StockGroupedByMaterialSortField = void 0;
836
+ (function (StockGroupedByMaterialSortField) {
837
+ StockGroupedByMaterialSortField["MATERIAL_KEY"] = "MATERIAL_KEY";
838
+ StockGroupedByMaterialSortField["MATERIAL_DESCRIPTION"] = "MATERIAL_DESCRIPTION";
839
+ /** The material's total over the matching positions (`SUM(quantity)`). */
840
+ StockGroupedByMaterialSortField["QUANTITY"] = "QUANTITY";
841
+ /** The material's base unit `key`. */
842
+ StockGroupedByMaterialSortField["BASE_UNIT"] = "BASE_UNIT";
843
+ })(exports.StockGroupedByMaterialSortField || (exports.StockGroupedByMaterialSortField = {}));
605
844
 
606
845
  const ReceiveInventoryOrderEntity = Symbol('ReceiveInventoryOrderEntity');
607
846
  exports.ReceiveInventoryOrderEntityClass = class ReceiveInventoryOrderEntityClass {
@@ -3414,6 +3653,96 @@ class BaseOrderService {
3414
3653
  }
3415
3654
  }
3416
3655
 
3656
+ /**
3657
+ * NULLs sort last in **both** directions.
3658
+ *
3659
+ * PostgreSQL's own default flips with the direction (NULLS LAST for ASC, NULLS
3660
+ * FIRST for DESC), so a column with gaps would open every descending page with
3661
+ * its empty rows. A missing value is "no value", not "the largest value": it
3662
+ * belongs at the end whichever way the user sorts.
3663
+ */
3664
+ const LIST_SORT_NULLS = 'NULLS LAST';
3665
+ const ENTITY_PATH = /^([A-Za-z_][A-Za-z0-9_]*)\.([A-Za-z_][A-Za-z0-9_.]*)$/;
3666
+ const isSortOrder = (value) => value === exports.SortOrder.ASC || value === exports.SortOrder.DESC;
3667
+ /**
3668
+ * The ORDER BY clauses `applyListSort` would apply, without a query builder.
3669
+ * Pure — this is what the unit tests pin down.
3670
+ *
3671
+ * Throws on a field outside the whitelist or an unknown direction: the GraphQL
3672
+ * enums already reject both, so reaching here with one means a host called the
3673
+ * service directly with a bad value, and falling back to the default order would
3674
+ * hand it a plausible-looking wrong answer.
3675
+ */
3676
+ function resolveListSort(options) {
3677
+ const { sort, fields, defaultOrder, tiebreaker } = options;
3678
+ const requested = sort
3679
+ ? [sort]
3680
+ : Array.isArray(defaultOrder)
3681
+ ? defaultOrder
3682
+ : [defaultOrder];
3683
+ const clauses = requested.map(({ field, order }) => {
3684
+ if (!Object.prototype.hasOwnProperty.call(fields, field)) {
3685
+ throw new Error(`Unknown sort field "${String(field)}"`);
3686
+ }
3687
+ if (!isSortOrder(order)) {
3688
+ throw new Error(`Unknown sort order "${String(order)}"`);
3689
+ }
3690
+ return { expression: fields[field], order, nulls: LIST_SORT_NULLS };
3691
+ });
3692
+ const tiebreakers = typeof tiebreaker === 'string' ? [tiebreaker] : tiebreaker;
3693
+ // TypeORM keys ORDER BY by expression, so appending a tiebreaker column that
3694
+ // is already a criterion would overwrite that criterion's direction.
3695
+ return [
3696
+ ...clauses,
3697
+ ...tiebreakers
3698
+ .filter((column) => clauses.every(({ expression }) => expression !== column))
3699
+ .map((expression) => ({ expression, order: exports.SortOrder.ASC })),
3700
+ ];
3701
+ }
3702
+ function assertEntityOrderPath(qb, expression) {
3703
+ const match = ENTITY_PATH.exec(expression);
3704
+ if (!match) {
3705
+ throw new Error(`Sort expression "${expression}" must be "alias.propertyPath" in entity mode; use mode 'raw' for SQL expressions`);
3706
+ }
3707
+ const [, aliasName, propertyPath] = match;
3708
+ const alias = qb.expressionMap.aliases.find(({ name }) => name === aliasName);
3709
+ if (!alias?.hasMetadata) {
3710
+ throw new Error(`Sort expression "${expression}": alias "${aliasName}" is not an entity alias of this query — join it (by entity class) before applyListSort`);
3711
+ }
3712
+ if (!alias.metadata.findColumnWithPropertyPath(propertyPath)) {
3713
+ throw new Error(`Sort expression "${expression}": "${propertyPath}" is not a column of ${alias.metadata.name}`);
3714
+ }
3715
+ const isMainAlias = qb.expressionMap.mainAlias?.name === aliasName;
3716
+ const isSelected = qb.expressionMap.selects.some(({ selection }) => selection === aliasName || selection === expression);
3717
+ if (!isMainAlias && !isSelected) {
3718
+ throw new Error(`Sort expression "${expression}": joined alias "${aliasName}" must be selected (addSelect('${expression}')) or the paginated DISTINCT subquery cannot order by it`);
3719
+ }
3720
+ }
3721
+ /**
3722
+ * Replace the query's ORDER BY with the requested sort (or `defaultOrder`),
3723
+ * then the tiebreaker. Call it after every join the sort expressions need.
3724
+ *
3725
+ * ```ts
3726
+ * applyListSort(qb, {
3727
+ * sort: options.sort,
3728
+ * fields: { [MaterialSortField.KEY]: 'material.key', ... },
3729
+ * defaultOrder: { field: MaterialSortField.CREATED_AT, order: SortOrder.DESC },
3730
+ * tiebreaker: 'material.id',
3731
+ * });
3732
+ * ```
3733
+ */
3734
+ function applyListSort(qb, options) {
3735
+ const clauses = resolveListSort(options);
3736
+ if ((options.mode ?? 'entity') === 'entity') {
3737
+ clauses.forEach(({ expression }) => assertEntityOrderPath(qb, expression));
3738
+ }
3739
+ qb.orderBy();
3740
+ clauses.forEach(({ expression, order, nulls }) => {
3741
+ qb.addOrderBy(expression, order, nulls);
3742
+ });
3743
+ return qb;
3744
+ }
3745
+
3417
3746
  /**
3418
3747
  * The table an entity actually ended up in, as TypeORM resolved it — after
3419
3748
  * `withWmsTablePrefix`, and with its schema if it has one. Use it wherever SQL
@@ -3450,6 +3779,48 @@ const getWmsTablePrefix = () => readWmsTablePrefixState()?.prefix ?? '';
3450
3779
  */
3451
3780
  const wmsLogicalTableName = (tableName) => readWmsTablePrefixState()?.logicalNames.get(tableName) ?? tableName;
3452
3781
 
3782
+ /**
3783
+ * ORDER BY expressions for `findAggregatedStocks`, over the outer query: the
3784
+ * aggregated subquery is `agg`, and the joins a field needs are added by
3785
+ * `joinAggregatedStockSortTarget` under the `sort_*` aliases.
3786
+ */
3787
+ const AGGREGATED_STOCK_SORT_FIELDS = {
3788
+ [exports.AggregatedStockSortField.STATUS]: 'agg.status',
3789
+ [exports.AggregatedStockSortField.MATERIAL_KEY]: 'sort_material."key"',
3790
+ [exports.AggregatedStockSortField.MATERIAL_DESCRIPTION]: 'sort_material."description"',
3791
+ [exports.AggregatedStockSortField.BATCH_KEY]: 'sort_batch_group."key"',
3792
+ [exports.AggregatedStockSortField.LOCATION_KEY]: 'sort_location."key"',
3793
+ [exports.AggregatedStockSortField.LOADER_SERIAL_ID]: 'sort_loader."serialId"',
3794
+ [exports.AggregatedStockSortField.QUANTITY]: 'agg.quantity',
3795
+ [exports.AggregatedStockSortField.BASE_UNIT]: 'sort_unit."key"',
3796
+ [exports.AggregatedStockSortField.VENDOR_ID]: 'agg."vendorId"',
3797
+ [exports.AggregatedStockSortField.CUSTOMER_ID]: 'agg."customerId"',
3798
+ [exports.AggregatedStockSortField.SALE_ID]: 'agg."saleId"',
3799
+ [exports.AggregatedStockSortField.SALE_SERIAL_ID]: 'agg."saleSerialId"',
3800
+ };
3801
+ /**
3802
+ * What identifies an aggregated row, in the order the list has always used.
3803
+ * The batch columns grouped alongside are functionally dependent on `batchId`,
3804
+ * so these five are unique per row.
3805
+ */
3806
+ const AGGREGATED_STOCK_GROUP_KEY = [
3807
+ 'agg."materialId"',
3808
+ 'agg."batchId"',
3809
+ 'agg."locationId"',
3810
+ 'agg."loaderId"',
3811
+ 'agg.status',
3812
+ ];
3813
+ /** The parameter TypeORM gives a single-table child's discriminator values. */
3814
+ const TYPEORM_DISCRIMINATOR_PARAMETER = 'discriminatorColumnValues';
3815
+ /** Its renamed copy inside `findManyGroupedByMaterialId`'s stock subquery. */
3816
+ const STOCK_DISCRIMINATOR_PARAMETER = 'stockDiscriminatorColumnValues';
3817
+ /** ORDER BY expressions for `findManyGroupedByMaterialId`. */
3818
+ const STOCK_GROUPED_BY_MATERIAL_SORT_FIELDS = {
3819
+ [exports.StockGroupedByMaterialSortField.MATERIAL_KEY]: 'material."key"',
3820
+ [exports.StockGroupedByMaterialSortField.MATERIAL_DESCRIPTION]: 'material."description"',
3821
+ [exports.StockGroupedByMaterialSortField.QUANTITY]: 'totals.quantity',
3822
+ [exports.StockGroupedByMaterialSortField.BASE_UNIT]: 'sort_unit."key"',
3823
+ };
3453
3824
  /**
3454
3825
  * A lock taken in autocommit is released by the statement that took it, so a
3455
3826
  * check "protected" by one is not protected at all. Refuse instead.
@@ -3513,7 +3884,10 @@ exports.StockService = class StockService {
3513
3884
  .addSelect('b."vendorId"', 'vendorId')
3514
3885
  .addSelect('b."customerId"', 'customerId')
3515
3886
  .from(tablePathOf(this.dataSource, this.stockEntity), 's')
3516
- .innerJoin(tablePathOf(this.dataSource, this.entities.batch), 'b', 's."batchId" = b.id'), 'stock_status', `stock_status."stockId" = ${alias}.id`)
3887
+ // The entity, not its table path: a schema-qualified path such as
3888
+ // `shuttle.wms_batches` reads to TypeORM as `<alias>.<relation>`
3889
+ // in a join and fails with `"shuttle" alias was not found`.
3890
+ .innerJoin(this.entities.batch, 'b', 's."batchId" = b.id'), 'stock_status', `stock_status."stockId" = ${alias}.id`)
3517
3891
  .addSelect('stock_status.status', 'status')
3518
3892
  .addSelect('stock_status."transferId"', 'transferId')
3519
3893
  .addSelect('stock_status.held', 'held')
@@ -3727,7 +4101,8 @@ exports.StockService = class StockService {
3727
4101
  if (options.limit !== undefined && options.limit > 0)
3728
4102
  queryBuilder.take(options.limit);
3729
4103
  if (aggregated) {
3730
- queryBuilder.innerJoin(tablePathOf(this.dataSource, this.entities.batch), 'b', 'stock."batchId" = b.id');
4104
+ // The entity, not its table path — see `selectQueryBuilder`.
4105
+ queryBuilder.innerJoin(this.entities.batch, 'b', 'stock."batchId" = b.id');
3731
4106
  queryBuilder.select('stock."materialId"', 'materialId');
3732
4107
  queryBuilder.addSelect('stock."batchId"', 'batchId');
3733
4108
  queryBuilder.addSelect('stock."locationId"', 'locationId');
@@ -3786,27 +4161,76 @@ exports.StockService = class StockService {
3786
4161
  const queryBuilder = this.pipeSelectOptionsToQueryBuilder(options, this.selectQueryBuilder('stock'));
3787
4162
  return queryBuilder.getManyAndCount();
3788
4163
  }
4164
+ /**
4165
+ * Materials with stock, one page of them, in one statement.
4166
+ *
4167
+ * A material is listed when any of its (material, batch, location, loader,
4168
+ * status) positions nets to non-zero after the filters — the aggregated
4169
+ * subquery's `HAVING` — not when the material's own total does: +5 in one
4170
+ * place and -5 in another is listed. Soft-deleted materials are left out
4171
+ * (the material repository is the main alias).
4172
+ *
4173
+ * The positions are summed per material in the database, joined to the
4174
+ * material, sorted and paged there; `total` comes from a window count on the
4175
+ * same statement. Only a page past the end, which has no row to carry it,
4176
+ * costs a second query.
4177
+ */
3789
4178
  async findManyGroupedByMaterialId(options) {
3790
- // Build aggregated subquery to get distinct materialIds where SUM(quantity) != 0
3791
- const aggregateSubquery = this.pipeSelectOptionsToQueryBuilder({ ...options, offset: undefined, limit: undefined }, this.selectQueryBuilder('stock'), true);
3792
- const rawMaterialIds = await this.dataSource
3793
- .createQueryBuilder()
3794
- .select('DISTINCT agg."materialId"', 'materialId')
3795
- .from(`(${aggregateSubquery.getQuery()})`, 'agg')
3796
- .setParameters(aggregateSubquery.getParameters())
3797
- .getRawMany();
3798
- const ids = rawMaterialIds.map((r) => r.materialId);
3799
- if (ids.length === 0)
3800
- return [[], 0];
3801
- const queryBuilder = this.dataSource
4179
+ const { sort, offset, limit, ...filters } = options;
4180
+ const aggregateSubquery = this.pipeSelectOptionsToQueryBuilder(filters, this.selectQueryBuilder('stock'), true);
4181
+ /*
4182
+ * Both the stock subquery and the material main alias are single-table
4183
+ * children, and TypeORM names *every* discriminator parameter
4184
+ * `discriminatorColumnValues`. Embedded as is, the outer query's value
4185
+ * (the material's) would overwrite the inner one and the stock filter would
4186
+ * match nothing — so the inner placeholder gets a name of its own.
4187
+ */
4188
+ const { [TYPEORM_DISCRIMINATOR_PARAMETER]: stockDiscriminatorValues, ...aggregateParameters } = aggregateSubquery.getParameters();
4189
+ const aggregateSql = aggregateSubquery
4190
+ .getQuery()
4191
+ .split(`:...${TYPEORM_DISCRIMINATOR_PARAMETER}`)
4192
+ .join(`:...${STOCK_DISCRIMINATOR_PARAMETER}`);
4193
+ const queryBuilder = () => this.dataSource
3802
4194
  .getRepository(this.materialEntity)
3803
4195
  .createQueryBuilder('material')
3804
- .where('material.id IN (:...materialIds)', { materialIds: ids });
3805
- if (options.offset !== undefined && options.offset >= 0)
3806
- queryBuilder.skip(options.offset);
3807
- if (options.limit !== undefined && options.limit > 0)
3808
- queryBuilder.take(options.limit);
3809
- return queryBuilder.getManyAndCount();
4196
+ .innerJoin((subQuery) => subQuery
4197
+ .select('agg."materialId"', 'materialId')
4198
+ .addSelect('SUM(agg.quantity)', 'quantity')
4199
+ .from(`(${aggregateSql})`, 'agg')
4200
+ .groupBy('agg."materialId"'), 'totals', 'totals."materialId" = material.id')
4201
+ .setParameters({
4202
+ ...aggregateParameters,
4203
+ ...(stockDiscriminatorValues === undefined
4204
+ ? {}
4205
+ : { [STOCK_DISCRIMINATOR_PARAMETER]: stockDiscriminatorValues }),
4206
+ });
4207
+ const pageBuilder = queryBuilder().addSelect('COUNT(*) OVER ()', 'total');
4208
+ // `materials.baseUnit` holds the unit's id, so its key needs a join; one
4209
+ // unit per material, so the join keeps one row per material.
4210
+ if (sort?.field === exports.StockGroupedByMaterialSortField.BASE_UNIT) {
4211
+ pageBuilder.leftJoin(exports.UnitEntityClass, 'sort_unit', 'CAST(sort_unit.id AS text) = material."baseUnit"');
4212
+ }
4213
+ applyListSort(pageBuilder, {
4214
+ sort,
4215
+ fields: STOCK_GROUPED_BY_MATERIAL_SORT_FIELDS,
4216
+ defaultOrder: {
4217
+ field: exports.StockGroupedByMaterialSortField.MATERIAL_KEY,
4218
+ order: exports.SortOrder.ASC,
4219
+ },
4220
+ tiebreaker: 'material.id',
4221
+ mode: 'raw',
4222
+ });
4223
+ // `totals` is one row per material, so LIMIT/OFFSET cut whole materials.
4224
+ if (offset !== undefined && offset >= 0)
4225
+ pageBuilder.offset(offset);
4226
+ if (limit !== undefined && limit > 0)
4227
+ pageBuilder.limit(limit);
4228
+ const { entities, raw } = await pageBuilder.getRawAndEntities();
4229
+ if (raw.length)
4230
+ return [entities, parseInt(raw[0].total, 10)];
4231
+ if (!offset)
4232
+ return [[], 0];
4233
+ return [[], await queryBuilder().getCount()];
3810
4234
  }
3811
4235
  async findAggregatedStock(options, manager = this.dataSource.manager) {
3812
4236
  const queryBuilder = this.pipeSelectOptionsToQueryBuilder(options, this.selectQueryBuilder('stock', manager.getRepository(this.stockEntity).createQueryBuilder('stock')), true);
@@ -3868,6 +4292,39 @@ exports.StockService = class StockService {
3868
4292
  throw new Error(`Insufficient stock: available ${available}, requested ${quantity} (materialId=${materialId}, batchId=${batchId}, loaderId=${loaderId})`);
3869
4293
  }
3870
4294
  }
4295
+ /**
4296
+ * Join what a sort field of `findAggregatedStocks` orders by, and nothing
4297
+ * else: an unsorted call (every internal caller) keeps its plain query.
4298
+ * Each join is on a primary key, so the outer query stays one row per
4299
+ * aggregated position and LIMIT/OFFSET still cut whole rows. Entities, not
4300
+ * table names, so a table prefix and an overridden entity both follow.
4301
+ */
4302
+ joinAggregatedStockSortTarget(queryBuilder, field) {
4303
+ switch (field) {
4304
+ case exports.AggregatedStockSortField.MATERIAL_KEY:
4305
+ case exports.AggregatedStockSortField.MATERIAL_DESCRIPTION:
4306
+ queryBuilder.leftJoin(this.materialEntity, 'sort_material', 'sort_material.id = agg."materialId"');
4307
+ break;
4308
+ case exports.AggregatedStockSortField.BASE_UNIT:
4309
+ queryBuilder
4310
+ .leftJoin(this.materialEntity, 'sort_material', 'sort_material.id = agg."materialId"')
4311
+ .leftJoin(exports.UnitEntityClass, 'sort_unit', 'CAST(sort_unit.id AS text) = sort_material."baseUnit"');
4312
+ break;
4313
+ case exports.AggregatedStockSortField.BATCH_KEY:
4314
+ // What `batch { key }` shows is the batch *group*'s key.
4315
+ queryBuilder
4316
+ .leftJoin(this.entities.batch, 'sort_batch', 'sort_batch.id = agg."batchId"')
4317
+ .leftJoin(exports.BatchGroupEntityClass, 'sort_batch_group', 'CAST(sort_batch_group.id AS text) = CAST(sort_batch."groupId" AS text)');
4318
+ break;
4319
+ case exports.AggregatedStockSortField.LOCATION_KEY:
4320
+ queryBuilder.leftJoin(this.entities.location, 'sort_location', 'sort_location.id = agg."locationId"');
4321
+ break;
4322
+ case exports.AggregatedStockSortField.LOADER_SERIAL_ID:
4323
+ // `stocks.loaderId` is varchar, `loaders.id` uuid.
4324
+ queryBuilder.leftJoin(exports.LoadersEntityClass, 'sort_loader', 'CAST(sort_loader.id AS text) = agg."loaderId"');
4325
+ break;
4326
+ }
4327
+ }
3871
4328
  async findAggregatedStocks(options, manager = this.dataSource.manager) {
3872
4329
  // Create the aggregated subquery without pagination
3873
4330
  const aggregateSubquery = this.pipeSelectOptionsToQueryBuilder({ ...options, offset: undefined, limit: undefined }, this.selectQueryBuilder('stock', manager.getRepository(this.stockEntity).createQueryBuilder('stock')),
@@ -3903,12 +4360,26 @@ exports.StockService = class StockService {
3903
4360
  // (material, batch, location, loader) plus the derived status -- which is
3904
4361
  // what makes a row unique here; without a total order LIMIT/OFFSET pages
3905
4362
  // can repeat or skip rows.
3906
- paginatedQueryBuilder
3907
- .orderBy('agg."materialId"', 'ASC')
3908
- .addOrderBy('agg."batchId"', 'ASC')
3909
- .addOrderBy('agg."locationId"', 'ASC', 'NULLS FIRST')
3910
- .addOrderBy('agg."loaderId"', 'ASC', 'NULLS FIRST')
3911
- .addOrderBy('agg.status', 'ASC', 'NULLS FIRST');
4363
+ if (options.sort) {
4364
+ this.joinAggregatedStockSortTarget(paginatedQueryBuilder, options.sort.field);
4365
+ applyListSort(paginatedQueryBuilder, {
4366
+ sort: options.sort,
4367
+ fields: AGGREGATED_STOCK_SORT_FIELDS,
4368
+ defaultOrder: options.sort,
4369
+ tiebreaker: AGGREGATED_STOCK_GROUP_KEY,
4370
+ mode: 'raw',
4371
+ });
4372
+ }
4373
+ else {
4374
+ // The order this list has always had, kept verbatim (NULLS FIRST
4375
+ // included) so callers paging without a sort see no change.
4376
+ paginatedQueryBuilder
4377
+ .orderBy('agg."materialId"', 'ASC')
4378
+ .addOrderBy('agg."batchId"', 'ASC')
4379
+ .addOrderBy('agg."locationId"', 'ASC', 'NULLS FIRST')
4380
+ .addOrderBy('agg."loaderId"', 'ASC', 'NULLS FIRST')
4381
+ .addOrderBy('agg.status', 'ASC', 'NULLS FIRST');
4382
+ }
3912
4383
  if (options.offset !== undefined && options.offset >= 0) {
3913
4384
  paginatedQueryBuilder.offset(options.offset);
3914
4385
  }
@@ -3935,10 +4406,11 @@ exports.StockService = class StockService {
3935
4406
  return [items, count];
3936
4407
  }
3937
4408
  async findChangeLogs(options) {
4409
+ const { sort, ...filters } = options;
3938
4410
  // Our own change tables, named as they ended up under `withWmsTablePrefix`.
3939
4411
  const prefix = getWmsTablePrefix();
3940
4412
  // Build base query with all change entity joins
3941
- const changesQueryBuilder = this.pipeSelectOptionsToQueryBuilder({ ...options, offset: undefined, limit: undefined }, this.selectQueryBuilder('stock'), false)
4413
+ const changesQueryBuilder = this.pipeSelectOptionsToQueryBuilder({ ...filters, offset: undefined, limit: undefined }, this.selectQueryBuilder('stock'), false)
3942
4414
  .leftJoin(`${prefix}receive_inventory_order_changes`, 'receive_change', 'stock."orderId" = receive_change.id')
3943
4415
  .leftJoin(`${prefix}ship_inventory_order_changes`, 'ship_change', 'stock."orderId" = ship_change.id')
3944
4416
  .leftJoin(`${prefix}transfer_order_changes`, 'transfer_change', 'stock."orderId" = transfer_change.id')
@@ -3988,16 +4460,9 @@ exports.StockService = class StockService {
3988
4460
  if (options.limit !== undefined && options.limit > 0) {
3989
4461
  resultQueryBuilder.limit(options.limit);
3990
4462
  }
3991
- // Explicitly select only the fields needed for ChangeLog
3992
- resultQueryBuilder
3993
- .select('stock.id', 'id')
3994
- .addSelect('stock.quantity', 'quantity')
3995
- .addSelect('stock_status.status', 'status')
3996
- .addSelect('stock."materialId"', 'materialId')
3997
- .addSelect('stock."batchId"', 'batchId')
3998
- .addSelect('stock."locationId"', 'locationId')
3999
- .addSelect('stock."loaderId"', 'loaderId')
4000
- .addSelect(`CASE
4463
+ // Also the ORDER BY for CHANGE_TYPE: PostgreSQL accepts an output alias
4464
+ // in ORDER BY only on its own, never inside an expression.
4465
+ const changeTypeSql = `CASE
4001
4466
  WHEN receive_change.id IS NOT NULL THEN '${exports.ChangeType.RECEIVED}'
4002
4467
  WHEN ship_change.id IS NOT NULL THEN
4003
4468
  CASE WHEN ship_change."quantityChanged" > 0 THEN '${exports.ChangeType.IN_SHIPMENT}'
@@ -4022,13 +4487,61 @@ exports.StockService = class StockService {
4022
4487
  WHEN reclassify_change.id IS NOT NULL THEN '${exports.ChangeType.RECLASSIFIED}'
4023
4488
  WHEN scrape_change.id IS NOT NULL THEN '${exports.ChangeType.SCRAPED}'
4024
4489
  ELSE NULL
4025
- END`, 'changeType');
4490
+ END`;
4491
+ // Explicitly select only the fields needed for ChangeLog
4492
+ resultQueryBuilder
4493
+ .select('stock.id', 'id')
4494
+ .addSelect('stock.quantity', 'quantity')
4495
+ .addSelect('stock_status.status', 'status')
4496
+ .addSelect('stock."materialId"', 'materialId')
4497
+ .addSelect('stock."batchId"', 'batchId')
4498
+ .addSelect('stock."locationId"', 'locationId')
4499
+ .addSelect('stock."loaderId"', 'loaderId')
4500
+ .addSelect(changeTypeSql, 'changeType');
4501
+ // Joined only for the column asked for, by entity (the overridable ones
4502
+ // through `WmsEntities`) so the table prefix applies; every join is on a
4503
+ // primary key, so no row is multiplied. Aliases avoid the filter joins'.
4504
+ if (sort?.field === exports.ChangeLogSortField.MATERIAL_KEY ||
4505
+ sort?.field === exports.ChangeLogSortField.MATERIAL_DESCRIPTION ||
4506
+ sort?.field === exports.ChangeLogSortField.BASE_UNIT) {
4507
+ resultQueryBuilder.leftJoin(this.entities.material, 'cl_material', 'cl_material.id = stock."materialId"');
4508
+ }
4509
+ if (sort?.field === exports.ChangeLogSortField.BASE_UNIT) {
4510
+ resultQueryBuilder.leftJoin(exports.UnitEntityClass, 'cl_unit', 'CAST(cl_unit.id AS text) = cl_material."baseUnit"');
4511
+ }
4512
+ if (sort?.field === exports.ChangeLogSortField.BATCH_KEY) {
4513
+ resultQueryBuilder.leftJoin(this.entities.batch, 'cl_batch', 'cl_batch.id = stock."batchId"');
4514
+ }
4515
+ if (sort?.field === exports.ChangeLogSortField.LOCATION_KEY) {
4516
+ resultQueryBuilder.leftJoin(this.entities.location, 'cl_location', 'cl_location.id = stock."locationId"');
4517
+ }
4518
+ const changeTypeRank = `(CASE ${changeTypeSql} ${Object.values(exports.ChangeType)
4519
+ .map((type, rank) => `WHEN '${type}' THEN ${rank}`)
4520
+ .join(' ')} END)`;
4026
4521
  // The id tiebreaker is what keeps two pages from overlapping when several
4027
4522
  // rows share a timestamp, which a multi-line order always produces.
4028
- const items = await resultQueryBuilder
4029
- .addOrderBy('stock."createdAt"', 'DESC')
4030
- .addOrderBy('stock.id', 'ASC')
4031
- .getRawMany();
4523
+ applyListSort(resultQueryBuilder, {
4524
+ sort,
4525
+ fields: {
4526
+ [exports.ChangeLogSortField.CHANGE_TYPE]: changeTypeRank,
4527
+ [exports.ChangeLogSortField.MATERIAL_KEY]: 'cl_material.key',
4528
+ [exports.ChangeLogSortField.MATERIAL_DESCRIPTION]: 'cl_material.description',
4529
+ [exports.ChangeLogSortField.BATCH_KEY]: 'cl_batch.key',
4530
+ [exports.ChangeLogSortField.LOCATION_KEY]: 'cl_location.key',
4531
+ // The magnitude, as `changeLogs` displays it: the sign is the change
4532
+ // type's to carry, and sorting it would put every outflow first.
4533
+ [exports.ChangeLogSortField.QUANTITY]: 'ABS(stock.quantity)',
4534
+ [exports.ChangeLogSortField.BASE_UNIT]: 'cl_unit.key',
4535
+ [exports.ChangeLogSortField.CREATED_AT]: 'stock."createdAt"',
4536
+ },
4537
+ defaultOrder: {
4538
+ field: exports.ChangeLogSortField.CREATED_AT,
4539
+ order: exports.SortOrder.DESC,
4540
+ },
4541
+ tiebreaker: 'stock.id',
4542
+ mode: 'raw',
4543
+ });
4544
+ const items = await resultQueryBuilder.getRawMany();
4032
4545
  return [items, count];
4033
4546
  }
4034
4547
  };
@@ -4210,6 +4723,27 @@ exports.WmsSequenceService = tslib.__decorate([
4210
4723
  tslib.__metadata("design:paramtypes", [typeorm.DataSource, Object])
4211
4724
  ], exports.WmsSequenceService);
4212
4725
 
4726
+ /** ORDER BY per sort field; `sort_type` / `sort_location` are joined on demand. */
4727
+ const LOADER_SORT_FIELDS = {
4728
+ [exports.LoaderSortField.SERIAL_ID]: 'loader.serialId',
4729
+ [exports.LoaderSortField.TYPE_DESCRIPTION]: 'sort_type.description',
4730
+ [exports.LoaderSortField.LOCATION_KEY]: 'sort_location.key',
4731
+ [exports.LoaderSortField.LENGTH]: 'loader.length',
4732
+ [exports.LoaderSortField.WIDTH]: 'loader.width',
4733
+ [exports.LoaderSortField.HEIGHT]: 'loader.height',
4734
+ [exports.LoaderSortField.SIZE_UNIT]: 'loader.sizeUnit',
4735
+ [exports.LoaderSortField.VOLUME]: 'loader.volume',
4736
+ [exports.LoaderSortField.VOLUME_UNIT]: 'loader.volumeUnit',
4737
+ [exports.LoaderSortField.NOTE]: 'loader.note',
4738
+ [exports.LoaderSortField.IS_ACTIVE]: 'loader.isActive',
4739
+ [exports.LoaderSortField.CREATED_AT]: 'loader.createdAt',
4740
+ };
4741
+ const LOADER_TYPE_SORT_FIELDS = {
4742
+ [exports.LoaderTypeSortField.KEY]: 'loader_type.key',
4743
+ [exports.LoaderTypeSortField.DESCRIPTION]: 'loader_type.description',
4744
+ [exports.LoaderTypeSortField.IS_ACTIVE]: 'loader_type.isActive',
4745
+ [exports.LoaderTypeSortField.CREATED_AT]: 'loader_type.createdAt',
4746
+ };
4213
4747
  /**
4214
4748
  * Service for managing loaders and their types
4215
4749
  * Supports dynamic entity injection for customization
@@ -4323,7 +4857,7 @@ exports.LoaderService = class LoaderService {
4323
4857
  return this.sequenceService.reserve(`${prefix}_SEQ`, count, transactionManager, { consecutive: true, maxValue });
4324
4858
  });
4325
4859
  }
4326
- findManyLoaders(options) {
4860
+ async findManyLoaders(options) {
4327
4861
  const queryBuilder = this.dataSource
4328
4862
  .getRepository(this.loaderEntity)
4329
4863
  .createQueryBuilder('loader');
@@ -4382,13 +4916,38 @@ exports.LoaderService = class LoaderService {
4382
4916
  value: `%${value}%`,
4383
4917
  });
4384
4918
  }
4919
+ // Joined by class (the location through `WmsEntities`: it may be a host override) and only when that
4920
+ // column is asked for; both joins are on a primary key, one row per loader.
4921
+ // Selected because the paginated DISTINCT subquery must see the column.
4922
+ if (options.sort?.field === exports.LoaderSortField.TYPE_DESCRIPTION) {
4923
+ queryBuilder
4924
+ .leftJoin(
4925
+ // Loader types are owned by this package (no base override), so the
4926
+ // class is the table; a host subclass would share it.
4927
+ exports.LoaderTypeEntityClass, 'sort_type', 'sort_type.id = loader.typeId')
4928
+ .addSelect('sort_type.description');
4929
+ }
4930
+ if (options.sort?.field === exports.LoaderSortField.LOCATION_KEY) {
4931
+ queryBuilder
4932
+ .leftJoin(this.entities.location, 'sort_location', 'sort_location.id = loader.locationId')
4933
+ .addSelect('sort_location.key');
4934
+ }
4935
+ applyListSort(queryBuilder, {
4936
+ sort: options.sort,
4937
+ fields: LOADER_SORT_FIELDS,
4938
+ defaultOrder: {
4939
+ field: exports.LoaderSortField.CREATED_AT,
4940
+ order: exports.SortOrder.DESC,
4941
+ },
4942
+ tiebreaker: 'loader.id',
4943
+ });
4385
4944
  if (options.offset !== undefined && options.offset >= 0)
4386
4945
  queryBuilder.skip(options.offset);
4387
4946
  if (options.limit !== undefined && options.limit > 0)
4388
4947
  queryBuilder.take(options.limit);
4389
4948
  return queryBuilder.getManyAndCount();
4390
4949
  }
4391
- findManyLoaderTypes(options) {
4950
+ async findManyLoaderTypes(options) {
4392
4951
  const queryBuilder = this.dataSource
4393
4952
  .getRepository(this.loaderTypeEntity)
4394
4953
  .createQueryBuilder('loader_type');
@@ -4411,6 +4970,15 @@ exports.LoaderService = class LoaderService {
4411
4970
  value: `%${value}%`,
4412
4971
  });
4413
4972
  }
4973
+ applyListSort(queryBuilder, {
4974
+ sort: options.sort,
4975
+ fields: LOADER_TYPE_SORT_FIELDS,
4976
+ defaultOrder: {
4977
+ field: exports.LoaderTypeSortField.CREATED_AT,
4978
+ order: exports.SortOrder.DESC,
4979
+ },
4980
+ tiebreaker: 'loader_type.id',
4981
+ });
4414
4982
  if (options.offset !== undefined && options.offset >= 0)
4415
4983
  queryBuilder.skip(options.offset);
4416
4984
  if (options.limit !== undefined && options.limit > 0)
@@ -4428,6 +4996,14 @@ exports.LoaderService = tslib.__decorate([
4428
4996
  exports.WmsEntities, Object, Object, Object])
4429
4997
  ], exports.LoaderService);
4430
4998
 
4999
+ /** ORDER BY expressions per sort field; `baseUnit` is joined on demand. */
5000
+ const MATERIAL_SORT_FIELDS = {
5001
+ [exports.MaterialSortField.KEY]: 'material.key',
5002
+ [exports.MaterialSortField.DESCRIPTION]: 'material.description',
5003
+ [exports.MaterialSortField.BASE_UNIT]: 'baseUnit.key',
5004
+ [exports.MaterialSortField.IS_ACTIVE]: 'material.isActive',
5005
+ [exports.MaterialSortField.CREATED_AT]: 'material.createdAt',
5006
+ };
4431
5007
  /**
4432
5008
  * Service for managing materials and their units
4433
5009
  * Supports dynamic entity injection for customization
@@ -4511,7 +5087,7 @@ exports.MaterialService = class MaterialService {
4511
5087
  }
4512
5088
  return updated;
4513
5089
  }
4514
- findMany(options) {
5090
+ async findMany(options) {
4515
5091
  const queryBuilder = this.dataSource
4516
5092
  .getRepository(this.materialEntity)
4517
5093
  .createQueryBuilder('material');
@@ -4533,6 +5109,27 @@ exports.MaterialService = class MaterialService {
4533
5109
  value: `%${value}%`,
4534
5110
  });
4535
5111
  }
5112
+ // `materials.baseUnit` holds the unit's id; sorting by it would order by
5113
+ // uuid. Join the unit (by class, so the table prefix and the paginated
5114
+ // DISTINCT subquery both resolve it) and select its key, only when asked —
5115
+ // the join is one row per material (`units.id` is the primary key).
5116
+ if (options.sort?.field === exports.MaterialSortField.BASE_UNIT) {
5117
+ queryBuilder
5118
+ .leftJoin(exports.UnitEntityClass, 'baseUnit',
5119
+ // `CAST(...)`, not `::text`: TypeORM only rewrites `alias.property`
5120
+ // when a space, `=`, `)` or `,` follows it.
5121
+ 'CAST(baseUnit.id AS text) = material.baseUnit')
5122
+ .addSelect('baseUnit.key');
5123
+ }
5124
+ applyListSort(queryBuilder, {
5125
+ sort: options.sort,
5126
+ fields: MATERIAL_SORT_FIELDS,
5127
+ defaultOrder: {
5128
+ field: exports.MaterialSortField.CREATED_AT,
5129
+ order: exports.SortOrder.DESC,
5130
+ },
5131
+ tiebreaker: 'material.id',
5132
+ });
4536
5133
  if (options.offset !== undefined && options.offset >= 0)
4537
5134
  queryBuilder.skip(options.offset);
4538
5135
  if (options.limit !== undefined && options.limit > 0)
@@ -4822,6 +5419,23 @@ exports.HelperService = tslib.__decorate([
4822
5419
  * T - Receive Inventory Order entity type
4823
5420
  * K - Receive Inventory Order Item entity type
4824
5421
  */
5422
+ /**
5423
+ * ORDER BY per sort field. Raw mode: the list reads with `getRawMany`, and
5424
+ * `status` is the `order_status` join's computed column — ranked by lifecycle
5425
+ * rather than spelled, since its values sort alphabetically into nonsense.
5426
+ */
5427
+ const RECEIVE_ORDER_SORT_FIELDS = {
5428
+ [exports.ReceiveInventoryOrderSortField.STATUS]: `(CASE order_status.status
5429
+ WHEN '${exports.ReceiveInventoryOrderStatus.PENDING}' THEN 0
5430
+ WHEN '${exports.ReceiveInventoryOrderStatus.PARTIAL_RECEIVED}' THEN 1
5431
+ WHEN '${exports.ReceiveInventoryOrderStatus.RECEIVED}' THEN 2
5432
+ WHEN '${exports.ReceiveInventoryOrderStatus.REMOVED}' THEN 3
5433
+ END)`,
5434
+ [exports.ReceiveInventoryOrderSortField.KEY]: 'orders.key',
5435
+ [exports.ReceiveInventoryOrderSortField.CREATED_BY]: 'orders."createdBy"',
5436
+ [exports.ReceiveInventoryOrderSortField.CREATED_AT]: 'orders."createdAt"',
5437
+ [exports.ReceiveInventoryOrderSortField.DESCRIPTION]: 'orders.description',
5438
+ };
4825
5439
  exports.ReceiveInventoryOrderService = class ReceiveInventoryOrderService {
4826
5440
  dataSource;
4827
5441
  entities;
@@ -5064,9 +5678,18 @@ exports.ReceiveInventoryOrderService = class ReceiveInventoryOrderService {
5064
5678
  // `offset`/`limit` go straight into the SQL. The join is one row per
5065
5679
  // order, so a page is exactly `limit` orders — and a page is only a page
5066
5680
  // with a stable order underneath it.
5067
- queryBuilder
5068
- .orderBy('orders."createdAt"', 'DESC')
5069
- .addOrderBy('orders.id', 'ASC');
5681
+ // After `getCount()`, which cannot carry an ORDER BY on the computed
5682
+ // column. The join is one row per order, so a page is exactly `limit`.
5683
+ applyListSort(queryBuilder, {
5684
+ sort: options.sort,
5685
+ fields: RECEIVE_ORDER_SORT_FIELDS,
5686
+ defaultOrder: {
5687
+ field: exports.ReceiveInventoryOrderSortField.CREATED_AT,
5688
+ order: exports.SortOrder.DESC,
5689
+ },
5690
+ tiebreaker: 'orders.id',
5691
+ mode: 'raw',
5692
+ });
5070
5693
  if (options.offset !== undefined && options.offset >= 0)
5071
5694
  queryBuilder.offset(options.offset);
5072
5695
  if (options.limit !== undefined && options.limit > 0)
@@ -5247,6 +5870,23 @@ exports.ReceiveInventoryOrderService = tslib.__decorate([
5247
5870
  * T - Ship Inventory Order entity type
5248
5871
  * K - Ship Inventory Order Item entity type
5249
5872
  */
5873
+ /**
5874
+ * ORDER BY per sort field. Raw mode: the list reads with `getRawMany`, and
5875
+ * `status` is the `order_status` join's computed column — ranked by lifecycle
5876
+ * rather than spelled, since its values sort alphabetically into nonsense.
5877
+ */
5878
+ const SHIP_ORDER_SORT_FIELDS = {
5879
+ [exports.ShipInventoryOrderSortField.STATUS]: `(CASE order_status.status
5880
+ WHEN '${exports.ShipInventoryOrderStatus.PENDING}' THEN 0
5881
+ WHEN '${exports.ShipInventoryOrderStatus.PARTIAL_SHIPPED}' THEN 1
5882
+ WHEN '${exports.ShipInventoryOrderStatus.SHIPPED}' THEN 2
5883
+ WHEN '${exports.ShipInventoryOrderStatus.REMOVED}' THEN 3
5884
+ END)`,
5885
+ [exports.ShipInventoryOrderSortField.KEY]: 'orders.key',
5886
+ [exports.ShipInventoryOrderSortField.CREATED_BY]: 'orders."createdBy"',
5887
+ [exports.ShipInventoryOrderSortField.CREATED_AT]: 'orders."createdAt"',
5888
+ [exports.ShipInventoryOrderSortField.DESCRIPTION]: 'orders.description',
5889
+ };
5250
5890
  exports.ShipInventoryOrderService = class ShipInventoryOrderService {
5251
5891
  dataSource;
5252
5892
  entities;
@@ -5290,7 +5930,11 @@ exports.ShipInventoryOrderService = class ShipInventoryOrderService {
5290
5930
  .select('i."orderId"', 'orderid')
5291
5931
  .addSelect(`SUM(CASE WHEN CAST(c."quantityChanged" AS NUMERIC) < 0 THEN ABS(CAST(c."quantityChanged" AS NUMERIC)) ELSE 0 END)`, 'shippedsum')
5292
5932
  .from(tablePathOf(this.dataSource, exports.ShipInventoryOrderChangeEntityClass), 'c')
5293
- .innerJoin(tablePathOf(this.dataSource, this.shipInventoryOrderItemEntity), 'i', 'c."itemId" = i.id')
5933
+ // The entity, not its table path: a schema-qualified path
5934
+ // reads to TypeORM as `<alias>.<relation>` in a join.
5935
+ // `.target` only narrows `EntityTarget` to the class (or,
5936
+ // for an EntitySchema, its name) that `innerJoin` accepts.
5937
+ .innerJoin(this.dataSource.getMetadata(this.shipInventoryOrderItemEntity).target, 'i', 'c."itemId" = i.id')
5294
5938
  .groupBy('i."orderId"'), 'change_sums', 'change_sums.orderid = o.id'), 'order_status', `${alias}.id = order_status.orderid`)
5295
5939
  .select('orders.id', 'id')
5296
5940
  .addSelect('orders.key', 'key')
@@ -5694,9 +6338,18 @@ exports.ShipInventoryOrderService = class ShipInventoryOrderService {
5694
6338
  // Raw query with a join (see ReceiveInventoryOrderService.findMany):
5695
6339
  // `skip`/`take` would be dropped silently, `offset`/`limit` are honoured.
5696
6340
  // `order_status` is one row per order, so the page size is exact.
5697
- queryBuilder
5698
- .orderBy('orders."createdAt"', 'DESC')
5699
- .addOrderBy('orders.id', 'ASC');
6341
+ // After `getCount()`, which cannot carry an ORDER BY on the computed
6342
+ // column. The join is one row per order, so a page is exactly `limit`.
6343
+ applyListSort(queryBuilder, {
6344
+ sort: options.sort,
6345
+ fields: SHIP_ORDER_SORT_FIELDS,
6346
+ defaultOrder: {
6347
+ field: exports.ShipInventoryOrderSortField.CREATED_AT,
6348
+ order: exports.SortOrder.DESC,
6349
+ },
6350
+ tiebreaker: 'orders.id',
6351
+ mode: 'raw',
6352
+ });
5700
6353
  if (options.offset !== undefined && options.offset >= 0)
5701
6354
  queryBuilder.offset(options.offset);
5702
6355
  if (options.limit !== undefined && options.limit > 0)
@@ -5815,6 +6468,12 @@ exports.ShipInventoryOrderService = tslib.__decorate([
5815
6468
  exports.StockService, Object, Object, Object, Object])
5816
6469
  ], exports.ShipInventoryOrderService);
5817
6470
 
6471
+ const LOCATION_SORT_FIELDS = {
6472
+ [exports.LocationSortField.KEY]: 'location.key',
6473
+ [exports.LocationSortField.DESCRIPTION]: 'location.description',
6474
+ [exports.LocationSortField.IS_ACTIVE]: 'location.isActive',
6475
+ [exports.LocationSortField.CREATED_AT]: 'location.createdAt',
6476
+ };
5818
6477
  exports.LocationService = class LocationService {
5819
6478
  dataSource;
5820
6479
  locationEntity;
@@ -5879,6 +6538,15 @@ exports.LocationService = class LocationService {
5879
6538
  value: `%${value}%`,
5880
6539
  });
5881
6540
  }
6541
+ applyListSort(queryBuilder, {
6542
+ sort: options.sort,
6543
+ fields: LOCATION_SORT_FIELDS,
6544
+ defaultOrder: {
6545
+ field: exports.LocationSortField.CREATED_AT,
6546
+ order: exports.SortOrder.DESC,
6547
+ },
6548
+ tiebreaker: 'location.id',
6549
+ });
5882
6550
  if (options.offset !== undefined && options.offset >= 0)
5883
6551
  queryBuilder.skip(options.offset);
5884
6552
  if (options.limit !== undefined && options.limit > 0)
@@ -5906,6 +6574,13 @@ exports.UnitService = tslib.__decorate([
5906
6574
  tslib.__metadata("design:paramtypes", [typeorm.DataSource])
5907
6575
  ], exports.UnitService);
5908
6576
 
6577
+ const TRANSFER_ORDER_SORT_FIELDS = {
6578
+ [exports.TransferOrderSortField.KEY]: 'to.key',
6579
+ [exports.TransferOrderSortField.RECEIVER]: 'to.receiver',
6580
+ [exports.TransferOrderSortField.DESCRIPTION]: 'to.description',
6581
+ [exports.TransferOrderSortField.CREATED_BY]: 'to.createdBy',
6582
+ [exports.TransferOrderSortField.CREATED_AT]: 'to.createdAt',
6583
+ };
5909
6584
  /**
5910
6585
  * What an item still has reserved and not yet executed, in base units.
5911
6586
  *
@@ -6248,7 +6923,7 @@ exports.TransferOrderService = class TransferOrderService {
6248
6923
  }
6249
6924
  return updated;
6250
6925
  }
6251
- findMany(options) {
6926
+ async findMany(options) {
6252
6927
  const queryBuilder = this.dataSource
6253
6928
  .getRepository(this.transferOrderEntity)
6254
6929
  .createQueryBuilder('to');
@@ -6325,6 +7000,15 @@ exports.TransferOrderService = class TransferOrderService {
6325
7000
  WHERE to_tgt_ldr_items."orderId" = to.id
6326
7001
  AND to_tgt_ldr."serialId" ILIKE :targetLoaderKey
6327
7002
  )`, { targetLoaderKey: `%${options.targetLoaderKey}%` });
7003
+ applyListSort(queryBuilder, {
7004
+ sort: options.sort,
7005
+ fields: TRANSFER_ORDER_SORT_FIELDS,
7006
+ defaultOrder: {
7007
+ field: exports.TransferOrderSortField.CREATED_AT,
7008
+ order: exports.SortOrder.DESC,
7009
+ },
7010
+ tiebreaker: 'to.id',
7011
+ });
6328
7012
  if (options.offset !== undefined && options.offset >= 0)
6329
7013
  queryBuilder.skip(options.offset);
6330
7014
  if (options.limit !== undefined && options.limit > 0)
@@ -6670,6 +7354,11 @@ exports.HoldInventoryOrderService = class HoldInventoryOrderService {
6670
7354
  queryBuilder.innerJoin('to.items', 'ld_items', 'ld_items.loaderId = :loaderId', {
6671
7355
  loaderId: options.loaderId,
6672
7356
  });
7357
+ // No UI sorts this list, so it takes no `sort`; it still needs a fixed
7358
+ // order or `skip`/`take` pages can repeat or skip orders. Property paths,
7359
+ // not quoted columns: the item joins above put the paginated DISTINCT
7360
+ // subquery in play, which can only carry those.
7361
+ queryBuilder.orderBy('to.createdAt', 'DESC').addOrderBy('to.id', 'ASC');
6673
7362
  if (options.offset !== undefined && options.offset >= 0)
6674
7363
  queryBuilder.skip(options.offset);
6675
7364
  if (options.limit !== undefined && options.limit > 0)
@@ -6998,6 +7687,11 @@ exports.AllocateInventoryOrderService = class AllocateInventoryOrderService {
6998
7687
  queryBuilder.innerJoin('to.items', 'ld_items', 'ld_items.loaderId = :loaderId', {
6999
7688
  loaderId: options.loaderId,
7000
7689
  });
7690
+ // No UI sorts this list, so it takes no `sort`; it still needs a fixed
7691
+ // order or `skip`/`take` pages can repeat or skip orders. Property paths,
7692
+ // not quoted columns: the item joins above put the paginated DISTINCT
7693
+ // subquery in play, which can only carry those.
7694
+ queryBuilder.orderBy('to.createdAt', 'DESC').addOrderBy('to.id', 'ASC');
7001
7695
  if (options.offset !== undefined && options.offset >= 0)
7002
7696
  queryBuilder.skip(options.offset);
7003
7697
  if (options.limit !== undefined && options.limit > 0)
@@ -7293,6 +7987,11 @@ exports.MergeBatchOrderService = tslib.__decorate([
7293
7987
  exports.StockService, Object, Object])
7294
7988
  ], exports.MergeBatchOrderService);
7295
7989
 
7990
+ const CONSUMPTION_ORDER_SORT_FIELDS = {
7991
+ [exports.ConsumptionOrderSortField.KEY]: 'consumption.key',
7992
+ [exports.ConsumptionOrderSortField.DESCRIPTION]: 'consumption.description',
7993
+ [exports.ConsumptionOrderSortField.CREATED_AT]: 'consumption.createdAt',
7994
+ };
7296
7995
  /**
7297
7996
  * Material handed to a process that consumes it: issue it out, take back what
7298
7997
  * came home, settle what was used.
@@ -7689,16 +8388,18 @@ exports.ConsumptionOrderService = class ConsumptionOrderService {
7689
8388
  createdAtTo: options.createdAtTo,
7690
8389
  });
7691
8390
  }
7692
- /*
7693
- * The property path, not a quoted column. `getManyAndCount` with a joined
7694
- * relation and a limit wraps the query in a `SELECT DISTINCT` over the root
7695
- * ids, and it can only carry an ordering across that wrapper if it
7696
- * recognises the expression as a column of the aliased entity. Given raw
7697
- * SQL it copies the string through verbatim and Postgres rejects
7698
- * `distinctAlias.consumption_"createdAt"`. Unpaginated calls never hit it,
7699
- * which is why it took a page-sized query to surface.
7700
- */
7701
- queryBuilder.orderBy('consumption.createdAt', 'DESC');
8391
+ // Property paths only (entity mode): `getManyAndCount` with the joined
8392
+ // items and a limit wraps the query in a `SELECT DISTINCT` over the root
8393
+ // ids, and raw SQL there renders `distinctAlias.consumption_"createdAt"`.
8394
+ applyListSort(queryBuilder, {
8395
+ sort: options.sort,
8396
+ fields: CONSUMPTION_ORDER_SORT_FIELDS,
8397
+ defaultOrder: {
8398
+ field: exports.ConsumptionOrderSortField.CREATED_AT,
8399
+ order: exports.SortOrder.DESC,
8400
+ },
8401
+ tiebreaker: 'consumption.id',
8402
+ });
7702
8403
  if (options.offset !== undefined && options.offset >= 0) {
7703
8404
  queryBuilder.skip(options.offset);
7704
8405
  }
@@ -8580,6 +9281,38 @@ exports.SaleOrderService = tslib.__decorate([
8580
9281
  tslib.__metadata("design:paramtypes", [typeorm.DataSource])
8581
9282
  ], exports.SaleOrderService);
8582
9283
 
9284
+ const INVENTORY_COUNT_ORDER_SORT_FIELDS = {
9285
+ [exports.InventoryCountOrderSortField.NAME]: 'count_order.name',
9286
+ // A PostgreSQL enum: ORDER BY follows its declaration order (the lifecycle).
9287
+ [exports.InventoryCountOrderSortField.STATUS]: 'count_order.status',
9288
+ [exports.InventoryCountOrderSortField.COUNT_DATE]: 'count_order.countDate',
9289
+ [exports.InventoryCountOrderSortField.CREATED_BY]: 'count_order.createdBy',
9290
+ [exports.InventoryCountOrderSortField.CREATED_AT]: 'count_order.createdAt',
9291
+ };
9292
+ /**
9293
+ * The count sheet reads with `getMany` + `offset`/`limit` over string-table
9294
+ * joins, so these are SQL (raw mode). The three flag fields sort by the same
9295
+ * test the sheet's icons render from.
9296
+ */
9297
+ const INVENTORY_COUNT_ORDER_ITEM_SORT_FIELDS = {
9298
+ [exports.InventoryCountOrderItemSortField.MATERIAL_KEY]: 'material.key',
9299
+ [exports.InventoryCountOrderItemSortField.MATERIAL_DESCRIPTION]: 'material.description',
9300
+ [exports.InventoryCountOrderItemSortField.BATCH_KEY]: 'batch.key',
9301
+ [exports.InventoryCountOrderItemSortField.LOCATION_KEY]: 'location.key',
9302
+ [exports.InventoryCountOrderItemSortField.LOADER_SERIAL_ID]: 'loader."serialId"',
9303
+ [exports.InventoryCountOrderItemSortField.VENDOR_ID]: 'item."vendorId"',
9304
+ [exports.InventoryCountOrderItemSortField.CUSTOMER_ID]: 'item."customerId"',
9305
+ [exports.InventoryCountOrderItemSortField.SALE_ID]: 'item."saleId"',
9306
+ [exports.InventoryCountOrderItemSortField.SALE_SERIAL_ID]: 'item."saleSerialId"',
9307
+ [exports.InventoryCountOrderItemSortField.IS_ADDITION]: 'item."isAddition"',
9308
+ [exports.InventoryCountOrderItemSortField.HELD]: 'COALESCE(item.held, false)',
9309
+ [exports.InventoryCountOrderItemSortField.IN_TRANSFER]: '(item."transferId" IS NOT NULL)',
9310
+ [exports.InventoryCountOrderItemSortField.INSPECTION]: `(CASE
9311
+ WHEN item."requiresInspection" = true AND item."inspectionResult" IS NULL THEN 2
9312
+ WHEN item."inspectionResult" = false THEN 1
9313
+ ELSE 0
9314
+ END)`,
9315
+ };
8583
9316
  /**
8584
9317
  * Inventory counting: compare the ledger against what is physically there, then
8585
9318
  * adjust the ledger to match.
@@ -8817,9 +9550,7 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
8817
9550
  // `order."countDate"` and fail to parse; and a camelCase alias would be
8818
9551
  // emitted quoted by the query builder while the unquoted references here
8819
9552
  // fold to lowercase, so the two would never match.
8820
- .order.createQueryBuilder('count_order')
8821
- .orderBy('count_order."countDate"', 'DESC')
8822
- .addOrderBy('count_order."createdAt"', 'DESC');
9553
+ .order.createQueryBuilder('count_order');
8823
9554
  if (options.name) {
8824
9555
  query.andWhere('count_order.name ILIKE :name', {
8825
9556
  name: `%${options.name}%`,
@@ -8854,6 +9585,21 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
8854
9585
  AND scope."locationId" IN (:...locationIds)
8855
9586
  )`, { locationIds: options.locationIds });
8856
9587
  }
9588
+ applyListSort(query, {
9589
+ sort: options.sort,
9590
+ fields: INVENTORY_COUNT_ORDER_SORT_FIELDS,
9591
+ defaultOrder: [
9592
+ {
9593
+ field: exports.InventoryCountOrderSortField.COUNT_DATE,
9594
+ order: exports.SortOrder.DESC,
9595
+ },
9596
+ {
9597
+ field: exports.InventoryCountOrderSortField.CREATED_AT,
9598
+ order: exports.SortOrder.DESC,
9599
+ },
9600
+ ],
9601
+ tiebreaker: 'count_order.id',
9602
+ });
8857
9603
  if (options.offset !== undefined && options.offset >= 0) {
8858
9604
  query.skip(options.offset);
8859
9605
  }
@@ -8915,13 +9661,28 @@ exports.InventoryCountOrderService = class InventoryCountOrderService {
8915
9661
  // into a COUNT, and an ORDER BY on a joined column it does not select makes
8916
9662
  // that rewrite fail.
8917
9663
  const total = await query.getCount();
8918
- // Additions first — they are what the operator just typed — then a stable
8919
- // order so paging cannot repeat or skip a line.
8920
- query
8921
- .orderBy('item."isAddition"', 'DESC')
8922
- .addOrderBy('material.key', 'ASC')
8923
- .addOrderBy('batch.key', 'ASC')
8924
- .addOrderBy('item.id', 'ASC');
9664
+ // Default: additions first — they are what the operator just typed — then
9665
+ // material and batch; `id` last so paging cannot repeat or skip a line.
9666
+ applyListSort(query, {
9667
+ sort: options.sort,
9668
+ fields: INVENTORY_COUNT_ORDER_ITEM_SORT_FIELDS,
9669
+ defaultOrder: [
9670
+ {
9671
+ field: exports.InventoryCountOrderItemSortField.IS_ADDITION,
9672
+ order: exports.SortOrder.DESC,
9673
+ },
9674
+ {
9675
+ field: exports.InventoryCountOrderItemSortField.MATERIAL_KEY,
9676
+ order: exports.SortOrder.ASC,
9677
+ },
9678
+ {
9679
+ field: exports.InventoryCountOrderItemSortField.BATCH_KEY,
9680
+ order: exports.SortOrder.ASC,
9681
+ },
9682
+ ],
9683
+ tiebreaker: 'item.id',
9684
+ mode: 'raw',
9685
+ });
8925
9686
  // `limit`/`offset` rather than `take`/`skip`: the latter wraps the query in a
8926
9687
  // DISTINCT subquery to survive one-to-many joins, and then cannot map an
8927
9688
  // ORDER BY on a joined column into it. Every join here is many-to-one, so no
@@ -9319,6 +10080,8 @@ exports.ScrapeService = tslib.__decorate([
9319
10080
  exports.StockService, Object, Object])
9320
10081
  ], exports.ScrapeService);
9321
10082
 
10083
+ /** Ancestor walk limit; a deeper chain than this is treated as corrupt data. */
10084
+ const LOCATION_MAP_PREVIEW_MAX_DEPTH = 32;
9322
10085
  exports.WarehouseMapDataService = class WarehouseMapDataService {
9323
10086
  dataSource;
9324
10087
  entities;
@@ -9329,6 +10092,64 @@ exports.WarehouseMapDataService = class WarehouseMapDataService {
9329
10092
  this.entities = entities;
9330
10093
  this.warehouseMapDataRepository = this.dataSource.getRepository(this.entities.warehouseMap);
9331
10094
  }
10095
+ /**
10096
+ * The map that draws `locationKey`, plus the breadcrumb from the root to it.
10097
+ *
10098
+ * The map hierarchy is kept apart from `locations.parentId`: a map's id is the
10099
+ * key of the location it drills into, and `mapData.ranges[].id` names the
10100
+ * child locations drawn on it. So "where is X drawn" is "which map has a range
10101
+ * whose id is X", and a map's parent is the map that draws the map's own id.
10102
+ *
10103
+ * Returns `null` when no map draws the location.
10104
+ *
10105
+ * When a key is drawn on several maps (the editor does not forbid it), the map
10106
+ * with the lowest id wins — byte order (`COLLATE "C"`), so every deployment
10107
+ * agrees regardless of its database locale, rather than whatever the planner
10108
+ * returns first. The same rule picks a parent at every step of the walk.
10109
+ *
10110
+ * The walk stops at a map nobody draws, at an id it has already visited
10111
+ * (a cycle in hand-edited map data), or after
10112
+ * `LOCATION_MAP_PREVIEW_MAX_DEPTH` maps.
10113
+ */
10114
+ async findLocationMapPreview(locationKey, manager) {
10115
+ const repository = (manager ?? this.dataSource.manager).getRepository(this.entities.warehouseMap);
10116
+ const holder = await this.findMapDrawing(repository, locationKey);
10117
+ if (!holder)
10118
+ return null;
10119
+ // `ancestors` doubles as the visited set: the walk only ever prepends.
10120
+ const walk = async (ancestors, currentId) => {
10121
+ if (ancestors.length >= LOCATION_MAP_PREVIEW_MAX_DEPTH)
10122
+ return ancestors;
10123
+ const parent = await this.findMapDrawing(repository, currentId);
10124
+ if (!parent || ancestors.includes(parent.id))
10125
+ return ancestors;
10126
+ return walk([parent.id, ...ancestors], parent.id);
10127
+ };
10128
+ const path = await walk([holder.id], holder.id);
10129
+ return {
10130
+ locationKey,
10131
+ mapKey: holder.id,
10132
+ path,
10133
+ mapData: holder.mapData,
10134
+ };
10135
+ }
10136
+ /** The lowest-id map whose ranges include one with `id = rangeId`. */
10137
+ async findMapDrawing(repository, rangeId) {
10138
+ const alias = 'map';
10139
+ const { metadata } = repository;
10140
+ const escape = (name) => repository.manager.connection.driver.escape(name);
10141
+ const mapDataColumn = metadata.findColumnWithPropertyName('mapData')?.databaseName;
10142
+ const idColumn = metadata.findColumnWithPropertyName('id')?.databaseName;
10143
+ if (!mapDataColumn || !idColumn) {
10144
+ throw new Error(`${metadata.name} has no mapData/id column; cannot resolve map previews`);
10145
+ }
10146
+ return repository
10147
+ .createQueryBuilder(alias)
10148
+ .where(`${escape(alias)}.${escape(mapDataColumn)} @> CAST(:needle AS jsonb)`, { needle: JSON.stringify({ ranges: [{ id: rangeId }] }) })
10149
+ .orderBy(`${escape(alias)}.${escape(idColumn)} COLLATE "C"`, 'ASC')
10150
+ .limit(1)
10151
+ .getOne();
10152
+ }
9332
10153
  /**
9333
10154
  * Seed the default map row.
9334
10155
  *
@@ -10382,6 +11203,8 @@ exports.InventoryCountOrderChangeEntity = InventoryCountOrderChangeEntity;
10382
11203
  exports.InventoryCountOrderEntity = InventoryCountOrderEntity;
10383
11204
  exports.InventoryCountOrderItemEntity = InventoryCountOrderItemEntity;
10384
11205
  exports.InventoryCountOrderLocationEntity = InventoryCountOrderLocationEntity;
11206
+ exports.LIST_SORT_NULLS = LIST_SORT_NULLS;
11207
+ exports.LOCATION_MAP_PREVIEW_MAX_DEPTH = LOCATION_MAP_PREVIEW_MAX_DEPTH;
10385
11208
  exports.LoaderTypeEntity = LoaderTypeEntity;
10386
11209
  exports.LoaderUnitEntity = LoaderUnitEntity;
10387
11210
  exports.LoadersEntity = LoadersEntity;
@@ -10433,9 +11256,11 @@ exports.WMS_EVENT_OPTIONS = WMS_EVENT_OPTIONS;
10433
11256
  exports.WMS_OPERATION_NAMES = WMS_OPERATION_NAMES;
10434
11257
  exports.WMS_STOCK_ENRICH = WMS_STOCK_ENRICH;
10435
11258
  exports.WarehouseMapEntity = WarehouseMapEntity;
11259
+ exports.applyListSort = applyListSort;
10436
11260
  exports.applyWmsTablePrefix = applyWmsTablePrefix;
10437
11261
  exports.collectToScope = collectToScope;
10438
11262
  exports.getWmsTablePrefix = getWmsTablePrefix;
11263
+ exports.resolveListSort = resolveListSort;
10439
11264
  exports.runInDispatchScope = runInDispatchScope;
10440
11265
  exports.runInTransaction = runInTransaction;
10441
11266
  exports.withWmsTablePrefix = withWmsTablePrefix;