@opencrvs/toolkit 2.0.0-rc.cfbf60d → 2.0.0-rc.d13cd56

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.
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+
3
+ /*
4
+ * This Source Code Form is subject to the terms of the Mozilla Public
5
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ *
8
+ * OpenCRVS is also distributed under the terms of the Civil Registration
9
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
10
+ *
11
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
12
+ */
13
+
14
+ const { execSync } = require('child_process')
15
+ const path = require('path')
16
+ const fs = require('fs')
17
+
18
+ const REPO_URL = 'https://github.com/opencrvs/opencrvs-countryconfig.git'
19
+
20
+ const projectName = process.argv[2]
21
+
22
+ if (!projectName) {
23
+ console.error(
24
+ 'Please specify a project name:\n\n npm create @opencrvs/countryconfig <project-name>\n'
25
+ )
26
+ process.exit(1)
27
+ }
28
+
29
+ const targetDir = path.resolve(process.cwd(), projectName)
30
+
31
+ if (fs.existsSync(targetDir)) {
32
+ console.error(`Error: Directory "${projectName}" already exists.`)
33
+ process.exit(1)
34
+ }
35
+
36
+ console.log(`\nScaffolding OpenCRVS country config in ./${projectName}...\n`)
37
+
38
+ try {
39
+ execSync(`git clone --depth 1 ${REPO_URL} ${projectName}`, {
40
+ stdio: 'inherit'
41
+ })
42
+ } catch (err) {
43
+ console.error('Failed to clone the repository:', err.message)
44
+ process.exit(1)
45
+ }
46
+
47
+ try {
48
+ fs.rmSync(path.join(targetDir, '.git'), { recursive: true, force: true })
49
+ } catch (err) {
50
+ console.error('Failed to remove .git directory:', err.message)
51
+ process.exit(1)
52
+ }
53
+
54
+ const pkgPath = path.join(targetDir, 'package.json')
55
+ if (fs.existsSync(pkgPath)) {
56
+ try {
57
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
58
+ pkg.name = projectName
59
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
60
+ } catch (err) {
61
+ console.error('Failed to update package.json:', err.message)
62
+ process.exit(1)
63
+ }
64
+ } else {
65
+ console.warn(
66
+ `Warning: No package.json found in the cloned repository. Project name was not updated.`
67
+ )
68
+ }
69
+
70
+ console.log(`\nDone! To get started:\n`)
71
+ console.log(` cd ${projectName}`)
72
+ console.log(` git init`)
73
+ console.log(` npm install\n`)
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "@opencrvs/create-countryconfig",
3
+ "version": "1.0.0",
4
+ "description": "Scaffold a new OpenCRVS country configuration",
5
+ "bin": {
6
+ "create-countryconfig": "./index.js"
7
+ },
8
+ "files": ["index.js"],
9
+ "keywords": ["opencrvs", "countryconfig", "create"],
10
+ "license": "MPL-2.0"
11
+ }
package/dist/cli.js CHANGED
@@ -3674,6 +3674,10 @@ var ACTION_PROPERTY_NAME2 = "action";
3674
3674
  var CONDITIONALS_PROPERTY_NAME = "conditionals";
3675
3675
  var TYPE_PROPERTY_NAME7 = "type";
3676
3676
  var SLUG_PROPERTY_NAME = "slug";
3677
+ var READ_ACTION_TYPE = "READ";
3678
+ var ACTION_TYPE_IMPORT_NAME = "ActionType";
3679
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
3680
+ var READ_ACTION_FALLBACK_INITIALIZER = `{ type: ${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE} }`;
3677
3681
  var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
3678
3682
  "READ",
3679
3683
  "DELETE",
@@ -3721,91 +3725,137 @@ function isUnsupportedActionType(action) {
3721
3725
  }
3722
3726
  return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3723
3727
  }
3724
- function migrateWorkqueueActions(workqueue, relPath) {
3725
- const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3726
- if (!actionsProperty || !import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3727
- return 0;
3728
- }
3729
- const actionsInitializer = actionsProperty.getInitializer();
3730
- if (!actionsInitializer || !import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3731
- return 0;
3728
+ function ensureValidAction(workqueue, relPath) {
3729
+ const workqueueLabel = getWorkqueueLabel(workqueue);
3730
+ const actionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3731
+ if (actionProperty && import_ts_morph17.Node.isPropertyAssignment(actionProperty)) {
3732
+ const initializer = actionProperty.getInitializer();
3733
+ if (initializer && import_ts_morph17.Node.isObjectLiteralExpression(initializer)) {
3734
+ if (!isUnsupportedActionType(initializer)) {
3735
+ return { changed: false, usedReadFallback: false };
3736
+ }
3737
+ actionProperty.set({
3738
+ name: ACTION_PROPERTY_NAME2,
3739
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3740
+ });
3741
+ console.log(
3742
+ ` [${relPath}] Replaced unsupported 'action' type with '${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE}' on workqueue '${workqueueLabel}'`
3743
+ );
3744
+ return { changed: true, usedReadFallback: true };
3745
+ }
3732
3746
  }
3747
+ workqueue.addPropertyAssignment({
3748
+ name: ACTION_PROPERTY_NAME2,
3749
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3750
+ });
3751
+ console.log(
3752
+ ` [${relPath}] Added default 'action: ${READ_ACTION_FALLBACK_INITIALIZER}' to workqueue '${workqueueLabel}'`
3753
+ );
3754
+ return { changed: true, usedReadFallback: true };
3755
+ }
3756
+ function migrateWorkqueueActions(workqueue, relPath) {
3733
3757
  const workqueueLabel = getWorkqueueLabel(workqueue);
3734
- const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3735
- if (existingActionProperty) {
3736
- if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3737
- const existingActionInitializer = existingActionProperty.getInitializer();
3738
- if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3739
- const conditionalsProperty2 = existingActionInitializer.getProperty(
3740
- CONDITIONALS_PROPERTY_NAME
3758
+ const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3759
+ let actionsArrayMigrated = false;
3760
+ if (actionsProperty && import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3761
+ const actionsInitializer = actionsProperty.getInitializer();
3762
+ if (actionsInitializer && import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3763
+ const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3764
+ if (existingActionProperty) {
3765
+ if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3766
+ const existingActionInitializer = existingActionProperty.getInitializer();
3767
+ if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3768
+ const conditionalsProperty = existingActionInitializer.getProperty(
3769
+ CONDITIONALS_PROPERTY_NAME
3770
+ );
3771
+ if (conditionalsProperty) {
3772
+ conditionalsProperty.remove();
3773
+ console.log(
3774
+ ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3775
+ );
3776
+ }
3777
+ }
3778
+ }
3779
+ actionsProperty.remove();
3780
+ console.log(
3781
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3782
+ );
3783
+ actionsArrayMigrated = true;
3784
+ } else {
3785
+ const actionCandidates = actionsInitializer.getElements().filter(
3786
+ (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3741
3787
  );
3742
- if (conditionalsProperty2) {
3743
- conditionalsProperty2.remove();
3788
+ if (actionCandidates.length === 0) {
3789
+ actionsProperty.remove();
3744
3790
  console.log(
3745
- ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3791
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3746
3792
  );
3747
- }
3748
- if (isUnsupportedActionType(existingActionInitializer)) {
3749
- existingActionProperty.remove();
3750
- console.log(
3751
- ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
3793
+ actionsArrayMigrated = true;
3794
+ } else {
3795
+ if (actionCandidates.length > 1) {
3796
+ const droppedCount = actionCandidates.length - 1;
3797
+ console.warn(
3798
+ ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3799
+ );
3800
+ }
3801
+ const conditionalsProperty = actionCandidates[0].getProperty(
3802
+ CONDITIONALS_PROPERTY_NAME
3752
3803
  );
3804
+ if (conditionalsProperty) {
3805
+ conditionalsProperty.remove();
3806
+ console.log(
3807
+ ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3808
+ );
3809
+ }
3810
+ if (isUnsupportedActionType(actionCandidates[0])) {
3811
+ actionsProperty.remove();
3812
+ console.log(
3813
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3814
+ );
3815
+ actionsArrayMigrated = true;
3816
+ } else {
3817
+ const firstActionText = actionCandidates[0].getText();
3818
+ workqueue.addPropertyAssignment({
3819
+ name: ACTION_PROPERTY_NAME2,
3820
+ initializer: firstActionText
3821
+ });
3822
+ actionsProperty.remove();
3823
+ console.log(
3824
+ ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3825
+ );
3826
+ actionsArrayMigrated = true;
3827
+ }
3753
3828
  }
3754
3829
  }
3755
3830
  }
3756
- actionsProperty.remove();
3757
- console.log(
3758
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3759
- );
3760
- return 1;
3761
- }
3762
- const actionCandidates = actionsInitializer.getElements().filter(
3763
- (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3764
- );
3765
- if (actionCandidates.length === 0) {
3766
- actionsProperty.remove();
3767
- console.log(
3768
- ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3769
- );
3770
- return 1;
3771
3831
  }
3772
- if (actionCandidates.length > 1) {
3773
- const droppedCount = actionCandidates.length - 1;
3774
- console.warn(
3775
- ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3776
- );
3777
- }
3778
- const conditionalsProperty = actionCandidates[0].getProperty(
3779
- CONDITIONALS_PROPERTY_NAME
3832
+ const fallback = ensureValidAction(workqueue, relPath);
3833
+ return {
3834
+ changed: actionsArrayMigrated || fallback.changed,
3835
+ usedReadFallback: fallback.usedReadFallback
3836
+ };
3837
+ }
3838
+ function ensureActionTypeImport(sourceFile) {
3839
+ const existingImport = sourceFile.getImportDeclaration(
3840
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2
3780
3841
  );
3781
- if (conditionalsProperty) {
3782
- conditionalsProperty.remove();
3783
- console.log(
3784
- ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3785
- );
3786
- }
3787
- if (isUnsupportedActionType(actionCandidates[0])) {
3788
- actionsProperty.remove();
3789
- console.log(
3790
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3791
- );
3792
- return 1;
3842
+ if (existingImport) {
3843
+ const alreadyImported = existingImport.getNamedImports().some((ni) => ni.getName() === ACTION_TYPE_IMPORT_NAME);
3844
+ if (!alreadyImported) {
3845
+ existingImport.addNamedImport(ACTION_TYPE_IMPORT_NAME);
3846
+ }
3847
+ return;
3793
3848
  }
3794
- const firstActionText = actionCandidates[0].getText();
3795
- workqueue.addPropertyAssignment({
3796
- name: ACTION_PROPERTY_NAME2,
3797
- initializer: firstActionText
3849
+ sourceFile.addImportDeclaration({
3850
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE2,
3851
+ namedImports: [ACTION_TYPE_IMPORT_NAME]
3798
3852
  });
3799
- actionsProperty.remove();
3800
- console.log(
3801
- ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3802
- );
3803
- return 1;
3804
3853
  }
3805
3854
  function processFile13(filePath, project) {
3806
3855
  const sourceFile = project.getSourceFile(filePath);
3807
3856
  if (!sourceFile) return 0;
3808
3857
  let migratedWorkqueues = 0;
3858
+ let needsActionTypeImport = false;
3809
3859
  const relPath = import_path18.default.relative(process.cwd(), filePath);
3810
3860
  const callExpressions = sourceFile.getDescendantsOfKind(
3811
3861
  import_ts_morph17.SyntaxKind.CallExpression
@@ -3821,9 +3871,14 @@ function processFile13(filePath, project) {
3821
3871
  if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3822
3872
  for (const element of workqueuesArg.getElements()) {
3823
3873
  if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3824
- migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3874
+ const result = migrateWorkqueueActions(element, relPath);
3875
+ if (result.changed) migratedWorkqueues++;
3876
+ if (result.usedReadFallback) needsActionTypeImport = true;
3825
3877
  }
3826
3878
  }
3879
+ if (needsActionTypeImport) {
3880
+ ensureActionTypeImport(sourceFile);
3881
+ }
3827
3882
  return migratedWorkqueues;
3828
3883
  }
3829
3884
  async function main18() {
@@ -4158,7 +4213,7 @@ Saved ${handlerRelPath}.`);
4158
4213
  // src/migrations/v2.0/checkout-upstream-files.ts
4159
4214
  var import_child_process = require("child_process");
4160
4215
  var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
4161
- var UPSTREAM_BRANCH = "develop";
4216
+ var UPSTREAM_BRANCH = "release-v2.0.0";
4162
4217
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
4163
4218
  var FILES_TO_CHECKOUT = [
4164
4219
  "src/analytics/analytics.ts",
@@ -4708,9 +4763,13 @@ function gitShowBytes(ref, path23) {
4708
4763
  return null;
4709
4764
  }
4710
4765
  }
4711
- async function main25() {
4766
+ async function main25({
4767
+ subdirs = []
4768
+ } = {}) {
4769
+ const pathspecs = subdirs.length > 0 ? subdirs.map((s) => `${INFRASTRUCTURE_DIR}/${s}/`) : [`${INFRASTRUCTURE_DIR}/`];
4770
+ const scopeLabel = pathspecs.map((p) => `'${p}'`).join(", ");
4712
4771
  console.log(
4713
- `Merging '${INFRASTRUCTURE_DIR}/' from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4772
+ `Merging ${scopeLabel} from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4714
4773
  `
4715
4774
  );
4716
4775
  assertIsGitRepo();
@@ -4725,20 +4784,12 @@ async function main25() {
4725
4784
  const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4726
4785
  const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4727
4786
  const upstreamFiles = runGit(
4728
- [
4729
- "ls-tree",
4730
- "-r",
4731
- "--name-only",
4732
- "-z",
4733
- ref,
4734
- "--",
4735
- `${INFRASTRUCTURE_DIR}/`
4736
- ],
4787
+ ["ls-tree", "-r", "--name-only", "-z", ref, "--", ...pathspecs],
4737
4788
  { silent: true }
4738
4789
  ).split("\0").filter(Boolean);
4739
4790
  if (upstreamFiles.length === 0) {
4740
4791
  console.log(
4741
- ` No files found under '${INFRASTRUCTURE_DIR}/' on ${ref}. Nothing to merge.`
4792
+ ` No files found under ${scopeLabel} on ${ref}. Nothing to merge.`
4742
4793
  );
4743
4794
  return;
4744
4795
  }
@@ -4813,7 +4864,9 @@ async function main25() {
4813
4864
  var import_fs6 = require("fs");
4814
4865
  var import_path25 = require("path");
4815
4866
  var INFRASTRUCTURE_DIR2 = "infrastructure";
4816
- async function main26() {
4867
+ async function main26({
4868
+ keep = []
4869
+ } = {}) {
4817
4870
  const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4818
4871
  if (!(0, import_fs6.existsSync)(fullPath)) {
4819
4872
  console.log(
@@ -4821,24 +4874,64 @@ async function main26() {
4821
4874
  );
4822
4875
  return;
4823
4876
  }
4824
- console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4825
- `);
4826
4877
  assertIsGitRepo();
4827
- runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4828
- silent: true
4829
- });
4830
- console.log(` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4831
- if ((0, import_fs6.existsSync)(fullPath)) {
4832
- (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4833
- console.log(` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4878
+ if (keep.length === 0) {
4879
+ console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4880
+ `);
4881
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4882
+ silent: true
4883
+ });
4884
+ console.log(
4885
+ ` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`
4886
+ );
4887
+ if ((0, import_fs6.existsSync)(fullPath)) {
4888
+ (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4889
+ console.log(
4890
+ ` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`
4891
+ );
4892
+ }
4893
+ console.log(
4894
+ `
4895
+ Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4896
+ );
4897
+ return;
4898
+ }
4899
+ const keepSet = new Set(keep);
4900
+ console.log(
4901
+ `Deleting contents of '${INFRASTRUCTURE_DIR2}/' except: ${[...keepSet].map((name) => `'${name}'`).join(", ")}
4902
+ `
4903
+ );
4904
+ const topLevelEntries = (0, import_fs6.readdirSync)(fullPath, { withFileTypes: true });
4905
+ let deleted = 0;
4906
+ for (const entry of topLevelEntries) {
4907
+ if (keepSet.has(entry.name)) {
4908
+ console.log(` Keeping '${INFRASTRUCTURE_DIR2}/${entry.name}'.`);
4909
+ continue;
4910
+ }
4911
+ const relPath = `${INFRASTRUCTURE_DIR2}/${entry.name}${entry.isDirectory() ? "/" : ""}`;
4912
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", relPath], { silent: true });
4913
+ const fullEntryPath = (0, import_path25.join)(fullPath, entry.name);
4914
+ if ((0, import_fs6.existsSync)(fullEntryPath)) {
4915
+ (0, import_fs6.rmSync)(fullEntryPath, { recursive: true, force: true });
4916
+ }
4917
+ console.log(` Deleted '${relPath}'.`);
4918
+ deleted++;
4919
+ }
4920
+ const presentNames = new Set(topLevelEntries.map((e) => e.name));
4921
+ const missingKeeps = [...keepSet].filter((name) => !presentNames.has(name));
4922
+ if (missingKeeps.length > 0) {
4923
+ console.warn(
4924
+ ` [warn] Requested to keep ${missingKeeps.map((n) => `'${n}'`).join(", ")} but they don't exist under '${INFRASTRUCTURE_DIR2}/'.`
4925
+ );
4834
4926
  }
4835
4927
  console.log(
4836
4928
  `
4837
- Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4929
+ Done. Deleted ${deleted} top-level entr${deleted === 1 ? "y" : "ies"}. Review the staged deletions with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4838
4930
  );
4839
4931
  }
4840
4932
 
4841
4933
  // src/migrations/v2.0/index.ts
4934
+ var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
4842
4935
  async function runUpgrade(dockerSwarm) {
4843
4936
  await main18();
4844
4937
  await main();
@@ -4867,7 +4960,8 @@ async function runUpgrade(dockerSwarm) {
4867
4960
  if (dockerSwarm) {
4868
4961
  await main25();
4869
4962
  } else {
4870
- await main26();
4963
+ await main26({ keep: NON_SWARM_INFRA_SUBDIRS });
4964
+ await main25({ subdirs: NON_SWARM_INFRA_SUBDIRS });
4871
4965
  }
4872
4966
  }
4873
4967
 
@@ -4092,18 +4092,33 @@ export declare const appRouter: import("@trpc/server").TRPCBuiltRouter<{
4092
4092
  input: string[];
4093
4093
  output: ({
4094
4094
  id: string & import("zod").$brand<"UUID">;
4095
- type: "user";
4096
4095
  name: {
4097
4096
  firstname: string;
4098
4097
  surname: string;
4099
4098
  };
4100
4099
  role: string;
4101
- fullHonorificName?: string | undefined;
4100
+ primaryOfficeId: string & import("zod").$brand<"UUID">;
4101
+ type: "user";
4102
+ status: "active" | "pending" | "deactivated";
4103
+ avatar?: (string & import("zod").$brand<"DocumentPath">) | undefined;
4102
4104
  signature?: (string & import("zod").$brand<"DocumentPath">) | null | undefined;
4105
+ administrativeAreaId?: (string & import("zod").$brand<"UUID">) | null | undefined;
4106
+ device?: string | undefined;
4107
+ fullHonorificName?: string | undefined;
4108
+ mobile?: string | undefined;
4109
+ email?: string | undefined;
4110
+ data?: Record<string, import("../commons").FieldValue> | undefined;
4103
4111
  } | {
4104
4112
  id: string & import("zod").$brand<"UUID">;
4105
- type: "system";
4106
4113
  name: string;
4114
+ type: "system";
4115
+ primaryOfficeId?: (string & import("zod").$brand<"UUID">) | undefined;
4116
+ administrativeAreaId?: (string & import("zod").$brand<"UUID">) | undefined;
4117
+ signature?: undefined;
4118
+ avatar?: undefined;
4119
+ fullHonorificName?: string | undefined;
4120
+ legacyId?: string | undefined;
4121
+ status?: undefined;
4107
4122
  })[];
4108
4123
  meta: import("trpc-to-openapi").OpenApiMeta;
4109
4124
  }>;
@@ -73,5 +73,26 @@ export declare function canAccessOtherUserWithScopes({ scopes, userToAccess, use
73
73
  * One of the scopes must allow access for the event to be accessible.
74
74
  */
75
75
  export declare function userCanAccessEventWithScopes(event: Partial<EventIndexWithAdministrativeHierarchy>, scopes: RecordScopeV2[], user: UserContext | SystemContext, customActionType?: string): boolean;
76
+ export declare function getAdministrativeAreaHierarchy(administrativeAreaId: string | undefined | null, administrativeAreas: Map<UUID, AdministrativeArea>): {
77
+ id: string & z.core.$brand<"UUID">;
78
+ name: string;
79
+ parentId: (string & z.core.$brand<"UUID">) | null;
80
+ validUntil: string | null;
81
+ externalId?: string | null | undefined;
82
+ }[];
83
+ /**
84
+ * Resolves a location or administrative area UUID into a root-first hierarchy of UUIDs.
85
+ *
86
+ * If the ID refers to a `Location` (e.g. CRVS office), the hierarchy includes
87
+ * the administrative area ancestors followed by the location itself.
88
+ * If the ID refers to an `AdministrativeArea`, returns the area's ancestor chain (root-first).
89
+ *
90
+ * Uses `getAdministrativeAreaHierarchy` which returns leaf-first order,
91
+ * so the result is reversed to match the root-first convention used by the server.
92
+ */
93
+ export declare function getLocationHierarchy(selectedId: UUID, context: {
94
+ administrativeAreas: Map<UUID, AdministrativeArea>;
95
+ locations: Map<UUID, Location>;
96
+ }): UUID[];
76
97
  export {};
77
98
  //# sourceMappingURL=locations.d.ts.map
@@ -0,0 +1,19 @@
1
+ import { AdministrativeArea, Location } from './locations';
2
+ export declare const V2_DEFAULT_MOCK_ADMINISTRATIVE_AREAS: AdministrativeArea[];
3
+ export declare const V2_DEFAULT_MOCK_LOCATIONS: Location[];
4
+ export declare const V2_DEFAULT_MOCK_LOCATIONS_MAP: Map<string & import("zod").$brand<"UUID">, {
5
+ id: string & import("zod").$brand<"UUID">;
6
+ name: string;
7
+ administrativeAreaId: (string & import("zod").$brand<"UUID">) | null;
8
+ validUntil: string | null;
9
+ locationType: string | null;
10
+ externalId?: string | null | undefined;
11
+ }>;
12
+ export declare const V2_DEFAULT_MOCK_ADMINISTRATIVE_AREAS_MAP: Map<string & import("zod").$brand<"UUID">, {
13
+ id: string & import("zod").$brand<"UUID">;
14
+ name: string;
15
+ parentId: (string & import("zod").$brand<"UUID">) | null;
16
+ validUntil: string | null;
17
+ externalId?: string | null | undefined;
18
+ }>;
19
+ //# sourceMappingURL=mocks.test.utils.d.ts.map
@@ -1,8 +1,9 @@
1
1
  import { DisplayableAction } from './ActionType';
2
- import { EncodedScope } from '../scopes';
2
+ import { EncodedScope, UserScopeV2 } from '../scopes';
3
3
  import { EventIndexWithAdministrativeHierarchy } from './locations';
4
4
  import { UserContext } from '../users/User';
5
5
  import { EventIndex } from './EventIndex';
6
+ import { UUID } from 'src/uuid';
6
7
  export declare const ACTION_SCOPE_MAP: {
7
8
  READ: "record.read"[];
8
9
  CREATE: "record.create"[];
@@ -53,4 +54,26 @@ export declare function isActionInScope({ scopes, action, event, currentUser }:
53
54
  event: EventIndexWithAdministrativeHierarchy;
54
55
  currentUser: UserContext;
55
56
  }): boolean;
57
+ /**
58
+ *
59
+ *
60
+ * @param allRoles - All possible roles in the system
61
+ * @param userLocation - The location and role information of the user whose role options are being determined
62
+ * @param acceptedScopes - The scopes of the user requesting the role update, used to determine which roles they can assign.
63
+ * @param userRequesting - The user context of the user requesting the role update, used to check location-based access to the target user's location.
64
+ *
65
+ * @returns An array of roles that the requesting user is allowed to assign to the target user based on their scopes and location
66
+ *
67
+ * 1) Used to determine which roles should be available in the dropdown when a user is editing another user's role in the user management interface.
68
+ * 2) Used to check if payload includes valid role.
69
+ */
70
+ export declare function getAvailableRolesForUserUpdatePayload({ allRoles, userLocation, acceptedScopes, userRequesting }: {
71
+ allRoles: string[];
72
+ userRequesting: UserContext;
73
+ acceptedScopes: UserScopeV2[];
74
+ userLocation: {
75
+ administrativeHierarchy: UUID[];
76
+ primaryOfficeId: UUID;
77
+ };
78
+ }): string[];
56
79
  //# sourceMappingURL=scopes.d.ts.map
@@ -302,12 +302,14 @@ __export(events_exports, {
302
302
  getActionConfig: () => getActionConfig,
303
303
  getActionReview: () => getActionReview,
304
304
  getActionReviewFields: () => getActionReviewFields,
305
+ getAdministrativeAreaHierarchy: () => getAdministrativeAreaHierarchy,
305
306
  getAllUniqueFields: () => getAllUniqueFields,
306
307
  getAnnotationFromDrafts: () => getAnnotationFromDrafts,
307
308
  getAssignedUserFromActions: () => getAssignedUserFromActions,
308
309
  getAssignedUserSignatureFromActions: () => getAssignedUserSignatureFromActions,
309
310
  getAssignmentStatus: () => getAssignmentStatus,
310
311
  getAvailableActionsForEvent: () => getAvailableActionsForEvent,
312
+ getAvailableRolesForUserUpdatePayload: () => getAvailableRolesForUserUpdatePayload,
311
313
  getCompleteActionAnnotation: () => getCompleteActionAnnotation,
312
314
  getCompleteActionDeclaration: () => getCompleteActionDeclaration,
313
315
  getCurrentEventState: () => getCurrentEventState,
@@ -318,6 +320,7 @@ __export(events_exports, {
318
320
  getDeclarationPages: () => getDeclarationPages,
319
321
  getEventConfigById: () => getEventConfigById,
320
322
  getFilePathsFromEvent: () => getFilePathsFromEvent,
323
+ getLocationHierarchy: () => getLocationHierarchy,
321
324
  getMixedPath: () => getMixedPath,
322
325
  getPendingAction: () => getPendingAction,
323
326
  getPrintCertificatePages: () => getPrintCertificatePages,
@@ -10003,6 +10006,39 @@ function userCanAccessEventWithScopes(event2, scopes, user2, customActionType) {
10003
10006
  (scope) => canAccessEventWithScope(event2, scope, user2, customActionType)
10004
10007
  );
10005
10008
  }
10009
+ function getAdministrativeAreaHierarchy(administrativeAreaId, administrativeAreas) {
10010
+ const collectedLocations = [];
10011
+ const parsedAdministrativeAreaId = administrativeAreaId && UUID.safeParse(administrativeAreaId).data;
10012
+ let current = parsedAdministrativeAreaId ? administrativeAreas.get(parsedAdministrativeAreaId) : null;
10013
+ while (current) {
10014
+ collectedLocations.push(current);
10015
+ if (!current.parentId) {
10016
+ break;
10017
+ }
10018
+ const parentId = current.parentId;
10019
+ current = administrativeAreas.get(parentId);
10020
+ }
10021
+ return collectedLocations;
10022
+ }
10023
+ function getLocationHierarchy(selectedId, context) {
10024
+ const { administrativeAreas, locations } = context;
10025
+ const loc = locations.get(selectedId);
10026
+ if (loc) {
10027
+ if (loc.administrativeAreaId) {
10028
+ const hierarchy2 = getAdministrativeAreaHierarchy(
10029
+ loc.administrativeAreaId,
10030
+ administrativeAreas
10031
+ );
10032
+ return [...hierarchy2.reverse().map((area) => area.id), loc.id];
10033
+ }
10034
+ return [loc.id];
10035
+ }
10036
+ const hierarchy = getAdministrativeAreaHierarchy(
10037
+ selectedId,
10038
+ administrativeAreas
10039
+ );
10040
+ return hierarchy.reverse().map((area) => area.id);
10041
+ }
10006
10042
 
10007
10043
  // ../commons/src/events/scopes.ts
10008
10044
  var ACTION_SCOPE_MAP = {
@@ -10077,6 +10113,25 @@ function isActionInScope({
10077
10113
  );
10078
10114
  return canAccess;
10079
10115
  }
10116
+ function getAvailableRolesForUserUpdatePayload({
10117
+ allRoles,
10118
+ userLocation,
10119
+ acceptedScopes,
10120
+ userRequesting
10121
+ }) {
10122
+ const availableRoles = allRoles.filter((role) => {
10123
+ const canAccess = canAccessOtherUserWithScopes({
10124
+ userToAccess: {
10125
+ ...userLocation,
10126
+ role
10127
+ },
10128
+ user: userRequesting,
10129
+ scopes: acceptedScopes
10130
+ });
10131
+ return canAccess;
10132
+ });
10133
+ return availableRoles;
10134
+ }
10080
10135
 
10081
10136
  // ../commons/src/events/serializers/user/deserializer.ts
10082
10137
  function userDeserializer(serializedUserField, user2) {