refactor mode management
[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         // auto record proxy
330         if (! this.recordProxy && this.recordClass) {
331             Tine.log.debug('no record proxy given, creating a new one...');
332             this.recordProxy = new Tine.Tinebase.data.RecordProxy({
333                 recordClass: this.recordClass
334             });
335         }
336
337         // auto eval grants
338         if (this.recordClass) {
339             var grantsField = this.recordClass.getMeta('grantsPath')
340                 .replace(/^data\./, '')
341                 .replace(/\..+/g, '');
342
343             this.evalGrants = this.evalGrants && (grantsField == 'data' || this.recordClass.hasField(grantsField));
344         }
345
346         // init plugins
347         this.plugins = Ext.isString(this.plugins) ? Ext.decode(this.plugins) : Ext.isArray(this.plugins) ? this.plugins.concat(Ext.decode(this.initialConfig.plugins)) : [];
348         
349         this.plugins.push(this.tokenModePlugin = new Tine.widgets.dialog.TokenModeEditDialogPlugin({}));
350         // added possibility to disable using customfield plugin
351         if (this.disableCfs !== true) {
352             this.plugins.push(new Tine.widgets.customfields.EditDialogPlugin({}));
353         }
354         
355         // init actions
356         this.initActions();
357         // init buttons and tbar
358         this.initButtons();
359         // init container selector
360         this.initContainerSelector();
361         // init record 
362         this.initRecord();
363         // get items for this dialog
364         this.items = this.getFormItems();
365
366         // init relations panel if relations are defined
367         this.initRelationsPanel();
368         // init attachments panel
369         this.initAttachmentsPanel();
370         // init notes panel
371         this.initNotesPanel();
372
373         Tine.widgets.dialog.EditDialog.superclass.initComponent.call(this);
374
375         // set fields readOnly if set
376         this.fixFields();
377         
378         // firefox fix: blur each item before tab changes, so no field  will be focused afterwards
379         if (Ext.isGecko) {
380             this.items.items[0].addListener('beforetabchange', function(tabpanel, newtab, oldtab) {
381                 if (! oldtab) {
382                     return;
383                 }
384                 var form = this.getForm();
385                 
386                 if (form && form.hasOwnProperty('items'))
387                     form.items.each(function(item, index) {
388                         item.blur();
389                     });
390             }, this);
391         }
392
393         if (Ext.isFunction(this.window.relayEvents) && Tine.Tinebase.featureEnabled('featureRememberPopupSize')) {
394             this.window.relayEvents(this, ['resize']);
395         }
396     },
397
398     /**
399      * returns canonical path part
400      * @returns {string}
401      */
402     getCanonicalPathSegment: function () {
403         if (this.recordClass) {
404             return ['',
405                 this.recordClass.getMeta('appName'),
406                 this.canonicalName,
407                 this.recordClass.getMeta('modelName'),
408             ].join(Tine.Tinebase.CanonicalPath.separator);
409         }
410     },
411
412     /**
413      * generic form layout
414      */
415     getFormItems: function() {
416         return {
417             xtype: 'tabpanel',
418             border: false,
419             plain:true,
420             activeTab: 0,
421             border: false,
422             defaults: {
423                 hideMode: 'offsets'
424             },
425             plugins: [{
426                 ptype : 'ux.tabpanelkeyplugin'
427             }],
428             items:[
429                 {
430                     title: this.i18nRecordName,
431                     autoScroll: true,
432                     border: false,
433                     frame: true,
434                     layout: 'border',
435                     defaults: { autoScroll: true },
436                     items: [Ext.applyIf(this.getRecordFormItems(), {
437                         region: 'center',
438                         xtype: 'columnform',
439                         labelAlign: 'top',
440                         formDefaults: {
441                             xtype:'textfield',
442                             anchor: '100%',
443                             labelSeparator: '',
444                             columnWidth: 1/2
445                         },
446                     })].concat(this.getEastPanel())
447                 }, new Tine.widgets.activities.ActivitiesTabPanel({
448                     app: this.appName,
449                     record_id: this.record.id,
450                     record_model: this.modelName
451                 })
452             ]
453         };
454     },
455
456     getEastPanel: function() {
457         var items = [];
458         if (this.recordClass.hasField('description')) {
459             items.push(new Ext.Panel({
460                 title: i18n._('Description'),
461                 iconCls: 'descriptionIcon',
462                 layout: 'form',
463                 labelAlign: 'top',
464                 border: false,
465                 items: [{
466                     style: 'margin-top: -4px; border 0px;',
467                     labelSeparator: '',
468                     xtype: 'textarea',
469                     name: 'description',
470                     hideLabel: true,
471                     grow: false,
472                     preventScrollbars: false,
473                     anchor: '100% 100%',
474                     emptyText: i18n._('Enter description'),
475                     requiredGrant: 'editGrant'
476                 }]
477             }));
478         }
479
480         if (this.recordClass.hasField('tags')) {
481             items.push(new Tine.widgets.tags.TagPanel({
482                 app: this.appName,
483                 border: false,
484                 bodyStyle: 'border:1px solid #B5B8C8;'
485             }));
486         }
487
488         return items.length ? {
489             layout: 'accordion',
490             animate: true,
491             region: 'east',
492             width: 210,
493             split: true,
494             collapsible: true,
495             collapseMode: 'mini',
496             header: false,
497             margins: '0 5 0 5',
498             border: true,
499             items: items
500         } : [];
501     },
502
503     getRecordFormItems: function() {
504         return new Tine.widgets.form.RecordForm({
505             recordClass: this.recordClass
506         });
507     },
508
509     /**
510      * fix fields (used for preselecting form fields when called in dependency to another record)
511      * @return {Boolean}
512      */
513     fixFields: function() {
514         if (this.fixedFields && this.fixedFields.getCount() > 0) {
515             if (! this.rendered) {
516                 this.fixFields.defer(100, this);
517                 return false;
518             }
519             
520             this.fixedFields.each(function(value, index) {
521                 var key = this.fixedFields.keys[index]; 
522                 
523                 var field = this.getForm().findField(key);
524                 
525                 if (field) {
526                     if (Ext.isFunction(this.recordClass.getField(key).type)) {
527                         var foreignRecordClass = this.recordClass.getField(key).type;
528                         var record = new foreignRecordClass(value);
529                         field.selectedRecord = record;
530                         field.setValue(value);
531                         field.fireEvent('select');
532                     } else {
533                         field.setValue(value);
534                     }
535                     field.disable();
536                 }
537             }, this);
538         }
539     },
540
541     /**
542      * call checkState for every field
543      */
544     checkStates: function() {
545         this.onRecordUpdate();
546         this.getForm().items.each(function (item) {
547             if (Ext.isFunction(item.checkState)) {
548                 item.checkState(this, this.record);
549             }
550         }, this)
551     },
552
553     /**
554      * Get available model for given application
555      *
556      *  @param {Mixed} application
557      *  @param {Boolean} customFieldModel
558      */
559     getApplicationModels: function (application, customFieldModel) {
560         var models      = [],
561             useModel,
562             appName     = Ext.isString(application) ? application : application.get('name'),
563             app         = Tine.Tinebase.appMgr.get(appName),
564             trans       = app && app.i18n ? app.i18n : i18n,
565             appModels   = Tine[appName].Model;
566
567         if (appModels) {
568             for (var model in appModels) {
569                 if (appModels.hasOwnProperty(model) && typeof appModels[model].getMeta === 'function') {
570                     if (customFieldModel && appModels[model].getField('customfields')) {
571                         useModel = appModels[model].getMeta('appName') + '_Model_' + appModels[model].getMeta('modelName');
572
573                         Tine.log.info('Found model with customfields property: ' + useModel);
574                         models.push([useModel, trans.n_(appModels[model].getMeta('recordName'), appModels[model].getMeta('recordsName'), 1)]);
575                     } else if (! customFieldModel) {
576                         useModel = 'Tine.' + appModels[model].getMeta('appName') + '.Model.' + appModels[model].getMeta('modelName');
577
578                         Tine.log.info('Found model: ' + useModel);
579                         models.push([useModel, trans.n_(appModels[model].getMeta('recordName'), appModels[model].getMeta('recordsName'), 1)]);
580                     }
581                 }
582             }
583         }
584         return models;
585     },
586
587     /**
588      * init actions
589      */
590     initActions: function() {
591         this.action_saveAndClose = new Ext.Action({
592             requiredGrant: this.requiredSaveGrant,
593             text: (this.saveAndCloseButtonText != '') ? this.app.i18n._(this.saveAndCloseButtonText) : i18n._('Ok'),
594             minWidth: 70,
595             ref: '../btnSaveAndClose',
596             scope: this,
597             // TODO: remove the defer when all subpanels use the deferByTicket mechanism
598             handler: function() { this.onSaveAndClose.defer(500, this); },
599             iconCls: 'action_saveAndClose'
600         });
601     
602         this.action_applyChanges = new Ext.Action({
603             requiredGrant: this.requiredSaveGrant,
604             text: i18n._('Apply'),
605             minWidth: 70,
606             ref: '../btnApplyChanges',
607             scope: this,
608             handler: this.onApplyChanges,
609             iconCls: 'action_applyChanges'
610         });
611         
612         this.action_cancel = new Ext.Action({
613             text: (this.cancelButtonText != '') ? this.app.i18n._(this.cancelButtonText) : i18n._('Cancel'),
614             minWidth: 70,
615             scope: this,
616             handler: this.onCancel,
617             iconCls: 'action_cancel'
618         });
619         
620         this.action_delete = new Ext.Action({
621             requiredGrant: 'deleteGrant',
622             text: i18n._('delete'),
623             minWidth: 70,
624             scope: this,
625             handler: this.onDelete,
626             iconCls: 'action_delete',
627             disabled: true
628         });
629
630         this.action_export = Tine.widgets.exportAction.getExportButton(this.recordClass, {
631             getExportOptions: this.getExportOptions.createDelegate(this)
632         }, Tine.widgets.exportAction.SCOPE_SINGLE);
633
634         // init actions
635         this.actionUpdater = new Tine.widgets.ActionUpdater({
636             recordClass: this.recordClass,
637             evalGrants: this.evalGrants
638         });
639
640         this.actionUpdater.addActions([
641             this.action_saveAndClose,
642             this.action_applyChanges,
643             this.action_cancel,
644             this.action_delete
645         ]);
646     },
647
648     /**
649      * get export options/data
650      */
651     getExportOptions: function() {
652         this.onRecordUpdate();
653         return {
654             recordData: this.record.data
655         };
656     },
657
658     /**
659      * init buttons
660      *
661      * use button order from preference
662      */
663     initButtons: function () {
664         this.fbar = [
665             '->'
666         ];
667
668         this.fbar.push(this.action_cancel, this.action_saveAndClose);
669
670         if (this.action_export) {
671             this.actionUpdater.addAction(this.action_export);
672             this.tbarItems = this.tbarItems || [];
673             this.tbarItems.push(this.action_export);
674         }
675
676         if (this.tbarItems && this.tbarItems.length) {
677             this.actionUpdater.addActions(this.tbarItems);
678             this.tbar = new Ext.Toolbar({
679                 items: this.tbarItems
680             });
681         }
682     },
683     
684     /**
685      * init container selector
686      */
687     initContainerSelector: function() {
688         if (this.showContainerSelector) {
689             this.containerSelectCombo = new Tine.widgets.container.SelectionComboBox({
690                 id: this.app.appName + 'EditDialogContainerSelector-' + Ext.id(),
691                 fieldLabel: i18n._('Saved in'),
692                 width: 300,
693                 listWidth: 300,
694                 name: this.recordClass.getMeta('containerProperty'),
695                 recordClass: this.recordClass,
696                 containerName: this.app.i18n.n_hidden(this.recordClass.getMeta('containerName'), this.recordClass.getMeta('containersName'), 1),
697                 containersName: this.app.i18n._hidden(this.recordClass.getMeta('containersName')),
698                 appName: this.app.appName,
699                 requiredGrant: this.evalGrants ? 'addGrant' : false,
700                 disabled: this.isContainerSelectorDisabled(),
701                 listeners: {
702                     scope: this,
703                     select: function() {    
704                         // enable or disable save button dependent to containers account grants
705                         // on edit: check editGrant, on add: check addGrant
706                         var grants = this.containerSelectCombo.selectedContainer
707                             ? this.containerSelectCombo.selectedContainer.account_grants : {},
708                             grantToCheck = (this.record.data.id) ? 'editGrant' : 'addGrant',
709                             enabled =  grants.hasOwnProperty(grantToCheck) && grants[grantToCheck]
710                                     || grants.hasOwnProperty('adminGrant') && grants.adminGrant ? true : false;
711
712                         this.action_saveAndClose.setDisabled(! enabled);
713                     }
714                 }
715             });
716             this.on('render', function() { this.getForm().add(this.containerSelectCombo); }, this);
717             
718             this.fbar = [
719                 i18n._('Saved in'),
720                 this.containerSelectCombo
721             ].concat(this.fbar);
722         }
723         
724     },
725     
726     /**
727      * checks if the container selector should be disabled (dependent on account grants of the container itself)
728      * @return {}
729      */
730     isContainerSelectorDisabled: function() {
731         if (this.record) {
732             var cp = this.recordClass.getMeta('containerProperty'),
733                 container = this.record.data[cp],
734                 grants = (container && container.hasOwnProperty('account_grants')) ? container.account_grants : null,
735                 cond = false;
736                 
737             // check grants if record already exists and grants should be evaluated
738             if(this.evalGrants && this.record.data.id && grants) {
739                 cond = ! (grants.hasOwnProperty('editGrant') && grants.editGrant);
740             }
741             
742             return cond;
743         } else {
744             return false;
745         }
746     },
747     
748     /**
749      * init record to edit
750      */
751     initRecord: function() {
752         Tine.log.debug('init record with mode: ' + this.mode);
753         if (! this.record) {
754             Tine.log.debug('creating new default data record');
755             this.record = new this.recordClass(this.recordClass.getDefaultData(), 0);
756         }
757
758         if (typeof this.record === 'string') {
759             if (! Ext.isFunction(this.record.beginEdit)) {
760                 this.record = this.recordProxy.recordReader({responseText: this.record});
761             }
762             this.onRecordLoad.defer(10, this);
763         } else {
764             if (this.record && this.record.id) {
765                 this.loadRemoteRecord();
766             } else {
767                 this.onRecordLoad.defer(10, this);
768             }
769         }
770     },
771     
772     /**
773      * load record via record proxy
774      */
775     loadRemoteRecord: function() {
776         Tine.log.info('initiating record load via proxy');
777         this.loadRequest = this.recordProxy.loadRecord(this.record, {
778             scope: this,
779             success: function(record) {
780                 this.record = record;
781                 this.onRecordLoad();
782             }
783         });
784     },
785
786     /**
787      * copy this.record record
788      */
789     doCopyRecord: function() {
790         this.record = this.doCopyRecordToReturn(this.record);
791     },
792
793     /**
794      * Copy record and returns "new record with same settings"
795      *
796      * @param record
797      */
798     doCopyRecordToReturn: function(record) {
799         var omitFields = this.recordClass.getMeta('copyOmitFields') || [];
800         // always omit id + notes + attachments
801         omitFields = omitFields.concat(['id', 'notes', 'attachments', 'relations']);
802
803         var fieldsToCopy = this.recordClass.getFieldNames().diff(omitFields),
804             recordData = Ext.copyTo({}, record.data, fieldsToCopy);
805
806         var resetProperties = {
807             alarms:    ['id', 'record_id', 'sent_time', 'sent_message'],
808             relations: ['id', 'own_id', 'created_by', 'creation_time', 'last_modified_by', 'last_modified_time']
809         };
810
811         var setProperties = {alarms: {sent_status: 'pending'}};
812
813         Ext.iterate(resetProperties, function(property, properties) {
814             if (recordData.hasOwnProperty(property)) {
815                 var r = recordData[property];
816                 for (var index = 0; index < r.length; index++) {
817                     Ext.each(properties,
818                         function(prop) {
819                             r[index][prop] = null;
820                         }
821                     );
822                 }
823             }
824         });
825
826         Ext.iterate(setProperties, function(property, properties) {
827             if (recordData.hasOwnProperty(property)) {
828                 var r = recordData[property];
829                 for (var index = 0; index < r.length; index++) {
830                     Ext.iterate(properties,
831                         function(prop, value) {
832                             r[index][prop] = value;
833                         }
834                     );
835                 }
836             }
837         });
838
839         return new this.recordClass(recordData, 0);
840     },
841
842     
843     /**
844      * executed after record got updated from proxy
845      */
846     onRecordLoad: function() {
847         // interrupt process flow until dialog is rendered
848         if (! this.rendered) {
849             this.onRecordLoad.defer(250, this);
850             return;
851         }
852         Tine.log.debug('Tine.widgets.dialog.EditDialog::onRecordLoad() - Loading of the following record completed:');
853         Tine.log.debug(this.record);
854         
855         if (this.copyRecord) {
856             this.doCopyRecord();
857             this.window.setTitle(String.format(i18n._('Copy {0}'), this.i18nRecordName));
858         } else {
859             if (! this.record.id) {
860                 this.window.setTitle(String.format(i18n._('Add New {0}'), this.i18nRecordName));
861             } else {
862                 this.window.setTitle(String.format(i18n._('Edit {0} "{1}"'), this.i18nRecordName, this.record.getTitle()));
863             }
864         }
865         
866         var ticketFn = this.onAfterRecordLoad.deferByTickets(this),
867             wrapTicket = ticketFn();
868         
869         this.fireEvent('load', this, this.record, ticketFn);
870         wrapTicket();
871     },
872     
873     // finally load the record into the form
874     onAfterRecordLoad: function() {
875         var _ = window.lodash,
876             form = this.getForm();
877         
878         if (form) {
879             form.loadRecord(this.record);
880             form.clearInvalid();
881         }
882         
883         if (this.record && this.record.hasOwnProperty('data') && Ext.isObject(this.record.data[this.recordClass.getMeta('containerProperty')])) {
884             this.updateToolbars(this.record, this.recordClass.getMeta('containerProperty'));
885         }
886         
887         // add current timestamp as id, if this is a dependent record 
888         if (this.modelConfig && this.modelConfig.isDependent == true && this.record.id == 0) {
889             this.record.set('id', (new Date()).getTime());
890         }
891
892         // apply grants to fields with requiredGrant prop
893         if (this.evalGrants) {
894             this.getForm().items.each(function (f) {
895                 if (f.isFormField && f.requiredGrant !== undefined) {
896                     var hasRequiredGrant = _.get(this.record, this.recordClass.getMeta('grantsPath') + '.' + f.requiredGrant);
897                     f.setDisabled(!hasRequiredGrant);
898                 }
899             }, this);
900         }
901
902         this.checkStates.defer(100, this);
903
904         if (this.loadMask && !this.saving) {
905             this.loadMask.hide();
906         }
907     },
908     
909     /**
910      * executed when record gets updated from form
911      */
912     onRecordUpdate: function(callback, scope) {
913         var form = this.getForm();
914
915         // merge changes from form into record
916         form.updateRecord(this.record);
917
918         //TODO Use Promises instead of Tickets if async is needed
919         this.fireEvent('recordUpdate', this, this.record);
920     },
921     
922     /**
923      * @private
924      */
925     onRender : function(ct, position){
926         Tine.widgets.dialog.EditDialog.superclass.onRender.call(this, ct, position);
927         
928         // generalized keybord map for edit dlgs
929         new Ext.KeyMap(this.el, [
930             {
931                 key: [10,13], // ctrl + return
932                 ctrl: true,
933                 scope: this,
934                 fn: function() {
935                     if (this.getForm().hasOwnProperty('items')) {
936                         // force set last selected field
937                         this.getForm().items.each(function(item) {
938                             if (item.hasFocus) {
939                                 item.setValue(item.getRawValue());
940                             }
941                         }, this);
942                     }
943                     this.action_saveAndClose.execute();
944                 }
945             }
946         ]);
947         
948         if (this.loadMask !== false && this.i18nRecordName) {
949             this.loadMask = new Ext.LoadMask(ct, {msg: String.format(i18n._('Transferring {0}...'), this.i18nRecordName)});
950             this.loadMask.show();
951         }
952
953         // init change event
954         var form = this.getForm().items.each(function(item) {
955             this.relayEvents(item, ['change', 'select']);
956         }, this);
957         this.on('change', this.checkStates, this, {buffer: 100});
958         this.on('select', this.checkStates, this, {buffer: 100});
959     },
960     
961     /**
962      * update (action updateer) top and bottom toolbars
963      */
964     updateToolbars: function(record, containerField) {
965         if (! this.evalGrants) {
966             return;
967         }
968         
969         var actions = [
970             this.action_saveAndClose,
971             this.action_applyChanges,
972             this.action_delete,
973             this.action_cancel
974         ];
975         this.actionUpdater.updateActions(record);
976     },
977
978     /**
979      * get top toolbar
980      */
981     getToolbar: function() {
982         return this.getTopToolbar();
983     },
984     
985     /**
986      * is form valid?
987      * 
988      * @return {Boolean}
989      */
990     isValid: function() {
991         var me = this;
992         return new Promise(function (fulfill, reject) {
993             if (me.getForm().isValid()) {
994                 fulfill(true);
995             } else {
996                 reject(me.getValidationErrorMessage())
997             }
998         });
999     },
1000
1001     /**
1002      * vaidates on multiple edit
1003      * 
1004      * @return {Boolean}
1005      */
1006     isMultipleValid: function() {
1007         return true;
1008     },
1009     
1010     /**
1011      * @private
1012      */
1013     onCancel : function(){
1014         this.fireEvent('cancel');
1015         this.purgeListeners();
1016         this.window.close();
1017     },
1018     
1019     /**
1020      * @private
1021      */
1022     onSaveAndClose: function() {
1023         this.fireEvent('saveAndClose');
1024         this.onApplyChanges(true);
1025     },
1026     
1027     /**
1028      * generic apply changes handler
1029      * @param {Boolean} closeWindow
1030      */
1031     onApplyChanges: function(closeWindow) {
1032         if (this.saving) {
1033             return;
1034         }
1035         this.saving = true;
1036
1037         this.loadMask.show();
1038
1039         var ticketFn = this.doApplyChanges.deferByTickets(this, [closeWindow]),
1040             wrapTicket = ticketFn();
1041
1042         this.fireEvent('save', this, this.record, ticketFn);
1043         wrapTicket();
1044     },
1045     
1046     /**
1047      * is called from onApplyChanges
1048      * @param {Boolean} closeWindow
1049      */
1050     doApplyChanges: function(closeWindow) {
1051         // we need to sync record before validating to let (sub) panels have 
1052         // current data of other panels
1053         this.onRecordUpdate();
1054
1055         // quit copy mode
1056         this.copyRecord = false;
1057
1058         var isValid = this.isValid(),
1059             vBool = !! isValid,
1060             me = this;
1061
1062         if (Ext.isDefined(isValid) && ! Ext.isFunction(isValid.then)) {
1063             // convert legacy isValid into promise
1064             isValid = new Promise(function (fulfill, reject) {;
1065                 return vBool ? fulfill(true) : reject(me.getValidationErrorMessage());
1066             });
1067         }
1068
1069         isValid.then(function () {
1070             if (me.mode !== 'local') {
1071                 me.recordProxy.saveRecord(me.record, {
1072                     scope: me,
1073                     success: function (record) {
1074                         // override record with returned data
1075                         me.record = record;
1076                         if (!Ext.isFunction(me.window.cascade)) {
1077                             // update form with this new data
1078                             // NOTE: We update the form also when window should be closed,
1079                             //       cause sometimes security restrictions might prevent
1080                             //       closing of native windows
1081                             me.onRecordLoad();
1082                         }
1083                         var ticketFn = me.onAfterApplyChanges.deferByTickets(me, [closeWindow]),
1084                             wrapTicket = ticketFn();
1085
1086                         me.fireEvent('update', Ext.util.JSON.encode(me.record.data), me.mode, me, ticketFn);
1087                         wrapTicket();
1088                     },
1089                     failure: me.onRequestFailed,
1090                     timeout: 300000 // 5 minutes
1091                 }, me.getAdditionalSaveParams(me));
1092             } else {
1093                 me.onRecordLoad();
1094                 var ticketFn = me.onAfterApplyChanges.deferByTickets(me, [closeWindow]),
1095                     wrapTicket = ticketFn();
1096
1097                 me.fireEvent('update', Ext.util.JSON.encode(me.record.data), me.mode, me, ticketFn);
1098                 wrapTicket();
1099             }
1100         }, function (message) {
1101             me.saving = false;
1102             me.loadMask.hide();
1103             Ext.MessageBox.alert(i18n._('Errors'), message);
1104         });
1105     },
1106
1107     /**
1108      * returns additional save params
1109      *
1110      * @param {EditDialog} me
1111      * @returns {{duplicateCheck: boolean}}
1112      */
1113     getAdditionalSaveParams: function(me) {
1114         return {
1115             duplicateCheck: me.doDuplicateCheck
1116         };
1117     },
1118     
1119     onAfterApplyChanges: function(closeWindow) {
1120         this.window.rename(this.windowNamePrefix + this.record.id);
1121         this.saving = false;
1122         
1123         if (closeWindow) {
1124             this.window.fireEvent('saveAndClose');
1125             this.purgeListeners();
1126             this.window.close();
1127         } else {
1128             this.loadMask.hide();
1129         }
1130     },
1131     
1132     /**
1133      * get validation error message
1134      * 
1135      * @return {String}
1136      */
1137     getValidationErrorMessage: function() {
1138         return i18n._('Please fix the errors noted.');
1139     },
1140     
1141     /**
1142      * generic delete handler
1143      */
1144     onDelete: function(btn, e) {
1145         Ext.MessageBox.confirm(i18n._('Confirm'), String.format(i18n._('Do you really want to delete this {0}?'), this.i18nRecordName), function(_button) {
1146             if(btn == 'yes') {
1147                 var deleteMask = new Ext.LoadMask(this.getEl(), {msg: String.format(i18n._('Deleting {0}'), this.i18nRecordName)});
1148                 deleteMask.show();
1149                 
1150                 this.recordProxy.deleteRecords(this.record, {
1151                     scope: this,
1152                     success: function() {
1153                         this.purgeListeners();
1154                         this.window.close();
1155                     },
1156                     failure: function () {
1157                         Ext.MessageBox.alert(i18n._('Failed'), String.format(i18n._('Could not delete {0}.'), this.i18nRecordName));
1158                         Ext.MessageBox.hide();
1159                     }
1160                 });
1161             }
1162         });
1163     },
1164     
1165     /**
1166      * duplicate(s) found exception handler
1167      * 
1168      * @param {Object} exception
1169      */
1170     onDuplicateException: function(exception) {
1171         var resolveGridPanel = new Tine.widgets.dialog.DuplicateResolveGridPanel({
1172             app: this.app,
1173             store: new Tine.widgets.dialog.DuplicateResolveStore({
1174                 app: this.app,
1175                 recordClass: this.recordClass,
1176                 recordProxy: this.recordProxy,
1177                 data: {
1178                     clientRecord: exception.clientRecord,
1179                     duplicates: exception.duplicates
1180                 }
1181             }),
1182             fbar: [
1183                 '->',
1184                 this.action_cancel,
1185                 this.action_saveAndClose
1186             ]
1187         });
1188         
1189         // intercept save handler
1190         resolveGridPanel.btnSaveAndClose.setHandler(function(btn, e) {
1191             var resolveStrategy = resolveGridPanel.store.resolveStrategy;
1192             
1193             // action discard -> close window
1194             if (resolveStrategy == 'discard') {
1195                 return this.onCancel();
1196             }
1197             
1198             this.record = resolveGridPanel.store.getResolvedRecord();
1199             
1200             // quit copy mode before populating form with resolved data
1201             this.copyRecord = false;
1202             this.onRecordLoad();
1203             
1204             mainCardPanel.layout.setActiveItem(this.id);
1205             resolveGridPanel.doLayout();
1206             
1207             this.doDuplicateCheck = false;
1208             this.onSaveAndClose();
1209         }, this);
1210         
1211         // place in viewport
1212         this.window.setTitle(String.format(i18n._('Resolve Duplicate {0} Suspicion'), this.i18nRecordName));
1213         var mainCardPanel = this.findParentBy(function(p) {return p.isWindowMainCardPanel });
1214         mainCardPanel.add(resolveGridPanel);
1215         mainCardPanel.layout.setActiveItem(resolveGridPanel.id);
1216         resolveGridPanel.doLayout();
1217     },
1218     
1219     /**
1220      * generic request exception handler
1221      * 
1222      * @param {Object} exception
1223      */
1224     onRequestFailed: function(exception) {
1225         this.saving = false;
1226
1227         if (this.exceptionHandlingMap && this.exceptionHandlingMap[exception.code] && typeof this.exceptionHandlingMap[exception.code] === 'function') {
1228             this.exceptionHandlingMap[exception.code](exception);
1229
1230         } else if (exception.code == 629) {
1231             this.onDuplicateException.apply(this, arguments);
1232
1233         } else {
1234             Tine.Tinebase.ExceptionHandler.handleRequestException(exception);
1235         }
1236
1237         this.loadMask.hide();
1238     },
1239     
1240     /**
1241      * creates the relations panel, if relations are defined
1242      */
1243     initRelationsPanel: function() {
1244         if (! this.hideRelationsPanel && this.recordClass && this.recordClass.hasField('relations')) {
1245             // init relations panel before onRecordLoad
1246             if (! this.relationsPanel) {
1247                 this.relationsPanel = new Tine.widgets.relation.GenericPickerGridPanel({ anchor: '100% 100%', editDialog: this });
1248             }
1249             // interrupt process flow until dialog is rendered
1250             if (! this.rendered) {
1251                 this.initRelationsPanel.defer(250, this);
1252                 return;
1253             }
1254             // add relations panel if this is rendered
1255             if (this.items.items[0]) {
1256                 this.items.items[0].add(this.relationsPanel);
1257             }
1258             
1259             Tine.log.debug('Tine.widgets.dialog.EditDialog::initRelationsPanel() - Initialized relations panel and added to dialog tab items.');
1260         }
1261     },
1262
1263     /**
1264      * create notes panel
1265      */
1266     initNotesPanel: function() {
1267         // This dialog is pretty generic but for some cases it's used in a differend way
1268         if(this.displayNotes == true) {
1269             this.items.items.push(new Tine.widgets.activities.ActivitiesGridPanel({
1270                 anchor: '100% 100%',
1271                 editDialog: this
1272             }));
1273         }
1274     },
1275
1276     /**
1277      * creates attachments panel
1278      */
1279     initAttachmentsPanel: function() {
1280         if (! this.attachmentsPanel && ! this.hideAttachmentsPanel && this.recordClass && this.recordClass.hasField('attachments') && Tine.Tinebase.registry.get('filesystemAvailable')) {
1281             this.attachmentsPanel = new Tine.widgets.dialog.AttachmentsGridPanel({ anchor: '100% 100%', editDialog: this }); 
1282             this.items.items.push(this.attachmentsPanel);
1283         }
1284     }
1285 });