From c85c72f05e54ccf8bbdf6adf94f12dc9bc3cdebf Mon Sep 17 00:00:00 2001 From: AndreaCimini90 <99173401+AndreaCimini90@users.noreply.github.com> Date: Mon, 20 May 2024 11:34:41 +0200 Subject: [PATCH] feat(pn-10953): Mandate api migration (#1209) --- .../pn-commons/src/utility/redux.utility.ts | 6 +- .../pn-personafisica-webapp/openapitools.json | 11 + packages/pn-personafisica-webapp/src/App.tsx | 3 +- .../src/__mocks__/CreateDelegation.mock.ts | 20 +- .../src/__mocks__/Delegations.mock.ts | 8 +- .../src/__test__/App.test.tsx | 17 +- .../src/api/delegations/Delegations.api.ts | 116 -- .../__test__/Delegations.api.test.ts | 105 -- .../__test__/delegations.routes.test.ts | 40 - .../src/api/delegations/delegations.routes.ts | 78 - .../src/components/Deleghe/Delegates.tsx | 6 +- .../src/components/Deleghe/Delegators.tsx | 6 +- .../components/Deleghe/MobileDelegates.tsx | 6 +- .../components/Deleghe/MobileDelegators.tsx | 6 +- .../Deleghe/__test__/Delegates.test.tsx | 20 +- .../__test__/DelegationDataSwitch.test.tsx | 4 +- .../Deleghe/__test__/Delegators.test.tsx | 16 +- .../Deleghe/__test__/MobileDelegates.test.tsx | 12 +- .../__test__/MobileDelegators.test.tsx | 8 +- .../__test__/DesktopNotifications.test.tsx | 4 +- .../mandate/.openapi-generator-ignore | 28 + .../mandate/.openapi-generator/FILES | 8 + .../mandate/.openapi-generator/VERSION | 1 + .../src/generated-client/mandate/api.ts | 1269 +++++++++++++++++ .../src/generated-client/mandate/base.ts | 86 ++ .../src/generated-client/mandate/common.ts | 150 ++ .../generated-client/mandate/configuration.ts | 110 ++ .../src/generated-client/mandate/index.ts | 18 + .../src/models/PFEventsType.ts | 4 +- .../src/pages/Deleghe.page.tsx | 24 +- .../src/pages/__test__/Deleghe.page.test.tsx | 87 +- .../__test__/NotificationDetail.page.test.tsx | 8 +- .../src/pages/__test__/NuovaDelega.test.tsx | 9 +- .../delegation/__test__/reducers.test.ts | 97 +- .../src/redux/delegation/actions.ts | 94 +- .../src/redux/delegation/reducers.ts | 38 +- .../src/redux/delegation/types.ts | 36 +- .../newDelegation/__test__/reducers.test.ts | 18 +- .../src/redux/newDelegation/actions.ts | 25 +- .../src/redux/newDelegation/reducers.ts | 4 +- .../src/redux/newDelegation/types.ts | 7 - .../redux/sidemenu/__test__/reducers.test.ts | 51 +- .../src/redux/sidemenu/actions.ts | 40 +- .../src/redux/sidemenu/reducers.ts | 6 +- .../SendHasMandateGivensStrategy.ts | 4 +- .../Strategies/SendHasMandateStrategy.ts | 4 +- .../Strategies/SendYourMandatesStrategy.ts | 6 +- .../SendHasMandateGivenStrategy.test.ts | 4 +- .../SendHasMandateLoginStrategy.test.ts | 4 +- .../__test__/SendYourMandatesStrategy.test.ts | 6 +- .../SendYourNotificationsStrategy.test.ts | 4 +- .../__test__/delegation.utility.test.ts | 34 +- .../__test__/notification.utility.test.ts | 14 +- .../src/utility/delegation.utility.ts | 26 +- .../validators/CreateDelegationValidator.ts | 7 +- .../openapitools.json | 11 + .../src/__mocks__/CreateDelegation.mock.ts | 20 +- .../src/__mocks__/Delegations.mock.ts | 4 +- .../src/__test__/App.test.tsx | 25 +- .../src/api/delegations/Delegations.api.ts | 197 --- .../__test__/Delegations.api.test.ts | 122 -- .../__test__/delegations.routes.test.ts | 59 - .../src/api/delegations/delegations.routes.ts | 118 -- .../Deleghe/AcceptDelegationModal.tsx | 4 +- .../components/Deleghe/DelegatesByCompany.tsx | 6 +- .../Deleghe/DelegationsElements.tsx | 24 +- .../Deleghe/DelegationsOfTheCompany.tsx | 8 +- .../__test__/AcceptDelegationModal.test.tsx | 267 ++++ .../__test__/ConfirmationModal.test.tsx | 78 + .../__test__/DelegatesByCompany.test.tsx | 164 +++ .../__test__/DelegationDataSwitch.test.tsx | 123 ++ .../__test__/DelegationsElements.test.tsx | 396 +++++ .../__test__/DelegationsOfTheCompany.test.tsx | 475 ++++++ .../VerificationCodeComponent.test.tsx | 15 + .../mandate/.openapi-generator-ignore | 28 + .../mandate/.openapi-generator/FILES | 9 + .../mandate/.openapi-generator/VERSION | 1 + .../src/generated-client/mandate/api.ts | 1269 +++++++++++++++++ .../src/generated-client/mandate/base.ts | 86 ++ .../src/generated-client/mandate/common.ts | 150 ++ .../generated-client/mandate/configuration.ts | 110 ++ .../src/generated-client/mandate/index.ts | 18 + .../src/models/Deleghe.ts | 56 +- .../src/pages/Deleghe.page.tsx | 10 +- .../src/pages/__test__/Deleghe.page.test.tsx | 20 +- .../__test__/NotificationDetail.page.test.tsx | 4 +- .../pages/__test__/NuovaDelega.page.test.tsx | 19 +- .../delegation/__test__/reducers.test.ts | 132 +- .../src/redux/delegation/actions.ts | 130 +- .../src/redux/delegation/reducers.ts | 48 +- .../newDelegation/__test__/reducers.test.ts | 18 +- .../src/redux/newDelegation/actions.ts | 27 +- .../redux/sidemenu/__test__/reducers.test.ts | 31 +- .../src/redux/sidemenu/actions.ts | 36 +- .../src/redux/sidemenu/reducers.ts | 4 +- .../__test__/delegation.utility.test.ts | 34 +- .../src/utility/delegation.utility.ts | 22 +- 97 files changed, 5586 insertions(+), 1615 deletions(-) delete mode 100644 packages/pn-personafisica-webapp/src/api/delegations/Delegations.api.ts delete mode 100644 packages/pn-personafisica-webapp/src/api/delegations/__test__/Delegations.api.test.ts delete mode 100644 packages/pn-personafisica-webapp/src/api/delegations/__test__/delegations.routes.test.ts delete mode 100644 packages/pn-personafisica-webapp/src/api/delegations/delegations.routes.ts create mode 100644 packages/pn-personafisica-webapp/src/generated-client/mandate/.openapi-generator-ignore create mode 100644 packages/pn-personafisica-webapp/src/generated-client/mandate/.openapi-generator/FILES create mode 100644 packages/pn-personafisica-webapp/src/generated-client/mandate/.openapi-generator/VERSION create mode 100644 packages/pn-personafisica-webapp/src/generated-client/mandate/api.ts create mode 100644 packages/pn-personafisica-webapp/src/generated-client/mandate/base.ts create mode 100644 packages/pn-personafisica-webapp/src/generated-client/mandate/common.ts create mode 100644 packages/pn-personafisica-webapp/src/generated-client/mandate/configuration.ts create mode 100644 packages/pn-personafisica-webapp/src/generated-client/mandate/index.ts delete mode 100644 packages/pn-personafisica-webapp/src/redux/newDelegation/types.ts delete mode 100644 packages/pn-personagiuridica-webapp/src/api/delegations/Delegations.api.ts delete mode 100644 packages/pn-personagiuridica-webapp/src/api/delegations/__test__/Delegations.api.test.ts delete mode 100644 packages/pn-personagiuridica-webapp/src/api/delegations/__test__/delegations.routes.test.ts delete mode 100644 packages/pn-personagiuridica-webapp/src/api/delegations/delegations.routes.ts create mode 100644 packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/AcceptDelegationModal.test.tsx create mode 100644 packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/ConfirmationModal.test.tsx create mode 100644 packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegatesByCompany.test.tsx create mode 100644 packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegationDataSwitch.test.tsx create mode 100644 packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegationsElements.test.tsx create mode 100644 packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegationsOfTheCompany.test.tsx create mode 100644 packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/VerificationCodeComponent.test.tsx create mode 100644 packages/pn-personagiuridica-webapp/src/generated-client/mandate/.openapi-generator-ignore create mode 100644 packages/pn-personagiuridica-webapp/src/generated-client/mandate/.openapi-generator/FILES create mode 100644 packages/pn-personagiuridica-webapp/src/generated-client/mandate/.openapi-generator/VERSION create mode 100644 packages/pn-personagiuridica-webapp/src/generated-client/mandate/api.ts create mode 100644 packages/pn-personagiuridica-webapp/src/generated-client/mandate/base.ts create mode 100644 packages/pn-personagiuridica-webapp/src/generated-client/mandate/common.ts create mode 100644 packages/pn-personagiuridica-webapp/src/generated-client/mandate/configuration.ts create mode 100644 packages/pn-personagiuridica-webapp/src/generated-client/mandate/index.ts diff --git a/packages/pn-commons/src/utility/redux.utility.ts b/packages/pn-commons/src/utility/redux.utility.ts index 63f0548605..271f92f446 100644 --- a/packages/pn-commons/src/utility/redux.utility.ts +++ b/packages/pn-commons/src/utility/redux.utility.ts @@ -53,15 +53,15 @@ export function parseError(e: any) { * D'altro canto, la funzione che si passa verso performThunkAction può avere parametri, e può realizzare azione più complesse * che chiamare un'API senza parametri, o con i parametri che vengono passati. Un esempio - export const acceptDelegation = createAsyncThunk< + export const acceptMandate = createAsyncThunk< AcceptDelegationResponse, { id: string; code: string } - >('acceptDelegation', + >('acceptMandate', performThunkAction(async ({id, code}: { id: string; code: string }) => { const data = { verificationCode: code, }; - return await DelegationsApi.acceptDelegation(id, data); + return await DelegationsApi.acceptMandate(id, data); }) ); diff --git a/packages/pn-personafisica-webapp/openapitools.json b/packages/pn-personafisica-webapp/openapitools.json index 671d120701..4c4103fb08 100644 --- a/packages/pn-personafisica-webapp/openapitools.json +++ b/packages/pn-personafisica-webapp/openapitools.json @@ -58,6 +58,17 @@ "modelPackage": "models", "cleanupOutput": true } + }, + "bff-mandate": { + "generatorName": "typescript-axios", + "inputSpec": "https://raw.githubusercontent.com/pagopa/pn-bff/develop/docs/openapi/api-external-pn-bff-recipient-mandate.yaml", + "output": "./src/generated-client/mandate", + "additionalProperties": { + "supportsES6": true, + "apiPackage": "apis", + "modelPackage": "models", + "cleanupOutput": true + } } } } diff --git a/packages/pn-personafisica-webapp/src/App.tsx b/packages/pn-personafisica-webapp/src/App.tsx index 29de5e09ee..bbf4c9d9cd 100644 --- a/packages/pn-personafisica-webapp/src/App.tsx +++ b/packages/pn-personafisica-webapp/src/App.tsx @@ -34,7 +34,6 @@ import Router from './navigation/routes'; import * as routes from './navigation/routes.const'; import { getCurrentAppStatus } from './redux/appStatus/actions'; import { logout } from './redux/auth/actions'; -import { Delegation } from './redux/delegation/types'; import { useAppDispatch, useAppSelector } from './redux/hooks'; import { getDomicileInfo, getSidemenuInformation } from './redux/sidemenu/actions'; import { RootState } from './redux/store'; @@ -149,7 +148,7 @@ const App = () => { label: t('title', { ns: 'notifiche' }), route: routes.NOTIFICHE, }; - const mappedDelegators = delegators.map((delegator: Delegation) => ({ + const mappedDelegators = delegators.map((delegator) => ({ label: 'delegator' in delegator && delegator.delegator ? `${delegator.delegator.displayName}` diff --git a/packages/pn-personafisica-webapp/src/__mocks__/CreateDelegation.mock.ts b/packages/pn-personafisica-webapp/src/__mocks__/CreateDelegation.mock.ts index 92cd00a0e0..d9b48d8d21 100644 --- a/packages/pn-personafisica-webapp/src/__mocks__/CreateDelegation.mock.ts +++ b/packages/pn-personafisica-webapp/src/__mocks__/CreateDelegation.mock.ts @@ -1,6 +1,6 @@ import { RecipientType } from '@pagopa-pn/pn-commons'; -import { CreateDelegationResponse, NewDelegationFormProps } from '../redux/delegation/types'; +import { NewDelegationFormProps } from '../redux/delegation/types'; export const createDelegationPayload: NewDelegationFormProps = { selectPersonaFisicaOrPersonaGiuridica: RecipientType.PF, @@ -20,24 +20,6 @@ export const createDelegationSelectedPayload: NewDelegationFormProps = { enti: [{ name: 'test', id: 'test' }], }; -export const createDelegationResponse: CreateDelegationResponse = { - datefrom: '2022-01-01', - dateto: '2022-01-02', - delegate: { - firstName: 'nome', - lastName: 'cognome', - displayName: 'nome cognome', - fiscalCode: 'fiscalCode', - companyName: 'companyName', - person: true, - }, - delegator: null, - mandateId: '1', - status: 'pending', - verificationCode: '00000', - visibilityIds: [], -}; - export const createDelegationGenericErrorResponse = { status: 401, }; diff --git a/packages/pn-personafisica-webapp/src/__mocks__/Delegations.mock.ts b/packages/pn-personafisica-webapp/src/__mocks__/Delegations.mock.ts index 27b7b3aab9..ecbccc9f97 100644 --- a/packages/pn-personafisica-webapp/src/__mocks__/Delegations.mock.ts +++ b/packages/pn-personafisica-webapp/src/__mocks__/Delegations.mock.ts @@ -1,6 +1,6 @@ -import { CreateDelegationProps, Delegate, Delegator } from '../redux/delegation/types'; +import { Delegate, Delegator, NewMandateRequest } from '../redux/delegation/types'; -export const mockCreateDelegation: CreateDelegationProps = { +export const mockCreateDelegation: NewMandateRequest = { delegate: { firstName: 'Davide', lastName: 'Legato', @@ -19,7 +19,7 @@ export const mockCreateDelegation: CreateDelegationProps = { dateto: '2022-04-16', }; -export const arrayOfDelegates: Array = [ +export const mandatesByDelegator: Array = [ { mandateId: '1', delegate: { @@ -64,7 +64,7 @@ export const arrayOfDelegates: Array = [ }, ]; -export const arrayOfDelegators: Array = [ +export const mandatesByDelegate: Array = [ { mandateId: '3', delegator: { diff --git a/packages/pn-personafisica-webapp/src/__test__/App.test.tsx b/packages/pn-personafisica-webapp/src/__test__/App.test.tsx index f64bc31f31..ac94d44e88 100644 --- a/packages/pn-personafisica-webapp/src/__test__/App.test.tsx +++ b/packages/pn-personafisica-webapp/src/__test__/App.test.tsx @@ -10,9 +10,8 @@ import { currentStatusDTO } from '../__mocks__/AppStatus.mock'; import { userResponse } from '../__mocks__/Auth.mock'; import { tosPrivacyConsentMock } from '../__mocks__/Consents.mock'; import { digitalAddresses } from '../__mocks__/Contacts.mock'; -import { arrayOfDelegators } from '../__mocks__/Delegations.mock'; +import { mandatesByDelegate } from '../__mocks__/Delegations.mock'; import { apiClient } from '../api/apiClients'; -import { DELEGATIONS_BY_DELEGATE } from '../api/delegations/delegations.routes'; import { RenderResult, act, @@ -109,7 +108,7 @@ describe('App', async () => { mock.onGet('/bff/v1/tos-privacy').reply(200, tosPrivacyConsentMock(true, true)); mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); mock.onGet('/bff/v1/addresses').reply(200, digitalAddresses); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, arrayOfDelegators); + mock.onGet('/bff/v1/mandate/delegate').reply(200, mandatesByDelegate); await act(async () => { result = render(, { preloadedState: reduxInitialState }); }); @@ -127,7 +126,7 @@ describe('App', async () => { mock.onGet('/bff/v1/tos-privacy').reply(200, tosPrivacyConsentMock(true, true)); mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); mock.onGet('/bff/v1/addresses').reply(200, digitalAddresses); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, arrayOfDelegators); + mock.onGet('/bff/v1/mandate/delegate').reply(200, mandatesByDelegate); await act(async () => { result = render(, { preloadedState: reduxInitialState }); }); @@ -161,7 +160,7 @@ describe('App', async () => { mock.onGet('/bff/v1/tos-privacy').reply(500); mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); mock.onGet('/bff/v1/addresses').reply(200, digitalAddresses); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, arrayOfDelegators); + mock.onGet('/bff/v1/mandate/delegate').reply(200, mandatesByDelegate); await act(async () => { result = render(, { preloadedState: reduxInitialState }); }); @@ -175,7 +174,7 @@ describe('App', async () => { mock.onGet('/bff/v1/tos-privacy').reply(200, tosPrivacyConsentMock(false, false)); mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); mock.onGet('/bff/v1/addresses').reply(200, digitalAddresses); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, arrayOfDelegators); + mock.onGet('/bff/v1/mandate/delegate').reply(200, mandatesByDelegate); await act(async () => { result = render(, { preloadedState: reduxInitialState }); }); @@ -191,7 +190,7 @@ describe('App', async () => { mock.onGet('/bff/v1/tos-privacy').reply(200, tosPrivacyConsentMock(false, false)); mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); mock.onGet('/bff/v1/addresses').reply(200, digitalAddresses); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, arrayOfDelegators); + mock.onGet('/bff/v1/mandate/delegate').reply(200, mandatesByDelegate); await act(async () => { render(, { preloadedState: reduxInitialState }); }); @@ -208,7 +207,7 @@ describe('App', async () => { mock.onGet('/bff/v1/tos-privacy').reply(200, tosPrivacyConsentMock(true, true)); mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); mock.onGet('/bff/v1/addresses').reply(200, digitalAddresses); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, arrayOfDelegators); + mock.onGet('/bff/v1/mandate/delegate').reply(200, mandatesByDelegate); await act(async () => { result = render(, { preloadedState: reduxInitialState }); }); @@ -223,7 +222,7 @@ describe('App', async () => { mock.onGet('/bff/v1/tos-privacy').reply(200, tosPrivacyConsentMock(true, true)); mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); mock.onGet('/bff/v1/addresses').reply(200, digitalAddresses); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, []); + mock.onGet('/bff/v1/mandate/delegate').reply(200, []); await act(async () => { result = render(, { preloadedState: reduxInitialState }); }); diff --git a/packages/pn-personafisica-webapp/src/api/delegations/Delegations.api.ts b/packages/pn-personafisica-webapp/src/api/delegations/Delegations.api.ts deleted file mode 100644 index e2b6f7b2bc..0000000000 --- a/packages/pn-personafisica-webapp/src/api/delegations/Delegations.api.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { AxiosResponse } from 'axios'; -import { apiClient } from '../apiClients'; -import { - AcceptDelegationResponse, - CreateDelegationProps, - CreateDelegationResponse, - Delegate, - Delegation, - Delegator, -} from '../../redux/delegation/types'; -import { - ACCEPT_DELEGATION, - CREATE_DELEGATION, - DELEGATIONS_BY_DELEGATE, - DELEGATIONS_BY_DELEGATOR, - REJECT_DELEGATION, - REVOKE_DELEGATION, -} from './delegations.routes'; - -function checkResponseStatus(response: AxiosResponse, id: string) { - if (response.status === 204) { - return { id }; - } - return { id: '-1' }; -} - -export const DelegationsApi = { - /** - * Get all the delegates for the authenticated user - * @returns {Promise>} - */ - getDelegates: (): Promise> => - apiClient - .get>(DELEGATIONS_BY_DELEGATOR()) - .then((response: AxiosResponse>) => - response.data.map((delegation) => ({ - mandateId: delegation.mandateId, - status: delegation.status, - visibilityIds: delegation.visibilityIds, - verificationCode: delegation.verificationCode, - datefrom: delegation.datefrom, - dateto: delegation.dateto, - delegate: 'delegate' in delegation ? delegation.delegate : null, - })) - ), - - /** - * Get all the delegators for the authenticated user - * @return {Promise>} - */ - getDelegators: (): Promise> => - apiClient - .get>(DELEGATIONS_BY_DELEGATE()) - .then((response: AxiosResponse>) => - response.data.map((delegation) => ({ - mandateId: delegation.mandateId, - status: delegation.status, - visibilityIds: delegation.visibilityIds, - verificationCode: delegation.verificationCode, - datefrom: delegation.datefrom, - dateto: delegation.dateto, - delegator: 'delegator' in delegation ? delegation.delegator : null, - })) - ), - - /** - * Removes a delegation that the user created - * @param id - * @return {Promise<{id: string}>} - */ - revokeDelegation: (id: string): Promise<{ id: string }> => - apiClient - .patch(REVOKE_DELEGATION(id)) - .then((response: AxiosResponse) => checkResponseStatus(response, id)), - - /** - * Removes a delegation created for the user - * @param {string} id - * @returns {Promise<{id: string}>} - */ - rejectDelegation: (id: string): Promise<{ id: string }> => - apiClient - .patch(REJECT_DELEGATION(id)) - .then((response: AxiosResponse) => checkResponseStatus(response, id)), - - /** - * Accepts a delegation created for the user - * @param {string} id - * @param data - * @return {Promise<{id: string}>} - */ - acceptDelegation: ( - id: string, - data: { verificationCode: string } - ): Promise => - apiClient - .patch(ACCEPT_DELEGATION(id), data) - .then((response: AxiosResponse) => { - if (response.status === 204) { - return { ...response.data, id }; - } - return { - id: '-1', - } as AcceptDelegationResponse; - }), - - /** - * Creates a new delegation - * @param data - * @return {Promise} - */ - createDelegation: (data: CreateDelegationProps): Promise => - apiClient - .post(CREATE_DELEGATION(), data) - .then((response: AxiosResponse) => response.data), -}; diff --git a/packages/pn-personafisica-webapp/src/api/delegations/__test__/Delegations.api.test.ts b/packages/pn-personafisica-webapp/src/api/delegations/__test__/Delegations.api.test.ts deleted file mode 100644 index 506662b386..0000000000 --- a/packages/pn-personafisica-webapp/src/api/delegations/__test__/Delegations.api.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -import MockAdapter from 'axios-mock-adapter'; - -import { mockAuthentication } from '../../../__mocks__/Auth.mock'; -import { - arrayOfDelegates, - arrayOfDelegators, - mockCreateDelegation, -} from '../../../__mocks__/Delegations.mock'; -import { Delegation } from '../../../redux/delegation/types'; -import { apiClient } from '../../apiClients'; -import { DelegationsApi } from '../Delegations.api'; -import { - ACCEPT_DELEGATION, - CREATE_DELEGATION, - DELEGATIONS_BY_DELEGATE, - DELEGATIONS_BY_DELEGATOR, - REJECT_DELEGATION, - REVOKE_DELEGATION, -} from '../delegations.routes'; - -let mock: MockAdapter; - -async function getDelegates(response: Array | null) { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, response); - const res = await DelegationsApi.getDelegates(); - return res; -} - -async function getDelegators(response: Array | null) { - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, response); - const res = await DelegationsApi.getDelegators(); - return res; -} - -describe('Delegations api tests', () => { - mockAuthentication(); - - beforeAll(() => { - mock = new MockAdapter(apiClient); - }); - - afterEach(() => { - mock.reset(); - }); - - afterAll(() => { - mock.restore(); - }); - - it('gets non empty delegates', async () => { - const res = await getDelegates(arrayOfDelegates); - expect(res).toStrictEqual(arrayOfDelegates); - }); - - it('gets empty delegates', async () => { - const res = await getDelegates([]); - expect(res).toHaveLength(0); - }); - - it('gets non empty delegators', async () => { - const res = await getDelegators(arrayOfDelegators); - expect(res).toStrictEqual(arrayOfDelegators); - }); - - it('gets empty delegators', async () => { - const res = await getDelegators([]); - expect(res).toHaveLength(0); - }); - - it('revokes a delegation', async () => { - mock.onPatch(REVOKE_DELEGATION('7')).reply(204); - const res = await DelegationsApi.revokeDelegation('7'); - expect(res).toStrictEqual({ id: '7' }); - }); - - it("doesn't revoke a delegation", async () => { - mock.onPatch(REVOKE_DELEGATION('10')).reply(200); - const res = await DelegationsApi.revokeDelegation('10'); - expect(res).toStrictEqual({ id: '-1' }); - }); - - it('rejects a delegation', async () => { - mock.onPatch(REJECT_DELEGATION('8')).reply(204); - const res = await DelegationsApi.rejectDelegation('8'); - expect(res).toStrictEqual({ id: '8' }); - }); - - it("doesn't reject a delegation", async () => { - mock.onPatch(REJECT_DELEGATION('10')).reply(200); - const res = await DelegationsApi.rejectDelegation('10'); - expect(res).toStrictEqual({ id: '-1' }); - }); - - it('accept a delegation', async () => { - mock.onPatch(ACCEPT_DELEGATION('9')).reply(204, {}); - const res = await DelegationsApi.acceptDelegation('9', { verificationCode: '12345' }); - expect(res).toStrictEqual({ id: '9' }); - }); - - it('creates a new delegation', async () => { - mock.onPost(CREATE_DELEGATION()).reply(200, mockCreateDelegation); - const res = await DelegationsApi.createDelegation(mockCreateDelegation); - expect(res).toStrictEqual(mockCreateDelegation); - }); -}); diff --git a/packages/pn-personafisica-webapp/src/api/delegations/__test__/delegations.routes.test.ts b/packages/pn-personafisica-webapp/src/api/delegations/__test__/delegations.routes.test.ts deleted file mode 100644 index b83d772b9f..0000000000 --- a/packages/pn-personafisica-webapp/src/api/delegations/__test__/delegations.routes.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { - ACCEPT_DELEGATION, - CREATE_DELEGATION, - DELEGATIONS_BY_DELEGATE, - DELEGATIONS_BY_DELEGATOR, - REJECT_DELEGATION, - REVOKE_DELEGATION, -} from '../delegations.routes'; - -describe('Delegations routes', () => { - it('should compile DELEGATIONS_BY_DELEGATOR', () => { - const route = DELEGATIONS_BY_DELEGATOR(); - expect(route).toEqual(`/mandate/api/v1/mandates-by-delegator`); - }); - - it('should compile DELEGATIONS_BY_DELEGATE', () => { - const route = DELEGATIONS_BY_DELEGATE(); - expect(route).toEqual(`/mandate/api/v1/mandates-by-delegate`); - }); - - it('should compile CREATE_DELEGATION', () => { - const route = CREATE_DELEGATION(); - expect(route).toEqual(`/mandate/api/v1/mandate`); - }); - - it('should compile REVOKE_DELEGATION', () => { - const route = REVOKE_DELEGATION('mocked-id'); - expect(route).toEqual(`/mandate/api/v1/mandate/mocked-id/revoke`); - }); - - it('should compile REJECT_DELEGATION', () => { - const route = REJECT_DELEGATION('mocked-id'); - expect(route).toEqual(`/mandate/api/v1/mandate/mocked-id/reject`); - }); - - it('should compile ACCEPT_DELEGATION', () => { - const route = ACCEPT_DELEGATION('mocked-id'); - expect(route).toEqual(`/mandate/api/v1/mandate/mocked-id/accept`); - }); -}); diff --git a/packages/pn-personafisica-webapp/src/api/delegations/delegations.routes.ts b/packages/pn-personafisica-webapp/src/api/delegations/delegations.routes.ts deleted file mode 100644 index 611c0703d5..0000000000 --- a/packages/pn-personafisica-webapp/src/api/delegations/delegations.routes.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { compileRoute } from '@pagopa-pn/pn-commons'; - -// Prefixes -const API_DELEGATIONS_PREFIX = 'mandate'; - -// Segments -const API_SEGMENT = 'api'; -const API_VERSION_SEGMENT = 'v1'; -const API_DELEGATIONS_MANDATES_BY_DELEGATOR = 'mandates-by-delegator'; -const API_DELEGATIONS_MANDATES_BY_DELEGATE = 'mandates-by-delegate'; -const API_DELEGATIONS_MANDATE = 'mandate'; -const API_DELEGATIONS_REVOKE = 'revoke'; -const API_DELEGATIONS_REJECT = 'reject'; -const API_DELEGATIONS_ACCEPT = 'accept'; - -// Parameters -const API_DELEGATIONS_ID_PARAMETER = 'id'; - -// Paths -const API_DELEGATIONS_BASE_PATH = `${API_SEGMENT}/${API_VERSION_SEGMENT}`; -const API_DELEGATIONS_MANDATES_BY_DELEGATOR_PATH = `${API_DELEGATIONS_BASE_PATH}/${API_DELEGATIONS_MANDATES_BY_DELEGATOR}`; -const API_DELEGATIONS_MANDATES_BY_DELEGATE_PATH = `${API_DELEGATIONS_BASE_PATH}/${API_DELEGATIONS_MANDATES_BY_DELEGATE}`; -const API_DELEGATIONS_MANDATE_BASE_PATH = `${API_SEGMENT}/${API_VERSION_SEGMENT}/${API_DELEGATIONS_MANDATE}`; -const API_DELEGATIONS_MANDATE_REVOKE_PATH = `${API_DELEGATIONS_MANDATE_BASE_PATH}/:${API_DELEGATIONS_ID_PARAMETER}/${API_DELEGATIONS_REVOKE}`; -const API_DELEGATIONS_MANDATE_REJECT_PATH = `${API_DELEGATIONS_MANDATE_BASE_PATH}/:${API_DELEGATIONS_ID_PARAMETER}/${API_DELEGATIONS_REJECT}`; -const API_DELEGATIONS_MANDATE_ACCEPT_PATH = `${API_DELEGATIONS_MANDATE_BASE_PATH}/:${API_DELEGATIONS_ID_PARAMETER}/${API_DELEGATIONS_ACCEPT}`; - -// APIs -export function DELEGATIONS_BY_DELEGATOR() { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATES_BY_DELEGATOR_PATH, - }); -} - -export function DELEGATIONS_BY_DELEGATE() { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATES_BY_DELEGATE_PATH, - }); -} - -export function CREATE_DELEGATION() { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATE_BASE_PATH, - }); -} - -export function REVOKE_DELEGATION(id: string) { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATE_REVOKE_PATH, - params: { - [API_DELEGATIONS_ID_PARAMETER]: id, - }, - }); -} - -export function REJECT_DELEGATION(id: string) { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATE_REJECT_PATH, - params: { - [API_DELEGATIONS_ID_PARAMETER]: id, - }, - }); -} - -export function ACCEPT_DELEGATION(id: string) { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATE_ACCEPT_PATH, - params: { - [API_DELEGATIONS_ID_PARAMETER]: id, - }, - }); -} diff --git a/packages/pn-personafisica-webapp/src/components/Deleghe/Delegates.tsx b/packages/pn-personafisica-webapp/src/components/Deleghe/Delegates.tsx index 4f72f8ede8..a23b5d81c4 100644 --- a/packages/pn-personafisica-webapp/src/components/Deleghe/Delegates.tsx +++ b/packages/pn-personafisica-webapp/src/components/Deleghe/Delegates.tsx @@ -22,7 +22,7 @@ import { import { DelegationColumnData, DelegationData } from '../../models/Deleghe'; import { PFEventsType } from '../../models/PFEventsType'; import * as routes from '../../navigation/routes.const'; -import { DELEGATION_ACTIONS, getDelegates } from '../../redux/delegation/actions'; +import { DELEGATION_ACTIONS, getMandatesByDelegator } from '../../redux/delegation/actions'; import { setDelegatesSorting } from '../../redux/delegation/reducers'; import { useAppDispatch, useAppSelector } from '../../redux/hooks'; import { RootState } from '../../redux/store'; @@ -140,8 +140,8 @@ const Delegates = () => { dispatch(getDelegates())} + apiId={DELEGATION_ACTIONS.GET_MANDATES_BY_DELEGATOR} + reloadAction={() => dispatch(getMandatesByDelegator())} > {rows.length > 0 ? ( diff --git a/packages/pn-personafisica-webapp/src/components/Deleghe/Delegators.tsx b/packages/pn-personafisica-webapp/src/components/Deleghe/Delegators.tsx index 33c005cdda..80ae1763b2 100644 --- a/packages/pn-personafisica-webapp/src/components/Deleghe/Delegators.tsx +++ b/packages/pn-personafisica-webapp/src/components/Deleghe/Delegators.tsx @@ -17,7 +17,7 @@ import { } from '@pagopa-pn/pn-commons'; import { DelegationColumnData, DelegationData } from '../../models/Deleghe'; -import { DELEGATION_ACTIONS, getDelegators } from '../../redux/delegation/actions'; +import { DELEGATION_ACTIONS, getMandatesByDelegate } from '../../redux/delegation/actions'; import { setDelegatorsSorting } from '../../redux/delegation/reducers'; import { useAppDispatch, useAppSelector } from '../../redux/hooks'; import { RootState } from '../../redux/store'; @@ -81,8 +81,8 @@ const Delegators = () => { {t('deleghe.delegatorsTitle')} dispatch(getDelegators())} + apiId={DELEGATION_ACTIONS.GET_MANDATES_BY_DELEGATE} + reloadAction={() => dispatch(getMandatesByDelegate())} mainText={t('deleghe.delegatorsApiErrorMessage')} > {rows.length > 0 ? ( diff --git a/packages/pn-personafisica-webapp/src/components/Deleghe/MobileDelegates.tsx b/packages/pn-personafisica-webapp/src/components/Deleghe/MobileDelegates.tsx index ad274b28a1..1afb6f42e1 100644 --- a/packages/pn-personafisica-webapp/src/components/Deleghe/MobileDelegates.tsx +++ b/packages/pn-personafisica-webapp/src/components/Deleghe/MobileDelegates.tsx @@ -21,7 +21,7 @@ import { import { DelegationColumnData, DelegationData } from '../../models/Deleghe'; import { PFEventsType } from '../../models/PFEventsType'; import * as routes from '../../navigation/routes.const'; -import { DELEGATION_ACTIONS, getDelegates } from '../../redux/delegation/actions'; +import { DELEGATION_ACTIONS, getMandatesByDelegator } from '../../redux/delegation/actions'; import { useAppDispatch, useAppSelector } from '../../redux/hooks'; import { RootState } from '../../redux/store'; import PFEventStrategyFactory from '../../utility/MixpanelUtils/PFEventStrategyFactory'; @@ -120,8 +120,8 @@ const MobileDelegates = () => { dispatch(getDelegates())} + apiId={DELEGATION_ACTIONS.GET_MANDATES_BY_DELEGATOR} + reloadAction={() => dispatch(getMandatesByDelegator())} > {cardData.length ? ( diff --git a/packages/pn-personafisica-webapp/src/components/Deleghe/MobileDelegators.tsx b/packages/pn-personafisica-webapp/src/components/Deleghe/MobileDelegators.tsx index 8f2d5ee562..a8f76b40b8 100644 --- a/packages/pn-personafisica-webapp/src/components/Deleghe/MobileDelegators.tsx +++ b/packages/pn-personafisica-webapp/src/components/Deleghe/MobileDelegators.tsx @@ -16,7 +16,7 @@ import { } from '@pagopa-pn/pn-commons'; import { DelegationColumnData, DelegationData } from '../../models/Deleghe'; -import { DELEGATION_ACTIONS, getDelegators } from '../../redux/delegation/actions'; +import { DELEGATION_ACTIONS, getMandatesByDelegate } from '../../redux/delegation/actions'; import { useAppDispatch, useAppSelector } from '../../redux/hooks'; import { RootState } from '../../redux/store'; import delegationToItem from '../../utility/delegation.utility'; @@ -58,8 +58,8 @@ const MobileDelegators = () => { {t('deleghe.delegatorsTitle')} dispatch(getDelegators())} + apiId={DELEGATION_ACTIONS.GET_MANDATES_BY_DELEGATE} + reloadAction={() => dispatch(getMandatesByDelegate())} > {delegators.length > 0 ? ( diff --git a/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/Delegates.test.tsx b/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/Delegates.test.tsx index d9d3ae7c08..8b93e039a0 100644 --- a/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/Delegates.test.tsx +++ b/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/Delegates.test.tsx @@ -1,7 +1,7 @@ import { ReactNode } from 'react'; import { vi } from 'vitest'; -import { arrayOfDelegates } from '../../../__mocks__/Delegations.mock'; +import { mandatesByDelegator } from '../../../__mocks__/Delegations.mock'; import { fireEvent, render, testStore, waitFor, within } from '../../../__test__/test-utils'; import * as routes from '../../../navigation/routes.const'; import { Delegate } from '../../../redux/delegation/types'; @@ -59,14 +59,14 @@ describe('Delegates Component', async () => { it('renders the delegates', () => { const { getByTestId, getAllByTestId } = render(, { - preloadedState: { delegationsState: { delegations: { delegates: arrayOfDelegates } } }, + preloadedState: { delegationsState: { delegations: { delegates: mandatesByDelegator } } }, }); const delegatesTable = getByTestId('delegatesTable'); expect(delegatesTable).toBeInTheDocument(); const delegatesRows = getAllByTestId('delegatesTable.body.row'); - expect(delegatesRows).toHaveLength(arrayOfDelegates.length); + expect(delegatesRows).toHaveLength(mandatesByDelegator.length); delegatesRows.forEach((row, index) => { - expect(row).toHaveTextContent(arrayOfDelegates[index].delegate?.displayName!); + expect(row).toHaveTextContent(mandatesByDelegator[index].delegate?.displayName!); }); }); @@ -74,7 +74,7 @@ describe('Delegates Component', async () => { const { getByTestId, getAllByTestId } = render(, { preloadedState: { delegationsState: { - delegations: { delegates: arrayOfDelegates }, + delegations: { delegates: mandatesByDelegator }, sortDelegates: { orderBy: '', order: 'asc', @@ -95,7 +95,7 @@ describe('Delegates Component', async () => { }); }); let delegatesRows = getAllByTestId('delegatesTable.body.row'); - let sortedDelegates = sortDelegations('asc', 'name', arrayOfDelegates) as Array; + let sortedDelegates = sortDelegations('asc', 'name', mandatesByDelegator) as Array; delegatesRows.forEach((row, index) => { expect(row).toHaveTextContent(sortedDelegates[index].delegate?.displayName!); }); @@ -111,7 +111,7 @@ describe('Delegates Component', async () => { }); }); delegatesRows = getAllByTestId('delegatesTable.body.row'); - sortedDelegates = sortDelegations('desc', 'name', arrayOfDelegates) as Array; + sortedDelegates = sortDelegations('desc', 'name', mandatesByDelegator) as Array; delegatesRows.forEach((row, index) => { expect(row).toHaveTextContent(sortedDelegates[index].delegate?.displayName!); }); @@ -129,7 +129,7 @@ describe('Delegates Component', async () => { }); }); delegatesRows = getAllByTestId('delegatesTable.body.row'); - sortedDelegates = sortDelegations('asc', 'endDate', arrayOfDelegates) as Array; + sortedDelegates = sortDelegations('asc', 'endDate', mandatesByDelegator) as Array; delegatesRows.forEach((row, index) => { expect(row).toHaveTextContent(sortedDelegates[index].delegate?.displayName!); }); @@ -139,7 +139,7 @@ describe('Delegates Component', async () => { const { getByTestId, getAllByTestId } = render(, { preloadedState: { delegationsState: { - delegations: { delegates: arrayOfDelegates }, + delegations: { delegates: mandatesByDelegator }, }, }, }); @@ -158,7 +158,7 @@ describe('Delegates Component', async () => { expect(dialog).toHaveTextContent('deleghe.close'); expect(dialog).toHaveTextContent('deleghe.verification_code'); const codeInputs = dialog?.querySelectorAll('input'); - const codes = arrayOfDelegates[0].verificationCode.split(''); + const codes = mandatesByDelegator[0].verificationCode.split(''); codeInputs?.forEach((input, index) => { expect(input).toHaveValue(codes[index]); }); diff --git a/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/DelegationDataSwitch.test.tsx b/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/DelegationDataSwitch.test.tsx index e849d5e265..f3552ef401 100644 --- a/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/DelegationDataSwitch.test.tsx +++ b/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/DelegationDataSwitch.test.tsx @@ -1,6 +1,6 @@ import { vi } from 'vitest'; -import { arrayOfDelegators } from '../../../__mocks__/Delegations.mock'; +import { mandatesByDelegate } from '../../../__mocks__/Delegations.mock'; import { render } from '../../../__test__/test-utils'; import delegationToItem from '../../../utility/delegation.utility'; import { DelegationStatus, getDelegationStatusKeyAndColor } from '../../../utility/status.utility'; @@ -14,7 +14,7 @@ vi.mock('react-i18next', () => ({ })); const data = { - ...delegationToItem(arrayOfDelegators)[0], + ...delegationToItem(mandatesByDelegate)[0], }; describe('DowntimeLogDataSwitch Component', () => { diff --git a/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/Delegators.test.tsx b/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/Delegators.test.tsx index caf2fdc709..a12df84558 100644 --- a/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/Delegators.test.tsx +++ b/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/Delegators.test.tsx @@ -1,6 +1,6 @@ import { vi } from 'vitest'; -import { arrayOfDelegators } from '../../../__mocks__/Delegations.mock'; +import { mandatesByDelegate } from '../../../__mocks__/Delegations.mock'; import { fireEvent, render, testStore, waitFor, within } from '../../../__test__/test-utils'; import { Delegator } from '../../../redux/delegation/types'; import { sortDelegations } from '../../../utility/delegation.utility'; @@ -25,14 +25,14 @@ describe('Delegators Component', async () => { it('renders the delegators', () => { const { getByTestId, getAllByTestId } = render(, { - preloadedState: { delegationsState: { delegations: { delegators: arrayOfDelegators } } }, + preloadedState: { delegationsState: { delegations: { delegators: mandatesByDelegate } } }, }); const delegatorsTable = getByTestId('delegatorsTable'); expect(delegatorsTable).toBeInTheDocument(); const delegatorsRows = getAllByTestId('delegatorsTable.body.row'); - expect(delegatorsRows).toHaveLength(arrayOfDelegators.length); + expect(delegatorsRows).toHaveLength(mandatesByDelegate.length); delegatorsRows.forEach((row, index) => { - expect(row).toHaveTextContent(arrayOfDelegators[index].delegator?.displayName!); + expect(row).toHaveTextContent(mandatesByDelegate[index].delegator?.displayName!); }); }); @@ -40,7 +40,7 @@ describe('Delegators Component', async () => { const { getByTestId, getAllByTestId } = render(, { preloadedState: { delegationsState: { - delegations: { delegators: arrayOfDelegators }, + delegations: { delegators: mandatesByDelegate }, sortDelegators: { orderBy: '', order: 'asc', @@ -61,7 +61,7 @@ describe('Delegators Component', async () => { }); }); let delegatorsRows = getAllByTestId('delegatorsTable.body.row'); - let sortedDelegators = sortDelegations('asc', 'name', arrayOfDelegators) as Array; + let sortedDelegators = sortDelegations('asc', 'name', mandatesByDelegate) as Array; delegatorsRows.forEach((row, index) => { expect(row).toHaveTextContent(sortedDelegators[index].delegator?.displayName!); }); @@ -77,7 +77,7 @@ describe('Delegators Component', async () => { }); }); delegatorsRows = getAllByTestId('delegatorsTable.body.row'); - sortedDelegators = sortDelegations('desc', 'name', arrayOfDelegators) as Array; + sortedDelegators = sortDelegations('desc', 'name', mandatesByDelegate) as Array; delegatorsRows.forEach((row, index) => { expect(row).toHaveTextContent(sortedDelegators[index].delegator?.displayName!); }); @@ -95,7 +95,7 @@ describe('Delegators Component', async () => { }); }); delegatorsRows = getAllByTestId('delegatorsTable.body.row'); - sortedDelegators = sortDelegations('asc', 'endDate', arrayOfDelegators) as Array; + sortedDelegators = sortDelegations('asc', 'endDate', mandatesByDelegate) as Array; delegatorsRows.forEach((row, index) => { expect(row).toHaveTextContent(sortedDelegators[index].delegator?.displayName!); }); diff --git a/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/MobileDelegates.test.tsx b/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/MobileDelegates.test.tsx index ece6fd638f..e00ddec433 100644 --- a/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/MobileDelegates.test.tsx +++ b/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/MobileDelegates.test.tsx @@ -1,7 +1,7 @@ import { ReactNode } from 'react'; import { vi } from 'vitest'; -import { arrayOfDelegates } from '../../../__mocks__/Delegations.mock'; +import { mandatesByDelegator } from '../../../__mocks__/Delegations.mock'; import { fireEvent, render, waitFor, within } from '../../../__test__/test-utils'; import * as routes from '../../../navigation/routes.const'; import MobileDelegates from '../MobileDelegates'; @@ -57,12 +57,12 @@ describe('MobileDelegates Component', () => { it('renders the delegates', () => { const { getAllByTestId } = render(, { - preloadedState: { delegationsState: { delegations: { delegates: arrayOfDelegates } } }, + preloadedState: { delegationsState: { delegations: { delegates: mandatesByDelegator } } }, }); const itemCards = getAllByTestId('mobileDelegatesCards'); - expect(itemCards).toHaveLength(arrayOfDelegates.length); + expect(itemCards).toHaveLength(mandatesByDelegator.length); itemCards.forEach((card, index) => { - expect(card).toHaveTextContent(arrayOfDelegates[index].delegate?.displayName!); + expect(card).toHaveTextContent(mandatesByDelegator[index].delegate?.displayName!); }); }); @@ -76,7 +76,7 @@ describe('MobileDelegates Component', () => { const { getByTestId, getAllByTestId } = render(, { preloadedState: { delegationsState: { - delegations: { delegates: arrayOfDelegates }, + delegations: { delegates: mandatesByDelegator }, }, }, }); @@ -95,7 +95,7 @@ describe('MobileDelegates Component', () => { expect(dialog).toHaveTextContent('deleghe.close'); expect(dialog).toHaveTextContent('deleghe.verification_code'); const codeInputs = dialog?.querySelectorAll('input'); - const codes = arrayOfDelegates[0].verificationCode.split(''); + const codes = mandatesByDelegator[0].verificationCode.split(''); codeInputs?.forEach((input, index) => { expect(input).toHaveValue(codes[index]); }); diff --git a/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/MobileDelegators.test.tsx b/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/MobileDelegators.test.tsx index 0d83abad8d..6fe8689545 100644 --- a/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/MobileDelegators.test.tsx +++ b/packages/pn-personafisica-webapp/src/components/Deleghe/__test__/MobileDelegators.test.tsx @@ -1,6 +1,6 @@ import { vi } from 'vitest'; -import { arrayOfDelegators } from '../../../__mocks__/Delegations.mock'; +import { mandatesByDelegate } from '../../../__mocks__/Delegations.mock'; import { render } from '../../../__test__/test-utils'; import MobileDelegators from '../MobileDelegators'; @@ -23,12 +23,12 @@ describe('MobileDelegators Component', () => { it('renders the delegators', () => { const { getAllByTestId } = render(, { - preloadedState: { delegationsState: { delegations: { delegators: arrayOfDelegators } } }, + preloadedState: { delegationsState: { delegations: { delegators: mandatesByDelegate } } }, }); const itemCards = getAllByTestId('mobileDelegatorsCards'); - expect(itemCards).toHaveLength(arrayOfDelegators.length); + expect(itemCards).toHaveLength(mandatesByDelegate.length); itemCards.forEach((card, index) => { - expect(card).toHaveTextContent(arrayOfDelegators[index].delegator?.displayName!); + expect(card).toHaveTextContent(mandatesByDelegate[index].delegator?.displayName!); }); }); diff --git a/packages/pn-personafisica-webapp/src/components/Notifications/__test__/DesktopNotifications.test.tsx b/packages/pn-personafisica-webapp/src/components/Notifications/__test__/DesktopNotifications.test.tsx index 2ab00195b9..d4765e0393 100644 --- a/packages/pn-personafisica-webapp/src/components/Notifications/__test__/DesktopNotifications.test.tsx +++ b/packages/pn-personafisica-webapp/src/components/Notifications/__test__/DesktopNotifications.test.tsx @@ -3,7 +3,7 @@ import { vi } from 'vitest'; import { formatToTimezoneString, tenYearsAgo, today } from '@pagopa-pn/pn-commons'; -import { arrayOfDelegators } from '../../../__mocks__/Delegations.mock'; +import { mandatesByDelegate } from '../../../__mocks__/Delegations.mock'; import { notificationsToFe } from '../../../__mocks__/Notifications.mock'; import { RenderResult, @@ -66,7 +66,7 @@ describe('DesktopNotifications Component', () => { // render component await act(async () => { result = render( - + ); }); const filters = result.queryByTestId('filter-form'); diff --git a/packages/pn-personafisica-webapp/src/generated-client/mandate/.openapi-generator-ignore b/packages/pn-personafisica-webapp/src/generated-client/mandate/.openapi-generator-ignore new file mode 100644 index 0000000000..39b092c3ec --- /dev/null +++ b/packages/pn-personafisica-webapp/src/generated-client/mandate/.openapi-generator-ignore @@ -0,0 +1,28 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md + +# Prevent generator from creating these files: +git_push.sh +.gitignore +.npmignore \ No newline at end of file diff --git a/packages/pn-personafisica-webapp/src/generated-client/mandate/.openapi-generator/FILES b/packages/pn-personafisica-webapp/src/generated-client/mandate/.openapi-generator/FILES new file mode 100644 index 0000000000..a80cd4f07b --- /dev/null +++ b/packages/pn-personafisica-webapp/src/generated-client/mandate/.openapi-generator/FILES @@ -0,0 +1,8 @@ +.gitignore +.npmignore +api.ts +base.ts +common.ts +configuration.ts +git_push.sh +index.ts diff --git a/packages/pn-personafisica-webapp/src/generated-client/mandate/.openapi-generator/VERSION b/packages/pn-personafisica-webapp/src/generated-client/mandate/.openapi-generator/VERSION new file mode 100644 index 0000000000..ba7f754d0c --- /dev/null +++ b/packages/pn-personafisica-webapp/src/generated-client/mandate/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.4.0 diff --git a/packages/pn-personafisica-webapp/src/generated-client/mandate/api.ts b/packages/pn-personafisica-webapp/src/generated-client/mandate/api.ts new file mode 100644 index 0000000000..4a7830de89 --- /dev/null +++ b/packages/pn-personafisica-webapp/src/generated-client/mandate/api.ts @@ -0,0 +1,1269 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * PN BFF BE Microservice - Deleghe + * Documentation APIs v1.0 + * + * The version of the OpenAPI document: 1.0.0 + * Contact: pn@pagopa.it + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import type { Configuration } from './configuration'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; +import globalAxios from 'axios'; +// Some imports not used depending on template conditions +// @ts-ignore +import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; +import type { RequestArgs } from './base'; +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; + +/** + * + * @export + * @interface AcceptRequestDto + */ +export interface AcceptRequestDto { + /** + * + * @type {string} + * @memberof AcceptRequestDto + */ + 'verificationCode'?: string; + /** + * + * @type {Array} + * @memberof AcceptRequestDto + */ + 'groups'?: Array; +} +/** + * + * @export + * @interface BffAcceptRequest + */ +export interface BffAcceptRequest { + /** + * + * @type {string} + * @memberof BffAcceptRequest + */ + 'verificationCode'?: string; + /** + * + * @type {Array} + * @memberof BffAcceptRequest + */ + 'groups'?: Array; +} +/** + * + * @export + * @interface BffMandate + */ +export interface BffMandate { + /** + * Available always, not required on mandate creation. + * @type {string} + * @memberof BffMandate + */ + 'mandateId'?: string | null; + /** + * + * @type {UserDto} + * @memberof BffMandate + */ + 'delegator'?: UserDto | null; + /** + * + * @type {UserDto} + * @memberof BffMandate + */ + 'delegate'?: UserDto | null; + /** + * Available always, not required on mandate creation. + * @type {string} + * @memberof BffMandate + */ + 'status'?: BffMandateStatusEnum | null; + /** + * Available always, not required on mandate creation. + * @type {Array} + * @memberof BffMandate + */ + 'visibilityIds'?: Array | null; + /** + * Available only for request where requesting user is the delegator + * @type {string} + * @memberof BffMandate + */ + 'verificationCode'?: string | null; + /** + * ISO 8601 format + * @type {string} + * @memberof BffMandate + */ + 'datefrom'?: string; + /** + * ISO 8601 format + * @type {string} + * @memberof BffMandate + */ + 'dateto'?: string; + /** + * + * @type {Array} + * @memberof BffMandate + */ + 'groups'?: Array; +} + +export const BffMandateStatusEnum = { + Pending: 'pending', + Active: 'active', + Revoked: 'revoked', + Rejected: 'rejected', + Expired: 'expired' +} as const; + +export type BffMandateStatusEnum = typeof BffMandateStatusEnum[keyof typeof BffMandateStatusEnum]; + +/** + * + * @export + * @interface BffMandatesCount + */ +export interface BffMandatesCount { + /** + * + * @type {number} + * @memberof BffMandatesCount + */ + 'value'?: number; +} +/** + * + * @export + * @interface BffNewMandateRequest + */ +export interface BffNewMandateRequest { + /** + * + * @type {UserDto} + * @memberof BffNewMandateRequest + */ + 'delegate': UserDto | null; + /** + * Available always, not required on mandate creation. + * @type {Array} + * @memberof BffNewMandateRequest + */ + 'visibilityIds'?: Array | null; + /** + * Available only for request where requesting user is the delegator + * @type {string} + * @memberof BffNewMandateRequest + */ + 'verificationCode': string | null; + /** + * ISO 8601 format + * @type {string} + * @memberof BffNewMandateRequest + */ + 'dateto': string; + /** + * + * @type {Array} + * @memberof BffNewMandateRequest + */ + 'groups'?: Array; +} +/** + * + * @export + * @interface BffSearchMandateRequest + */ +export interface BffSearchMandateRequest { + /** + * + * @type {string} + * @memberof BffSearchMandateRequest + */ + 'taxId'?: string; + /** + * + * @type {Array} + * @memberof BffSearchMandateRequest + */ + 'groups'?: Array; + /** + * + * @type {Array} + * @memberof BffSearchMandateRequest + */ + 'status'?: Array; +} +/** + * + * @export + * @interface BffSearchMandateResponse + */ +export interface BffSearchMandateResponse { + /** + * + * @type {Array} + * @memberof BffSearchMandateResponse + */ + 'resultsPage'?: Array; + /** + * Indica se sono presenti ulteriori pagine di risultati + * @type {boolean} + * @memberof BffSearchMandateResponse + */ + 'moreResult'?: boolean; + /** + * Elenco, non esaustivo, delle chiavi da usare per richiedere le pagine di risultati successive a quella corrente.
Valorizzato solo se il campo __moreResult__ ha valore __true__. + * @type {Array} + * @memberof BffSearchMandateResponse + */ + 'nextPagesKey'?: Array; +} +/** + * + * @export + * @interface BffUpdateRequest + */ +export interface BffUpdateRequest { + /** + * + * @type {Array} + * @memberof BffUpdateRequest + */ + 'groups'?: Array; +} +/** + * + * @export + * @interface GroupDto + */ +export interface GroupDto { + /** + * + * @type {string} + * @memberof GroupDto + */ + 'id'?: string; + /** + * + * @type {string} + * @memberof GroupDto + */ + 'name'?: string; +} +/** + * + * @export + * @interface MandateCountsDto + */ +export interface MandateCountsDto { + /** + * + * @type {number} + * @memberof MandateCountsDto + */ + 'value'?: number; +} +/** + * + * @export + * @interface MandateDto + */ +export interface MandateDto { + /** + * Available always, not required on mandate creation. + * @type {string} + * @memberof MandateDto + */ + 'mandateId'?: string | null; + /** + * + * @type {UserDto} + * @memberof MandateDto + */ + 'delegator'?: UserDto | null; + /** + * + * @type {UserDto} + * @memberof MandateDto + */ + 'delegate'?: UserDto | null; + /** + * Available always, not required on mandate creation. + * @type {string} + * @memberof MandateDto + */ + 'status'?: MandateDtoStatusEnum | null; + /** + * Available always, not required on mandate creation. + * @type {Array} + * @memberof MandateDto + */ + 'visibilityIds'?: Array | null; + /** + * Available only for request where requesting user is the delegator + * @type {string} + * @memberof MandateDto + */ + 'verificationCode'?: string | null; + /** + * ISO 8601 format + * @type {string} + * @memberof MandateDto + */ + 'datefrom'?: string; + /** + * ISO 8601 format + * @type {string} + * @memberof MandateDto + */ + 'dateto'?: string; + /** + * + * @type {Array} + * @memberof MandateDto + */ + 'groups'?: Array; +} + +export const MandateDtoStatusEnum = { + Pending: 'pending', + Active: 'active', + Revoked: 'revoked', + Rejected: 'rejected', + Expired: 'expired' +} as const; + +export type MandateDtoStatusEnum = typeof MandateDtoStatusEnum[keyof typeof MandateDtoStatusEnum]; + +/** + * Available always, not required on mandate creation. + * @export + * @interface OrganizationIdDto + */ +export interface OrganizationIdDto { + /** + * + * @type {string} + * @memberof OrganizationIdDto + */ + 'name'?: string; + /** + * + * @type {string} + * @memberof OrganizationIdDto + */ + 'uniqueIdentifier'?: string; +} +/** + * + * @export + * @interface Problem + */ +export interface Problem { + /** + * URI reference of type definition + * @type {string} + * @memberof Problem + */ + 'type'?: string; + /** + * The HTTP status code generated by the origin server for this occurrence of the problem. + * @type {number} + * @memberof Problem + */ + 'status': number; + /** + * A short, summary of the problem type. Written in english and readable + * @type {string} + * @memberof Problem + */ + 'title'?: string; + /** + * A human readable explanation of the problem. + * @type {string} + * @memberof Problem + */ + 'detail'?: string; + /** + * Internal support identifier associated to error + * @type {string} + * @memberof Problem + */ + 'traceId'?: string; + /** + * date and time referred to UTC + * @type {string} + * @memberof Problem + */ + 'timestamp'?: string; + /** + * + * @type {Array} + * @memberof Problem + */ + 'errors': Array; +} +/** + * + * @export + * @interface ProblemError + */ +export interface ProblemError { + /** + * Internal code of the error, in human-readable format + * @type {string} + * @memberof ProblemError + */ + 'code': string; + /** + * Parameter or request body field name for validation error + * @type {string} + * @memberof ProblemError + */ + 'element'?: string; + /** + * A human readable explanation specific to this occurrence of the problem. + * @type {string} + * @memberof ProblemError + */ + 'detail'?: string; +} +/** + * + * @export + * @interface SearchMandateRequestDto + */ +export interface SearchMandateRequestDto { + /** + * + * @type {string} + * @memberof SearchMandateRequestDto + */ + 'taxId'?: string; + /** + * + * @type {Array} + * @memberof SearchMandateRequestDto + */ + 'groups'?: Array; + /** + * + * @type {Array} + * @memberof SearchMandateRequestDto + */ + 'status'?: Array; +} +/** + * + * @export + * @interface SearchMandateResponseDto + */ +export interface SearchMandateResponseDto { + /** + * + * @type {Array} + * @memberof SearchMandateResponseDto + */ + 'resultsPage'?: Array; + /** + * Indica se sono presenti ulteriori pagine di risultati + * @type {boolean} + * @memberof SearchMandateResponseDto + */ + 'moreResult'?: boolean; + /** + * Elenco, non esaustivo, delle chiavi da usare per richiedere le pagine di risultati successive a quella corrente.
Valorizzato solo se il campo __moreResult__ ha valore __true__. + * @type {Array} + * @memberof SearchMandateResponseDto + */ + 'nextPagesKey'?: Array; +} +/** + * + * @export + * @interface UpdateRequestDto + */ +export interface UpdateRequestDto { + /** + * + * @type {Array} + * @memberof UpdateRequestDto + */ + 'groups'?: Array; +} +/** + * Available only for request where requesting user is the delegator + * @export + * @interface UserDto + */ +export interface UserDto { + /** + * + * @type {string} + * @memberof UserDto + */ + 'displayName'?: string; + /** + * + * @type {string} + * @memberof UserDto + */ + 'firstName'?: string; + /** + * + * @type {string} + * @memberof UserDto + */ + 'lastName'?: string; + /** + * + * @type {string} + * @memberof UserDto + */ + 'companyName'?: string; + /** + * + * @type {string} + * @memberof UserDto + */ + 'fiscalCode'?: string; + /** + * + * @type {boolean} + * @memberof UserDto + */ + 'person'?: boolean; +} + +/** + * MandateApi - axios parameter creator + * @export + */ +export const MandateApiAxiosParamCreator = function (configuration?: Configuration) { + return { + /** + * + * @summary Accept a mandate + * @param {string} mandateId + * @param {BffAcceptRequest} bffAcceptRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + acceptMandateV1: async (mandateId: string, bffAcceptRequest: BffAcceptRequest, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'mandateId' is not null or undefined + assertParamExists('acceptMandateV1', 'mandateId', mandateId) + // verify required parameter 'bffAcceptRequest' is not null or undefined + assertParamExists('acceptMandateV1', 'bffAcceptRequest', bffAcceptRequest) + const localVarPath = `/bff/v1/mandate/{mandateId}/accept` + .replace(`{${"mandateId"}}`, encodeURIComponent(String(mandateId))); + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(bffAcceptRequest, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Ritorna il numero totale di deleghe in base al filtro stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {CountMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + countMandatesByDelegateV1: async (status?: CountMandatesByDelegateV1StatusEnum, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/bff/v1/mandate/delegate/count`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (status !== undefined) { + localVarQueryParameter['status'] = status; + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Create a new mandate, returns the just created mandate if successful + * @param {BffNewMandateRequest} bffNewMandateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createMandateV1: async (bffNewMandateRequest: BffNewMandateRequest, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'bffNewMandateRequest' is not null or undefined + assertParamExists('createMandateV1', 'bffNewMandateRequest', bffNewMandateRequest) + const localVarPath = `/bff/v1/mandate`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(bffNewMandateRequest, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Ritorna la lista delle deleghe a carico in base al filtro per stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {GetMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getMandatesByDelegateV1: async (status?: GetMandatesByDelegateV1StatusEnum, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/bff/v1/mandate/delegate`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (status !== undefined) { + localVarQueryParameter['status'] = status; + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Ritorna tutte le deleghe create + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getMandatesByDelegatorV1: async (options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/bff/v1/mandate/delegator`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Reject a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + rejectMandateV1: async (mandateId: string, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'mandateId' is not null or undefined + assertParamExists('rejectMandateV1', 'mandateId', mandateId) + const localVarPath = `/bff/v1/mandate/{mandateId}/reject` + .replace(`{${"mandateId"}}`, encodeURIComponent(String(mandateId))); + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Revoke a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + revokeMandateV1: async (mandateId: string, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'mandateId' is not null or undefined + assertParamExists('revokeMandateV1', 'mandateId', mandateId) + const localVarPath = `/bff/v1/mandate/{mandateId}/revoke` + .replace(`{${"mandateId"}}`, encodeURIComponent(String(mandateId))); + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Ritorna la lista delle deleghe a carico in base ai filtri per stato, gruppo/i e delegante (taxId) + * @param {number} size + * @param {BffSearchMandateRequest} bffSearchMandateRequest + * @param {string} [nextPageKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + searchMandatesByDelegateV1: async (size: number, bffSearchMandateRequest: BffSearchMandateRequest, nextPageKey?: string, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'size' is not null or undefined + assertParamExists('searchMandatesByDelegateV1', 'size', size) + // verify required parameter 'bffSearchMandateRequest' is not null or undefined + assertParamExists('searchMandatesByDelegateV1', 'bffSearchMandateRequest', bffSearchMandateRequest) + const localVarPath = `/bff/v1/mandate/delegate`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (size !== undefined) { + localVarQueryParameter['size'] = size; + } + + if (nextPageKey !== undefined) { + localVarQueryParameter['nextPageKey'] = nextPageKey; + } + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(bffSearchMandateRequest, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Update a mandate + * @param {string} mandateId + * @param {BffUpdateRequest} bffUpdateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updateMandateV1: async (mandateId: string, bffUpdateRequest: BffUpdateRequest, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'mandateId' is not null or undefined + assertParamExists('updateMandateV1', 'mandateId', mandateId) + // verify required parameter 'bffUpdateRequest' is not null or undefined + assertParamExists('updateMandateV1', 'bffUpdateRequest', bffUpdateRequest) + const localVarPath = `/bff/v1/mandate/{mandateId}/update` + .replace(`{${"mandateId"}}`, encodeURIComponent(String(mandateId))); + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(bffUpdateRequest, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * MandateApi - functional programming interface + * @export + */ +export const MandateApiFp = function(configuration?: Configuration) { + const localVarAxiosParamCreator = MandateApiAxiosParamCreator(configuration) + return { + /** + * + * @summary Accept a mandate + * @param {string} mandateId + * @param {BffAcceptRequest} bffAcceptRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async acceptMandateV1(mandateId: string, bffAcceptRequest: BffAcceptRequest, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.acceptMandateV1(mandateId, bffAcceptRequest, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.acceptMandateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Ritorna il numero totale di deleghe in base al filtro stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {CountMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async countMandatesByDelegateV1(status?: CountMandatesByDelegateV1StatusEnum, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.countMandatesByDelegateV1(status, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.countMandatesByDelegateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Create a new mandate, returns the just created mandate if successful + * @param {BffNewMandateRequest} bffNewMandateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async createMandateV1(bffNewMandateRequest: BffNewMandateRequest, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.createMandateV1(bffNewMandateRequest, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.createMandateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Ritorna la lista delle deleghe a carico in base al filtro per stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {GetMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async getMandatesByDelegateV1(status?: GetMandatesByDelegateV1StatusEnum, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + const localVarAxiosArgs = await localVarAxiosParamCreator.getMandatesByDelegateV1(status, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.getMandatesByDelegateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Ritorna tutte le deleghe create + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async getMandatesByDelegatorV1(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + const localVarAxiosArgs = await localVarAxiosParamCreator.getMandatesByDelegatorV1(options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.getMandatesByDelegatorV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Reject a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async rejectMandateV1(mandateId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.rejectMandateV1(mandateId, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.rejectMandateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Revoke a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async revokeMandateV1(mandateId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.revokeMandateV1(mandateId, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.revokeMandateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Ritorna la lista delle deleghe a carico in base ai filtri per stato, gruppo/i e delegante (taxId) + * @param {number} size + * @param {BffSearchMandateRequest} bffSearchMandateRequest + * @param {string} [nextPageKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async searchMandatesByDelegateV1(size: number, bffSearchMandateRequest: BffSearchMandateRequest, nextPageKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.searchMandatesByDelegateV1(size, bffSearchMandateRequest, nextPageKey, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.searchMandatesByDelegateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Update a mandate + * @param {string} mandateId + * @param {BffUpdateRequest} bffUpdateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async updateMandateV1(mandateId: string, bffUpdateRequest: BffUpdateRequest, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.updateMandateV1(mandateId, bffUpdateRequest, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.updateMandateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + } +}; + +/** + * MandateApi - factory interface + * @export + */ +export const MandateApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { + const localVarFp = MandateApiFp(configuration) + return { + /** + * + * @summary Accept a mandate + * @param {string} mandateId + * @param {BffAcceptRequest} bffAcceptRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + acceptMandateV1(mandateId: string, bffAcceptRequest: BffAcceptRequest, options?: any): AxiosPromise { + return localVarFp.acceptMandateV1(mandateId, bffAcceptRequest, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Ritorna il numero totale di deleghe in base al filtro stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {CountMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + countMandatesByDelegateV1(status?: CountMandatesByDelegateV1StatusEnum, options?: any): AxiosPromise { + return localVarFp.countMandatesByDelegateV1(status, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Create a new mandate, returns the just created mandate if successful + * @param {BffNewMandateRequest} bffNewMandateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createMandateV1(bffNewMandateRequest: BffNewMandateRequest, options?: any): AxiosPromise { + return localVarFp.createMandateV1(bffNewMandateRequest, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Ritorna la lista delle deleghe a carico in base al filtro per stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {GetMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getMandatesByDelegateV1(status?: GetMandatesByDelegateV1StatusEnum, options?: any): AxiosPromise> { + return localVarFp.getMandatesByDelegateV1(status, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Ritorna tutte le deleghe create + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getMandatesByDelegatorV1(options?: any): AxiosPromise> { + return localVarFp.getMandatesByDelegatorV1(options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Reject a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + rejectMandateV1(mandateId: string, options?: any): AxiosPromise { + return localVarFp.rejectMandateV1(mandateId, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Revoke a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + revokeMandateV1(mandateId: string, options?: any): AxiosPromise { + return localVarFp.revokeMandateV1(mandateId, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Ritorna la lista delle deleghe a carico in base ai filtri per stato, gruppo/i e delegante (taxId) + * @param {number} size + * @param {BffSearchMandateRequest} bffSearchMandateRequest + * @param {string} [nextPageKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + searchMandatesByDelegateV1(size: number, bffSearchMandateRequest: BffSearchMandateRequest, nextPageKey?: string, options?: any): AxiosPromise { + return localVarFp.searchMandatesByDelegateV1(size, bffSearchMandateRequest, nextPageKey, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Update a mandate + * @param {string} mandateId + * @param {BffUpdateRequest} bffUpdateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updateMandateV1(mandateId: string, bffUpdateRequest: BffUpdateRequest, options?: any): AxiosPromise { + return localVarFp.updateMandateV1(mandateId, bffUpdateRequest, options).then((request) => request(axios, basePath)); + }, + }; +}; + +/** + * MandateApi - object-oriented interface + * @export + * @class MandateApi + * @extends {BaseAPI} + */ +export class MandateApi extends BaseAPI { + /** + * + * @summary Accept a mandate + * @param {string} mandateId + * @param {BffAcceptRequest} bffAcceptRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public acceptMandateV1(mandateId: string, bffAcceptRequest: BffAcceptRequest, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).acceptMandateV1(mandateId, bffAcceptRequest, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Ritorna il numero totale di deleghe in base al filtro stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {CountMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public countMandatesByDelegateV1(status?: CountMandatesByDelegateV1StatusEnum, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).countMandatesByDelegateV1(status, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Create a new mandate, returns the just created mandate if successful + * @param {BffNewMandateRequest} bffNewMandateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public createMandateV1(bffNewMandateRequest: BffNewMandateRequest, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).createMandateV1(bffNewMandateRequest, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Ritorna la lista delle deleghe a carico in base al filtro per stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {GetMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public getMandatesByDelegateV1(status?: GetMandatesByDelegateV1StatusEnum, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).getMandatesByDelegateV1(status, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Ritorna tutte le deleghe create + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public getMandatesByDelegatorV1(options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).getMandatesByDelegatorV1(options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Reject a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public rejectMandateV1(mandateId: string, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).rejectMandateV1(mandateId, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Revoke a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public revokeMandateV1(mandateId: string, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).revokeMandateV1(mandateId, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Ritorna la lista delle deleghe a carico in base ai filtri per stato, gruppo/i e delegante (taxId) + * @param {number} size + * @param {BffSearchMandateRequest} bffSearchMandateRequest + * @param {string} [nextPageKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public searchMandatesByDelegateV1(size: number, bffSearchMandateRequest: BffSearchMandateRequest, nextPageKey?: string, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).searchMandatesByDelegateV1(size, bffSearchMandateRequest, nextPageKey, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Update a mandate + * @param {string} mandateId + * @param {BffUpdateRequest} bffUpdateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public updateMandateV1(mandateId: string, bffUpdateRequest: BffUpdateRequest, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).updateMandateV1(mandateId, bffUpdateRequest, options).then((request) => request(this.axios, this.basePath)); + } +} + +/** + * @export + */ +export const CountMandatesByDelegateV1StatusEnum = { + Pending: 'pending', + Active: 'active', + Revoked: 'revoked', + Rejected: 'rejected', + Expired: 'expired' +} as const; +export type CountMandatesByDelegateV1StatusEnum = typeof CountMandatesByDelegateV1StatusEnum[keyof typeof CountMandatesByDelegateV1StatusEnum]; +/** + * @export + */ +export const GetMandatesByDelegateV1StatusEnum = { + Pending: 'pending', + Active: 'active', + Revoked: 'revoked', + Rejected: 'rejected', + Expired: 'expired' +} as const; +export type GetMandatesByDelegateV1StatusEnum = typeof GetMandatesByDelegateV1StatusEnum[keyof typeof GetMandatesByDelegateV1StatusEnum]; + + diff --git a/packages/pn-personafisica-webapp/src/generated-client/mandate/base.ts b/packages/pn-personafisica-webapp/src/generated-client/mandate/base.ts new file mode 100644 index 0000000000..9b608b7818 --- /dev/null +++ b/packages/pn-personafisica-webapp/src/generated-client/mandate/base.ts @@ -0,0 +1,86 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * PN BFF BE Microservice - Deleghe + * Documentation APIs v1.0 + * + * The version of the OpenAPI document: 1.0.0 + * Contact: pn@pagopa.it + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import type { Configuration } from './configuration'; +// Some imports not used depending on template conditions +// @ts-ignore +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; +import globalAxios from 'axios'; + +export const BASE_PATH = "https://webapi.notifichedigitali.it".replace(/\/+$/, ""); + +/** + * + * @export + */ +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +/** + * + * @export + * @interface RequestArgs + */ +export interface RequestArgs { + url: string; + options: RawAxiosRequestConfig; +} + +/** + * + * @export + * @class BaseAPI + */ +export class BaseAPI { + protected configuration: Configuration | undefined; + + constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { + if (configuration) { + this.configuration = configuration; + this.basePath = configuration.basePath ?? basePath; + } + } +}; + +/** + * + * @export + * @class RequiredError + * @extends {Error} + */ +export class RequiredError extends Error { + constructor(public field: string, msg?: string) { + super(msg); + this.name = "RequiredError" + } +} + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/packages/pn-personafisica-webapp/src/generated-client/mandate/common.ts b/packages/pn-personafisica-webapp/src/generated-client/mandate/common.ts new file mode 100644 index 0000000000..19c873d0a8 --- /dev/null +++ b/packages/pn-personafisica-webapp/src/generated-client/mandate/common.ts @@ -0,0 +1,150 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * PN BFF BE Microservice - Deleghe + * Documentation APIs v1.0 + * + * The version of the OpenAPI document: 1.0.0 + * Contact: pn@pagopa.it + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import type { Configuration } from "./configuration"; +import type { RequestArgs } from "./base"; +import type { AxiosInstance, AxiosResponse } from 'axios'; +import { RequiredError } from "./base"; + +/** + * + * @export + */ +export const DUMMY_BASE_URL = 'https://example.com' + +/** + * + * @throws {RequiredError} + * @export + */ +export const assertParamExists = function (functionName: string, paramName: string, paramValue: unknown) { + if (paramValue === null || paramValue === undefined) { + throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`); + } +} + +/** + * + * @export + */ +export const setApiKeyToObject = async function (object: any, keyParamName: string, configuration?: Configuration) { + if (configuration && configuration.apiKey) { + const localVarApiKeyValue = typeof configuration.apiKey === 'function' + ? await configuration.apiKey(keyParamName) + : await configuration.apiKey; + object[keyParamName] = localVarApiKeyValue; + } +} + +/** + * + * @export + */ +export const setBasicAuthToObject = function (object: any, configuration?: Configuration) { + if (configuration && (configuration.username || configuration.password)) { + object["auth"] = { username: configuration.username, password: configuration.password }; + } +} + +/** + * + * @export + */ +export const setBearerAuthToObject = async function (object: any, configuration?: Configuration) { + if (configuration && configuration.accessToken) { + const accessToken = typeof configuration.accessToken === 'function' + ? await configuration.accessToken() + : await configuration.accessToken; + object["Authorization"] = "Bearer " + accessToken; + } +} + +/** + * + * @export + */ +export const setOAuthToObject = async function (object: any, name: string, scopes: string[], configuration?: Configuration) { + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? await configuration.accessToken(name, scopes) + : await configuration.accessToken; + object["Authorization"] = "Bearer " + localVarAccessTokenValue; + } +} + +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (parameter == null) return; + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + +/** + * + * @export + */ +export const setSearchParams = function (url: URL, ...objects: any[]) { + const searchParams = new URLSearchParams(url.search); + setFlattenedQueryParams(searchParams, objects); + url.search = searchParams.toString(); +} + +/** + * + * @export + */ +export const serializeDataIfNeeded = function (value: any, requestOptions: any, configuration?: Configuration) { + const nonString = typeof value !== 'string'; + const needsSerialization = nonString && configuration && configuration.isJsonMime + ? configuration.isJsonMime(requestOptions.headers['Content-Type']) + : nonString; + return needsSerialization + ? JSON.stringify(value !== undefined ? value : {}) + : (value || ""); +} + +/** + * + * @export + */ +export const toPathString = function (url: URL) { + return url.pathname + url.search + url.hash +} + +/** + * + * @export + */ +export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { + return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; + return axios.request(axiosRequestArgs); + }; +} diff --git a/packages/pn-personafisica-webapp/src/generated-client/mandate/configuration.ts b/packages/pn-personafisica-webapp/src/generated-client/mandate/configuration.ts new file mode 100644 index 0000000000..13c3633d61 --- /dev/null +++ b/packages/pn-personafisica-webapp/src/generated-client/mandate/configuration.ts @@ -0,0 +1,110 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * PN BFF BE Microservice - Deleghe + * Documentation APIs v1.0 + * + * The version of the OpenAPI document: 1.0.0 + * Contact: pn@pagopa.it + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface ConfigurationParameters { + apiKey?: string | Promise | ((name: string) => string) | ((name: string) => Promise); + username?: string; + password?: string; + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); + basePath?: string; + serverIndex?: number; + baseOptions?: any; + formDataCtor?: new () => any; +} + +export class Configuration { + /** + * parameter for apiKey security + * @param name security name + * @memberof Configuration + */ + apiKey?: string | Promise | ((name: string) => string) | ((name: string) => Promise); + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + username?: string; + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + password?: string; + /** + * parameter for oauth2 security + * @param name security name + * @param scopes oauth2 scope + * @memberof Configuration + */ + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); + /** + * override base path + * + * @type {string} + * @memberof Configuration + */ + basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; + /** + * base options for axios calls + * + * @type {any} + * @memberof Configuration + */ + baseOptions?: any; + /** + * The FormData constructor that will be used to create multipart form data + * requests. You can inject this here so that execution environments that + * do not support the FormData class can still run the generated client. + * + * @type {new () => FormData} + */ + formDataCtor?: new () => any; + + constructor(param: ConfigurationParameters = {}) { + this.apiKey = param.apiKey; + this.username = param.username; + this.password = param.password; + this.accessToken = param.accessToken; + this.basePath = param.basePath; + this.serverIndex = param.serverIndex; + this.baseOptions = param.baseOptions; + this.formDataCtor = param.formDataCtor; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } +} diff --git a/packages/pn-personafisica-webapp/src/generated-client/mandate/index.ts b/packages/pn-personafisica-webapp/src/generated-client/mandate/index.ts new file mode 100644 index 0000000000..c1764635f8 --- /dev/null +++ b/packages/pn-personafisica-webapp/src/generated-client/mandate/index.ts @@ -0,0 +1,18 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * PN BFF BE Microservice - Deleghe + * Documentation APIs v1.0 + * + * The version of the OpenAPI document: 1.0.0 + * Contact: pn@pagopa.it + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export * from "./api"; +export * from "./configuration"; + diff --git a/packages/pn-personafisica-webapp/src/models/PFEventsType.ts b/packages/pn-personafisica-webapp/src/models/PFEventsType.ts index 7bfd84b7da..5f4282a2f7 100644 --- a/packages/pn-personafisica-webapp/src/models/PFEventsType.ts +++ b/packages/pn-personafisica-webapp/src/models/PFEventsType.ts @@ -87,10 +87,10 @@ export const eventsActionsMap: Record = { // --- PROFILE_PROPERTY 'getDomicileInfo/fulfilled': PFEventsType.SEND_HAS_ADDRESSES, 'getSidemenuInformation/fulfilled': PFEventsType.SEND_HAS_MANDATE_LOGIN, - 'getDelegates/fulfilled': PFEventsType.SEND_MANDATE_GIVEN, + 'getMandatesByDelegator/fulfilled': PFEventsType.SEND_MANDATE_GIVEN, 'enableIOAddress/fulfilled': PFEventsType.SEND_ENABLE_IO, 'disableIOAddress/fulfilled': PFEventsType.SEND_DISABLE_IO, - 'acceptDelegation/fulfilled': PFEventsType.SEND_ACCEPT_DELEGATION, + 'acceptMandate/fulfilled': PFEventsType.SEND_ACCEPT_DELEGATION, 'createOrUpdateLegalAddress/fulfilled': PFEventsType.SEND_ADD_LEGAL_ADDRESS, 'deleteLegalAddress/fulfilled': PFEventsType.SEND_REMOVE_LEGAL_ADDRESS, 'deleteCourtesyAddress/fulfilled': PFEventsType.SEND_REMOVE_COURTESY_ADDRESS, diff --git a/packages/pn-personafisica-webapp/src/pages/Deleghe.page.tsx b/packages/pn-personafisica-webapp/src/pages/Deleghe.page.tsx index 0378be71ee..0133bc07dc 100644 --- a/packages/pn-personafisica-webapp/src/pages/Deleghe.page.tsx +++ b/packages/pn-personafisica-webapp/src/pages/Deleghe.page.tsx @@ -18,11 +18,11 @@ import MobileDelegators from '../components/Deleghe/MobileDelegators'; import LoadingPageWrapper from '../components/LoadingPageWrapper/LoadingPageWrapper'; import { PFEventsType } from '../models/PFEventsType'; import { - acceptDelegation, - getDelegates, - getDelegators, - rejectDelegation, - revokeDelegation, + acceptMandate, + getMandatesByDelegate, + getMandatesByDelegator, + rejectMandate, + revokeMandate, } from '../redux/delegation/actions'; import { closeAcceptModal, closeRevocationModal, resetState } from '../redux/delegation/reducers'; import { useAppDispatch, useAppSelector } from '../redux/hooks'; @@ -58,14 +58,14 @@ const Deleghe = () => { const handleConfirmClick = () => { if (type === 'delegates') { PFEventStrategyFactory.triggerEvent(PFEventsType.SEND_MANDATE_REVOKED); - void dispatch(revokeDelegation(id)) + void dispatch(revokeMandate(id)) .unwrap() .then(() => PFEventStrategyFactory.triggerEvent(PFEventsType.SEND_MANDATE_GIVEN, { delegators }) ); } else { PFEventStrategyFactory.triggerEvent(PFEventsType.SEND_MANDATE_REJECTED); - void dispatch(rejectDelegation(id)) + void dispatch(rejectMandate(id)) .unwrap() .then(() => PFEventStrategyFactory.triggerEvent(PFEventsType.SEND_HAS_MANDATE, { delegates }) @@ -79,7 +79,7 @@ const Deleghe = () => { const handleAccept = (code: Array) => { PFEventStrategyFactory.triggerEvent(PFEventsType.SEND_MANDATE_ACCEPTED); - dispatch(acceptDelegation({ id: acceptId, code: code.join('') })) + dispatch(acceptMandate({ id: acceptId, code: code.join('') })) .unwrap() .then(() => { void dispatch(getSidemenuInformation()); @@ -96,8 +96,8 @@ const Deleghe = () => { ); const retrieveData = async () => { - await dispatch(getDelegates()); - await dispatch(getDelegators()); + await dispatch(getMandatesByDelegator()); + await dispatch(getMandatesByDelegate()); setPageReady(true); }; @@ -124,10 +124,10 @@ const Deleghe = () => { }, []); useEffect(() => { - AppResponsePublisher.error.subscribe('acceptDelegation', handleAcceptDelegationError); + AppResponsePublisher.error.subscribe('acceptMandate', handleAcceptDelegationError); return () => { - AppResponsePublisher.error.unsubscribe('acceptDelegation', handleAcceptDelegationError); + AppResponsePublisher.error.unsubscribe('acceptMandate', handleAcceptDelegationError); }; }, []); diff --git a/packages/pn-personafisica-webapp/src/pages/__test__/Deleghe.page.test.tsx b/packages/pn-personafisica-webapp/src/pages/__test__/Deleghe.page.test.tsx index f13979ea1f..08d58ed0d0 100644 --- a/packages/pn-personafisica-webapp/src/pages/__test__/Deleghe.page.test.tsx +++ b/packages/pn-personafisica-webapp/src/pages/__test__/Deleghe.page.test.tsx @@ -3,16 +3,9 @@ import { vi } from 'vitest'; import { createMatchMedia } from '@pagopa-pn/pn-commons/src/test-utils'; -import { arrayOfDelegates, arrayOfDelegators } from '../../__mocks__/Delegations.mock'; +import { mandatesByDelegate, mandatesByDelegator } from '../../__mocks__/Delegations.mock'; import { RenderResult, act, fireEvent, render, waitFor, within } from '../../__test__/test-utils'; import { apiClient } from '../../api/apiClients'; -import { - ACCEPT_DELEGATION, - DELEGATIONS_BY_DELEGATE, - DELEGATIONS_BY_DELEGATOR, - REJECT_DELEGATION, - REVOKE_DELEGATION, -} from '../../api/delegations/delegations.routes'; import { DelegationStatus } from '../../utility/status.utility'; import Deleghe from '../Deleghe.page'; @@ -43,8 +36,8 @@ describe('Deleghe page', async () => { }); it('renders the desktop view of the deleghe page - no data', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, []); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, []); + mock.onGet('/bff/v1/mandate/delegate').reply(200, []); + mock.onGet('/bff/v1/mandate/delegator').reply(200, []); await act(async () => { result = render(); }); @@ -63,8 +56,8 @@ describe('Deleghe page', async () => { it('renders the mobile view of the deleghe page - no data', async () => { window.matchMedia = createMatchMedia(800); - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, []); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, []); + mock.onGet('/bff/v1/mandate/delegate').reply(200, []); + mock.onGet('/bff/v1/mandate/delegator').reply(200, []); await act(async () => { result = render(); }); @@ -83,9 +76,9 @@ describe('Deleghe page', async () => { it('revoke a delegate', async () => { window.matchMedia = createMatchMedia(2000); - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, arrayOfDelegates); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, arrayOfDelegators); - mock.onPatch(REVOKE_DELEGATION(arrayOfDelegates[0].mandateId)).reply(204); + mock.onGet('/bff/v1/mandate/delegate').reply(200, mandatesByDelegate); + mock.onGet('/bff/v1/mandate/delegator').reply(200, mandatesByDelegator); + mock.onPatch(`/bff/v1/mandate/${mandatesByDelegator[0].mandateId}/revoke`).reply(204); await act(async () => { result = render(); }); @@ -107,24 +100,26 @@ describe('Deleghe page', async () => { fireEvent.click(confirmButton); await waitFor(() => { expect(mock.history.patch).toHaveLength(1); - expect(mock.history.patch[0].url).toBe(REVOKE_DELEGATION(arrayOfDelegates[0].mandateId)); + expect(mock.history.patch[0].url).toBe( + `/bff/v1/mandate/${mandatesByDelegator[0].mandateId}/revoke` + ); }); await waitFor(() => { expect(dialog).not.toBeInTheDocument(); }); // check that the list of delegates is updated delegatesRows = result.getAllByTestId('delegatesTable.body.row'); - expect(delegatesRows).toHaveLength(arrayOfDelegates.length - 1); + expect(delegatesRows).toHaveLength(mandatesByDelegator.length - 1); delegatesRows.forEach((row, index) => { // index + 1 because i suppose that the first delegate is revoked - expect(row).toHaveTextContent(arrayOfDelegates[index + 1].delegate?.displayName!); + expect(row).toHaveTextContent(mandatesByDelegator[index + 1].delegate?.displayName!); }); }); it('reject a delegator', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, arrayOfDelegates); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, arrayOfDelegators); - mock.onPatch(REJECT_DELEGATION(arrayOfDelegators[1].mandateId)).reply(204); + mock.onGet('/bff/v1/mandate/delegate').reply(200, mandatesByDelegate); + mock.onGet('/bff/v1/mandate/delegator').reply(200, mandatesByDelegator); + mock.onPatch(`/bff/v1/mandate/${mandatesByDelegate[1].mandateId}/reject`).reply(204); await act(async () => { result = render(); }); @@ -146,16 +141,18 @@ describe('Deleghe page', async () => { fireEvent.click(confirmButton); await waitFor(() => { expect(mock.history.patch).toHaveLength(1); - expect(mock.history.patch[0].url).toBe(REJECT_DELEGATION(arrayOfDelegators[1].mandateId)); + expect(mock.history.patch[0].url).toBe( + `/bff/v1/mandate/${mandatesByDelegate[1].mandateId}/reject` + ); }); await waitFor(() => { expect(dialog).not.toBeInTheDocument(); }); // check that the list of delegators is updated delegatorsRows = result.getAllByTestId('delegatorsTable.body.row'); - expect(delegatorsRows).toHaveLength(arrayOfDelegators.length - 1); - const newDelegators = arrayOfDelegators.filter( - (del) => del.mandateId !== arrayOfDelegators[1].mandateId + expect(delegatorsRows).toHaveLength(mandatesByDelegate.length - 1); + const newDelegators = mandatesByDelegate.filter( + (del) => del.mandateId !== mandatesByDelegate[1].mandateId ); delegatorsRows.forEach((row, index) => { expect(row).toHaveTextContent(newDelegators[index].delegator?.displayName!); @@ -163,11 +160,11 @@ describe('Deleghe page', async () => { }); it('accept a delegation', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, arrayOfDelegates); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, arrayOfDelegators); + mock.onGet('/bff/v1/mandate/delegate').reply(200, mandatesByDelegate); + mock.onGet('/bff/v1/mandate/delegator').reply(200, mandatesByDelegator); mock - .onPatch(ACCEPT_DELEGATION(arrayOfDelegators[0].mandateId), { - verificationCode: arrayOfDelegators[0].verificationCode, + .onPatch(`/bff/v1/mandate/${mandatesByDelegate[0].mandateId}/accept`, { + verificationCode: mandatesByDelegate[0].verificationCode, }) .reply(204); await act(async () => { @@ -186,7 +183,7 @@ describe('Deleghe page', async () => { // fill the inputs const codeInputs = dialog?.querySelectorAll('input'); expect(codeInputs).toHaveLength(5); - const codes = arrayOfDelegators[0].verificationCode.split(''); + const codes = mandatesByDelegate[0].verificationCode.split(''); codeInputs?.forEach((codeInput, index) => { fireEvent.change(codeInput, { target: { value: codes[index] } }); }); @@ -195,9 +192,11 @@ describe('Deleghe page', async () => { fireEvent.click(dialogButtons); await waitFor(() => { expect(mock.history.patch).toHaveLength(1); - expect(mock.history.patch[0].url).toBe(ACCEPT_DELEGATION(arrayOfDelegators[0].mandateId)); + expect(mock.history.patch[0].url).toBe( + `/bff/v1/mandate/${mandatesByDelegate[0].mandateId}/accept` + ); expect(JSON.parse(mock.history.patch[0].data)).toStrictEqual({ - verificationCode: arrayOfDelegators[0].verificationCode, + verificationCode: mandatesByDelegate[0].verificationCode, }); }); await waitFor(() => { @@ -205,9 +204,9 @@ describe('Deleghe page', async () => { }); // check that the list of delegators is updated delegatorsRows = result.getAllByTestId('delegatorsTable.body.row'); - expect(delegatorsRows).toHaveLength(arrayOfDelegators.length); + expect(delegatorsRows).toHaveLength(mandatesByDelegate.length); delegatorsRows.forEach((row, index) => { - expect(row).toHaveTextContent(arrayOfDelegators[index].delegator?.displayName!); + expect(row).toHaveTextContent(mandatesByDelegate[index].delegator?.displayName!); }); const newAcceptButton = within(delegatorsRows[0]).queryByTestId('acceptButton'); expect(newAcceptButton).not.toBeInTheDocument(); @@ -215,11 +214,11 @@ describe('Deleghe page', async () => { }); it('accept a delegation - error', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, arrayOfDelegates); - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, arrayOfDelegators); + mock.onGet('/bff/v1/mandate/delegate').reply(200, mandatesByDelegate); + mock.onGet('/bff/v1/mandate/delegator').reply(200, mandatesByDelegator); mock - .onPatch(ACCEPT_DELEGATION(arrayOfDelegators[0].mandateId), { - verificationCode: arrayOfDelegators[0].verificationCode, + .onPatch(`/bff/v1/mandate/${mandatesByDelegate[0].mandateId}/accept`, { + verificationCode: mandatesByDelegate[0].verificationCode, }) .reply(500); await act(async () => { @@ -238,7 +237,7 @@ describe('Deleghe page', async () => { // fill the inputs const codeInputs = dialog?.querySelectorAll('input'); expect(codeInputs).toHaveLength(5); - const codes = arrayOfDelegators[0].verificationCode.split(''); + const codes = mandatesByDelegate[0].verificationCode.split(''); codeInputs?.forEach((codeInput, index) => { fireEvent.change(codeInput, { target: { value: codes[index] } }); }); @@ -247,18 +246,20 @@ describe('Deleghe page', async () => { fireEvent.click(dialogButtons); await waitFor(() => { expect(mock.history.patch).toHaveLength(1); - expect(mock.history.patch[0].url).toBe(ACCEPT_DELEGATION(arrayOfDelegators[0].mandateId)); + expect(mock.history.patch[0].url).toBe( + `/bff/v1/mandate/${mandatesByDelegate[0].mandateId}/accept` + ); expect(JSON.parse(mock.history.patch[0].data)).toStrictEqual({ - verificationCode: arrayOfDelegators[0].verificationCode, + verificationCode: mandatesByDelegate[0].verificationCode, }); }); const error = await waitFor(() => within(dialog).getByTestId('errorAlert')); expect(error).toBeInTheDocument(); // check that accept button is still active in deleghe page delegatorsRows = result.getAllByTestId('delegatorsTable.body.row'); - expect(delegatorsRows).toHaveLength(arrayOfDelegators.length); + expect(delegatorsRows).toHaveLength(mandatesByDelegate.length); delegatorsRows.forEach((row, index) => { - expect(row).toHaveTextContent(arrayOfDelegators[index].delegator?.displayName!); + expect(row).toHaveTextContent(mandatesByDelegate[index].delegator?.displayName!); }); acceptButton = within(delegatorsRows[0]).getByTestId('acceptButton'); expect(acceptButton).toBeInTheDocument(); diff --git a/packages/pn-personafisica-webapp/src/pages/__test__/NotificationDetail.page.test.tsx b/packages/pn-personafisica-webapp/src/pages/__test__/NotificationDetail.page.test.tsx index c8279fc49a..e54642f868 100644 --- a/packages/pn-personafisica-webapp/src/pages/__test__/NotificationDetail.page.test.tsx +++ b/packages/pn-personafisica-webapp/src/pages/__test__/NotificationDetail.page.test.tsx @@ -19,7 +19,7 @@ import { } from '@pagopa-pn/pn-commons'; import { downtimesDTO } from '../../__mocks__/AppStatus.mock'; -import { arrayOfDelegators } from '../../__mocks__/Delegations.mock'; +import { mandatesByDelegate } from '../../__mocks__/Delegations.mock'; import { paymentInfo } from '../../__mocks__/ExternalRegistry.mock'; import { cachedPayments, @@ -73,7 +73,7 @@ const getLegalFactIds = (notification: NotificationDetailModel, recIndex: number return timelineElementDigitalSuccessWorkflow.legalFactsIds![0] as LegalFactId; }; -const delegator = arrayOfDelegators.find( +const delegator = mandatesByDelegate.find( (delegator) => delegator.delegator?.fiscalCode === notificationDTO.recipients[2].taxId ); @@ -520,7 +520,7 @@ describe('NotificationDetail Page', async () => { preloadedState: { userState: { user: { fiscal_number: 'CGNNMO80A03H501U' } }, generalInfoState: { - delegators: arrayOfDelegators, + delegators: mandatesByDelegate, }, }, }); @@ -582,7 +582,7 @@ describe('NotificationDetail Page', async () => { preloadedState: { userState: { user: { fiscal_number: 'CGNNMO80A03H501U' } }, generalInfoState: { - delegators: arrayOfDelegators, + delegators: mandatesByDelegate, defaultAddresses: [], }, }, diff --git a/packages/pn-personafisica-webapp/src/pages/__test__/NuovaDelega.test.tsx b/packages/pn-personafisica-webapp/src/pages/__test__/NuovaDelega.test.tsx index 3a64ecc374..0f74a9ec0a 100644 --- a/packages/pn-personafisica-webapp/src/pages/__test__/NuovaDelega.test.tsx +++ b/packages/pn-personafisica-webapp/src/pages/__test__/NuovaDelega.test.tsx @@ -15,7 +15,6 @@ import { createDelegationPayload } from '../../__mocks__/CreateDelegation.mock'; import { parties } from '../../__mocks__/ExternalRegistry.mock'; import { RenderResult, act, fireEvent, render, waitFor } from '../../__test__/test-utils'; import { apiClient } from '../../api/apiClients'; -import { CREATE_DELEGATION } from '../../api/delegations/delegations.routes'; import { GET_ALL_ACTIVATED_PARTIES } from '../../api/external-registries/external-registries-routes'; import * as routes from '../../navigation/routes.const'; import { createDelegationMapper } from '../../redux/newDelegation/actions'; @@ -169,7 +168,7 @@ describe('NuovaDelega page', async () => { expirationDate: new Date('01/01/2122'), verificationCode: '34153', }; - mock.onPost(CREATE_DELEGATION()).reply(200, createDelegationMapper(creationPayload)); + mock.onPost('/bff/v1/mandate', createDelegationMapper(creationPayload)).reply(200); const { container, getByTestId, getByText } = render(); const form = container.querySelector('form') as HTMLFormElement; await testInput(form, 'nome', createDelegationPayload.nome); @@ -180,7 +179,7 @@ describe('NuovaDelega page', async () => { fireEvent.click(button); await waitFor(() => { expect(mock.history.post).toHaveLength(1); - expect(mock.history.post[0].url).toBe(CREATE_DELEGATION()); + expect(mock.history.post[0].url).toBe('/bff/v1/mandate'); expect(JSON.parse(mock.history.post[0].data)).toStrictEqual( createDelegationMapper(creationPayload) ); @@ -258,7 +257,7 @@ describe('NuovaDelega page', async () => { enti: [parties[1]], selectTuttiEntiOrSelezionati: 'entiSelezionati', }; - mock.onPost(CREATE_DELEGATION()).reply(200, createDelegationMapper(creationPayload)); + mock.onPost('/bff/v1/mandate', createDelegationMapper(creationPayload)).reply(200); const { container, getByTestId } = render(); // switch to persona giuridica await testRadio( @@ -288,7 +287,7 @@ describe('NuovaDelega page', async () => { fireEvent.click(button); await waitFor(() => { expect(mock.history.post).toHaveLength(1); - expect(mock.history.post[0].url).toBe(CREATE_DELEGATION()); + expect(mock.history.post[0].url).toBe('/bff/v1/mandate'); expect(JSON.parse(mock.history.post[0].data)).toStrictEqual( createDelegationMapper(creationPayload) ); diff --git a/packages/pn-personafisica-webapp/src/redux/delegation/__test__/reducers.test.ts b/packages/pn-personafisica-webapp/src/redux/delegation/__test__/reducers.test.ts index 221d207697..0078b7c2f9 100644 --- a/packages/pn-personafisica-webapp/src/redux/delegation/__test__/reducers.test.ts +++ b/packages/pn-personafisica-webapp/src/redux/delegation/__test__/reducers.test.ts @@ -1,23 +1,16 @@ import MockAdapter from 'axios-mock-adapter'; import { mockAuthentication } from '../../../__mocks__/Auth.mock'; -import { arrayOfDelegates, arrayOfDelegators } from '../../../__mocks__/Delegations.mock'; +import { mandatesByDelegate, mandatesByDelegator } from '../../../__mocks__/Delegations.mock'; import { createMockedStore } from '../../../__test__/test-utils'; import { apiClient } from '../../../api/apiClients'; -import { - ACCEPT_DELEGATION, - DELEGATIONS_BY_DELEGATE, - DELEGATIONS_BY_DELEGATOR, - REJECT_DELEGATION, - REVOKE_DELEGATION, -} from '../../../api/delegations/delegations.routes'; import { store } from '../../store'; import { - acceptDelegation, - getDelegates, - getDelegators, - rejectDelegation, - revokeDelegation, + acceptMandate, + getMandatesByDelegate, + getMandatesByDelegator, + rejectMandate, + revokeMandate, } from '../actions'; import { closeAcceptModal, @@ -28,8 +21,8 @@ import { setDelegatorsSorting, } from '../reducers'; -const pendingDelegator = arrayOfDelegators.find((d) => d.status === 'pending'); -const pendingDelegates = arrayOfDelegates.find((d) => d.status === 'pending'); +const pendingDelegator = mandatesByDelegate.find((d) => d.status === 'pending'); +const pendingDelegates = mandatesByDelegator.find((d) => d.status === 'pending'); const initialState = { delegations: { delegators: [], @@ -78,18 +71,18 @@ describe('delegation redux state tests', () => { expect(state).toEqual(initialState); }); - it('should be able to fetch the delegates', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, arrayOfDelegates); - const action = await store.dispatch(getDelegates()); - expect(action.type).toBe('getDelegates/fulfilled'); - expect(action.payload).toEqual(arrayOfDelegates); + it('should be able to fetch the mandates by delegator', async () => { + mock.onGet('/bff/v1/mandate/delegator').reply(200, mandatesByDelegator); + const action = await store.dispatch(getMandatesByDelegator()); + expect(action.type).toBe('getMandatesByDelegator/fulfilled'); + expect(action.payload).toEqual(mandatesByDelegator); }); - it('should be able to fetch the delegators', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, arrayOfDelegators); - const action = await store.dispatch(getDelegators()); - expect(action.type).toBe('getDelegators/fulfilled'); - expect(action.payload).toEqual(arrayOfDelegators); + it('should be able to fetch the mandates by delegate', async () => { + mock.onGet('/bff/v1/mandate/delegate').reply(200, mandatesByDelegate); + const action = await store.dispatch(getMandatesByDelegate()); + expect(action.type).toBe('getMandatesByDelegate/fulfilled'); + expect(action.payload).toEqual(mandatesByDelegate); }); it('should accept a delegation request', async () => { @@ -98,18 +91,16 @@ describe('delegation redux state tests', () => { delegationsState: { ...initialState, delegations: { - delegators: arrayOfDelegators, + delegators: mandatesByDelegate, }, }, }); - mock - .onPatch(ACCEPT_DELEGATION(pendingDelegator!.mandateId)) - .reply(204, { id: pendingDelegator!.mandateId }); + mock.onPatch(`/bff/v1/mandate/${pendingDelegator!.mandateId}/accept`).reply(204); const action = await testStore.dispatch( - acceptDelegation({ id: pendingDelegator!.mandateId, code: '12345' }) + acceptMandate({ id: pendingDelegator!.mandateId, code: '12345' }) ); - expect(action.type).toBe('acceptDelegation/fulfilled'); - expect(action.payload).toEqual({ id: pendingDelegator!.mandateId }); + expect(action.type).toBe('acceptMandate/fulfilled'); + expect(action.payload).toEqual(void 0); const state = testStore.getState().delegationsState; expect(state.acceptModalState.open).toBeFalsy(); expect(state.acceptModalState.error).toBeFalsy(); @@ -117,9 +108,9 @@ describe('delegation redux state tests', () => { }); it('should set the accept modal state to error', async () => { - mock.onPatch(ACCEPT_DELEGATION('1')).reply(500, 'error'); - const action = await store.dispatch(acceptDelegation({ id: '1', code: '12345' })); - expect(action.type).toBe('acceptDelegation/rejected'); + mock.onPatch(`/bff/v1/mandate/1/accept`).reply(500, 'error'); + const action = await store.dispatch(acceptMandate({ id: '1', code: '12345' })); + expect(action.type).toBe('acceptMandate/rejected'); expect(action.payload).toStrictEqual({ response: { status: 500, data: 'error' } }); const state = store.getState().delegationsState; expect(state.acceptModalState.error).toBeTruthy(); @@ -131,16 +122,14 @@ describe('delegation redux state tests', () => { delegationsState: { ...initialState, delegations: { - delegators: arrayOfDelegators, + delegators: mandatesByDelegate, }, }, }); - mock - .onPatch(REJECT_DELEGATION(pendingDelegator!.mandateId)) - .reply(204, { id: pendingDelegator!.mandateId }); - const action = await testStore.dispatch(rejectDelegation(pendingDelegator!.mandateId)); - expect(action.type).toBe('rejectDelegation/fulfilled'); - expect(action.payload).toEqual({ id: pendingDelegator!.mandateId }); + mock.onPatch(`/bff/v1/mandate/${pendingDelegator!.mandateId}/reject`).reply(204); + const action = await testStore.dispatch(rejectMandate(pendingDelegator!.mandateId)); + expect(action.type).toBe('rejectMandate/fulfilled'); + expect(action.payload).toEqual(void 0); const state = testStore.getState().delegationsState; expect(state.modalState.open).toBeFalsy(); expect( @@ -149,9 +138,9 @@ describe('delegation redux state tests', () => { }); it('should throw an error trying to reject a delegation', async () => { - mock.onPatch(REJECT_DELEGATION('2')).reply(500, 'error'); - const action = await store.dispatch(rejectDelegation('2')); - expect(action.type).toBe('rejectDelegation/rejected'); + mock.onPatch(`/bff/v1/mandate/2/reject`).reply(500, 'error'); + const action = await store.dispatch(rejectMandate('2')); + expect(action.type).toBe('rejectMandate/rejected'); expect(action.payload).toStrictEqual({ response: { status: 500, data: 'error' } }); const state = store.getState().delegationsState; expect(state.modalState.open).toBeFalsy(); @@ -163,16 +152,14 @@ describe('delegation redux state tests', () => { delegationsState: { ...initialState, delegations: { - delegates: arrayOfDelegates, + delegates: mandatesByDelegator, }, }, }); - mock - .onPatch(REVOKE_DELEGATION(pendingDelegates!.mandateId)) - .reply(204, { id: pendingDelegates!.mandateId }); - const action = await testStore.dispatch(revokeDelegation(pendingDelegates!.mandateId)); - expect(action.type).toBe('revokeDelegation/fulfilled'); - expect(action.payload).toEqual({ id: pendingDelegates!.mandateId }); + mock.onPatch(`/bff/v1/mandate/${pendingDelegates!.mandateId}/revoke`).reply(204); + const action = await testStore.dispatch(revokeMandate(pendingDelegates!.mandateId)); + expect(action.type).toBe('revokeMandate/fulfilled'); + expect(action.payload).toEqual(void 0); const state = testStore.getState().delegationsState; expect(state.modalState.open).toBeFalsy(); expect( @@ -181,9 +168,9 @@ describe('delegation redux state tests', () => { }); it('should throw an error trying to revoke a delegation', async () => { - mock.onPatch(REVOKE_DELEGATION('2')).reply(500, 'error'); - const action = await store.dispatch(revokeDelegation('2')); - expect(action.type).toBe('revokeDelegation/rejected'); + mock.onPatch(`/bff/v1/mandate/2/revoke`).reply(500, 'error'); + const action = await store.dispatch(revokeMandate('2')); + expect(action.type).toBe('revokeMandate/rejected'); expect(action.payload).toStrictEqual({ response: { status: 500, data: 'error' } }); const state = store.getState().delegationsState; expect(state.modalState.open).toBeFalsy(); diff --git a/packages/pn-personafisica-webapp/src/redux/delegation/actions.ts b/packages/pn-personafisica-webapp/src/redux/delegation/actions.ts index 4f6c7f1ea9..ab4e47ba50 100644 --- a/packages/pn-personafisica-webapp/src/redux/delegation/actions.ts +++ b/packages/pn-personafisica-webapp/src/redux/delegation/actions.ts @@ -1,46 +1,84 @@ -import { Sort, performThunkAction } from '@pagopa-pn/pn-commons'; +import { Sort, parseError } from '@pagopa-pn/pn-commons'; import { createAction, createAsyncThunk } from '@reduxjs/toolkit'; -import { DelegationsApi } from '../../api/delegations/Delegations.api'; +import { apiClient } from '../../api/apiClients'; +import { MandateApiFactory } from '../../generated-client/mandate'; import { DelegationData } from '../../models/Deleghe'; -import { AcceptDelegationResponse, Delegation } from './types'; +import { Delegate, Delegator } from './types'; export enum DELEGATION_ACTIONS { - GET_DELEGATES = 'getDelegates', - GET_DELEGATORS = 'getDelegators', + GET_MANDATES_BY_DELEGATOR = 'getMandatesByDelegator', + GET_MANDATES_BY_DELEGATE = 'getMandatesByDelegate', + REVOKE_MANDATE = 'revokeMandate', + REJECT_MANDATE = 'rejectMandate', + ACCEPT_MANDATE = 'acceptMandate', } -export const getDelegates = createAsyncThunk>( - DELEGATION_ACTIONS.GET_DELEGATES, - performThunkAction(() => DelegationsApi.getDelegates()) +export const getMandatesByDelegator = createAsyncThunk>( + DELEGATION_ACTIONS.GET_MANDATES_BY_DELEGATOR, + async (_params, { rejectWithValue }) => { + try { + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.getMandatesByDelegatorV1(); + return response.data as Array; + } catch (e) { + return rejectWithValue(parseError(e)); + } + } ); -export const getDelegators = createAsyncThunk>( - DELEGATION_ACTIONS.GET_DELEGATORS, - performThunkAction(() => DelegationsApi.getDelegators()) +export const getMandatesByDelegate = createAsyncThunk>( + DELEGATION_ACTIONS.GET_MANDATES_BY_DELEGATE, + async (_params, { rejectWithValue }) => { + try { + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.getMandatesByDelegateV1(); + return response.data as Array; + } catch (e) { + return rejectWithValue(parseError(e)); + } + } ); -export const revokeDelegation = createAsyncThunk<{ id: string }, string>( - 'revokeDelegation', - performThunkAction((id) => DelegationsApi.revokeDelegation(id)) +export const revokeMandate = createAsyncThunk( + DELEGATION_ACTIONS.REVOKE_MANDATE, + async (params, { rejectWithValue }) => { + try { + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.revokeMandateV1(params); + return response.data; + } catch (e) { + return rejectWithValue(parseError(e)); + } + } ); -export const rejectDelegation = createAsyncThunk<{ id: string }, string>( - 'rejectDelegation', - performThunkAction((id) => DelegationsApi.rejectDelegation(id)) +export const rejectMandate = createAsyncThunk( + DELEGATION_ACTIONS.REJECT_MANDATE, + async (params, { rejectWithValue }) => { + try { + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.rejectMandateV1(params); + return response.data; + } catch (e) { + return rejectWithValue(parseError(e)); + } + } ); -export const acceptDelegation = createAsyncThunk< - AcceptDelegationResponse, - { id: string; code: string } ->( - 'acceptDelegation', - performThunkAction(async ({ id, code }: { id: string; code: string }) => { - const data = { - verificationCode: code, - }; - return await DelegationsApi.acceptDelegation(id, data); - }) +export const acceptMandate = createAsyncThunk( + DELEGATION_ACTIONS.ACCEPT_MANDATE, + async (params, { rejectWithValue }) => { + try { + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.acceptMandateV1(params.id, { + verificationCode: params.code, + }); + return response.data; + } catch (e) { + return rejectWithValue(parseError(e)); + } + } ); export const openRevocationModal = diff --git a/packages/pn-personafisica-webapp/src/redux/delegation/reducers.ts b/packages/pn-personafisica-webapp/src/redux/delegation/reducers.ts index eb8c202fee..ee980efc25 100644 --- a/packages/pn-personafisica-webapp/src/redux/delegation/reducers.ts +++ b/packages/pn-personafisica-webapp/src/redux/delegation/reducers.ts @@ -4,18 +4,18 @@ import { PayloadAction, createSlice, isAnyOf } from '@reduxjs/toolkit'; import { DelegationColumnData } from '../../models/Deleghe'; import { sortDelegations } from '../../utility/delegation.utility'; import { - acceptDelegation, - getDelegates, - getDelegators, - rejectDelegation, - revokeDelegation, + acceptMandate, + getMandatesByDelegate, + getMandatesByDelegator, + rejectMandate, + revokeMandate, } from './actions'; -import { Delegation } from './types'; +import { Delegate, Delegator } from './types'; const initialState = { delegations: { - delegators: [] as Array, - delegates: [] as Array, + delegators: [] as Array, + delegates: [] as Array, isCompany: false, }, modalState: { @@ -82,35 +82,35 @@ const delegationsSlice = createSlice({ resetState: () => initialState, }, extraReducers: (builder) => { - builder.addCase(getDelegates.fulfilled, (state, action) => { + builder.addCase(getMandatesByDelegator.fulfilled, (state, action) => { state.delegations.delegates = action.payload; }); - builder.addCase(getDelegators.fulfilled, (state, action) => { + builder.addCase(getMandatesByDelegate.fulfilled, (state, action) => { state.delegations.delegators = action.payload; }); - builder.addCase(acceptDelegation.fulfilled, (state, action) => { - state.delegations.delegators = state.delegations.delegators.map((delegator: Delegation) => - delegator.mandateId === action.payload.id ? { ...delegator, status: 'active' } : delegator + builder.addCase(acceptMandate.fulfilled, (state, action) => { + state.delegations.delegators = state.delegations.delegators.map((delegator) => + delegator.mandateId === action.meta.arg.id ? { ...delegator, status: 'active' } : delegator ); state.acceptModalState.open = false; state.acceptModalState.error = false; }); - builder.addCase(acceptDelegation.rejected, (state) => { + builder.addCase(acceptMandate.rejected, (state) => { state.acceptModalState.error = true; }); - builder.addCase(revokeDelegation.fulfilled, (state, action) => { + builder.addCase(revokeMandate.fulfilled, (state, action) => { state.modalState.open = false; state.delegations.delegates = state.delegations.delegates.filter( - (delegate: Delegation) => delegate.mandateId !== action.payload.id + (delegate) => delegate.mandateId !== action.meta.arg ); }); - builder.addCase(rejectDelegation.fulfilled, (state, action) => { + builder.addCase(rejectMandate.fulfilled, (state, action) => { state.modalState.open = false; state.delegations.delegators = state.delegations.delegators.filter( - (delegator: Delegation) => delegator.mandateId !== action.meta.arg + (delegator) => delegator.mandateId !== action.meta.arg ); }); - builder.addMatcher(isAnyOf(rejectDelegation.rejected, revokeDelegation.rejected), (state) => { + builder.addMatcher(isAnyOf(rejectMandate.rejected, revokeMandate.rejected), (state) => { state.modalState.open = false; }); }, diff --git a/packages/pn-personafisica-webapp/src/redux/delegation/types.ts b/packages/pn-personafisica-webapp/src/redux/delegation/types.ts index 8564f7ce70..84d58371a4 100644 --- a/packages/pn-personafisica-webapp/src/redux/delegation/types.ts +++ b/packages/pn-personafisica-webapp/src/redux/delegation/types.ts @@ -1,17 +1,9 @@ import { RecipientType } from '@pagopa-pn/pn-commons'; + import { DelegationParty } from '../../models/Deleghe'; import { Party } from '../../models/party'; -import { User } from '../auth/types'; - -export type UserAndDelegations = User & DelegationsList; -export interface DelegationsList { - delegators: Array; - delegations: Array; - isCompany: boolean; -} - -export interface IDelegation { +interface IDelegation { mandateId: string; status: 'active' | 'pending'; visibilityIds: Array; @@ -28,14 +20,6 @@ export interface Delegate extends IDelegation { delegate: Person | null; } -export type Delegation = Delegator | Delegate; - -export interface RevocationModalProps { - open: boolean; - id: string; - type: string; -} - export interface Person { firstName?: string; lastName?: string; @@ -56,24 +40,10 @@ export interface NewDelegationFormProps { enti: Array; verificationCode: string; } -export interface AcceptDelegationResponse { - id: string; -} -export interface CreateDelegationProps { +export interface NewMandateRequest { delegate: Person; visibilityIds: Array; verificationCode: string; dateto: string; } - -export interface CreateDelegationResponse { - datefrom: string; - dateto: string; - delegate: Person; - delegator: Person | null; - mandateId: string; - status: string; - verificationCode: string; - visibilityIds: Array; -} diff --git a/packages/pn-personafisica-webapp/src/redux/newDelegation/__test__/reducers.test.ts b/packages/pn-personafisica-webapp/src/redux/newDelegation/__test__/reducers.test.ts index ec878c6ffe..dfb54d2149 100644 --- a/packages/pn-personafisica-webapp/src/redux/newDelegation/__test__/reducers.test.ts +++ b/packages/pn-personafisica-webapp/src/redux/newDelegation/__test__/reducers.test.ts @@ -4,12 +4,10 @@ import { createDelegationDuplicatedErrorResponse, createDelegationGenericErrorResponse, createDelegationPayload, - createDelegationResponse, createDelegationSelectedPayload, } from '../../../__mocks__/CreateDelegation.mock'; import { parties } from '../../../__mocks__/ExternalRegistry.mock'; import { apiClient } from '../../../api/apiClients'; -import { CREATE_DELEGATION } from '../../../api/delegations/delegations.routes'; import { GET_ALL_ACTIVATED_PARTIES } from '../../../api/external-registries/external-registries-routes'; import { store } from '../../store'; import { createDelegation, createDelegationMapper, getAllEntities } from '../actions'; @@ -42,26 +40,24 @@ describe('delegation redux state tests', () => { }); it('creates a new delegation with all organizations', async () => { - mock - .onPost(CREATE_DELEGATION(), createDelegationMapper(createDelegationPayload)) - .reply(200, createDelegationResponse); + mock.onPost('/bff/v1/mandate', createDelegationMapper(createDelegationPayload)).reply(200); const action = await store.dispatch(createDelegation(createDelegationPayload)); expect(action.type).toBe('createDelegation/fulfilled'); - expect(action.payload).toEqual(createDelegationResponse); + expect(action.payload).toEqual(void 0); }); it('creates a new delegation with a single organization', async () => { mock - .onPost(CREATE_DELEGATION(), createDelegationMapper(createDelegationSelectedPayload)) - .reply(200, createDelegationResponse); + .onPost('/bff/v1/mandate', createDelegationMapper(createDelegationSelectedPayload)) + .reply(200); const action = await store.dispatch(createDelegation(createDelegationSelectedPayload)); expect(action.type).toBe('createDelegation/fulfilled'); - expect(action.payload).toEqual(createDelegationResponse); + expect(action.payload).toEqual(void 0); }); it("can't create a new delegation", async () => { mock - .onPost(CREATE_DELEGATION(), createDelegationMapper(createDelegationPayload)) + .onPost('/bff/v1/mandate', createDelegationMapper(createDelegationPayload)) .reply(401, createDelegationGenericErrorResponse); const action = await store.dispatch(createDelegation(createDelegationPayload)); expect(action.type).toBe('createDelegation/rejected'); @@ -70,7 +66,7 @@ describe('delegation redux state tests', () => { it("can't create a new delegation (duplicated)", async () => { mock - .onPost(CREATE_DELEGATION(), createDelegationMapper(createDelegationPayload)) + .onPost('/bff/v1/mandate', createDelegationMapper(createDelegationPayload)) .reply(400, createDelegationDuplicatedErrorResponse); const action = await store.dispatch(createDelegation(createDelegationPayload)); expect(action.type).toBe('createDelegation/rejected'); diff --git a/packages/pn-personafisica-webapp/src/redux/newDelegation/actions.ts b/packages/pn-personafisica-webapp/src/redux/newDelegation/actions.ts index 33bbb80f94..fce563b940 100644 --- a/packages/pn-personafisica-webapp/src/redux/newDelegation/actions.ts +++ b/packages/pn-personafisica-webapp/src/redux/newDelegation/actions.ts @@ -1,18 +1,13 @@ -import { RecipientType, formatToSlicedISOString } from '@pagopa-pn/pn-commons'; +import { RecipientType, formatToSlicedISOString, parseError } from '@pagopa-pn/pn-commons'; import { createAsyncThunk } from '@reduxjs/toolkit'; -import { DelegationsApi } from '../../api/delegations/Delegations.api'; +import { apiClient } from '../../api/apiClients'; import { ExternalRegistriesAPI } from '../../api/external-registries/External-registries.api'; -import { DelegationParty } from '../../models/Deleghe'; +import { MandateApiFactory } from '../../generated-client/mandate'; import { FilterPartiesParams, Party } from '../../models/party'; -import { - CreateDelegationProps, - CreateDelegationResponse, - NewDelegationFormProps, - Person, -} from '../delegation/types'; +import { NewDelegationFormProps, NewMandateRequest, Person } from '../delegation/types'; -export function createDelegationMapper(formData: NewDelegationFormProps): CreateDelegationProps { +export function createDelegationMapper(formData: NewDelegationFormProps): NewMandateRequest { const delegate = { fiscalCode: formData.codiceFiscale, } as Person; @@ -39,21 +34,23 @@ export function createDelegationMapper(formData: NewDelegationFormProps): Create return { uniqueIdentifier: ente.id, name: ente.name, - } as DelegationParty; + }; }), verificationCode: formData.verificationCode, dateto: formatToSlicedISOString(formData.expirationDate), }; } -export const createDelegation = createAsyncThunk( +export const createDelegation = createAsyncThunk( 'createDelegation', async (data, { rejectWithValue }) => { try { const payload = createDelegationMapper(data); - return await DelegationsApi.createDelegation(payload); + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.createMandateV1(payload); + return response.data; } catch (e: any) { - return rejectWithValue(e); + return rejectWithValue(parseError(e)); } } ); diff --git a/packages/pn-personafisica-webapp/src/redux/newDelegation/reducers.ts b/packages/pn-personafisica-webapp/src/redux/newDelegation/reducers.ts index 02a70a20a0..e2a5203e60 100644 --- a/packages/pn-personafisica-webapp/src/redux/newDelegation/reducers.ts +++ b/packages/pn-personafisica-webapp/src/redux/newDelegation/reducers.ts @@ -1,7 +1,7 @@ import { createSlice } from '@reduxjs/toolkit'; + import { Party } from '../../models/party'; import { createDelegation, getAllEntities } from './actions'; -import { newDelegation } from './types'; /* eslint-disable functional/immutable-data */ const newDelegationSlice = createSlice({ @@ -10,7 +10,7 @@ const newDelegationSlice = createSlice({ created: false, error: false, entities: [] as Array, - } as newDelegation, + }, reducers: { resetNewDelegation: (state) => { state.created = false; diff --git a/packages/pn-personafisica-webapp/src/redux/newDelegation/types.ts b/packages/pn-personafisica-webapp/src/redux/newDelegation/types.ts deleted file mode 100644 index 91f31dea23..0000000000 --- a/packages/pn-personafisica-webapp/src/redux/newDelegation/types.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { Party } from '../../models/party'; - -export interface newDelegation { - created: boolean; - error: boolean; - entities: Array; -} diff --git a/packages/pn-personafisica-webapp/src/redux/sidemenu/__test__/reducers.test.ts b/packages/pn-personafisica-webapp/src/redux/sidemenu/__test__/reducers.test.ts index fbcdbe1302..8c567f4279 100644 --- a/packages/pn-personafisica-webapp/src/redux/sidemenu/__test__/reducers.test.ts +++ b/packages/pn-personafisica-webapp/src/redux/sidemenu/__test__/reducers.test.ts @@ -1,15 +1,10 @@ import MockAdapter from 'axios-mock-adapter'; import { mockAuthentication } from '../../../__mocks__/Auth.mock'; -import { arrayOfDelegators } from '../../../__mocks__/Delegations.mock'; +import { mandatesByDelegate } from '../../../__mocks__/Delegations.mock'; import { createMockedStore } from '../../../__test__/test-utils'; import { apiClient } from '../../../api/apiClients'; -import { - ACCEPT_DELEGATION, - DELEGATIONS_BY_DELEGATE, - REJECT_DELEGATION, -} from '../../../api/delegations/delegations.routes'; -import { acceptDelegation, rejectDelegation } from '../../delegation/actions'; +import { acceptMandate, rejectMandate } from '../../delegation/actions'; import { store } from '../../store'; import { getSidemenuInformation } from '../actions'; import { closeDomicileBanner } from '../reducers'; @@ -21,8 +16,8 @@ const initialState = { domicileBannerOpened: true, }; -const pendingDelegators = arrayOfDelegators.filter((d) => d.status === 'pending'); -const activeDelegators = arrayOfDelegators.filter((d) => d.status === 'active'); +const pendingDelegators = mandatesByDelegate.filter((d) => d.status === 'pending'); +const activeDelegators = mandatesByDelegate.filter((d) => d.status === 'active'); describe('Sidemenu redux state tests', () => { let mock: MockAdapter; @@ -53,10 +48,10 @@ describe('Sidemenu redux state tests', () => { }); it('Should load state properly', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATE()).reply(200, arrayOfDelegators); + mock.onGet('/bff/v1/mandate/delegate').reply(200, mandatesByDelegate); const action = await store.dispatch(getSidemenuInformation()); expect(action.type).toBe('getSidemenuInformation/fulfilled'); - expect(action.payload).toEqual(arrayOfDelegators); + expect(action.payload).toEqual(mandatesByDelegate); const state = store.getState().generalInfoState; expect(state.delegators).toHaveLength(activeDelegators.length); expect(state.pendingDelegators).toBe(pendingDelegators.length); @@ -71,14 +66,12 @@ describe('Sidemenu redux state tests', () => { pendingDelegators: pendingDelegators.length, }, }); - mock - .onPatch(ACCEPT_DELEGATION(pendingDelegators[0].mandateId)) - .reply(204, { id: pendingDelegators[0].mandateId }); + mock.onPatch(`/bff/v1/mandate/${pendingDelegators[0].mandateId}/accept`).reply(204); const action = await testStore.dispatch( - acceptDelegation({ id: pendingDelegators[0].mandateId, code: '12345' }) + acceptMandate({ id: pendingDelegators[0].mandateId, code: '12345' }) ); - expect(action.type).toBe('acceptDelegation/fulfilled'); - expect(action.payload).toEqual({ id: pendingDelegators[0].mandateId }); + expect(action.type).toBe('acceptMandate/fulfilled'); + expect(action.payload).toEqual(void 0); const state = testStore.getState().generalInfoState; expect(state.pendingDelegators).toBe(0); }); @@ -92,14 +85,12 @@ describe('Sidemenu redux state tests', () => { pendingDelegators: pendingDelegators.length, }, }); - mock - .onPatch(REJECT_DELEGATION(pendingDelegators[0].mandateId)) - .reply(204, { id: pendingDelegators[0].mandateId }); - const action = await testStore.dispatch(rejectDelegation(pendingDelegators[0].mandateId)); - expect(action.type).toBe('rejectDelegation/fulfilled'); - expect(action.payload).toEqual({ id: pendingDelegators[0].mandateId }); + mock.onPatch(`/bff/v1/mandate/${pendingDelegators[0].mandateId}/reject`).reply(204); + const action = await testStore.dispatch(rejectMandate(pendingDelegators[0].mandateId)); + expect(action.type).toBe('rejectMandate/fulfilled'); + expect(action.payload).toEqual(void 0); const state = testStore.getState().generalInfoState; - expect(action.type).toBe('rejectDelegation/fulfilled'); + expect(action.type).toBe('rejectMandate/fulfilled'); expect(state.delegators.length).toBe(activeDelegators.length); expect(state.pendingDelegators).toBe(0); }); @@ -113,14 +104,12 @@ describe('Sidemenu redux state tests', () => { pendingDelegators: pendingDelegators.length, }, }); - mock - .onPatch(REJECT_DELEGATION(activeDelegators[0].mandateId)) - .reply(204, { id: activeDelegators[0].mandateId }); - const action = await testStore.dispatch(rejectDelegation(activeDelegators[0].mandateId)); - expect(action.type).toBe('rejectDelegation/fulfilled'); - expect(action.payload).toEqual({ id: activeDelegators[0].mandateId }); + mock.onPatch(`/bff/v1/mandate/${activeDelegators[0].mandateId}/reject`).reply(204); + const action = await testStore.dispatch(rejectMandate(activeDelegators[0].mandateId)); + expect(action.type).toBe('rejectMandate/fulfilled'); + expect(action.payload).toEqual(void 0); const state = testStore.getState().generalInfoState; - expect(action.type).toBe('rejectDelegation/fulfilled'); + expect(action.type).toBe('rejectMandate/fulfilled'); expect(state.delegators.length).toBe(activeDelegators.length - 1); expect(state.pendingDelegators).toBe(pendingDelegators.length); }); diff --git a/packages/pn-personafisica-webapp/src/redux/sidemenu/actions.ts b/packages/pn-personafisica-webapp/src/redux/sidemenu/actions.ts index 34ed1c5518..73cdea4592 100644 --- a/packages/pn-personafisica-webapp/src/redux/sidemenu/actions.ts +++ b/packages/pn-personafisica-webapp/src/redux/sidemenu/actions.ts @@ -1,24 +1,26 @@ -import { performThunkAction } from '@pagopa-pn/pn-commons'; +import { parseError } from '@pagopa-pn/pn-commons'; import { createAsyncThunk } from '@reduxjs/toolkit'; import { apiClient } from '../../api/apiClients'; -import { DelegationsApi } from '../../api/delegations/Delegations.api'; import { AddressesApiFactory } from '../../generated-client/digital-addresses'; +import { MandateApiFactory } from '../../generated-client/mandate'; import { CourtesyChannelType, DigitalAddress, IOAllowedValues } from '../../models/contacts'; import { Delegator } from '../delegation/types'; export enum SIDEMENU_ACTIONS { GET_SIDEMENU_INFORMATION = 'getSidemenuInformation', + GET_DOMICILE_INFO = 'getDomicileInfo', } export const getSidemenuInformation = createAsyncThunk>( SIDEMENU_ACTIONS.GET_SIDEMENU_INFORMATION, - // performThunkAction(() => DelegationsApi.getDelegators()) - async () => { + async (_params, { rejectWithValue }) => { try { - return await DelegationsApi.getDelegators(); + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.getMandatesByDelegateV1(); + return response.data as Array; } catch (e) { - return []; + return rejectWithValue(parseError(e)); } } ); @@ -27,17 +29,21 @@ export const getSidemenuInformation = createAsyncThunk>( // si devono prendere gli indirizzi default, tranne per AppIO che si prendono tutti (senza verificare default) // il cui valore non sia DISABLED (cfr. description e commenti della issue JIRA) export const getDomicileInfo = createAsyncThunk>( - 'getDomicileInfo', - performThunkAction(async () => { - const isDefaultAddress = (address: DigitalAddress) => - (address.channelType !== CourtesyChannelType.IOMSG && address.senderId === 'default') || - (address.channelType === CourtesyChannelType.IOMSG && - address.value !== IOAllowedValues.DISABLED); + SIDEMENU_ACTIONS.GET_DOMICILE_INFO, + async (_params, { rejectWithValue }) => { + try { + const isDefaultAddress = (address: DigitalAddress) => + (address.channelType !== CourtesyChannelType.IOMSG && address.senderId === 'default') || + (address.channelType === CourtesyChannelType.IOMSG && + address.value !== IOAllowedValues.DISABLED); - const digitalAddressesFactory = AddressesApiFactory(undefined, undefined, apiClient); - const response = await digitalAddressesFactory.getAddressesV1(); - const allAddresses = response.data as Array; + const digitalAddressesFactory = AddressesApiFactory(undefined, undefined, apiClient); + const response = await digitalAddressesFactory.getAddressesV1(); + const allAddresses = response.data as Array; - return [...allAddresses.filter(isDefaultAddress)]; - }) + return [...allAddresses.filter(isDefaultAddress)]; + } catch (e) { + return rejectWithValue(parseError(e)); + } + } ); diff --git a/packages/pn-personafisica-webapp/src/redux/sidemenu/reducers.ts b/packages/pn-personafisica-webapp/src/redux/sidemenu/reducers.ts index 340326aae0..12ffacf599 100644 --- a/packages/pn-personafisica-webapp/src/redux/sidemenu/reducers.ts +++ b/packages/pn-personafisica-webapp/src/redux/sidemenu/reducers.ts @@ -1,7 +1,7 @@ import { createSlice } from '@reduxjs/toolkit'; import { DigitalAddress } from '../../models/contacts'; -import { acceptDelegation, rejectDelegation } from '../delegation/actions'; +import { acceptMandate, rejectMandate } from '../delegation/actions'; import { Delegator } from '../delegation/types'; import { getDomicileInfo, getSidemenuInformation } from './actions'; @@ -29,12 +29,12 @@ const generalInfoSlice = createSlice({ builder.addCase(getDomicileInfo.fulfilled, (state, action) => { state.defaultAddresses = action.payload; }); - builder.addCase(acceptDelegation.fulfilled, (state) => { + builder.addCase(acceptMandate.fulfilled, (state) => { if (state.pendingDelegators > 0) { state.pendingDelegators--; } }); - builder.addCase(rejectDelegation.fulfilled, (state, action) => { + builder.addCase(rejectMandate.fulfilled, (state, action) => { const startingDelegatorsNum = state.delegators.length; state.delegators = state.delegators.filter( (delegator) => delegator.mandateId !== action.meta.arg diff --git a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/SendHasMandateGivensStrategy.ts b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/SendHasMandateGivensStrategy.ts index e986ab6f30..ba2f9f8de5 100644 --- a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/SendHasMandateGivensStrategy.ts +++ b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/SendHasMandateGivensStrategy.ts @@ -1,6 +1,6 @@ import { EventPropertyType, EventStrategy, TrackedEvent } from '@pagopa-pn/pn-commons'; -import { Delegation } from '../../../redux/delegation/types'; +import { Delegator } from '../../../redux/delegation/types'; import { DelegationStatus } from '../../status.utility'; type SendHasMandateGiven = { @@ -8,7 +8,7 @@ type SendHasMandateGiven = { }; type SendHasMandateGivenData = { - payload: Array; + payload: Array; }; export class SendHasMandateGivenStrategy implements EventStrategy { diff --git a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/SendHasMandateStrategy.ts b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/SendHasMandateStrategy.ts index ce3bae862c..e4bd5912f0 100644 --- a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/SendHasMandateStrategy.ts +++ b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/SendHasMandateStrategy.ts @@ -1,10 +1,10 @@ import { EventPropertyType, EventStrategy, TrackedEvent } from '@pagopa-pn/pn-commons'; -import { Delegation } from '../../../redux/delegation/types'; +import { Delegate } from '../../../redux/delegation/types'; import { DelegationStatus } from '../../status.utility'; type SendHasMandate = { - delegates: Array; + delegates: Array; }; export class SendHasMandateStrategy implements EventStrategy { diff --git a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/SendYourMandatesStrategy.ts b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/SendYourMandatesStrategy.ts index df1ca2eadc..0c502d4033 100644 --- a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/SendYourMandatesStrategy.ts +++ b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/SendYourMandatesStrategy.ts @@ -7,12 +7,12 @@ import { TrackedEvent, } from '@pagopa-pn/pn-commons'; -import { Delegation } from '../../../redux/delegation/types'; +import { Delegate, Delegator } from '../../../redux/delegation/types'; import { DelegationStatus } from '../../status.utility'; type SendYourMandate = { - delegates: Array; - delegators: Array; + delegates: Array; + delegators: Array; }; export class SendYourMandatesStrategy implements EventStrategy { diff --git a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendHasMandateGivenStrategy.test.ts b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendHasMandateGivenStrategy.test.ts index 4fed0c5b38..0e909b21cc 100644 --- a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendHasMandateGivenStrategy.test.ts +++ b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendHasMandateGivenStrategy.test.ts @@ -1,13 +1,13 @@ import { EventPropertyType } from '@pagopa-pn/pn-commons'; -import { arrayOfDelegators } from '../../../../__mocks__/Delegations.mock'; +import { mandatesByDelegate } from '../../../../__mocks__/Delegations.mock'; import { SendHasMandateGivenStrategy } from '../SendHasMandateGivensStrategy'; describe('Mixpanel - Has Mandate Given Strategy', () => { it('should return has mandate given event', () => { const strategy = new SendHasMandateGivenStrategy(); - const mandateGiven = strategy.performComputations({ payload: arrayOfDelegators }); + const mandateGiven = strategy.performComputations({ payload: mandatesByDelegate }); expect(mandateGiven).toEqual({ [EventPropertyType.PROFILE]: { SEND_MANDATE_GIVEN: 'yes', diff --git a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendHasMandateLoginStrategy.test.ts b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendHasMandateLoginStrategy.test.ts index f5c7f4c5cb..b17044d9d3 100644 --- a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendHasMandateLoginStrategy.test.ts +++ b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendHasMandateLoginStrategy.test.ts @@ -1,13 +1,13 @@ import { EventPropertyType } from '@pagopa-pn/pn-commons'; -import { arrayOfDelegators } from '../../../../__mocks__/Delegations.mock'; +import { mandatesByDelegate } from '../../../../__mocks__/Delegations.mock'; import { SendHasMandateLoginStrategy } from '../SendHasMandateLoginStrategy'; describe('Mixpanel - Has Mandate Login Strategy', () => { it('should return has mandate login event', () => { const strategy = new SendHasMandateLoginStrategy(); - const mandateGiven = strategy.performComputations({ payload: arrayOfDelegators }); + const mandateGiven = strategy.performComputations({ payload: mandatesByDelegate }); expect(mandateGiven).toEqual({ [EventPropertyType.PROFILE]: { SEND_HAS_MANDATE: 'yes', diff --git a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendYourMandatesStrategy.test.ts b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendYourMandatesStrategy.test.ts index 785676685b..51f0e42edd 100644 --- a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendYourMandatesStrategy.test.ts +++ b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendYourMandatesStrategy.test.ts @@ -1,6 +1,6 @@ import { EventAction, EventCategory, EventPropertyType } from '@pagopa-pn/pn-commons'; -import { arrayOfDelegates, arrayOfDelegators } from '../../../../__mocks__/Delegations.mock'; +import { mandatesByDelegate, mandatesByDelegator } from '../../../../__mocks__/Delegations.mock'; import { DelegationStatus } from '../../../status.utility'; import { SendYourMandatesStrategy } from '../SendYourMandatesStrategy'; @@ -8,8 +8,8 @@ describe('Mixpanel - Send Your Mandates Strategy', () => { it('should return your mandates event', () => { const strategy = new SendYourMandatesStrategy(); - const delegates = arrayOfDelegates; - const delegators = arrayOfDelegators; + const delegates = mandatesByDelegator; + const delegators = mandatesByDelegate; const yourMandatesEvents = strategy.performComputations({ delegates, delegators }); expect(yourMandatesEvents).toEqual({ diff --git a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendYourNotificationsStrategy.test.ts b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendYourNotificationsStrategy.test.ts index a2d4a46b85..2e45ed61ef 100644 --- a/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendYourNotificationsStrategy.test.ts +++ b/packages/pn-personafisica-webapp/src/utility/MixpanelUtils/Strategies/__test__/SendYourNotificationsStrategy.test.ts @@ -6,7 +6,7 @@ import { isNewNotification, } from '@pagopa-pn/pn-commons'; -import { arrayOfDelegators } from '../../../../__mocks__/Delegations.mock'; +import { mandatesByDelegate } from '../../../../__mocks__/Delegations.mock'; import { SendYourNotificationsStrategy } from '../SendYourNotificationsStrategy'; describe('Mixpanel - Send Your Notification Strategy', () => { @@ -27,7 +27,7 @@ describe('Mixpanel - Send Your Notification Strategy', () => { group: '', }, ], - delegators: arrayOfDelegators, + delegators: mandatesByDelegate, pagination: { nextPagesKey: [], size: 1, diff --git a/packages/pn-personafisica-webapp/src/utility/__test__/delegation.utility.test.ts b/packages/pn-personafisica-webapp/src/utility/__test__/delegation.utility.test.ts index 260302f462..e59de411ce 100644 --- a/packages/pn-personafisica-webapp/src/utility/__test__/delegation.utility.test.ts +++ b/packages/pn-personafisica-webapp/src/utility/__test__/delegation.utility.test.ts @@ -2,7 +2,7 @@ import crypto from 'crypto'; import { formatDate } from '@pagopa-pn/pn-commons'; -import { arrayOfDelegates, arrayOfDelegators } from '../../__mocks__/Delegations.mock'; +import { mandatesByDelegate, mandatesByDelegator } from '../../__mocks__/Delegations.mock'; import delegationToItem, { generateVCode, sortDelegations } from '../delegation.utility'; Object.defineProperty(global, 'crypto', { @@ -13,8 +13,8 @@ Object.defineProperty(global, 'crypto', { describe('Delegation utility test', () => { it('Should convert an delegation array of delegate to an item array - delegate', () => { - const item = delegationToItem(arrayOfDelegates); - const expected = arrayOfDelegates.map((delegation) => ({ + const item = delegationToItem(mandatesByDelegator); + const expected = mandatesByDelegator.map((delegation) => ({ id: delegation.mandateId, name: delegation.delegate?.displayName, // la data arriva nel formato YYYY-MM-DDZ rimuovere slice in caso di rimozione di Z @@ -28,8 +28,8 @@ describe('Delegation utility test', () => { }); it('Should convert an delegation array of delegate to an item array - delegator', () => { - const item = delegationToItem(arrayOfDelegators); - const expected = arrayOfDelegators.map((delegation) => ({ + const item = delegationToItem(mandatesByDelegate); + const expected = mandatesByDelegate.map((delegation) => ({ id: delegation.mandateId, name: delegation.delegator?.displayName, // la data arriva nel formato YYYY-MM-DDZ rimuovere slice in caso di rimozione di Z @@ -51,64 +51,64 @@ describe('Delegation utility test', () => { it('sort delegation by name - delegates', () => { // sort ascending const sortedCopy = (order: 'asc' | 'desc') => - [...arrayOfDelegates].sort((a, b) => { + [...mandatesByDelegator].sort((a, b) => { const multiplier = order === 'asc' ? 1 : -1; if (a.delegate?.displayName === b.delegate?.displayName) { return 0; } return (a.delegate?.displayName! < b.delegate?.displayName! ? -1 : 1) * multiplier; }); - let result = sortDelegations('asc', 'name', arrayOfDelegates); + let result = sortDelegations('asc', 'name', mandatesByDelegator); expect(sortedCopy('asc')).toStrictEqual(result); // sort descending - result = sortDelegations('desc', 'name', arrayOfDelegates); + result = sortDelegations('desc', 'name', mandatesByDelegator); expect(sortedCopy('desc')).toStrictEqual(result); }); it('sort delegation by endDate - delegates', () => { const sortedCopy = (order: 'asc' | 'desc') => - [...arrayOfDelegates].sort((a, b) => { + [...mandatesByDelegator].sort((a, b) => { const multiplier = order === 'asc' ? 1 : -1; const dateA = new Date(a.dateto).getTime(); const dateB = new Date(b.dateto).getTime(); return (dateA - dateB) * multiplier; }); - let result = sortDelegations('asc', 'endDate', arrayOfDelegates); + let result = sortDelegations('asc', 'endDate', mandatesByDelegator); expect(sortedCopy('asc')).toStrictEqual(result); - result = sortDelegations('desc', 'endDate', arrayOfDelegates); + result = sortDelegations('desc', 'endDate', mandatesByDelegator); expect(sortedCopy('desc')).toStrictEqual(result); }); it('sort delegation by name - delegators', () => { // sort ascending const sortedCopy = (order: 'asc' | 'desc') => - [...arrayOfDelegators].sort((a, b) => { + [...mandatesByDelegate].sort((a, b) => { const multiplier = order === 'asc' ? 1 : -1; if (a.delegator?.displayName === b.delegator?.displayName) { return 0; } return (a.delegator?.displayName! < b.delegator?.displayName! ? -1 : 1) * multiplier; }); - let result = sortDelegations('asc', 'name', arrayOfDelegators); + let result = sortDelegations('asc', 'name', mandatesByDelegate); expect(sortedCopy('asc')).toStrictEqual(result); // sort descending - result = sortDelegations('desc', 'name', arrayOfDelegators); + result = sortDelegations('desc', 'name', mandatesByDelegate); expect(sortedCopy('desc')).toStrictEqual(result); }); it('sort delegation by endDate - delegators', () => { // sort ascending const sortedCopy = (order: 'asc' | 'desc') => - [...arrayOfDelegators].sort((a, b) => { + [...mandatesByDelegate].sort((a, b) => { const multiplier = order === 'asc' ? 1 : -1; const dateA = new Date(a.dateto).getTime(); const dateB = new Date(b.dateto).getTime(); return (dateA - dateB) * multiplier; }); - let result = sortDelegations('asc', 'endDate', arrayOfDelegators); + let result = sortDelegations('asc', 'endDate', mandatesByDelegate); expect(sortedCopy('asc')).toStrictEqual(result); // sort descending - result = sortDelegations('desc', 'endDate', arrayOfDelegators); + result = sortDelegations('desc', 'endDate', mandatesByDelegate); expect(sortedCopy('desc')).toStrictEqual(result); }); }); diff --git a/packages/pn-personafisica-webapp/src/utility/__test__/notification.utility.test.ts b/packages/pn-personafisica-webapp/src/utility/__test__/notification.utility.test.ts index b0cf43c90d..564c5e9bf4 100644 --- a/packages/pn-personafisica-webapp/src/utility/__test__/notification.utility.test.ts +++ b/packages/pn-personafisica-webapp/src/utility/__test__/notification.utility.test.ts @@ -1,6 +1,6 @@ import _ from 'lodash'; -import { arrayOfDelegators } from '../../__mocks__/Delegations.mock'; +import { mandatesByDelegate } from '../../__mocks__/Delegations.mock'; import { notificationDTO } from '../../__mocks__/NotificationDetail.mock'; import { parseNotificationDetailForRecipient } from '../notification.utility'; @@ -12,7 +12,7 @@ describe('Tests notification utility', () => { const notification = parseNotificationDetailForRecipient( _.cloneDeep(notificationDTO), notificationDTO.recipients[recipientIndex].taxId, - arrayOfDelegators + mandatesByDelegate ); expect(notification.currentRecipientIndex).toEqual(recipientIndex); expect(notification.currentRecipient.taxId).toEqual( @@ -24,7 +24,7 @@ describe('Tests notification utility', () => { const notification = parseNotificationDetailForRecipient( _.cloneDeep(notificationDTO), notificationDTO.recipients[filterOutRecipientIndex].taxId, - arrayOfDelegators + mandatesByDelegate ); expect(notification.currentRecipientIndex).toEqual(0); expect(notification.currentRecipient.taxId).toBeUndefined(); @@ -34,8 +34,8 @@ describe('Tests notification utility', () => { const notification = parseNotificationDetailForRecipient( _.cloneDeep(notificationDTO), 'CGNNMO80A03H501U', - arrayOfDelegators, - arrayOfDelegators[2].mandateId + mandatesByDelegate, + mandatesByDelegate[2].mandateId ); expect(notification.currentRecipientIndex).toEqual(recipientIndex); expect(notification.currentRecipient.taxId).toEqual( @@ -47,8 +47,8 @@ describe('Tests notification utility', () => { const notification = parseNotificationDetailForRecipient( _.cloneDeep(notificationDTO), 'CGNNMO80A03H501U', - arrayOfDelegators, - arrayOfDelegators[0].mandateId + mandatesByDelegate, + mandatesByDelegate[0].mandateId ); expect(notification.currentRecipientIndex).toEqual(0); expect(notification.currentRecipient.taxId).toBeUndefined(); diff --git a/packages/pn-personafisica-webapp/src/utility/delegation.utility.ts b/packages/pn-personafisica-webapp/src/utility/delegation.utility.ts index 85b72e0c7c..bee8b91162 100644 --- a/packages/pn-personafisica-webapp/src/utility/delegation.utility.ts +++ b/packages/pn-personafisica-webapp/src/utility/delegation.utility.ts @@ -1,19 +1,19 @@ import { Row, formatDate } from '@pagopa-pn/pn-commons'; import { DelegationColumnData, DelegationData } from '../models/Deleghe'; -import { Delegation, Person } from '../redux/delegation/types'; +import { Delegate, Delegator, Person } from '../redux/delegation/types'; /** * Maps Delegation object to Item, in order to be visualised in an PnCardsList or PnTable component - * @param {Array} delegations + * @param {Array} delegations * @param {boolean} isDelegator * @returns Array */ -export default function delegationToItem( - delegations: Array +export default function delegationToItem( + delegations: Array ): Array> { - return delegations.map((delegation: Delegation) => ({ + return delegations.map((delegation: T) => ({ id: delegation.mandateId, name: getFirstName(delegation), // la data arriva nel formato YYYY-MM-DDZ rimuovere slice in caso di rimozione di Z @@ -31,16 +31,16 @@ export function generateVCode() { return crypto.getRandomValues(array).toString().slice(0, 5); } -export function sortDelegations( +export function sortDelegations( order: string, sortAttr: keyof DelegationColumnData | '', - values: Array -): Array { + values: Array +): Array { if (sortAttr === '') { return values; } /* eslint-disable-next-line functional/immutable-data */ - return values.sort((a: Delegation, b: Delegation) => { + return values.sort((a: T, b: T) => { const orderDirection = order === 'desc' ? 1 : -1; if (sortAttr === 'endDate') { const dateA = new Date(a.dateto).getTime(); @@ -51,7 +51,11 @@ export function sortDelegations( }); } -function compareDelegationsStrings(a: Delegation, b: Delegation, orderAttr: string): number { +function compareDelegationsStrings( + a: T, + b: T, + orderAttr: string +): number { if ('delegator' in a && a.delegator && 'delegator' in b && b.delegator) { const delegator1 = compareOrderAttribute(a.delegator, orderAttr); const delegator2 = compareOrderAttribute(b.delegator, orderAttr); @@ -71,7 +75,7 @@ function compareOrderAttribute(person: Person, orderAttr: string) { : person[orderAttr as keyof Person] ?? ''; } -function getFirstName(delegation: Delegation): string { +function getFirstName(delegation: T): string { if ('delegator' in delegation && delegation.delegator) { return `${delegation.delegator?.displayName}`; } else if ('delegate' in delegation && delegation.delegate) { diff --git a/packages/pn-personafisica-webapp/src/validators/CreateDelegationValidator.ts b/packages/pn-personafisica-webapp/src/validators/CreateDelegationValidator.ts index 6eeb352d59..6fd6d13502 100644 --- a/packages/pn-personafisica-webapp/src/validators/CreateDelegationValidator.ts +++ b/packages/pn-personafisica-webapp/src/validators/CreateDelegationValidator.ts @@ -1,12 +1,13 @@ import { Validator } from '@pagopa-pn/pn-validator'; -import { CreateDelegationProps } from '../redux/delegation/types'; +import { NewMandateRequest } from '../redux/delegation/types'; import { PersonValidator } from './PersonValidator'; + /** * PN-2005 - * Esempi di utilizzo della libreria pn-validator + * Esempi di utilizzo della libreria pn-validator */ -class CreateDelegationValidator extends Validator { +class CreateDelegationValidator extends Validator { constructor() { super(); this.ruleFor('delegate').isObject().setValidator(new PersonValidator()); diff --git a/packages/pn-personagiuridica-webapp/openapitools.json b/packages/pn-personagiuridica-webapp/openapitools.json index 671d120701..4c4103fb08 100644 --- a/packages/pn-personagiuridica-webapp/openapitools.json +++ b/packages/pn-personagiuridica-webapp/openapitools.json @@ -58,6 +58,17 @@ "modelPackage": "models", "cleanupOutput": true } + }, + "bff-mandate": { + "generatorName": "typescript-axios", + "inputSpec": "https://raw.githubusercontent.com/pagopa/pn-bff/develop/docs/openapi/api-external-pn-bff-recipient-mandate.yaml", + "output": "./src/generated-client/mandate", + "additionalProperties": { + "supportsES6": true, + "apiPackage": "apis", + "modelPackage": "models", + "cleanupOutput": true + } } } } diff --git a/packages/pn-personagiuridica-webapp/src/__mocks__/CreateDelegation.mock.ts b/packages/pn-personagiuridica-webapp/src/__mocks__/CreateDelegation.mock.ts index 662dcf9fd4..e39a2ce8f1 100644 --- a/packages/pn-personagiuridica-webapp/src/__mocks__/CreateDelegation.mock.ts +++ b/packages/pn-personagiuridica-webapp/src/__mocks__/CreateDelegation.mock.ts @@ -1,6 +1,6 @@ import { RecipientType } from '@pagopa-pn/pn-commons'; -import { CreateDelegationResponse, NewDelegationFormProps } from '../models/Deleghe'; +import { NewDelegationFormProps } from '../models/Deleghe'; export const createDelegationPayload: NewDelegationFormProps = { selectPersonaFisicaOrPersonaGiuridica: RecipientType.PF, @@ -20,24 +20,6 @@ export const createDelegationSelectedPayload: NewDelegationFormProps = { enti: [{ name: 'test', id: 'test' }], }; -export const createDelegationResponse: CreateDelegationResponse = { - datefrom: '2022-01-01', - dateto: '2022-01-02', - delegate: { - firstName: 'nome', - lastName: 'cognome', - displayName: 'nome cognome', - fiscalCode: 'fiscalCode', - companyName: 'companyName', - person: true, - }, - delegator: null, - mandateId: '1', - status: 'pending', - verificationCode: '00000', - visibilityIds: [], -}; - export const createDelegationGenericErrorResponse = { status: 401, }; diff --git a/packages/pn-personagiuridica-webapp/src/__mocks__/Delegations.mock.ts b/packages/pn-personagiuridica-webapp/src/__mocks__/Delegations.mock.ts index f90442b4fa..98a3be60a5 100644 --- a/packages/pn-personagiuridica-webapp/src/__mocks__/Delegations.mock.ts +++ b/packages/pn-personagiuridica-webapp/src/__mocks__/Delegations.mock.ts @@ -19,7 +19,7 @@ export const mockCreateDelegation = { dateto: '2022-04-16', }; -export const arrayOfDelegates: Array = [ +export const mandatesByDelegator: Array = [ { mandateId: '1', delegate: { @@ -64,7 +64,7 @@ export const arrayOfDelegates: Array = [ }, ]; -export const arrayOfDelegators: Array = [ +export const mandatesByDelegate: Array = [ { mandateId: '3', delegator: { diff --git a/packages/pn-personagiuridica-webapp/src/__test__/App.test.tsx b/packages/pn-personagiuridica-webapp/src/__test__/App.test.tsx index 7929f489c2..5bb7d2a581 100644 --- a/packages/pn-personagiuridica-webapp/src/__test__/App.test.tsx +++ b/packages/pn-personagiuridica-webapp/src/__test__/App.test.tsx @@ -10,7 +10,6 @@ import { userResponse } from '../__mocks__/Auth.mock'; import { tosPrivacyConsentMock } from '../__mocks__/Consents.mock'; import { digitalAddresses } from '../__mocks__/Contacts.mock'; import { apiClient } from '../api/apiClients'; -import { COUNT_DELEGATORS } from '../api/delegations/delegations.routes'; import { DelegationStatus } from '../models/Deleghe'; import { PNRole, PartyRole } from '../redux/auth/types'; import { RenderResult, act, render } from './test-utils'; @@ -93,9 +92,9 @@ describe('App', async () => { it('render component - user logged in', async () => { mock.onGet('/bff/v1/tos-privacy').reply(200, tosPrivacyConsentMock(true, true)); - mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); + mock.onGet('/bff/downtime/v1/status').reply(200, currentStatusDTO); mock.onGet('/bff/v1/addresses').reply(200, digitalAddresses); - mock.onGet(COUNT_DELEGATORS(DelegationStatus.PENDING)).reply(200, 3); + mock.onGet(`/bff/v1/mandate/delegate/count?status=${DelegationStatus.PENDING}`).reply(200, 3); let result: RenderResult; await act(async () => { result = render(, { preloadedState: reduxInitialState }); @@ -112,9 +111,9 @@ describe('App', async () => { it('sidemenu not included if error in API call to fetch TOS and privacy', async () => { mock.onGet('/bff/v1/tos-privacy').reply(500); - mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); + mock.onGet('/bff/downtime/v1/status').reply(200, currentStatusDTO); mock.onGet('/bff/v1/addresses').reply(200, digitalAddresses); - mock.onGet(COUNT_DELEGATORS(DelegationStatus.PENDING)).reply(200, 3); + mock.onGet(`/bff/v1/mandate/delegate/count?status=${DelegationStatus.PENDING}`).reply(200, 3); let result: RenderResult; await act(async () => { result = render(, { preloadedState: reduxInitialState }); @@ -127,9 +126,9 @@ describe('App', async () => { it('sidemenu not included if user has not accepted the TOS and PRIVACY', async () => { mock.onGet('/bff/v1/tos-privacy').reply(200, tosPrivacyConsentMock(false, false)); - mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); + mock.onGet('/bff/downtime/v1/status').reply(200, currentStatusDTO); mock.onGet('/bff/v1/addresses').reply(200, digitalAddresses); - mock.onGet(COUNT_DELEGATORS(DelegationStatus.PENDING)).reply(200, 3); + mock.onGet(`/bff/v1/mandate/delegate/count?status=${DelegationStatus.PENDING}`).reply(200, 3); let result: RenderResult; await act(async () => { result = render(, { preloadedState: reduxInitialState }); @@ -144,9 +143,9 @@ describe('App', async () => { it('sidemenu items if user is admin', async () => { mock.onGet('/bff/v1/tos-privacy').reply(200, tosPrivacyConsentMock(true, true)); - mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); + mock.onGet('/bff/downtime/v1/status').reply(200, currentStatusDTO); mock.onGet('/bff/v1/addresses').reply(200, digitalAddresses); - mock.onGet(COUNT_DELEGATORS(DelegationStatus.PENDING)).reply(200, 3); + mock.onGet(`/bff/v1/mandate/delegate/count?status=${DelegationStatus.PENDING}`).reply(200, 3); let result: RenderResult; await act(async () => { result = render(, { preloadedState: reduxInitialState }); @@ -162,8 +161,8 @@ describe('App', async () => { it('sidemenu items if user is a group admin', async () => { mock.onGet('/bff/v1/tos-privacy').reply(200, tosPrivacyConsentMock(true, true)); - mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); - mock.onGet(COUNT_DELEGATORS(DelegationStatus.PENDING)).reply(200, 3); + mock.onGet('/bff/downtime/v1/status').reply(200, currentStatusDTO); + mock.onGet(`/bff/v1/mandate/delegate/count?status=${DelegationStatus.PENDING}`).reply(200, 3); let result: RenderResult; await act(async () => { result = render(, { @@ -190,7 +189,7 @@ describe('App', async () => { it('sidemenu items if user is an operator', async () => { mock.onGet('/bff/v1/tos-privacy').reply(200, tosPrivacyConsentMock(true, true)); - mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); + mock.onGet('/bff/downtime/v1/status').reply(200, currentStatusDTO); let result: RenderResult; await act(async () => { result = render(, { @@ -225,7 +224,7 @@ describe('App', async () => { it('sidemenu items if user is a group operator', async () => { mock.onGet('/bff/v1/tos-privacy').reply(200, tosPrivacyConsentMock(true, true)); - mock.onGet('downtime/v1/status').reply(200, currentStatusDTO); + mock.onGet('/bff/downtime/v1/status').reply(200, currentStatusDTO); let result: RenderResult; await act(async () => { result = render(, { diff --git a/packages/pn-personagiuridica-webapp/src/api/delegations/Delegations.api.ts b/packages/pn-personagiuridica-webapp/src/api/delegations/Delegations.api.ts deleted file mode 100644 index 431aa70ebd..0000000000 --- a/packages/pn-personagiuridica-webapp/src/api/delegations/Delegations.api.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { AxiosResponse } from 'axios'; - -import { - AcceptDelegationResponse, - CreateDelegationProps, - CreateDelegationResponse, - Delegate, - Delegation, - DelegationStatus, - Delegator, - DelegatorsNames, - GetDelegatorsFilters, - GetDelegatorsResponse, -} from '../../models/Deleghe'; -import { apiClient } from '../apiClients'; -import { - ACCEPT_DELEGATION, - COUNT_DELEGATORS, - CREATE_DELEGATION, - DELEGATIONS_BY_DELEGATE, - DELEGATIONS_BY_DELEGATOR, - DELEGATIONS_NAME_BY_DELEGATE, - REJECT_DELEGATION, - REVOKE_DELEGATION, - UPDATE_DELEGATION, -} from './delegations.routes'; - -function checkResponseStatus(response: AxiosResponse, id: string) { - if (response.status === 204) { - return { id }; - } - return { id: '-1' }; -} - -export const DelegationsApi = { - /** - * Get all the delegates for the authenticated user - * @returns {Promise>} - */ - getDelegatesByCompany: (): Promise> => - apiClient - .get>(DELEGATIONS_BY_DELEGATOR()) - .then((response: AxiosResponse>) => - response.data.map((delegation) => ({ - mandateId: delegation.mandateId, - status: delegation.status, - visibilityIds: delegation.visibilityIds, - verificationCode: delegation.verificationCode, - datefrom: delegation.datefrom, - dateto: delegation.dateto, - delegate: 'delegate' in delegation ? delegation.delegate : null, - })) - ), - - /** - * Get all the delegators for the authenticated user - * @param {GetDelegatorsFilters} params - * @return {Promise} - */ - getDelegators: (params: GetDelegatorsFilters): Promise => - apiClient - .post( - DELEGATIONS_BY_DELEGATE({ size: params.size, nextPageKey: params.nextPageKey }), - { taxId: params.taxId, groups: params.groups, status: params.status } - ) - .then((response: AxiosResponse) => ({ - ...response.data, - resultsPage: response.data.resultsPage.map((delegation) => ({ - mandateId: delegation.mandateId, - status: delegation.status, - visibilityIds: delegation.visibilityIds, - verificationCode: delegation.verificationCode, - datefrom: delegation.datefrom, - dateto: delegation.dateto, - delegator: 'delegator' in delegation ? delegation.delegator : null, - groups: delegation.groups, - })), - })), - - /** - * Removes a delegation that the user created - * @param id - * @return {Promise<{id: string}>} - */ - revokeDelegation: (id: string): Promise<{ id: string }> => - apiClient - .patch(REVOKE_DELEGATION(id)) - .then((response: AxiosResponse) => checkResponseStatus(response, id)), - - /** - * Removes a delegation created for the user - * @param {string} id - * @returns {Promise<{id: string}>} - */ - rejectDelegation: (id: string): Promise<{ id: string }> => - apiClient - .patch(REJECT_DELEGATION(id)) - .then((response: AxiosResponse) => checkResponseStatus(response, id)), - - /** - * Accepts a delegation created for the user - * @param {string} id - * @param data - * @return {Promise<{id: string}>} - */ - acceptDelegation: ( - id: string, - data: { verificationCode: string; groups: Array<{ id: string; name: string }> } - ): Promise => - apiClient - .patch(ACCEPT_DELEGATION(id), { - ...data, - groups: data.groups.map((g) => g.id), - }) - .then((response: AxiosResponse) => { - if (response.status === 204) { - return { ...response.data, id, groups: data.groups }; - } - return { - id: '-1', - } as AcceptDelegationResponse; - }), - - /** - * Creates a new delegation - * @param data - * @return {Promise} - */ - createDelegation: (data: CreateDelegationProps): Promise => - apiClient - .post(CREATE_DELEGATION(), data) - .then((response: AxiosResponse) => response.data), - - /** - * Count pending delegators - * @param status status of the delegation - * @returns {Promise<{value: number}>} - */ - - countDelegators: (status: DelegationStatus): Promise<{ value: number }> => - apiClient - .get<{ value: number }>(COUNT_DELEGATORS(status)) - .then((response: AxiosResponse<{ value: number }>) => response.data), - - /** - * Get all the delegators names for the authenticated user - * @param {GetDelegatorsFilters} params - * @return {Promise} - * @deprecated since pn-5795 - */ - getDelegatorsNames: (): Promise> => - apiClient - .get>(DELEGATIONS_NAME_BY_DELEGATE()) - .then((response: AxiosResponse>) => { - if (response.data) { - return response.data.reduce((arr, delegator) => { - /* eslint-disable functional/immutable-data */ - const isInArray = arr.findIndex((elem) => elem.id === delegator.delegator?.fiscalCode); - if (isInArray > -1) { - arr[isInArray].mandateIds.push(delegator.mandateId); - return arr; - } - arr.push({ - id: delegator.delegator?.fiscalCode || '', - name: delegator.delegator?.displayName || '', - mandateIds: [delegator.mandateId], - }); - return arr; - /* eslint-enable functional/immutable-data */ - }, [] as Array); - } - return []; - }), - - /** - * Update a delegation created for the user - * @param {string} id - * @param data - * @return {Promise<{id: string}>} - */ - updateDelegation: ( - id: string, - groups: Array<{ id: string; name: string }> - ): Promise => - apiClient - .patch(UPDATE_DELEGATION(id), { - groups: groups.map((g) => g.id), - }) - .then((response: AxiosResponse) => { - if (response.status === 204) { - return { ...response.data, id, groups }; - } - return { - id: '-1', - } as AcceptDelegationResponse; - }), -}; diff --git a/packages/pn-personagiuridica-webapp/src/api/delegations/__test__/Delegations.api.test.ts b/packages/pn-personagiuridica-webapp/src/api/delegations/__test__/Delegations.api.test.ts deleted file mode 100644 index 9439f39dfb..0000000000 --- a/packages/pn-personagiuridica-webapp/src/api/delegations/__test__/Delegations.api.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import MockAdapter from 'axios-mock-adapter'; - -import { mockAuthentication } from '../../../__mocks__/Auth.mock'; -import { - arrayOfDelegates, - arrayOfDelegators, - mockCreateDelegation, -} from '../../../__mocks__/Delegations.mock'; -import { DelegationStatus } from '../../../models/Deleghe'; -import { apiClient } from '../../apiClients'; -import { DelegationsApi } from '../Delegations.api'; -import { - ACCEPT_DELEGATION, - COUNT_DELEGATORS, - CREATE_DELEGATION, - DELEGATIONS_BY_DELEGATE, - DELEGATIONS_BY_DELEGATOR, - REJECT_DELEGATION, - REVOKE_DELEGATION, - UPDATE_DELEGATION, -} from '../delegations.routes'; - -describe('Delegations api tests', () => { - let mock: MockAdapter; - - mockAuthentication(); - - beforeAll(() => { - mock = new MockAdapter(apiClient); - }); - - afterEach(() => { - mock.reset(); - }); - - afterAll(() => { - mock.restore(); - }); - - it('gets non empty delegates', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, arrayOfDelegates); - const res = await DelegationsApi.getDelegatesByCompany(); - expect(res).toStrictEqual(arrayOfDelegates); - }); - - it('gets empty delegates', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, []); - const res = await DelegationsApi.getDelegatesByCompany(); - expect(res).toHaveLength(0); - }); - - it('gets non empty delegators', async () => { - mock.onPost(DELEGATIONS_BY_DELEGATE({ size: 10 })).reply(200, { - resultsPage: arrayOfDelegators, - moreResult: false, - nextPagesKey: [], - }); - const res = await DelegationsApi.getDelegators({ size: 10 }); - expect(res.resultsPage).toStrictEqual(arrayOfDelegators); - }); - - it('gets empty delegators', async () => { - mock.onPost(DELEGATIONS_BY_DELEGATE({ size: 10 })).reply(200, { - resultsPage: [], - moreResult: false, - nextPagesKey: [], - }); - const res = await DelegationsApi.getDelegators({ size: 10 }); - expect(res.resultsPage).toHaveLength(0); - }); - - it('revokes a delegation', async () => { - mock.onPatch(REVOKE_DELEGATION('7')).reply(204, { id: '7' }); - const res = await DelegationsApi.revokeDelegation('7'); - expect(res).toStrictEqual({ id: '7' }); - }); - - it("doesn't revoke a delegation", async () => { - mock.onPatch(REVOKE_DELEGATION('10')).reply(200); - const res = await DelegationsApi.revokeDelegation('10'); - expect(res).toStrictEqual({ id: '-1' }); - }); - - it('rejects a delegation', async () => { - mock.onPatch(REJECT_DELEGATION('8')).reply(204); - const res = await DelegationsApi.rejectDelegation('8'); - expect(res).toStrictEqual({ id: '8' }); - }); - - it("doesn't reject a delegation", async () => { - mock.onPatch(REJECT_DELEGATION('10')).reply(200); - const res = await DelegationsApi.rejectDelegation('10'); - expect(res).toStrictEqual({ id: '-1' }); - }); - - it('accept a delegation', async () => { - mock.onPatch(ACCEPT_DELEGATION('9')).reply(204); - const res = await DelegationsApi.acceptDelegation('9', { - verificationCode: '12345', - groups: [{ id: 'group-1', name: 'Group 1' }], - }); - expect(res).toStrictEqual({ id: '9', groups: [{ id: 'group-1', name: 'Group 1' }] }); - }); - - it('creates a new delegation', async () => { - mock.onPost(CREATE_DELEGATION(), mockCreateDelegation).reply(200, mockCreateDelegation); - const res = await DelegationsApi.createDelegation(mockCreateDelegation); - expect(res).toStrictEqual(mockCreateDelegation); - }); - - it('count delegators', async () => { - mock.onGet(COUNT_DELEGATORS(DelegationStatus.PENDING)).reply(200, { value: 5 }); - const res = await DelegationsApi.countDelegators(DelegationStatus.PENDING); - expect(res).toStrictEqual({ value: 5 }); - }); - - it('update a delegation', async () => { - mock.onPatch(UPDATE_DELEGATION('9')).reply(204, { id: '9' }); - const res = await DelegationsApi.updateDelegation('9', [{ id: 'group-1', name: 'Group 1' }]); - expect(res).toStrictEqual({ id: '9', groups: [{ id: 'group-1', name: 'Group 1' }] }); - }); -}); diff --git a/packages/pn-personagiuridica-webapp/src/api/delegations/__test__/delegations.routes.test.ts b/packages/pn-personagiuridica-webapp/src/api/delegations/__test__/delegations.routes.test.ts deleted file mode 100644 index 55bc41c617..0000000000 --- a/packages/pn-personagiuridica-webapp/src/api/delegations/__test__/delegations.routes.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { DelegationStatus } from '../../../models/Deleghe'; -import { - ACCEPT_DELEGATION, - COUNT_DELEGATORS, - CREATE_DELEGATION, - DELEGATIONS_BY_DELEGATE, - DELEGATIONS_BY_DELEGATOR, - DELEGATIONS_NAME_BY_DELEGATE, - REJECT_DELEGATION, - REVOKE_DELEGATION, - UPDATE_DELEGATION, -} from '../delegations.routes'; - -describe('Delegations routes', () => { - it('should compile DELEGATIONS_BY_DELEGATOR', () => { - const route = DELEGATIONS_BY_DELEGATOR(); - expect(route).toEqual(`/mandate/api/v1/mandates-by-delegator`); - }); - - it('should compile DELEGATIONS_BY_DELEGATE', () => { - const route = DELEGATIONS_BY_DELEGATE({ size: 10 }); - expect(route).toEqual(`/mandate/api/v1/mandates-by-delegate?size=10`); - }); - - it('should compile CREATE_DELEGATION', () => { - const route = CREATE_DELEGATION(); - expect(route).toEqual(`/mandate/api/v1/mandate`); - }); - - it('should compile REVOKE_DELEGATION', () => { - const route = REVOKE_DELEGATION('mocked-id'); - expect(route).toEqual(`/mandate/api/v1/mandate/mocked-id/revoke`); - }); - - it('should compile REJECT_DELEGATION', () => { - const route = REJECT_DELEGATION('mocked-id'); - expect(route).toEqual(`/mandate/api/v1/mandate/mocked-id/reject`); - }); - - it('should compile ACCEPT_DELEGATION', () => { - const route = ACCEPT_DELEGATION('mocked-id'); - expect(route).toEqual(`/mandate/api/v1/mandate/mocked-id/accept`); - }); - - it('should compile COUNT_DELEGATORS', () => { - const route = COUNT_DELEGATORS(DelegationStatus.ACTIVE); - expect(route).toEqual(`/mandate/api/v1/count-by-delegate?status=active`); - }); - - it('should compile DELEGATIONS_NAME_BY_DELEGATE', () => { - const route = DELEGATIONS_NAME_BY_DELEGATE(); - expect(route).toEqual(`/mandate/api/v1/mandates-by-delegate`); - }); - - it('should compile UPDATE_DELEGATION', () => { - const route = UPDATE_DELEGATION('mocked-id'); - expect(route).toEqual(`/mandate/api/v1/mandate/mocked-id/update`); - }); -}); diff --git a/packages/pn-personagiuridica-webapp/src/api/delegations/delegations.routes.ts b/packages/pn-personagiuridica-webapp/src/api/delegations/delegations.routes.ts deleted file mode 100644 index 7f25f6e9a3..0000000000 --- a/packages/pn-personagiuridica-webapp/src/api/delegations/delegations.routes.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { compileRoute } from '@pagopa-pn/pn-commons'; - -import { DelegationStatus, GetDelegatorsParams } from '../../models/Deleghe'; - -// Prefixes -const API_DELEGATIONS_PREFIX = 'mandate'; - -// Segments -const API_SEGMENT = 'api'; -const API_VERSION_SEGMENT = 'v1'; -const API_DELEGATIONS_MANDATES_BY_DELEGATOR = 'mandates-by-delegator'; -const API_DELEGATIONS_MANDATES_BY_DELEGATE = 'mandates-by-delegate'; -const API_DELEGATIONS_MANDATE = 'mandate'; -const API_DELEGATIONS_REVOKE = 'revoke'; -const API_DELEGATIONS_REJECT = 'reject'; -const API_DELEGATIONS_ACCEPT = 'accept'; -const API_DELEGATIONS_COUNT_BY_DELEGATE = 'count-by-delegate'; -const API_DELEGATIONS_UPDATE = 'update'; - -// Parameters -const API_DELEGATIONS_ID_PARAMETER = 'id'; -const API_DELEGATIONS_SIZE_PARAMETER = 'size'; -const API_DELEGATIONS_NEXT_PAGES_KEY_PARAMETER = 'nextPageKey'; -const API_DELEGATIONS_STATUS_PARAMETER = 'status'; - -// Paths -const API_DELEGATIONS_BASE_PATH = `${API_SEGMENT}/${API_VERSION_SEGMENT}`; -const API_DELEGATIONS_MANDATES_BY_DELEGATOR_PATH = `${API_DELEGATIONS_BASE_PATH}/${API_DELEGATIONS_MANDATES_BY_DELEGATOR}`; -const API_DELEGATIONS_MANDATES_BY_DELEGATE_PATH = `${API_DELEGATIONS_BASE_PATH}/${API_DELEGATIONS_MANDATES_BY_DELEGATE}`; -const API_DELEGATIONS_MANDATE_BASE_PATH = `${API_SEGMENT}/${API_VERSION_SEGMENT}/${API_DELEGATIONS_MANDATE}`; -const API_DELEGATIONS_MANDATE_REVOKE_PATH = `${API_DELEGATIONS_MANDATE_BASE_PATH}/:${API_DELEGATIONS_ID_PARAMETER}/${API_DELEGATIONS_REVOKE}`; -const API_DELEGATIONS_MANDATE_REJECT_PATH = `${API_DELEGATIONS_MANDATE_BASE_PATH}/:${API_DELEGATIONS_ID_PARAMETER}/${API_DELEGATIONS_REJECT}`; -const API_DELEGATIONS_MANDATE_ACCEPT_PATH = `${API_DELEGATIONS_MANDATE_BASE_PATH}/:${API_DELEGATIONS_ID_PARAMETER}/${API_DELEGATIONS_ACCEPT}`; -const API_DELEGATIONS_COUNT_BY_DELEGATE_PATH = `${API_DELEGATIONS_BASE_PATH}/${API_DELEGATIONS_COUNT_BY_DELEGATE}`; -const API_DELEGATIONS_MANDATE_UPDATE_PATH = `${API_DELEGATIONS_MANDATE_BASE_PATH}/:${API_DELEGATIONS_ID_PARAMETER}/${API_DELEGATIONS_UPDATE}`; - -// APIs -export function DELEGATIONS_BY_DELEGATOR() { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATES_BY_DELEGATOR_PATH, - }); -} - -export function DELEGATIONS_BY_DELEGATE(params: GetDelegatorsParams) { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATES_BY_DELEGATE_PATH, - query: { - [API_DELEGATIONS_SIZE_PARAMETER]: params.size ? params.size.toString() : '', - [API_DELEGATIONS_NEXT_PAGES_KEY_PARAMETER]: params.nextPageKey || '', - }, - }); -} - -export function CREATE_DELEGATION() { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATE_BASE_PATH, - }); -} - -export function REVOKE_DELEGATION(id: string) { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATE_REVOKE_PATH, - params: { - [API_DELEGATIONS_ID_PARAMETER]: id, - }, - }); -} - -export function REJECT_DELEGATION(id: string) { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATE_REJECT_PATH, - params: { - [API_DELEGATIONS_ID_PARAMETER]: id, - }, - }); -} - -export function ACCEPT_DELEGATION(id: string) { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATE_ACCEPT_PATH, - params: { - [API_DELEGATIONS_ID_PARAMETER]: id, - }, - }); -} - -export function COUNT_DELEGATORS(status: DelegationStatus | Array) { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_COUNT_BY_DELEGATE_PATH, - query: { - [API_DELEGATIONS_STATUS_PARAMETER]: status, - }, - }); -} - -export function DELEGATIONS_NAME_BY_DELEGATE() { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATES_BY_DELEGATE_PATH, - }); -} - -export function UPDATE_DELEGATION(id: string) { - return compileRoute({ - prefix: API_DELEGATIONS_PREFIX, - path: API_DELEGATIONS_MANDATE_UPDATE_PATH, - params: { - [API_DELEGATIONS_ID_PARAMETER]: id, - }, - }); -} diff --git a/packages/pn-personagiuridica-webapp/src/components/Deleghe/AcceptDelegationModal.tsx b/packages/pn-personagiuridica-webapp/src/components/Deleghe/AcceptDelegationModal.tsx index 2b1781d499..03dce7348d 100644 --- a/packages/pn-personagiuridica-webapp/src/components/Deleghe/AcceptDelegationModal.tsx +++ b/packages/pn-personagiuridica-webapp/src/components/Deleghe/AcceptDelegationModal.tsx @@ -111,12 +111,12 @@ const AcceptDelegationModal: React.FC = ({ useEffect(() => { // code validation is done only during acceptance and not during update if (!isEditMode) { - AppResponsePublisher.error.subscribe('acceptDelegation', handleAcceptanceError); + AppResponsePublisher.error.subscribe('acceptMandate', handleAcceptanceError); } return () => { if (!isEditMode) { - AppResponsePublisher.error.unsubscribe('acceptDelegation', handleAcceptanceError); + AppResponsePublisher.error.unsubscribe('acceptMandate', handleAcceptanceError); } }; }, [handleAcceptanceError]); diff --git a/packages/pn-personagiuridica-webapp/src/components/Deleghe/DelegatesByCompany.tsx b/packages/pn-personagiuridica-webapp/src/components/Deleghe/DelegatesByCompany.tsx index 50bdaa26a7..5884820f0e 100644 --- a/packages/pn-personagiuridica-webapp/src/components/Deleghe/DelegatesByCompany.tsx +++ b/packages/pn-personagiuridica-webapp/src/components/Deleghe/DelegatesByCompany.tsx @@ -22,7 +22,7 @@ import { import { DelegationColumnData } from '../../models/Deleghe'; import * as routes from '../../navigation/routes.const'; -import { DELEGATION_ACTIONS, getDelegatesByCompany } from '../../redux/delegation/actions'; +import { DELEGATION_ACTIONS, getMandatesByDelegator } from '../../redux/delegation/actions'; import { useAppDispatch, useAppSelector } from '../../redux/hooks'; import { RootState } from '../../redux/store'; import delegationToItem from '../../utility/delegation.utility'; @@ -165,8 +165,8 @@ const DelegatesByCompany = () => { dispatch(getDelegatesByCompany())} + apiId={DELEGATION_ACTIONS.GET_MANDATES_BY_DELEGATOR} + reloadAction={() => dispatch(getMandatesByDelegator())} > {delegatesByCompany.length > 0 ? ( = ({ menuType, id, userLogged, row, onAction }; const handleConfirmClick = () => { - const actionToDispatch = menuType === 'delegates' ? revokeDelegation : rejectDelegation; + const actionToDispatch = menuType === 'delegates' ? revokeMandate : rejectMandate; const message = menuType === 'delegates' ? t('deleghe.revoke-successfully') @@ -151,7 +151,7 @@ export const Menu: React.FC = ({ menuType, id, userLogged, row, onAction }, []); const handleUpdate = (_code: Array, groups: Array<{ id: string; name: string }>) => { - void dispatch(updateDelegation({ id, groups })) + void dispatch(updateMandate({ id, groups })) .unwrap() .then(() => { dispatch( @@ -168,16 +168,16 @@ export const Menu: React.FC = ({ menuType, id, userLogged, row, onAction }; useEffect(() => { - const action = menuType === 'delegates' ? 'revokeDelegation' : 'rejectDelegation'; + const action = menuType === 'delegates' ? 'revokeMandate' : 'rejectMandate'; AppResponsePublisher.error.subscribe(action, handleConfirmationError); if (menuType === 'delegators' && groups.length) { - AppResponsePublisher.error.subscribe('updateDelegation', handleUpdateError); + AppResponsePublisher.error.subscribe('updateMandate', handleUpdateError); } return () => { AppResponsePublisher.error.unsubscribe(action, handleConfirmationError); if (menuType === 'delegators' && groups.length) { - AppResponsePublisher.error.unsubscribe('updateDelegation', handleUpdateError); + AppResponsePublisher.error.unsubscribe('updateMandate', handleUpdateError); } }; }, [handleConfirmationError]); @@ -331,7 +331,7 @@ export const AcceptButton: React.FC = ({ id, name, onAccept } }; const handleConfirm = (code: Array, groups: Array<{ id: string; name: string }>) => { - void dispatch(acceptDelegation({ id, code: code.join(''), groups })) + void dispatch(acceptMandate({ id, code: code.join(''), groups })) .unwrap() .then(async () => { dispatch( @@ -351,10 +351,10 @@ export const AcceptButton: React.FC = ({ id, name, onAccept } ); useEffect(() => { - AppResponsePublisher.error.subscribe('acceptDelegation', handleAcceptanceError); + AppResponsePublisher.error.subscribe('acceptMandate', handleAcceptanceError); return () => { - AppResponsePublisher.error.unsubscribe('acceptDelegation', handleAcceptanceError); + AppResponsePublisher.error.unsubscribe('acceptMandate', handleAcceptanceError); }; }, [handleAcceptanceError]); diff --git a/packages/pn-personagiuridica-webapp/src/components/Deleghe/DelegationsOfTheCompany.tsx b/packages/pn-personagiuridica-webapp/src/components/Deleghe/DelegationsOfTheCompany.tsx index dfb8de94ef..762b1f8938 100644 --- a/packages/pn-personagiuridica-webapp/src/components/Deleghe/DelegationsOfTheCompany.tsx +++ b/packages/pn-personagiuridica-webapp/src/components/Deleghe/DelegationsOfTheCompany.tsx @@ -45,7 +45,7 @@ import { GetDelegatorsFilters, } from '../../models/Deleghe'; import { GroupStatus } from '../../models/groups'; -import { DELEGATION_ACTIONS, getDelegators } from '../../redux/delegation/actions'; +import { DELEGATION_ACTIONS, searchMandatesByDelegate } from '../../redux/delegation/actions'; import { setFilters } from '../../redux/delegation/reducers'; import { useAppDispatch, useAppSelector } from '../../redux/hooks'; import { RootState } from '../../redux/store'; @@ -309,7 +309,7 @@ const DelegationsOfTheCompany = () => { groups: filters.groups, status: filters.status, } as GetDelegatorsFilters; - void dispatch(getDelegators(delegatorsFilters)); + void dispatch(searchMandatesByDelegate(delegatorsFilters)); }; useEffect(() => { @@ -327,8 +327,8 @@ const DelegationsOfTheCompany = () => { {t('deleghe.delegatorsTitle')} dispatch(getDelegators(filters))} + apiId={DELEGATION_ACTIONS.SEARCH_MANDATES_BY_DELEGATE} + reloadAction={() => dispatch(searchMandatesByDelegate(filters))} mainText={t('deleghe.delegatorsApiErrorMessage')} > {rows.length > 0 || !_.isEqual({ size: 10, page: 0 }, filters) ? ( diff --git a/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/AcceptDelegationModal.test.tsx b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/AcceptDelegationModal.test.tsx new file mode 100644 index 0000000000..ca6a50d7fb --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/AcceptDelegationModal.test.tsx @@ -0,0 +1,267 @@ +import { vi } from 'vitest'; + +import { testAutocomplete } from '@pagopa-pn/pn-commons/src/test-utils'; + +import { fireEvent, render, screen, waitFor, within } from '../../../__test__/test-utils'; +import AcceptDelegationModal from '../AcceptDelegationModal'; + +vi.mock('react-i18next', () => ({ + // this mock makes sure any components using the translate hook can use it without a warning being shown + useTranslation: () => ({ + t: (str: string) => str, + }), +})); + +const confirmCbk = vi.fn(); +const cancelCbk = vi.fn(); + +describe('AcceptDelegationModal', () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it('renders CodeModal', async () => { + render( + + ); + const dialog = screen.getByTestId('codeDialog') as Element; + expect(dialog).toBeInTheDocument(); + }); + + it('calls cancel callback - codeModal', () => { + render( + + ); + const dialog = screen.getByTestId('codeDialog'); + const codeConfirmButton = within(dialog).getByTestId('codeConfirmButton'); + const codeCancelButton = within(dialog).getByTestId('codeCancelButton'); + expect(codeConfirmButton).toBeDisabled(); + fireEvent.click(codeCancelButton); + expect(cancelCbk).toBeCalledTimes(1); + }); + + it('renders GroupModal - no groups selected', () => { + render( + + ); + const dialog = screen.getByTestId('groupDialog'); + expect(dialog).toBeInTheDocument(); + const noGroupRadio = dialog.querySelector('[data-testid="no-group"] input'); + expect(noGroupRadio).toBeChecked(); + }); + + it('renders GroupModal - groups selected', () => { + const groups = [ + { id: 'group-1', name: 'Group 1' }, + { id: 'group-2', name: 'Group 2' }, + ]; + render( + , + { + preloadedState: { + delegationsState: { + groups, + }, + }, + } + ); + const dialog = screen.getByTestId('groupDialog'); + expect(dialog).toBeInTheDocument(); + const associateGroupRadio = dialog.querySelector('[data-testid="associate-group"] input'); + expect(associateGroupRadio).toBeChecked(); + const autocomplete = within(dialog).getByTestId(`groups`); + expect(autocomplete).toHaveTextContent(groups[1].name); + }); + + it('calls cancel callback - groupModal', () => { + render( + + ); + const dialog = screen.getByTestId('groupDialog'); + const groupConfirmButton = within(dialog).getByTestId('groupConfirmButton'); + const groupCancelButton = within(dialog).getByTestId('groupCancelButton'); + expect(groupConfirmButton).toBeEnabled(); + expect(groupCancelButton).toHaveTextContent('button.annulla'); + fireEvent.click(groupCancelButton); + expect(cancelCbk).toBeCalledTimes(1); + }); + + it('selects groups - groupModal', async () => { + const groups = [ + { id: 'group-1', name: 'Group 1', status: 'ACTIVE' }, + { id: 'group-2', name: 'Group 2', status: 'ACTIVE' }, + ]; + render( + , + { + preloadedState: { + delegationsState: { + groups, + }, + }, + } + ); + const dialog = screen.getByTestId('groupDialog'); + const groupConfirmButton = within(dialog).getByTestId('groupConfirmButton'); + const associateGroupRadio = within(dialog).getByTestId('associate-group'); + fireEvent.click(associateGroupRadio); + await testAutocomplete(dialog, 'groups', groups, true, 1); + expect(groupConfirmButton).toBeEnabled(); + fireEvent.click(groupConfirmButton); + expect(confirmCbk).toBeCalledTimes(1); + expect(confirmCbk).toBeCalledWith([], [groups[1]]); + }); + + it('fills the code, go next step and returns back', async () => { + const groups = [ + { id: 'group-1', name: 'Group 1' }, + { id: 'group-2', name: 'Group 2' }, + ]; + render( + , + { + preloadedState: { + delegationsState: { + groups, + }, + }, + } + ); + let codeDialog = screen.getByTestId('codeDialog'); + const codeConfirmButton = within(codeDialog).getByTestId('codeConfirmButton'); + expect(codeConfirmButton).toBeDisabled(); + const codeInputs = codeDialog.querySelectorAll('input'); + codeInputs.forEach((input, index) => { + fireEvent.change(input, { target: { value: index.toString() } }); + }); + expect(codeConfirmButton).toBeEnabled(); + // got to next step + fireEvent.click(codeConfirmButton); + const groupDialog = await waitFor(() => screen.findByTestId('groupDialog')); + expect(codeDialog).not.toBeInTheDocument(); + expect(groupDialog).toBeInTheDocument(); + // go to previous step and check that inputs are filled with previous values + const groupCancelButton = within(groupDialog).getByTestId('groupCancelButton'); + expect(groupCancelButton).toHaveTextContent('button.indietro'); + fireEvent.click(groupCancelButton); + await waitFor(() => { + codeDialog = screen.getByTestId('codeDialog'); + expect(groupDialog).not.toBeInTheDocument(); + }); + expect(codeDialog).toBeInTheDocument(); + codeInputs.forEach((input, index) => { + expect(input).toHaveValue(index.toString()); + }); + }); + + it('fills the code and confirm - no groups', async () => { + render( + + ); + const codeDialog = screen.getByTestId('codeDialog'); + const codeConfirmButton = within(codeDialog).getByTestId('codeConfirmButton'); + expect(codeConfirmButton).toBeDisabled(); + const codeInputs = codeDialog.querySelectorAll('input'); + codeInputs.forEach((input, index) => { + fireEvent.change(input, { target: { value: index.toString() } }); + }); + expect(codeConfirmButton).toBeEnabled(); + fireEvent.click(codeConfirmButton); + expect(confirmCbk).toBeCalledTimes(1); + expect(confirmCbk).toBeCalledWith(['0', '1', '2', '3', '4'], []); + }); + + it('fills the code, go next step, choose groups and confirm', async () => { + const groups = [ + { id: 'group-1', name: 'Group 1', status: 'ACTIVE' }, + { id: 'group-2', name: 'Group 2', status: 'ACTIVE' }, + ]; + render( + , + { + preloadedState: { + delegationsState: { + groups, + }, + }, + } + ); + const codeDialog = screen.getByTestId('codeDialog'); + const codeConfirmButton = within(codeDialog).getByTestId('codeConfirmButton'); + expect(codeConfirmButton).toBeDisabled(); + const codeInputs = codeDialog.querySelectorAll('input'); + codeInputs.forEach((input, index) => { + fireEvent.change(input, { target: { value: index.toString() } }); + }); + expect(codeConfirmButton).toBeEnabled(); + // got to next step + fireEvent.click(codeConfirmButton); + const groupDialog = await waitFor(() => screen.findByTestId('groupDialog')); + expect(codeDialog).not.toBeInTheDocument(); + expect(groupDialog).toBeInTheDocument(); + const associateGroupRadio = await waitFor(() => + within(groupDialog).getByTestId('associate-group') + ); + fireEvent.click(associateGroupRadio); + await testAutocomplete(groupDialog, 'groups', groups, true, 1); + const groupConfirmButton = within(groupDialog).getByTestId('groupConfirmButton'); + fireEvent.click(groupConfirmButton); + expect(confirmCbk).toBeCalledTimes(1); + expect(confirmCbk).toBeCalledWith(['0', '1', '2', '3', '4'], [groups[1]]); + }); +}); diff --git a/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/ConfirmationModal.test.tsx b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/ConfirmationModal.test.tsx new file mode 100644 index 0000000000..bd3fc9b567 --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/ConfirmationModal.test.tsx @@ -0,0 +1,78 @@ +import { vi } from 'vitest'; + +import { fireEvent, render } from '../../../__test__/test-utils'; +import ConfirmationModal from '../ConfirmationModal'; + +const mockCancelFunction = vi.fn(); +const mockConfirmFunction = vi.fn(); + +describe('ConfirmationModal Component', () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + it('renders the component', () => { + const { getByRole, getAllByTestId } = render( + + ); + const dialog = getByRole('dialog'); + expect(dialog).toBeInTheDocument(); + expect(dialog).toHaveTextContent(/Test Title/i); + const dialogActions = getAllByTestId('dialogAction'); + expect(dialogActions).toHaveLength(2); + expect(dialogActions[1]).toHaveTextContent(/Confirm/i); + expect(dialogActions[0]).toHaveTextContent(/Cancel/i); + }); + + it('checks that the confirm and cancel functions are executed', () => { + const { getAllByTestId } = render( + + ); + const dialogActions = getAllByTestId('dialogAction'); + const confirm = dialogActions[1]; + const cancel = dialogActions[0]; + fireEvent.click(confirm); + expect(mockConfirmFunction).toBeCalledTimes(1); + fireEvent.click(cancel); + expect(mockCancelFunction).toBeCalledTimes(1); + }); + + it('renders the dialog with default labels', () => { + const { getAllByTestId } = render( + + ); + const dialogActions = getAllByTestId('dialogAction'); + const confirm = dialogActions[1]; + const cancel = dialogActions[0]; + expect(confirm).toHaveTextContent(/Riprova/i); + expect(cancel).toHaveTextContent(/Annulla/i); + }); + + it('renders the dialog with no confirm button', () => { + const { getAllByTestId } = render( + + ); + const dialogActions = getAllByTestId('dialogAction'); + expect(dialogActions).toHaveLength(1); + expect(dialogActions[0]).toHaveTextContent(/Annulla/i); + }); +}); diff --git a/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegatesByCompany.test.tsx b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegatesByCompany.test.tsx new file mode 100644 index 0000000000..4e73e0ca75 --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegatesByCompany.test.tsx @@ -0,0 +1,164 @@ +import MockAdapter from 'axios-mock-adapter'; +import { ReactNode } from 'react'; +import { vi } from 'vitest'; + +import { mandatesByDelegator } from '../../../__mocks__/Delegations.mock'; +import { fireEvent, render, waitFor, within } from '../../../__test__/test-utils'; +import { apiClient } from '../../../api/apiClients'; +import * as routes from '../../../navigation/routes.const'; +import DelegatesByCompany from '../DelegatesByCompany'; + +const mockNavigateFn = vi.fn(); + +vi.mock('react-i18next', () => ({ + // this mock makes sure any components using the translate hook can use it without a warning being shown + useTranslation: () => ({ + t: (str: string) => str, + }), + Trans: (props: { i18nKey: string; components?: Array }) => ( + <> + {props.i18nKey} {props.components!.map((c) => c)} + + ), +})); + +vi.mock('react-router-dom', async () => ({ + ...(await vi.importActual('react-router-dom')), + useNavigate: () => mockNavigateFn, +})); + +describe('Delegates Component - assuming delegates API works properly', async () => { + let mock: MockAdapter; + + beforeAll(() => { + mock = new MockAdapter(apiClient); + }); + + afterEach(() => { + mock.reset(); + vi.clearAllMocks(); + }); + + afterAll(() => { + vi.clearAllMocks(); + mock.restore(); + }); + + it('renders the empty state', () => { + const { container, getByTestId } = render(, { + preloadedState: { + delegationsState: { + delegations: { + delegates: [], + }, + }, + }, + }); + expect(container).toHaveTextContent(/deleghe.delegatesTitle/i); + const addButton = getByTestId('addDeleghe'); + expect(addButton).toBeInTheDocument(); + expect(container).toHaveTextContent(/deleghe.add/i); + expect(container).toHaveTextContent(/deleghe.no_delegates/i); + // clicks on empty state action + const button = getByTestId('link-add-delegate'); + fireEvent.click(button); + expect(mockNavigateFn).toBeCalledTimes(1); + expect(mockNavigateFn).toBeCalledWith(routes.NUOVA_DELEGA); + }); + + it('render table with data', async () => { + const { container, getByTestId, getAllByTestId } = render(, { + preloadedState: { + delegationsState: { + delegations: { + delegates: mandatesByDelegator, + }, + }, + }, + }); + expect(container).not.toHaveTextContent(/deleghe.no_delegates/i); + const table = getByTestId('delegatesTableDesktop'); + expect(table).toBeInTheDocument(); + const rows = getAllByTestId('delegatesBodyRowDesktop'); + expect(rows).toHaveLength(mandatesByDelegator.length); + rows.forEach((row, index) => { + expect(row).toHaveTextContent(mandatesByDelegator[index].delegate?.displayName!); + }); + }); + + it('clicks on add button and navigate to new delegation page', () => { + const { getByTestId } = render(); + const addButton = getByTestId('addDeleghe'); + fireEvent.click(addButton); + expect(mockNavigateFn).toBeCalledTimes(1); + expect(mockNavigateFn).toBeCalledWith(routes.NUOVA_DELEGA); + }); + + it('visualize modal code and check code', async () => { + const { getAllByTestId, getByTestId } = render(, { + preloadedState: { + delegationsState: { + delegations: { + delegates: mandatesByDelegator, + }, + }, + }, + }); + const menu = getAllByTestId('delegationMenuIcon'); + fireEvent.click(menu[0]); + const menuOpen = await waitFor(async () => getByTestId('delegationMenu')); + const menuItems = menuOpen.querySelectorAll('[role="menuitem"]'); + expect(menuItems).toHaveLength(2); + expect(menuItems[0]).toHaveTextContent(/deleghe.show/i); + fireEvent.click(menuItems[0]); + await waitFor(() => { + const dialog = getByTestId('codeDialog'); + const arrayOfVerificationCode = mandatesByDelegator[0].verificationCode.split(''); + const codeInputs = dialog?.querySelectorAll('input'); + codeInputs?.forEach((input, index) => { + expect(input).toHaveValue(arrayOfVerificationCode[index]); + }); + }); + }); + + it('revoke mandate', async () => { + mock.onPatch(`/bff/v1/mandate/${mandatesByDelegator[0].mandateId}/revoke`).reply(204); + const { getAllByTestId, getByTestId } = render(, { + preloadedState: { + delegationsState: { + delegations: { + delegates: mandatesByDelegator, + delegators: [], + }, + }, + }, + }); + const menu = getAllByTestId('delegationMenuIcon'); + fireEvent.click(menu[0]); + const menuOpen = await waitFor(async () => getByTestId('delegationMenu')); + const menuItems = menuOpen.querySelectorAll('[role="menuitem"]'); + expect(menuItems).toHaveLength(2); + expect(menuItems[1]).toHaveTextContent(/deleghe.revoke/i); + fireEvent.click(menuItems[1]); + const dialog = await waitFor(() => getByTestId('confirmationDialog')); + expect(dialog).toBeInTheDocument(); + const dialogAction = within(dialog).getAllByTestId('dialogAction'); + // click on confirm button + fireEvent.click(dialogAction[1]); + await waitFor(() => { + expect(mock.history.patch.length).toBe(1); + expect(mock.history.patch[0].url).toContain( + `/bff/v1/mandate/${mandatesByDelegator[0].mandateId}/revoke` + ); + expect(dialog).not.toBeInTheDocument(); + }); + const table = getByTestId('delegatesTableDesktop'); + expect(table).toBeInTheDocument(); + const rows = getAllByTestId('delegatesBodyRowDesktop'); + expect(rows).toHaveLength(mandatesByDelegator.length - 1); + // the index + 1 is because wie revoke the first delegation + rows.forEach((row, index) => { + expect(row).toHaveTextContent(mandatesByDelegator[index + 1].delegate?.displayName!); + }); + }); +}); diff --git a/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegationDataSwitch.test.tsx b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegationDataSwitch.test.tsx new file mode 100644 index 0000000000..d31139a122 --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegationDataSwitch.test.tsx @@ -0,0 +1,123 @@ +import { vi } from 'vitest'; + +import { Row } from '@pagopa-pn/pn-commons'; + +import { mandatesByDelegate } from '../../../__mocks__/Delegations.mock'; +import { render } from '../../../__test__/test-utils'; +import { DelegationColumnData } from '../../../models/Deleghe'; +import delegationToItem from '../../../utility/delegation.utility'; +import { DelegationStatus, getDelegationStatusKeyAndColor } from '../../../utility/status.utility'; +import DelegationDataSwitch from '../DelegationDataSwitch'; + +vi.mock('react-i18next', () => ({ + // this mock makes sure any components using the translate hook can use it without a warning being shown + useTranslation: () => ({ + t: (str: string) => str, + }), +})); + +const data = { + ...(delegationToItem(mandatesByDelegate)[0] as Row), +}; + +describe('DowntimeLogDataSwitch Component', () => { + it('renders component - name', () => { + const { container } = render( + {}} /> + ); + const regexp = new RegExp(`^${data.name}$`, 'ig'); + expect(container).toHaveTextContent(regexp); + }); + + it('renders component - startDate', () => { + const { container } = render( + {}} + /> + ); + const regexp = new RegExp(`^${data.startDate}$`, 'ig'); + expect(container).toHaveTextContent(regexp); + }); + + it('renders component - endDate', () => { + const { container } = render( + {}} /> + ); + const regexp = new RegExp(`^${data.endDate}$`, 'ig'); + expect(container).toHaveTextContent(regexp); + }); + + it('renders component - visibilityIds', () => { + const { container } = render( + {}} + /> + ); + const regexp = new RegExp( + `^deleghe.table.notificationsFrom${data.visibilityIds.join()}$`, + 'ig' + ); + expect(container).toHaveTextContent(regexp); + }); + + it('renders component - status', () => { + const { getByTestId } = render( + {}} /> + ); + const button = getByTestId('acceptButton'); + expect(button).toBeInTheDocument(); + }); + + it('renders component - status active', () => { + const { key } = getDelegationStatusKeyAndColor(DelegationStatus.ACTIVE); + const { container, queryByTestId } = render( + {}} + /> + ); + const regexp = new RegExp(`^${key}$`, 'ig'); + expect(container).toHaveTextContent(regexp); + const button = queryByTestId('acceptButton'); + expect(button).not.toBeInTheDocument(); + }); + + it('renders component - groups', () => { + const groupData = { + ...data, + groups: [ + { id: 'group-1', name: 'Group1' }, + { id: 'group-2', name: 'Group2' }, + { id: 'group-3', name: 'Group3' }, + ], + }; + const { container, queryByTestId } = render( + {}} + /> + ); + const regexp = new RegExp(`^${groupData.groups.map((g) => g.name).join('')}$`, 'ig'); + expect(container).toHaveTextContent(regexp); + const button = queryByTestId('acceptButton'); + expect(button).not.toBeInTheDocument(); + }); + + it('renders component - menu', () => { + const { getByTestId } = render( + {}} /> + ); + const menu = getByTestId('delegationMenuIcon'); + expect(menu).toBeInTheDocument(); + }); +}); diff --git a/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegationsElements.test.tsx b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegationsElements.test.tsx new file mode 100644 index 0000000000..b85d6b4b38 --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegationsElements.test.tsx @@ -0,0 +1,396 @@ +import MockAdapter from 'axios-mock-adapter'; +import { vi } from 'vitest'; + +import { Row } from '@pagopa-pn/pn-commons'; +import { testAutocomplete } from '@pagopa-pn/pn-commons/src/test-utils'; + +import { mandatesByDelegate } from '../../../__mocks__/Delegations.mock'; +import { fireEvent, render, screen, waitFor, within } from '../../../__test__/test-utils'; +import { apiClient } from '../../../api/apiClients'; +import { DelegationColumnData, DelegationStatus } from '../../../models/Deleghe'; +import { AcceptButton, Menu, OrganizationsList } from '../DelegationsElements'; + +vi.mock('react-i18next', () => ({ + // this mock makes sure any components using the translate hook can use it without a warning being shown + useTranslation: () => ({ + t: (str: string) => str, + }), +})); + +const actionCbk = vi.fn(); + +describe('DelegationElements', async () => { + let mock: MockAdapter; + + beforeAll(() => { + mock = new MockAdapter(apiClient); + }); + + afterEach(() => { + mock.reset(); + vi.clearAllMocks(); + }); + + afterAll(() => { + mock.restore(); + }); + + it('renders the Menu closed', () => { + const { queryByTestId, getByTestId } = render(); + const menuIcon = getByTestId('delegationMenuIcon'); + const closedMenu = queryByTestId('delegationMenu'); + expect(menuIcon).not.toBeNull(); + expect(closedMenu).toBeNull(); + }); + + it('opens the delegate Menu', () => { + const { queryByTestId, getByTestId } = render(); + const menuIcon = getByTestId('delegationMenuIcon'); + const closedMenu = queryByTestId('delegationMenu'); + expect(closedMenu).toBeNull(); + fireEvent.click(menuIcon); + const menu = getByTestId('delegationMenu'); + expect(menu).toHaveTextContent(/deleghe.revoke/i); + expect(menu).toHaveTextContent(/deleghe.show/i); + }); + + it('opens the delegator Menu', () => { + const { queryByTestId, getByTestId } = render(); + const menuIcon = getByTestId('delegationMenuIcon'); + const closedMenu = queryByTestId('delegationMenu'); + expect(closedMenu).toBeNull(); + fireEvent.click(menuIcon); + const menu = getByTestId('delegationMenu'); + expect(menu).toHaveTextContent(/deleghe.reject/i); + }); + + it('renders the OrganizationList with all notifications label', () => { + const { container } = render(); + expect(container).toHaveTextContent(/deleghe.table.allNotifications/i); + }); + + it('renders the OrganizationList with one organization', () => { + const { container } = render( + + ); + expect(container).toHaveTextContent(/deleghe.table.notificationsFrom/i); + expect(container).toHaveTextContent(/Bollate/i); + expect(container).toHaveTextContent(/Comune di Milano/i); + expect(container).toHaveTextContent(/Comune di Palermo/i); + }); + + it('renders the OrganizationList with multiple organizations and visibleItems set to 3', async () => { + const { container, getByTestId } = render( + + ); + const organizationsList = getByTestId('custom-tooltip-indicator'); + expect(container).toHaveTextContent(/deleghe.table.notificationsFrom/i); + expect(container).toHaveTextContent(/Bollate/i); + expect(container).toHaveTextContent(/Milano/i); + expect(container).toHaveTextContent(/Abbiategrasso/i); + expect(container).toHaveTextContent(/\+1/i); + expect(container).not.toHaveTextContent(/Malpesa/i); + await waitFor(() => fireEvent.mouseOver(organizationsList)); + await waitFor(() => expect(screen.getByText(/Malpensa/i)).toBeInTheDocument()); + }); + + it('renders the AcceptButton - open the modal', async () => { + const { container, getByTestId } = render( + + ); + expect(container).toHaveTextContent(/deleghe.accept/i); + const button = getByTestId('acceptButton'); + fireEvent.click(button); + const codeDialog = await waitFor(() => screen.getByTestId('codeDialog')); + expect(codeDialog).toBeInTheDocument(); + }); + + it('renders the AcceptButton - close the modal', async () => { + const { container, getByTestId } = render( + + ); + expect(container).toHaveTextContent(/deleghe.accept/i); + const button = getByTestId('acceptButton'); + fireEvent.click(button); + const codeDialog = await waitFor(() => screen.getByTestId('codeDialog')); + expect(codeDialog).toBeInTheDocument(); + const cancelButton = getByTestId('codeCancelButton'); + fireEvent.click(cancelButton); + await waitFor(() => expect(codeDialog).not.toBeInTheDocument()); + expect(actionCbk).not.toBeCalled(); + }); + + it('renders the AcceptButton - accept the delegation', async () => { + const groups = [ + { id: 'group-1', name: 'Group 1', status: 'ACTIVE' }, + { id: 'group-2', name: 'Group 2', status: 'ACTIVE' }, + ]; + mock.onPatch(`/bff/v1/mandate/4/accept`).reply(204); + const { container, getByTestId } = render( + , + { + preloadedState: { + delegationsState: { + groups, + delegations: { + delegators: mandatesByDelegate, + }, + }, + }, + } + ); + expect(container).toHaveTextContent(/deleghe.accept/i); + const button = getByTestId('acceptButton'); + fireEvent.click(button); + const codeDialog = await waitFor(() => screen.getByTestId('codeDialog')); + expect(codeDialog).toBeInTheDocument(); + const codeConfirmButton = within(codeDialog).getByTestId('codeConfirmButton'); + expect(codeConfirmButton).toBeDisabled(); + // fill the code + const codeInputs = codeDialog.querySelectorAll('input'); + codeInputs.forEach((input, index) => { + fireEvent.change(input, { target: { value: index.toString() } }); + }); + expect(codeConfirmButton).toBeEnabled(); + // got to next step + fireEvent.click(codeConfirmButton); + const groupDialog = await waitFor(() => screen.getByTestId('groupDialog')); + expect(groupDialog).toBeInTheDocument(); + // select groups to associate + const associateGroupRadio = await waitFor(() => + within(groupDialog).getByTestId('associate-group') + ); + fireEvent.click(associateGroupRadio); + await testAutocomplete(groupDialog, 'groups', groups, true, 1); + const groupConfirmButton = within(groupDialog).getByTestId('groupConfirmButton'); + fireEvent.click(groupConfirmButton); + await waitFor(() => { + expect(mock.history.patch.length).toBe(1); + expect(mock.history.patch[0].url).toContain(`/bff/v1/mandate/4/accept`); + expect(JSON.parse(mock.history.patch[0].data)).toStrictEqual({ + groups: ['group-2'], + verificationCode: '01234', + }); + }); + expect(actionCbk).toBeCalledTimes(1); + }); + + it('check verificationCode for delegates', async () => { + const verificationCode = '123456'; + const { getByTestId } = render( + } + /> + ); + const menuIcon = getByTestId('delegationMenuIcon'); + + fireEvent.click(menuIcon); + const menu = getByTestId('delegationMenu'); + const show = menu.querySelectorAll('[role="menuitem"]')[0]; + fireEvent.click(show); + const showDialog = await waitFor(() => screen.getByTestId('codeDialog')); + const codeInputs = showDialog?.querySelectorAll('input'); + const arrayOfVerificationCode = verificationCode.split(''); + codeInputs?.forEach((input, index) => { + expect(input).toHaveValue(arrayOfVerificationCode[index]); + }); + const cancelButton = within(showDialog).getByTestId('codeCancelButton'); + fireEvent.click(cancelButton!); + await waitFor(() => { + expect(showDialog).not.toBeInTheDocument(); + }); + }); + + it('check revoke for delegatates', async () => { + mock.onPatch('/bff/v1/mandate/111/revoke').reply(204); + const { getByTestId } = render( + } + onAction={actionCbk} + /> + ); + const menuIcon = getByTestId('delegationMenuIcon'); + fireEvent.click(menuIcon); + const menu = getByTestId('delegationMenu'); + const revoke = menu.querySelectorAll('[role="menuitem"]')[1]; + fireEvent.click(revoke); + const showDialog = await waitFor(() => screen.getByTestId('confirmationDialog')); + const revokeButton = within(showDialog).getAllByTestId('dialogAction')[1]; + fireEvent.click(revokeButton); + await waitFor(() => { + expect(mock.history.patch.length).toBe(1); + expect(mock.history.patch[0].url).toContain('/bff/v1/mandate/111/revoke'); + expect(showDialog).not.toBeInTheDocument(); + }); + expect(actionCbk).toBeCalledTimes(1); + }); + + it('check close confimationDialog', async () => { + const { getByTestId } = render( + } + /> + ); + const menuIcon = getByTestId('delegationMenuIcon'); + fireEvent.click(menuIcon); + const menu = getByTestId('delegationMenu'); + const revoke = menu.querySelectorAll('[role="menuitem"]')[1]; + fireEvent.click(revoke); + const showDialog = await waitFor(() => screen.getByTestId('confirmationDialog')); + const cancelButton = within(showDialog).getAllByTestId('dialogAction')[0]; + fireEvent.click(cancelButton!); + await waitFor(() => { + expect(showDialog).not.toBeInTheDocument(); + }); + }); + + it('check reject for delegator', async () => { + mock.onPatch('/bff/v1/mandate/111/reject').reply(204); + const { getByTestId } = render( + } + /> + ); + const menuIcon = getByTestId('delegationMenuIcon'); + fireEvent.click(menuIcon); + const menu = getByTestId('delegationMenu'); + const reject = menu.querySelectorAll('[role="menuitem"]')[0]; + fireEvent.click(reject); + const showDialog = await waitFor(() => screen.getByTestId('confirmationDialog')); + const rejectButton = within(showDialog).getAllByTestId('dialogAction')[1]; + fireEvent.click(rejectButton); + await waitFor(() => { + expect(mock.history.patch.length).toBe(1); + expect(mock.history.patch[0].url).toContain('/bff/v1/mandate/111/reject'); + expect(showDialog).not.toBeInTheDocument(); + }); + }); + + it("doesn't show the update button - delegator", async () => { + const { getByTestId } = render( + + } + /> + ); + const menuIcon = getByTestId('delegationMenuIcon'); + fireEvent.click(menuIcon); + const menu = getByTestId('delegationMenu'); + const menuItems = menu.querySelectorAll('[role="menuitem"]'); + expect(menuItems).toHaveLength(1); + }); + + it('shows the update button and modal - delegator', async () => { + const groups = [ + { id: 'group-1', name: 'Group 1' }, + { id: 'group-2', name: 'Group 2' }, + { id: 'group-3', name: 'Group 3' }, + ]; + const { getByTestId } = render( + + } + />, + { + preloadedState: { + delegationsState: { + groups, + }, + }, + } + ); + const menuIcon = getByTestId('delegationMenuIcon'); + fireEvent.click(menuIcon); + const menu = getByTestId('delegationMenu'); + const menuItems = menu.querySelectorAll('[role="menuitem"]'); + expect(menuItems).toHaveLength(2); + const updateButton = menuItems[1]; + fireEvent.click(updateButton); + const updateDialog = await waitFor(() => screen.getByTestId('groupDialog')); + expect(updateDialog).toBeInTheDocument(); + const cancelButton = getByTestId('groupCancelButton'); + fireEvent.click(cancelButton); + await waitFor(() => expect(updateDialog).not.toBeInTheDocument()); + expect(actionCbk).not.toBeCalled(); + }); + + it('update groups - delegator', async () => { + const groups = [ + { id: 'group-1', name: 'Group 1', status: 'ACTIVE' }, + { id: 'group-2', name: 'Group 2', status: 'ACTIVE' }, + { id: 'group-3', name: 'Group 3', status: 'ACTIVE' }, + ]; + mock.onPatch(`/bff/v1/mandate/4/update`).reply(204); + const { getByTestId } = render( + , + } as Row + } + onAction={actionCbk} + />, + { + preloadedState: { + delegationsState: { + groups, + delegations: { + delegators: mandatesByDelegate, + }, + }, + }, + } + ); + const menuIcon = getByTestId('delegationMenuIcon'); + fireEvent.click(menuIcon); + const menu = getByTestId('delegationMenu'); + const menuItems = menu.querySelectorAll('[role="menuitem"]'); + expect(menuItems).toHaveLength(2); + const updateButton = menuItems[1]; + fireEvent.click(updateButton); + const updateDialog = await waitFor(() => screen.getByTestId('groupDialog')); + expect(updateDialog).toBeInTheDocument(); + await testAutocomplete(updateDialog, 'groups', groups, true, 2); + const groupConfirmButton = within(updateDialog).getByTestId('groupConfirmButton'); + fireEvent.click(groupConfirmButton); + await waitFor(() => { + expect(mock.history.patch.length).toBe(1); + expect(mock.history.patch[0].url).toContain(`/bff/v1/mandate/4/update`); + expect(JSON.parse(mock.history.patch[0].data)).toStrictEqual({ + groups: ['group-2', 'group-3'], + }); + }); + expect(actionCbk).toBeCalledTimes(1); + }); +}); diff --git a/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegationsOfTheCompany.test.tsx b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegationsOfTheCompany.test.tsx new file mode 100644 index 0000000000..1f56ae4d38 --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/DelegationsOfTheCompany.test.tsx @@ -0,0 +1,475 @@ +import MockAdapter from 'axios-mock-adapter'; +import { ReactNode } from 'react'; +import { vi } from 'vitest'; + +import { testAutocomplete } from '@pagopa-pn/pn-commons/src/test-utils'; + +import { mandatesByDelegate } from '../../../__mocks__/Delegations.mock'; +import { fireEvent, render, screen, waitFor, within } from '../../../__test__/test-utils'; +import { apiClient } from '../../../api/apiClients'; +import { DelegationStatus } from '../../../models/Deleghe'; +import DelegationsOfTheCompany from '../DelegationsOfTheCompany'; + +vi.mock('react-i18next', () => ({ + // this mock makes sure any components using the translate hook can use it without a warning being shown + useTranslation: () => ({ + t: (str: string) => str, + }), + Trans: (props: { i18nKey: string; components?: Array }) => ( + <> + {props.i18nKey} {props.components && props.components!.map((c) => c)} + + ), +})); + +export async function testMultiSelect( + form: HTMLElement, + elementName: string, + options: Array<{ id: string; name: string }>, + optToSelect: number, + mustBeOpened: boolean +) { + if (mustBeOpened) { + const selectButton = form.querySelector(`div[id="${elementName}"]`); + fireEvent.mouseDown(selectButton!); + } + const selectOptionsContainer = await screen.findByRole('presentation'); + expect(selectOptionsContainer).toBeInTheDocument(); + const selectOptionsList = await within(selectOptionsContainer).findByRole('listbox'); + expect(selectOptionsList).toBeInTheDocument(); + const selectOptionsListItems = await within(selectOptionsList).findAllByRole('option'); + expect(selectOptionsListItems).toHaveLength(options.length); + selectOptionsListItems.forEach((opt, index) => { + expect(opt).toHaveTextContent(options[index].name); + }); + fireEvent.click(selectOptionsListItems[optToSelect]); +} + +const initialState = { + delegations: { + delegators: [], + delegates: [], + }, + pagination: { + nextPagesKey: [], + moreResult: false, + }, + groups: [], + filters: { + size: 10, + page: 0, + }, +}; + +describe('DelegationsOfTheCompany Component', async () => { + let mock: MockAdapter; + + beforeAll(() => { + mock = new MockAdapter(apiClient); + }); + + afterEach(() => { + mock.reset(); + }); + + afterAll(() => { + mock.restore(); + }); + + it('renders the empty state', () => { + const { container } = render(); + expect(container).toHaveTextContent(/deleghe.delegatorsTitle/i); + expect(container).toHaveTextContent(/deleghe.no_delegators/i); + expect(container).not.toHaveTextContent(/deleghe.table.name/i); + expect(container).not.toHaveTextContent(/deleghe.table.delegationStart/i); + expect(container).not.toHaveTextContent(/deleghe.table.delegationEnd/i); + expect(container).not.toHaveTextContent(/deleghe.table.permissions/i); + expect(container).not.toHaveTextContent(/deleghe.table.groups/i); + expect(container).not.toHaveTextContent(/deleghe.table.status/i); + }); + + it('renders the table', () => { + const { container, getByTestId, getAllByTestId } = render(, { + preloadedState: { + delegationsState: { + ...initialState, + delegations: { + delegators: mandatesByDelegate, + }, + }, + }, + }); + + expect(container).not.toHaveTextContent(/deleghe.no_delegators/i); + expect(container).toHaveTextContent(/deleghe.table.name/i); + expect(container).toHaveTextContent(/deleghe.table.delegationStart/i); + expect(container).toHaveTextContent(/deleghe.table.delegationEnd/i); + expect(container).toHaveTextContent(/deleghe.table.permissions/i); + expect(container).toHaveTextContent(/deleghe.table.groups/i); + expect(container).toHaveTextContent(/deleghe.table.status/i); + const table = getByTestId('delegationsDesktop'); + expect(table).toBeInTheDocument(); + const rows = getAllByTestId('delegationsBodyRowDesktop'); + expect(rows).toHaveLength(mandatesByDelegate.length); + rows.forEach((row, index) => { + expect(row).toHaveTextContent(mandatesByDelegate[index].delegator?.displayName!); + }); + }); + + it('filters the results', async () => { + mock + .onPost('/bff/v1/mandate/delegate?size=10', { + groups: ['group-2'], + status: [DelegationStatus.ACTIVE, DelegationStatus.REJECTED], + }) + .reply(200, { + resultsPage: [mandatesByDelegate[1]], + moreResult: false, + nextPagesKey: [], + }); + const groups = [ + { + id: 'group-1', + name: 'Group 1', + status: 'ACTIVE', + }, + { + id: 'group-2', + name: 'Group 2', + status: 'ACTIVE', + }, + ]; + const status = [ + { id: DelegationStatus.ACTIVE, name: 'deleghe.table.active' }, + { id: DelegationStatus.PENDING, name: 'deleghe.table.pending' }, + { id: DelegationStatus.REJECTED, name: 'deleghe.table.rejected' }, + ]; + const { container, getAllByTestId } = render(, { + preloadedState: { + delegationsState: { + ...initialState, + delegations: { + delegators: mandatesByDelegate, + }, + groups, + }, + }, + }); + + const form = container.querySelector('form'); + const cancelButton = within(form!).getByTestId('cancelButton'); + const confirmButton = within(form!).getByTestId('confirmButton'); + expect(cancelButton).toBeInTheDocument(); + expect(cancelButton).toBeDisabled(); + expect(confirmButton).toBeInTheDocument(); + expect(confirmButton).toBeDisabled(); + await testAutocomplete(form!, 'groups', groups, true, 1, false); + await testMultiSelect(form!, 'status', status, 0, true); + await testMultiSelect(form!, 'status', status, 2, false); + expect(confirmButton).toBeEnabled(); + fireEvent.click(confirmButton); + await waitFor(() => { + expect(mock.history.post.length).toBe(1); + expect(mock.history.post[0].url).toContain('/bff/v1/mandate/delegate?size=10'); + expect(JSON.parse(mock.history.post[0].data)).toStrictEqual({ + groups: ['group-2'], + status: [DelegationStatus.ACTIVE, DelegationStatus.REJECTED], + }); + }); + const rows = getAllByTestId('delegationsBodyRowDesktop'); + expect(rows).toHaveLength(1); + expect(rows[0]).toHaveTextContent(mandatesByDelegate[1].delegator?.displayName!); + expect(cancelButton).toBeEnabled(); + }); + + it('filters the results and show empty state', async () => { + mock + .onPost('/bff/v1/mandate/delegate?size=10', { + groups: ['group-2'], + status: [DelegationStatus.ACTIVE, DelegationStatus.REJECTED], + }) + .reply(200, { + resultsPage: [], + moreResult: false, + nextPagesKey: [], + }); + mock.onPost('/bff/v1/mandate/delegate?size=10').reply(200, { + resultsPage: mandatesByDelegate, + moreResult: false, + nextPagesKey: [], + }); + const groups = [ + { + id: 'group-1', + name: 'Group 1', + status: 'ACTIVE', + }, + { + id: 'group-2', + name: 'Group 2', + status: 'ACTIVE', + }, + ]; + const status = [ + { id: DelegationStatus.ACTIVE, name: 'deleghe.table.active' }, + { id: DelegationStatus.PENDING, name: 'deleghe.table.pending' }, + { id: DelegationStatus.REJECTED, name: 'deleghe.table.rejected' }, + ]; + const { container, queryByTestId, getByTestId } = render(, { + preloadedState: { + delegationsState: { + ...initialState, + delegations: { + delegators: mandatesByDelegate, + }, + groups, + }, + }, + }); + const form = container.querySelector('form'); + const cancelButton = within(form!).getByTestId('cancelButton'); + const confirmButton = within(form!).getByTestId('confirmButton'); + expect(cancelButton).toBeInTheDocument(); + expect(cancelButton).toBeDisabled(); + expect(confirmButton).toBeInTheDocument(); + expect(confirmButton).toBeDisabled(); + await testAutocomplete(form!, 'groups', groups, true, 1, false); + await testMultiSelect(form!, 'status', status, 0, true); + await testMultiSelect(form!, 'status', status, 2, false); + expect(confirmButton).toBeEnabled(); + fireEvent.click(confirmButton); + await waitFor(() => { + expect(mock.history.post.length).toBe(1); + expect(mock.history.post[0].url).toContain('/bff/v1/mandate/delegate?size=10'); + expect(JSON.parse(mock.history.post[0].data)).toStrictEqual({ + groups: ['group-2'], + status: [DelegationStatus.ACTIVE, DelegationStatus.REJECTED], + }); + }); + let table = queryByTestId('delegationsDesktop'); + expect(table).not.toBeInTheDocument(); + expect(container).toHaveTextContent(/deleghe.no_delegators_after_filters/i); + // clicks on empty state action + const button = getByTestId('link-remove-filters'); + fireEvent.click(button); + await waitFor(() => { + expect(mock.history.post.length).toBe(2); + expect(mock.history.post[0].url).toContain('/bff/v1/mandate/delegate?size=10'); + }); + expect(container).not.toHaveTextContent(/deleghe.no_delegators_after_filters/i); + table = getByTestId('delegationsDesktop'); + expect(table).toBeInTheDocument(); + }); + + it('change pagination size', async () => { + mock.onPost('/bff/v1/mandate/delegate?size=20').reply(200, { + resultsPage: [mandatesByDelegate[1]], + moreResult: false, + nextPagesKey: [], + }); + const { getAllByTestId, getByTestId } = render(, { + preloadedState: { + delegationsState: { + ...initialState, + delegations: { + delegators: [mandatesByDelegate[0]], + }, + }, + }, + }); + + let rows = getAllByTestId('delegationsBodyRowDesktop'); + expect(rows).toHaveLength(1); + expect(rows[0]).toHaveTextContent(mandatesByDelegate[0].delegator?.displayName!); + const itemsPerPageSelector = getByTestId('itemsPerPageSelector'); + const button = itemsPerPageSelector.querySelector('button'); + expect(button).toHaveTextContent(/10/i); + fireEvent.click(button!); + const itemsPerPageListContainer = await waitFor(() => screen.queryByRole('presentation')); + expect(itemsPerPageListContainer).toBeInTheDocument(); + const itemsPerPageList = screen.getAllByRole('menuitem'); + expect(itemsPerPageList).toHaveLength(3); + fireEvent.click(itemsPerPageList[1]!); + await waitFor(() => { + expect(button).toHaveTextContent(/20/i); + expect(mock.history.post.length).toBe(1); + expect(mock.history.post[0].url).toContain('/bff/v1/mandate/delegate?size=20'); + }); + rows = getAllByTestId('delegationsBodyRowDesktop'); + expect(rows).toHaveLength(1); + expect(rows[0]).toHaveTextContent(mandatesByDelegate[1].delegator?.displayName!); + }); + + it('change pagination page', async () => { + mock.onPost('/bff/v1/mandate/delegate?size=10&nextPageKey=page-1').reply(200, { + resultsPage: [mandatesByDelegate[1]], + moreResult: false, + nextPagesKey: [], + }); + const { getAllByTestId, getByTestId } = render(, { + preloadedState: { + delegationsState: { + ...initialState, + delegations: { + delegators: [mandatesByDelegate[0]], + }, + pagination: { + nextPagesKey: ['page-1', 'page-2', 'page-3'], + moreResult: false, + }, + }, + }, + }); + let rows = getAllByTestId('delegationsBodyRowDesktop'); + expect(rows).toHaveLength(1); + expect(rows[0]).toHaveTextContent(mandatesByDelegate[0].delegator?.displayName!); + const pageSelector = getByTestId('pageSelector'); + const pageButtons = pageSelector.querySelectorAll('button'); + // depends on mui pagination + // for 10 pages we have: < 1 2 3 > + expect(pageButtons).toHaveLength(5); + expect(pageButtons[1]).toHaveTextContent(/1/i); + expect(pageButtons[2]).toHaveTextContent(/2/i); + expect(pageButtons[3]).toHaveTextContent(/3/i); + fireEvent.click(pageButtons[2]); + await waitFor(() => { + expect(mock.history.post.length).toBe(1); + expect(mock.history.post[0].url).toContain( + '/bff/v1/mandate/delegate?size=10&nextPageKey=page-1' + ); + }); + rows = getAllByTestId('delegationsBodyRowDesktop'); + expect(rows).toHaveLength(1); + expect(rows[0]).toHaveTextContent(mandatesByDelegate[1].delegator?.displayName!); + }); + + it('test reject delegation', async () => { + mock.onPatch(`/bff/v1/mandate/${mandatesByDelegate[0].mandateId}/reject`).reply(204); + const { getAllByTestId, getByTestId } = render(, { + preloadedState: { + delegationsState: { + ...initialState, + delegations: { + delegators: mandatesByDelegate, + delegates: [], + }, + }, + }, + }); + const menu = getAllByTestId('delegationMenuIcon'); + fireEvent.click(menu[0]); + const menuOpen = await waitFor(async () => getByTestId('delegationMenu')); + const menuItems = menuOpen.querySelectorAll('[role="menuitem"]'); + expect(menuItems).toHaveLength(1); + expect(menuItems[0]).toHaveTextContent(/deleghe.reject/i); + fireEvent.click(menuItems[0]); + const dialog = await waitFor(() => getByTestId('confirmationDialog')); + expect(dialog).toBeInTheDocument(); + const dialogAction = within(dialog).getAllByTestId('dialogAction'); + // click on confirm button + fireEvent.click(dialogAction[1]); + await waitFor(() => { + expect(mock.history.patch.length).toBe(1); + expect(mock.history.patch[0].url).toContain( + `/bff/v1/mandate/${mandatesByDelegate[0].mandateId}/reject` + ); + expect(dialog).not.toBeInTheDocument(); + }); + const rows = getAllByTestId('delegationsBodyRowDesktop'); + expect(rows).toHaveLength(mandatesByDelegate.length - 1); + // the index + 1 is because we reject the first delegator + rows.forEach((row, index) => { + expect(row).toHaveTextContent(mandatesByDelegate[index + 1].delegator?.displayName!); + }); + }); + + it('test accept delegation', async () => { + mock.onPatch(`/bff/v1/mandate/${mandatesByDelegate[0].mandateId}/accept`).reply(204); + const { getByTestId } = render(, { + preloadedState: { + delegationsState: { + ...initialState, + delegations: { + delegators: mandatesByDelegate, + delegates: [], + }, + }, + }, + }); + const table = getByTestId('delegationsDesktop'); + expect(table).toBeInTheDocument(); + const acceptButton = within(table).getByTestId('acceptButton'); + expect(acceptButton).toBeInTheDocument(); + fireEvent.click(acceptButton); + const dialog = await waitFor(() => getByTestId('codeDialog')); + expect(dialog).toBeInTheDocument(); + // fill the code + const codeInputs = dialog.querySelectorAll('input'); + codeInputs.forEach((input, index) => { + fireEvent.change(input, { target: { value: index.toString() } }); + }); + const codeConfirmButton = within(dialog).getByTestId('codeConfirmButton'); + // click on confirm button + fireEvent.click(codeConfirmButton); + await waitFor(() => { + expect(mock.history.patch.length).toBe(1); + expect(mock.history.patch[0].url).toContain( + `/bff/v1/mandate/${mandatesByDelegate[0].mandateId}/accept` + ); + expect(JSON.parse(mock.history.patch[0].data)).toStrictEqual({ + groups: [], + verificationCode: '01234', + }); + expect(dialog).not.toBeInTheDocument(); + }); + expect(acceptButton).not.toBeInTheDocument(); + }); + + it('test update delegation', async () => { + const groups = [ + { id: 'group-1', name: 'Group 1', status: 'ACTIVE' }, + { id: 'group-2', name: 'Group 2', status: 'ACTIVE' }, + { id: 'group-3', name: 'Group 3', status: 'ACTIVE' }, + ]; + mock.onPatch(`/bff/v1/mandate/${mandatesByDelegate[1].mandateId}/update`).reply(204); + const { getByTestId, getAllByTestId } = render(, { + preloadedState: { + delegationsState: { + ...initialState, + delegations: { + delegators: mandatesByDelegate, + delegates: [], + }, + groups, + }, + }, + }); + let rows = getAllByTestId('delegationsBodyRowDesktop'); + expect(rows[1]).not.toHaveTextContent('Group 3'); + const menu = within(rows[1]).getByTestId('delegationMenuIcon'); + fireEvent.click(menu); + const menuOpen = await waitFor(async () => getByTestId('delegationMenu')); + const menuItems = menuOpen.querySelectorAll('[role="menuitem"]'); + expect(menuItems).toHaveLength(2); + expect(menuItems[1]).toHaveTextContent(/deleghe.update/i); + fireEvent.click(menuItems[1]); + const updateDialog = await waitFor(() => screen.getByTestId('groupDialog')); + expect(updateDialog).toBeInTheDocument(); + const associateGroupRadio = within(updateDialog).getByTestId('associate-group'); + fireEvent.click(associateGroupRadio); + await testAutocomplete(updateDialog, 'groups', groups, true, 2); + const groupConfirmButton = within(updateDialog).getByTestId('groupConfirmButton'); + fireEvent.click(groupConfirmButton); + await waitFor(() => { + expect(mock.history.patch.length).toBe(1); + expect(mock.history.patch[0].url).toContain( + `/bff/v1/mandate/${mandatesByDelegate[1].mandateId}/update` + ); + expect(JSON.parse(mock.history.patch[0].data)).toStrictEqual({ + groups: ['group-3'], + }); + }); + rows = getAllByTestId('delegationsBodyRowDesktop'); + expect(rows[1]).toHaveTextContent('Group 3'); + }); +}); diff --git a/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/VerificationCodeComponent.test.tsx b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/VerificationCodeComponent.test.tsx new file mode 100644 index 0000000000..29d7da508e --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/components/Deleghe/__test__/VerificationCodeComponent.test.tsx @@ -0,0 +1,15 @@ +import { render } from '../../../__test__/test-utils'; +import VerificationCodeComponent from '../VerificationCodeComponent'; + +describe('VerificationCodeComponent', () => { + it('renders the component and checks the digits', () => { + const fiveDigits = '12345'; + const { queryAllByTestId } = render(); + const digitsElements = queryAllByTestId('codeDigit'); + const codes = fiveDigits.split(''); + expect(digitsElements).toHaveLength(fiveDigits.length); + digitsElements.forEach((code, index) => { + expect(code).toHaveTextContent(codes[index]); + }); + }); +}); diff --git a/packages/pn-personagiuridica-webapp/src/generated-client/mandate/.openapi-generator-ignore b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/.openapi-generator-ignore new file mode 100644 index 0000000000..39b092c3ec --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/.openapi-generator-ignore @@ -0,0 +1,28 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md + +# Prevent generator from creating these files: +git_push.sh +.gitignore +.npmignore \ No newline at end of file diff --git a/packages/pn-personagiuridica-webapp/src/generated-client/mandate/.openapi-generator/FILES b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/.openapi-generator/FILES new file mode 100644 index 0000000000..16b445eee6 --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/.openapi-generator/FILES @@ -0,0 +1,9 @@ +.gitignore +.npmignore +.openapi-generator-ignore +api.ts +base.ts +common.ts +configuration.ts +git_push.sh +index.ts diff --git a/packages/pn-personagiuridica-webapp/src/generated-client/mandate/.openapi-generator/VERSION b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/.openapi-generator/VERSION new file mode 100644 index 0000000000..ba7f754d0c --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.4.0 diff --git a/packages/pn-personagiuridica-webapp/src/generated-client/mandate/api.ts b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/api.ts new file mode 100644 index 0000000000..4a7830de89 --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/api.ts @@ -0,0 +1,1269 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * PN BFF BE Microservice - Deleghe + * Documentation APIs v1.0 + * + * The version of the OpenAPI document: 1.0.0 + * Contact: pn@pagopa.it + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import type { Configuration } from './configuration'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; +import globalAxios from 'axios'; +// Some imports not used depending on template conditions +// @ts-ignore +import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; +import type { RequestArgs } from './base'; +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; + +/** + * + * @export + * @interface AcceptRequestDto + */ +export interface AcceptRequestDto { + /** + * + * @type {string} + * @memberof AcceptRequestDto + */ + 'verificationCode'?: string; + /** + * + * @type {Array} + * @memberof AcceptRequestDto + */ + 'groups'?: Array; +} +/** + * + * @export + * @interface BffAcceptRequest + */ +export interface BffAcceptRequest { + /** + * + * @type {string} + * @memberof BffAcceptRequest + */ + 'verificationCode'?: string; + /** + * + * @type {Array} + * @memberof BffAcceptRequest + */ + 'groups'?: Array; +} +/** + * + * @export + * @interface BffMandate + */ +export interface BffMandate { + /** + * Available always, not required on mandate creation. + * @type {string} + * @memberof BffMandate + */ + 'mandateId'?: string | null; + /** + * + * @type {UserDto} + * @memberof BffMandate + */ + 'delegator'?: UserDto | null; + /** + * + * @type {UserDto} + * @memberof BffMandate + */ + 'delegate'?: UserDto | null; + /** + * Available always, not required on mandate creation. + * @type {string} + * @memberof BffMandate + */ + 'status'?: BffMandateStatusEnum | null; + /** + * Available always, not required on mandate creation. + * @type {Array} + * @memberof BffMandate + */ + 'visibilityIds'?: Array | null; + /** + * Available only for request where requesting user is the delegator + * @type {string} + * @memberof BffMandate + */ + 'verificationCode'?: string | null; + /** + * ISO 8601 format + * @type {string} + * @memberof BffMandate + */ + 'datefrom'?: string; + /** + * ISO 8601 format + * @type {string} + * @memberof BffMandate + */ + 'dateto'?: string; + /** + * + * @type {Array} + * @memberof BffMandate + */ + 'groups'?: Array; +} + +export const BffMandateStatusEnum = { + Pending: 'pending', + Active: 'active', + Revoked: 'revoked', + Rejected: 'rejected', + Expired: 'expired' +} as const; + +export type BffMandateStatusEnum = typeof BffMandateStatusEnum[keyof typeof BffMandateStatusEnum]; + +/** + * + * @export + * @interface BffMandatesCount + */ +export interface BffMandatesCount { + /** + * + * @type {number} + * @memberof BffMandatesCount + */ + 'value'?: number; +} +/** + * + * @export + * @interface BffNewMandateRequest + */ +export interface BffNewMandateRequest { + /** + * + * @type {UserDto} + * @memberof BffNewMandateRequest + */ + 'delegate': UserDto | null; + /** + * Available always, not required on mandate creation. + * @type {Array} + * @memberof BffNewMandateRequest + */ + 'visibilityIds'?: Array | null; + /** + * Available only for request where requesting user is the delegator + * @type {string} + * @memberof BffNewMandateRequest + */ + 'verificationCode': string | null; + /** + * ISO 8601 format + * @type {string} + * @memberof BffNewMandateRequest + */ + 'dateto': string; + /** + * + * @type {Array} + * @memberof BffNewMandateRequest + */ + 'groups'?: Array; +} +/** + * + * @export + * @interface BffSearchMandateRequest + */ +export interface BffSearchMandateRequest { + /** + * + * @type {string} + * @memberof BffSearchMandateRequest + */ + 'taxId'?: string; + /** + * + * @type {Array} + * @memberof BffSearchMandateRequest + */ + 'groups'?: Array; + /** + * + * @type {Array} + * @memberof BffSearchMandateRequest + */ + 'status'?: Array; +} +/** + * + * @export + * @interface BffSearchMandateResponse + */ +export interface BffSearchMandateResponse { + /** + * + * @type {Array} + * @memberof BffSearchMandateResponse + */ + 'resultsPage'?: Array; + /** + * Indica se sono presenti ulteriori pagine di risultati + * @type {boolean} + * @memberof BffSearchMandateResponse + */ + 'moreResult'?: boolean; + /** + * Elenco, non esaustivo, delle chiavi da usare per richiedere le pagine di risultati successive a quella corrente.
Valorizzato solo se il campo __moreResult__ ha valore __true__. + * @type {Array} + * @memberof BffSearchMandateResponse + */ + 'nextPagesKey'?: Array; +} +/** + * + * @export + * @interface BffUpdateRequest + */ +export interface BffUpdateRequest { + /** + * + * @type {Array} + * @memberof BffUpdateRequest + */ + 'groups'?: Array; +} +/** + * + * @export + * @interface GroupDto + */ +export interface GroupDto { + /** + * + * @type {string} + * @memberof GroupDto + */ + 'id'?: string; + /** + * + * @type {string} + * @memberof GroupDto + */ + 'name'?: string; +} +/** + * + * @export + * @interface MandateCountsDto + */ +export interface MandateCountsDto { + /** + * + * @type {number} + * @memberof MandateCountsDto + */ + 'value'?: number; +} +/** + * + * @export + * @interface MandateDto + */ +export interface MandateDto { + /** + * Available always, not required on mandate creation. + * @type {string} + * @memberof MandateDto + */ + 'mandateId'?: string | null; + /** + * + * @type {UserDto} + * @memberof MandateDto + */ + 'delegator'?: UserDto | null; + /** + * + * @type {UserDto} + * @memberof MandateDto + */ + 'delegate'?: UserDto | null; + /** + * Available always, not required on mandate creation. + * @type {string} + * @memberof MandateDto + */ + 'status'?: MandateDtoStatusEnum | null; + /** + * Available always, not required on mandate creation. + * @type {Array} + * @memberof MandateDto + */ + 'visibilityIds'?: Array | null; + /** + * Available only for request where requesting user is the delegator + * @type {string} + * @memberof MandateDto + */ + 'verificationCode'?: string | null; + /** + * ISO 8601 format + * @type {string} + * @memberof MandateDto + */ + 'datefrom'?: string; + /** + * ISO 8601 format + * @type {string} + * @memberof MandateDto + */ + 'dateto'?: string; + /** + * + * @type {Array} + * @memberof MandateDto + */ + 'groups'?: Array; +} + +export const MandateDtoStatusEnum = { + Pending: 'pending', + Active: 'active', + Revoked: 'revoked', + Rejected: 'rejected', + Expired: 'expired' +} as const; + +export type MandateDtoStatusEnum = typeof MandateDtoStatusEnum[keyof typeof MandateDtoStatusEnum]; + +/** + * Available always, not required on mandate creation. + * @export + * @interface OrganizationIdDto + */ +export interface OrganizationIdDto { + /** + * + * @type {string} + * @memberof OrganizationIdDto + */ + 'name'?: string; + /** + * + * @type {string} + * @memberof OrganizationIdDto + */ + 'uniqueIdentifier'?: string; +} +/** + * + * @export + * @interface Problem + */ +export interface Problem { + /** + * URI reference of type definition + * @type {string} + * @memberof Problem + */ + 'type'?: string; + /** + * The HTTP status code generated by the origin server for this occurrence of the problem. + * @type {number} + * @memberof Problem + */ + 'status': number; + /** + * A short, summary of the problem type. Written in english and readable + * @type {string} + * @memberof Problem + */ + 'title'?: string; + /** + * A human readable explanation of the problem. + * @type {string} + * @memberof Problem + */ + 'detail'?: string; + /** + * Internal support identifier associated to error + * @type {string} + * @memberof Problem + */ + 'traceId'?: string; + /** + * date and time referred to UTC + * @type {string} + * @memberof Problem + */ + 'timestamp'?: string; + /** + * + * @type {Array} + * @memberof Problem + */ + 'errors': Array; +} +/** + * + * @export + * @interface ProblemError + */ +export interface ProblemError { + /** + * Internal code of the error, in human-readable format + * @type {string} + * @memberof ProblemError + */ + 'code': string; + /** + * Parameter or request body field name for validation error + * @type {string} + * @memberof ProblemError + */ + 'element'?: string; + /** + * A human readable explanation specific to this occurrence of the problem. + * @type {string} + * @memberof ProblemError + */ + 'detail'?: string; +} +/** + * + * @export + * @interface SearchMandateRequestDto + */ +export interface SearchMandateRequestDto { + /** + * + * @type {string} + * @memberof SearchMandateRequestDto + */ + 'taxId'?: string; + /** + * + * @type {Array} + * @memberof SearchMandateRequestDto + */ + 'groups'?: Array; + /** + * + * @type {Array} + * @memberof SearchMandateRequestDto + */ + 'status'?: Array; +} +/** + * + * @export + * @interface SearchMandateResponseDto + */ +export interface SearchMandateResponseDto { + /** + * + * @type {Array} + * @memberof SearchMandateResponseDto + */ + 'resultsPage'?: Array; + /** + * Indica se sono presenti ulteriori pagine di risultati + * @type {boolean} + * @memberof SearchMandateResponseDto + */ + 'moreResult'?: boolean; + /** + * Elenco, non esaustivo, delle chiavi da usare per richiedere le pagine di risultati successive a quella corrente.
Valorizzato solo se il campo __moreResult__ ha valore __true__. + * @type {Array} + * @memberof SearchMandateResponseDto + */ + 'nextPagesKey'?: Array; +} +/** + * + * @export + * @interface UpdateRequestDto + */ +export interface UpdateRequestDto { + /** + * + * @type {Array} + * @memberof UpdateRequestDto + */ + 'groups'?: Array; +} +/** + * Available only for request where requesting user is the delegator + * @export + * @interface UserDto + */ +export interface UserDto { + /** + * + * @type {string} + * @memberof UserDto + */ + 'displayName'?: string; + /** + * + * @type {string} + * @memberof UserDto + */ + 'firstName'?: string; + /** + * + * @type {string} + * @memberof UserDto + */ + 'lastName'?: string; + /** + * + * @type {string} + * @memberof UserDto + */ + 'companyName'?: string; + /** + * + * @type {string} + * @memberof UserDto + */ + 'fiscalCode'?: string; + /** + * + * @type {boolean} + * @memberof UserDto + */ + 'person'?: boolean; +} + +/** + * MandateApi - axios parameter creator + * @export + */ +export const MandateApiAxiosParamCreator = function (configuration?: Configuration) { + return { + /** + * + * @summary Accept a mandate + * @param {string} mandateId + * @param {BffAcceptRequest} bffAcceptRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + acceptMandateV1: async (mandateId: string, bffAcceptRequest: BffAcceptRequest, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'mandateId' is not null or undefined + assertParamExists('acceptMandateV1', 'mandateId', mandateId) + // verify required parameter 'bffAcceptRequest' is not null or undefined + assertParamExists('acceptMandateV1', 'bffAcceptRequest', bffAcceptRequest) + const localVarPath = `/bff/v1/mandate/{mandateId}/accept` + .replace(`{${"mandateId"}}`, encodeURIComponent(String(mandateId))); + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(bffAcceptRequest, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Ritorna il numero totale di deleghe in base al filtro stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {CountMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + countMandatesByDelegateV1: async (status?: CountMandatesByDelegateV1StatusEnum, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/bff/v1/mandate/delegate/count`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (status !== undefined) { + localVarQueryParameter['status'] = status; + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Create a new mandate, returns the just created mandate if successful + * @param {BffNewMandateRequest} bffNewMandateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createMandateV1: async (bffNewMandateRequest: BffNewMandateRequest, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'bffNewMandateRequest' is not null or undefined + assertParamExists('createMandateV1', 'bffNewMandateRequest', bffNewMandateRequest) + const localVarPath = `/bff/v1/mandate`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(bffNewMandateRequest, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Ritorna la lista delle deleghe a carico in base al filtro per stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {GetMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getMandatesByDelegateV1: async (status?: GetMandatesByDelegateV1StatusEnum, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/bff/v1/mandate/delegate`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (status !== undefined) { + localVarQueryParameter['status'] = status; + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Ritorna tutte le deleghe create + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getMandatesByDelegatorV1: async (options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/bff/v1/mandate/delegator`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Reject a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + rejectMandateV1: async (mandateId: string, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'mandateId' is not null or undefined + assertParamExists('rejectMandateV1', 'mandateId', mandateId) + const localVarPath = `/bff/v1/mandate/{mandateId}/reject` + .replace(`{${"mandateId"}}`, encodeURIComponent(String(mandateId))); + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Revoke a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + revokeMandateV1: async (mandateId: string, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'mandateId' is not null or undefined + assertParamExists('revokeMandateV1', 'mandateId', mandateId) + const localVarPath = `/bff/v1/mandate/{mandateId}/revoke` + .replace(`{${"mandateId"}}`, encodeURIComponent(String(mandateId))); + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Ritorna la lista delle deleghe a carico in base ai filtri per stato, gruppo/i e delegante (taxId) + * @param {number} size + * @param {BffSearchMandateRequest} bffSearchMandateRequest + * @param {string} [nextPageKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + searchMandatesByDelegateV1: async (size: number, bffSearchMandateRequest: BffSearchMandateRequest, nextPageKey?: string, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'size' is not null or undefined + assertParamExists('searchMandatesByDelegateV1', 'size', size) + // verify required parameter 'bffSearchMandateRequest' is not null or undefined + assertParamExists('searchMandatesByDelegateV1', 'bffSearchMandateRequest', bffSearchMandateRequest) + const localVarPath = `/bff/v1/mandate/delegate`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (size !== undefined) { + localVarQueryParameter['size'] = size; + } + + if (nextPageKey !== undefined) { + localVarQueryParameter['nextPageKey'] = nextPageKey; + } + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(bffSearchMandateRequest, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * + * @summary Update a mandate + * @param {string} mandateId + * @param {BffUpdateRequest} bffUpdateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updateMandateV1: async (mandateId: string, bffUpdateRequest: BffUpdateRequest, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'mandateId' is not null or undefined + assertParamExists('updateMandateV1', 'mandateId', mandateId) + // verify required parameter 'bffUpdateRequest' is not null or undefined + assertParamExists('updateMandateV1', 'bffUpdateRequest', bffUpdateRequest) + const localVarPath = `/bff/v1/mandate/{mandateId}/update` + .replace(`{${"mandateId"}}`, encodeURIComponent(String(mandateId))); + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(bffUpdateRequest, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * MandateApi - functional programming interface + * @export + */ +export const MandateApiFp = function(configuration?: Configuration) { + const localVarAxiosParamCreator = MandateApiAxiosParamCreator(configuration) + return { + /** + * + * @summary Accept a mandate + * @param {string} mandateId + * @param {BffAcceptRequest} bffAcceptRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async acceptMandateV1(mandateId: string, bffAcceptRequest: BffAcceptRequest, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.acceptMandateV1(mandateId, bffAcceptRequest, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.acceptMandateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Ritorna il numero totale di deleghe in base al filtro stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {CountMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async countMandatesByDelegateV1(status?: CountMandatesByDelegateV1StatusEnum, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.countMandatesByDelegateV1(status, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.countMandatesByDelegateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Create a new mandate, returns the just created mandate if successful + * @param {BffNewMandateRequest} bffNewMandateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async createMandateV1(bffNewMandateRequest: BffNewMandateRequest, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.createMandateV1(bffNewMandateRequest, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.createMandateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Ritorna la lista delle deleghe a carico in base al filtro per stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {GetMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async getMandatesByDelegateV1(status?: GetMandatesByDelegateV1StatusEnum, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + const localVarAxiosArgs = await localVarAxiosParamCreator.getMandatesByDelegateV1(status, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.getMandatesByDelegateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Ritorna tutte le deleghe create + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async getMandatesByDelegatorV1(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + const localVarAxiosArgs = await localVarAxiosParamCreator.getMandatesByDelegatorV1(options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.getMandatesByDelegatorV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Reject a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async rejectMandateV1(mandateId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.rejectMandateV1(mandateId, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.rejectMandateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Revoke a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async revokeMandateV1(mandateId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.revokeMandateV1(mandateId, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.revokeMandateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Ritorna la lista delle deleghe a carico in base ai filtri per stato, gruppo/i e delegante (taxId) + * @param {number} size + * @param {BffSearchMandateRequest} bffSearchMandateRequest + * @param {string} [nextPageKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async searchMandatesByDelegateV1(size: number, bffSearchMandateRequest: BffSearchMandateRequest, nextPageKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.searchMandatesByDelegateV1(size, bffSearchMandateRequest, nextPageKey, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.searchMandatesByDelegateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + /** + * + * @summary Update a mandate + * @param {string} mandateId + * @param {BffUpdateRequest} bffUpdateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async updateMandateV1(mandateId: string, bffUpdateRequest: BffUpdateRequest, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.updateMandateV1(mandateId, bffUpdateRequest, options); + const localVarOperationServerIndex = configuration?.serverIndex ?? 0; + const localVarOperationServerBasePath = operationServerMap['MandateApi.updateMandateV1']?.[localVarOperationServerIndex]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath); + }, + } +}; + +/** + * MandateApi - factory interface + * @export + */ +export const MandateApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { + const localVarFp = MandateApiFp(configuration) + return { + /** + * + * @summary Accept a mandate + * @param {string} mandateId + * @param {BffAcceptRequest} bffAcceptRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + acceptMandateV1(mandateId: string, bffAcceptRequest: BffAcceptRequest, options?: any): AxiosPromise { + return localVarFp.acceptMandateV1(mandateId, bffAcceptRequest, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Ritorna il numero totale di deleghe in base al filtro stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {CountMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + countMandatesByDelegateV1(status?: CountMandatesByDelegateV1StatusEnum, options?: any): AxiosPromise { + return localVarFp.countMandatesByDelegateV1(status, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Create a new mandate, returns the just created mandate if successful + * @param {BffNewMandateRequest} bffNewMandateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + createMandateV1(bffNewMandateRequest: BffNewMandateRequest, options?: any): AxiosPromise { + return localVarFp.createMandateV1(bffNewMandateRequest, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Ritorna la lista delle deleghe a carico in base al filtro per stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {GetMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getMandatesByDelegateV1(status?: GetMandatesByDelegateV1StatusEnum, options?: any): AxiosPromise> { + return localVarFp.getMandatesByDelegateV1(status, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Ritorna tutte le deleghe create + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + getMandatesByDelegatorV1(options?: any): AxiosPromise> { + return localVarFp.getMandatesByDelegatorV1(options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Reject a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + rejectMandateV1(mandateId: string, options?: any): AxiosPromise { + return localVarFp.rejectMandateV1(mandateId, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Revoke a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + revokeMandateV1(mandateId: string, options?: any): AxiosPromise { + return localVarFp.revokeMandateV1(mandateId, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Ritorna la lista delle deleghe a carico in base ai filtri per stato, gruppo/i e delegante (taxId) + * @param {number} size + * @param {BffSearchMandateRequest} bffSearchMandateRequest + * @param {string} [nextPageKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + searchMandatesByDelegateV1(size: number, bffSearchMandateRequest: BffSearchMandateRequest, nextPageKey?: string, options?: any): AxiosPromise { + return localVarFp.searchMandatesByDelegateV1(size, bffSearchMandateRequest, nextPageKey, options).then((request) => request(axios, basePath)); + }, + /** + * + * @summary Update a mandate + * @param {string} mandateId + * @param {BffUpdateRequest} bffUpdateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + updateMandateV1(mandateId: string, bffUpdateRequest: BffUpdateRequest, options?: any): AxiosPromise { + return localVarFp.updateMandateV1(mandateId, bffUpdateRequest, options).then((request) => request(axios, basePath)); + }, + }; +}; + +/** + * MandateApi - object-oriented interface + * @export + * @class MandateApi + * @extends {BaseAPI} + */ +export class MandateApi extends BaseAPI { + /** + * + * @summary Accept a mandate + * @param {string} mandateId + * @param {BffAcceptRequest} bffAcceptRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public acceptMandateV1(mandateId: string, bffAcceptRequest: BffAcceptRequest, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).acceptMandateV1(mandateId, bffAcceptRequest, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Ritorna il numero totale di deleghe in base al filtro stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {CountMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public countMandatesByDelegateV1(status?: CountMandatesByDelegateV1StatusEnum, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).countMandatesByDelegateV1(status, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Create a new mandate, returns the just created mandate if successful + * @param {BffNewMandateRequest} bffNewMandateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public createMandateV1(bffNewMandateRequest: BffNewMandateRequest, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).createMandateV1(bffNewMandateRequest, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Ritorna la lista delle deleghe a carico in base al filtro per stato (se specificato). Se non è presente nessun filtro, sono ritornate tutte le deleghe attive e pending + * @param {GetMandatesByDelegateV1StatusEnum} [status] Stato della delega + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public getMandatesByDelegateV1(status?: GetMandatesByDelegateV1StatusEnum, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).getMandatesByDelegateV1(status, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Ritorna tutte le deleghe create + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public getMandatesByDelegatorV1(options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).getMandatesByDelegatorV1(options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Reject a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public rejectMandateV1(mandateId: string, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).rejectMandateV1(mandateId, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Revoke a mandate + * @param {string} mandateId + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public revokeMandateV1(mandateId: string, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).revokeMandateV1(mandateId, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Ritorna la lista delle deleghe a carico in base ai filtri per stato, gruppo/i e delegante (taxId) + * @param {number} size + * @param {BffSearchMandateRequest} bffSearchMandateRequest + * @param {string} [nextPageKey] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public searchMandatesByDelegateV1(size: number, bffSearchMandateRequest: BffSearchMandateRequest, nextPageKey?: string, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).searchMandatesByDelegateV1(size, bffSearchMandateRequest, nextPageKey, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * + * @summary Update a mandate + * @param {string} mandateId + * @param {BffUpdateRequest} bffUpdateRequest + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof MandateApi + */ + public updateMandateV1(mandateId: string, bffUpdateRequest: BffUpdateRequest, options?: RawAxiosRequestConfig) { + return MandateApiFp(this.configuration).updateMandateV1(mandateId, bffUpdateRequest, options).then((request) => request(this.axios, this.basePath)); + } +} + +/** + * @export + */ +export const CountMandatesByDelegateV1StatusEnum = { + Pending: 'pending', + Active: 'active', + Revoked: 'revoked', + Rejected: 'rejected', + Expired: 'expired' +} as const; +export type CountMandatesByDelegateV1StatusEnum = typeof CountMandatesByDelegateV1StatusEnum[keyof typeof CountMandatesByDelegateV1StatusEnum]; +/** + * @export + */ +export const GetMandatesByDelegateV1StatusEnum = { + Pending: 'pending', + Active: 'active', + Revoked: 'revoked', + Rejected: 'rejected', + Expired: 'expired' +} as const; +export type GetMandatesByDelegateV1StatusEnum = typeof GetMandatesByDelegateV1StatusEnum[keyof typeof GetMandatesByDelegateV1StatusEnum]; + + diff --git a/packages/pn-personagiuridica-webapp/src/generated-client/mandate/base.ts b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/base.ts new file mode 100644 index 0000000000..9b608b7818 --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/base.ts @@ -0,0 +1,86 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * PN BFF BE Microservice - Deleghe + * Documentation APIs v1.0 + * + * The version of the OpenAPI document: 1.0.0 + * Contact: pn@pagopa.it + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import type { Configuration } from './configuration'; +// Some imports not used depending on template conditions +// @ts-ignore +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; +import globalAxios from 'axios'; + +export const BASE_PATH = "https://webapi.notifichedigitali.it".replace(/\/+$/, ""); + +/** + * + * @export + */ +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +/** + * + * @export + * @interface RequestArgs + */ +export interface RequestArgs { + url: string; + options: RawAxiosRequestConfig; +} + +/** + * + * @export + * @class BaseAPI + */ +export class BaseAPI { + protected configuration: Configuration | undefined; + + constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { + if (configuration) { + this.configuration = configuration; + this.basePath = configuration.basePath ?? basePath; + } + } +}; + +/** + * + * @export + * @class RequiredError + * @extends {Error} + */ +export class RequiredError extends Error { + constructor(public field: string, msg?: string) { + super(msg); + this.name = "RequiredError" + } +} + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/packages/pn-personagiuridica-webapp/src/generated-client/mandate/common.ts b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/common.ts new file mode 100644 index 0000000000..19c873d0a8 --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/common.ts @@ -0,0 +1,150 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * PN BFF BE Microservice - Deleghe + * Documentation APIs v1.0 + * + * The version of the OpenAPI document: 1.0.0 + * Contact: pn@pagopa.it + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import type { Configuration } from "./configuration"; +import type { RequestArgs } from "./base"; +import type { AxiosInstance, AxiosResponse } from 'axios'; +import { RequiredError } from "./base"; + +/** + * + * @export + */ +export const DUMMY_BASE_URL = 'https://example.com' + +/** + * + * @throws {RequiredError} + * @export + */ +export const assertParamExists = function (functionName: string, paramName: string, paramValue: unknown) { + if (paramValue === null || paramValue === undefined) { + throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`); + } +} + +/** + * + * @export + */ +export const setApiKeyToObject = async function (object: any, keyParamName: string, configuration?: Configuration) { + if (configuration && configuration.apiKey) { + const localVarApiKeyValue = typeof configuration.apiKey === 'function' + ? await configuration.apiKey(keyParamName) + : await configuration.apiKey; + object[keyParamName] = localVarApiKeyValue; + } +} + +/** + * + * @export + */ +export const setBasicAuthToObject = function (object: any, configuration?: Configuration) { + if (configuration && (configuration.username || configuration.password)) { + object["auth"] = { username: configuration.username, password: configuration.password }; + } +} + +/** + * + * @export + */ +export const setBearerAuthToObject = async function (object: any, configuration?: Configuration) { + if (configuration && configuration.accessToken) { + const accessToken = typeof configuration.accessToken === 'function' + ? await configuration.accessToken() + : await configuration.accessToken; + object["Authorization"] = "Bearer " + accessToken; + } +} + +/** + * + * @export + */ +export const setOAuthToObject = async function (object: any, name: string, scopes: string[], configuration?: Configuration) { + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? await configuration.accessToken(name, scopes) + : await configuration.accessToken; + object["Authorization"] = "Bearer " + localVarAccessTokenValue; + } +} + +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (parameter == null) return; + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + +/** + * + * @export + */ +export const setSearchParams = function (url: URL, ...objects: any[]) { + const searchParams = new URLSearchParams(url.search); + setFlattenedQueryParams(searchParams, objects); + url.search = searchParams.toString(); +} + +/** + * + * @export + */ +export const serializeDataIfNeeded = function (value: any, requestOptions: any, configuration?: Configuration) { + const nonString = typeof value !== 'string'; + const needsSerialization = nonString && configuration && configuration.isJsonMime + ? configuration.isJsonMime(requestOptions.headers['Content-Type']) + : nonString; + return needsSerialization + ? JSON.stringify(value !== undefined ? value : {}) + : (value || ""); +} + +/** + * + * @export + */ +export const toPathString = function (url: URL) { + return url.pathname + url.search + url.hash +} + +/** + * + * @export + */ +export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { + return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; + return axios.request(axiosRequestArgs); + }; +} diff --git a/packages/pn-personagiuridica-webapp/src/generated-client/mandate/configuration.ts b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/configuration.ts new file mode 100644 index 0000000000..13c3633d61 --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/configuration.ts @@ -0,0 +1,110 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * PN BFF BE Microservice - Deleghe + * Documentation APIs v1.0 + * + * The version of the OpenAPI document: 1.0.0 + * Contact: pn@pagopa.it + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface ConfigurationParameters { + apiKey?: string | Promise | ((name: string) => string) | ((name: string) => Promise); + username?: string; + password?: string; + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); + basePath?: string; + serverIndex?: number; + baseOptions?: any; + formDataCtor?: new () => any; +} + +export class Configuration { + /** + * parameter for apiKey security + * @param name security name + * @memberof Configuration + */ + apiKey?: string | Promise | ((name: string) => string) | ((name: string) => Promise); + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + username?: string; + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + password?: string; + /** + * parameter for oauth2 security + * @param name security name + * @param scopes oauth2 scope + * @memberof Configuration + */ + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); + /** + * override base path + * + * @type {string} + * @memberof Configuration + */ + basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; + /** + * base options for axios calls + * + * @type {any} + * @memberof Configuration + */ + baseOptions?: any; + /** + * The FormData constructor that will be used to create multipart form data + * requests. You can inject this here so that execution environments that + * do not support the FormData class can still run the generated client. + * + * @type {new () => FormData} + */ + formDataCtor?: new () => any; + + constructor(param: ConfigurationParameters = {}) { + this.apiKey = param.apiKey; + this.username = param.username; + this.password = param.password; + this.accessToken = param.accessToken; + this.basePath = param.basePath; + this.serverIndex = param.serverIndex; + this.baseOptions = param.baseOptions; + this.formDataCtor = param.formDataCtor; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } +} diff --git a/packages/pn-personagiuridica-webapp/src/generated-client/mandate/index.ts b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/index.ts new file mode 100644 index 0000000000..c1764635f8 --- /dev/null +++ b/packages/pn-personagiuridica-webapp/src/generated-client/mandate/index.ts @@ -0,0 +1,18 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * PN BFF BE Microservice - Deleghe + * Documentation APIs v1.0 + * + * The version of the OpenAPI document: 1.0.0 + * Contact: pn@pagopa.it + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export * from "./api"; +export * from "./configuration"; + diff --git a/packages/pn-personagiuridica-webapp/src/models/Deleghe.ts b/packages/pn-personagiuridica-webapp/src/models/Deleghe.ts index ac44869eac..c7efd1881f 100644 --- a/packages/pn-personagiuridica-webapp/src/models/Deleghe.ts +++ b/packages/pn-personagiuridica-webapp/src/models/Deleghe.ts @@ -1,6 +1,5 @@ import { RecipientType } from '@pagopa-pn/pn-commons'; -import { User } from '../redux/auth/types'; import { Party } from './party'; export type DelegationData = { @@ -15,8 +14,6 @@ export type DelegationData = { export type DelegationColumnData = DelegationData & { menu: string }; -export type DelegationParty = { name: string | null; uniqueIdentifier: string }; - export interface NewDelegationFormProps { selectPersonaFisicaOrPersonaGiuridica: RecipientType; codiceFiscale: string; @@ -38,41 +35,22 @@ export interface Person { person: boolean; } -export interface CreateDelegationProps { +type DelegationParty = { name: string; uniqueIdentifier: string }; + +export interface NewMandateRequest { delegate: Person; visibilityIds: Array; verificationCode: string; dateto: string; } -export interface CreateDelegationResponse { - datefrom: string; - dateto: string; - delegate: Person; - delegator: Person | null; - mandateId: string; - status: string; - verificationCode: string; - visibilityIds: Array<{ - name: string; - uniqueIdentifier: string; - }>; -} - -export type UserAndDelegations = User & DelegationsList; - -export interface DelegationsList { - delegators: Array; - delegations: Array; -} - export enum DelegationStatus { ACTIVE = 'active', PENDING = 'pending', REJECTED = 'rejected', } -export interface IDelegation { +interface IDelegation { mandateId: string; status: DelegationStatus; visibilityIds: Array<{ @@ -93,25 +71,12 @@ export interface Delegate extends IDelegation { delegate: Person | null; } -export type Delegation = Delegator | Delegate; - -export interface RevocationModalProps { - open: boolean; - id: string; - type: string; -} - -export interface AcceptDelegationResponse { - id: string; - groups: Array<{ id: string; name: string }>; -} - -export interface GetDelegatorsParams { +interface GetDelegatorsParams { size: number; nextPageKey?: string; } -export interface GetDelegatorsRequest { +interface GetDelegatorsRequest { taxId?: string; groups?: Array; status?: Array; @@ -126,12 +91,3 @@ export interface GetDelegatorsResponse { export type GetDelegatorsFilters = GetDelegatorsParams & GetDelegatorsRequest; export type DelegatorsFormFilters = Omit & { page: number }; - -/** - * @deprecated since pn-5795 - */ -export interface DelegatorsNames { - id: string; - name: string; - mandateIds: Array; -} diff --git a/packages/pn-personagiuridica-webapp/src/pages/Deleghe.page.tsx b/packages/pn-personagiuridica-webapp/src/pages/Deleghe.page.tsx index 6de0212349..c84f44ab38 100644 --- a/packages/pn-personagiuridica-webapp/src/pages/Deleghe.page.tsx +++ b/packages/pn-personagiuridica-webapp/src/pages/Deleghe.page.tsx @@ -7,7 +7,11 @@ import { TabPanel, TitleBox } from '@pagopa-pn/pn-commons'; import LoadingPageWrapper from '../components/LoadingPageWrapper/LoadingPageWrapper'; import * as routes from '../navigation/routes.const'; -import { getDelegatesByCompany, getDelegators, getGroups } from '../redux/delegation/actions'; +import { + getGroups, + getMandatesByDelegator, + searchMandatesByDelegate, +} from '../redux/delegation/actions'; import { resetState } from '../redux/delegation/reducers'; import { useAppDispatch, useAppSelector } from '../redux/hooks'; import { RootState } from '../redux/store'; @@ -36,10 +40,10 @@ const Deleghe = () => { const retrieveData = useCallback(() => { // groups administrator cannot see the delegates by the company if (!hasGroup) { - void dispatch(getDelegatesByCompany()); + void dispatch(getMandatesByDelegator()); } if (DELEGATIONS_TO_PG_ENABLED) { - void dispatch(getDelegators({ size: 10 })); + void dispatch(searchMandatesByDelegate({ size: 10 })); void dispatch(getGroups()); } setPageReady(true); diff --git a/packages/pn-personagiuridica-webapp/src/pages/__test__/Deleghe.page.test.tsx b/packages/pn-personagiuridica-webapp/src/pages/__test__/Deleghe.page.test.tsx index 0218f9613b..3e37da6b87 100644 --- a/packages/pn-personagiuridica-webapp/src/pages/__test__/Deleghe.page.test.tsx +++ b/packages/pn-personagiuridica-webapp/src/pages/__test__/Deleghe.page.test.tsx @@ -3,13 +3,9 @@ import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { vi } from 'vitest'; import { userResponse } from '../../__mocks__/Auth.mock'; -import { arrayOfDelegates, arrayOfDelegators } from '../../__mocks__/Delegations.mock'; +import { mandatesByDelegate, mandatesByDelegator } from '../../__mocks__/Delegations.mock'; import { fireEvent, render, waitFor } from '../../__test__/test-utils'; import { apiClient } from '../../api/apiClients'; -import { - DELEGATIONS_BY_DELEGATE, - DELEGATIONS_BY_DELEGATOR, -} from '../../api/delegations/delegations.routes'; import { GET_GROUPS } from '../../api/external-registries/external-registries-routes'; import DelegatesByCompany from '../../components/Deleghe/DelegatesByCompany'; import DelegationsOfTheCompany from '../../components/Deleghe/DelegationsOfTheCompany'; @@ -40,9 +36,9 @@ describe('Deleghe page', async () => { }); it('renders deleghe page', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, arrayOfDelegates); - mock.onPost(DELEGATIONS_BY_DELEGATE({ size: 10 })).reply(200, { - resultsPage: arrayOfDelegators, + mock.onGet('/bff/v1/mandate/delegator').reply(200, mandatesByDelegator); + mock.onPost(`/bff/v1/mandate/delegate/?size=10`).reply(200, { + resultsPage: mandatesByDelegate, nextPagesKey: [], moreResult: false, }); @@ -73,9 +69,9 @@ describe('Deleghe page', async () => { }); it('test changing tab', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, arrayOfDelegates); - mock.onPost(DELEGATIONS_BY_DELEGATE({ size: 10 })).reply(200, { - resultsPage: arrayOfDelegators, + mock.onGet('/bff/v1/mandate/delegator').reply(200, mandatesByDelegator); + mock.onPost(`/bff/v1/mandate/delegate/?size=10`).reply(200, { + resultsPage: mandatesByDelegate, nextPagesKey: [], moreResult: false, }); @@ -102,7 +98,7 @@ describe('Deleghe page', async () => { }); it('user with groups', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, arrayOfDelegates); + mock.onGet('/bff/v1/mandate/delegator').reply(200, mandatesByDelegator); const { container, queryByTestId, getByTestId } = render( diff --git a/packages/pn-personagiuridica-webapp/src/pages/__test__/NotificationDetail.page.test.tsx b/packages/pn-personagiuridica-webapp/src/pages/__test__/NotificationDetail.page.test.tsx index 277254489c..1ccd7d0d02 100644 --- a/packages/pn-personagiuridica-webapp/src/pages/__test__/NotificationDetail.page.test.tsx +++ b/packages/pn-personagiuridica-webapp/src/pages/__test__/NotificationDetail.page.test.tsx @@ -20,7 +20,7 @@ import { import { downtimesDTO } from '../../__mocks__/AppStatus.mock'; import { userResponse } from '../../__mocks__/Auth.mock'; -import { arrayOfDelegators } from '../../__mocks__/Delegations.mock'; +import { mandatesByDelegate } from '../../__mocks__/Delegations.mock'; import { paymentInfo } from '../../__mocks__/ExternalRegistry.mock'; import { cachedPayments, @@ -78,7 +78,7 @@ const getLegalFactIds = (notification: NotificationDetailModel, recIndex: number return timelineElementDigitalSuccessWorkflow.legalFactsIds![0] as LegalFactId; }; -const delegator = arrayOfDelegators.find( +const delegator = mandatesByDelegate.find( (delegator) => delegator.delegator?.fiscalCode === notificationDTO.recipients[1].taxId ); diff --git a/packages/pn-personagiuridica-webapp/src/pages/__test__/NuovaDelega.page.test.tsx b/packages/pn-personagiuridica-webapp/src/pages/__test__/NuovaDelega.page.test.tsx index ada564f71f..1737fa2986 100644 --- a/packages/pn-personagiuridica-webapp/src/pages/__test__/NuovaDelega.page.test.tsx +++ b/packages/pn-personagiuridica-webapp/src/pages/__test__/NuovaDelega.page.test.tsx @@ -15,7 +15,6 @@ import { createDelegationPayload } from '../../__mocks__/CreateDelegation.mock'; import { parties } from '../../__mocks__/ExternalRegistry.mock'; import { RenderResult, act, fireEvent, render, waitFor } from '../../__test__/test-utils'; import { apiClient } from '../../api/apiClients'; -import { CREATE_DELEGATION } from '../../api/delegations/delegations.routes'; import { GET_ALL_ACTIVATED_PARTIES } from '../../api/external-registries/external-registries-routes'; import * as routes from '../../navigation/routes.const'; import { createDelegationMapper } from '../../redux/newDelegation/actions'; @@ -148,7 +147,7 @@ describe('NuovaDelega page', async () => { // simulate click of "back" button const backButton = result.getByTestId('breadcrumb-indietro-button'); - fireEvent.click(backButton!); + fireEvent.click(backButton); // after clicking "back" button - mocked page present await waitFor(() => { @@ -163,7 +162,7 @@ describe('NuovaDelega page', async () => { expirationDate: new Date('01/01/2122'), verificationCode: '34153', }; - mock.onPost(CREATE_DELEGATION()).reply(200, createDelegationMapper(creationPayload)); + mock.onPost('/bff/v1/mandate', createDelegationMapper(creationPayload)).reply(200); const { container, getByTestId, getByText } = render(); const form = container.querySelector('form') as HTMLFormElement; await testInput(form, 'nome', createDelegationPayload.nome); @@ -171,10 +170,10 @@ describe('NuovaDelega page', async () => { await testInput(form, 'codiceFiscale', createDelegationPayload.codiceFiscale); await testInput(form, 'expirationDate', '01/01/2122'); const button = getByTestId('createButton'); - fireEvent.click(button!); + fireEvent.click(button); await waitFor(() => { expect(mock.history.post).toHaveLength(1); - expect(mock.history.post[0].url).toBe(CREATE_DELEGATION()); + expect(mock.history.post[0].url).toBe('/bff/v1/mandate'); expect(JSON.parse(mock.history.post[0].data)).toStrictEqual( createDelegationMapper(creationPayload) ); @@ -194,7 +193,7 @@ describe('NuovaDelega page', async () => { // the form is validate on submit await testInput(container, 'expirationDate', ''); const button = getByTestId('createButton'); - fireEvent.click(button!); + fireEvent.click(button); // check errors on required field const nameError = container.querySelector('#nome-helper-text'); expect(nameError).toHaveTextContent('nuovaDelega.validation.name.required'); @@ -236,7 +235,7 @@ describe('NuovaDelega page', async () => { const businessName = container.querySelector('input[name="ragioneSociale"]'); expect(businessName).toBeInTheDocument(); // rerun form submission - fireEvent.click(button!); + fireEvent.click(button); const businessNameError = await waitFor(() => container.querySelector('#ragioneSociale-helper-text') ); @@ -252,7 +251,7 @@ describe('NuovaDelega page', async () => { enti: [parties[1]], selectTuttiEntiOrSelezionati: 'entiSelezionati', }; - mock.onPost(CREATE_DELEGATION()).reply(200, createDelegationMapper(creationPayload)); + mock.onPost('/bff/v1/mandate', createDelegationMapper(creationPayload)).reply(200); const { container, getByTestId } = render(); // switch to persona giuridica await testRadio( @@ -279,10 +278,10 @@ describe('NuovaDelega page', async () => { await testAutocomplete(container, 'enti', parties, true, 1); // create delegation const button = getByTestId('createButton'); - fireEvent.click(button!); + fireEvent.click(button); await waitFor(() => { expect(mock.history.post).toHaveLength(1); - expect(mock.history.post[0].url).toBe(CREATE_DELEGATION()); + expect(mock.history.post[0].url).toBe('/bff/v1/mandate'); expect(JSON.parse(mock.history.post[0].data)).toStrictEqual( createDelegationMapper(creationPayload) ); diff --git a/packages/pn-personagiuridica-webapp/src/redux/delegation/__test__/reducers.test.ts b/packages/pn-personagiuridica-webapp/src/redux/delegation/__test__/reducers.test.ts index d86a5f598e..df8a800905 100644 --- a/packages/pn-personagiuridica-webapp/src/redux/delegation/__test__/reducers.test.ts +++ b/packages/pn-personagiuridica-webapp/src/redux/delegation/__test__/reducers.test.ts @@ -1,35 +1,27 @@ import MockAdapter from 'axios-mock-adapter'; import { mockAuthentication } from '../../../__mocks__/Auth.mock'; -import { arrayOfDelegates, arrayOfDelegators } from '../../../__mocks__/Delegations.mock'; +import { mandatesByDelegate, mandatesByDelegator } from '../../../__mocks__/Delegations.mock'; import { createMockedStore } from '../../../__test__/test-utils'; import { apiClient } from '../../../api/apiClients'; -import { - ACCEPT_DELEGATION, - DELEGATIONS_BY_DELEGATE, - DELEGATIONS_BY_DELEGATOR, - REJECT_DELEGATION, - REVOKE_DELEGATION, - UPDATE_DELEGATION, -} from '../../../api/delegations/delegations.routes'; import { GET_GROUPS } from '../../../api/external-registries/external-registries-routes'; import { DelegationStatus } from '../../../models/Deleghe'; import { GroupStatus } from '../../../models/groups'; import { store } from '../../store'; import { - acceptDelegation, - getDelegatesByCompany, - getDelegators, + acceptMandate, getGroups, - rejectDelegation, - revokeDelegation, - updateDelegation, + getMandatesByDelegator, + rejectMandate, + revokeMandate, + searchMandatesByDelegate, + updateMandate, } from '../actions'; import { resetState, setFilters } from '../reducers'; -const pendingDelegator = arrayOfDelegators.find((d) => d.status === 'pending'); -const activeDelegator = arrayOfDelegators.find((d) => d.status === 'active'); -const pendingDelegates = arrayOfDelegates.find((d) => d.status === 'pending'); +const pendingDelegator = mandatesByDelegate.find((d) => d.status === 'pending'); +const activeDelegator = mandatesByDelegate.find((d) => d.status === 'active'); +const pendingDelegates = mandatesByDelegator.find((d) => d.status === 'pending'); const initialState = { delegations: { delegators: [], @@ -69,29 +61,29 @@ describe('delegation redux state tests', () => { }); it('should be able to fetch the delegates', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, arrayOfDelegates); - const action = await store.dispatch(getDelegatesByCompany()); - expect(action.type).toBe('getDelegatesByCompany/fulfilled'); - expect(action.payload).toEqual(arrayOfDelegates); + mock.onGet('/bff/v1/mandate/delegator').reply(200, mandatesByDelegator); + const action = await store.dispatch(getMandatesByDelegator()); + expect(action.type).toBe('getMandatesByDelegator/fulfilled'); + expect(action.payload).toEqual(mandatesByDelegator); }); it('should be able to fetch the delegates', async () => { - mock.onGet(DELEGATIONS_BY_DELEGATOR()).reply(200, arrayOfDelegates); - const action = await store.dispatch(getDelegatesByCompany()); - expect(action.type).toBe('getDelegatesByCompany/fulfilled'); - expect(action.payload).toEqual(arrayOfDelegates); + mock.onGet('/bff/v1/mandate/delegator').reply(200, mandatesByDelegator); + const action = await store.dispatch(getMandatesByDelegator()); + expect(action.type).toBe('getMandatesByDelegator/fulfilled'); + expect(action.payload).toEqual(mandatesByDelegator); }); it('should be able to fetch the delegators', async () => { - mock.onPost(DELEGATIONS_BY_DELEGATE({ size: 10 })).reply(200, { - resultsPage: arrayOfDelegators, + mock.onPost(`/bff/v1/mandate/delegate?size=10`).reply(200, { + resultsPage: mandatesByDelegate, nextPagesKey: [], moreResult: false, }); - const action = await store.dispatch(getDelegators({ size: 10 })); - expect(action.type).toBe('getDelegators/fulfilled'); + const action = await store.dispatch(searchMandatesByDelegate({ size: 10 })); + expect(action.type).toBe('searchMandatesByDelegate/fulfilled'); expect(action.payload).toEqual({ - resultsPage: arrayOfDelegators, + resultsPage: mandatesByDelegate, nextPagesKey: [], moreResult: false, }); @@ -103,25 +95,20 @@ describe('delegation redux state tests', () => { delegationsState: { ...initialState, delegations: { - delegators: arrayOfDelegators, + delegators: mandatesByDelegate, }, }, }); - mock - .onPatch(ACCEPT_DELEGATION(pendingDelegator!.mandateId)) - .reply(204, { id: pendingDelegator!.mandateId }); + mock.onPatch(`/bff/v1/mandate/${pendingDelegator!.mandateId}/accept`).reply(204); const action = await testStore.dispatch( - acceptDelegation({ + acceptMandate({ id: pendingDelegator!.mandateId, code: '12345', groups: [{ id: 'group-1', name: 'Group 1' }], }) ); - expect(action.type).toBe('acceptDelegation/fulfilled'); - expect(action.payload).toEqual({ - id: pendingDelegator!.mandateId, - groups: [{ id: 'group-1', name: 'Group 1' }], - }); + expect(action.type).toBe('acceptMandate/fulfilled'); + expect(action.payload).toEqual(void 0); const state = testStore.getState().delegationsState; expect(state.delegations.delegators[0].status).toBe('active'); expect(state.delegations.delegators[0].groups).toStrictEqual([ @@ -130,9 +117,9 @@ describe('delegation redux state tests', () => { }); it('should throw an error trying to accept a delegation', async () => { - mock.onPatch(ACCEPT_DELEGATION('1')).reply(500, 'error'); - const action = await store.dispatch(acceptDelegation({ id: '1', code: '12345', groups: [] })); - expect(action.type).toBe('acceptDelegation/rejected'); + mock.onPatch(`/bff/v1/mandate/1/accept`).reply(500, 'error'); + const action = await store.dispatch(acceptMandate({ id: '1', code: '12345', groups: [] })); + expect(action.type).toBe('acceptMandate/rejected'); expect(action.payload).toStrictEqual({ response: { status: 500, data: 'error' } }); }); @@ -142,17 +129,15 @@ describe('delegation redux state tests', () => { delegationsState: { ...initialState, delegations: { - delegators: arrayOfDelegators, + delegators: mandatesByDelegate, delegates: [], }, }, }); - mock - .onPatch(REJECT_DELEGATION(pendingDelegator!.mandateId)) - .reply(204, { id: pendingDelegator!.mandateId }); - const action = await testStore.dispatch(rejectDelegation(pendingDelegator!.mandateId)); - expect(action.type).toBe('rejectDelegation/fulfilled'); - expect(action.payload).toEqual({ id: pendingDelegator!.mandateId }); + mock.onPatch(`/bff/v1/mandate/${pendingDelegator!.mandateId}/reject`).reply(204); + const action = await testStore.dispatch(rejectMandate(pendingDelegator!.mandateId)); + expect(action.type).toBe('rejectMandate/fulfilled'); + expect(action.payload).toEqual(void 0); const state = testStore.getState().delegationsState; expect( state.delegations.delegators.find((d) => d.mandateId === pendingDelegator!.mandateId) @@ -160,9 +145,9 @@ describe('delegation redux state tests', () => { }); it('should throw an error trying to reject a delegation', async () => { - mock.onPatch(REJECT_DELEGATION('2')).reply(500, 'error'); - const action = await store.dispatch(rejectDelegation('2')); - expect(action.type).toBe('rejectDelegation/rejected'); + mock.onPatch(`/bff/v1/mandate/2/reject`).reply(500, 'error'); + const action = await store.dispatch(rejectMandate('2')); + expect(action.type).toBe('rejectMandate/rejected'); expect(action.payload).toEqual({ response: { status: 500, data: 'error' } }); }); @@ -172,16 +157,14 @@ describe('delegation redux state tests', () => { delegationsState: { ...initialState, delegations: { - delegates: arrayOfDelegates, + delegates: mandatesByDelegator, }, }, }); - mock - .onPatch(REVOKE_DELEGATION(pendingDelegates!.mandateId)) - .reply(204, { id: pendingDelegates!.mandateId }); - const action = await testStore.dispatch(revokeDelegation(pendingDelegates!.mandateId)); - expect(action.type).toBe('revokeDelegation/fulfilled'); - expect(action.payload).toEqual({ id: pendingDelegates!.mandateId }); + mock.onPatch(`/bff/v1/mandate/${pendingDelegates!.mandateId}/revoke`).reply(204); + const action = await testStore.dispatch(revokeMandate(pendingDelegates!.mandateId)); + expect(action.type).toBe('revokeMandate/fulfilled'); + expect(action.payload).toEqual(void 0); const state = testStore.getState().delegationsState; expect( state.delegations.delegates.find((d) => d.mandateId === pendingDelegates!.mandateId) @@ -189,9 +172,9 @@ describe('delegation redux state tests', () => { }); it('should throw an error trying to revoke a delegation', async () => { - mock.onPatch(REVOKE_DELEGATION('2')).reply(500, 'error'); - const action = await store.dispatch(revokeDelegation('2')); - expect(action.type).toBe('revokeDelegation/rejected'); + mock.onPatch(`/bff/v1/mandate/2/revoke`).reply(500, 'error'); + const action = await store.dispatch(revokeMandate('2')); + expect(action.type).toBe('revokeMandate/rejected'); expect(action.payload).toEqual({ response: { status: 500, data: 'error' } }); }); @@ -216,24 +199,19 @@ describe('delegation redux state tests', () => { delegationsState: { ...initialState, delegations: { - delegators: arrayOfDelegators, + delegators: mandatesByDelegate, }, }, }); - mock - .onPatch(UPDATE_DELEGATION(activeDelegator!.mandateId)) - .reply(204, { id: activeDelegator!.mandateId }); + mock.onPatch(`/bff/v1/mandate/${activeDelegator!.mandateId}/update`).reply(204); const action = await testStore.dispatch( - updateDelegation({ + updateMandate({ id: activeDelegator!.mandateId, groups: [{ id: 'group-1', name: 'Group 1' }], }) ); - expect(action.type).toBe('updateDelegation/fulfilled'); - expect(action.payload).toEqual({ - id: activeDelegator!.mandateId, - groups: [{ id: 'group-1', name: 'Group 1' }], - }); + expect(action.type).toBe('updateMandate/fulfilled'); + expect(action.payload).toEqual(void 0); const state = testStore.getState().delegationsState; const delegator = state.delegations.delegators.find( (d) => d.mandateId === activeDelegator!.mandateId @@ -242,9 +220,9 @@ describe('delegation redux state tests', () => { }); it('should throw an error trying to update a delegation', async () => { - mock.onPatch(UPDATE_DELEGATION('1')).reply(500, 'error'); - const action = await store.dispatch(updateDelegation({ id: '1', groups: [] })); - expect(action.type).toBe('updateDelegation/rejected'); + mock.onPatch(`/bff/v1/mandate/1/update`).reply(500, 'error'); + const action = await store.dispatch(updateMandate({ id: '1', groups: [] })); + expect(action.type).toBe('updateMandate/rejected'); expect(action.payload).toEqual({ response: { status: 500, data: 'error' } }); }); diff --git a/packages/pn-personagiuridica-webapp/src/redux/delegation/actions.ts b/packages/pn-personagiuridica-webapp/src/redux/delegation/actions.ts index 69579dcf49..ca7ccbb912 100644 --- a/packages/pn-personagiuridica-webapp/src/redux/delegation/actions.ts +++ b/packages/pn-personagiuridica-webapp/src/redux/delegation/actions.ts @@ -1,65 +1,111 @@ -import { performThunkAction } from '@pagopa-pn/pn-commons'; -import { createAsyncThunk, createAction } from '@reduxjs/toolkit'; -import { DelegationsApi } from '../../api/delegations/Delegations.api'; +import { parseError, performThunkAction } from '@pagopa-pn/pn-commons'; +import { createAction, createAsyncThunk } from '@reduxjs/toolkit'; + +import { apiClient } from '../../api/apiClients'; import { ExternalRegistriesAPI } from '../../api/external-registries/External-registries.api'; -import { - AcceptDelegationResponse, - Delegation, - GetDelegatorsFilters, - GetDelegatorsResponse, -} from '../../models/Deleghe'; +import { MandateApiFactory } from '../../generated-client/mandate'; +import { Delegate, GetDelegatorsFilters, GetDelegatorsResponse } from '../../models/Deleghe'; import { Groups } from '../../models/groups'; export enum DELEGATION_ACTIONS { - GET_DELEGATES_BY_COMPANY = 'getDelegatesByCompany', - GET_DELEGATORS = 'getDelegators', + GET_MANDATES_BY_DELEGATOR = 'getMandatesByDelegator', + SEARCH_MANDATES_BY_DELEGATE = 'searchMandatesByDelegate', + REVOKE_MANDATE = 'revokeMandate', + REJECT_MANDATE = 'rejectMandate', + ACCEPT_MANDATE = 'acceptMandate', + UPDATE_MANDATE = 'updateMandate', } -export const getDelegatesByCompany = createAsyncThunk>( - DELEGATION_ACTIONS.GET_DELEGATES_BY_COMPANY, - performThunkAction(() => DelegationsApi.getDelegatesByCompany()) +export const getMandatesByDelegator = createAsyncThunk>( + DELEGATION_ACTIONS.GET_MANDATES_BY_DELEGATOR, + async (_params, { rejectWithValue }) => { + try { + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.getMandatesByDelegatorV1(); + return response.data as Array; + } catch (e) { + return rejectWithValue(parseError(e)); + } + } ); -export const getDelegators = createAsyncThunk( - DELEGATION_ACTIONS.GET_DELEGATORS, - performThunkAction((params: GetDelegatorsFilters) => DelegationsApi.getDelegators(params)) -); +export const searchMandatesByDelegate = createAsyncThunk< + GetDelegatorsResponse, + GetDelegatorsFilters +>(DELEGATION_ACTIONS.SEARCH_MANDATES_BY_DELEGATE, async (params, { rejectWithValue }) => { + try { + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.searchMandatesByDelegateV1( + params.size, + { taxId: params.taxId, groups: params.groups, status: params.status }, + params.nextPageKey + ); + return response.data as GetDelegatorsResponse; + } catch (e) { + return rejectWithValue(parseError(e)); + } +}); -export const revokeDelegation = createAsyncThunk<{ id: string }, string>( - 'revokeDelegation', - performThunkAction((id) => DelegationsApi.revokeDelegation(id)) +export const revokeMandate = createAsyncThunk( + DELEGATION_ACTIONS.REVOKE_MANDATE, + async (params, { rejectWithValue }) => { + try { + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.revokeMandateV1(params); + return response.data; + } catch (e) { + return rejectWithValue(parseError(e)); + } + } ); -export const rejectDelegation = createAsyncThunk<{ id: string }, string>( - 'rejectDelegation', - performThunkAction((id) => DelegationsApi.rejectDelegation(id)) +export const rejectMandate = createAsyncThunk( + DELEGATION_ACTIONS.REJECT_MANDATE, + async (params, { rejectWithValue }) => { + try { + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.rejectMandateV1(params); + return response.data; + } catch (e) { + return rejectWithValue(parseError(e)); + } + } ); -export const acceptDelegation = createAsyncThunk< - AcceptDelegationResponse, +export const acceptMandate = createAsyncThunk< + void, { id: string; code: string; groups: Array<{ id: string; name: string }> } ->( - 'acceptDelegation', - performThunkAction(({ id, code, groups }) => { - const data = { - verificationCode: code, - groups, - }; - return DelegationsApi.acceptDelegation(id, data); - }) -); +>(DELEGATION_ACTIONS.ACCEPT_MANDATE, async (params, { rejectWithValue }) => { + try { + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.acceptMandateV1(params.id, { + verificationCode: params.code, + groups: params.groups.map((g) => g.id), + }); + return response.data; + } catch (e) { + return rejectWithValue(parseError(e)); + } +}); export const getGroups = createAsyncThunk>( 'getGroups', performThunkAction(() => ExternalRegistriesAPI.getGroups()) ); -export const updateDelegation = createAsyncThunk< - AcceptDelegationResponse, +export const updateMandate = createAsyncThunk< + void, { id: string; groups: Array<{ id: string; name: string }> } ->( - 'updateDelegation', - performThunkAction(({ id, groups }) => DelegationsApi.updateDelegation(id, groups)) -); +>(DELEGATION_ACTIONS.UPDATE_MANDATE, async (params, { rejectWithValue }) => { + try { + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.updateMandateV1(params.id, { + groups: params.groups.map((g) => g.id), + }); + return response.data; + } catch (e) { + return rejectWithValue(parseError(e)); + } +}); export const resetDelegationsState = createAction('resetDelegationsState'); diff --git a/packages/pn-personagiuridica-webapp/src/redux/delegation/reducers.ts b/packages/pn-personagiuridica-webapp/src/redux/delegation/reducers.ts index 9ac31c0ea7..93fc9978aa 100644 --- a/packages/pn-personagiuridica-webapp/src/redux/delegation/reducers.ts +++ b/packages/pn-personagiuridica-webapp/src/redux/delegation/reducers.ts @@ -1,21 +1,21 @@ import { PayloadAction, createSlice } from '@reduxjs/toolkit'; -import { Delegation, DelegationStatus, DelegatorsFormFilters } from '../../models/Deleghe'; +import { Delegate, DelegationStatus, Delegator, DelegatorsFormFilters } from '../../models/Deleghe'; import { Groups } from '../../models/groups'; import { - acceptDelegation, - getDelegatesByCompany, - getDelegators, + acceptMandate, getGroups, - rejectDelegation, - revokeDelegation, - updateDelegation, + getMandatesByDelegator, + rejectMandate, + revokeMandate, + searchMandatesByDelegate, + updateMandate, } from './actions'; const initialState = { delegations: { - delegators: [] as Array, - delegates: [] as Array, + delegators: [] as Array, + delegates: [] as Array, }, pagination: { nextPagesKey: [] as Array, @@ -54,10 +54,10 @@ const delegationsSlice = createSlice({ resetState: () => initialState, }, extraReducers: (builder) => { - builder.addCase(getDelegatesByCompany.fulfilled, (state, action) => { + builder.addCase(getMandatesByDelegator.fulfilled, (state, action) => { state.delegations.delegates = action.payload; }); - builder.addCase(getDelegators.fulfilled, (state, action) => { + builder.addCase(searchMandatesByDelegate.fulfilled, (state, action) => { state.delegations.delegators = action.payload.resultsPage; state.pagination.moreResult = action.payload.moreResult; // because we can jump from a page to another and nextPagesKey returns only the next three pages, we have to check if that pages already exists @@ -69,34 +69,34 @@ const delegationsSlice = createSlice({ } } }); - builder.addCase(acceptDelegation.fulfilled, (state, action) => { - state.delegations.delegators = state.delegations.delegators.map((delegator: Delegation) => - delegator.mandateId === action.payload.id - ? { ...delegator, status: DelegationStatus.ACTIVE, groups: action.payload.groups } + builder.addCase(acceptMandate.fulfilled, (state, action) => { + state.delegations.delegators = state.delegations.delegators.map((delegator) => + delegator.mandateId === action.meta.arg.id + ? { ...delegator, status: DelegationStatus.ACTIVE, groups: action.meta.arg.groups } : delegator ); }); - builder.addCase(revokeDelegation.fulfilled, (state, action) => { + builder.addCase(revokeMandate.fulfilled, (state, action) => { state.delegations.delegates = state.delegations.delegates.filter( - (delegate: Delegation) => delegate.mandateId !== action.payload.id + (delegate) => delegate.mandateId !== action.meta.arg ); }); - builder.addCase(rejectDelegation.fulfilled, (state, action) => { + builder.addCase(rejectMandate.fulfilled, (state, action) => { state.delegations.delegators = state.delegations.delegators.filter( - (delegator: Delegation) => delegator.mandateId !== action.meta.arg + (delegator) => delegator.mandateId !== action.meta.arg ); // because a PG can delegate itself, we must check if the rejected delegation is in delegates object and remove it state.delegations.delegates = state.delegations.delegates.filter( - (delegate) => delegate.mandateId !== action.payload.id + (delegate) => delegate.mandateId !== action.meta.arg ); }); builder.addCase(getGroups.fulfilled, (state, action) => { state.groups = action.payload; }); - builder.addCase(updateDelegation.fulfilled, (state, action) => { - state.delegations.delegators = state.delegations.delegators.map((delegator: Delegation) => - delegator.mandateId === action.payload.id - ? { ...delegator, groups: action.payload.groups } + builder.addCase(updateMandate.fulfilled, (state, action) => { + state.delegations.delegators = state.delegations.delegators.map((delegator) => + delegator.mandateId === action.meta.arg.id + ? { ...delegator, groups: action.meta.arg.groups } : delegator ); }); diff --git a/packages/pn-personagiuridica-webapp/src/redux/newDelegation/__test__/reducers.test.ts b/packages/pn-personagiuridica-webapp/src/redux/newDelegation/__test__/reducers.test.ts index b2754ad983..a846151e99 100644 --- a/packages/pn-personagiuridica-webapp/src/redux/newDelegation/__test__/reducers.test.ts +++ b/packages/pn-personagiuridica-webapp/src/redux/newDelegation/__test__/reducers.test.ts @@ -5,12 +5,10 @@ import { createDelegationDuplicatedErrorResponse, createDelegationGenericErrorResponse, createDelegationPayload, - createDelegationResponse, createDelegationSelectedPayload, } from '../../../__mocks__/CreateDelegation.mock'; import { parties } from '../../../__mocks__/ExternalRegistry.mock'; import { apiClient } from '../../../api/apiClients'; -import { CREATE_DELEGATION } from '../../../api/delegations/delegations.routes'; import { GET_ALL_ACTIVATED_PARTIES } from '../../../api/external-registries/external-registries-routes'; import { store } from '../../store'; import { createDelegation, createDelegationMapper, getAllEntities } from '../actions'; @@ -44,26 +42,24 @@ describe('delegation redux state tests', () => { }); it('creates a new delegation with all organizations', async () => { - mock - .onPost(CREATE_DELEGATION(), createDelegationMapper(createDelegationPayload)) - .reply(200, createDelegationResponse); + mock.onPost('/bff/v1/mandate', createDelegationMapper(createDelegationPayload)).reply(200); const action = await store.dispatch(createDelegation(createDelegationPayload)); expect(action.type).toBe('createDelegation/fulfilled'); - expect(action.payload).toEqual(createDelegationResponse); + expect(action.payload).toEqual(void 0); }); it('creates a new delegation with a single organization', async () => { mock - .onPost(CREATE_DELEGATION(), createDelegationMapper(createDelegationSelectedPayload)) - .reply(200, createDelegationResponse); + .onPost('/bff/v1/mandate', createDelegationMapper(createDelegationSelectedPayload)) + .reply(200); const action = await store.dispatch(createDelegation(createDelegationSelectedPayload)); expect(action.type).toBe('createDelegation/fulfilled'); - expect(action.payload).toEqual(createDelegationResponse); + expect(action.payload).toEqual(void 0); }); it("can't create a new delegation", async () => { mock - .onPost(CREATE_DELEGATION(), createDelegationMapper(createDelegationPayload)) + .onPost('/bff/v1/mandate', createDelegationMapper(createDelegationPayload)) .reply(401, createDelegationGenericErrorResponse); const action = await store.dispatch(createDelegation(createDelegationPayload)); expect(action.type).toBe('createDelegation/rejected'); @@ -72,7 +68,7 @@ describe('delegation redux state tests', () => { it("can't create a new delegation (duplicated)", async () => { mock - .onPost(CREATE_DELEGATION(), createDelegationMapper(createDelegationPayload)) + .onPost('/bff/v1/mandate', createDelegationMapper(createDelegationPayload)) .reply(400, createDelegationDuplicatedErrorResponse); const action = await store.dispatch(createDelegation(createDelegationPayload)); expect(action.type).toBe('createDelegation/rejected'); diff --git a/packages/pn-personagiuridica-webapp/src/redux/newDelegation/actions.ts b/packages/pn-personagiuridica-webapp/src/redux/newDelegation/actions.ts index b316dcb602..6e2be2a5c7 100644 --- a/packages/pn-personagiuridica-webapp/src/redux/newDelegation/actions.ts +++ b/packages/pn-personagiuridica-webapp/src/redux/newDelegation/actions.ts @@ -1,18 +1,13 @@ -import { RecipientType, formatToSlicedISOString } from '@pagopa-pn/pn-commons'; +import { RecipientType, formatToSlicedISOString, parseError } from '@pagopa-pn/pn-commons'; import { createAsyncThunk } from '@reduxjs/toolkit'; -import { DelegationsApi } from '../../api/delegations/Delegations.api'; +import { apiClient } from '../../api/apiClients'; import { ExternalRegistriesAPI } from '../../api/external-registries/External-registries.api'; -import { - CreateDelegationProps, - CreateDelegationResponse, - DelegationParty, - NewDelegationFormProps, - Person, -} from '../../models/Deleghe'; +import { MandateApiFactory } from '../../generated-client/mandate'; +import { NewDelegationFormProps, NewMandateRequest, Person } from '../../models/Deleghe'; import { FilterPartiesParams, Party } from '../../models/party'; -export function createDelegationMapper(formData: NewDelegationFormProps): CreateDelegationProps { +export function createDelegationMapper(formData: NewDelegationFormProps): NewMandateRequest { const delegate = { fiscalCode: formData.codiceFiscale, } as Person; @@ -39,21 +34,23 @@ export function createDelegationMapper(formData: NewDelegationFormProps): Create return { uniqueIdentifier: ente.id, name: ente.name, - } as DelegationParty; + }; }), verificationCode: formData.verificationCode, dateto: formatToSlicedISOString(formData.expirationDate), }; } -export const createDelegation = createAsyncThunk( +export const createDelegation = createAsyncThunk( 'createDelegation', async (data, { rejectWithValue }) => { - const payload = createDelegationMapper(data); try { - return await DelegationsApi.createDelegation(payload); + const payload = createDelegationMapper(data); + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.createMandateV1(payload); + return response.data; } catch (e: any) { - return rejectWithValue(e); + return rejectWithValue(parseError(e)); } } ); diff --git a/packages/pn-personagiuridica-webapp/src/redux/sidemenu/__test__/reducers.test.ts b/packages/pn-personagiuridica-webapp/src/redux/sidemenu/__test__/reducers.test.ts index fff0c58260..a9a93bb664 100644 --- a/packages/pn-personagiuridica-webapp/src/redux/sidemenu/__test__/reducers.test.ts +++ b/packages/pn-personagiuridica-webapp/src/redux/sidemenu/__test__/reducers.test.ts @@ -2,13 +2,8 @@ import MockAdapter from 'axios-mock-adapter'; import { mockAuthentication } from '../../../__mocks__/Auth.mock'; import { apiClient } from '../../../api/apiClients'; -import { - ACCEPT_DELEGATION, - COUNT_DELEGATORS, - REJECT_DELEGATION, -} from '../../../api/delegations/delegations.routes'; import { DelegationStatus } from '../../../models/Deleghe'; -import { acceptDelegation, rejectDelegation } from '../../delegation/actions'; +import { acceptMandate, rejectMandate } from '../../delegation/actions'; import { store } from '../../store'; import { getSidemenuInformation } from '../actions'; import { closeDomicileBanner } from '../reducers'; @@ -48,7 +43,9 @@ describe('Sidemenu redux state tests', () => { }); it('Should load delegators count', async () => { - mock.onGet(COUNT_DELEGATORS(DelegationStatus.PENDING)).reply(200, { value: 2 }); + mock + .onGet(`/bff/v1/mandate/delegate/count?status=${DelegationStatus.PENDING}`) + .reply(200, { value: 2 }); const action = await store.dispatch(getSidemenuInformation()); const state = store.getState().generalInfoState; expect(action.type).toBe('getSidemenuInformation/fulfilled'); @@ -56,24 +53,28 @@ describe('Sidemenu redux state tests', () => { }); it('Should update state after accepting a delegation', async () => { - mock.onPatch(ACCEPT_DELEGATION('1dc53e54-1368-4c2d-8583-2f1d672350d8')).reply(204); - mock.onGet(COUNT_DELEGATORS(DelegationStatus.PENDING)).reply(200, { value: 2 }); + mock.onPatch('/bff/v1/mandate/1dc53e54-1368-4c2d-8583-2f1d672350d8/accept').reply(204); + mock + .onGet(`/bff/v1/mandate/delegate/count?status=${DelegationStatus.PENDING}`) + .reply(200, { value: 2 }); await store.dispatch(getSidemenuInformation()); const action = await store.dispatch( - acceptDelegation({ id: '1dc53e54-1368-4c2d-8583-2f1d672350d8', code: '12345', groups: [] }) + acceptMandate({ id: '1dc53e54-1368-4c2d-8583-2f1d672350d8', code: '12345', groups: [] }) ); const state = store.getState().generalInfoState; - expect(action.type).toBe('acceptDelegation/fulfilled'); + expect(action.type).toBe('acceptMandate/fulfilled'); expect(state.pendingDelegators).toBe(1); }); it('Should update state after rejecting a pending delegation', async () => { - mock.onPatch(REJECT_DELEGATION('1dc53e54-1368-4c2d-8583-2f1d672350d8')).reply(204); - mock.onGet(COUNT_DELEGATORS(DelegationStatus.PENDING)).reply(200, { value: 2 }); + mock.onPatch('/bff/v1/mandate/1dc53e54-1368-4c2d-8583-2f1d672350d8/reject').reply(204); + mock + .onGet(`/bff/v1/mandate/delegate/count?status=${DelegationStatus.PENDING}`) + .reply(200, { value: 2 }); await store.dispatch(getSidemenuInformation()); - const action = await store.dispatch(rejectDelegation('1dc53e54-1368-4c2d-8583-2f1d672350d8')); + const action = await store.dispatch(rejectMandate('1dc53e54-1368-4c2d-8583-2f1d672350d8')); const state = store.getState().generalInfoState; - expect(action.type).toBe('rejectDelegation/fulfilled'); + expect(action.type).toBe('rejectMandate/fulfilled'); expect(state.pendingDelegators).toBe(1); }); }); diff --git a/packages/pn-personagiuridica-webapp/src/redux/sidemenu/actions.ts b/packages/pn-personagiuridica-webapp/src/redux/sidemenu/actions.ts index 97b2055e71..88398073a0 100644 --- a/packages/pn-personagiuridica-webapp/src/redux/sidemenu/actions.ts +++ b/packages/pn-personagiuridica-webapp/src/redux/sidemenu/actions.ts @@ -1,36 +1,42 @@ -import { performThunkAction } from '@pagopa-pn/pn-commons'; +import { parseError } from '@pagopa-pn/pn-commons'; import { createAsyncThunk } from '@reduxjs/toolkit'; import { apiClient } from '../../api/apiClients'; -import { DelegationsApi } from '../../api/delegations/Delegations.api'; import { AddressesApiFactory } from '../../generated-client/digital-addresses'; +import { MandateApiFactory } from '../../generated-client/mandate'; import { DelegationStatus } from '../../models/Deleghe'; import { DigitalAddress } from '../../models/contacts'; export enum SIDEMENU_ACTIONS { GET_SIDEMENU_INFORMATION = 'getSidemenuInformation', + GET_DOMICILE_INFO = 'getDomicileInfo', } export const getSidemenuInformation = createAsyncThunk( SIDEMENU_ACTIONS.GET_SIDEMENU_INFORMATION, - async () => { + async (_, { rejectWithValue }) => { try { - const response = await DelegationsApi.countDelegators(DelegationStatus.PENDING); - return response.value; - } catch (e) { - return 0; + const mandateApiFactory = MandateApiFactory(undefined, undefined, apiClient); + const response = await mandateApiFactory.countMandatesByDelegateV1(DelegationStatus.PENDING); + return response.data.value ?? 0; + } catch (e: any) { + return rejectWithValue(parseError(e)); } } ); export const getDomicileInfo = createAsyncThunk>( - 'getDomicileInfo', - performThunkAction(async () => { - const isDefaultAddress = (address: DigitalAddress) => address.senderId === 'default'; - const digitalAddressesFactory = AddressesApiFactory(undefined, undefined, apiClient); - const response = await digitalAddressesFactory.getAddressesV1(); - const allAddresses = response.data as Array; + SIDEMENU_ACTIONS.GET_DOMICILE_INFO, + async (_, { rejectWithValue }) => { + try { + const isDefaultAddress = (address: DigitalAddress) => address.senderId === 'default'; + const digitalAddressesFactory = AddressesApiFactory(undefined, undefined, apiClient); + const response = await digitalAddressesFactory.getAddressesV1(); + const allAddresses = response.data as Array; - return [...allAddresses.filter(isDefaultAddress)]; - }) + return [...allAddresses.filter(isDefaultAddress)]; + } catch (e: any) { + return rejectWithValue(parseError(e)); + } + } ); diff --git a/packages/pn-personagiuridica-webapp/src/redux/sidemenu/reducers.ts b/packages/pn-personagiuridica-webapp/src/redux/sidemenu/reducers.ts index 2c2c1d6500..e013a4e4a9 100644 --- a/packages/pn-personagiuridica-webapp/src/redux/sidemenu/reducers.ts +++ b/packages/pn-personagiuridica-webapp/src/redux/sidemenu/reducers.ts @@ -1,7 +1,7 @@ import { createSlice, isAnyOf } from '@reduxjs/toolkit'; import { DigitalAddress } from '../../models/contacts'; -import { acceptDelegation, rejectDelegation } from '../delegation/actions'; +import { acceptMandate, rejectMandate } from '../delegation/actions'; import { getDomicileInfo, getSidemenuInformation } from './actions'; /* eslint-disable functional/immutable-data */ @@ -24,7 +24,7 @@ const generalInfoSlice = createSlice({ builder.addCase(getDomicileInfo.fulfilled, (state, action) => { state.defaultAddresses = action.payload; }); - builder.addMatcher(isAnyOf(acceptDelegation.fulfilled, rejectDelegation.fulfilled), (state) => { + builder.addMatcher(isAnyOf(acceptMandate.fulfilled, rejectMandate.fulfilled), (state) => { if (state.pendingDelegators > 0) { state.pendingDelegators--; } diff --git a/packages/pn-personagiuridica-webapp/src/utility/__test__/delegation.utility.test.ts b/packages/pn-personagiuridica-webapp/src/utility/__test__/delegation.utility.test.ts index f5c6feb574..34bb00846e 100644 --- a/packages/pn-personagiuridica-webapp/src/utility/__test__/delegation.utility.test.ts +++ b/packages/pn-personagiuridica-webapp/src/utility/__test__/delegation.utility.test.ts @@ -2,7 +2,7 @@ import crypto from 'crypto'; import { formatDate } from '@pagopa-pn/pn-commons'; -import { arrayOfDelegates, arrayOfDelegators } from '../../__mocks__/Delegations.mock'; +import { mandatesByDelegate, mandatesByDelegator } from '../../__mocks__/Delegations.mock'; import delegationToItem, { generateVCode, sortDelegations } from '../delegation.utility'; Object.defineProperty(global, 'crypto', { @@ -13,8 +13,8 @@ Object.defineProperty(global, 'crypto', { describe('Delegation utility test', () => { it('Should convert an delegation array of delegate to an item array - delegate', () => { - const item = delegationToItem(arrayOfDelegates); - const expected = arrayOfDelegates.map((delegation) => ({ + const item = delegationToItem(mandatesByDelegator); + const expected = mandatesByDelegator.map((delegation) => ({ id: delegation.mandateId, name: delegation.delegate?.displayName, // la data arriva nel formato YYYY-MM-DDZ rimuovere slice in caso di rimozione di Z @@ -29,8 +29,8 @@ describe('Delegation utility test', () => { }); it('Should convert an delegation array of delegate to an item array - delegator', () => { - const item = delegationToItem(arrayOfDelegators); - const expected = arrayOfDelegators.map((delegation) => ({ + const item = delegationToItem(mandatesByDelegate); + const expected = mandatesByDelegate.map((delegation) => ({ id: delegation.mandateId, name: delegation.delegator?.displayName, // la data arriva nel formato YYYY-MM-DDZ rimuovere slice in caso di rimozione di Z @@ -53,64 +53,64 @@ describe('Delegation utility test', () => { it('sort delegation by name - delegates', () => { // sort ascending const sortedCopy = (order: 'asc' | 'desc') => - [...arrayOfDelegates].sort((a, b) => { + [...mandatesByDelegator].sort((a, b) => { const multiplier = order === 'asc' ? 1 : -1; if (a.delegate?.displayName === b.delegate?.displayName) { return 0; } return (a.delegate?.displayName! < b.delegate?.displayName! ? -1 : 1) * multiplier; }); - let result = sortDelegations('asc', 'displayName', arrayOfDelegates); + let result = sortDelegations('asc', 'displayName', mandatesByDelegator); expect(sortedCopy('asc')).toStrictEqual(result); // sort descending - result = sortDelegations('desc', 'displayName', arrayOfDelegates); + result = sortDelegations('desc', 'displayName', mandatesByDelegator); expect(sortedCopy('desc')).toStrictEqual(result); }); it('sort delegation by endDate - delegates', () => { const sortedCopy = (order: 'asc' | 'desc') => - [...arrayOfDelegates].sort((a, b) => { + [...mandatesByDelegator].sort((a, b) => { const multiplier = order === 'asc' ? 1 : -1; const dateA = new Date(a.dateto).getTime(); const dateB = new Date(b.dateto).getTime(); return (dateA - dateB) * multiplier; }); - let result = sortDelegations('asc', 'endDate', arrayOfDelegates); + let result = sortDelegations('asc', 'endDate', mandatesByDelegator); expect(sortedCopy('asc')).toStrictEqual(result); - result = sortDelegations('desc', 'endDate', arrayOfDelegates); + result = sortDelegations('desc', 'endDate', mandatesByDelegator); expect(sortedCopy('desc')).toStrictEqual(result); }); it('sort delegation by name - delegators', () => { // sort ascending const sortedCopy = (order: 'asc' | 'desc') => - [...arrayOfDelegators].sort((a, b) => { + [...mandatesByDelegate].sort((a, b) => { const multiplier = order === 'asc' ? 1 : -1; if (a.delegator?.displayName === b.delegator?.displayName) { return 0; } return (a.delegator?.displayName! < b.delegator?.displayName! ? -1 : 1) * multiplier; }); - let result = sortDelegations('asc', 'displayName', arrayOfDelegators); + let result = sortDelegations('asc', 'displayName', mandatesByDelegate); expect(sortedCopy('asc')).toStrictEqual(result); // sort descending - result = sortDelegations('desc', 'displayName', arrayOfDelegators); + result = sortDelegations('desc', 'displayName', mandatesByDelegate); expect(sortedCopy('desc')).toStrictEqual(result); }); it('sort delegation by endDate - delegators', () => { // sort ascending const sortedCopy = (order: 'asc' | 'desc') => - [...arrayOfDelegators].sort((a, b) => { + [...mandatesByDelegate].sort((a, b) => { const multiplier = order === 'asc' ? 1 : -1; const dateA = new Date(a.dateto).getTime(); const dateB = new Date(b.dateto).getTime(); return (dateA - dateB) * multiplier; }); - let result = sortDelegations('asc', 'endDate', arrayOfDelegators); + let result = sortDelegations('asc', 'endDate', mandatesByDelegate); expect(sortedCopy('asc')).toStrictEqual(result); // sort descending - result = sortDelegations('desc', 'endDate', arrayOfDelegators); + result = sortDelegations('desc', 'endDate', mandatesByDelegate); expect(sortedCopy('desc')).toStrictEqual(result); }); }); diff --git a/packages/pn-personagiuridica-webapp/src/utility/delegation.utility.ts b/packages/pn-personagiuridica-webapp/src/utility/delegation.utility.ts index faa11e4b7e..1da527e1bd 100644 --- a/packages/pn-personagiuridica-webapp/src/utility/delegation.utility.ts +++ b/packages/pn-personagiuridica-webapp/src/utility/delegation.utility.ts @@ -1,17 +1,17 @@ import { Row, formatDate } from '@pagopa-pn/pn-commons'; -import { Delegation, DelegationData, Person } from '../models/Deleghe'; +import { Delegate, DelegationData, Delegator, Person } from '../models/Deleghe'; /** * Maps Delegation object to Item, in order to be visualised in an PnCardsList or PnTable component - * @param {Array} delegations + * @param {Array} delegations * @param {boolean} isDelegator * @returns Array */ -export default function delegationToItem( - delegations: Array +export default function delegationToItem( + delegations: Array ): Array> { - return delegations.map((delegation: Delegation) => ({ + return delegations.map((delegation: T) => ({ id: delegation.mandateId, name: getFirstName(delegation), // la data arriva nel formato YYYY-MM-DDZ rimuovere slice in caso di rimozione di Z @@ -32,9 +32,13 @@ export function generateVCode() { return crypto.getRandomValues(array).toString().slice(0, 5); } -export function sortDelegations(order: string, sortAttr: string, values: Array) { +export function sortDelegations( + order: string, + sortAttr: string, + values: Array +) { /* eslint-disable-next-line functional/immutable-data */ - return values.sort((a: Delegation, b: Delegation) => { + return values.sort((a: T, b: T) => { const orderDirection = order === 'desc' ? 1 : -1; if (sortAttr === 'endDate') { const dateA = new Date(a.dateto).getTime(); @@ -45,7 +49,7 @@ export function sortDelegations(order: string, sortAttr: string, values: Array(a: T, b: T, orderAttr: string) { if ('delegator' in a && a.delegator && 'delegator' in b && b.delegator) { const delegator1 = compareOrderAttribute(a.delegator, orderAttr); const delegator2 = compareOrderAttribute(b.delegator, orderAttr); @@ -65,7 +69,7 @@ function compareOrderAttribute(person: Person, orderAttr: string) { : person[orderAttr as keyof Person] ?? ''; } -function getFirstName(delegation: Delegation): string { +function getFirstName(delegation: T): string { if ('delegator' in delegation && delegation.delegator) { return `${delegation.delegator?.displayName}`; } else if ('delegate' in delegation && delegation.delegate) {