/
data_context.js
3135 lines (2885 loc) · 122 KB
/
data_context.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
// ==========================================================================
// DG.DataContext
//
// The DataContext corresponds to a hierarchical data set comprised of
// multiple collections in a linear parent/child relationship. Currently,
// the data are limited to two levels (i.e. parent and child), but future
// extension to support arbitrary number of levels is an eventual goal.
//
// Author: Kirk Swenson
//
// Copyright (c) 2014 by The Concord Consortium, Inc. All rights reserved.
//
// 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.
// ==========================================================================
/*global pluralize:true*/
/** @class
Coordinating controller which manages a set of collections that form the
hierarchical data model.
@extends SC.Object
*/
DG.DataContext = SC.Object.extend((function () // closure
/** @scope DG.DataContext.prototype */ {
/**
* Returns an integer constrained within the specified limits including the max.
* If undefined, returns the max value.
* @param {number|undefined} num
* @param {number} min // assumed an integer
* @param {number} max // assumed an integer
* @return {number}
*/
function constrainInt(num, min, max) {
var n = isNaN(num) ? Number.MAX_SAFE_INTEGER : Math.round(num);
// clipToIntegerRange is exclusive of the max value
return DG.MathUtilities.clipToIntegerRange(n, min, max + 1);
}
return { // return from closure
/**
* The type of DataContext, for use when archiving/restoring.
* @property {String}
*/
type: 'DG.DataContext',
/**
* The id of the DG.GameController | DG.ComponentController that manages this context.
* @property {string}
*/
_managingControllerID: null,
/**
* The DG.DataContextRecord for which this is the controller.
* @property {DG.DataContextRecord}
*/
model: null,
name: function (k, v) {
if (!SC.none(v)) {
this.setPath('model.name', v);
}
return this.getPath('model.name');
}.property(),
title: function (k, v) {
if (!SC.none(v)) {
this.setPath('model.title', v);
}
return this.getPath('model.title');
}.property(),
description: function (k, v) {
if (!SC.none(v)) {
this.setPath('model.description', v);
}
return this.getPath('model.description');
}.property(),
preventReorg: function (k, v) {
if (!SC.none(v)) {
this.setPath('model.preventReorg', v);
}
return this.getPath('model.preventReorg');
}.property(),
/**
The Dependency Manager object for this context
@property {DG.DependencyMgr}
*/
dependencyMgr: function () {
return this.getPath('model.dependencyMgr');
}.property(),
/**
The number of change requests that have been applied.
Clients can use this like a seed value to determine when they're out of date
and by how many changes they're behind. Clients that observe this property
will be notified whenever a change is applied.
@property {Number}
*/
changeCount: 0,
/**
The number of selection change requests that have been applied.
Clients can use this like a seed value to determine when they're out of date
and by how many selection changes they're behind. Clients that observe this property
will be notified whenever a selection change is applied.
@property {Number}
*/
selectionChangeCount: 0,
/**
* The number of metadata changes that have occurred.
* Clients can observe this to be notified of metadata changes.
* Initially triggered only by the 'managingController' property.
* @property {Number}
*/
metadataChangeCount: 0,
/**
Array of change objects that have been applied to/by this data context.
Newly-applied changes are appended to the array, so the most recent changes
are at the end.
@property {[Object]} Array of change objects
*/
changes: null,
/**
* Flag to indicate that the user has moved attributes within a collection
* or between grids in a way that invalidates the Data Interactive
* specification. If this happens we will block new createCase(s), openCase,
* or updateCase requests from the data interactives to avoid corrupting
* the data.
*/
flexibleGroupingChangeFlag: function (key, value) {
if (!SC.none(value)) {
this.setPath('model.flexibleGroupingChangeFlag', value);
}
return this.getPath('model.flexibleGroupingChangeFlag');
}.property(),
// The following code should be uncommented if changes to the above property
// are to be observed. SC does not support chained properties, and so the
// observer pattern below is recommended and required for v1.10 and above.
//flexibleGroupingChangeFlagDidChange: function () {
// this.notifyPropertyChange('flexibleGroupingChangeFlag',
// this.get('flexibleGroupingChangeFlag'));
//}.observes('*model.flexibleGroupingChangeFlag'),
canonicalizeName: function (iName) {
return DG.Attribute.canonicalizeName(iName);
},
/**
* The id of our DG.DataContextRecord.
* Bound to the 'id' property of the model.
* @property {Number}
*/
id: function () {
return this.getPath('model.id');
}.property('model'),
collections: null,
/**
* Return the total number of cases, obtained by summing the case count over all collections
* @property{ Number }
*/
totalCaseCount: function () {
var tTotalCount = 0;
this.forEachCollection(function (iCollection) {
tTotalCount += iCollection.getPath('collection.cases').length;
});
return tTotalCount;
}.property('collectionCount'),
/**
* Returns a single array containing all cases of all collections
* @property {[DG.Case]}
*/
allCases: function () {
var tResult = [];
this.forEachCollection(function (iCollection) {
tResult = tResult.concat(iCollection.getPath('collection.cases'));
});
return tResult;
}.property('collectionCount'),
itemCount: function () {
var dataSet = this.get('dataSet');
return dataSet && dataSet.getDataItemCount();
}.property(),
dataSet: function () {
return this.getPath('model.dataSet');
}.property(),
setAsideCount: function () {
return this.get('dataSet').getSetAsideCount();
}.property(),
/**
* The collections for which this controller is responsible.
* Clients expect the order of this array to be parent --> child.
* This function is responsible for guaranteeing the order.
* In particular, games using the old API often create their
* collections in child --> parent order, and need to be reversed
* in this function.
*
* @property {[DG.Collection]}
*/
collectionsDidChange: function () {
var srcCollections = this.getPath('model.collections'),
srcCollectionArray = DG.ObjectMap.values(srcCollections),
i, c,
collectionCount = srcCollectionArray.length;
// Reset and restock the cached array
this.collections = [];
// find the ur-parent, then follow it to all its children.
c = srcCollectionArray[0];
i = 0;
if (c) {
while (!SC.none(c.get('parent')) && i <= collectionCount) {
c = c.get('parent');
i++;
}
if (i > collectionCount) {
DG.logError('Circular parental links among collections in context: ' + this.name);
}
i = 0;
while (!SC.none(c) && i <= collectionCount) {
this.collections.pushObject(c);
c = c.get('children')[0];
i++;
}
if (i > collectionCount) {
DG.logError('Circular child links among collections in context: ' + this.name);
}
}
// Return the cached array in the proper order
return this.collections;
}.observes('model.collectionsChangeCount'),
/**
* Map of DG.CollectionClients, corresponding one-to-one to the DG.Collections.
* @property {Object} Map from collectionID to DG.CollectionClients
*/
_collectionClients: null,
/**
* Whether there are Data Interactives which are affiliated with this
* data context.
* @type {boolean}
*/
hasDataInteractive: function () {
return !SC.none(this.get('owningDataInteractive'));
}.property(),
/**
* Returns the Data Interactives for which are affiliated with this
* data context.
* @type {DG.GameController}
*/
owningDataInteractive: function () {
var dataInteractives = DG.currDocumentController().get('dataInteractives');
var myID = this.get('id');
var found = dataInteractives && DG.ObjectMap.values(dataInteractives).find(function (dataInteractive) {
var id = (dataInteractive.getPath('context.id'));
return (!SC.none(id) && (id === myID));
}.bind(this));
DG.assert(SC.none(found) || found.constructor === DG.GameController, "Found Game Controller");
return found;
}.property(),
/**
* Returns the Data Interactive which manages this data context.
* May be generalized to support affiliation with other components at some point.
* @type {DG.GameController}
*/
managingController: function (key, value) {
if (value != null) {
this._managingControllerID = value;
this.incrementProperty('metadataChangeCount');
}
// if no manager specified, default to owner
if (this._managingControllerID == null)
return this.get('owningDataInteractive');
// search for manager
var dataInteractives = DG.currDocumentController().get('dataInteractives');
return dataInteractives &&
DG.ObjectMap.values(dataInteractives)
.find(function (dataInteractive) {
var id = (dataInteractive.getPath('model.id'));
return ((id != null) && (id === this._managingControllerID));
}.bind(this));
}.property(),
/**
* Whether there are Data Interactives for which are affiliated with this
* data context.
* @type {boolean}
*/
hasGameInteractive: function () {
var owningDataInteractive = this.get('owningDataInteractive');
var activeChannel = owningDataInteractive && owningDataInteractive.activeChannel();
// Its possible that the owning interactive has not contacted codap, so has not
// established a channel. We assume this is a Game Interactive.
if (owningDataInteractive) {
return SC.none(activeChannel) || (activeChannel.constructor === DG.GamePhoneHandler);
} else {
return false;
}
}.property(),
/**
Initialization method.
*/
init: function () {
sc_super();
this._collectionClients = {};
this.changes = [];
this.collectionsDidChange();
DG.globalsController.addObserver('globalNameChanges', this, 'globalNamesDidChange');
DG.globalsController.addObserver('globalValueChanges', this, 'globalValuesDidChange');
},
/**
Destruction method.
*/
destroy: function () {
DG.globalsController.removeObserver('globalNameChanges', this, 'globalNamesDidChange');
DG.globalsController.removeObserver('globalValueChanges', this, 'globalValuesDidChange');
var i, collectionCount = this.get('collectionCount');
for (i = 0; i < collectionCount; ++i) {
var collection = this.getCollectionAtIndex(i);
if (collection) this.willRemoveCollection(collection);
}
this.model.destroy();
sc_super();
},
/**
Returns an array of DG.Case objects corresponding to the selected cases.
Optionally returns another array of DG.Case objects for the unselected cases.
Note that the cases may come from multiple collections within the data context.
@returns {[DG.Case]} The currently selected cases
or
{
selected: {Array of DG.Case} The currently selected cases,
unselected: {Array of DG.Case} The currently unselected cases
}
*/
getSelectedCases: function (iReturnUnselectedAlso) {
var i, collectionCount = this.get('collectionCount'),
selectedIds = {},
selectedCases = [],
unselectedCases = [];
// utility function for adding individual cases to the selection object to return
function addSelectedCase(iCase) {
selectedCases.push(iCase);
// parents of selected cases are considered selected when determining unselected
for (; iCase; iCase = iCase.get('parent')) {
selectedIds[iCase.get('id')] = true;
}
}
function addCaseIfUnselected(selection, iCase) {
if (!selection.contains(iCase) && !selectedIds[iCase.get('id')]) {
unselectedCases.push(iCase);
}
}
// add each selected case from all collections to the selection object to return
for (i = collectionCount - 1; i >= 0; --i) {
var collection = this.getCollectionAtIndex(i),
collCases = iReturnUnselectedAlso && collection && collection.get('casesController'),
collSelection = collection && collection.getPath('casesController.selection');
if (collSelection)
collSelection.forEach(addSelectedCase);
if (collCases)
collCases.forEach(addCaseIfUnselected.bind(null, collSelection));
}
return iReturnUnselectedAlso
? {selected: selectedCases, unselected: unselectedCases}
: selectedCases;
},
/**
* Accesses a case from its ID.
*
* Centralized method for Component layer objects.
* @param iCaseID
* @returns {*}
*/
getCaseByID: function (iCaseID) {
var iCase = DG.store.find(DG.Case, iCaseID);
if (iCase && iCase instanceof DG.Case) return iCase;
},
/**
Private properties used internally to synchronize changes with notifications.
*/
_changeCount: 0,
_prevChangeCount: 0,
/**
Returns the most-recently applied change object. Clients that observe the 'changeCount'
property can call this function to determine what change triggered the notification.
@property {Object} [computed] The most-recently applied change object
*/
lastChange: function () {
var count = this.changes.length;
return count > 0 ? this.changes[count - 1] : null;
}.property(),
/**
Returns an array of change objects which correspond to the changes that have
occurred since the last change notification.
@property {[Object]}
*/
newChanges: function () {
var changesLength = this.changes && this.changes.length,
newCount = this._changeCount - this._prevChangeCount;
DG.assert(this._changeCount <= changesLength);
DG.assert(this._prevChangeCount <= this._changeCount);
return this.changes.slice(changesLength - newCount);
}.property(),
/**
Apply the specified change object to this data context.
@param {Object} iChange -- An object specifying the change(s) to apply
{String} iChange.operation -- The name of the change to apply
Other change properties are operation-specific
*/
applyChange: function (iChange) {
var this_ = this,
result = this.performChange(iChange);
iChange.result = DG.ObjectMap.join((iChange.result || {}), result);
// TODO: Figure out how/when to prune the changes array so it doesn't grow unbounded.
this.changes.push(iChange);
++this._changeCount;
// We may not be in a runloop if we got here through an event
SC.run(function () {
// Delay the notification until the end of the runloop, so that SproutCore has a
// chance to flush its caches, update bindings, etc.
this_.invokeLast(function () {
this_.set('changeCount', this_._changeCount);
this_._prevChangeCount = this_._changeCount;
});
});
return iChange.result;
},
/**
Performs the specified change(s) to this data context.
Called by the applyChange() method.
@param {Object} iChange -- An object specifying the change(s) to apply
{String} iChange.operation -- The name of the change to apply
Other change properties are operation-specific
*/
performChange: function (iChange) {
// If the client indicates that the action has already
// been taken, simply return with success.
if (iChange.isComplete) return {success: true};
var result = {success: false},
shouldDirtyDoc = true,
shouldRetainUndo = false;
switch (iChange.operation) {
case 'createCollection':
result = this.doCreateCollection(iChange);
break;
case 'updateCollection':
result = this.doUpdateCollection(iChange);
break;
case 'deleteCollection':
result = this.doDeleteCollection(iChange);
break;
case 'createCase':
// doCreateCases() takes an array of values arrays
iChange.values = [iChange.values || []];
result = this.doCreateCases(iChange);
if (result.caseIDs && result.caseIDs.length)
result.caseID = result.caseIDs[0];
shouldRetainUndo = true;
break;
case 'createCases':
result = this.doCreateCases(iChange);
shouldRetainUndo = true;
break;
case 'updateCases':
result = this.doUpdateCases(iChange);
break;
case 'moveCases':
result = this.doMoveCases(iChange);
break;
case 'deleteCases':
result = this.doDeleteCases(iChange);
shouldDirtyDoc = false;
break;
case 'selectCases':
result = this.doSelectCases(iChange);
shouldDirtyDoc = false;
break;
case 'createItems':
result = this.doCreateItems(iChange);
shouldDirtyDoc = false;
break;
case 'updateItems':
result = this.doUpdateItem(iChange);
shouldDirtyDoc = false;
break;
case 'moveItems':
result = this.doMoveItems(iChange);
shouldDirtyDoc = false;
break;
case 'deleteItems':
result = this.doDeleteItems(iChange);
shouldDirtyDoc = false;
break;
case 'createAttributes':
result = this.doCreateAttributes(iChange);
break;
case 'updateAttributes':
result = this.doUpdateAttributes(iChange);
break;
case 'unhideAttributes':
case 'hideAttributes':
result = this.doChangeAttributesVisibility(iChange);
break;
case 'deleteAttributes':
result = this.doDeleteAttributes(iChange);
break;
case 'moveAttribute':
result = this.doMoveAttribute(iChange);
shouldDirtyDoc = false;
break;
case 'resetCollections':
result = this.doResetCollections(iChange);
break;
case 'deleteDataContext':
result = this.destroy();
break;
case 'updateDataContext':
result = this.doUpdateDataContext(iChange);
break;
default:
DG.logWarn('DataContext.performChange: unknown operation: '
+ iChange.operation);
}
if (shouldDirtyDoc && (iChange.dirtyDocument !== false))
DG.dirtyCurrentDocument(this.get('model'), shouldRetainUndo);
return result;
},
/**
Creates a collection according to the arguments specified.
@param {Object} iChange
{String} iChange.operation -- 'createCollection'
{Object} iChange.properties -- properties of the new collection
{Array of Object} iChange.attributes -- array of attribute specifications
@returns {Object} a result object
{Boolean} result.success -- true on success, false on failure
{DG.CollectionClient} result.collection -- the newly created collection
*/
doCreateCollection: function (iChange) {
var tCollection = this.guaranteeCollection(iChange.properties);
var results;
if (tCollection) {
iChange.attributes && iChange.attributes.forEach(function (iAttrSpec) {
if (!SC.none(iAttrSpec.id) && !SC.none(iAttrSpec.collection)) {
this.moveAttribute(iAttrSpec, tCollection);
} else {
tCollection.guaranteeAttribute(iAttrSpec);
}
}.bind(this));
// if this is a recreation of the collection make sure the ordering corresponds
// to DI expectations.
iChange.attributes && tCollection.reorderAttributes(iChange.attributes.getEach('name'));
results = this.regenerateCollectionCases();
if (results) {
return {success: true, collection: tCollection};
}
}
return {success: false};
},
/**
* Updates the properties of a collection.
* @param {object} iChange
* {String} iChange.operation -- 'updateCollection'
* {String|DG.CollectionClient} iChange.collection -- the affected collection
* {Object} iChange.properties -- properties of the new collection
* @returns {{success: boolean}}
*/
doUpdateCollection: function (iChange) {
var success = true;
var updatedProperties = {};
var kMetaProperties = ['name', 'title'];
var collection = (SC.typeOf(iChange.collection) === SC.T_STRING)
? this.getCollectionByName(iChange.collection)
: iChange.collection;
DG.ObjectMap.forEach(iChange.properties, function (key, value) {
if (kMetaProperties.contains(key)) {
updatedProperties[key] = value;
collection.set(key, value);
} else {
DG.logWarn('Attempt to update "%@" of collection %@[%@] not permitted.',
key, collection.get('name'), collection.get('id'));
delete iChange.properties.key;
}
}.bind(this));
return {
success: success,
properties: updatedProperties
};
},
/**
* Updates the properties of a dataContext. That is: title, description, preventReorg...
* @param {object} iChange
* {String} iChange.operation -- 'updateDataContext'
* {Object} iChange.properties -- new property values
* @returns {{success: boolean}}
*/
doUpdateDataContext: function (iChange) {
var success = true;
var updatedProperties = {};
var kMetaProperties = ['name', 'title', 'preventReorg'];
DG.ObjectMap.forEach(iChange.properties, function (key, value) {
// name is not mutable
if (kMetaProperties.contains(key)) {
this.set(key, value);
updatedProperties[key] = value;
} else {
DG.logWarn('Attempt to update "%@" of data context %@[%@] not permitted.',
key, this.get('name'), this.get('id'));
delete iChange.properties.key;
}
}.bind(this));
return {
success: success,
properties: updatedProperties
};
},
/**
Creates one or more cases according to the arguments specified.
@param {Object} iChange
{String} iChange.operation -- 'createCase'|'createCases'
{DG.CollectionClient} iChange.collection (optional) -- collection containing cases
If not present, the case will be created in the child collection.
{Array of iChange.values -- The array of values to use for the case values.
Arrays of Values}
The order of the values should match the order of the attributes
in the collection specification (e.g. 'initGame').
@returns {Object} An object is returned
{Boolean} result.success -- true on success, false on failure
{Number} result.caseID -- the case ID of the first newly created case
{[Number]} result.caseIDs -- an array ids of all cases created
{Number} result.itemID -- the item ID of the first newly created item
{[Number]} result.itemIDs -- an array ids of all items created
*/
doCreateCases: function (iChange) {
function createOneCase(iValues) {
var properties = {};
var newCase;
if (iChange.properties) {
DG.ObjectMap.copy(properties, iChange.properties);
}
if (Array.isArray(iValues)) {
newCase = collection.createCase(properties);
if (newCase) {
collection.setCaseValuesFromArray(newCase, iValues);
}
} else {
properties.values = iValues;
newCase = collection.createCase(properties);
}
if (newCase) {
result.success = true;
result.caseIDs.push(newCase.get('id'));
result.itemIDs.push(newCase.item.id);
}
}
/**
* returns true if either the collection is a child collection or the parentKey
* resolves to an existing parent.
* @param parentKey {number}
*/
var validateParent = function (collection, parentKey) {
var rslt = true;
var parentCollectionID = collection.getParentCollectionID();
if (parentCollectionID) {
rslt = !SC.none(this.getCaseByID(parentKey));
if (!rslt) {
DG.logWarn('Cannot create case with invalid or deleted parent: ' + parentKey);
}
}
return rslt;
}.bind(this);
var collection,
valuesArrays,
parentIsValid = true,
result = {success: false, caseIDs: [], itemIDs: []};
if (!iChange.collection) {
iChange.collection = this.get('childCollection');
}
if( !iChange.collection.casesController)
iChange.collection = iChange.collection.get('name');
if (typeof iChange.collection === "string") {
collection = this.getCollectionByName( iChange.collection);
iChange.collection = collection; // Because we'll need it as an object later
} else {
collection = iChange.collection;
}
// we hold off on observers because of performance issues adding many
// cases when some cases are selected
collection.casesController.beginPropertyChanges();
try {
if (!iChange.properties) {
iChange.properties = {};
}
if (typeof iChange.properties.parent !== 'object') {
parentIsValid = validateParent(collection, iChange.properties.parent);
}
if (collection && parentIsValid) {
valuesArrays = iChange.values || [[]];
valuesArrays.forEach(createOneCase);
if (result.caseIDs && (result.caseIDs.length > 0)) {
result.caseID = result.caseIDs[0];
}
if (result.itemIDs && (result.itemIDs.length > 0)) {
result.itemID = result.itemIDs[0];
}
}
} finally {
collection.casesController.endPropertyChanges();
}
// invalidate dependents; aggregate functions may need to recalculate
this.invalidateAttrsOfCollections([collection], iChange);
return result;
},
/**
Adds new items to context.
@param {Object} iChange
{String} iChange.operation -- 'createItems'
{Array of DG.Case} iChange.items (optional)-- DG.Item objects to be added
{number} iChange.requester -- ID of requesting object
*/
doCreateItems: function (iChange) {
var IDs = this.addItems(iChange.items);
if (!IDs) {
return {success: false};
}
var caseIDs = IDs.caseIDs;
var itemIDs = IDs.itemIDs;
return {success: true, caseIDs: caseIDs, itemIDs: itemIDs};
},
/**
Updates values in one or more items
@param {Object} iChange
{String} iChange.operation -- 'createItems'
{Array of DG.Case} iChange.items (optional)-- DG.Item objects to be added
{number} iChange.requester -- ID of requesting object
*/
doUpdateItem: function (iChange) {
function findCaseForItem(item, collection) {
return collection.get('casesController').find(function (myCase) {
return myCase.item.id === item.id;
});
}
var itemsUpdate = iChange.items;
if (itemsUpdate && !Array.isArray(itemsUpdate)) {
itemsUpdate = [itemsUpdate];
}
var items = itemsUpdate.map(function (itemUpdate) {
return this.updateItem(itemUpdate.id, itemUpdate.values);
}.bind(this));
var regenResults = this.regenerateCollectionCases();
var deletedCases = regenResults && regenResults.deletedCases;
var createdCases = regenResults && regenResults.createdCases;
var deletedCaseIDs;
var collectionIDCaseMap;
var collections = [];
var myCases = items.map(function (item) {
var myCase = findCaseForItem(item, this.getLastCollection());
return myCase && myCase.id;
}.bind(this));
var result = {
success: true,
changedCases: myCases,
deletedCases: deletedCases,
createCases: createdCases
};
if (myCases && myCases.length) {
this.applyChange({
operation: 'updateCases',
collection: regenResults.collection,
isComplete: true,
requester: iChange.requester,
result: result
});
return result;
}
if (deletedCases && deletedCases.length) {
deletedCaseIDs = regenResults.deletedCases.map(function (iCase) {
return iCase.id;
});
this.applyChange({
operation: 'deleteCases',
isComplete: true,
requester: iChange.requester,
result: {
caseIDs: deletedCaseIDs
}
});
}
if (createdCases && createdCases.length) {
createdCases.forEach(function (iCase) {
var collectionID = iCase.collection.get('id');
var collectionCases = collectionIDCaseMap[collectionID];
if (!collectionCases) {
collections.push(iCase.collection);
collectionCases = collectionIDCaseMap[collectionID] = [];
}
collectionCases.push(iCase.get('id'));
});
DG.dirtyCurrentDocument(this.get('model'), false);
collections.forEach(function (collection) {
var cases = collectionIDCaseMap[collection.get('id')];
var change = {
operation: 'createCases',
collection: this.getCollectionByID(collection.get('id')),
isComplete: true,
properties: {index: true},
result: {
caseIDs: cases,
caseID: cases[0]
}
};
this.applyChange(change);
}.bind(this));
}
},
doMoveItems: function (iChange) {
var dataSet = this.get('dataSet');
if (dataSet && iChange.items && (iChange.itemOrder != null)) {
var oldIndexMap = dataSet.getClientIndexMapCopy();
iChange.items.forEach(function (item, index) {
var itemOrder = Array.isArray(iChange.itemOrder)
? iChange.itemOrder[index]
: iChange.itemOrder;
if (item.id) {
dataSet.moveDataItemByID(item.id, itemOrder);
}
});
var newIndexMap = dataSet.getClientIndexMapCopy();
var isChanged = !newIndexMap
.every(function (itemIndex, arrayIndex) {
return oldIndexMap[arrayIndex] === itemIndex;
});
if (isChanged) {
this.regenerateCollectionCases(null, 'moveCases');
}
}
},
/**
Deletes items in this context.
@param {Object} iChange
{String} iChange.operation -- 'createItems'
{Array of DG.Case} iChange.items (optional)-- DG.Item objects to be added
{number} iChange.requester -- ID of requesting object
*/
doDeleteItems: function (iChange) {
var deletedCaseIDs;
var deletedItems = this.deleteItems(iChange.items);
var regenResults = this.regenerateCollectionCases();
if (regenResults) {
deletedCaseIDs = regenResults.deletedCases.map(function (iCase) {
return iCase.id;
});
this.applyChange({
operation: 'deleteCases',
isComplete: true,
requester: iChange.requester,
result: {
caseIDs: deletedCaseIDs
}
});
return {
deletedCaseIDs: deletedCaseIDs,
deletedItemIDs: deletedItems && deletedItems.map(function (item) {
return item.id;
})
};
} else {
return {success: false};
}
},
/**
Selects/deselects the specified cases.
@param {Object} iChange
{String} iChange.operation -- 'selectCases'
{DG.CollectionClient} iChange.collection (optional) -- collection containing cases
If not present, collection will be looked up from cases,
which is less efficient but more flexible.
{Array of DG.Case} iChange.cases (optional)-- DG.Case objects to be changed
If not present, all cases in collection will be changed.
{Boolean} iChange.select -- true for selection, false for deselection
{Boolean} iChange.extend -- true to extend the current selection
*/
doSelectCases: function (iChange) {
var tCollection = iChange.collection || this.get('childCollection'),
tController = tCollection && tCollection.get('casesController'),
tExtend = iChange.extend || false,
tCollectionExtendMap = {},
tCollectionSelectionMap = {},
isSelectionChanged = false,
this_ = this;
// First selection change for each collection should respect iChange.extend.
// Subsequent changes for each collection should always extend, otherwise
// they wipe out any selection done previously.
function extendForCollection(iCollection) {
var collectionID = iCollection.get('id').toString();
if (tCollectionExtendMap[collectionID] === undefined) {
tCollectionExtendMap[collectionID] = true;
return tExtend;
}
// After the first one, always return true
return true;
}
function addSelectionToCollectionMap(iCollection, iCase) {
var collectionID = iCollection.get('id').toString();
if (tCollectionSelectionMap[collectionID] === undefined) {
tCollectionSelectionMap[collectionID] = {collection: iCollection, cases: []};
}
tCollectionSelectionMap[collectionID].cases.push(iCase);
}
function doSelectByCollection() {
DG.ObjectMap.forEach(tCollectionSelectionMap, function (iCollectionID, iCaseMap) {
var tCollection = iCaseMap.collection,
tCases = iCaseMap.cases,
tController = tCollection.get('casesController');
tController.selectObjects(tCases, extendForCollection(tCollection));
});
}
function doDeselectByCollection() {
DG.ObjectMap.forEach(tCollectionSelectionMap, function (iCollectionID, iCaseMap) {
var tCollection = iCaseMap.collection,