cht-conf 4.1.3 → 4.3.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 +14 -0
- package/package.json +1 -1
- package/src/fn/edit-contacts.js +70 -50
- package/src/fn/merge-contacts.js +74 -0
- package/src/fn/move-contacts.js +13 -236
- package/src/fn/upload-docs.js +104 -18
- package/src/lib/api.js +24 -0
- package/src/lib/hierarchy-operations/hierarchy-data-source.js +103 -0
- package/src/lib/hierarchy-operations/index.js +187 -0
- package/src/lib/hierarchy-operations/jsdocFolder.js +37 -0
- package/src/lib/hierarchy-operations/lineage-constraints.js +170 -0
- package/src/lib/hierarchy-operations/lineage-manipulation.js +63 -0
- package/src/lib/hierarchy-operations/replace-lineage.js +76 -0
- package/src/lib/user-prompt.js +10 -1
- package/src/lib/lineage-constraints.js +0 -94
- package/src/lib/lineage-manipulation.js +0 -107
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
+
# [4.3.0](https://github.com/medic/cht-conf/compare/v4.2.0...v4.3.0) (2024-12-16)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Features
|
|
5
|
+
|
|
6
|
+
* **#648:** add --disable-users command for merge-contacts action ([#649](https://github.com/medic/cht-conf/issues/649)) ([c78d3fd](https://github.com/medic/cht-conf/commit/c78d3fd1ed1588cfefdf21384840743f5faea62d)), closes [#648](https://github.com/medic/cht-conf/issues/648)
|
|
7
|
+
|
|
8
|
+
# [4.2.0](https://github.com/medic/cht-conf/compare/v4.1.3...v4.2.0) (2024-12-11)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Features
|
|
12
|
+
|
|
13
|
+
* **#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)
|
|
14
|
+
|
|
1
15
|
## [4.1.3](https://github.com/medic/cht-conf/compare/v4.1.2...v4.1.3) (2024-11-13)
|
|
2
16
|
|
|
3
17
|
|
package/package.json
CHANGED
package/src/fn/edit-contacts.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
134
|
+
return `${idPrefix}${documentId}`;
|
|
135
|
+
};
|
|
147
136
|
|
|
137
|
+
const getCsvRowFilterFn = (uuidIndex, toIncludeIndex) => {
|
|
148
138
|
if (toIncludeIndex.length > 0) {
|
|
149
|
-
row
|
|
150
|
-
} else {
|
|
151
|
-
row.splice(uuidIndex,1);
|
|
139
|
+
return row => toIncludeIndex.map(index => row[index]);
|
|
152
140
|
}
|
|
153
141
|
|
|
154
|
-
|
|
155
|
-
const
|
|
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
|
-
|
|
158
|
-
|
|
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
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
}
|
|
157
|
+
toDocs.setCol(doc, col, val);
|
|
158
|
+
if (excluded) {
|
|
159
|
+
model.exclusions.push({
|
|
160
|
+
doc,
|
|
161
|
+
propertyName: col,
|
|
162
|
+
});
|
|
168
163
|
}
|
|
169
|
-
|
|
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,74 @@
|
|
|
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
|
+
disableUsers: args.disableUsers,
|
|
17
|
+
docDirectoryPath: args.docDirectoryPath,
|
|
18
|
+
force: args.force,
|
|
19
|
+
};
|
|
20
|
+
return HierarchyOperations(db, options).merge(args.sourceIds, args.destinationId);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// Parses extraArgs and asserts if required parameters are not present
|
|
25
|
+
const parseExtraArgs = (projectDir, extraArgs = []) => {
|
|
26
|
+
const args = minimist(extraArgs, { boolean: true });
|
|
27
|
+
|
|
28
|
+
const sourceIds = (args.sources || args.source || '')
|
|
29
|
+
.split(',')
|
|
30
|
+
.filter(Boolean);
|
|
31
|
+
|
|
32
|
+
if (!args.destination) {
|
|
33
|
+
usage();
|
|
34
|
+
throw Error(`Action "merge-contacts" is missing required contact ID ${bold('--destination')}. Other contacts will be merged into this contact.`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (sourceIds.length === 0) {
|
|
38
|
+
usage();
|
|
39
|
+
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')}`);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
destinationId: args.destination,
|
|
44
|
+
sourceIds,
|
|
45
|
+
disableUsers: !!args['disable-users'],
|
|
46
|
+
docDirectoryPath: path.resolve(projectDir, args.docDirectoryPath || 'json_docs'),
|
|
47
|
+
force: !!args.force,
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const bold = text => `\x1b[1m${text}\x1b[0m`;
|
|
52
|
+
const usage = () => {
|
|
53
|
+
info(`
|
|
54
|
+
${bold('cht-conf\'s merge-contacts action')}
|
|
55
|
+
When combined with 'upload-docs' this action moves all of the contacts and reports under ${bold('sources')} to be under ${bold('destination')}.
|
|
56
|
+
The top-level ${bold('source contact(s)')} are deleted and no data from this document is merged or preserved.
|
|
57
|
+
|
|
58
|
+
${bold('USAGE')}
|
|
59
|
+
cht --local merge-contacts -- --destination=<destination_id> --sources=<source_id1>,<source_id2>
|
|
60
|
+
|
|
61
|
+
${bold('OPTIONS')}
|
|
62
|
+
--destination=<destination_id>
|
|
63
|
+
Specifies the ID of the contact that should receive the moving contacts and reports.
|
|
64
|
+
|
|
65
|
+
--sources=<source_id1>,<source_id2>
|
|
66
|
+
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.
|
|
67
|
+
|
|
68
|
+
--disable-users
|
|
69
|
+
When flag is present, users at any deleted place will be updated and may be permanently disabled. Supported by CHT Core 4.7 and above.
|
|
70
|
+
|
|
71
|
+
--docDirectoryPath=<path to stage docs>
|
|
72
|
+
Specifies the folder used to store the documents representing the changes in hierarchy.
|
|
73
|
+
`);
|
|
74
|
+
};
|
package/src/fn/move-contacts.js
CHANGED
|
@@ -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 {
|
|
6
|
+
const { info } = require('../lib/log');
|
|
11
7
|
|
|
12
|
-
const
|
|
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
|
-
|
|
21
|
-
|
|
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
|
|
27
|
+
const sourceIds = (args.contacts || args.contact || '')
|
|
99
28
|
.split(',')
|
|
100
29
|
.filter(id => id);
|
|
101
30
|
|
|
102
|
-
if (
|
|
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
|
-
|
|
114
|
-
|
|
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
|
|
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
|
-
}, []);
|