Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat!(policies): Create or re-use already created policies in manual upload #80

Merged
merged 3 commits into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/assets/locales/de/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"previewTableTitle": "Vorschau des semantischen Modells inkl. Beschreibung",
"uploadStep_1": "1. Wählen Sie die Datei aus, welche hochgeladen werden soll",
"uploadStep_2": "2. Klicken Sie auf „Nächster Schritt – Policies konfigurieren“ um festzulegen wer die Daten (ggf. mit Einschränkungen) sehen darf und um die entsprechenden „Digitalen Zwillinge“ zu erzeugen/registrieren.",
"uploadStep_3": "3. Erstellen Sie eine neue Richtlinie oder verwenden Sie eine bereits erstellte.",
"manualStep_1": "1. Klicken Sie auf „Zeile einfügen“ um die Daten für eine neue Zeile erfassen zu können. Zur Eingabe müssen Sie das entsprechende Feld anklicken",
"manualInfo_1": "Um einen neuen Datensatz (Digitalen Zwilling) anzulegen, lassen Sie das Feld UUID bitte leer",
"manualInfo_2": "Um einen bestehenden Datensatz zu aktualisieren, geben Sie bitte die UUID dieses Datensatzes (Digitaler Zwilling) an."
Expand Down
1 change: 1 addition & 0 deletions src/assets/locales/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"previewTableTitle": "Preview of Submodel including help description",
"uploadStep_1": "1. Choose the file you want to upload.",
"uploadStep_2": "2. Click on “Next Step – Configure Policies” to manage with whom to share your data and register the digital twin(s)",
"uploadStep_3": "3. Create a new policy or use and already created one",
"manualStep_1": "1. For manual entries click 'add a row' and enter the values by clicking inside the respective fields.",
"manualInfo_1": "For creating new data leave the field 'UUID' empty.",
"manualInfo_2": "For updating existing data you need to enter the respective 'UUID' of the digital twin."
Expand Down
13 changes: 5 additions & 8 deletions src/components/SubmodelDataTable.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/********************************************************************************
* Copyright (c) 2021,2022,2023 T-Systems International GmbH
* Copyright (c) 2022,2023 Contributors to the Eclipse Foundation
* Copyright (c) 2022,2024 T-Systems International GmbH
* Copyright (c) 2022,2024 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
Expand All @@ -26,6 +26,7 @@ import { addRows, deleteRows, setRows, setSelectionModel } from '../features/pro
import { useAppDispatch, useAppSelector } from '../features/store';
import { schemaValidator } from '../helpers/SchemaValidator';
import InfoSteps from './InfoSteps';
import UploadInfo from './provider/UploadInfo';

export default function DataTable() {
const { submodelDetails, columns, rows, selectionModel, selectedRows } = useAppSelector(state => state.submodelSlice);
Expand All @@ -34,12 +35,8 @@ export default function DataTable() {

return (
<Box>
<InfoSteps
icon="info"
steps={['content.provider.manualStep_1', 'content.provider.uploadStep_2']}
sx={{ mb: 3 }}
/>
<Box display="flex" justifyContent="space-between" mb={3}>
<UploadInfo />
<Box display="flex" justifyContent="space-between" my={3}>
<Box>
<Button variant="contained" size="small" onClick={() => dispatch(addRows())}>
{t('content.provider.addRow')}
Expand Down
4 changes: 2 additions & 2 deletions src/components/UploadFile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import { useAppDispatch, useAppSelector } from '../features/store';
import { Config } from '../utils/config';
import { DEFAULT_POLICY_DATA } from '../utils/constants';
import { trimText } from '../utils/utils';
import InfoSteps from './InfoSteps';
import UploadInfo from './provider/UploadInfo';

export default function UploadFile() {
const { selectedFiles, uploadStatus } = useAppSelector(state => state.uploadFileSlice);
Expand Down Expand Up @@ -160,7 +160,7 @@ export default function UploadFile() {
)}
</Box>
</Box>
<InfoSteps icon="info" steps={['content.provider.uploadStep_1', 'content.provider.uploadStep_2']} />
<UploadInfo />
</>
);
}
2 changes: 1 addition & 1 deletion src/components/dialogs/OfferDetailsDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const OfferDetailsDialog = ({ open, offerObj, handleConfirm, handleClose, isMult
created,
description,
publisher,
policy: { usage_policies: usagePolicies },
policy: { Usage: usagePolicies },
fileContentType,
} = offer;
const { t } = useTranslation();
Expand Down
100 changes: 100 additions & 0 deletions src/components/policies/PolicySelection.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/********************************************************************************
* Copyright (c) 2024 T-Systems International GmbH
* Copyright (c) 2024 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/

import { Box, FormControl } from '@mui/material';
import { SelectList } from 'cx-portal-shared-components';
import { useEffect, useState } from 'react';

import { NEW_POLICY_ITEM } from '../../constants/policies';
import { prepareFormData } from '../../features/provider/policies/actions';
import { useGetPoliciesQuery, useGetSinglePolicyMutation } from '../../features/provider/policies/apiSlice';
import { setPolicyData, setSelectedPolicy } from '../../features/provider/policies/slice';
import { PolicyHubResponse } from '../../features/provider/policies/types';
import { useAppDispatch, useAppSelector } from '../../features/store';
import { ISelectList } from '../../models/Common';

function PolicySelection({ data }: { data: PolicyHubResponse[] }) {
const { policyDialogType, selectedPolicy } = useAppSelector(state => state.policySlice);
const showPolicySelection = policyDialogType === 'FileWithPolicy' || policyDialogType === 'TableWithPolicy';
const [policyList, setPolicyList] = useState([]);
const dispatch = useAppDispatch();

const { data: policyListResponse, isSuccess: isPolicyDataSuccess } = useGetPoliciesQuery(
{},
{ skip: !showPolicySelection },
);
const [getSinglePolicy] = useGetSinglePolicyMutation();

useEffect(() => {
dispatch(setSelectedPolicy(NEW_POLICY_ITEM));
}, [dispatch]);

useEffect(() => {
if (isPolicyDataSuccess) {
const list = policyListResponse?.items.map((policy: any) => {
return {
id: policy.uuid,
title: policy.policy_name,
value: 'EXISTING',
};
});
setPolicyList([NEW_POLICY_ITEM, ...list]);
}
}, [isPolicyDataSuccess, policyListResponse]);

const handlePolicySelection = async (item: ISelectList) => {
dispatch(setSelectedPolicy(item));
if (item.value === 'NEW') {
dispatch(prepareFormData({ data }));
} else {
await getSinglePolicy(item.id)
.unwrap()
.then((res: any) => {
if (res) {
dispatch(setPolicyData(res));
dispatch(prepareFormData({ data, edit: true }));
}
});
}
};

if (showPolicySelection) {
return (
<Box>
<FormControl sx={{ mb: 1, width: 300 }}>
<SelectList
keyTitle="title"
defaultValue={selectedPolicy}
items={policyList}
variant="filled"
label={'Create new or choose existing policy'}
placeholder="Select a value"
type={'text'}
disableClearable={true}
onChangeItem={handlePolicySelection}
/>
</FormControl>
</Box>
);
} else return null;
}

export default PolicySelection;
32 changes: 32 additions & 0 deletions src/components/provider/UploadInfo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/********************************************************************************
* Copyright (c) 2024 T-Systems International GmbH
* Copyright (c) 2024 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/

import InfoSteps from '../InfoSteps';

function UploadInfo() {
return (
<InfoSteps
icon="tips"
steps={['content.provider.uploadStep_1', 'content.provider.uploadStep_2', 'content.provider.uploadStep_3']}
/>
);
}

export default UploadInfo;
2 changes: 1 addition & 1 deletion src/features/app/apiSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export const apiSlice = createApi({
},
}),
}),
tagTypes: ['UploadHistory', 'DeleteContract'],
tagTypes: ['UploadHistory', 'DeleteContract', 'Policies'],
});

export const { useGetUseCasesQuery, useGetPermissionsQuery } = apiSlice;
32 changes: 22 additions & 10 deletions src/features/provider/policies/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ import { createAsyncThunk } from '@reduxjs/toolkit';
import { omit } from 'lodash';

import { PolicyHubModel } from '../../../models/Polices.models';
import ProviderService from '../../../services/ProviderService';
import { setSnackbarMessage } from '../../notifiication/slice';
import { RootState } from '../../store';
import { clearRows } from '../submodels/slice';
import { uploadApiSlice } from '../upload/apiSlice';
import { removeSelectedFiles } from '../upload/slice';
import { handleDialogClose, setPolicyFormData } from './slice';
import { PolicyHubResponse } from './types';
Expand All @@ -46,14 +46,20 @@ const uploadFileWithPolicy = createAsyncThunk('/upload-file-with-policy', async
const state = getState() as RootState;
const { selectedFiles } = state.uploadFileSlice;
const { selectedSubmodel } = state.submodelSlice;
const { selectedPolicy } = state.policySlice;

const formData = new FormData();
formData.append('file', selectedFiles[0]);
formData.append('meta_data', JSON.stringify({ ...omit(data, 'lastUpdatedTime'), type: 'NEW' }));
formData.append('meta_data', JSON.stringify({ ...omit(data, 'lastUpdatedTime'), type: selectedPolicy.value }));

try {
await ProviderService.getInstance()
.uploadData(selectedSubmodel.value, formData)
await dispatch(
uploadApiSlice.endpoints.uploadFile.initiate({
submodel: selectedSubmodel.value,
data: formData,
}),
)
.unwrap()
.then(res => {
if (res) {
dispatch(clearUpload());
Expand All @@ -76,14 +82,20 @@ const uploadTableWithPolicy = createAsyncThunk(
async (formData: any, { dispatch, getState }) => {
const state = getState() as RootState;
const { selectedSubmodel, rows } = state.submodelSlice;
const { selectedPolicy } = state.policySlice;

try {
await ProviderService.getInstance()
.submitSubmodalData(selectedSubmodel.value, {
...omit(formData, 'lastUpdatedTime'),
row_data: rows,
type: 'NEW',
})
await dispatch(
uploadApiSlice.endpoints.uploadManualEntry.initiate({
submodel: selectedSubmodel.value,
data: {
...omit(formData, 'lastUpdatedTime'),
row_data: rows,
type: selectedPolicy.value,
},
}),
)
.unwrap()
.then(res => {
if (res) {
dispatch(clearUpload());
Expand Down
21 changes: 20 additions & 1 deletion src/features/provider/policies/apiSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,24 @@ import { apiSlice } from '../../app/apiSlice';

export const policiesApiSlice = apiSlice.injectEndpoints({
endpoints: builder => ({
getPolicies: builder.query({
query: params => {
return {
url: '/policy',
params,
};
},
providesTags: ['Policies'],
onQueryStarted: setLoadingHandler,
}),
getSinglePolicy: builder.mutation({
query: uuid => {
return {
url: `/policy/${uuid}`,
};
},
onQueryStarted: setLoadingHandler,
}),
validateBpn: builder.mutation({
query: bpn => {
return {
Expand All @@ -42,4 +60,5 @@ export const policiesApiSlice = apiSlice.injectEndpoints({
}),
});

export const { useValidateBpnMutation, useGetPolicyTemplateQuery } = policiesApiSlice;
export const { useValidateBpnMutation, useGetPolicyTemplateQuery, useGetPoliciesQuery, useGetSinglePolicyMutation } =
policiesApiSlice;
7 changes: 7 additions & 0 deletions src/features/provider/policies/slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { isArray } from 'lodash';

import { NEW_POLICY_ITEM } from '../../../constants/policies';
import { ISelectList } from '../../../models/Common';
import { IAccessPolicyState } from './types';

const initialState: IAccessPolicyState = {
Expand All @@ -30,6 +32,7 @@ const initialState: IAccessPolicyState = {
policyDialog: false,
policyDialogType: '',
policyFormData: {},
selectedPolicy: NEW_POLICY_ITEM,
};

export const policySlice = createSlice({
Expand All @@ -46,6 +49,9 @@ export const policySlice = createSlice({
state.policyDialogType = action.payload;
},
handleDialogClose: state => Object.assign(state, initialState),
setSelectedPolicy: (state, action: PayloadAction<ISelectList>) => {
state.selectedPolicy = action.payload;
},
setPolicyFormData: (state, action: PayloadAction<any>) => {
state.policyFormData = action.payload;
},
Expand Down Expand Up @@ -76,6 +82,7 @@ export const {
handleDialogClose,
setPolicyFormData,
handlePolicyFormData,
setSelectedPolicy,
} = policySlice.actions;

export default policySlice.reducer;
3 changes: 3 additions & 0 deletions src/features/provider/policies/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,15 @@

import { Key } from 'react';

import { ISelectList } from '../../../models/Common';

export interface IAccessPolicyState {
openDialog: boolean;
policyData: any;
policyDialog: boolean;
policyDialogType: string;
policyFormData: any;
selectedPolicy: ISelectList;
}
export interface PolicyHubResponse {
technicalKey: string;
Expand Down
Loading
Loading