From 8497f99f33b3305b12a830e035c0b719f08c0e80 Mon Sep 17 00:00:00 2001
From: Ramesh Kumar <r.kumar@redkarma.eu>
Date: Fri, 11 Sep 2020 17:16:56 +0530
Subject: [PATCH] TMSS-226: Updated code to update multiple tasks.

---
 .../tmss_webapp/src/routes/Scheduling/edit.js | 77 +++++++++++--------
 .../src/services/schedule.service.js          | 17 ++--
 2 files changed, 54 insertions(+), 40 deletions(-)

diff --git a/SAS/TMSS/frontend/tmss_webapp/src/routes/Scheduling/edit.js b/SAS/TMSS/frontend/tmss_webapp/src/routes/Scheduling/edit.js
index 0b929e3f66c..2150c5ab674 100644
--- a/SAS/TMSS/frontend/tmss_webapp/src/routes/Scheduling/edit.js
+++ b/SAS/TMSS/frontend/tmss_webapp/src/routes/Scheduling/edit.js
@@ -19,7 +19,9 @@ import ScheduleService from '../../services/schedule.service';
 import TaskService from '../../services/task.service';
 import UIConstants from '../../utils/ui.constants';
 
-
+/**
+ * Compoenent to edit scheduling unit draft
+ */
 export class EditSchedulingUnit extends Component {
     constructor(props) {
         super(props);
@@ -36,7 +38,7 @@ export class EditSchedulingUnit extends Component {
             paramsSchema: null,                     
             validEditor: false,                     
             validFields: {},  
-            taskDraft: {}                     
+            observStrategyVisible: false                     
         }
         this.projects = [];                         
         this.schedulingSets = [];                   
@@ -68,7 +70,7 @@ export class EditSchedulingUnit extends Component {
      * @param {number} strategyId 
      */
     async changeStrategy (strategyId) {
-        let taskDraftName;
+        let tasksToUpdate = {};
         const observStrategy = _.find(this.observStrategies, {'id': strategyId});
         const tasks = observStrategy.template.tasks;    
         let paramsOutput = {};
@@ -90,7 +92,7 @@ export class EditSchedulingUnit extends Component {
             schema['$schema'] = taskTemplate.schema['$schema'];
             observStrategy.template.parameters.forEach(async(param, index) => {
                 if (param.refs[0].indexOf(`/tasks/${taskName}`) > 0) {
-                    taskDraftName = taskName;
+                    tasksToUpdate[taskName] = taskName;
                     // Resolve the identified template
                     const $templateRefs = await $RefParser.resolve(taskTemplate);
                     let property = { };
@@ -117,7 +119,7 @@ export class EditSchedulingUnit extends Component {
                 }
             });
         }
-        this.setState({observStrategy: observStrategy, paramsSchema: schema, paramsOutput: paramsOutput, taskDraft: taskDraftName});
+        this.setState({observStrategy: observStrategy, paramsSchema: schema, paramsOutput: paramsOutput, tasksToUpdate: tasksToUpdate});
 
         // Function called to clear the JSON Editor fields and reload with new schema
         if (this.state.editorFunction) {
@@ -138,10 +140,12 @@ export class EditSchedulingUnit extends Component {
             this.schedulingSets = responses[1];
             this.observStrategies = responses[2];
             this.taskTemplates = responses[3];
-            this.setState({ taskDrafts: responses[5].data.results });
             responses[4].project = this.schedulingSets.find(i => i.id === responses[4].scheduling_set_id).project_id;
-            this.setState({ schedulingUnit: responses[4] });
-            this.changeStrategy(responses[4].observation_strategy_template_id);
+            this.setState({ schedulingUnit: responses[4], taskDrafts: responses[5].data.results,
+                            observStrategyVisible: responses[4].observation_strategy_template_id?true:false });
+            if (responses[4].observation_strategy_template_id) {
+                this.changeStrategy(responses[4].observation_strategy_template_id);
+            }
             if (this.state.schedulingUnit.project) {
                 const projectSchedSets = _.filter(this.schedulingSets, {'project_id': this.state.schedulingUnit.project});
                 this.setState({isLoading: false, schedulingSets: projectSchedSets});
@@ -241,21 +245,24 @@ export class EditSchedulingUnit extends Component {
      * Function to create Scheduling unit
      */
     async saveSchedulingUnit() {
-        let observStrategy = _.cloneDeep(this.state.observStrategy);
-        const $refs = await $RefParser.resolve(observStrategy.template);
-        observStrategy.template.parameters.forEach(async(param, index) => {
-            $refs.set(observStrategy.template.parameters[index]['refs'][0], this.state.paramsOutput['param_' + index]);
-        });
-        const task = this.state.taskDrafts.find(draft => draft.name === this.state.taskDraft);
-        const schedulingUnit = await ScheduleService.updateSUDraftFromObservStrategy(observStrategy, this.state.schedulingUnit, task, this.state.taskDraft);
-        if (schedulingUnit) {
-           this.growl.show({severity: 'success', summary: 'Success', detail: 'Scheduling Unit and tasks edited successfully!'});
-            this.props.history.push({
-                pathname: `/schedulingunit/view/draft/${this.props.match.params.id}`,
-            }); 
-        } else {
-            this.growl.show({severity: 'error', summary: 'Error Occured', detail: 'Unable to update Scheduling Unit/Tasks'});
-        } 
+        if (this.state.schedulingUnit.observation_strategy_template_id) {
+            let observStrategy = _.cloneDeep(this.state.observStrategy);
+            const $refs = await $RefParser.resolve(observStrategy.template);
+            observStrategy.template.parameters.forEach(async(param, index) => {
+                $refs.set(observStrategy.template.parameters[index]['refs'][0], this.state.paramsOutput['param_' + index]);
+            });
+            const schedulingUnit = await ScheduleService.updateSUDraftFromObservStrategy(observStrategy, this.state.schedulingUnit, this.state.taskDrafts, this.state.tasksToUpdate);
+            if (schedulingUnit) {
+                // this.growl.show({severity: 'success', summary: 'Success', detail: 'Scheduling Unit and tasks edited successfully!'});
+                this.props.history.push({
+                    pathname: `/schedulingunit/view/draft/${this.props.match.params.id}`,
+                }); 
+            } else {
+                this.growl.show({severity: 'error', summary: 'Error Occured', detail: 'Unable to update Scheduling Unit/Tasks'});
+            } 
+        }   else {
+            this.growl.show({severity: 'error', summary: 'Error Occured', detail: 'Template Missing.'});
+        }
     }
 
     /**
@@ -337,16 +344,20 @@ export class EditSchedulingUnit extends Component {
                             </div>
                         </div>
                         <div className="p-field p-grid">
-                            <label htmlFor="observStrategy" className="col-lg-2 col-md-2 col-sm-12">Observation Strategy </label>
-                            <div className="col-lg-3 col-md-3 col-sm-12" data-testid="observStrategy" >
-                                <Dropdown inputId="observStrategy" optionLabel="name" optionValue="id" 
-                                        tooltip="Observation Strategy Template to be used to create the Scheduling Unit and Tasks" tooltipOptions={this.tooltipOptions}
-                                        value={this.state.schedulingUnit.observation_strategy_template_id} 
-                                        disabled={this.state.schedulingUnit.observation_strategy_template_id} 
-                                        options={this.observStrategies} 
-                                        onChange={(e) => {this.changeStrategy(e.value)}} 
-                                        placeholder="Select Strategy" />
-                            </div>
+                            { this.state.observStrategyVisible && 
+                                <>
+                                    <label htmlFor="observStrategy" className="col-lg-2 col-md-2 col-sm-12">Observation Strategy </label>
+                                    <div className="col-lg-3 col-md-3 col-sm-12" data-testid="observStrategy" >
+                                        <Dropdown inputId="observStrategy" optionLabel="name" optionValue="id" 
+                                                tooltip="Observation Strategy Template to be used to create the Scheduling Unit and Tasks" tooltipOptions={this.tooltipOptions}
+                                                value={this.state.schedulingUnit.observation_strategy_template_id} 
+                                                disabled={this.state.schedulingUnit.observation_strategy_template_id} 
+                                                options={this.observStrategies} 
+                                                onChange={(e) => {this.changeStrategy(e.value)}} 
+                                                placeholder="Select Strategy" />
+                                    </div>
+                                </>
+                            }
                             <div className="col-lg-1 col-md-1 col-sm-12"></div>
                         </div>
                         
diff --git a/SAS/TMSS/frontend/tmss_webapp/src/services/schedule.service.js b/SAS/TMSS/frontend/tmss_webapp/src/services/schedule.service.js
index fefe9515235..4a32a098a4e 100644
--- a/SAS/TMSS/frontend/tmss_webapp/src/services/schedule.service.js
+++ b/SAS/TMSS/frontend/tmss_webapp/src/services/schedule.service.js
@@ -211,16 +211,19 @@ const ScheduleService = {
         };
     },
     
-    updateSUDraftFromObservStrategy: async function(observStrategy, schedulingUnit,task,taskName) {
+    updateSUDraftFromObservStrategy: async function(observStrategy, schedulingUnit,tasks,tasksToUpdate) {
         try {
             delete schedulingUnit['duration'];
             schedulingUnit = await this.updateSchedulingUnitDraft(schedulingUnit);
-            task.specifications_doc = observStrategy.template.tasks[taskName].specifications_doc;
-            delete task['duration'];
-            delete task['relative_start_time'];
-            delete task['relative_stop_time'];
-            task = await this.updateTask(task);
-            return task;
+            for (const taskToUpdate in tasksToUpdate) {
+                let task = tasks.find(task => { return task.name === taskToUpdate});
+                task.specifications_doc = observStrategy.template.tasks[taskToUpdate].specifications_doc;
+                delete task['duration'];
+                delete task['relative_start_time'];
+                delete task['relative_stop_time'];
+                task = await this.updateTask(task);
+            }
+            return schedulingUnit;
         }   catch(error) {
             console.error(error);
             return null;
-- 
GitLab