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;
7 instance.web.account = instance.web.account || {};
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',
14 "click .statement_name span": "statementNameClickHandler",
15 "keyup .change_statement_name_field": "changeStatementNameFieldHandler",
16 "click .change_statement_name_button": "changeStatementButtonClickHandler",
19 init: function(parent, context) {
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");
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
36 // Only for statistical purposes
37 this.lines_reconciled_with_ctrl_enter = 0;
38 this.time_widget_loaded = Date.now();
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 = {};
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 = {
56 corresponding_property: "account_id", // a account.move field name
60 constructor: instance.web.form.FieldMany2One,
62 relation: "account.account",
63 string: _t("Account"),
65 domain: [['type','not in',['view', 'closed', 'consolidation']]],
71 corresponding_property: "label",
75 constructor: instance.web.form.FieldChar,
84 corresponding_property: "tax_id",
88 constructor: instance.web.form.FieldMany2One,
90 relation: "account.tax",
93 domain: [['type_tax_use','in',['purchase', 'all']], ['parent_id', '=', false]],
99 corresponding_property: "amount",
103 constructor: instance.web.form.FieldFloat,
105 string: _t("Amount"),
109 analytic_account_id: {
110 id: "analytic_account_id",
112 corresponding_property: "analytic_account_id",
113 label: _t("Analytic Acc."),
116 group:"analytic.group_analytic_accounting",
117 constructor: instance.web.form.FieldMany2One,
119 relation: "account.analytic.account",
120 string: _t("Analytic Acc."),
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 = [];
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]);
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
142 .filter([['id', '=', self.statement_ids[0]]])
144 .then(function(title){
145 self.title = title.name;
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;
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;
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);
176 // Get statement lines
177 deferred_promises.push(self.model_bank_statement_line
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 });
186 // When queries are done, render template and reconciliation lines
187 return $.when.apply($, deferred_promises).then(function(){
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"));
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 });
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 });
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();
216 // Bind keyboard events TODO : méthode standard ?
217 $("body").on("keypress", function (e) {
218 self.keyboardShortcutsHandler(e);
221 // Render and display
222 self.$el.prepend(QWeb.render("bank_statement_reconciliation", {
224 single_statement: self.single_statement,
225 total_lines: self.already_reconciled_lines+self.st_lines.length
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);
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));
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);
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();
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");
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();
270 changeStatementButtonClickHandler: function() {
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}])
279 self.$(".statement_name span").text(name).show();
280 self.$(".change_statement_name_container").hide();
284 keyboardShortcutsHandler: function(e) {
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++;
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) {
300 _.each(lines, function(o) {
302 line_ids = line_ids.concat(o.partial_reconciliation_siblings_ids);
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;
313 if (! excluded_move_lines_changed)
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])
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();
340 unexcludeMoveLines: function(source_child, partner_id, lines) {
343 _.each(lines, function(o) {
345 line_ids = line_ids.concat(o.partial_reconciliation_siblings_ids);
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)
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();
360 displayReconciliation: function(st_line_id, mode, animate_entrance, initial_data_provided, st_line, reconciliation_proposition) {
362 animate_entrance = (animate_entrance === undefined ? true : animate_entrance);
363 initial_data_provided = (initial_data_provided === undefined ? false : initial_data_provided);
366 st_line_id: st_line_id,
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,
373 var widget = new instance.web.account.bankStatementReconciliationLine(self, context);
374 return widget.appendTo(self.$(".reconciliation_lines_container"));
377 childValidated: function(child) {
380 self.reconciled_lines++;
381 self.updateProgressbar();
382 self.doReloadMenuReconciliation();
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');
388 // Congratulate the user if the work is done
389 if (self.reconciled_lines === self.st_lines.length) {
390 self.displayDoneMessage();
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");
402 goBackToStatementsTreeView: function() {
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;
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);
424 instance.web.Home(self);
428 displayDoneMessage: function() {
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 = [];
436 if (sec_taken/60 >= 1) time_taken = Math.floor(sec_taken/60) +"' "+ sec_taken%60 +"''";
437 else time_taken = sec_taken%60 +" seconds";
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>";
443 if (self.lines_reconciled_with_ctrl_enter === self.reconciled_lines)
445 title: _t("Efficiency at its finest"),
446 desc: _t("Only use the ctrl-enter shortcut to validate reconciliations."),
447 icon: "fa-keyboard-o"}
450 if (sec_per_item < 5)
452 title: _t("Fast reconciler"),
453 desc: _t("Take on average less than 5 seconds to reconcile a transaction."),
458 self.$(".protip").hide();
459 self.$(".oe_form_sheet").append(QWeb.render("bank_statement_reconciliation_done_message", {
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,
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");
476 // Make it interactive
477 self.$(".achievement").popover({'placement': 'top', 'container': self.el, 'trigger': 'hover'});
479 if (self.$(".button_back_to_statement").length !== 0) {
480 self.$(".button_back_to_statement").click(function() {
481 self.goBackToStatementsTreeView();
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]])
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])
499 self.goBackToStatementsTreeView();
501 self.$(".button_close_statement").removeAttr("disabled");
509 updateProgressbar: function() {
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);
519 /* reloads the needaction badge */
520 doReloadMenuReconciliation: function () {
521 var menu = instance.webclient.menu;
522 if (!menu || !this.reconciliation_menu_id) {
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");
533 instance.web.account.bankStatementReconciliationLine = instance.web.Widget.extend({
534 className: 'oe_bank_statement_reconciliation_line',
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",
552 init: function(parent, context) {
555 this.formatCurrency = this.getParent().formatCurrency;
556 if (context.initial_data_provided) {
558 _.each(context.reconciliation_proposition, function(line) {
559 this.decorateMoveLine(line, context.st_line.currency_id);
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);
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);
571 this.set("mv_lines_selected", []);
572 this.st_line = undefined;
573 this.partner_id = undefined;
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
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;
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);
615 return self._super().then(function() {
616 // no animation while loading
617 self.animation_speed = 0;
618 self.aestetic_animation_speed = 0;
620 self.is_consistent = false;
621 if (self.context.animate_entrance) {
625 return $.when(self.loadData()).then(function(){
626 return $.when(self.render()).then(function(){
627 self.is_consistent = true;
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);
639 loadData: function() {
641 if (self.context.initial_data_provided)
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);
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] = [];
661 _.each(data[0].reconciliation_proposition, function(line) {
662 self.decorateMoveLine(line, self.st_line.currency_id);
665 self.set("mv_lines_selected", self.get("mv_lines_selected").concat(mv_lines));
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", {
677 mode: self.context.mode,
678 presets: presets_array
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);
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();
712 restart: function(mode) {
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') });
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;
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});
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);
746 /* create form widgets, append them to the dom and bind their events handlers */
747 createFormWidgets: function() {
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 });
757 var dataset = new instance.web.DataSet(this, "account.account", self.context);
760 attrs: { string: "Stéphanie de Monaco", version: "7.0", class: "oe_form_container" },
765 var field_manager = new instance.web.FormView (
766 this, dataset, false, {
767 initial_mode: 'edit',
768 disable_autofocus: false,
773 field_manager.load_form(dataset);
775 // fields default properties
776 var Default_field = function() {
780 this.readonly = false;
781 this.required = true;
782 this.selectable = true;
786 var Default_node = function(field_name) {
789 this.required = true;
792 modifiers: '{"required":true}',
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);
803 field_manager.fields_view.fields["change_partner"] = _.extend(new Default_field(), {
804 relation: "res.partner",
805 string: _t("Partner"),
807 domain: [['parent_id','=',false], '|', ['customer','=',true], ['supplier','=',true]],
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();
815 field_widget.destroy();
817 delete self[obj_key];
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];
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);
834 // on update : change the last created line
835 field.corresponding_property = field_data.corresponding_property;
836 field.on("change:value", self, self.formCreateInputChanged);
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);
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));
848 field.$el.find("input").attr("tabindex", field_data.tabindex);
850 // Hide the field if group not OK
851 if (field_data.group !== undefined) {
852 var target = $field_container;
855 .call("has_group", [field_data.group])
856 .then(hideGroupResponseClosureFactory(field, target, (field_data.id+"_field")));
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());
867 self.change_partner_field.$el.find("input").attr("placeholder", _t("Select Partner"));
869 field_manager.do_show();
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});
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;
896 bindPopoverTo: function(el) {
898 $(el).addClass("bootstrap_popover");
901 'container': self.el,
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
916 /* returns the created lines, plus the ones being edited if valid */
917 getCreatedLines: function() {
919 var created_lines = self.get("lines_created").slice();
920 if (self.islineCreatedBeingEditedValid())
921 return created_lines.concat(self.get("line_created_being_edited"));
923 return created_lines;
928 moveLineClickHandler: function(e) {
930 if (e.currentTarget.dataset.selected === "true") self.deselectMoveLine(e.currentTarget);
931 else self.selectMoveLine(e.currentTarget);
934 selectMoveLine: function(mv_line) {
936 var line_id = mv_line.dataset.lineid;
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});
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 });
944 if (! line) return; // If no line found, we've got a syncing problem (let's turn a deaf ear)
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"),
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();
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);
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]);
970 deselectMoveLine: function(mv_line) {
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)
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 });
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;
984 self.$el.removeClass("no_match");
985 self.set("mode", "match");
986 self.set("mv_lines_selected", mv_lines_selected);
989 // $(mv_line).attr('data-selected','false');
990 // this.set("mv_lines", this.get("mv_lines").concat(line));
991 // this.getParent().unexcludeMoveLines([line_id]);
994 /** Matches pagination */
996 pagerControlLeftHandler: function() {
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 );
1003 pagerControlRightHandler: function() {
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 );
1011 filterHandler: function() {
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);
1022 initializeCreateForm: function() {
1025 _.each(self.create_form, function(field) {
1026 field.set("value", false);
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();
1033 addLineBeingEdited: function() {
1035 if (! self.islineCreatedBeingEditedValid()) return;
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}]);
1042 self.initializeCreateForm();
1045 removeLine: function($line) {
1047 var line_id = $line.data("lineid");
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();
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"));
1057 presetClickHandler: function(e) {
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);
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]);
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);
1088 initialLineClickHandler: function() {
1090 if (self.get("mode") === "match") {
1091 self.set("mode", "inactive");
1093 self.set("mode", "match");
1097 lineOpenBalanceClickHandler: function() {
1099 if (self.get("mode") === "create") {
1100 self.addLineBeingEdited();
1101 self.set("mode", "match");
1103 self.set("mode", "create");
1107 removePartnerClickHandler: function() {
1109 // Delete statement line's partner
1110 return self.changePartner('', function() {
1111 self.$(".partner_name").hide();
1112 self.$(".change_partner_container").show();
1117 /** Views updating */
1119 updateAccountingViewMatchedLines: function() {
1121 $.each(self.$(".tbody_matched_lines .bootstrap_popover"), function(){ $(this).popover('destroy') });
1122 self.$(".tbody_matched_lines").empty();
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);
1133 updateAccountingViewCreatedLines: function() {
1135 $.each(self.$(".tbody_created_lines .bootstrap_popover"), function(){ $(this).popover('destroy') });
1136 self.$(".tbody_created_lines").empty();
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") });
1149 updateMatchView: function() {
1151 var table = self.$(".match table");
1152 var nothing_displayed = true;
1154 // Display move lines
1155 $.each(self.$(".match table .bootstrap_popover"), function(){ $(this).popover('destroy') });
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;
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;
1173 if (nothing_displayed && this.filter !== "")
1174 table.append(QWeb.render("filter_no_match", {filter_str: self.filter}));
1177 updatePagerControls: function() {
1180 if (self.get("pager_index") === 0)
1181 self.$(".pager_control_left").addClass("disabled");
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");
1187 self.$(".pager_control_right").removeClass("disabled");
1190 /** Properties changed */
1192 // Updates the validation button and the "open balance" line
1193 balanceChanged: function() {
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;
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", {
1214 account_code: self.map_account_id_code[self.st_line.open_balance_account_id]
1216 $line.find('.js_open_balance')[0].innerHTML = _t("Choose counterpart");
1217 self.$(".tbody_open_balance").append($line);
1222 if (Math.abs(balance).toFixed(3) === "0.000") {
1223 self.$(".button_ok").addClass("oe_highlight");
1224 self.$(".button_ok").text("OK");
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", {
1233 account_code: self.map_account_id_code[self.st_line.open_balance_account_id]
1235 self.$(".tbody_open_balance").append($line);
1239 modeChanged: function() {
1242 self.$(".action_pane.active").removeClass("active");
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";
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";
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";
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");
1272 self.$(".match").slideDown(self.animation_speed);
1273 self.$(".create").slideUp(self.animation_speed);
1274 self.el.dataset.mode = "match";
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";
1285 pagerChanged: function() {
1286 this.updateMatches();
1289 mvLinesChanged: function() {
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);
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");
1303 self.$el.removeClass("no_match");
1306 self.updateMatchView();
1307 self.updatePagerControls();
1310 mvLinesSelectedChanged: function(elt, val) {
1313 var added_lines = _.difference(val.newValue, val.oldValue);
1314 var removed_lines = _.difference(val.oldValue, val.newValue);
1316 self.getParent().excludeMoveLines(self, self.partner_id, added_lines);
1317 self.getParent().unexcludeMoveLines(self, self.partner_id, removed_lines);
1319 $.when(self.updateMatches()).then(function(){
1320 self.updateAccountingViewMatchedLines();
1321 self.updateBalance();
1325 // Generic function for updating the line_created_being_edited
1326 formCreateInputChanged: function(elt, val) {
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;
1333 if (elt === self.account_id_field)
1334 line_created_being_edited[0].account_num = self.map_account_id_code[elt.get("value")];
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],
1358 no_remove_action: true,
1359 currency_id: self.st_line.currency_id,
1362 current_line_cursor = current_line_cursor + 1;
1368 line_created_being_edited[0].amount = amount;
1369 line_created_being_edited.length = 1;
1370 deferred_tax.resolve();
1372 } else { deferred_tax.resolve(); }
1374 $.when(deferred_tax).then(function(){
1376 $.each(line_created_being_edited, function(index, val) {
1378 line_created_being_edited[index].amount_str = self.formatCurrency(Math.abs(val.amount), val.currency_id);
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
1385 createdLinesChanged: function() {
1387 self.updateAccountingViewCreatedLines();
1388 self.updateBalance();
1390 if (self.islineCreatedBeingEditedValid()) self.$(".add_line").show();
1391 else self.$(".add_line").hide();
1397 doPartialReconcileButtonClickHandler: function(e) {
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);
1404 $(e.currentTarget).popover('destroy');
1405 self.updateAccountingViewMatchedLines();
1406 self.updateBalance();
1407 e.stopPropagation();
1410 partialReconcileLine: function(line) {
1412 var balance = self.get("balance");
1413 line.initial_amount = line.debit !== 0 ? line.debit : -1 * line.credit;
1415 line.debit += balance;
1416 line.debit_str = self.formatCurrency(line.debit, self.st_line.currency_id);
1418 line.credit -= balance;
1419 line.credit_str = self.formatCurrency(line.credit, self.st_line.currency_id);
1421 line.propose_partial_reconcile = false;
1422 line.partial_reconcile = true;
1425 undoPartialReconcileButtonClickHandler: function(e) {
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);
1432 $(e.currentTarget).popover('destroy');
1433 self.updateAccountingViewMatchedLines();
1434 self.updateBalance();
1435 e.stopPropagation();
1438 unpartialReconcileLine: function(line) {
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);
1444 line.credit = -1 * line.initial_amount;
1445 line.credit_str = self.formatCurrency(line.credit, self.st_line.currency_id);
1447 line.propose_partial_reconcile = true;
1448 line.partial_reconcile = false;
1451 updateBalance: function() {
1453 var mv_lines_selected = self.get("mv_lines_selected");
1454 var lines_selected_num = mv_lines_selected.length;
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;
1462 self.updateAccountingViewMatchedLines();
1467 balance -= self.st_line.amount;
1468 _.each(mv_lines_selected, function(o) {
1469 balance = balance - o.debit + o.credit;
1471 _.each(self.getCreatedLines(), function(o) {
1472 balance += o.amount;
1474 // Dealing with floating-point
1475 balance = Math.round(balance*1000)/1000;
1476 self.set("balance", balance);
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) {
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();
1492 // Loads move lines according to the widget's state
1493 updateMatches: function() {
1494 if (this.st_line.has_no_partner) return;
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);
1508 var deferred_move_lines;
1509 var 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);
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;
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);
1535 // Changes the partner_id of the statement_line in the DB and reloads the widget
1536 changePartner: function(partner_id, callback) {
1538 self.is_consistent = false;
1539 return self.model_bank_statement_line
1541 .call("write", [[self.st_line_id], {'partner_id': partner_id}])
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();
1553 // Returns an object that can be passed to process_reconciliation()
1554 prepareSelectedMoveLineForPersisting: function(line) {
1558 credit: line.credit,
1559 counterpart_move_line_id: line.id,
1564 prepareCreatedMoveLineForPersisting: function(line) {
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;
1580 prepareOpenBalanceForPersisting: function() {
1581 var balance = this.get("balance");
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;
1592 // Persist data, notify parent view and terminate widget
1593 persistAndDestroy: function(speed) {
1595 speed = (isNaN(speed) ? self.animation_speed : speed);
1596 if (! self.is_consistent) return;
1598 self.getParent().unexcludeMoveLines(self, self.partner_id, self.get("mv_lines_selected"));
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);
1610 return $.when(self.makeRPCForPersisting())
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);
1621 self.$el.parent().slideDown(speed*height/150, function(){
1627 makeRPCForPersisting: function() {
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]);
1638 instance.web.views.add('tree_account_reconciliation', 'instance.web.account.ReconciliationListView');
1639 instance.web.account.ReconciliationListView = instance.web.ListView.extend({
1641 this._super.apply(this, arguments);
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", "");
1648 self.$(".oe_account_recon_reconcile").removeAttr("disabled");
1652 load_list: function() {
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();
1661 this.$(".oe_account_recon_next").click(function() {
1662 self.current_partner = (self.current_partner + 1) % self.partners.length;
1663 self.search_by_partner();
1665 this.$(".oe_account_recon_reconcile").click(function() {
1668 this.$(".oe_account_recom_mark_as_reconciled").click(function() {
1669 self.mark_as_reconciled();
1674 do_search: function(domain, context, group_by) {
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])
1688 if (index !== undefined)
1689 self.current_partner = index;
1691 self.current_partner = self.partners.length == 0 ? null : 0;
1692 self.search_by_partner();
1695 search_by_partner: function() {
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);
1702 if (self.current_partner === null) {
1703 self.last_reconciliation_date = _t("Never");
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"));
1714 reconcile: function() {
1716 var ids = this.get_selected_ids();
1717 if (ids.length === 0) {
1718 new instance.web.Dialog(this, {
1719 title: _t("Warning"),
1721 }, $("<div />").text(_t("You must choose at least one record."))).open();
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({
1729 active_model: self.model
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);
1746 mark_as_reconciled: function() {
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);
1753 do_select: function (ids, records) {
1754 this.trigger('record_selected')
1755 this._super.apply(this, arguments);