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