-
Notifications
You must be signed in to change notification settings - Fork 13.9k
Expand file tree
/
Copy pathresolveContactConflicts.ts
More file actions
67 lines (56 loc) · 2.19 KB
/
Copy pathresolveContactConflicts.ts
File metadata and controls
67 lines (56 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import type { ILivechatContact, ILivechatContactConflictingField } from '@rocket.chat/core-typings';
import { LivechatContacts, Settings } from '@rocket.chat/models';
import { validateContactManager } from './validateContactManager';
import { notifyOnSettingChanged } from '../../../../lib/server/lib/notifyListener';
export type ResolveContactConflictsParams = {
contactId: string;
name?: string;
customFields?: Record<string, unknown>;
contactManager?: string;
wipeConflicts?: boolean;
};
export async function resolveContactConflicts(params: ResolveContactConflictsParams): Promise<ILivechatContact> {
const { contactId, name, customFields, contactManager, wipeConflicts } = params;
const contact = await LivechatContacts.findOneEnabledById<Pick<ILivechatContact, '_id' | 'customFields' | 'conflictingFields'>>(
contactId,
{
projection: { _id: 1, customFields: 1, conflictingFields: 1 },
},
);
if (!contact) {
throw new Error('error-contact-not-found');
}
if (!contact.conflictingFields?.length) {
throw new Error('error-contact-has-no-conflicts');
}
if (contactManager) {
await validateContactManager(contactManager);
}
let updatedConflictingFieldsArr: ILivechatContactConflictingField[] = [];
if (wipeConflicts) {
const value = await Settings.incrementValueById('Resolved_Conflicts_Count', contact.conflictingFields.length, {
returnDocument: 'after',
});
if (value) {
void notifyOnSettingChanged(value);
}
} else {
const fieldsToRemove = new Set<string>(
[
name && 'name',
contactManager && 'manager',
...(customFields ? Object.keys(customFields).map((key) => `customFields.${key}`) : []),
].filter((field): field is string => !!field),
);
updatedConflictingFieldsArr = contact.conflictingFields.filter(
(conflictingField: ILivechatContactConflictingField) => !fieldsToRemove.has(conflictingField.field),
) as ILivechatContactConflictingField[];
}
const dataToUpdate = {
...(name && { name }),
...(contactManager && { contactManager }),
...(customFields && { customFields: { ...contact.customFields, ...customFields } }),
conflictingFields: updatedConflictingFieldsArr,
};
return LivechatContacts.updateContact(contactId, dataToUpdate);
}