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