1 import { useCallback } from 'react';
3 import { c } from 'ttag';
5 import { useGetUserKeys } from '@proton/account/userKeys/hooks';
6 import useApi from '@proton/components/hooks/useApi';
7 import useEventManager from '@proton/components/hooks/useEventManager';
8 import useNotifications from '@proton/components/hooks/useNotifications';
9 import { addContacts, labelContactEmails, unLabelContactEmails } from '@proton/shared/lib/api/contacts';
10 import { createContactGroup, updateLabel } from '@proton/shared/lib/api/labels';
11 import { CATEGORIES, OVERWRITE } from '@proton/shared/lib/contacts/constants';
12 import { prepareVCardContacts } from '@proton/shared/lib/contacts/encrypt';
13 import { createContactPropertyUid } from '@proton/shared/lib/contacts/properties';
14 import type { Label } from '@proton/shared/lib/interfaces';
15 import type { ContactEmail } from '@proton/shared/lib/interfaces/contacts';
17 export type UpdateGroupOptions = {
18 groupID: string | undefined;
21 toAdd: ContactEmail[];
22 toRemove: ContactEmail[];
23 toCreate: ContactEmail[];
24 onDelayedSave?: (groupID: string) => void;
27 const useUpdateGroup = () => {
29 const { call } = useEventManager();
30 const { createNotification } = useNotifications();
31 const getUserKeys = useGetUserKeys();
34 async ({ groupID, name, color, toAdd, toRemove, toCreate, onDelayedSave }: UpdateGroupOptions) => {
35 // Update contact group
36 const contactGroupParams = { Name: name, Color: color };
38 Label: { ID: LabelID },
39 } = await api<{ Label: Label }>(
40 groupID ? updateLabel(groupID, contactGroupParams) : createContactGroup(contactGroupParams)
44 onDelayedSave(LabelID);
47 // Create new contacts
48 if (toCreate.length) {
49 const vCardContacts = toCreate.map(({ Email }) => ({
50 fn: [{ field: 'fn', value: Email, uid: createContactPropertyUid() }],
51 email: [{ field: 'email', value: Email, group: 'item1', uid: createContactPropertyUid() }],
52 categories: [{ field: 'categories', value: name, group: 'item1', uid: createContactPropertyUid() }],
54 const userKeys = await getUserKeys();
55 const Contacts = await prepareVCardContacts(vCardContacts, userKeys[0]);
59 Overwrite: OVERWRITE.THROW_ERROR_IF_CONFLICT,
60 Labels: CATEGORIES.INCLUDE,
65 // Label and unlabel existing contact emails
68 toAdd.length && api(labelContactEmails({ LabelID, ContactEmailIDs: toAdd.map(({ ID }) => ID) })),
70 api(unLabelContactEmails({ LabelID, ContactEmailIDs: toRemove.map(({ ID }) => ID) })),
75 text: groupID ? c('Notification').t`Contact group updated` : c('Notification').t`Contact group created`,
82 export default useUpdateGroup;