[FIX] hr_timesheet_sheet: accept custom fields in timesheets
[odoo/odoo.git] / addons / hr_timesheet_sheet / static / src / js / timesheet.js
1
2 openerp.hr_timesheet_sheet = function(instance) {
3     var QWeb = instance.web.qweb;
4     var _t = instance.web._t;
5
6     instance.hr_timesheet_sheet.WeeklyTimesheet = instance.web.form.FormWidget.extend(instance.web.form.ReinitializeWidgetMixin, {
7         events: {
8             "click .oe_timesheet_weekly_account a": "go_to",
9         },
10         ignore_fields: function() {
11             return ['line_id'];
12         },
13         init: function() {
14             this._super.apply(this, arguments);
15             var self = this;
16             this.set({
17                 sheets: [],
18                 date_to: false,
19                 date_from: false,
20             });
21             this.updating = false;
22             this.defs = [];
23             this.field_manager.on("field_changed:timesheet_ids", this, this.query_sheets);
24             this.field_manager.on("field_changed:date_from", this, function() {
25                 this.set({"date_from": instance.web.str_to_date(this.field_manager.get_field_value("date_from"))});
26             });
27             this.field_manager.on("field_changed:date_to", this, function() {
28                 this.set({"date_to": instance.web.str_to_date(this.field_manager.get_field_value("date_to"))});
29             });
30             this.field_manager.on("field_changed:user_id", this, function() {
31                 this.set({"user_id": this.field_manager.get_field_value("user_id")});
32             });
33             this.on("change:sheets", this, this.update_sheets);
34             this.res_o2m_drop = new instance.web.DropMisordered();
35             this.render_drop = new instance.web.DropMisordered();
36             this.description_line = _t("/");
37             // Original save function is overwritten in order to wait all running deferreds to be done before actually applying the save.
38             this.view.original_save = _.bind(this.view.save, this.view);
39             this.view.save = function(prepend_on_create){
40                 self.prepend_on_create = prepend_on_create;
41                 return $.when.apply($, self.defs).then(function(){
42                     return self.view.original_save(self.prepend_on_create);
43                 });
44             };
45         },
46         go_to: function(event) {
47             var id = JSON.parse($(event.target).data("id"));
48             this.do_action({
49                 type: 'ir.actions.act_window',
50                 res_model: "account.analytic.account",
51                 res_id: id,
52                 views: [[false, 'form']],
53                 target: 'current'
54             });
55         },
56         query_sheets: function() {
57             var self = this;
58             if (self.updating)
59                 return;
60             var commands = this.field_manager.get_field_value("timesheet_ids");
61             this.res_o2m_drop.add(new instance.web.Model(this.view.model).call("resolve_2many_commands", ["timesheet_ids", commands, [], 
62                     new instance.web.CompoundContext()]))
63                 .done(function(result) {
64                 self.querying = true;
65                 self.set({sheets: result});
66                 self.querying = false;
67             });
68         },
69         update_sheets: function() {
70             var self = this;
71             if (self.querying)
72                 return;
73             self.updating = true;
74             self.field_manager.set_values({timesheet_ids: self.get("sheets")}).done(function() {
75                 self.updating = false;
76             });
77         },
78         initialize_field: function() {
79             instance.web.form.ReinitializeWidgetMixin.initialize_field.call(this);
80             var self = this;
81             self.on("change:sheets", self, self.initialize_content);
82             self.on("change:date_to", self, self.initialize_content);
83             self.on("change:date_from", self, self.initialize_content);
84             self.on("change:user_id", self, self.initialize_content);
85         },
86         initialize_content: function() {
87             var self = this;
88             if (self.setting)
89                 return;
90             // don't render anything until we have date_to and date_from
91             if (!self.get("date_to") || !self.get("date_from"))
92                 return;
93             this.destroy_content();
94
95             // it's important to use those vars to avoid race conditions
96             var dates;
97             var accounts;
98             var account_names;
99             var default_get;
100             return this.render_drop.add(new instance.web.Model("hr.analytic.timesheet").call("default_get", [
101                 ['account_id','general_account_id', 'journal_id','date','name','user_id','product_id','product_uom_id','to_invoice','amount','unit_amount'],
102                 new instance.web.CompoundContext({'user_id': self.get('user_id')})]).then(function(result) {
103                 default_get = result;
104                 // calculating dates
105                 dates = [];
106                 var start = self.get("date_from");
107                 var end = self.get("date_to");
108                 while (start <= end) {
109                     dates.push(start);
110                     start = start.clone().addDays(1);
111                 }
112                 // group by account
113                 accounts = _(self.get("sheets")).chain()
114                 .map(function(el) {
115                     // much simpler to use only the id in all cases
116                     if (typeof(el.account_id) === "object")
117                         el.account_id = el.account_id[0];
118                     return el;
119                 })
120                 .groupBy("account_id").value();
121
122                 var account_ids = _.map(_.keys(accounts), function(el) { return el === "false" ? false : Number(el) });
123
124                 return new instance.web.Model("hr.analytic.timesheet").call("multi_on_change_account_id", [[], account_ids,
125                     new instance.web.CompoundContext({'user_id': self.get('user_id')})]).then(function(accounts_defaults) {
126                     accounts = _(accounts).chain().map(function(lines, account_id) {
127                         account_defaults = _.extend({}, default_get, (accounts_defaults[account_id] || {}).value || {});
128                         // group by days
129                         account_id = account_id === "false" ? false :  Number(account_id);
130                         var index = _.groupBy(lines, "date");
131                         var days = _.map(dates, function(date) {
132                             var day = {day: date, lines: index[instance.web.date_to_str(date)] || []};
133                             // add line where we will insert/remove hours
134                             var to_add = _.find(day.lines, function(line) { return line.name === self.description_line });
135                             if (to_add) {
136                                 day.lines = _.without(day.lines, to_add);
137                                 day.lines.unshift(to_add);
138                             } else {
139                                 day.lines.unshift(_.extend(_.clone(account_defaults), {
140                                     name: self.description_line,
141                                     unit_amount: 0,
142                                     date: instance.web.date_to_str(date),
143                                     account_id: account_id,
144                                 }));
145                             }
146                             return day;
147                         });
148                         return {account: account_id, days: days, account_defaults: account_defaults};
149                     }).value();
150
151                     // we need the name_get of the analytic accounts
152                     return new instance.web.Model("account.analytic.account").call("name_get", [_.pluck(accounts, "account"),
153                         new instance.web.CompoundContext()]).then(function(result) {
154                         account_names = {};
155                         _.each(result, function(el) {
156                             account_names[el[0]] = el[1];
157                         });
158                         accounts = _.sortBy(accounts, function(el) {
159                             return account_names[el.account];
160                         });
161                     });;
162                 });
163             })).then(function(result) {
164                 // we put all the gathered data in self, then we render
165                 self.dates = dates;
166                 self.accounts = accounts;
167                 self.account_names = account_names;
168                 self.default_get = default_get;
169                 //real rendering
170                 self.display_data();
171             });
172         },
173         destroy_content: function() {
174             if (this.dfm) {
175                 this.dfm.destroy();
176                 this.dfm = undefined;
177             }
178         },
179         is_valid_value:function(value){
180             var split_value = value.split(":");
181             var valid_value = true;
182             if (split_value.length > 2)
183                 return false;
184             _.detect(split_value,function(num){
185                 if(isNaN(num)){
186                     valid_value = false;
187                 }
188             });
189             return valid_value;
190         },
191         display_data: function() {
192             var self = this;
193             self.$el.html(QWeb.render("hr_timesheet_sheet.WeeklyTimesheet", {widget: self}));
194             _.each(self.accounts, function(account) {
195                 _.each(_.range(account.days.length), function(day_count) {
196                     if (!self.get('effective_readonly')) {
197                         self.get_box(account, day_count).val(self.sum_box(account, day_count, true)).change(function() {
198                             var num = $(this).val();
199                             if (self.is_valid_value(num)){
200                                 num = (num == 0)?0:Number(self.parse_client(num));
201                             }
202                             if (isNaN(num)) {
203                                 $(this).val(self.sum_box(account, day_count, true));
204                             } else {
205                                 account.days[day_count].lines[0].unit_amount += num - self.sum_box(account, day_count);
206                                 var product = (account.days[day_count].lines[0].product_id instanceof Array) ? account.days[day_count].lines[0].product_id[0] : account.days[day_count].lines[0].product_id
207                                 var journal = (account.days[day_count].lines[0].journal_id instanceof Array) ? account.days[day_count].lines[0].journal_id[0] : account.days[day_count].lines[0].journal_id
208                                 self.defs.push(new instance.web.Model("hr.analytic.timesheet").call("on_change_unit_amount", [[], product, account.days[day_count].lines[0].unit_amount, false, false, journal]).then(function(res) {
209                                     account.days[day_count].lines[0]['amount'] = res.value.amount || 0;
210                                     self.display_totals();
211                                     self.sync();
212                                 }));
213                                 if(!isNaN($(this).val())){
214                                     $(this).val(self.sum_box(account, day_count, true));
215                                 }
216                             }
217                         });
218                     } else {
219                         self.get_box(account, day_count).html(self.sum_box(account, day_count, true));
220                     }
221                 });
222             });
223             self.display_totals();
224             self.$(".oe_timesheet_weekly_adding button").click(_.bind(this.init_add_account, this));
225         },
226         init_add_account: function() {
227             var self = this;
228             if (self.dfm)
229                 return;
230             self.$(".oe_timesheet_weekly_add_row").show();
231             self.dfm = new instance.web.form.DefaultFieldManager(self);
232             self.dfm.extend_field_desc({
233                 account: {
234                     relation: "account.analytic.account",
235                 },
236             });
237             self.account_m2o = new instance.web.form.FieldMany2One(self.dfm, {
238                 attrs: {
239                     name: "account",
240                     type: "many2one",
241                     domain: [
242                         ['type','in',['normal', 'contract']],
243                         ['state', '<>', 'close'],
244                         ['use_timesheets','=',1],
245                         ['id', 'not in', _.pluck(self.accounts, "account")],
246                     ],
247                     context: {
248                         default_use_timesheets: 1,
249                         default_type: "contract",
250                     },
251                     modifiers: '{"required": true}',
252                 },
253             });
254             self.account_m2o.prependTo(self.$(".oe_timesheet_weekly_add_row td"));
255             self.$(".oe_timesheet_weekly_add_row button").click(function() {
256                 var id = self.account_m2o.get_value();
257                 if (id === false) {
258                     self.dfm.set({display_invalid_fields: true});
259                     return;
260                 }
261                 var ops = self.generate_o2m_value();
262                 new instance.web.Model("hr.analytic.timesheet").call("on_change_account_id", [[], id]).then(function(res) {
263                     var def = _.extend({}, self.default_get, res.value, {
264                         name: self.description_line,
265                         unit_amount: 0,
266                         date: instance.web.date_to_str(self.dates[0]),
267                         account_id: id,
268                     });
269                     ops.push(def);
270                     self.set({"sheets": ops});
271                 });
272             });
273         },
274         get_box: function(account, day_count) {
275             return this.$('[data-account="' + account.account + '"][data-day-count="' + day_count + '"]');
276         },
277         get_total: function(account) {
278             return this.$('[data-account-total="' + account.account + '"]');
279         },
280         get_day_total: function(day_count) {
281             return this.$('[data-day-total="' + day_count + '"]');
282         },
283         get_super_total: function() {
284             return this.$('.oe_timesheet_weekly_supertotal');
285         },
286         sum_box: function(account, day_count, show_value_in_hour) {
287             var line_total = 0;
288             _.each(account.days[day_count].lines, function(line) {
289                 line_total += line.unit_amount;
290             });
291             return (show_value_in_hour && line_total != 0)?this.format_client(line_total):line_total;
292         },
293         display_totals: function() {
294             var self = this;
295             var day_tots = _.map(_.range(self.dates.length), function() { return 0 });
296             var super_tot = 0;
297             _.each(self.accounts, function(account) {
298                 var acc_tot = 0;
299                 _.each(_.range(self.dates.length), function(day_count) {
300                     var sum = self.sum_box(account, day_count);
301                     acc_tot += sum;
302                     day_tots[day_count] += sum;
303                     super_tot += sum;
304                 });
305                 self.get_total(account).html(self.format_client(acc_tot));
306             });
307             _.each(_.range(self.dates.length), function(day_count) {
308                 self.get_day_total(day_count).html(self.format_client(day_tots[day_count]));
309             });
310             self.get_super_total().html(self.format_client(super_tot));
311         },
312         sync: function() {
313             var self = this;
314             self.setting = true;
315             self.set({sheets: this.generate_o2m_value()});
316             self.setting = false;
317         },
318         //converts hour value to float
319         parse_client: function(value) {
320             return instance.web.parse_value(value, { type:"float_time" });
321         },
322         //converts float value to hour
323         format_client:function(value){
324             return instance.web.format_value(value, { type:"float_time" });
325         },
326         generate_o2m_value: function() {
327             var self = this;
328             var ops = [];
329             var ignored_fields = self.ignore_fields();
330             _.each(self.accounts, function(account) {
331                 _.each(account.days, function(day) {
332                     _.each(day.lines, function(line) {
333                         if (line.unit_amount !== 0) {
334                             var tmp = _.clone(line);
335                             tmp.id = undefined;
336                             _.each(line, function(v, k) {
337                                 if (v instanceof Array) {
338                                     tmp[k] = v[0];
339                                 }
340                             });
341                             // we remove line_id as the reference to the _inherits field will no longer exists
342                             tmp = _.omit(tmp, ignored_fields);
343                             ops.push(tmp);
344                         }
345                     });
346                 });
347             });
348             return ops;
349         },
350     });
351
352     instance.web.form.custom_widgets.add('weekly_timesheet', 'instance.hr_timesheet_sheet.WeeklyTimesheet');
353
354 };