Bonjour.

J'ai créé une barre d'outils permettant de tracer le temps passé sur une tâche (on sélectionne d'abord le projet, puis la tâche sur laquelle on veut travailler, puis on lance un compteur temps...on final quand on arrête, un task.work est créé)

Je n'arrive pas à externaliser mon code, et donc à surclasser (si le mot est bon) la fonction instance.web.WebClient présente dans chrome.js

Pour l'instant donc, mes fonctions se trouvent directement dans la fonction instance.web.WebClient, responsable de l'affichage de l'interface web d'openerp, située dans le fichier chrome.js, et mon compteur temps est chargé/instancié/affiché dans show_application().

Pouvez vous m'expliquer comment "surcharger" cette fonction ???

Le but est de pouvoir insérer des nouveaux éléments dans le menu principal...

Merci d'avance.

Voici le code que j'ai inséré dans chrome.js (dans events j'ai ajouté les événements pour gérer mes boutons/liste déroulantes, dans init je mets des variables globales à null, dans show_application je lance ma fonction (init_watch))

mes ajouts en bleu...

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
instance.web.WebClient = instance.web.Client.extend({
    _template: 'WebClient',
    events: {
        'click .oe_logo_edit_admin': 'logo_edit',
	       'click .oe_web_example_start button': 'watch_start',
	       'click .oe_web_example_stop button': 'watch_stop',
	       'change .oe_button_project_class select': function (event) {
	       	
	       	//alert(event.target.innerHTML);
	       	this.loadtask(event.target.options[event.target.selectedIndex].text);},
	       	
	       'change .oe_button_task_class select': function (event) {
	       	
	       	//alert(event.target.innerHTML);
	       	//this.workontask(event.target.innerHTML);}
	       	this.workontask(event.target.options[event.target.selectedIndex].text);}
    },
    init: function(parent) {
        this._super(parent);
        this._current_state = null;
        this.menu_dm = new instance.web.DropMisordered();
        this.action_mutex = new $.Mutex();
        this._start = null;
        this._watch = null;
        this.workontaskid = '';
    },
    start: function() {
        var self = this;
        return $.when(this._super()).then(function() {
            if (jQuery.param !== undefined && jQuery.deparam(jQuery.param.querystring()).kitten !== undefined) {
                $("body").addClass("kitten-mode-activated");
                if ($.blockUI) {
                    $.blockUI.defaults.message = '<img src="http://www.amigrave.com/kitten.gif">';
                }
            }
            if (!self.session.session_is_valid()) {
                self.show_login();
            } else {
                self.show_application();
            }
        });
    },
    set_title: function(title) {
        title = _.str.clean(title);
        var sep = _.isEmpty(title) ? '' : ' - ';
        document.title = title + sep + 'OpenERP';
    },
    show_common: function() {
        var self = this;
        this._super();
        window.onerror = function (message, file, line) {
            self.crashmanager.show_error({
                type: _t("Client Error"),
                message: message,
                data: {debug: file + ':' + line}
            });
        };
    },
    show_login: function() {
        this.toggle_bars(false);

        var state = $.bbq.getState(true);
        var action = {
            type: 'ir.actions.client',
            tag: 'login',
            _push_me: false,
        };

        this.action_manager.do_action(action);
        this.action_manager.inner_widget.on('login_successful', this, function() {
            this.show_application();        // will load the state we just pushed
        });
    },
    show_application: function() {
        var self = this;
        self.toggle_bars(true);
        self.update_logo();
        self.menu = new instance.web.Menu(self);
        self.menu.replace(this.$el.find('.oe_menu_placeholder'));
        self.menu.on('menu_click', this, this.on_menu_action);
        self.user_menu = new instance.web.UserMenu(self);
        self.user_menu.replace(this.$el.find('.oe_user_menu_placeholder'));
        self.user_menu.on('user_logout', self, self.on_logout);
        self.user_menu.do_update();
        self.bind_hashchange();
        self.set_title();
        self.check_timezone();
        self.init_watch();
    },
    
    init_watch: function() {
        	this._start = null;
					dfd = new instance.web.Model('project.project').query(['name']).all().then(
        		function (result)
        		{
							console.log("L'appel a réussi.");
					    l = result.length;
            	i = 0;
            	document.getElementById("select_project").innerHTML = '<option value="">Select A Project</option>';
            	for(i=0;i<l;i++)
            	{
								//document.getElementById("p_project").innerHTML += '<button class="oe_button_project_class">' + result[i].name + '</button><br/><hr style="width:200px; color:firebrick; background-color:firebrick; height:3px;"/>';
								document.getElementById("select_project").innerHTML += '<option value="' + result[i].name + '">' + result[i].name + '</option>';
								//document.getElementById("select_project").options[i].text = result[i].name;
            	}
        		},  // Callback de réussite
						function ()
						{
							console.log("L'appel est raté.");
						},    // Callback d'échec
						function ()
						{
							console.log("L'appel est en cours.");
						} // Callback de progression
					);

    },
    
    loadtask: function (mybutton) {
				//var Sender = document.event.srcElement;
				//alert("le bouton presse est:"+mybutton);
			dfd = new instance.web.Model('project.task').query(['name']).filter([['project_id','=',mybutton]]).all().then(
    		function (result)
    		{
					console.log("L'appel a réussi.");
			    l = result.length;
			    console.log(l + " taches trouves.");
        	i = 0;
        	document.getElementById("select_task").innerHTML = '<option value="">Select A Task</option>';
        	for(i=0;i<l;i++)
        	{
						//document.getElementById("p_task").innerHTML += '<button class="oe_button_task_class">' + result[i].name + '</button><br/><hr style="width:200px; color:firebrick; background-color:firebrick; height:3px;"/>';
						document.getElementById("select_task").innerHTML += '<option value="' + result[i].name + '">' + result[i].name + '</option>';
        	}
    		},  // Callback de réussite
				function ()
				{
					console.log("L'appel est raté.");
				},    // Callback d'échec
				function ()
				{
					console.log("L'appel est en cours.");
				} // Callback de progression
			);

    },

    workontask: function (mybutton) {
    	console.log("workontask success.");
    	this.workontaskid = mybutton;
    	
    	
    },
    
    countUP: function (counter,minutes,hours,timer,todisplay,h2disp,m2disp,s2disp)
		{
        var h, m, s;
        // Subtracting javascript dates returns the difference in milliseconds
        var diff = new Date() - this._start;
        s = diff / 1000;
        m = Math.floor(s / 60);
        s -= 60*m;
        h = Math.floor(m / 60);
        m -= 60*h;
		 	todisplay = _.str.sprintf("%02d:%02d:%02d", h, m, s);
		 	document.getElementById("extimer").innerHTML = todisplay;
		},
    
    watch_start: function () {
    	alert('i m here');
    	this._start = new Date();
    	this._watch = setInterval(this.proxy('countUP'),33);
	   },
	   
	   watch_stop: function () {
	   		console.log('task id = ' + this.workontaskid);
				(new instance.web.Model('web.ex.class')).get_func('update_task_work')(this.workontaskid,document.getElementById("extimer").innerHTML)
				                .fail(function(unused, event){
				                    //don't show error popup if it fails 
				                    //event.preventDefault();
				                    console.log("create new work failed");
				                })
				                .done(function(){
				                    console.log("create new work success");
				                });
	      clearInterval(this._watch);
		 		document.getElementById("extimer").innerHTML = '00:00:00';
	      this._start = this._watch = null;
	      this.$el.removeClass('oe_web_example_started')
	              .addClass('oe_web_example_stopped');
	   },
    
    update_logo: function() {
        var img = this.session.url('/web/binary/company_logo');
        this.$('.oe_logo img').attr('src', '').attr('src', img);
        this.$('.oe_logo_edit').toggleClass('oe_logo_edit_admin', this.session.uid === 1);
    },
    logo_edit: function(ev) {
        var self = this;
        new instance.web.Model("res.users").get_func("read")(this.session.uid, ["company_id"]).then(function(res) {
            self.rpc("/web/action/load", { action_id: "base.action_res_company_form" }).done(function(result) {
                result.res_id = res['company_id'][0];
                result.target = "new";
                result.views = [[false, 'form']];
                result.flags = {
                    action_buttons: true,
                };
                self.action_manager.do_action(result);
                var form = self.action_manager.dialog_widget.views.form.controller;
                form.on("on_button_cancel", self.action_manager.dialog, self.action_manager.dialog.close);
                form.on('record_saved', self, function() {
                    self.action_manager.dialog.close();
                    self.update_logo();
                });
            });
        });
        return false;
    },
    check_timezone: function() {
        var self = this;
        return new instance.web.Model('res.users').call('read', [[this.session.uid], ['tz_offset']]).then(function(result) {
            var user_offset = result[0]['tz_offset'];
            var offset = -(new Date().getTimezoneOffset());
            // _.str.sprintf()'s zero front padding is buggy with signed decimals, so doing it manually
            var browser_offset = (offset < 0) ? "-" : "+";
            browser_offset += _.str.sprintf("%02d", Math.abs(offset / 60));
            browser_offset += _.str.sprintf("%02d", Math.abs(offset % 60));
            if (browser_offset !== user_offset) {
                var $icon = $(QWeb.render('WebClient.timezone_systray'));
                $icon.on('click', function() {
                    var notification = self.do_warn(_t("Timezone mismatch"), QWeb.render('WebClient.timezone_notification', {
                        user_timezone: instance.session.user_context.tz || 'UTC',
                        user_offset: user_offset,
                        browser_offset: browser_offset,
                    }), true);
                    notification.element.find('.oe_webclient_timezone_notification').on('click', function() {
                        notification.close();
                    }).find('a').on('click', function() {
                        notification.close();
                        self.user_menu.on_menu_settings();
                        return false;
                    });
                });
                $icon.appendTo(self.$('.oe_systray'));
            }
        });
    },
    destroy_content: function() {
        _.each(_.clone(this.getChildren()), function(el) {
            el.destroy();
        });
        this.$el.children().remove();
    },
    do_reload: function() {
        var self = this;
        return this.session.session_reload().then(function () {
            instance.session.load_modules(true).then(
                self.menu.proxy('do_reload')); });

    },
    do_notify: function() {
        var n = this.notification;
        return n.notify.apply(n, arguments);
    },
    do_warn: function() {
        var n = this.notification;
        return n.warn.apply(n, arguments);
    },
    on_logout: function() {
        var self = this;
        if (!this.has_uncommitted_changes()) {
            this.session.session_logout().done(function () {
                $(window).unbind('hashchange', self.on_hashchange);
                self.do_push_state({});
                window.location.reload();
            });
        }
    },
    bind_hashchange: function() {
        var self = this;
        $(window).bind('hashchange', this.on_hashchange);

        var state = $.bbq.getState(true);
        if (_.isEmpty(state) || state.action == "login") {
            self.menu.has_been_loaded.done(function() {
                var first_menu_id = self.menu.$el.find("a:first").data("menu");
                if(first_menu_id) {
                    self.menu.menu_click(first_menu_id);
                }
            });
        } else {
            $(window).trigger('hashchange');
        }
    },
    on_hashchange: function(event) {
        var self = this;
        var state = event.getState(true);
        if (!_.isEqual(this._current_state, state)) {
            if(!state.action && state.menu_id) {
                self.menu.has_been_loaded.done(function() {
                    self.menu.do_reload().done(function() {
                        self.menu.menu_click(state.menu_id);
                    });
                });
            } else {
                state._push_me = false;  // no need to push state back...
                this.action_manager.do_load_state(state, !!this._current_state);
            }
        }
        this._current_state = state;
    },
    do_push_state: function(state) {
        this.set_title(state.title);
        delete state.title;
        var url = '#' + $.param(state);
        this._current_state = _.clone(state);
        $.bbq.pushState(url);
        this.trigger('state_pushed', state);
    },
    on_menu_action: function(options) {
        var self = this;
        return this.menu_dm.add(this.rpc("/web/action/load", { action_id: options.action_id }))
            .then(function (result) {
                return self.action_mutex.exec(function() {
                    if (options.needaction) {
                        result.context = new instance.web.CompoundContext(
                            result.context,
                            {search_default_message_unread: true});
                    }
                    var completed = $.Deferred();
                    $.when(self.action_manager.do_action(result, {
                        clear_breadcrumbs: true,
                        action_menu_id: self.menu.current_menu,
                    })).fail(function() {
                        self.menu.open_menu(options.previous_menu_id);
                    }).always(function() {
                        completed.resolve();
                    });
                    setTimeout(function() {
                        completed.resolve();
                    }, 2000);
                    // We block the menu when clicking on an element until the action has correctly finished
                    // loading. If something crash, there is a 2 seconds timeout before it's unblocked.
                    return completed;
                });
            });
    },
    set_content_full_screen: function(fullscreen) {
        $(document.body).css('overflow-y', fullscreen ? 'hidden' : 'scroll');
        this.$('.oe_webclient').toggleClass(
            'oe_content_full_screen', fullscreen);
    },
    has_uncommitted_changes: function() {
        var $e = $.Event('clear_uncommitted_changes');
        instance.web.bus.trigger('clear_uncommitted_changes', $e);
        if ($e.isDefaultPrevented()) {
            return true;
        } else {
            return this._super.apply(this, arguments);
        }
    },
});

instance.web.EmbeddedClient = instance.web.Client.extend({
    _template: 'EmbedClient',
    init: function(parent, origin, dbname, login, key, action_id, options) {
        this._super(parent, origin);
        this.bind_credentials(dbname, login, key);
        this.action_id = action_id;
        this.options = options || {};
    },
    start: function() {
        var self = this;
        return $.when(this._super()).then(function() {
            return self.authenticate().then(function() {
                if (!self.action_id) {
                    return;
                }
                return self.rpc("/web/action/load", { action_id: self.action_id }).done(function(result) {
                    var action = result;
                    action.flags = _.extend({
                        //views_switcher : false,
                        search_view : false,
                        action_buttons : false,
                        sidebar : false
                        //pager : false
                    }, self.options, action.flags || {});

                    self.do_action(action);
                });
            });
        });
    },

    do_action: function(action) {
        return this.action_manager.do_action(action);
    },

    authenticate: function() {
        var s = instance.session;
        if (s.session_is_valid() && s.db === this.dbname && s.login === this.login) {
            return $.when();
        }
        return instance.session.session_authenticate(this.dbname, this.login, this.key, true);
    },

    bind_credentials: function(dbname, login, key) {
        this.dbname = dbname;
        this.login = login;
        this.key = key;
    },

});