diff --git a/hr_expense_tax_adjust/README.rst b/hr_expense_tax_adjust/README.rst new file mode 100644 index 00000000..943ea418 --- /dev/null +++ b/hr_expense_tax_adjust/README.rst @@ -0,0 +1,88 @@ +====================== +Expense Tax Adjustment +====================== + +.. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |badge1| image:: https://img.shields.io/badge/maturity-Alpha-red.png + :target: https://odoo-community.org/page/development-status + :alt: Alpha +.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png + :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html + :alt: License: AGPL-3 +.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fhr--expense-lightgray.png?logo=github + :target: https://github.com/OCA/hr-expense/tree/14.0/hr_expense_tax_adjust + :alt: OCA/hr-expense +.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png + :target: https://translation.odoo-community.org/projects/hr-expense-14-0/hr-expense-14-0-hr_expense_tax_adjust + :alt: Translate me on Weblate +.. |badge5| image:: https://img.shields.io/badge/runbot-Try%20me-875A7B.png + :target: https://runbot.odoo-community.org/runbot/289/14.0 + :alt: Try me on Runbot + +|badge1| |badge2| |badge3| |badge4| |badge5| + +This module allows to edit tax amount before Post Journal Entries on Expense Report. + +.. IMPORTANT:: + This is an alpha version, the data model and design can change at any time without warning. + Only for development or testing purpose, do not use in production. + `More details on development status `_ + +**Table of contents** + +.. contents:: + :local: + +Bug Tracker +=========== + +Bugs are tracked on `GitHub Issues `_. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us smashing it by providing a detailed and welcomed +`feedback `_. + +Do not contact contributors directly about support or help with technical issues. + +Credits +======= + +Authors +~~~~~~~ + +* Ecosoft + +Contributors +~~~~~~~~~~~~ + +* `Ecosoft `__: + + * Pimolnat Suntian + +Maintainers +~~~~~~~~~~~ + +This module is maintained by the OCA. + +.. image:: https://odoo-community.org/logo.png + :alt: Odoo Community Association + :target: https://odoo-community.org + +OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use. + +.. |maintainer-ps-tubtim| image:: https://github.com/ps-tubtim.png?size=40px + :target: https://github.com/ps-tubtim + :alt: ps-tubtim + +Current `maintainer `__: + +|maintainer-ps-tubtim| + +This module is part of the `OCA/hr-expense `_ project on GitHub. + +You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/hr_expense_tax_adjust/__init__.py b/hr_expense_tax_adjust/__init__.py new file mode 100644 index 00000000..69f7babd --- /dev/null +++ b/hr_expense_tax_adjust/__init__.py @@ -0,0 +1,3 @@ +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +from . import models diff --git a/hr_expense_tax_adjust/__manifest__.py b/hr_expense_tax_adjust/__manifest__.py new file mode 100644 index 00000000..9577d8a2 --- /dev/null +++ b/hr_expense_tax_adjust/__manifest__.py @@ -0,0 +1,23 @@ +# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +{ + "name": "Expense Tax Adjustment", + "version": "14.0.1.0.0", + "author": "Ecosoft, Odoo Community Association (OCA)", + "summary": "Allow to edit tax amount on expenses", + "website": "https://github.com/OCA/hr-expense", + "license": "AGPL-3", + "depends": ["hr_expense"], + "category": "Human Resources/Expenses", + "data": [ + "views/asset_backend.xml", + "views/hr_expense_views.xml", + ], + "qweb": [ + "static/src/xml/tax_group.xml", + ], + "installable": True, + "maintainers": ["ps-tubtim"], + "development_status": "Alpha", +} diff --git a/hr_expense_tax_adjust/models/__init__.py b/hr_expense_tax_adjust/models/__init__.py new file mode 100644 index 00000000..ced2eb18 --- /dev/null +++ b/hr_expense_tax_adjust/models/__init__.py @@ -0,0 +1,3 @@ +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +from . import hr_expense diff --git a/hr_expense_tax_adjust/models/hr_expense.py b/hr_expense_tax_adjust/models/hr_expense.py new file mode 100644 index 00000000..5aecbfb4 --- /dev/null +++ b/hr_expense_tax_adjust/models/hr_expense.py @@ -0,0 +1,215 @@ +# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +import ast +from collections import defaultdict + +from odoo import api, fields, models +from odoo.tools.misc import formatLang + + +class HrExpense(models.Model): + _inherit = "hr.expense" + + tax_amount = fields.Float( + digits="Account", + string="Tax", + compute="_compute_tax_amount", + store=True, + readonly=False, + ) + amount_by_group = fields.Binary( + string="Tax amount by group", + compute="_compute_amount_by_group", + help="Edit Tax amounts if you encounter rounding issues.", + ) + amount_by_group_txt = fields.Text( + string="Tax Amount Text", + default="[]", + compute="_compute_expense_taxes_by_group", + store=True, + readonly=False, + ) + editable_tax_adjustment = fields.Boolean( + compute="_compute_editable_tax_adjustment", + string="Edit Tax Adjustment", + ) + + @api.depends("state", "sheet_id.state") + def _compute_editable_tax_adjustment(self): + """Editable tax adjustment on expense state + 'Draft', 'Submited' and 'Approved'""" + for rec in self: + rec.editable_tax_adjustment = ( + ( + rec.sheet_id.state in ["draft", "submit", "approve"] + or rec.state == "draft" + ) + and True + or False + ) + + @api.depends("amount_by_group_txt") + def _compute_amount_by_group(self): + for expense in self: + expense.amount_by_group = ast.literal_eval( + expense.amount_by_group_txt or "[]" + ) + + @api.depends("amount_by_group") + def _compute_tax_amount(self): + for expense in self: + tax_amount = 0.0 + for amount_line in expense.amount_by_group: + tax_amount += amount_line[1] + expense.tax_amount = tax_amount + + @api.depends("quantity", "unit_amount", "tax_ids", "currency_id", "tax_amount") + def _compute_amount(self): + """Override the `_compute_amount()`.""" + self._compute_tax_amount() # Make sure that tax_amount updated + for expense in self: + taxes = expense.tax_ids.with_context(round=True).compute_all( + expense.unit_amount, + expense.currency_id, + expense.quantity, + expense.product_id, + expense.employee_id.user_id.partner_id, + ) + expense.untaxed_amount = taxes.get("total_excluded", 0.0) + expense.total_amount = expense.untaxed_amount + expense.tax_amount + + @api.depends("quantity", "unit_amount", "tax_ids", "currency_id", "employee_id") + def _compute_expense_taxes_by_group(self): + for expense in self: + partner_id = expense.employee_id.user_id.partner_id + lang_env = expense.with_context(lang=partner_id.lang).env + taxes = expense.tax_ids.with_context(round=True).compute_all( + expense.unit_amount, + expense.currency_id, + expense.quantity, + expense.product_id, + expense.employee_id.user_id.partner_id, + ) + base_amount = taxes.get("total_excluded", 0.0) + + tax_group_mapping = defaultdict( + lambda: { + "base_amount": base_amount, + "tax_amount": 0.0, + "tax_name": "", + } + ) + + for tax in expense.tax_ids.flatten_taxes_hierarchy(): + tax_group_vals = tax_group_mapping[tax.id] + tax_group_vals["tax_name"] = tax.name + for tax_line in taxes["taxes"]: + tax_id = tax_line["id"] + tax_group_vals = tax_group_mapping[tax_id] + tax_group_vals["tax_amount"] += tax_line["amount"] + amount_by_group = [] + for tax_group in tax_group_mapping.keys(): + tax_group_vals = tax_group_mapping[tax_group] + if isinstance(tax_group, models.NewId): + tax_group = tax_group.origin + amount_by_group_str = "['{}', {}, {}, '{}', '{}', {}, {}]".format( + tax_group_vals["tax_name"], + tax_group_vals["tax_amount"], + tax_group_vals["base_amount"], + formatLang( + lang_env, + tax_group_vals["tax_amount"], + currency_obj=expense.currency_id, + ), + formatLang( + lang_env, + tax_group_vals["base_amount"], + currency_obj=expense.currency_id, + ), + len(tax_group_mapping), + tax_group, + ) + amount_by_group.append(amount_by_group_str) + expense.amount_by_group_txt = "[{}]".format(", ".join(amount_by_group)) + + # def _get_expense_account_destination(self): + # self.ensure_one() + # # support module `hr_expense_advance_clearing` for case clearing + # if ( + # self.sheet_id._fields.get("advance_sheet_id", False) + # and self.sheet_id.advance_sheet_id + # ): + # account_dest = self.env["account.account"] + # if not self.employee_id.sudo().address_home_id: + # raise UserError( + # _( + # "No Home Address found for the employee %s, please configure one." + # ) + # % (self.employee_id.name) + # ) + # partner = self.employee_id.sudo().address_home_id.with_company( + # self.company_id + # ) + # # clearing is reverse payable to receivable + # account_dest = ( + # partner.property_account_receivable_id.id + # or partner.parent_id.property_account_receivable_id.id + # ) + # return account_dest + # return super()._get_expense_account_destination() + + def _get_account_move_line_values(self): + move_line_values_by_expense = super()._get_account_move_line_values() + for expense in self: + # Prepare data + account_dst = expense._get_expense_account_destination() + account_date = ( + expense.sheet_id.accounting_date + or expense.date + or fields.Date.context_today(expense) + ) + company_currency = expense.company_id.currency_id + new_tax_amount = 0.0 + old_tax_amount = 0.0 + amount_by_group = dict() + for amount_line in expense.amount_by_group: + amount_by_group[amount_line[0]] = amount_line[1] + + # Update move_line_values_by_expense + for line in move_line_values_by_expense[expense.id]: + # taxes move lines + if line["name"] in amount_by_group.keys(): + tax = amount_by_group[line["name"]] + balance = expense.currency_id._convert( + tax, company_currency, expense.company_id, account_date + ) + old_tax_amount += line["amount_currency"] + new_tax_amount += balance + line.update( + { + "debit": balance if balance > 0 else 0, + "credit": -balance if balance < 0 else 0, + "amount_currency": balance, + } + ) + # destination move line + if line["account_id"] == account_dst: + debit = line["debit"] or 0 + credit = line["credit"] or 0 + amount = debit - credit + old_tax_amount = expense.currency_id._convert( + old_tax_amount, + company_currency, + expense.company_id, + account_date, + ) + balance = amount + (old_tax_amount - new_tax_amount) + line.update( + { + "debit": balance if balance > 0 else 0, + "credit": -balance if balance < 0 else 0, + "amount_currency": balance, + } + ) + return move_line_values_by_expense diff --git a/hr_expense_tax_adjust/readme/CONTRIBUTORS.rst b/hr_expense_tax_adjust/readme/CONTRIBUTORS.rst new file mode 100644 index 00000000..ea63aa7b --- /dev/null +++ b/hr_expense_tax_adjust/readme/CONTRIBUTORS.rst @@ -0,0 +1,3 @@ +* `Ecosoft `__: + + * Pimolnat Suntian diff --git a/hr_expense_tax_adjust/readme/DESCRIPTION.rst b/hr_expense_tax_adjust/readme/DESCRIPTION.rst new file mode 100644 index 00000000..75cbaa0f --- /dev/null +++ b/hr_expense_tax_adjust/readme/DESCRIPTION.rst @@ -0,0 +1 @@ +This module allows to edit tax amount before Post Journal Entries on Expense Report. diff --git a/hr_expense_tax_adjust/static/description/icon.png b/hr_expense_tax_adjust/static/description/icon.png new file mode 100644 index 00000000..3a0328b5 Binary files /dev/null and b/hr_expense_tax_adjust/static/description/icon.png differ diff --git a/hr_expense_tax_adjust/static/description/index.html b/hr_expense_tax_adjust/static/description/index.html new file mode 100644 index 00000000..7ce650c3 --- /dev/null +++ b/hr_expense_tax_adjust/static/description/index.html @@ -0,0 +1,430 @@ + + + + + + +Expense Tax Adjustment + + + +
+

Expense Tax Adjustment

+ + +

Alpha License: AGPL-3 OCA/hr-expense Translate me on Weblate Try me on Runbot

+

This module allows to edit tax amount before Post Journal Entries on Expense Report.

+
+

Important

+

This is an alpha version, the data model and design can change at any time without warning. +Only for development or testing purpose, do not use in production. +More details on development status

+
+

Table of contents

+ +
+

Bug Tracker

+

Bugs are tracked on GitHub Issues. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us smashing it by providing a detailed and welcomed +feedback.

+

Do not contact contributors directly about support or help with technical issues.

+
+
+

Credits

+
+

Authors

+
    +
  • Ecosoft
  • +
+
+
+

Contributors

+ +
+
+

Maintainers

+

This module is maintained by the OCA.

+Odoo Community Association +

OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use.

+

Current maintainer:

+

ps-tubtim

+

This module is part of the OCA/hr-expense project on GitHub.

+

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

+
+
+
+ + diff --git a/hr_expense_tax_adjust/static/src/js/tax_group.js b/hr_expense_tax_adjust/static/src/js/tax_group.js new file mode 100644 index 00000000..460ce73d --- /dev/null +++ b/hr_expense_tax_adjust/static/src/js/tax_group.js @@ -0,0 +1,189 @@ +odoo.define("hr_expense_tax_adjust.ExpenseTaxGroupCustomField", function (require) { + "use strict"; + + var core = require("web.core"); + var session = require("web.session"); + var fieldRegistry = require("web.field_registry"); + var AbstractField = require("web.AbstractField"); + var fieldUtils = require("web.field_utils"); + var QWeb = core.qweb; + + var ExpenseTaxGroupCustomField = AbstractField.extend({ + events: { + "click .tax_group_edit": "_onClick", + "keydown .oe_tax_group_editable .tax_group_edit_input input": "_onKeydown", + "blur .oe_tax_group_editable .tax_group_edit_input input": "_onBlur", + }, + + // -------------------------------------------------------------------------- + // Private + // -------------------------------------------------------------------------- + + /** + * This method is called by "_setTaxGroups". It is + * responsible for calculating taxes based on + * tax groups and triggering an event to + * notify the ORM of a change. + * + * @param {Id} taxGroupId + * @param {Float} newValue + * @param {Object} currency + */ + _changeTaxValueByTaxGroup: function (taxGroupId, newValue, currency) { + var self = this; + var amount_by_group_txt = this.record.data.amount_by_group_txt; + var amount_by_group = amount_by_group_txt + .replace(/\[|\]|'|"/g, "") + .split(", "); + var new_amount_by_group = []; + var lst_amount = "[]"; + var base_amount = 0.0; + var tax_amount = 0.0; + var tax_amount_sign = ""; + var n = 0; + console.log(amount_by_group_txt); + console.log(amount_by_group); + for (var i = 0, len = amount_by_group.length; i < len / 7; i++) { + n = i * 7; + tax_amount = fieldUtils.parse.float(amount_by_group[n + 1]); + base_amount = fieldUtils.parse.float(amount_by_group[n + 2]); + tax_amount_sign = amount_by_group[n + 3]; + if (amount_by_group[n + 6] == taxGroupId) { + // Update tax_amount + tax_amount = newValue; + // Update tax_amount_sign + var formatOptions = { + currency: currency, + forceString: true, + }; + tax_amount_sign = fieldUtils.format.monetary( + tax_amount, + {}, + formatOptions + ); + } + lst_amount = `['${ + amount_by_group[n] + }', ${tax_amount}, ${base_amount}, '${tax_amount_sign}', '${ + amount_by_group[n + 4] + }', ${amount_by_group[n + 5]}, ${amount_by_group[n + 6]}]`; + new_amount_by_group.push(lst_amount); + } + var new_amount_by_group_str = new_amount_by_group.join(", "); + var new_amount_by_group_txt = `[${new_amount_by_group_str}]`; + // Trigger ORM + self.trigger_up("field_changed", { + dataPointID: self.record.id, + changes: {amount_by_group_txt: new_amount_by_group_txt}, + }); + }, + + /** + * This method is part of the widget life cycle and allows you to render + * the widget. + * + * @private + * @override + */ + _render: function () { + var self = this; + // Display the pencil and allow the event to click and edit only on expense that are not posted and in edit mode. + // since the field is readonly its mode will always be readonly. Therefore we have to use a trick by checking the + // formRenderer (the parent) and check if it is in edit in order to know the correct mode. + var displayEditWidget = + this.record.data.editable_tax_adjustment && + this.getParent().mode === "edit"; + this.$el.html( + $( + QWeb.render("ExpenseAccountTaxGroupTemplate", { + lines: self.value, + displayEditWidget: displayEditWidget, + }) + ) + ); + }, + + // -------------------------------------------------------------------------- + // Handler + // -------------------------------------------------------------------------- + + /** + * This method is called when the user is in edit mode and + * leaves the field. Then, we execute the code that + * modifies the information. + * + * @param {event} ev + * @returns {Object} + */ + _onBlur: function (ev) { + ev.preventDefault(); + var $input = $(ev.target); + var newValue = $input.val(); + var currency = session.get_currency(this.record.data.currency_id.data.id); + try { + // Need a float for format the value. + newValue = fieldUtils.parse.float(newValue); + // Return a string rounded to currency precision + newValue = fieldUtils.format.float(newValue, null, { + digits: currency.digits, + }); + // Convert back to Float to compare with oldValue to know if value has changed + newValue = fieldUtils.parse.float(newValue); + } catch (err) { + $input.addClass("o_field_invalid"); + return; + } + var oldValue = $input.data("originalValue"); + if (newValue === oldValue || newValue === 0) { + return this._render(); + } + var taxGroupId = $input + .parents(".oe_tax_group_editable") + .data("taxGroupId"); + this._changeTaxValueByTaxGroup(taxGroupId, newValue, currency); + }, + + /** + * This method is called when the user clicks on a specific . + * it will hide the edit button and display the field to be edited. + * + * @param {event} ev + */ + _onClick: function (ev) { + ev.preventDefault(); + var $taxGroupElement = $(ev.target).parents(".oe_tax_group_editable"); + // Show input and hide previous element + $taxGroupElement.find(".tax_group_edit").addClass("d-none"); + $taxGroupElement.find(".tax_group_edit_input").removeClass("d-none"); + var $input = $taxGroupElement.find(".tax_group_edit_input input"); + // Get original value and display it in user locale in the input + var formatedOriginalValue = fieldUtils.format.float( + $input.data("originalValue"), + {}, + {} + ); + // Focus the input + $input.focus(); + // Add value in user locale to the input + $input.val(formatedOriginalValue); + }, + + /** + * This method is called when the user is in edit mode and pressing + * a key on his keyboard. If this key corresponds to ENTER or TAB, + * the code that modifies the information is executed. + * + * @param {event} ev + */ + _onKeydown: function (ev) { + switch (ev.which) { + // Trigger only if the user clicks on ENTER or on TAB. + case $.ui.keyCode.ENTER: + case $.ui.keyCode.TAB: + // Trigger blur to prevent the code being executed twice + $(ev.target).blur(); + } + }, + }); + fieldRegistry.add("expense-tax-group-custom-field", ExpenseTaxGroupCustomField); +}); diff --git a/hr_expense_tax_adjust/static/src/xml/tax_group.xml b/hr_expense_tax_adjust/static/src/xml/tax_group.xml new file mode 100644 index 00000000..d4510c42 --- /dev/null +++ b/hr_expense_tax_adjust/static/src/xml/tax_group.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + diff --git a/hr_expense_tax_adjust/views/asset_backend.xml b/hr_expense_tax_adjust/views/asset_backend.xml new file mode 100644 index 00000000..482215ec --- /dev/null +++ b/hr_expense_tax_adjust/views/asset_backend.xml @@ -0,0 +1,11 @@ + + +