@opencrvs/toolkit 2.2.0-rc.045257f → 2.2.0-rc.19ec10b

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 (84) hide show
  1. package/build.sh +7 -2
  2. package/dist/application-config/index.js +16 -5
  3. package/dist/authentication/index.d.ts +1 -1
  4. package/dist/authentication/index.js +4 -8
  5. package/dist/cli.js +927 -356
  6. package/dist/commons/api/router.d.ts +17 -4
  7. package/dist/commons/application-config/index.d.ts +1 -1
  8. package/dist/commons/conditionals/conditionals.d.ts +55 -4
  9. package/dist/commons/conditionals/validate.d.ts +1 -1
  10. package/dist/commons/events/ActionStatus.d.ts +2 -2
  11. package/dist/commons/events/ActionType.d.ts +2 -0
  12. package/dist/commons/events/AdvancedSearchConfig.d.ts +3 -0
  13. package/dist/commons/events/Draft.d.ts +34 -1
  14. package/dist/commons/events/EventConfig.d.ts +446 -0
  15. package/dist/commons/events/EventDocument.d.ts +2 -0
  16. package/dist/commons/events/EventIndex.d.ts +1 -0
  17. package/dist/commons/events/EventInput.d.ts +1 -0
  18. package/dist/commons/events/EventMetadata.d.ts +1 -0
  19. package/dist/commons/events/FieldTypeMapping.d.ts +19 -19
  20. package/dist/commons/events/PlainDate.d.ts +5 -0
  21. package/dist/commons/events/defineConfig.d.ts +7 -2
  22. package/dist/commons/events/event.d.ts +20 -1
  23. package/dist/commons/events/field.d.ts +37 -0
  24. package/dist/commons/events/locations.d.ts +1 -1
  25. package/dist/commons/events/scopes.d.ts +2 -1
  26. package/dist/commons/events/state/index.d.ts +1 -0
  27. package/dist/commons/events/test.utils.d.ts +59 -6
  28. package/dist/commons/events/utils.d.ts +28 -2
  29. package/dist/commons/users/Role.d.ts +23 -0
  30. package/dist/commons/users/User.d.ts +263 -0
  31. package/dist/commons/users/authentication.d.ts +67 -0
  32. package/dist/commons/users/index.d.ts +5 -0
  33. package/dist/commons/users/roleValidations.d.ts +15 -0
  34. package/dist/commons/users/scopes.d.ts +1402 -0
  35. package/dist/commons/users/userReferences.d.ts +176 -0
  36. package/dist/conditionals/index.js +13 -5
  37. package/dist/environment/custom-types.d.ts +1 -0
  38. package/dist/environment/custom-types.d.ts.map +1 -1
  39. package/dist/environment/derived-variables.d.ts +8 -0
  40. package/dist/environment/derived-variables.d.ts.map +1 -1
  41. package/dist/environment/derived-variables.js +9 -0
  42. package/dist/environment/questions.d.ts +42 -9
  43. package/dist/environment/questions.d.ts.map +1 -1
  44. package/dist/environment/questions.js +70 -47
  45. package/dist/environment/registry.d.ts +15 -0
  46. package/dist/environment/registry.d.ts.map +1 -0
  47. package/dist/environment/registry.js +112 -0
  48. package/dist/environment/setup-environment.d.ts.map +1 -1
  49. package/dist/environment/setup-environment.js +104 -23
  50. package/dist/events/index.js +1627 -1100
  51. package/dist/migrations/add-notify-config.d.ts +40 -0
  52. package/dist/migrations/add-notify-config.d.ts.map +1 -0
  53. package/dist/migrations/add-notify-config.js +249 -0
  54. package/dist/migrations/index.d.ts.map +1 -1
  55. package/dist/migrations/index.js +602 -143
  56. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -1
  57. package/dist/migrations/move-declaration-to-declare-action.js +27 -144
  58. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -1
  59. package/dist/migrations/read-declaration-through-helper.js +3 -61
  60. package/dist/migrations/resolve-versioned-event-config.d.ts +56 -0
  61. package/dist/migrations/resolve-versioned-event-config.d.ts.map +1 -0
  62. package/dist/migrations/resolve-versioned-event-config.js +353 -0
  63. package/dist/migrations/utils.d.ts +61 -0
  64. package/dist/migrations/utils.d.ts.map +1 -0
  65. package/dist/migrations/utils.js +218 -0
  66. package/dist/notification/index.js +707 -119
  67. package/dist/roles/index.d.ts +2 -0
  68. package/dist/roles/index.d.ts.map +1 -0
  69. package/dist/roles/index.js +730 -0
  70. package/dist/scopes/index.d.ts +0 -10
  71. package/dist/scopes/index.js +3 -7
  72. package/dist/templates/charts-values/dependencies/values.yaml +5 -2
  73. package/dist/templates/charts-values/opencrvs-services/values.yaml +2 -5
  74. package/dist/verify/endpoints.d.ts +11 -0
  75. package/dist/verify/endpoints.d.ts.map +1 -1
  76. package/dist/verify/endpoints.js +21 -27
  77. package/opencrvs-toolkit-2.2.0-rc.19ec10b.tgz +0 -0
  78. package/package.json +4 -2
  79. package/tsconfig.build.tsbuildinfo +1 -1
  80. package/tsconfig.json +3 -5
  81. package/dist/environment/dockerhub.d.ts +0 -15
  82. package/dist/environment/dockerhub.d.ts.map +0 -1
  83. package/dist/environment/dockerhub.js +0 -104
  84. package/opencrvs-toolkit-2.2.0-rc.045257f.tgz +0 -0
@@ -88,6 +88,7 @@ __export(events_exports, {
88
88
  CustomFieldValue: () => CustomFieldValue,
89
89
  CustomFlag: () => CustomFlag,
90
90
  DEFAULT_DATE_OF_EVENT_PROPERTY: () => DEFAULT_DATE_OF_EVENT_PROPERTY,
91
+ DEFAULT_EFFECTIVE_FROM: () => DEFAULT_EFFECTIVE_FROM,
91
92
  DEFAULT_PLACE_OF_EVENT_PROPERTY: () => DEFAULT_PLACE_OF_EVENT_PROPERTY,
92
93
  DOCUMENT_DELETE_SCOPES: () => DOCUMENT_DELETE_SCOPES,
93
94
  DataEntry: () => DataEntry,
@@ -117,7 +118,7 @@ __export(events_exports, {
117
118
  EmailField: () => EmailField,
118
119
  EmailValue: () => EmailValue,
119
120
  EnableConditional: () => EnableConditional,
120
- EventConfig: () => EventConfig,
121
+ EventConfig: () => EventConfig2,
121
122
  EventDocument: () => EventDocument,
122
123
  EventDocumentOnlyLastAction: () => EventDocumentOnlyLastAction,
123
124
  EventFieldConfigSchema: () => EventFieldConfigSchema,
@@ -161,6 +162,7 @@ __export(events_exports, {
161
162
  HiddenFieldValue: () => HiddenFieldValue,
162
163
  HttpFieldUpdateValue: () => HttpFieldUpdateValue,
163
164
  HttpFieldValue: () => HttpFieldValue,
165
+ INITIAL_EVENT_CONFIG_VERSION_ID: () => INITIAL_EVENT_CONFIG_VERSION_ID,
164
166
  IdReaderFieldValue: () => IdReaderFieldValue,
165
167
  ImageMimeType: () => ImageMimeType,
166
168
  InactiveOfficeError: () => InactiveOfficeError,
@@ -208,6 +210,7 @@ __export(events_exports, {
208
210
  RejectCorrectionActionInput: () => RejectCorrectionActionInput,
209
211
  RejectDeclarationActionInput: () => RejectDeclarationActionInput,
210
212
  RejectedCorrectionAction: () => RejectedCorrectionAction,
213
+ RemoteDraft: () => RemoteDraft,
211
214
  RequestCorrectionActionInput: () => RequestCorrectionActionInput,
212
215
  RevokeRegistrationActionInput: () => RevokeRegistrationActionInput,
213
216
  SearchQuery: () => SearchQuery,
@@ -247,6 +250,7 @@ __export(events_exports, {
247
250
  VerificationActionConfig: () => VerificationActionConfig,
248
251
  VerificationPageConfig: () => VerificationPageConfig,
249
252
  VerificationStatusValue: () => VerificationStatusValue,
253
+ VersionedEventConfig: () => VersionedEventConfig2,
250
254
  WithdrawAdministrativeAreaVersionPayload: () => WithdrawAdministrativeAreaVersionPayload,
251
255
  WithdrawLocationVersionPayload: () => WithdrawLocationVersionPayload,
252
256
  Within: () => Within,
@@ -276,6 +280,7 @@ __export(events_exports, {
276
280
  areConditionsMet: () => areConditionsMet,
277
281
  buildClientFunctionContext: () => buildClientFunctionContext,
278
282
  buildFormState: () => buildFormState,
283
+ byEffectiveFrom: () => byEffectiveFrom,
279
284
  canAccessEventWithScope: () => canAccessEventWithScope,
280
285
  canAccessOtherUserWithScopes: () => canAccessOtherUserWithScopes,
281
286
  canAccessUserWithScope: () => canAccessUserWithScope,
@@ -313,6 +318,8 @@ __export(events_exports, {
313
318
  filterActionsByFlags: () => filterActionsByFlags,
314
319
  findActiveDraftForEvent: () => findActiveDraftForEvent,
315
320
  findAllFields: () => findAllFields,
321
+ findConfigVersion: () => findConfigVersion,
322
+ findEventConfigForRecord: () => findEventConfigForRecord,
316
323
  findLastAssignmentAction: () => findLastAssignmentAction,
317
324
  findPendingCorrectionAction: () => findPendingCorrectionAction,
318
325
  findRecordActionPages: () => findRecordActionPages,
@@ -321,6 +328,7 @@ __export(events_exports, {
321
328
  flattenFormState: () => flattenFormState,
322
329
  generateActionDeclarationInput: () => generateActionDeclarationInput,
323
330
  generateActionDocument: () => generateActionDocument,
331
+ generateActionDocuments: () => generateActionDocuments,
324
332
  generateActionDuplicateDeclarationInput: () => generateActionDuplicateDeclarationInput,
325
333
  generateEventConfig: () => generateEventConfig,
326
334
  generateEventDocument: () => generateEventDocument,
@@ -353,17 +361,22 @@ __export(events_exports, {
353
361
  getCompleteActionAnnotation: () => getCompleteActionAnnotation,
354
362
  getCompleteActionContent: () => getCompleteActionContent,
355
363
  getCompleteActionDeclaration: () => getCompleteActionDeclaration,
364
+ getConfigVersion: () => getConfigVersion,
356
365
  getCurrentEventState: () => getCurrentEventState,
357
366
  getCustomActionFields: () => getCustomActionFields,
358
367
  getDeclaration: () => getDeclaration,
359
368
  getDeclarationAfterEachAction: () => getDeclarationAfterEachAction,
360
369
  getDeclarationFieldById: () => getDeclarationFieldById,
361
370
  getDeclarationFields: () => getDeclarationFields,
371
+ getDeclarationFieldsOfAllVersions: () => getDeclarationFieldsOfAllVersions,
362
372
  getDeclarationPages: () => getDeclarationPages,
363
373
  getDeclarationWithPendingAction: () => getDeclarationWithPendingAction,
364
374
  getEventConfigById: () => getEventConfigById,
375
+ getEventConfigForRecord: () => getEventConfigForRecord,
376
+ getEventConfigOfVersion: () => getEventConfigOfVersion,
365
377
  getEventFlags: () => getEventFlags,
366
378
  getEventValidatorContext: () => getEventValidatorContext,
379
+ getEventWithCompleteAcceptedActions: () => getEventWithCompleteAcceptedActions,
367
380
  getFilePathsFromEvent: () => getFilePathsFromEvent,
368
381
  getLeafAdministrativeAreaIds: () => getLeafAdministrativeAreaIds,
369
382
  getLocationHierarchy: () => getLocationHierarchy,
@@ -375,11 +388,13 @@ __export(events_exports, {
375
388
  getRandomDate: () => getRandomDate,
376
389
  getStatusFromActions: () => getStatusFromActions,
377
390
  getValidatorsForField: () => getValidatorsForField,
391
+ getVersionsInEffect: () => getVersionsInEffect,
378
392
  getVisibleVerificationPageIds: () => getVisibleVerificationPageIds,
379
393
  hasActiveExternalIdOnOrAfter: () => hasActiveExternalIdOnOrAfter,
380
394
  hasAnyOfScopes: () => hasAnyOfScopes,
381
395
  isActionAvailable: () => isActionAvailable,
382
396
  isActionConfigType: () => isActionConfigType,
397
+ isActionDateReference: () => isActionDateReference,
383
398
  isActionDocument: () => isActionDocument,
384
399
  isActionEnabled: () => isActionEnabled,
385
400
  isActionInScope: () => isActionInScope,
@@ -474,6 +489,10 @@ __export(events_exports, {
474
489
  plainDateToLocalDate: () => plainDateToLocalDate,
475
490
  precompileActionSchemas: () => precompileActionSchemas,
476
491
  resolveDateOfEvent: () => resolveDateOfEvent,
492
+ resolveEffectiveVersion: () => resolveEffectiveVersion,
493
+ resolveEventConfig: () => resolveEventConfig,
494
+ resolveEventConfigInTimeZone: () => resolveEventConfigInTimeZone,
495
+ resolveEventConfigOnDate: () => resolveEventConfigOnDate,
477
496
  resolveEventCustomFlags: () => resolveEventCustomFlags,
478
497
  resolvePath: () => resolvePath,
479
498
  resolvePlaceOfEvent: () => resolvePlaceOfEvent,
@@ -486,13 +505,18 @@ __export(events_exports, {
486
505
  timePeriodToDateRange: () => timePeriodToDateRange,
487
506
  toClientAdministrativeArea: () => toClientAdministrativeArea,
488
507
  toClientLocation: () => toClientLocation,
508
+ toEventConfig: () => toEventConfig,
489
509
  toNotificationForm: () => toNotificationForm,
490
510
  toNotificationReview: () => toNotificationReview,
491
511
  toPlainDate: () => toPlainDate,
512
+ toPlainDateInTimeZone: () => toPlainDateInTimeZone,
513
+ toVersionedEventConfig: () => toVersionedEventConfig,
492
514
  todayISO: () => todayISO,
493
515
  user: () => user,
494
516
  userCanAccessEventWithScopes: () => userCanAccessEventWithScopes,
495
517
  validate: () => validate,
518
+ validateEachVersion: () => validateEachVersion,
519
+ validateEventConfig: () => validateEventConfig,
496
520
  validateFieldInput: () => validateFieldInput,
497
521
  validateValue: () => validateValue,
498
522
  window: () => window2,
@@ -507,11 +531,11 @@ var import_compile = require("zod/compile");
507
531
  // ../commons/src/events/AuditLog.ts
508
532
  var z9 = __toESM(require("zod/v4"));
509
533
 
510
- // ../commons/src/authentication.ts
534
+ // ../commons/src/users/authentication.ts
511
535
  var import_jwt_decode = __toESM(require("jwt-decode"));
512
536
  var z8 = __toESM(require("zod/v4"));
513
537
 
514
- // ../commons/src/scopes.ts
538
+ // ../commons/src/users/scopes.ts
515
539
  var z7 = __toESM(require("zod/v4"));
516
540
  var qs = __toESM(require("qs"));
517
541
 
@@ -603,7 +627,9 @@ var ActionTypes = z2.enum([
603
627
  "CUSTOM"
604
628
  ]);
605
629
  var ClientSpecificAction = {
606
- REVIEW_CORRECTION_REQUEST: "REVIEW_CORRECTION_REQUEST"
630
+ REVIEW_CORRECTION_REQUEST: "REVIEW_CORRECTION_REQUEST",
631
+ /** Opens the user's declare or notify draft of the event in its own flow */
632
+ CONTINUE_DRAFT: "CONTINUE_DRAFT"
607
633
  };
608
634
  var declarationActionValues = [
609
635
  ActionTypes.enum.DECLARE,
@@ -798,7 +824,7 @@ var EventStatus = z6.enum([
798
824
  "ARCHIVED"
799
825
  ]);
800
826
 
801
- // ../commons/src/scopes.ts
827
+ // ../commons/src/users/scopes.ts
802
828
  var JurisdictionFilter = z7.enum(["administrativeArea", "location", "all"]).describe(
803
829
  "Filters based on user jurisdiction relative to their office location in hierarchy."
804
830
  );
@@ -1130,7 +1156,7 @@ function getAcceptedScopesByType({
1130
1156
  }).filter((scope) => scope !== null);
1131
1157
  }
1132
1158
 
1133
- // ../commons/src/authentication.ts
1159
+ // ../commons/src/users/authentication.ts
1134
1160
  var TokenUserType = z8.enum(["user", "system"]);
1135
1161
  var TokenWithBearer = z8.string().regex(/^Bearer\s/);
1136
1162
 
@@ -1655,6 +1681,26 @@ var isPlainDate = (date) => PlainDate.validate(date);
1655
1681
  function toPlainDate(dateTime) {
1656
1682
  return dateTime.split("T")[0];
1657
1683
  }
1684
+ var dateFormats = /* @__PURE__ */ new Map();
1685
+ function getDateFormat(timeZone) {
1686
+ let format2 = dateFormats.get(timeZone);
1687
+ if (!format2) {
1688
+ format2 = new Intl.DateTimeFormat("en-US", {
1689
+ timeZone,
1690
+ year: "numeric",
1691
+ month: "2-digit",
1692
+ day: "2-digit"
1693
+ });
1694
+ dateFormats.set(timeZone, format2);
1695
+ }
1696
+ return format2;
1697
+ }
1698
+ function toPlainDateInTimeZone(date, timeZone) {
1699
+ const parts = Object.fromEntries(
1700
+ getDateFormat(timeZone).formatToParts(date).map(({ type, value }) => [type, value])
1701
+ );
1702
+ return `${parts.year}-${parts.month}-${parts.day}`;
1703
+ }
1658
1704
  function plainDateToLocalDate(date) {
1659
1705
  const [year, month, day] = date.split("-").map(Number);
1660
1706
  return new Date(year, month - 1, day);
@@ -2096,6 +2142,9 @@ var LegalStatuses = z17.object({
2096
2142
  var EventMetadata = z17.object({
2097
2143
  id: UUID,
2098
2144
  type: z17.string().describe("The type of event, such as birth, death, or marriage."),
2145
+ configVersionId: z17.string().describe(
2146
+ "Id of the event configuration version the record was created under. Records created before versioning have 'initial'."
2147
+ ),
2099
2148
  status: EventStatus,
2100
2149
  legalStatuses: LegalStatuses.describe(
2101
2150
  "Metadata related to the legal registration of the event, such as who registered it and when."
@@ -3736,7 +3785,7 @@ var ActionConfig = z25.discriminatedUnion("type", [
3736
3785
  }),
3737
3786
  NotifyConfig.meta({
3738
3787
  id: "NotifyActionConfig",
3739
- description: "Configuration for the notify action, including the notification form and its review page. When undefined, it is generated using the DeclareActionConfig."
3788
+ description: "Configuration for the notify action: the notification form and its review page. An event without a NOTIFY action cannot be notified."
3740
3789
  }),
3741
3790
  DeclareConfig.meta({
3742
3791
  id: "DeclareActionConfig",
@@ -4004,7 +4053,7 @@ var ReferenceField = BaseField2.extend({
4004
4053
  var Field = BaseField2.extend({
4005
4054
  id: z29.string().describe("Identifier of the summary field."),
4006
4055
  value: TranslationConfig.describe(
4007
- 'Field value template supports variables from configuration (e.g. "{informant.phoneNo} {informant.email}") and EventMetadata (e.g. "{event.legalStatuses.REGISTERED.acceptedAt, date, ::dd MMMM yyyy}").'
4056
+ 'Field value template supports variables from configuration (e.g. "{informant.phoneNo} {informant.email}") and EventMetadata (e.g. "{event.legalStatuses.REGISTERED.acceptedAt, date, ::dd MMMM yyyy}"). "{event.configVersionLabel}" gives the label of the configuration version that the record was created under.'
4008
4057
  ),
4009
4058
  label: TranslationConfig
4010
4059
  }).describe("Custom field defined for the summary view.");
@@ -4099,7 +4148,10 @@ var SearchQueryParams = z30.object({
4099
4148
  }).catchall(FieldValue);
4100
4149
  var FieldConfigSchema = BaseField3.extend({
4101
4150
  fieldId: z30.string(),
4102
- fieldType: z30.literal("field")
4151
+ fieldType: z30.literal("field"),
4152
+ defaultValue: z30.union([z30.boolean(), z30.string(), z30.number()]).optional().describe(
4153
+ `Value the field opens with in advanced search. Omitted or true uses the declaration form's defaultValue, false opens the field empty, and any other value opens it with that value. Only text, number and date fields take a value; every other field type, and date fields searched as a range, only accept true or false.`
4154
+ )
4103
4155
  });
4104
4156
  var EventFieldIdInput = z30.enum([
4105
4157
  "trackingId",
@@ -4148,6 +4200,41 @@ var AdvancedSearchConfig = z30.object({
4148
4200
  description: "Configuration of one advanced search tab. Each tab has a title and a list of searchable fields \u2014 either declaration fields (via `field()`) or event metadata (via `event()`)."
4149
4201
  });
4150
4202
 
4203
+ // ../commons/src/utils.ts
4204
+ var z31 = __toESM(require("zod/v4"));
4205
+ var _ = __toESM(require("lodash"));
4206
+ function getOrThrow(x, message) {
4207
+ if (x === void 0 || x === null) {
4208
+ throw new Error(message);
4209
+ }
4210
+ return x;
4211
+ }
4212
+ function joinValues(values, separator = " ") {
4213
+ return values.filter((value) => !!value).join(separator).trim();
4214
+ }
4215
+ var FullNameV1 = z31.array(
4216
+ z31.object({
4217
+ use: z31.string(),
4218
+ family: z31.string(),
4219
+ given: z31.array(z31.string())
4220
+ })
4221
+ );
4222
+ function omitKeyDeep(obj, keyToRemove) {
4223
+ if (Array.isArray(obj)) {
4224
+ return obj.map((item) => omitKeyDeep(item, keyToRemove));
4225
+ }
4226
+ if (obj === null || typeof obj !== "object") {
4227
+ return obj;
4228
+ }
4229
+ const newObj = {};
4230
+ for (const key of Object.keys(obj)) {
4231
+ if (key !== keyToRemove) {
4232
+ newObj[key] = omitKeyDeep(obj[key], keyToRemove);
4233
+ }
4234
+ }
4235
+ return newObj;
4236
+ }
4237
+
4151
4238
  // ../commons/src/events/utils.ts
4152
4239
  var import_lodash4 = require("lodash");
4153
4240
 
@@ -4157,952 +4244,275 @@ var import_ajv_formats = __toESM(require("ajv-formats"));
4157
4244
  var z34 = __toESM(require("zod/v4"));
4158
4245
  var import_date_fns2 = require("date-fns");
4159
4246
 
4160
- // ../commons/src/events/FieldTypeMapping.ts
4161
- var z32 = __toESM(require("zod/v4"));
4162
-
4163
- // ../commons/src/events/DynamicFieldValue.ts
4164
- var z31 = __toESM(require("zod/v4"));
4165
- function getDynamicNameValue(field3) {
4166
- const nameConfiguration = field3.configuration?.name;
4167
- const firstnameRequired = nameConfiguration?.firstname?.required ?? field3.required;
4168
- const surnameRequired = nameConfiguration?.surname?.required ?? field3.required;
4169
- return z31.object({
4170
- firstname: firstnameRequired ? NonEmptyTextValue : TextValue,
4171
- surname: surnameRequired ? NonEmptyTextValue : TextValue,
4172
- middlename: nameConfiguration?.middlename?.required ? NonEmptyTextValue : TextValue.optional()
4247
+ // ../commons/src/conditionals/conditionals.ts
4248
+ var objectHash = __toESM(require("object-hash"));
4249
+ function defineConditional(schema) {
4250
+ const schemaWithooutIDRef = omitKeyDeep(schema, "$id");
4251
+ return {
4252
+ $id: `https://opencrvs.org/conditionals/${objectHash.sha1(schemaWithooutIDRef)}`,
4253
+ ...schemaWithooutIDRef
4254
+ };
4255
+ }
4256
+ function defineFormConditional(schema) {
4257
+ const schemaWithForm = {
4258
+ type: "object",
4259
+ properties: {
4260
+ $form: schema
4261
+ },
4262
+ required: ["$form"]
4263
+ };
4264
+ return defineConditional(schemaWithForm);
4265
+ }
4266
+ function alwaysTrue() {
4267
+ return {};
4268
+ }
4269
+ function and(...conditions) {
4270
+ return defineConditional({
4271
+ type: "object",
4272
+ allOf: conditions,
4273
+ required: []
4173
4274
  });
4174
4275
  }
4175
- function getDynamicAddressFieldValue(field3) {
4176
- const schema = field3.required ? AddressFieldValue : AddressFieldUpdateValue;
4177
- const configIds = field3.configuration?.streetAddressForm?.map((a) => a.id) ?? [];
4178
- return schema.refine((arg) => {
4179
- if (!arg) {
4180
- return true;
4181
- }
4182
- const submittedKeys = Object.keys(arg.streetLevelDetails ?? {});
4183
- const invalidKeys = submittedKeys.filter((k) => !configIds.includes(k));
4184
- if (invalidKeys.length) {
4185
- console.log(
4186
- "Invalid streetLevelDetails: unknown keys",
4187
- JSON.stringify(invalidKeys, null, 2)
4188
- );
4189
- return false;
4190
- }
4191
- return true;
4276
+ function or(...conditions) {
4277
+ return defineConditional({
4278
+ type: "object",
4279
+ anyOf: conditions,
4280
+ required: []
4192
4281
  });
4193
4282
  }
4194
-
4195
- // ../commons/src/events/FieldTypeMapping.ts
4196
- function mapFieldTypeToZod(field3, actionType) {
4197
- let schema;
4198
- switch (field3.type) {
4199
- case FieldType.FIELD_GROUP: {
4200
- schema = z32.object(
4201
- field3.fields.reduce((acc, subfield) => {
4202
- acc[subfield.id] = mapFieldTypeToZod(subfield, actionType);
4203
- return acc;
4204
- }, {})
4205
- );
4206
- break;
4207
- }
4208
- case FieldType.DATE:
4209
- schema = PlainDate;
4210
- break;
4211
- case FieldType.AGE:
4212
- schema = AgeValue;
4213
- break;
4214
- case FieldType.TIME:
4215
- schema = TimeValue;
4216
- break;
4217
- case FieldType.EMAIL:
4218
- schema = EmailValue;
4219
- break;
4220
- case FieldType.DATE_RANGE:
4221
- schema = DateRangeFieldValue;
4222
- break;
4223
- case FieldType.SELECT_DATE_RANGE:
4224
- schema = SelectDateRangeValue;
4225
- break;
4226
- case FieldType.TEXT:
4227
- case FieldType.TEXTAREA:
4228
- case FieldType.DIVIDER:
4229
- case FieldType.BULLET_LIST:
4230
- case FieldType.PAGE_HEADER:
4231
- case FieldType.LOCATION:
4232
- case FieldType.SELECT:
4233
- case FieldType.COUNTRY:
4234
- case FieldType.RADIO_GROUP:
4235
- case FieldType.PARAGRAPH:
4236
- case FieldType.HEADING:
4237
- case FieldType.IMAGE_VIEW:
4238
- case FieldType.ADMINISTRATIVE_AREA:
4239
- case FieldType.FACILITY:
4240
- case FieldType.OFFICE:
4241
- case FieldType.PHONE:
4242
- case FieldType.LINK_BUTTON:
4243
- case FieldType.VERIFICATION_STATUS:
4244
- case FieldType.ID:
4245
- case FieldType.LOADER:
4246
- case FieldType.ALPHA_HIDDEN:
4247
- case FieldType.USER_ROLE:
4248
- schema = field3.required ? NonEmptyTextValue : TextValue;
4249
- break;
4250
- case FieldType.NUMBER:
4251
- schema = NumberFieldValue;
4252
- break;
4253
- case FieldType.NUMBER_WITH_UNIT:
4254
- schema = field3.required ? NumberWithUnitFieldValue : NumberWithUnitFieldUpdateValue;
4255
- break;
4256
- case FieldType.CHECKBOX:
4257
- schema = CheckboxFieldValue;
4258
- break;
4259
- case FieldType.SIGNATURE:
4260
- case FieldType.FILE:
4261
- schema = FileFieldValue;
4262
- break;
4263
- case FieldType.FILE_WITH_OPTIONS:
4264
- schema = field3.required ? FileFieldWithOptionValue.min(1) : FileFieldWithOptionValue;
4265
- break;
4266
- case FieldType.ADDRESS:
4267
- schema = getDynamicAddressFieldValue(field3);
4268
- break;
4269
- case FieldType.DATA:
4270
- schema = DataFieldValue;
4271
- break;
4272
- case FieldType.NAME:
4273
- schema = actionType === ActionType.NOTIFY ? NameFieldUpdateValue : getDynamicNameValue(field3);
4274
- break;
4275
- case FieldType.BUTTON:
4276
- schema = ButtonFieldValue;
4277
- break;
4278
- case FieldType.ALPHA_PRINT_BUTTON:
4279
- schema = TextValue;
4280
- break;
4281
- case FieldType.AUTOCOMPLETE:
4282
- schema = AutocompleteValue;
4283
- break;
4284
- case FieldType.HTTP:
4285
- case FieldType.SEARCH:
4286
- schema = HttpFieldUpdateValue;
4287
- break;
4288
- case FieldType.QUERY_PARAM_READER:
4289
- schema = QueryParamReaderFieldUpdateValue;
4290
- break;
4291
- case FieldType.QR_READER:
4292
- schema = QrReaderFieldValue;
4293
- break;
4294
- case FieldType.ID_READER:
4295
- schema = IdReaderFieldValue;
4296
- break;
4297
- case FieldType._EXPERIMENTAL_CUSTOM:
4298
- schema = CustomFieldValue;
4299
- break;
4283
+ function not(condition) {
4284
+ return defineConditional({
4285
+ type: "object",
4286
+ not: condition,
4287
+ required: []
4288
+ });
4289
+ }
4290
+ function never2() {
4291
+ return not(alwaysTrue());
4292
+ }
4293
+ function always() {
4294
+ return defineConditional(alwaysTrue());
4295
+ }
4296
+ function jsonFieldPath(field3) {
4297
+ return [field3.$$field, ...field3.$$subfield].join("/");
4298
+ }
4299
+ function wrapToPath(condition, path) {
4300
+ if (path.length === 0) {
4301
+ return condition;
4300
4302
  }
4301
- return field3.required ? schema : schema.nullish();
4303
+ return path.reduceRight((conditionNow, part) => {
4304
+ return {
4305
+ type: "object",
4306
+ properties: {
4307
+ [part]: conditionNow
4308
+ },
4309
+ required: [part]
4310
+ };
4311
+ }, condition);
4302
4312
  }
4303
- function mapFieldTypeToEmptyValue(field3) {
4304
- switch (field3.type) {
4305
- case FieldType.FIELD_GROUP:
4306
- const nestedEmpty = field3.fields.reduce(
4307
- (acc, subfield) => ({
4308
- ...acc,
4309
- [subfield.id]: mapFieldTypeToEmptyValue(subfield)
4310
- }),
4311
- {}
4312
- );
4313
- return nestedEmpty;
4314
- case FieldType.DIVIDER:
4315
- case FieldType.TEXT:
4316
- case FieldType.TEXTAREA:
4317
- case FieldType.BULLET_LIST:
4318
- case FieldType.PAGE_HEADER:
4319
- case FieldType.LOCATION:
4320
- case FieldType.SELECT:
4321
- case FieldType.COUNTRY:
4322
- case FieldType.RADIO_GROUP:
4323
- case FieldType.PARAGRAPH:
4324
- case FieldType.HEADING:
4325
- case FieldType.IMAGE_VIEW:
4326
- case FieldType.ADMINISTRATIVE_AREA:
4327
- case FieldType.FACILITY:
4328
- case FieldType.OFFICE:
4329
- case FieldType.NUMBER:
4330
- case FieldType.NUMBER_WITH_UNIT:
4331
- case FieldType.EMAIL:
4332
- case FieldType.DATE:
4333
- case FieldType.AGE:
4334
- case FieldType.TIME:
4335
- case FieldType.CHECKBOX:
4336
- case FieldType.DATE_RANGE:
4337
- case FieldType.SELECT_DATE_RANGE:
4338
- case FieldType.DATA:
4339
- case FieldType.NAME:
4340
- case FieldType.PHONE:
4341
- case FieldType.BUTTON:
4342
- case FieldType.ALPHA_PRINT_BUTTON:
4343
- case FieldType.HTTP:
4344
- case FieldType.AUTOCOMPLETE:
4345
- case FieldType.SEARCH:
4346
- case FieldType.LINK_BUTTON:
4347
- case FieldType.QUERY_PARAM_READER:
4348
- case FieldType.ID:
4349
- case FieldType.VERIFICATION_STATUS:
4350
- case FieldType.QR_READER:
4351
- case FieldType.ID_READER:
4352
- case FieldType.LOADER:
4353
- case FieldType.ALPHA_HIDDEN:
4354
- case FieldType.USER_ROLE:
4355
- return null;
4356
- case FieldType.ADDRESS:
4357
- return {
4358
- country: "",
4359
- addressType: AddressType.DOMESTIC,
4360
- administrativeArea: "",
4361
- streetLevelDetails: {}
4362
- };
4363
- case FieldType.SIGNATURE:
4364
- case FieldType.FILE:
4365
- return {
4366
- path: "",
4367
- originalFilename: "",
4368
- type: ""
4369
- };
4370
- case FieldType.FILE_WITH_OPTIONS:
4371
- return [];
4372
- case FieldType._EXPERIMENTAL_CUSTOM:
4373
- return void 0;
4374
- }
4375
- }
4376
- var isParagraphFieldType = (field3) => {
4377
- return field3.config.type === FieldType.PARAGRAPH;
4378
- };
4379
- var isHeadingFieldType = (field3) => {
4380
- return field3.config.type === FieldType.HEADING;
4381
- };
4382
- var isImageViewFieldType = (field3) => {
4383
- return field3.config.type === FieldType.IMAGE_VIEW;
4384
- };
4385
- var isDateFieldType = (field3) => {
4386
- return field3.config.type === FieldType.DATE;
4387
- };
4388
- var isAgeFieldType = (field3) => {
4389
- return field3.config.type === FieldType.AGE;
4390
- };
4391
- var isTimeFieldType = (field3) => {
4392
- return field3.config.type === FieldType.TIME;
4393
- };
4394
- var isDateRangeFieldType = (field3) => {
4395
- return field3.config.type === FieldType.DATE_RANGE;
4396
- };
4397
- var isSelectDateRangeFieldType = (field3) => {
4398
- return field3.config.type === FieldType.SELECT_DATE_RANGE;
4399
- };
4400
- var isPageHeaderFieldType = (field3) => {
4401
- return field3.config.type === FieldType.PAGE_HEADER;
4402
- };
4403
- var isTextFieldType = (field3) => {
4404
- return field3.config.type === FieldType.TEXT;
4405
- };
4406
- var isNumberFieldType = (field3) => {
4407
- return field3.config.type === FieldType.NUMBER;
4408
- };
4409
- var isNumberWithUnitFieldType = (field3) => {
4410
- return field3.config.type === FieldType.NUMBER_WITH_UNIT;
4411
- };
4412
- var isNameFieldType = (field3) => {
4413
- return field3.config.type === FieldType.NAME;
4414
- };
4415
- var isPhoneFieldType = (field3) => {
4416
- return field3.config.type === FieldType.PHONE;
4417
- };
4418
- var isIdFieldType = (field3) => {
4419
- return field3.config.type === FieldType.ID;
4420
- };
4421
- var isTextAreaFieldType = (field3) => {
4422
- return field3.config.type === FieldType.TEXTAREA;
4423
- };
4424
- var isSignatureFieldType = (field3) => {
4425
- return field3.config.type === FieldType.SIGNATURE;
4426
- };
4427
- var isEmailFieldType = (field3) => {
4428
- return field3.config.type === FieldType.EMAIL;
4429
- };
4430
- var isFileFieldType = (field3) => {
4431
- return field3.config.type === FieldType.FILE;
4432
- };
4433
- var isFileFieldWithOptionType = (field3) => {
4434
- return field3.config.type === FieldType.FILE_WITH_OPTIONS;
4435
- };
4436
- var isBulletListFieldType = (field3) => {
4437
- return field3.config.type === FieldType.BULLET_LIST;
4438
- };
4439
- var isSelectFieldType = (field3) => {
4440
- return field3.config.type === FieldType.SELECT;
4441
- };
4442
- var isAddressFieldType = (field3) => {
4443
- return field3.config.type === FieldType.ADDRESS;
4444
- };
4445
- var isCountryFieldType = (field3) => {
4446
- return field3.config.type === FieldType.COUNTRY;
4447
- };
4448
- var isCheckboxFieldType = (field3) => {
4449
- return field3.config.type === FieldType.CHECKBOX;
4450
- };
4451
- var isRadioGroupFieldType = (field3) => {
4452
- return field3.config.type === FieldType.RADIO_GROUP;
4453
- };
4454
- var isFieldGroupFieldType = (field3) => {
4455
- return field3.config.type === FieldType.FIELD_GROUP;
4456
- };
4457
- var isLocationFieldType = (field3) => {
4458
- return field3.config.type === FieldType.LOCATION;
4459
- };
4460
- var isDividerFieldType = (field3) => {
4461
- return field3.config.type === FieldType.DIVIDER;
4462
- };
4463
- var isAdministrativeAreaFieldType = (field3) => {
4464
- return field3.config.type === FieldType.ADMINISTRATIVE_AREA;
4465
- };
4466
- var isFacilityFieldType = (field3) => {
4467
- return field3.config.type === FieldType.FACILITY;
4468
- };
4469
- var isOfficeFieldType = (field3) => {
4470
- return field3.config.type === FieldType.OFFICE;
4471
- };
4472
- var isDataFieldType = (field3) => {
4473
- return field3.config.type === FieldType.DATA;
4474
- };
4475
- var isButtonFieldType = (field3) => {
4476
- return field3.config.type === FieldType.BUTTON;
4477
- };
4478
- var isPrintButtonFieldType = (field3) => {
4479
- return field3.config.type === FieldType.ALPHA_PRINT_BUTTON;
4480
- };
4481
- var isHttpFieldType = (field3) => {
4482
- return field3.config.type === FieldType.HTTP;
4483
- };
4484
- var isAutocompleteFieldType = (field3) => {
4485
- return field3.config.type === FieldType.AUTOCOMPLETE;
4486
- };
4487
- var isSearchFieldType = (field3) => {
4488
- return field3.config.type === FieldType.SEARCH;
4489
- };
4490
- var isLinkButtonFieldType = (field3) => {
4491
- return field3.config.type === FieldType.LINK_BUTTON;
4492
- };
4493
- var isVerificationStatusType = (field3) => {
4494
- return field3.config.type === FieldType.VERIFICATION_STATUS;
4495
- };
4496
- var isQueryParamReaderFieldType = (field3) => {
4497
- return field3.config.type === FieldType.QUERY_PARAM_READER;
4498
- };
4499
- var isQrReaderFieldType = (field3) => {
4500
- return field3.config.type === FieldType.QR_READER;
4501
- };
4502
- var isIdReaderFieldType = (field3) => {
4503
- return field3.config.type === FieldType.ID_READER;
4504
- };
4505
- var isLoaderFieldType = (field3) => {
4506
- return field3.config.type === FieldType.LOADER;
4507
- };
4508
- var isCustomFieldType = (field3) => {
4509
- return field3.config.type === FieldType._EXPERIMENTAL_CUSTOM;
4510
- };
4511
- var isUserRoleFieldType = (field3) => {
4512
- return field3.config.type === FieldType.USER_ROLE;
4513
- };
4514
- var isHiddenFieldType = (field3) => {
4515
- return field3.config.type === FieldType.ALPHA_HIDDEN;
4516
- };
4517
- var isNonInteractiveFieldType = (field3) => {
4518
- return field3.type === FieldType.DIVIDER || field3.type === FieldType.PAGE_HEADER || field3.type === FieldType.PARAGRAPH || field3.type === FieldType.HEADING || field3.type === FieldType.BULLET_LIST || field3.type === FieldType.DATA || field3.type === FieldType.ALPHA_PRINT_BUTTON || field3.type === FieldType.LINK_BUTTON || field3.type === FieldType.LOADER;
4519
- };
4520
-
4521
- // ../commons/src/events/state/index.ts
4522
- var import_lodash3 = require("lodash");
4523
-
4524
- // ../commons/src/utils.ts
4525
- var z33 = __toESM(require("zod/v4"));
4526
- var _ = __toESM(require("lodash"));
4527
- function getOrThrow(x, message) {
4528
- if (x === void 0 || x === null) {
4529
- throw new Error(message);
4530
- }
4531
- return x;
4532
- }
4533
- function joinValues(values, separator = " ") {
4534
- return values.filter((value) => !!value).join(separator).trim();
4535
- }
4536
- var FullNameV1 = z33.array(
4537
- z33.object({
4538
- use: z33.string(),
4539
- family: z33.string(),
4540
- given: z33.array(z33.string())
4541
- })
4542
- );
4543
- function omitKeyDeep(obj, keyToRemove) {
4544
- if (Array.isArray(obj)) {
4545
- return obj.map((item) => omitKeyDeep(item, keyToRemove));
4546
- }
4547
- if (obj === null || typeof obj !== "object") {
4548
- return obj;
4549
- }
4550
- const newObj = {};
4551
- for (const key of Object.keys(obj)) {
4552
- if (key !== keyToRemove) {
4553
- newObj[key] = omitKeyDeep(obj[key], keyToRemove);
4554
- }
4313
+ function wrapToPathOptional(condition, path) {
4314
+ if (path.length === 0) {
4315
+ return condition;
4555
4316
  }
4556
- return newObj;
4557
- }
4558
-
4559
- // ../commons/src/events/state/utils.ts
4560
- var import_lodash = require("lodash");
4561
- function getActionRequests(actionType, actions) {
4562
- const filtered = actions.filter((action) => action.type === actionType).reverse();
4563
- const accept = filtered.find(
4564
- (action) => action.status === ActionStatus.Accepted
4565
- );
4566
- const request = filtered.find(
4567
- (action) => action.status === ActionStatus.Requested
4568
- );
4569
- const reject = filtered.find(
4570
- (action) => action.status === ActionStatus.Rejected
4571
- );
4572
- return {
4573
- reject,
4574
- accept,
4575
- request
4576
- };
4317
+ return path.reduceRight((conditionNow, part) => {
4318
+ return {
4319
+ type: "object",
4320
+ properties: { [part]: conditionNow }
4321
+ };
4322
+ }, condition);
4577
4323
  }
4578
- function getDeclarationActionCreationMetadata(actionType, actions) {
4579
- const { accept: acceptAction, request: requestAction } = getActionRequests(
4580
- actionType,
4581
- actions
4582
- );
4583
- if (!acceptAction) {
4584
- return null;
4585
- }
4586
- const registrationNumber = acceptAction.type === ActionType.REGISTER ? acceptAction.registrationNumber : null;
4587
- return {
4588
- // When 3rd party API returns 200 OK, we assume that the request was accepted, and persist single 'accepted' action.
4589
- createdAt: requestAction?.createdAt ?? acceptAction.createdAt,
4590
- createdBy: requestAction?.createdBy ?? acceptAction.createdBy,
4591
- createdByUserType: requestAction?.createdByUserType ?? acceptAction.createdByUserType,
4592
- createdAtLocation: requestAction?.createdAtLocation ?? acceptAction.createdAtLocation,
4593
- acceptedAt: acceptAction.createdAt,
4594
- createdByRole: requestAction?.createdByRole ?? acceptAction.createdByRole,
4595
- registrationNumber
4596
- };
4597
- }
4598
- var updateActions = new Set(
4599
- ActionTypes.extract([
4600
- ActionType.CREATE,
4601
- ActionType.NOTIFY,
4602
- ActionType.EDIT,
4603
- ActionType.DECLARE,
4604
- ActionType.REGISTER,
4605
- ActionType.REJECT,
4606
- ActionType.ARCHIVE,
4607
- ActionType.UNARCHIVE,
4608
- ActionType.PRINT_CERTIFICATE,
4609
- ActionType.REQUEST_CORRECTION,
4610
- ActionType.APPROVE_CORRECTION,
4611
- ActionType.REJECT_CORRECTION,
4612
- ActionType.REVOKE_REGISTRATION,
4613
- ActionType.REINSTATE_REGISTRATION,
4614
- ActionType.CUSTOM
4615
- ]).options
4616
- );
4617
- function getActionUpdateMetadata(actions) {
4618
- const createAction = getOrThrow(
4619
- actions.find((action) => action.type === ActionType.CREATE),
4620
- `Event has no ${ActionType.CREATE} action`
4621
- );
4622
- const metadataFields = [
4623
- "createdAt",
4624
- "createdBy",
4625
- "createdByUserType",
4626
- "createdAtLocation",
4627
- "createdByRole"
4628
- ];
4629
- return actions.filter(({ type }) => updateActions.has(type)).reduce(
4630
- (_2, action) => {
4631
- if (action.originalActionId) {
4632
- const originalAction = actions.find(({ id }) => id === action.originalActionId) ?? action;
4633
- return (0, import_lodash.pick)(originalAction, metadataFields);
4324
+ var now = Object.assign(todayDateTimeValueSerializer, {});
4325
+ var user = Object.assign(userSerializer, {
4326
+ ...userReferenceFunctions,
4327
+ hasScope: (scope) => defineConditional({
4328
+ type: "object",
4329
+ properties: {
4330
+ $user: {
4331
+ type: "object",
4332
+ required: ["scope"],
4333
+ properties: {
4334
+ scope: {
4335
+ type: "array",
4336
+ contains: {
4337
+ type: "string",
4338
+ const: scope
4339
+ }
4340
+ }
4341
+ }
4634
4342
  }
4635
- return (0, import_lodash.pick)(action, metadataFields);
4636
4343
  },
4637
- (0, import_lodash.pick)(createAction, metadataFields)
4638
- );
4344
+ required: ["$user"]
4345
+ }),
4346
+ hasRole: (role) => defineConditional({
4347
+ type: "object",
4348
+ properties: {
4349
+ $user: {
4350
+ type: "object",
4351
+ required: ["role"],
4352
+ properties: {
4353
+ role: {
4354
+ type: "string",
4355
+ const: role
4356
+ }
4357
+ }
4358
+ }
4359
+ },
4360
+ required: ["$user"]
4361
+ }),
4362
+ isOnline: () => defineConditional({
4363
+ type: "object",
4364
+ properties: {
4365
+ $online: {
4366
+ type: "boolean",
4367
+ const: true
4368
+ }
4369
+ },
4370
+ required: ["$online"]
4371
+ }),
4372
+ locationLevel: (adminLevelId) => ({
4373
+ $user: { $location: adminLevelId }
4374
+ })
4375
+ });
4376
+ function isFieldReference(value) {
4377
+ return typeof value === "object" && value !== null && "$$field" in value;
4639
4378
  }
4640
- function getLegalStatuses(actions, status2) {
4379
+ function isEventFieldReference(value) {
4380
+ return typeof value === "object" && value !== null && "$$event" in value;
4381
+ }
4382
+ function isActionDateReference(value) {
4383
+ return typeof value === "object" && value !== null && "$action" in value;
4384
+ }
4385
+ function getDateRangeToFieldReference(field3, comparedField, clause) {
4641
4386
  return {
4642
- [EventStatus.enum.NOTIFIED]: getDeclarationActionCreationMetadata(
4643
- ActionType.NOTIFY,
4644
- actions
4645
- ),
4646
- [EventStatus.enum.DECLARED]: getDeclarationActionCreationMetadata(
4647
- ActionType.DECLARE,
4648
- actions
4649
- ),
4650
- [EventStatus.enum.REGISTERED]: getDeclarationActionCreationMetadata(
4651
- ActionType.REGISTER,
4652
- actions
4653
- ),
4654
- // A later reinstate does not remove the revoke action, so only report it while the record is still revoked.
4655
- [EventStatus.enum.REVOKED]: status2 === EventStatus.enum.REVOKED ? getDeclarationActionCreationMetadata(
4656
- ActionType.REVOKE_REGISTRATION,
4657
- actions
4658
- ) : null
4387
+ type: "object",
4388
+ properties: {
4389
+ [field3.$$field]: wrapToPath(
4390
+ {
4391
+ type: "string",
4392
+ format: "date",
4393
+ [clause]: {
4394
+ $data: `${field3.$$subfield.length + 1}/${jsonFieldPath(comparedField)}`
4395
+ }
4396
+ },
4397
+ field3.$$subfield
4398
+ ),
4399
+ [comparedField.$$field]: wrapToPath(
4400
+ { type: "string", format: "date" },
4401
+ comparedField.$$subfield
4402
+ )
4403
+ },
4404
+ required: [field3.$$field]
4659
4405
  };
4660
4406
  }
4661
-
4662
- // ../commons/src/events/state/flags.ts
4663
- var import_lodash2 = require("lodash");
4664
- var import_date_fns = require("date-fns");
4665
- function findPendingCorrectionAction(writeActions2) {
4666
- let correctionRequestAction;
4667
- for (let i = writeActions2.length - 1; i >= 0; i--) {
4668
- const action = writeActions2[i];
4669
- if (action.type === ActionType.APPROVE_CORRECTION || action.type === ActionType.REJECT_CORRECTION) {
4670
- break;
4671
- }
4672
- if (action.type === ActionType.REQUEST_CORRECTION) {
4673
- correctionRequestAction = action;
4674
- break;
4675
- }
4676
- }
4677
- return correctionRequestAction;
4678
- }
4679
- function isPotentialDuplicate(actions) {
4680
- return actions.reduce((prev, { type }) => {
4681
- if (type === ActionType.DUPLICATE_DETECTED) {
4682
- return true;
4683
- }
4684
- if (type === ActionType.MARK_AS_NOT_DUPLICATE || type === ActionType.MARK_AS_DUPLICATE) {
4685
- return false;
4686
- }
4687
- return prev;
4688
- }, false);
4407
+ function getDayRangeToFieldReference(field3, comparedField, days, clause) {
4408
+ return {
4409
+ type: "object",
4410
+ properties: {
4411
+ [field3.$$field]: wrapToPath(
4412
+ {
4413
+ type: "string",
4414
+ format: "date",
4415
+ daysFromDate: {
4416
+ referenceDate: {
4417
+ $data: `${field3.$$subfield.length + 1}/${jsonFieldPath(
4418
+ comparedField
4419
+ )}`
4420
+ },
4421
+ clause,
4422
+ days
4423
+ }
4424
+ },
4425
+ field3.$$subfield
4426
+ ),
4427
+ [comparedField.$$field]: wrapToPath(
4428
+ { type: "string", format: "date" },
4429
+ comparedField.$$subfield
4430
+ )
4431
+ },
4432
+ required: [field3.$$field]
4433
+ };
4689
4434
  }
4690
- function isFlagConditionMet(conditional, form, action) {
4691
- const now2 = (0, import_date_fns.isValid)((0, import_date_fns.parseISO)(action.createdAt)) ? (0, import_date_fns.formatISO)((0, import_date_fns.parseISO)(action.createdAt), { representation: "date" }) : (0, import_date_fns.formatISO)(/* @__PURE__ */ new Date(), { representation: "date" });
4692
- return validate(conditional, {
4693
- $form: form,
4694
- $now: now2,
4695
- $online: true,
4696
- $user: {
4697
- sub: "",
4698
- exp: "",
4699
- role: action.createdByRole,
4700
- algorithm: "",
4701
- scope: [],
4702
- userType: action.createdByUserType
4703
- }
4435
+ function defineComparison(field3, value, keyword) {
4436
+ if (isFieldReference(value)) {
4437
+ const comparedField = value;
4438
+ return defineFormConditional({
4439
+ type: "object",
4440
+ properties: {
4441
+ [field3.$$field]: wrapToPath(
4442
+ {
4443
+ type: ["number"],
4444
+ [keyword]: {
4445
+ $data: `${field3.$$subfield.length + 1}/${jsonFieldPath(comparedField)}`
4446
+ }
4447
+ },
4448
+ field3.$$subfield
4449
+ ),
4450
+ [comparedField.$$field]: wrapToPath(
4451
+ { type: "number" },
4452
+ comparedField.$$subfield
4453
+ )
4454
+ },
4455
+ required: [field3.$$field]
4456
+ });
4457
+ }
4458
+ return defineFormConditional({
4459
+ type: "object",
4460
+ properties: {
4461
+ [field3.$$field]: wrapToPath(
4462
+ { type: "number", [keyword]: value },
4463
+ field3.$$subfield
4464
+ )
4465
+ },
4466
+ required: [field3.$$field]
4704
4467
  });
4705
4468
  }
4706
- function actionConfigRemovesFlag(action, flagId, actionsUpToAndIncluding, event2, eventConfiguration) {
4707
- if (!isActionConfigType(action.type)) {
4708
- return false;
4709
- }
4710
- const actionConfig = getActionConfig({
4711
- eventConfiguration,
4712
- actionType: action.type,
4713
- customActionType: "customActionType" in action ? action.customActionType : void 0
4714
- });
4715
- const removeOperations = (actionConfig?.flags ?? []).filter(
4716
- ({ id, operation }) => id === flagId && operation === "remove"
4717
- );
4718
- if (removeOperations.length === 0) {
4719
- return false;
4720
- }
4721
- const eventUpToThisAction = { ...event2, actions: actionsUpToAndIncluding };
4722
- const declaration = aggregateActionDeclarations(eventUpToThisAction);
4723
- const annotation = aggregateActionAnnotations(eventUpToThisAction);
4724
- const form = { ...declaration, ...annotation };
4725
- return removeOperations.some(
4726
- ({ conditional }) => conditional ? isFlagConditionMet(conditional, form, action) : true
4727
- );
4728
- }
4729
- var INHERENT_FLAG_RULES = [
4730
- {
4731
- flag: InherentFlags.CORRECTION_REQUESTED,
4732
- setOn: [ActionType.REQUEST_CORRECTION],
4733
- resetOn: [ActionType.APPROVE_CORRECTION, ActionType.REJECT_CORRECTION]
4734
- },
4735
- {
4736
- flag: InherentFlags.REJECTED,
4737
- setOn: [ActionType.REJECT],
4738
- resetOn: [
4739
- ActionType.NOTIFY,
4740
- ActionType.DECLARE,
4741
- ActionType.EDIT,
4742
- ActionType.REGISTER
4743
- ]
4744
- },
4745
- {
4746
- flag: InherentFlags.POTENTIAL_DUPLICATE,
4747
- setOn: [ActionType.DUPLICATE_DETECTED],
4748
- resetOn: [ActionType.MARK_AS_DUPLICATE, ActionType.MARK_AS_NOT_DUPLICATE]
4749
- },
4750
- {
4751
- flag: InherentFlags.EDIT_IN_PROGRESS,
4752
- setOn: [ActionType.EDIT],
4753
- resetOnAnyOtherAction: true
4754
- }
4755
- ];
4756
- function resolveInherentFlag(rule, acceptedActions, event2, eventConfiguration) {
4757
- return acceptedActions.reduce((present, action, idx) => {
4758
- if (rule.setOn.includes(action.type)) {
4759
- return true;
4760
- }
4761
- if (rule.resetOnAnyOtherAction || (rule.resetOn ?? []).includes(action.type)) {
4762
- return false;
4763
- }
4764
- if (actionConfigRemovesFlag(
4765
- action,
4766
- rule.flag,
4767
- acceptedActions.slice(0, idx + 1),
4768
- event2,
4769
- eventConfiguration
4770
- )) {
4771
- return false;
4772
- }
4773
- return present;
4774
- }, false);
4775
- }
4776
- function resolveEventCustomFlags(event2, eventConfiguration) {
4777
- const actions = getAcceptedActions(event2).filter(({ type }) => !isMetaAction(type)).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
4778
- const declarations = getDeclarationAfterEachAction({ ...event2, actions });
4779
- let annotation = {};
4780
- return actions.reduce((acc, action, idx) => {
4781
- if (action.annotation) {
4782
- annotation = deepMerge(annotation, action.annotation);
4783
- }
4784
- let actionConfig;
4785
- if (isActionConfigType(action.type)) {
4786
- actionConfig = getActionConfig({
4787
- eventConfiguration,
4788
- actionType: action.type,
4789
- customActionType: "customActionType" in action ? action.customActionType : void 0
4790
- });
4791
- }
4792
- if (!actionConfig) {
4793
- return acc;
4794
- }
4795
- const form = { ...declarations[idx], ...annotation };
4796
- const flagsWithMetConditions = (actionConfig.flags ?? []).filter(
4797
- ({ conditional }) => (
4798
- // If conditional is not provided, the flag is resolved
4799
- conditional ? isFlagConditionMet(conditional, form, action) : true
4800
- )
4801
- );
4802
- const addedFlags = flagsWithMetConditions.filter(({ operation }) => operation === "add").map(({ id }) => id);
4803
- const removedFlags = flagsWithMetConditions.filter(({ operation }) => operation === "remove").map(({ id }) => id);
4804
- const flags = [...acc, ...addedFlags].filter(
4805
- (flagId) => !removedFlags.includes(flagId)
4806
- );
4807
- return (0, import_lodash2.uniq)(flags);
4808
- }, []);
4809
- }
4810
- function getActionStatusFlags(sortedActions) {
4811
- const actionStatus = sortedActions.reduce(
4812
- (actionStatuses, { type, status: status2 }) => ({
4813
- ...actionStatuses,
4814
- [type]: status2
4815
- }),
4816
- {}
4817
- );
4818
- return Object.entries(actionStatus).filter(([, status2]) => status2 !== ActionStatus.Accepted).map(([type, status2]) => {
4819
- const flag2 = joinValues([type, status2], ":").toLowerCase();
4820
- return flag2;
4821
- });
4822
- }
4823
- function getInherentFlags(sortedActions, event2, eventConfiguration) {
4824
- const acceptedActions = sortedActions.filter(
4825
- ({ status: status2 }) => status2 === ActionStatus.Accepted
4826
- );
4827
- return INHERENT_FLAG_RULES.filter(
4828
- (rule) => resolveInherentFlag(rule, acceptedActions, event2, eventConfiguration)
4829
- ).map(({ flag: flag2 }) => flag2);
4830
- }
4831
- function getEventFlags(event2, config) {
4832
- const sortedActions = event2.actions.filter(({ type }) => !isMetaAction(type)).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
4833
- return [
4834
- ...getActionStatusFlags(sortedActions),
4835
- ...getInherentFlags(sortedActions, event2, config),
4836
- ...resolveEventCustomFlags(event2, config)
4837
- ];
4838
- }
4839
-
4840
- // ../commons/src/conditionals/conditionals.ts
4841
- var objectHash = __toESM(require("object-hash"));
4842
- function defineConditional(schema) {
4843
- const schemaWithooutIDRef = omitKeyDeep(schema, "$id");
4844
- return {
4845
- $id: `https://opencrvs.org/conditionals/${objectHash.sha1(schemaWithooutIDRef)}`,
4846
- ...schemaWithooutIDRef
4847
- };
4848
- }
4849
- function defineFormConditional(schema) {
4850
- const schemaWithForm = {
4469
+ function flag(flagvalue) {
4470
+ return defineConditional({
4851
4471
  type: "object",
4852
4472
  properties: {
4853
- $form: schema
4473
+ $flags: {
4474
+ type: "array",
4475
+ contains: {
4476
+ type: "string",
4477
+ const: flagvalue
4478
+ }
4479
+ }
4854
4480
  },
4855
- required: ["$form"]
4856
- };
4857
- return defineConditional(schemaWithForm);
4858
- }
4859
- function alwaysTrue() {
4860
- return {};
4861
- }
4862
- function and(...conditions) {
4863
- return defineConditional({
4864
- type: "object",
4865
- allOf: conditions,
4866
- required: []
4867
- });
4868
- }
4869
- function or(...conditions) {
4870
- return defineConditional({
4871
- type: "object",
4872
- anyOf: conditions,
4873
- required: []
4481
+ required: ["$flags"]
4874
4482
  });
4875
4483
  }
4876
- function not(condition) {
4484
+ function status(statusValue) {
4877
4485
  return defineConditional({
4878
4486
  type: "object",
4879
- not: condition,
4880
- required: []
4487
+ properties: {
4488
+ $status: {
4489
+ type: "string",
4490
+ const: statusValue
4491
+ }
4492
+ },
4493
+ required: ["$status"]
4881
4494
  });
4882
4495
  }
4883
- function never2() {
4884
- return not(alwaysTrue());
4885
- }
4886
- function always() {
4887
- return defineConditional(alwaysTrue());
4888
- }
4889
- function jsonFieldPath(field3) {
4890
- return [field3.$$field, ...field3.$$subfield].join("/");
4891
- }
4892
- function wrapToPath(condition, path) {
4893
- if (path.length === 0) {
4894
- return condition;
4895
- }
4896
- return path.reduceRight((conditionNow, part) => {
4897
- return {
4898
- type: "object",
4899
- properties: {
4900
- [part]: conditionNow
4901
- },
4902
- required: [part]
4903
- };
4904
- }, condition);
4905
- }
4906
- function wrapToPathOptional(condition, path) {
4907
- if (path.length === 0) {
4908
- return condition;
4909
- }
4910
- return path.reduceRight((conditionNow, part) => {
4911
- return {
4912
- type: "object",
4913
- properties: { [part]: conditionNow }
4914
- };
4915
- }, condition);
4916
- }
4917
- var now = Object.assign(todayDateTimeValueSerializer, {});
4918
- var user = Object.assign(userSerializer, {
4919
- ...userReferenceFunctions,
4920
- hasScope: (scope) => defineConditional({
4496
+ function createFieldConditionals(fieldId) {
4497
+ const getDayRange = (field3, days, clause, referenceDate) => ({
4921
4498
  type: "object",
4922
4499
  properties: {
4923
- $user: {
4924
- type: "object",
4925
- required: ["scope"],
4926
- properties: {
4927
- scope: {
4928
- type: "array",
4929
- contains: {
4930
- type: "string",
4931
- const: scope
4932
- }
4500
+ [field3.$$field]: wrapToPath(
4501
+ {
4502
+ type: "string",
4503
+ format: "date",
4504
+ daysFromDate: {
4505
+ days,
4506
+ clause,
4507
+ referenceDate
4933
4508
  }
4934
- }
4935
- }
4509
+ },
4510
+ field3.$$subfield
4511
+ )
4936
4512
  },
4937
- required: ["$user"]
4938
- }),
4939
- hasRole: (role) => defineConditional({
4940
- type: "object",
4941
- properties: {
4942
- $user: {
4943
- type: "object",
4944
- required: ["role"],
4945
- properties: {
4946
- role: {
4947
- type: "string",
4948
- const: role
4949
- }
4950
- }
4951
- }
4952
- },
4953
- required: ["$user"]
4954
- }),
4955
- isOnline: () => defineConditional({
4956
- type: "object",
4957
- properties: {
4958
- $online: {
4959
- type: "boolean",
4960
- const: true
4961
- }
4962
- },
4963
- required: ["$online"]
4964
- }),
4965
- locationLevel: (adminLevelId) => ({
4966
- $user: { $location: adminLevelId }
4967
- })
4968
- });
4969
- function isFieldReference(value) {
4970
- return typeof value === "object" && value !== null && "$$field" in value;
4971
- }
4972
- function isEventFieldReference(value) {
4973
- return typeof value === "object" && value !== null && "$$event" in value;
4974
- }
4975
- function getDateRangeToFieldReference(field3, comparedField, clause) {
4976
- return {
4977
- type: "object",
4978
- properties: {
4979
- [field3.$$field]: wrapToPath(
4980
- {
4981
- type: "string",
4982
- format: "date",
4983
- [clause]: {
4984
- $data: `${field3.$$subfield.length + 1}/${jsonFieldPath(comparedField)}`
4985
- }
4986
- },
4987
- field3.$$subfield
4988
- ),
4989
- [comparedField.$$field]: wrapToPath(
4990
- { type: "string", format: "date" },
4991
- comparedField.$$subfield
4992
- )
4993
- },
4994
- required: [field3.$$field]
4995
- };
4996
- }
4997
- function getDayRangeToFieldReference(field3, comparedField, days, clause) {
4998
- return {
4999
- type: "object",
5000
- properties: {
5001
- [field3.$$field]: wrapToPath(
5002
- {
5003
- type: "string",
5004
- format: "date",
5005
- daysFromDate: {
5006
- referenceDate: {
5007
- $data: `${field3.$$subfield.length + 1}/${jsonFieldPath(
5008
- comparedField
5009
- )}`
5010
- },
5011
- clause,
5012
- days
5013
- }
5014
- },
5015
- field3.$$subfield
5016
- ),
5017
- [comparedField.$$field]: wrapToPath(
5018
- { type: "string", format: "date" },
5019
- comparedField.$$subfield
5020
- )
5021
- },
5022
- required: [field3.$$field]
5023
- };
5024
- }
5025
- function defineComparison(field3, value, keyword) {
5026
- if (isFieldReference(value)) {
5027
- const comparedField = value;
5028
- return defineFormConditional({
5029
- type: "object",
5030
- properties: {
5031
- [field3.$$field]: wrapToPath(
5032
- {
5033
- type: ["number"],
5034
- [keyword]: {
5035
- $data: `${field3.$$subfield.length + 1}/${jsonFieldPath(comparedField)}`
5036
- }
5037
- },
5038
- field3.$$subfield
5039
- ),
5040
- [comparedField.$$field]: wrapToPath(
5041
- { type: "number" },
5042
- comparedField.$$subfield
5043
- )
5044
- },
5045
- required: [field3.$$field]
5046
- });
5047
- }
5048
- return defineFormConditional({
5049
- type: "object",
5050
- properties: {
5051
- [field3.$$field]: wrapToPath(
5052
- { type: "number", [keyword]: value },
5053
- field3.$$subfield
5054
- )
5055
- },
5056
- required: [field3.$$field]
5057
- });
5058
- }
5059
- function flag(flagvalue) {
5060
- return defineConditional({
5061
- type: "object",
5062
- properties: {
5063
- $flags: {
5064
- type: "array",
5065
- contains: {
5066
- type: "string",
5067
- const: flagvalue
5068
- }
5069
- }
5070
- },
5071
- required: ["$flags"]
5072
- });
5073
- }
5074
- function status(statusValue) {
5075
- return defineConditional({
5076
- type: "object",
5077
- properties: {
5078
- $status: {
5079
- type: "string",
5080
- const: statusValue
5081
- }
5082
- },
5083
- required: ["$status"]
5084
- });
5085
- }
5086
- function createFieldConditionals(fieldId) {
5087
- const getDayRange = (field3, days, clause, referenceDate) => ({
5088
- type: "object",
5089
- properties: {
5090
- [field3.$$field]: wrapToPath(
5091
- {
5092
- type: "string",
5093
- format: "date",
5094
- daysFromDate: {
5095
- days,
5096
- clause,
5097
- referenceDate
5098
- }
5099
- },
5100
- field3.$$subfield
5101
- )
5102
- },
5103
- required: [field3.$$field]
5104
- });
5105
- const getDateRange = (field3, date, clause) => ({
4513
+ required: [field3.$$field]
4514
+ });
4515
+ const getDateRange = (field3, date, clause) => ({
5106
4516
  type: "object",
5107
4517
  properties: {
5108
4518
  [field3.$$field]: wrapToPath(
@@ -5159,7 +4569,9 @@ function createFieldConditionals(fieldId) {
5159
4569
  },
5160
4570
  fromNow: () => {
5161
4571
  return defineFormConditional(getDayRange(this, days, "after"));
5162
- }
4572
+ },
4573
+ beforeAction: (action) => defineFormConditional(getDayRange(this, -days, "after", action)),
4574
+ afterAction: (action) => defineFormConditional(getDayRange(this, days, "after", action))
5163
4575
  }),
5164
4576
  date: (date) => {
5165
4577
  if (isFieldReference(date)) {
@@ -5200,7 +4612,9 @@ function createFieldConditionals(fieldId) {
5200
4612
  },
5201
4613
  fromNow: () => {
5202
4614
  return defineFormConditional(getDayRange(this, -days, "before"));
5203
- }
4615
+ },
4616
+ beforeAction: (action) => defineFormConditional(getDayRange(this, -days, "before", action)),
4617
+ afterAction: (action) => defineFormConditional(getDayRange(this, days, "before", action))
5204
4618
  }),
5205
4619
  date: (date) => {
5206
4620
  if (isFieldReference(date)) {
@@ -5408,80 +4822,727 @@ function createFieldConditionals(fieldId) {
5408
4822
  required: [fieldId]
5409
4823
  });
5410
4824
  },
5411
- getId: () => ({ fieldId }),
5412
- /**
5413
- * @deprecated
5414
- * use field(fieldId).get(nestedProperty) instead
5415
- * with 'and' combinator e.g.
5416
- * and(
5417
- * field('child.name').get('firstname').isEqualTo('John'),
5418
- * field('child.name').get('surname').isEqualTo('Doe')
5419
- * )
5420
- */
5421
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
5422
- object: (options) => defineFormConditional({
5423
- type: "object",
5424
- properties: {
5425
- [fieldId]: {
5426
- type: "object",
5427
- properties: Object.fromEntries(
5428
- Object.entries(options).map(([key, value]) => {
5429
- return [key, value.properties.$form.properties[key]];
5430
- })
5431
- ),
5432
- required: Object.keys(options)
5433
- }
5434
- },
5435
- required: [fieldId]
5436
- }),
5437
- /**
5438
- * Custom client-side validator. The provided function is serialised and executed
5439
- * just-in-time on the client only. External references (e.g. lodash) are not
5440
- * available inside the function body — all logic must be self-contained.
5441
- *
5442
- * @example
5443
- * field('nid').customClientValidator((value) => {
5444
- * // LUHN check — all logic must be inline
5445
- * const digits = String(value).split('').map(Number)
5446
- * // ...
5447
- * return isValid
5448
- * })
5449
- */
5450
- customClientValidator(validationFn) {
5451
- const code = validationFn.toString();
5452
- return defineFormConditional({
5453
- type: "object",
5454
- properties: wrapToPath(
5455
- { [fieldId]: { customClientValidator: { code } } },
5456
- this.$$subfield
5457
- ),
5458
- required: [fieldId]
4825
+ getId: () => ({ fieldId }),
4826
+ /**
4827
+ * @deprecated
4828
+ * use field(fieldId).get(nestedProperty) instead
4829
+ * with 'and' combinator e.g.
4830
+ * and(
4831
+ * field('child.name').get('firstname').isEqualTo('John'),
4832
+ * field('child.name').get('surname').isEqualTo('Doe')
4833
+ * )
4834
+ */
4835
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4836
+ object: (options) => defineFormConditional({
4837
+ type: "object",
4838
+ properties: {
4839
+ [fieldId]: {
4840
+ type: "object",
4841
+ properties: Object.fromEntries(
4842
+ Object.entries(options).map(([key, value]) => {
4843
+ return [key, value.properties.$form.properties[key]];
4844
+ })
4845
+ ),
4846
+ required: Object.keys(options)
4847
+ }
4848
+ },
4849
+ required: [fieldId]
4850
+ }),
4851
+ /**
4852
+ * Custom client-side validator. The provided function is serialised and executed
4853
+ * just-in-time on the client only. External references (e.g. lodash) are not
4854
+ * available inside the function body — all logic must be self-contained.
4855
+ *
4856
+ * @example
4857
+ * field('nid').customClientValidator((value) => {
4858
+ * // LUHN check — all logic must be inline
4859
+ * const digits = String(value).split('').map(Number)
4860
+ * // ...
4861
+ * return isValid
4862
+ * })
4863
+ */
4864
+ customClientValidator(validationFn) {
4865
+ const code = validationFn.toString();
4866
+ return defineFormConditional({
4867
+ type: "object",
4868
+ properties: wrapToPath(
4869
+ { [fieldId]: { customClientValidator: { code } } },
4870
+ this.$$subfield
4871
+ ),
4872
+ required: [fieldId]
4873
+ });
4874
+ },
4875
+ /**
4876
+ * Custom client-side evaluation. Returns a {@link FieldReference} descriptor
4877
+ * that can be used as the `value` property or a DATA component entry.
4878
+ * The function receives the referenced field's value as the first argument and
4879
+ * the full form context as the second; its return value replaces the field reference.
4880
+ * The function is serialised and executed just-in-time on the client only.
4881
+ * External references (e.g. lodash) are not available inside the function body.
4882
+ *
4883
+ * For computing a default value without referencing a specific field, use
4884
+ * `evaluate(fn)` in the `defaultValue` property instead.
4885
+ *
4886
+ * @example
4887
+ * field('a').customClientEvaluation((aValue, ctx) =>
4888
+ * Number(aValue) + Number(ctx.$form.b)
4889
+ * )
4890
+ */
4891
+ customClientEvaluation(computationFn) {
4892
+ return {
4893
+ $$code: computationFn.toString(),
4894
+ $$field: fieldId,
4895
+ $$subfield: this.$$subfield
4896
+ };
4897
+ }
4898
+ };
4899
+ }
4900
+
4901
+ // ../commons/src/events/FieldTypeMapping.ts
4902
+ var z33 = __toESM(require("zod/v4"));
4903
+
4904
+ // ../commons/src/events/DynamicFieldValue.ts
4905
+ var z32 = __toESM(require("zod/v4"));
4906
+ function getDynamicNameValue(field3) {
4907
+ const nameConfiguration = field3.configuration?.name;
4908
+ const firstnameRequired = nameConfiguration?.firstname?.required ?? field3.required;
4909
+ const surnameRequired = nameConfiguration?.surname?.required ?? field3.required;
4910
+ return z32.object({
4911
+ firstname: firstnameRequired ? NonEmptyTextValue : TextValue,
4912
+ surname: surnameRequired ? NonEmptyTextValue : TextValue,
4913
+ middlename: nameConfiguration?.middlename?.required ? NonEmptyTextValue : TextValue.optional()
4914
+ });
4915
+ }
4916
+ function getDynamicAddressFieldValue(field3) {
4917
+ const schema = field3.required ? AddressFieldValue : AddressFieldUpdateValue;
4918
+ const configIds = field3.configuration?.streetAddressForm?.map((a) => a.id) ?? [];
4919
+ return schema.refine((arg) => {
4920
+ if (!arg) {
4921
+ return true;
4922
+ }
4923
+ const submittedKeys = Object.keys(arg.streetLevelDetails ?? {});
4924
+ const invalidKeys = submittedKeys.filter((k) => !configIds.includes(k));
4925
+ if (invalidKeys.length) {
4926
+ console.log(
4927
+ "Invalid streetLevelDetails: unknown keys",
4928
+ JSON.stringify(invalidKeys, null, 2)
4929
+ );
4930
+ return false;
4931
+ }
4932
+ return true;
4933
+ });
4934
+ }
4935
+
4936
+ // ../commons/src/events/FieldTypeMapping.ts
4937
+ function mapFieldTypeToZod(field3, actionType) {
4938
+ let schema;
4939
+ switch (field3.type) {
4940
+ case FieldType.FIELD_GROUP: {
4941
+ schema = z33.object(
4942
+ field3.fields.reduce((acc, subfield) => {
4943
+ acc[subfield.id] = mapFieldTypeToZod(subfield, actionType);
4944
+ return acc;
4945
+ }, {})
4946
+ );
4947
+ break;
4948
+ }
4949
+ case FieldType.DATE:
4950
+ schema = PlainDate;
4951
+ break;
4952
+ case FieldType.AGE:
4953
+ schema = AgeValue;
4954
+ break;
4955
+ case FieldType.TIME:
4956
+ schema = TimeValue;
4957
+ break;
4958
+ case FieldType.EMAIL:
4959
+ schema = EmailValue;
4960
+ break;
4961
+ case FieldType.DATE_RANGE:
4962
+ schema = DateRangeFieldValue;
4963
+ break;
4964
+ case FieldType.SELECT_DATE_RANGE:
4965
+ schema = SelectDateRangeValue;
4966
+ break;
4967
+ case FieldType.TEXT:
4968
+ case FieldType.TEXTAREA:
4969
+ case FieldType.DIVIDER:
4970
+ case FieldType.BULLET_LIST:
4971
+ case FieldType.PAGE_HEADER:
4972
+ case FieldType.LOCATION:
4973
+ case FieldType.SELECT:
4974
+ case FieldType.COUNTRY:
4975
+ case FieldType.RADIO_GROUP:
4976
+ case FieldType.PARAGRAPH:
4977
+ case FieldType.HEADING:
4978
+ case FieldType.IMAGE_VIEW:
4979
+ case FieldType.ADMINISTRATIVE_AREA:
4980
+ case FieldType.FACILITY:
4981
+ case FieldType.OFFICE:
4982
+ case FieldType.PHONE:
4983
+ case FieldType.LINK_BUTTON:
4984
+ case FieldType.VERIFICATION_STATUS:
4985
+ case FieldType.ID:
4986
+ case FieldType.LOADER:
4987
+ case FieldType.ALPHA_HIDDEN:
4988
+ case FieldType.USER_ROLE:
4989
+ schema = field3.required ? NonEmptyTextValue : TextValue;
4990
+ break;
4991
+ case FieldType.NUMBER:
4992
+ schema = NumberFieldValue;
4993
+ break;
4994
+ case FieldType.NUMBER_WITH_UNIT:
4995
+ schema = field3.required ? NumberWithUnitFieldValue : NumberWithUnitFieldUpdateValue;
4996
+ break;
4997
+ case FieldType.CHECKBOX:
4998
+ schema = CheckboxFieldValue;
4999
+ break;
5000
+ case FieldType.SIGNATURE:
5001
+ case FieldType.FILE:
5002
+ schema = FileFieldValue;
5003
+ break;
5004
+ case FieldType.FILE_WITH_OPTIONS:
5005
+ schema = field3.required ? FileFieldWithOptionValue.min(1) : FileFieldWithOptionValue;
5006
+ break;
5007
+ case FieldType.ADDRESS:
5008
+ schema = getDynamicAddressFieldValue(field3);
5009
+ break;
5010
+ case FieldType.DATA:
5011
+ schema = DataFieldValue;
5012
+ break;
5013
+ case FieldType.NAME:
5014
+ schema = actionType === ActionType.NOTIFY ? NameFieldUpdateValue : getDynamicNameValue(field3);
5015
+ break;
5016
+ case FieldType.BUTTON:
5017
+ schema = ButtonFieldValue;
5018
+ break;
5019
+ case FieldType.ALPHA_PRINT_BUTTON:
5020
+ schema = TextValue;
5021
+ break;
5022
+ case FieldType.AUTOCOMPLETE:
5023
+ schema = AutocompleteValue;
5024
+ break;
5025
+ case FieldType.HTTP:
5026
+ case FieldType.SEARCH:
5027
+ schema = HttpFieldUpdateValue;
5028
+ break;
5029
+ case FieldType.QUERY_PARAM_READER:
5030
+ schema = QueryParamReaderFieldUpdateValue;
5031
+ break;
5032
+ case FieldType.QR_READER:
5033
+ schema = QrReaderFieldValue;
5034
+ break;
5035
+ case FieldType.ID_READER:
5036
+ schema = IdReaderFieldValue;
5037
+ break;
5038
+ case FieldType._EXPERIMENTAL_CUSTOM:
5039
+ schema = CustomFieldValue;
5040
+ break;
5041
+ }
5042
+ return field3.required ? schema : schema.nullish();
5043
+ }
5044
+ function mapFieldTypeToEmptyValue(field3) {
5045
+ switch (field3.type) {
5046
+ case FieldType.FIELD_GROUP:
5047
+ const nestedEmpty = field3.fields.reduce(
5048
+ (acc, subfield) => ({
5049
+ ...acc,
5050
+ [subfield.id]: mapFieldTypeToEmptyValue(subfield)
5051
+ }),
5052
+ {}
5053
+ );
5054
+ return nestedEmpty;
5055
+ case FieldType.DIVIDER:
5056
+ case FieldType.TEXT:
5057
+ case FieldType.TEXTAREA:
5058
+ case FieldType.BULLET_LIST:
5059
+ case FieldType.PAGE_HEADER:
5060
+ case FieldType.LOCATION:
5061
+ case FieldType.SELECT:
5062
+ case FieldType.COUNTRY:
5063
+ case FieldType.RADIO_GROUP:
5064
+ case FieldType.PARAGRAPH:
5065
+ case FieldType.HEADING:
5066
+ case FieldType.IMAGE_VIEW:
5067
+ case FieldType.ADMINISTRATIVE_AREA:
5068
+ case FieldType.FACILITY:
5069
+ case FieldType.OFFICE:
5070
+ case FieldType.NUMBER:
5071
+ case FieldType.NUMBER_WITH_UNIT:
5072
+ case FieldType.EMAIL:
5073
+ case FieldType.DATE:
5074
+ case FieldType.AGE:
5075
+ case FieldType.TIME:
5076
+ case FieldType.CHECKBOX:
5077
+ case FieldType.DATE_RANGE:
5078
+ case FieldType.SELECT_DATE_RANGE:
5079
+ case FieldType.DATA:
5080
+ case FieldType.NAME:
5081
+ case FieldType.PHONE:
5082
+ case FieldType.BUTTON:
5083
+ case FieldType.ALPHA_PRINT_BUTTON:
5084
+ case FieldType.HTTP:
5085
+ case FieldType.AUTOCOMPLETE:
5086
+ case FieldType.SEARCH:
5087
+ case FieldType.LINK_BUTTON:
5088
+ case FieldType.QUERY_PARAM_READER:
5089
+ case FieldType.ID:
5090
+ case FieldType.VERIFICATION_STATUS:
5091
+ case FieldType.QR_READER:
5092
+ case FieldType.ID_READER:
5093
+ case FieldType.LOADER:
5094
+ case FieldType.ALPHA_HIDDEN:
5095
+ case FieldType.USER_ROLE:
5096
+ return null;
5097
+ case FieldType.ADDRESS:
5098
+ return {
5099
+ country: "",
5100
+ addressType: AddressType.DOMESTIC,
5101
+ administrativeArea: "",
5102
+ streetLevelDetails: {}
5103
+ };
5104
+ case FieldType.SIGNATURE:
5105
+ case FieldType.FILE:
5106
+ return {
5107
+ path: "",
5108
+ originalFilename: "",
5109
+ type: ""
5110
+ };
5111
+ case FieldType.FILE_WITH_OPTIONS:
5112
+ return [];
5113
+ case FieldType._EXPERIMENTAL_CUSTOM:
5114
+ return void 0;
5115
+ }
5116
+ }
5117
+ var isParagraphFieldType = (field3) => {
5118
+ return field3.config.type === FieldType.PARAGRAPH;
5119
+ };
5120
+ var isHeadingFieldType = (field3) => {
5121
+ return field3.config.type === FieldType.HEADING;
5122
+ };
5123
+ var isImageViewFieldType = (field3) => {
5124
+ return field3.config.type === FieldType.IMAGE_VIEW;
5125
+ };
5126
+ var isDateFieldType = (field3) => {
5127
+ return field3.config.type === FieldType.DATE;
5128
+ };
5129
+ var isAgeFieldType = (field3) => {
5130
+ return field3.config.type === FieldType.AGE;
5131
+ };
5132
+ var isTimeFieldType = (field3) => {
5133
+ return field3.config.type === FieldType.TIME;
5134
+ };
5135
+ var isDateRangeFieldType = (field3) => {
5136
+ return field3.config.type === FieldType.DATE_RANGE;
5137
+ };
5138
+ var isSelectDateRangeFieldType = (field3) => {
5139
+ return field3.config.type === FieldType.SELECT_DATE_RANGE;
5140
+ };
5141
+ var isPageHeaderFieldType = (field3) => {
5142
+ return field3.config.type === FieldType.PAGE_HEADER;
5143
+ };
5144
+ var isTextFieldType = (field3) => {
5145
+ return field3.config.type === FieldType.TEXT;
5146
+ };
5147
+ var isNumberFieldType = (field3) => {
5148
+ return field3.config.type === FieldType.NUMBER;
5149
+ };
5150
+ var isNumberWithUnitFieldType = (field3) => {
5151
+ return field3.config.type === FieldType.NUMBER_WITH_UNIT;
5152
+ };
5153
+ var isNameFieldType = (field3) => {
5154
+ return field3.config.type === FieldType.NAME;
5155
+ };
5156
+ var isPhoneFieldType = (field3) => {
5157
+ return field3.config.type === FieldType.PHONE;
5158
+ };
5159
+ var isIdFieldType = (field3) => {
5160
+ return field3.config.type === FieldType.ID;
5161
+ };
5162
+ var isTextAreaFieldType = (field3) => {
5163
+ return field3.config.type === FieldType.TEXTAREA;
5164
+ };
5165
+ var isSignatureFieldType = (field3) => {
5166
+ return field3.config.type === FieldType.SIGNATURE;
5167
+ };
5168
+ var isEmailFieldType = (field3) => {
5169
+ return field3.config.type === FieldType.EMAIL;
5170
+ };
5171
+ var isFileFieldType = (field3) => {
5172
+ return field3.config.type === FieldType.FILE;
5173
+ };
5174
+ var isFileFieldWithOptionType = (field3) => {
5175
+ return field3.config.type === FieldType.FILE_WITH_OPTIONS;
5176
+ };
5177
+ var isBulletListFieldType = (field3) => {
5178
+ return field3.config.type === FieldType.BULLET_LIST;
5179
+ };
5180
+ var isSelectFieldType = (field3) => {
5181
+ return field3.config.type === FieldType.SELECT;
5182
+ };
5183
+ var isAddressFieldType = (field3) => {
5184
+ return field3.config.type === FieldType.ADDRESS;
5185
+ };
5186
+ var isCountryFieldType = (field3) => {
5187
+ return field3.config.type === FieldType.COUNTRY;
5188
+ };
5189
+ var isCheckboxFieldType = (field3) => {
5190
+ return field3.config.type === FieldType.CHECKBOX;
5191
+ };
5192
+ var isRadioGroupFieldType = (field3) => {
5193
+ return field3.config.type === FieldType.RADIO_GROUP;
5194
+ };
5195
+ var isFieldGroupFieldType = (field3) => {
5196
+ return field3.config.type === FieldType.FIELD_GROUP;
5197
+ };
5198
+ var isLocationFieldType = (field3) => {
5199
+ return field3.config.type === FieldType.LOCATION;
5200
+ };
5201
+ var isDividerFieldType = (field3) => {
5202
+ return field3.config.type === FieldType.DIVIDER;
5203
+ };
5204
+ var isAdministrativeAreaFieldType = (field3) => {
5205
+ return field3.config.type === FieldType.ADMINISTRATIVE_AREA;
5206
+ };
5207
+ var isFacilityFieldType = (field3) => {
5208
+ return field3.config.type === FieldType.FACILITY;
5209
+ };
5210
+ var isOfficeFieldType = (field3) => {
5211
+ return field3.config.type === FieldType.OFFICE;
5212
+ };
5213
+ var isDataFieldType = (field3) => {
5214
+ return field3.config.type === FieldType.DATA;
5215
+ };
5216
+ var isButtonFieldType = (field3) => {
5217
+ return field3.config.type === FieldType.BUTTON;
5218
+ };
5219
+ var isPrintButtonFieldType = (field3) => {
5220
+ return field3.config.type === FieldType.ALPHA_PRINT_BUTTON;
5221
+ };
5222
+ var isHttpFieldType = (field3) => {
5223
+ return field3.config.type === FieldType.HTTP;
5224
+ };
5225
+ var isAutocompleteFieldType = (field3) => {
5226
+ return field3.config.type === FieldType.AUTOCOMPLETE;
5227
+ };
5228
+ var isSearchFieldType = (field3) => {
5229
+ return field3.config.type === FieldType.SEARCH;
5230
+ };
5231
+ var isLinkButtonFieldType = (field3) => {
5232
+ return field3.config.type === FieldType.LINK_BUTTON;
5233
+ };
5234
+ var isVerificationStatusType = (field3) => {
5235
+ return field3.config.type === FieldType.VERIFICATION_STATUS;
5236
+ };
5237
+ var isQueryParamReaderFieldType = (field3) => {
5238
+ return field3.config.type === FieldType.QUERY_PARAM_READER;
5239
+ };
5240
+ var isQrReaderFieldType = (field3) => {
5241
+ return field3.config.type === FieldType.QR_READER;
5242
+ };
5243
+ var isIdReaderFieldType = (field3) => {
5244
+ return field3.config.type === FieldType.ID_READER;
5245
+ };
5246
+ var isLoaderFieldType = (field3) => {
5247
+ return field3.config.type === FieldType.LOADER;
5248
+ };
5249
+ var isCustomFieldType = (field3) => {
5250
+ return field3.config.type === FieldType._EXPERIMENTAL_CUSTOM;
5251
+ };
5252
+ var isUserRoleFieldType = (field3) => {
5253
+ return field3.config.type === FieldType.USER_ROLE;
5254
+ };
5255
+ var isHiddenFieldType = (field3) => {
5256
+ return field3.config.type === FieldType.ALPHA_HIDDEN;
5257
+ };
5258
+ var isNonInteractiveFieldType = (field3) => {
5259
+ return field3.type === FieldType.DIVIDER || field3.type === FieldType.PAGE_HEADER || field3.type === FieldType.PARAGRAPH || field3.type === FieldType.HEADING || field3.type === FieldType.BULLET_LIST || field3.type === FieldType.DATA || field3.type === FieldType.ALPHA_PRINT_BUTTON || field3.type === FieldType.LINK_BUTTON || field3.type === FieldType.LOADER;
5260
+ };
5261
+
5262
+ // ../commons/src/events/state/index.ts
5263
+ var import_lodash3 = require("lodash");
5264
+
5265
+ // ../commons/src/events/state/utils.ts
5266
+ var import_lodash = require("lodash");
5267
+ function getActionRequests(actionType, actions) {
5268
+ const filtered = actions.filter((action) => action.type === actionType).reverse();
5269
+ const accept = filtered.find(
5270
+ (action) => action.status === ActionStatus.Accepted
5271
+ );
5272
+ const request = filtered.find(
5273
+ (action) => action.status === ActionStatus.Requested
5274
+ );
5275
+ const reject = filtered.find(
5276
+ (action) => action.status === ActionStatus.Rejected
5277
+ );
5278
+ return {
5279
+ reject,
5280
+ accept,
5281
+ request
5282
+ };
5283
+ }
5284
+ function getDeclarationActionCreationMetadata(actionType, actions) {
5285
+ const { accept: acceptAction, request: requestAction } = getActionRequests(
5286
+ actionType,
5287
+ actions
5288
+ );
5289
+ if (!acceptAction) {
5290
+ return null;
5291
+ }
5292
+ const registrationNumber = acceptAction.type === ActionType.REGISTER ? acceptAction.registrationNumber : null;
5293
+ return {
5294
+ // When 3rd party API returns 200 OK, we assume that the request was accepted, and persist single 'accepted' action.
5295
+ createdAt: requestAction?.createdAt ?? acceptAction.createdAt,
5296
+ createdBy: requestAction?.createdBy ?? acceptAction.createdBy,
5297
+ createdByUserType: requestAction?.createdByUserType ?? acceptAction.createdByUserType,
5298
+ createdAtLocation: requestAction?.createdAtLocation ?? acceptAction.createdAtLocation,
5299
+ acceptedAt: acceptAction.createdAt,
5300
+ createdByRole: requestAction?.createdByRole ?? acceptAction.createdByRole,
5301
+ registrationNumber
5302
+ };
5303
+ }
5304
+ var updateActions = new Set(
5305
+ ActionTypes.extract([
5306
+ ActionType.CREATE,
5307
+ ActionType.NOTIFY,
5308
+ ActionType.EDIT,
5309
+ ActionType.DECLARE,
5310
+ ActionType.REGISTER,
5311
+ ActionType.REJECT,
5312
+ ActionType.ARCHIVE,
5313
+ ActionType.UNARCHIVE,
5314
+ ActionType.PRINT_CERTIFICATE,
5315
+ ActionType.REQUEST_CORRECTION,
5316
+ ActionType.APPROVE_CORRECTION,
5317
+ ActionType.REJECT_CORRECTION,
5318
+ ActionType.REVOKE_REGISTRATION,
5319
+ ActionType.REINSTATE_REGISTRATION,
5320
+ ActionType.CUSTOM
5321
+ ]).options
5322
+ );
5323
+ function getActionUpdateMetadata(actions) {
5324
+ const createAction = getOrThrow(
5325
+ actions.find((action) => action.type === ActionType.CREATE),
5326
+ `Event has no ${ActionType.CREATE} action`
5327
+ );
5328
+ const metadataFields = [
5329
+ "createdAt",
5330
+ "createdBy",
5331
+ "createdByUserType",
5332
+ "createdAtLocation",
5333
+ "createdByRole"
5334
+ ];
5335
+ return actions.filter(({ type }) => updateActions.has(type)).reduce(
5336
+ (_2, action) => {
5337
+ if (action.originalActionId) {
5338
+ const originalAction = actions.find(({ id }) => id === action.originalActionId) ?? action;
5339
+ return (0, import_lodash.pick)(originalAction, metadataFields);
5340
+ }
5341
+ return (0, import_lodash.pick)(action, metadataFields);
5342
+ },
5343
+ (0, import_lodash.pick)(createAction, metadataFields)
5344
+ );
5345
+ }
5346
+ function getLegalStatuses(actions, status2) {
5347
+ return {
5348
+ [EventStatus.enum.NOTIFIED]: getDeclarationActionCreationMetadata(
5349
+ ActionType.NOTIFY,
5350
+ actions
5351
+ ),
5352
+ [EventStatus.enum.DECLARED]: getDeclarationActionCreationMetadata(
5353
+ ActionType.DECLARE,
5354
+ actions
5355
+ ),
5356
+ [EventStatus.enum.REGISTERED]: getDeclarationActionCreationMetadata(
5357
+ ActionType.REGISTER,
5358
+ actions
5359
+ ),
5360
+ // A later reinstate does not remove the revoke action, so only report it while the record is still revoked.
5361
+ [EventStatus.enum.REVOKED]: status2 === EventStatus.enum.REVOKED ? getDeclarationActionCreationMetadata(
5362
+ ActionType.REVOKE_REGISTRATION,
5363
+ actions
5364
+ ) : null
5365
+ };
5366
+ }
5367
+
5368
+ // ../commons/src/events/state/flags.ts
5369
+ var import_lodash2 = require("lodash");
5370
+ var import_date_fns = require("date-fns");
5371
+ function findPendingCorrectionAction(writeActions2) {
5372
+ let correctionRequestAction;
5373
+ for (let i = writeActions2.length - 1; i >= 0; i--) {
5374
+ const action = writeActions2[i];
5375
+ if (action.type === ActionType.APPROVE_CORRECTION || action.type === ActionType.REJECT_CORRECTION) {
5376
+ break;
5377
+ }
5378
+ if (action.type === ActionType.REQUEST_CORRECTION) {
5379
+ correctionRequestAction = action;
5380
+ break;
5381
+ }
5382
+ }
5383
+ return correctionRequestAction;
5384
+ }
5385
+ function isPotentialDuplicate(actions) {
5386
+ return actions.reduce((prev, { type }) => {
5387
+ if (type === ActionType.DUPLICATE_DETECTED) {
5388
+ return true;
5389
+ }
5390
+ if (type === ActionType.MARK_AS_NOT_DUPLICATE || type === ActionType.MARK_AS_DUPLICATE) {
5391
+ return false;
5392
+ }
5393
+ return prev;
5394
+ }, false);
5395
+ }
5396
+ function isFlagConditionMet(conditional, form, action, event2) {
5397
+ const now2 = (0, import_date_fns.isValid)((0, import_date_fns.parseISO)(action.createdAt)) ? (0, import_date_fns.formatISO)((0, import_date_fns.parseISO)(action.createdAt), { representation: "date" }) : (0, import_date_fns.formatISO)(/* @__PURE__ */ new Date(), { representation: "date" });
5398
+ return validate(conditional, {
5399
+ $form: form,
5400
+ $now: now2,
5401
+ $online: true,
5402
+ $event: event2,
5403
+ $user: {
5404
+ sub: "",
5405
+ exp: "",
5406
+ role: action.createdByRole,
5407
+ algorithm: "",
5408
+ scope: [],
5409
+ userType: action.createdByUserType
5410
+ }
5411
+ });
5412
+ }
5413
+ function actionConfigRemovesFlag(action, flagId, actionsUpToAndIncluding, event2, eventConfiguration) {
5414
+ if (!isActionConfigType(action.type)) {
5415
+ return false;
5416
+ }
5417
+ const actionConfig = getActionConfig({
5418
+ eventConfiguration,
5419
+ actionType: action.type,
5420
+ customActionType: "customActionType" in action ? action.customActionType : void 0
5421
+ });
5422
+ const removeOperations = (actionConfig?.flags ?? []).filter(
5423
+ ({ id, operation }) => id === flagId && operation === "remove"
5424
+ );
5425
+ if (removeOperations.length === 0) {
5426
+ return false;
5427
+ }
5428
+ const eventUpToThisAction = { ...event2, actions: actionsUpToAndIncluding };
5429
+ const declaration = aggregateActionDeclarations(eventUpToThisAction);
5430
+ const annotation = aggregateActionAnnotations(eventUpToThisAction);
5431
+ const form = { ...declaration, ...annotation };
5432
+ return removeOperations.some(
5433
+ ({ conditional }) => conditional ? isFlagConditionMet(conditional, form, action, eventUpToThisAction) : true
5434
+ );
5435
+ }
5436
+ var INHERENT_FLAG_RULES = [
5437
+ {
5438
+ flag: InherentFlags.CORRECTION_REQUESTED,
5439
+ setOn: [ActionType.REQUEST_CORRECTION],
5440
+ resetOn: [ActionType.APPROVE_CORRECTION, ActionType.REJECT_CORRECTION]
5441
+ },
5442
+ {
5443
+ flag: InherentFlags.REJECTED,
5444
+ setOn: [ActionType.REJECT],
5445
+ resetOn: [
5446
+ ActionType.NOTIFY,
5447
+ ActionType.DECLARE,
5448
+ ActionType.EDIT,
5449
+ ActionType.REGISTER
5450
+ ]
5451
+ },
5452
+ {
5453
+ flag: InherentFlags.POTENTIAL_DUPLICATE,
5454
+ setOn: [ActionType.DUPLICATE_DETECTED],
5455
+ resetOn: [ActionType.MARK_AS_DUPLICATE, ActionType.MARK_AS_NOT_DUPLICATE]
5456
+ },
5457
+ {
5458
+ flag: InherentFlags.EDIT_IN_PROGRESS,
5459
+ setOn: [ActionType.EDIT],
5460
+ resetOnAnyOtherAction: true
5461
+ }
5462
+ ];
5463
+ function resolveInherentFlag(rule, acceptedActions, event2, eventConfiguration) {
5464
+ return acceptedActions.reduce((present, action, idx) => {
5465
+ if (rule.setOn.includes(action.type)) {
5466
+ return true;
5467
+ }
5468
+ if (rule.resetOnAnyOtherAction || (rule.resetOn ?? []).includes(action.type)) {
5469
+ return false;
5470
+ }
5471
+ if (actionConfigRemovesFlag(
5472
+ action,
5473
+ rule.flag,
5474
+ acceptedActions.slice(0, idx + 1),
5475
+ event2,
5476
+ eventConfiguration
5477
+ )) {
5478
+ return false;
5479
+ }
5480
+ return present;
5481
+ }, false);
5482
+ }
5483
+ function resolveEventCustomFlags(event2, eventConfiguration) {
5484
+ const actions = getAcceptedActions(event2).filter(({ type }) => !isMetaAction(type)).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
5485
+ const declarations = getDeclarationAfterEachAction({ ...event2, actions });
5486
+ let annotation = {};
5487
+ return actions.reduce((acc, action, idx) => {
5488
+ if (action.annotation) {
5489
+ annotation = deepMerge(annotation, action.annotation);
5490
+ }
5491
+ let actionConfig;
5492
+ if (isActionConfigType(action.type)) {
5493
+ actionConfig = getActionConfig({
5494
+ eventConfiguration,
5495
+ actionType: action.type,
5496
+ customActionType: "customActionType" in action ? action.customActionType : void 0
5459
5497
  });
5460
- },
5461
- /**
5462
- * Custom client-side evaluation. Returns a {@link FieldReference} descriptor
5463
- * that can be used as the `value` property or a DATA component entry.
5464
- * The function receives the referenced field's value as the first argument and
5465
- * the full form context as the second; its return value replaces the field reference.
5466
- * The function is serialised and executed just-in-time on the client only.
5467
- * External references (e.g. lodash) are not available inside the function body.
5468
- *
5469
- * For computing a default value without referencing a specific field, use
5470
- * `evaluate(fn)` in the `defaultValue` property instead.
5471
- *
5472
- * @example
5473
- * field('a').customClientEvaluation((aValue, ctx) =>
5474
- * Number(aValue) + Number(ctx.$form.b)
5475
- * )
5476
- */
5477
- customClientEvaluation(computationFn) {
5478
- return {
5479
- $$code: computationFn.toString(),
5480
- $$field: fieldId,
5481
- $$subfield: this.$$subfield
5482
- };
5483
5498
  }
5484
- };
5499
+ if (!actionConfig) {
5500
+ return acc;
5501
+ }
5502
+ const form = { ...declarations[idx], ...annotation };
5503
+ const eventUpToThisAction = { ...event2, actions: actions.slice(0, idx + 1) };
5504
+ const flagsWithMetConditions = (actionConfig.flags ?? []).filter(
5505
+ ({ conditional }) => (
5506
+ // If conditional is not provided, the flag is resolved
5507
+ conditional ? isFlagConditionMet(conditional, form, action, eventUpToThisAction) : true
5508
+ )
5509
+ );
5510
+ const addedFlags = flagsWithMetConditions.filter(({ operation }) => operation === "add").map(({ id }) => id);
5511
+ const removedFlags = flagsWithMetConditions.filter(({ operation }) => operation === "remove").map(({ id }) => id);
5512
+ const flags = [...acc, ...addedFlags].filter(
5513
+ (flagId) => !removedFlags.includes(flagId)
5514
+ );
5515
+ return (0, import_lodash2.uniq)(flags);
5516
+ }, []);
5517
+ }
5518
+ function getActionStatusFlags(sortedActions) {
5519
+ const actionStatus = sortedActions.reduce(
5520
+ (actionStatuses, { type, status: status2 }) => ({
5521
+ ...actionStatuses,
5522
+ [type]: status2
5523
+ }),
5524
+ {}
5525
+ );
5526
+ return Object.entries(actionStatus).filter(([, status2]) => status2 !== ActionStatus.Accepted).map(([type, status2]) => {
5527
+ const flag2 = joinValues([type, status2], ":").toLowerCase();
5528
+ return flag2;
5529
+ });
5530
+ }
5531
+ function getInherentFlags(sortedActions, event2, eventConfiguration) {
5532
+ const acceptedActions = sortedActions.filter(
5533
+ ({ status: status2 }) => status2 === ActionStatus.Accepted
5534
+ );
5535
+ return INHERENT_FLAG_RULES.filter(
5536
+ (rule) => resolveInherentFlag(rule, acceptedActions, event2, eventConfiguration)
5537
+ ).map(({ flag: flag2 }) => flag2);
5538
+ }
5539
+ function getEventFlags(event2, config) {
5540
+ const sortedActions = event2.actions.filter(({ type }) => !isMetaAction(type)).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
5541
+ return [
5542
+ ...getActionStatusFlags(sortedActions),
5543
+ ...getInherentFlags(sortedActions, event2, config),
5544
+ ...resolveEventCustomFlags(event2, config)
5545
+ ];
5485
5546
  }
5486
5547
 
5487
5548
  // ../commons/src/events/state/index.ts
@@ -5642,6 +5703,7 @@ function getCurrentEventState(event2, config) {
5642
5703
  updatedAtLocation: requestActionMetadata.createdAtLocation,
5643
5704
  declaration,
5644
5705
  trackingId: event2.trackingId,
5706
+ configVersionId: event2.configVersionId,
5645
5707
  updatedByUserRole: requestActionMetadata.createdByRole,
5646
5708
  placeOfEvent: resolvePlaceOfEvent(
5647
5709
  { createdAtLocation: creationAction.createdAtLocation },
@@ -5779,6 +5841,15 @@ function resolveDataPath(rootData, dataPath, instancePath) {
5779
5841
  }
5780
5842
  return current;
5781
5843
  }
5844
+ function resolveActionDate(event2, { match, occurrence }) {
5845
+ const dates = (event2?.actions ?? []).filter(({ status: status2 }) => status2 === ActionStatus.Accepted).filter(
5846
+ (action) => match.some(
5847
+ ({ type, customActionType }) => action.type === type && (!customActionType || "customActionType" in action && action.customActionType === customActionType)
5848
+ )
5849
+ ).map(({ createdAt }) => createdAt).sort();
5850
+ const date = occurrence === "first" ? dates[0] : dates[dates.length - 1];
5851
+ return date && (0, import_date_fns2.formatISO)((0, import_date_fns2.parseISO)(date), { representation: "date" });
5852
+ }
5782
5853
  function todayISO() {
5783
5854
  return (0, import_date_fns2.formatISO)(/* @__PURE__ */ new Date(), { representation: "date" });
5784
5855
  }
@@ -5800,7 +5871,9 @@ function buildClientFunctionContext(input) {
5800
5871
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
5801
5872
  $online: isOnline(),
5802
5873
  $user: input.validatorContext?.user,
5803
- $event: input.validatorContext?.event?.document,
5874
+ $event: input.validatorContext?.event?.document ? getEventWithCompleteAcceptedActions(
5875
+ input.validatorContext.event.document
5876
+ ) : void 0,
5804
5877
  $leafAdminStructureLocationIds: input.validatorContext?.leafAdminStructureLocationIds ?? [],
5805
5878
  user: input.systemVariables?.user,
5806
5879
  $window: input.systemVariables?.$window,
@@ -5830,6 +5903,10 @@ ajv.addKeyword({
5830
5903
  return false;
5831
5904
  }
5832
5905
  let referenceDate = schema.referenceDate;
5906
+ if (isActionDateReference(referenceDate)) {
5907
+ const rootData = dataContext.rootData;
5908
+ referenceDate = resolveActionDate(rootData.$event, referenceDate.$action);
5909
+ }
5833
5910
  if (referenceDate && typeof referenceDate === "object" && "$data" in referenceDate) {
5834
5911
  referenceDate = resolveDataPath(
5835
5912
  dataContext.rootData,
@@ -6321,14 +6398,25 @@ function getDeclarationPages(configuration) {
6321
6398
  function getDeclarationFields(configuration) {
6322
6399
  return getDeclarationPages(configuration).flatMap(({ fields }) => fields);
6323
6400
  }
6324
- function getConfiguredNotificationForm(configuration) {
6401
+ function getDeclarationFieldsOfAllVersions(config) {
6402
+ const oldestFirst = [...config.versions].sort(byEffectiveFrom);
6403
+ const fieldsById = new Map(
6404
+ oldestFirst.flatMap(
6405
+ (version) => getDeclarationFields(toEventConfig(config, version)).map(
6406
+ (field3) => [field3.id, field3]
6407
+ )
6408
+ )
6409
+ );
6410
+ return [...fieldsById.values()];
6411
+ }
6412
+ function findNotificationForm(configuration) {
6325
6413
  const notifyAction = configuration.actions.find(
6326
6414
  (action) => action.type === ActionType.NOTIFY
6327
6415
  );
6328
6416
  return notifyAction?.type === ActionType.NOTIFY ? notifyAction.notificationForm : void 0;
6329
6417
  }
6330
6418
  function getNotificationForm(configuration) {
6331
- const notificationForm = getConfiguredNotificationForm(configuration);
6419
+ const notificationForm = findNotificationForm(configuration);
6332
6420
  if (!notificationForm) {
6333
6421
  throw new Error(
6334
6422
  `Event '${configuration.id}' has no ${ActionType.NOTIFY} action.`
@@ -6604,9 +6692,7 @@ function isWriteAction(actionType) {
6604
6692
  var findAllFields = (config) => {
6605
6693
  return (0, import_lodash4.flattenDeep)([
6606
6694
  ...getDeclarationFields(config),
6607
- ...getConfiguredNotificationForm(config)?.pages.flatMap(
6608
- ({ fields }) => fields
6609
- ) ?? [],
6695
+ ...findNotificationForm(config)?.pages.flatMap(({ fields }) => fields) ?? [],
6610
6696
  ...getAllAnnotationFields(config)
6611
6697
  ]);
6612
6698
  };
@@ -6629,10 +6715,10 @@ function getMixedPath(obj, path, defaultValue) {
6629
6715
  return (0, import_lodash4.isNil)(result) ? defaultValue : result;
6630
6716
  }
6631
6717
  function getEventConfigById(eventConfigs, id) {
6632
- const eventConfig = eventConfigs.find(
6633
- (eventConfiguration) => eventConfiguration.id === id
6718
+ return getOrThrow(
6719
+ eventConfigs.find((eventConfiguration) => eventConfiguration.id === id),
6720
+ `No configuration found for event type: ${id}`
6634
6721
  );
6635
- return getOrThrow(eventConfig, `Event config for ${id} not found`);
6636
6722
  }
6637
6723
  function timePeriodToDateRange(value) {
6638
6724
  let startDate;
@@ -6742,12 +6828,41 @@ function getCompleteActionDeclaration(declaration, event2, action) {
6742
6828
  }
6743
6829
  return deepMerge(declaration, action.declaration);
6744
6830
  }
6745
- function getAcceptedActions(event2) {
6746
- return event2.actions.filter(isAcceptedAction).map((action) => ({
6831
+ function completeAcceptedAction(event2, action) {
6832
+ return {
6747
6833
  ...action,
6748
6834
  declaration: getCompleteActionDeclaration({}, event2, action),
6749
6835
  annotation: getCompleteActionAnnotation(event2, action)
6750
- }));
6836
+ };
6837
+ }
6838
+ function getAcceptedActions(event2) {
6839
+ return event2.actions.filter(isAcceptedAction).map((action) => completeAcceptedAction(event2, action));
6840
+ }
6841
+ function getEventWithCompleteAcceptedActions(event2) {
6842
+ return {
6843
+ ...event2,
6844
+ actions: event2.actions.map((action) => {
6845
+ if (!isAcceptedAction(action) || !action.originalActionId) {
6846
+ return action;
6847
+ }
6848
+ const requestedAction = event2.actions.find(
6849
+ ({ id }) => id === action.originalActionId
6850
+ );
6851
+ if (requestedAction?.status !== ActionStatus.Requested) {
6852
+ return action;
6853
+ }
6854
+ const content = getCompleteActionContent(event2, action);
6855
+ return {
6856
+ ...completeAcceptedAction(event2, action),
6857
+ // Who requested the action, as getActionUpdateMetadata resolves it.
6858
+ createdBy: requestedAction.createdBy,
6859
+ createdByRole: requestedAction.createdByRole,
6860
+ createdByUserType: requestedAction.createdByUserType,
6861
+ createdAtLocation: requestedAction.createdAtLocation,
6862
+ ...content ? { content } : {}
6863
+ };
6864
+ })
6865
+ };
6751
6866
  }
6752
6867
  var EXCLUDED_ACTIONS = [
6753
6868
  ActionType.REQUEST_CORRECTION,
@@ -6846,6 +6961,20 @@ function dropSecuredDeclarationFields(eventConfig, eventIndex, validatorContext)
6846
6961
  }
6847
6962
 
6848
6963
  // ../commons/src/events/eventConfigValidation.ts
6964
+ var SEARCH_DEFAULT_VALUE_FIELD_TYPES = [
6965
+ FieldType.TEXT,
6966
+ FieldType.TEXTAREA,
6967
+ FieldType.EMAIL,
6968
+ FieldType.PHONE,
6969
+ FieldType.ID,
6970
+ FieldType.SELECT,
6971
+ FieldType.RADIO_GROUP,
6972
+ FieldType.COUNTRY,
6973
+ FieldType.LOCATION,
6974
+ FieldType.ADMINISTRATIVE_AREA,
6975
+ FieldType.NUMBER,
6976
+ FieldType.DATE
6977
+ ];
6849
6978
  function validateAdvancedSearchConfig(event2, ctx) {
6850
6979
  const allFields = findAllFields(event2);
6851
6980
  const fieldIds = allFields.map((field3) => field3.id);
@@ -6877,6 +7006,56 @@ function validateAdvancedSearchConfig(event2, ctx) {
6877
7006
  path: ["advancedSearch"]
6878
7007
  });
6879
7008
  }
7009
+ event2.advancedSearch.forEach((section, sectionIndex) => {
7010
+ section.fields.forEach((searchField, fieldIndex) => {
7011
+ if (searchField.fieldType !== "field" || searchField.defaultValue === void 0) {
7012
+ return;
7013
+ }
7014
+ const path = [
7015
+ "advancedSearch",
7016
+ sectionIndex,
7017
+ "fields",
7018
+ fieldIndex,
7019
+ "defaultValue"
7020
+ ];
7021
+ if (searchField.config.searchFields && searchField.config.searchFields.length > 0) {
7022
+ ctx.addIssue({
7023
+ code: "custom",
7024
+ message: `Advanced search field ${searchField.fieldId} searches across several form fields, so it does not support a defaultValue.`,
7025
+ path
7026
+ });
7027
+ return;
7028
+ }
7029
+ if (typeof searchField.defaultValue === "boolean") {
7030
+ return;
7031
+ }
7032
+ const formField = allFields.find(({ id }) => id === searchField.fieldId);
7033
+ if (!formField) {
7034
+ return;
7035
+ }
7036
+ if (!SEARCH_DEFAULT_VALUE_FIELD_TYPES.some(
7037
+ (type) => type === formField.type
7038
+ )) {
7039
+ ctx.addIssue({
7040
+ code: "custom",
7041
+ message: `Advanced search field ${searchField.fieldId} is a ${formField.type} field, which does not support a defaultValue value, only true or false. Field types that support a defaultValue value: ${SEARCH_DEFAULT_VALUE_FIELD_TYPES.join(", ")}.`,
7042
+ path
7043
+ });
7044
+ } else if (formField.type === FieldType.DATE && searchField.config.type === "range") {
7045
+ ctx.addIssue({
7046
+ code: "custom",
7047
+ message: `Advanced search field ${searchField.fieldId} is searched as a date range, so its defaultValue can only be true or false.`,
7048
+ path
7049
+ });
7050
+ } else if (!mapFieldTypeToZod(formField).safeParse(searchField.defaultValue).success) {
7051
+ ctx.addIssue({
7052
+ code: "custom",
7053
+ message: `Advanced search field ${searchField.fieldId} has defaultValue "${searchField.defaultValue}", which is not a valid ${formField.type} value.`,
7054
+ path
7055
+ });
7056
+ }
7057
+ });
7058
+ });
6880
7059
  }
6881
7060
  function validateDateOfEvent(event2, ctx) {
6882
7061
  if (event2.dateOfEvent && isFieldReference(event2.dateOfEvent)) {
@@ -7049,10 +7228,16 @@ function validateNotificationForm(event2, ctx) {
7049
7228
  var EventFieldReference = z35.object({ $$event: EventMetadataDateFieldIdInput }).describe(
7050
7229
  "Reference to a field defined in the event metadata, using the field id."
7051
7230
  );
7052
- var _EventConfigBase = z35.object({
7231
+ var eventLevelFields = {
7053
7232
  id: z35.string().describe(
7054
7233
  'Machine-readable identifier of the event (e.g. "birth", "death").'
7055
7234
  ),
7235
+ label: TranslationConfig.describe("Human-readable label for the event type."),
7236
+ advancedSearch: z35.array(AdvancedSearchConfig).optional().default([]).describe(
7237
+ "Configuration of fields available in the advanced search feature."
7238
+ )
7239
+ };
7240
+ var versionFields = {
7056
7241
  dateOfEvent: FieldReference.or(EventFieldReference).optional().describe(
7057
7242
  "Reference to the field capturing the date of the event (e.g. date of birth). Defaults to the event creation date if unspecified."
7058
7243
  ),
@@ -7068,18 +7253,12 @@ var _EventConfigBase = z35.object({
7068
7253
  summary: SummaryConfig.describe(
7069
7254
  "Summary information displayed in the event overview."
7070
7255
  ),
7071
- label: TranslationConfig.describe(
7072
- "Human-readable label for the event type."
7073
- ),
7074
7256
  actions: z35.array(ActionConfig).describe(
7075
7257
  "Configuration of core and custom actions associated with the event."
7076
7258
  ),
7077
7259
  actionOrder: z35.array(z35.string()).optional().describe(
7078
7260
  "Order of actions in the action menu. Use either the action type for core actions or the customActionType for custom actions."
7079
7261
  ),
7080
- advancedSearch: z35.array(AdvancedSearchConfig).optional().default([]).describe(
7081
- "Configuration of fields available in the advanced search feature."
7082
- ),
7083
7262
  flags: z35.array(FlagConfig).optional().default([]).describe(
7084
7263
  "Configuration of custom flags associated with the actions of this event type."
7085
7264
  ),
@@ -7089,8 +7268,9 @@ var _EventConfigBase = z35.object({
7089
7268
  icon: z35.partialRecord(AvailableIcons, Conditional).optional().describe(
7090
7269
  'Maps an icon name to a conditional. The icon of the first entry (in definition order) whose conditional matches the event is used when rendering it (e.g. in the "iconWithName"/"iconWithNameEvent" workqueue columns). Falls back to the default status-based icon when unset or when no conditional matches.'
7091
7270
  )
7092
- });
7093
- var EventConfig = _EventConfigBase.superRefine((event2, ctx) => {
7271
+ };
7272
+ var _EventConfigBase = z35.object({ ...eventLevelFields, ...versionFields });
7273
+ function validateEventConfig(event2, ctx) {
7094
7274
  if (!validateExactlyOneDeclareAction(event2, ctx)) {
7095
7275
  return;
7096
7276
  }
@@ -7100,10 +7280,168 @@ var EventConfig = _EventConfigBase.superRefine((event2, ctx) => {
7100
7280
  validatePlaceOfEvent(event2, ctx);
7101
7281
  validateActionFlags(event2, ctx);
7102
7282
  validateActionOrder(event2, ctx);
7103
- }).meta({
7283
+ }
7284
+ var EventConfig2 = _EventConfigBase.superRefine(validateEventConfig).meta({
7104
7285
  id: "EventConfig",
7105
7286
  description: "Configuration defining an event type registered in OpenCRVS (for example birth or death)."
7106
7287
  });
7288
+ var INITIAL_EVENT_CONFIG_VERSION_ID = "initial";
7289
+ var DEFAULT_EFFECTIVE_FROM = "0001-01-01";
7290
+ var _EventConfigVersion = z35.object({
7291
+ id: z35.string().describe(
7292
+ 'Identifier of the version, unique within the event (e.g. "birth-v2").'
7293
+ ),
7294
+ label: TranslationConfig.describe(
7295
+ 'Name of the version, which the UI shows wherever it names the version. For example, "{event.configVersionLabel}" in the event summary.'
7296
+ ),
7297
+ effectiveFrom: z35.iso.date().default(DEFAULT_EFFECTIVE_FROM).describe(
7298
+ `Date (YYYY-MM-DD) from which this version is effective. A version without one is effective from the beginning of time ('${DEFAULT_EFFECTIVE_FROM}').`
7299
+ ),
7300
+ ...versionFields
7301
+ });
7302
+ var resolvedConfigs = /* @__PURE__ */ new WeakMap();
7303
+ function toEventConfig(config, version) {
7304
+ let resolvedVersions = resolvedConfigs.get(config);
7305
+ if (!resolvedVersions) {
7306
+ resolvedVersions = /* @__PURE__ */ new WeakMap();
7307
+ resolvedConfigs.set(config, resolvedVersions);
7308
+ }
7309
+ const cached = resolvedVersions.get(version);
7310
+ if (cached) {
7311
+ return cached;
7312
+ }
7313
+ const {
7314
+ id: _id,
7315
+ label: _label,
7316
+ effectiveFrom: _effectiveFrom,
7317
+ ...fields
7318
+ } = version;
7319
+ const resolved = {
7320
+ ...fields,
7321
+ id: config.id,
7322
+ label: config.label,
7323
+ advancedSearch: config.advancedSearch
7324
+ };
7325
+ resolvedVersions.set(version, resolved);
7326
+ return resolved;
7327
+ }
7328
+ function findConfigVersion(config, versionId) {
7329
+ return config.versions.find(({ id }) => id === versionId);
7330
+ }
7331
+ function getConfigVersion(config, versionId) {
7332
+ return getOrThrow(
7333
+ findConfigVersion(config, versionId),
7334
+ `Event '${config.id}' has no version '${versionId}'`
7335
+ );
7336
+ }
7337
+ function getEventConfigOfVersion(config, versionId) {
7338
+ return toEventConfig(config, getConfigVersion(config, versionId));
7339
+ }
7340
+ function byEffectiveFrom(a, b) {
7341
+ return a.effectiveFrom.localeCompare(b.effectiveFrom);
7342
+ }
7343
+ function getVersionsInEffectOn(config, date) {
7344
+ return config.versions.filter(({ effectiveFrom }) => effectiveFrom <= date).sort(byEffectiveFrom);
7345
+ }
7346
+ function findVersionInEffectOn(config, date) {
7347
+ return getVersionsInEffectOn(config, date).at(-1);
7348
+ }
7349
+ function getVersionsInEffect(config, now2, timeZone) {
7350
+ return getVersionsInEffectOn(config, toPlainDateInTimeZone(now2, timeZone));
7351
+ }
7352
+ function resolveEffectiveVersion(config, now2, timeZone) {
7353
+ return findVersionInEffectOn(config, toPlainDateInTimeZone(now2, timeZone));
7354
+ }
7355
+ function findEventConfigForRecord(config, record8) {
7356
+ const version = findConfigVersion(config, record8.configVersionId);
7357
+ return version && toEventConfig(config, version);
7358
+ }
7359
+ function getEventConfigForRecord(config, record8) {
7360
+ return getEventConfigOfVersion(config, record8.configVersionId);
7361
+ }
7362
+ function resolveEventConfigOnDate(config, date) {
7363
+ return toEventConfig(
7364
+ config,
7365
+ getOrThrow(
7366
+ findVersionInEffectOn(config, date),
7367
+ `Event '${config.id}' has no version in effect on ${date}`
7368
+ )
7369
+ );
7370
+ }
7371
+ function resolveEventConfigInTimeZone(config, timeZone, now2 = /* @__PURE__ */ new Date()) {
7372
+ return resolveEventConfigOnDate(config, toPlainDateInTimeZone(now2, timeZone));
7373
+ }
7374
+ function resolveEventConfig(config) {
7375
+ return resolveEventConfigInTimeZone(config, "UTC");
7376
+ }
7377
+ function validateVersionList(config, ctx) {
7378
+ const ids = /* @__PURE__ */ new Set();
7379
+ const versionIdByEffectiveFrom = /* @__PURE__ */ new Map();
7380
+ config.versions.forEach((version, index) => {
7381
+ if (ids.has(version.id)) {
7382
+ ctx.addIssue({
7383
+ code: "custom",
7384
+ message: `Event '${config.id}' has more than one version with id '${version.id}'. Each version must have a different id.`,
7385
+ path: ["versions", index, "id"]
7386
+ });
7387
+ }
7388
+ ids.add(version.id);
7389
+ const sameEffectiveFromId = versionIdByEffectiveFrom.get(
7390
+ version.effectiveFrom
7391
+ );
7392
+ if (sameEffectiveFromId !== void 0) {
7393
+ const versionIds = `'${sameEffectiveFromId}', '${version.id}'`;
7394
+ ctx.addIssue({
7395
+ code: "custom",
7396
+ message: version.effectiveFrom !== DEFAULT_EFFECTIVE_FROM ? `Event '${config.id}' has more than one version with \`effectiveFrom\` '${version.effectiveFrom}' (${versionIds}). Each version must have a different \`effectiveFrom\`.` : `Event '${config.id}' has more than one version without \`effectiveFrom\` (${versionIds}). At most one version may omit it.`,
7397
+ path: ["versions", index, "effectiveFrom"]
7398
+ });
7399
+ } else {
7400
+ versionIdByEffectiveFrom.set(version.effectiveFrom, version.id);
7401
+ }
7402
+ });
7403
+ }
7404
+ function validateEachVersion(ctx, events, validate2) {
7405
+ const reported = /* @__PURE__ */ new Set();
7406
+ events.forEach((event2, index) => {
7407
+ const addIssue = (issue) => {
7408
+ if (typeof issue === "string") {
7409
+ ctx.addIssue({
7410
+ code: "custom",
7411
+ message: issue,
7412
+ path: ["versions", index]
7413
+ });
7414
+ return;
7415
+ }
7416
+ const [field3] = issue.path ?? [];
7417
+ const isEventLevel = typeof field3 === "string" && field3 in eventLevelFields;
7418
+ const path = isEventLevel ? issue.path ?? [] : ["versions", index, ...issue.path ?? []];
7419
+ const key = JSON.stringify([path, issue.message]);
7420
+ if (reported.has(key)) {
7421
+ return;
7422
+ }
7423
+ reported.add(key);
7424
+ ctx.addIssue({ ...issue, path });
7425
+ };
7426
+ validate2(event2, { value: event2, addIssue });
7427
+ });
7428
+ }
7429
+ var VersionedEventConfig2 = z35.object({
7430
+ ...eventLevelFields,
7431
+ versions: z35.array(_EventConfigVersion).min(1).describe(
7432
+ `Versions of the event configuration, each effective from its \`effectiveFrom\`. An event configured without versions has a single version, with id '${INITIAL_EVENT_CONFIG_VERSION_ID}' and \`effectiveFrom\` '${DEFAULT_EFFECTIVE_FROM}'.`
7433
+ )
7434
+ }).superRefine((config, ctx) => {
7435
+ validateVersionList(config, ctx);
7436
+ validateEachVersion(
7437
+ ctx,
7438
+ config.versions.map((version) => toEventConfig(config, version)),
7439
+ validateEventConfig
7440
+ );
7441
+ }).meta({
7442
+ id: "VersionedEventConfig",
7443
+ description: "Configuration of an event type registered in OpenCRVS (for example birth or death), with every version of it."
7444
+ });
7107
7445
 
7108
7446
  // ../commons/src/events/EventConfigInput.ts
7109
7447
  var defineDeclarationForm = (form) => DeclarationFormConfig.parse(form);
@@ -7201,9 +7539,20 @@ function createEventFieldConfig(fieldId) {
7201
7539
  function eventFn(fieldId) {
7202
7540
  return createEventFieldConfig(fieldId);
7203
7541
  }
7542
+ function actionDateReference(match, occurrence) {
7543
+ return {
7544
+ $action: {
7545
+ match: match.map((m) => typeof m === "string" ? { type: m } : m),
7546
+ occurrence
7547
+ }
7548
+ };
7549
+ }
7204
7550
  var event = Object.assign(eventFn, {
7205
7551
  /**
7206
- * Checks if the event contains a specific action type.
7552
+ * Checks if the event contains a specific accepted action type.
7553
+ * Only Accepted actions are matched: a confirmable action is stored as a
7554
+ * Requested and an Accepted action, and a pending or rejected request must
7555
+ * not count as the action having happened.
7207
7556
  * Can be used directly as a conditional or chained with additional methods.
7208
7557
  * @param action - The action type to check for.
7209
7558
  */
@@ -7221,9 +7570,12 @@ var event = Object.assign(eventFn, {
7221
7570
  properties: {
7222
7571
  type: {
7223
7572
  const: action
7573
+ },
7574
+ status: {
7575
+ const: ActionStatus.Accepted
7224
7576
  }
7225
7577
  },
7226
- required: ["type"]
7578
+ required: ["type", "status"]
7227
7579
  }
7228
7580
  }
7229
7581
  },
@@ -7234,9 +7586,10 @@ var event = Object.assign(eventFn, {
7234
7586
  });
7235
7587
  const buildActionConstraints = (additionalFields) => {
7236
7588
  const actionProperties = {
7237
- type: { const: action }
7589
+ type: { const: action },
7590
+ status: { const: ActionStatus.Accepted }
7238
7591
  };
7239
- const requiredFields = ["type"];
7592
+ const requiredFields = ["type", "status"];
7240
7593
  if (additionalFields) {
7241
7594
  Object.entries(additionalFields).forEach(([key, value]) => {
7242
7595
  actionProperties[key] = { const: value };
@@ -7310,6 +7663,16 @@ var event = Object.assign(eventFn, {
7310
7663
  $event: field3
7311
7664
  };
7312
7665
  },
7666
+ /**
7667
+ * References the date of the first action matching any of the given types,
7668
+ * e.g. `field('child.dob').isAfter().days(30).beforeAction(event.firstAction(ActionType.DECLARE))`.
7669
+ * Until a matching action exists, the comparison uses $now.
7670
+ */
7671
+ firstAction: (first, ...rest) => actionDateReference([first, ...rest], "first"),
7672
+ /**
7673
+ * Like {@link event.firstAction}, but references the most recent matching action.
7674
+ */
7675
+ lastAction: (first, ...rest) => actionDateReference([first, ...rest], "last"),
7313
7676
  /**
7314
7677
  * Checks if the event currently has the given status.
7315
7678
  * @param eventStatus - The status to check for.
@@ -7717,17 +8080,19 @@ var DraftInput = BaseActionInput.omit({ waitFor: true }).extend({
7717
8080
  /*
7718
8081
  * A draft can name a file that no action references. Such a file stays until
7719
8082
  * the record is deleted or the record's next action sweeps its prefix.
7720
- * DECLARE is available only where one of those is still coming: a created
7721
- * record, which can still be deleted, and a record part way through an edit,
7722
- * which is about to be declared or registered.
8083
+ * Drafts are therefore saved only on a created record, which can still be deleted.
8084
+ * The server refuses them on any other record.
7723
8085
  */
7724
- type: z40.literal(ActionTypes.enum.DECLARE),
8086
+ type: z40.enum([ActionTypes.enum.DECLARE, ActionTypes.enum.NOTIFY]),
7725
8087
  status: z40.enum([
7726
8088
  ActionStatus.Requested,
7727
8089
  ActionStatus.Accepted,
7728
8090
  ActionStatus.Rejected
7729
8091
  ])
7730
8092
  });
8093
+ var RemoteDraft = Draft.extend({
8094
+ action: Draft.shape.action.extend({ type: DraftInput.shape.type })
8095
+ });
7731
8096
 
7732
8097
  // ../commons/src/events/EventInput.ts
7733
8098
  var z41 = __toESM(require("zod/v4"));
@@ -7737,6 +8102,9 @@ var EventInput = z41.object({
7737
8102
  type: z41.string(),
7738
8103
  createdAtLocation: UUID.nullish().describe(
7739
8104
  "Location where the event occurred. Required for system users."
8105
+ ),
8106
+ configVersionId: z41.string().optional().describe(
8107
+ "Id of the event configuration version the client created the record under, e.g. while offline. Must be configured and not take effect in the future. Defaults to the version in effect when the server receives the record."
7740
8108
  )
7741
8109
  }).meta({ default: { transactionId: (0, import_uuid11.v4)(), type: "birth" } });
7742
8110
 
@@ -7752,6 +8120,9 @@ var EventDocument = z42.object({
7752
8120
  actions: z42.array(Action).describe("Ordered list of actions associated with the event."),
7753
8121
  trackingId: z42.string().describe(
7754
8122
  "System-generated tracking identifier used to look up the event."
8123
+ ),
8124
+ configVersionId: z42.string().describe(
8125
+ "Id of the event configuration version the record was created under. Every action on the record uses that version. Records created before versioning have 'initial'."
7755
8126
  )
7756
8127
  }).meta({ id: "EventDocument" });
7757
8128
  var EventDocumentOnlyLastAction = EventDocument.extend({
@@ -7771,16 +8142,69 @@ function moveDeclarationToDeclareAction({
7771
8142
  }
7772
8143
  return {
7773
8144
  ...config,
7774
- actions: config.actions.map(
7775
- (action) => action.type === ActionType.DECLARE && declaration ? { ...action, declaration } : action
7776
- )
8145
+ actions: config.actions.map((action) => {
8146
+ if (action.type !== ActionType.DECLARE) {
8147
+ return action;
8148
+ }
8149
+ const declarationOfAction = action.declaration ?? declaration;
8150
+ if (!declarationOfAction) {
8151
+ throw new Error(`Event '${config.id}' does not define \`declaration\`.`);
8152
+ }
8153
+ return { ...action, declaration: declarationOfAction };
8154
+ })
8155
+ };
8156
+ }
8157
+ var VERSIONED_EVENT_FIELDS = [
8158
+ "id",
8159
+ "label",
8160
+ "advancedSearch",
8161
+ "versions"
8162
+ ];
8163
+ function validateNoVersionFieldsAtTopLevel(config, ctx) {
8164
+ Object.keys(config).filter((key) => !VERSIONED_EVENT_FIELDS.includes(key)).forEach((key) => {
8165
+ ctx.addIssue({
8166
+ code: "custom",
8167
+ message: `Event '${config.id}' defines \`versions\`, so \`${key}\` must be defined on each version, not at the top level.`,
8168
+ path: [key]
8169
+ });
8170
+ });
8171
+ }
8172
+ function toVersionedInput(config) {
8173
+ if ("versions" in config) {
8174
+ return config;
8175
+ }
8176
+ const { id, label, advancedSearch, ...version } = moveDeclarationToDeclareAction(config);
8177
+ return {
8178
+ id,
8179
+ label,
8180
+ advancedSearch,
8181
+ versions: [{ ...version, id: INITIAL_EVENT_CONFIG_VERSION_ID, label }]
7777
8182
  };
7778
8183
  }
8184
+ var WESTERNMOST_TIME_ZONE = "Etc/GMT+12";
8185
+ function validateVersionInEffectToday(config, ctx) {
8186
+ const today = toPlainDateInTimeZone(/* @__PURE__ */ new Date(), WESTERNMOST_TIME_ZONE);
8187
+ const isAnyVersionInEffect = config.versions.some(
8188
+ ({ effectiveFrom }) => effectiveFrom <= today
8189
+ );
8190
+ if (!isAnyVersionInEffect) {
8191
+ ctx.addIssue({
8192
+ code: "custom",
8193
+ message: `Event '${config.id}' has no version in effect today (${today}, UTC\u221212, the last time zone to begin the day). At least one version must omit \`effectiveFrom\` or take effect on or before that date.`,
8194
+ path: ["versions"]
8195
+ });
8196
+ }
8197
+ }
7779
8198
  var EventConfigDefinition = z43.custom().superRefine((config, ctx) => {
7780
- if (validateExactlyOneDeclareAction(config, ctx)) {
7781
- validateDeclarationGivenExactlyOnce(config, ctx);
8199
+ if ("versions" in config) {
8200
+ validateNoVersionFieldsAtTopLevel(config, ctx);
8201
+ return;
8202
+ }
8203
+ const eventCtx = { ...ctx, value: config };
8204
+ if (validateExactlyOneDeclareAction(config, eventCtx)) {
8205
+ validateDeclarationGivenExactlyOnce(config, eventCtx);
7782
8206
  }
7783
- }).transform(moveDeclarationToDeclareAction).pipe(EventConfig);
8207
+ }).transform(toVersionedInput).pipe(VersionedEventConfig2).superRefine(validateVersionInEffectToday);
7784
8208
  var defineConfig = (config) => EventConfigDefinition.parse(config);
7785
8209
 
7786
8210
  // ../commons/src/events/toNotificationForm.ts
@@ -9071,7 +9495,7 @@ var TENNIS_CLUB_DECLARATION_FORM = defineDeclarationForm({
9071
9495
  });
9072
9496
 
9073
9497
  // ../commons/src/fixtures/tennis-club-membership-event.ts
9074
- var tennisClubMembershipEvent = defineConfig({
9498
+ var versionedTennisClubMembershipEvent = defineConfig({
9075
9499
  id: TENNIS_CLUB_MEMBERSHIP,
9076
9500
  declaration: TENNIS_CLUB_DECLARATION_FORM,
9077
9501
  label: {
@@ -9428,9 +9852,12 @@ var tennisClubMembershipEvent = defineConfig({
9428
9852
  }
9429
9853
  ]
9430
9854
  });
9855
+ var tennisClubMembershipEvent = resolveEventConfig(
9856
+ versionedTennisClubMembershipEvent
9857
+ );
9431
9858
 
9432
9859
  // ../commons/src/fixtures/football-club-membership-event.ts
9433
- var footballClubMembershipEvent = defineConfig({
9860
+ var versionedFootballClubMembershipEvent = defineConfig({
9434
9861
  id: "FOOTBALL_CLUB_MEMBERSHIP",
9435
9862
  label: {
9436
9863
  defaultMessage: "Football club membership application",
@@ -9753,6 +10180,9 @@ var footballClubMembershipEvent = defineConfig({
9753
10180
  ],
9754
10181
  declaration: TENNIS_CLUB_DECLARATION_FORM
9755
10182
  });
10183
+ var footballClubMembershipEvent = resolveEventConfig(
10184
+ versionedFootballClubMembershipEvent
10185
+ );
9756
10186
 
9757
10187
  // ../commons/src/fixtures/library-membership-event.ts
9758
10188
  var libraryMembershipForm = defineDeclarationForm({
@@ -9796,7 +10226,7 @@ var libraryMembershipForm = defineDeclarationForm({
9796
10226
  }
9797
10227
  ]
9798
10228
  });
9799
- var libraryMembershipEvent = defineConfig({
10229
+ var versionedLibraryMembershipEvent = defineConfig({
9800
10230
  id: "library-membership",
9801
10231
  label: {
9802
10232
  defaultMessage: "Library membership application",
@@ -9829,6 +10259,9 @@ var libraryMembershipEvent = defineConfig({
9829
10259
  ],
9830
10260
  declaration: libraryMembershipForm
9831
10261
  });
10262
+ var libraryMembershipEvent = resolveEventConfig(
10263
+ versionedLibraryMembershipEvent
10264
+ );
9832
10265
 
9833
10266
  // ../commons/src/fixtures/child-onboarding-event.ts
9834
10267
  function generateTranslationConfig(message) {
@@ -10042,7 +10475,7 @@ var CHILD_ONBOARDING_DECLARATION_FORM = defineDeclarationForm({
10042
10475
  label: generateTranslationConfig("Birth decalration form"),
10043
10476
  pages: [child, mother]
10044
10477
  });
10045
- var ChildOnboardingEvent = defineConfig({
10478
+ var versionedChildOnboardingEvent = defineConfig({
10046
10479
  id: CHILD_ONBOARDING_EVENT,
10047
10480
  title: generateTranslationConfig(
10048
10481
  "{child.name.firstname} {child.name.surname}"
@@ -10070,6 +10503,9 @@ var ChildOnboardingEvent = defineConfig({
10070
10503
  ],
10071
10504
  advancedSearch: []
10072
10505
  });
10506
+ var ChildOnboardingEvent = resolveEventConfig(
10507
+ versionedChildOnboardingEvent
10508
+ );
10073
10509
 
10074
10510
  // ../commons/src/fixtures/digital-identity-issuance-event.ts
10075
10511
  var PRINT_DIGITAL_ID_CERTIFICATE_FORM = defineActionForm({
@@ -10258,7 +10694,7 @@ var digitalIdentityForm = defineDeclarationForm({
10258
10694
  }
10259
10695
  ]
10260
10696
  });
10261
- var digitalIdentityEvent = defineConfig({
10697
+ var versionedDigitalIdentityEvent = defineConfig({
10262
10698
  id: "digital-identity",
10263
10699
  label: {
10264
10700
  defaultMessage: "Digital identity issuance",
@@ -10300,6 +10736,9 @@ var digitalIdentityEvent = defineConfig({
10300
10736
  ],
10301
10737
  declaration: digitalIdentityForm
10302
10738
  });
10739
+ var digitalIdentityEvent = resolveEventConfig(
10740
+ versionedDigitalIdentityEvent
10741
+ );
10303
10742
 
10304
10743
  // ../commons/src/events/test.utils.ts
10305
10744
  var z45 = __toESM(require("zod/v4"));
@@ -11328,7 +11767,8 @@ function eventPayloadGenerator(rng, configuration = tennisClubMembershipEvent) {
11328
11767
  ...input
11329
11768
  }),
11330
11769
  /**
11331
- * Notify allows sending incomplete data. Think it as 'partial declare' for now.
11770
+ * NOTIFY submits the values of the notification form, and the record can stay incomplete.
11771
+ * When `declaration` is not given, string values are left out of the generated declaration to make it incomplete.
11332
11772
  */
11333
11773
  notify: (eventId, input = {}) => {
11334
11774
  let declaration = input.declaration;
@@ -11583,9 +12023,9 @@ function generateActionDocument({
11583
12023
  return { ...actionBase, type: action };
11584
12024
  case ActionType.EDIT:
11585
12025
  return {
12026
+ content: { comment: "Test comment" },
11586
12027
  ...actionBase,
11587
- type: action,
11588
- content: { comment: "Test comment" }
12028
+ type: action
11589
12029
  };
11590
12030
  case ActionType.CUSTOM:
11591
12031
  return {
@@ -11604,9 +12044,9 @@ function generateActionDocument({
11604
12044
  };
11605
12045
  }
11606
12046
  case ActionType.ARCHIVE:
11607
- return { ...actionBase, type: action, content: { reason: "Archive" } };
12047
+ return { content: { reason: "Archive" }, ...actionBase, type: action };
11608
12048
  case ActionType.REJECT:
11609
- return { ...actionBase, type: action, content: { reason: "Reject" } };
12049
+ return { content: { reason: "Reject" }, ...actionBase, type: action };
11610
12050
  case ActionType.PRINT_CERTIFICATE: {
11611
12051
  const printActionDefaults = defaults;
11612
12052
  return {
@@ -11616,13 +12056,13 @@ function generateActionDocument({
11616
12056
  };
11617
12057
  }
11618
12058
  case ActionType.APPROVE_CORRECTION:
11619
- return { ...actionBase, requestId: getUUID(), type: action };
12059
+ return { requestId: getUUID(), ...actionBase, type: action };
11620
12060
  case ActionType.REJECT_CORRECTION:
11621
12061
  return {
11622
- ...actionBase,
11623
12062
  requestId: getUUID(),
11624
- type: action,
11625
- content: { reason: "Correction rejection" }
12063
+ content: { reason: "Correction rejection" },
12064
+ ...actionBase,
12065
+ type: action
11626
12066
  };
11627
12067
  case ActionType.DUPLICATE_DETECTED: {
11628
12068
  const duplicateActionDefaults = defaults;
@@ -11639,6 +12079,65 @@ function generateActionDocument({
11639
12079
  throw new Error(`Unsupported action type: ${action}`);
11640
12080
  }
11641
12081
  }
12082
+ function isConfirmableAction(type) {
12083
+ return ConfirmableActions.some((confirmable) => confirmable === type);
12084
+ }
12085
+ function generateActionDocuments({
12086
+ confirmation,
12087
+ ...args
12088
+ }) {
12089
+ const actionDocument = generateActionDocument(args);
12090
+ if (!isConfirmableAction(actionDocument.type)) {
12091
+ return [actionDocument];
12092
+ }
12093
+ if (args.defaults?.status !== void 0) {
12094
+ throw new Error(
12095
+ `generateActionDocuments: set the status of ${actionDocument.type} with confirmation.status, not defaults.status`
12096
+ );
12097
+ }
12098
+ const status2 = confirmation?.status ?? ActionStatus.Accepted;
12099
+ if (status2 === ActionStatus.Requested) {
12100
+ if (confirmation?.defaults) {
12101
+ throw new Error(
12102
+ "generateActionDocuments: confirmation.defaults have no confirming action to apply to while the request is pending"
12103
+ );
12104
+ }
12105
+ return [{ ...actionDocument, status: ActionStatus.Requested }];
12106
+ }
12107
+ const requestedAction = {
12108
+ ...actionDocument,
12109
+ id: getUUID(),
12110
+ status: ActionStatus.Requested
12111
+ };
12112
+ const confirmingAction = {
12113
+ ...actionDocument,
12114
+ originalActionId: requestedAction.id,
12115
+ createdAt: new Date(
12116
+ new Date(actionDocument.createdAt).getTime() + 1
12117
+ ).toISOString(),
12118
+ ...confirmation?.defaults
12119
+ };
12120
+ if (status2 === ActionStatus.Rejected) {
12121
+ const { declaration, annotation, ...rejectedAction } = confirmingAction;
12122
+ return [
12123
+ requestedAction,
12124
+ {
12125
+ ...rejectedAction,
12126
+ type: actionDocument.type,
12127
+ status: ActionStatus.Rejected
12128
+ }
12129
+ ];
12130
+ }
12131
+ return [
12132
+ requestedAction,
12133
+ {
12134
+ ...confirmingAction,
12135
+ status: ActionStatus.Accepted,
12136
+ declaration: {},
12137
+ annotation: {}
12138
+ }
12139
+ ];
12140
+ }
11642
12141
  function generateRandomDatetime(rng, start, end) {
11643
12142
  const range = end.getTime() - start.getTime();
11644
12143
  const offset = Math.floor(rng() * range);
@@ -11657,9 +12156,20 @@ function generateEventDocument({
11657
12156
  }) {
11658
12157
  return {
11659
12158
  trackingId: generateTrackingId(rng),
12159
+ configVersionId: INITIAL_EVENT_CONFIG_VERSION_ID,
11660
12160
  type: configuration.id,
11661
- actions: actions.map(
11662
- (action, i) => generateActionDocument({
12161
+ actions: actions.flatMap((action, i) => {
12162
+ const createdAt = (0, import_date_fns4.addDays)(
12163
+ new Date(
12164
+ generateRandomDatetime(
12165
+ rng,
12166
+ new Date(2025, 0, 1),
12167
+ new Date(2025, 11, 31)
12168
+ )
12169
+ ),
12170
+ i
12171
+ );
12172
+ return generateActionDocuments({
11663
12173
  configuration,
11664
12174
  action: action.type,
11665
12175
  defaults: {
@@ -11667,20 +12177,11 @@ function generateEventDocument({
11667
12177
  createdAtLocation: action.user?.primaryOfficeId,
11668
12178
  assignedTo: action.user?.assignedTo,
11669
12179
  createdByRole: action.user?.role,
11670
- createdAt: (0, import_date_fns4.addDays)(
11671
- new Date(
11672
- generateRandomDatetime(
11673
- rng,
11674
- new Date(2025, 0, 1),
11675
- new Date(2025, 11, 31)
11676
- )
11677
- ),
11678
- i
11679
- ).toISOString()
12180
+ createdAt: createdAt.toISOString()
11680
12181
  },
11681
12182
  declarationOverrides: action.declarationOverrides
11682
- })
11683
- ),
12183
+ });
12184
+ }),
11684
12185
  // Offset is needed so the createdAt timestamps for events, actions and drafts make logical sense in storybook tests.
11685
12186
  // @TODO: This should be fixed in the future.
11686
12187
  createdAt: new Date(Date.now() - 1e3).toISOString(),
@@ -11707,6 +12208,7 @@ function generateEventDraftDocument({
11707
12208
  transactionId: getUUID(),
11708
12209
  action: {
11709
12210
  ...action,
12211
+ type: actionType,
11710
12212
  declaration: {
11711
12213
  ...action.declaration,
11712
12214
  ...declaration
@@ -11749,6 +12251,7 @@ var eventQueryDataGenerator = (overrides = {}, seed = 1) => {
11749
12251
  return {
11750
12252
  id: overrides.id ?? generateUuid(rng),
11751
12253
  type: overrides.type ?? TENNIS_CLUB_MEMBERSHIP,
12254
+ configVersionId: overrides.configVersionId ?? INITIAL_EVENT_CONFIG_VERSION_ID,
11752
12255
  status: overrides.status ?? pickRandom(rng, EventStatus.options),
11753
12256
  createdAt: overrides.createdAt ?? createdAt,
11754
12257
  createdByUserType: overrides.createdByUserType ?? "user",
@@ -11794,45 +12297,47 @@ var generateEventConfig = ({
11794
12297
  dateOfEventId,
11795
12298
  actions = []
11796
12299
  }) => {
11797
- return defineConfig({
11798
- id,
11799
- label: generateTranslationConfig2(id),
11800
- title: generateTranslationConfig2(`${id} Event`),
11801
- summary: {
11802
- fields: []
11803
- },
11804
- placeOfEvent: placeOfEventId ? { $$field: placeOfEventId } : void 0,
11805
- dateOfEvent: dateOfEventId ? { $$field: dateOfEventId } : void 0,
11806
- declaration: {
11807
- label: generateTranslationConfig2(`${id} Declaration`),
11808
- pages: [
11809
- {
11810
- id: "page1",
11811
- title: generateTranslationConfig2("Page 1"),
11812
- fields
11813
- }
11814
- ]
11815
- },
11816
- actions: [
11817
- {
11818
- type: ActionType.READ,
11819
- label: generateTranslationConfig2("Read"),
11820
- review: {
11821
- title: generateTranslationConfig2("Review Read Action"),
11822
- fields: []
11823
- }
12300
+ return resolveEventConfig(
12301
+ defineConfig({
12302
+ id,
12303
+ label: generateTranslationConfig2(id),
12304
+ title: generateTranslationConfig2(`${id} Event`),
12305
+ summary: {
12306
+ fields: []
11824
12307
  },
11825
- {
11826
- type: ActionType.DECLARE,
11827
- label: generateTranslationConfig2("Declare"),
11828
- review: {
11829
- title: generateTranslationConfig2("Review Declare Action"),
11830
- fields: []
11831
- }
12308
+ placeOfEvent: placeOfEventId ? { $$field: placeOfEventId } : void 0,
12309
+ dateOfEvent: dateOfEventId ? { $$field: dateOfEventId } : void 0,
12310
+ declaration: {
12311
+ label: generateTranslationConfig2(`${id} Declaration`),
12312
+ pages: [
12313
+ {
12314
+ id: "page1",
12315
+ title: generateTranslationConfig2("Page 1"),
12316
+ fields
12317
+ }
12318
+ ]
11832
12319
  },
11833
- ...actions
11834
- ]
11835
- });
12320
+ actions: [
12321
+ {
12322
+ type: ActionType.READ,
12323
+ label: generateTranslationConfig2("Read"),
12324
+ review: {
12325
+ title: generateTranslationConfig2("Review Read Action"),
12326
+ fields: []
12327
+ }
12328
+ },
12329
+ {
12330
+ type: ActionType.DECLARE,
12331
+ label: generateTranslationConfig2("Declare"),
12332
+ review: {
12333
+ title: generateTranslationConfig2("Review Declare Action"),
12334
+ fields: []
12335
+ }
12336
+ },
12337
+ ...actions
12338
+ ]
12339
+ })
12340
+ );
11836
12341
  };
11837
12342
  function withDeclaration(configuration, declaration) {
11838
12343
  return {
@@ -11896,6 +12401,26 @@ function generateTestValidatorContext(userRole2, eventWithConfig) {
11896
12401
  event: getEventValidatorContext(event2, eventConfig)
11897
12402
  };
11898
12403
  }
12404
+ function toVersionedEventConfig({
12405
+ id,
12406
+ label,
12407
+ advancedSearch,
12408
+ ...version
12409
+ }) {
12410
+ return {
12411
+ id,
12412
+ label,
12413
+ advancedSearch,
12414
+ versions: [
12415
+ {
12416
+ ...version,
12417
+ id: INITIAL_EVENT_CONFIG_VERSION_ID,
12418
+ label,
12419
+ effectiveFrom: DEFAULT_EFFECTIVE_FROM
12420
+ }
12421
+ ]
12422
+ };
12423
+ }
11899
12424
 
11900
12425
  // ../commons/src/events/TemplateConfig.ts
11901
12426
  var window2 = () => ({
@@ -11952,6 +12477,8 @@ var ACTION_SCOPE_MAP = {
11952
12477
  "record.correct"
11953
12478
  ],
11954
12479
  [ClientSpecificAction.REVIEW_CORRECTION_REQUEST]: ["record.correct"],
12480
+ // Not granted by a scope: the client checks the draft's own action instead
12481
+ [ClientSpecificAction.CONTINUE_DRAFT]: [],
11955
12482
  [ActionType.REJECT_CORRECTION]: ["record.correct"],
11956
12483
  [ActionType.APPROVE_CORRECTION]: ["record.correct"],
11957
12484
  [ActionType.REVOKE_REGISTRATION]: ["record.revoke-registration"],