cht-conf 4.1.2 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ # [4.2.0](https://github.com/medic/cht-conf/compare/v4.1.3...v4.2.0) (2024-12-11)
2
+
3
+
4
+ ### Features
5
+
6
+ * **#373:** merge-contacts action ([#647](https://github.com/medic/cht-conf/issues/647)) ([006554c](https://github.com/medic/cht-conf/commit/006554cf3a414d9577e05c6dfaef3bbd59849403)), closes [#373](https://github.com/medic/cht-conf/issues/373)
7
+
8
+ ## [4.1.3](https://github.com/medic/cht-conf/compare/v4.1.2...v4.1.3) (2024-11-13)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * **#644:** support node 22 ([d8ece55](https://github.com/medic/cht-conf/commit/d8ece55cd601ae8f4f1a98cd496394f14c5ded0d)), closes [#644](https://github.com/medic/cht-conf/issues/644)
14
+
1
15
  ## [4.1.2](https://github.com/medic/cht-conf/compare/v4.1.1...v4.1.2) (2024-10-09)
2
16
 
3
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cht-conf",
3
- "version": "4.1.2",
3
+ "version": "4.2.0",
4
4
  "description": "Configure CHT deployments",
5
5
  "main": "./src/lib/main.js",
6
6
  "engines": {
@@ -9,9 +9,7 @@
9
9
  "scripts": {
10
10
  "clean": "rm -rf ./build/",
11
11
  "eslint": "eslint 'src/**/*.js' test/*.js 'test/**/*.js'",
12
- "docker-start-couchdb": "npm run docker-stop-couchdb && docker run -d -p 6984:5984 --rm --name cht-conf-couchdb couchdb:2.3.1 && sh test/scripts/wait_for_response_code.sh 6984 200 CouchDB",
13
- "docker-stop-couchdb": "docker stop cht-conf-couchdb || true",
14
- "test": "npm run eslint && npm run docker-start-couchdb && npm run clean && mkdir -p build/test && cp -r test/data build/test/data && cd build/test && nyc --reporter=html mocha --forbid-only \"../../test/**/*.spec.js\" --exclude \"../../test/e2e/**/*.spec.js\" && cd ../.. && npm run docker-stop-couchdb",
12
+ "test": "npm run clean && mkdir -p build/test && cp -r test/data build/test/data && cd build/test && nyc --reporter=html mocha \"../../test/**/*.spec.js\" --exclude \"../../test/e2e/**/*.spec.js\"",
15
13
  "test-e2e": "mocha --config test/e2e/.mocharc.js",
16
14
  "semantic-release": "semantic-release"
17
15
  },
@@ -105,69 +105,89 @@ function getIDs(csv, docType) {
105
105
  return rows.map((item) => idPrefix + item[index]);
106
106
  }
107
107
 
108
- function processDocs(docType, csv, documentDocs, args) {
109
- const { rows, cols } = fs.readCsv(csv);
110
- const uuidIndex = cols.indexOf(DOCUMENT_ID);
111
- const colNames = args.colNames;
112
- let toIncludeColumns, toIncludeIndex;
113
- if (!colNames.length) {
114
- warn(' No columns specified, the script will add all the columns in the CSV!');
115
- toIncludeColumns = cols;
116
- toIncludeIndex = [];
117
-
118
- } else {
119
- if (!columnsAreValid(cols,colNames)) {
120
- throw Error('The column name(s) specified do not exist.');
121
- }
122
-
123
- toIncludeColumns = cols.filter(column => colNames.includes(column.split(':')[0]));
124
- toIncludeIndex = toIncludeColumns.map(column => cols.indexOf(column));
125
-
126
- if (toIncludeColumns.includes(DOCUMENT_ID)) {
127
- toIncludeIndex.splice(toIncludeColumns.indexOf(DOCUMENT_ID),1);
128
- }
129
- }
130
-
131
- if (toIncludeColumns.includes(DOCUMENT_ID)) {
132
- toIncludeColumns.splice(toIncludeColumns.indexOf(DOCUMENT_ID),1);
133
- }
134
- return rows
135
- .map(r => processCsv(docType, toIncludeColumns, r, uuidIndex, toIncludeIndex, documentDocs));
136
- }
137
-
138
108
  function columnsAreValid(csvColumns, toIncludeColumns) {
139
109
  const splitCsvColumns = csvColumns.map(column => column && column.split(':')[0]);
140
110
  return toIncludeColumns.every(column => splitCsvColumns.includes(column));
141
111
  }
112
+ const parseColName = colName => colName.split(':')[0];
113
+ const getColNamesToInclude = (csvColNames, targetColNames) => {
114
+ const filteredCsvColNames = csvColNames.filter(colName => colName !== DOCUMENT_ID);
115
+ if (!targetColNames.length) {
116
+ warn(' No columns specified, the script will add all the columns in the CSV!');
117
+ return filteredCsvColNames;
118
+ }
119
+
120
+ if (!columnsAreValid(filteredCsvColNames, targetColNames)) {
121
+ throw Error('The column name(s) specified do not exist.');
122
+ }
123
+
124
+ return filteredCsvColNames.filter(column => targetColNames.includes(parseColName(column)));
125
+ };
142
126
 
143
- function processCsv(docType, cols, row, uuidIndex, toIncludeIndex, documentDocs) {
127
+ const getCsvColNameIndex = csvColNames => colName => csvColNames.indexOf(colName);
128
+ const mapColNamesToCsvIndex = (csvColNames, toIncludeColumns) => toIncludeColumns.map(getCsvColNameIndex(csvColNames));
129
+
130
+
131
+ const getDocIdForCsvRow = (docType, uuidIndex) => row => {
144
132
  const documentId = row[uuidIndex];
145
133
  const idPrefix = docType === 'contact' ? '' : 'org.couchdb.user:';
146
- const doc = documentDocs[idPrefix + documentId];
134
+ return `${idPrefix}${documentId}`;
135
+ };
147
136
 
137
+ const getCsvRowFilterFn = (uuidIndex, toIncludeIndex) => {
148
138
  if (toIncludeIndex.length > 0) {
149
- row = toIncludeIndex.map(index => row[index]);
150
- } else {
151
- row.splice(uuidIndex,1);
139
+ return row => toIncludeIndex.map(index => row[index]);
152
140
  }
153
141
 
154
- for(let i=0; i<cols.length; ++i) {
155
- const { col, val, excluded } = toDocs.parseColumn(cols[i], row[i]);
142
+ return row => {
143
+ const updatedRow = [...row];
144
+ updatedRow.splice(uuidIndex, 1);
145
+ return updatedRow;
146
+ };
147
+ };
148
+
149
+ const isColNameProtected = col => EDIT_RESERVED_COL_NAMES.includes(col.split('.')[0]);
150
+ const processCsvColumn = (doc, row) => (colName, index) => {
151
+ const { col, val, excluded } = toDocs.parseColumn(colName, row[index]);
156
152
 
157
- if (EDIT_RESERVED_COL_NAMES.includes(col.split('.')[0])) {
158
- throw new Error(`Cannot set property defined by column '${col}' - this property name is protected.`);
159
- }
153
+ if (isColNameProtected(col)) {
154
+ throw new Error(`Cannot set property defined by column '${col}' - this property name is protected.`);
155
+ }
160
156
 
161
- toDocs.setCol(doc, col, val);
162
- if (excluded) {
163
- model.exclusions.push({
164
- doc: doc,
165
- propertyName: col,
166
- });
167
- }
157
+ toDocs.setCol(doc, col, val);
158
+ if (excluded) {
159
+ model.exclusions.push({
160
+ doc,
161
+ propertyName: col,
162
+ });
168
163
  }
169
- return doc;
170
- }
164
+ };
165
+ const processCsvRow = colNames => ([doc, row]) => colNames.forEach(processCsvColumn(doc, row));
166
+
167
+ const getColIndexesToInclude = (colNames, cols, toIncludeColumns) => {
168
+ if(colNames.length) {
169
+ return mapColNamesToCsvIndex(cols, toIncludeColumns);
170
+ }
171
+ return [];
172
+ };
173
+
174
+ const processDocs = (docType, csv, documentDocs, args) => {
175
+ const { rows, cols } = fs.readCsv(csv);
176
+ const uuidIndex = cols.indexOf(DOCUMENT_ID);
177
+ const colNamesToInclude = getColNamesToInclude(cols, args.colNames);
178
+ const colIndexesToInclude = getColIndexesToInclude(args.colNames, cols, colNamesToInclude);
179
+ const getFilteredCsvRow = getCsvRowFilterFn(uuidIndex, colIndexesToInclude);
180
+
181
+ const rowDocs = rows
182
+ .map(getDocIdForCsvRow(docType, uuidIndex))
183
+ .map(id => documentDocs[id]);
184
+
185
+ rows
186
+ .map(getFilteredCsvRow)
187
+ .map((row, index) => [rowDocs[index], row])
188
+ .map(processCsvRow(colNamesToInclude));
189
+ return rowDocs;
190
+ };
171
191
 
172
192
  const processDocuments = async (docType, csv, ids, db, args) => {
173
193
  const documentDocs = await fetchDocumentList(db, ids, args);
@@ -196,4 +216,4 @@ const parseExtraArgs = (projectDir, extraArgs = []) => {
196
216
  module.exports = {
197
217
  requiresInstance: true,
198
218
  execute
199
- };
219
+ };
@@ -0,0 +1,69 @@
1
+ const minimist = require('minimist');
2
+ const path = require('path');
3
+
4
+ const environment = require('../lib/environment');
5
+ const pouch = require('../lib/db');
6
+ const { info } = require('../lib/log');
7
+
8
+ const HierarchyOperations = require('../lib/hierarchy-operations');
9
+
10
+ module.exports = {
11
+ requiresInstance: true,
12
+ execute: () => {
13
+ const args = parseExtraArgs(environment.pathToProject, environment.extraArgs);
14
+ const db = pouch();
15
+ const options = {
16
+ docDirectoryPath: args.docDirectoryPath,
17
+ force: args.force,
18
+ };
19
+ return HierarchyOperations(db, options).merge(args.sourceIds, args.destinationId);
20
+ }
21
+ };
22
+
23
+ // Parses extraArgs and asserts if required parameters are not present
24
+ const parseExtraArgs = (projectDir, extraArgs = []) => {
25
+ const args = minimist(extraArgs, { boolean: true });
26
+
27
+ const sourceIds = (args.sources || args.source || '')
28
+ .split(',')
29
+ .filter(Boolean);
30
+
31
+ if (!args.destination) {
32
+ usage();
33
+ throw Error(`Action "merge-contacts" is missing required contact ID ${bold('--destination')}. Other contacts will be merged into this contact.`);
34
+ }
35
+
36
+ if (sourceIds.length === 0) {
37
+ usage();
38
+ throw Error(`Action "merge-contacts" is missing required contact ID(s) ${bold('--sources')}. These contacts will be merged into the contact specified by ${bold('--destination')}`);
39
+ }
40
+
41
+ return {
42
+ destinationId: args.destination,
43
+ sourceIds,
44
+ docDirectoryPath: path.resolve(projectDir, args.docDirectoryPath || 'json_docs'),
45
+ force: !!args.force,
46
+ };
47
+ };
48
+
49
+ const bold = text => `\x1b[1m${text}\x1b[0m`;
50
+ const usage = () => {
51
+ info(`
52
+ ${bold('cht-conf\'s merge-contacts action')}
53
+ When combined with 'upload-docs' this action moves all of the contacts and reports under ${bold('sources')} to be under ${bold('destination')}.
54
+ The top-level ${bold('source contact(s)')} are deleted and no data from this document is merged or preserved.
55
+
56
+ ${bold('USAGE')}
57
+ cht --local merge-contacts -- --destination=<destination_id> --sources=<source_id1>,<source_id2>
58
+
59
+ ${bold('OPTIONS')}
60
+ --destination=<destination_id>
61
+ Specifies the ID of the contact that should receive the moving contacts and reports.
62
+
63
+ --sources=<source_id1>,<source_id2>
64
+ A comma delimited list of IDs of contacts which will be deleted. The hierarchy of contacts and reports under it will be moved to be under the destination contact.
65
+
66
+ --docDirectoryPath=<path to stage docs>
67
+ Specifies the folder used to store the documents representing the changes in hierarchy.
68
+ `);
69
+ };
@@ -1,105 +1,34 @@
1
1
  const minimist = require('minimist');
2
2
  const path = require('path');
3
- const userPrompt = require('../lib/user-prompt');
4
3
 
5
4
  const environment = require('../lib/environment');
6
- const fs = require('../lib/sync-fs');
7
- const lineageManipulation = require('../lib/lineage-manipulation');
8
- const lineageConstraints = require('../lib/lineage-constraints');
9
5
  const pouch = require('../lib/db');
10
- const { warn, trace, info } = require('../lib/log');
6
+ const { info } = require('../lib/log');
11
7
 
12
- const HIERARCHY_ROOT = 'root';
13
- const BATCH_SIZE = 10000;
8
+ const HierarchyOperations = require('../lib/hierarchy-operations');
14
9
 
15
10
  module.exports = {
16
11
  requiresInstance: true,
17
12
  execute: () => {
18
13
  const args = parseExtraArgs(environment.pathToProject, environment.extraArgs);
19
14
  const db = pouch();
20
- prepareDocumentDirectory(args);
21
- return updateLineagesAndStage(args, db);
15
+ const options = {
16
+ docDirectoryPath: args.docDirectoryPath,
17
+ force: args.force,
18
+ };
19
+ return HierarchyOperations(db, options).move(args.sourceIds, args.destinationId);
22
20
  }
23
21
  };
24
22
 
25
- const prettyPrintDocument = doc => `'${doc.name}' (${doc._id})`;
26
- const updateLineagesAndStage = async (options, db) => {
27
- trace(`Fetching contact details for parent: ${options.parentId}`);
28
- const parentDoc = await fetch.contact(db, options.parentId);
29
-
30
- const constraints = await lineageConstraints(db, parentDoc);
31
- const contactDocs = await fetch.contactList(db, options.contactIds);
32
- await validateContacts(contactDocs, constraints);
33
-
34
- let affectedContactCount = 0, affectedReportCount = 0;
35
- const replacementLineage = lineageManipulation.createLineageFromDoc(parentDoc);
36
- for (let contactId of options.contactIds) {
37
- const contactDoc = contactDocs[contactId];
38
- const descendantsAndSelf = await fetch.descendantsOf(db, contactId);
39
-
40
- // Check that primary contact is not removed from areas where they are required
41
- const invalidPrimaryContactDoc = await constraints.getPrimaryContactViolations(contactDoc, descendantsAndSelf);
42
- if (invalidPrimaryContactDoc) {
43
- throw Error(`Cannot remove contact ${prettyPrintDocument(invalidPrimaryContactDoc)} from the hierarchy for which they are a primary contact.`);
44
- }
45
-
46
- trace(`Considering lineage updates to ${descendantsAndSelf.length} descendant(s) of contact ${prettyPrintDocument(contactDoc)}.`);
47
- const updatedDescendants = replaceLineageInContacts(descendantsAndSelf, replacementLineage, contactId);
48
-
49
- const ancestors = await fetch.ancestorsOf(db, contactDoc);
50
- trace(`Considering primary contact updates to ${ancestors.length} ancestor(s) of contact ${prettyPrintDocument(contactDoc)}.`);
51
- const updatedAncestors = replaceLineageInAncestors(descendantsAndSelf, ancestors);
52
-
53
- minifyLineageAndWriteToDisk([...updatedDescendants, ...updatedAncestors], options);
54
-
55
- const movedReportsCount = await moveReports(db, descendantsAndSelf, options, replacementLineage, contactId);
56
- trace(`${movedReportsCount} report(s) created by these affected contact(s) will be updated`);
57
-
58
- affectedContactCount += updatedDescendants.length + updatedAncestors.length;
59
- affectedReportCount += movedReportsCount;
60
-
61
- info(`Staged updates to ${prettyPrintDocument(contactDoc)}. ${updatedDescendants.length} contact(s) and ${movedReportsCount} report(s).`);
62
- }
63
-
64
- info(`Staged changes to lineage information for ${affectedContactCount} contact(s) and ${affectedReportCount} report(s).`);
65
- };
66
-
67
- /*
68
- Checks for any errors which this will create in the hierarchy (hierarchy schema, circular hierarchies)
69
- Confirms the list of contacts are possible to move
70
- */
71
- const validateContacts = async (contactDocs, constraints) => {
72
- Object.values(contactDocs).forEach(doc => {
73
- const hierarchyError = constraints.getHierarchyErrors(doc);
74
- if (hierarchyError) {
75
- throw Error(`Hierarchy Constraints: ${hierarchyError}`);
76
- }
77
- });
78
-
79
- /*
80
- It is nice that the tool can move lists of contacts as one operation, but strange things happen when two contactIds are in the same lineage.
81
- For example, moving a district_hospital and moving a contact under that district_hospital to a new clinic causes multiple colliding writes to the same json file.
82
- */
83
- const contactIds = Object.keys(contactDocs);
84
- Object.values(contactDocs)
85
- .forEach(doc => {
86
- const parentIdsOfDoc = (doc.parent && lineageManipulation.pluckIdsFromLineage(doc.parent)) || [];
87
- const violatingParentId = parentIdsOfDoc.find(parentId => contactIds.includes(parentId));
88
- if (violatingParentId) {
89
- throw Error(`Unable to move two documents from the same lineage: '${doc._id}' and '${violatingParentId}'`);
90
- }
91
- });
92
- };
93
-
94
23
  // Parses extraArgs and asserts if required parameters are not present
95
24
  const parseExtraArgs = (projectDir, extraArgs = []) => {
96
25
  const args = minimist(extraArgs, { boolean: true });
97
26
 
98
- const contactIds = (args.contacts || args.contact || '')
27
+ const sourceIds = (args.contacts || args.contact || '')
99
28
  .split(',')
100
29
  .filter(id => id);
101
30
 
102
- if (contactIds.length === 0) {
31
+ if (sourceIds.length === 0) {
103
32
  usage();
104
33
  throw Error('Action "move-contacts" is missing required list of contacts to be moved');
105
34
  }
@@ -110,28 +39,15 @@ const parseExtraArgs = (projectDir, extraArgs = []) => {
110
39
  }
111
40
 
112
41
  return {
113
- parentId: args.parent,
114
- contactIds,
42
+ destinationId: args.parent,
43
+ sourceIds,
115
44
  docDirectoryPath: path.resolve(projectDir, args.docDirectoryPath || 'json_docs'),
116
45
  force: !!args.force,
117
46
  };
118
47
  };
119
48
 
120
- const prepareDocumentDirectory = ({ docDirectoryPath, force }) => {
121
- if (!fs.exists(docDirectoryPath)) {
122
- fs.mkdir(docDirectoryPath);
123
- } else if (!force && fs.recurseFiles(docDirectoryPath).length > 0) {
124
- warn(`The document folder '${docDirectoryPath}' already contains files. It is recommended you start with a clean folder. Do you want to delete the contents of this folder and continue?`);
125
- if(userPrompt.keyInYN()) {
126
- fs.deleteFilesInFolder(docDirectoryPath);
127
- } else {
128
- throw new Error('User aborted execution.');
129
- }
130
- }
131
- };
132
-
49
+ const bold = text => `\x1b[1m${text}\x1b[0m`;
133
50
  const usage = () => {
134
- const bold = text => `\x1b[1m${text}\x1b[0m`;
135
51
  info(`
136
52
  ${bold('cht-conf\'s move-contacts action')}
137
53
  When combined with 'upload-docs' this action effectively moves a contact from one place in the hierarchy to another.
@@ -144,148 +60,9 @@ ${bold('OPTIONS')}
144
60
  A comma delimited list of ids of contacts to be moved.
145
61
 
146
62
  --parent=<parent_id>
147
- Specifies the ID of the new parent. Use '${HIERARCHY_ROOT}' to identify the top of the hierarchy (no parent).
63
+ Specifies the ID of the new parent. Use '${HierarchyOperations.HIERARCHY_ROOT}' to identify the top of the hierarchy (no parent).
148
64
 
149
65
  --docDirectoryPath=<path to stage docs>
150
66
  Specifies the folder used to store the documents representing the changes in hierarchy.
151
67
  `);
152
68
  };
153
-
154
- const moveReports = async (db, descendantsAndSelf, writeOptions, replacementLineage, contactId) => {
155
- const contactIds = descendantsAndSelf.map(contact => contact._id);
156
-
157
- let skip = 0;
158
- let reportDocsBatch;
159
- do {
160
- info(`Processing ${skip} to ${skip + BATCH_SIZE} report docs`);
161
- reportDocsBatch = await fetch.reportsCreatedBy(db, contactIds, skip);
162
-
163
- const updatedReports = replaceLineageInReports(reportDocsBatch, replacementLineage, contactId);
164
- minifyLineageAndWriteToDisk(updatedReports, writeOptions);
165
-
166
- skip += reportDocsBatch.length;
167
- } while (reportDocsBatch.length >= BATCH_SIZE);
168
-
169
- return skip;
170
- };
171
-
172
- const minifyLineageAndWriteToDisk = (docs, parsedArgs) => {
173
- docs.forEach(doc => {
174
- lineageManipulation.minifyLineagesInDoc(doc);
175
- writeDocumentToDisk(parsedArgs, doc);
176
- });
177
- };
178
-
179
- const writeDocumentToDisk = ({ docDirectoryPath }, doc) => {
180
- const destinationPath = path.join(docDirectoryPath, `${doc._id}.doc.json`);
181
- if (fs.exists(destinationPath)) {
182
- warn(`File at ${destinationPath} already exists and is being overwritten.`);
183
- }
184
-
185
- trace(`Writing updated document to ${destinationPath}`);
186
- fs.writeJson(destinationPath, doc);
187
- };
188
-
189
- const fetch = {
190
- /*
191
- Fetches all of the documents associated with the "contactIds" and confirms they exist.
192
- */
193
- contactList: async (db, ids) => {
194
- const contactDocs = await db.allDocs({
195
- keys: ids,
196
- include_docs: true,
197
- });
198
-
199
- const missingContactErrors = contactDocs.rows.filter(row => !row.doc).map(row => `Contact with id '${row.key}' could not be found.`);
200
- if (missingContactErrors.length > 0) {
201
- throw Error(missingContactErrors);
202
- }
203
-
204
- return contactDocs.rows.reduce((agg, curr) => Object.assign(agg, { [curr.doc._id]: curr.doc }), {});
205
- },
206
-
207
- contact: async (db, id) => {
208
- try {
209
- if (id === HIERARCHY_ROOT) {
210
- return undefined;
211
- }
212
-
213
- return await db.get(id);
214
- } catch (err) {
215
- if (err.name !== 'not_found') {
216
- throw err;
217
- }
218
-
219
- throw Error(`Contact with id '${id}' could not be found`);
220
- }
221
- },
222
-
223
- /*
224
- Given a contact's id, obtain the documents of all descendant contacts
225
- */
226
- descendantsOf: async (db, contactId) => {
227
- const descendantDocs = await db.query('medic/contacts_by_depth', {
228
- key: [contactId],
229
- include_docs: true,
230
- });
231
-
232
- return descendantDocs.rows
233
- .map(row => row.doc)
234
- /* We should not move or update tombstone documents */
235
- .filter(doc => doc && doc.type !== 'tombstone');
236
- },
237
-
238
- reportsCreatedBy: async (db, contactIds, skip) => {
239
- const reports = await db.query('medic-client/reports_by_freetext', {
240
- keys: contactIds.map(id => [`contact:${id}`]),
241
- include_docs: true,
242
- limit: BATCH_SIZE,
243
- skip: skip,
244
- });
245
-
246
- return reports.rows.map(row => row.doc);
247
- },
248
-
249
- ancestorsOf: async (db, contactDoc) => {
250
- const ancestorIds = lineageManipulation.pluckIdsFromLineage(contactDoc.parent);
251
- const ancestors = await db.allDocs({
252
- keys: ancestorIds,
253
- include_docs: true,
254
- });
255
-
256
- const ancestorIdsNotFound = ancestors.rows.filter(ancestor => !ancestor.doc).map(ancestor => ancestor.key);
257
- if (ancestorIdsNotFound.length > 0) {
258
- throw Error(`Contact '${prettyPrintDocument(contactDoc)} has parent id(s) '${ancestorIdsNotFound.join(',')}' which could not be found.`);
259
- }
260
-
261
- return ancestors.rows.map(ancestor => ancestor.doc);
262
- },
263
- };
264
-
265
- const replaceLineageInReports = (reportsCreatedByDescendants, replaceWith, startingFromIdInLineage) => reportsCreatedByDescendants.reduce((agg, doc) => {
266
- if (lineageManipulation.replaceLineage(doc, 'contact', replaceWith, startingFromIdInLineage)) {
267
- agg.push(doc);
268
- }
269
- return agg;
270
- }, []);
271
-
272
- const replaceLineageInContacts = (descendantsAndSelf, replacementLineage, contactId) => descendantsAndSelf.reduce((agg, doc) => {
273
- const startingFromIdInLineage = doc._id === contactId ? undefined : contactId;
274
- const parentWasUpdated = lineageManipulation.replaceLineage(doc, 'parent', replacementLineage, startingFromIdInLineage);
275
- const contactWasUpdated = lineageManipulation.replaceLineage(doc, 'contact', replacementLineage, contactId);
276
- if (parentWasUpdated || contactWasUpdated) {
277
- agg.push(doc);
278
- }
279
- return agg;
280
- }, []);
281
-
282
- const replaceLineageInAncestors = (descendantsAndSelf, ancestors) => ancestors.reduce((agg, ancestor) => {
283
- let result = agg;
284
- const primaryContact = descendantsAndSelf.find(descendant => ancestor.contact && descendant._id === ancestor.contact._id);
285
- if (primaryContact) {
286
- ancestor.contact = lineageManipulation.createLineageFromDoc(primaryContact);
287
- result = [ancestor, ...result];
288
- }
289
-
290
- return result;
291
- }, []);
@@ -0,0 +1,103 @@
1
+ const lineageManipulation = require('./lineage-manipulation');
2
+
3
+ const HIERARCHY_ROOT = 'root';
4
+ const BATCH_SIZE = 10000;
5
+
6
+ /*
7
+ Fetches all of the documents associated with the "contactIds" and confirms they exist.
8
+ */
9
+ async function getContactsByIds(db, ids) {
10
+ const contactDocs = await db.allDocs({
11
+ keys: ids,
12
+ include_docs: true,
13
+ });
14
+
15
+ const missingContactErrors = contactDocs.rows.filter(row => !row.doc).map(row => `Contact with id '${row.key}' could not be found.`);
16
+ if (missingContactErrors.length > 0) {
17
+ throw Error(missingContactErrors);
18
+ }
19
+
20
+ const contactDict = {};
21
+ contactDocs.rows.forEach(({ doc }) => contactDict[doc._id] = doc);
22
+ return contactDict;
23
+ }
24
+
25
+ async function getContact(db, id) {
26
+ try {
27
+ if (id === HIERARCHY_ROOT) {
28
+ return undefined;
29
+ }
30
+
31
+ return await db.get(id);
32
+ } catch (err) {
33
+ if (err.status !== 404) {
34
+ throw err;
35
+ }
36
+
37
+ throw Error(`Contact with id '${id}' could not be found`);
38
+ }
39
+ }
40
+
41
+ /*
42
+ Given a contact's id, obtain the documents of all descendant contacts
43
+ */
44
+ async function getContactWithDescendants(db, contactId) {
45
+ const descendantDocs = await db.query('medic/contacts_by_depth', {
46
+ key: [contactId],
47
+ include_docs: true,
48
+ });
49
+
50
+ return descendantDocs.rows
51
+ .map(row => row.doc)
52
+ // We should not move or update tombstone documents
53
+ // Not relevant for 4.x cht-core versions, but needed in older versions.
54
+ .filter(doc => doc && doc.type !== 'tombstone');
55
+ }
56
+
57
+ async function getReportsForContacts(db, createdByIds, createdAtId, skip) {
58
+ const createdByKeys = createdByIds.map(id => [`contact:${id}`]);
59
+ const createdAtKeys = createdAtId ? [
60
+ [`patient_id:${createdAtId}`],
61
+ [`patient_uuid:${createdAtId}`],
62
+ [`place_id:${createdAtId}`],
63
+ [`place_uuid:${createdAtId}`]
64
+ ] : [];
65
+
66
+ const reports = await db.query('medic-client/reports_by_freetext', {
67
+ keys: [
68
+ ...createdByKeys,
69
+ ...createdAtKeys,
70
+ ],
71
+ include_docs: true,
72
+ limit: BATCH_SIZE,
73
+ skip,
74
+ });
75
+
76
+ const docsWithId = reports.rows.map(({ doc }) => [doc._id, doc]);
77
+ return Array.from(new Map(docsWithId).values());
78
+ }
79
+
80
+ async function getAncestorsOf(db, contactDoc) {
81
+ const ancestorIds = lineageManipulation.pluckIdsFromLineage(contactDoc.parent);
82
+ const ancestors = await db.allDocs({
83
+ keys: ancestorIds,
84
+ include_docs: true,
85
+ });
86
+
87
+ const ancestorIdsNotFound = ancestors.rows.filter(ancestor => !ancestor.doc).map(ancestor => ancestor.key);
88
+ if (ancestorIdsNotFound.length > 0) {
89
+ throw Error(`Contact '${contactDoc?.name}' (${contactDoc?._id}) has parent id(s) '${ancestorIdsNotFound.join(',')}' which could not be found.`);
90
+ }
91
+
92
+ return ancestors.rows.map(ancestor => ancestor.doc);
93
+ }
94
+
95
+ module.exports = {
96
+ BATCH_SIZE,
97
+ HIERARCHY_ROOT,
98
+ getAncestorsOf,
99
+ getContactWithDescendants,
100
+ getContact,
101
+ getContactsByIds,
102
+ getReportsForContacts,
103
+ };