forest-express-sequelize 9.6.16 → 9.7.1

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/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ ## [9.7.1](https://github.com/ForestAdmin/forest-express-sequelize/compare/v9.7.0...v9.7.1) (2026-12-01)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **deps:** bump forest-express to 10.10.1 ([#1160](https://github.com/ForestAdmin/forest-express-sequelize/issues/1160)) ([d4d81bc](https://github.com/ForestAdmin/forest-express-sequelize/commit/d4d81bc871add3eae127c9d2e05197f9badb1938))
7
+
8
+ # [9.7.0](https://github.com/ForestAdmin/forest-express-sequelize/compare/v9.6.16...v9.7.0) (2026-11-26)
9
+
10
+
11
+ ### Features
12
+
13
+ * **scopes:** apply a related collection's scope when the server flags it ([#1158](https://github.com/ForestAdmin/forest-express-sequelize/issues/1158)) ([98dd0e6](https://github.com/ForestAdmin/forest-express-sequelize/commit/98dd0e66f5a9844f3a867b77cd4be0c169e93c71))
14
+
1
15
  ## [9.6.16](https://github.com/ForestAdmin/forest-express-sequelize/compare/v9.6.15...v9.6.16) (2026-11-03)
2
16
 
3
17
 
@@ -8,6 +8,7 @@ var _lodash = require("lodash");
8
8
  var _sequelizeCompatibility = _interopRequireDefault(require("../utils/sequelize-compatibility"));
9
9
  var _primaryKeysManager = _interopRequireDefault(require("./primary-keys-manager"));
10
10
  var _resourcesGetter = _interopRequireDefault(require("./resources-getter"));
11
+ var _relatedRecordScopes = _interopRequireDefault(require("./related-record-scopes"));
11
12
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
12
13
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
13
14
  class HasManyGetter extends _resourcesGetter.default {
@@ -21,7 +22,7 @@ class HasManyGetter extends _resourcesGetter.default {
21
22
  const parentRecord = await this._parentModel.findOne(options);
22
23
  const records = (_parentRecord$this$_p = parentRecord === null || parentRecord === void 0 ? void 0 : parentRecord[this._params.associationName]) !== null && _parentRecord$this$_p !== void 0 ? _parentRecord$this$_p : [];
23
24
  new _primaryKeysManager.default(this._model).annotateRecords(records);
24
- return records;
25
+ return (0, _relatedRecordScopes.default)(this._model, records, this._user, this._params.timezone);
25
26
  }
26
27
  async count() {
27
28
  const options = await this._buildQueryOptions({
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ require("core-js/modules/es.promise.js");
5
+ require("core-js/modules/es.array.iterator.js");
6
+ var _lodash = require("lodash");
7
+ var _forestExpress = require("forest-express");
8
+ var _operators = _interopRequireDefault(require("../utils/operators"));
9
+ var _query = _interopRequireDefault(require("../utils/query"));
10
+ var _queryOptions = _interopRequireDefault(require("./query-options"));
11
+ const TO_ONE = ['BelongsTo', 'HasOne'];
12
+
13
+ /**
14
+ * Empties a to-one related record that its own collection's scope hides, when the server flags
15
+ * that scope as applying to related records. The root record is kept: a scope on accounts
16
+ * restricts which accounts are seen, never which cards exist.
17
+ *
18
+ * Each related collection is checked with one query under its own scope, restricted to the
19
+ * loaded records' primary keys, so values compare as they do when listing that collection.
20
+ * A relation whose check fails is served empty rather than failing the request, which may
21
+ * follow a write that is already saved.
22
+ */
23
+ async function redactRelatedRecords(model, records, user, timezone) {
24
+ const associations = Object.values(model.associations).filter(function (association) {
25
+ return TO_ONE.includes(association.associationType);
26
+ });
27
+ await Promise.all(associations.map(async function ({
28
+ as,
29
+ target
30
+ }) {
31
+ const loaded = records.filter(function (record) {
32
+ return record === null || record === void 0 ? void 0 : record[as];
33
+ });
34
+ if (!loaded.length) return;
35
+ const primaryKeys = Object.keys(target.primaryKeys);
36
+ const keyOf = function (record) {
37
+ return JSON.stringify(primaryKeys.map(function (key) {
38
+ return record[key];
39
+ }));
40
+ };
41
+ let visibleKeys;
42
+ try {
43
+ var _scopeManager$scopeAp;
44
+ // A forest-express release without the lookup reads as not flagged.
45
+ if (!(await ((_scopeManager$scopeAp = _forestExpress.scopeManager.scopeAppliesToRelatedRecords) === null || _scopeManager$scopeAp === void 0 ? void 0 : _scopeManager$scopeAp.call(_forestExpress.scopeManager, user, target.name)))) return;
46
+ // Without a primary key the loaded records cannot be matched: they are served as before.
47
+ if (!primaryKeys.length) return;
48
+ const operators = _operators.default.getInstance({
49
+ Sequelize: target.sequelize.constructor
50
+ });
51
+ // Built from the raw key values, so composite keys need no packing into strings.
52
+ const idsWhere = primaryKeys.length === 1 ? {
53
+ [primaryKeys[0]]: [...new Set(loaded.map(function (record) {
54
+ return record[as][primaryKeys[0]];
55
+ }))]
56
+ } : {
57
+ [operators.OR]: loaded.map(function (record) {
58
+ return (0, _lodash.pick)(record[as], primaryKeys);
59
+ })
60
+ };
61
+ const queryOptions = new _queryOptions.default(target);
62
+ await queryOptions.filterByConditionTree(await _forestExpress.scopeManager.getScopeForUser(user, target.name, true), timezone);
63
+ const {
64
+ where,
65
+ include
66
+ } = queryOptions.sequelizeOptions;
67
+ const visible = await target.unscoped().findAll({
68
+ where: _query.default.mergeWhere(operators, idsWhere, where),
69
+ include,
70
+ attributes: primaryKeys
71
+ });
72
+ visibleKeys = new Set(visible.map(keyOf));
73
+ } catch (error) {
74
+ _forestExpress.logger.warn(`Related ${target.name} records served empty, their scope could not be checked: ${error.message}`);
75
+ visibleKeys = new Set();
76
+ }
77
+ loaded.filter(function (record) {
78
+ return !visibleKeys.has(keyOf(record[as]));
79
+ }).forEach(function (record) {
80
+ record[as] = null;
81
+ if (record.dataValues) record.dataValues[as] = null;
82
+ });
83
+ }));
84
+ return records;
85
+ }
86
+ module.exports = redactRelatedRecords;
@@ -17,12 +17,13 @@ const PrimaryKeysManager = require('./primary-keys-manager');
17
17
  const associationRecord = require('../utils/association-record');
18
18
  const isPrimaryKeyAForeignKey = require('../utils/is-primary-key-a-foreign-key');
19
19
  class ResourceCreator {
20
- constructor(model, params, body, user) {
20
+ constructor(model, params, body, user, options = {}) {
21
21
  this.model = model;
22
22
  this.params = params;
23
23
  this.body = body;
24
24
  this.schema = Interface.Schemas.schemas[model.name];
25
25
  this.user = user;
26
+ this.options = options;
26
27
  }
27
28
  async _getTargetKey(name, association) {
28
29
  const primaryKey = this.body[name];
@@ -96,7 +97,7 @@ class ResourceCreator {
96
97
  try {
97
98
  return await new ResourceGetter(this.model, _objectSpread(_objectSpread({}, this.params), {}, {
98
99
  recordId: record[this.schema.idField]
99
- }), this.user).perform();
100
+ }), this.user, this.options).perform();
100
101
  } catch (error) {
101
102
  if (error.statusCode === 404 && scopeFilters) {
102
103
  return record;
@@ -6,11 +6,17 @@ var _forestExpress = require("forest-express");
6
6
  var _httpErrors = _interopRequireDefault(require("http-errors"));
7
7
  var _primaryKeysManager = _interopRequireDefault(require("./primary-keys-manager"));
8
8
  var _queryOptions = _interopRequireDefault(require("./query-options"));
9
+ var _relatedRecordScopes = _interopRequireDefault(require("./related-record-scopes"));
9
10
  class ResourceGetter {
10
- constructor(model, params, user) {
11
+ constructor(model, params, user, {
12
+ redactRelatedRecords: redactRelated = true
13
+ } = {}) {
11
14
  this._model = model.unscoped();
12
15
  this._params = params;
13
16
  this._user = user;
17
+ // Code calling the getter itself, such as a smart action, reads related records as stored: only
18
+ // what the agent serves is emptied.
19
+ this._redact = redactRelated;
14
20
  }
15
21
  async perform() {
16
22
  const {
@@ -27,6 +33,7 @@ class ResourceGetter {
27
33
  throw (0, _httpErrors.default)(404, `The ${this._model.name} #${this._params.recordId} does not exist.`);
28
34
  }
29
35
  new _primaryKeysManager.default(this._model).annotateRecords([record]);
36
+ if (this._redact) await (0, _relatedRecordScopes.default)(this._model, [record], this._user, timezone);
30
37
  return record;
31
38
  }
32
39
  }
@@ -11,11 +11,12 @@ var _resourceGetter = _interopRequireDefault(require("./resource-getter"));
11
11
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
12
12
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
13
13
  class ResourceUpdater {
14
- constructor(model, params, newRecord, user) {
14
+ constructor(model, params, newRecord, user, options = {}) {
15
15
  this._model = model.unscoped();
16
16
  this._params = params;
17
17
  this._newRecord = newRecord;
18
18
  this._user = user;
19
+ this._options = options;
19
20
  }
20
21
  async perform() {
21
22
  const {
@@ -40,7 +41,7 @@ class ResourceUpdater {
40
41
  try {
41
42
  return await new _resourceGetter.default(this._model, _objectSpread(_objectSpread({}, this._params), {}, {
42
43
  recordId: this._params.recordId
43
- }), this._user).perform();
44
+ }), this._user, this._options).perform();
44
45
  } catch (error) {
45
46
  if (error.statusCode === 404 && scopeFilters) {
46
47
  return record;
@@ -10,15 +10,21 @@ var _forestExpress = require("forest-express");
10
10
  var _lodash = _interopRequireDefault(require("lodash"));
11
11
  var _primaryKeysManager = _interopRequireDefault(require("./primary-keys-manager"));
12
12
  var _queryOptions = _interopRequireDefault(require("./query-options"));
13
+ var _relatedRecordScopes = _interopRequireDefault(require("./related-record-scopes"));
13
14
  var _requestedFieldsExtractor = _interopRequireDefault(require("./requested-fields-extractor"));
14
15
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
15
16
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
16
17
  class ResourcesGetter {
17
- constructor(model, lianaOptions, params, user) {
18
+ constructor(model, lianaOptions, params, user, {
19
+ redactRelatedRecords: redactRelated = true
20
+ } = {}) {
18
21
  // lianaOptions is kept for compatibility with forest-express-mongoose
19
22
  this._model = model.unscoped();
20
23
  this._params = params;
21
24
  this._user = user;
25
+ // Code calling the getter itself, such as a smart action, reads related records as stored: only
26
+ // what the agent serves is emptied.
27
+ this._redact = redactRelated;
22
28
  }
23
29
  async perform() {
24
30
  return [await this._getRecords(), await this._getFieldsSearched()];
@@ -41,7 +47,8 @@ class ResourcesGetter {
41
47
  const [model, options] = await this._buildQueryOptions();
42
48
  const records = await model.findAll(options);
43
49
  new _primaryKeysManager.default(this._model).annotateRecords(records);
44
- return records;
50
+ if (!this._redact) return records;
51
+ return (0, _relatedRecordScopes.default)(this._model, records, this._user, this._params.timezone);
45
52
  }
46
53
 
47
54
  /** Get list of fields descriptors which are used when searching (for frontend highlighting). */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "forest-express-sequelize",
3
3
  "description": "Official Express/Sequelize Liana for Forest",
4
- "version": "9.6.16",
4
+ "version": "9.7.1",
5
5
  "author": "Sandro Munda <sandro@munda.me>",
6
6
  "contributors": [
7
7
  "Arnaud Besnier <arnaudibesnier@gmail.com>",
@@ -31,7 +31,7 @@
31
31
  "@babel/runtime": "7.15.4",
32
32
  "bluebird": "2.9.25",
33
33
  "core-js": "3.6.5",
34
- "forest-express": "10.9.8",
34
+ "forest-express": "10.10.1",
35
35
  "http-errors": "1.6.1",
36
36
  "lodash": "4.18.1",
37
37
  "moment": "2.29.4",
@@ -22,6 +22,9 @@ const QueryStatGetter = require('../src/services/query-stat-getter');
22
22
  const baseParams = { timezone: 'Europe/Paris' };
23
23
  const user = { renderingId: 1 };
24
24
 
25
+ // No server answers here: these tests run with no scope applying to related records.
26
+ jest.spyOn(scopeManager, 'scopeAppliesToRelatedRecords').mockResolvedValue(false);
27
+
25
28
  [
26
29
  sequelizePostgres,
27
30
  sequelizeMySQLMin,
@@ -0,0 +1,250 @@
1
+ import Sequelize from 'sequelize';
2
+ import Interface, { scopeManager } from 'forest-express';
3
+ import HasManyGetter from '../../src/services/has-many-getter';
4
+ import redactRelatedRecords from '../../src/services/related-record-scopes';
5
+ import ResourceGetter from '../../src/services/resource-getter';
6
+ import ResourceUpdater from '../../src/services/resource-updater';
7
+ import ResourcesExporter from '../../src/services/resources-exporter';
8
+ import ResourcesGetter from '../../src/services/resources-getter';
9
+
10
+ describe('services > related record scopes', () => {
11
+ // Sequelize is created here without connection to a database
12
+ const sequelize = new Sequelize({ dialect: 'postgres' });
13
+ const Account = sequelize.define('accounts', { organization: Sequelize.STRING });
14
+ const Holder = sequelize.define('holders', { region: Sequelize.STRING });
15
+ const Card = sequelize.define('cards', { panLast4: Sequelize.STRING });
16
+ const Owner = sequelize.define('owners', {});
17
+ const Organization = sequelize.define('organizations', { name: Sequelize.STRING });
18
+ Account.belongsTo(Organization, { as: 'tenant' });
19
+ Card.belongsTo(Account, { as: 'account' });
20
+ Card.belongsTo(Holder, { as: 'holder' });
21
+ Owner.hasMany(Card, { as: 'cards' });
22
+
23
+ const cardIncludes = [{ model: Account, as: 'account' }, { model: Holder, as: 'holder' }];
24
+ const user = { id: 1, renderingId: 1 };
25
+ const timezone = 'Europe/Paris';
26
+ const fields = { cards: 'id,panLast4,account,holder', account: 'id', holder: 'id' };
27
+ const accountScope = { field: 'organization', operator: 'equal', value: 'own' };
28
+
29
+ const schema = (name, ownFields) => ({
30
+ name,
31
+ idField: 'id',
32
+ primaryKeys: ['id'],
33
+ fields: [{ field: 'id', type: 'Number', columnName: 'id' }, ...ownFields],
34
+ });
35
+
36
+ function buildCards() {
37
+ return [
38
+ { id: 1, account: { id: 10 }, holder: { id: 20 } },
39
+ { id: 2, account: { id: 11 }, holder: { id: 21 } },
40
+ { id: 3, account: null, holder: { id: 20 } },
41
+ ].map((values) => Card.build(values, { include: cardIncludes }));
42
+ }
43
+
44
+ const relatedIds = (records) => records.map((record) => [
45
+ record.id, record.account?.id ?? null, record.holder?.id ?? null,
46
+ ]);
47
+
48
+ // forest-express exposes the flag lookup from the release that follows this change.
49
+ if (!scopeManager.scopeAppliesToRelatedRecords) {
50
+ scopeManager.scopeAppliesToRelatedRecords = async () => false;
51
+ }
52
+
53
+ function setup({ flagged, scope = accountScope }) {
54
+ // Assigned in place: forest-express resolves nested smart fields through the same object.
55
+ Interface.Schemas.schemas = {
56
+ cards: schema('cards', [
57
+ { field: 'panLast4', type: 'String', columnName: 'panLast4' },
58
+ { field: 'account', type: 'Number', reference: 'accounts.id' },
59
+ { field: 'holder', type: 'Number', reference: 'holders.id' },
60
+ ]),
61
+ accounts: schema('accounts', [
62
+ { field: 'organization', type: 'String', columnName: 'organization' },
63
+ { field: 'tenant', type: 'Number', reference: 'organizations.id' },
64
+ ]),
65
+ organizations: schema('organizations', [{ field: 'name', type: 'String', columnName: 'name' }]),
66
+ holders: schema('holders', [{ field: 'region', type: 'String', columnName: 'region' }]),
67
+ owners: schema('owners', [{ field: 'cards', type: ['Number'], reference: 'cards.id' }]),
68
+ };
69
+
70
+ jest.spyOn(scopeManager, 'getScopeForUser').mockImplementation(async (_user, collectionName) => (
71
+ collectionName === 'accounts' ? JSON.stringify(scope) : null
72
+ ));
73
+ jest.spyOn(scopeManager, 'scopeAppliesToRelatedRecords')
74
+ .mockImplementation(async (_user, collectionName) => flagged.includes(collectionName));
75
+ jest.spyOn(Account, 'findAll').mockResolvedValue([Account.build({ id: 10 })]);
76
+ jest.spyOn(Holder, 'findAll').mockResolvedValue([]);
77
+ }
78
+
79
+ describe('when the related collection scope is flagged', () => {
80
+ it('empties a related record outside the scope on list and keeps the row', async () => {
81
+ expect.hasAssertions();
82
+ setup({ flagged: ['accounts'] });
83
+ jest.spyOn(Card, 'findAll').mockResolvedValue(buildCards());
84
+
85
+ const [records] = await new ResourcesGetter(Card, {}, { timezone, fields }, user).perform();
86
+
87
+ expect(relatedIds(records)).toStrictEqual([[1, 10, 20], [2, null, 21], [3, null, 20]]);
88
+ expect(records[1].toJSON().account).toBeNull();
89
+ expect(Account.findAll).toHaveBeenCalledTimes(1);
90
+ const [{ where, attributes }] = Account.findAll.mock.calls[0];
91
+ expect(attributes).toStrictEqual(['id']);
92
+ expect(where).toStrictEqual({ id: [10, 11], organization: { [Sequelize.Op.eq]: 'own' } });
93
+ expect(Holder.findAll).not.toHaveBeenCalled();
94
+ jest.restoreAllMocks();
95
+ });
96
+
97
+ it('empties a related record outside the scope on get and still returns the record', async () => {
98
+ expect.hasAssertions();
99
+ setup({ flagged: ['accounts'] });
100
+ jest.spyOn(Card, 'findOne').mockResolvedValue(buildCards()[1]);
101
+
102
+ const record = await new ResourceGetter(Card, { recordId: 2, timezone }, user).perform();
103
+
104
+ expect(relatedIds([record])).toStrictEqual([[2, null, 21]]);
105
+ jest.restoreAllMocks();
106
+ });
107
+
108
+ it('empties a related record outside the scope on related list', async () => {
109
+ expect.hasAssertions();
110
+ setup({ flagged: ['accounts'] });
111
+ const owner = Owner.build({ id: 1, cards: [] }, { include: [{ model: Card, as: 'cards' }] });
112
+ owner.cards = buildCards();
113
+ jest.spyOn(Owner, 'findOne').mockResolvedValue(owner);
114
+ const params = {
115
+ timezone, fields, associationName: 'cards', recordId: 1,
116
+ };
117
+
118
+ const [records] = await new HasManyGetter(Owner, Card, {}, params, user).perform();
119
+
120
+ expect(relatedIds(records)).toStrictEqual([[1, 10, 20], [2, null, 21], [3, null, 20]]);
121
+ jest.restoreAllMocks();
122
+ });
123
+
124
+ it('empties a related record outside the scope in each CSV batch', async () => {
125
+ expect.hasAssertions();
126
+ setup({ flagged: ['accounts'] });
127
+ jest.spyOn(Card, 'findAll').mockResolvedValue(buildCards());
128
+ const batches = [];
129
+
130
+ await new ResourcesExporter(Card, {}, { timezone, fields }, null, user)
131
+ .perform(async (records) => { batches.push(relatedIds(records)); });
132
+
133
+ expect(batches).toStrictEqual([[[1, 10, 20], [2, null, 21], [3, null, 20]]]);
134
+ jest.restoreAllMocks();
135
+ });
136
+ });
137
+
138
+ it('checks a scope that reaches through a relation of the related collection', async () => {
139
+ expect.hasAssertions();
140
+ setup({ flagged: ['accounts'], scope: { field: 'tenant:name', operator: 'equal', value: 'own' } });
141
+ jest.spyOn(Card, 'findAll').mockResolvedValue(buildCards());
142
+
143
+ const [records] = await new ResourcesGetter(Card, {}, { timezone, fields }, user).perform();
144
+
145
+ expect(relatedIds(records)).toStrictEqual([[1, 10, 20], [2, null, 21], [3, null, 20]]);
146
+ const [{ where, include }] = Account.findAll.mock.calls[0];
147
+ expect(where).toStrictEqual({ id: [10, 11], '$tenant.name$': { [Sequelize.Op.eq]: 'own' } });
148
+ expect(include).toStrictEqual([expect.objectContaining({ as: 'tenant' })]);
149
+ jest.restoreAllMocks();
150
+ });
151
+
152
+ it('serves related records as before when their scope is not flagged', async () => {
153
+ expect.hasAssertions();
154
+ setup({ flagged: [] });
155
+ jest.spyOn(Card, 'findAll').mockResolvedValue(buildCards());
156
+
157
+ const [records] = await new ResourcesGetter(Card, {}, { timezone, fields }, user).perform();
158
+
159
+ expect(relatedIds(records)).toStrictEqual([[1, 10, 20], [2, 11, 21], [3, null, 20]]);
160
+ expect(Account.findAll).not.toHaveBeenCalled();
161
+ jest.restoreAllMocks();
162
+ });
163
+
164
+ describe('when the caller asks for the related records as stored', () => {
165
+ it('serves them unchanged on list', async () => {
166
+ expect.hasAssertions();
167
+ setup({ flagged: ['accounts'] });
168
+ jest.spyOn(Card, 'findAll').mockResolvedValue(buildCards());
169
+
170
+ const [records] = await new ResourcesGetter(
171
+ Card, {}, { timezone, fields }, user, { redactRelatedRecords: false },
172
+ ).perform();
173
+
174
+ expect(relatedIds(records)).toStrictEqual([[1, 10, 20], [2, 11, 21], [3, null, 20]]);
175
+ expect(Account.findAll).not.toHaveBeenCalled();
176
+ jest.restoreAllMocks();
177
+ });
178
+
179
+ it('serves them unchanged on get', async () => {
180
+ expect.hasAssertions();
181
+ setup({ flagged: ['accounts'] });
182
+ jest.spyOn(Card, 'findOne').mockResolvedValue(buildCards()[1]);
183
+
184
+ const record = await new ResourceGetter(
185
+ Card, { recordId: 2, timezone }, user, { redactRelatedRecords: false },
186
+ ).perform();
187
+
188
+ expect(relatedIds([record])).toStrictEqual([[2, 11, 21]]);
189
+ jest.restoreAllMocks();
190
+ });
191
+ });
192
+
193
+ describe('when the scope of a related collection cannot be checked', () => {
194
+ it('serves that related record empty instead of failing the request', async () => {
195
+ expect.hasAssertions();
196
+ setup({ flagged: ['accounts'] });
197
+ scopeManager.scopeAppliesToRelatedRecords.mockRejectedValue(new Error('server unreachable'));
198
+ jest.spyOn(Card, 'findOne').mockResolvedValue(buildCards()[0]);
199
+
200
+ const record = await new ResourceGetter(Card, { recordId: 1, timezone }, user).perform();
201
+
202
+ expect(relatedIds([record])).toStrictEqual([[1, null, null]]);
203
+ jest.restoreAllMocks();
204
+ });
205
+
206
+ it('still answers an update that was saved', async () => {
207
+ expect.hasAssertions();
208
+ setup({ flagged: ['accounts'] });
209
+ Account.findAll.mockRejectedValue(new Error('invalid scope'));
210
+ const [saved] = buildCards();
211
+ jest.spyOn(saved, 'validate').mockResolvedValue();
212
+ jest.spyOn(saved, 'save').mockResolvedValue(saved);
213
+ jest.spyOn(Card, 'findOne').mockResolvedValue(saved);
214
+
215
+ const record = await new ResourceUpdater(
216
+ Card, { recordId: 1, timezone }, { panLast4: '1234' }, user,
217
+ ).perform();
218
+
219
+ expect(saved.save).toHaveBeenCalledTimes(1);
220
+ expect(relatedIds([record])).toStrictEqual([[1, null, 20]]);
221
+ jest.restoreAllMocks();
222
+ });
223
+ });
224
+
225
+ it('matches a related record with a composite primary key on its raw key values', async () => {
226
+ expect.hasAssertions();
227
+ const Slot = sequelize.define('slots', {
228
+ label: { type: Sequelize.STRING, primaryKey: true },
229
+ startsAt: { type: Sequelize.DATE, primaryKey: true },
230
+ });
231
+ const Booking = sequelize.define('bookings', {});
232
+ Booking.belongsTo(Slot, { as: 'slot', foreignKey: 'slotLabel', targetKey: 'label' });
233
+ const startsAt = new Date('2026-01-01T09:00:00Z');
234
+ const bookings = [
235
+ { id: 1, slot: { label: 'a|b', startsAt } },
236
+ { id: 2, slot: { label: 'c', startsAt } },
237
+ ].map((values) => Booking.build(values, { include: [{ model: Slot, as: 'slot' }] }));
238
+ jest.spyOn(scopeManager, 'scopeAppliesToRelatedRecords').mockResolvedValue(true);
239
+ jest.spyOn(scopeManager, 'getScopeForUser').mockResolvedValue(null);
240
+ jest.spyOn(Slot, 'findAll').mockResolvedValue([Slot.build({ label: 'a|b', startsAt })]);
241
+
242
+ await redactRelatedRecords(Booking, bookings, user, timezone);
243
+
244
+ expect(bookings.map((booking) => booking.slot?.label ?? null)).toStrictEqual(['a|b', null]);
245
+ expect(Slot.findAll.mock.calls[0][0].where).toStrictEqual({
246
+ [Sequelize.Op.or]: [{ label: 'a|b', startsAt }, { label: 'c', startsAt }],
247
+ });
248
+ jest.restoreAllMocks();
249
+ });
250
+ });