@remit/backend 0.0.143 → 0.0.145

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 (279) hide show
  1. package/dist/dev-server/content-handler.d.ts +38 -0
  2. package/dist/dev-server/content-handler.js +46 -0
  3. package/dist/src/api.d.ts +5 -0
  4. package/dist/src/api.js +73 -0
  5. package/dist/src/auth.d.ts +24 -0
  6. package/dist/src/auth.js +81 -0
  7. package/dist/src/config/api-config.d.ts +20 -0
  8. package/dist/src/config/api-config.js +1 -0
  9. package/dist/src/config/from-env.d.ts +2 -0
  10. package/dist/src/config/from-env.js +65 -0
  11. package/dist/src/config/msoauth-secrets-manager.d.ts +2 -0
  12. package/dist/src/config/msoauth-secrets-manager.js +28 -0
  13. package/dist/src/config/msoauth.d.ts +19 -0
  14. package/dist/src/config/msoauth.js +6 -0
  15. package/{src/derive/autoMoved.ts → dist/src/derive/autoMoved.d.ts} +1 -29
  16. package/dist/src/derive/autoMoved.js +49 -0
  17. package/dist/src/derive/contentSignature.d.ts +40 -0
  18. package/{src/derive/contentSignature.ts → dist/src/derive/contentSignature.js} +23 -77
  19. package/dist/src/derive/contentUrl.d.ts +33 -0
  20. package/dist/src/derive/contentUrl.js +27 -0
  21. package/{src/derive/deriveMuted.ts → dist/src/derive/deriveMuted.d.ts} +1 -3
  22. package/dist/src/derive/deriveMuted.js +7 -0
  23. package/dist/src/derive/enrichThreadRows.d.ts +118 -0
  24. package/dist/src/derive/enrichThreadRows.js +151 -0
  25. package/dist/src/derive/filterThreadCriteria.d.ts +23 -0
  26. package/dist/src/derive/filterThreadCriteria.js +24 -0
  27. package/{src/derive/pendingMoveCounts.ts → dist/src/derive/pendingMoveCounts.d.ts} +5 -53
  28. package/dist/src/derive/pendingMoveCounts.js +53 -0
  29. package/{src/derive/senderTrust.ts → dist/src/derive/senderTrust.d.ts} +1 -9
  30. package/dist/src/derive/senderTrust.js +19 -0
  31. package/dist/src/error.d.ts +21 -0
  32. package/dist/src/error.js +85 -0
  33. package/dist/src/handlers/account-guards.d.ts +36 -0
  34. package/dist/src/handlers/account-guards.js +107 -0
  35. package/dist/src/handlers/account-oauth.d.ts +15 -0
  36. package/dist/src/handlers/account-oauth.js +334 -0
  37. package/dist/src/handlers/account-overrides.d.ts +53 -0
  38. package/dist/src/handlers/account-overrides.js +233 -0
  39. package/dist/src/handlers/account-signature.d.ts +28 -0
  40. package/dist/src/handlers/account-signature.js +85 -0
  41. package/dist/src/handlers/account.d.ts +7 -0
  42. package/dist/src/handlers/account.js +337 -0
  43. package/dist/src/handlers/address.d.ts +35 -0
  44. package/dist/src/handlers/address.js +133 -0
  45. package/dist/src/handlers/calendar-event.d.ts +70 -0
  46. package/dist/src/handlers/calendar-event.js +417 -0
  47. package/dist/src/handlers/calendar-feed.d.ts +47 -0
  48. package/dist/src/handlers/calendar-feed.js +184 -0
  49. package/dist/src/handlers/calendar-suggestion.d.ts +47 -0
  50. package/dist/src/handlers/calendar-suggestion.js +204 -0
  51. package/dist/src/handlers/calendar.d.ts +116 -0
  52. package/dist/src/handlers/calendar.js +323 -0
  53. package/dist/src/handlers/config.d.ts +43 -0
  54. package/dist/src/handlers/config.js +164 -0
  55. package/dist/src/handlers/ensure-account-config.d.ts +9 -0
  56. package/dist/src/handlers/ensure-account-config.js +27 -0
  57. package/dist/src/handlers/filter.d.ts +3 -0
  58. package/dist/src/handlers/filter.js +88 -0
  59. package/dist/src/handlers/folder-role-appointments.d.ts +68 -0
  60. package/dist/src/handlers/folder-role-appointments.js +168 -0
  61. package/dist/src/handlers/folder-role-labels.d.ts +26 -0
  62. package/dist/src/handlers/folder-role-labels.js +40 -0
  63. package/dist/src/handlers/folder-role.d.ts +9 -0
  64. package/dist/src/handlers/folder-role.js +37 -0
  65. package/dist/src/handlers/index.d.ts +88 -0
  66. package/dist/src/handlers/index.js +62 -0
  67. package/dist/src/handlers/label.d.ts +43 -0
  68. package/dist/src/handlers/label.js +107 -0
  69. package/dist/src/handlers/mailbox-bindings.d.ts +41 -0
  70. package/dist/src/handlers/mailbox-bindings.js +61 -0
  71. package/dist/src/handlers/mailbox.d.ts +23 -0
  72. package/dist/src/handlers/mailbox.js +211 -0
  73. package/dist/src/handlers/me.d.ts +2 -0
  74. package/dist/src/handlers/me.js +117 -0
  75. package/dist/src/handlers/message.d.ts +82 -0
  76. package/dist/src/handlers/message.js +595 -0
  77. package/dist/src/handlers/organize.d.ts +10 -0
  78. package/dist/src/handlers/organize.js +103 -0
  79. package/dist/src/handlers/outbox-attachment.d.ts +25 -0
  80. package/dist/src/handlers/outbox-attachment.js +77 -0
  81. package/dist/src/handlers/outbox.d.ts +4 -0
  82. package/dist/src/handlers/outbox.js +136 -0
  83. package/dist/src/handlers/sync-progress.d.ts +46 -0
  84. package/dist/src/handlers/sync-progress.js +63 -0
  85. package/dist/src/handlers/sync.d.ts +28 -0
  86. package/dist/src/handlers/sync.js +73 -0
  87. package/dist/src/handlers/system-update.d.ts +2 -0
  88. package/dist/src/handlers/system-update.js +159 -0
  89. package/dist/src/handlers/thread.d.ts +148 -0
  90. package/dist/src/handlers/thread.js +228 -0
  91. package/dist/src/handlers/unified-threads.d.ts +247 -0
  92. package/dist/src/handlers/unified-threads.js +406 -0
  93. package/{src/handlers/vip-suggestions.ts → dist/src/handlers/vip-suggestions.d.ts} +1 -13
  94. package/dist/src/handlers/vip-suggestions.js +16 -0
  95. package/dist/src/index.d.ts +5 -0
  96. package/dist/src/index.js +53 -0
  97. package/{src/json.ts → dist/src/json.d.ts} +1 -4
  98. package/dist/src/json.js +10 -0
  99. package/dist/src/jwt-auth.d.ts +15 -0
  100. package/dist/src/jwt-auth.js +45 -0
  101. package/dist/src/lambda.d.ts +13 -0
  102. package/dist/src/lambda.js +33 -0
  103. package/dist/src/request.d.ts +9 -0
  104. package/dist/src/request.js +17 -0
  105. package/dist/src/response.d.ts +44 -0
  106. package/dist/src/response.js +80 -0
  107. package/dist/src/serve.d.ts +31 -0
  108. package/dist/src/serve.js +117 -0
  109. package/dist/src/service/account-deletion.d.ts +20 -0
  110. package/dist/src/service/account-deletion.js +33 -0
  111. package/dist/src/service/compose-sqlite.d.ts +3 -0
  112. package/dist/src/service/compose-sqlite.js +13 -0
  113. package/dist/src/service/create-remit-client.d.ts +109 -0
  114. package/dist/src/service/create-remit-client.js +188 -0
  115. package/dist/src/service/data-client.d.ts +12 -0
  116. package/dist/src/service/data-client.js +42 -0
  117. package/dist/src/service/export-identity.d.ts +4 -0
  118. package/dist/src/service/export-identity.js +33 -0
  119. package/dist/src/service/fire-and-forget.d.ts +54 -0
  120. package/dist/src/service/fire-and-forget.js +37 -0
  121. package/dist/src/service/organize.d.ts +181 -0
  122. package/dist/src/service/organize.js +367 -0
  123. package/dist/src/service/queues.d.ts +12 -0
  124. package/dist/src/service/queues.js +1 -0
  125. package/dist/src/service/refusal.d.ts +4 -0
  126. package/dist/src/service/refusal.js +20 -0
  127. package/dist/src/service/sender-category.d.ts +51 -0
  128. package/{src/service/sender-category.ts → dist/src/service/sender-category.js} +40 -81
  129. package/dist/src/service/shared-deps.d.ts +6 -0
  130. package/dist/src/service/shared-deps.js +24 -0
  131. package/dist/src/service/trigger-sync.d.ts +57 -0
  132. package/dist/src/service/trigger-sync.js +31 -0
  133. package/dist/src/types.d.ts +72 -0
  134. package/dist/src/types.js +1 -0
  135. package/package.json +125 -98
  136. package/.env.test +0 -4
  137. package/dev-server/content-auth.test.ts +0 -113
  138. package/dev-server/content-auth.ts +0 -54
  139. package/dev-server/content-handler.test.ts +0 -105
  140. package/dev-server/content-handler.ts +0 -79
  141. package/dev-server/content-path.test.ts +0 -37
  142. package/dev-server/content-path.ts +0 -27
  143. package/dev-server/cors.test.ts +0 -48
  144. package/dev-server/cors.ts +0 -25
  145. package/dev-server/keep-alive.test.ts +0 -24
  146. package/dev-server/lambda-helpers.ts +0 -69
  147. package/dev-server/log-output.test.ts +0 -173
  148. package/dev-server/oauth-callback-route.test.ts +0 -66
  149. package/dev-server/relational-health.test.ts +0 -83
  150. package/dev-server/relational-health.ts +0 -39
  151. package/dev-server/server.ts +0 -384
  152. package/dev-server/sync-age.test.ts +0 -91
  153. package/dev-server/sync-age.ts +0 -55
  154. package/dev-server/upload-handler.ts +0 -132
  155. package/dev-server/upload-route.test.ts +0 -196
  156. package/scripts/backfill-classification.ts +0 -91
  157. package/scripts/backfill-list-id.ts +0 -83
  158. package/scripts/config-save.ts +0 -128
  159. package/src/auth.test.ts +0 -12
  160. package/src/auth.ts +0 -92
  161. package/src/config/msoauth.test.ts +0 -48
  162. package/src/config/msoauth.ts +0 -48
  163. package/src/data-backend.test.ts +0 -23
  164. package/src/data-backend.ts +0 -14
  165. package/src/derive/autoMoved.test.ts +0 -104
  166. package/src/derive/contentSignature.test.ts +0 -161
  167. package/src/derive/contentUrl.test.ts +0 -172
  168. package/src/derive/contentUrl.ts +0 -86
  169. package/src/derive/deriveMuted.test.ts +0 -34
  170. package/src/derive/enrichThreadRows.test.ts +0 -360
  171. package/src/derive/enrichThreadRows.ts +0 -234
  172. package/src/derive/filterThreadCriteria.test.ts +0 -126
  173. package/src/derive/filterThreadCriteria.ts +0 -51
  174. package/src/derive/senderTrust.test.ts +0 -67
  175. package/src/error.test.ts +0 -201
  176. package/src/error.ts +0 -123
  177. package/src/handlers/account-guards.test.ts +0 -67
  178. package/src/handlers/account-guards.ts +0 -169
  179. package/src/handlers/account-oauth-callback.test.ts +0 -155
  180. package/src/handlers/account-oauth-consent.test.ts +0 -336
  181. package/src/handlers/account-oauth-start.test.ts +0 -191
  182. package/src/handlers/account-oauth.test.ts +0 -439
  183. package/src/handlers/account-oauth.ts +0 -635
  184. package/src/handlers/account-overrides.test.ts +0 -88
  185. package/src/handlers/account-overrides.ts +0 -323
  186. package/src/handlers/account-ownership.ts +0 -25
  187. package/src/handlers/account-signature.ts +0 -117
  188. package/src/handlers/account-synced-services.test.ts +0 -245
  189. package/src/handlers/account.ts +0 -552
  190. package/src/handlers/address.test.ts +0 -381
  191. package/src/handlers/address.ts +0 -200
  192. package/src/handlers/calendar-event.test.ts +0 -685
  193. package/src/handlers/calendar-event.ts +0 -738
  194. package/src/handlers/calendar-feed-validators.test.ts +0 -228
  195. package/src/handlers/calendar-feed.test.ts +0 -439
  196. package/src/handlers/calendar-feed.ts +0 -291
  197. package/src/handlers/calendar-sqlite-fixture.ts +0 -36
  198. package/src/handlers/calendar-suggestion.test.ts +0 -1269
  199. package/src/handlers/calendar-suggestion.ts +0 -425
  200. package/src/handlers/calendar.test.ts +0 -1080
  201. package/src/handlers/calendar.ts +0 -517
  202. package/src/handlers/config.test.ts +0 -245
  203. package/src/handlers/config.ts +0 -332
  204. package/src/handlers/ensure-account-config.ts +0 -30
  205. package/src/handlers/filter.test.ts +0 -644
  206. package/src/handlers/filter.ts +0 -518
  207. package/src/handlers/folder-role-appointments.test.ts +0 -438
  208. package/src/handlers/folder-role-appointments.ts +0 -249
  209. package/src/handlers/folder-role-labels.ts +0 -63
  210. package/src/handlers/folder-role.test.ts +0 -209
  211. package/src/handlers/folder-role.ts +0 -80
  212. package/src/handlers/index.ts +0 -83
  213. package/src/handlers/label.test.ts +0 -112
  214. package/src/handlers/label.ts +0 -210
  215. package/src/handlers/mailbox-bindings.ts +0 -111
  216. package/src/handlers/mailbox-rename-refusal.test.ts +0 -247
  217. package/src/handlers/mailbox-settled-target.test.ts +0 -251
  218. package/src/handlers/mailbox.test.ts +0 -280
  219. package/src/handlers/mailbox.ts +0 -581
  220. package/src/handlers/me.test.ts +0 -81
  221. package/src/handlers/me.ts +0 -203
  222. package/src/handlers/message-read-backfill.test.ts +0 -103
  223. package/src/handlers/message.test.ts +0 -131
  224. package/src/handlers/message.ts +0 -1131
  225. package/src/handlers/organize.test.ts +0 -277
  226. package/src/handlers/organize.ts +0 -197
  227. package/src/handlers/outbox-attachment.test.ts +0 -765
  228. package/src/handlers/outbox-attachment.ts +0 -126
  229. package/src/handlers/outbox-list.test.ts +0 -179
  230. package/src/handlers/outbox.test.ts +0 -772
  231. package/src/handlers/outbox.ts +0 -258
  232. package/src/handlers/search.test.ts +0 -161
  233. package/src/handlers/search.ts +0 -105
  234. package/src/handlers/sync-progress.test.ts +0 -205
  235. package/src/handlers/sync-progress.ts +0 -99
  236. package/src/handlers/sync.test.ts +0 -168
  237. package/src/handlers/sync.ts +0 -118
  238. package/src/handlers/system-update.test.ts +0 -497
  239. package/src/handlers/system-update.ts +0 -230
  240. package/src/handlers/thread.test.ts +0 -396
  241. package/src/handlers/thread.ts +0 -427
  242. package/src/handlers/unified-threads-mail-sources.sqlite.test.ts +0 -197
  243. package/src/handlers/unified-threads.test.ts +0 -785
  244. package/src/handlers/unified-threads.ts +0 -669
  245. package/src/index.test.ts +0 -83
  246. package/src/index.ts +0 -228
  247. package/src/jwt-auth.test.ts +0 -152
  248. package/src/jwt-auth.ts +0 -132
  249. package/src/log-redaction.test.ts +0 -144
  250. package/src/openapi-spec.test.ts +0 -118
  251. package/src/request-context.test.ts +0 -61
  252. package/src/request-context.ts +0 -33
  253. package/src/request-pipeline.test.ts +0 -88
  254. package/src/request.ts +0 -10
  255. package/src/response.test.ts +0 -130
  256. package/src/response.ts +0 -144
  257. package/src/service/compose-sqlite.ts +0 -98
  258. package/src/service/config-import.ts +0 -39
  259. package/src/service/create-remit-client.ts +0 -522
  260. package/src/service/data-client.test.ts +0 -97
  261. package/src/service/data-client.ts +0 -58
  262. package/src/service/export-identity.ts +0 -39
  263. package/src/service/filter.ts +0 -40
  264. package/src/service/fire-and-forget.test.ts +0 -126
  265. package/src/service/fire-and-forget.ts +0 -79
  266. package/src/service/localhost-env-config.test.ts +0 -36
  267. package/src/service/organize-queue.ts +0 -98
  268. package/src/service/organize.test.ts +0 -1451
  269. package/src/service/organize.ts +0 -1025
  270. package/src/service/read-path-filter-config.test.ts +0 -243
  271. package/src/service/semantic-capability.test.ts +0 -78
  272. package/src/service/semantic-capability.ts +0 -95
  273. package/src/service/sender-category.test.ts +0 -235
  274. package/src/service/sqs.ts +0 -4
  275. package/src/service/trigger-sync.test.ts +0 -205
  276. package/src/service/trigger-sync.ts +0 -100
  277. package/src/stdout-capture-fixture.ts +0 -40
  278. package/src/types.ts +0 -271
  279. package/tsconfig.json +0 -7
@@ -1,277 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { afterEach, describe, it, mock } from "node:test";
3
- import type { SendMessageCommand } from "@aws-sdk/client-sqs";
4
- import type { OrganizeInput } from "@remit/api-openapi-types";
5
- import type {
6
- CreateOrganizeJobRequestInput,
7
- FilterItem,
8
- IAccountRepository,
9
- IOrganizeJobRequestRepository,
10
- OrganizeJobRequestItem,
11
- } from "@remit/data-ports";
12
- import { BadRequestError, NotFoundError } from "@remit/data-ports/errors";
13
- import { FilterMatchOperator } from "@remit/domain-enums";
14
- import type { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
15
- import type { Context } from "openapi-backend";
16
- import { deriveAccountConfigId } from "../auth.js";
17
- import { handleError } from "../error.js";
18
- import { formatResponse } from "../response.js";
19
- import {
20
- _resetForTest,
21
- type RemitClient,
22
- setClient,
23
- } from "../service/data-client.js";
24
- import { sqsClient } from "../service/sqs.js";
25
- import { OrganizeOperations, predicateFromInput } from "./organize.js";
26
-
27
- const input = (over: Partial<OrganizeInput> = {}): OrganizeInput => ({
28
- matchOperator: FilterMatchOperator.And,
29
- literalClauses: [],
30
- actionLabelId: "None",
31
- actionMailboxId: "None",
32
- ...over,
33
- });
34
-
35
- // A move back-apply is accepted end to end: createOrganizeJob and
36
- // previewOrganize no longer reject `actionMailboxId` up front (the removed
37
- // label-only 400). Both endpoints flatten the request into the predicate the
38
- // job row and the matcher share, so the proof of acceptance is that the move
39
- // action survives that mapping verbatim — the worker then applies it through
40
- // the wired placement mover (see service/organize.test.ts).
41
- describe("predicateFromInput (move back-apply accepted)", () => {
42
- it("carries a requested move action through to the predicate", () => {
43
- const predicate = predicateFromInput(
44
- input({ actionMailboxId: "mbox-target" }),
45
- );
46
- assert.equal(predicate.actionMailboxId, "mbox-target");
47
- assert.equal(predicate.actionLabelId, "None");
48
- });
49
-
50
- it("carries a combined move + label action through to the predicate", () => {
51
- const predicate = predicateFromInput(
52
- input({ actionLabelId: "lbl-1", actionMailboxId: "mbox-target" }),
53
- );
54
- assert.equal(predicate.actionMailboxId, "mbox-target");
55
- assert.equal(predicate.actionLabelId, "lbl-1");
56
- });
57
-
58
- it("preserves the None sentinel for an absent action", () => {
59
- const predicate = predicateFromInput(input());
60
- assert.equal(predicate.actionMailboxId, "None");
61
- assert.equal(predicate.actionLabelId, "None");
62
- });
63
- });
64
-
65
- // The matcher returns a body-content (HasWords) refusal as a result (see
66
- // service/organize.test.ts); previewOrganize is the boundary that words it as a
67
- // BadRequestError. Proving the 4xx actually reaches the wire — not just that the
68
- // right class is raised — means proving the shared error handler maps it, since
69
- // a plain Error would otherwise fall through to a 500 (reader #457).
70
- describe("previewOrganize rejected-rule response (reader #457)", () => {
71
- it("maps a rejected HasWords clause to a 400 naming the reason, not a 500", async () => {
72
- const error = new BadRequestError(
73
- "Organize literal matching cannot evaluate a body-content (HasWords) clause without the vector pipeline — it requires the semantic widen path",
74
- );
75
-
76
- const response = await handleError(error);
77
-
78
- assert.equal(response.statusCode, 400);
79
- assert.match(JSON.parse(response.body).message, /HasWords/);
80
- });
81
- });
82
-
83
- const SUB = "cognito-sub-995";
84
- const ACCOUNT_CONFIG_ID = deriveAccountConfigId(SUB);
85
- const ACCOUNT_ID = "acc-995";
86
-
87
- const createdRows: CreateOrganizeJobRequestInput[] = [];
88
- const enqueued: SendMessageCommand[] = [];
89
-
90
- const installClient = (): void => {
91
- createdRows.length = 0;
92
- setClient({
93
- account: {
94
- get: async () => ({
95
- accountId: ACCOUNT_ID,
96
- accountConfigId: ACCOUNT_CONFIG_ID,
97
- }),
98
- } as unknown as IAccountRepository,
99
- organizeJobRequest: {
100
- create: async (input: CreateOrganizeJobRequestInput) => {
101
- createdRows.push(input);
102
- return {
103
- ...input,
104
- organizeJobId: `job-${createdRows.length}`,
105
- state: "Pending",
106
- } as unknown as OrganizeJobRequestItem;
107
- },
108
- } as unknown as IOrganizeJobRequestRepository,
109
- } as unknown as RemitClient);
110
- };
111
-
112
- const authorizedEvent = (): APIGatewayProxyEvent =>
113
- ({
114
- body: null,
115
- requestContext: { authorizer: { claims: { sub: SUB } } },
116
- }) as unknown as APIGatewayProxyEvent;
117
-
118
- const createJob = OrganizeOperations.OrganizeOperations_createOrganizeJob as (
119
- context: Context,
120
- event: APIGatewayProxyEvent,
121
- ) => Promise<Record<string, unknown>>;
122
-
123
- /** The response the browser receives, error funnel included. */
124
- const postOrganize = async (
125
- body: OrganizeInput,
126
- ): Promise<APIGatewayProxyResult> => {
127
- const context = {
128
- request: { params: { accountId: ACCOUNT_ID }, requestBody: body },
129
- } as unknown as Context;
130
- return createJob(context, authorizedEvent()).then(
131
- (response) => formatResponse(response),
132
- (error: unknown) => handleError(error),
133
- );
134
- };
135
-
136
- // A rule the matcher can never honour — a body-content clause with no anchor to
137
- // widen from — is refused on the request instead of accepted with a 202 for a
138
- // job the worker can only fail (reader #463, #995). The contract now declares
139
- // the 400, so the proof is the response the client gets plus the absence of the
140
- // two side effects a 202 promises: a job row and a queued message.
141
- describe("createOrganizeJob rejected-rule refusal (reader #995)", () => {
142
- afterEach(() => {
143
- mock.restoreAll();
144
- _resetForTest();
145
- });
146
-
147
- const withStubbedQueue = (): void => {
148
- process.env.SQS_QUEUE_URL_ACCOUNT_FANOUT =
149
- "http://localhost:9324/queue/account-fanout-test";
150
- enqueued.length = 0;
151
- mock.method(sqsClient, "send", async (command: SendMessageCommand) => {
152
- enqueued.push(command);
153
- return {};
154
- });
155
- installClient();
156
- };
157
-
158
- it("refuses an anchorless body-content clause with a 400 and creates nothing", async () => {
159
- withStubbedQueue();
160
-
161
- const response = await postOrganize(
162
- input({ literalClauses: [{ field: "HasWords", value: "invoice" }] }),
163
- );
164
-
165
- assert.equal(response.statusCode, 400);
166
- assert.match(JSON.parse(response.body).message, /HasWords/);
167
- assert.deepEqual(createdRows, []);
168
- assert.deepEqual(enqueued, []);
169
- });
170
-
171
- it("accepts the same clause when an anchor gives the widen something to run on", async () => {
172
- withStubbedQueue();
173
-
174
- const response = await postOrganize(
175
- input({
176
- anchorMessageId: "msg-anchor",
177
- literalClauses: [{ field: "HasWords", value: "invoice" }],
178
- }),
179
- );
180
-
181
- assert.equal(response.statusCode, 202);
182
- assert.equal(createdRows.length, 1);
183
- assert.equal(enqueued.length, 1);
184
- assert.match(
185
- String(enqueued[0]?.input.MessageBody),
186
- new RegExp(String(JSON.parse(response.body).organizeJobId)),
187
- );
188
- });
189
- });
190
-
191
- describe("createOrganizeJob by filterId — Run now (#1354)", () => {
192
- afterEach(() => {
193
- mock.restoreAll();
194
- _resetForTest();
195
- });
196
-
197
- const standing = (state: FilterItem["state"]): FilterItem => ({
198
- filterId: "flt-1",
199
- accountConfigId: ACCOUNT_CONFIG_ID,
200
- name: "Invoices",
201
- scope: "Standing",
202
- state,
203
- disabledReason: state === "Active" ? "None" : "UserDisabled",
204
- hasAnchor: false,
205
- ruleChangedAt: 1,
206
- actionChangedAt: 1,
207
- matchOperator: FilterMatchOperator.And,
208
- literalClauses: [{ field: "From", value: "billing@example.com" }],
209
- actionLabelId: "None",
210
- actionMailboxId: "mbx-invoices",
211
- createdAt: 0,
212
- updatedAt: 0,
213
- });
214
-
215
- const withFilter = (filter: FilterItem): void => {
216
- process.env.SQS_QUEUE_URL_ACCOUNT_FANOUT =
217
- "http://localhost:9324/queue/account-fanout-test";
218
- enqueued.length = 0;
219
- createdRows.length = 0;
220
- mock.method(sqsClient, "send", async (command: SendMessageCommand) => {
221
- enqueued.push(command);
222
- return {};
223
- });
224
- setClient({
225
- account: {
226
- get: async () => ({
227
- accountId: ACCOUNT_ID,
228
- accountConfigId: ACCOUNT_CONFIG_ID,
229
- }),
230
- },
231
- filter: {
232
- get: async () => filter,
233
- },
234
- organizeJobRequest: {
235
- create: async (row: CreateOrganizeJobRequestInput) => {
236
- createdRows.push(row);
237
- return { ...row, organizeJobId: "job-run", state: "Pending" };
238
- },
239
- },
240
- } as unknown as RemitClient);
241
- };
242
-
243
- it("queues a job that names only the filter", async () => {
244
- withFilter(standing("Active"));
245
-
246
- const response = await postOrganize(input({ filterId: "flt-1" }));
247
-
248
- assert.equal(response.statusCode, 202);
249
- assert.equal(createdRows[0]?.filterId, "flt-1");
250
- assert.equal(createdRows[0]?.actionMailboxId, "None");
251
- assert.deepEqual(createdRows[0]?.literalClauses, []);
252
- assert.equal(enqueued.length, 1);
253
- });
254
-
255
- it("answers an unknown filter with a 404 and queues nothing", async () => {
256
- withFilter(standing("Active"));
257
- setClient({
258
- account: {
259
- get: async () => ({
260
- accountId: ACCOUNT_ID,
261
- accountConfigId: ACCOUNT_CONFIG_ID,
262
- }),
263
- },
264
- filter: {
265
- get: async () => {
266
- throw new NotFoundError("Filter not found: flt-gone");
267
- },
268
- },
269
- } as unknown as RemitClient);
270
-
271
- const response = await postOrganize(input({ filterId: "flt-gone" }));
272
-
273
- assert.equal(response.statusCode, 404);
274
- assert.deepEqual(createdRows, []);
275
- assert.deepEqual(enqueued, []);
276
- });
277
- });
@@ -1,197 +0,0 @@
1
- import type {
2
- CreateOrganizeJobResponse,
3
- OrganizeInput,
4
- OrganizeJobResponse,
5
- OrganizePreviewResponse,
6
- } from "@remit/api-openapi-types";
7
- import { BadRequestError, NotFoundError } from "@remit/data-ports/errors";
8
- import type { APIGatewayProxyEvent } from "aws-lambda";
9
- import type { Context } from "openapi-backend";
10
- import { getAccountConfigIdFromEvent, getSubFromEvent } from "../auth.js";
11
- import { getClient, type RemitClient } from "../service/data-client.js";
12
- import {
13
- buildOrganizeMatchDeps,
14
- matchOrganize,
15
- ORGANIZE_MATCH_LIMIT,
16
- type OrganizePredicate,
17
- organizePredicateRejection,
18
- } from "../service/organize.js";
19
- import {
20
- type OrganizeJobRequest,
21
- queueOrganizeJob,
22
- } from "../service/organize-queue.js";
23
- import type {
24
- OperationHandler,
25
- OrganizeJobDetailOperationIds,
26
- OrganizeOperationIds,
27
- } from "../types.js";
28
- import { assertAccountOwnership } from "./account-ownership.js";
29
-
30
- const NONE = "None";
31
-
32
- /**
33
- * Normalize the request body into the flattened predicate the job row and the
34
- * matcher share. `anchorMessageId` collapses to the `"None"` sentinel when
35
- * absent, and `similarityThreshold` to the server default — the persisted entity
36
- * carries no optional fields (RFC 032).
37
- */
38
- export const predicateFromInput = (
39
- input: OrganizeInput,
40
- ): OrganizePredicate => ({
41
- anchorMessageId: input.anchorMessageId ?? NONE,
42
- matchOperator: input.matchOperator,
43
- literalClauses: input.literalClauses,
44
- similarityThreshold: input.similarityThreshold ?? 0.75,
45
- actionLabelId: input.actionLabelId,
46
- actionMailboxId: input.actionMailboxId,
47
- });
48
-
49
- const assertAccount = async (
50
- client: RemitClient,
51
- accountId: string,
52
- accountConfigId: string,
53
- mode: "read" | "act",
54
- ): Promise<void> => {
55
- const account = await client.account.get(accountId);
56
- assertAccountOwnership(account, accountConfigId, mode);
57
- };
58
-
59
- const toOrganizeJobResponse = (
60
- job: Awaited<ReturnType<RemitClient["organizeJobRequest"]["get"]>>,
61
- ): OrganizeJobResponse => ({
62
- organizeJobId: job.organizeJobId,
63
- accountConfigId: job.accountConfigId,
64
- userId: job.userId,
65
- state: job.state,
66
- filterId: job.filterId,
67
- anchorMessageId: job.anchorMessageId,
68
- matchOperator: job.matchOperator,
69
- literalClauses: job.literalClauses,
70
- similarityThreshold: job.similarityThreshold,
71
- actionLabelId: job.actionLabelId,
72
- actionMailboxId: job.actionMailboxId,
73
- matchedCount: job.matchedCount,
74
- appliedCount: job.appliedCount,
75
- failedCount: job.failedCount,
76
- errorMessage: job.errorMessage,
77
- createdAt: job.createdAt,
78
- updatedAt: job.updatedAt,
79
- });
80
-
81
- /**
82
- * What a create asks the worker to run. A saved filter is named and read when
83
- * the job runs, so Run now and a filter's create share one path (#1354); an
84
- * "all like these" predicate the matcher can never honour is answered here,
85
- * not with a 202 the worker has to fail later (reader #463).
86
- */
87
- const requestedJob = async (
88
- client: RemitClient,
89
- owner: { accountConfigId: string; userId: string },
90
- input: OrganizeInput,
91
- ): Promise<OrganizeJobRequest> => {
92
- if (input.filterId) {
93
- await client.filter.get(owner.accountConfigId, input.filterId);
94
- return { ...owner, filterId: input.filterId };
95
- }
96
- const predicate = predicateFromInput(input);
97
- const rejection = organizePredicateRejection(predicate);
98
- if (rejection) throw new BadRequestError(rejection.message);
99
- return { ...owner, predicate };
100
- };
101
-
102
- export const OrganizeOperations: Record<
103
- OrganizeOperationIds,
104
- OperationHandler<OrganizeOperationIds>
105
- > = {
106
- OrganizeOperations_createOrganizeJob: async (
107
- context: Context,
108
- ...args: unknown[]
109
- ): Promise<CreateOrganizeJobResponse> => {
110
- const event = args[0] as APIGatewayProxyEvent;
111
- const accountConfigId = getAccountConfigIdFromEvent(event);
112
- const { accountId } = context.request.params as { accountId: string };
113
- const input = context.request.requestBody as OrganizeInput;
114
-
115
- const userId = getSubFromEvent(event);
116
- if (!userId) {
117
- throw new Error(
118
- "Missing Cognito `sub`: cannot attribute an organize job to a user",
119
- );
120
- }
121
-
122
- const client = await getClient();
123
- await assertAccount(client, accountId, accountConfigId, "act");
124
-
125
- const job = await queueOrganizeJob(
126
- client,
127
- await requestedJob(client, { accountConfigId, userId }, input),
128
- );
129
-
130
- return {
131
- statusCode: 202,
132
- organizeJobId: job.organizeJobId,
133
- state: job.state,
134
- };
135
- },
136
-
137
- OrganizeOperations_previewOrganize: async (
138
- context: Context,
139
- ...args: unknown[]
140
- ): Promise<OrganizePreviewResponse> => {
141
- const event = args[0] as APIGatewayProxyEvent;
142
- const accountConfigId = getAccountConfigIdFromEvent(event);
143
- const { accountId } = context.request.params as { accountId: string };
144
- const input = context.request.requestBody as OrganizeInput;
145
-
146
- const client = await getClient();
147
- await assertAccount(client, accountId, accountConfigId, "read");
148
-
149
- if (input.filterId) {
150
- throw new BadRequestError(
151
- "Preview takes a rule, not a saved filter. Run the filter to apply it.",
152
- );
153
- }
154
- const result = await matchOrganize(
155
- buildOrganizeMatchDeps(client),
156
- accountConfigId,
157
- predicateFromInput(input),
158
- ORGANIZE_MATCH_LIMIT,
159
- );
160
- if (result.rejected) throw new BadRequestError(result.rejected.message);
161
-
162
- const response: OrganizePreviewResponse = {
163
- matchedCount: result.messageIds.length,
164
- messageIds: result.messageIds,
165
- };
166
- if (result.semanticUnavailable) response.semanticUnavailable = true;
167
- if (result.semanticIndexEmpty) response.semanticIndexEmpty = true;
168
- return response;
169
- },
170
- };
171
-
172
- export const OrganizeJobDetailOperations: Record<
173
- OrganizeJobDetailOperationIds,
174
- OperationHandler<OrganizeJobDetailOperationIds>
175
- > = {
176
- OrganizeJobDetailOperations_getOrganizeJob: async (
177
- context: Context,
178
- ...args: unknown[]
179
- ): Promise<OrganizeJobResponse> => {
180
- const event = args[0] as APIGatewayProxyEvent;
181
- const accountConfigId = getAccountConfigIdFromEvent(event);
182
- const { accountId, organizeJobId } = context.request.params as {
183
- accountId: string;
184
- organizeJobId: string;
185
- };
186
-
187
- const client = await getClient();
188
- await assertAccount(client, accountId, accountConfigId, "read");
189
-
190
- const job = await client.organizeJobRequest.get(organizeJobId);
191
- if (job.accountConfigId !== accountConfigId) {
192
- throw new NotFoundError(`Organize job not found: ${organizeJobId}`);
193
- }
194
-
195
- return toOrganizeJobResponse(job);
196
- },
197
- };