0013280: can't set attendee status for non organisers via editDialog
[tine20] / tine20 / Tinebase / js / widgets / dialog / EditDialog.js
1 /*
2  * Tine 2.0
3  * 
4  * @license     http://www.gnu.org/licenses/agpl.html AGPL Version 3
5  * @author      Cornelius Weiss <c.weiss@metaways.de>
6  * @copyright   Copyright (c) 2007-2013 Metaways Infosystems GmbH (http://www.metaways.de)
7  */
8 Ext.ns('Tine.widgets.dialog');
9
10 /**
11  * Generic 'Edit Record' dialog
12  * Base class for all 'Edit Record' dialogs
13  * 
14  * @namespace   Tine.widgets.dialog
15  * @class       Tine.widgets.dialog.EditDialog
16  * @extends     Ext.FormPanel
17  * @author      Cornelius Weiss <c.weiss@metaways.de>
18  * @constructor
19  * @param {Object} config The configuration options.
20  */
21
22 Tine.widgets.dialog.EditDialog = Ext.extend(Ext.FormPanel, {
23     /**
24      * @cfg {Tine.Tinebase.Application} app
25      * instance of the app object (required)
26      */
27     app: null,
28     /**
29      * @cfg {String} mode
30      * Set to 'local' if the EditDialog only operates on this.record (defaults to 'remote' which loads and saves using the recordProxy)
31      */
32     mode : 'remote',
33     /**
34      * @cfg {Array} tbarItems
35      * additional toolbar items (defaults to false)
36      */
37     tbarItems: false,
38     /**
39      * internal/untranslated app name (required)
40      * 
41      * @cfg {String} appName
42      */
43     appName: null,
44     /**
45      * the modelName (filled by application starter)
46      * 
47      * @type {String} modelName
48      */
49     modelName: null,
50     
51     /**
52      * record definition class  (required if no modelconfig! don't declare for modelconfig!!)
53      * 
54      * @cfg {Ext.data.Record} recordClass
55      */
56     recordClass: null,
57     /**
58      * @cfg {Ext.data.DataProxy} recordProxy
59      */
60     recordProxy: null,
61     /**
62      * @cfg {Bool} showContainerSelector
63      * show container selector in bottom area
64      */
65     showContainerSelector: null,
66     /**
67      * @cfg {Bool} evalGrants
68      * should grants of a grant-aware records be evaluated (defaults to true)
69      */
70     evalGrants: true,
71     /**
72      * @cfg {String} requiredSaveGrant
73      * required grant for apply/save
74      */
75     requiredSaveGrant: 'editGrant',
76
77     /**
78      * @cfg {Ext.data.Record} record
79      * record in edit process.
80      */
81     record: null,
82     
83     /**
84      * holds the modelConfig for the handled record (json-encoded object)
85      * will be decoded in initComponent
86      * 
87      * @type 
88      */
89     modelConfig: null,
90     
91     /**
92      * @cfg {String} saveAndCloseButtonText
93      * text of save and close button
94      */
95     saveAndCloseButtonText: '',
96     /**
97      * @cfg {String} cancelButtonText
98      * text of cancel button
99      */
100     cancelButtonText: '',
101     
102     /**
103      * @cfg {Boolean} copyRecord
104      * copy record
105      */
106     copyRecord: false,
107     
108     /**
109      * @cfg {Boolean} doDuplicateCheck
110      * do duplicate check when saving record (mode remote only)
111      */
112     doDuplicateCheck: true,
113
114     /**
115      * when a record has the relations-property the relations-panel can be disabled here
116      * @cfg {Boolean} hideRelationsPanel
117      */
118     hideRelationsPanel: false,
119     
120     /**
121      * when a record has the attachments-property the attachments-panel can be disabled here
122      * @cfg {Boolean} hideAttachmentsPanel
123      */
124     hideAttachmentsPanel: false,
125     
126     /**
127      * Registry for other relationgridpanels than the generic one,
128      * handling special types of relations the generic one will not.
129      * Panels registered here must have a store with the relation records.
130      * 
131      * @type {Array}
132      */
133     relationPanelRegistry: null,
134     
135     /**
136      * ignore relations to given php-class names in the relation grid
137      * @type {Array}
138      */
139     ignoreRelatedModels: null,
140     
141     /**
142      * dialog is currently saving data
143      * @type Boolean
144      */
145     saving: false,
146     
147     /**
148      * Disable adding cf tab even if model has support for customfields
149      * @type Boolean
150      */
151     disableCfs: false,
152     
153     /**
154      * @property window {Ext.Window|Ext.ux.PopupWindow|Ext.Air.Window}
155      */
156     /**
157      * @property {Number} loadRequest 
158      * transaction id of loadData request
159      */
160     /**
161      * @property loadMask {Ext.LoadMask}
162      */
163     
164     /**
165      * @property containerSelectCombo {Tine.widgets.container.SelectionComboBox}
166      */
167     containerSelectCombo: null,
168     
169     /**
170      * If set, these fields are readOnly (when called dependent to related record)
171      * 
172      * @type {Ext.util.MixedCollection}
173      */
174     fixedFields: null,
175
176     /**
177      * Plain Object with additional configuration (JSON-encoded)
178      * 
179      * @type {Object}
180      */
181     additionalConfig: null,
182
183     /**
184      * canonical name
185      * @cfg {String} canonicalName
186      */
187     canonicalName: 'EditDialog',
188     
189     // private
190     bodyStyle:'padding:5px',
191     layout: 'fit',
192     border: false,
193     cls: 'tw-editdialog',
194     anchor:'100% 100%',
195     deferredRender: false,
196     buttonAlign: null,
197     bufferResize: 500,
198
199     /**
200      * relations panel
201      * 
202      * @type Tine.widgets.relation.GenericPickerGridPanel
203      */
204     relationsPanel: null,
205     
206     // Array of Relation Pickers
207     relationPickers: null,
208     
209     /**
210      * attachments panel
211      * 
212      * @type Tine.widgets.dialog.AttachmentsGridPanel
213      */
214     attachmentsPanel: null,
215     
216     /**
217      * holds the loadMask
218      * set this to false, if no loadMask should be shown
219      * 
220      * @type {Ext.LoadMask}
221      */
222     loadMask: null,
223
224     /**
225      * hook notes panel into dialog
226      */
227     displayNotes: false,
228
229     useMultiple: false,
230
231     //private
232     initComponent: function() {
233         this.relationPanelRegistry = this.relationPanelRegistry ? this.relationPanelRegistry : [];
234         this.addEvents(
235             /**
236              * @event cancel
237              * Fired when user pressed cancel button
238              */
239             'cancel',
240             /**
241              * @event saveAndClose
242              * Fired when user pressed OK button
243              */
244             'saveAndClose',
245             /**
246              * @event update
247              * @desc  Fired when the record got updated
248              * @param {Json String} data data of the entry
249              * @pram  {String} this.mode
250              */
251             'update',
252             /**
253              * @event apply
254              * Fired when user pressed apply button
255              */
256             'apply',
257             /**
258              * @event load
259              * @param {Tine.widgets.dialog.EditDialog} this
260              * @param {Tine.data.Record} record which got loaded
261              * @param {Function} ticket function for async defer
262              * Fired when record is loaded
263              */
264             'load',
265             /**
266              * @event save
267              * @param {Tine.widgets.dialog.EditDialog} this
268              * @param {Tine.data.Record} record which got loaded
269              * @param {Function} ticket function for async defer
270              * Fired when remote record is saving
271              */
272             'save',
273             /**
274              * @event updateDependent
275              * Fired when a subpanel updates the record locally
276              */
277             'updateDependent',
278             /**
279              * @event change
280              * Fires just before the field blurs if the field value has changed.
281              * @param {Ext.form.Field} this
282              * @param {Mixed} newValue The new value
283              * @param {Mixed} oldValue The original value
284              */
285             'change'
286         );
287
288         if (Ext.isString(this.modelConfig)) {
289             this.modelConfig = Ext.decode(this.modelConfig);
290         }
291         
292         if (Ext.isString(this.additionalConfig)) {
293             Ext.apply(this, Ext.decode(this.additionalConfig));
294         }
295         
296         if (Ext.isString(this.fixedFields)) {
297             var decoded = Ext.decode(this.fixedFields);
298             this.fixedFields = new Ext.util.MixedCollection();
299             this.fixedFields.addAll(decoded);
300         }
301         
302         if (! this.recordClass && this.modelName) {
303             this.recordClass = Tine[this.appName].Model[this.modelName];
304         }
305         
306         if (this.recordClass) {
307             this.appName    = this.appName    ? this.appName    : this.recordClass.getMeta('appName');
308             this.modelName  = this.modelName  ? this.modelName  : this.recordClass.getMeta('modelName');
309         }
310
311         if (! this.app) {
312             this.app = Tine.Tinebase.appMgr.get(this.appName);
313         }
314         
315         if (! this.windowNamePrefix) {
316             this.windowNamePrefix = this.modelName + 'EditWindow_';
317         }
318         
319         Tine.log.debug('initComponent: appName: ', this.appName);
320         Tine.log.debug('initComponent: modelName: ', this.modelName);
321         Tine.log.debug('initComponent: app: ', this.app);
322         
323         // init some translations
324         if (this.app.i18n && this.recordClass !== null) {
325             this.i18nRecordName = this.app.i18n.n_hidden(this.recordClass.getMeta('recordName'), this.recordClass.getMeta('recordsName'), 1);
326             this.i18nRecordsName = this.app.i18n._hidden(this.recordClass.getMeta('recordsName'));
327         }
328     
329         if (! this.recordProxy && this.recordClass) {
330             Tine.log.debug('no record proxy given, creating a new one...');
331             this.recordProxy = new Tine.Tinebase.data.RecordProxy({
332                 recordClass: this.recordClass
333             });
334         }
335         // init plugins
336         this.plugins = Ext.isString(this.plugins) ? Ext.decode(this.plugins) : Ext.isArray(this.plugins) ? this.plugins.concat(Ext.decode(this.initialConfig.plugins)) : [];
337         
338         this.plugins.push(this.tokenModePlugin = new Tine.widgets.dialog.TokenModeEditDialogPlugin({}));
339         // added possibility to disable using customfield plugin
340         if (this.disableCfs !== true) {
341             this.plugins.push(new Tine.widgets.customfields.EditDialogPlugin({}));
342         }
343         
344         // init actions
345         this.initActions();
346         // init buttons and tbar
347         this.initButtons();
348         // init container selector
349         this.initContainerSelector();
350         // init record 
351         this.initRecord();
352         // get items for this dialog
353         this.items = this.getFormItems();
354
355         // init relations panel if relations are defined
356         this.initRelationsPanel();
357         // init attachments panel
358         this.initAttachmentsPanel();
359         // init notes panel
360         this.initNotesPanel();
361
362         Tine.widgets.dialog.EditDialog.superclass.initComponent.call(this);
363
364         // set fields readOnly if set
365         this.fixFields();
366         
367         // firefox fix: blur each item before tab changes, so no field  will be focused afterwards
368         if (Ext.isGecko) {
369             this.items.items[0].addListener('beforetabchange', function(tabpanel, newtab, oldtab) {
370                 if (! oldtab) {
371                     return;
372                 }
373                 var form = this.getForm();
374                 
375                 if (form && form.hasOwnProperty('items'))
376                     form.items.each(function(item, index) {
377                         item.blur();
378                     });
379             }, this);
380         }
381
382         if (Ext.isFunction(this.window.relayEvents) && Tine.Tinebase.featureEnabled('featureRememberPopupSize')) {
383             this.window.relayEvents(this, ['resize']);
384         }
385     },
386
387     /**
388      * returns canonical path part
389      * @returns {string}
390      */
391     getCanonicalPathSegment: function () {
392         if (this.recordClass) {
393             return ['',
394                 this.recordClass.getMeta('appName'),
395                 this.canonicalName,
396                 this.recordClass.getMeta('modelName'),
397             ].join(Tine.Tinebase.CanonicalPath.separator);
398         }
399     },
400
401     /**
402      * generic form layout
403      */
404     getFormItems: function() {
405         return {
406             xtype: 'tabpanel',
407             border: false,
408             plain:true,
409             activeTab: 0,
410             border: false,
411             defaults: {
412                 hideMode: 'offsets'
413             },
414             plugins: [{
415                 ptype : 'ux.tabpanelkeyplugin'
416             }],
417             items:[
418                 {
419                     title: this.i18nRecordName,
420                     autoScroll: true,
421                     border: false,
422                     frame: true,
423                     layout: 'border',
424                     defaults: { autoScroll: true },
425                     items: [Ext.applyIf(this.getRecordFormItems(), {
426                         region: 'center',
427                         xtype: 'columnform',
428                         labelAlign: 'top',
429                         formDefaults: {
430                             xtype:'textfield',
431                             anchor: '100%',
432                             labelSeparator: '',
433                             columnWidth: 1/2
434                         },
435                     })].concat(this.getEastPanel())
436                 }, new Tine.widgets.activities.ActivitiesTabPanel({
437                     app: this.appName,
438                     record_id: this.record.id,
439                     record_model: this.modelName
440                 })
441             ]
442         };
443     },
444
445     getEastPanel: function() {
446         var items = [];
447         if (this.recordClass.hasField('description')) {
448             items.push(new Ext.Panel({
449                 title: i18n._('Description'),
450                 iconCls: 'descriptionIcon',
451                 layout: 'form',
452                 labelAlign: 'top',
453                 border: false,
454                 items: [{
455                     style: 'margin-top: -4px; border 0px;',
456                     labelSeparator: '',
457                     xtype: 'textarea',
458                     name: 'description',
459                     hideLabel: true,
460                     grow: false,
461                     preventScrollbars: false,
462                     anchor: '100% 100%',
463                     emptyText: i18n._('Enter description'),
464                     requiredGrant: 'editGrant'
465                 }]
466             }));
467         }
468
469         if (this.recordClass.hasField('tags')) {
470             items.push(new Tine.widgets.tags.TagPanel({
471                 app: this.appName,
472                 border: false,
473                 bodyStyle: 'border:1px solid #B5B8C8;'
474             }));
475         }
476
477         return items.length ? {
478             layout: 'accordion',
479             animate: true,
480             region: 'east',
481             width: 210,
482             split: true,
483             collapsible: true,
484             collapseMode: 'mini',
485             header: false,
486             margins: '0 5 0 5',
487             border: true,
488             items: items
489         } : [];
490     },
491
492     getRecordFormItems: function() {
493         return new Tine.widgets.form.RecordForm({
494             recordClass: this.recordClass
495         });
496     },
497
498     /**
499      * fix fields (used for preselecting form fields when called in dependency to another record)
500      * @return {Boolean}
501      */
502     fixFields: function() {
503         if (this.fixedFields && this.fixedFields.getCount() > 0) {
504             if (! this.rendered) {
505                 this.fixFields.defer(100, this);
506                 return false;
507             }
508             
509             this.fixedFields.each(function(value, index) {
510                 var key = this.fixedFields.keys[index]; 
511                 
512                 var field = this.getForm().findField(key);
513                 
514                 if (field) {
515                     if (Ext.isFunction(this.recordClass.getField(key).type)) {
516                         var foreignRecordClass = this.recordClass.getField(key).type;
517                         var record = new foreignRecordClass(value);
518                         field.selectedRecord = record;
519                         field.setValue(value);
520                         field.fireEvent('select');
521                     } else {
522                         field.setValue(value);
523                     }
524                     field.disable();
525                 }
526             }, this);
527         }
528     },
529
530     /**
531      * call checkState for every field
532      */
533     checkStates: function() {
534         this.onRecordUpdate();
535         this.getForm().items.each(function (item) {
536             if (Ext.isFunction(item.checkState)) {
537                 item.checkState(this, this.record);
538             }
539         }, this)
540     },
541
542     /**
543      * Get available model for given application
544      *
545      *  @param {Mixed} application
546      *  @param {Boolean} customFieldModel
547      */
548     getApplicationModels: function (application, customFieldModel) {
549         var models      = [],
550             useModel,
551             appName     = Ext.isString(application) ? application : application.get('name'),
552             app         = Tine.Tinebase.appMgr.get(appName),
553             trans       = app && app.i18n ? app.i18n : i18n,
554             appModels   = Tine[appName].Model;
555
556         if (appModels) {
557             for (var model in appModels) {
558                 if (appModels.hasOwnProperty(model) && typeof appModels[model].getMeta === 'function') {
559                     if (customFieldModel && appModels[model].getField('customfields')) {
560                         useModel = appModels[model].getMeta('appName') + '_Model_' + appModels[model].getMeta('modelName');
561
562                         Tine.log.info('Found model with customfields property: ' + useModel);
563                         models.push([useModel, trans.n_(appModels[model].getMeta('recordName'), appModels[model].getMeta('recordsName'), 1)]);
564                     } else if (! customFieldModel) {
565                         useModel = 'Tine.' + appModels[model].getMeta('appName') + '.Model.' + appModels[model].getMeta('modelName');
566
567                         Tine.log.info('Found model: ' + useModel);
568                         models.push([useModel, trans.n_(appModels[model].getMeta('recordName'), appModels[model].getMeta('recordsName'), 1)]);
569                     }
570                 }
571             }
572         }
573         return models;
574     },
575
576     /**
577      * init actions
578      */
579     initActions: function() {
580         this.action_saveAndClose = new Ext.Action({
581             requiredGrant: this.requiredSaveGrant,
582             text: (this.saveAndCloseButtonText != '') ? this.app.i18n._(this.saveAndCloseButtonText) : i18n._('Ok'),
583             minWidth: 70,
584             ref: '../btnSaveAndClose',
585             scope: this,
586             // TODO: remove the defer when all subpanels use the deferByTicket mechanism
587             handler: function() { this.onSaveAndClose.defer(500, this); },
588             iconCls: 'action_saveAndClose'
589         });
590     
591         this.action_applyChanges = new Ext.Action({
592             requiredGrant: this.requiredSaveGrant,
593             text: i18n._('Apply'),
594             minWidth: 70,
595             ref: '../btnApplyChanges',
596             scope: this,
597             handler: this.onApplyChanges,
598             iconCls: 'action_applyChanges'
599         });
600         
601         this.action_cancel = new Ext.Action({
602             text: (this.cancelButtonText != '') ? this.app.i18n._(this.cancelButtonText) : i18n._('Cancel'),
603             minWidth: 70,
604             scope: this,
605             handler: this.onCancel,
606             iconCls: 'action_cancel'
607         });
608         
609         this.action_delete = new Ext.Action({
610             requiredGrant: 'deleteGrant',
611             text: i18n._('delete'),
612             minWidth: 70,
613             scope: this,
614             handler: this.onDelete,
615             iconCls: 'action_delete',
616             disabled: true
617         });
618
619         this.action_export = Tine.widgets.exportAction.getExportButton(this.recordClass, {
620             getExportOptions: this.getExportOptions.createDelegate(this)
621         }, Tine.widgets.exportAction.SCOPE_SINGLE);
622
623         // init actions
624         this.actionUpdater = new Tine.widgets.ActionUpdater({
625             recordClass: this.recordClass,
626             evalGrants: this.evalGrants
627         });
628
629         this.actionUpdater.addActions([
630             this.action_saveAndClose,
631             this.action_applyChanges,
632             this.action_cancel,
633             this.action_delete
634         ]);
635     },
636
637     /**
638      * get export options/data
639      */
640     getExportOptions: function() {
641         this.onRecordUpdate();
642         return {
643             recordData: this.record.data
644         };
645     },
646
647     /**
648      * init buttons
649      *
650      * use button order from preference
651      */
652     initButtons: function () {
653         this.fbar = [
654             '->'
655         ];
656
657         this.fbar.push(this.action_cancel, this.action_saveAndClose);
658
659         if (this.action_export) {
660             this.actionUpdater.addAction(this.action_export);
661             this.tbarItems = this.tbarItems || [];
662             this.tbarItems.push(this.action_export);
663         }
664
665         if (this.tbarItems && this.tbarItems.length) {
666             this.actionUpdater.addActions(this.tbarItems);
667             this.tbar = new Ext.Toolbar({
668                 items: this.tbarItems
669             });
670         }
671     },
672     
673     /**
674      * init container selector
675      */
676     initContainerSelector: function() {
677         if (this.showContainerSelector) {
678             this.containerSelectCombo = new Tine.widgets.container.SelectionComboBox({
679                 id: this.app.appName + 'EditDialogContainerSelector-' + Ext.id(),
680                 fieldLabel: i18n._('Saved in'),
681                 width: 300,
682                 listWidth: 300,
683                 name: this.recordClass.getMeta('containerProperty'),
684                 recordClass: this.recordClass,
685                 containerName: this.app.i18n.n_hidden(this.recordClass.getMeta('containerName'), this.recordClass.getMeta('containersName'), 1),
686                 containersName: this.app.i18n._hidden(this.recordClass.getMeta('containersName')),
687                 appName: this.app.appName,
688                 requiredGrant: this.evalGrants ? 'addGrant' : false,
689                 disabled: this.isContainerSelectorDisabled(),
690                 listeners: {
691                     scope: this,
692                     select: function() {    
693                         // enable or disable save button dependent to containers account grants
694                         // on edit: check editGrant, on add: check addGrant
695                         var grants = this.containerSelectCombo.selectedContainer
696                             ? this.containerSelectCombo.selectedContainer.account_grants : {},
697                             grantToCheck = (this.record.data.id) ? 'editGrant' : 'addGrant',
698                             enabled =  grants.hasOwnProperty(grantToCheck) && grants[grantToCheck]
699                                     || grants.hasOwnProperty('adminGrant') && grants.adminGrant ? true : false;
700
701                         this.action_saveAndClose.setDisabled(! enabled);
702                     }
703                 }
704             });
705             this.on('render', function() { this.getForm().add(this.containerSelectCombo); }, this);
706             
707             this.fbar = [
708                 i18n._('Saved in'),
709                 this.containerSelectCombo
710             ].concat(this.fbar);
711         }
712         
713     },
714     
715     /**
716      * checks if the container selector should be disabled (dependent on account grants of the container itself)
717      * @return {}
718      */
719     isContainerSelectorDisabled: function() {
720         if (this.record) {
721             var cp = this.recordClass.getMeta('containerProperty'),
722                 container = this.record.data[cp],
723                 grants = (container && container.hasOwnProperty('account_grants')) ? container.account_grants : null,
724                 cond = false;
725                 
726             // check grants if record already exists and grants should be evaluated
727             if(this.evalGrants && this.record.data.id && grants) {
728                 cond = ! (grants.hasOwnProperty('editGrant') && grants.editGrant);
729             }
730             
731             return cond;
732         } else {
733             return false;
734         }
735     },
736     
737     /**
738      * init record to edit
739      */
740     initRecord: function() {
741         Tine.log.debug('init record with mode: ' + this.mode);
742         if (! this.record) {
743             Tine.log.debug('creating new default data record');
744             this.record = new this.recordClass(this.recordClass.getDefaultData(), 0);
745         }
746         
747         if (this.mode !== 'local') {
748             if (this.record && this.record.id) {
749                 this.loadRemoteRecord();
750             } else {
751                 this.onRecordLoad.defer(10, this);
752             }
753         } else {
754             // note: in local mode we expect a valid record
755             if (! Ext.isFunction(this.record.beginEdit)) {
756                 this.record = this.recordProxy.recordReader({responseText: this.record});
757             }
758             this.onRecordLoad.defer(10, this);
759         }
760     },
761     
762     /**
763      * load record via record proxy
764      */
765     loadRemoteRecord: function() {
766         Tine.log.info('initiating record load via proxy');
767         this.loadRequest = this.recordProxy.loadRecord(this.record, {
768             scope: this,
769             success: function(record) {
770                 this.record = record;
771                 this.onRecordLoad();
772             }
773         });
774     },
775
776     /**
777      * copy this.record record
778      */
779     doCopyRecord: function() {
780         this.record = this.doCopyRecordToReturn(this.record);
781     },
782
783     /**
784      * Copy record and returns "new record with same settings"
785      *
786      * @param record
787      */
788     doCopyRecordToReturn: function(record) {
789         var omitFields = this.recordClass.getMeta('copyOmitFields') || [];
790         // always omit id + notes + attachments
791         omitFields = omitFields.concat(['id', 'notes', 'attachments', 'relations']);
792
793         var fieldsToCopy = this.recordClass.getFieldNames().diff(omitFields),
794             recordData = Ext.copyTo({}, record.data, fieldsToCopy);
795
796         var resetProperties = {
797             alarms:    ['id', 'record_id', 'sent_time', 'sent_message'],
798             relations: ['id', 'own_id', 'created_by', 'creation_time', 'last_modified_by', 'last_modified_time']
799         };
800
801         var setProperties = {alarms: {sent_status: 'pending'}};
802
803         Ext.iterate(resetProperties, function(property, properties) {
804             if (recordData.hasOwnProperty(property)) {
805                 var r = recordData[property];
806                 for (var index = 0; index < r.length; index++) {
807                     Ext.each(properties,
808                         function(prop) {
809                             r[index][prop] = null;
810                         }
811                     );
812                 }
813             }
814         });
815
816         Ext.iterate(setProperties, function(property, properties) {
817             if (recordData.hasOwnProperty(property)) {
818                 var r = recordData[property];
819                 for (var index = 0; index < r.length; index++) {
820                     Ext.iterate(properties,
821                         function(prop, value) {
822                             r[index][prop] = value;
823                         }
824                     );
825                 }
826             }
827         });
828
829         return new this.recordClass(recordData, 0);
830     },
831
832     
833     /**
834      * executed after record got updated from proxy
835      */
836     onRecordLoad: function() {
837         // interrupt process flow until dialog is rendered
838         if (! this.rendered) {
839             this.onRecordLoad.defer(250, this);
840             return;
841         }
842         Tine.log.debug('Tine.widgets.dialog.EditDialog::onRecordLoad() - Loading of the following record completed:');
843         Tine.log.debug(this.record);
844         
845         if (this.copyRecord) {
846             this.doCopyRecord();
847             this.window.setTitle(String.format(i18n._('Copy {0}'), this.i18nRecordName));
848         } else {
849             if (! this.record.id) {
850                 this.window.setTitle(String.format(i18n._('Add New {0}'), this.i18nRecordName));
851             } else {
852                 this.window.setTitle(String.format(i18n._('Edit {0} "{1}"'), this.i18nRecordName, this.record.getTitle()));
853             }
854         }
855         
856         var ticketFn = this.onAfterRecordLoad.deferByTickets(this),
857             wrapTicket = ticketFn();
858         
859         this.fireEvent('load', this, this.record, ticketFn);
860         wrapTicket();
861     },
862     
863     // finally load the record into the form
864     onAfterRecordLoad: function() {
865         var _ = window.lodash,
866             form = this.getForm();
867         
868         if (form) {
869             form.loadRecord(this.record);
870             form.clearInvalid();
871         }
872         
873         if (this.record && this.record.hasOwnProperty('data') && Ext.isObject(this.record.data[this.recordClass.getMeta('containerProperty')])) {
874             this.updateToolbars(this.record, this.recordClass.getMeta('containerProperty'));
875         }
876         
877         // add current timestamp as id, if this is a dependent record 
878         if (this.modelConfig && this.modelConfig.isDependent == true && this.record.id == 0) {
879             this.record.set('id', (new Date()).getTime());
880         }
881
882         // apply grants to fields with requiredGrant prop
883         if (this.evalGrants) {
884             this.getForm().items.each(function (f) {
885                 if (f.isFormField && f.requiredGrant !== undefined) {
886                     var hasRequiredGrant = _.get(this.record, this.recordClass.getMeta('grantsPath') + '.' + f.requiredGrant);
887                     f.setDisabled(!hasRequiredGrant);
888                 }
889             }, this);
890         }
891
892         this.checkStates.defer(100, this);
893
894         if (this.loadMask) {
895             this.loadMask.hide();
896         }
897     },
898     
899     /**
900      * executed when record gets updated from form
901      */
902     onRecordUpdate: function(callback, scope) {
903         var form = this.getForm();
904
905         // merge changes from form into record
906         form.updateRecord(this.record);
907
908         //TODO Use Promises instead of Tickets if async is needed
909         this.fireEvent('recordUpdate', this, this.record);
910     },
911     
912     /**
913      * @private
914      */
915     onRender : function(ct, position){
916         Tine.widgets.dialog.EditDialog.superclass.onRender.call(this, ct, position);
917         
918         // generalized keybord map for edit dlgs
919         new Ext.KeyMap(this.el, [
920             {
921                 key: [10,13], // ctrl + return
922                 ctrl: true,
923                 scope: this,
924                 fn: function() {
925                     if (this.getForm().hasOwnProperty('items')) {
926                         // force set last selected field
927                         this.getForm().items.each(function(item) {
928                             if (item.hasFocus) {
929                                 item.setValue(item.getRawValue());
930                             }
931                         }, this);
932                     }
933                     this.action_saveAndClose.execute();
934                 }
935             }
936         ]);
937         
938         if (this.loadMask !== false && this.i18nRecordName) {
939             this.loadMask = new Ext.LoadMask(ct, {msg: String.format(i18n._('Transferring {0}...'), this.i18nRecordName)});
940             this.loadMask.show();
941         }
942
943         // init change event
944         var form = this.getForm().items.each(function(item) {
945             this.relayEvents(item, ['change', 'select']);
946         }, this);
947         this.on('change', this.checkStates, this, {buffer: 100});
948         this.on('select', this.checkStates, this, {buffer: 100});
949     },
950     
951     /**
952      * update (action updateer) top and bottom toolbars
953      */
954     updateToolbars: function(record, containerField) {
955         if (! this.evalGrants) {
956             return;
957         }
958         
959         var actions = [
960             this.action_saveAndClose,
961             this.action_applyChanges,
962             this.action_delete,
963             this.action_cancel
964         ];
965         this.actionUpdater.updateActions(record);
966     },
967
968     /**
969      * get top toolbar
970      */
971     getToolbar: function() {
972         return this.getTopToolbar();
973     },
974     
975     /**
976      * is form valid?
977      * 
978      * @return {Boolean}
979      */
980     isValid: function() {
981         var me = this;
982         return new Promise(function (fulfill, reject) {
983             if (me.getForm().isValid()) {
984                 fulfill(true);
985             } else {
986                 reject(me.getValidationErrorMessage())
987             }
988         });
989     },
990
991     /**
992      * vaidates on multiple edit
993      * 
994      * @return {Boolean}
995      */
996     isMultipleValid: function() {
997         return true;
998     },
999     
1000     /**
1001      * @private
1002      */
1003     onCancel : function(){
1004         this.fireEvent('cancel');
1005         this.purgeListeners();
1006         this.window.close();
1007     },
1008     
1009     /**
1010      * @private
1011      */
1012     onSaveAndClose: function() {
1013         this.fireEvent('saveAndClose');
1014         this.onApplyChanges(true);
1015     },
1016     
1017     /**
1018      * generic apply changes handler
1019      * @param {Boolean} closeWindow
1020      */
1021     onApplyChanges: function(closeWindow) {
1022         if (this.saving) {
1023             return;
1024         }
1025         this.saving = true;
1026
1027         this.loadMask.show();
1028
1029         var ticketFn = this.doApplyChanges.deferByTickets(this, [closeWindow]),
1030             wrapTicket = ticketFn();
1031
1032         this.fireEvent('save', this, this.record, ticketFn);
1033         wrapTicket();
1034     },
1035     
1036     /**
1037      * is called from onApplyChanges
1038      * @param {Boolean} closeWindow
1039      */
1040     doApplyChanges: function(closeWindow) {
1041         // we need to sync record before validating to let (sub) panels have 
1042         // current data of other panels
1043         this.onRecordUpdate();
1044
1045         // quit copy mode
1046         this.copyRecord = false;
1047
1048         var isValid = this.isValid(),
1049             vBool = !! isValid,
1050             me = this;
1051
1052         if (Ext.isDefined(isValid) && ! Ext.isFunction(isValid.then)) {
1053             // convert legacy isValid into promise
1054             isValid = new Promise(function (fulfill, reject) {;
1055                 return vBool ? fulfill(true) : reject(me.getValidationErrorMessage());
1056             });
1057         }
1058
1059         isValid.then(function () {
1060             if (me.mode !== 'local') {
1061                 me.recordProxy.saveRecord(me.record, {
1062                     scope: me,
1063                     success: function (record) {
1064                         // override record with returned data
1065                         me.record = record;
1066                         if (!Ext.isFunction(me.window.cascade)) {
1067                             // update form with this new data
1068                             // NOTE: We update the form also when window should be closed,
1069                             //       cause sometimes security restrictions might prevent
1070                             //       closing of native windows
1071                             me.onRecordLoad();
1072                         }
1073                         var ticketFn = me.onAfterApplyChanges.deferByTickets(me, [closeWindow]),
1074                             wrapTicket = ticketFn();
1075
1076                         me.fireEvent('update', Ext.util.JSON.encode(me.record.data), me.mode, me, ticketFn);
1077                         wrapTicket();
1078                     },
1079                     failure: me.onRequestFailed,
1080                     timeout: 300000 // 5 minutes
1081                 }, me.getAdditionalSaveParams(me));
1082             } else {
1083                 me.onRecordLoad();
1084                 var ticketFn = me.onAfterApplyChanges.deferByTickets(me, [closeWindow]),
1085                     wrapTicket = ticketFn();
1086
1087                 me.fireEvent('update', Ext.util.JSON.encode(me.record.data), me.mode, me, ticketFn);
1088                 wrapTicket();
1089             }
1090         }, function (message) {
1091             me.saving = false;
1092             me.loadMask.hide();
1093             Ext.MessageBox.alert(i18n._('Errors'), message);
1094         });
1095     },
1096
1097     /**
1098      * returns additional save params
1099      *
1100      * @param {EditDialog} me
1101      * @returns {{duplicateCheck: boolean}}
1102      */
1103     getAdditionalSaveParams: function(me) {
1104         return {
1105             duplicateCheck: me.doDuplicateCheck
1106         };
1107     },
1108     
1109     onAfterApplyChanges: function(closeWindow) {
1110         this.window.rename(this.windowNamePrefix + this.record.id);
1111         this.loadMask.hide();
1112         this.saving = false;
1113         
1114         if (closeWindow) {
1115             this.window.fireEvent('saveAndClose');
1116             this.purgeListeners();
1117             this.window.close();
1118         }
1119     },
1120     
1121     /**
1122      * get validation error message
1123      * 
1124      * @return {String}
1125      */
1126     getValidationErrorMessage: function() {
1127         return i18n._('Please fix the errors noted.');
1128     },
1129     
1130     /**
1131      * generic delete handler
1132      */
1133     onDelete: function(btn, e) {
1134         Ext.MessageBox.confirm(i18n._('Confirm'), String.format(i18n._('Do you really want to delete this {0}?'), this.i18nRecordName), function(_button) {
1135             if(btn == 'yes') {
1136                 var deleteMask = new Ext.LoadMask(this.getEl(), {msg: String.format(i18n._('Deleting {0}'), this.i18nRecordName)});
1137                 deleteMask.show();
1138                 
1139                 this.recordProxy.deleteRecords(this.record, {
1140                     scope: this,
1141                     success: function() {
1142                         this.purgeListeners();
1143                         this.window.close();
1144                     },
1145                     failure: function () {
1146                         Ext.MessageBox.alert(i18n._('Failed'), String.format(i18n._('Could not delete {0}.'), this.i18nRecordName));
1147                         Ext.MessageBox.hide();
1148                     }
1149                 });
1150             }
1151         });
1152     },
1153     
1154     /**
1155      * duplicate(s) found exception handler
1156      * 
1157      * @param {Object} exception
1158      */
1159     onDuplicateException: function(exception) {
1160         var resolveGridPanel = new Tine.widgets.dialog.DuplicateResolveGridPanel({
1161             app: this.app,
1162             store: new Tine.widgets.dialog.DuplicateResolveStore({
1163                 app: this.app,
1164                 recordClass: this.recordClass,
1165                 recordProxy: this.recordProxy,
1166                 data: {
1167                     clientRecord: exception.clientRecord,
1168                     duplicates: exception.duplicates
1169                 }
1170             }),
1171             fbar: [
1172                 '->',
1173                 this.action_cancel,
1174                 this.action_saveAndClose
1175             ]
1176         });
1177         
1178         // intercept save handler
1179         resolveGridPanel.btnSaveAndClose.setHandler(function(btn, e) {
1180             var resolveStrategy = resolveGridPanel.store.resolveStrategy;
1181             
1182             // action discard -> close window
1183             if (resolveStrategy == 'discard') {
1184                 return this.onCancel();
1185             }
1186             
1187             this.record = resolveGridPanel.store.getResolvedRecord();
1188             
1189             // quit copy mode before populating form with resolved data
1190             this.copyRecord = false;
1191             this.onRecordLoad();
1192             
1193             mainCardPanel.layout.setActiveItem(this.id);
1194             resolveGridPanel.doLayout();
1195             
1196             this.doDuplicateCheck = false;
1197             this.onSaveAndClose();
1198         }, this);
1199         
1200         // place in viewport
1201         this.window.setTitle(String.format(i18n._('Resolve Duplicate {0} Suspicion'), this.i18nRecordName));
1202         var mainCardPanel = this.findParentBy(function(p) {return p.isWindowMainCardPanel });
1203         mainCardPanel.add(resolveGridPanel);
1204         mainCardPanel.layout.setActiveItem(resolveGridPanel.id);
1205         resolveGridPanel.doLayout();
1206     },
1207     
1208     /**
1209      * generic request exception handler
1210      * 
1211      * @param {Object} exception
1212      */
1213     onRequestFailed: function(exception) {
1214         this.saving = false;
1215
1216         if (this.exceptionHandlingMap && this.exceptionHandlingMap[exception.code] && typeof this.exceptionHandlingMap[exception.code] === 'function') {
1217             this.exceptionHandlingMap[exception.code](exception);
1218
1219         } else if (exception.code == 629) {
1220             this.onDuplicateException.apply(this, arguments);
1221
1222         } else {
1223             Tine.Tinebase.ExceptionHandler.handleRequestException(exception);
1224         }
1225
1226         this.loadMask.hide();
1227     },
1228     
1229     /**
1230      * creates the relations panel, if relations are defined
1231      */
1232     initRelationsPanel: function() {
1233         if (! this.hideRelationsPanel && this.recordClass && this.recordClass.hasField('relations')) {
1234             // init relations panel before onRecordLoad
1235             if (! this.relationsPanel) {
1236                 this.relationsPanel = new Tine.widgets.relation.GenericPickerGridPanel({ anchor: '100% 100%', editDialog: this });
1237             }
1238             // interrupt process flow until dialog is rendered
1239             if (! this.rendered) {
1240                 this.initRelationsPanel.defer(250, this);
1241                 return;
1242             }
1243             // add relations panel if this is rendered
1244             if (this.items.items[0]) {
1245                 this.items.items[0].add(this.relationsPanel);
1246             }
1247             
1248             Tine.log.debug('Tine.widgets.dialog.EditDialog::initRelationsPanel() - Initialized relations panel and added to dialog tab items.');
1249         }
1250     },
1251
1252     /**
1253      * create notes panel
1254      */
1255     initNotesPanel: function() {
1256         // This dialog is pretty generic but for some cases it's used in a differend way
1257         if(this.displayNotes == true) {
1258             this.items.items.push(new Tine.widgets.activities.ActivitiesGridPanel({
1259                 anchor: '100% 100%',
1260                 editDialog: this
1261             }));
1262         }
1263     },
1264
1265     /**
1266      * creates attachments panel
1267      */
1268     initAttachmentsPanel: function() {
1269         if (! this.attachmentsPanel && ! this.hideAttachmentsPanel && this.recordClass && this.recordClass.hasField('attachments') && Tine.Tinebase.registry.get('filesystemAvailable')) {
1270             this.attachmentsPanel = new Tine.widgets.dialog.AttachmentsGridPanel({ anchor: '100% 100%', editDialog: this }); 
1271             this.items.items.push(this.attachmentsPanel);
1272         }
1273     }
1274 });