-
Notifications
You must be signed in to change notification settings - Fork 1
/
ganttMaster.js
1487 lines (1196 loc) · 42.5 KB
/
ganttMaster.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2012-2017 Open Lab
Written by Roberto Bicchierai and Silvia Chelazzi http://roberto.open-lab.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
function GanttMaster() {
this.tasks = [];
this.deletedTaskIds = [];
this.links = [];
this.editor; //element for editor
this.gantt; //element for gantt
this.splitter; //element for splitter
this.isMultiRoot=false; // set to true in case of tasklist
this.element;
this.resources; //list of resources
this.roles; //list of roles
this.minEditableDate = 0;
this.maxEditableDate = Infinity;
this.set100OnClose=false;
this.fillWithEmptyLines=true; //when is used by widget it could be usefull to do not fill with empty lines
this.minRowsInEditor=30; // number of rows always visible in editor
this.permissions = {
canWriteOnParent: true,
canWrite: true,
canAdd: true,
canInOutdent: true,
canMoveUpDown: true,
canSeePopEdit: true,
canSeeFullEdit: true,
canSeeDep: true,
canSeeCriticalPath: true,
canAddIssue: false,
cannotCloseTaskIfIssueOpen: false
};
this.firstDayOfWeek = Date.firstDayOfWeek;
this.serverClientTimeOffset = 0;
this.currentTask; // task currently selected;
this.resourceUrl = "res/"; // URL to resources (images etc.)
this.__currentTransaction; // a transaction object holds previous state during changes
this.__undoStack = [];
this.__redoStack = [];
this.__inUndoRedo = false; // a control flag to avoid Undo/Redo stacks reset when needed
var self = this;
}
GanttMaster.prototype.init = function (place) {
this.element = place;
var self = this;
//load templates
$("#gantEditorTemplates").loadTemplates().remove();
//create editor
this.editor = new GridEditor(this);
place.append(this.editor.gridified);
//create gantt
this.gantt = new Ganttalendar("m", new Date().getTime() - 3600000 * 24 * 2, new Date().getTime() + 3600000 * 24 * 15, this, place.width() * .6);
//setup splitter
self.splitter = $.splittify.init(place, this.editor.gridified, this.gantt.element, 60);
self.splitter.firstBoxMinWidth = 5;
self.splitter.secondBoxMinWidth = 20;
//prepend buttons
var ganttButtons = $.JST.createFromTemplate({}, "GANTBUTTONS");
//hide buttons basing on permissions
if (!self.permissions.canWrite)
ganttButtons.find(".requireCanWrite").hide();
if (!self.permissions.canAdd)
ganttButtons.find(".requireCanAdd").hide();
if (!self.permissions.canInOutdent)
ganttButtons.find(".requireCanInOutdent").hide();
if (!self.permissions.canMoveUpDown)
ganttButtons.find(".requireCanMoveUpDown").hide();
if (!self.permissions.canSeeCriticalPath)
ganttButtons.find(".requireCanSeeCriticalPath").hide();
if (!self.permissions.canAddIssue)
ganttButtons.find(".requireCanAddIssue").hide();
place.before(ganttButtons);
//bindings
place.bind("refreshTasks.gantt", function () {
self.redrawTasks();
}).bind("refreshTask.gantt", function (e, task) {
self.drawTask(task);
}).bind("deleteCurrentTask.gantt", function (e) {
self.deleteCurrentTask();
}).bind("addAboveCurrentTask.gantt", function () {
self.addAboveCurrentTask();
}).bind("addBelowCurrentTask.gantt", function () {
self.addBelowCurrentTask();
}).bind("indentCurrentTask.gantt", function () {
self.indentCurrentTask();
}).bind("outdentCurrentTask.gantt", function () {
self.outdentCurrentTask();
}).bind("moveUpCurrentTask.gantt", function () {
self.moveUpCurrentTask();
}).bind("moveDownCurrentTask.gantt", function () {
self.moveDownCurrentTask();
}).bind("collapseAll.gantt", function () {
self.collapseAll();
}).bind("expandAll.gantt", function () {
self.expandAll();
}).bind("zoomPlus.gantt", function () {
self.gantt.zoomGantt(true);
}).bind("zoomMinus.gantt", function () {
self.gantt.zoomGantt(false);
}).bind("addIssue.gantt", function () {
self.addIssue();
}).bind("undo.gantt", function () {
if (!self.permissions.canWrite)
return;
self.undo();
}).bind("redo.gantt", function () {
if (!self.permissions.canWrite)
return;
self.redo();
}).bind("resize.gantt", function () {
self.resize();
});
//keyboard management bindings
$("body").bind("keydown.body", function (e) {
//console.debug(e.keyCode+ " "+e.target.nodeName, e.ctrlKey)
var eventManaged = true;
var isCtrl = e.ctrlKey || e.metaKey;
var bodyOrSVG = e.target.nodeName.toLowerCase() == "body" || e.target.nodeName.toLowerCase() == "svg";
var inWorkSpace=$(e.target).closest("#workSpace").length>0;
//store focused field
var focusedField=$(":focus");
var focusedSVGElement = self.gantt.element.find(".focused.focused");// orrible hack for chrome that seems to keep in memory a cached object
var isFocusedSVGElement=focusedSVGElement.length >0;
if ((inWorkSpace ||isFocusedSVGElement) && isCtrl && e.keyCode == 37) { // CTRL+LEFT on the grid
self.outdentCurrentTask();
focusedField.focus();
} else if (inWorkSpace && isCtrl && e.keyCode == 38) { // CTRL+UP on the grid
self.moveUpCurrentTask();
focusedField.focus();
} else if (inWorkSpace && isCtrl && e.keyCode == 39) { //CTRL+RIGHT on the grid
self.indentCurrentTask();
focusedField.focus();
} else if (inWorkSpace && isCtrl && e.keyCode == 40) { //CTRL+DOWN on the grid
self.moveDownCurrentTask();
focusedField.focus();
} else if (isCtrl && e.keyCode == 89) { //CTRL+Y
self.redo();
} else if (isCtrl && e.keyCode == 90) { //CTRL+Y
self.undo();
} else if ( (isCtrl && inWorkSpace) && (e.keyCode == 8 || e.keyCode == 46) ) { //CTRL+DEL CTRL+BACKSPACE on grid
self.deleteCurrentTask();
} else if ( focusedSVGElement.is(".taskBox") && (e.keyCode == 8 || e.keyCode == 46) ) { //DEL BACKSPACE svg task
self.deleteCurrentTask();
} else if ( focusedSVGElement.is(".linkGroup") && (e.keyCode == 8 || e.keyCode == 46) ) { //DEL BACKSPACE svg link
self.removeLink(focused.data("from"), focused.data("to"));
} else {
eventManaged=false;
}
if (eventManaged) {
e.preventDefault();
e.stopPropagation();
}
});
//ask for comment input
$("#saveGanttButton").after($('#LOG_CHANGES_CONTAINER'));
//ask for comment management
this.element.on("gantt.saveRequired",this.manageSaveRequired)
};
GanttMaster.messages = {
"CANNOT_WRITE": "CANNOT_WRITE",
"CHANGE_OUT_OF_SCOPE": "NO_RIGHTS_FOR_UPDATE_PARENTS_OUT_OF_EDITOR_SCOPE",
"START_IS_MILESTONE": "START_IS_MILESTONE",
"END_IS_MILESTONE": "END_IS_MILESTONE",
"TASK_HAS_CONSTRAINTS": "TASK_HAS_CONSTRAINTS",
"GANTT_ERROR_DEPENDS_ON_OPEN_TASK": "GANTT_ERROR_DEPENDS_ON_OPEN_TASK",
"GANTT_ERROR_DESCENDANT_OF_CLOSED_TASK": "GANTT_ERROR_DESCENDANT_OF_CLOSED_TASK",
"TASK_HAS_EXTERNAL_DEPS": "TASK_HAS_EXTERNAL_DEPS",
"GANTT_ERROR_LOADING_DATA_TASK_REMOVED": "GANTT_ERROR_LOADING_DATA_TASK_REMOVED",
"CIRCULAR_REFERENCE": "CIRCULAR_REFERENCE",
"CANNOT_MOVE_TASK": "CANNOT_MOVE_TASK",
"CANNOT_DEPENDS_ON_ANCESTORS": "CANNOT_DEPENDS_ON_ANCESTORS",
"CANNOT_DEPENDS_ON_DESCENDANTS": "CANNOT_DEPENDS_ON_DESCENDANTS",
"INVALID_DATE_FORMAT": "INVALID_DATE_FORMAT",
"GANTT_QUARTER_SHORT": "GANTT_QUARTER_SHORT",
"GANTT_SEMESTER_SHORT": "GANTT_SEMESTER_SHORT",
"CANNOT_CLOSE_TASK_IF_OPEN_ISSUE": "CANNOT_CLOSE_TASK_IF_OPEN_ISSUE",
"PLEASE_SAVE_PROJECT": "PLEASE_SAVE_PROJECT"
};
GanttMaster.prototype.createTask = function (id, name, code, level, start, duration) {
var factory = new TaskFactory();
return factory.build(id, name, code, level, start, duration);
};
GanttMaster.prototype.getOrCreateResource = function (id, name) {
var res= this.getResource(id);
if (!res && id && name) {
res = this.createResource(id, name);
}
return res
};
GanttMaster.prototype.createResource = function (id, name) {
var res = new Resource(id, name);
this.resources.push(res);
return res;
};
//update depends strings
GanttMaster.prototype.updateDependsStrings = function () {
//remove all deps
for (var i = 0; i < this.tasks.length; i++) {
this.tasks[i].depends = "";
}
for (var i = 0; i < this.links.length; i++) {
var link = this.links[i];
var dep = link.to.depends;
link.to.depends = link.to.depends + (link.to.depends == "" ? "" : ",") + (link.from.getRow() + 1) + (link.lag ? ":" + link.lag : "");
}
};
GanttMaster.prototype.removeLink = function (fromTask, toTask) {
//console.debug("removeLink");
if (!this.permissions.canWrite || (!fromTask.canWrite && !toTask.canWrite))
return;
this.beginTransaction();
var found = false;
for (var i = 0; i < this.links.length; i++) {
if (this.links[i].from == fromTask && this.links[i].to == toTask) {
this.links.splice(i, 1);
found = true;
break;
}
}
if (found) {
this.updateDependsStrings();
if (this.updateLinks(toTask))
this.changeTaskDates(toTask, toTask.start, toTask.end); // fake change to force date recomputation from dependencies
}
this.endTransaction();
};
GanttMaster.prototype.removeAllLinks = function (task, openTrans) {
//console.debug("removeLink");
if (!this.permissions.canWrite || (!task.canWrite && !task.canWrite))
return;
if (openTrans)
this.beginTransaction();
var found = false;
for (var i = 0; i < this.links.length; i++) {
if (this.links[i].from == task || this.links[i].to == task) {
this.links.splice(i, 1);
found = true;
}
}
if (found) {
this.updateDependsStrings();
}
if (openTrans)
this.endTransaction();
};
//------------------------------------ ADD TASK --------------------------------------------
GanttMaster.prototype.addTask = function (task, row) {
//console.debug("master.addTask",task,row,this);
if (!this.permissions.canWrite || !this.permissions.canAdd )
return;
task.master = this; // in order to access controller from task
//replace if already exists
var pos = -1;
for (var i = 0; i < this.tasks.length; i++) {
if (task.id == this.tasks[i].id) {
pos = i;
break;
}
}
if (pos >= 0) {
this.tasks.splice(pos, 1);
row = parseInt(pos);
}
//add task in collection
if (typeof(row) != "number") {
this.tasks.push(task);
} else {
this.tasks.splice(row, 0, task);
//recompute depends string
this.updateDependsStrings();
}
//add Link collection in memory
var linkLoops = !this.updateLinks(task);
//set the status according to parent
if (task.getParent())
task.status = task.getParent().status;
else
task.status = "STATUS_ACTIVE";
var ret = task;
if (linkLoops || !task.setPeriod(task.start, task.end)) {
//remove task from in-memory collection
//console.debug("removing task from memory",task);
this.tasks.splice(task.getRow(), 1);
ret = undefined;
} else {
//append task to editor
this.editor.addTask(task, row);
//append task to gantt
this.gantt.addTask(task);
}
//trigger addedTask event
$(this.element).trigger("addedTask.gantt", task);
return ret;
};
/**
* a project contais tasks, resources, roles, and info about permisions
* @param project
*/
GanttMaster.prototype.loadProject = function (project) {
//console.debug("loadProject", project)
this.beginTransaction();
this.serverClientTimeOffset = typeof project.serverTimeOffset !="undefined"? (parseInt(project.serverTimeOffset) + new Date().getTimezoneOffset() * 60000) : 0;
this.resources = project.resources;
this.roles = project.roles;
this.permissions.canWrite = project.canWrite;
this.permissions.canWriteOnParent = project.canWriteOnParent;
this.permissions.cannotCloseTaskIfIssueOpen = project.cannotCloseTaskIfIssueOpen;
if (project.minEditableDate)
this.minEditableDate = computeStart(project.minEditableDate);
else
this.minEditableDate = -Infinity;
if (project.maxEditableDate)
this.maxEditableDate = computeEnd(project.maxEditableDate);
else
this.maxEditableDate = Infinity;
//recover stored ccollapsed statuas
var collTasks=this.loadCollapsedTasks();
//shift dates in order to have client side the same hour (e.g.: 23:59) of the server side
for (var i = 0; i < project.tasks.length; i++) {
var task = project.tasks[i];
task.start += this.serverClientTimeOffset;
task.end += this.serverClientTimeOffset;
//set initial collapsed status
task.collapsed=collTasks.indexOf(task.id)>=0;
}
this.loadTasks(project.tasks, project.selectedRow);
this.deletedTaskIds = [];
//recover saved zoom level
if (project.zoom){
this.gantt.zoom = project.zoom;
}
this.endTransaction();
var self = this;
this.gantt.element.oneTime(200, function () {self.gantt.centerOnToday()});
};
GanttMaster.prototype.loadTasks = function (tasks, selectedRow) {
//console.debug("GanttMaster.prototype.loadTasks")
var factory = new TaskFactory();
//reset
this.reset();
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
if (!(task instanceof Task)) {
var t = factory.build(task.id, task.name, task.code, task.level, task.start, task.duration, task.collapsed);
for (var key in task) {
if (key != "end" && key != "start")
t[key] = task[key]; //copy all properties
}
task = t;
}
task.master = this; // in order to access controller from task
this.tasks.push(task); //append task at the end
}
//var prof=new Profiler("gm_loadTasks_addTaskLoop");
for (var i = 0; i < this.tasks.length; i++) {
var task = this.tasks[i];
var numOfError = this.__currentTransaction && this.__currentTransaction.errors ? this.__currentTransaction.errors.length : 0;
//add Link collection in memory
while (!this.updateLinks(task)) { // error on update links while loading can be considered as "warning". Can be displayed and removed in order to let transaction commits.
if (this.__currentTransaction && numOfError != this.__currentTransaction.errors.length) {
var msg = "ERROR:\n";
while (numOfError < this.__currentTransaction.errors.length) {
var err = this.__currentTransaction.errors.pop();
msg = msg + err.msg + "\n\n";
}
alert(msg);
}
this.removeAllLinks(task, false);
}
if (!task.setPeriod(task.start, task.end)) {
alert(GanttMaster.messages.GANNT_ERROR_LOADING_DATA_TASK_REMOVED + "\n" + task.name );
//remove task from in-memory collection
this.tasks.splice(task.getRow(), 1);
} else {
//append task to editor
this.editor.addTask(task, null, true);
//append task to gantt
this.gantt.addTask(task);
}
}
//this.editor.fillEmptyLines();
//prof.stop();
// re-select old row if tasks is not empty
if (this.tasks && this.tasks.length > 0) {
selectedRow = selectedRow ? selectedRow : 0;
this.tasks[selectedRow].rowElement.click();
}
};
GanttMaster.prototype.getTask = function (taskId) {
var ret;
for (var i = 0; i < this.tasks.length; i++) {
var tsk = this.tasks[i];
if (tsk.id == taskId) {
ret = tsk;
break;
}
}
return ret;
};
GanttMaster.prototype.getResource = function (resId) {
var ret;
for (var i = 0; i < this.resources.length; i++) {
var res = this.resources[i];
if (res.id == resId) {
ret = res;
break;
}
}
return ret;
};
GanttMaster.prototype.changeTaskDeps = function (task) {
return task.moveTo(task.start);
};
GanttMaster.prototype.changeTaskDates = function (task, start, end) {
return task.setPeriod(start, end);
};
GanttMaster.prototype.moveTask = function (task, newStart) {
return task.moveTo(newStart, true);
};
GanttMaster.prototype.taskIsChanged = function () {
//console.debug("taskIsChanged");
var master = this;
//refresh is executed only once every 50ms
this.element.stopTime("gnnttaskIsChanged");
//var profilerext = new Profiler("gm_taskIsChangedRequest");
this.element.oneTime(50, "gnnttaskIsChanged", function () {
//console.debug("task Is Changed real call to redraw");
//var profiler = new Profiler("gm_taskIsChangedReal");
master.editor.redraw();
master.gantt.refreshGantt();
master.element.trigger("gantt.refreshGanttCompleted");
//profiler.stop();
});
//profilerext.stop();
};
GanttMaster.prototype.redraw = function () {
this.editor.redraw();
this.gantt.refreshGantt();
};
GanttMaster.prototype.reset = function () {
//console.debug("GanttMaster.prototype.reset");
this.tasks = [];
this.links = [];
this.deletedTaskIds = [];
if (!this.__inUndoRedo) {
this.__undoStack = [];
this.__redoStack = [];
} else { // don't reset the stacks if we're in an Undo/Redo, but restart the inUndoRedo control
this.__inUndoRedo = false;
}
delete this.currentTask;
this.editor.reset();
this.gantt.reset();
};
GanttMaster.prototype.showTaskEditor = function (taskId) {
var task = this.getTask(taskId);
task.rowElement.find(".edit").click();
};
GanttMaster.prototype.saveProject = function () {
return this.saveGantt(false);
};
GanttMaster.prototype.saveGantt = function (forTransaction) {
//var prof = new Profiler("gm_saveGantt");
var saved = [];
for (var i = 0; i < this.tasks.length; i++) {
var task = this.tasks[i];
var cloned = task.clone();
delete cloned.master;
delete cloned.rowElement;
delete cloned.ganttElement;
//shift back to server side timezone
if (!forTransaction) {
cloned.start -= this.serverClientTimeOffset;
cloned.end -= this.serverClientTimeOffset;
}
saved.push(cloned);
}
var ret = {tasks: saved};
if (this.currentTask) {
ret.selectedRow = this.currentTask.getRow();
}
ret.deletedTaskIds = this.deletedTaskIds; //this must be consistent with transactions and undo
if (!forTransaction) {
ret.resources = this.resources;
ret.roles = this.roles;
ret.canWrite = this.permissions.canWrite;
ret.canWriteOnParent = this.permissions.canWriteOnParent;
ret.zoom = this.gantt.zoom;
//save collapsed tasks on localStorage
this.storeCollapsedTasks();
//mark un-changed task and assignments
this.markUnChangedTasksAndAssignments(ret);
//si aggiunge il commento al cambiamento di date/status
ret.changesReasonWhy=$("#LOG_CHANGES").val();
}
//prof.stop();
return ret;
};
GanttMaster.prototype.markUnChangedTasksAndAssignments=function(newProject){
//console.debug("markUnChangedTasksAndAssignments");
//si controlla che ci sia qualcosa di cambiato, ovvero che ci sia l'undo stack
if (this.__undoStack.length>0){
var oldProject=JSON.parse(ge.__undoStack[0]);
//si looppano i "nuovi" task
for (var i=0;i<newProject.tasks.length;i++){
var newTask=newProject.tasks[i];
//se è un task che c'erà già
if (typeof (newTask.id)=="String" && !newTask.id.startsWith("tmp_")){
//si recupera il vecchio task
var oldTask;
for (var j=0;j<oldProject.tasks.length;j++){
if (oldProject.tasks[j].id==newTask.id){
oldTask=oldProject.tasks[j];
break;
}
}
//si controlla se ci sono stati cambiamenti
var taskChanged=
oldTask.id != newTask.id ||
oldTask.code != newTask.code ||
oldTask.name != newTask.name ||
oldTask.start != newTask.start ||
oldTask.startIsMilestone != newTask.startIsMilestone ||
oldTask.end != newTask.end ||
oldTask.endIsMilestone != newTask.endIsMilestone ||
oldTask.duration != newTask.duration ||
oldTask.status != newTask.status ||
oldTask.typeId != newTask.typeId ||
oldTask.relevance != newTask.relevance ||
oldTask.progress != newTask.progress ||
oldTask.progressByWorklog != newTask.progressByWorklog ||
oldTask.description != newTask.description ||
oldTask.level != newTask.level||
oldTask.depends != newTask.depends;
newTask.unchanged=!taskChanged;
//se ci sono assegnazioni
if (newTask.assigs&&newTask.assigs.length>0){
//se abbiamo trovato il vecchio task e questo aveva delle assegnazioni
if (oldTask && oldTask.assigs && oldTask.assigs.length>0){
for (var j=0;j<oldTask.assigs.length;j++){
var oldAssig=oldTask.assigs[j];
//si cerca la nuova assegnazione corrispondente
var newAssig;
for (var k=0;k<newTask.assigs.length;k++){
if(oldAssig.id==newTask.assigs[k].id){
newAssig=newTask.assigs[k];
break;
}
}
//se c'è una nuova assig corrispondente
if(newAssig){
//si confrontano i valori per vedere se è cambiata
newAssig.unchanged=
newAssig.resourceId==oldAssig.resourceId &&
newAssig.roleId==oldAssig.roleId &&
newAssig.effort==oldAssig.effort;
}
}
}
}
}
}
}
};
GanttMaster.prototype.loadCollapsedTasks = function () {
var collTasks=[];
if (localStorage ) {
if (localStorage.getObject("TWPGanttCollTasks"))
collTasks = localStorage.getObject("TWPGanttCollTasks");
return collTasks;
}
};
GanttMaster.prototype.storeCollapsedTasks = function () {
//console.debug("storeCollapsedTasks");
if (localStorage) {
var collTasks;
if (!localStorage.getObject("TWPGanttCollTasks"))
collTasks = [];
else
collTasks = localStorage.getObject("TWPGanttCollTasks");
for (var i = 0; i < this.tasks.length; i++) {
var task = this.tasks[i];
var pos=collTasks.indexOf(task.id);
if (task.collapsed){
if (pos<0)
collTasks.push(task.id);
} else {
if (pos>=0)
collTasks.splice(pos,1);
}
}
localStorage.setObject("TWPGanttCollTasks", collTasks);
}
};
GanttMaster.prototype.updateLinks = function (task) {
//console.debug("updateLinks",task);
//var prof= new Profiler("gm_updateLinks");
// defines isLoop function
function isLoop(task, target, visited) {
//var prof= new Profiler("gm_isLoop");
//console.debug("isLoop :"+task.name+" - "+target.name);
if (target == task) {
return true;
}
var sups = task.getSuperiors();
//my parent' superiors are my superiors too
var p = task.getParent();
while (p) {
sups = sups.concat(p.getSuperiors());
p = p.getParent();
}
//my children superiors are my superiors too
var chs = task.getChildren();
for (var i = 0; i < chs.length; i++) {
sups = sups.concat(chs[i].getSuperiors());
}
var loop = false;
//check superiors
for (var i = 0; i < sups.length; i++) {
var supLink = sups[i];
if (supLink.from == target) {
loop = true;
break;
} else {
if (visited.indexOf(supLink.from.id + "x" + target.id) <= 0) {
visited.push(supLink.from.id + "x" + target.id);
if (isLoop(supLink.from, target, visited)) {
loop = true;
break;
}
}
}
}
//check target parent
var tpar = target.getParent();
if (tpar) {
if (visited.indexOf(task.id + "x" + tpar.id) <= 0) {
visited.push(task.id + "x" + tpar.id);
if (isLoop(task, tpar, visited)) {
loop = true;
}
}
}
//prof.stop();
return loop;
}
//remove my depends
this.links = this.links.filter(function (link) {
return link.to != task;
});
var todoOk = true;
if (task.depends) {
//cannot depend from an ancestor
var parents = task.getParents();
//cannot depend from descendants
var descendants = task.getDescendant();
var deps = task.depends.split(",");
var newDepsString = "";
var visited = [];
for (var j = 0; j < deps.length; j++) {
var dep = deps[j]; // in the form of row(lag) e.g. 2:3,3:4,5
var par = dep.split(":");
var lag = 0;
if (par.length > 1) {
lag = parseInt(par[1]);
}
var sup = this.tasks[parseInt(par[0] - 1)];
if (sup) {
if (parents && parents.indexOf(sup) >= 0) {
this.setErrorOnTransaction("\""+task.name + "\"\n" + GanttMaster.messages.CANNOT_DEPENDS_ON_ANCESTORS + "\n\"" + sup.name+"\"");
todoOk = false;
} else if (descendants && descendants.indexOf(sup) >= 0) {
this.setErrorOnTransaction("\""+task.name + "\"\n" + GanttMaster.messages.CANNOT_DEPENDS_ON_DESCENDANTS + "\n\"" + sup.name+"\"");
todoOk = false;
} else if (isLoop(sup, task, visited)) {
todoOk = false;
this.setErrorOnTransaction(GanttMaster.messages.CIRCULAR_REFERENCE + "\n\"" + task.name + "\" -> \"" + sup.name+"\"");
} else {
this.links.push(new Link(sup, task, lag));
newDepsString = newDepsString + (newDepsString.length > 0 ? "," : "") + dep;
}
}
}
task.depends = newDepsString;
}
//prof.stop();
return todoOk;
};
GanttMaster.prototype.moveUpCurrentTask = function () {
var self = this;
//console.debug("moveUpCurrentTask",self.currentTask)
if (!self.permissions.canWrite || !self.currentTask.canWrite || !self.permissions.canMoveUpDown )
return;
if (self.currentTask) {
self.beginTransaction();
self.currentTask.moveUp();
self.endTransaction();
}
};
GanttMaster.prototype.moveDownCurrentTask = function () {
var self = this;
//console.debug("moveDownCurrentTask",self.currentTask)
if (!self.permissions.canWrite || !self.currentTask.canWrite || !self.permissions.canMoveUpDown )
return;
if (self.currentTask) {
self.beginTransaction();
self.currentTask.moveDown();
self.endTransaction();
}
};
GanttMaster.prototype.outdentCurrentTask = function () {
var self = this;
if (!self.permissions.canWrite || !self.currentTask.canWrite || !self.permissions.canInOutdent)
return;
if (self.currentTask) {
var par = self.currentTask.getParent();
self.beginTransaction();
self.currentTask.outdent();
self.endTransaction();
//[expand]
if (par) self.editor.refreshExpandStatus(par);
}
};
GanttMaster.prototype.indentCurrentTask = function () {
var self = this;
if (!self.permissions.canWrite || !self.currentTask.canWrite|| !self.permissions.canInOutdent)
return;
if (self.currentTask) {
self.beginTransaction();
self.currentTask.indent();
self.endTransaction();
}
};
GanttMaster.prototype.addBelowCurrentTask = function () {
var self = this;
if (!self.permissions.canWrite|| !self.permissions.canAdd)
return;
var factory = new TaskFactory();
var ch;
var row = 0;
if (self.currentTask && self.currentTask.name) {
ch = factory.build("tmp_" + new Date().getTime(), "", "", self.currentTask.level + 1, self.currentTask.start, 1);
row = self.currentTask.getRow() + 1;
if (row>0) {
self.beginTransaction();
var task = self.addTask(ch, row);
if (task) {
task.rowElement.click();
task.rowElement.find("[name=name]").focus();
}
self.endTransaction();
}
}
};
GanttMaster.prototype.addAboveCurrentTask = function () {
var self = this;
if (!self.permissions.canWrite || !self.permissions.canAdd)
return;
var factory = new TaskFactory();
var ch;
var row = 0;
if (self.currentTask && self.currentTask.name) {
//cannot add brothers to root
if (self.currentTask.level <= 0)
return;
ch = factory.build("tmp_" + new Date().getTime(), "", "", self.currentTask.level, self.currentTask.start, 1);
row = self.currentTask.getRow();
if (row > 0) {
self.beginTransaction();
var task = self.addTask(ch, row);
if (task) {
task.rowElement.click();
task.rowElement.find("[name=name]").focus();
}
self.endTransaction();
}
}
};
GanttMaster.prototype.deleteCurrentTask = function () {
//console.debug("deleteCurrentTask",this.currentTask , this.isMultiRoot)
var self = this;
if (!self.currentTask || !self.permissions.canWrite || !self.currentTask.canWrite)
return;
var row = self.currentTask.getRow();
if (self.currentTask && (row > 0 || self.isMultiRoot || self.currentTask.isNew()) ) {
var par = self.currentTask.getParent();
self.beginTransaction();
self.currentTask.deleteTask();
self.currentTask = undefined;
//recompute depends string