@quad-education/sdk 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +5 -2
  2. package/dist/contract-tests/apps.d.ts +617 -0
  3. package/dist/contract-tests/apps.js +215 -1
  4. package/dist/contract-tests/harness.d.ts +1 -1
  5. package/dist/contract-tests/harness.js +7 -0
  6. package/dist/contract-tests/lists-and-files.d.ts +19 -0
  7. package/dist/contract-tests/lists-and-files.js +279 -0
  8. package/dist/contract-tests/live.d.ts +3 -0
  9. package/dist/contract-tests/live.js +156 -0
  10. package/dist/contract-tests/notifications.d.ts +3 -0
  11. package/dist/contract-tests/notifications.js +218 -0
  12. package/dist/contract-tests/search-and-totals.d.ts +13 -0
  13. package/dist/contract-tests/search-and-totals.js +226 -0
  14. package/dist/contract-tests/suite.d.ts +7 -0
  15. package/dist/contract-tests/suite.js +180 -2
  16. package/dist/contract-tests/writes.d.ts +3 -0
  17. package/dist/contract-tests/writes.js +265 -0
  18. package/dist/src/base64.d.ts +3 -0
  19. package/dist/src/base64.js +52 -0
  20. package/dist/src/client/connect.d.ts +1 -0
  21. package/dist/src/client/connect.js +1 -0
  22. package/dist/src/client/create-client.js +39 -5
  23. package/dist/src/client/save-file.d.ts +16 -0
  24. package/dist/src/client/save-file.js +28 -0
  25. package/dist/src/client/watch.d.ts +20 -0
  26. package/dist/src/client/watch.js +175 -0
  27. package/dist/src/contract/errors.d.ts +1 -1
  28. package/dist/src/contract/types.d.ts +220 -10
  29. package/dist/src/contract/types.js +4 -1
  30. package/dist/src/engine/engine.d.ts +91 -2
  31. package/dist/src/engine/engine.js +604 -67
  32. package/dist/src/engine/files.d.ts +25 -0
  33. package/dist/src/engine/files.js +88 -0
  34. package/dist/src/engine/index.d.ts +1 -1
  35. package/dist/src/engine/memory-store.d.ts +33 -3
  36. package/dist/src/engine/memory-store.js +116 -8
  37. package/dist/src/engine/notify-content.d.ts +9 -0
  38. package/dist/src/engine/notify-content.js +88 -0
  39. package/dist/src/engine/query.d.ts +14 -2
  40. package/dist/src/engine/query.js +45 -13
  41. package/dist/src/engine/search.d.ts +8 -0
  42. package/dist/src/engine/search.js +32 -0
  43. package/dist/src/engine/state.d.ts +5 -0
  44. package/dist/src/engine/storage.d.ts +46 -1
  45. package/dist/src/engine/storage.js +46 -3
  46. package/dist/src/engine/store.d.ts +39 -2
  47. package/dist/src/engine/summary.d.ts +25 -0
  48. package/dist/src/engine/summary.js +107 -0
  49. package/dist/src/engine/validate-input.d.ts +7 -1
  50. package/dist/src/engine/validate-input.js +28 -1
  51. package/dist/src/engine/working-copy.d.ts +30 -0
  52. package/dist/src/engine/working-copy.js +91 -0
  53. package/dist/src/platform-types.d.ts +11 -1
  54. package/dist/src/protocol.d.ts +1 -1
  55. package/dist/src/protocol.js +9 -0
  56. package/dist/src/testing/index.d.ts +9 -0
  57. package/dist/src/testing/index.js +16 -1
  58. package/package.json +4 -4
@@ -0,0 +1,156 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any -- the suite drives the SDK untyped, like plain JS would */
2
+ import { describe, expect, it } from 'vitest';
3
+ import { LISTED_APP, WRITES_APP } from "./apps.js";
4
+ import { expectError } from "./helpers.js";
5
+ /** Watching the app's records (D157): what ADR 0044 adds. */
6
+ export function live({ env, useApp, staff, otherStaff, student }) {
7
+ /** A watch, how many times it has called back, and a check that tells how many more that made. */
8
+ const watching = (sdk, entities, options = {}) => {
9
+ let calls = 0;
10
+ const watch = sdk.db.watch(entities, () => void (calls += 1), options);
11
+ return {
12
+ watch,
13
+ calls: () => calls,
14
+ async more() {
15
+ const before = calls;
16
+ await watch.check();
17
+ return calls - before;
18
+ },
19
+ };
20
+ };
21
+ describe('db watch (D157)', () => {
22
+ useApp(WRITES_APP);
23
+ it('calls back once at the start, and not again while nothing changes', async () => {
24
+ const w = watching(await env().connect(staff), ['slot']);
25
+ await w.watch.check();
26
+ expect(w.calls()).toBe(1);
27
+ expect(await w.more()).toBe(0);
28
+ expect(await w.more()).toBe(0);
29
+ w.watch.stop();
30
+ });
31
+ it("calls back after another person's create, update and delete", async () => {
32
+ const w = watching(await env().connect(staff), ['slot']);
33
+ await w.watch.check();
34
+ const slots = (await env().connect(otherStaff)).db.entity('slot');
35
+ const made = await slots.create({ label: 'Mon 9', status: 'free' });
36
+ expect(await w.more()).toBe(1);
37
+ await slots.update(made.id, { status: 'taken' });
38
+ expect(await w.more()).toBe(1);
39
+ await slots.delete(made.id);
40
+ expect(await w.more()).toBe(1);
41
+ expect(await w.more()).toBe(0);
42
+ w.watch.stop();
43
+ });
44
+ it('calls back once for a batch, and for the entities it wrote only', async () => {
45
+ const sdk = await env().connect(staff);
46
+ const slot = watching(sdk, ['slot']);
47
+ const booking = watching(sdk, ['booking']);
48
+ const both = watching(sdk, ['slot', 'booking']);
49
+ await both.watch.check();
50
+ const other = await env().connect(otherStaff);
51
+ await other.db.batch([
52
+ { create: 'slot', input: { label: 'Tue 9', status: 'free' } },
53
+ { create: 'slot', input: { label: 'Tue 10', status: 'free' } },
54
+ ]);
55
+ expect(await slot.more()).toBe(1);
56
+ expect(await booking.more()).toBe(0);
57
+ expect(await both.more()).toBe(0); // it ran in the same round as `slot`
58
+ expect(both.calls()).toBe(2);
59
+ for (const w of [slot, booking, both])
60
+ w.watch.stop();
61
+ });
62
+ it('stays silent after a read, and after a write that was refused', async () => {
63
+ const w = watching(await env().connect(staff), ['slot']);
64
+ const slots = (await env().connect(otherStaff)).db.entity('slot');
65
+ await slots.create({ label: 'Wed 9', status: 'free' });
66
+ await w.watch.check();
67
+ await slots.list();
68
+ await slots.count();
69
+ await expectError(slots.create({ label: 'Wed 9', status: 'free' }), 'CONFLICT');
70
+ await expectError((await env().connect(otherStaff)).db.batch([
71
+ { create: 'slot', input: { label: 'Wed 10', status: 'free' } },
72
+ { create: 'slot', input: { label: 'Wed 9', status: 'free' } },
73
+ ]), 'CONFLICT');
74
+ expect(await w.more()).toBe(0);
75
+ w.watch.stop();
76
+ });
77
+ it("follows a person's own write without being asked", async () => {
78
+ const sdk = await env().connect(staff);
79
+ const w = watching(sdk, ['slot']);
80
+ await w.watch.check();
81
+ await sdk.db.entity('slot').create({ label: 'Thu 9', status: 'free' });
82
+ await expect.poll(() => w.calls(), { timeout: 2000 }).toBe(2);
83
+ w.watch.stop();
84
+ });
85
+ it('tells a person that a table changed, whoever wrote and whatever they may read of it', async () => {
86
+ const w = watching(await env().connect(student), ['booking']);
87
+ await w.watch.check();
88
+ await (await env().connect(staff)).db.entity('booking').create({ slotLabel: 'Fri 9' });
89
+ expect(await w.more()).toBe(1);
90
+ // What they read is still only their own.
91
+ expect((await (await env().connect(student)).db.entity('booking').list()).items).toEqual([]);
92
+ w.watch.stop();
93
+ });
94
+ it('stops when asked', async () => {
95
+ const w = watching(await env().connect(staff), ['slot']);
96
+ await w.watch.check();
97
+ w.watch.stop();
98
+ await (await env().connect(otherStaff)).db
99
+ .entity('slot')
100
+ .create({ label: 'Sat 9', status: 'free' });
101
+ expect(await w.more()).toBe(0);
102
+ });
103
+ it('calls back after the app is reset', async () => {
104
+ const w = watching(await env().connect(staff), ['slot']);
105
+ await w.watch.check();
106
+ await env().control.reset();
107
+ expect(await w.more()).toBe(1);
108
+ w.watch.stop();
109
+ });
110
+ it('refuses a table the person may not read, and one that does not exist', async () => {
111
+ const sdk = await env().connect(student);
112
+ const errors = [];
113
+ const refused = sdk.db.watch(['slot'], () => undefined, {
114
+ onError: (e) => errors.push(e),
115
+ });
116
+ await expectError(refused.check(), 'NOT_PERMITTED');
117
+ expect(errors).toHaveLength(1);
118
+ const unknown = sdk.db.watch(['nothing'], () => undefined, { onError: () => undefined });
119
+ await expectError(unknown.check(), 'VALIDATION');
120
+ // A refused watch does not stop the others.
121
+ const fine = watching(sdk, ['booking']);
122
+ const bad = sdk.db.watch(['slot'], () => undefined, { onError: () => undefined });
123
+ await fine.watch.check();
124
+ expect(fine.calls()).toBe(1);
125
+ await expectError(bad.check(), 'NOT_PERMITTED');
126
+ fine.watch.stop();
127
+ });
128
+ it('says what it takes when called wrongly', async () => {
129
+ const sdk = await env().connect(staff);
130
+ expect(() => sdk.db.watch('slot', () => undefined)).toThrow(/list of the app's entities/);
131
+ expect(() => sdk.db.watch([], () => undefined)).toThrow(/list of the app's entities/);
132
+ expect(() => sdk.db.watch(['slot'])).toThrow(/function to call/);
133
+ expect(() => sdk.db.watch(['slot'], () => undefined, { intervalMs: 'fast' })).toThrow(/number of milliseconds/);
134
+ });
135
+ });
136
+ describe('db watch and listed access (D157, D142)', () => {
137
+ useApp(LISTED_APP);
138
+ it('calls back when a table its rules look people up in changes', async () => {
139
+ const me = staff;
140
+ await env().control.setAppAdmins([me.personId]);
141
+ const sdk = await env().connect(staff);
142
+ const signups = sdk.db.entity('signups');
143
+ const listing = await signups.create({ staffId: me.personId });
144
+ const roster = watching(sdk, ['roster']);
145
+ const setting = watching(sdk, ['setting']);
146
+ await roster.watch.check();
147
+ await setting.watch.check();
148
+ // Who may read the roster has changed, though no roster record has.
149
+ await (await env().connect(otherStaff)).db.entity('signups').delete(listing.id);
150
+ expect(await roster.more()).toBe(1);
151
+ expect(await setting.more()).toBe(0);
152
+ roster.watch.stop();
153
+ setting.watch.stop();
154
+ });
155
+ });
156
+ }
@@ -0,0 +1,3 @@
1
+ import type { Setup } from './lists-and-files.ts';
2
+ /** Formatted notifications (D151) and attachments (D152): what ADR 0041 adds. */
3
+ export declare function notifications({ env, useApp, staff, otherStaff, student, parent, childId, }: Setup): void;
@@ -0,0 +1,218 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any -- the suite drives the SDK untyped, like plain JS would */
2
+ import { describe, expect, it } from 'vitest';
3
+ import { parentsOf } from "../src/index.js";
4
+ import { NOTIFY_APP } from "./apps.js";
5
+ import { expectError } from "./helpers.js";
6
+ const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4];
7
+ const PDF = [0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x34];
8
+ const blob = (bytes, type) => new Blob([new Uint8Array(bytes)], { type });
9
+ /** Formatted notifications (D151) and attachments (D152): what ADR 0041 adds. */
10
+ export function notifications({ env, useApp, staff, otherStaff, student, parent, childId, }) {
11
+ const staffId = otherStaff.personId;
12
+ const base = { type: 'notice.sent', subject: 'Zoo excursion', to: { person: staffId } };
13
+ const content = [
14
+ { heading: 'Year 9 zoo excursion' },
15
+ { text: 'Please give your consent by Friday.' },
16
+ {
17
+ details: [
18
+ ['Date', 'Thursday 12 March'],
19
+ ['Cost', '$18'],
20
+ ],
21
+ },
22
+ { list: ['Bus leaves at 8:45 am', 'Back by 3:00 pm'] },
23
+ { button: { label: 'Give consent', link: '/consent/1' } },
24
+ ];
25
+ describe('notify: formatted messages (D151)', () => {
26
+ useApp(NOTIFY_APP);
27
+ it('keeps the blocks, and makes the plain text from them', async () => {
28
+ const sdk = await env().connect(staff);
29
+ await sdk.notify.send({ ...base, content });
30
+ const [entry] = (await env().control.outbox());
31
+ expect(entry.content).toEqual(content);
32
+ expect(entry.body).toBe([
33
+ 'Year 9 zoo excursion',
34
+ '',
35
+ 'Please give your consent by Friday.',
36
+ '',
37
+ 'Date: Thursday 12 March',
38
+ 'Cost: $18',
39
+ '',
40
+ '- Bus leaves at 8:45 am',
41
+ '- Back by 3:00 pm',
42
+ '',
43
+ 'Give consent: /consent/1',
44
+ ].join('\n'));
45
+ });
46
+ it('uses the body an app gives beside the blocks, and still takes a body alone', async () => {
47
+ const sdk = await env().connect(staff);
48
+ await sdk.notify.send({ ...base, body: 'Short version', content });
49
+ await sdk.notify.send({ ...base, body: 'Just text' });
50
+ const outbox = (await env().control.outbox());
51
+ expect(outbox.map((e) => e.body).sort()).toEqual(['Just text', 'Short version']);
52
+ expect(outbox.find((e) => e.body === 'Just text').content).toBeUndefined();
53
+ await expectError(sdk.notify.send({ ...base }), 'VALIDATION');
54
+ });
55
+ it('keeps HTML as text: an app never writes markup', async () => {
56
+ const sdk = await env().connect(staff);
57
+ const html = '<img src=x onerror=alert(1)><a href="https://evil.example">x</a>';
58
+ await sdk.notify.send({ ...base, content: [{ heading: html }, { text: html }] });
59
+ const [entry] = (await env().control.outbox());
60
+ expect(entry.content).toEqual([{ heading: html }, { text: html }]);
61
+ expect(entry.body).toContain(html);
62
+ });
63
+ it('refuses anything that is not one of the blocks, and a link out of the app', async () => {
64
+ const sdk = await env().connect(staff);
65
+ const bad = (blocks) => expectError(sdk.notify.send({ ...base, content: blocks }), 'VALIDATION');
66
+ await bad('hello');
67
+ await bad([]);
68
+ await bad([{ html: '<p>x</p>' }]);
69
+ await bad([{ heading: 'a', text: 'b' }]);
70
+ await bad([{ heading: '' }]);
71
+ await bad([{ heading: 'x'.repeat(201) }]);
72
+ await bad([{ text: 'x'.repeat(2001) }]);
73
+ await bad([{ list: [] }]);
74
+ await bad([{ list: ['a', 2] }]);
75
+ await bad([{ details: [['Date']] }]);
76
+ await bad([{ details: [['Date', 'x', 'y']] }]);
77
+ await bad([{ button: { label: 'Go', link: 'https://evil.example' } }]);
78
+ await bad([{ button: { label: 'Go', link: '//evil.example' } }]);
79
+ await bad([{ button: { label: 'Go' } }]);
80
+ await bad([
81
+ { button: { label: 'One', link: '/a' } },
82
+ { button: { label: 'Two', link: '/b' } },
83
+ ]);
84
+ await bad(Array.from({ length: 31 }, () => ({ text: 'x' })));
85
+ await bad(Array.from({ length: 6 }, () => ({ text: 'x'.repeat(2000) })));
86
+ expect(await env().control.outbox()).toEqual([]);
87
+ });
88
+ });
89
+ describe('notify: attachments (D152)', () => {
90
+ useApp(NOTIFY_APP);
91
+ it('carries a copy of each file to every recipient', async () => {
92
+ const sdk = await env().connect(staff);
93
+ const slip = await sdk.files.upload(blob(PDF, 'application/pdf'), { name: 'slip.pdf' });
94
+ const photo = await sdk.files.upload(blob(PNG, 'image/png'), { name: 'zoo.png' });
95
+ await sdk.db.entity('notice').create({ title: 'Zoo', slip: slip.id });
96
+ const { recipients } = await sdk.notify.send({
97
+ ...base,
98
+ to: parentsOf(childId),
99
+ regarding: { studentId: childId },
100
+ content,
101
+ attachments: [slip.id, photo.id],
102
+ });
103
+ expect(recipients.some((r) => r.personId === parent.personId)).toBe(true);
104
+ const outbox = (await env().control.outbox());
105
+ expect(outbox).toHaveLength(recipients.length);
106
+ for (const entry of outbox)
107
+ expect(entry.attachments.map((a) => [a.name, a.type, a.size])).toEqual([
108
+ ['slip.pdf', 'application/pdf', PDF.length],
109
+ ['zoo.png', 'image/png', PNG.length],
110
+ ]);
111
+ const [first, second] = outbox[0].attachments;
112
+ // The copy is its own file: not the one the record holds.
113
+ expect(first.id).not.toBe(slip.id);
114
+ expect((await env().control.outboxAttachment(first.id)).bytes).toEqual(PDF);
115
+ expect((await env().control.outboxAttachment(second.id)).name).toBe('zoo.png');
116
+ // What was sent is not a file an app can read.
117
+ await expectError(sdk.files.info(first.id), 'NOT_FOUND');
118
+ await expectError((await env().connect(parent)).files.read(first.id), 'NOT_FOUND');
119
+ expect(await env().control.outboxAttachment(slip.id)).toBeUndefined();
120
+ });
121
+ it('keeps what was sent after the record is gone and a day has passed', async () => {
122
+ await env().control.setClock('2026-03-04T03:00:00.000Z');
123
+ const sdk = await env().connect(staff);
124
+ const slip = await sdk.files.upload(blob(PDF, 'application/pdf'), { name: 'slip.pdf' });
125
+ const notice = await sdk.db.entity('notice').create({ title: 'Zoo', slip: slip.id });
126
+ await sdk.notify.send({ ...base, body: 'See attached', attachments: [slip.id] });
127
+ await sdk.db.entity('notice').delete(notice.id);
128
+ await env().control.advanceClock(48 * 60 * 60 * 1000);
129
+ // An upload sweeps files nobody attached; a sent copy is not one of them.
130
+ await sdk.files.upload(blob(PNG, 'image/png'));
131
+ const [entry] = (await env().control.outbox());
132
+ expect((await env().control.outboxAttachment(entry.attachments[0].id)).bytes).toEqual(PDF);
133
+ await env().control.restart();
134
+ expect((await env().control.outboxAttachment(entry.attachments[0].id)).bytes).toEqual(PDF);
135
+ });
136
+ it('sends only files the sender can read', async () => {
137
+ const mine = await env().connect(student);
138
+ const theirs = await (await env().connect(staff)).files.upload(blob(PNG, 'image/png'));
139
+ const send = (attachments) => mine.notify.send({ ...base, body: 'x', attachments });
140
+ await expectError(send([theirs.id]), 'NOT_FOUND');
141
+ await expectError(send(['file_nothing']), 'NOT_FOUND');
142
+ await expectError(send('one'), 'VALIDATION');
143
+ await expectError(send([1]), 'VALIDATION');
144
+ const own = await mine.files.upload(blob(PNG, 'image/png'));
145
+ await expectError(send([own.id, own.id]), 'VALIDATION');
146
+ expect(await env().control.outbox()).toEqual([]);
147
+ expect((await send([own.id])).recipients).toHaveLength(1);
148
+ });
149
+ // Two 6 MB uploads: slow on a busy machine, so it is given more time than the default.
150
+ it('takes at most five files and 10 MB in all', async () => {
151
+ const sdk = await env().connect(staff);
152
+ const small = [];
153
+ for (let i = 0; i < 6; i++)
154
+ small.push((await sdk.files.upload(blob(PNG, 'image/png'))).id);
155
+ await expectError(sdk.notify.send({ ...base, body: 'x', attachments: small }), 'VALIDATION');
156
+ const big = [];
157
+ for (let i = 0; i < 2; i++)
158
+ big.push((await sdk.files.upload(new Blob([new Uint8Array(6 * 1024 * 1024)], { type: 'text/plain' }))).id);
159
+ const e = await expectError(sdk.notify.send({ ...base, body: 'x', attachments: big }), 'VALIDATION');
160
+ expect(e.message).toContain('10 MB');
161
+ expect(await env().control.outbox()).toEqual([]);
162
+ }, 30_000);
163
+ it('never sends a file to a role its field is hidden from, or a staff-only level beyond staff', async () => {
164
+ const sdk = await env().connect(staff);
165
+ const note = await sdk.files.upload(blob(PDF, 'application/pdf'), { name: 'note.pdf' });
166
+ const review = await sdk.files.upload(blob(PDF, 'application/pdf'), { name: 'review.pdf' });
167
+ await sdk.db.entity('notice').create({ title: 'x', staffNote: note.id, review: review.id });
168
+ const toParents = { to: parentsOf(childId), regarding: { studentId: childId } };
169
+ for (const [id, field] of [
170
+ [note.id, 'staffNote'],
171
+ [review.id, 'review'],
172
+ ]) {
173
+ const e = await expectError(sdk.notify.send({ ...base, ...toParents, body: 'x', attachments: [id] }), 'NOT_PERMITTED');
174
+ expect(e.message).toContain(`notice.${field}`);
175
+ }
176
+ expect(await env().control.outbox()).toEqual([]);
177
+ // To staff, both go.
178
+ const sent = await sdk.notify.send({ ...base, body: 'x', attachments: [note.id, review.id] });
179
+ expect(sent.recipients).toEqual([{ personId: staffId, role: 'staff' }]);
180
+ });
181
+ it('sends and copies once for a repeated key', async () => {
182
+ const sdk = await env().connect(staff);
183
+ const slip = await sdk.files.upload(blob(PDF, 'application/pdf'));
184
+ const send = () => sdk.notify.send({ ...base, body: 'x', attachments: [slip.id], idempotencyKey: 'once' });
185
+ await send();
186
+ await send();
187
+ const outbox = (await env().control.outbox());
188
+ expect(outbox).toHaveLength(1);
189
+ });
190
+ it('records for the school who sent which files to whom, and tells the app nothing more', async () => {
191
+ const sdk = await env().connect(staff);
192
+ const slip = await sdk.files.upload(blob(PDF, 'application/pdf'), { name: 'slip.pdf' });
193
+ const notice = await sdk.db.entity('notice').create({ title: 'Zoo', slip: slip.id });
194
+ await sdk.notify.send({ ...base, body: 'x', attachments: [slip.id] });
195
+ const log = await env().control.auditLog();
196
+ const entry = log.find((e) => e.action === 'notification.attachments');
197
+ expect(entry).toMatchObject({
198
+ source: 'platform',
199
+ visibility: 'cio',
200
+ actor: staff.personId,
201
+ });
202
+ expect(entry.data).toMatchObject({
203
+ type: 'notice.sent',
204
+ recipients: [staffId],
205
+ files: [{ name: 'slip.pdf', entity: 'notice', recordId: notice.id, field: 'slip' }],
206
+ });
207
+ expect((await sdk.audit.list()).items).toEqual([]);
208
+ });
209
+ it('clears what was sent with the app’s data', async () => {
210
+ const sdk = await env().connect(staff);
211
+ const slip = await sdk.files.upload(blob(PDF, 'application/pdf'));
212
+ await sdk.notify.send({ ...base, body: 'x', attachments: [slip.id] });
213
+ const [entry] = (await env().control.outbox());
214
+ await env().control.reset();
215
+ expect(await env().control.outboxAttachment(entry.attachments[0].id)).toBeUndefined();
216
+ });
217
+ });
218
+ }
@@ -0,0 +1,13 @@
1
+ import type { Setup } from './lists-and-files.ts';
2
+ type Person = {
3
+ id: string;
4
+ givenName: string;
5
+ familyName: string;
6
+ email?: string;
7
+ };
8
+ /** Search by words (D153) and counts and totals (D154): what ADR 0042 adds. */
9
+ export declare function searchAndTotals({ env, useApp, staff, student, students, }: Setup & {
10
+ students: readonly Person[];
11
+ staffRecords: readonly Person[];
12
+ }): void;
13
+ export {};
@@ -0,0 +1,226 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any -- the suite drives the SDK untyped, like plain JS would */
2
+ import { describe, expect, it } from 'vitest';
3
+ import { SEARCH_APP } from "./apps.js";
4
+ import { expectError, listAll } from "./helpers.js";
5
+ /** Search by words (D153) and counts and totals (D154): what ADR 0042 adds. */
6
+ export function searchAndTotals({ env, useApp, staff, student, students, }) {
7
+ const titles = async (sdk, options) => (await sdk.db.entity('request').list({ orderBy: { field: 'title' }, ...options })).items.map((r) => r.title);
8
+ describe('db search (D153)', () => {
9
+ useApp(SEARCH_APP);
10
+ const seed = async () => {
11
+ const sdk = await env().connect(staff);
12
+ const requests = sdk.db.entity('request');
13
+ await requests.create({ title: 'Zoo excursion', body: 'Bus to the zoo', status: 'open' });
14
+ await requests.create({ title: 'Zoë’s camp', body: 'Three nights', status: 'open' });
15
+ await requests.create({
16
+ title: 'Swimming carnival',
17
+ tags: ['bus', 'Pool'],
18
+ status: 'closed',
19
+ secret: 'budget overrun',
20
+ });
21
+ await requests.create({ title: 'Museum visit', status: 'open' });
22
+ return sdk;
23
+ };
24
+ it('matches records where every word appears somewhere in the searchable fields', async () => {
25
+ const sdk = await seed();
26
+ expect(await titles(sdk, { search: 'zoo' })).toEqual(['Zoo excursion']);
27
+ // Across fields, and in a list of text.
28
+ expect(await titles(sdk, { search: 'bus' })).toEqual(['Swimming carnival', 'Zoo excursion']);
29
+ expect(await titles(sdk, { search: 'bus zoo' })).toEqual(['Zoo excursion']);
30
+ expect(await titles(sdk, { search: 'bus pool' })).toEqual(['Swimming carnival']);
31
+ expect(await titles(sdk, { search: 'bus museum' })).toEqual([]);
32
+ expect(await titles(sdk, { search: 'nothing' })).toEqual([]);
33
+ });
34
+ it('ignores case and accents, and matches part of a word', async () => {
35
+ const sdk = await seed();
36
+ expect(await titles(sdk, { search: 'ZOO' })).toEqual(['Zoo excursion']);
37
+ expect(await titles(sdk, { search: 'zoe' })).toEqual(['Zoë’s camp']);
38
+ expect(await titles(sdk, { search: 'Zoë' })).toEqual(['Zoë’s camp']);
39
+ expect(await titles(sdk, { search: 'exc' })).toEqual(['Zoo excursion']);
40
+ expect(await titles(sdk, { search: ' carnival swim ' })).toEqual(['Swimming carnival']);
41
+ });
42
+ it('works with where, an order and pages', async () => {
43
+ const sdk = await seed();
44
+ expect(await titles(sdk, { search: 'bus', where: { status: 'open' } })).toEqual([
45
+ 'Zoo excursion',
46
+ ]);
47
+ const requests = sdk.db.entity('request');
48
+ const first = await requests.list({ search: 'bus', orderBy: { field: 'title' }, limit: 1 });
49
+ expect(first.items.map((r) => r.title)).toEqual(['Swimming carnival']);
50
+ const second = await requests.list({
51
+ search: 'bus',
52
+ orderBy: { field: 'title' },
53
+ limit: 1,
54
+ cursor: first.nextCursor,
55
+ });
56
+ expect(second.items.map((r) => r.title)).toEqual(['Zoo excursion']);
57
+ expect(second.nextCursor).toBeNull();
58
+ // A cursor belongs to its search.
59
+ await expectError(requests.list({
60
+ search: 'zoo',
61
+ orderBy: { field: 'title' },
62
+ limit: 1,
63
+ cursor: first.nextCursor,
64
+ }), 'VALIDATION');
65
+ });
66
+ it('never looks in a field hidden from the reader, or in records they cannot read', async () => {
67
+ await seed();
68
+ const asStaff = await env().connect(staff);
69
+ expect(await titles(asStaff, { search: 'overrun' })).toEqual(['Swimming carnival']);
70
+ const mine = await env().connect(student);
71
+ await mine.db.entity('request').create({ title: 'My excursion idea', status: 'open' });
72
+ // The student reads only their own row: staff's rows are not found, whatever they hold.
73
+ expect(await titles(mine, { search: 'excursion' })).toEqual(['My excursion idea']);
74
+ expect(await titles(mine, { search: 'overrun' })).toEqual([]);
75
+ // Staff write a secret onto the student's own row; the student's search still can't see it.
76
+ const row = (await asStaff.db.entity('request').list({ search: 'idea' })).items[0];
77
+ await asStaff.db.entity('request').update(row.id, { secret: 'flagged for review' });
78
+ expect(await titles(mine, { search: 'flagged' })).toEqual([]);
79
+ expect(await titles(asStaff, { search: 'flagged' })).toEqual(['My excursion idea']);
80
+ });
81
+ it('takes 1 to 5 words, and refuses an entity that names no searchable fields', async () => {
82
+ const sdk = await seed();
83
+ const requests = sdk.db.entity('request');
84
+ await expectError(requests.list({ search: '' }), 'VALIDATION');
85
+ await expectError(requests.list({ search: ' ' }), 'VALIDATION');
86
+ await expectError(requests.list({ search: 5 }), 'VALIDATION');
87
+ await expectError(requests.list({ search: 'a b c d e f' }), 'VALIDATION');
88
+ await expectError(requests.list({ search: 'x'.repeat(101) }), 'VALIDATION');
89
+ const e = await expectError(sdk.db.entity('plain').list({ search: 'x' }), 'VALIDATION');
90
+ expect(e.message).toContain('search: [');
91
+ });
92
+ });
93
+ describe('school search (D153)', () => {
94
+ useApp(SEARCH_APP);
95
+ it('finds people by name, in any order of words, among those the person may see', async () => {
96
+ const sdk = await env().connect(staff);
97
+ const target = students[40];
98
+ const found = await listAll(sdk.school.students, {
99
+ search: `${target.familyName} ${target.givenName}`.toLowerCase(),
100
+ });
101
+ expect(found.map((s) => s.id)).toContain(target.id);
102
+ for (const s of found) {
103
+ const text = `${s.givenName} ${s.familyName}`.toLowerCase();
104
+ expect(text).toContain(target.givenName.toLowerCase());
105
+ }
106
+ // A student sees themselves and nobody else, searched or not.
107
+ const mine = await env().connect(student);
108
+ expect(await listAll(mine.school.students, { search: target.familyName })).toEqual(target.id === student.personId ? found : []);
109
+ });
110
+ it('looks only in the text the app has been granted', async () => {
111
+ const sdk = await env().connect(staff);
112
+ // This app holds the basic level only, so an email address, a contact detail, is not searched.
113
+ const withEmail = students.find((s) => typeof s.email === 'string');
114
+ if (withEmail)
115
+ expect(await listAll(sdk.school.students, { search: withEmail.email })).toEqual([]);
116
+ await expectError(sdk.school.students.list({ search: '' }), 'VALIDATION');
117
+ });
118
+ });
119
+ describe('db counts and totals (D154)', () => {
120
+ useApp(SEARCH_APP);
121
+ const seed = async () => {
122
+ const sdk = await env().connect(staff);
123
+ const requests = sdk.db.entity('request');
124
+ await requests.create({ title: 'a', status: 'open', term: 'T1', cost: 10, margin: 1 });
125
+ await requests.create({ title: 'b', status: 'open', term: 'T1', cost: 20.5, margin: 2 });
126
+ await requests.create({ title: 'c', status: 'closed', term: 'T2', cost: 5 });
127
+ await requests.create({ title: 'd bus', status: 'closed' });
128
+ return sdk;
129
+ };
130
+ it('counts the records that match', async () => {
131
+ const sdk = await seed();
132
+ const requests = sdk.db.entity('request');
133
+ expect(await requests.count()).toBe(4);
134
+ expect(await requests.count({ where: { status: 'open' } })).toBe(2);
135
+ expect(await requests.count({ search: 'bus' })).toBe(1);
136
+ expect(await requests.count({ where: { cost: { gte: 10 } } })).toBe(2);
137
+ expect(await requests.count({ where: { status: 'open', term: 'T2' } })).toBe(0);
138
+ await expectError(requests.count({ limit: 5 }), 'VALIDATION');
139
+ await expectError(requests.count({ where: { nope: 1 } }), 'VALIDATION');
140
+ });
141
+ it('adds up, and finds the least, the greatest and the average of number fields', async () => {
142
+ const sdk = await seed();
143
+ const summary = await sdk.db
144
+ .entity('request')
145
+ .summarise({ sum: ['cost'], min: ['cost'], max: ['cost'], avg: ['cost', 'margin'] });
146
+ expect(summary).toEqual({
147
+ count: 4,
148
+ sum: { cost: 35.5 },
149
+ min: { cost: 5 },
150
+ max: { cost: 20.5 },
151
+ // An average is over the records that have the field.
152
+ avg: { cost: 11.8333333333, margin: 1.5 },
153
+ });
154
+ expect(await sdk.db.entity('request').summarise()).toEqual({ count: 4 });
155
+ // With nothing to work on, a sum is zero and the others are empty.
156
+ expect(await sdk.db
157
+ .entity('request')
158
+ .summarise({ where: { term: 'T9' }, sum: ['cost'], min: ['cost'], avg: ['cost'] })).toEqual({ count: 0, sum: { cost: 0 }, min: { cost: null }, avg: { cost: null } });
159
+ });
160
+ it('gives the same for each value of one field, with a group for the empty ones', async () => {
161
+ const sdk = await seed();
162
+ const byTerm = await sdk.db
163
+ .entity('request')
164
+ .summarise({ groupBy: 'term', sum: ['cost'], where: { cost: { gte: 0 } } });
165
+ expect(byTerm).toEqual({
166
+ count: 3,
167
+ sum: { cost: 35.5 },
168
+ groups: [
169
+ { value: 'T1', count: 2, sum: { cost: 30.5 } },
170
+ { value: 'T2', count: 1, sum: { cost: 5 } },
171
+ ],
172
+ });
173
+ const byStatus = await sdk.db.entity('request').summarise({ groupBy: 'term' });
174
+ expect(byStatus.groups).toEqual([
175
+ { value: 'T1', count: 2 },
176
+ { value: 'T2', count: 1 },
177
+ { value: null, count: 1 },
178
+ ]);
179
+ const byWho = await sdk.db.entity('request').summarise({ groupBy: 'createdBy' });
180
+ expect(byWho.groups).toEqual([{ value: staff.personId, count: 4 }]);
181
+ });
182
+ it('covers only what the person may read, and only fields they can see', async () => {
183
+ await seed();
184
+ const mine = await env().connect(student);
185
+ const requests = mine.db.entity('request');
186
+ await requests.create({ title: 'mine', status: 'open', cost: 3 });
187
+ expect(await requests.count()).toBe(1);
188
+ expect(await requests.summarise({ sum: ['cost'], groupBy: 'status' })).toEqual({
189
+ count: 1,
190
+ sum: { cost: 3 },
191
+ groups: [{ value: 'open', count: 1, sum: { cost: 3 } }],
192
+ });
193
+ await expectError(requests.summarise({ sum: ['margin'] }), 'VALIDATION');
194
+ await expectError(requests.summarise({ groupBy: 'secret' }), 'VALIDATION');
195
+ await expectError(requests.count({ where: { secret: 'x' } }), 'VALIDATION');
196
+ // An entity the role may not read at all refuses a count as it refuses a list.
197
+ await expectError(mine.db.entity('plain').count(), 'NOT_PERMITTED');
198
+ });
199
+ it('takes number fields to total and a single-valued field to group by', async () => {
200
+ const sdk = await seed();
201
+ const requests = sdk.db.entity('request');
202
+ await expectError(requests.summarise({ sum: ['title'] }), 'VALIDATION');
203
+ await expectError(requests.summarise({ sum: 'cost' }), 'VALIDATION');
204
+ await expectError(requests.summarise({ sum: [] }), 'VALIDATION');
205
+ await expectError(requests.summarise({ sum: ['cost', 'cost'] }), 'VALIDATION');
206
+ await expectError(requests.summarise({ groupBy: 'tags' }), 'VALIDATION');
207
+ await expectError(requests.summarise({ groupBy: 'proof' }), 'VALIDATION');
208
+ await expectError(requests.summarise({ groupBy: 'nope' }), 'VALIDATION');
209
+ await expectError(requests.summarise({ median: ['cost'] }), 'VALIDATION');
210
+ });
211
+ it('refuses more than 200 groups, in words, and never returns a wrong answer', async () => {
212
+ const sdk = await env().connect(staff);
213
+ for (let start = 0; start < 225; start += 25)
214
+ await sdk.db.batch(Array.from({ length: 25 }, (_, i) => ({
215
+ create: 'request',
216
+ input: { title: `r${start + i}`, status: 'open', term: `t${start + i}` },
217
+ })));
218
+ const e = await expectError(sdk.db.entity('request').summarise({ groupBy: 'term' }), 'VALIDATION');
219
+ expect(e.message).toContain('more than 200');
220
+ expect(await sdk.db.entity('request').count()).toBe(225);
221
+ expect((await sdk.db.entity('request').summarise({ groupBy: 'status' })).groups).toEqual([
222
+ { value: 'open', count: 225 },
223
+ ]);
224
+ });
225
+ });
226
+ }
@@ -46,12 +46,19 @@ export type ContractEnv = {
46
46
  type: string;
47
47
  title: string;
48
48
  }[]>;
49
+ /** A file a sent notification carries (D152), by the id its outbox entry gives; undefined when there is none. */
50
+ outboxAttachment(id: string): Promise<{
51
+ name: string;
52
+ bytes: number[];
53
+ } | undefined>;
49
54
  /** Every audit entry, including CIO-only ones (D19). */
50
55
  auditLog(): Promise<readonly (Record<string, any> & {
51
56
  visibility: 'app' | 'cio';
52
57
  })[]>;
53
58
  /** The installation's app admins, as the school sets them (D133): person ids, replacing any before. */
54
59
  setAppAdmins(personIds: readonly string[]): Promise<void>;
60
+ /** Who holds the app's own roles, as the school assigns them (D143): person id to role names, replacing any before. */
61
+ setAppRoles(assignments: Readonly<Record<string, readonly string[]>>): Promise<void>;
55
62
  };
56
63
  dispose(): Promise<void>;
57
64
  };