DataObjects/Core_locking.php
[Pman.Core] / Pman.js
1 //<script type="text/javascript">
2
3 /**
4  * 
5  * >>> Pman.layout.getRegion('center').tabs.stripWrap
6  * ==> tab.???
7  * var tbh = Pman.layout.getRegion('center').tabs.stripWrap.child('div').createChild(
8  * 
9  * {tag: 'div', style: 'display:block;position:absolute;top:2;left:300;width:100%;height:25px'});
10  * 
11  * 
12  *  CHANGES
13  *  - gtranslate moved to Pman.GoogleTranslate
14  * 
15  * 
16  */
17  
18 if (typeof(_T) == 'undefined') { _T={};}
19  
20
21
22   
23
24 Pman = new Roo.Document(
25 {
26    /// appVersion: '1.7', // fixme = needs to be removed - use Global AppVersion
27     subMenuItems : [],
28     topMenuItems : [],
29     rightNames: { }, /// register right names here - so they can be translated and rendered.
30     buildCompleted : false, // flag to say if we are building interface..
31     events : {
32         'beforeload' : true, // fired after page ready, before module building.
33         'load' : true, // fired after module building
34         'authrefreshed' : true // fire on auth updated?? - should be on Login?!?!?
35     },
36     
37     listeners : {
38         'ready' : function()
39         {
40             // kludge to fix firebug debugger
41             if (typeof(console) == 'undefined') {
42                 console = { log : function() {  } };
43             }
44             
45             // remove loader..
46             if (Roo.get('loading')) {
47                 Roo.get('loading').remove();
48             }
49             
50             Roo.state.Manager.setProvider(new Roo.state.CookieProvider());
51             
52             // link errors...
53             
54             if (AppLinkError.length) {
55                 Roo.MessageBox.alert("Error", AppLinkError, function() {
56                     Pman.Login.onLoad();
57                 });
58                 return;
59             }
60             
61             
62             // reset password!!!!
63             if (showNewPass.length) {
64                 Pman.PasswordChange.show(  { passwordReset : showNewPass },
65                     function(data) {
66                         // fail and success we do  a load...
67                         Pman.Login.onLoad();
68                     }
69                 );
70                 return;
71             }
72              
73             Pman.Login.onLoad();
74             
75         },
76         'load' : function()
77         {
78             if (Roo.get('loading-logo-tile')) {
79                 Roo.get('loading-logo-tile').remove();
80             }
81             if (Roo.get('loading-logo-tile-top')) {
82                 Roo.get('loading-logo-tile-top').remove();
83             }
84             if (Roo.get('loading-logo-bottom')) {
85                 Roo.get('loading-logo-bottom').remove();
86             }
87             if (Roo.get('loading-logo-center')) {
88                 Roo.get('loading-logo-center').remove();
89             }
90         }   
91         
92     },
93    
94
95     
96     layout: false,
97     
98     onload: function() {
99         //this.fireEvent('beforeload',this);
100         
101         
102         
103         if (this.layout) {
104             return; // already loaded
105         } 
106         if (Roo.get('loading')) {
107             Roo.get('loading').remove();
108         }
109         if (Roo.get('loading-mask')) {
110             Roo.get('loading-mask').show();
111         }
112         
113         
114        
115         
116         /*
117         Roo.MessageBox.show({
118            title: "Please wait...",
119            msg: "Building Interface...",
120            width:340,
121            progress:true,
122            closable:false
123           
124         });
125         */
126         //Pman.onLoadBuild();
127         //Roo.get(document.body).mask("Building Interface");
128         //Pman.onLoadBuild.defer(100, Pman);
129        //Pman.onLoadBuild();
130                     
131    // },
132     //onLoadBuild : function() {
133         
134         var _this = this;
135         this.stime = new Date();
136         this.layout = new Roo.BorderLayout(document.body, {
137             north: {
138                 split:false,
139                 initialSize: 25,
140                 titlebar: false
141             },
142          
143              
144             center: {
145                 titlebar: false,
146                 autoScroll:false,
147                 closeOnTab: true,
148                 tabPosition: 'top',
149                 //resizeTabs: true,
150                 alwaysShowTabs: true,
151                 minTabWidth: 140
152             } /*,
153             south: {
154                 split:false,
155                 initialSize: 25,
156                 titlebar: false
157             }
158             */
159         });
160         
161         this.fireEvent('beforeload',this);
162         
163         
164         
165         this.layout.beginUpdate();
166         this.layout.add('north', new Roo.ContentPanel('title', 'North'));
167         var au = Pman.Login.authUser;
168         if (au.id > 0 && au.company_id_background_color.length) {
169             Roo.get('title').dom.style.backgroundColor = '#' + au.company_id_background_color;
170             Roo.get('headerInformation').dom.style.color = this.invertColor('#' + au.company_id_background_color);
171         }
172         if (au.id > 0 && au.company_id_logo_id * 1 > 0) {
173             Roo.get('headerInformation-company-logo').dom.src =  baseURL + 
174                 '/Images/' + au.company_id_logo_id + '/' + au.company_id_logo_id_filename;
175         } else {
176             Roo.get('headerInformation-company-logo').dom.src = Roo.BLANK_IMAGE_URL;
177         }
178         
179         Roo.get('headerInformation').dom.innerHTML = String.format(
180                 "You are Logged in as <b>{0} ({1})</b>", // to {4} v{3}", // for <b>{2}</b>",
181                 au.name, au.email, au.company_id_name, 
182                 AppVersion , appNameShort
183         );
184         
185         
186         document.title = appName + ' v' + AppVersion + ' - ' + au.company_id_name;
187         Roo.QuickTips.init(); 
188         if (Roo.isGecko) {
189            Roo.useShims = true;
190         }
191        
192         //this.mainLayout.beginUpdate();
193         //var maskDom = Roo.get(document.body)._maskMsg.dom
194         this.layout.beginUpdate();
195         
196         Pman.building = true;
197         
198         this.buildModules(this, 
199             function() {
200                 
201                 _this.layout.getRegion('center').showPanel(0);
202                 _this.layout.endUpdate(); 
203                 _this.addTopToolbar();  
204                 _this.finalize();
205                 _this.fireEvent('load',this);
206             }
207         );
208         
209         
210      
211     },
212     
213     addTopToolbar : function()
214     {
215           //console.log( "t6:" + ((new Date())-stime));
216         //this.mainLayout.endUpdate();
217         // make a new tab to hold administration stuff...
218         
219        
220         //console.log( "t7:" + ((new Date())-stime));
221         var se = Pman.layout.getRegion('center').tabs.stripEl;
222         var tbh = se.createChild( 
223                 { tag: 'td', style: 'width:100%;'  });
224         
225         var lotb = new Roo.Toolbar(tbh);
226         
227         if (Roo.isSafari) {
228             var tbl = se.child('table', true);
229             tbl.setAttribute('width', '100%');
230         }
231         lotb.add(
232             new Roo.Toolbar.Fill(), 
233      
234             {
235                 text: "Change Password",
236                 cls: 'x-btn-text-icon',
237                 icon: rootURL + '/Pman/templates/images/change-password.gif',
238                 handler : function(){
239                     Pman.PasswordChange.show({});
240                 }
241             }, '-'
242         );
243          
244         
245         if (this.topMenuItems.length) {
246             
247             Roo.each(this.topMenuItems, function (mi) {
248                 lotb.add(mi);
249             });
250             lotb.add('-');
251         }
252         
253         
254         
255         if (this.subMenuItems.length) {
256             
257             this.subMenuItems.sort(function (a,b) {
258                 return a.seqid > b.seqid ? 1 : -1;
259             });
260             // chop off last seperator.
261             // since we always add it.. just chop of last item
262             this.subMenuItems.pop(); 
263             
264             lotb.add(
265                 {
266                      
267                     text: "Add New Item",
268                     cls: 'x-btn-text-icon',
269                     icon: Roo.rootURL + 'images/default/dd/drop-add.gif',
270                     menu : {
271                         items : this.subMenuItems
272                     }     
273                 } ,'-'
274             );
275         }
276        
277         lotb.add(
278             {
279                 text: "Logout",
280                 cls: 'x-btn-text-icon',
281                 icon: rootURL + '/Pman/templates/images/logout.gif',
282                 handler: function() {
283                     Pman.Login.logout();
284                 }
285                  
286             }
287         );
288       
289        // this.layout.endUpdate();
290     },
291     
292     
293     finalize : function() {
294         
295       
296        
297         window.onbeforeunload = function(e) { 
298             var e = e || window.event;
299             var r = "Closing this window will loose changes, are you sure you want to do that?";
300
301             // For IE and Firefox
302             if (e) {
303                 e.returnValue = r;
304             }
305
306             // For Safari
307             return r;
308             
309         };
310         
311         Roo.MessageBox.hide();
312         if (Roo.get('loading-mask')) {
313            Roo.get('loading-mask').remove();
314         }
315         
316         
317         this.buildCompleted = true; // now we can force refreshes on everything..
318         
319         
320         // does the URL indicate we want to see a system..
321         if (AppTrackOnLoad * 1 > 0) {
322             this.onLoadTrack(AppTrackOnLoad,false);
323         }
324         
325         // Open system..
326         
327         var forceAdmin = function(data)
328         {
329             if (!data || !data.id) {
330                 Pman.Dialog.PersonStaff.show( 
331                     { 
332                         id : 0, 
333                         company_id : Pman.Login.authUser.company_id * 1, 
334                         company_id_name : Pman.Login.authUser.company_id_name
335                     }, function(data) {
336                         forceAdmin(data);
337                     }
338                 );
339                 return;
340             }
341             Roo.state.Manager.set('Pman.Login.username', data.email),
342             window.onbeforeunload = false;
343             document.location = baseURL + '?ts=' + Math.random();
344         }
345         
346         var forceCompany = function(data) {
347             if (Pman.Login.authUser.company_id * 1 > 0) {
348                 forceAdmin();
349                 return;
350             }
351             if (!data || !data.id) {
352                 Pman.Dialog.Companies.show( { id : 0, isOwner : 1, comptype: 'OWNER' }, function(data) {
353                     forceCompany(data);
354                 });
355                 return;
356             }
357             Pman.Login.authUser.company_id  = data.id;
358             Pman.Login.authUser.company_id_name  = data.name;
359             forceAdmin();
360         }
361         
362         if (Pman.Login.authUser.id < 0) {
363             forceCompany();
364             /// create account..
365             
366             
367         }
368         
369
370     },
371     
372     
373     
374     
375      
376     onLoadTrack : function(id,cb) {
377         this.onLoadTrackCall(id, cb, 'DocumentsCirc_');
378     },
379     onLoadTrackEdit : function(id,cb) {
380         this.onLoadTrackCall(id, cb, 'Documents_');
381     },
382     
383     
384     /// ----------- FIXME -----
385     
386     
387     onLoadTrackCall : function(id,cb, cls) {
388         Roo.get(document.body).mask("Loading Document details");
389
390         Pman.request({
391             url: baseURL + '/Roo/Documents.html',  
392             params: {
393                 _id: id
394             },  
395             method: 'GET',  
396             success : function(data) {
397                 Roo.get(document.body).unmask();
398              
399                 
400                 switch(data.in_out) {
401                     case 'IN' : cls+='In';break;
402                     case 'OUT' : cls+='Out';break;
403                     case 'WIP' : cls+='Wip';break;
404                     default: 
405                         Roo.MessageBox.alert("Error", "invalid in_out");
406                         return;
407                 }
408                 Pman.Dialog[cls].show(data, cb ? cb : Pman.refreshActivePanel);
409             }, 
410             
411             failure: function() {
412                 Roo.get(document.body).unmask();
413                 //if (cb) {
414                 //    cb.call(false);
415                 //}
416                  
417            }
418         });
419           
420     },
421     
422     /**
423      * eg. has Pman.hasPerm('Admin.Admin_Tab', 'S') == showlist..
424      * 
425      */
426     hasPerm: function(name, lvl) {
427         if (typeof(Pman.Login.authUser) != 'object') {
428             return false;
429         }
430         if (typeof(Pman.Login.authUser.perms[name]) != 'string') {
431             return false;
432         }
433         return Pman.Login.authUser.perms[name].indexOf(lvl) > -1;
434         
435     },
436     
437     
438     
439     
440     
441     
442     
443     
444     Readers : {},
445     ColModels : {},
446     Forms : {},
447     Tab : {},
448     Dialog : {},
449     
450     processResponse : function (response)
451     {
452         var res = '';
453         try {
454             res = Roo.decode(response.responseText);
455             // oops...
456             if (typeof(res) != 'object') {
457                 res = { success : false, errorMsg : res, errors : true };
458             }
459             if (typeof(res.success) == 'undefined') {
460                 res.success = false;
461             }
462             
463         } catch(e) {
464             res = { success : false,  errorMsg : response.responseText, errors : true };
465         }
466         return res;
467     },
468     genericDelete : function(tab,tbl) {
469         
470         var r = [];
471         
472             
473         var s = tab.grid.getSelectionModel().getSelections();
474         if (!s.length)  {
475             Roo.MessageBox.alert("Error", "Select at least one Row to delete" );
476             return '';
477         }
478         
479         for(var i = 0; i < s.length; i++) {
480             r.push(s[i].data.id);
481         }
482     
483         Roo.MessageBox.confirm("Confirm", "Are you sure you want to delete that?",
484             function(btn) {
485                 if (btn != 'yes') {
486                     return;
487                 }
488                 // what about the toolbar??
489                 tab.grid.getView().mainWrap.mask("Deleting");
490                 Pman.request({
491                     url: baseURL + '/Roo/'+tbl+'.php',
492                     method: 'GET',
493                     params: {
494                         _delete : r.join(',')
495                     },
496                     success: function(response) {
497                         tab.grid.getView().mainWrap.unmask();
498                         if ( tab.paging ) {
499                             tab.paging.onClick('refresh');   
500                         } else if (tab.refresh) {
501                             tab.refresh();
502                         } else if (tab.grid.footer && tab.grid.footer.onClick) {
503                             // new xtype built grids
504                             tab.grid.footer.onClick('refresh');   
505                         } else {
506                             tab.grid.getDataSource().load();
507                         }
508                         
509                         
510                         
511                     },
512                     failure: function(act) {
513                         tab.grid.getView().mainWrap.unmask();
514                         Roo.MessageBox.alert("Error", "Error Deleting");
515                     }
516                     
517                 });
518             }
519         );
520     },
521     refreshActivePanel : function() {
522         var actpan = this.layout.getRegion('center').getActivePanel();
523         if (actpan.controller && actpan.controller.paging) {
524             actpan.controller.paging.onClick('refresh');
525             return;
526         }
527         
528         var agid = Pman.layout.getRegion('center').getActivePanel().id;
529         if (!agid) {
530             return;
531         }
532         Pman.Tab[agid].paging.onClick('refresh');
533     },
534     toCidV : function(data) {
535         return 'C' + data.in_out.substring(0,1) + data.cid;
536     },
537     
538     standardActionFailed :  function(f, act, cb) {
539     
540         if (act.failureType == 'client') {
541             Roo.MessageBox.alert("Error", "Please Correct all the errors in red", cb);
542             return;
543         }
544         if (act.failureType == 'connect') {
545             Roo.MessageBox.alert("Error", "Problem Connecting to Server - please try again.", cb);
546             return;
547         }
548         
549         if (act.type == 'submit') {
550             
551             Roo.MessageBox.alert("Error", typeof(act.result.errorMsg) == 'string' ?
552                 String.format('{0}', act.result.errorMsg) : 
553                 "Saving failed = fix errors and try again", cb);
554             return;
555         }
556         
557         // what about load failing..
558         Roo.MessageBox.alert("Error", "Error loading details",cb); 
559     },
560     /**
561      * 
562      * similar to Roo.Ajax, but handles our responses better...
563      * c.url
564      * c.method
565      * c.params
566      * c.failure() == failure function..
567      * c.success(data) == success function..
568      * 
569      * 
570      */
571     request : function(c) {
572         var r= new Roo.data.Connection({
573             timeout : typeof(c.timeout) == 'undefined' ?  30000 : c.timeout
574         });
575         r.request({
576             url: c.url,
577             method : c.method,
578             params: c.params,
579             xmlData : c.xmlData,
580             success:  function(response, opts)  {  // check successfull...
581                
582                 var res = Pman.processResponse(response);
583                 
584                 if (!res.success) { // error!
585                     if (c.failure) {
586                         if (true === c.failure.call(this,response, opts)) {
587                             return;
588                         }
589                     }
590                     Roo.MessageBox.hide();
591                     Roo.MessageBox.alert("Error", res.errorMsg ? res.errorMsg : "Error Sending");
592                     return;
593                 }
594                 
595                 c.success.call(this, res.data);
596                 
597                 return; 
598             },
599             failure :  function(response, opts)  {  // check successfull...
600                 
601                 if (c.failure) {
602                     if (true === c.failure.call(this,response, opts)) {
603                         return;
604                     }
605                 }
606                 Roo.MessageBox.hide();
607                 Roo.MessageBox.alert("Error", "Connection timed out sending");
608                 Roo.log(response);
609                 
610             },
611             scope: this
612             
613         });
614     },
615     
616     
617     // depreciated - use Pman.Download()
618     
619     download : function(c) {
620         
621         return new Pman.Download(c);
622     },
623     
624     // fixme - move to document manager...
625     downloadRevision : function(doc, rev)
626     {
627         this.download({
628             url: baseURL + '/Documents/Doc/DownloadRev/'+ doc.id + '/' + rev + '/' +
629                 doc.project_id_code + '-' + doc.cidV + '-' + rev  + '-' +  doc.filename
630         }); 
631                     
632     },
633     
634     
635     exportCSV : function(c) {
636         
637         for(var i=0;i < c.csvFormat.length;i++) {
638             c.params['csvCols['+i+']'] = c.csvFormat[i][0];
639             c.params['csvTitles['+i+']'] = c.csvFormat[i][1];
640         }
641         c.url +=  '?' + Roo.urlEncode(c.params);
642         this.download(c);
643
644     },
645     
646     
647     prettyDate : function (value) 
648     {
649         if (typeof(value) == 'string') {
650             var ds = Date.parseDate(value, 'Y-m-d H:i:s');
651             if (ds) {
652                 return this.prettyDate(ds);
653             }
654             ds = Date.parseDate(value, 'Y-m-d');
655             if (ds) {
656                 return this.prettyDate(ds);
657             }
658             return '';
659         }
660 // last 7 days...
661         if (!value) {
662             return '';
663         }
664         var td = new Date();
665         var daysSince = Math.floor(td.getElapsed(value) / (1000 * 60*60*24));
666         if (daysSince < 7) {
667             return value.dateFormat('D H:i');
668         }
669         
670         // same month
671         if (td.dateFormat('m') == value.dateFormat('m')) {
672             return value.dateFormat('dS D');
673         }
674         // same year?
675         if (td.dateFormat('Y') == value.dateFormat('Y')) {
676             return value.dateFormat('dS M');
677         }
678         return value.dateFormat('d M Y');
679     },
680     loadException : function(a,b,c,d)
681     {
682         if (d && d.authFailure) {
683             Pman.Login.show();
684             return;
685         }
686         Roo.MessageBox.alert("Problem Loading Data", a.message || c.statusText);
687     },
688     
689     
690     /**
691      * 
692      * Routine to flash alerts in the title bar..
693      * 
694      * 
695      */
696     
697     notifyActive : false,
698     
699     notifyTitle: function(msg)
700     {
701         if (this.notifyActive ) {
702             return;
703         }
704         var stop = false;
705         
706         var stopper = function() {
707             stop = true;
708              document.title = oldtitle;
709         };
710         
711         Roo.get(document.body).on('mousemove', stopper, this);
712         var oldtitle = document.title;
713         var s = 1;
714         var _this = this;
715         var ivl = window.setInterval(function() {
716             
717             if (stop) {
718                 Roo.get(document.body).un('mousemove', stopper, this);
719                 _this.notifyActive = false;
720                 document.title = oldtitle;
721                 window.clearInterval(ivl);
722                 return true;
723             }
724             s = !s;
725             document.title = s ? msg : oldtitle;
726                   
727         }, 1000); // every 120 secs = 2mins..
728          document.title =   msg;
729         
730         
731         
732     },
733     
734     modules : false,
735     /**
736      * example:
737      * 
738      * Pman.register({
739           modKey : '00-admin-xxxx',
740           module : Pman.Tab.projectMgr,
741           region : 'center',
742           parent : Pman.layout
743         })
744      * 
745      */
746     register : function(obj) {
747         if (!obj.parent) {
748             if (obj.parent === false) {
749                 //console.log('skip module (no parent)' + obj.modkey);
750                 return;
751             }
752             
753             console.log(obj);
754         }
755         if (!obj.parent.modules) {
756             obj.parent.modules = new Roo.util.MixedCollection(false, function(o) { return o.modKey });
757         }
758         
759         obj.parent.modules.add(obj);
760         
761     },
762     
763     buildModules : function(parent, onComplete) 
764     {
765         
766         var _this = this;
767         var cmp = function(a,b) {   
768             return String(a).toUpperCase() > String(b).toUpperCase() ? 1 : -1;
769             
770         };
771         if (!parent.modules) {
772             return;
773         }
774         parent.modules.keySort('ASC',  cmp );
775         var mods = [];
776         
777         
778         // add modules to their parents..
779         var addMod = function(m) {
780            // console.log(m.modKey);
781             
782             mods.push(m);
783             if (m.module.modules) {
784                 m.module.modules.keySort('ASC',  cmp );
785                 m.module.modules.each(addMod);
786             }
787             if (m.finalize) {
788                 m.finalize.name = m.name + " (clean up) ";
789                 mods.push(m.finalize);
790             }
791             
792         }
793  
794         parent.modules.each(addMod);
795         //this.allmods = mods;
796         //console.log(mods);
797         //return;
798         if (!mods.length) {
799             if (onComplete) onComplete();
800             return;
801         }
802         // flash it up as modal - so we store the mask!?
803         Roo.MessageBox.show({ title: 'loading' });
804         Roo.MessageBox.show({
805            title: "Please wait...",
806            msg: "Building Interface...",
807            width:450,
808            progress:true,
809            closable:false,
810            modal: false
811           
812         });
813         var n = 0;
814         var progressRun = function() {
815             
816             var mod = mods[n];
817             
818             
819             Roo.MessageBox.updateProgress(
820                 (n+1)/mods.length,  "Building Interface " + (n+1) + 
821                     " of " + mods.length + 
822                     (mod.name ? (' - ' + mod.name) : '')
823                     );
824             
825             
826             
827             if (typeof(mod) == 'function') {
828                 mod();
829                 
830             } else  if (mod.parent.layout && !mod.module.disabled) {
831                 // honour permname setings..
832                 if (mod.permname && mod.permname.length) {
833                     if (Pman.hasPerm(mod.permname, 'S')) {
834                         mod.module.add(mod.parent.layout, mod.region);    
835                     }
836                 } else {
837                     mod.module.add(mod.parent.layout, mod.region);    
838                 }
839                     
840                  
841             }
842             
843             
844             n++;
845             if (n >= mods.length) {
846                 onComplete();  
847                 return;
848             }
849                 
850             
851             progressRun.defer(10, Pman);    
852         }
853         progressRun.defer(1, Pman);
854      
855         
856         
857     },
858     
859     invertColor : function(c)
860     {
861         // read..
862         var ca = [];
863         for(var i = 0; i < 3; i++){
864             ca[i] = parseInt(c.charAt((i*2)+1) + c.charAt((i*2)+2), 16);
865         }
866             
867         // invert..
868         var col = '';
869         Roo.each(ca, function(hi) {
870             var h = parseInt(255-hi).toString(16);
871             if(h < 16){
872                 h = '0' + h;
873             }
874             col += h;
875         });
876         return '#' + col;
877         
878     }
879     
880     
881     
882     
883     
884     
885     
886 });
887