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