Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring/queue members api [WTEL-3619] #481

Merged
merged 11 commits into from
Nov 7, 2023
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import eventBus from '@webitel/ui-sdk/src/scripts/eventBus';
import deepCopy from 'deep-copy';
import { MemberServiceApiFactory } from 'webitel-sdk';
import {
SdkCreatorApiConsumer,
SdkDeleterApiConsumer,
SdkGetterApiConsumer,
SdkListGetterApiConsumer,
SdkPatcherApiConsumer,
SdkUpdaterApiConsumer,
} from 'webitel-sdk/esm2015/api-consumers';
import instance from '../../../../../../../app/api/old/instance';
getDefaultGetListResponse,
getDefaultGetParams,
} from '@webitel/ui-sdk/src/api/defaults';
import applyTransform, {
camelToSnake,
merge, mergeEach, notify, sanitize, snakeToCamel,
starToSearch,
} from '@webitel/ui-sdk/src/api/transformers';
import { MemberServiceApiFactory } from 'webitel-sdk';
import instance from '../../../../../../../app/api/instance';
import configuration from '../../../../../../../app/api/openAPIConfig';
import sanitizer from '../../../../../../../app/api/old/utils/sanitizer';

const memberService = new MemberServiceApiFactory(configuration, '', instance);

Expand All @@ -30,23 +28,6 @@ const communicationsFieldsToSend = [
'dtmf',
];

const defaultListObject = {
createdAt: 'unknown',
priority: 0,
};

const defaultSingleObject = {
createdAt: 'unknown',
priority: '0',
name: 'member',
expireAt: 0,
bucket: {},
timezone: {},
agent: {},
communications: [],
variables: [],
};

const defaultSingleObjectCommunication = {
destination: '',
display: '',
Expand All @@ -57,99 +38,213 @@ const defaultSingleObjectCommunication = {
dtmf: '',
};

const mapDefaultCommunications = (item) => (
item.communications ? item.communications
.map((comm) => ({ ...defaultSingleObjectCommunication, ...comm })) : []
);

const _getMembersList = (getList) => function({
page,
size,
search,
sort,
fields,
id,
parentId,
from,
to,
bucket,
priorityFrom,
priorityTo,
priority,
cause,
agent,
}) {
const params = [
parentId, page, size, search, sort, fields, id, bucket,
undefined, from, to, undefined, undefined, cause,
priorityFrom || priority?.from, priorityTo || priority?.to,
undefined, undefined, undefined, agent,
];

return getList(params);
};

const listResponseHandler = (response) => {
const items = response.items.map((item) => ({
...item,
communications: mapDefaultCommunications(item),
}));
return { items, next: response.next };
};

const itemResponseHandler = (response) => {
let variables = [];
if (response.variables) {
variables = Object.keys(response.variables).map((key) => ({
key,
value: response.variables[key],
}));
}
const communications = mapDefaultCommunications(response);
return { ...response, variables, communications };
const mapDefaultCommunications = (item) => {
return item.communications ? item.communications
.map((comm) => ({ ...defaultSingleObjectCommunication, ...comm })) : [];
};

const preRequestHandler = (item) => {
item.communications
.forEach((item) => sanitizer(item, communicationsFieldsToSend));
.forEach((item) => sanitize(item, communicationsFieldsToSend));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

мутує початковий об'єкт
треба зробити копію спершу

const variables = item.variables.reduce((variables, variable) => ({
...variables,
[variable.key]: variable.value,
}), {});
return { ...item, variables };
};

const listGetter = new SdkListGetterApiConsumer(
memberService.searchMemberInQueue,
{ defaultListObject, listResponseHandler },
)
.setGetListMethod(_getMembersList);
const itemGetter = new SdkGetterApiConsumer(
memberService.readMember,
{ defaultSingleObject, itemResponseHandler },
);
const itemCreator = new SdkCreatorApiConsumer(
memberService.createMember,
{ fieldsToSend, preRequestHandler },
);
const itemUpdater = new SdkUpdaterApiConsumer(
memberService.updateMember,
{ fieldsToSend, preRequestHandler },
);
const itemDeleter = new SdkDeleterApiConsumer(memberService.deleteMember);

const resetMembersApiConsumer = new SdkPatcherApiConsumer(memberService.resetMembers);

const getMembersList = (params) => listGetter.getList(params);
const getMember = (params) => itemGetter.getNestedItem(params);
const addMember = (params) => itemCreator.createNestedItem(params);
const updateMember = (params) => itemUpdater.updateNestedItem(params);
const deleteMember = (params) => itemDeleter.deleteNestedItem(params);

const resetMembers = ({ parentId }) => resetMembersApiConsumer
.patchItem({ id: parentId, changes: {} });

export const deleteMembersBulk = async (queueId, {
const getMembersList = async (params) => {
const defaultObject = {
createdAt: 'unknown',
priority: 0,
}
const listHandler = (items) => {
return items.map((item) => ({
...item,
communications: mapDefaultCommunications(item),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

зійде для сільської місцевості, але якщо хочеш по-крутому, то було би круто на коммунікації накласти трансформер, замість виклику метода)

}));
};

const {
page,
size,
search,
sort,
fields,
id,
parentId,
from,
to,
bucket,
priorityFrom,
priorityTo,
priority,
cause,
agent,
} = applyTransform(params, [
merge(getDefaultGetParams()),
starToSearch('search'),
]);

try {
const response = await memberService.searchMemberInQueue(
parentId,
page,
size,
search,
sort,
fields,
id,
bucket,
undefined,
from,
to,
undefined,
undefined,
cause,
priorityFrom || priority?.from,
priorityTo || priority?.to,
undefined,
undefined,
undefined,
agent,
);
const { items, next } = applyTransform(response.data, [
snakeToCamel(),
merge(getDefaultGetListResponse()),
]);
return {
items: applyTransform(items, [
mergeEach(defaultObject),
listHandler,
]),
next,
};
} catch (err) {
throw applyTransform(err, [
notify,
]);
}
};

const getMember = async ({ parentId, itemId: id }) => {
const defaultObject = {
createdAt: 'unknown',
priority: '0',
name: 'member',
expireAt: 0,
bucket: {},
timezone: {},
agent: {},
communications: [],
variables: [],
};

const responseHandler = (response) => {
let variables = [];
if (response.variables) {
variables = Object.keys(response.variables).map((key) => ({
key,
value: response.variables[key],
}));
}
const communications = mapDefaultCommunications(response);
return { ...response, variables, communications };
};

try {
const response = await memberService.readMember(parentId, id);
return applyTransform(response.data, [
snakeToCamel(),
merge(defaultObject),
responseHandler,
]);
} catch (err) {
throw applyTransform(err, [
notify,
]);
}
};

const addMember = async ({ parentId, itemInstance }) => {
const item = applyTransform(itemInstance, [
preRequestHandler,
sanitize(fieldsToSend),
camelToSnake(),
]);
try {
const response = await memberService.createMember(parentId, item);
return applyTransform(response.data, [
snakeToCamel(),
]);
} catch (err) {
throw applyTransform(err, [
notify,
]);
}
};

const updateMember = async ({ itemInstance, itemId: id, parentId }) => {
const body = applyTransform(itemInstance, [
preRequestHandler,
sanitize(fieldsToSend),
camelToSnake(),
]);
try {
const response = await memberService.updateMember(parentId, id, body);
return applyTransform(response.data, [
snakeToCamel(),
]);
} catch (err) {
throw applyTransform(err, [
notify,
]);
}
};

const deleteMember = async ({ parentId, id }) => {
try {
const response = await memberService.deleteMember(parentId, id);
return applyTransform(response.data, []);
} catch (err) {
throw applyTransform(err, [
notify,
]);
}
};

const resetMembers = async ({ parentId }) => {
try {
const response = await memberService.resetMembers(parentId, {});
return applyTransform(response.data, [
snakeToCamel(),
]);
} catch (err) {
throw applyTransform(err, [
notify,
]);
}
};

const addMembersBulk = async (parentId, fileName, items) => {
const body = { parentId, fileName, items };
try {
const response = await memberService.createMemberBulk(parentId, body);
return applyTransform(response.data, [
snakeToCamel(),
notify(({ callback }) => callback({
type: 'info',
text: 'Successfully added',
})),
]);
} catch (err) {
throw applyTransform(err, [
notify,
]);
}
};

export const deleteMembersBulk = async (parentId, {
search,
id,
from,
Expand All @@ -158,31 +253,21 @@ export const deleteMembersBulk = async (queueId, {
priority,
cause,
}) => {
const body = {
id,
q: search,
createdAt: (from || to) ? { from, to } : undefined,
priority,
stopCause: cause,
bucketId: bucket,
};
try {
await memberService.deleteMembers(queueId, {
id,
q: search,
createdAt: (from || to) ? { from, to } : undefined,
priority,
stopCause: cause,
bucketId: bucket,
});
} catch (err) {
throw err;
}
};

const addMembersBulk = async (queueId, fileName, items) => {
const itemsCopy = deepCopy(items);
const body = { queueId, fileName, items: itemsCopy };
try {
await memberService.createMemberBulk(queueId, body);
eventBus.$emit('notification', {
type: 'info',
text: 'Successfully added',
});
const response = await memberService.deleteMembers(parentId, body);
return applyTransform(response.data, []);
} catch (err) {
throw err;
throw applyTransform(err, [
notify,
]);
}
};

Expand Down
Loading