[SDC-29] Amdocs OnBoard 1707 initial commit.
[sdc.git] / openecomp-ui / src / sdc-app / heatvalidation / UploadScreenActionHelper.js
1 /*!
2  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13  * or implied. See the License for the specific language governing
14  * permissions and limitations under the License.
15  */
16 import RestAPIUtil from 'nfvo-utils/RestAPIUtil.js';
17 import i18n from 'nfvo-utils/i18n/i18n.js';
18 import isEqual from 'lodash/isEqual.js';
19 import cloneDeep from 'lodash/cloneDeep.js';
20 import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js';
21 import {modalContentMapper} from 'sdc-app/common/modal/ModalContentMapper.js';
22 import {actionTypes as softwareProductsActionTypes} from '../onboarding/softwareProduct/SoftwareProductConstants.js';
23 import {actionTypes as HeatSetupActions} from '../onboarding/softwareProduct/attachments/setup/HeatSetupConstants.js';
24
25
26
27 const options = {
28         headers: {
29                 HTTP_CSP_ATTUID: 'validationOnlyVspUser'
30         }
31 };
32
33
34 function getTimestampString() {
35         let date = new Date();
36         let z = n => n < 10 ? '0' + n : n;
37         return `${date.getFullYear()}-${z(date.getMonth())}-${z(date.getDate())}_${z(date.getHours())}-${z(date.getMinutes())}`;
38 }
39
40 function fetchVspId() {
41
42         let vspId = sessionStorage.getItem('validationAppVspId');
43         if (vspId) {
44                 return  Promise.resolve({value: vspId});
45         }else {
46                 return RestAPIUtil.fetch('/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/validation-vsp', options)
47                         .then(response => {
48                                 sessionStorage.setItem('validationAppVspId', response.value);
49                                 return Promise.resolve(response);
50                         });
51         }
52
53 }
54
55
56 function showFileSaveDialog({blob, xhr, defaultFilename, addTimestamp}) {
57         let filename;
58         let contentDisposition = xhr.getResponseHeader('content-disposition');
59         let match = contentDisposition ? contentDisposition.match(/filename=(.*?)(;|$)/) : false;
60         if (match) {
61                 filename = match[1];
62         } else {
63                 filename = defaultFilename;
64         }
65
66         if (addTimestamp) {
67                 filename = filename.replace(/(^.*?)\.([^.]+$)/, `$1_${getTimestampString()}.$2`);
68         }
69
70         let link = document.createElement('a');
71         let url = URL.createObjectURL(blob);
72         link.href = url;
73         link.download = filename;
74         link.style.display = 'none';
75         document.body.appendChild(link);
76         link.click();
77         setTimeout(function(){
78                 document.body.removeChild(link);
79                 URL.revokeObjectURL(url);
80         }, 0);
81 }
82
83
84 function uploadFile(formData) {
85         return fetchVspId()
86                 .then(response => {
87                         return RestAPIUtil.post(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/0.1/orchestration-template-candidate`, formData, options);
88                 });
89 }
90
91 function loadSoftwareProductHeatCandidate(dispatch){
92         return fetchVspId()
93                 .then(response => {
94                         return RestAPIUtil.fetch(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/0.1/orchestration-template-candidate/manifest`, options)
95                                 .then(response => dispatch({
96                                         type: HeatSetupActions.MANIFEST_LOADED,
97                                         response
98                                 }));
99                 });
100 }
101
102 function updateHeatCandidate(dispatch, heatCandidate) {
103         return fetchVspId()
104                 .then(response => {
105                         return RestAPIUtil.put(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/0.1/orchestration-template-candidate/manifest`,
106                                 heatCandidate.heatData, options)
107                                 .then(null, error => {
108                                         dispatch({
109                                                 type: modalActionTypes.GLOBAL_MODAL_ERROR,
110                                                 data: {
111                                                         title: i18n('Save Failed'), 
112                                                         modalComponentName: modalContentMapper.SUMBIT_ERROR_RESPONSE,                                                   
113                                                         modalComponentProps: {
114                                                                 validationResponse: error.responseJSON
115                                                         },                                      
116                                                         cancelButtonText: i18n('Ok')
117                                                 }
118                                         });
119                                         return Promise.reject(error);
120                                 });
121                 });
122 }
123
124 function fetchSoftwareProduct() {
125         return fetchVspId()
126                 .then(response => {
127                         return RestAPIUtil.fetch(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/0.1`, options);
128                 });
129 }
130
131 function downloadHeatFile() {
132         return fetchVspId()
133                 .then(response => {
134                         RestAPIUtil.fetch(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/0.1/orchestration-template-candidate`, {
135                                 ...options,
136                                 dataType: 'binary'
137                         })
138                                 .done((blob, statusText, xhr) => showFileSaveDialog({
139                                         blob,
140                                         xhr,
141                                         defaultFilename: 'HEAT_file.zip',
142                                         addTimestamp: true
143                                 }));
144                 });
145 }
146
147 function processAndValidateHeatCandidate(dispatch) {
148         return fetchVspId()
149                 .then(response => {
150                         return RestAPIUtil.put(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/0.1/orchestration-template-candidate/process`, {}, options)
151                                 .then(response => {
152                                         if (response.status === 'Success') {
153                                                 fetchSoftwareProduct().then(response => {
154                                                         dispatch({
155                                                                 type: softwareProductsActionTypes.SOFTWARE_PRODUCT_LOADED,
156                                                                 response
157                                                         });
158                                                 });
159                                         }
160                                 });
161                 });
162 }
163
164 const UploadScreenActionHelper = {
165         uploadFile(dispatch, formData) {
166
167                 return Promise.resolve()
168                         .then(() => uploadFile(formData))
169                         .then(response => {
170                                 dispatch({
171                                         type: softwareProductsActionTypes.SOFTWARE_PRODUCT_LOADED,
172                                         response
173                                 });
174                                 dispatch({
175                                         type: HeatSetupActions.FILL_HEAT_SETUP_CACHE,
176                                         payload:{}
177                                 });
178                                 loadSoftwareProductHeatCandidate(dispatch);
179                         })
180                         .catch(error => {
181                                 dispatch({                                      
182                                         type: modalActionTypes.GLOBAL_MODAL_ERROR,
183                                         data: {
184                                                 title: i18n('File Upload Failed'),                                                                                                      
185                                                 msg: error.responseJSON.message,                                        
186                                                 cancelButtonText: i18n('Ok')
187                                         }
188                                 });
189                         });
190         },
191
192         processAndValidateHeat(dispatch, heatData, heatDataCache){
193                 return isEqual(heatData, heatDataCache) ? Promise.resolve() :
194                         updateHeatCandidate(dispatch, heatData)
195                                 .then(() => processAndValidateHeatCandidate(dispatch))
196                                 .then(() => dispatch({type: HeatSetupActions.FILL_HEAT_SETUP_CACHE, payload: cloneDeep(heatData)}));
197         },
198
199         downloadHeatFile(){
200                 return downloadHeatFile();
201         },
202 };
203
204 export default UploadScreenActionHelper;