@sdflc/backend-helpers 1.0.134 → 1.0.136

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/README.md CHANGED
@@ -778,40 +778,50 @@ export { NoteGw };
778
778
 
779
779
  #### Gateway config flags
780
780
 
781
- | Flag | Type | Description |
782
- | ---------------------- | --------------------- | ------------------------------------------------------------------------------------------------ |
783
- | `table` | `string` | Database table name |
784
- | `idField` | `string` | Primary key for SELECT/loader — table-qualify for joined queries (default: `id`) |
785
- | `idFieldAs` | `string` | Alias for the id column when it differs from the lookup key |
786
- | `idFieldUpdateRemove` | `string` | Primary key for UPDATE/DELETE WHERE — must be unqualified |
787
- | `setFields` | `string \| string[]` | Conflict target field(s) for the `set()` upsert operation |
788
- | `mergeFields` | `string[]` | Explicit field list for the ON CONFLICT MERGE clause |
789
- | `hasStatus` | `boolean` | Status filtering and REMOVED guard |
790
- | `hasCreatedAt` | `boolean` | Auto-set `created_at` on insert |
791
- | `hasUpdatedAt` | `boolean` | Auto-set `updated_at` on update |
792
- | `hasRemovedAt` | `boolean` | Soft-delete via `removed_at` timestamp |
793
- | `hasRemovedAtStr` | `boolean` | Also writes a formatted string timestamp to `removed_at_str` |
794
- | `hasCreatedBy` | `boolean` | Auto-set `created_by` from `context.userId` on insert |
795
- | `hasUpdatedBy` | `boolean` | Auto-set `updated_by` from `context.userId` on update |
796
- | `hasRemovedBy` | `boolean` | Auto-set `removed_by` from `context.userId` on soft-delete |
797
- | `hasSpace` | `boolean` | Scopes reads/writes to `context.spaceId` |
798
- | `hasUserId` | `boolean` | Sets `userId` from context on create |
799
- | `hasVersion` | `boolean` | Optimistic locking via version field |
800
- | `hasLang` | `boolean` | Language-scoped records |
801
- | `localizationForField` | `string` | Field combined with `lang` to build a composite localisation id |
802
- | `hardRemove` | `boolean` | Hard DELETE instead of soft-delete |
803
- | `noCache` | `boolean` | Bypass DataLoader cache |
804
- | `returnFields` | `string[]` | Columns in RETURNING clause (default: `['*']`) |
805
- | `defaultSorting` | `SortItemInterface[]` | Default ORDER BY when none provided |
806
- | `filterByUserField` | `string` | Auto-scope list queries to `context.userId` |
807
- | `fieldForKeyword` | `string` | Column to apply keyword ILIKE/LIKE search against |
808
- | `selectFields` | `string[]` | Columns selected when `useCache: false` (default: `['*']`) |
809
- | `activeStatuses` | `number[]` | Status values considered active for list filtering |
810
- | `insertChunkSize` | `number` | Records per INSERT batch — prevents DB parameter limit errors (default: `2500`) |
811
- | `listFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `list()` — see [Declarative filter rules](#declarative-filter-rules) |
812
- | `updateFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `update()` |
813
- | `removeFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `remove()` |
814
- | `countFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `count()` — falls back to `listFilters` when not set |
781
+ | Flag | Type | Description |
782
+ | ---------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
783
+ | `table` | `string` | Database table name |
784
+ | `idField` | `string` | Primary key for SELECT/loader — table-qualify for joined queries (default: `id`) |
785
+ | `idFieldAs` | `string` | Alias for the id column when it differs from the lookup key |
786
+ | `idFieldUpdateRemove` | `string` | Primary key for UPDATE/DELETE WHERE — must be unqualified |
787
+ | `statusField` | `string` | Column name for the status field (default: `'status'`). Set to `'Status_ID'` etc. on legacy tables — affects all status WHERE clauses and the soft-delete patch |
788
+ | `setFields` | `string \| string[]` | Conflict target field(s) for the `set()` upsert operation |
789
+ | `mergeFields` | `string[]` | Explicit field list for the ON CONFLICT MERGE clause |
790
+ | `hasStatus` | `boolean` | Status filtering and REMOVED guard |
791
+ | `hasCreatedAt` | `boolean` | Auto-set `created_at` on insert |
792
+ | `hasUpdatedAt` | `boolean` | Auto-set `updated_at` on update |
793
+ | `hasRemovedAt` | `boolean` | Soft-delete via `removed_at` timestamp |
794
+ | `hasRemovedAtStr` | `boolean` | Also writes a formatted string timestamp to `removed_at_str` |
795
+ | `hasCreatedBy` | `boolean` | Auto-set `created_by` from `context.userId` on insert |
796
+ | `hasUpdatedBy` | `boolean` | Auto-set `updated_by` from `context.userId` on update |
797
+ | `hasRemovedBy` | `boolean` | Auto-set `removed_by` from `context.userId` on soft-delete |
798
+ | `hasSpace` | `boolean` | Scopes reads/writes to `context.spaceId` |
799
+ | `hasUserId` | `boolean` | Sets `userId` from context on create |
800
+ | `hasVersion` | `boolean` | Optimistic locking via version field |
801
+ | `hasLang` | `boolean` | Language-scoped records |
802
+ | `localizationForField` | `string` | Field combined with `lang` to build a composite localisation id |
803
+ | `hardRemove` | `boolean` | Hard DELETE instead of soft-delete |
804
+ | `noCache` | `boolean` | Bypass DataLoader cache |
805
+ | `returnFields` | `string[]` | Columns in RETURNING clause (default: `['*']`) |
806
+ | `defaultSorting` | `SortItemInterface[]` | Default ORDER BY when none provided |
807
+ | `filterByUserField` | `string` | Auto-scope list queries to `context.userId` |
808
+ | `fieldForKeyword` | `string` | Column to apply keyword ILIKE/LIKE search against |
809
+ | `selectFields` | `string[]` | Columns selected when `useCache: false` (default: `['*']`) |
810
+ | `activeStatuses` | `number[]` | Status values considered active for list filtering |
811
+ | `insertChunkSize` | `number` | Records per INSERT batch — prevents DB parameter limit errors (default: `2500`) |
812
+ | `listFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `list()` — see [Declarative filter rules](#declarative-filter-rules) |
813
+ | `updateFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `update()` |
814
+ | `removeFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `remove()` |
815
+ | `countFilters` | `GatewayFilterRule[]` | Declarative WHERE rules for `count()` — falls back to `listFilters` when not set |
816
+ | `nonCreatableFields` | `string[]` | Field names callers cannot set on create — stripped before INSERT. snake_case or camelCase both accepted |
817
+ | `nonUpdatableFields` | `string[]` | Field names callers cannot change on update — stripped before UPDATE. snake_case or camelCase both accepted |
818
+
819
+ > **Implicit write protection.** In addition to `nonCreatableFields` / `nonUpdatableFields`, the framework always strips a baseline set of fields the framework owns:
820
+ >
821
+ > - **On create** — `id`, `removedAt`, `removedBy` (the framework generates `id` via `generateId()`; removal markers only belong on the remove path)
822
+ > - **On update** — `id`, `createdAt`, `createdBy`, `removedAt`, `removedBy` (write-once and remove-only markers)
823
+ >
824
+ > This implicit stripping happens regardless of whether `nonCreatableFields` / `nonUpdatableFields` are set. Use those arrays only for additional resource-specific immutables (e.g. `partyId` on a junction table whose identity is fixed at creation time). |
815
825
 
816
826
  #### Filter hooks
817
827
 
@@ -825,6 +835,52 @@ export { NoteGw };
825
835
 
826
836
  Always call `super.onListFilter()` / `super.onUpdateFilter()` / `super.onRemoveFilter()` at the top of any override so base-class scoping (soft-delete, space, user) runs first.
827
837
 
838
+ **Soft-delete guards on writes.** When `hasRemovedAt: true`, the base implementations of `onUpdateFilter` and `onRemoveFilter` automatically add `WHERE table.removed_at IS NULL`. This guard is independent of `hasStatus` — it fires on tables that use `Removed_At` without the framework's standard `status` column (a common shape for PartyLabz tables, where `hasStatus` is `false` and the row's lifecycle is tracked through `Status_ID` + `Removed_At` instead).
839
+
840
+ The guard prevents two failure modes silently breaking writes:
841
+
842
+ - An `update()` on an already-removed row would otherwise produce a half-mutated record (new `updated_at` and `updated_by`, original `removed_at` still set).
843
+ - A `remove()` on an already-removed row would otherwise re-write `removed_at` and `removed_by` with a fresh timestamp, masking the fact that the row was removed earlier.
844
+ **Configurable status column.** When `statusField` is set in the config (e.g. `statusField: 'Status_ID'`), every status-related WHERE clause in `onListFilter`, `onUpdateFilter`, `onRemoveFilter`, and the soft-delete patch in `transformOnRemove` uses that column name. Set this once on legacy tables that do not use the framework's default `status` column.
845
+
846
+ #### Field-level write protection
847
+
848
+ `BaseGateway` strips fields that callers should not be able to set from `params` before the INSERT or UPDATE statement runs. Two layers cooperate:
849
+
850
+ **Implicit framework-managed fields** are always stripped, regardless of configuration. These are columns the framework owns and either generates itself or sets only on a specific path.
851
+
852
+ | Path | Always stripped |
853
+ | -------- | -------------------------------------------------------- |
854
+ | `create` | `id`, `removedAt`, `removedBy` |
855
+ | `update` | `id`, `createdAt`, `createdBy`, `removedAt`, `removedBy` |
856
+
857
+ `removedAt` and `removedBy` are only included when their `has*` flags are set on the gateway. `id` is always stripped — `BaseGateway.generateId()` produces it.
858
+
859
+ **Gateway-configured immutables** are declared per-gateway via `nonCreatableFields` and `nonUpdatableFields`. Names can be supplied in `snake_case` (DB column form) or `camelCase` (VM/API form) — both spellings are stripped from the params object so callers can be consistent with whichever convention they prefer.
860
+
861
+ ```typescript
862
+ class PartyGuestGw extends BaseGateway {
863
+ constructor(props: BaseGatewayPropsInterface) {
864
+ super({
865
+ ...props,
866
+ table: 'Party_Guest',
867
+ hasStatus: false, // PartyLabz uses Status_ID
868
+ statusField: 'Status_ID',
869
+
870
+ // partyId / personId define the row's identity. Once a guest record
871
+ // exists in a party, those values must never change — only the RSVP
872
+ // state, notes, and audit fields evolve. Stripping them on update
873
+ // ensures a malformed client payload cannot reassign a guest.
874
+ nonUpdatableFields: ['partyId', 'personId'],
875
+ });
876
+ }
877
+ }
878
+ ```
879
+
880
+ **Logging.** Every stripped field is logged at `debug` level with the table name and field name, so it is easy to confirm during troubleshooting that a "ignored" client value was, in fact, dropped by the framework rather than silently overwritten.
881
+
882
+ **Why this matters.** Without this protection, a request like `update(where, { id: 'evil', createdBy: 'attacker', myField: 'ok' })` would attempt to rewrite framework-owned columns. The framework strips `id` and `createdBy` automatically; the gateway author can extend the strip-list to cover any additional columns whose values must come from the server, not the client.
883
+
828
884
  ---
829
885
 
830
886
  #### Declarative filter rules
@@ -889,6 +945,13 @@ const total = await this.gateway.count({ partyId: args.partyId, rsvpStatus: [1,
889
945
 
890
946
  Gateways that already declare `listFilters` get `count()` for free with no additional configuration. Set `countFilters` explicitly only when count needs different scoping than list.
891
947
 
948
+ **Soft-delete guard order.** `count()` adds the soft-delete guard automatically based on the gateway's flags:
949
+
950
+ 1. When `hasRemovedBy: true` → `WHERE table.removed_by IS NULL`
951
+ 2. Otherwise, when `hasRemovedAt: true` → `WHERE table.removed_at IS NULL`
952
+ 3. Otherwise — no soft-delete guard
953
+ `Removed_By IS NULL` is preferred because, in this codebase, `Removed_By` and `Removed_At` are always set together on the remove path and `Removed_By` is the primary sentinel. The fallback to `Removed_At` covers tables that have a timestamp column but no author column (uncommon but valid).
954
+
892
955
  To add custom WHERE logic beyond what declarative rules express, override `onCountFilter()`:
893
956
 
894
957
  ```typescript
@@ -1324,37 +1387,67 @@ try {
1324
1387
  `DataCache` is the default per-request DataLoader-backed cache. You can provide a **custom loader** when you need non-standard fetching — for example enriching records with a JOIN.
1325
1388
 
1326
1389
  ```typescript
1327
- // src/gateways/NoteGw.ts — gateway with a custom loader
1328
- import { BaseGateway, BaseGatewayPropsInterface, DataCache } from '@sdflc/backend-helpers';
1390
+ // src/gateways/NoteGw.ts
1391
+ import { BaseGateway, BaseGatewayPropsInterface } from '@sdflc/backend-helpers';
1329
1392
 
1330
1393
  class NoteGw extends BaseGateway {
1331
1394
  constructor(props: BaseGatewayPropsInterface) {
1332
- super({ ...props, table: 'note', keyPrefix: 'note' });
1333
-
1334
- // Replace the default loader with one that enriches notes with author info
1335
- this.setLoader(
1336
- new DataCache({
1337
- ...props,
1338
- table: 'note',
1339
- idField: 'id',
1340
- keyPrefix: 'note-with-author',
1341
- loaderFn: this.batchLoadWithAuthor.bind(this),
1342
- }),
1343
- );
1395
+ super({
1396
+ ...props,
1397
+ table: 'note',
1398
+ keyPrefix: 'note',
1399
+ hasStatus: true,
1400
+ // statusField: 'Status_ID', // ← uncomment for legacy tables that don't use 'status'
1401
+ hasCreatedAt: true,
1402
+ hasUpdatedAt: true,
1403
+ hasRemovedAt: true, // soft-delete
1404
+ hasCreatedBy: true,
1405
+ hasUpdatedBy: true,
1406
+ hasUserId: true,
1407
+ selectFields: ['note.*'],
1408
+ idField: 'note.id',
1409
+ idFieldUpdateRemove: 'id',
1410
+ defaultSorting: [{ name: 'created_at', order: 'desc' }],
1411
+
1412
+ // Declarative write protection — these fields are stripped from
1413
+ // the params object before INSERT / UPDATE runs. id, audit, and
1414
+ // removal fields are stripped automatically by the framework, so
1415
+ // these arrays are for additional resource-specific immutables only.
1416
+ nonCreatableFields: ['accountId'], // server-derived, never client-supplied
1417
+ nonUpdatableFields: ['userId'], // ownership cannot change after creation
1418
+ });
1344
1419
  }
1345
1420
 
1346
- // Must return results in the same order as the input ids array
1347
- private async batchLoadWithAuthor(ids: string[]): Promise<any[]> {
1348
- const rows = await this.getDb()
1349
- .getBuilder('note')
1350
- .select('note.*', 'user.name as authorName')
1351
- .leftJoin('user', 'user.id', 'note.user_id')
1352
- .whereIn('note.id', ids);
1421
+ async onListFilter(query: any, filterParams: any): Promise<void> {
1422
+ await super.onListFilter(query, filterParams);
1423
+
1424
+ const { userId, title } = filterParams || {};
1425
+
1426
+ if (userId) {
1427
+ query.where('note.user_id', userId);
1428
+ }
1353
1429
 
1354
- const map = new Map(rows.map((row: any) => [row.id, row]));
1355
- return ids.map((id) => map.get(id) || null);
1430
+ if (title) {
1431
+ query.whereILike('note.title', `%${title}%`);
1432
+ }
1433
+ }
1434
+
1435
+ // BaseGateway.onUpdateFilter already adds the soft-delete guard
1436
+ // (WHERE removed_at IS NULL) when hasRemovedAt is true, so we don't
1437
+ // need to add it here. Just call super and add resource-specific scoping.
1438
+ async onUpdateFilter(query: any, whereParams: any): Promise<number> {
1439
+ let count = await super.onUpdateFilter(query, whereParams);
1440
+
1441
+ if (whereParams?.userId != null) {
1442
+ count++;
1443
+ query.where({ user_id: whereParams.userId });
1444
+ }
1445
+
1446
+ return count;
1356
1447
  }
1357
1448
  }
1449
+
1450
+ export { NoteGw };
1358
1451
  ```
1359
1452
 
1360
1453
  You can also swap loaders at runtime:
@@ -1938,7 +2031,7 @@ ORDER_BYS.DESC; // 'desc'
1938
2031
  | `ApiContextInterface` | Arguments for `createApiContext()` |
1939
2032
  | `BaseCorePropsInterface` | Constructor props for `BaseCore` subclasses |
1940
2033
  | `BaseCoreRateLimitOnActionInterface` | Per-action rate-limit rule map used in `BaseCorePropsInterface` |
1941
- | `BaseGatewayPropsInterface` | Constructor props for `BaseGateway` subclasses |
2034
+ | `BaseGatewayPropsInterface` | Constructor props for `BaseGateway` subclasses — includes `statusField`, `nonCreatableFields`, `nonUpdatableFields`, and the filter rule arrays |
1942
2035
  | `BaseExternalApiGatewayPropsInterface` | Constructor props for `BaseExternalApiGateway` |
1943
2036
  | `BaseRestApiCrudControllerPropsInterface` | Constructor props for `BaseRestApiCrudController` |
1944
2037
  | `BuildDefaultResolvers` | Arguments for `buildDefaultResolvers()` |
@@ -659,6 +659,40 @@ declare class BaseCore {
659
659
  * @param args.gateway Gateway instance to query for the current max orderNo
660
660
  */
661
661
  setOrderNo(args: any): Promise<void>;
662
+ /**
663
+ * Lifts an optimistic-concurrency `version` value from update params into
664
+ * the where filter.
665
+ *
666
+ * GraphQL clients typically send `version` inside the params payload (the
667
+ * UI reads it on get/list, then sends it back on update so concurrent
668
+ * edits are detected). The gateway, however, expects `version` in the
669
+ * where clause so it can be added to the UPDATE's WHERE. This helper
670
+ * bridges the two conventions:
671
+ *
672
+ * - When `params.version` is present and `where.version` is absent,
673
+ * copy params.version → where.version.
674
+ * - The original params.version is intentionally LEFT IN PLACE.
675
+ * transformOnUpdate() in the gateway only increments version when it
676
+ * is already present in params; stripping it would skip the bump and
677
+ * leave the version column stale.
678
+ * - When `where.version` is already populated, params.version is
679
+ * ignored with a debug log. The where value wins so older code paths
680
+ * that populate version explicitly are preserved unchanged.
681
+ * - When neither is set, the helper is a no-op.
682
+ *
683
+ * The pair operates as expected end-to-end:
684
+ *
685
+ * client { where: {id}, params: {..., version: 7} }
686
+ * → after lift: where = {id, version: 7}, params = {..., version: 7}
687
+ * → transformOnUpdate increments params.version to 8
688
+ * → onUpdateFilter adds WHERE version = 7
689
+ * → UPDATE ... SET version = 8 WHERE id = ... AND version = 7
690
+ *
691
+ * @param args The action args object — typically { where, params, ... }
692
+ * Mutated in place: where is initialised to {} if absent so
693
+ * the lift target always exists.
694
+ */
695
+ private liftVersionFromParamsToWhere;
662
696
  /**
663
697
  * Stores a typed value in the action-scoped request store.
664
698
  *
package/build/BaseCore.js CHANGED
@@ -929,6 +929,10 @@ class BaseCore {
929
929
  validate: this.getValidators().update,
930
930
  accessRights: [utils_1.ACCESS_RIGHTS.UPDATE],
931
931
  action: async (args, opt) => {
932
+ // Lift version from params into where for optimistic-concurrency.
933
+ // Mutates args in place — done BEFORE destructuring so the
934
+ // local where binding picks up the lifted value.
935
+ this.liftVersionFromParamsToWhere(args);
932
936
  const { where, params } = args || {};
933
937
  const object = await this.beforeUpdate(params, opt);
934
938
  if ((0, api_helpers_1.isOpResult)(object)) {
@@ -958,6 +962,15 @@ class BaseCore {
958
962
  accessRights: [utils_1.ACCESS_RIGHTS.UPDATE],
959
963
  action: async (args, opt) => {
960
964
  const { params } = args || {};
965
+ // Lift version from params into where for optimistic-concurrency,
966
+ // per pair. Mutates each pair in place. Tolerates a non-array
967
+ // params input — beforeUpdateMany handles the normalisation
968
+ // and a non-array shape will simply be skipped here.
969
+ if (Array.isArray(params)) {
970
+ for (const pair of params) {
971
+ this.liftVersionFromParamsToWhere(pair);
972
+ }
973
+ }
961
974
  const object = await this.beforeUpdateMany(params, opt);
962
975
  if ((0, api_helpers_1.isOpResult)(object)) {
963
976
  return object.toJS();
@@ -1499,6 +1512,63 @@ class BaseCore {
1499
1512
  }
1500
1513
  }
1501
1514
  }
1515
+ // ─── Update-version helpers ────────────────────────────────────────────────
1516
+ /**
1517
+ * Lifts an optimistic-concurrency `version` value from update params into
1518
+ * the where filter.
1519
+ *
1520
+ * GraphQL clients typically send `version` inside the params payload (the
1521
+ * UI reads it on get/list, then sends it back on update so concurrent
1522
+ * edits are detected). The gateway, however, expects `version` in the
1523
+ * where clause so it can be added to the UPDATE's WHERE. This helper
1524
+ * bridges the two conventions:
1525
+ *
1526
+ * - When `params.version` is present and `where.version` is absent,
1527
+ * copy params.version → where.version.
1528
+ * - The original params.version is intentionally LEFT IN PLACE.
1529
+ * transformOnUpdate() in the gateway only increments version when it
1530
+ * is already present in params; stripping it would skip the bump and
1531
+ * leave the version column stale.
1532
+ * - When `where.version` is already populated, params.version is
1533
+ * ignored with a debug log. The where value wins so older code paths
1534
+ * that populate version explicitly are preserved unchanged.
1535
+ * - When neither is set, the helper is a no-op.
1536
+ *
1537
+ * The pair operates as expected end-to-end:
1538
+ *
1539
+ * client { where: {id}, params: {..., version: 7} }
1540
+ * → after lift: where = {id, version: 7}, params = {..., version: 7}
1541
+ * → transformOnUpdate increments params.version to 8
1542
+ * → onUpdateFilter adds WHERE version = 7
1543
+ * → UPDATE ... SET version = 8 WHERE id = ... AND version = 7
1544
+ *
1545
+ * @param args The action args object — typically { where, params, ... }
1546
+ * Mutated in place: where is initialised to {} if absent so
1547
+ * the lift target always exists.
1548
+ */
1549
+ liftVersionFromParamsToWhere(args) {
1550
+ if (!args || typeof args !== 'object')
1551
+ return;
1552
+ const params = args.params;
1553
+ if (!params || typeof params !== 'object')
1554
+ return;
1555
+ const versionInParams = params.version;
1556
+ if (versionInParams == null)
1557
+ return;
1558
+ // Initialise where if absent — gives the lift somewhere to land.
1559
+ if (!args.where || typeof args.where !== 'object') {
1560
+ args.where = {};
1561
+ }
1562
+ if (args.where.version != null) {
1563
+ // Where wins. params.version is left in place — transformOnUpdate
1564
+ // will still see it and bump it, which is the desired outcome.
1565
+ this.logger.debug(`Update — both where.version (${args.where.version}) and params.version (${versionInParams}) ` +
1566
+ `were supplied; where.version wins (params.version left in payload for the increment).`);
1567
+ return;
1568
+ }
1569
+ args.where.version = versionInParams;
1570
+ this.logger.debug(`Update — lifted version=${versionInParams} from params into where for optimistic-concurrency check.`);
1571
+ }
1502
1572
  // ─── Action-scoped request store helpers ──────────────────────────────────
1503
1573
  // These helpers provide typed access to the per-action requestStore carried
1504
1574
  // in BaseCoreActionsInterface.opt. Use them in any before*, after*, validate,
@@ -311,6 +311,31 @@ declare class BaseGateway {
311
311
  * path — they are skipped with a warning log.
312
312
  */
313
313
  private applyDeclarativeRemoveFilters;
314
+ /**
315
+ * Returns the full set of field names (camelCase + snake_case) that
316
+ * should be stripped from a params object on the given write path.
317
+ *
318
+ * Combines two sources:
319
+ * 1. The framework's implicit immutables, derived from has* flags:
320
+ * - 'create' → id, removedAt, removedBy
321
+ * - 'update' → id, createdAt, createdBy, removedAt, removedBy
322
+ * 2. The gateway's own nonCreatableFields / nonUpdatableFields config.
323
+ *
324
+ * For each source name, both snake_case (matches DB / FIELDS constants)
325
+ * and camelCase (matches VM / API params) are added so callers do not
326
+ * have to be consistent with one convention.
327
+ *
328
+ * Returns a Set for O(1) lookup inside the strip loop.
329
+ */
330
+ private buildNonWritableFieldSet;
331
+ /**
332
+ * Strips every key whose name appears in `nonWritable` from `params`.
333
+ * Logs each strip at debug level so audit / troubleshooting can see
334
+ * exactly which client-supplied keys were ignored.
335
+ *
336
+ * Mutates and returns `params` for chaining.
337
+ */
338
+ private stripNonWritableFields;
314
339
  /**
315
340
  * Generates a unique ID for a new record.
316
341
  *
@@ -621,14 +646,26 @@ declare class BaseGateway {
621
646
  * no second pass over the results here.
622
647
  */
623
648
  updateMany(params: any): Promise<any[]>;
649
+ /**
650
+ * Builds the audit fields (updatedAt / updatedBy) to SET on an increment /
651
+ * decrement. These must be applied as normal assignments — NOT fed through the
652
+ * counter, which would try to do `updated_at = updated_at + <ts>` /
653
+ * `updated_by = updated_by + <uuid>`. Returns only the fields the gateway is
654
+ * configured to manage; an empty object when the table has no audit columns
655
+ * (so counter-only tables behave exactly as a bare increment).
656
+ */
657
+ buildAuditFieldsForCounter(): Record<string, any>;
624
658
  /**
625
659
  * Increments numeric field(s) on records matching the `where` filter.
626
660
  * Uses the database's native INCREMENT operation rather than a read-modify-write,
627
661
  * making it safe for concurrent requests.
628
662
  *
629
663
  * `params` should be an object mapping field names to the increment amounts
630
- * (e.g. `{ viewCount: 1 }`). `transformOnUpdate()` is still called, so
631
- * audit fields (updatedAt, updatedBy) and version are updated as normal.
664
+ * (e.g. `{ viewCount: 1 }`). ONLY those caller fields are incremented; audit
665
+ * fields (updatedAt / updatedBy) are applied as normal SET assignments so
666
+ * timestamp / uuid columns are never fed through the counter (which would fail
667
+ * with `operator does not exist`). Knex compiles the chained increment + update
668
+ * into a single UPDATE ... SET.
632
669
  *
633
670
  * Throws if no filter conditions are applied (same safety guard as `update()`).
634
671
  * Clears affected records from the loader cache after the operation.
@@ -638,7 +675,9 @@ declare class BaseGateway {
638
675
  * Decrements numeric field(s) on records matching the `where` filter.
639
676
  * Mirror of `increment()` using the database's native DECREMENT operation.
640
677
  *
641
- * Same behaviour, safety guards, and cache invalidation as `increment()`.
678
+ * Same behaviour, safety guards, and cache invalidation as `increment()` —
679
+ * caller fields only are decremented; audit fields are SET, not fed through the
680
+ * counter.
642
681
  */
643
682
  decrement(where: any, params: any): Promise<any[]>;
644
683
  /**
@@ -575,6 +575,87 @@ class BaseGateway {
575
575
  }
576
576
  return count;
577
577
  }
578
+ // ─── Write-protection helpers ──────────────────────────────────────────────
579
+ /**
580
+ * Returns the full set of field names (camelCase + snake_case) that
581
+ * should be stripped from a params object on the given write path.
582
+ *
583
+ * Combines two sources:
584
+ * 1. The framework's implicit immutables, derived from has* flags:
585
+ * - 'create' → id, removedAt, removedBy
586
+ * - 'update' → id, createdAt, createdBy, removedAt, removedBy
587
+ * 2. The gateway's own nonCreatableFields / nonUpdatableFields config.
588
+ *
589
+ * For each source name, both snake_case (matches DB / FIELDS constants)
590
+ * and camelCase (matches VM / API params) are added so callers do not
591
+ * have to be consistent with one convention.
592
+ *
593
+ * Returns a Set for O(1) lookup inside the strip loop.
594
+ */
595
+ buildNonWritableFieldSet(path) {
596
+ const { hasCreatedAt, hasCreatedBy, hasRemovedAt, hasRemovedBy, nonCreatableFields, nonUpdatableFields } = this.config;
597
+ const fields = [];
598
+ // ── Framework-implicit immutables (always stripped) ──────────────────────
599
+ // id is always framework-managed via generateId(), so it must never be
600
+ // honoured from caller input on create OR update.
601
+ fields.push(this.getIdField().split('.').pop());
602
+ if (path === 'create') {
603
+ // Soft-delete markers are only set on the remove path. A caller
604
+ // sending them on create would record a "born already removed" row.
605
+ if (hasRemovedAt)
606
+ fields.push(constants_1.FIELDS.REMOVED_AT);
607
+ if (hasRemovedBy)
608
+ fields.push(constants_1.FIELDS.REMOVED_BY);
609
+ }
610
+ else {
611
+ // On update, creation-time markers are write-once and removal-time
612
+ // markers are managed by the remove path.
613
+ if (hasCreatedAt)
614
+ fields.push(constants_1.FIELDS.CREATED_AT);
615
+ if (hasCreatedBy)
616
+ fields.push(constants_1.FIELDS.CREATED_BY);
617
+ if (hasRemovedAt)
618
+ fields.push(constants_1.FIELDS.REMOVED_AT);
619
+ if (hasRemovedBy)
620
+ fields.push(constants_1.FIELDS.REMOVED_BY);
621
+ }
622
+ // ── Gateway-configured immutables ────────────────────────────────────────
623
+ const configured = path === 'create' ? nonCreatableFields : nonUpdatableFields;
624
+ if (Array.isArray(configured)) {
625
+ fields.push(...configured);
626
+ }
627
+ // ── Expand each entry to both snake_case and camelCase ───────────────────
628
+ // This way the gateway author can write columns the way they think of
629
+ // them (snake_case for DB-minded folks, camelCase for VM-minded folks)
630
+ // and both forms are stripped from incoming params.
631
+ const out = new Set();
632
+ for (const name of fields) {
633
+ if (typeof name !== 'string' || name.length === 0)
634
+ continue;
635
+ out.add(name);
636
+ out.add((0, lodash_1.camelCase)(name));
637
+ out.add((0, lodash_1.snakeCase)(name));
638
+ }
639
+ return out;
640
+ }
641
+ /**
642
+ * Strips every key whose name appears in `nonWritable` from `params`.
643
+ * Logs each strip at debug level so audit / troubleshooting can see
644
+ * exactly which client-supplied keys were ignored.
645
+ *
646
+ * Mutates and returns `params` for chaining.
647
+ */
648
+ stripNonWritableFields(params, nonWritable, path) {
649
+ if (!params || typeof params !== 'object')
650
+ return params;
651
+ for (const key of Object.keys(params)) {
652
+ if (nonWritable.has(key)) {
653
+ this.logger.debug(`${this.config.table}: field "${key}" is not writable on ${path} and was stripped from the payload`);
654
+ delete params[key];
655
+ }
656
+ }
657
+ return params;
658
+ }
578
659
  // ─── ID generation ─────────────────────────────────────────────────────────
579
660
  /**
580
661
  * Generates a unique ID for a new record.
@@ -663,7 +744,7 @@ class BaseGateway {
663
744
  * - `updateFilters` — applies declarative GatewayFilterRule array (new)
664
745
  */
665
746
  async onUpdateFilter(query, filterParams) {
666
- const { hasStatus, hasVersion } = this.config;
747
+ const { table, hasStatus, hasVersion, hasRemovedAt } = this.config;
667
748
  const idName = this.getIdFieldUpdateRemove();
668
749
  let filtersAppliedQty = 0;
669
750
  if (filterParams[idName]) {
@@ -686,6 +767,16 @@ class BaseGateway {
686
767
  query.where(statusField, '!=', utils_1.STATUSES.REMOVED);
687
768
  }
688
769
  }
770
+ // Skip already-removed rows on soft-delete tables. Without this guard,
771
+ // a regular update call on a soft-deleted row would silently bring it
772
+ // back into a half-mutated state (new updatedAt / updatedBy, old
773
+ // Removed_At still set). For tables where hasStatus is true, the
774
+ // status-based REMOVED guard above already covers this; for PartyLabz
775
+ // tables (Status_Id, hasStatus: false) this is the only line of defence.
776
+ if (hasRemovedAt === true) {
777
+ filtersAppliedQty++;
778
+ query.whereNull(`${table}.${constants_1.FIELDS.REMOVED_AT}`);
779
+ }
689
780
  // Declarative update filter rules — applied after base logic.
690
781
  filtersAppliedQty += this.applyDeclarativeUpdateFilters(query, filterParams);
691
782
  return filtersAppliedQty;
@@ -709,7 +800,7 @@ class BaseGateway {
709
800
  * - `removeFilters` — applies declarative GatewayFilterRule array (new)
710
801
  */
711
802
  async onRemoveFilter(query, filterParams) {
712
- const { hasStatus } = this.config;
803
+ const { table, hasStatus, hasRemovedAt } = this.config;
713
804
  const arr = filterParams ? (0, lodash_1.castArray)(filterParams) : [];
714
805
  let filtersAppliedQty = 0;
715
806
  const idName = this.getIdFieldUpdateRemove();
@@ -727,6 +818,17 @@ class BaseGateway {
727
818
  filtersAppliedQty++;
728
819
  query.where(this.getStatusField(), '!=', utils_1.STATUSES.REMOVED);
729
820
  }
821
+ // Skip already-removed rows on soft-delete tables. Without this guard,
822
+ // a "remove" call on an already-removed row would re-write Removed_At
823
+ // and Removed_By with a new timestamp / user and return the row as if
824
+ // it was just removed — masking the fact that it was removed earlier.
825
+ // This guard is independent of hasStatus because PartyLabz tables use
826
+ // Status_Id (not "status"), so hasStatus is false on those tables and
827
+ // the status-based REMOVED guard above does not fire.
828
+ if (hasRemovedAt === true) {
829
+ filtersAppliedQty++;
830
+ query.whereNull(`${table}.${constants_1.FIELDS.REMOVED_AT}`);
831
+ }
730
832
  // Declarative remove filter rules — applied after base logic.
731
833
  filtersAppliedQty += this.applyDeclarativeRemoveFilters(query, filterParams);
732
834
  return filtersAppliedQty;
@@ -771,6 +873,11 @@ class BaseGateway {
771
873
  */
772
874
  async transformOnCreate(params) {
773
875
  const { hasCreatedAt, hasCreatedBy, hasSpace, hasVersion, hasLang, localizationForField, hasUserId } = this.config;
876
+ // Strip client-supplied values for fields the framework manages or
877
+ // the gateway explicitly forbids from being set on create. Runs FIRST
878
+ // so the auto-set logic for createdAt / createdBy / spaceId / version
879
+ // below operates on a clean payload.
880
+ this.stripNonWritableFields(params, this.buildNonWritableFieldSet('create'), 'create');
774
881
  if (hasCreatedAt) {
775
882
  params[(0, lodash_1.camelCase)(constants_1.FIELDS.CREATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
776
883
  }
@@ -822,6 +929,11 @@ class BaseGateway {
822
929
  */
823
930
  async transformOnUpdate(params, where) {
824
931
  const { hasUpdatedAt, hasUpdatedBy, hasVersion, hasLang, localizationForField } = this.config;
932
+ // Strip client-supplied values for fields the framework manages or
933
+ // the gateway explicitly forbids from being changed. Runs FIRST so
934
+ // the auto-set logic for updatedAt / updatedBy / version below
935
+ // operates on a clean payload.
936
+ this.stripNonWritableFields(params, this.buildNonWritableFieldSet('update'), 'update');
825
937
  if (hasUpdatedAt) {
826
938
  params[(0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
827
939
  }
@@ -1167,21 +1279,50 @@ class BaseGateway {
1167
1279
  }
1168
1280
  return results.map((item) => this.transformOnOut(item));
1169
1281
  }
1282
+ /**
1283
+ * Builds the audit fields (updatedAt / updatedBy) to SET on an increment /
1284
+ * decrement. These must be applied as normal assignments — NOT fed through the
1285
+ * counter, which would try to do `updated_at = updated_at + <ts>` /
1286
+ * `updated_by = updated_by + <uuid>`. Returns only the fields the gateway is
1287
+ * configured to manage; an empty object when the table has no audit columns
1288
+ * (so counter-only tables behave exactly as a bare increment).
1289
+ */
1290
+ buildAuditFieldsForCounter() {
1291
+ const { hasUpdatedAt, hasUpdatedBy } = this.config;
1292
+ const out = {};
1293
+ if (hasUpdatedAt) {
1294
+ out[(0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
1295
+ }
1296
+ if (hasUpdatedBy) {
1297
+ const userId = this.getContext()?.userId;
1298
+ if (userId != null) {
1299
+ out[(0, lodash_1.camelCase)(constants_1.FIELDS.UPDATED_BY)] = userId;
1300
+ }
1301
+ }
1302
+ return out;
1303
+ }
1170
1304
  /**
1171
1305
  * Increments numeric field(s) on records matching the `where` filter.
1172
1306
  * Uses the database's native INCREMENT operation rather than a read-modify-write,
1173
1307
  * making it safe for concurrent requests.
1174
1308
  *
1175
1309
  * `params` should be an object mapping field names to the increment amounts
1176
- * (e.g. `{ viewCount: 1 }`). `transformOnUpdate()` is still called, so
1177
- * audit fields (updatedAt, updatedBy) and version are updated as normal.
1310
+ * (e.g. `{ viewCount: 1 }`). ONLY those caller fields are incremented; audit
1311
+ * fields (updatedAt / updatedBy) are applied as normal SET assignments so
1312
+ * timestamp / uuid columns are never fed through the counter (which would fail
1313
+ * with `operator does not exist`). Knex compiles the chained increment + update
1314
+ * into a single UPDATE ... SET.
1178
1315
  *
1179
1316
  * Throws if no filter conditions are applied (same safety guard as `update()`).
1180
1317
  * Clears affected records from the loader cache after the operation.
1181
1318
  */
1182
1319
  async increment(where, params) {
1183
- const object = await this.transformOnUpdate(params, where);
1184
- const query = this.getBuilder().increment(object).returning(this.config.returnFields);
1320
+ let query = this.getBuilder().increment({ ...params });
1321
+ const audit = this.buildAuditFieldsForCounter();
1322
+ if (Object.keys(audit).length > 0) {
1323
+ query = query.update(audit);
1324
+ }
1325
+ query = query.returning(this.config.returnFields);
1185
1326
  const filtersAppliedQty = await this.onUpdateFilter(query, where);
1186
1327
  if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
1187
1328
  throw new Error(`Failed to increment in table '${this.config.table}': no filters applied. ` +
@@ -1202,11 +1343,17 @@ class BaseGateway {
1202
1343
  * Decrements numeric field(s) on records matching the `where` filter.
1203
1344
  * Mirror of `increment()` using the database's native DECREMENT operation.
1204
1345
  *
1205
- * Same behaviour, safety guards, and cache invalidation as `increment()`.
1346
+ * Same behaviour, safety guards, and cache invalidation as `increment()` —
1347
+ * caller fields only are decremented; audit fields are SET, not fed through the
1348
+ * counter.
1206
1349
  */
1207
1350
  async decrement(where, params) {
1208
- const object = await this.transformOnUpdate(params, where);
1209
- const query = this.getBuilder().decrement(object).returning(this.config.returnFields);
1351
+ let query = this.getBuilder().decrement({ ...params });
1352
+ const audit = this.buildAuditFieldsForCounter();
1353
+ if (Object.keys(audit).length > 0) {
1354
+ query = query.update(audit);
1355
+ }
1356
+ query = query.returning(this.config.returnFields);
1210
1357
  const filtersAppliedQty = await this.onUpdateFilter(query, where);
1211
1358
  if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
1212
1359
  throw new Error(`Failed to decrement in table '${this.config.table}': no filters applied. ` +
@@ -659,6 +659,40 @@ declare class BaseCore {
659
659
  * @param args.gateway Gateway instance to query for the current max orderNo
660
660
  */
661
661
  setOrderNo(args: any): Promise<void>;
662
+ /**
663
+ * Lifts an optimistic-concurrency `version` value from update params into
664
+ * the where filter.
665
+ *
666
+ * GraphQL clients typically send `version` inside the params payload (the
667
+ * UI reads it on get/list, then sends it back on update so concurrent
668
+ * edits are detected). The gateway, however, expects `version` in the
669
+ * where clause so it can be added to the UPDATE's WHERE. This helper
670
+ * bridges the two conventions:
671
+ *
672
+ * - When `params.version` is present and `where.version` is absent,
673
+ * copy params.version → where.version.
674
+ * - The original params.version is intentionally LEFT IN PLACE.
675
+ * transformOnUpdate() in the gateway only increments version when it
676
+ * is already present in params; stripping it would skip the bump and
677
+ * leave the version column stale.
678
+ * - When `where.version` is already populated, params.version is
679
+ * ignored with a debug log. The where value wins so older code paths
680
+ * that populate version explicitly are preserved unchanged.
681
+ * - When neither is set, the helper is a no-op.
682
+ *
683
+ * The pair operates as expected end-to-end:
684
+ *
685
+ * client { where: {id}, params: {..., version: 7} }
686
+ * → after lift: where = {id, version: 7}, params = {..., version: 7}
687
+ * → transformOnUpdate increments params.version to 8
688
+ * → onUpdateFilter adds WHERE version = 7
689
+ * → UPDATE ... SET version = 8 WHERE id = ... AND version = 7
690
+ *
691
+ * @param args The action args object — typically { where, params, ... }
692
+ * Mutated in place: where is initialised to {} if absent so
693
+ * the lift target always exists.
694
+ */
695
+ private liftVersionFromParamsToWhere;
662
696
  /**
663
697
  * Stores a typed value in the action-scoped request store.
664
698
  *
@@ -923,6 +923,10 @@ class BaseCore {
923
923
  validate: this.getValidators().update,
924
924
  accessRights: [ACCESS_RIGHTS.UPDATE],
925
925
  action: async (args, opt) => {
926
+ // Lift version from params into where for optimistic-concurrency.
927
+ // Mutates args in place — done BEFORE destructuring so the
928
+ // local where binding picks up the lifted value.
929
+ this.liftVersionFromParamsToWhere(args);
926
930
  const { where, params } = args || {};
927
931
  const object = await this.beforeUpdate(params, opt);
928
932
  if (isOpResult(object)) {
@@ -952,6 +956,15 @@ class BaseCore {
952
956
  accessRights: [ACCESS_RIGHTS.UPDATE],
953
957
  action: async (args, opt) => {
954
958
  const { params } = args || {};
959
+ // Lift version from params into where for optimistic-concurrency,
960
+ // per pair. Mutates each pair in place. Tolerates a non-array
961
+ // params input — beforeUpdateMany handles the normalisation
962
+ // and a non-array shape will simply be skipped here.
963
+ if (Array.isArray(params)) {
964
+ for (const pair of params) {
965
+ this.liftVersionFromParamsToWhere(pair);
966
+ }
967
+ }
955
968
  const object = await this.beforeUpdateMany(params, opt);
956
969
  if (isOpResult(object)) {
957
970
  return object.toJS();
@@ -1493,6 +1506,63 @@ class BaseCore {
1493
1506
  }
1494
1507
  }
1495
1508
  }
1509
+ // ─── Update-version helpers ────────────────────────────────────────────────
1510
+ /**
1511
+ * Lifts an optimistic-concurrency `version` value from update params into
1512
+ * the where filter.
1513
+ *
1514
+ * GraphQL clients typically send `version` inside the params payload (the
1515
+ * UI reads it on get/list, then sends it back on update so concurrent
1516
+ * edits are detected). The gateway, however, expects `version` in the
1517
+ * where clause so it can be added to the UPDATE's WHERE. This helper
1518
+ * bridges the two conventions:
1519
+ *
1520
+ * - When `params.version` is present and `where.version` is absent,
1521
+ * copy params.version → where.version.
1522
+ * - The original params.version is intentionally LEFT IN PLACE.
1523
+ * transformOnUpdate() in the gateway only increments version when it
1524
+ * is already present in params; stripping it would skip the bump and
1525
+ * leave the version column stale.
1526
+ * - When `where.version` is already populated, params.version is
1527
+ * ignored with a debug log. The where value wins so older code paths
1528
+ * that populate version explicitly are preserved unchanged.
1529
+ * - When neither is set, the helper is a no-op.
1530
+ *
1531
+ * The pair operates as expected end-to-end:
1532
+ *
1533
+ * client { where: {id}, params: {..., version: 7} }
1534
+ * → after lift: where = {id, version: 7}, params = {..., version: 7}
1535
+ * → transformOnUpdate increments params.version to 8
1536
+ * → onUpdateFilter adds WHERE version = 7
1537
+ * → UPDATE ... SET version = 8 WHERE id = ... AND version = 7
1538
+ *
1539
+ * @param args The action args object — typically { where, params, ... }
1540
+ * Mutated in place: where is initialised to {} if absent so
1541
+ * the lift target always exists.
1542
+ */
1543
+ liftVersionFromParamsToWhere(args) {
1544
+ if (!args || typeof args !== 'object')
1545
+ return;
1546
+ const params = args.params;
1547
+ if (!params || typeof params !== 'object')
1548
+ return;
1549
+ const versionInParams = params.version;
1550
+ if (versionInParams == null)
1551
+ return;
1552
+ // Initialise where if absent — gives the lift somewhere to land.
1553
+ if (!args.where || typeof args.where !== 'object') {
1554
+ args.where = {};
1555
+ }
1556
+ if (args.where.version != null) {
1557
+ // Where wins. params.version is left in place — transformOnUpdate
1558
+ // will still see it and bump it, which is the desired outcome.
1559
+ this.logger.debug(`Update — both where.version (${args.where.version}) and params.version (${versionInParams}) ` +
1560
+ `were supplied; where.version wins (params.version left in payload for the increment).`);
1561
+ return;
1562
+ }
1563
+ args.where.version = versionInParams;
1564
+ this.logger.debug(`Update — lifted version=${versionInParams} from params into where for optimistic-concurrency check.`);
1565
+ }
1496
1566
  // ─── Action-scoped request store helpers ──────────────────────────────────
1497
1567
  // These helpers provide typed access to the per-action requestStore carried
1498
1568
  // in BaseCoreActionsInterface.opt. Use them in any before*, after*, validate,
@@ -311,6 +311,31 @@ declare class BaseGateway {
311
311
  * path — they are skipped with a warning log.
312
312
  */
313
313
  private applyDeclarativeRemoveFilters;
314
+ /**
315
+ * Returns the full set of field names (camelCase + snake_case) that
316
+ * should be stripped from a params object on the given write path.
317
+ *
318
+ * Combines two sources:
319
+ * 1. The framework's implicit immutables, derived from has* flags:
320
+ * - 'create' → id, removedAt, removedBy
321
+ * - 'update' → id, createdAt, createdBy, removedAt, removedBy
322
+ * 2. The gateway's own nonCreatableFields / nonUpdatableFields config.
323
+ *
324
+ * For each source name, both snake_case (matches DB / FIELDS constants)
325
+ * and camelCase (matches VM / API params) are added so callers do not
326
+ * have to be consistent with one convention.
327
+ *
328
+ * Returns a Set for O(1) lookup inside the strip loop.
329
+ */
330
+ private buildNonWritableFieldSet;
331
+ /**
332
+ * Strips every key whose name appears in `nonWritable` from `params`.
333
+ * Logs each strip at debug level so audit / troubleshooting can see
334
+ * exactly which client-supplied keys were ignored.
335
+ *
336
+ * Mutates and returns `params` for chaining.
337
+ */
338
+ private stripNonWritableFields;
314
339
  /**
315
340
  * Generates a unique ID for a new record.
316
341
  *
@@ -621,14 +646,26 @@ declare class BaseGateway {
621
646
  * no second pass over the results here.
622
647
  */
623
648
  updateMany(params: any): Promise<any[]>;
649
+ /**
650
+ * Builds the audit fields (updatedAt / updatedBy) to SET on an increment /
651
+ * decrement. These must be applied as normal assignments — NOT fed through the
652
+ * counter, which would try to do `updated_at = updated_at + <ts>` /
653
+ * `updated_by = updated_by + <uuid>`. Returns only the fields the gateway is
654
+ * configured to manage; an empty object when the table has no audit columns
655
+ * (so counter-only tables behave exactly as a bare increment).
656
+ */
657
+ buildAuditFieldsForCounter(): Record<string, any>;
624
658
  /**
625
659
  * Increments numeric field(s) on records matching the `where` filter.
626
660
  * Uses the database's native INCREMENT operation rather than a read-modify-write,
627
661
  * making it safe for concurrent requests.
628
662
  *
629
663
  * `params` should be an object mapping field names to the increment amounts
630
- * (e.g. `{ viewCount: 1 }`). `transformOnUpdate()` is still called, so
631
- * audit fields (updatedAt, updatedBy) and version are updated as normal.
664
+ * (e.g. `{ viewCount: 1 }`). ONLY those caller fields are incremented; audit
665
+ * fields (updatedAt / updatedBy) are applied as normal SET assignments so
666
+ * timestamp / uuid columns are never fed through the counter (which would fail
667
+ * with `operator does not exist`). Knex compiles the chained increment + update
668
+ * into a single UPDATE ... SET.
632
669
  *
633
670
  * Throws if no filter conditions are applied (same safety guard as `update()`).
634
671
  * Clears affected records from the loader cache after the operation.
@@ -638,7 +675,9 @@ declare class BaseGateway {
638
675
  * Decrements numeric field(s) on records matching the `where` filter.
639
676
  * Mirror of `increment()` using the database's native DECREMENT operation.
640
677
  *
641
- * Same behaviour, safety guards, and cache invalidation as `increment()`.
678
+ * Same behaviour, safety guards, and cache invalidation as `increment()` —
679
+ * caller fields only are decremented; audit fields are SET, not fed through the
680
+ * counter.
642
681
  */
643
682
  decrement(where: any, params: any): Promise<any[]>;
644
683
  /**
@@ -1,7 +1,7 @@
1
1
  import { v4 } from 'uuid';
2
2
  import dayjs from 'dayjs';
3
3
  import check from 'check-types';
4
- import { camelCase, castArray, pullAll } from 'lodash';
4
+ import { camelCase, castArray, pullAll, snakeCase } from 'lodash';
5
5
  import { arrToChunks, STATUSES, DateTimeHelpers, buildKey, Logger, LoggerLevels, isLogger, camelResponse, } from '@sdflc/utils';
6
6
  import { DataCache } from './DataCache';
7
7
  import { FIELDS, ID_FIELD } from './constants';
@@ -569,6 +569,87 @@ class BaseGateway {
569
569
  }
570
570
  return count;
571
571
  }
572
+ // ─── Write-protection helpers ──────────────────────────────────────────────
573
+ /**
574
+ * Returns the full set of field names (camelCase + snake_case) that
575
+ * should be stripped from a params object on the given write path.
576
+ *
577
+ * Combines two sources:
578
+ * 1. The framework's implicit immutables, derived from has* flags:
579
+ * - 'create' → id, removedAt, removedBy
580
+ * - 'update' → id, createdAt, createdBy, removedAt, removedBy
581
+ * 2. The gateway's own nonCreatableFields / nonUpdatableFields config.
582
+ *
583
+ * For each source name, both snake_case (matches DB / FIELDS constants)
584
+ * and camelCase (matches VM / API params) are added so callers do not
585
+ * have to be consistent with one convention.
586
+ *
587
+ * Returns a Set for O(1) lookup inside the strip loop.
588
+ */
589
+ buildNonWritableFieldSet(path) {
590
+ const { hasCreatedAt, hasCreatedBy, hasRemovedAt, hasRemovedBy, nonCreatableFields, nonUpdatableFields } = this.config;
591
+ const fields = [];
592
+ // ── Framework-implicit immutables (always stripped) ──────────────────────
593
+ // id is always framework-managed via generateId(), so it must never be
594
+ // honoured from caller input on create OR update.
595
+ fields.push(this.getIdField().split('.').pop());
596
+ if (path === 'create') {
597
+ // Soft-delete markers are only set on the remove path. A caller
598
+ // sending them on create would record a "born already removed" row.
599
+ if (hasRemovedAt)
600
+ fields.push(FIELDS.REMOVED_AT);
601
+ if (hasRemovedBy)
602
+ fields.push(FIELDS.REMOVED_BY);
603
+ }
604
+ else {
605
+ // On update, creation-time markers are write-once and removal-time
606
+ // markers are managed by the remove path.
607
+ if (hasCreatedAt)
608
+ fields.push(FIELDS.CREATED_AT);
609
+ if (hasCreatedBy)
610
+ fields.push(FIELDS.CREATED_BY);
611
+ if (hasRemovedAt)
612
+ fields.push(FIELDS.REMOVED_AT);
613
+ if (hasRemovedBy)
614
+ fields.push(FIELDS.REMOVED_BY);
615
+ }
616
+ // ── Gateway-configured immutables ────────────────────────────────────────
617
+ const configured = path === 'create' ? nonCreatableFields : nonUpdatableFields;
618
+ if (Array.isArray(configured)) {
619
+ fields.push(...configured);
620
+ }
621
+ // ── Expand each entry to both snake_case and camelCase ───────────────────
622
+ // This way the gateway author can write columns the way they think of
623
+ // them (snake_case for DB-minded folks, camelCase for VM-minded folks)
624
+ // and both forms are stripped from incoming params.
625
+ const out = new Set();
626
+ for (const name of fields) {
627
+ if (typeof name !== 'string' || name.length === 0)
628
+ continue;
629
+ out.add(name);
630
+ out.add(camelCase(name));
631
+ out.add(snakeCase(name));
632
+ }
633
+ return out;
634
+ }
635
+ /**
636
+ * Strips every key whose name appears in `nonWritable` from `params`.
637
+ * Logs each strip at debug level so audit / troubleshooting can see
638
+ * exactly which client-supplied keys were ignored.
639
+ *
640
+ * Mutates and returns `params` for chaining.
641
+ */
642
+ stripNonWritableFields(params, nonWritable, path) {
643
+ if (!params || typeof params !== 'object')
644
+ return params;
645
+ for (const key of Object.keys(params)) {
646
+ if (nonWritable.has(key)) {
647
+ this.logger.debug(`${this.config.table}: field "${key}" is not writable on ${path} and was stripped from the payload`);
648
+ delete params[key];
649
+ }
650
+ }
651
+ return params;
652
+ }
572
653
  // ─── ID generation ─────────────────────────────────────────────────────────
573
654
  /**
574
655
  * Generates a unique ID for a new record.
@@ -657,7 +738,7 @@ class BaseGateway {
657
738
  * - `updateFilters` — applies declarative GatewayFilterRule array (new)
658
739
  */
659
740
  async onUpdateFilter(query, filterParams) {
660
- const { hasStatus, hasVersion } = this.config;
741
+ const { table, hasStatus, hasVersion, hasRemovedAt } = this.config;
661
742
  const idName = this.getIdFieldUpdateRemove();
662
743
  let filtersAppliedQty = 0;
663
744
  if (filterParams[idName]) {
@@ -680,6 +761,16 @@ class BaseGateway {
680
761
  query.where(statusField, '!=', STATUSES.REMOVED);
681
762
  }
682
763
  }
764
+ // Skip already-removed rows on soft-delete tables. Without this guard,
765
+ // a regular update call on a soft-deleted row would silently bring it
766
+ // back into a half-mutated state (new updatedAt / updatedBy, old
767
+ // Removed_At still set). For tables where hasStatus is true, the
768
+ // status-based REMOVED guard above already covers this; for PartyLabz
769
+ // tables (Status_Id, hasStatus: false) this is the only line of defence.
770
+ if (hasRemovedAt === true) {
771
+ filtersAppliedQty++;
772
+ query.whereNull(`${table}.${FIELDS.REMOVED_AT}`);
773
+ }
683
774
  // Declarative update filter rules — applied after base logic.
684
775
  filtersAppliedQty += this.applyDeclarativeUpdateFilters(query, filterParams);
685
776
  return filtersAppliedQty;
@@ -703,7 +794,7 @@ class BaseGateway {
703
794
  * - `removeFilters` — applies declarative GatewayFilterRule array (new)
704
795
  */
705
796
  async onRemoveFilter(query, filterParams) {
706
- const { hasStatus } = this.config;
797
+ const { table, hasStatus, hasRemovedAt } = this.config;
707
798
  const arr = filterParams ? castArray(filterParams) : [];
708
799
  let filtersAppliedQty = 0;
709
800
  const idName = this.getIdFieldUpdateRemove();
@@ -721,6 +812,17 @@ class BaseGateway {
721
812
  filtersAppliedQty++;
722
813
  query.where(this.getStatusField(), '!=', STATUSES.REMOVED);
723
814
  }
815
+ // Skip already-removed rows on soft-delete tables. Without this guard,
816
+ // a "remove" call on an already-removed row would re-write Removed_At
817
+ // and Removed_By with a new timestamp / user and return the row as if
818
+ // it was just removed — masking the fact that it was removed earlier.
819
+ // This guard is independent of hasStatus because PartyLabz tables use
820
+ // Status_Id (not "status"), so hasStatus is false on those tables and
821
+ // the status-based REMOVED guard above does not fire.
822
+ if (hasRemovedAt === true) {
823
+ filtersAppliedQty++;
824
+ query.whereNull(`${table}.${FIELDS.REMOVED_AT}`);
825
+ }
724
826
  // Declarative remove filter rules — applied after base logic.
725
827
  filtersAppliedQty += this.applyDeclarativeRemoveFilters(query, filterParams);
726
828
  return filtersAppliedQty;
@@ -765,6 +867,11 @@ class BaseGateway {
765
867
  */
766
868
  async transformOnCreate(params) {
767
869
  const { hasCreatedAt, hasCreatedBy, hasSpace, hasVersion, hasLang, localizationForField, hasUserId } = this.config;
870
+ // Strip client-supplied values for fields the framework manages or
871
+ // the gateway explicitly forbids from being set on create. Runs FIRST
872
+ // so the auto-set logic for createdAt / createdBy / spaceId / version
873
+ // below operates on a clean payload.
874
+ this.stripNonWritableFields(params, this.buildNonWritableFieldSet('create'), 'create');
768
875
  if (hasCreatedAt) {
769
876
  params[camelCase(FIELDS.CREATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
770
877
  }
@@ -816,6 +923,11 @@ class BaseGateway {
816
923
  */
817
924
  async transformOnUpdate(params, where) {
818
925
  const { hasUpdatedAt, hasUpdatedBy, hasVersion, hasLang, localizationForField } = this.config;
926
+ // Strip client-supplied values for fields the framework manages or
927
+ // the gateway explicitly forbids from being changed. Runs FIRST so
928
+ // the auto-set logic for updatedAt / updatedBy / version below
929
+ // operates on a clean payload.
930
+ this.stripNonWritableFields(params, this.buildNonWritableFieldSet('update'), 'update');
819
931
  if (hasUpdatedAt) {
820
932
  params[camelCase(FIELDS.UPDATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
821
933
  }
@@ -1161,21 +1273,50 @@ class BaseGateway {
1161
1273
  }
1162
1274
  return results.map((item) => this.transformOnOut(item));
1163
1275
  }
1276
+ /**
1277
+ * Builds the audit fields (updatedAt / updatedBy) to SET on an increment /
1278
+ * decrement. These must be applied as normal assignments — NOT fed through the
1279
+ * counter, which would try to do `updated_at = updated_at + <ts>` /
1280
+ * `updated_by = updated_by + <uuid>`. Returns only the fields the gateway is
1281
+ * configured to manage; an empty object when the table has no audit columns
1282
+ * (so counter-only tables behave exactly as a bare increment).
1283
+ */
1284
+ buildAuditFieldsForCounter() {
1285
+ const { hasUpdatedAt, hasUpdatedBy } = this.config;
1286
+ const out = {};
1287
+ if (hasUpdatedAt) {
1288
+ out[camelCase(FIELDS.UPDATED_AT)] = this.dateTime.dbFormat(this.dateTimeNow);
1289
+ }
1290
+ if (hasUpdatedBy) {
1291
+ const userId = this.getContext()?.userId;
1292
+ if (userId != null) {
1293
+ out[camelCase(FIELDS.UPDATED_BY)] = userId;
1294
+ }
1295
+ }
1296
+ return out;
1297
+ }
1164
1298
  /**
1165
1299
  * Increments numeric field(s) on records matching the `where` filter.
1166
1300
  * Uses the database's native INCREMENT operation rather than a read-modify-write,
1167
1301
  * making it safe for concurrent requests.
1168
1302
  *
1169
1303
  * `params` should be an object mapping field names to the increment amounts
1170
- * (e.g. `{ viewCount: 1 }`). `transformOnUpdate()` is still called, so
1171
- * audit fields (updatedAt, updatedBy) and version are updated as normal.
1304
+ * (e.g. `{ viewCount: 1 }`). ONLY those caller fields are incremented; audit
1305
+ * fields (updatedAt / updatedBy) are applied as normal SET assignments so
1306
+ * timestamp / uuid columns are never fed through the counter (which would fail
1307
+ * with `operator does not exist`). Knex compiles the chained increment + update
1308
+ * into a single UPDATE ... SET.
1172
1309
  *
1173
1310
  * Throws if no filter conditions are applied (same safety guard as `update()`).
1174
1311
  * Clears affected records from the loader cache after the operation.
1175
1312
  */
1176
1313
  async increment(where, params) {
1177
- const object = await this.transformOnUpdate(params, where);
1178
- const query = this.getBuilder().increment(object).returning(this.config.returnFields);
1314
+ let query = this.getBuilder().increment({ ...params });
1315
+ const audit = this.buildAuditFieldsForCounter();
1316
+ if (Object.keys(audit).length > 0) {
1317
+ query = query.update(audit);
1318
+ }
1319
+ query = query.returning(this.config.returnFields);
1179
1320
  const filtersAppliedQty = await this.onUpdateFilter(query, where);
1180
1321
  if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
1181
1322
  throw new Error(`Failed to increment in table '${this.config.table}': no filters applied. ` +
@@ -1196,11 +1337,17 @@ class BaseGateway {
1196
1337
  * Decrements numeric field(s) on records matching the `where` filter.
1197
1338
  * Mirror of `increment()` using the database's native DECREMENT operation.
1198
1339
  *
1199
- * Same behaviour, safety guards, and cache invalidation as `increment()`.
1340
+ * Same behaviour, safety guards, and cache invalidation as `increment()` —
1341
+ * caller fields only are decremented; audit fields are SET, not fed through the
1342
+ * counter.
1200
1343
  */
1201
1344
  async decrement(where, params) {
1202
- const object = await this.transformOnUpdate(params, where);
1203
- const query = this.getBuilder().decrement(object).returning(this.config.returnFields);
1345
+ let query = this.getBuilder().decrement({ ...params });
1346
+ const audit = this.buildAuditFieldsForCounter();
1347
+ if (Object.keys(audit).length > 0) {
1348
+ query = query.update(audit);
1349
+ }
1350
+ query = query.returning(this.config.returnFields);
1204
1351
  const filtersAppliedQty = await this.onUpdateFilter(query, where);
1205
1352
  if (filtersAppliedQty == null || filtersAppliedQty <= 0) {
1206
1353
  throw new Error(`Failed to decrement in table '${this.config.table}': no filters applied. ` +
@@ -190,4 +190,37 @@ export interface BaseGatewayPropsInterface extends CacheInterface {
190
190
  * ]
191
191
  */
192
192
  countFilters?: GatewayFilterRule[];
193
+ /**
194
+ * Field names that callers cannot set when creating a new record.
195
+ * Stripped from the params object inside transformOnCreate() before
196
+ * the INSERT statement is built.
197
+ *
198
+ * Names can be in snake_case or camelCase — both forms are stripped.
199
+ *
200
+ * The framework already implicitly strips id, removedAt, and removedBy
201
+ * on create (those are managed by the framework / the remove path).
202
+ * Use this array for additional resource-specific immutables — e.g.
203
+ * a foreign key that should be derived from session context, or a
204
+ * computed column that should never come from the client.
205
+ *
206
+ * Example:
207
+ * nonCreatableFields: ['accountId', 'sentAt']
208
+ */
209
+ nonCreatableFields?: string[];
210
+ /**
211
+ * Field names that callers cannot change after a record is created.
212
+ * Stripped from the params object inside transformOnUpdate() before
213
+ * the UPDATE statement is built.
214
+ *
215
+ * Names can be in snake_case or camelCase — both forms are stripped.
216
+ *
217
+ * The framework already implicitly strips id, createdAt, createdBy,
218
+ * removedAt, and removedBy on update. Use this array for additional
219
+ * resource-specific immutables — for example partyId on a junction
220
+ * table whose (party, child) identity is fixed at creation time.
221
+ *
222
+ * Example:
223
+ * nonUpdatableFields: ['partyId', 'offeringId']
224
+ */
225
+ nonUpdatableFields?: string[];
193
226
  }
@@ -190,4 +190,37 @@ export interface BaseGatewayPropsInterface extends CacheInterface {
190
190
  * ]
191
191
  */
192
192
  countFilters?: GatewayFilterRule[];
193
+ /**
194
+ * Field names that callers cannot set when creating a new record.
195
+ * Stripped from the params object inside transformOnCreate() before
196
+ * the INSERT statement is built.
197
+ *
198
+ * Names can be in snake_case or camelCase — both forms are stripped.
199
+ *
200
+ * The framework already implicitly strips id, removedAt, and removedBy
201
+ * on create (those are managed by the framework / the remove path).
202
+ * Use this array for additional resource-specific immutables — e.g.
203
+ * a foreign key that should be derived from session context, or a
204
+ * computed column that should never come from the client.
205
+ *
206
+ * Example:
207
+ * nonCreatableFields: ['accountId', 'sentAt']
208
+ */
209
+ nonCreatableFields?: string[];
210
+ /**
211
+ * Field names that callers cannot change after a record is created.
212
+ * Stripped from the params object inside transformOnUpdate() before
213
+ * the UPDATE statement is built.
214
+ *
215
+ * Names can be in snake_case or camelCase — both forms are stripped.
216
+ *
217
+ * The framework already implicitly strips id, createdAt, createdBy,
218
+ * removedAt, and removedBy on update. Use this array for additional
219
+ * resource-specific immutables — for example partyId on a junction
220
+ * table whose (party, child) identity is fixed at creation time.
221
+ *
222
+ * Example:
223
+ * nonUpdatableFields: ['partyId', 'offeringId']
224
+ */
225
+ nonUpdatableFields?: string[];
193
226
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.134",
3
+ "version": "1.0.136",
4
4
  "description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
5
5
  "type": "commonjs",
6
6
  "exports": {