Obtain and control VSP package upload status

Obtain the upload status and control the upload from the frontend
perspective.

Change-Id: Idcc921cf592efea33df35c557afcfae827af3a39
Issue-ID: SDC-3862
Signed-off-by: andre.schmid <andre.schmid@est.tech>
diff --git a/openecomp-ui/src/nfvo-components/loader/LoaderReducer.js b/openecomp-ui/src/nfvo-components/loader/LoaderReducer.js
index 3f9eb17..4222c3d 100644
--- a/openecomp-ui/src/nfvo-components/loader/LoaderReducer.js
+++ b/openecomp-ui/src/nfvo-components/loader/LoaderReducer.js
@@ -32,7 +32,9 @@
                 isLoading: true
             };
         case actionTypes.RECEIVE_RESPONSE:
-            fetchingRequests--;
+            if (fetchingRequests > 0) {
+                fetchingRequests--;
+            }
 
             newArray = state.currentlyFetching.filter(item => {
                 return item !== action.url;
diff --git a/openecomp-ui/src/nfvo-components/vnfMarketPlace/VnfRepositorySearchBox.jsx b/openecomp-ui/src/nfvo-components/vnfMarketPlace/VnfRepositorySearchBox.jsx
index 2c82c2b..32e3a3e 100644
--- a/openecomp-ui/src/nfvo-components/vnfMarketPlace/VnfRepositorySearchBox.jsx
+++ b/openecomp-ui/src/nfvo-components/vnfMarketPlace/VnfRepositorySearchBox.jsx
@@ -50,22 +50,27 @@
             dataTestId,
             isReadOnlyMode
         } = this.props;
-        let showVNF = Configuration.get('showBrowseVNF');
+        const showVNF = Configuration.get('showBrowseVNF');
         return (
-            <div className={`${className}${isReadOnlyMode ? ' disabled' : ''}`}>
+            <div
+                className={`${className}${isReadOnlyMode ? ' disabled' : ''}${
+                    showVNF ? ' showVnf' : ''
+                }`}>
                 <DraggableUploadFileBox
                     dataTestId={dataTestId}
                     isReadOnlyMode={isReadOnlyMode}
                     className={'upload'}
                     onClick={onClick}
                 />
-
-                <div className={`${'verticalLine'}${showVNF ? '' : ' hide'}`} />
-
-                <VNFBrowse
-                    onBrowseVNF={onBrowseVNF}
-                    isReadOnlyMode={isReadOnlyMode}
-                />
+                {showVNF && (
+                    <div className={`verticalLine${showVNF ? '' : ' hide'}`} />
+                )}
+                {showVNF && (
+                    <VNFBrowse
+                        onBrowseVNF={onBrowseVNF}
+                        isReadOnlyMode={isReadOnlyMode}
+                    />
+                )}
             </div>
         );
     }
diff --git a/openecomp-ui/src/nfvo-utils/ErrorResponseHandler.js b/openecomp-ui/src/nfvo-utils/ErrorResponseHandler.js
index 5c55855..e7d3f8a 100644
--- a/openecomp-ui/src/nfvo-utils/ErrorResponseHandler.js
+++ b/openecomp-ui/src/nfvo-utils/ErrorResponseHandler.js
@@ -64,7 +64,7 @@
     return { title, msg };
 }
 
-var errorResponseHandler = error => {
+const errorResponseHandler = error => {
     let errorData;
     if (error.data) {
         errorData = parseCatalogExceptionObject(error.data);
diff --git a/openecomp-ui/src/nfvo-utils/RestAPIUtil.js b/openecomp-ui/src/nfvo-utils/RestAPIUtil.js
index 03908d8..97d3847 100644
--- a/openecomp-ui/src/nfvo-utils/RestAPIUtil.js
+++ b/openecomp-ui/src/nfvo-utils/RestAPIUtil.js
@@ -77,55 +77,69 @@
     handleRequest(url, type, options = {}, data = {}) {
         applySecurity(options, data);
 
-        let config = {
+        const config = {
             method: type,
             url: url,
             headers: options.headers,
             data: data
         };
 
-        store.dispatch({ type: LoaderConstants.SEND_REQUEST, url: url });
+        if (options.validateStatus) {
+            config.validateStatus = options.validateStatus;
+        }
+
+        if (options.onUploadProgress) {
+            config.onUploadProgress = options.onUploadProgress;
+        }
+
+        if (!options.noLoading) {
+            store.dispatch({ type: LoaderConstants.SEND_REQUEST, url: url });
+        }
         if (options.dataType === BINARY) {
             config.responseType = 'arraybuffer';
             return axios(config)
                 .then(result => {
-                    store.dispatch({
-                        type: LoaderConstants.RECEIVE_RESPONSE,
-                        url: result.config.url
-                    });
+                    if (!options.noLoading) {
+                        store.dispatch({
+                            type: LoaderConstants.RECEIVE_RESPONSE,
+                            url: result.config.url
+                        });
+                    }
+
                     return {
                         blob: new Blob([result.data]),
                         headers: result.headers
                     };
                 })
                 .catch(error => {
-                    store.dispatch({
-                        type: LoaderConstants.RECEIVE_RESPONSE,
-                        url: error.config.url
-                    });
+                    if (!options.noLoading) {
+                        store.dispatch({
+                            type: LoaderConstants.RECEIVE_RESPONSE,
+                            url: error.config.url
+                        });
+                    }
                     errorResponseHandler(error.response);
                 });
-        } else {
-            return axios(config)
-                .then(result => {
-                    store.dispatch({
-                        type: LoaderConstants.RECEIVE_RESPONSE,
-                        url: result.config.url
-                    });
-                    handleSuccess(result.headers, result.config.headers);
-                    return result.data;
-                })
-                .catch(error => {
-                    store.dispatch({
-                        type: LoaderConstants.RECEIVE_RESPONSE,
-                        url: error.config.url
-                    });
-                    errorResponseHandler(error.response);
-                    return Promise.reject({
-                        responseJSON: error.response.data
-                    });
-                });
         }
+        return axios(config)
+            .then(result => {
+                store.dispatch({
+                    type: LoaderConstants.RECEIVE_RESPONSE,
+                    url: result.config.url
+                });
+                handleSuccess(result.headers, result.config.headers);
+                return result.data;
+            })
+            .catch(error => {
+                store.dispatch({
+                    type: LoaderConstants.RECEIVE_RESPONSE,
+                    url: error.config.url
+                });
+                errorResponseHandler(error.response);
+                return Promise.reject({
+                    responseJSON: error.response.data
+                });
+            });
     }
 
     fetch(url, options) {
diff --git a/openecomp-ui/src/nfvo-utils/i18n/en.json b/openecomp-ui/src/nfvo-utils/i18n/en.json
index 7a2e66a..ada011f 100644
--- a/openecomp-ui/src/nfvo-utils/i18n/en.json
+++ b/openecomp-ui/src/nfvo-utils/i18n/en.json
@@ -662,6 +662,10 @@
   "Unknown": "Unknown",
   "No Test Result Available": "No Test Result Available",
   "Test is In-progress": "Test is In-progress",
-  "has passed all checks": "has passed all checks"
-
+  "has passed all checks": "has passed all checks",
+  "upload.status.uploading": "Package upload is in progress",
+  "upload.status.validating": "Package is in validation",
+  "upload.status.processing": "Package is being processed",
+  "upload.status.success": "Package was successfully uploaded",
+  "upload.status.error": "Package upload resulted in error"
 }
diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js
index 5c82c70..3364edf 100644
--- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js
+++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/SoftwareProductActionHelper.js
@@ -112,12 +112,19 @@
     return `${restCatalogPrefix}/v1/catalog/model?modelType=normative`;
 }
 
-function uploadFile(vspId, formData, version) {
+function uploadFile(vspId, formData, version, onUploadProgress = undefined) {
+    const options = {
+        noLoading: true
+    };
+    if (onUploadProgress) {
+        options.onUploadProgress = onUploadProgress;
+    }
     return RestAPIUtil.post(
         `${baseUrl()}${vspId}/versions/${
             version.id
         }/orchestration-template-candidate`,
-        formData
+        formData,
+        options
     );
 }
 
@@ -346,6 +353,19 @@
         );
     },
 
+    fetchUploadStatus(vspId, versionId) {
+        const options = {
+            validateStatus: function(status) {
+                return status < 400 || status === 404;
+            },
+            noLoading: true
+        };
+        return RestAPIUtil.get(
+            `${baseUrl()}${vspId}/versions/${versionId}/orchestration-template-candidate/upload`,
+            options
+        );
+    },
+
     loadSoftwareProductAssociatedData(dispatch) {
         fetchSoftwareProductCategories(dispatch);
         fetchModelList(dispatch);
@@ -435,15 +455,27 @@
 
     uploadFile(
         dispatch,
-        { softwareProductId, formData, failedNotificationTitle, version }
+        {
+            softwareProductId,
+            formData,
+            failedNotificationTitle,
+            version,
+            onUploadProgress = undefined
+        }
     ) {
         dispatch({
             type: HeatSetupActions.FILL_HEAT_SETUP_CACHE,
             payload: {}
         });
-        displayTimingValidationInfo(dispatch);
-        Promise.resolve()
-            .then(() => uploadFile(softwareProductId, formData, version))
+        return Promise.resolve()
+            .then(() =>
+                uploadFile(
+                    softwareProductId,
+                    formData,
+                    version,
+                    onUploadProgress
+                )
+            )
             .then(response => {
                 if (response.status === 'Success') {
                     dispatch({
diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPage.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPage.js
index fa136f2..4b4c2fa 100644
--- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPage.js
+++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPage.js
@@ -109,15 +109,40 @@
                 screenType: screenTypes.SOFTWARE_PRODUCT,
                 props: { softwareProductId, version }
             }),
-        onUpload: (softwareProductId, formData) =>
+        onUpload: (
+            softwareProductId,
+            formData,
+            onUploadStart = () => {
+                // do nothing by default
+            },
+            onUploadProgress = undefined,
+            onUploadFinished = () => {
+                // do nothing by default
+            }
+        ) => {
             SoftwareProductActionHelper.uploadFile(dispatch, {
                 softwareProductId,
                 formData,
                 failedNotificationTitle: i18n('Upload validation failed'),
-                version
-            }),
+                version,
+                onUploadProgress
+            }).finally(() => {
+                onUploadFinished();
+            });
+            onUploadStart();
+        },
 
-        onUploadConfirmation: (softwareProductId, formData) =>
+        onUploadConfirmation: (
+            softwareProductId,
+            formData,
+            onUploadStart = () => {
+                // do nothing by default
+            },
+            onUploadProgress = undefined,
+            onUploadFinished = () => {
+                // do nothing by default
+            }
+        ) =>
             dispatch({
                 type: modalActionTypes.GLOBAL_MODAL_WARNING,
                 data: {
@@ -126,15 +151,21 @@
                     ),
                     confirmationButtonText: i18n('Continue'),
                     title: i18n('Warning'),
-                    onConfirmed: () =>
+                    onConfirmed: () => {
                         SoftwareProductActionHelper.uploadFile(dispatch, {
                             softwareProductId,
                             formData,
                             failedNotificationTitle: i18n(
                                 'Upload validation failed'
                             ),
-                            version
-                        }),
+                            version,
+                            onUploadProgress
+                        }).finally(value => {
+                            console.log('upload finished', value);
+                            onUploadFinished();
+                        });
+                        onUploadStart();
+                    },
                     onDeclined: () =>
                         dispatch({
                             type: modalActionTypes.GLOBAL_MODAL_CLOSE
@@ -153,6 +184,14 @@
                     )
                 }
             }),
+
+        fetchUploadStatus: softwareProductId => {
+            return SoftwareProductActionHelper.fetchUploadStatus(
+                softwareProductId,
+                version.id
+            );
+        },
+
         onComponentSelect: ({ id: softwareProductId, componentId }) =>
             ScreensHelper.loadScreen(dispatch, {
                 screen: screenTypes.SOFTWARE_PRODUCT_COMPONENT_DEFAULT_GENERAL,
diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPageView.jsx b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPageView.jsx
index 5f20834..c560a73 100644
--- a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPageView.jsx
+++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/SoftwareProductLandingPageView.jsx
@@ -20,12 +20,12 @@
 import Dropzone from 'react-dropzone';
 
 import i18n from 'nfvo-utils/i18n/i18n.js';
-import Configuration from 'sdc-app/config/Configuration.js';
-import DraggableUploadFileBox from 'nfvo-components/fileupload/DraggableUploadFileBox.jsx';
 import VnfRepositorySearchBox from 'nfvo-components/vnfMarketPlace/VnfRepositorySearchBox.jsx';
 
 import { SVGIcon } from 'onap-ui-react';
 import SoftwareProductComponentsList from 'sdc-app/onboarding/softwareProduct/components/SoftwareProductComponents.js';
+import VspUploadStatus from 'sdc-app/onboarding/softwareProduct/landingPage/VspUploadStatus';
+import ProgressBar from 'react-bootstrap/lib/ProgressBar';
 
 const SoftwareProductPropType = PropTypes.shape({
     name: PropTypes.string,
@@ -52,7 +52,10 @@
     state = {
         fileName: '',
         dragging: false,
-        files: []
+        uploadStatus: {},
+        files: [],
+        uploadProgress: 0,
+        showProgressBar: false
     };
 
     constructor(props) {
@@ -69,11 +72,13 @@
         version: PropTypes.object,
         onLicenseChange: PropTypes.func,
         onUpload: PropTypes.func,
+        fetchUploadStatus: PropTypes.func,
         onUploadConfirmation: PropTypes.func,
         onInvalidFileSizeUpload: PropTypes.func,
         onComponentSelect: PropTypes.func,
         onAddComponent: PropTypes.func
     };
+
     componentDidMount() {
         const {
             onCandidateInProcess,
@@ -83,6 +88,41 @@
         if (currentSoftwareProduct.candidateOnboardingOrigin && !isCertified) {
             onCandidateInProcess(currentSoftwareProduct.id);
         }
+        this.keepCheckingUploadStatus();
+    }
+
+    componentWillUnmount() {
+        this.stopUploadStatusChecking();
+    }
+
+    keepCheckingUploadStatus(initialDelayInMs = 0, updatePeriodInMs = 10000) {
+        this.stopUploadStatusChecking();
+        setTimeout(() => this.updateUploadStatus(), initialDelayInMs);
+        this.uploadStatusInterval = setInterval(
+            () => this.updateUploadStatus(),
+            updatePeriodInMs
+        );
+    }
+
+    stopUploadStatusChecking() {
+        clearInterval(this.uploadStatusInterval);
+    }
+
+    updateUploadStatus() {
+        const currentVspId = this.props.currentSoftwareProduct.id;
+        this.props
+            .fetchUploadStatus(currentVspId)
+            .then(uploadStatusResponse => {
+                const vspUploadStatus = new VspUploadStatus(
+                    uploadStatusResponse
+                );
+                this.setState({
+                    uploadStatus: vspUploadStatus
+                });
+            })
+            .catch(error =>
+                console.error('Could not retrieve upload status', error)
+            );
     }
 
     licenceChange = (e, currentSoftwareProduct, onLicenseChange) => {
@@ -93,7 +133,7 @@
     };
 
     getExternalLicenceFeatureState() {
-        var licenseFeature = this.props.features.find(
+        const licenseFeature = this.props.features.find(
             feature => feature.name === 'EXTERNAL_LICENSE'
         );
         return licenseFeature ? licenseFeature.active : true;
@@ -136,10 +176,11 @@
                                     onLicenseChange={onLicenseChange}
                                     externalLicenceEnabled={this.getExternalLicenceFeatureState()}
                                 />
-                                {this.renderProductDetails(
-                                    isManual,
-                                    isReadOnlyMode
-                                )}
+                                <div className="details-panel">
+                                    {this.renderProductAttachments(
+                                        isReadOnlyMode
+                                    )}
+                                </div>
                             </div>
                         </div>
                     </div>
@@ -155,56 +196,50 @@
         }
     }
 
-    renderProductDetails(isManual, isReadOnlyMode) {
+    isUploadInProgress() {
+        return (
+            this.state.uploadStatus.complete !== undefined &&
+            !this.state.uploadStatus.complete
+        );
+    }
+
+    renderProductAttachments(isReadOnlyMode) {
         let { onBrowseVNF, currentSoftwareProduct } = this.props;
 
-        if (Configuration.get('showBrowseVNF')) {
+        if (this.isUploadInProgress()) {
             return (
-                <div className="details-panel">
-                    {!isManual && (
-                        <div>
-                            <div className="software-product-landing-view-heading-title">
-                                {i18n('Software Product Attachments')}
-                            </div>
-                            <VnfRepositorySearchBox
-                                dataTestId="upload-btn"
-                                isReadOnlyMode={isReadOnlyMode}
-                                className={classnames(
-                                    'software-product-landing-view-top-block-col-upl showVnf',
-                                    { disabled: isReadOnlyMode }
-                                )}
-                                onClick={() => this.refs.fileInput.open()}
-                                onBrowseVNF={() =>
-                                    onBrowseVNF(currentSoftwareProduct)
-                                }
-                            />
+                <div>
+                    <div className="software-product-landing-view-heading-title">
+                        {i18n('Software Product Attachments')}
+                    </div>
+                    <div className="software-product-landing-view-top-block-col-upl ">
+                        <div className="upload-status-text">
+                            {this.state.uploadStatus.statusToString()}
+                            {this.state.showProgressBar && (
+                                <ProgressBar now={this.state.uploadProgress} />
+                            )}
                         </div>
-                    )}
-                </div>
-            );
-        } else {
-            return (
-                <div className="details-panel">
-                    {!isManual && (
-                        <div>
-                            <div className="software-product-landing-view-heading-title">
-                                {i18n('Software Product Attachments')}
-                            </div>
-                            <DraggableUploadFileBox
-                                dataTestId="upload-btn"
-                                isReadOnlyMode={isReadOnlyMode}
-                                className={classnames(
-                                    'software-product-landing-view-top-block-col-upl',
-                                    { disabled: isReadOnlyMode }
-                                )}
-                                onClick={() => this.refs.fileInput.open()}
-                                onBrowseVNF={() => onBrowseVNF()}
-                            />
-                        </div>
-                    )}
+                    </div>
                 </div>
             );
         }
+        return (
+            <div>
+                <div className="software-product-landing-view-heading-title">
+                    {i18n('Software Product Attachments')}
+                </div>
+                <VnfRepositorySearchBox
+                    dataTestId="upload-btn"
+                    isReadOnlyMode={isReadOnlyMode}
+                    className={classnames(
+                        'software-product-landing-view-top-block-col-upl',
+                        { disabled: isReadOnlyMode }
+                    )}
+                    onClick={() => this.refs.fileInput.open()}
+                    onBrowseVNF={() => onBrowseVNF(currentSoftwareProduct)}
+                />
+            </div>
+        );
     }
 
     handleImportSubmit(files, isReadOnlyMode, isManual) {
@@ -226,6 +261,48 @@
         }
     }
 
+    onUploadStart = () => {
+        this.stopUploadStatusChecking();
+        this.showProgressBar();
+    };
+
+    onUploadProgress = progressEvent => {
+        const vspUploadStatus = new VspUploadStatus({
+            status: VspUploadStatus.UPLOADING,
+            complete: false
+        });
+        this.setState({
+            uploadStatus: vspUploadStatus
+        });
+        const percentCompleted = Math.round(
+            progressEvent.loaded * 100 / progressEvent.total
+        );
+        if (percentCompleted === 100) {
+            this.keepCheckingUploadStatus(5000);
+            this.resetUploadProgress(2000);
+        }
+        this.setState({ uploadProgress: percentCompleted });
+    };
+
+    onUploadFinished = () => {
+        this.updateUploadStatus();
+    };
+
+    showProgressBar() {
+        this.setState({ showProgressBar: true });
+    }
+
+    hideProgressBar() {
+        this.setState({ showProgressBar: false });
+    }
+
+    resetUploadProgress(milliseconds) {
+        setTimeout(() => {
+            this.setState({ uploadProgress: 0 });
+            this.hideProgressBar();
+        }, milliseconds);
+    }
+
     startUploading(files) {
         let {
             onUpload,
@@ -244,9 +321,21 @@
         this.refs.fileInput.value = '';
 
         if (validationData) {
-            onUploadConfirmation(currentSoftwareProduct.id, formData);
+            onUploadConfirmation(
+                currentSoftwareProduct.id,
+                formData,
+                () => this.onUploadStart(),
+                this.onUploadProgress,
+                this.onUploadFinished
+            );
         } else {
-            onUpload(currentSoftwareProduct.id, formData);
+            onUpload(
+                currentSoftwareProduct.id,
+                formData,
+                () => this.onUploadStart(),
+                this.onUploadProgress,
+                this.onUploadFinished
+            );
         }
     }
 }
diff --git a/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/VspUploadStatus.js b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/VspUploadStatus.js
new file mode 100644
index 0000000..abb2a98
--- /dev/null
+++ b/openecomp-ui/src/sdc-app/onboarding/softwareProduct/landingPage/VspUploadStatus.js
@@ -0,0 +1,73 @@
+/*
+ * -
+ *  ============LICENSE_START=======================================================
+ *  Copyright (C) 2022 Nordix Foundation.
+ *  ================================================================================
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *       http://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
+ *  ============LICENSE_END=========================================================
+ */
+
+import i18n from 'nfvo-utils/i18n/i18n';
+
+export default class VspUploadStatus {
+    static UPLOADING = 'UPLOADING';
+    static VALIDATING = 'VALIDATING';
+    static PROCESSING = 'PROCESSING';
+    static SUCCESS = 'SUCCESS';
+    static ERROR = 'ERROR';
+
+    complete;
+    created;
+    lockId;
+    status;
+    updated;
+    vspId;
+    vspVersionId;
+
+    constructor(vspUploadStatusResponse) {
+        this.status = vspUploadStatusResponse.status;
+        this.complete = vspUploadStatusResponse.complete;
+        this.created = vspUploadStatusResponse.created;
+        this.lockId = vspUploadStatusResponse.lockId;
+        this.updated = vspUploadStatusResponse.updated;
+        this.vspId = vspUploadStatusResponse.vspId;
+        this.vspVersionId = vspUploadStatusResponse.vspVersionId;
+    }
+
+    statusToString() {
+        if (!this.status) {
+            return '';
+        }
+        switch (this.status) {
+            case VspUploadStatus.UPLOADING: {
+                return i18n('upload.status.uploading');
+            }
+            case VspUploadStatus.VALIDATING: {
+                return i18n('upload.status.validating');
+            }
+            case VspUploadStatus.PROCESSING: {
+                return i18n('upload.status.processing');
+            }
+            case VspUploadStatus.SUCCESS: {
+                return i18n('upload.status.success');
+            }
+            case VspUploadStatus.ERROR: {
+                return i18n('upload.status.error');
+            }
+            default:
+                return this.status;
+        }
+    }
+}