Add new code new version
[sdc.git] / openecomp-ui / src / sdc-app / onboarding / softwareProduct / SoftwareProductActionHelper.js
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 import RestAPIUtil from 'nfvo-utils/RestAPIUtil.js';
22 import Configuration from 'sdc-app/config/Configuration.js';
23 import i18n from 'nfvo-utils/i18n/i18n.js';
24 import LicenseModelActionHelper from 'sdc-app/onboarding/licenseModel/LicenseModelActionHelper.js';
25 import LicenseAgreementActionHelper from 'sdc-app/onboarding/licenseModel/licenseAgreement/LicenseAgreementActionHelper.js';
26 import FeatureGroupsActionHelper from 'sdc-app/onboarding/licenseModel/featureGroups/FeatureGroupsActionHelper.js';
27
28 import {actionTypes} from './SoftwareProductConstants.js';
29 import NotificationConstants from 'nfvo-components/notifications/NotificationConstants.js';
30 import OnboardingActionHelper from 'sdc-app/onboarding/OnboardingActionHelper.js';
31 import SoftwareProductComponentsActionHelper from './components/SoftwareProductComponentsActionHelper.js';
32 import {actionsEnum as VersionControllerActionsEnum} from 'nfvo-components/panel/versionController/VersionControllerConstants.js';
33
34 function baseUrl() {
35         const restPrefix = Configuration.get('restPrefix');
36         return `${restPrefix}/v1.0/vendor-software-products/`;
37 }
38 function softwareProductCategoriesUrl() {
39         const restATTPrefix = Configuration.get('restATTPrefix');
40         return `${restATTPrefix}/v1/categories/resources/`;
41 }
42
43 function uploadFile(vspId, formData) {
44
45         return RestAPIUtil.create(`${baseUrl()}${vspId}/upload`, formData);
46
47 }
48
49 function putSoftwareProduct(softwareData) {
50         return RestAPIUtil.save(`${baseUrl()}${softwareData.id}`, {
51                 name: softwareData.name,
52                 description: softwareData.description,
53                 category: softwareData.category,
54                 subCategory: softwareData.subCategory,
55                 vendorId: softwareData.vendorId,
56                 vendorName: softwareData.vendorName,
57                 licensingVersion: softwareData.licensingVersion,
58                 icon: softwareData.icon,
59                 licensingData: softwareData.licensingData
60         });
61 }
62
63 function putSoftwareProductQuestionnaire(vspId, qdata) {
64         return RestAPIUtil.save(`${baseUrl()}${vspId}/questionnaire`, qdata);
65 }
66
67 function putSoftwareProductAction(id, action) {
68         return RestAPIUtil.save(`${baseUrl()}${id}/actions`, {action: action});
69 }
70
71 function fetchSoftwareProductList() {
72         return RestAPIUtil.fetch(baseUrl());
73 }
74
75 function fetchSoftwareProduct(vspId, version) {
76         let versionQuery = version ? `?version=${version}` : '';
77         return RestAPIUtil.fetch(`${baseUrl()}${vspId}${versionQuery}`);
78 }
79
80 function fetchSoftwareProductQuestionnaire(vspId, version) {
81         let versionQuery = version ? `?version=${version}` : '';
82         return RestAPIUtil.fetch(`${baseUrl()}${vspId}/questionnaire${versionQuery}`);
83 }
84
85 function objToString(obj) {
86         let str = '';
87         if (obj instanceof Array) {
88                 obj.forEach((item) => {
89                         str += objToString(item) + '\n';
90                 });
91         } else {
92                 for (let p in obj) {
93                         if (obj.hasOwnProperty(p)) {
94                                 str += obj[p] + '\n';
95                         }
96                 }
97         }
98         return str;
99 }
100
101 function parseUploadErrorMsg(error) {
102         let message = '';
103         for (let key in error) {
104                 if (error.hasOwnProperty(key)) {
105                         message += objToString(error[key]) + '\n';
106                 }
107         }
108         return message;
109 }
110
111 function fetchSoftwareProductCategories(dispatch) {
112         let handleResponse = response => dispatch({
113                 type: actionTypes.SOFTWARE_PRODUCT_CATEGORIES_LOADED,
114                 softwareProductCategories: response
115         });
116         return RestAPIUtil.fetch(softwareProductCategoriesUrl())
117                 .then(handleResponse)
118                 .fail(() => handleResponse(null));
119 }
120
121 function loadLicensingData(dispatch, {licenseModelId, licensingVersion}) {
122         LicenseAgreementActionHelper.fetchLicenseAgreementList(dispatch, {licenseModelId, version: licensingVersion});
123         FeatureGroupsActionHelper.fetchFeatureGroupsList(dispatch, {licenseModelId, version: licensingVersion});
124 }
125
126 function getExpandedItemsId(items, itemIdToToggle) {
127         for(let i = 0; i < items.length; i++) {
128                 if(items[i].id === itemIdToToggle) {
129                         if (items[i].expanded) {
130                                 return {};
131                         } else {
132                                 return {[itemIdToToggle]: true};
133                         }
134                 }
135                 else if(items[i].items && items[i].items.length > 0) {
136                         let mapOfExpandedIds = getExpandedItemsId(items[i].items, itemIdToToggle);
137                         if (mapOfExpandedIds !== false) {
138                                 mapOfExpandedIds[items[i].id] = true;
139                                 return mapOfExpandedIds;
140                         }
141                 }
142         }
143         return false;
144 }
145
146 const SoftwareProductActionHelper = {
147
148         loadSoftwareProductAssociatedData(dispatch) {
149                 fetchSoftwareProductCategories(dispatch);
150                 LicenseModelActionHelper.fetchFinalizedLicenseModels(dispatch);
151         },
152
153         loadSoftwareProductDetailsData(dispatch, {licenseModelId, licensingVersion}) {
154                 SoftwareProductActionHelper.loadSoftwareProductAssociatedData(dispatch);
155                 loadLicensingData(dispatch, {licenseModelId, licensingVersion});
156         },
157
158         fetchSoftwareProductList(dispatch) {
159                 return fetchSoftwareProductList().then(response => dispatch({
160                         type: actionTypes.SOFTWARE_PRODUCT_LIST_LOADED,
161                         response
162                 }));
163         },
164
165         uploadFile(dispatch, {softwareProductId, formData, failedNotificationTitle}) {
166                 Promise.resolve()
167                         .then(() => uploadFile(softwareProductId, formData))
168                         .then(response => {
169                                 if (response.status !== 'Success') {
170                                         throw new Error(parseUploadErrorMsg(response.errors));
171                                 }
172                         })
173                         .then(() => {
174                                 SoftwareProductComponentsActionHelper.fetchSoftwareProductComponents(dispatch, {softwareProductId});
175                                 OnboardingActionHelper.navigateToSoftwareProductAttachments(dispatch, {softwareProductId});
176                                 SoftwareProductActionHelper.fetchSoftwareProduct(dispatch, {softwareProductId});
177                         })
178                         .catch(error => {
179                                 dispatch({
180                                         type: NotificationConstants.NOTIFY_ERROR,
181                                         data: {title: failedNotificationTitle, msg: error.message}
182                                 });
183                         });
184         },
185
186         uploadConfirmation(dispatch, {softwareProductId, formData, failedNotificationTitle}) {
187                 dispatch({
188                         type: actionTypes.softwareProductEditor.UPLOAD_CONFIRMATION,
189                         uploadData: {
190                                 softwareProductId,
191                                 formData,
192                                 failedNotificationTitle
193                         }
194                 });
195         },
196         hideUploadConfirm (dispatch) {
197                 dispatch({
198                         type: actionTypes.softwareProductEditor.UPLOAD_CONFIRMATION
199                 });
200         },
201         updateSoftwareProduct(dispatch, {softwareProduct, qdata}) {
202                 return Promise.all([
203                         SoftwareProductActionHelper.updateSoftwareProductData(dispatch, {softwareProduct}).then(
204                                 () => dispatch({
205                                         type: actionTypes.SOFTWARE_PRODUCT_LIST_EDIT,
206                                         payload: {softwareProduct}
207                                 })
208                         ),
209                         SoftwareProductActionHelper.updateSoftwareProductQuestionnaire(dispatch, {
210                                 softwareProductId: softwareProduct.id,
211                                 qdata
212                         })
213                 ]);
214         },
215
216         updateSoftwareProductData(dispatch, {softwareProduct}) {
217                 return putSoftwareProduct(softwareProduct);
218         },
219
220         updateSoftwareProductQuestionnaire(dispatch, {softwareProductId, qdata}) {
221                 return putSoftwareProductQuestionnaire(softwareProductId, qdata);
222         },
223
224         softwareProductEditorDataChanged(dispatch, {deltaData}) {
225                 dispatch({
226                         type: actionTypes.softwareProductEditor.DATA_CHANGED,
227                         deltaData
228                 });
229         },
230
231         softwareProductQuestionnaireUpdate(dispatch, {data}) {
232                 dispatch({
233                         type: actionTypes.SOFTWARE_PRODUCT_QUESTIONNAIRE_UPDATE,
234                         payload: {qdata: data}
235                 });
236         },
237
238         softwareProductEditorVendorChanged(dispatch, {deltaData}) {
239                 LicenseAgreementActionHelper.fetchLicenseAgreementList(dispatch, {licenseModelId: deltaData.vendorId, version: deltaData.licensingVersion});
240                 FeatureGroupsActionHelper.fetchFeatureGroupsList(dispatch, {licenseModelId: deltaData.vendorId, version: deltaData.licensingVersion});
241                 SoftwareProductActionHelper.softwareProductEditorDataChanged(dispatch, {deltaData});
242         },
243
244         setIsValidityData(dispatch, {isValidityData}) {
245                 dispatch({
246                         type: actionTypes.softwareProductEditor.IS_VALIDITY_DATA_CHANGED,
247                         isValidityData
248                 });
249         },
250
251         addSoftwareProduct(dispatch, {softwareProduct}) {
252                 dispatch({
253                         type: actionTypes.ADD_SOFTWARE_PRODUCT,
254                         softwareProduct
255                 });
256         },
257
258         fetchSoftwareProduct(dispatch, {softwareProductId, version}) {
259                 return Promise.all([
260                         fetchSoftwareProduct(softwareProductId, version).then(response => {
261                                 dispatch({
262                                         type: actionTypes.SOFTWARE_PRODUCT_LOADED,
263                                         response
264                                 });
265                                 return response;
266                         }),
267                         fetchSoftwareProductQuestionnaire(softwareProductId, version).then(response => {
268                                 dispatch({
269                                         type: actionTypes.SOFTWARE_PRODUCT_QUESTIONNAIRE_UPDATE,
270                                         payload: {
271                                                 qdata: response.data ? JSON.parse(response.data) : {},
272                                                 qschema: JSON.parse(response.schema)
273                                         }
274                                 });
275                         })
276                 ]);
277         },
278
279         performVCAction(dispatch, {softwareProductId, action}) {
280                 if (action === VersionControllerActionsEnum.SUBMIT) {
281                         return putSoftwareProductAction(softwareProductId, action).then(() => {
282                                 return putSoftwareProductAction(softwareProductId, VersionControllerActionsEnum.CREATE_PACKAGE).then(() => {
283                                         dispatch({
284                                                 type: NotificationConstants.NOTIFY_SUCCESS,
285                                                 data: {
286                                                         title: i18n('Submit Succeeded'),
287                                                         msg: i18n('This software product successfully submitted'),
288                                                         timeout: 2000
289                                                 }
290                                         });
291                                         fetchSoftwareProduct(softwareProductId).then(response => {
292                                                 dispatch({
293                                                         type: actionTypes.SOFTWARE_PRODUCT_LOADED,
294                                                         response
295                                                 });
296                                         });
297                                 });
298                         }, error => dispatch({
299                                 type: NotificationConstants.NOTIFY_ERROR,
300                                 data: {title: i18n('Submit Failed'), validationResponse: error.responseJSON}
301                         }));
302                 }
303                 else {
304                         return putSoftwareProductAction(softwareProductId, action).then(() => {
305                                 fetchSoftwareProduct(softwareProductId).then(response => {
306                                         dispatch({
307                                                 type: actionTypes.SOFTWARE_PRODUCT_LOADED,
308                                                 response
309                                         });
310                                 });
311                         });
312                 }
313         },
314
315         switchVersion(dispatch, {softwareProductId, licenseModelId, version}) {
316                 OnboardingActionHelper.navigateToSoftwareProductLandingPage(dispatch, {softwareProductId, licenseModelId, version});
317         },
318
319         toggleNavigationItems(dispatch, {items, itemIdToExpand}) {
320                 let mapOfExpandedIds = getExpandedItemsId(items, itemIdToExpand);
321                 dispatch({
322                         type: actionTypes.TOGGLE_NAVIGATION_ITEM,
323                         mapOfExpandedIds
324                 });
325         },
326
327         /** for the next verision */
328         addComponent(dispatch) {
329                 return dispatch;
330         }
331 };
332
333 export default SoftwareProductActionHelper;