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.
@@ -0,0 +1,186 @@
1
+ const lineageManipulation = require('./lineage-manipulation');
2
+ const LineageConstraints = require('./lineage-constraints');
3
+ const { trace, info } = require('../log');
4
+
5
+ const JsDocs = require('./jsdocFolder');
6
+ const DataSource = require('./hierarchy-data-source');
7
+
8
+ async function moveHierarchy(db, options, sourceIds, destinationId) {
9
+ JsDocs.prepareFolder(options);
10
+ trace(`Fetching contact details: ${destinationId}`);
11
+ const constraints = await LineageConstraints(db, options);
12
+ const destinationDoc = await DataSource.getContact(db, destinationId);
13
+ const sourceDocs = await DataSource.getContactsByIds(db, sourceIds);
14
+ constraints.assertNoHierarchyErrors(Object.values(sourceDocs), destinationDoc);
15
+
16
+ let affectedContactCount = 0;
17
+ let affectedReportCount = 0;
18
+ const replacementLineage = lineageManipulation.createLineageFromDoc(destinationDoc);
19
+ for (const sourceId of sourceIds) {
20
+ const sourceDoc = sourceDocs[sourceId];
21
+ const descendantsAndSelf = await DataSource.getContactWithDescendants(db, sourceId);
22
+ const moveContext = {
23
+ sourceId,
24
+ destinationId,
25
+ descendantsAndSelf,
26
+ replacementLineage,
27
+ merge: !!options.merge,
28
+ };
29
+
30
+ await constraints.assertNoPrimaryContactViolations(sourceDoc, destinationDoc, descendantsAndSelf);
31
+
32
+ if (options.merge) {
33
+ JsDocs.writeDoc(options, {
34
+ _id: sourceDoc._id,
35
+ _rev: sourceDoc._rev,
36
+ _deleted: true,
37
+ });
38
+ }
39
+
40
+ const prettyPrintDocument = doc => `'${doc.name}' (${doc._id})`;
41
+ trace(`Considering lineage updates to ${descendantsAndSelf.length} descendant(s) of contact ${prettyPrintDocument(sourceDoc)}.`);
42
+ const updatedDescendants = replaceLineageInContacts(moveContext);
43
+
44
+ const ancestors = await DataSource.getAncestorsOf(db, sourceDoc);
45
+ trace(`Considering primary contact updates to ${ancestors.length} ancestor(s) of contact ${prettyPrintDocument(sourceDoc)}.`);
46
+ const updatedAncestors = replaceLineageInAncestors(descendantsAndSelf, ancestors);
47
+
48
+ minifyLineageAndWriteToDisk(options, [...updatedDescendants, ...updatedAncestors]);
49
+
50
+ const movedReportsCount = await updateReports(db, options, moveContext);
51
+ trace(`${movedReportsCount} report(s) created by these affected contact(s) will be updated`);
52
+
53
+ affectedContactCount += updatedDescendants.length + updatedAncestors.length;
54
+ affectedReportCount += movedReportsCount;
55
+
56
+ info(`Staged updates to ${prettyPrintDocument(sourceDoc)}. ${updatedDescendants.length} contact(s) and ${movedReportsCount} report(s).`);
57
+ }
58
+
59
+ info(`Staged changes to lineage information for ${affectedContactCount} contact(s) and ${affectedReportCount} report(s).`);
60
+ }
61
+
62
+ async function updateReports(db, options, moveContext) {
63
+ const descendantIds = moveContext.descendantsAndSelf.map(contact => contact._id);
64
+
65
+ let skip = 0;
66
+ let reportDocsBatch;
67
+ do {
68
+ info(`Processing ${skip} to ${skip + DataSource.BATCH_SIZE} report docs`);
69
+ const createdAtId = options.merge && moveContext.sourceId;
70
+ reportDocsBatch = await DataSource.getReportsForContacts(db, descendantIds, createdAtId, skip);
71
+
72
+ const lineageUpdates = replaceLineageOfReportCreator(reportDocsBatch, moveContext);
73
+ const reassignUpdates = reassignReports(reportDocsBatch, moveContext);
74
+ const updatedReports = reportDocsBatch.filter(doc => lineageUpdates.has(doc._id) || reassignUpdates.has(doc._id));
75
+
76
+ minifyLineageAndWriteToDisk(options, updatedReports);
77
+
78
+ skip += reportDocsBatch.length;
79
+ } while (reportDocsBatch.length >= DataSource.BATCH_SIZE);
80
+
81
+ return skip;
82
+ }
83
+
84
+ function reassignReportSubjects(report, { sourceId, destinationId }) {
85
+ const SUBJECT_IDS = ['patient_id', 'patient_uuid', 'place_id', 'place_uuid'];
86
+ let updated = false;
87
+ for (const subjectId of SUBJECT_IDS) {
88
+ if (report[subjectId] === sourceId) {
89
+ report[subjectId] = destinationId;
90
+ updated = true;
91
+ }
92
+
93
+ if (report.fields[subjectId] === sourceId) {
94
+ report.fields[subjectId] = destinationId;
95
+ updated = true;
96
+ }
97
+ }
98
+
99
+ return updated;
100
+ }
101
+
102
+ function reassignReports(reports, moveContext) {
103
+ const updated = new Set();
104
+ if (!moveContext.merge) {
105
+ return updated;
106
+ }
107
+
108
+ for (const report of reports) {
109
+ const isUpdated = reassignReportSubjects(report, moveContext);
110
+ if (isUpdated) {
111
+ updated.add(report._id);
112
+ }
113
+ }
114
+
115
+ return updated;
116
+ }
117
+
118
+ // This ensures all documents written are fully minified. Some docs in CouchDB are not minified to start with.
119
+ function minifyLineageAndWriteToDisk(options, docs) {
120
+ docs.forEach(doc => {
121
+ lineageManipulation.minifyLineagesInDoc(doc);
122
+ JsDocs.writeDoc(options, doc);
123
+ });
124
+ }
125
+
126
+ function replaceLineageOfReportCreator(reports, moveContext) {
127
+ const replaceContactLineage = doc => lineageManipulation.replaceContactLineage(doc, {
128
+ replaceWith: moveContext.replacementLineage,
129
+ startingFromId: moveContext.sourceId,
130
+ merge: moveContext.merge,
131
+ });
132
+
133
+ const updatedReportIds = reports
134
+ .filter(replaceContactLineage)
135
+ .map(({ _id }) => _id);
136
+ return new Set(updatedReportIds);
137
+ }
138
+
139
+ function replaceLineageInAncestors(descendantsAndSelf, ancestors) {
140
+ const updatedAncestors = [];
141
+ for (const ancestor of ancestors) {
142
+ const primaryContact = descendantsAndSelf.find(descendant => descendant._id === ancestor.contact?._id);
143
+ if (primaryContact) {
144
+ ancestor.contact = lineageManipulation.createLineageFromDoc(primaryContact);
145
+ updatedAncestors.unshift(ancestor);
146
+ }
147
+ }
148
+
149
+ return updatedAncestors;
150
+ }
151
+
152
+ function replaceLineageInSingleContact(doc, moveContext) {
153
+ const docIsSource = doc._id === moveContext.sourceId;
154
+ if (docIsSource && moveContext.merge) {
155
+ return;
156
+ }
157
+
158
+ const startingFromId = moveContext.merge || !docIsSource ? moveContext.sourceId : undefined;
159
+ const replaceLineageOptions = {
160
+ replaceWith: moveContext.replacementLineage,
161
+ startingFromId,
162
+ merge: moveContext.merge,
163
+ };
164
+ const parentWasUpdated = lineageManipulation.replaceParentLineage(doc, replaceLineageOptions);
165
+
166
+ replaceLineageOptions.startingFromId = moveContext.sourceId;
167
+ const contactWasUpdated = lineageManipulation.replaceContactLineage(doc, replaceLineageOptions);
168
+ if (parentWasUpdated || contactWasUpdated) {
169
+ return doc;
170
+ }
171
+ }
172
+
173
+ function replaceLineageInContacts(moveContext) {
174
+ return moveContext.descendantsAndSelf
175
+ .map(descendant => replaceLineageInSingleContact(descendant, moveContext))
176
+ .filter(Boolean);
177
+ }
178
+
179
+ module.exports = (db, options) => {
180
+ return {
181
+ HIERARCHY_ROOT: DataSource.HIERARCHY_ROOT,
182
+ move: (sourceIds, destinationId) => moveHierarchy(db, { ...options, merge: false }, sourceIds, destinationId),
183
+ merge: (sourceIds, destinationId) => moveHierarchy(db, { ...options, merge: true }, sourceIds, destinationId),
184
+ };
185
+ };
186
+
@@ -0,0 +1,37 @@
1
+ const path = require('path');
2
+ const userPrompt = require('../user-prompt');
3
+ const fs = require('../sync-fs');
4
+ const { warn, trace } = require('../log');
5
+
6
+ function prepareFolder({ docDirectoryPath, force }) {
7
+ if (!fs.exists(docDirectoryPath)) {
8
+ fs.mkdir(docDirectoryPath);
9
+ } else if (!force && fs.recurseFiles(docDirectoryPath).length > 0) {
10
+ deleteAfterConfirmation(docDirectoryPath);
11
+ }
12
+ }
13
+
14
+ function writeDoc({ docDirectoryPath }, doc) {
15
+ const destinationPath = path.join(docDirectoryPath, `${doc._id}.doc.json`);
16
+ if (fs.exists(destinationPath)) {
17
+ warn(`File at ${destinationPath} already exists and is being overwritten.`);
18
+ }
19
+
20
+ trace(`Writing updated document to ${destinationPath}`);
21
+ fs.writeJson(destinationPath, doc);
22
+ }
23
+
24
+ function deleteAfterConfirmation(docDirectoryPath) {
25
+ 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?`);
26
+ if (!userPrompt.keyInYN()) {
27
+ throw new Error('User aborted execution.');
28
+ }
29
+
30
+ fs.deleteFilesInFolder(docDirectoryPath);
31
+ }
32
+
33
+ module.exports = {
34
+ prepareFolder,
35
+ writeDoc,
36
+ };
37
+
@@ -0,0 +1,170 @@
1
+ const log = require('../log');
2
+ const { HIERARCHY_ROOT } = require('./hierarchy-data-source');
3
+ const { trace } = log;
4
+
5
+ const lineageManipulation = require('./lineage-manipulation');
6
+
7
+ module.exports = async (db, options) => {
8
+ const mapTypeToAllowedParents = await fetchAllowedParents(db);
9
+
10
+ return {
11
+ assertNoPrimaryContactViolations: async (sourceDoc, destinationDoc, descendantDocs) => {
12
+ const invalidPrimaryContactDoc = await getPrimaryContactViolations(db, sourceDoc, destinationDoc, descendantDocs);
13
+ if (invalidPrimaryContactDoc) {
14
+ throw Error(`Cannot remove contact '${invalidPrimaryContactDoc?.name}' (${invalidPrimaryContactDoc?._id}) from the hierarchy for which they are a primary contact.`);
15
+ }
16
+ },
17
+ assertNoHierarchyErrors: (sourceDocs, destinationDoc) => {
18
+
19
+ sourceDocs.forEach(sourceDoc => {
20
+ const commonViolations = getCommonViolations(sourceDoc, destinationDoc);
21
+ const specificViolation = options.merge ?
22
+ getMergeViolations(sourceDoc, destinationDoc)
23
+ : getMovingViolations(mapTypeToAllowedParents, sourceDoc, destinationDoc);
24
+
25
+ const hierarchyError = commonViolations || specificViolation;
26
+ if (hierarchyError) {
27
+ throw Error(`Hierarchy Constraints: ${hierarchyError}`);
28
+ }
29
+ });
30
+
31
+ /*
32
+ 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.
33
+ 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.
34
+ */
35
+ const contactIds = sourceDocs.map(doc => doc._id);
36
+ sourceDocs
37
+ .forEach(doc => {
38
+ const parentIdsOfDoc = lineageManipulation.pluckIdsFromLineage(doc.parent);
39
+ const violatingParentId = parentIdsOfDoc.find(parentId => contactIds.includes(parentId));
40
+ if (violatingParentId) {
41
+ throw Error(`Unable to move two documents from the same lineage: '${doc._id}' and '${violatingParentId}'`);
42
+ }
43
+ });
44
+ }
45
+ };
46
+ };
47
+
48
+ /*
49
+ Enforce the list of allowed parents for each contact type
50
+ Ensure we are not creating a circular hierarchy
51
+ */
52
+ const getMovingViolations = (mapTypeToAllowedParents, sourceDoc, destinationDoc) => {
53
+ const contactTypeError = getMovingContactTypeError(mapTypeToAllowedParents, sourceDoc, destinationDoc);
54
+ const circularHierarchyError = findCircularHierarchyErrors(sourceDoc, destinationDoc);
55
+ return contactTypeError || circularHierarchyError;
56
+ };
57
+
58
+ function getMovingContactTypeError(mapTypeToAllowedParents, sourceDoc, destinationDoc) {
59
+ const sourceContactType = getContactType(sourceDoc);
60
+ const destinationType = getContactType(destinationDoc);
61
+ const rulesForContact = mapTypeToAllowedParents[sourceContactType];
62
+ if (!rulesForContact) {
63
+ return `cannot move contact with unknown type '${sourceContactType}'`;
64
+ }
65
+
66
+ const isPermittedMoveToRoot = !destinationDoc && rulesForContact.length === 0;
67
+ if (!isPermittedMoveToRoot && !rulesForContact.includes(destinationType)) {
68
+ return `contacts of type '${sourceContactType}' cannot have parent of type '${destinationType}'`;
69
+ }
70
+ }
71
+
72
+ function findCircularHierarchyErrors(sourceDoc, destinationDoc) {
73
+ if (!destinationDoc) {
74
+ return;
75
+ }
76
+
77
+ const parentAncestry = lineageManipulation.pluckIdsFromLineage(destinationDoc);
78
+ if (parentAncestry.includes(sourceDoc._id)) {
79
+ return `Circular hierarchy: Cannot set parent of contact '${sourceDoc._id}' as it would create a circular hierarchy.`;
80
+ }
81
+ }
82
+
83
+ const getCommonViolations = (sourceDoc, destinationDoc) => {
84
+ if (!sourceDoc) {
85
+ return `source doc cannot be found`;
86
+ }
87
+
88
+ const sourceContactType = getContactType(sourceDoc);
89
+ const destinationContactType = getContactType(destinationDoc);
90
+ if (!sourceContactType) {
91
+ return `source contact "${sourceDoc._id}" required attribute "type" is undefined`;
92
+ }
93
+
94
+ if (destinationDoc && !destinationContactType) {
95
+ return `destination contact "${destinationDoc._id}" required attribute "type" is undefined`;
96
+ }
97
+
98
+ if (sourceDoc._id === destinationDoc?._id) {
99
+ return `cannot move or merge contact that is itself`;
100
+ }
101
+ };
102
+
103
+ const getMergeViolations = (sourceDoc, destinationDoc) => {
104
+ if (!destinationDoc) {
105
+ return `destination doc cannot be found`;
106
+ }
107
+
108
+ if ([sourceDoc._id, destinationDoc._id].includes(HIERARCHY_ROOT)) {
109
+ return `cannot merge using id: "${HIERARCHY_ROOT}"`;
110
+ }
111
+
112
+ const sourceContactType = getContactType(sourceDoc);
113
+ const destinationContactType = getContactType(destinationDoc);
114
+ if (sourceContactType !== destinationContactType) {
115
+ return `source and destinations must have the same type. Source is "${sourceContactType}" while destination is "${destinationContactType}".`;
116
+ }
117
+ };
118
+
119
+ /*
120
+ A place's primary contact must be a descendant of that place.
121
+
122
+ 1. Check to see which part of the contact's lineage will be removed
123
+ 2. For each removed part of the contact's lineage, confirm that place's primary contact isn't being removed.
124
+ */
125
+ const getPrimaryContactViolations = async (db, contactDoc, destinationDoc, descendantDocs) => {
126
+ const contactsLineageIds = lineageManipulation.pluckIdsFromLineage(contactDoc?.parent);
127
+ const parentsLineageIds = lineageManipulation.pluckIdsFromLineage(destinationDoc);
128
+
129
+ const docIdsRemovedFromContactLineage = contactsLineageIds.filter(value => !parentsLineageIds.includes(value));
130
+ const docsRemovedFromContactLineage = await db.allDocs({
131
+ keys: docIdsRemovedFromContactLineage,
132
+ include_docs: true,
133
+ });
134
+
135
+ const primaryContactIds = docsRemovedFromContactLineage.rows
136
+ .map(row => row?.doc?.contact?._id)
137
+ .filter(Boolean);
138
+
139
+ return descendantDocs.find(descendant => primaryContactIds.some(primaryId => descendant._id === primaryId));
140
+ };
141
+
142
+ const getContactType = doc => doc && (doc.type === 'contact' ? doc.contact_type : doc.type);
143
+
144
+ async function fetchAllowedParents(db) {
145
+ try {
146
+ const { settings: { contact_types } } = await db.get('settings');
147
+
148
+ if (Array.isArray(contact_types)) {
149
+ trace('Found app_settings.contact_types. Configurable hierarchy constraints will be enforced.');
150
+ const parentDict = {};
151
+ contact_types
152
+ .filter(Boolean)
153
+ .forEach(({ id, parents }) => parentDict[id] = parents);
154
+ return parentDict;
155
+ }
156
+ } catch (err) {
157
+ if (err.status !== 404) {
158
+ throw err;
159
+ }
160
+ }
161
+
162
+ trace('Default hierarchy constraints will be enforced.');
163
+ return {
164
+ district_hospital: [],
165
+ health_center: ['district_hospital'],
166
+ clinic: ['health_center'],
167
+ person: ['district_hospital', 'health_center', 'clinic'],
168
+ };
169
+ }
170
+
@@ -0,0 +1,63 @@
1
+ const { replaceContactLineage, replaceParentLineage } = require('./replace-lineage');
2
+
3
+ /*
4
+ Function borrowed from shared-lib/lineage
5
+ */
6
+ const minifyLineagesInDoc = doc => {
7
+ const minifyLineage = lineage => {
8
+ if (!lineage?._id) {
9
+ return;
10
+ }
11
+
12
+ return {
13
+ _id: lineage._id,
14
+ parent: minifyLineage(lineage.parent),
15
+ };
16
+ };
17
+
18
+ if (!doc) {
19
+ return;
20
+ }
21
+
22
+ if ('parent' in doc) {
23
+ doc.parent = minifyLineage(doc.parent);
24
+ }
25
+
26
+ if ('contact' in doc) {
27
+ doc.contact = minifyLineage(doc.contact);
28
+ }
29
+
30
+ if (doc.type === 'data_record') {
31
+ delete doc.patient;
32
+ }
33
+ };
34
+
35
+ const createLineageFromDoc = doc => {
36
+ if (!doc) {
37
+ return undefined;
38
+ }
39
+
40
+ return {
41
+ _id: doc._id,
42
+ parent: doc.parent || undefined,
43
+ };
44
+ };
45
+
46
+ /*
47
+ Given a lineage, return the ids therein
48
+ */
49
+ const pluckIdsFromLineage = (lineage, results = []) => {
50
+ if (!lineage) {
51
+ return results;
52
+ }
53
+
54
+ return pluckIdsFromLineage(lineage.parent, [...results, lineage._id]);
55
+ };
56
+
57
+ module.exports = {
58
+ createLineageFromDoc,
59
+ minifyLineagesInDoc,
60
+ pluckIdsFromLineage,
61
+ replaceParentLineage,
62
+ replaceContactLineage,
63
+ };
@@ -0,0 +1,76 @@
1
+ function replaceLineage(doc, lineageAttributeName, params) {
2
+ // Replace the full lineage
3
+ if (!params.startingFromId) {
4
+ return replaceEntireLineage(doc, lineageAttributeName, params.replaceWith);
5
+ }
6
+
7
+ const selectedFunction = params.merge ? replaceLineageForMerge : replaceLineageForMove;
8
+ return selectedFunction(doc, lineageAttributeName, params);
9
+ }
10
+
11
+ function replaceLineageForMove(doc, lineageAttributeName, params) {
12
+ let currentElement = doc[lineageAttributeName];
13
+ while (currentElement) {
14
+ if (currentElement?._id === params.startingFromId) {
15
+ return replaceEntireLineage(currentElement, 'parent', params.replaceWith);
16
+ }
17
+
18
+ currentElement = currentElement.parent;
19
+ }
20
+
21
+ return false;
22
+ }
23
+
24
+ function replaceLineageForMerge(doc, lineageAttributeName, params) {
25
+ let currentElement = doc;
26
+ let currentAttributeName = lineageAttributeName;
27
+ while (currentElement) {
28
+ if (currentElement[currentAttributeName]?._id === params.startingFromId) {
29
+ return replaceEntireLineage(currentElement, currentAttributeName, params.replaceWith);
30
+ }
31
+
32
+ currentElement = currentElement[currentAttributeName];
33
+ currentAttributeName = 'parent';
34
+ }
35
+
36
+ return false;
37
+ }
38
+
39
+ function replaceEntireLineage(replaceInDoc, lineageAttributeName, replaceWith) {
40
+ if (!replaceWith) {
41
+ const lineageWasDeleted = !!replaceInDoc[lineageAttributeName];
42
+ replaceInDoc[lineageAttributeName] = undefined;
43
+ return lineageWasDeleted;
44
+ }
45
+
46
+ replaceInDoc[lineageAttributeName] = replaceWith;
47
+ return true;
48
+ }
49
+
50
+ module.exports = {
51
+ /**
52
+ * Given a doc, replace the parent's lineage
53
+ *
54
+ * @param {Object} doc A CouchDB document containing a parent lineage (eg. parent.parent._id)
55
+ * @param {Object} params
56
+ * @param {Object} params.replaceWith The new hierarchy { parent: { _id: 'parent', parent: { _id: 'grandparent' } }
57
+ * @param {string} params.startingFromId Only the part of the lineage "after" this id will be replaced
58
+ * @param {boolean} params.merge When true, startingFromId is replaced and when false, startingFromId's parent is replaced
59
+ */
60
+ replaceParentLineage: (doc, params) => {
61
+ return replaceLineage(doc, 'parent', params);
62
+ },
63
+
64
+ /**
65
+ * Given a doc, replace the contact's lineage
66
+ *
67
+ * @param {Object} doc A CouchDB document containing a contact lineage (eg. contact.parent._id)
68
+ * @param {Object} params
69
+ * @param {Object} params.replaceWith The new hierarchy { parent: { _id: 'parent', parent: { _id: 'grandparent' } }
70
+ * @param {string} params.startingFromId Only the part of the lineage "after" this id will be replaced
71
+ * @param {boolean} params.merge When true, startingFromId is replaced and when false, startingFromId's parent is replaced
72
+ */
73
+ replaceContactLineage: (doc, params) => {
74
+ return replaceLineage(doc, 'contact', params);
75
+ },
76
+ };
@@ -1,94 +0,0 @@
1
- const log = require('./log');
2
- const { trace } = log;
3
-
4
- const { pluckIdsFromLineage } = require('./lineage-manipulation');
5
-
6
- const lineageConstraints = async (repository, parentDoc) => {
7
- let mapTypeToAllowedParents;
8
- try {
9
- const { settings } = await repository.get('settings');
10
- const { contact_types } = settings;
11
-
12
- if (Array.isArray(contact_types)) {
13
- trace('Found app_settings.contact_types. Configurable hierarchy constraints will be enforced.');
14
- mapTypeToAllowedParents = contact_types
15
- .filter(rule => rule)
16
- .reduce((agg, curr) => Object.assign(agg, { [curr.id]: curr.parents }), {});
17
- }
18
- } catch (err) {
19
- if (err.name !== 'not_found') {
20
- throw err;
21
- }
22
- }
23
-
24
- if (!mapTypeToAllowedParents) {
25
- trace('Default hierarchy constraints will be enforced.');
26
- mapTypeToAllowedParents = {
27
- district_hospital: [],
28
- health_center: ['district_hospital'],
29
- clinic: ['health_center'],
30
- person: ['district_hospital', 'health_center', 'clinic'],
31
- };
32
- }
33
-
34
- return {
35
- getHierarchyErrors: contactDoc => getHierarchyViolations(mapTypeToAllowedParents, contactDoc, parentDoc),
36
- getPrimaryContactViolations: (contactDoc, descendantDocs) => getPrimaryContactViolations(repository, contactDoc, parentDoc, descendantDocs),
37
- };
38
- };
39
-
40
- /*
41
- Enforce the list of allowed parents for each contact type
42
- Ensure we are not creating a circular hierarchy
43
- */
44
- const getHierarchyViolations = (mapTypeToAllowedParents, contactDoc, parentDoc) => {
45
- const getContactType = doc => doc && (doc.type === 'contact' ? doc.contact_type : doc.type);
46
- const contactType = getContactType(contactDoc);
47
- const parentType = getContactType(parentDoc);
48
- if (!contactType) return 'contact required attribute "type" is undefined';
49
- if (parentDoc && !parentType) return `parent contact "${parentDoc._id}" required attribute "type" is undefined`;
50
- if (!mapTypeToAllowedParents) return 'hierarchy constraints are undefined';
51
-
52
- const rulesForContact = mapTypeToAllowedParents[contactType];
53
- if (!rulesForContact) return `cannot move contact with unknown type '${contactType}'`;
54
-
55
- const isPermittedMoveToRoot = !parentDoc && rulesForContact.length === 0;
56
- if (!isPermittedMoveToRoot && !rulesForContact.includes(parentType)) return `contacts of type '${contactType}' cannot have parent of type '${parentType}'`;
57
-
58
- if (parentDoc && contactDoc._id) {
59
- const parentAncestry = [parentDoc._id, ...pluckIdsFromLineage(parentDoc.parent)];
60
- if (parentAncestry.includes(contactDoc._id)) {
61
- return `Circular hierarchy: Cannot set parent of contact '${contactDoc._id}' as it would create a circular hierarchy.`;
62
- }
63
- }
64
- };
65
-
66
- /*
67
- A place's primary contact must be a descendant of that place.
68
-
69
- 1. Check to see which part of the contact's lineage will be removed
70
- 2. For each removed part of the contact's lineage, confirm that place's primary contact isn't being removed.
71
- */
72
- const getPrimaryContactViolations = async (repository, contactDoc, parentDoc, descendantDocs) => {
73
- const safeGetLineageFromDoc = doc => doc ? pluckIdsFromLineage(doc.parent) : [];
74
- const contactsLineageIds = safeGetLineageFromDoc(contactDoc);
75
- const parentsLineageIds = safeGetLineageFromDoc(parentDoc);
76
-
77
- if (parentDoc) {
78
- parentsLineageIds.push(parentDoc._id);
79
- }
80
-
81
- const docIdsRemovedFromContactLineage = contactsLineageIds.filter(value => !parentsLineageIds.includes(value));
82
- const docsRemovedFromContactLineage = await repository.allDocs({
83
- keys: docIdsRemovedFromContactLineage,
84
- include_docs: true,
85
- });
86
-
87
- const primaryContactIds = docsRemovedFromContactLineage.rows
88
- .map(row => row.doc && row.doc.contact && row.doc.contact._id)
89
- .filter(id => id);
90
-
91
- return descendantDocs.find(descendant => primaryContactIds.some(primaryId => descendant._id === primaryId));
92
- };
93
-
94
- module.exports = lineageConstraints;