79a8645909f120eeb99ff43e39bd149d55016fa8
[odoo/odoo.git] / addons / account / static / src / js / account_widgets.js
1 openerp.account = function (instance) {
2     openerp.account.quickadd(instance);
3     var _t = instance.web._t,
4         _lt = instance.web._lt;
5     var QWeb = instance.web.qweb;
6     
7     instance.web.account = instance.web.account || {};
8     
9     instance.web.client_actions.add('bank_statement_reconciliation_view', 'instance.web.account.bankStatementReconciliation');
10     instance.web.account.bankStatementReconciliation = instance.web.Widget.extend({
11         className: 'oe_bank_statement_reconciliation',
12
13         events: {
14             "click .statement_name span": "statementNameClickHandler",
15             "keyup .change_statement_name_field": "changeStatementNameFieldHandler",
16             "click .change_statement_name_button": "changeStatementButtonClickHandler",
17         },
18     
19         init: function(parent, context) {
20             this._super(parent);
21             this.max_reconciliations_displayed = 10;
22             if (context.context.statement_id) this.statement_ids = [context.context.statement_id];
23             if (context.context.statement_ids) this.statement_ids = context.context.statement_ids;
24             this.single_statement = this.statement_ids !== undefined && this.statement_ids.length === 1;
25             this.multiple_statements = this.statement_ids !== undefined && this.statement_ids.length > 1;
26             this.title = context.context.title || _t("Reconciliation");
27             this.st_lines = [];
28             this.last_displayed_reconciliation_index = undefined; // Flow control
29             this.reconciled_lines = 0; // idem
30             this.already_reconciled_lines = 0; // Number of lines of the statement which were already reconciled
31             this.model_bank_statement = new instance.web.Model("account.bank.statement");
32             this.model_bank_statement_line = new instance.web.Model("account.bank.statement.line");
33             this.reconciliation_menu_id = false; // Used to update the needaction badge
34             this.formatCurrency; // Method that formats the currency ; loaded from the server
35     
36             // Only for statistical purposes
37             this.lines_reconciled_with_ctrl_enter = 0;
38             this.time_widget_loaded = Date.now();
39     
40             // Stuff used by the children bankStatementReconciliationLine
41             this.max_move_lines_displayed = 5;
42             this.animation_speed = 100; // "Blocking" animations
43             this.aestetic_animation_speed = 300; // eye candy
44             this.map_tax_id_amount = {};
45             this.presets = {};
46             // We'll need to get the code of an account selected in a many2one (whose value is the id)
47             this.map_account_id_code = {};
48             // The same move line cannot be selected for multiple resolutions
49             this.excluded_move_lines_ids = {};
50             // Description of the fields to initialize in the "create new line" form
51             // NB : for presets to work correctly, a field id must be the same string as a preset field
52             this.create_form_fields = {
53                 account_id: {
54                     id: "account_id",
55                     index: 0,
56                     corresponding_property: "account_id", // a account.move field name
57                     label: _t("Account"),
58                     required: true,
59                     tabindex: 10,
60                     constructor: instance.web.form.FieldMany2One,
61                     field_properties: {
62                         relation: "account.account",
63                         string: _t("Account"),
64                         type: "many2one",
65                         domain: [['type','not in',['view', 'closed', 'consolidation']]],
66                     },
67                 },
68                 label: {
69                     id: "label",
70                     index: 1,
71                     corresponding_property: "label",
72                     label: _t("Label"),
73                     required: true,
74                     tabindex: 11,
75                     constructor: instance.web.form.FieldChar,
76                     field_properties: {
77                         string: _t("Label"),
78                         type: "char",
79                     },
80                 },
81                 tax_id: {
82                     id: "tax_id",
83                     index: 2,
84                     corresponding_property: "tax_id",
85                     label: _t("Tax"),
86                     required: false,
87                     tabindex: 12,
88                     constructor: instance.web.form.FieldMany2One,
89                     field_properties: {
90                         relation: "account.tax",
91                         string: _t("Tax"),
92                         type: "many2one",
93                         domain: [['type_tax_use','in',['purchase', 'all']], ['parent_id', '=', false]],
94                     },
95                 },
96                 amount: {
97                     id: "amount",
98                     index: 3,
99                     corresponding_property: "amount",
100                     label: _t("Amount"),
101                     required: true,
102                     tabindex: 13,
103                     constructor: instance.web.form.FieldFloat,
104                     field_properties: {
105                         string: _t("Amount"),
106                         type: "float",
107                     },
108                 },
109                 analytic_account_id: {
110                     id: "analytic_account_id",
111                     index: 4,
112                     corresponding_property: "analytic_account_id",
113                     label: _t("Analytic Acc."),
114                     required: false,
115                     tabindex: 14,
116                     group:"analytic.group_analytic_accounting",
117                     constructor: instance.web.form.FieldMany2One,
118                     field_properties: {
119                         relation: "account.analytic.account",
120                         string: _t("Analytic Acc."),
121                         type: "many2one",
122                     },
123                 },
124             };
125         },
126     
127         start: function() {
128             this._super();
129             var self = this;
130             // Retreive statement infos and reconciliation data from the model
131             var lines_filter = [['journal_entry_id', '=', false], ['account_id', '=', false]];
132             var deferred_promises = [];
133             
134             // Working on specified statement(s)
135             if (self.statement_ids && self.statement_ids.length > 0) {
136                 lines_filter.push(['statement_id', 'in', self.statement_ids]);
137
138                 // If only one statement, display its name as title and allow to modify it
139                 if (self.single_statement) {
140                     deferred_promises.push(self.model_bank_statement
141                         .query(["name"])
142                         .filter([['id', '=', self.statement_ids[0]]])
143                         .first()
144                         .then(function(title){
145                             self.title = title.name;
146                         })
147                     );
148                 }
149                 // Anyway, find out how many statement lines are reconciled (for the progressbar)
150                 deferred_promises.push(self.model_bank_statement
151                     .call("number_of_lines_reconciled", [self.statement_ids])
152                     .then(function(num) {
153                         self.already_reconciled_lines = num;
154                     })
155                 );
156             }
157             
158             // Get operation templates
159             deferred_promises.push(new instance.web.Model("account.statement.operation.template")
160                 .query(['id','name','account_id','label','amount_type','amount','tax_id','analytic_account_id'])
161                 .all().then(function (data) {
162                     _(data).each(function(preset){
163                         self.presets[preset.id] = preset;
164                     });
165                 })
166             );
167
168             // Get the function to format currencies
169             deferred_promises.push(new instance.web.Model("res.currency")
170                 .call("get_format_currencies_js_function")
171                 .then(function(data) {
172                     self.formatCurrency = new Function("amount, currency_id", data);
173                 })
174             );
175     
176             // Get statement lines
177             deferred_promises.push(self.model_bank_statement_line
178                 .query(['id'])
179                 .filter(lines_filter)
180                 .order_by('statement_id, id')
181                 .all().then(function (data) {
182                     self.st_lines = _(data).map(function(o){ return o.id });
183                 })
184             );
185     
186             // When queries are done, render template and reconciliation lines
187             return $.when.apply($, deferred_promises).then(function(){
188     
189                 // If there is no statement line to reconcile, stop here
190                 if (self.st_lines.length === 0) {
191                     self.$el.prepend(QWeb.render("bank_statement_nothing_to_reconcile"));
192                     return;
193                 }
194     
195                 // Create a dict account id -> account code for display facilities
196                 new instance.web.Model("account.account")
197                     .query(['id', 'code'])
198                     .all().then(function(data) {
199                         _.each(data, function(o) { self.map_account_id_code[o.id] = o.code });
200                     });
201
202                 // Create a dict tax id -> amount
203                 new instance.web.Model("account.tax")
204                     .query(['id', 'amount'])
205                     .all().then(function(data) {
206                         _.each(data, function(o) { self.map_tax_id_amount[o.id] = o.amount });
207                     });
208             
209                 new instance.web.Model("ir.model.data")
210                     .call("xmlid_to_res_id", ["account.menu_bank_reconcile_bank_statements"])
211                     .then(function(data) {
212                         self.reconciliation_menu_id = data;
213                         self.doReloadMenuReconciliation();
214                     });
215
216                 // Bind keyboard events TODO : méthode standard ?
217                 $("body").on("keypress", function (e) {
218                     self.keyboardShortcutsHandler(e);
219                 });
220     
221                 // Render and display
222                 self.$el.prepend(QWeb.render("bank_statement_reconciliation", {
223                     title: self.title,
224                     single_statement: self.single_statement,
225                     total_lines: self.already_reconciled_lines+self.st_lines.length
226                 }));
227                 self.updateProgressbar();
228                 var reconciliations_to_show = self.st_lines.slice(0, self.max_reconciliations_displayed);
229                 self.last_displayed_reconciliation_index = reconciliations_to_show.length;
230                 self.$(".reconciliation_lines_container").css("opacity", 0);
231     
232                 // Display the reconciliations
233                 return self.model_bank_statement_line
234                     .call("get_data_for_reconciliations", [reconciliations_to_show])
235                     .then(function (data) {
236                         var child_promises = [];
237                         var datum = data.shift();
238                         child_promises.push(self.displayReconciliation(datum.st_line.id, 'match', false, true, datum.st_line, datum.reconciliation_proposition));
239                         while ((datum = data.shift()) !== undefined)
240                             child_promises.push(self.displayReconciliation(datum.st_line.id, 'inactive', false, true, datum.st_line, datum.reconciliation_proposition));
241                         $.when.apply($, child_promises).then(function(){
242                             self.$(".reconciliation_lines_container").animate({opacity: 1}, self.aestetic_animation_speed);
243                         });
244                     });
245             });
246         },
247
248         statementNameClickHandler: function() {
249             if (! this.single_statement) return;
250             this.$(".statement_name span").hide();
251             this.$(".change_statement_name_field").attr("value", this.title);
252             this.$(".change_statement_name_container").show();
253             this.$(".change_statement_name_field").focus();
254         },
255
256         changeStatementNameFieldHandler: function(e) {
257             var name = this.$(".change_statement_name_field").val();
258             if (name === "") this.$(".change_statement_name_button").attr("disabled", "disabled");
259             else this.$(".change_statement_name_button").removeAttr("disabled");
260             
261             if (name !== "" && e.which === 13) // Enter
262                 this.$(".change_statement_name_button").trigger("click");
263             if (e.which === 27) { // Escape
264                 this.$(".statement_name span").show();
265                 this.$(".change_statement_name_container").hide();
266             }
267         },
268
269         changeStatementButtonClickHandler: function() {
270             var self = this;
271             if (! self.single_statement) return;
272             var name = self.$(".change_statement_name_field").val();
273             if (name === "") return;
274             return self.model_bank_statement
275                 .call("write", [[self.statement_ids[0]], {'name': name}])
276                 .then(function () {
277                     self.title = name;
278                     self.$(".statement_name span").text(name).show();
279                     self.$(".change_statement_name_container").hide();
280                 });
281         },
282     
283         keyboardShortcutsHandler: function(e) {
284             var self = this;
285             if ((e.which === 13 || e.which === 10) && (e.ctrlKey || e.metaKey)) {
286                 self.persistReconciliations(_.filter(self.getChildren(), function(o) { return o.is_valid; }));
287             }
288         },
289
290         persistReconciliations: function(reconciliations) {
291             if (reconciliations.length === 0) return;
292             var self = this;
293             // Prepare data
294             var data = [];
295             for (var i=0; i<reconciliations.length; i++) {
296                 var child = reconciliations[i];
297                 data.push([child.st_line_id, child.makeMoveLineDicts()]);
298             }
299             var deferred_animation = self.$(".reconciliation_lines_container").fadeOut(self.aestetic_animation_speed);
300             deferred_rpc = self.model_bank_statement_line.call("process_reconciliations", [data]);
301             return $.when(deferred_animation, deferred_rpc)
302                 .done(function() {
303                     // Remove children
304                     for (var i=0; i<reconciliations.length; i++) {
305                         var child = reconciliations[i];
306                         self.unexcludeMoveLines(child, child.partner_id, child.get("mv_lines_selected"));
307                         $.each(child.$(".bootstrap_popover"), function(){ $(this).popover('destroy') });
308                         child.destroy();
309                     }
310                     // Update interface
311                     self.lines_reconciled_with_ctrl_enter += reconciliations.length;
312                     self.reconciled_lines += reconciliations.length;
313                     self.updateProgressbar();
314                     self.doReloadMenuReconciliation();
315
316                     // Display new line if there are left
317                     if (self.last_displayed_reconciliation_index < self.st_lines.length) {
318                         var begin = self.last_displayed_reconciliation_index;
319                         var end = Math.min((begin+self.max_reconciliations_displayed), self.st_lines.length);
320                         var reconciliations_to_show = self.st_lines.slice(begin, end);
321
322                         return self.model_bank_statement_line
323                             .call("get_data_for_reconciliations", [reconciliations_to_show])
324                             .then(function (data) {
325                                 var child_promises = [];
326                                 var datum;
327                                 while ((datum = data.shift()) !== undefined) {
328                                     var context = {
329                                         st_line_id: datum.st_line.id,
330                                         mode: 'inactive',
331                                         animate_entrance: false,
332                                         initial_data_provided: true,
333                                         st_line: datum.st_line,
334                                         reconciliation_proposition: datum.reconciliation_proposition,
335                                     };
336                                     var widget = new instance.web.account.bankStatementReconciliationLine(self, context);
337                                     child_promises.push(widget.appendTo(self.$(".reconciliation_lines_container")));
338                                 }
339                                 self.last_displayed_reconciliation_index += reconciliations_to_show.length;
340                                 return $.when.apply($, child_promises).then(function() {
341                                     // Put the first line in match mode
342                                     if (self.reconciled_lines !== self.st_lines.length) {
343                                         var first_child = self.getChildren()[0];
344                                         if (first_child.get("mode") === "inactive") {
345                                             first_child.set("mode", "match");
346                                         }
347                                     }
348                                     self.$(".reconciliation_lines_container").fadeIn(self.aestetic_animation_speed);
349                                 });
350                             });
351                     }
352                     // Congratulate the user if the work is done
353                     if (self.reconciled_lines === self.st_lines.length) {
354                         self.displayDoneMessage();
355                     }
356                 }).fail(function() {
357                     self.$(".reconciliation_lines_container").fadeIn(self.aestetic_animation_speed);
358                 });
359         },
360
361         // Adds move line ids to the list of move lines not to fetch for a given partner
362         // This is required because the same move line cannot be selected for multiple reconciliation
363         // and because for a partial reconciliation only one line can be fetched)
364         excludeMoveLines: function(source_child, partner_id, lines) {
365             var self = this;
366             var line_ids = _.collect(lines, function(o) { return o.id });
367         
368             var excluded_ids = this.excluded_move_lines_ids[partner_id];
369             var excluded_move_lines_changed = false;
370             _.each(line_ids, function(line_id){
371                 if (excluded_ids.indexOf(line_id) === -1) {
372                     excluded_ids.push(line_id);
373                     excluded_move_lines_changed = true;
374                 }
375             });
376             if (! excluded_move_lines_changed)
377                 return;
378         
379             // Function that finds if an array of line objects contains at least a line identified by its id
380             var contains_lines = function(lines_array, line_ids) {
381                 for (var i = 0; i < lines_array.length; i++)
382                     for (var j = 0; j < line_ids.length; j++)
383                         if (lines_array[i].id === line_ids[j])
384                             return true;
385                 return false;
386             };
387         
388             // Update children if needed
389             _.each(self.getChildren(), function(child){
390                 if (child.partner_id === partner_id && child !== source_child) {
391                     if (contains_lines(child.get("mv_lines_selected"), line_ids)) {
392                         child.set("mv_lines_selected", _.filter(child.get("mv_lines_selected"), function(o){ return line_ids.indexOf(o.id) === -1 }));
393                     } else if (contains_lines(child.mv_lines_deselected, line_ids)) {
394                         child.mv_lines_deselected = _.filter(child.mv_lines_deselected, function(o){ return line_ids.indexOf(o.id) === -1 });
395                         child.updateMatches();
396                     } else if (contains_lines(child.get("mv_lines"), line_ids)) {
397                         child.updateMatches();
398                     }
399                 }
400             });
401         },
402         
403         unexcludeMoveLines: function(source_child, partner_id, lines) {
404             var self = this;
405             var line_ids = _.collect(lines, function(o) { return o.id });
406
407             var initial_excluded_lines_num = this.excluded_move_lines_ids[partner_id].length;
408             this.excluded_move_lines_ids[partner_id] = _.difference(this.excluded_move_lines_ids[partner_id], line_ids);
409             if (this.excluded_move_lines_ids[partner_id].length === initial_excluded_lines_num)
410                 return;
411         
412             // Update children if needed
413             _.each(self.getChildren(), function(child){
414                 if (child.partner_id === partner_id && child !== source_child && (child.get("mode") === "match" || child.$el.hasClass("no_match")))
415                     child.updateMatches();
416             });
417         },
418     
419         displayReconciliation: function(st_line_id, mode, animate_entrance, initial_data_provided, st_line, reconciliation_proposition) {
420             var self = this;
421             animate_entrance = (animate_entrance === undefined ? true : animate_entrance);
422             initial_data_provided = (initial_data_provided === undefined ? false : initial_data_provided);
423     
424             var context = {
425                 st_line_id: st_line_id,
426                 mode: mode,
427                 animate_entrance: animate_entrance,
428                 initial_data_provided: initial_data_provided,
429                 st_line: initial_data_provided ? st_line : undefined,
430                 reconciliation_proposition: initial_data_provided ? reconciliation_proposition : undefined,
431             };
432             var widget = new instance.web.account.bankStatementReconciliationLine(self, context);
433             return widget.appendTo(self.$(".reconciliation_lines_container"));
434         },
435     
436         childValidated: function(child) {
437             var self = this;
438     
439             self.reconciled_lines++;
440             self.updateProgressbar();
441             self.doReloadMenuReconciliation();
442     
443             // Display new line if there are left
444             if (self.last_displayed_reconciliation_index < self.st_lines.length) {
445                 self.displayReconciliation(self.st_lines[self.last_displayed_reconciliation_index++], 'inactive');
446             }
447             // Congratulate the user if the work is done
448             if (self.reconciled_lines === self.st_lines.length) {
449                 self.displayDoneMessage();
450             }
451         
452             // Put the first line in match mode
453             if (self.reconciled_lines !== self.st_lines.length) {
454                 var first_child = self.getChildren()[0];
455                 if (first_child.get("mode") === "inactive") {
456                     first_child.set("mode", "match");
457                 }
458             }
459         },
460
461         goBackToStatementsTreeView: function() {
462             var self = this;
463             new instance.web.Model("ir.model.data")
464                 .call("get_object_reference", ['account', 'action_bank_statement_tree'])
465                 .then(function (result) {
466                     var action_id = result[1];
467                     // Warning : altough I don't see why this widget wouldn't be directly instanciated by the
468                     // action manager, if it wasn't, this code wouldn't work. You'd have to do something like :
469                     // var action_manager = self;
470                     // while (! action_manager instanceof ActionManager)
471                     //    action_manager = action_manager.getParent();
472                     var action_manager = self.getParent();
473                     var breadcrumbs = action_manager.breadcrumbs;
474                     var found = false;
475                     for (var i=breadcrumbs.length-1; i>=0; i--) {
476                         if (breadcrumbs[i].action && breadcrumbs[i].action.id === action_id) {
477                             var title = breadcrumbs[i].get_title();
478                             action_manager.select_breadcrumb(i, _.isArray(title) ? i : undefined);
479                             found = true;
480                         }
481                     }
482                     if (!found)
483                         instance.web.Home(self);
484                 });
485         },
486     
487         displayDoneMessage: function() {
488             var self = this;
489     
490             var sec_taken = Math.round((Date.now()-self.time_widget_loaded)/1000);
491             var sec_per_item = Math.round(sec_taken/self.reconciled_lines);
492             var achievements = [];
493     
494             var time_taken;
495             if (sec_taken/60 >= 1) time_taken = Math.floor(sec_taken/60) +"' "+ sec_taken%60 +"''";
496             else time_taken = sec_taken%60 +" seconds";
497     
498             var title;
499             if (sec_per_item < 5) title = _t("Whew, that was fast !") + " <i class='fa fa-trophy congrats_icon'></i>";
500             else title = _t("Congrats, you're all done !") + " <i class='fa fa-thumbs-o-up congrats_icon'></i>";
501     
502             if (self.lines_reconciled_with_ctrl_enter === self.reconciled_lines)
503                 achievements.push({
504                     title: _t("Efficiency at its finest"),
505                     desc: _t("Only use the ctrl-enter shortcut to validate reconciliations."),
506                     icon: "fa-keyboard-o"}
507                 );
508     
509             if (sec_per_item < 5)
510                 achievements.push({
511                     title: _t("Fast reconciler"),
512                     desc: _t("Take on average less than 5 seconds to reconcile a transaction."),
513                     icon: "fa-bolt"}
514                 );
515     
516             // Render it
517             self.$(".protip").hide();
518             self.$(".oe_form_sheet").append(QWeb.render("bank_statement_reconciliation_done_message", {
519                 title: title,
520                 time_taken: time_taken,
521                 sec_per_item: sec_per_item,
522                 transactions_done: self.reconciled_lines,
523                 done_with_ctrl_enter: self.lines_reconciled_with_ctrl_enter,
524                 achievements: achievements,
525                 single_statement: self.single_statement,
526                 multiple_statements: self.multiple_statements,
527             }));
528     
529             // Animate it
530             var container = $("<div style='overflow: hidden;' />");
531             self.$(".done_message").wrap(container).css("opacity", 0).css("position", "relative").css("left", "-50%");
532             self.$(".done_message").animate({opacity: 1, left: 0}, self.aestetic_animation_speed*2, "easeOutCubic");
533             self.$(".done_message").animate({opacity: 1}, self.aestetic_animation_speed*3, "easeOutCubic");
534     
535             // Make it interactive
536             self.$(".achievement").popover({'placement': 'top', 'container': self.el, 'trigger': 'hover'});
537
538             if (self.$(".button_back_to_statement").length !== 0) {
539                 self.$(".button_back_to_statement").click(function() {
540                     self.goBackToStatementsTreeView();
541                 });
542             }
543
544             if (self.$(".button_close_statement").length !== 0) {
545                 self.$(".button_close_statement").hide();
546                 self.model_bank_statement
547                     .query(["balance_end_real", "balance_end"])
548                     .filter([['id', 'in', self.statement_ids]])
549                     .all()
550                     .then(function(data){
551                         if (_.all(data, function(o) { return o.balance_end_real === o.balance_end })) {
552                             self.$(".button_close_statement").show();
553                             self.$(".button_close_statement").click(function() {
554                                 self.$(".button_close_statement").attr("disabled", "disabled");
555                                 self.model_bank_statement
556                                     .call("button_confirm_bank", [self.statement_ids])
557                                     .then(function () {
558                                         self.goBackToStatementsTreeView();
559                                     }, function() {
560                                         self.$(".button_close_statement").removeAttr("disabled");
561                                     });
562                             });
563                         }
564                     });
565             }
566         },
567     
568         updateProgressbar: function() {
569             var self = this;
570             var done = self.already_reconciled_lines + self.reconciled_lines;
571             var total = self.already_reconciled_lines + self.st_lines.length;
572             var prog_bar = self.$(".progress .progress-bar");
573             prog_bar.attr("aria-valuenow", done);
574             prog_bar.css("width", (done/total*100)+"%");
575             self.$(".progress .progress-text .valuenow").text(done);
576         },
577     
578         /* reloads the needaction badge */
579         doReloadMenuReconciliation: function () {
580             var menu = instance.webclient.menu;
581             if (!menu || !this.reconciliation_menu_id) {
582                 return $.when();
583             }
584             return menu.rpc("/web/menu/load_needaction", {'menu_ids': [this.reconciliation_menu_id]}).done(function(r) {
585                 menu.on_needaction_loaded(r);
586             }).then(function () {
587                 menu.trigger("need_action_reloaded");
588             });
589         },
590     });
591     
592     instance.web.account.bankStatementReconciliationLine = instance.web.Widget.extend({
593         className: 'oe_bank_statement_reconciliation_line',
594     
595         events: {
596             "click .change_partner": "changePartnerClickHandler",
597             "click .button_ok": "persistAndDestroy",
598             "click .mv_line": "moveLineClickHandler",
599             "click .initial_line": "initialLineClickHandler",
600             "click .line_open_balance": "lineOpenBalanceClickHandler",
601             "click .pager_control_left:not(.disabled)": "pagerControlLeftHandler",
602             "click .pager_control_right:not(.disabled)": "pagerControlRightHandler",
603             "keyup .filter": "filterHandler",
604             "click .line_info_button": function(e){e.stopPropagation()}, // small usability hack
605             "click .add_line": "addLineBeingEdited",
606             "click .preset": "presetClickHandler",
607             "click .do_partial_reconcile_button": "doPartialReconcileButtonClickHandler",
608             "click .undo_partial_reconcile_button": "undoPartialReconcileButtonClickHandler",
609         },
610     
611         init: function(parent, context) {
612             this._super(parent);
613     
614             this.formatCurrency = this.getParent().formatCurrency;
615             if (context.initial_data_provided) {
616                 // Process data
617                 _.each(context.reconciliation_proposition, function(line) {
618                     this.decorateMoveLine(line, context.st_line.currency_id);
619                 }, this);
620                 this.set("mv_lines_selected", context.reconciliation_proposition);
621                 this.st_line = context.st_line;
622                 this.partner_id = context.st_line.partner_id;
623                 this.decorateStatementLine(this.st_line);
624     
625                 // Exclude selected move lines
626                 if (this.getParent().excluded_move_lines_ids[this.partner_id] === undefined)
627                     this.getParent().excluded_move_lines_ids[this.partner_id] = [];
628                 this.getParent().excludeMoveLines(this, this.partner_id, context.reconciliation_proposition);
629             } else {
630                 this.set("mv_lines_selected", []);
631                 this.st_line = undefined;
632                 this.partner_id = undefined;
633             }
634     
635             this.context = context;
636             this.st_line_id = context.st_line_id;
637             this.max_move_lines_displayed = this.getParent().max_move_lines_displayed;
638             this.animation_speed = this.getParent().animation_speed;
639             this.aestetic_animation_speed = this.getParent().aestetic_animation_speed;
640             this.model_bank_statement_line = new instance.web.Model("account.bank.statement.line");
641             this.model_res_users = new instance.web.Model("res.users");
642             this.model_tax = new instance.web.Model("account.tax");
643             this.map_account_id_code = this.getParent().map_account_id_code;
644             this.map_tax_id_amount = this.getParent().map_tax_id_amount;
645             this.presets = this.getParent().presets;
646             this.is_valid = true;
647             this.is_consistent = true; // Used to prevent bad server requests
648             this.total_move_lines_num = undefined; // Used for pagers
649             this.filter = "";
650             // In rare cases like when deleting a statement line's partner we don't want the server to
651             // look for a reconciliation proposition (in this particular case it might find a move line
652             // matching the statement line and decide to set the statement line's partner accordingly)
653             this.do_load_reconciliation_proposition = true;
654     
655             this.set("mode", undefined);
656             this.on("change:mode", this, this.modeChanged);
657             this.set("balance", undefined); // Debit is +, credit is -
658             this.on("change:balance", this, this.balanceChanged);
659             this.set("pager_index", 0);
660             this.on("change:pager_index", this, this.pagerChanged);
661             // NB : mv_lines represent the counterpart that will be created to reconcile existing move lines, so debit and credit are inverted
662             this.set("mv_lines", []);
663             this.on("change:mv_lines", this, this.mvLinesChanged);
664             this.mv_lines_deselected = []; // deselected lines are displayed on top of the match table
665             this.on("change:mv_lines_selected", this, this.mvLinesSelectedChanged);
666             this.set("lines_created", []);
667             this.set("line_created_being_edited", [{'id': 0}]);
668             this.on("change:lines_created", this, this.createdLinesChanged);
669             this.on("change:line_created_being_edited", this, this.createdLinesChanged);
670         },
671     
672         start: function() {
673             var self = this;
674             return self._super().then(function() {
675                 // no animation while loading
676                 self.animation_speed = 0;
677                 self.aestetic_animation_speed = 0;
678     
679                 self.is_consistent = false;
680                 if (self.context.animate_entrance) {
681                     self.$el.fadeOut(0);
682                     self.$el.slideUp(0);
683                 }
684                 return $.when(self.loadData()).then(function(){
685                     return $.when(self.render()).then(function(){
686                         self.is_consistent = true;
687                         // Make an entrance
688                         self.animation_speed = self.getParent().animation_speed;
689                         self.aestetic_animation_speed = self.getParent().aestetic_animation_speed;
690                         if (self.context.animate_entrance) {
691                             return self.$el.stop(true, true).fadeIn({ duration: self.aestetic_animation_speed, queue: false }).css('display', 'none').slideDown(self.aestetic_animation_speed); 
692                         }
693                     });
694                 });
695             });
696         },
697
698         loadData: function() {
699             var self = this;
700             if (self.context.initial_data_provided)
701                 return;
702
703             // Get ids of selected move lines (to exclude them from reconciliation proposition)
704             var excluded_move_lines_ids = [];
705             if (self.do_load_reconciliation_proposition) {
706                 _.each(self.getParent().excluded_move_lines_ids, function(o){
707                     excluded_move_lines_ids = excluded_move_lines_ids.concat(o);
708                 });
709             }
710             // Load statement line
711             return self.model_bank_statement_line
712                 .call("get_data_for_reconciliations", [[self.st_line_id], excluded_move_lines_ids, self.do_load_reconciliation_proposition])
713                 .then(function (data) {
714                     self.st_line = data[0].st_line;
715                     self.decorateStatementLine(self.st_line);
716                     self.partner_id = data[0].st_line.partner_id;
717                     if (self.getParent().excluded_move_lines_ids[self.partner_id] === undefined)
718                         self.getParent().excluded_move_lines_ids[self.partner_id] = [];
719                     var mv_lines = [];
720                     _.each(data[0].reconciliation_proposition, function(line) {
721                         self.decorateMoveLine(line, self.st_line.currency_id);
722                         mv_lines.push(line);
723                     }, self);
724                     self.set("mv_lines_selected", self.get("mv_lines_selected").concat(mv_lines));
725                 });
726         },
727
728         render: function() {
729             var self = this;
730             var presets_array = [];
731             for (var id in self.presets)
732                 if (self.presets.hasOwnProperty(id))
733                     presets_array.push(self.presets[id]);
734             self.$el.prepend(QWeb.render("bank_statement_reconciliation_line", {
735                 line: self.st_line,
736                 mode: self.context.mode,
737                 presets: presets_array
738             }));
739             
740             // Stuff that require the template to be rendered
741             self.$(".match").slideUp(0);
742             self.$(".create").slideUp(0);
743             if (self.st_line.no_match) self.$el.addClass("no_match");
744             self.bindPopoverTo(self.$(".line_info_button"));
745             self.createFormWidgets();
746             // Special case hack : no identified partner
747             if (self.st_line.has_no_partner) {
748                 self.$el.css("opacity", "0");
749                 self.updateBalance();
750                 self.$(".change_partner_container").show(0);
751                 self.$(".match").slideUp(0);
752                 self.$el.addClass("no_partner");
753                 self.set("mode", self.context.mode);
754                 self.balanceChanged();
755                 self.updateAccountingViewMatchedLines();
756                 self.animation_speed = self.getParent().animation_speed;
757                 self.aestetic_animation_speed = self.getParent().aestetic_animation_speed;
758                 self.$el.animate({opacity: 1}, self.aestetic_animation_speed);
759                 return;
760             }
761             
762             // TODO : the .on handler's returned deferred is lost
763             return $.when(self.set("mode", self.context.mode)).then(function(){
764                 // Make sure the display is OK
765                 self.balanceChanged();
766                 self.createdLinesChanged();
767                 self.updateAccountingViewMatchedLines();
768             });
769         },
770
771         restart: function(mode) {
772             var self = this;
773             mode = (mode === undefined ? 'inactive' : mode);
774             self.context.animate_entrance = false;
775             self.$el.css("height", self.$el.outerHeight());
776             // Destroy everything
777             _.each(self.getChildren(), function(o){ o.destroy() });
778             self.is_consistent = false;
779             return $.when(self.$el.animate({opacity: 0}, self.animation_speed)).then(function() {
780                 self.getParent().unexcludeMoveLines(self, self.partner_id, self.get("mv_lines_selected"));
781                 $.each(self.$(".bootstrap_popover"), function(){ $(this).popover('destroy') });
782                 self.$el.empty();
783                 self.$el.removeClass("no_partner");
784                 self.context.mode = mode;
785                 self.context.initial_data_provided = false;
786                 self.is_valid = true;
787                 self.is_consistent = true;
788                 self.filter = "";
789                 self.set("balance", undefined, {silent: true});
790                 self.set("mode", undefined, {silent: true});
791                 self.set("pager_index", 0, {silent: true});
792                 self.set("mv_lines", [], {silent: true});
793                 self.set("mv_lines_selected", [], {silent: true});
794                 self.mv_lines_deselected = [];
795                 self.set("lines_created", [], {silent: true});
796                 self.set("line_created_being_edited", [{'id': 0}], {silent: true});
797                 // Rebirth
798                 return $.when(self.start()).then(function() {
799                     self.$el.css("height", "auto");
800                     self.is_consistent = true;
801                     self.$el.animate({opacity: 1}, self.animation_speed);
802                 });
803             });
804         },
805     
806         /* create form widgets, append them to the dom and bind their events handlers */
807         createFormWidgets: function() {
808             var self = this;
809             var create_form_fields = self.getParent().create_form_fields;
810             var create_form_fields_arr = [];
811             for (var key in create_form_fields)
812                 if (create_form_fields.hasOwnProperty(key))
813                     create_form_fields_arr.push(create_form_fields[key]);
814             create_form_fields_arr.sort(function(a, b){ return b.index - a.index });
815     
816             // field_manager
817             var dataset = new instance.web.DataSet(this, "account.account", self.context);
818             dataset.ids = [];
819             dataset.arch = {
820                 attrs: { string: "Stéphanie de Monaco", version: "7.0", class: "oe_form_container" },
821                 children: [],
822                 tag: "form"
823             };
824     
825             var field_manager = new instance.web.FormView (
826                 this, dataset, false, {
827                     initial_mode: 'edit',
828                     disable_autofocus: false,
829                     $buttons: $(),
830                     $pager: $()
831             });
832     
833             field_manager.load_form(dataset);
834     
835             // fields default properties
836             var Default_field = function() {
837                 this.context = {};
838                 this.domain = [];
839                 this.help = "";
840                 this.readonly = false;
841                 this.required = true;
842                 this.selectable = true;
843                 this.states = {};
844                 this.views = {};
845             };
846             var Default_node = function(field_name) {
847                 this.tag = "field";
848                 this.children = [];
849                 this.required = true;
850                 this.attrs = {
851                     invisible: "False",
852                     modifiers: '{"required":true}',
853                     name: field_name,
854                     nolabel: "True",
855                 };
856             };
857     
858             // Append fields to the field_manager
859             field_manager.fields_view.fields = {};
860             for (var i=0; i<create_form_fields_arr.length; i++) {
861                 field_manager.fields_view.fields[create_form_fields_arr[i].id] = _.extend(new Default_field(), create_form_fields_arr[i].field_properties);
862             }
863             field_manager.fields_view.fields["change_partner"] = _.extend(new Default_field(), {
864                 relation: "res.partner",
865                 string: _t("Partner"),
866                 type: "many2one",
867                 domain: [['parent_id','=',false], '|', ['customer','=',true], ['supplier','=',true]],
868             });
869     
870             // Returns a function that serves as a xhr response handler
871             var hideGroupResponseClosureFactory = function(field_widget, $container, obj_key){
872                 return function(has_group){
873                     if (has_group) $container.show();
874                     else {
875                         field_widget.destroy();
876                         $container.remove();
877                         delete self[obj_key];
878                     }
879                 };
880             };
881     
882             // generate the create "form"
883             self.create_form = [];
884             for (var i=0; i<create_form_fields_arr.length; i++) {
885                 var field_data = create_form_fields_arr[i];
886     
887                 // create widgets
888                 var node = new Default_node(field_data.id);
889                 if (! field_data.required) node.attrs.modifiers = "";
890                 var field = new field_data.constructor(field_manager, node);
891                 self[field_data.id+"_field"] = field;
892                 self.create_form.push(field);
893     
894                 // on update : change the last created line
895                 field.corresponding_property = field_data.corresponding_property;
896                 field.on("change:value", self, self.formCreateInputChanged);
897     
898                 // append to DOM
899                 var $field_container = $(QWeb.render("form_create_field", {id: field_data.id, label: field_data.label}));
900                 field.appendTo($field_container.find("td"));
901                 self.$(".create_form").prepend($field_container);
902     
903                 // now that widget's dom has been created (appendTo does that), bind events and adds tabindex
904                 if (field_data.field_properties.type != "many2one") {
905                     // Triggers change:value TODO : moche bind ?
906                     field.$el.find("input").keyup(function(e, field){ field.commit_value(); }.bind(null, null, field));
907                 }
908                 field.$el.find("input").attr("tabindex", field_data.tabindex);
909     
910                 // Hide the field if group not OK
911                 if (field_data.group !== undefined) {
912                     var target = $field_container;
913                     target.hide();
914                     self.model_res_users
915                         .call("has_group", [field_data.group])
916                         .then(hideGroupResponseClosureFactory(field, target, (field_data.id+"_field")));
917                 }
918             }
919     
920             // generate the change partner "form"
921             var change_partner_node = new Default_node("change_partner"); change_partner_node.attrs.modifiers = "";
922             self.change_partner_field = new instance.web.form.FieldMany2One(field_manager, change_partner_node);
923             self.change_partner_field.appendTo(self.$(".change_partner_container"));
924             self.change_partner_field.on("change:value", self.change_partner_field, function() {
925                 self.changePartner(this.get_value());
926             });
927             self.change_partner_field.$el.find("input").attr("placeholder", self.st_line.communication_partner_name || _t("Select Partner"));
928     
929             field_manager.do_show();
930         },
931     
932         /** Utils */
933     
934         /* TODO : if t-call for attr, all in qweb */
935         decorateStatementLine: function(line){
936             line.q_popover = QWeb.render("bank_statement_reconciliation_line_details", {line: line});
937         },
938     
939         // adds fields, prefixed with q_, to the move line for qweb rendering
940         decorateMoveLine: function(line, currency_id) {
941             line.partial_reconcile = false;
942             line.propose_partial_reconcile = false;
943             line['credit'] = [line['debit'], line['debit'] = line['credit']][0];
944             line.q_due_date = (line.date_maturity === false ? line.date : line.date_maturity);
945             line.q_amount = (line.debit !== 0 ? "- "+line.q_debit : "") + (line.credit !== 0 ? line.q_credit : "");
946             line.q_label = line.name;
947             line.debit_str = this.formatCurrency(line.debit, currency_id);
948             line.credit_str = this.formatCurrency(line.credit, currency_id);
949             line.q_popover = QWeb.render("bank_statement_reconciliation_move_line_details", {line: line});
950             if (line.has_no_partner)
951                 line.q_label = line.partner_name + ': ' + line.q_label;
952             if (line.ref && line.ref !== line.name)
953                 line.q_label += " : " + line.ref;
954         },
955     
956         bindPopoverTo: function(el) {
957             var self = this;
958             $(el).addClass("bootstrap_popover");
959             el.popover({
960                 'placement': 'left',
961                 'container': self.el,
962                 'html': true,
963                 'trigger': 'hover',
964                 'animation': false,
965                 'toggle': 'popover'
966             });
967         },
968     
969         islineCreatedBeingEditedValid: function() {
970             var line = this.get("line_created_being_edited")[0];
971             return line.amount // must be defined and not 0
972                 && line.account_id // must be defined (and will never be 0)
973                 && line.label; // must be defined and not empty
974         },
975     
976         /* returns the created lines, plus the ones being edited if valid */
977         getCreatedLines: function() {
978             var self = this;
979             var created_lines = self.get("lines_created").slice();
980             if (self.islineCreatedBeingEditedValid())
981                 return created_lines.concat(self.get("line_created_being_edited"));
982             else
983                 return created_lines;
984         },
985     
986         /** Matching */
987     
988         moveLineClickHandler: function(e) {
989             var self = this;
990             if (e.currentTarget.dataset.selected === "true") self.deselectMoveLine(e.currentTarget);
991             else self.selectMoveLine(e.currentTarget);
992         },
993
994         selectMoveLine: function(mv_line) {
995             var self = this;
996             var line_id = mv_line.dataset.lineid;
997
998             // find the line in mv_lines or mv_lines_deselected
999             var line = _.find(self.get("mv_lines"), function(o){ return o.id == line_id});
1000             if (! line) {
1001                 line = _.find(self.mv_lines_deselected, function(o){ return o.id == line_id });
1002                 self.mv_lines_deselected = _.filter(self.mv_lines_deselected, function(o) { return o.id != line_id });
1003             }
1004             if (! line) return; // If no line found, we've got a syncing problem (let's turn a deaf ear)
1005
1006             // Warn the user if he's selecting lines from both a payable and a receivable account
1007             var last_selected_line = _.last(self.get("mv_lines_selected"));
1008             if (last_selected_line && last_selected_line.account_type != line.account_type) {
1009                 new instance.web.Dialog(this, {
1010                     title: _t("Warning"),
1011                     size: 'medium',
1012                 }, $("<div />").text(_.str.sprintf(_t("You are selecting transactions from both a payable and a receivable account.\n\nIn order to proceed, you first need to deselect the %s transactions."), last_selected_line.account_type))).open();
1013                 return;
1014             }
1015
1016             // If statement line has no partner, give it the partner of the selected move line
1017             if (!this.st_line.partner_id && line.partner_id) {
1018                 self.changePartner(line.partner_id, function() {
1019                     self.selectMoveLine(mv_line);
1020                 });
1021             } else {
1022                 self.set("mv_lines_selected", self.get("mv_lines_selected").concat(line));
1023                 // $(mv_line).attr('data-selected','true');
1024                 // self.set("mv_lines_selected", self.get("mv_lines_selected").concat(line));
1025                 // this.set("mv_lines", _.reject(this.get("mv_lines"), function(o){return o.id == line_id}));
1026                 // this.getParent().excludeMoveLines([line_id]);
1027             }
1028         },
1029
1030         deselectMoveLine: function(mv_line) {
1031             var self = this;
1032             var line_id = mv_line.dataset.lineid;
1033             var line = _.find(self.get("mv_lines_selected"), function(o){ return o.id == line_id});
1034             if (! line) return; // If no line found, we've got a syncing problem (let's turn a deaf ear)
1035
1036             // add the line to mv_lines_deselected and remove it from mv_lines_selected
1037             self.mv_lines_deselected.unshift(line);
1038             var mv_lines_selected = _.filter(self.get("mv_lines_selected"), function(o) { return o.id != line_id });
1039             
1040             // remove partial reconciliation stuff if necessary
1041             if (line.partial_reconcile === true) self.unpartialReconcileLine(line);
1042             if (line.propose_partial_reconcile === true) line.propose_partial_reconcile = false;
1043             
1044             self.$el.removeClass("no_match");
1045             self.set("mode", "match");
1046             self.set("mv_lines_selected", mv_lines_selected);
1047
1048
1049             // $(mv_line).attr('data-selected','false');
1050             // this.set("mv_lines", this.get("mv_lines").concat(line));
1051             // this.getParent().unexcludeMoveLines([line_id]);
1052         },
1053     
1054         /** Matches pagination */
1055     
1056         pagerControlLeftHandler: function() {
1057             var self = this;
1058             if (self.$(".pager_control_left").hasClass("disabled")) { return; /* shouldn't happen, anyway*/ }
1059             if (self.total_move_lines_num < 0) { return; }
1060             self.set("pager_index", self.get("pager_index")-1 );
1061         },
1062         
1063         pagerControlRightHandler: function() {
1064             var self = this;
1065             var new_index = self.get("pager_index")+1;
1066             if (self.$(".pager_control_right").hasClass("disabled")) { return; /* shouldn't happen, anyway*/ }
1067             if ((new_index * self.max_move_lines_displayed) >= self.total_move_lines_num) { return; }
1068             self.set("pager_index", new_index );
1069         },
1070     
1071         filterHandler: function() {
1072             var self = this;
1073             self.set("pager_index", 0);
1074             self.filter = self.$(".filter").val();
1075             window.clearTimeout(self.apply_filter_timeout);
1076             self.apply_filter_timeout = window.setTimeout(self.proxy('updateMatches'), 200);
1077         },
1078
1079     
1080         /** Creating */
1081     
1082         initializeCreateForm: function() {
1083             var self = this;
1084     
1085             _.each(self.create_form, function(field) {
1086                 field.set("value", false);
1087             });
1088             self.label_field.set("value", self.st_line.name);
1089             self.amount_field.set("value", -1*self.get("balance"));
1090             self.account_id_field.focus();
1091         },
1092     
1093         addLineBeingEdited: function() {
1094             var self = this;
1095             if (! self.islineCreatedBeingEditedValid()) return;
1096             
1097             self.set("lines_created", self.get("lines_created").concat(self.get("line_created_being_edited")));
1098             // Add empty created line
1099             var new_id = self.get("line_created_being_edited")[0].id + 1;
1100             self.set("line_created_being_edited", [{'id': new_id}]);
1101     
1102             self.initializeCreateForm();
1103         },
1104     
1105         removeLine: function($line) {
1106             var self = this;
1107             var line_id = $line.data("lineid");
1108     
1109             // if deleting the created line that is being edited, validate it before
1110             if (line_id === self.get("line_created_being_edited")[0].id) {
1111                 self.addLineBeingEdited();
1112             }
1113             self.set("lines_created", _.filter(self.get("lines_created"), function(o) { return o.id != line_id }));
1114             self.amount_field.set("value", -1*self.get("balance"));
1115         },
1116     
1117         presetClickHandler: function(e) {
1118             var self = this;
1119             self.initializeCreateForm();
1120             var preset = self.presets[e.currentTarget.dataset.presetid];
1121             // Hack : set_value of a field calls a handler that returns a deferred because it could make a RPC call
1122             // to compute the tax before it updates the line being edited. Unfortunately this deferred is lost.
1123             // Hence this ugly hack to avoid concurrency problem that arose when setting amount (in initializeCreateForm), then tax, then another amount
1124             if (preset.tax && self.tax_field) self.tax_field.set_value(false);
1125             if (preset.amount && self.amount_field) self.amount_field.set_value(false);
1126
1127             for (var key in preset) {
1128                 if (! preset.hasOwnProperty(key) || key === "amount") continue;
1129                 if (preset[key] && self.hasOwnProperty(key+"_field"))
1130                     self[key+"_field"].set_value(preset[key]);
1131             }
1132             if (preset.amount && self.amount_field) {
1133                 if (preset.amount_type === "fixed")
1134                     self.amount_field.set_value(preset.amount);
1135                 else if (preset.amount_type === "percentage_of_total")
1136                     self.amount_field.set_value(self.st_line.amount * preset.amount / 100);
1137                 else if (preset.amount_type === "percentage_of_balance") {
1138                     self.amount_field.set_value(0);
1139                     self.updateBalance();
1140                     self.amount_field.set_value(-1 * self.get("balance") * preset.amount / 100);
1141                 }
1142             }
1143         },
1144     
1145
1146         /** Display */
1147     
1148         initialLineClickHandler: function() {
1149             var self = this;
1150             if (self.get("mode") === "match") {
1151                 self.set("mode", "inactive");
1152             } else {
1153                 self.set("mode", "match");
1154             }
1155         },
1156     
1157         lineOpenBalanceClickHandler: function() {
1158             var self = this;
1159             if (self.get("mode") === "create") {
1160                 self.set("mode", "match");
1161             } else {
1162                 self.set("mode", "create");
1163             }
1164         },
1165     
1166         changePartnerClickHandler: function() {
1167             var self = this;
1168             self.$(".change_partner_container").find("input").attr("placeholder", self.st_line.partner_name);
1169             self.$(".change_partner_container").show();
1170             self.$(".partner_name").hide();
1171             self.change_partner_field.$drop_down.trigger("click");
1172         },
1173     
1174     
1175         /** Views updating */
1176     
1177         updateAccountingViewMatchedLines: function() {
1178             var self = this;
1179             $.each(self.$(".tbody_matched_lines .bootstrap_popover"), function(){ $(this).popover('destroy') });
1180             self.$(".tbody_matched_lines").empty();
1181     
1182             _(self.get("mv_lines_selected")).each(function(line){
1183                 var $line = $(QWeb.render("bank_statement_reconciliation_move_line", {line: line, selected: true}));
1184                 self.bindPopoverTo($line.find(".line_info_button"));
1185                 if (line.propose_partial_reconcile) self.bindPopoverTo($line.find(".do_partial_reconcile_button"));
1186                 if (line.partial_reconcile) self.bindPopoverTo($line.find(".undo_partial_reconcile_button"));
1187                 self.$(".tbody_matched_lines").append($line);
1188             });
1189         },
1190     
1191         updateAccountingViewCreatedLines: function() {
1192             var self = this;
1193             $.each(self.$(".tbody_created_lines .bootstrap_popover"), function(){ $(this).popover('destroy') });
1194             self.$(".tbody_created_lines").empty();
1195     
1196             _(self.getCreatedLines()).each(function(line){
1197                 var $line = $(QWeb.render("bank_statement_reconciliation_created_line", {line: line}));
1198                 $line.find(".line_remove_button").click(function(){ self.removeLine($(this).closest(".created_line")) });
1199                 self.$(".tbody_created_lines").append($line);
1200                 if (line.no_remove_action) {
1201                     // Then the previous line's remove button deletes this line too
1202                     $line.hover(function(){ $(this).prev().addClass("active") },function(){ $(this).prev().removeClass("active") });
1203                 }
1204             });
1205         },
1206     
1207         updateMatchView: function() {
1208             var self = this;
1209             var table = self.$(".match table");
1210             var nothing_displayed = true;
1211         
1212             // Display move lines
1213             $.each(self.$(".match table .bootstrap_popover"), function(){ $(this).popover('destroy') });
1214             table.empty();
1215             var slice_start = self.get("pager_index") * self.max_move_lines_displayed;
1216             var slice_end = (self.get("pager_index")+1) * self.max_move_lines_displayed;
1217             _( _.filter(self.mv_lines_deselected, function(o){
1218                     return o.name.indexOf(self.filter) !== -1 || o.ref.indexOf(self.filter) !== -1 })
1219                 .slice(slice_start, slice_end)).each(function(line){
1220                 var $line = $(QWeb.render("bank_statement_reconciliation_move_line", {line: line, selected: false}));
1221                 self.bindPopoverTo($line.find(".line_info_button"));
1222                 table.append($line);
1223                 nothing_displayed = false;
1224             });
1225             _(self.get("mv_lines")).each(function(line){
1226                 var $line = $(QWeb.render("bank_statement_reconciliation_move_line", {line: line, selected: false}));
1227                 self.bindPopoverTo($line.find(".line_info_button"));
1228                 table.append($line);
1229                 nothing_displayed = false;
1230             });
1231             if (nothing_displayed && this.filter !== "")
1232                 table.append(QWeb.render("filter_no_match", {filter_str: self.filter}));
1233         },
1234     
1235         updatePagerControls: function() {
1236             var self = this;
1237         
1238             if (self.get("pager_index") === 0)
1239                 self.$(".pager_control_left").addClass("disabled");
1240             else
1241                 self.$(".pager_control_left").removeClass("disabled");
1242             if (self.total_move_lines_num <= ((self.get("pager_index")+1) * self.max_move_lines_displayed))
1243                 self.$(".pager_control_right").addClass("disabled");
1244             else
1245                 self.$(".pager_control_right").removeClass("disabled");
1246         },
1247     
1248         /** Properties changed */
1249     
1250         // Updates the validation button and the "open balance" line
1251         balanceChanged: function() {
1252             var self = this;
1253             var balance = self.get("balance");
1254             self.$(".tbody_open_balance").empty();
1255             // Special case hack : no identified partner
1256             if (self.st_line.has_no_partner) {
1257                 if (Math.abs(balance).toFixed(3) === "0.000") {
1258                     self.$(".button_ok").addClass("oe_highlight");
1259                     self.$(".button_ok").removeAttr("disabled");
1260                     self.$(".button_ok").text("OK");
1261                     self.is_valid = true;
1262                 } else {
1263                     self.$(".button_ok").removeClass("oe_highlight");
1264                     self.$(".button_ok").attr("disabled", "disabled");
1265                     self.$(".button_ok").text("OK");
1266                     self.is_valid = false;
1267                     var debit = (balance > 0 ? self.formatCurrency(balance, self.st_line.currency_id) : "");
1268                     var credit = (balance < 0 ? self.formatCurrency(-1*balance, self.st_line.currency_id) : "");
1269                     var $line = $(QWeb.render("bank_statement_reconciliation_line_open_balance", {
1270                         debit: debit,
1271                         credit: credit,
1272                         account_code: self.map_account_id_code[self.st_line.open_balance_account_id]
1273                     }));
1274                     $line.find('.js_open_balance')[0].innerHTML = _t("Choose counterpart");
1275                     self.$(".tbody_open_balance").append($line);
1276                 }
1277                 return;
1278             }
1279     
1280             if (Math.abs(balance).toFixed(3) === "0.000") {
1281                 self.$(".button_ok").addClass("oe_highlight");
1282                 self.$(".button_ok").text("OK");
1283             } else {
1284                 self.$(".button_ok").removeClass("oe_highlight");
1285                 self.$(".button_ok").text("Keep open");
1286                 var debit = (balance > 0 ? self.formatCurrency(balance, self.st_line.currency_id) : "");
1287                 var credit = (balance < 0 ? self.formatCurrency(-1*balance, self.st_line.currency_id) : "");
1288                 var $line = $(QWeb.render("bank_statement_reconciliation_line_open_balance", {
1289                     debit: debit,
1290                     credit: credit,
1291                     account_code: self.map_account_id_code[self.st_line.open_balance_account_id]
1292                 }));
1293                 self.$(".tbody_open_balance").append($line);
1294             }
1295         },
1296     
1297         modeChanged: function(o, val) {
1298             var self = this;
1299     
1300             self.$(".action_pane.active").removeClass("active");
1301
1302             if (val.oldValue === "create")
1303                 self.addLineBeingEdited();
1304     
1305             if (self.get("mode") === "inactive") {
1306                 self.$(".match").slideUp(self.animation_speed);
1307                 self.$(".create").slideUp(self.animation_speed);
1308                 self.el.dataset.mode = "inactive";
1309     
1310             } else if (self.get("mode") === "match") {
1311                 // TODO : remove this old_animation_speed / new_animation_speed hack
1312                 // when .on handler's returned deferred's no longer lost
1313                 var old_animation_speed = self.animation_speed;
1314                 return $.when(self.updateMatches()).then(function() {
1315                     var new_animation_speed = self.animation_speed;
1316                     self.animation_speed = old_animation_speed;
1317                     if (self.$el.hasClass("no_match")) {
1318                         self.animation_speed = 0;
1319                         self.set("mode", "create");
1320                         return;
1321                     }
1322                     self.$(".match").slideDown(self.animation_speed);
1323                     self.$(".create").slideUp(self.animation_speed);
1324                     self.el.dataset.mode = "match";
1325                     self.animation_speed = new_animation_speed;
1326                 });
1327     
1328             } else if (self.get("mode") === "create") {
1329                 self.initializeCreateForm();
1330                 self.$(".match").slideUp(self.animation_speed);
1331                 self.$(".create").slideDown(self.animation_speed);
1332                 self.el.dataset.mode = "create";
1333             }
1334         },
1335     
1336         pagerChanged: function() {
1337             this.updateMatches();
1338         },
1339     
1340         mvLinesChanged: function() {
1341             var self = this;
1342             // If pager_index is out of range, set it to display the last page
1343             if (self.get("pager_index") !== 0 && self.total_move_lines_num <= (self.get("pager_index") * self.max_move_lines_displayed)) {
1344                 self.set("pager_index", Math.ceil(self.total_move_lines_num/self.max_move_lines_displayed)-1);
1345             }
1346         
1347             // If there is no match to display, disable match view and pass in mode inactive
1348             if (self.total_move_lines_num + self.mv_lines_deselected.length === 0 && self.filter === "") {
1349                 self.$el.addClass("no_match");
1350                 if (self.get("mode") === "match") {
1351                     self.set("mode", "inactive");
1352                 }
1353             } else {
1354                 self.$el.removeClass("no_match");
1355             }
1356
1357             _.each(self.get("mv_lines"), function(line) {
1358                 if (line.partial_reconciliation_siblings_ids.length > 0) {
1359                     var correct_format = _.collect(line.partial_reconciliation_siblings_ids, function(o) { return {'id': o} });
1360                     self.getParent().excludeMoveLines(self, self.partner_id, correct_format);
1361                 }
1362             });
1363
1364             self.updateMatchView();
1365             self.updatePagerControls();
1366         },
1367     
1368         mvLinesSelectedChanged: function(elt, val) {
1369             var self = this;
1370         
1371             var added_lines = _.difference(val.newValue, val.oldValue);
1372             var removed_lines = _.difference(val.oldValue, val.newValue);
1373         
1374             self.getParent().excludeMoveLines(self, self.partner_id, added_lines);
1375             self.getParent().unexcludeMoveLines(self, self.partner_id, removed_lines);
1376         
1377             $.when(self.updateMatches()).then(function(){
1378                 self.updateAccountingViewMatchedLines();
1379                 self.updateBalance();
1380             });
1381         },
1382
1383         // Generic function for updating the line_created_being_edited
1384         formCreateInputChanged: function(elt, val) {
1385             var self = this;
1386             var line_created_being_edited = self.get("line_created_being_edited");
1387             line_created_being_edited[0][elt.corresponding_property] = val.newValue;
1388             line_created_being_edited[0].currency_id = self.st_line.currency_id;
1389     
1390             // Specific cases
1391             if (elt === self.account_id_field)
1392                 line_created_being_edited[0].account_num = self.map_account_id_code[elt.get("value")];
1393     
1394             // Update tax line
1395             var deferred_tax = new $.Deferred();
1396             if (elt === self.tax_id_field || elt === self.amount_field) {
1397                 var amount = self.amount_field.get("value");
1398                 var tax = self.map_tax_id_amount[self.tax_id_field.get("value")];
1399                 if (amount && tax) {
1400                     deferred_tax = $.when(self.model_tax
1401                         .call("compute_for_bank_reconciliation", [self.tax_id_field.get("value"), amount]))
1402                         .then(function(data){
1403                             line_created_being_edited[0].amount_with_tax = line_created_being_edited[0].amount;
1404                             line_created_being_edited[0].amount = (data.total.toFixed(3) === amount.toFixed(3) ? amount : data.total);
1405                             var current_line_cursor = 1;
1406                             $.each(data.taxes, function(index, tax){
1407                                 if (tax.amount !== 0.0) {
1408                                     var tax_account_id = (amount > 0 ? tax.account_collected_id : tax.account_paid_id);
1409                                     tax_account_id = tax_account_id !== false ? tax_account_id: line_created_being_edited[0].account_id;
1410                                     line_created_being_edited[current_line_cursor] = {
1411                                         id: line_created_being_edited[0].id,
1412                                         account_id: tax_account_id,
1413                                         account_num: self.map_account_id_code[tax_account_id],
1414                                         label: tax.name,
1415                                         amount: tax.amount,
1416                                         no_remove_action: true,
1417                                         currency_id: self.st_line.currency_id,
1418                                         is_tax_line: true
1419                                     };
1420                                     current_line_cursor = current_line_cursor + 1;
1421                                 }
1422                             });
1423                         }
1424                     );
1425                 } else {
1426                     line_created_being_edited[0].amount = amount;
1427                     line_created_being_edited.length = 1;
1428                     deferred_tax.resolve();
1429                 }
1430             } else { deferred_tax.resolve(); }
1431     
1432             $.when(deferred_tax).then(function(){
1433                 // Format amounts
1434                 $.each(line_created_being_edited, function(index, val) {
1435                     if (val.amount)
1436                         line_created_being_edited[index].amount_str = self.formatCurrency(Math.abs(val.amount), val.currency_id);
1437                 });
1438                 self.set("line_created_being_edited", line_created_being_edited);
1439                 self.createdLinesChanged(); // TODO For some reason, previous line doesn't trigger change handler
1440             });
1441         },
1442     
1443         createdLinesChanged: function() {
1444             var self = this;
1445             self.updateAccountingViewCreatedLines();
1446             self.updateBalance();
1447     
1448             if (self.islineCreatedBeingEditedValid()) self.$(".add_line").show();
1449             else self.$(".add_line").hide();
1450         },
1451     
1452     
1453         /** Model */
1454     
1455         doPartialReconcileButtonClickHandler: function(e) {
1456             var self = this;
1457     
1458             var line_id = $(e.currentTarget).closest("tr").data("lineid");
1459             var line = _.find(self.get("mv_lines_selected"), function(o) { return o.id == line_id });
1460             self.partialReconcileLine(line);
1461     
1462             $(e.currentTarget).popover('destroy');
1463             self.updateAccountingViewMatchedLines();
1464             self.updateBalance();
1465             e.stopPropagation();
1466         },
1467     
1468         partialReconcileLine: function(line) {
1469             var self = this;
1470             var balance = self.get("balance");
1471             line.initial_amount = line.debit !== 0 ? line.debit : -1 * line.credit;
1472             if (balance < 0) {
1473                 line.debit += balance;
1474                 line.debit_str = self.formatCurrency(line.debit, self.st_line.currency_id);
1475             } else {
1476                 line.credit -= balance;
1477                 line.credit_str = self.formatCurrency(line.credit, self.st_line.currency_id);
1478             }
1479             line.propose_partial_reconcile = false;
1480             line.partial_reconcile = true;
1481         },
1482     
1483         undoPartialReconcileButtonClickHandler: function(e) {
1484             var self = this;
1485     
1486             var line_id = $(e.currentTarget).closest("tr").data("lineid");
1487             var line = _.find(self.get("mv_lines_selected"), function(o) { return o.id == line_id });
1488             self.unpartialReconcileLine(line);
1489     
1490             $(e.currentTarget).popover('destroy');
1491             self.updateAccountingViewMatchedLines();
1492             self.updateBalance();
1493             e.stopPropagation();
1494         },
1495     
1496         unpartialReconcileLine: function(line) {
1497             var self = this;
1498             if (line.initial_amount > 0) {
1499                 line.debit = line.initial_amount;
1500                 line.debit_str = self.formatCurrency(line.debit, self.st_line.currency_id);
1501             } else {
1502                 line.credit = -1 * line.initial_amount;
1503                 line.credit_str = self.formatCurrency(line.credit, self.st_line.currency_id);
1504             }
1505             line.propose_partial_reconcile = true;
1506             line.partial_reconcile = false;
1507         },
1508     
1509         updateBalance: function() {
1510             var self = this;
1511             var mv_lines_selected = self.get("mv_lines_selected");
1512             var lines_selected_num = mv_lines_selected.length;
1513
1514             // Undo partial reconciliation if necessary
1515             if (lines_selected_num !== 1) {
1516                 _.each(mv_lines_selected, function(line) {
1517                     if (line.partial_reconcile === true) self.unpartialReconcileLine(line);
1518                     if (line.propose_partial_reconcile === true) line.propose_partial_reconcile = false;
1519                 });
1520                 self.updateAccountingViewMatchedLines();
1521             }
1522
1523             // Compute balance
1524             var balance = 0;
1525             balance -= self.st_line.amount;
1526             _.each(mv_lines_selected, function(o) {
1527                 balance = balance - o.debit + o.credit;
1528             });
1529             _.each(self.getCreatedLines(), function(o) {
1530                 balance += o.amount;
1531             });
1532             // Dealing with floating-point
1533             balance = Math.round(balance*1000)/1000;
1534             self.set("balance", balance);
1535     
1536             // Propose partial reconciliation if necessary
1537             if (lines_selected_num === 1 &&
1538                 self.st_line.amount * balance > 0 &&
1539                 self.st_line.amount * (mv_lines_selected[0].debit - mv_lines_selected[0].credit) < 0 &&
1540                 ! mv_lines_selected[0].partial_reconcile) {
1541                 
1542                 mv_lines_selected[0].propose_partial_reconcile = true;
1543                 self.updateAccountingViewMatchedLines();
1544             } else if (lines_selected_num === 1) {
1545                 mv_lines_selected[0].propose_partial_reconcile = false;
1546                 self.updateAccountingViewMatchedLines();
1547             }
1548         },
1549
1550         // Loads move lines according to the widget's state
1551         updateMatches: function() {
1552             var self = this;
1553             var deselected_lines_num = self.mv_lines_deselected.length;
1554             var move_lines_num = 0;
1555             var offset = self.get("pager_index") * self.max_move_lines_displayed - deselected_lines_num;
1556             if (offset < 0) offset = 0;
1557             var limit = (self.get("pager_index")+1) * self.max_move_lines_displayed - deselected_lines_num;
1558             if (limit > self.max_move_lines_displayed) limit = self.max_move_lines_displayed;
1559             var excluded_ids = self.getParent().excluded_move_lines_ids[self.partner_id];
1560             var excluded_ids = _.collect(self.get("mv_lines_selected").concat(self.mv_lines_deselected), function(o) { return o.id; });
1561             var globally_excluded_ids = self.getParent().excluded_move_lines_ids[self.partner_id];
1562             if (globally_excluded_ids !== undefined)
1563                 for (var i=0; i<globally_excluded_ids.length; i++)
1564                     if (excluded_ids.indexOf(globally_excluded_ids[i]) === -1)
1565                         excluded_ids.push(globally_excluded_ids[i]);
1566             
1567             var deferred_move_lines;
1568             var move_lines = [];
1569             if (limit > 0) {
1570                 // Load move lines
1571                 deferred_move_lines = self.model_bank_statement_line
1572                     .call("get_move_lines_for_reconciliation_by_statement_line_id", [self.st_line.id, excluded_ids, self.filter, offset, limit])
1573                     .then(function (lines) {
1574                         _.each(lines, function(line) {
1575                             self.decorateMoveLine(line, self.st_line.currency_id);
1576                             move_lines.push(line);
1577                         }, self);
1578                     });
1579             }
1580         
1581             // Fetch the number of move lines corresponding to this statement line and this filter
1582             var deferred_total_move_lines_num = self.model_bank_statement_line
1583                 .call("get_move_lines_for_reconciliation_by_statement_line_id", [self.st_line.id, excluded_ids, self.filter, 0, undefined, true])
1584                 .then(function(num){
1585                     move_lines_num = num;
1586                 });
1587         
1588             return $.when(deferred_move_lines, deferred_total_move_lines_num).then(function(){
1589                 self.total_move_lines_num = move_lines_num + deselected_lines_num;
1590                 self.set("mv_lines", move_lines);
1591             });
1592         },
1593
1594         // Changes the partner_id of the statement_line in the DB and reloads the widget
1595         changePartner: function(partner_id, callback) {
1596             var self = this;
1597             self.is_consistent = false;
1598             return self.model_bank_statement_line
1599                 // Update model
1600                 .call("write", [[self.st_line_id], {'partner_id': partner_id}])
1601                 .then(function () {
1602                     self.do_load_reconciliation_proposition = false; // of the server might set the statement line's partner
1603                     self.animation_speed = 0;
1604                     return $.when(self.restart(self.get("mode"))).then(function(){
1605                         self.do_load_reconciliation_proposition = true;
1606                         self.is_consistent = true;
1607                         self.set("mode", "match");
1608                         if (callback) callback();
1609                     });
1610                 });
1611         },
1612     
1613         // Returns an object that can be passed to process_reconciliation()
1614         prepareSelectedMoveLineForPersisting: function(line) {
1615             return {
1616                 name: line.name,
1617                 debit: line.debit,
1618                 credit: line.credit,
1619                 counterpart_move_line_id: line.id,
1620             };
1621         },
1622     
1623         // idem
1624         prepareCreatedMoveLineForPersisting: function(line) {
1625             var dict = {};
1626             if (dict['account_id'] === undefined)
1627                 dict['account_id'] = line.account_id;
1628             dict['name'] = line.label;
1629             var amount = line.tax_id ? line.amount_with_tax: line.amount;
1630             if (amount > 0) dict['credit'] = amount;
1631             if (amount < 0) dict['debit'] = -1 * amount;
1632             if (line.tax_id) dict['account_tax_id'] = line.tax_id;
1633             if (line.is_tax_line) dict['is_tax_line'] = line.is_tax_line;
1634             if (line.analytic_account_id) dict['analytic_account_id'] = line.analytic_account_id;
1635     
1636             return dict;
1637         },
1638     
1639         // idem
1640         prepareOpenBalanceForPersisting: function() {
1641             var balance = this.get("balance");
1642             var dict = {};
1643     
1644             dict['account_id'] = this.st_line.open_balance_account_id;
1645             dict['name'] = _t("Open balance");
1646             if (balance > 0) dict['debit'] = balance;
1647             if (balance < 0) dict['credit'] = -1*balance;
1648     
1649             return dict;
1650         },
1651
1652         makeMoveLineDicts: function() {
1653             var self = this;
1654             var mv_line_dicts = [];
1655             _.each(self.get("mv_lines_selected"), function(o) { mv_line_dicts.push(self.prepareSelectedMoveLineForPersisting(o)) });
1656             _.each(self.getCreatedLines(), function(o) { mv_line_dicts.push(self.prepareCreatedMoveLineForPersisting(o)) });
1657             if (Math.abs(self.get("balance")).toFixed(3) !== "0.000") mv_line_dicts.push(self.prepareOpenBalanceForPersisting());
1658             return mv_line_dicts;
1659         },
1660     
1661         // Persist data, notify parent view and terminate widget
1662         persistAndDestroy: function(speed) {
1663             var self = this;
1664             speed = (isNaN(speed) ? self.animation_speed : speed);
1665             if (! self.is_consistent) return;
1666
1667             // Sliding animation
1668             var height = self.$el.outerHeight();
1669             var container = $("<div />");
1670             container.css("height", height)
1671                      .css("marginTop", self.$el.css("marginTop"))
1672                      .css("marginBottom", self.$el.css("marginBottom"));
1673             self.$el.wrap(container);
1674             var deferred_animation = self.$el.parent().slideUp(speed*height/150);
1675     
1676             // RPC
1677             return self.model_bank_statement_line
1678                 .call("process_reconciliation", [self.st_line_id, self.makeMoveLineDicts()])
1679                 .then(function () {
1680                     self.getParent().unexcludeMoveLines(self, self.partner_id, self.get("mv_lines_selected"));
1681                     $.each(self.$(".bootstrap_popover"), function(){ $(this).popover('destroy') });
1682                     return $.when(deferred_animation).then(function(){
1683                         self.$el.parent().remove();
1684                         var parent = self.getParent();
1685                         return $.when(self.destroy()).then(function() {
1686                             parent.childValidated(self);
1687                         });
1688                     });
1689                 }, function(){
1690                     self.$el.parent().slideDown(speed*height/150, function(){
1691                         self.$el.unwrap();
1692                     });
1693                 });
1694         },
1695     });
1696
1697     instance.web.views.add('tree_account_reconciliation', 'instance.web.account.ReconciliationListView');
1698     instance.web.account.ReconciliationListView = instance.web.ListView.extend({
1699         init: function() {
1700             this._super.apply(this, arguments);
1701             var self = this;
1702             this.current_partner = null;
1703             this.on('record_selected', this, function() {
1704                 if (self.get_selected_ids().length === 0) {
1705                     self.$(".oe_account_recon_reconcile").attr("disabled", "");
1706                 } else {
1707                     self.$(".oe_account_recon_reconcile").removeAttr("disabled");
1708                 }
1709             });
1710         },
1711         load_list: function() {
1712             var self = this;
1713             var tmp = this._super.apply(this, arguments);
1714             if (this.partners) {
1715                 this.$el.prepend(QWeb.render("AccountReconciliation", {widget: this}));
1716                 this.$(".oe_account_recon_previous").click(function() {
1717                     self.current_partner = (((self.current_partner - 1) % self.partners.length) + self.partners.length) % self.partners.length;
1718                     self.search_by_partner();
1719                 });
1720                 this.$(".oe_account_recon_next").click(function() {
1721                     self.current_partner = (self.current_partner + 1) % self.partners.length;
1722                     self.search_by_partner();
1723                 });
1724                 this.$(".oe_account_recon_reconcile").click(function() {
1725                     self.reconcile();
1726                 });
1727                 this.$(".oe_account_recom_mark_as_reconciled").click(function() {
1728                     self.mark_as_reconciled();
1729                 });
1730             }
1731             return tmp;
1732         },
1733         do_search: function(domain, context, group_by) {
1734             var self = this;
1735             this.last_domain = domain;
1736             this.last_context = context;
1737             this.last_group_by = group_by;
1738             this.old_search = _.bind(this._super, this);
1739             var mod = new instance.web.Model("account.move.line", context, domain);
1740             return mod.call("list_partners_to_reconcile", []).then(function(result) {
1741                 var current = self.current_partner !== null ? self.partners[self.current_partner][0] : null;
1742                 self.partners = result;
1743                 var index = _.find(_.range(self.partners.length), function(el) {
1744                     if (current === self.partners[el][0])
1745                         return true;
1746                 });
1747                 if (index !== undefined)
1748                     self.current_partner = index;
1749                 else
1750                     self.current_partner = self.partners.length == 0 ? null : 0;
1751                 self.search_by_partner();
1752             });
1753         },
1754         search_by_partner: function() {
1755             var self = this;
1756             var fct = function() {
1757                 return self.old_search(new instance.web.CompoundDomain(self.last_domain, 
1758                     [["partner_id", "in", self.current_partner === null ? [] :
1759                     [self.partners[self.current_partner][0]] ]]), self.last_context, self.last_group_by);
1760             };
1761             if (self.current_partner === null) {
1762                 self.last_reconciliation_date = _t("Never");
1763                 return fct();
1764             } else {
1765                 return new instance.web.Model("res.partner").call("read",
1766                     [self.partners[self.current_partner][0], ["last_reconciliation_date"]]).then(function(res) {
1767                     self.last_reconciliation_date = 
1768                         instance.web.format_value(res.last_reconciliation_date, {"type": "datetime"}, _t("Never"));
1769                     return fct();
1770                 });
1771             }
1772         },
1773         reconcile: function() {
1774             var self = this;
1775             var ids = this.get_selected_ids();
1776             if (ids.length === 0) {
1777                 new instance.web.Dialog(this, {
1778                     title: _t("Warning"),
1779                     size: 'medium',
1780                 }, $("<div />").text(_t("You must choose at least one record."))).open();
1781                 return false;
1782             }
1783
1784             new instance.web.Model("ir.model.data").call("get_object_reference", ["account", "action_view_account_move_line_reconcile"]).then(function(result) {
1785                 var additional_context = _.extend({
1786                     active_id: ids[0],
1787                     active_ids: ids,
1788                     active_model: self.model
1789                 });
1790                 return self.rpc("/web/action/load", {
1791                     action_id: result[1],
1792                     context: additional_context
1793                 }).done(function (result) {
1794                     result.context = instance.web.pyeval.eval('contexts', [result.context, additional_context]);
1795                     result.flags = result.flags || {};
1796                     result.flags.new_window = true;
1797                     return self.do_action(result, {
1798                         on_close: function () {
1799                             self.do_search(self.last_domain, self.last_context, self.last_group_by);
1800                         }
1801                     });
1802                 });
1803             });
1804         },
1805         mark_as_reconciled: function() {
1806             var self = this;
1807             var id = self.partners[self.current_partner][0];
1808             new instance.web.Model("res.partner").call("mark_as_reconciled", [[id]]).then(function() {
1809                 self.do_search(self.last_domain, self.last_context, self.last_group_by);
1810             });
1811         },
1812         do_select: function (ids, records) {
1813             this.trigger('record_selected')
1814             this._super.apply(this, arguments);
1815         },
1816     });
1817     
1818 };