size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
588
py
PYTHON
15.0
# Copyright 2017 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Report QWeb Parameter", "version": "15.0.1.0.0", "license": "AGPL-3", "summary": """ Add new parameters for qweb templates in order to reduce field length and check minimal length """, "author": "Creu Blanca, Odoo Community Association (OCA)", "website": "https://github.com/OCA/reporting-engine", "category": "Technical Settings", "depends": ["web"], "demo": ["demo/test_report_field_length.xml"], "installable": True, }
32.666667
588
1,673
py
PYTHON
15.0
# Copyright 2017 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). import xml.etree.ElementTree as ET from odoo.tests import common from odoo.addons.base.models.qweb import QWebException class TestReportQWebParameter(common.TransactionCase): def test_qweb_parameter(self): report_name = "report_qweb_parameter.test_report_length" report_obj = self.env["ir.actions.report"] report_object = report_obj._get_report_from_name(report_name) docs = self.env["res.company"].create( { "name": "Test company", "street": "12345678901", "vat": "12345678901", "company_registry": "1234567890", } ) docs.website = "1234567890" # for avoding that Odoo adds http:// rep = report_object._render(docs.ids, False) root = ET.fromstring(rep[0]) self.assertEqual(root[0].text, "1234567890") self.assertEqual(root[2].text, "1234567890") docs.update({"street": "123456789"}) with self.assertRaises(QWebException): report_object._render(docs.ids, False) docs.update({"street": "1234567890", "vat": "123456789"}) with self.assertRaises(QWebException): report_object._render(docs.ids, False) docs.update({"vat": "1234567890", "website": "12345678901"}) with self.assertRaises(QWebException): report_object._render(docs.ids, False) docs.update({"website": "1234567890", "company_registry": "12345678901"}) with self.assertRaises(QWebException): report_object._render(docs.ids, False)
41.825
1,673
2,061
py
PYTHON
15.0
# Copyright 2017 Creu Blanca # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, models from odoo.exceptions import ValidationError class IrQWeb(models.AbstractModel): _inherit = "ir.qweb" @staticmethod def check_length(value, min_length=False, max_length=False): if min_length and len(value) < min_length: raise ValidationError(_("Length cannot be less than %s") % str(min_length)) if max_length and len(value) > max_length: raise ValidationError(_("Length cannot be more than %s") % str(max_length)) return value def _compile_directive_esc(self, el, options, indent): min_value = el.attrib.pop("t-minlength", False) max_value = el.attrib.pop("t-maxlength", False) if min_value or max_value: el.attrib["t-esc"] = ( 'docs.env["ir.qweb"].check_length(' + el.attrib["t-esc"] + ", " + (min_value or "False") + ", " + (max_value or "False") + ")" ) if "t-length" in el.attrib: tlength = el.attrib.pop("t-length") el.attrib["t-esc"] = "(" + el.attrib["t-esc"] + ")[:" + tlength + "]" return super()._compile_directive_esc(el, options, indent) def _compile_directive_raw(self, el, options, indent): min_value = el.attrib.pop("t-minlength", False) max_value = el.attrib.pop("t-maxlength", False) if min_value or max_value: el.attrib["t-raw"] = ( 'docs.env["ir.qweb"].check_length(' + el.attrib["t-raw"] + ", " + (min_value or "False") + ", " + (max_value or "False") + ")" ) if "t-length" in el.attrib: tlength = el.attrib.pop("t-length") el.attrib["t-raw"] = el.attrib["t-raw"] + "[:" + tlength + "]" return super()._compile_directive_raw(el, options, indent)
38.886792
2,061
363
py
PYTHON
15.0
# Copyright 2015-2017 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import SUPERUSER_ID from odoo.api import Environment def uninstall_hook(cr, registry): env = Environment(cr, SUPERUSER_ID, {}) recs = env["bi.sql.view"].search([]) for rec in recs: rec.button_set_draft()
33
363
871
py
PYTHON
15.0
# Copyright (C) 2017 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "BI SQL Editor", "summary": "BI Views builder, based on Materialized or Normal SQL Views", "version": "15.0.1.0.3", "license": "AGPL-3", "category": "Reporting", "author": "GRAP,Odoo Community Association (OCA)", "website": "https://github.com/OCA/reporting-engine", "depends": ["base", "sql_request_abstract"], "data": [ "security/ir.model.access.csv", "views/view_bi_sql_view.xml", "views/action.xml", "views/menu.xml", ], "demo": ["demo/res_groups_demo.xml", "demo/bi_sql_view_demo.xml"], "installable": True, "uninstall_hook": "uninstall_hook", "maintainers": ["legalsylvain"], }
36.291667
871
3,687
py
PYTHON
15.0
# Copyright 2017 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.exceptions import AccessError, UserError from odoo.tests import tagged from odoo.tests.common import SingleTransactionCase @tagged("-at_install", "post_install") class TestBiSqlViewEditor(SingleTransactionCase): @classmethod def setUpClass(cls): super(TestBiSqlViewEditor, cls).setUpClass() cls.res_partner = cls.env["res.partner"] cls.res_users = cls.env["res.users"] cls.bi_sql_view = cls.env["bi.sql.view"] cls.group_bi_user = cls.env.ref( "sql_request_abstract.group_sql_request_manager" ) cls.group_user = cls.env.ref("base.group_user") cls.view = cls.bi_sql_view.create( { "name": "Partners View 2", "is_materialized": True, "technical_name": "partners_view_2", "query": "SELECT name as x_name, street as x_street," "company_id as x_company_id FROM res_partner " "ORDER BY name", } ) cls.company = cls.env.ref("base.main_company") # Create bi user cls.bi_user = cls._create_user("bi_user", cls.group_bi_user, cls.company) cls.no_bi_user = cls._create_user("no_bi_user", cls.group_user, cls.company) @classmethod def _create_user(cls, login, groups, company): """Create a user.""" user = cls.res_users.create( { "name": login, "login": login, "password": "demo", "email": "example@yourcompany.com", "company_id": company.id, "groups_id": [(6, 0, groups.ids)], } ) return user def test_process_view(self): view = self.view self.assertEqual(view.state, "draft", "state not draft") view.button_validate_sql_expression() self.assertEqual(view.state, "sql_valid", "state not sql_valid") view.button_create_sql_view_and_model() self.assertEqual(view.state, "model_valid", "state not model_valid") view.button_create_ui() self.assertEqual(view.state, "ui_valid", "state not ui_valid") view.button_update_model_access() self.assertEqual(view.has_group_changed, False, "has_group_changed not False") cron_res = view.cron_id.method_direct_trigger() self.assertEqual(cron_res, True, "something went wrong with the cron") def test_copy(self): copy_view = self.view.copy() self.assertEqual(copy_view.name, "Partners View 2 (Copy)", "Wrong name") def test_security(self): with self.assertRaises(AccessError): self.bi_sql_view.with_user(self.no_bi_user.id).search( [("name", "=", "Partners View 2")] ) bi = self.bi_sql_view.with_user(self.bi_user.id).search( [("name", "=", "Partners View 2")] ) self.assertEqual( len(bi), 1, "Bi user should not have access to " "bi %s" % self.view.name ) def test_unlink(self): self.assertEqual(self.view.state, "ui_valid", "state not ui_valid") with self.assertRaises(UserError): self.view.unlink() self.view.button_set_draft() self.assertNotEqual( self.view.cron_id, False, "Set to draft materialized view should" " not unlink cron", ) self.view.unlink() res = self.bi_sql_view.search([("name", "=", "Partners View 2")]) self.assertEqual(len(res), 0, "View not deleted")
39.223404
3,687
262
py
PYTHON
15.0
from odoo import models class IrModelFields(models.Model): _inherit = "ir.model.fields" def _add_manual_fields(self, model): res = super()._add_manual_fields(model) self.env["bi.sql.view"].check_manual_fields(model) return res
26.2
262
25,622
py
PYTHON
15.0
# Copyright (C) 2017 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging from datetime import datetime, timedelta from psycopg2 import ProgrammingError from odoo import SUPERUSER_ID, _, api, fields, models from odoo.exceptions import UserError from odoo.tools import sql, table_columns from odoo.tools.safe_eval import safe_eval _logger = logging.getLogger(__name__) class BiSQLView(models.Model): _name = "bi.sql.view" _description = "BI SQL View" _order = "sequence" _inherit = ["sql.request.mixin"] _sql_prefix = "x_bi_sql_view_" _model_prefix = "x_bi_sql_view." _sql_request_groups_relation = "bi_sql_view_groups_rel" _sql_request_users_relation = "bi_sql_view_users_rel" _STATE_SQL_EDITOR = [ ("model_valid", "SQL View and Model Created"), ("ui_valid", "Views, Action and Menu Created"), ] technical_name = fields.Char( required=True, help="Suffix of the SQL view. SQL full name will be computed and" " prefixed by 'x_bi_sql_view_'. Syntax should follow: " "https://www.postgresql.org/" "docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS", ) view_name = fields.Char( compute="_compute_view_name", readonly=True, store=True, help="Full name of the SQL view", ) model_name = fields.Char( compute="_compute_model_name", readonly=True, store=True, help="Full Qualified Name of the transient model that will" " be created.", ) is_materialized = fields.Boolean( string="Is Materialized View", default=True, readonly=True, states={"draft": [("readonly", False)], "sql_valid": [("readonly", False)]}, ) materialized_text = fields.Char(compute="_compute_materialized_text", store=True) size = fields.Char( string="Database Size", readonly=True, help="Size of the materialized view and its indexes", ) state = fields.Selection(selection_add=_STATE_SQL_EDITOR) view_order = fields.Char( required=True, readonly=False, states={"ui_valid": [("readonly", True)]}, default="pivot,graph,tree", help="Comma-separated text. Possible values:" ' "graph", "pivot" or "tree"', ) query = fields.Text( help="SQL Request that will be inserted as the view. Take care to :\n" " * set a name for all your selected fields, specially if you use" " SQL function (like EXTRACT, ...);\n" " * Do not use 'SELECT *' or 'SELECT table.*';\n" " * prefix the name of the selectable columns by 'x_';", default="SELECT\n" " my_field as x_my_field\n" "FROM my_table", ) domain_force = fields.Text( string="Extra Rule Definition", default="[]", readonly=True, help="Define here access restriction to data.\n" " Take care to use field name prefixed by 'x_'." " A global 'ir.rule' will be created." " A typical Multi Company rule is for exemple \n" " ['|', ('x_company_id','child_of', [user.company_id.id])," "('x_company_id','=',False)].", states={"draft": [("readonly", False)], "sql_valid": [("readonly", False)]}, ) computed_action_context = fields.Text(compute="_compute_computed_action_context") action_context = fields.Text( default="{}", readonly=True, help="Define here a context that will be used" " by default, when creating the action.", states={ "draft": [("readonly", False)], "sql_valid": [("readonly", False)], "model_valid": [("readonly", False)], }, ) has_group_changed = fields.Boolean(copy=False) bi_sql_view_field_ids = fields.One2many( string="SQL Fields", comodel_name="bi.sql.view.field", inverse_name="bi_sql_view_id", ) model_id = fields.Many2one( string="Odoo Model", comodel_name="ir.model", readonly=True ) tree_view_id = fields.Many2one( string="Odoo Tree View", comodel_name="ir.ui.view", readonly=True ) graph_view_id = fields.Many2one( string="Odoo Graph View", comodel_name="ir.ui.view", readonly=True ) pivot_view_id = fields.Many2one( string="Odoo Pivot View", comodel_name="ir.ui.view", readonly=True ) search_view_id = fields.Many2one( string="Odoo Search View", comodel_name="ir.ui.view", readonly=True ) action_id = fields.Many2one( string="Odoo Action", comodel_name="ir.actions.act_window", readonly=True ) menu_id = fields.Many2one( string="Odoo Menu", comodel_name="ir.ui.menu", readonly=True ) cron_id = fields.Many2one( string="Odoo Cron", comodel_name="ir.cron", readonly=True, help="Cron Task that will refresh the materialized view", ) rule_id = fields.Many2one(string="Odoo Rule", comodel_name="ir.rule", readonly=True) group_ids = fields.Many2many( comodel_name="res.groups", readonly=True, states={"draft": [("readonly", False)], "sql_valid": [("readonly", False)]}, ) sequence = fields.Integer(string="sequence") # Constrains Section @api.constrains("is_materialized") def _check_index_materialized(self): for rec in self.filtered(lambda x: not x.is_materialized): if rec.bi_sql_view_field_ids.filtered(lambda x: x.is_index): raise UserError( _("You can not create indexes on non materialized views") ) @api.constrains("view_order") def _check_view_order(self): for rec in self: if rec.view_order: for vtype in rec.view_order.split(","): if vtype not in ("graph", "pivot", "tree"): raise UserError( _("Only graph, pivot or tree views are supported") ) # Compute Section @api.depends("bi_sql_view_field_ids.graph_type") def _compute_computed_action_context(self): for rec in self: action = { "pivot_measures": [], "pivot_row_groupby": [], "pivot_column_groupby": [], } for field in rec.bi_sql_view_field_ids.filtered( lambda x: x.graph_type == "measure" ): action["pivot_measures"].append(field.name) for field in rec.bi_sql_view_field_ids.filtered( lambda x: x.graph_type == "row" ): action["pivot_row_groupby"].append(field.name) for field in rec.bi_sql_view_field_ids.filtered( lambda x: x.graph_type == "col" ): action["pivot_column_groupby"].append(field.name) rec.computed_action_context = str(action) @api.depends("is_materialized") def _compute_materialized_text(self): for sql_view in self: sql_view.materialized_text = ( sql_view.is_materialized and "MATERIALIZED" or "" ) @api.depends("technical_name") def _compute_view_name(self): for sql_view in self: sql_view.view_name = "{}{}".format( sql_view._sql_prefix, sql_view.technical_name, ) @api.depends("technical_name") def _compute_model_name(self): for sql_view in self: sql_view.model_name = "{}{}".format( sql_view._model_prefix, sql_view.technical_name, ) @api.onchange("group_ids") def onchange_group_ids(self): if self.state not in ("draft", "sql_valid"): self.has_group_changed = True # Overload Section def write(self, vals): res = super(BiSQLView, self).write(vals) if vals.get("sequence", False): for rec in self.filtered(lambda x: x.menu_id): rec.menu_id.sequence = rec.sequence return res def unlink(self): if any(view.state not in ("draft", "sql_valid") for view in self): raise UserError( _( "You can only unlink draft views." "If you want to delete them, first set them to draft." ) ) self.cron_id.unlink() return super(BiSQLView, self).unlink() def copy(self, default=None): self.ensure_one() default = dict(default or {}) default.update( { "name": _("%s (Copy)") % self.name, "technical_name": "%s_copy" % self.technical_name, } ) return super(BiSQLView, self).copy(default=default) # Action Section def button_create_sql_view_and_model(self): for sql_view in self.filtered(lambda x: x.state == "sql_valid"): # Create ORM and access sql_view._create_model_and_fields() sql_view._create_model_access() # Create SQL View and indexes sql_view._create_view() sql_view._create_index() if sql_view.is_materialized: if not sql_view.cron_id: sql_view.cron_id = ( self.env["ir.cron"].create(sql_view._prepare_cron()).id ) else: sql_view.cron_id.active = True sql_view.state = "model_valid" def button_set_draft(self): for sql_view in self.filtered(lambda x: x.state != "draft"): sql_view.menu_id.unlink() sql_view.action_id.unlink() sql_view.tree_view_id.unlink() sql_view.graph_view_id.unlink() sql_view.pivot_view_id.unlink() sql_view.search_view_id.unlink() if sql_view.state in ("model_valid", "ui_valid"): # Drop SQL View (and indexes by cascade) if sql_view.is_materialized: sql_view._drop_view() if sql_view.cron_id: sql_view.cron_id.active = False # Drop ORM sql_view._drop_model_and_fields() sql_view.has_group_changed = False super(BiSQLView, sql_view).button_set_draft() return True def button_create_ui(self): self.tree_view_id = self.env["ir.ui.view"].create(self._prepare_tree_view()).id self.graph_view_id = ( self.env["ir.ui.view"].create(self._prepare_graph_view()).id ) self.pivot_view_id = ( self.env["ir.ui.view"].create(self._prepare_pivot_view()).id ) self.search_view_id = ( self.env["ir.ui.view"].create(self._prepare_search_view()).id ) self.action_id = ( self.env["ir.actions.act_window"].create(self._prepare_action()).id ) self.menu_id = self.env["ir.ui.menu"].create(self._prepare_menu()).id self.write({"state": "ui_valid"}) def button_update_model_access(self): self._drop_model_access() self._create_model_access() self.write({"has_group_changed": False}) def button_refresh_materialized_view(self): self._refresh_materialized_view() def button_open_view(self): return { "type": "ir.actions.act_window", "res_model": self.model_id.model, "search_view_id": self.search_view_id.id, "view_mode": self.action_id.view_mode, } # Prepare Function def _prepare_model(self): self.ensure_one() field_id = [] for field in self.bi_sql_view_field_ids.filtered( lambda x: x.field_description is not False ): field_id.append([0, False, field._prepare_model_field()]) return { "name": self.name, "model": self.model_name, "access_ids": [], "field_id": field_id, } def _prepare_model_access(self): self.ensure_one() res = [] for group in self.group_ids: res.append( { "name": _("%(model_name)s Access %(full_name)s") % {"model_name": self.model_name, "full_name": group.full_name}, "model_id": self.model_id.id, "group_id": group.id, "perm_read": True, "perm_create": False, "perm_write": False, "perm_unlink": False, } ) return res def _prepare_cron(self): now = datetime.now() return { "name": _("Refresh Materialized View %s") % self.view_name, "user_id": SUPERUSER_ID, "model_id": self.env["ir.model"] .search([("model", "=", self._name)], limit=1) .id, "state": "code", "code": "model._refresh_materialized_view_cron(%s)" % self.ids, "numbercall": -1, "interval_number": 1, "interval_type": "days", "nextcall": now + timedelta(days=1), "active": True, } def _prepare_rule(self): self.ensure_one() return { "name": _("Access %s") % self.name, "model_id": self.model_id.id, "domain_force": self.domain_force, "global": True, } def _prepare_tree_view(self): self.ensure_one() return { "name": self.name, "type": "tree", "model": self.model_id.model, "arch": """<?xml version="1.0"?>""" """<tree string="Analysis">{}""" """</tree>""".format( "".join([x._prepare_tree_field() for x in self.bi_sql_view_field_ids]) ), } def _prepare_graph_view(self): self.ensure_one() return { "name": self.name, "type": "graph", "model": self.model_id.model, "arch": """<?xml version="1.0"?>""" """<graph string="Analysis" type="bar" stacked="True">{}""" """</graph>""".format( "".join([x._prepare_graph_field() for x in self.bi_sql_view_field_ids]) ), } def _prepare_pivot_view(self): self.ensure_one() return { "name": self.name, "type": "pivot", "model": self.model_id.model, "arch": """<?xml version="1.0"?>""" """<pivot string="Analysis" stacked="True">{}""" """</pivot>""".format( "".join([x._prepare_pivot_field() for x in self.bi_sql_view_field_ids]) ), } def _prepare_search_view(self): self.ensure_one() return { "name": self.name, "type": "search", "model": self.model_id.model, "arch": """<?xml version="1.0"?>""" """<search string="Analysis">{}""" """<group expand="1" string="Group By">{}</group>""" """</search>""".format( "".join( [x._prepare_search_field() for x in self.bi_sql_view_field_ids] ), "".join( [ x._prepare_search_filter_field() for x in self.bi_sql_view_field_ids ] ), ), } def _prepare_action(self): self.ensure_one() view_mode = self.view_order first_view = view_mode.split(",")[0] if first_view == "tree": view_id = self.tree_view_id.id elif first_view == "pivot": view_id = self.pivot_view_id.id else: view_id = self.graph_view_id.id action = safe_eval(self.computed_action_context) for k, v in safe_eval(self.action_context).items(): action[k] = v return { "name": self._prepare_action_name(), "res_model": self.model_id.model, "type": "ir.actions.act_window", "view_mode": view_mode, "view_id": view_id, "search_view_id": self.search_view_id.id, "context": str(action), } def _prepare_action_name(self): self.ensure_one() if not self.is_materialized: return self.name return "{} ({})".format( self.name, datetime.utcnow().strftime("%m/%d/%Y %H:%M:%S UTC"), ) def _prepare_menu(self): self.ensure_one() return { "name": self.name, "parent_id": self.env.ref("bi_sql_editor.menu_bi_sql_editor").id, "action": "ir.actions.act_window,%s" % self.action_id.id, "sequence": self.sequence, } # Custom Section def _log_execute(self, req): _logger.info("Executing SQL Request %s ..." % req) self.env.cr.execute(req) def _drop_view(self): for sql_view in self: self._log_execute( "DROP %s VIEW IF EXISTS %s" % (sql_view.materialized_text, sql_view.view_name) ) sql_view.size = False def _create_view(self): for sql_view in self: sql_view._drop_view() try: self._log_execute(sql_view._prepare_request_for_execution()) sql_view._refresh_size() except ProgrammingError as e: raise UserError( _( "SQL Error while creating %(materialized_text)s" " VIEW %(view_name)s :\n %(error)s" ) % { "materialized_text": sql_view.materialized_text, "view_name": sql_view.view_name, "error": str(e), } ) from e def _create_index(self): for sql_view in self: for sql_field in sql_view.bi_sql_view_field_ids.filtered( lambda x: x.is_index is True ): self._log_execute( "CREATE INDEX %(index_name)s ON %(view_name)s (%(field_name)s);" % { "index_name": sql_field.index_name, "view_name": sql_view.view_name, "field_name": sql_field.name, } ) def _create_model_and_fields(self): for sql_view in self: # Create model sql_view.model_id = self.env["ir.model"].create(self._prepare_model()).id sql_view.rule_id = self.env["ir.rule"].create(self._prepare_rule()).id # Drop table, created by the ORM if sql.table_exists(self._cr, sql_view.view_name): req = "DROP TABLE %s" % sql_view.view_name self._log_execute(req) def _create_model_access(self): for sql_view in self: for item in sql_view._prepare_model_access(): self.env["ir.model.access"].create(item) def _drop_model_access(self): for sql_view in self: self.env["ir.model.access"].search( [("model_id", "=", sql_view.model_name)] ).unlink() def _drop_model_and_fields(self): for sql_view in self: if sql_view.rule_id: sql_view.rule_id.unlink() if sql_view.model_id: sql_view.model_id.with_context(_force_unlink=True).unlink() def _hook_executed_request(self): self.ensure_one() req = ( """ SELECT attnum, attname AS column, format_type(atttypid, atttypmod) AS type FROM pg_attribute WHERE attrelid = '%s'::regclass AND NOT attisdropped AND attnum > 0 ORDER BY attnum;""" % self.view_name ) self._log_execute(req) return self.env.cr.fetchall() def _prepare_request_check_execution(self): self.ensure_one() return "CREATE VIEW {} AS ({});".format(self.view_name, self.query) def _prepare_request_for_execution(self): self.ensure_one() query = ( """ SELECT CAST(row_number() OVER () as integer) AS id, CAST(Null as timestamp without time zone) as create_date, CAST(Null as integer) as create_uid, CAST(Null as timestamp without time zone) as write_date, CAST(Null as integer) as write_uid, my_query.* FROM (%s) as my_query """ % self.query ) return "CREATE {} VIEW {} AS ({});".format( self.materialized_text, self.view_name, query, ) def _check_execution(self): """Ensure that the query is valid, trying to execute it. a non materialized view is created for this check. A rollback is done at the end. After the execution, and before the rollback, an analysis of the database structure is done, to know fields type.""" self.ensure_one() sql_view_field_obj = self.env["bi.sql.view.field"] columns = super(BiSQLView, self)._check_execution() field_ids = [] for column in columns: existing_field = self.bi_sql_view_field_ids.filtered( lambda x: x.name == column[1] ) if existing_field: # Update existing field field_ids.append(existing_field.id) existing_field.write({"sequence": column[0], "sql_type": column[2]}) else: # Create a new one if name is prefixed by x_ if column[1][:2] == "x_": field_ids.append( sql_view_field_obj.create( { "sequence": column[0], "name": column[1], "sql_type": column[2], "bi_sql_view_id": self.id, } ).id ) # Drop obsolete view field self.bi_sql_view_field_ids.filtered(lambda x: x.id not in field_ids).unlink() if not self.bi_sql_view_field_ids: raise UserError( _("No Column was found.\n" "Columns name should be prefixed by 'x_'.") ) return columns @api.model def _refresh_materialized_view_cron(self, view_ids): sql_views = self.search( [ ("is_materialized", "=", True), ("state", "in", ["model_valid", "ui_valid"]), ("id", "in", view_ids), ] ) return sql_views._refresh_materialized_view() def _refresh_materialized_view(self): for sql_view in self.filtered(lambda x: x.is_materialized): req = "REFRESH {} VIEW {}".format( sql_view.materialized_text, sql_view.view_name, ) self._log_execute(req) sql_view._refresh_size() if sql_view.action_id: # Alter name of the action, to display last refresh # datetime of the materialized view sql_view.action_id.with_context( lang=self.env.user.lang ).name = sql_view._prepare_action_name() def _refresh_size(self): for sql_view in self: req = "SELECT pg_size_pretty(pg_total_relation_size('%s'));" % ( sql_view.view_name ) self._log_execute(req) sql_view.size = self.env.cr.fetchone()[0] def check_manual_fields(self, model): # check the fields we need are defined on self, to stop it going # early on install / startup - particularly problematic during upgrade if "group_operator" in table_columns( self.env.cr, "bi_sql_view_field" ) and model._name.startswith(self._model_prefix): # Use SQL instead of ORM, as ORM might not be fully initialised - # we have no control over the order that fields are defined! # We are not concerned about user security rules. self.env.cr.execute( """ SELECT f.name, f.ttype, f.group_operator FROM bi_sql_view v LEFT JOIN bi_sql_view_field f ON f.bi_sql_view_id = v.id WHERE v.model_name = %s ; """, (model._name,), ) sql_fields = self.env.cr.fetchall() for sql_field in sql_fields: if ( sql_field[0] in model._fields and sql_field[1] in ("integer", "float") and sql_field[2] ): model._fields[sql_field[0]].group_operator = sql_field[2] def button_preview_sql_expression(self): self.button_validate_sql_expression() res = self._execute_sql_request() raise UserError("\n".join(map(lambda x: str(x), res[:100])))
34.438172
25,622
8,300
py
PYTHON
15.0
# Copyright (C) 2017 - Today: GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import re from odoo import _, api, fields, models from odoo.exceptions import UserError class BiSQLViewField(models.Model): _name = "bi.sql.view.field" _description = "Bi SQL View Field" _order = "sequence" _TTYPE_SELECTION = [ ("boolean", "boolean"), ("char", "char"), ("date", "date"), ("datetime", "datetime"), ("float", "float"), ("integer", "integer"), ("many2one", "many2one"), ("selection", "selection"), ] _GRAPH_TYPE_SELECTION = [ ("col", "Column"), ("row", "Row"), ("measure", "Measure"), ] _TREE_VISIBILITY_SELECTION = [ ("unavailable", "Unavailable"), ("hidden", "Hidden"), ("available", "Available"), ] # Mapping to guess Odoo field type, from SQL column type _SQL_MAPPING = { "boolean": "boolean", "bigint": "integer", "integer": "integer", "double precision": "float", "numeric": "float", "text": "char", "character varying": "char", "date": "date", "timestamp without time zone": "datetime", } _GROUP_OPERATOR_SELECTION = [ ("sum", "Sum"), ("avg", "Average"), ("min", "Minimum"), ("max", "Maximum"), ] name = fields.Char(required=True, readonly=True) sql_type = fields.Char( string="SQL Type", required=True, readonly=True, help="SQL Type in the database" ) sequence = fields.Integer(string="sequence", required=True, readonly=True) bi_sql_view_id = fields.Many2one( string="SQL View", comodel_name="bi.sql.view", ondelete="cascade" ) is_index = fields.Boolean( help="Check this box if you want to create" " an index on that field. This is recommended for searchable and" " groupable fields, to reduce duration", ) is_group_by = fields.Boolean( string="Is Group by", help="Check this box if you want to create" " a 'group by' option in the search view", ) index_name = fields.Char(compute="_compute_index_name") graph_type = fields.Selection(selection=_GRAPH_TYPE_SELECTION) tree_visibility = fields.Selection( selection=_TREE_VISIBILITY_SELECTION, default="available", required=True, ) field_description = fields.Char( help="This will be used as the name" " of the Odoo field, displayed for users", ) ttype = fields.Selection( string="Field Type", selection=_TTYPE_SELECTION, help="Type of the" " Odoo field that will be created. Keep empty if you don't want to" " create a new field. If empty, this field will not be displayed" " neither available for search or group by function", ) selection = fields.Text( string="Selection Options", default="[]", help="For 'Selection' Odoo field.\n" " List of options, specified as a Python expression defining a list of" " (key, label) pairs. For example:" " [('blue','Blue'), ('yellow','Yellow')]", ) many2one_model_id = fields.Many2one( comodel_name="ir.model", string="Model", help="For 'Many2one' Odoo field.\n" " Comodel of the field.", ) group_operator = fields.Selection( selection=_GROUP_OPERATOR_SELECTION, help="By default, Odoo will sum the values when grouping. If you wish " "to alter the behaviour, choose an alternate Group Operator", ) # Constrains Section @api.constrains("is_index") def _check_index_materialized(self): for rec in self.filtered(lambda x: x.is_index): if not rec.bi_sql_view_id.is_materialized: raise UserError( _("You can not create indexes on non materialized views") ) # Compute Section def _compute_index_name(self): for sql_field in self: sql_field.index_name = "{}_{}".format( sql_field.bi_sql_view_id.view_name, sql_field.name, ) # Overload Section @api.model def create(self, vals): field_without_prefix = vals["name"][2:] # guess field description field_description = re.sub( r"\w+", lambda m: m.group(0).capitalize(), field_without_prefix.replace("_id", "").replace("_", " "), ) # Guess ttype # Don't execute as simple .get() in the dict to manage # correctly the type 'character varying(x)' ttype = False for k, v in self._SQL_MAPPING.items(): if k in vals["sql_type"]: ttype = v # Guess many2one_model_id many2one_model_id = False if vals["sql_type"] == "integer" and (vals["name"][-3:] == "_id"): ttype = "many2one" model_name = self._model_mapping().get(field_without_prefix, "") many2one_model_id = ( self.env["ir.model"].search([("model", "=", model_name)]).id ) vals.update( { "ttype": ttype, "field_description": field_description, "many2one_model_id": many2one_model_id, } ) return super(BiSQLViewField, self).create(vals) # Custom Section @api.model def _model_mapping(self): """Return dict of key value, to try to guess the model based on a field name. Sample : {'account_id': 'account.account'; 'product_id': 'product.product'} """ relation_fields = self.env["ir.model.fields"].search( [("ttype", "=", "many2one")] ) res = {} keys_to_pop = [] for field in relation_fields: if field.name in res and res.get(field.name) != field.relation: # The field name is not predictive keys_to_pop.append(field.name) else: res.update({field.name: field.relation}) for key in list(set(keys_to_pop)): res.pop(key) return res def _prepare_model_field(self): self.ensure_one() return { "name": self.name, "field_description": self.field_description, "model_id": self.bi_sql_view_id.model_id.id, "ttype": self.ttype, "selection": self.ttype == "selection" and self.selection or False, "relation": self.ttype == "many2one" and self.many2one_model_id.model or False, } def _prepare_tree_field(self): self.ensure_one() res = "" if self.field_description and self.tree_visibility != "unavailable": res = """<field name="{}" {}/>""".format( self.name, self.tree_visibility == "hidden" and 'invisible="1"' or "" ) return res def _prepare_graph_field(self): self.ensure_one() res = "" if self.graph_type and self.field_description: res = """<field name="{}" type="{}" />\n""".format( self.name, self.graph_type ) return res def _prepare_pivot_field(self): self.ensure_one() res = "" if self.field_description: graph_type_text = self.graph_type and 'type="%s"' % (self.graph_type) or "" res = """<field name="{}" {} />\n""".format(self.name, graph_type_text) return res def _prepare_search_field(self): self.ensure_one() res = "" if self.field_description: res = """<field name="{}"/>\n""".format(self.name) return res def _prepare_search_filter_field(self): self.ensure_one() res = "" if self.field_description and self.is_group_by: res = """<filter name="group_by_%s" string="%s" context="{'group_by':'%s'}"/>\n""" % ( self.name, self.field_description, self.name, ) return res
31.800766
8,300
617
py
PYTHON
15.0
# Copyright 2019 Akretion # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "SQL Export Excel", "version": "15.0.1.0.0", "author": "Akretion,Odoo Community Association (OCA)", "website": "https://github.com/OCA/reporting-engine", "license": "AGPL-3", "category": "Generic Modules/Others", "summary": "Allow to export a sql query to an excel file.", "depends": ["sql_export"], "external_dependencies": { "python": [ "openpyxl", ], }, "data": [ "views/sql_export_view.xml", ], "installable": True, }
28.045455
617
4,147
py
PYTHON
15.0
# Copyright (C) 2019 Akretion (<http://www.akretion.com>) # @author: Florian da Costa # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import base64 import logging from io import BytesIO from odoo.tests.common import TransactionCase _logger = logging.getLogger(__name__) try: import openpyxl except ImportError: _logger.debug("Can not import openpyxl") class TestExportSqlQueryExcel(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.wizard_obj = cls.env["sql.file.wizard"] def get_workbook_from_query(self, wizard): wizard.export_sql() decoded_data = base64.b64decode(wizard.binary_file) xlsx_file = BytesIO(decoded_data) return openpyxl.load_workbook(xlsx_file) def test_excel_file_generation(self): test_query = "SELECT 'testcol1' as firstcol, 2 as second_col" query_vals = { "name": "Test Query Excel", "query": test_query, "file_format": "excel", } query = self.env["sql.export"].create(query_vals) query.button_validate_sql_expression() wizard = self.wizard_obj.create( { "sql_export_id": query.id, } ) workbook = self.get_workbook_from_query(wizard) ws = workbook.active # Check values, header should be here by default self.assertEqual(ws.cell(row=1, column=1).value, "firstcol") self.assertEqual(ws.cell(row=2, column=1).value, "testcol1") self.assertEqual(ws.cell(row=2, column=2).value, 2) query.write({"header": False}) wb2 = self.get_workbook_from_query(wizard) ws2 = wb2.active # Check values, the header should not be present self.assertEqual(ws2.cell(row=1, column=1).value, "testcol1") self.assertEqual(ws2.cell(row=1, column=2).value, 2) def test_excel_file_insert(self): # Create excel file with 2 sheets. Create a header in second sheet # where data will be inserted wb = openpyxl.Workbook() ws = wb.active ws.cell(row=1, column=1, value="My Test Value") ws2 = wb.create_sheet("data") ws2.cell(row=1, column=1, value="Partner Id") ws2.cell(row=1, column=2, value="Partner Name") output = BytesIO() wb.save(output) data = output.getvalue() # Create attachment with the created xlsx file which will be used as # template in the sql query attachmnent_vals = { "name": "template xlsx sql export Res Partner", "datas": base64.b64encode(data), } attachment = self.env["ir.attachment"].create(attachmnent_vals) # Create the query and configure it to insert the data in the second # sheet of the xlsx template file and start inserting data at the # second row, ignoring header (because the template excel file # already contains a header) test_query = "SELECT id, name FROM res_partner" query_vals = { "name": "Test Query Excel", "query": test_query, "file_format": "excel", "attachment_id": attachment.id, "sheet_position": 2, "header": False, "row_position": 2, } query = self.env["sql.export"].create(query_vals) query.button_validate_sql_expression() wizard = self.wizard_obj.create( { "sql_export_id": query.id, } ) # Check the generated excel file. The first sheet should still contain # the same data and the second sheet should have kept the header and # inserted data from the query wb2 = self.get_workbook_from_query(wizard) sheets = wb2.worksheets ws1 = sheets[0] # Check values, header should be here by default self.assertEqual(ws1.cell(row=1, column=1).value, "My Test Value") ws2 = sheets[1] self.assertEqual(ws2.cell(row=1, column=1).value, "Partner Id") self.assertTrue(ws2.cell(row=2, column=1).value)
37.026786
4,147
4,054
py
PYTHON
15.0
# Copyright 2019 Akretion # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import base64 import logging from io import BytesIO from odoo import _, api, exceptions, fields, models _logger = logging.getLogger(__name__) try: import openpyxl except ImportError: _logger.debug("Can not import openpyxl") class SqlExport(models.Model): _inherit = "sql.export" file_format = fields.Selection( selection_add=[("excel", "Excel")], ondelete={"excel": "set default"} ) header = fields.Boolean( default=True, help="Indicate if the header should be exported to the file." ) attachment_id = fields.Many2one( "ir.attachment", string="Excel Template", help="If you configure an excel file (in xlsx format) here, the " "result of the query will be injected in it.\nIt is usefull to " "feed data in a excel file pre-configured with calculation", ) sheet_position = fields.Integer( default=1, help="Indicate the sheet's position of the excel template where the " "result of the sql query should be injected.", ) row_position = fields.Integer( default=1, help="Indicate from which row the result of the query should be " "injected.", ) col_position = fields.Integer( string="Column Position", default=1, help="Indicate from which column the result of the query should be " "injected.", ) @api.constrains("sheet_position") def check_sheet_position(self): for export in self: if export.sheet_position < 1: raise exceptions.ValidationError( _("The sheet position can't be less than 1.") ) @api.constrains("row_position") def check_row_position(self): for export in self: if export.row_position < 1: raise exceptions.ValidationError( _("The row position can't be less than 1.") ) @api.constrains("col_position") def check_column_position(self): for export in self: if export.col_position < 1: raise exceptions.ValidationError( _("The column position can't be less than 1.") ) def _get_file_extension(self): self.ensure_one() if self.file_format == "excel": return "xlsx" else: return super()._get_file_extension() def excel_get_data_from_query(self, variable_dict): self.ensure_one() res = self._execute_sql_request( params=variable_dict, mode="fetchall", header=self.header ) # Case we insert data in an existing excel file. if self.attachment_id: datas = self.attachment_id.datas infile = BytesIO() infile.write(base64.b64decode(datas)) infile.seek(0) wb = openpyxl.load_workbook(filename=infile) sheets = wb.worksheets try: ws = sheets[self.sheet_position - 1] except IndexError as err: raise exceptions.ValidationError( _( "The Excel Template file contains less than %s sheets " "Please, adjust the Sheet Position parameter." ) ) from err row_position = self.row_position or 1 col_position = self.col_position or 1 # Case of excel file creation else: wb = openpyxl.Workbook() ws = wb.active row_position = 1 col_position = 1 for index, row in enumerate(res, row_position): for col, val in enumerate(row, col_position): ws.cell(row=index, column=col).value = val output = BytesIO() wb.save(output) output.getvalue() output_datas = base64.b64encode(output.getvalue()) output.close() return output_datas
34.067227
4,054
550
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Product Category Taxes", "summary": "Configure taxes in the product category", "version": "15.0.1.1.0", "license": "AGPL-3", "author": "ForgeFlow S.L., Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "depends": ["account", "product_category_product_link"], "data": ["views/product_category.xml", "views/product_template.xml"], }
42.307692
550
4,011
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests.common import TransactionCase class ProductCategoryTax(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.categ_obj = cls.env["product.category"] cls.product_obj = cls.env["product.product"] cls.tax_model = cls.env["account.tax"] cls.uom_kg = cls.env.ref("uom.product_uom_kgm") # Create product and related records: cls.tax_sale = cls.tax_model.create( { "name": "Include tax", "type_tax_use": "sale", "amount": 21.00, "price_include": True, } ) cls.tax_purchase = cls.tax_model.create( { "name": "Some tax", "type_tax_use": "purchase", "amount": 21.00, "price_include": True, } ) cls.tax_purchase2 = cls.tax_model.create( { "name": "Abusive tax", "type_tax_use": "purchase", "amount": 50.00, "price_include": True, } ) def test_01_copy_taxes(self): """Default taxes taken from the category""" test_categ = self.categ_obj.create( { "name": "Super Category", "taxes_id": [(6, 0, self.tax_sale.ids)], "supplier_taxes_id": [(6, 0, self.tax_purchase.ids)], } ) self.product_test = self.product_obj.create( {"name": "TEST 01", "categ_id": test_categ.id, "list_price": 155.0} ) self.product_test.product_tmpl_id.onchange_categ_id() self.assertEqual(self.product_test.supplier_taxes_id, self.tax_purchase) def test_02_update_taxes(self): """Default update""" self.product_test = self.product_obj.create( { "name": "TEST 02", "default_code": "TESTcode2", "list_price": 155.0, "supplier_taxes_id": [(6, 0, self.tax_purchase2.ids)], } ) test_categ = self.categ_obj.create( { "name": "Super Category", "taxes_id": [(6, 0, self.tax_sale.ids)], "supplier_taxes_id": [(6, 0, self.tax_purchase.ids)], } ) self.assertEqual(self.product_test.supplier_taxes_id, self.tax_purchase2) self.product_test.categ_id = test_categ.id test_categ.update_product_taxes() self.assertEqual(self.product_test.supplier_taxes_id, self.tax_purchase) def test_03_taxes_not_updeatable(self): """Avoid update specific products""" self.product_test3 = self.product_obj.create( { "name": "TEST 03", "default_code": "TESTcode3", "list_price": 155.0, "supplier_taxes_id": [(6, 0, self.tax_purchase2.ids)], } ) self.product_test4 = self.product_obj.create( { "name": "TEST 04", "default_code": "TESTcode3", "list_price": 155.0, "taxes_updeatable_from_category": False, "supplier_taxes_id": [(6, 0, self.tax_purchase2.ids)], } ) test_categ = self.categ_obj.create( { "name": "Super Category", "taxes_id": [(6, 0, self.tax_sale.ids)], "supplier_taxes_id": [(6, 0, self.tax_purchase.ids)], } ) self.product_test3.categ_id = test_categ.id self.product_test4.categ_id = test_categ.id test_categ.update_product_taxes() self.assertEqual(self.product_test3.supplier_taxes_id, self.tax_purchase) self.assertNotEqual(self.product_test4.supplier_taxes_id, self.tax_purchase)
36.463636
4,011
1,161
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class ProductCategory(models.Model): _inherit = "product.category" taxes_id = fields.Many2many( "account.tax", "product_category_taxes_rel", "categ_id", "tax_id", help="Default taxes used when selling the product.", string="Customer Taxes", domain=[("type_tax_use", "=", "sale")], default=lambda self: self.env.company.account_sale_tax_id, ) supplier_taxes_id = fields.Many2many( "account.tax", "product_category_supplier_taxes_rel", "categ_id", "tax_id", string="Vendor Taxes", help="Default taxes used when buying the product.", domain=[("type_tax_use", "=", "purchase")], default=lambda self: self.env.company.account_purchase_tax_id, ) def update_product_taxes(self): for template in self.product_template_ids.filtered( lambda p: p.taxes_updeatable_from_category ): template.set_tax_from_category()
33.171429
1,161
642
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class ProductTemplate(models.Model): _inherit = "product.template" taxes_updeatable_from_category = fields.Boolean(default=True) @api.onchange("categ_id") def onchange_categ_id(self): if self.categ_id: self.set_tax_from_category() def set_tax_from_category(self): self.ensure_one() self.taxes_id = [(6, 0, self.categ_id.taxes_id.ids)] self.supplier_taxes_id = [(6, 0, self.categ_id.supplier_taxes_id.ids)]
32.1
642
565
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). from odoo import api, models class ProductProduct(models.Model): _inherit = "product.product" @api.onchange("categ_id") def onchange_categ_id(self): if self.categ_id: self.set_tax_from_category() def set_tax_from_category(self): self.ensure_one() self.taxes_id = [(6, 0, self.categ_id.taxes_id.ids)] self.supplier_taxes_id = [(6, 0, self.categ_id.supplier_taxes_id.ids)]
31.388889
565
515
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). { "name": "Account Move Force Removal", "summary": """Allow force removal account moves""", "version": "15.0.1.1.0", "category": "Account", "license": "AGPL-3", "website": "https://github.com/OCA/account-financial-tools", "author": "Tecnativa, Odoo Community Association (OCA)", "depends": ["account"], "data": ["security/account_move_force_removal_security.xml"], }
36.642857
513
300
py
PYTHON
15.0
from openupgradelib import openupgrade @openupgrade.migrate() def migrate(env, version): users_billing = env.ref("account.group_account_invoice").users group = env.ref("account_move_force_removal.group_account_move_force_removal") group.users = [(4, user.id) for user in users_billing]
37.5
300
3,245
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Víctor Martínez # License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html from odoo.exceptions import UserError from odoo.tests import Form, tagged from odoo.tests.common import TransactionCase @tagged("post_install", "-at_install") class TestMove(TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.partner = cls.env["res.partner"].create( {"name": "Test customer", "customer_rank": 1} ) cls.journal = cls.env["account.journal"].create( { "name": "Test journal", "type": "sale", "code": "test-sale-jorunal", "company_id": cls.env.company.id, } ) cls.product = cls.env["product.product"].create( {"name": "Test product", "type": "service"} ) cls.company = cls.env.company cls.company.currency_id.active = True account_type = cls.env.ref("account.data_account_type_other_income") cls.income_account = cls.env["account.account"].search( [ ("user_type_id", "=", account_type.id), ("company_id", "=", cls.company.id), ], limit=1, ) invoice = Form( cls.env["account.move"].with_context( default_type="out_invoice", default_company_id=cls.env.company.id ) ) invoice.partner_id = cls.partner invoice.journal_id = cls.journal with invoice.invoice_line_ids.new() as line_form: line_form.name = cls.product.name line_form.product_id = cls.product line_form.quantity = 1.0 line_form.price_unit = 10 line_form.account_id = cls.income_account invoice = invoice.save() invoice.action_post() cls.invoice = invoice cls.invoice2 = cls.invoice.copy() cls.invoice2.action_post() cls.invoice3 = cls.invoice.copy() cls.invoice3.action_post() def test_remove_invoice_error(self): # Delete invoice while name isn't / and # user not in group_account_move_force_removal with self.assertRaises(UserError): self.invoice.unlink() # Delete invoice (previously draft + cancel) and # user not in group_account_move_force_removal self.invoice.button_draft() self.invoice.button_cancel() with self.assertRaises(UserError): self.invoice.unlink() # Delete invoice while name isn't / and # user in group_account_move_force_removal self.env.user.groups_id += self.env.ref( "account_move_force_removal.group_account_move_force_removal" ) with self.assertRaises(UserError): self.invoice3.unlink() def test_ok_invoice_error(self): # Delete invoice (previously draft + cancel) and # user in group_account_move_force_removal self.invoice.button_draft() self.invoice.button_cancel() self.env.user.groups_id += self.env.ref( "account_move_force_removal.group_account_move_force_removal" ) self.invoice.unlink()
37.275862
3,243
629
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Víctor Martínez # License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html from odoo import models class AccountMove(models.Model): _inherit = "account.move" def unlink(self): cancelled_moves = self.env["account.move"] if self.env.user.has_group( "account_move_force_removal.group_account_move_force_removal" ): cancelled_moves = self.filtered(lambda m: m.state == "cancel") super(AccountMove, cancelled_moves.with_context(force_delete=True)).unlink() return super(AccountMove, self - cancelled_moves).unlink()
36.882353
627
591
py
PYTHON
15.0
# Copyright 2017-20 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). { "name": "Account Move Print", "version": "15.0.1.0.0", "category": "Accounting", "license": "LGPL-3", "summary": "Adds the option to print Journal Entries", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "depends": ["account"], "maintainers": ["JordiBForgeFlow"], "data": ["report/journal_report.xml"], "demo": [], "installable": True, }
36.9375
591
619
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Lock Date Update", "summary": """ Allow an Account adviser to update locking date without having access to all technical settings""", "version": "15.0.1.0.1", "license": "AGPL-3", "author": "ACSONE SA/NV, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "installable": True, "depends": ["account"], "data": [ "security/ir.model.access.csv", "wizards/account_update_lock_date.xml", ], }
32.578947
619
1,704
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields from odoo.exceptions import AccessError from odoo.tests.common import TransactionCase class TestAccountLockDateUpdate(TransactionCase): def setUp(self): super().setUp() self.company = self.env.ref("base.main_company") self.demo_user = self.env.ref("base.user_demo") self.adviser_group = self.env.ref("account.group_account_manager") def test_01_update_without_access(self): self.demo_user.write({"groups_id": [(3, self.adviser_group.id)]}) with self.assertRaises(AccessError): self.env["account.update.lock_date"].with_user(self.demo_user.id).create( {"company_id": self.company.id} ) def test_02_update_with_access(self): self.demo_user.write({"groups_id": [(4, self.adviser_group.id)]}) wizard = ( self.env["account.update.lock_date"] .with_user(self.demo_user.id) .create({"company_id": self.company.id}) ) wizard.write( { "period_lock_date": "2000-02-01", "fiscalyear_lock_date": "2000-01-01", "tax_lock_date": "2000-01-01", } ) wizard.with_user(self.demo_user.id).execute() self.assertEqual( fields.Date.to_string(self.company.period_lock_date), "2000-02-01" ) self.assertEqual( fields.Date.to_string(self.company.fiscalyear_lock_date), "2000-01-01" ) self.assertEqual( fields.Date.to_string(self.company.tax_lock_date), "2000-01-01" )
37.043478
1,704
2,156
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import UserError class AccountUpdateLockDate(models.TransientModel): _name = "account.update.lock_date" _description = "Account Update Lock_date" company_id = fields.Many2one(comodel_name="res.company", required=True) period_lock_date = fields.Date( string="Lock Date for Non-Advisers", help="Only users with the 'Adviser' role can edit accounts prior to " "and inclusive of this date. Use it for period locking inside an " "open fiscal year, for example.", ) fiscalyear_lock_date = fields.Date( string="Lock Date for All Users", help="No users, including Advisers, can edit accounts prior to and " "inclusive of this date. Use it for fiscal year locking for " "example.", ) tax_lock_date = fields.Date( help="No users can edit journal entries related to a tax prior and " "inclusive of this date.", ) @api.model def default_get(self, field_list): res = super().default_get(field_list) company = self.env.company res.update( { "company_id": company.id, "period_lock_date": company.period_lock_date, "fiscalyear_lock_date": company.fiscalyear_lock_date, "tax_lock_date": company.tax_lock_date, } ) return res def _check_execute_allowed(self): self.ensure_one() has_adviser_group = self.env.user.has_group("account.group_account_manager") if not (has_adviser_group or self.env.user._is_admin()): raise UserError(_("You are not allowed to execute this action.")) def execute(self): self.ensure_one() self._check_execute_allowed() self.company_id.sudo().write( { "period_lock_date": self.period_lock_date, "fiscalyear_lock_date": self.fiscalyear_lock_date, "tax_lock_date": self.tax_lock_date, } )
36.542373
2,156
888
py
PYTHON
15.0
# Copyright 2016 Jairo Llopis <jairo.llopis@tecnativa.com> # Copyright 2016 Jacques-Etienne Baudoux <je@bcim.be> # Copyright 2016 Sylvain Van Hoof <sylvain@okia.be> # Copyright 2015-2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Detect changes and update the Account Chart from a template", "summary": "Wizard to update a company's account chart from a template", "version": "15.0.1.2.0", "author": "Tecnativa, BCIM, Okia, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "depends": ["account", "l10n_generic_coa"], "category": "Accounting", "license": "AGPL-3", "data": [ "security/ir.model.access.csv", "wizard/wizard_chart_update_view.xml", "views/account_config_settings_view.xml", ], "installable": True, }
40.363636
888
26,065
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from odoo import fields from odoo.tests import common from odoo.tools import mute_logger _logger = logging.getLogger(__name__) class TestAccountChartUpdate(common.HttpCase): at_install = False post_install = True def _create_xml_id(self, record): return self.env["ir.model.data"].create( { "module": "account_chart_update", "name": "{}-{}".format(record._table, record.id), "model": record._name, "res_id": record.id, } ) def _create_account_tmpl(self, name, code, user_type, chart_template): record = self.env["account.account.template"].create( { "name": name, "code": code, "user_type_id": user_type.id, "chart_template_id": chart_template and chart_template.id, } ) self._create_xml_id(record) return record def _create_tax_tmpl(self, name, chart_template): record = self.env["account.tax.template"].create( { "name": name, "amount": 0, "chart_template_id": chart_template.id, "tax_group_id": self.env.ref("account.tax_group_taxes").id, "refund_repartition_line_ids": [ (0, 0, {"repartition_type": "base", "factor_percent": 100.0}), (0, 0, {"repartition_type": "tax", "factor_percent": 100.0}), (0, 0, {"repartition_type": "tax", "factor_percent": 100.0}), ], "invoice_repartition_line_ids": [ (0, 0, {"repartition_type": "base", "factor_percent": 100.0}), (0, 0, {"repartition_type": "tax", "factor_percent": 100.0}), (0, 0, {"repartition_type": "tax", "factor_percent": 100.0}), ], } ) self._create_xml_id(record) return record def _create_tax_template_with_account(self, name, chart_template, account): record = self.env["account.tax.template"].create( { "name": name, "amount": 0, "chart_template_id": chart_template.id, "tax_group_id": self.env.ref("account.tax_group_taxes").id, "refund_repartition_line_ids": [ (0, 0, {"repartition_type": "base", "factor_percent": 100.0}), ( 0, 0, { "repartition_type": "tax", "factor_percent": 100.0, "account_id": account.id, }, ), ], "invoice_repartition_line_ids": [ (0, 0, {"repartition_type": "base", "factor_percent": 100.0}), ( 0, 0, { "repartition_type": "tax", "factor_percent": 100.0, "account_id": account.id, }, ), ], } ) self._create_xml_id(record) return record def _create_fp_tmpl(self, name, chart_template): record = self.env["account.fiscal.position.template"].create( {"name": name, "chart_template_id": chart_template.id} ) self._create_xml_id(record) return record def _get_model_data(self, record): return self.env["ir.model.data"].search( [("model", "=", record._name), ("res_id", "=", record.id)] ) def setUp(self): super(TestAccountChartUpdate, self).setUp() self.env.user.lang = "en_US" self.env.user.write( { "groups_id": [ (6, 0, self.env.user.groups_id.ids), (4, self.env.ref("account.group_account_user").id), (4, self.env.ref("account.group_account_invoice").id), (4, self.env.ref("base.group_multi_company").id), ] } ) self.account_type = self.env["account.account.type"].create( { "name": "Test account_chart_update account type", "internal_group": "income", } ) self.account_template = self._create_account_tmpl( "Test", "100000", self.account_type, False ) self.chart_template = self.env.ref( "l10n_generic_coa.configurable_chart_template" ) # Avoid re-creating taxes. # If false, the taxes that are created will be overwrited. self.chart_template.complete_tax_set = True self.account_template.chart_template_id = self.chart_template.id self.account_template_pl = self._create_account_tmpl( "Undistributed Profits/Losses", "999999", self.env.ref("account.data_unaffected_earnings"), self.chart_template, ) self.tax_template = self._create_tax_tmpl("Test tax", self.chart_template) self.fp_template = self._create_fp_tmpl("Test fp", self.chart_template) self.fp_template_tax = self.env["account.fiscal.position.tax.template"].create( {"tax_src_id": self.tax_template.id, "position_id": self.fp_template.id} ) self._create_xml_id(self.fp_template_tax) self.fp_template_account = self.env[ "account.fiscal.position.account.template" ].create( { "account_src_id": self.account_template.id, "account_dest_id": self.account_template.id, "position_id": self.fp_template.id, } ) self._create_xml_id(self.fp_template_account) self.tax_group = self.env["account.tax.group"].create( {"name": "Test tax group"} ) self.account_tag_1 = self.env["account.account.tag"].create( {"name": "Test account tag 1"} ) self.account_tag_2 = self.env["account.account.tag"].create( {"name": "Test account tag 2"} ) self.company = self.env["res.company"].create( { "name": "Test account_chart_update company", "currency_id": self.chart_template.currency_id.id, "country_id": self.env.ref("base.es").id, } ) self.env.user.write( { "company_ids": [ (6, 0, self.env.user.company_ids.ids), (4, self.company.id), ], "company_id": self.company.id, } ) chart_by_company_user = self.chart_template.with_user(self.env.user) chart_by_company_user.try_loading() self.tax = self.env["account.tax"].search( [ ("name", "=", self.tax_template.name), ("company_id", "=", self.company.id), ] ) self.account = self.env["account.account"].search( [ ("code", "=", self.account_template.code), ("company_id", "=", self.company.id), ] ) self.fp = self.env["account.fiscal.position"].search( [("name", "=", self.fp_template.name), ("company_id", "=", self.company.id)] ) # Prepare wizard values self.wizard_obj = self.env["wizard.update.charts.accounts"] self.wizard_vals = { "company_id": self.company.id, "chart_template_id": self.chart_template.id, "code_digits": 6, "lang": "en_US", } @mute_logger("odoo.sql_db") def test_chart_update(self): wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() # Test ir.model.fields name_get field = wizard.fp_field_ids[:1] name = field.with_context(account_chart_update=True).name_get()[0] self.assertEqual(name[0], field.id) self.assertEqual(name[1], "{} ({})".format(field.field_description, field.name)) name = field.name_get()[0] self.assertEqual(name[0], field.id) self.assertEqual( name[1], "{} ({})".format(field.field_description, field.model) ) # Test no changes self.assertEqual(wizard.state, "ready") self.assertFalse(wizard.tax_ids) self.assertFalse(wizard.account_ids) self.assertFalse(wizard.fiscal_position_ids) wizard.unlink() # Add templates new_tax_tmpl = self._create_tax_tmpl("Test tax 2", self.chart_template) new_tax_tmpl.refund_repartition_line_ids[2].write( {"tag_ids": [(6, 0, self.account_tag_1.ids)]} ) new_tax_tmpl.invoice_repartition_line_ids[2].write( {"tag_ids": [(6, 0, self.account_tag_1.ids)]} ) new_account_tmpl = self._create_account_tmpl( "Test account 2", "333333", self.account_type, self.chart_template ) new_fp = self._create_fp_tmpl("Test fp 2", self.chart_template) fp_template_tax = self.env["account.fiscal.position.tax.template"].create( {"tax_src_id": self.tax_template.id, "position_id": new_fp.id} ) self._create_xml_id(fp_template_tax) fp_template_account = self.env[ "account.fiscal.position.account.template" ].create( { "account_src_id": self.account_template.id, "account_dest_id": self.account_template.id, "position_id": new_fp.id, } ) self._create_xml_id(fp_template_account) # Tax with account in repartition lines tax_template_with_account = self._create_tax_template_with_account( "Test tax with account", self.chart_template, new_account_tmpl ) # Check that no action is performed if the option is not selected wizard_vals = self.wizard_vals.copy() wizard_vals.update( { "update_tax": False, "update_account": False, "update_fiscal_position": False, "update_tax_repartition_line_account": False, "update_tax_repartition_line_tags": False, } ) wizard = self.wizard_obj.create(wizard_vals) wizard.action_find_records() self.assertFalse(wizard.tax_ids) self.assertFalse(wizard.account_ids) self.assertFalse(wizard.fiscal_position_ids) wizard.unlink() # Now do the real one for detecting additions wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertTrue(wizard.tax_ids) self.assertEqual( wizard.tax_ids.tax_id, new_tax_tmpl + tax_template_with_account ) for tax in wizard.tax_ids: self.assertEqual(tax.type, "new") self.assertTrue(wizard.account_ids) self.assertEqual(wizard.account_ids.account_id, new_account_tmpl) self.assertTrue(wizard.fiscal_position_ids) self.assertEqual(wizard.fiscal_position_ids.fiscal_position_id, new_fp) self.assertEqual(wizard.fiscal_position_ids.type, "new") wizard.action_update_records() self.assertEqual(wizard.state, "done") self.assertEqual(wizard.new_taxes, 2) self.assertEqual(wizard.new_accounts, 1) self.assertEqual(wizard.new_fps, 1) self.assertTrue(wizard.log) new_tax = self.env["account.tax"].search( [("name", "=", new_tax_tmpl.name), ("company_id", "=", self.company.id)] ) self.assertTrue(new_tax) tax_with_account = self.env["account.tax"].search( [ ("name", "=", "Test tax with account"), ("company_id", "=", self.company.id), ] ) self.assertTrue(tax_with_account) new_account = self.env["account.account"].search( [("code", "=", new_account_tmpl.code), ("company_id", "=", self.company.id)] ) self.assertTrue(new_account) fp = self.env["account.fiscal.position"].search( [("name", "=", new_fp.name), ("company_id", "=", self.company.id)] ) self.assertTrue(fp) self.assertTrue(fp.tax_ids) self.assertTrue(fp.account_ids) wizard.unlink() # Update objects self.tax_template.description = "Test description" self.tax_template.tax_group_id = self.tax_group.id repartition = self.tax_template.refund_repartition_line_ids.filtered( lambda r: r.repartition_type == "tax" )[0] repartition.account_id = new_account_tmpl.id self.account_template.name = "Other name" self.account_template.tag_ids = [ (6, 0, [self.account_tag_1.id, self.account_tag_2.id]) ] self.fp_template.note = "Test note. \n \n Multiline. \n" self.fp_template.account_ids.account_dest_id = new_account_tmpl.id self.fp_template.tax_ids.tax_dest_id = self.tax_template.id wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertTrue(wizard.tax_ids) self.assertEqual( wizard.tax_ids.tax_id.ids, [self.tax_template.id, new_tax_tmpl.id] ) self.assertEqual(list(set(wizard.tax_ids.mapped("type")))[0], "updated") self.assertTrue(wizard.account_ids) self.assertEqual(wizard.account_ids.account_id, self.account_template) self.assertEqual(wizard.account_ids.type, "updated") self.assertTrue(wizard.fiscal_position_ids) self.assertEqual(wizard.fiscal_position_ids.type, "updated") self.assertEqual( wizard.fiscal_position_ids.fiscal_position_id, self.fp_template ) self.assertEqual(wizard.fiscal_position_ids.type, "updated") wizard.action_update_records() self.assertEqual(wizard.updated_taxes, 2) self.assertEqual(wizard.updated_accounts, 1) self.assertEqual(wizard.updated_fps, 1) self.assertEqual(self.tax.description, self.tax_template.description) self.assertEqual(self.tax.tax_group_id, self.tax_group) repartition = self.tax.refund_repartition_line_ids.filtered( lambda r: r.repartition_type == "tax" ) self.assertEqual(repartition.account_id, new_account) self.assertEqual(self.account.name, self.account_template.name) self.assertIn(self.account_tag_1, self.account.tag_ids) self.assertIn(self.account_tag_2, self.account.tag_ids) self.assertEqual(self.fp.note, f"<p>{self.fp_template.note}</p>") self.assertEqual(self.fp.account_ids.account_dest_id, new_account) self.assertEqual(self.fp.tax_ids.tax_dest_id, self.tax) wizard.unlink() # Exclude fields from check self.tax_template.description = "Test description 2" self.account_template.name = "Other name 2" self.fp_template.note = "Test note 2" wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() wizard.tax_field_ids -= self.env["ir.model.fields"].search( [("model", "=", "account.tax.template"), ("name", "=", "description")] ) wizard.account_field_ids -= self.env["ir.model.fields"].search( [("model", "=", "account.account.template"), ("name", "=", "name")] ) wizard.fp_field_ids -= self.env["ir.model.fields"].search( [("model", "=", "account.fiscal.position.template"), ("name", "=", "note")] ) wizard.action_find_records() self.assertTrue(wizard.tax_ids) self.assertFalse(wizard.account_ids) self.assertFalse(wizard.fiscal_position_ids) self.tax_template.description = "Test description" self.account_template.name = "Other name" wizard.unlink() # Remove objects new_tax_tmpl.unlink() wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertTrue(wizard.tax_ids) self.assertEqual(wizard.tax_ids.update_tax_id, new_tax) self.assertEqual(wizard.tax_ids.type, "deleted") wizard.action_update_records() self.assertEqual(wizard.deleted_taxes, 1) self.assertFalse(new_tax.active) wizard.unlink() # Errors on account update self.account_template.currency_id = self.ref("base.USD") self.env["account.move"].create( { "name": "Test move", "move_type": "entry", "journal_id": self.env["account.journal"] .search([("company_id", "=", self.company.id)], limit=1) .id, "date": fields.Date.today(), "line_ids": [ ( 0, 0, { "account_id": self.account.id, "name": "Test move line", "debit": 10, "credit": 0, "amount_currency": 8, "currency_id": self.ref("base.GBP"), }, ), ( 0, 0, { "account_id": self.account.id, "name": "Test move line2", "debit": 0, "credit": 10, "amount_currency": -8, "currency_id": self.ref("base.GBP"), }, ), ], } ) self.tax_template.description = "Other description" wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() with self.assertRaises(Exception): # noqa: B017 wizard.action_update_records() # Errors on account update - continuing after that wizard.continue_on_errors = True wizard.action_update_records() self.assertFalse(self.account.currency_id) self.assertEqual(self.tax.description, self.tax_template.description) self.assertEqual(wizard.rejected_updated_account_number, 1) self.assertEqual(wizard.updated_accounts, 0) wizard.unlink() # Errors on account_creation self.account_template.currency_id = False new_account_tmpl_2 = self._create_account_tmpl( "Test account 3", "444444", self.account_type, self.chart_template ) wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertEqual(wizard.account_ids.type, "new") new_account_tmpl_2.code = "333333" # Trick the code for forcing error with self.assertRaises(Exception): # noqa: B017 wizard.action_update_records() wizard.continue_on_errors = True wizard.action_update_records() self.assertEqual(wizard.rejected_new_account_number, 1) self.assertEqual(wizard.new_accounts, 0) wizard.unlink() def test_matching(self): # Test XML-ID matching self.tax_template.name = "Test 1 tax name changed" self.tax_template.description = "Test tax 1 description changed" self.account_template.code = "200000" self.fp_template.name = "Test 1 fp name changed" wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertEqual(wizard.tax_ids.tax_id, self.tax_template) self.assertEqual(wizard.tax_ids.type, "updated") self.assertEqual(wizard.account_ids.account_id, self.account_template) self.assertEqual(wizard.account_ids.type, "updated") self.assertTrue(wizard.fiscal_position_ids.type, "updated") self.assertEqual( wizard.fiscal_position_ids.fiscal_position_id, self.fp_template ) wizard.action_update_records() self.assertEqual(wizard.updated_taxes, 1) self.assertEqual(wizard.updated_accounts, 1) self.assertEqual(wizard.updated_fps, 1) self.assertEqual(self.tax.name, self.tax_template.name) self.assertEqual(self.tax.description, self.tax_template.description) self.assertEqual(self.account.code, self.account_template.code) self.assertEqual(self.fp.name, self.fp_template.name) wizard.unlink() # Test match by another field, there is no match by XML-ID self._get_model_data(self.tax).unlink() self._get_model_data(self.account).unlink() self._get_model_data(self.fp).unlink() self.tax_template.description = "Test 2 tax description changed" self.account_template.name = "Test 2 account name changed" self.fp_template.note = "<p>Test 2 fp note changed</p>" wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertEqual(wizard.tax_ids.tax_id, self.tax_template) self.assertEqual(wizard.tax_ids.type, "updated") self.assertEqual(wizard.account_ids.account_id, self.account_template) self.assertEqual(wizard.account_ids.type, "updated") self.assertTrue(wizard.fiscal_position_ids.type, "updated") self.assertEqual( wizard.fiscal_position_ids.fiscal_position_id, self.fp_template ) wizard.action_update_records() self.assertEqual(wizard.updated_taxes, 1) self.assertEqual(wizard.updated_accounts, 1) self.assertEqual(wizard.updated_fps, 1) self.assertEqual(self.tax.description, self.tax_template.description) self.assertEqual(self.account.name, self.account_template.name) self.assertEqual(self.fp.note, self.fp_template.note) wizard.unlink() # Test match by name, there is no match by XML-ID or by code self.account_template.code = "300000" wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertEqual(wizard.account_ids.account_id, self.account_template) self.assertEqual(wizard.account_ids.type, "updated") wizard.action_update_records() self.assertEqual(wizard.updated_accounts, 1) self.assertEqual(self.account.code, self.account_template.code) wizard.unlink() # Test 1 recreate XML-ID self.tax_template.description = "Test 4 tax description changed" self.account_template.name = "Test 4 account name changed" self.fp_template.note = "<p>Test 4 fp note changed</p>" self.wizard_vals.update(recreate_xml_ids=True) wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertEqual(wizard.tax_ids.tax_id, self.tax_template) self.assertEqual(wizard.tax_ids.type, "updated") self.assertEqual(wizard.account_ids.account_id, self.account_template) self.assertEqual(wizard.account_ids.type, "updated") self.assertTrue(wizard.fiscal_position_ids.type, "updated") self.assertEqual( wizard.fiscal_position_ids.fiscal_position_id, self.fp_template ) # There is no XML-ID self.assertFalse(list(self.tax.get_xml_id().values())[0]) self.assertFalse(list(self.account.get_xml_id().values())[0]) self.assertFalse(list(self.fp.get_xml_id().values())[0]) # Update for recreating XML-ID wizard.action_update_records() self.assertEqual(wizard.updated_taxes, 1) self.assertEqual(wizard.updated_accounts, 1) self.assertEqual(wizard.updated_fps, 1) self.assertEqual(self.tax.description, self.tax_template.description) self.assertEqual(self.account.name, self.account_template.name) self.assertEqual(self.fp.note, self.fp_template.note) # There is XML-ID now self.assertTrue(list(self.tax.get_xml_id().values())[0]) self.assertTrue(list(self.account.get_xml_id().values())[0]) self.assertTrue(list(self.fp.get_xml_id().values())[0]) wizard.unlink() # Test 2 recreate XML-ID self._get_model_data(self.tax).unlink() self._get_model_data(self.account).unlink() self._get_model_data(self.fp).unlink() wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertEqual(wizard.tax_ids.tax_id, self.tax_template) self.assertEqual(wizard.tax_ids.type, "updated") self.assertEqual(wizard.account_ids.account_id, self.account_template) self.assertEqual(wizard.account_ids.type, "updated") self.assertTrue(wizard.fiscal_position_ids.type, "updated") self.assertEqual( wizard.fiscal_position_ids.fiscal_position_id, self.fp_template ) # There is no XML-ID self.assertFalse(list(self.tax.get_xml_id().values())[0]) self.assertFalse(list(self.account.get_xml_id().values())[0]) self.assertFalse(list(self.fp.get_xml_id().values())[0]) # Update for recreating XML-ID wizard.action_update_records() self.assertEqual(wizard.updated_taxes, 1) self.assertEqual(wizard.updated_accounts, 1) self.assertEqual(wizard.updated_fps, 1) # There is XML-ID now self.assertTrue(list(self.tax.get_xml_id().values())[0]) self.assertTrue(list(self.account.get_xml_id().values())[0]) self.assertTrue(list(self.fp.get_xml_id().values())[0]) wizard.unlink()
44.177966
26,065
53,474
py
PYTHON
15.0
# Copyright 2010 Jordi Esteve, Zikzakmedia S.L. (http://www.zikzakmedia.com) # Copyright 2010 Pexego Sistemas Informáticos S.L.(http://www.pexego.es) # Borja López Soilán # Copyright 2013 Joaquin Gutierrez (http://www.gutierrezweb.es) # Copyright 2015 Antonio Espinosa <antonioea@tecnativa.com> # Copyright 2016 Jairo Llopis <jairo.llopis@tecnativa.com> # Copyright 2016 Jacques-Etienne Baudoux <je@bcim.be> # Copyright 2018 Tecnativa - Pedro M. Baeza # Copyright 2020 Noviat - Luc De Meyer # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging from contextlib import closing from io import StringIO from markupsafe import Markup from odoo import _, api, exceptions, fields, models, tools from odoo.tools import config _logger = logging.getLogger(__name__) EXCEPTION_TEXT = "Traceback (most recent call last)" class WizardUpdateChartsAccounts(models.TransientModel): _name = "wizard.update.charts.accounts" _description = "Wizard Update Charts Accounts" state = fields.Selection( selection=[ ("init", "Configuration"), ("ready", "Select records to update"), ("done", "Wizard completed"), ], string="Status", readonly=True, default="init", ) company_id = fields.Many2one( comodel_name="res.company", string="Company", required=True, default=lambda self: self.env.user.company_id.id, ) chart_template_id = fields.Many2one( comodel_name="account.chart.template", string="Chart Template", ondelete="cascade", required=True, ) chart_template_ids = fields.Many2many( "account.chart.template", string="Chart Templates", compute="_compute_chart_template_ids", help="Includes all chart templates.", ) code_digits = fields.Integer(related="chart_template_id.code_digits") lang = fields.Selection( lambda self: self._get_lang_selection_options(), "Language", required=True, help="For records searched by name (taxes, fiscal " "positions), the template name will be matched against the " "record name on this language.", default=lambda self: self.env.context.get("lang", self.env.user.lang), ) update_tax = fields.Boolean( string="Update taxes", default=True, help="Existing taxes are updated. Taxes are searched by name.", ) update_tax_repartition_line_account = fields.Boolean( string="Update Tax Accounts", default=True, help="Update account_id field on existing Tax repartition lines", ) update_tax_repartition_line_tags = fields.Boolean( string="Update Tax Tags", default=True, help="Update tag_ids field on existing Tax repartition lines", ) update_account = fields.Boolean( string="Update accounts", default=True, help="Existing accounts are updated. Accounts are searched by code.", ) update_fiscal_position = fields.Boolean( string="Update fiscal positions", default=True, help="Existing fiscal positions are updated. Fiscal positions are " "searched by name.", ) continue_on_errors = fields.Boolean( default=False, help="If set, the wizard will continue to the next step even if " "there are minor errors.", ) recreate_xml_ids = fields.Boolean(string="Recreate missing XML-IDs") tax_ids = fields.One2many( comodel_name="wizard.update.charts.accounts.tax", inverse_name="update_chart_wizard_id", string="Taxes", ) account_ids = fields.One2many( comodel_name="wizard.update.charts.accounts.account", inverse_name="update_chart_wizard_id", string="Accounts", ) fiscal_position_ids = fields.One2many( comodel_name="wizard.update.charts.accounts.fiscal.position", inverse_name="update_chart_wizard_id", string="Fiscal positions", ) new_taxes = fields.Integer(compute="_compute_new_taxes_count") new_accounts = fields.Integer(compute="_compute_new_accounts_count") rejected_new_account_number = fields.Integer() new_fps = fields.Integer( string="New fiscal positions", compute="_compute_new_fps_count" ) updated_taxes = fields.Integer(compute="_compute_updated_taxes_count") rejected_updated_account_number = fields.Integer() updated_accounts = fields.Integer(compute="_compute_updated_accounts_count") updated_fps = fields.Integer( string="Updated fiscal positions", compute="_compute_updated_fps_count" ) deleted_taxes = fields.Integer( string="Deactivated taxes", compute="_compute_deleted_taxes_count" ) log = fields.Text(string="Messages and Errors", readonly=True) tax_field_ids = fields.Many2many( comodel_name="ir.model.fields", relation="wizard_update_charts_tax_fields_rel", string="Tax fields", domain=lambda self: self._domain_tax_field_ids(), default=lambda self: self._default_tax_field_ids(), ) account_field_ids = fields.Many2many( comodel_name="ir.model.fields", relation="wizard_update_charts_account_fields_rel", string="Account fields", domain=lambda self: self._domain_account_field_ids(), default=lambda self: self._default_account_field_ids(), ) fp_field_ids = fields.Many2many( comodel_name="ir.model.fields", relation="wizard_update_charts_fp_fields_rel", string="Fiscal position fields", domain=lambda self: self._domain_fp_field_ids(), default=lambda self: self._default_fp_field_ids(), ) tax_matching_ids = fields.One2many( comodel_name="wizard.tax.matching", inverse_name="update_chart_wizard_id", string="Taxes matching", default=lambda self: self._default_tax_matching_ids(), ) account_matching_ids = fields.One2many( comodel_name="wizard.account.matching", inverse_name="update_chart_wizard_id", string="Accounts matching", default=lambda self: self._default_account_matching_ids(), ) fp_matching_ids = fields.One2many( comodel_name="wizard.fp.matching", inverse_name="update_chart_wizard_id", string="Fiscal positions matching", default=lambda self: self._default_fp_matching_ids(), ) def _domain_per_name(self, name): return [ ("model", "=", name), ("name", "not in", tuple(self.fields_to_ignore(name))), ] def _domain_tax_field_ids(self): return self._domain_per_name("account.tax.template") def _domain_account_field_ids(self): return self._domain_per_name("account.account.template") def _domain_fp_field_ids(self): return self._domain_per_name("account.fiscal.position.template") def _default_tax_field_ids(self): return [ (4, x.id) for x in self.env["ir.model.fields"].search(self._domain_tax_field_ids()) ] def _default_account_field_ids(self): return [ (4, x.id) for x in self.env["ir.model.fields"].search( self._domain_account_field_ids() ) ] def _default_fp_field_ids(self): return [ (4, x.id) for x in self.env["ir.model.fields"].search(self._domain_fp_field_ids()) ] def _get_matching_ids(self, model_name, ordered_opts): vals = [] for seq, opt in enumerate(ordered_opts, 1): vals.append((0, False, {"sequence": seq, "matching_value": opt})) all_options = self.env[model_name]._get_matching_selection() all_options = map(lambda x: x[0], all_options) all_options = list(set(all_options) - set(ordered_opts)) for seq, opt in enumerate(all_options, len(ordered_opts) + 1): vals.append((0, False, {"sequence": seq, "matching_value": opt})) return vals def _default_fp_matching_ids(self): ordered_opts = ["xml_id", "name"] return self._get_matching_ids("wizard.fp.matching", ordered_opts) def _default_tax_matching_ids(self): ordered_opts = ["xml_id", "description", "name"] return self._get_matching_ids("wizard.tax.matching", ordered_opts) def _default_account_matching_ids(self): ordered_opts = ["xml_id", "code", "name"] return self._get_matching_ids("wizard.account.matching", ordered_opts) @api.model def _get_lang_selection_options(self): """Gets the available languages for the selection.""" langs = self.env["res.lang"].search([]) return [(lang.code, lang.name) for lang in langs] @api.depends("chart_template_id") def _compute_chart_template_ids(self): all_parents = self.chart_template_id._get_chart_parent_ids() self.chart_template_ids = all_parents @api.depends("tax_ids") def _compute_new_taxes_count(self): self.new_taxes = len(self.tax_ids.filtered(lambda x: x.type == "new")) @api.depends("account_ids") def _compute_new_accounts_count(self): self.new_accounts = ( len(self.account_ids.filtered(lambda x: x.type == "new")) - self.rejected_new_account_number ) @api.depends("fiscal_position_ids") def _compute_new_fps_count(self): self.new_fps = len(self.fiscal_position_ids.filtered(lambda x: x.type == "new")) @api.depends("tax_ids") def _compute_updated_taxes_count(self): self.updated_taxes = len(self.tax_ids.filtered(lambda x: x.type == "updated")) @api.depends("account_ids") def _compute_updated_accounts_count(self): self.updated_accounts = ( len(self.account_ids.filtered(lambda x: x.type == "updated")) - self.rejected_updated_account_number ) @api.depends("fiscal_position_ids") def _compute_updated_fps_count(self): self.updated_fps = len( self.fiscal_position_ids.filtered(lambda x: x.type == "updated") ) @api.depends("tax_ids") def _compute_deleted_taxes_count(self): self.deleted_taxes = len(self.tax_ids.filtered(lambda x: x.type == "deleted")) @api.onchange("company_id") def _onchage_company_update_chart_template(self): self.chart_template_id = self.company_id.chart_template_id def _reopen(self): return { "type": "ir.actions.act_window", "view_mode": "form", "res_id": self.id, "res_model": self._name, "target": "new", # save original model in context, # because selecting the list of available # templates requires a model in context "context": {"default_model": self._name}, } def action_init(self): """Initial action that sets the initial state.""" self.write( { "state": "init", "tax_ids": [(2, r.id, False) for r in self.tax_ids], "account_ids": [(2, r.id, False) for r in self.account_ids], "fiscal_position_ids": [ (2, r.id, False) for r in self.fiscal_position_ids ], } ) return self._reopen() def action_find_records(self): """Searchs for records to update/create and shows them.""" self.clear_caches() self = self.with_context(lang=self.lang) # Search for, and load, the records to create/update. if self.update_tax: self._find_taxes() if self.update_account: self._find_accounts() if self.update_fiscal_position: self._find_fiscal_positions() # Write the results, and go to the next step. self.state = "ready" return self._reopen() def _check_consistency(self): """Method for assuring consistency in operations before performing them. For now, implemented: - If a parent tax is tried to be created, children taxes must be also included to be created. TODO: - Check that needed accounts in taxes/FPs are created at the same time. - Check that needed taxes in FPs are created at the same time. """ taxes2create = self.tax_ids.filtered(lambda x: x.type == "new") parents2create = taxes2create.filtered(lambda x: x.tax_id.children_tax_ids) for parent in parents2create: if bool( parent.tax_id.children_tax_ids - taxes2create.mapped("tax_id") ): # some children taxes are not included to be added raise exceptions.UserError( _( "You have at least one parent tax template (%s) whose " "children taxes are not going to be created. Aborting " "as this will provoke an infinite loop. Please check " "if children have been matched, but not the parent one." ) % parent.tax_id.name ) def action_update_records(self): """Action that creates/updates/deletes the selected elements.""" self._check_consistency() self = self.with_context(lang=self.lang) self.rejected_new_account_number = 0 self.rejected_updated_account_number = 0 with closing(StringIO()) as log_output: handler = logging.StreamHandler(log_output) _logger.addHandler(handler) # Create or update the records. if self.update_tax: todo_dict = self._update_taxes() perform_rest = True if self.update_account: self._update_accounts() if ( EXCEPTION_TEXT in log_output.getvalue() and not self.continue_on_errors ): # Abort early perform_rest = False # Clear this cache for avoiding incorrect account hits (as it was # queried before account creation) self.find_account_by_templates.clear_cache(self) if self.update_tax and perform_rest: self._update_taxes_pending_for_accounts(todo_dict) if self.update_fiscal_position and perform_rest: self._update_fiscal_positions() # Store new chart in the company self.company_id.chart_template_id = self.chart_template_id _logger.removeHandler(handler) self.log = log_output.getvalue() # Check if errors where detected and wether we should stop. if EXCEPTION_TEXT in self.log and not self.continue_on_errors: raise exceptions.UserError( _("One or more errors detected!\n\n%s") % self.log ) # Store the data and go to the next step. self.state = "done" return self._reopen() def _get_real_xml_name(self, template): [external_id] = template.get_external_id().values() (name, module) = external_id.split(".") return "%s.%d_%s" % (name, self.company_id.id, module) @tools.ormcache("templates") def find_taxes_by_templates(self, templates): tax_ids = [] for tax in templates: tax_ids.append(self.find_tax_by_templates(tax)) return self.env["account.tax"].browse(tax_ids) @tools.ormcache("templates") def find_tax_by_templates(self, templates): """Find a tax that matches the template.""" # search inactive taxes too, to avoid re-creating # taxes that have been deactivated before tax_model = self.env["account.tax"].with_context(active_test=False) for template in templates: for matching in self.tax_matching_ids.sorted("sequence"): if matching.matching_value == "xml_id": real = self.env.ref( self._get_real_xml_name(template), raise_if_not_found=False ) if not real: continue criteria = ("id", "=", real.id) else: field_name = matching.matching_value if not template[field_name]: continue criteria = (field_name, "=", template[field_name]) result = tax_model.search( [ criteria, ("company_id", "=", self.company_id.id), ("type_tax_use", "=", template.type_tax_use), ], limit=1, ) if result: return result.id return False @tools.ormcache("templates", "current_repartition") def find_repartition_by_templates( self, templates, current_repartition, tax, inverse_name ): upd_acc = self.update_tax_repartition_line_account upd_tags = self.update_tax_repartition_line_tags result = [] existing_ids = [] for i, tpl in enumerate(templates): factor_percent = tpl.factor_percent repartition_type = tpl.repartition_type account_id = self.find_account_by_templates(tpl.account_id) tags = self.env["account.account.tag"] tags += tpl.plus_report_line_ids.mapped("tag_ids").filtered( lambda x: not x.tax_negate ) tags += tpl.minus_report_line_ids.mapped("tag_ids").filtered( lambda x: x.tax_negate ) tags += tpl.tag_ids existing = self.env["account.tax.repartition.line"] existing_candidates = current_repartition.filtered( lambda r: r.factor_percent == factor_percent and r.repartition_type == repartition_type and r.id not in existing_ids ) if len(existing_candidates) == 1: existing = existing_candidates elif len(existing_candidates) > 1: # We may have this situation in case of e.g. 50%/50% on tax. # In this case we assume that the repartition line order # is the same between templates and actual tax objects existing_candidate = current_repartition[i] if existing_candidate in existing_candidates: existing = existing_candidate if existing: existing_ids.append(existing.id) upd_vals = {} if upd_acc and existing.account_id.id != account_id: upd_vals["account_id"] = account_id if upd_tags: if existing.tag_ids != tags: upd_vals["tag_ids"] = [(6, 0, tags.ids)] if upd_vals: # update record result.append((1, existing.id, upd_vals)) if not existing: # create a new mapping result.append( ( 0, 0, { inverse_name: tax.id, "factor_percent": factor_percent, "repartition_type": repartition_type, "account_id": account_id, "tag_ids": [(6, 0, tags.ids)], }, ) ) # Mark to be removed the lines not found remove_ids = [x for x in current_repartition.ids if x not in existing_ids] result += [(2, x) for x in remove_ids] return result @api.model @tools.ormcache("code") def padded_code(self, code): """Return a right-zero-padded code with the chosen digits.""" return code.ljust(self.code_digits, "0") @tools.ormcache("templates") def find_accounts_by_templates(self, templates): account_ids = [] for account in templates: account_ids.append(self.find_account_by_templates(account)) return self.env["account.account"].browse(account_ids) @tools.ormcache("templates") def find_account_by_templates(self, templates): """Find an account that matches the template.""" account_model = self.env["account.account"] for matching in self.account_matching_ids.sorted("sequence"): if matching.matching_value == "xml_id": real = self.env["account.account"] for template in templates: try: real |= self.env.ref(self._get_real_xml_name(template)) except BaseException: _logger.info("Is not real xml Name") if not real: continue criteria = ("id", "in", real.ids) elif matching.matching_value == "code": codes = templates.mapped("code") if not codes: continue criteria = ("code", "in", list(map(self.padded_code, codes))) else: field_name = matching.matching_value field_values = templates.mapped(field_name) if not field_values: continue criteria = (field_name, "in", field_values) result = account_model.search( [criteria, ("company_id", "=", self.company_id.id)] ) if result: return result.id return False @tools.ormcache("templates") def find_fp_by_templates(self, templates): """Find a real fiscal position from a template.""" fp_model = self.env["account.fiscal.position"] for matching in self.fp_matching_ids.sorted("sequence"): if matching.matching_value == "xml_id": real = self.env["account.fiscal.position"] for template in templates: try: real |= self.env.ref(self._get_real_xml_name(template)) except BaseException: _logger.info("Is not real xml Name") if not real: continue criteria = ("id", "in", real.ids) else: field_name = matching.matching_value field_values = templates.mapped(field_name) if not field_values: continue criteria = (field_name, "in", field_values) result = fp_model.search( [criteria, ("company_id", "=", self.company_id.id)], limit=1 ) if result: return result.id return False @tools.ormcache("templates", "current_fp_accounts") def find_fp_account_by_templates(self, templates, current_fp_accounts): result = [] for tpl in templates: pos_id = self.find_fp_by_templates(tpl.position_id) src_id = self.find_account_by_templates(tpl.account_src_id) dest_id = self.find_account_by_templates(tpl.account_dest_id) existing = self.env["account.fiscal.position.account"].search( [ ("position_id", "=", pos_id), ("account_src_id", "=", src_id), ("account_dest_id", "=", dest_id), ] ) if not existing: # create a new mapping result.append( ( 0, 0, { "position_id": pos_id, "account_src_id": src_id, "account_dest_id": dest_id, }, ) ) else: current_fp_accounts -= existing # Mark to be removed the lines not found if current_fp_accounts: result += [(2, x.id) for x in current_fp_accounts] return result @tools.ormcache("templates", "current_fp_taxes") def find_fp_tax_by_templates(self, templates, current_fp_taxes): result = [] for tpl in templates: pos_id = self.find_fp_by_templates(tpl.position_id) src_id = self.find_tax_by_templates(tpl.tax_src_id) dest_id = self.find_tax_by_templates(tpl.tax_dest_id) existing = self.env["account.fiscal.position.tax"].search( [ ("position_id", "=", pos_id), ("tax_src_id", "=", src_id), ("tax_dest_id", "=", dest_id), ] ) if not existing: # create a new mapping result.append( ( 0, 0, { "position_id": pos_id, "tax_src_id": src_id, "tax_dest_id": dest_id, }, ) ) else: current_fp_taxes -= existing # Mark to be removed the lines not found if current_fp_taxes: result += [(2, x.id) for x in current_fp_taxes] return result @api.model @tools.ormcache("name") def fields_to_ignore(self, name): """Get fields that will not be used when checking differences. :param str template: A template record. :param str name: The name of the template model. :return set: Fields to ignore in diff. """ specials_mapping = { "account.tax.template": {"chart_template_id", "children_tax_ids"}, "account.account.template": set(self.env["mail.thread"]._fields) | {"chart_template_id", "root_id", "nocreate"}, "account.fiscal.position.template": {"chart_template_id"}, } specials = { "display_name", "__last_update", "company_id", } | specials_mapping.get(name, set()) return set(models.MAGIC_COLUMNS) | specials @api.model def diff_fields(self, template, real): # noqa: C901 """Get fields that are different in template and real records. :param odoo.models.Model template: Template record. :param odoo.models.Model real: Real record. :return dict: Fields that are different in both records, and the expected value. """ result = dict() ignore = self.fields_to_ignore(template._name) template_field_mapping = { "account.tax.template": self.tax_field_ids, "account.account.template": self.account_field_ids, "account.fiscal.position.template": self.fp_field_ids, } to_include = template_field_mapping[template._name].mapped("name") for key, field in template._fields.items(): if key in ignore or key not in to_include or not hasattr(real, key): continue expected = None # Translate template records to reals for comparison relation = field.get_description(self.env).get("relation", "") if relation: if relation == "account.tax.template": expected = self.find_taxes_by_templates(template[key]) elif relation == "account.account.template": expected = self.find_accounts_by_templates(template[key]) elif relation == "account.fiscal.position.tax.template": expected = self.find_fp_tax_by_templates(template[key], real[key]) elif relation == "account.fiscal.position.account.template": expected = self.find_fp_account_by_templates( template[key], real[key] ) elif relation == "account.tax.repartition.line.template": expected = self.find_repartition_by_templates( template[key], real[key], real, field.inverse_name ) # Register detected differences if expected is not None: if expected != [] and ( key in ["invoice_repartition_line_ids", "refund_repartition_line_ids"] or expected != real[key] ): result[key] = expected else: template_value, real_value = template[key], real[key] if template._name == "account.account.template" and key == "code": template_value = self.padded_code(template["code"]) # Normalize values when one field is Char and the other is Html if ( isinstance(template_value, str) and isinstance(real_value, Markup) ) or ( isinstance(template_value, Markup) and isinstance(real_value, str) ): template_value = Markup(template_value).striptags() real_value = Markup(real_value).striptags() if template_value != real_value: result[key] = template_value # Avoid to cache recordset references if key in result: if isinstance(real._fields[key], fields.Many2many): result[key] = [(6, 0, result[key].ids)] elif isinstance(real._fields[key], fields.Many2one): result[key] = result[key].id return result @api.model def diff_notes(self, template, real): """Get notes for humans on why is this record going to be updated. :param openerp.models.Model template: Template record. :param openerp.models.Model real: Real record. :return str: Notes result. """ result = list() different_fields = sorted( template._fields[f].get_description(self.env)["string"] for f in self.diff_fields(template, real).keys() ) if different_fields: result.append( _("Differences in these fields: %s.") % ", ".join(different_fields) ) # Special for taxes if template._name == "account.tax.template": if not real.active: result.append(_("Tax is disabled.")) return "\n".join(result) @tools.ormcache("self", "template", "real_obj") def missing_xml_id(self, template, real_obj): ir_model_data = self.env["ir.model.data"] template_xmlid = ir_model_data.search( [("model", "=", template._name), ("res_id", "=", template.id)] ) new_xml_id = "%d_%s" % (self.company_id.id, template_xmlid.name) return not ir_model_data.search( [ ("res_id", "=", real_obj.id), ("model", "=", real_obj._name), ("module", "=", template_xmlid.module), ("name", "=", new_xml_id), ] ) def _domain_taxes_to_deactivate(self, found_taxes_ids): return [ ("company_id", "=", self.company_id.id), ("id", "not in", found_taxes_ids), ("active", "=", True), ] def _find_taxes(self): """Search for, and load, tax templates to create/update/delete.""" found_taxes_ids = [] self.tax_ids.unlink() # Search for changes between template and real tax for template in self.chart_template_ids.with_context(active_test=False).mapped( "tax_template_ids" ): # Check if the template matches a real tax tax_id = self.find_tax_by_templates(template) if not tax_id: # Tax to be created self.tax_ids.create( { "tax_id": template.id, "update_chart_wizard_id": self.id, "type": "new", "notes": _("Name or description not found."), } ) else: found_taxes_ids.append(tax_id) # Check the tax for changes tax = self.env["account.tax"].browse(tax_id) notes = self.diff_notes(template, tax) if self.recreate_xml_ids and self.missing_xml_id(template, tax): notes += (notes and "\n" or "") + _("Missing XML-ID.") if notes: # Tax to be updated self.tax_ids.create( { "tax_id": template.id, "update_chart_wizard_id": self.id, "type": "updated", "update_tax_id": tax_id, "notes": notes, } ) # search for taxes not in the template and propose them for # deactivation taxes_to_deactivate = self.env["account.tax"].search( self._domain_taxes_to_deactivate(found_taxes_ids) ) for tax in taxes_to_deactivate: self.tax_ids.create( { "update_chart_wizard_id": self.id, "type": "deleted", "update_tax_id": tax.id, "notes": _("To deactivate: not in the template"), } ) def _find_accounts(self): """Load account templates to create/update.""" self.account_ids.unlink() for template in self.chart_template_ids.mapped("account_ids"): # Search for a real account that matches the template account_id = self.find_account_by_templates(template) if not account_id: # Account to be created self.account_ids.create( { "account_id": template.id, "update_chart_wizard_id": self.id, "type": "new", "notes": _("No account found with this code."), } ) else: # Check the account for changes account = self.env["account.account"].browse(account_id) notes = self.diff_notes(template, account) if self.recreate_xml_ids and self.missing_xml_id(template, account): notes += (notes and "\n" or "") + _("Missing XML-ID.") if notes: # Account to be updated self.account_ids.create( { "account_id": template.id, "update_chart_wizard_id": self.id, "type": "updated", "update_account_id": account_id, "notes": notes, } ) def _find_fiscal_positions(self): """Load fiscal position templates to create/update.""" wiz_fp = self.env["wizard.update.charts.accounts.fiscal.position"] self.fiscal_position_ids.unlink() # Search for new / updated fiscal positions templates = self.env["account.fiscal.position.template"].search( [("chart_template_id", "in", self.chart_template_ids.ids)] ) for template in templates: # Search for a real fiscal position that matches the template fp_id = self.find_fp_by_templates(template) if not fp_id: # Fiscal position to be created wiz_fp.create( { "fiscal_position_id": template.id, "update_chart_wizard_id": self.id, "type": "new", "notes": _("No fiscal position found with this name."), } ) else: # Check the fiscal position for changes fp = self.env["account.fiscal.position"].browse(fp_id) notes = self.diff_notes(template, fp) if self.recreate_xml_ids and self.missing_xml_id(template, fp): notes += (notes and "\n" or "") + _("Missing XML-ID.") if notes: # Fiscal position template to be updated wiz_fp.create( { "fiscal_position_id": template.id, "update_chart_wizard_id": self.id, "type": "updated", "update_fiscal_position_id": fp_id, "notes": notes, } ) def recreate_xml_id(self, template, real_obj): ir_model_data = self.env["ir.model.data"] template_xmlid = ir_model_data.search( [("model", "=", template._name), ("res_id", "=", template.id)] ) new_xml_id = "%d_%s" % (self.company_id.id, template_xmlid.name) ir_model_data.search( [("model", "=", real_obj._name), ("res_id", "=", real_obj.id)] ).unlink() template_xmlid.copy( { "model": real_obj._name, "res_id": real_obj.id, "name": new_xml_id, "noupdate": True, } ) def _update_taxes(self): """Process taxes to create/update/deactivate.""" # First create taxes in batch taxes_to_create = self.tax_ids.filtered(lambda x: x.type == "new") todo_dict = taxes_to_create.mapped("tax_id")._generate_tax(self.company_id) template_to_tax_dict = {} for key in todo_dict["tax_template_to_tax"].keys(): template_to_tax_dict[key.id] = todo_dict["tax_template_to_tax"][key].id for wiz_tax in taxes_to_create: new_tax = self.env["account.tax"].browse( template_to_tax_dict[wiz_tax.tax_id.id] ) _logger.info( _("Created tax %s."), "'{}' (ID:{})".format(new_tax.name, new_tax.id) ) for wiz_tax in self.tax_ids.filtered(lambda x: x.type != "new"): template, tax = wiz_tax.tax_id, wiz_tax.update_tax_id # Deactivate tax if wiz_tax.type == "deleted": tax.active = False _logger.info(_("Deactivated tax %s."), "'%s'" % tax.name) continue else: updated = False for key, value in self.diff_fields(template, tax).items(): # We defer update because account might not be created yet if key in [ "cash_basis_transition_account_id", "invoice_repartition_line_ids", "refund_repartition_line_ids", ]: continue tax[key] = value updated = True if updated: _logger.info(_("Updated tax %s."), "'%s'" % template.name) if self.recreate_xml_ids and self.missing_xml_id(template, tax): self.recreate_xml_id(template, tax) _logger.info( _("Updated tax %s. (Recreated XML-IDs)"), "'%s'" % template.name ) return todo_dict def _update_accounts(self): """Process accounts to create/update.""" for wiz_account in self.account_ids: account, template = (wiz_account.update_account_id, wiz_account.account_id) if wiz_account.type == "new": # Create the account tax_template_ref = { tax.id: self.find_tax_by_templates(tax) for tax in template.tax_ids } vals = self.chart_template_id._get_account_vals( self.company_id, template, self.padded_code(template.code), tax_template_ref, ) try: with self.env.cr.savepoint(): self.chart_template_id.create_record_with_xmlid( self.company_id, template, "account.account", vals ) _logger.info( _("Created account %s."), "'{} - {}'".format(vals["code"], vals["name"]), ) except Exception: self.rejected_new_account_number += 1 if config["test_enable"]: _logger.info(EXCEPTION_TEXT) else: # pragma: no cover _logger.exception( "ERROR: " + _("Exception creating account %s."), "'{} - {}'".format(template.code, template.name), ) if not self.continue_on_errors: break else: # Update the account try: with self.env.cr.savepoint(): for key, value in iter( self.diff_fields(template, account).items() ): account[key] = value _logger.info( _("Updated account %s."), "'{} - {}'".format(account.code, account.name), ) if self.recreate_xml_ids and self.missing_xml_id( template, account ): self.recreate_xml_id(template, account) _logger.info( _("Updated account %s. (Recreated XML-ID)"), "'{} - {}'".format(account.code, account.name), ) except Exception: self.rejected_updated_account_number += 1 if config["test_enable"]: _logger.info(EXCEPTION_TEXT) else: # pragma: no cover _logger.exception( "ERROR: " + _("Exception writing account %s."), "'{} - {}'".format(account.code, account.name), ) if not self.continue_on_errors: break def _update_taxes_pending_for_accounts(self, todo_dict): """Updates the taxes (created or updated on previous steps) to set the references to the accounts (the taxes where created/updated first, when the referenced accounts are still not available). """ done = self.env["account.tax"] for k, v in todo_dict["account_dict"]["account.tax"].items(): vals = {} for fld in [ "cash_basis_transition_account_id", ]: if v[fld]: acc_id = self.find_account_by_templates( self.env["account.account.template"].browse(v[fld].id) ) if acc_id: vals[fld] = acc_id else: raise exceptions.UserError( _("No real account found for template account with ID %s") % v[fld].id ) if vals: tax = self.env["account.tax"].browse(k) tax.write(vals) done |= tax for rep_line, v in todo_dict["account_dict"][ "account.tax.repartition.line" ].items(): if v["account_id"]: acc_id = self.find_account_by_templates( self.env["account.account.template"].browse(v["account_id"].id) ) if acc_id: rep_line.write({"account_id": acc_id}) done |= rep_line.invoice_tax_id or rep_line.refund_tax_id else: raise exceptions.UserError( _("No real account found for template account with ID %s") % v["account_id"].id ) for wiz_tax in self.tax_ids.filtered(lambda r: r.type == "updated"): template = wiz_tax.tax_id tax = wiz_tax.update_tax_id vals = {} for key, value in self.diff_fields(template, tax).items(): if key in { "cash_basis_transition_account_id", "invoice_repartition_line_ids", "refund_repartition_line_ids", }: vals[key] = value if vals: tax.write(vals) done |= tax if done: _logger.info( _("Post-updated account fields for taxes with IDs %s."), "%s" % done.ids ) def _prepare_fp_vals(self, fp_template): # Tax mappings tax_mapping = [] for fp_tax in fp_template.tax_ids: # Create the fp tax mapping tax_mapping.append( { "tax_src_id": self.find_tax_by_templates(fp_tax.tax_src_id), "tax_dest_id": self.find_tax_by_templates(fp_tax.tax_dest_id), } ) # Account mappings account_mapping = [] for fp_account in fp_template.account_ids: # Create the fp account mapping account_mapping.append( { "account_src_id": ( self.find_account_by_templates(fp_account.account_src_id) ), "account_dest_id": ( self.find_account_by_templates(fp_account.account_dest_id) ), } ) return { "company_id": self.company_id.id, "name": fp_template.name, "tax_ids": [(0, 0, x) for x in tax_mapping], "account_ids": [(0, 0, x) for x in account_mapping], } def _update_fiscal_positions(self): """Process fiscal position templates to create/update.""" for wiz_fp in self.fiscal_position_ids: fp, template = (wiz_fp.update_fiscal_position_id, wiz_fp.fiscal_position_id) if wiz_fp.type == "new": # Create a new fiscal position self.chart_template_id.create_record_with_xmlid( self.company_id, template, "account.fiscal.position", self._prepare_fp_vals(template), ) _logger.info(_("Created fiscal position %s."), "'%s'" % template.name) else: for key, value in self.diff_fields(template, fp).items(): fp[key] = value _logger.info( _("Updated fiscal position %s."), "'%s'" % template.name ) if self.recreate_xml_ids and self.missing_xml_id(template, fp): self.recreate_xml_id(template, fp) _logger.info( _("Updated fiscal position %s. (Recreated XML-ID)"), "'%s'" % template.name, ) class WizardUpdateChartsAccountsTax(models.TransientModel): _name = "wizard.update.charts.accounts.tax" _description = "Tax that needs to be updated (new or updated in the " "template)." tax_id = fields.Many2one( comodel_name="account.tax.template", string="Tax template", ondelete="set null" ) update_chart_wizard_id = fields.Many2one( comodel_name="wizard.update.charts.accounts", string="Update chart wizard", required=True, ondelete="cascade", ) type = fields.Selection( selection=[ ("new", "New template"), ("updated", "Updated template"), ("deleted", "Tax to deactivate"), ], readonly=False, ) type_tax_use = fields.Selection(related="tax_id.type_tax_use", readonly=True) update_tax_id = fields.Many2one( comodel_name="account.tax", string="Tax to update", required=False, ondelete="set null", ) notes = fields.Text(readonly=True) recreate_xml_ids = fields.Boolean(related="update_chart_wizard_id.recreate_xml_ids") class WizardUpdateChartsAccountsAccount(models.TransientModel): _name = "wizard.update.charts.accounts.account" _description = ( "Account that needs to be updated (new or updated in the " "template)." ) account_id = fields.Many2one( comodel_name="account.account.template", string="Account template", required=True, ) update_chart_wizard_id = fields.Many2one( comodel_name="wizard.update.charts.accounts", string="Update chart wizard", required=True, ondelete="cascade", ) type = fields.Selection( selection=[("new", "New template"), ("updated", "Updated template")], readonly=False, ) update_account_id = fields.Many2one( comodel_name="account.account", string="Account to update", required=False, ondelete="set null", ) notes = fields.Text(readonly=True) recreate_xml_ids = fields.Boolean(related="update_chart_wizard_id.recreate_xml_ids") class WizardUpdateChartsAccountsFiscalPosition(models.TransientModel): _name = "wizard.update.charts.accounts.fiscal.position" _description = ( "Fiscal position that needs to be updated (new or updated " "in the template)." ) fiscal_position_id = fields.Many2one( comodel_name="account.fiscal.position.template", string="Fiscal position template", required=True, ) update_chart_wizard_id = fields.Many2one( comodel_name="wizard.update.charts.accounts", string="Update chart wizard", required=True, ondelete="cascade", ) type = fields.Selection( selection=[("new", "New template"), ("updated", "Updated template")], readonly=False, ) update_fiscal_position_id = fields.Many2one( comodel_name="account.fiscal.position", required=False, string="Fiscal position to update", ondelete="set null", ) notes = fields.Text(readonly=True) recreate_xml_ids = fields.Boolean( string="Recreate missing XML-IDs", related="update_chart_wizard_id.recreate_xml_ids", ) class WizardMatching(models.TransientModel): _name = "wizard.matching" _description = "Wizard Matching" _order = "sequence" update_chart_wizard_id = fields.Many2one( comodel_name="wizard.update.charts.accounts", string="Update chart wizard", required=True, ondelete="cascade", ) sequence = fields.Integer(required=True, default=1) matching_value = fields.Selection(selection="_get_matching_selection") def _get_matching_selection(self): return [("xml_id", "XML-ID")] def _selection_from_files(self, model_name, field_opts): result = [] for opt in field_opts: model = self.env[model_name] desc = model._fields[opt].get_description(self.env)["string"] result.append((opt, "{} ({})".format(desc, opt))) return result class WizardTaxMatching(models.TransientModel): _name = "wizard.tax.matching" _description = "Wizard Tax Matching" _inherit = "wizard.matching" def _get_matching_selection(self): vals = super(WizardTaxMatching, self)._get_matching_selection() vals += self._selection_from_files( "account.tax.template", ["description", "name"] ) return vals class WizardAccountMatching(models.TransientModel): _name = "wizard.account.matching" _description = "Wizard Account Matching" _inherit = "wizard.matching" def _get_matching_selection(self): vals = super(WizardAccountMatching, self)._get_matching_selection() vals += self._selection_from_files("account.account.template", ["code", "name"]) return vals class WizardFpMatching(models.TransientModel): _name = "wizard.fp.matching" _description = "Wizard Fiscal Position Matching" _inherit = "wizard.matching" def _get_matching_selection(self): vals = super(WizardFpMatching, self)._get_matching_selection() vals += self._selection_from_files("account.fiscal.position.template", ["name"]) return vals
39.963378
53,471
628
py
PYTHON
15.0
# Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class IrModelFields(models.Model): _inherit = "ir.model.fields" def name_get(self): """Return special label when showing fields in chart update wizard.""" if self.env.context.get("account_chart_update"): res = [] for record in self: res.append( (record.id, "{} ({})".format(record.field_description, record.name)) ) return res return super(IrModelFields, self).name_get()
33.052632
628
597
py
PYTHON
15.0
# Copyright (C) 2021 Open Source Integrators # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Move Line Menu", "version": "15.0.1.0.0", "author": "Open Source Integrators, Odoo Community Association (OCA)", "summary": "Adds a Journal Items menu", "website": "https://github.com/OCA/account-financial-tools", "license": "AGPL-3", "depends": ["account"], "category": "Accounting", "data": [ "views/account_menu_views.xml", ], "installable": True, "maintainer": "dreispt", "development_status": "Beta", }
31.421053
597
569
py
PYTHON
15.0
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Assets Number", "version": "15.0.1.0.0", "license": "AGPL-3", "depends": ["account_asset_management"], "author": "Ecosoft, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "category": "Accounting & Finance", "data": [ "views/account_asset_profile.xml", "views/account_asset.xml", "report/account_asset_number_report.xml", ], }
33.470588
569
1,764
py
PYTHON
15.0
# Copyright 2022 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import time from odoo.tests import tagged from odoo.addons.account_asset_management.tests.test_account_asset_management import ( TestAssetManagement, ) @tagged("post_install", "-at_install") class TestAssetNumber(TestAssetManagement): @classmethod def setUpClass(cls): super().setUpClass() cls.sequence_asset = cls.env["ir.sequence"].create( { "name": "Asset Number Test", "code": "account.asset.sequence", "implementation": "standard", "prefix": "AC", "padding": 5, } ) def test_01_asset_number(self): # use sequence number on profile_id self.car5y.write( { "use_sequence": True, "sequence_id": self.sequence_asset.id, } ) asset = self.asset_model.create( { "name": "test asset", "profile_id": self.car5y.id, "purchase_value": 1000, "salvage_value": 0, "date_start": time.strftime("%Y-07-07"), "method_time": "year", "method": "degr-linear", "method_progress_factor": 0.40, "method_number": 5, "method_period": "year", "prorata": False, } ) asset.compute_depreciation_board() asset.refresh() # check number in the asset self.assertFalse(asset.number) asset.validate() self.assertTrue(asset.number) self.assertEqual(asset.number[:2], "AC")
30.947368
1,764
717
py
PYTHON
15.0
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class AccountAssetProfile(models.Model): _inherit = "account.asset.profile" use_sequence = fields.Boolean( string="Auto Asset Number by Sequence", default=False, help="If check, asset number auto run by sequence.", ) sequence_id = fields.Many2one( comodel_name="ir.sequence", string="Asset Number Sequence", domain=lambda self: self._get_domain_sequence_id(), ) @api.model def _get_domain_sequence_id(self): return [("company_id", "in", [False, self.env.company.id])]
31.173913
717
1,470
py
PYTHON
15.0
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, fields, models class AccountAsset(models.Model): _inherit = "account.asset" _rec_name = "number" number = fields.Char( string="Asset Number", default="", index=True, copy=False, ) use_sequence = fields.Boolean(related="profile_id.use_sequence") def validate(self): res = super().validate() for asset in self: asset_profile = asset.profile_id if ( asset.number in [False, ""] and asset_profile.use_sequence and asset_profile.sequence_id ): asset.number = asset_profile.sequence_id.next_by_id() return res @api.model def _xls_acquisition_fields(self): acquisition_fields = super()._xls_acquisition_fields() acquisition_fields.insert(acquisition_fields.index("name"), "number") return acquisition_fields @api.model def _xls_active_fields(self): active_fields = super()._xls_active_fields() active_fields.insert(active_fields.index("name"), "number") return active_fields @api.model def _xls_removal_fields(self): removal_fields = super()._xls_removal_fields() removal_fields.insert(removal_fields.index("name"), "number") return removal_fields
31.276596
1,470
739
py
PYTHON
15.0
# Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.co.th) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import models class AssetReportXlsx(models.AbstractModel): _inherit = "report.account_asset_management.asset_report_xls" def _get_asset_template(self): res = super()._get_asset_template() res.update( { "number": { "header": {"type": "string", "value": self._("Number")}, "asset": { "type": "string", "value": self._render("asset.number or ''"), }, "width": 20, } } ) return res
30.791667
739
1,905
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). def post_init_hook(cr, registry): """INIT sale references in account move line""" # FOR stock moves cr.execute( """ UPDATE account_move_line aml SET sale_line_id = sm.sale_line_id FROM account_move_line aml2 INNER JOIN stock_move sm ON aml2.stock_move_id = sm.id WHERE aml.id = aml2.id; """ ) # FOR invoices cr.execute( """ UPDATE account_move_line aml SET sale_line_id = sol.id FROM account_move_line aml2 INNER JOIN account_move am ON am.id = aml2.move_id INNER JOIN sale_order_line_invoice_rel rel ON rel.invoice_line_id = aml2.id INNER JOIN sale_order_line sol ON rel.order_line_id = sol.id AND sol.product_id = aml2.product_id WHERE aml.id = aml2.id; """ ) # NOW we can fill the SO cr.execute( """ UPDATE account_move_line aml SET sale_order_id = sol.order_id FROM sale_order_line AS sol WHERE aml.sale_line_id = sol.id RETURNING aml.move_id """ ) # NOW we can fill the lines without invoice_id (Odoo put it very # complicated) cr.execute( """ UPDATE account_move_line aml SET sale_order_id = so.id FROM sale_order so LEFT JOIN account_move_line aml2 ON aml2.sale_order_id = so.id WHERE aml2.move_id = aml.move_id """ ) cr.execute( """ update account_move_line aml set sale_line_id = sol.id FROM account_move_line aml2 INNER JOIN sale_order so ON so.id = aml2.sale_order_id INNER JOIN sale_order_line sol ON so.id = sol.order_id AND sol.product_id = aml2.product_id WHERE aml.id = aml2.id; """ )
27.214286
1,905
668
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Account Move Line Sale Info", "summary": "Introduces the purchase order line to the journal items", "version": "15.0.1.0.3", "author": "ForgeFlow S.L., " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "category": "Generic", "depends": [ "account_move_line_stock_info", "sale_stock", ], "license": "AGPL-3", "data": ["security/account_security.xml", "views/account_move_view.xml"], "installable": True, "post_init_hook": "post_init_hook", }
35.157895
668
10,086
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.tests import common class TestAccountMoveLineSaleInfo(common.TransactionCase): def setUp(self): super(TestAccountMoveLineSaleInfo, self).setUp() self.sale_model = self.env["sale.order"] self.sale_line_model = self.env["sale.order.line"] self.product_model = self.env["product.product"] self.product_ctg_model = self.env["product.category"] self.acc_type_model = self.env["account.account.type"] self.account_model = self.env["account.account"] self.aml_model = self.env["account.move.line"] self.res_users_model = self.env["res.users"] self.partner1 = self.env.ref("base.res_partner_1") self.location_stock = self.env.ref("stock.stock_location_stock") self.company = self.env.ref("base.main_company") self.group_sale_user = self.env.ref("sales_team.group_sale_salesman") self.group_account_invoice = self.env.ref("account.group_account_invoice") self.group_account_manager = self.env.ref("account.group_account_manager") # Create account for Goods Received Not Invoiced acc_type = self._create_account_type("equity", "other") name = "Goods Received Not Invoiced" code = "grni" self.account_grni = self._create_account(acc_type, name, code, self.company) # Create account for Cost of Goods Sold acc_type = self._create_account_type("expense", "other") name = "Cost of Goods Sold" code = "cogs" self.account_cogs = self._create_account(acc_type, name, code, self.company) # Create account for Inventory acc_type = self._create_account_type("asset", "other") name = "Inventory" code = "inventory" self.account_inventory = self._create_account( acc_type, name, code, self.company ) # Create Product self.product = self._create_product() # Create users self.sale_user = self._create_user( "sale_user", [self.group_sale_user, self.group_account_invoice], self.company, ) self.account_invoice = self._create_user( "account_invoice", [self.group_account_invoice], self.company ) self.account_manager = self._create_user( "account_manager", [self.group_account_manager], self.company ) self.JournalObj = self.env["account.journal"] self.journal_sale = self.JournalObj.create( { "name": "Test journal sale", "code": "TST-JRNL-S", "type": "sale", "company_id": self.company.id, } ) def _create_user(self, login, groups, company): """Create a user.""" group_ids = [group.id for group in groups] user = self.res_users_model.with_context(**{"no_reset_password": True}).create( { "name": "Test User", "login": login, "password": "demo", "email": "test@yourcompany.com", "company_id": company.id, "company_ids": [(4, company.id)], "groups_id": [(6, 0, group_ids)], } ) return user.id def _create_account_type(self, name, atype): acc_type = self.acc_type_model.create( {"name": name, "type": atype, "internal_group": name} ) return acc_type def _create_account(self, acc_type, name, code, company): """Create an account.""" account = self.account_model.create( { "name": name, "code": code, "user_type_id": acc_type.id, "company_id": company.id, } ) return account def _create_product(self): """Create a Product.""" # group_ids = [group.id for group in groups] product_ctg = self.product_ctg_model.create( { "name": "test_product_ctg", "property_stock_valuation_account_id": self.account_inventory.id, "property_valuation": "real_time", "property_stock_account_input_categ_id": self.account_grni.id, "property_stock_account_output_categ_id": self.account_cogs.id, } ) product = self.product_model.create( { "name": "test_product", "categ_id": product_ctg.id, "type": "product", "standard_price": 1.0, "list_price": 1.0, } ) return product def _create_sale(self, line_products): """Create a sale order. ``line_products`` is a list of tuple [(product, qty)] """ lines = [] for product, qty in line_products: line_values = { "name": product.name, "product_id": product.id, "product_uom_qty": qty, "product_uom": product.uom_id.id, "price_unit": 500, } lines.append((0, 0, line_values)) return self.sale_model.create( {"partner_id": self.partner1.id, "order_line": lines} ) def _get_balance(self, domain): """ Call read_group method and return the balance of particular account. """ aml_rec = self.aml_model.read_group( domain, ["debit", "credit", "account_id"], ["account_id"] ) if aml_rec: return aml_rec[0].get("debit", 0) - aml_rec[0].get("credit", 0) else: return 0.0 def _check_account_balance(self, account_id, sale_line=None, expected_balance=0.0): """ Check the balance of the account """ domain = [("account_id", "=", account_id)] if sale_line: domain.extend([("sale_line_id", "=", sale_line.id)]) balance = self._get_balance(domain) if sale_line: self.assertEqual( balance, expected_balance, "Balance is not %s for sale Line %s." % (str(expected_balance), sale_line.name), ) def move_reversal_wiz(self, move): wizard = ( self.env["account.move.reversal"] .with_context(active_model="account.move", active_ids=[move.id]) .create({"journal_id": move.journal_id.id}) ) return wizard def test_01_sale_invoice(self): """Test that the po line moves from the sale order to the account move line and to the invoice line. """ sale = self._create_sale([(self.product, 1)]) so_line = False for line in sale.order_line: so_line = line break sale.action_confirm() picking = sale.picking_ids[0] picking.move_lines.write({"quantity_done": 1.0}) picking.button_validate() expected_balance = -1.0 self._check_account_balance( self.account_inventory.id, sale_line=so_line, expected_balance=expected_balance, ) self.context = { "active_model": "sale.order", "active_ids": [sale.id], "active_id": sale.id, "default_journal_id": self.journal_sale.id, } payment = ( self.env["sale.advance.payment.inv"] .with_context(**self.context) .create({"advance_payment_method": "delivered"}) ) payment.create_invoices() invoice = sale.invoice_ids[0] invoice._post() for aml in invoice.line_ids: if aml.product_id == so_line.product_id and aml.move_id: self.assertEqual( aml.sale_line_id, so_line, "sale Order line has not been copied " "from the invoice to the account move line.", ) def test_02_name_get(self): sale = self._create_sale([(self.product, 1)]) so_line = sale.order_line[0] name_get = so_line.with_context(**{"so_line_info": True}).name_get() self.assertEqual( name_get, [ ( so_line.id, "[%s] %s - (%s)" % ( so_line.order_id.name, so_line.product_id.name, so_line.order_id.state, ), ) ], ) name_get_no_ctx = so_line.with_context(**{}).name_get() self.assertEqual( name_get_no_ctx, [ ( so_line.id, "{} - {}".format(so_line.order_id.name, so_line.product_id.name), ) ], ) def test_03_credit_note(self): """Test the credit note is linked to the sale order line""" sale = self._create_sale([(self.product, 1)]) so_line = False for line in sale.order_line: so_line = line break sale.action_confirm() picking = sale.picking_ids[0] picking.move_lines.write({"quantity_done": 1.0}) picking.button_validate() sale._create_invoices() invoice = sale.invoice_ids[0] invoice._post() reversal_wizard = self.move_reversal_wiz(invoice) credit_note = self.env["account.move"].browse( reversal_wizard.reverse_moves()["res_id"] ) for aml in credit_note.line_ids: if aml.product_id == so_line.product_id and aml.move_id: self.assertEqual( aml.sale_line_id, so_line, "sale Order line has not been copied " "from the invoice to the credit note.", )
36.150538
10,086
1,571
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountMove(models.Model): _inherit = "account.move" def _stock_account_prepare_anglo_saxon_out_lines_vals(self): res = super()._stock_account_prepare_anglo_saxon_out_lines_vals() for i, vals in enumerate(res): am = self.env["account.move"].browse(vals["move_id"]) sale_line_id = am.invoice_line_ids.filtered( lambda il: il.product_id.id == vals["product_id"] and il.quantity == vals["quantity"] ).mapped("sale_line_ids") if sale_line_id and len(sale_line_id) == 1: res[i]["sale_line_id"] = sale_line_id.id return res class AccountMoveLine(models.Model): _inherit = "account.move.line" sale_line_id = fields.Many2one( comodel_name="sale.order.line", string="Sale Order Line", ondelete="set null", index=True, copy=False, ) sale_order_id = fields.Many2one( comodel_name="sale.order", related="sale_line_id.order_id", string="Sales Order", ondelete="set null", store=True, index=True, copy=False, ) def _copy_data_extend_business_fields(self, values): # Same way Odoo standard does for purchase_line_id field res = super(AccountMoveLine, self)._copy_data_extend_business_fields(values) values["sale_line_id"] = self.sale_line_id.id return res
32.061224
1,571
820
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models class SaleOrderLine(models.Model): _inherit = "sale.order.line" def name_get(self): result = [] orig_name = dict(super(SaleOrderLine, self).name_get()) for line in self: name = orig_name[line.id] if self.env.context.get("so_line_info", False): name = "[{}] {} - ({})".format( line.order_id.name, line.product_id.name, line.order_id.state ) result.append((line.id, name)) return result def _prepare_invoice_line(self, **optional_values): res = super()._prepare_invoice_line(**optional_values) res["sale_line_id"] = self.id return res
32.8
820
575
py
PYTHON
15.0
# Copyright 2020 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, models class StockMove(models.Model): _inherit = "stock.move" @api.model def _prepare_account_move_line( self, qty, cost, credit_account_id, debit_account_id, description ): res = super(StockMove, self)._prepare_account_move_line( qty, cost, credit_account_id, debit_account_id, description ) for line in res: line[2]["sale_line_id"] = self.sale_line_id.id return res
31.944444
575
563
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Lock To Date", "summary": """ Allows to set an account lock date in the future.""", "version": "15.0.1.0.0", "license": "AGPL-3", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "installable": True, "depends": ["account"], "data": [ "security/ir.model.access.csv", "wizards/account_update_lock_to_date.xml", ], }
31.277778
563
5,284
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from datetime import datetime from odoo.exceptions import ValidationError from odoo.tests.common import TransactionCase from odoo.tools.misc import DEFAULT_SERVER_DATE_FORMAT class TestAccountLockToDateUpdate(TransactionCase): def setUp(self): super(TestAccountLockToDateUpdate, self).setUp() self.company = self.env.ref("base.main_company") self.demo_user = self.env.ref("base.user_demo") self.adviser_group = self.env.ref("account.group_account_manager") self.UpdateLockToDateUpdateObj = self.env[ "account.update.lock_to_date" ].with_user(self.demo_user) self.AccountObj = self.env["account.account"] self.AccountJournalObj = self.env["account.journal"] self.AccountMoveObj = self.env["account.move"] self.bank_journal = self.AccountJournalObj.create( { "name": "Bank Journal - BJ", "code": "BJ", "type": "bank", "company_id": self.company.id, } ) self.account_type_recv = self.env.ref("account.data_account_type_receivable") self.account_type_rev = self.env.ref("account.data_account_type_revenue") self.account_recv = self.AccountObj.create( { "code": "RECV_DR", "name": "Receivable (test)", "reconcile": True, "user_type_id": self.account_type_recv.id, } ) self.account_sale = self.AccountObj.create( { "code": "SALE_DR", "name": "Receivable (sale)", "reconcile": True, "user_type_id": self.account_type_rev.id, } ) def create_account_move(self, date_str): return self.AccountMoveObj.create( { "journal_id": self.bank_journal.id, "date": date_str, "line_ids": [ ( 0, 0, { "name": "Debit", "debit": 1000, "account_id": self.account_recv.id, }, ), ( 0, 0, { "name": "Credit", "credit": 1000, "account_id": self.account_sale.id, }, ), ], } ) def create_account_lock_date_update(self): return self.UpdateLockToDateUpdateObj.create({"company_id": self.company.id}) def test_01_update_without_access(self): wizard = self.create_account_lock_date_update() wizard.write( { "period_lock_to_date": "2900-01-01", "fiscalyear_lock_to_date": "2900-01-01", } ) self.demo_user.write({"groups_id": [(3, self.adviser_group.id)]}) with self.assertRaises(ValidationError): wizard.with_user(self.demo_user.id).execute() def test_02_update_with_access(self): wizard = self.create_account_lock_date_update() wizard.write( { "period_lock_to_date": "2900-01-01", "fiscalyear_lock_to_date": "2900-02-01", } ) self.demo_user.write({"groups_id": [(4, self.adviser_group.id)]}) wizard.with_user(self.demo_user.id).execute() self.assertEqual( self.company.period_lock_to_date, datetime.strptime("2900-01-01", DEFAULT_SERVER_DATE_FORMAT).date(), ) self.assertEqual( self.company.fiscalyear_lock_to_date, datetime.strptime("2900-02-01", DEFAULT_SERVER_DATE_FORMAT).date(), ) def test_03_create_move_outside_period(self): """We test that we cannot create journal entries after the locked date""" self.company.period_lock_to_date = "2900-01-01" self.company.fiscalyear_lock_to_date = "2900-02-01" move = self.create_account_move("2900-01-01") with self.assertRaises(ValidationError): move.with_user(self.demo_user.id).action_post() def test_04_create_move_inside_period(self): """We test that we can successfully create a journal entry within period that is not locked""" self.company.period_lock_to_date = "2900-01-01" self.company.fiscalyear_lock_to_date = "2900-02-01" move = self.create_account_move("2800-01-01") move.with_user(self.demo_user.id).action_post() self.assertEqual(move.state, "posted") def test_05_lock_period_with_draft_moves(self): """We test that we cannot change the fiscal year lock to date if there are draft journal entries after that date.""" self.create_account_move("2900-02-01") with self.assertRaises(ValidationError): self.company.period_lock_to_date = "2900-01-01" self.company.fiscalyear_lock_to_date = "2900-02-01"
38.569343
5,284
2,127
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import _, models from odoo.exceptions import ValidationError class AccountMove(models.Model): _inherit = "account.move" def _check_lock_to_dates(self): """Prevent moves that are on or after lock to date. Advisors have more freedom than other users and are only constrained by the fiscalyear_lock_to_date. Other users will also be restricted by the period_lock_to_date. """ is_advisor = self.user_has_groups("account.group_account_manager") for move in self: advisor_lock_to_date = move.company_id.fiscalyear_lock_to_date user_lock_to_date = move.company_id.period_lock_to_date if is_advisor: lock_to_date = advisor_lock_to_date or False else: lock_to_date = ( min(user_lock_to_date, advisor_lock_to_date) if user_lock_to_date and advisor_lock_to_date else user_lock_to_date or advisor_lock_to_date or False ) if lock_to_date and move.date >= lock_to_date: if is_advisor: message = _( "You cannot add/modify entries after and " "inclusive of the lock to date %s" ) % (lock_to_date,) else: message = _( "You cannot add/modify entries after and " "inclusive of the lock to date %s. " "Check the company settings or ask someone " "with the 'Adviser' role" ) % (lock_to_date,) raise ValidationError(message) def action_post(self): self._check_lock_to_dates() return super().action_post() def button_cancel(self): self._check_lock_to_dates() return super().button_cancel() def button_draft(self): self._check_lock_to_dates() return super().button_draft()
39.388889
2,127
5,483
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import calendar import time from datetime import datetime from time import mktime from dateutil.relativedelta import relativedelta from odoo import SUPERUSER_ID, _, fields, models from odoo.exceptions import ValidationError from odoo.tools.misc import DEFAULT_SERVER_DATE_FORMAT class ResCompany(models.Model): _inherit = "res.company" period_lock_to_date = fields.Date( string="Lock To Date for Non-Advisers", help="Only users with the 'Adviser' role can edit " "accounts after this date. " "Use it for period locking inside an open fiscal year, " "for example.", ) fiscalyear_lock_to_date = fields.Date( string="Lock To Date", help="No users, including Advisers, can edit accounts after " "this date. Use it for fiscal year locking for example.", ) def write(self, vals): # fiscalyear_lock_date can't be set to a prior date if "fiscalyear_lock_to_date" in vals or "period_lock_to_date" in vals: self._check_lock_to_dates(vals) return super(ResCompany, self).write(vals) def _check_lock_to_dates(self, vals): """Check the lock to dates for the current companies. :param vals: The values passed to the write method. """ period_lock_to_date = vals.get("period_lock_to_date") fiscalyear_lock_to_date = vals.get("fiscalyear_lock_to_date") next_month = datetime.now() + relativedelta(months=+1) days_next_month = calendar.monthrange(next_month.year, next_month.month) next_month = next_month.replace(day=days_next_month[1]).timetuple() next_month = datetime.fromtimestamp(mktime(next_month)).date() for company in self: old_fiscalyear_lock_to_date = company.fiscalyear_lock_to_date # The user attempts to remove the lock date for advisors if ( old_fiscalyear_lock_to_date and not fiscalyear_lock_to_date and "fiscalyear_lock_to_date" in vals and not self._uid == SUPERUSER_ID ): raise ValidationError( _( "The lock date for advisors is " "irreversible and can't be removed." ) ) # The user attempts to set a lock date for advisors prior # to the previous one if ( old_fiscalyear_lock_to_date and fiscalyear_lock_to_date and fiscalyear_lock_to_date > old_fiscalyear_lock_to_date ): raise ValidationError( _( "The new lock to date for advisors must be set after " "the previous lock to date." ) ) # In case of no new fiscal year in vals, fallback to the oldest if not fiscalyear_lock_to_date: if old_fiscalyear_lock_to_date: fiscalyear_lock_to_date = old_fiscalyear_lock_to_date else: continue # The user attempts to set a lock date for advisors after # the first day of next month if fiscalyear_lock_to_date < next_month: raise ValidationError( _( "You cannot lock a period that is not finished yet. " "Please make sure that the lock date for advisors is " "set at or after the last day of the next month." ) ) # In case of no new period lock to date in vals, # fallback to the one defined in the company if not period_lock_to_date: if company.period_lock_date: period_lock_to_date = time.strptime( company.period_lock_to_date, DEFAULT_SERVER_DATE_FORMAT ) else: continue # The user attempts to set a lock to date for advisors # prior to the lock to date for users if period_lock_to_date > fiscalyear_lock_to_date: raise ValidationError( _( "You cannot define stricter conditions on advisors " "than on users. Please make sure that the lock date " "on advisor is set after the lock date for users." ) ) def _validate_fiscalyear_lock(self, values): res = super()._validate_fiscalyear_lock(values) if values.get("fiscalyear_lock_to_date"): nb_draft_entries = self.env["account.move"].search( [ ("company_id", "in", self.ids), ("state", "=", "draft"), ("date", ">=", values["fiscalyear_lock_to_date"]), ], limit=1, ) if nb_draft_entries: raise ValidationError( _( "There are still unposted entries in the period to date" " you want to lock. " "You should either post or delete them." ) ) return res
39.731884
5,483
2,093
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import SUPERUSER_ID, _, api, fields, models from odoo.exceptions import ValidationError class AccountUpdateLockToDate(models.TransientModel): _name = "account.update.lock_to_date" _description = "Account Update Lock_to_date" company_id = fields.Many2one( comodel_name="res.company", string="Company", required=True, default=lambda self: self.env.user.company_id, ) period_lock_to_date = fields.Date( string="Lock To Date for Non-Advisers", help="Only users with the 'Adviser' role can edit accounts after " "and inclusive of this date. Use it for period locking inside an " "open fiscal year, for example.", ) fiscalyear_lock_to_date = fields.Date( string="Lock To Date", help="No users, including Advisers, can edit accounts after and " "inclusive of this date. Use it for fiscal year locking for " "example.", ) @api.model def default_get(self, field_list): res = super(AccountUpdateLockToDate, self).default_get(field_list) company = self.env.user.company_id res.update( { "company_id": company.id, "period_lock_to_date": company.period_lock_to_date, "fiscalyear_lock_to_date": company.fiscalyear_lock_to_date, } ) return res def _check_execute_allowed(self): self.ensure_one() has_adviser_group = self.env.user.has_group("account.group_account_manager") if not (has_adviser_group or self.env.uid == SUPERUSER_ID): raise ValidationError(_("You are not allowed to execute this action.")) def execute(self): self.ensure_one() self._check_execute_allowed() self.company_id.sudo().write( { "period_lock_to_date": self.period_lock_to_date, "fiscalyear_lock_to_date": self.fiscalyear_lock_to_date, } )
36.086207
2,093
772
py
PYTHON
15.0
# Copyright 2016-2020 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Costcenter", "summary": "Cost center information for invoice lines", "author": "Onestein, Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/account-financial-tools", "category": "Accounting", "version": "15.0.1.0.0", "depends": ["account"], "data": [ "security/ir.model.access.csv", "security/account_cost_center_security.xml", "views/account_cost_center_views.xml", "views/account_move_views.xml", "views/account_move_line_views.xml", "views/account_invoice_report_views.xml", ], "installable": True, }
35.090909
772
3,579
py
PYTHON
15.0
# Copyright 2017-2020 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests import Form, tagged from odoo.addons.account.tests.common import AccountTestInvoicingCommon @tagged("post_install", "-at_install") class TestAccountCostCenter(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.expenses_account = cls.env["account.account"].create( { "user_type_id": cls.env.ref("account.data_account_type_expenses").id, "code": "EXPTEST", "name": "Test expense account", } ) cls.costcenter = cls.env["account.cost.center"].create( { "name": "Cost Center Test", "code": "CC1", "company_id": cls.env.company.id, } ) # Invoice created with tests Form cls.invoice1 = cls.init_invoice("in_invoice") # Invoice created with standard create cls.invoice2 = ( cls.env["account.move"] .with_context(cost_center_id=cls.costcenter.id) .create( { "partner_id": cls.env.ref("base.res_partner_2").id, "move_type": "in_invoice", "cost_center_id": cls.costcenter.id, } ) ) cls.invoice2.invoice_line_ids += cls.env["account.move.line"].new( { "product_id": cls.env.ref("product.product_product_4").id, "quantity": 1.0, "price_unit": 130.0, "name": "product that cost 130", "cost_center_id": cls.costcenter.id, } ) def test_01_check_lines(self): self.assertFalse( self.invoice1.invoice_line_ids.cost_center_id, "Default cost center per line not set", ) self.assertEqual( self.invoice2.invoice_line_ids[0].cost_center_id, self.costcenter ) def test_02_check_lines(self): invoice_lines = self.invoice1.invoice_line_ids self.assertFalse(any(line.cost_center_id for line in invoice_lines)) invoice_form = Form(self.invoice1) invoice_form.cost_center_id = self.costcenter with invoice_form.invoice_line_ids.new() as line: line.name = "Test line2" line.quantity = 2.0 line.price_unit = 200.0 line.account_id = self.expenses_account self.invoice1 = invoice_form.save() invoice_lines = self.invoice1.invoice_line_ids self.assertFalse(any(line.cost_center_id for line in invoice_lines)) self.assertTrue(any(not line.cost_center_id for line in invoice_lines)) def test_03_confirm_invoice(self): invoice_lines = self.invoice2.invoice_line_ids for move_line in invoice_lines: self.assertEqual(move_line.cost_center_id, self.costcenter) for move_line in self.invoice2.line_ids - invoice_lines: self.assertFalse(move_line.cost_center_id) def test_04_search_read(self): expected_cost_center = self.costcenter records = self.env["account.invoice.report"].sudo().search_read([]) result = records[0].get("cost_center_id") self.assertTrue(result) self.assertEqual(result[0], expected_cost_center.id) self.assertEqual(result[1], expected_cost_center.name)
36.520408
3,579
452
py
PYTHON
15.0
# Copyright 2015-2020 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountCostCenter(models.Model): _name = "account.cost.center" _description = "Account Cost Center" name = fields.Char(string="Title", required=True) code = fields.Char(required=True) company_id = fields.Many2one("res.company", default=lambda self: self.env.company)
34.769231
452
405
py
PYTHON
15.0
# Copyright 2015-2020 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountMove(models.Model): _inherit = "account.move" cost_center_id = fields.Many2one( "account.cost.center", readonly=True, states={"draft": [("readonly", False)]}, help="Default Cost Center", )
27
405
303
py
PYTHON
15.0
# Copyright 2015-2020 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountMoveLine(models.Model): _inherit = "account.move.line" cost_center_id = fields.Many2one("account.cost.center", index=True)
30.3
303
479
py
PYTHON
15.0
# Copyright 2015-2020 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountInvoiceReport(models.Model): _inherit = "account.invoice.report" cost_center_id = fields.Many2one("account.cost.center", readonly=True) def _select(self): return ( super(AccountInvoiceReport, self)._select() + ", line.cost_center_id as cost_center_id" )
29.9375
479
536
py
PYTHON
15.0
# Copyright 2015-2019 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2021 CorporateHub (https://corporatehub.eu) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Account Invoice Constraint Chronology", "version": "15.0.1.0.1", "author": "Odoo Community Association (OCA), ACSONE SA/NV, CorporateHub", "website": "https://github.com/OCA/account-financial-tools", "license": "AGPL-3", "category": "Accounting", "depends": ["account"], "data": ["view/account_journal.xml"], }
41.230769
536
5,931
py
PYTHON
15.0
# Copyright 2015-2019 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2021 CorporateHub (https://corporatehub.eu) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from datetime import timedelta from odoo import fields from odoo.exceptions import UserError from odoo.tests import common class TestAccountInvoiceConstraintChronology(common.TransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.company = cls.env.ref("base.main_company") cls.partner_2 = cls.env.ref("base.res_partner_2") cls.today = fields.Date.today() cls.yesterday = cls.today - timedelta(days=1) cls.tomorrow = cls.today + timedelta(days=1) cls.AccountJournal = cls.env["account.journal"] cls.sale_journal = cls.AccountJournal.create( { "name": "Sale journal", "code": "SALE", "type": "sale", "check_chronology": True, } ) cls.ProductProduct = cls.env["product.product"] cls.product = cls.ProductProduct.create({"name": "Product"}) cls.AccountMove = cls.env["account.move"] with common.Form( cls.AccountMove.with_context(default_move_type="out_invoice") ) as invoice_form: invoice_form.invoice_date = cls.today invoice_form.partner_id = cls.partner_2 invoice_form.journal_id = cls.sale_journal with invoice_form.invoice_line_ids.new() as line_form: line_form.product_id = cls.product cls.invoice_1 = invoice_form.save() cls.invoice_2 = cls.invoice_1.copy() cls.AccountMoveReversal = cls.env["account.move.reversal"] def test_journal_type_change(self): self.assertTrue(self.sale_journal.check_chronology) with common.Form(self.sale_journal) as form: form.type = "general" self.assertFalse(self.sale_journal.check_chronology) with common.Form(self.sale_journal) as form: form.type = "sale" self.assertFalse(self.sale_journal.check_chronology) with common.Form(self.sale_journal) as form: form.check_chronology = True self.assertTrue(self.sale_journal.check_chronology) def test_invoice_draft(self): self.invoice_1.invoice_date = self.yesterday self.invoice_2.invoice_date = self.today with self.assertRaises(UserError): self.invoice_2.action_post() def test_invoice_draft_nocheck(self): self.invoice_1.invoice_date = self.yesterday self.invoice_2.invoice_date = self.today self.sale_journal.check_chronology = False self.invoice_2.action_post() def test_invoice_validate(self): self.invoice_1.invoice_date = self.tomorrow self.invoice_1.action_post() self.invoice_2.invoice_date = self.today with self.assertRaises(UserError): self.invoice_2.action_post() def test_invoice_without_date(self): self.invoice_1.invoice_date = self.yesterday self.invoice_2.invoice_date = False with self.assertRaises(UserError): self.invoice_2.action_post() def test_invoice_refund_before(self): self.invoice_1.invoice_date = self.tomorrow self.invoice_1.action_post() refund = ( self.AccountMoveReversal.with_context( active_model="account.move", active_ids=self.invoice_1.ids, ) .create( { "date": self.today, "reason": "no reason", "refund_method": "refund", "journal_id": self.invoice_1.journal_id.id, } ) .reverse_moves() ) refund = self.AccountMove.browse(refund["res_id"]) refund.action_post() def test_invoice_refund_before_same_sequence(self): self.sale_journal.refund_sequence = False self.invoice_1.invoice_date = self.tomorrow self.invoice_1.action_post() refund = ( self.AccountMoveReversal.with_context( active_model="account.move", active_ids=self.invoice_1.ids, ) .create( { "date": self.today, "reason": "no reason", "refund_method": "refund", "journal_id": self.invoice_1.journal_id.id, } ) .reverse_moves() ) refund = self.AccountMove.browse(refund["res_id"]) with self.assertRaises(UserError): refund.action_post() def test_invoice_higher_number(self): self.invoice_1.invoice_date = self.yesterday self.invoice_1.action_post() self.invoice_1.button_draft() self.invoice_1.invoice_date = False self.invoice_2.invoice_date = self.today self.invoice_2.action_post() self.invoice_1.invoice_date = self.tomorrow with self.assertRaisesRegex(UserError, "higher number"): self.invoice_1.action_post() def test_modify_validated_past_invoice(self): """We've got an invoice from yesterday that we need to modify but new ones have been posted since. As the invoice already has a name, we should be able to validate it""" self.invoice_1.invoice_date = self.yesterday self.invoice_1.action_post() self.invoice_2.invoice_date = self.today self.invoice_2.action_post() self.invoice_1.button_cancel() self.invoice_1.button_draft() self.invoice_1.action_post() self.invoice_1_5 = self.invoice_1.copy() self.invoice_1_5.invoice_date = self.yesterday with self.assertRaises(UserError): self.invoice_1_5.action_post()
36.838509
5,931
4,039
py
PYTHON
15.0
# Copyright 2015-2019 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2021 CorporateHub (https://corporatehub.eu) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, models from odoo.exceptions import UserError from odoo.osv import expression from odoo.tools.misc import format_date class AccountMove(models.Model): _inherit = "account.move" def _get_conflicting_invoices_domain(self): self.ensure_one() domain = [ ("journal_id", "=", self.journal_id.id), ("move_type", "!=", "entry"), ] if self.journal_id.refund_sequence: domain.append(("move_type", "=", self.move_type)) return domain def _get_older_conflicting_invoices_domain(self): self.ensure_one() return expression.AND( [ self._get_conflicting_invoices_domain(), [ ("state", "=", "draft"), ("invoice_date", "!=", False), ("invoice_date", "<", self.invoice_date), ], ] ) def _raise_older_conflicting_invoices(self): self.ensure_one() raise UserError( _( "Chronology conflict: A conflicting draft invoice dated before " "{date_invoice} exists, please validate it first." ).format(date_invoice=format_date(self.env, self.invoice_date)) ) def _get_newer_conflicting_invoices_domain(self): self.ensure_one() return expression.AND( [ self._get_conflicting_invoices_domain(), [("state", "=", "posted"), ("invoice_date", ">", self.invoice_date)], ] ) def _raise_newer_conflicting_invoices(self): self.ensure_one() raise UserError( _( "Chronology conflict: A conflicting validated invoice dated after " "{date_invoice} exists." ).format(date_invoice=format_date(self.env, self.invoice_date)) ) def _get_sequence_order_conflicting_invoices_domain(self): self.ensure_one() if not self.name or self.name == "/": return expression.FALSE_DOMAIN last_sequence = self._get_last_sequence() if not last_sequence or self.name > last_sequence: return expression.FALSE_DOMAIN return expression.AND( [ [("name", "=", last_sequence)], self._get_conflicting_invoices_domain(), [("state", "=", "posted"), ("invoice_date", "<", self.invoice_date)], ] ) def _raise_sequence_ordering_conflict(self): self.ensure_one() raise UserError( _( "Chronology conflict: An invoice with a higher number {highest_name}" " dated before {date_invoice} exists." ).format( highest_name=self._get_last_sequence(), date_invoice=format_date(self.env, self.invoice_date), ) ) def write(self, vals): if vals.get("state") != "posted": return super().write(vals) previously_validated = self.filtered(lambda m: m.name and m.name != "/") newly_posted = self.filtered(lambda move: move.state != "posted") res = super().write(vals) for move in newly_posted & self.filtered("journal_id.check_chronology"): if self.search( move._get_sequence_order_conflicting_invoices_domain(), limit=1 ): move._raise_sequence_ordering_conflict() if self.search(move._get_older_conflicting_invoices_domain(), limit=1): move._raise_older_conflicting_invoices() if move in previously_validated: continue if self.search(move._get_newer_conflicting_invoices_domain(), limit=1): move._raise_newer_conflicting_invoices() return res
36.0625
4,039
539
py
PYTHON
15.0
# Copyright 2015-2019 ACSONE SA/NV (<http://acsone.eu>) # Copyright 2021 CorporateHub (https://corporatehub.eu) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import api, fields, models class AccountJournal(models.Model): _inherit = "account.journal" check_chronology = fields.Boolean() @api.onchange("type") def _onchange_type(self): res = super()._onchange_type() if self.type not in ["sale", "purchase"]: self.check_chronology = False return res
29.944444
539
1,061
py
PYTHON
15.0
# Copyright 2012-2021 Akretion France (http://www.akretion.com/) # @author: Benoît GUILLOT <benoit.guillot@akretion.com> # @author: Chafique DELLI <chafique.delli@akretion.com> # @author: Alexis de Lattre <alexis.delattre@akretion.com> # Copyright 2018-2021 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Account Check Deposit", "version": "15.0.1.0.0", "category": "Accounting", "license": "AGPL-3", "summary": "Manage deposit of checks to the bank", "author": "Akretion, Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "depends": ["account"], "development_status": "Mature", "data": [ "security/ir.model.access.csv", "security/check_deposit_security.xml", "data/sequence.xml", "views/account_check_deposit_view.xml", "views/account_move_line_view.xml", "report/report.xml", "report/report_checkdeposit.xml", ], "installable": True, }
37.857143
1,060
6,126
py
PYTHON
15.0
# Copyright 2014-2016 Akretion - Mourad EL HADJ MIMOUNE # Copyright 2018 Tecnativa - Pedro M. Baeza # Copyright 2022 Tecnativa - Víctor Martínez # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo.tests import tagged from odoo.tests.common import TransactionCase @tagged("post_install", "-at_install") class TestPayment(TransactionCase): def setUp(self): super().setUp() self.account_model = self.env["account.account"] self.partner = self.env["res.partner"].create({"name": "Test partner"}) self.main_company = self.env.company self.currency = self.main_company.currency_id self.product = self.env["product.product"].create({"name": "Test product"}) # check if those accounts exist otherwise create them self.account_model.create( { "code": "411100", "name": "Debtors - (test)", "reconcile": True, "user_type_id": self.ref("account.data_account_type_receivable"), "company_id": self.main_company.id, } ) self.account_model.create( { "code": "707100", "name": "Product Sales - (test)", "user_type_id": self.ref("account.data_account_type_revenue"), "company_id": self.main_company.id, } ) received_check_account = self.account_model.create( { "code": "511200", "name": "Received check - (test)", "reconcile": True, "user_type_id": self.ref("account.data_account_type_current_assets"), "company_id": self.main_company.id, } ) self.transfer_account = self.account_model.create( { "code": "511500", "name": "Check deposis waiting for credit on bank account - (test)", "reconcile": True, "user_type_id": self.ref("account.data_account_type_current_assets"), "company_id": self.main_company.id, } ) self.manual_method_in = self.env.ref("account.account_payment_method_manual_in") self.check_journal = self._create_journal( "received check", "bank", "CHK", received_check_account ) self.bank_journal = self._create_journal( "Bank Test Chq", "bank", "TEST@@", self.transfer_account ) self.bank_journal.bank_account_id = self.env["res.partner.bank"].create( { "acc_number": "SI56 1910 0000 0123 438 584", "partner_id": self.main_company.partner_id.id, } ) def _create_journal(self, name, journal_type, code, payment_account): return self.env["account.journal"].create( { "name": name, "type": journal_type, "code": code, "company_id": self.main_company.id, "inbound_payment_method_line_ids": [ ( 0, 0, { "payment_method_id": self.manual_method_in.id, "payment_account_id": payment_account.id, }, ) ], } ) def create_invoice(self, amount=100): """Returns an open invoice""" invoice = self.env["account.move"].create( { "company_id": self.main_company.id, "move_type": "out_invoice", "partner_id": self.partner.id, "currency_id": self.currency.id, "invoice_line_ids": [ ( 0, 0, { "product_id": self.product.id, "quantity": 1, "price_unit": amount, }, ) ], } ) invoice.action_post() return invoice def create_check_deposit(self): """Returns an validated check deposit""" check_deposit = self.env["account.check.deposit"].create( { "company_id": self.main_company.id, "journal_id": self.check_journal.id, "bank_journal_id": self.bank_journal.id, "currency_id": self.currency.id, } ) check_deposit.get_all_checks() check_deposit.validate_deposit() return check_deposit def test_full_payment_process(self): """Create a payment for on invoice by check, post it and create check deposit""" inv_1 = self.create_invoice(amount=100) inv_2 = self.create_invoice(amount=200) register_payments = ( self.env["account.payment.register"] .with_context( active_model="account.move", active_ids=[inv_1.id, inv_2.id], default_journal_id=self.check_journal.id, ) .create({"group_payment": True}) ) payment = register_payments._create_payments() self.assertAlmostEqual(payment.amount, 300) self.assertEqual(payment.state, "posted") check_deposit = self.create_check_deposit() liquidity_aml = check_deposit.move_id.line_ids.filtered( lambda r: r.account_id == self.transfer_account ) self.assertAlmostEqual(check_deposit.total_amount, 300) self.assertAlmostEqual(liquidity_aml.debit, 300) self.assertEqual(check_deposit.move_id.state, "posted") self.assertEqual(check_deposit.state, "done") res = ( self.env["ir.actions.report"] ._get_report_from_name("account_check_deposit.report_checkdeposit") ._render_qweb_text(check_deposit.ids, False) ) self.assertRegex(str(res[0]), "SI56 1910 0000 0123 438 584")
39.006369
6,124
706
py
PYTHON
15.0
# Copyright 2012-2021 Akretion France (http://www.akretion.com/) # @author: Benoît GUILLOT <benoit.guillot@akretion.com> # @author: Chafique DELLI <chafique.delli@akretion.com> # @author: Alexis de Lattre <alexis.delattre@akretion.com> # @author: Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com> # Copyright 2018-2021 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import fields, models class AccountMoveLine(models.Model): _inherit = "account.move.line" check_deposit_id = fields.Many2one( comodel_name="account.check.deposit", string="Check Deposit", copy=False, check_company=True, )
35.25
705
12,848
py
PYTHON
15.0
# Copyright 2012-2021 Akretion (http://www.akretion.com/) # @author: Benoît GUILLOT <benoit.guillot@akretion.com> # @author: Chafique DELLI <chafique.delli@akretion.com> # @author: Alexis de Lattre <alexis.delattre@akretion.com> # @author: Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com> # Copyright 2018-2021 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import UserError, ValidationError class AccountCheckDeposit(models.Model): _name = "account.check.deposit" _description = "Account Check Deposit" _inherit = ["mail.thread", "mail.activity.mixin"] _order = "deposit_date desc" _check_company_auto = True name = fields.Char(size=64, readonly=True, default="/", copy=False) check_payment_ids = fields.One2many( comodel_name="account.move.line", inverse_name="check_deposit_id", string="Check Payments", states={"done": [("readonly", "=", True)]}, ) deposit_date = fields.Date( required=True, states={"done": [("readonly", "=", True)]}, default=fields.Date.context_today, tracking=True, copy=False, ) journal_id = fields.Many2one( comodel_name="account.journal", string="Check Journal", domain="[('company_id', '=', company_id), ('type', '=', 'bank'), " "('bank_account_id', '=', False)]", required=True, check_company=True, states={"done": [("readonly", "=", True)]}, tracking=True, ) in_hand_check_account_id = fields.Many2one( comodel_name="account.account", compute="_compute_in_hand_check_account_id", store=True, ) currency_id = fields.Many2one( comodel_name="res.currency", required=True, states={"done": [("readonly", "=", True)]}, tracking=True, ) state = fields.Selection( selection=[("draft", "Draft"), ("done", "Done")], string="Status", default="draft", readonly=True, tracking=True, ) move_id = fields.Many2one( comodel_name="account.move", string="Journal Entry", readonly=True, check_company=True, ) bank_journal_id = fields.Many2one( comodel_name="account.journal", string="Bank Account", required=True, domain="[('company_id', '=', company_id), ('type', '=', 'bank'), " "('bank_account_id', '!=', False)]", check_company=True, states={"done": [("readonly", "=", True)]}, tracking=True, ) line_ids = fields.One2many( comodel_name="account.move.line", related="move_id.line_ids", string="Lines", ) company_id = fields.Many2one( comodel_name="res.company", required=True, states={"done": [("readonly", "=", True)]}, default=lambda self: self.env.company, tracking=True, ) total_amount = fields.Monetary( compute="_compute_check_deposit", store=True, currency_field="currency_id", tracking=True, ) check_count = fields.Integer( compute="_compute_check_deposit", store=True, string="Number of Checks", tracking=True, ) _sql_constraints = [ ( "name_company_unique", "unique(company_id, name)", "A check deposit with this reference already exists in this company.", ) ] @api.depends( "company_id", "currency_id", "check_payment_ids.debit", "check_payment_ids.amount_currency", "move_id.line_ids.reconciled", ) def _compute_check_deposit(self): rg_res = self.env["account.move.line"].read_group( [("check_deposit_id", "in", self.ids)], ["check_deposit_id", "debit", "amount_currency"], ["check_deposit_id"], ) mapped_data = { x["check_deposit_id"][0]: { "debit": x["debit"], "amount_currency": x["amount_currency"], "count": x["check_deposit_id_count"], } for x in rg_res } for deposit in self: if deposit.company_id.currency_id != deposit.currency_id: total = mapped_data.get(deposit.id, {"amount_currency": 0.0})[ "amount_currency" ] else: total = mapped_data.get(deposit.id, {"debit": 0.0})["debit"] count = mapped_data.get(deposit.id, {"count": 0})["count"] deposit.total_amount = total deposit.check_count = count @api.depends("journal_id") def _compute_in_hand_check_account_id(self): for rec in self: account = rec.journal_id.inbound_payment_method_line_ids.filtered( lambda line: line.payment_method_id.code == "manual" ).payment_account_id rec.in_hand_check_account_id = account @api.model def default_get(self, fields_list): res = super().default_get(fields_list) ajo = self.env["account.journal"] company_id = res.get("company_id") # pre-set journal_id and bank_journal_id is there is only one domain = [("company_id", "=", company_id), ("type", "=", "bank")] journals = ajo.search(domain + [("bank_account_id", "=", False)]) if len(journals) == 1: res["journal_id"] = journals.id bank_journals = ajo.search(domain + [("bank_account_id", "!=", False)]) if len(bank_journals) == 1: res["bank_journal_id"] = bank_journals.id return res @api.constrains("currency_id", "check_payment_ids", "company_id") def _check_deposit(self): for deposit in self: deposit_currency = deposit.currency_id for line in deposit.check_payment_ids: if line.currency_id != deposit_currency: raise ValidationError( _( "The check with amount {amount} and reference '{ref}' " "is in currency {check_currency} but the deposit is in " "currency {deposit_currency}." ).format( amount=line.debit, ref=line.ref or "", check_currency=line.currency_id.name, deposit_currency=deposit_currency.name, ) ) def unlink(self): for deposit in self.filtered(lambda x: x.state == "done"): raise UserError( _( "The deposit '%s' is in valid state, so you must " "cancel it before deleting it." ) % deposit.name ) return super().unlink() def backtodraft(self): for deposit in self: if deposit.move_id: move = deposit.move_id # It will raise here if journal_id.update_posted = False if move.state == "posted": move.button_draft() for line in deposit.check_payment_ids: if line.reconciled: line.remove_move_reconcile() move.unlink() deposit.write({"state": "draft"}) return True @api.model def create(self, vals): if "company_id" in vals: self = self.with_company(vals["company_id"]) if vals.get("name", "/") == "/": vals["name"] = self.env["ir.sequence"].next_by_code( "account.check.deposit", vals.get("deposit_date") ) return super().create(vals) def _prepare_account_move_vals(self): self.ensure_one() move_vals = { "journal_id": self.journal_id.id, "date": self.deposit_date, "ref": _("Check Deposit %s") % self.name, "company_id": self.company_id.id, } return move_vals @api.model def _prepare_move_line_vals(self, line): assert line.debit > 0, "Debit must have a value" return { "name": line.ref and _("Check Ref. %s") % line.ref or False, "credit": line.debit, "debit": 0.0, "account_id": line.account_id.id, "partner_id": line.partner_id.id, "currency_id": line.currency_id.id or False, "amount_currency": line.amount_currency * -1, } def _prepare_counterpart_move_lines_vals(self, total_debit, total_amount_currency): self.ensure_one() account_id = False for line in self.bank_journal_id.inbound_payment_method_line_ids: if line.payment_method_id.code == "manual" and line.payment_account_id: account_id = line.payment_account_id.id break if not account_id: account_id = self.company_id.account_journal_payment_debit_account_id.id if not account_id: raise UserError( _("Missing 'Outstanding Receipts Account' on the company '%s'.") % self.company_id.display_name ) return { "debit": total_debit, "credit": 0.0, "account_id": account_id, "partner_id": False, "currency_id": self.currency_id.id or False, "amount_currency": total_amount_currency, } def validate_deposit(self): am_obj = self.env["account.move"] move_line_obj = self.env["account.move.line"] for deposit in self: move = am_obj.create(deposit._prepare_account_move_vals()) total_debit = 0.0 total_amount_currency = 0.0 to_reconcile_lines = [] for line in deposit.check_payment_ids: total_debit += line.debit total_amount_currency += line.amount_currency line_vals = self._prepare_move_line_vals(line) line_vals["move_id"] = move.id move_line = move_line_obj.with_context( check_move_validity=False ).create(line_vals) to_reconcile_lines.append(line + move_line) # Create counter-part counter_vals = deposit._prepare_counterpart_move_lines_vals( total_debit, total_amount_currency ) counter_vals["move_id"] = move.id move_line_obj.create(counter_vals) move.action_post() deposit.write({"state": "done", "move_id": move.id}) for reconcile_lines in to_reconcile_lines: reconcile_lines.reconcile() return True @api.onchange("company_id") def onchange_company_id(self): if self.company_id: self.bank_journal_id = self.env["account.journal"].search( [ ("company_id", "=", self.company_id.id), ("type", "=", "bank"), ("bank_account_id", "!=", False), ], limit=1, ) else: self.bank_journal_id = False @api.onchange("journal_id") def onchange_journal_id(self): self.currency_id = ( self.journal_id.currency_id or self.journal_id.company_id.currency_id ) def get_report(self): report = self.env.ref("account_check_deposit.report_account_check_deposit") action = report.report_action(self) return action def get_all_checks(self): self.ensure_one() all_pending_checks = self.env["account.move.line"].search( [ ("company_id", "=", self.company_id.id), ("reconciled", "=", False), ("account_id", "=", self.in_hand_check_account_id.id), ("debit", ">", 0), ("check_deposit_id", "=", False), ("currency_id", "=", self.currency_id.id), ("parent_state", "=", "posted"), ] ) if all_pending_checks: self.message_post(body=_("Get All Received Checks")) all_pending_checks.write({"check_deposit_id": self.id}) else: raise UserError( _( "There are no received checks in account '{account}' in currency " "'{currency}' that are not already in this check deposit." ).format( account=self.in_hand_check_account_id.display_name, currency=self.currency_id.display_name, ) )
36.916667
12,847
683
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (http://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Move Budget", "summary": "Create Accounting Budgets", "version": "15.0.1.0.0", "category": "Accounting & Finance", "website": "https://github.com/OCA/account-financial-tools", "author": "ForgeFlow, " "Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": ["account", "date_range"], "data": [ "security/ir.model.access.csv", "views/account_move_budget_line_views.xml", "views/account_move_budget_views.xml", ], }
34.15
683
2,454
py
PYTHON
15.0
# Copyright 2019 ACSONE SA/NV # Copyright 2019 ForgeFlow S.L. (http://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models class AccountMoveBudget(models.Model): _name = "account.move.budget" _description = "Account Move Budget" _inherit = ["mail.thread", "mail.activity.mixin"] name = fields.Char( required=True, tracking=True, ) description = fields.Char( tracking=True, ) date_range_id = fields.Many2one(comodel_name="date.range", string="Date range") date_from = fields.Date( required=True, string="From Date", tracking=True, ) date_to = fields.Date( required=True, string="To Date", tracking=True, ) state = fields.Selection( [("draft", "Draft"), ("confirmed", "Confirmed"), ("cancelled", "Cancelled")], required=True, default="draft", tracking=True, ) line_ids = fields.One2many( comodel_name="account.move.budget.line", inverse_name="budget_id", copy=True ) company_id = fields.Many2one( comodel_name="res.company", string="Company", default=lambda self: self.env.company, ) @api.returns("self", lambda value: value.id) def copy(self, default=None): self.ensure_one() if default is None: default = {} if "name" not in default: default["name"] = _("%s (copy)") % self.name return super(AccountMoveBudget, self).copy(default=default) @api.onchange("date_range_id") def _onchange_date_range(self): for rec in self: if rec.date_range_id: rec.date_from = rec.date_range_id.date_start rec.date_to = rec.date_range_id.date_end @api.onchange("date_from", "date_to") def _onchange_dates(self): for rec in self: if rec.date_range_id: if ( rec.date_from != rec.date_range_id.date_start or rec.date_to != rec.date_range_id.date_end ): rec.date_range_id = False def action_draft(self): for rec in self: rec.state = "draft" def action_cancel(self): for rec in self: rec.state = "cancelled" def action_confirm(self): for rec in self: rec.state = "confirmed"
29.926829
2,454
2,391
py
PYTHON
15.0
# Copyright 2019 ForgeFlow S.L. (http://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class AccountMoveBudgetLine(models.Model): _name = "account.move.budget.line" _description = "Account Move Budget Line" _order = "date desc, id desc" budget_id = fields.Many2one( comodel_name="account.move.budget", string="Budget", required=True, ondelete="cascade", index=True, ) name = fields.Char(string="Label") debit = fields.Monetary(default=0.0, currency_field="company_currency_id") credit = fields.Monetary(default=0.0, currency_field="company_currency_id") balance = fields.Monetary( compute="_compute_store_balance", store=True, currency_field="company_currency_id", help="Technical field holding the debit - " "credit in order to open meaningful " "graph views from reports", ) company_currency_id = fields.Many2one( "res.currency", related="company_id.currency_id", string="Company Currency", readonly=True, help="Utility field to express amount currency", store=True, ) account_id = fields.Many2one( "account.account", string="Account", required=True, index=True, ondelete="cascade", domain=[("deprecated", "=", False)], default=lambda self: self._context.get("account_id", False), ) date = fields.Date(index=True, required=True) analytic_account_id = fields.Many2one( "account.analytic.account", string="Analytic Account" ) company_id = fields.Many2one( "res.company", related="account_id.company_id", string="Company", store=True, readonly=True, ) partner_id = fields.Many2one("res.partner", string="Partner", ondelete="restrict") @api.depends("debit", "credit") def _compute_store_balance(self): for line in self: line.balance = line.debit - line.credit @api.constrains("date") def _constraint_date(self): for rec in self: if rec.budget_id.date_from > rec.date or rec.budget_id.date_to < rec.date: raise ValidationError(_("The date must be within the budget period."))
34.157143
2,391
656
py
PYTHON
15.0
# Copyright 2015 Tecnativa - Antonio Espinosa # Copyright 2016 Tecnativa - Sergio Teruel # Copyright 2017 Tecnativa - David Vidal # Copyright 2019 FactorLibre - Rodrigo Bonilla # Copyright 2022 Moduon - Eduardo de Miguel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Optional validation of VAT via VIES", "category": "Accounting", "version": "15.0.1.0.3", "depends": ["base_vat"], "data": ["views/res_partner_view.xml"], "author": "Tecnativa," "Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "license": "AGPL-3", "installable": True, }
38.588235
656
2,650
py
PYTHON
15.0
# Copyright 2015 Tecnativa - Antonio Espinosa # Copyright 2016 Tecnativa - Sergio Teruel # Copyright 2017 Tecnativa - David Vidal # Copyright 2022 Moduon - Eduardo de Miguel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import mock from odoo.exceptions import ValidationError from odoo.tests import common class TestResPartner(common.TransactionCase): def setUp(self): super(TestResPartner, self).setUp() self.company = self.env.user.company_id self.company.vat_check_vies = True self.partner = self.env["res.partner"].create( {"name": "Test partner", "is_company": True} ) self.vatnumber_path = "odoo.addons.base_vat.models.res_partner.check_vies" def test_validate_vat_vies(self): with mock.patch(self.vatnumber_path) as mock_vatnumber: mock_vatnumber.check_vies.return_value = True self.partner.vat = "ESB87530432" self.partner.country_id = self.env.ref("base.be") self.assertEqual(self.partner.vies_passed, True) def test_exception_vat_vies(self): with mock.patch(self.vatnumber_path) as mock_vatnumber: mock_vatnumber.check_vies.side_effect = Exception() self.partner.vat = "ESB87530432" self.assertEqual(self.partner.vies_passed, False) def test_no_validate_vat(self): with mock.patch(self.vatnumber_path) as mock_vatnumber: mock_vatnumber.check_vies.return_value = False self.partner.vat = "ESB87530432" self.assertEqual(self.partner.vies_passed, False) def test_validate_simple_vat_vies(self): with mock.patch(self.vatnumber_path) as mock_vatnumber: self.company.vat_check_vies = False mock_vatnumber.check_vies.return_value = False self.partner.vat = "MXGODE561231GR8" self.partner.country_id = self.env.ref("base.mx") self.assertEqual(self.partner.vies_passed, False) def test_validate_vies_passed_false_when_vat_set_to_false(self): with mock.patch(self.vatnumber_path) as mock_vatnumber: mock_vatnumber.check_vies.return_value = True self.partner.vat = "ESB87530432" self.partner.country_id = self.env.ref("base.be") self.assertEqual(self.partner.vies_passed, True) self.partner.vat = False self.assertEqual(self.partner.vies_passed, False) def test_validate_wrong_vat_shows_simple_message(self): with self.assertRaisesRegex(ValidationError, "does not seem to be valid"): self.partner.vat = "ES11111111A"
43.442623
2,650
2,273
py
PYTHON
15.0
# Copyright 2015 Tecnativa - Antonio Espinosa # Copyright 2017 Tecnativa - David Vidal # Copyright 2019 FactorLibre - Rodrigo Bonilla # Copyright 2022 Moduon - Eduardo de Miguel # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.addons.base_vat.models.res_partner import _ref_vat class ResPartner(models.Model): _inherit = "res.partner" vies_passed = fields.Boolean(string="VIES validation", readonly=True) @api.model def simple_vat_check(self, country_code, vat_number): res = super(ResPartner, self).simple_vat_check( country_code, vat_number, ) partner = self.env.context.get("vat_partner") if partner: partner.update({"vies_passed": False}) return res @api.model def vies_vat_check(self, country_code, vat_number): partner = self.env.context.get("vat_partner") if partner: # If there's an exception checking VIES, the upstream method will # call simple_vat_check and thus the flag will be removed partner.update({"vies_passed": True}) res = super(ResPartner, self).vies_vat_check(country_code, vat_number) if res is False: if partner: partner.update({"vies_passed": False}) return self.simple_vat_check(country_code, vat_number) elif partner: partner.update({"vies_passed": True}) return res @api.constrains("vat", "country_id") def check_vat(self): self.update({"vies_passed": False}) for partner in self: partner = partner.with_context(vat_partner=partner) super(ResPartner, partner).check_vat() return True @api.model def _build_vat_error_message(self, country_code, wrong_vat, record_label): return "\n" + _( "The VAT number [%(wrong_vat)s] for %(record_label)s does not seem to be valid. " "\nNote: the expected format is %(expected_format)s", wrong_vat=wrong_vat, record_label=record_label, expected_format=_ref_vat.get( country_code, "'CC##' (CC=Country Code, ##=VAT Number)" ), )
37.262295
2,273
606
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Journal Lock Date", "summary": "Lock each journal independently", "version": "15.0.1.0.1", "license": "AGPL-3", "author": "ACSONE SA/NV, Tecnativa, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "depends": ["account"], "data": [ "security/ir.model.access.csv", "views/account_journal.xml", "wizards/update_journal_lock_dates_views.xml", ], "demo": [], "installable": True, }
31.894737
606
8,443
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import date, timedelta from odoo.exceptions import UserError from odoo.tests import tagged from odoo.addons.account.tests import common @tagged("post_install", "-at_install") class TestJournalLockDate(common.AccountTestInvoicingCommon): def setUp(self): super(TestJournalLockDate, self).setUp() self.account_move_obj = self.env["account.move"] self.account_move_line_obj = self.env["account.move.line"] self.company_id = self.ref("base.main_company") self.partner = self.browse_ref("base.res_partner_12") self.account = self.company_data["default_account_revenue"] self.account2 = self.company_data["default_account_expense"] self.journal = self.company_data["default_journal_bank"] # create a move and post it self.move = self.account_move_obj.create( { "date": date.today(), "journal_id": self.journal.id, "line_ids": [ ( 0, 0, { "account_id": self.account.id, "credit": 1000.0, "name": "Credit line", }, ), ( 0, 0, { "account_id": self.account2.id, "debit": 1000.0, "name": "Debit line", }, ), ], } ) self.move.action_post() # lock journal, set 'Lock Date for Non-Advisers' self.journal.period_lock_date = date.today() + timedelta(days=2) def test_journal_lock_date(self): self.env.user.write({"groups_id": [(3, self.ref("base.group_system"))]}) self.env.user.write( {"groups_id": [(3, self.ref("account.group_account_manager"))]} ) self.assertFalse(self.env.user.has_group("account.group_account_manager")) # Test that the move cannot be created, written, or cancelled with self.assertRaises(UserError): self.account_move_obj.create( { "date": date.today(), "journal_id": self.journal.id, "line_ids": [ ( 0, 0, { "account_id": self.account.id, "credit": 1000.0, "name": "Credit line", }, ), ( 0, 0, { "account_id": self.account2.id, "debit": 1000.0, "name": "Debit line", }, ), ], } ) with self.assertRaises(UserError): self.move.write({"name": "TEST"}) with self.assertRaises(UserError): self.move.button_cancel() # create a move after the 'Lock Date for Non-Advisers' and post it move2 = self.account_move_obj.create( { "date": self.journal.period_lock_date + timedelta(days=3), "journal_id": self.journal.id, "line_ids": [ ( 0, 0, { "account_id": self.account.id, "credit": 1000.0, "name": "Credit line", }, ), ( 0, 0, { "account_id": self.account2.id, "debit": 1000.0, "name": "Debit line", }, ), ], } ) move2.action_post() # force create move in a lock date move3 = self.account_move_obj.with_context( bypass_journal_lock_date=True ).create( { "date": self.journal.period_lock_date, "journal_id": self.journal.id, "line_ids": [ ( 0, 0, { "account_id": self.account.id, "credit": 1000.0, "name": "Credit line", }, ), ( 0, 0, { "account_id": self.account2.id, "debit": 1000.0, "name": "Debit line", }, ), ], } ) move3.action_post() def test_journal_lock_date_adviser(self): """The journal lock date is ignored for Advisers""" self.env.user.write( {"groups_id": [(4, self.env.ref("account.group_account_manager").id)]} ) self.assertTrue(self.env.user.has_group("account.group_account_manager")) wizard = ( self.env["update.journal.lock.dates.wizard"] .with_context(active_model="account.journal", active_ids=self.journal.id) .create( { "fiscalyear_lock_date": date.today() + timedelta(days=2), "period_lock_date": date.today() + timedelta(days=4), } ) ) wizard.action_update_lock_dates() # Advisers cannot create, write, or cancel moves before 'Lock Date' with self.assertRaises(UserError): self.account_move_obj.create( { "date": date.today(), "journal_id": self.journal.id, "line_ids": [ ( 0, 0, { "account_id": self.account.id, "credit": 1000.0, "name": "Credit line", }, ), ( 0, 0, { "account_id": self.account2.id, "debit": 1000.0, "name": "Debit line", }, ), ], } ) with self.assertRaises(UserError): self.move.write({"name": "TEST"}) with self.assertRaises(UserError): self.move.button_cancel() # Advisers can create movements on a date after the 'Lock Date' # even if that date is before and inclusive of # the 'Lock Date for Non-Advisers' (self.journal.period_lock_date) move2 = self.account_move_obj.create( { "date": self.journal.period_lock_date, "journal_id": self.journal.id, "line_ids": [ ( 0, 0, { "account_id": self.account.id, "credit": 1000.0, "name": "Credit line", }, ), ( 0, 0, { "account_id": self.account2.id, "debit": 1000.0, "name": "Debit line", }, ), ], } ) move2.action_post()
35.624473
8,443
2,090
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from datetime import date from odoo import _, models from odoo.exceptions import UserError from odoo.tools.misc import format_date class AccountMove(models.Model): _inherit = "account.move" def write(self, values): res = super().write(values) self._check_fiscalyear_lock_date() return res def _check_fiscalyear_lock_date(self): res = super()._check_fiscalyear_lock_date() if self.env.context.get("bypass_journal_lock_date"): return res for move in self: if self.user_has_groups("account.group_account_manager"): lock_date = move.journal_id.fiscalyear_lock_date or date.min else: lock_date = max( move.journal_id.period_lock_date or date.min, move.journal_id.fiscalyear_lock_date or date.min, ) if move.date <= lock_date: lock_date = format_date(self.env, lock_date) if self.user_has_groups("account.group_account_manager"): message = _( "You cannot add/modify entries for the journal '%(journal)s' " "prior to and inclusive of the lock date %(journal_date)s" ) % { "journal": move.journal_id.display_name, "journal_date": lock_date, } else: message = _( "You cannot add/modify entries for the journal '%(journal)s' " "prior to and inclusive of the lock date %(journal_date)s. " "Check the Journal settings or ask someone " "with the 'Adviser' role" ) % { "journal": move.journal_id.display_name, "journal_date": lock_date, } raise UserError(message) return res
39.433962
2,090
803
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountJournal(models.Model): _inherit = "account.journal" fiscalyear_lock_date = fields.Date( string="Lock Date", help="No users, including Advisers, can edit accounts prior " "to and inclusive of this date for this journal. Use it " "for fiscal year locking for this journal, for example.", ) period_lock_date = fields.Date( string="Lock Date for Non-Advisers", help="Only users with the 'Adviser' role can edit accounts " "prior to and inclusive of this date for this journal. " "Use it for period locking inside an open fiscal year " "for this journal, for example.", )
34.913043
803
1,233
py
PYTHON
15.0
# Copyright 2020 Tecnativa - Ernesto Tejeda # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import SUPERUSER_ID, _, fields, models from odoo.exceptions import UserError class UpdateJournalLockDatesWizard(models.TransientModel): _name = "update.journal.lock.dates.wizard" _description = "Mass Update Journal Lock Dates Wizard" period_lock_date = fields.Date(string="Lock Date for Non-Advisers") fiscalyear_lock_date = fields.Date(string="Lock Date") def _check_execute_allowed(self): self.ensure_one() has_adviser_group = self.env.user.has_group("account.group_account_manager") if not (has_adviser_group or self.env.uid == SUPERUSER_ID): raise UserError(_("You are not allowed to execute this action.")) def action_update_lock_dates(self): self.ensure_one() self._check_execute_allowed() active_ids = self.env.context.get("active_ids", False) if active_ids: self.env["account.journal"].browse(active_ids).write( { "period_lock_date": self.period_lock_date, "fiscalyear_lock_date": self.fiscalyear_lock_date, } )
39.774194
1,233
550
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Move Fiscal Year", "summary": """ Display the fiscal year on journal entries/item""", "version": "15.0.1.0.1", "license": "AGPL-3", "author": "ACSONE SA/NV, Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-financial-tools", "depends": [ "account_fiscal_year", ], "data": [ "views/account_move.xml", "views/account_move_line.xml", ], }
28.947368
550
5,121
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.fields import Date from odoo.tests.common import TransactionCase class TestAccountMoveFiscalYear(TransactionCase): def setUp(self): super(TestAccountMoveFiscalYear, self).setUp() self.AccountObj = self.env["account.account"] self.AccountJournalObj = self.env["account.journal"] self.AccountMoveObj = self.env["account.move"] self.DateRangeObj = self.env["account.fiscal.year"] self.bank_journal = self.AccountJournalObj.search( [("type", "=", "bank")], limit=1 ) self.account_type_recv = self.env.ref("account.data_account_type_receivable") self.account_type_rev = self.env.ref("account.data_account_type_revenue") self.account_recv = self.AccountObj.create( { "code": "RECV_DR", "name": "Receivable (test)", "reconcile": True, "user_type_id": self.account_type_recv.id, } ) self.account_sale = self.AccountObj.create( { "code": "SALE_DR", "name": "Receivable (sale)", "reconcile": True, "user_type_id": self.account_type_rev.id, } ) self.date_range_2017 = self.DateRangeObj.create( { "name": "2017", "date_from": "2017-01-01", "date_to": "2017-12-31", } ) self.date_range_2018 = self.DateRangeObj.create( { "name": "2018", "date_from": "2018-01-01", "date_to": "2018-12-31", } ) def create_account_move(self, date_str): return self.AccountMoveObj.create( { "journal_id": self.bank_journal.id, "date": date_str, "line_ids": [ ( 0, 0, { "name": "Debit", "debit": 1000, "account_id": self.account_recv.id, }, ), ( 0, 0, { "name": "Credit", "credit": 1000, "account_id": self.account_sale.id, }, ), ], } ) def test_01_account_move_date_range_fy_id_compute(self): january_1st = Date.to_date("2017-01-01") move = self.create_account_move(january_1st) self.assertEqual( move.date_range_fy_id, self.date_range_2017, msg="Move period should be 2017", ) self.assertTrue( all( [ line.date_range_fy_id == self.date_range_2017 for line in move.line_ids ] ), msg="All lines period should be 2017", ) january_2019 = Date.to_date("2019-01-01") move = self.create_account_move(january_2019) self.assertFalse( bool(move.date_range_fy_id), msg="Move shouldn't have any date range" ) def test_02_account_move_date_range_fy_id_search(self): january_2017 = Date.to_date("2017-01-01") january_2018 = Date.to_date("2018-01-01") january_2019 = Date.to_date("2019-01-01") move_2017 = self.create_account_move(january_2017) move_2018 = self.create_account_move(january_2018) move_2019 = self.create_account_move(january_2019) moves = self.AccountMoveObj.search( [ ("date_range_fy_id", "ilike", "2017"), ] ) self.assertTrue( all( [ move_2017 in moves, move_2018 not in moves, move_2019 not in moves, ] ), msg="There should be only moves in 2017", ) moves = self.AccountMoveObj.search( [ ("date_range_fy_id", "=", self.date_range_2017.id), ] ) self.assertTrue( all( [ move_2017 in moves, move_2018 not in moves, move_2019 not in moves, ] ) ) moves = self.AccountMoveObj.search( [ ( "date_range_fy_id", "in", (self.date_range_2017.id, self.date_range_2018.id), ), ] ) self.assertTrue( all( [ move_2017 in moves, move_2018 in moves, move_2019 not in moves, ] ) )
30.301775
5,121
1,604
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, fields, models from odoo.osv import expression class AccountMove(models.Model): _inherit = "account.move" date_range_fy_id = fields.Many2one( comodel_name="account.fiscal.year", string="Fiscal year", compute="_compute_date_range_fy", search="_search_date_range_fy", ) @api.depends("date", "company_id") def _compute_date_range_fy(self): for rec in self: date = fields.Date.to_date(rec.date) company = rec.company_id rec.date_range_fy_id = company and company.find_daterange_fy(date) or False @api.model def _search_date_range_fy(self, operator, value): if operator in ("=", "!=", "in", "not in"): date_range_domain = [("id", operator, value)] else: date_range_domain = [("name", operator, value)] date_ranges = self.env["account.fiscal.year"].search(date_range_domain) domain = [("id", "=", -1)] for date_range in date_ranges: domain = expression.OR( [ domain, [ "&", ("date", ">=", date_range.date_from), ("date", "<=", date_range.date_to), "|", ("company_id", "=", False), ("company_id", "=", date_range.company_id.id), ], ] ) return domain
32.08
1,604
293
py
PYTHON
15.0
# Copyright 2017 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class AccountMoveLine(models.Model): _inherit = "account.move.line" date_range_fy_id = fields.Many2one( related="move_id.date_range_fy_id", )
22.538462
293
679
py
PYTHON
15.0
# Author: Damien Crier # Copyright 2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models class ResCompany(models.Model): _inherit = "res.company" def find_daterange_fy(self, date): """ try to find a date range with type 'fiscalyear' with @param:date contained in its date_start/date_end interval """ fiscalyear = self.env["account.fiscal.year"].search( [ ("company_id", "=", self.id), ("date_from", "<=", date), ("date_to", ">=", date), ], limit=1, ) return fiscalyear
28.291667
679
549
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Chart update OSS ", "version": "15.0.1.0.0", "author": "ForgeFlow, Odoo Community Association (OCA)", "maintainers": ["LoisRForgeFlow"], "website": "https://github.com/OCA/account-financial-tools", "category": "Accounting", "license": "AGPL-3", "depends": [ "account_chart_update", "l10n_eu_oss", ], "installable": True, "auto_install": True, }
30.5
549
474
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class WizardUpdateChartsAccounts(models.TransientModel): _inherit = "wizard.update.charts.accounts" def _domain_taxes_to_deactivate(self, found_taxes_ids): domain = super()._domain_taxes_to_deactivate(found_taxes_ids) domain.append(("tax_group_id.name", "not like", "OSS%%")) return domain
36.461538
474
819
py
PYTHON
15.0
# Copyright 2016 Camptocamp SA # Copyright 2018 Lorenzo Battistini <https://github.com/eLBati> # Copyright 2020 Simone Rubino - Agile Business Group # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). { "name": "Account Fiscal Year", "summary": "Create Account Fiscal Year", "version": "15.0.1.3.0", "development_status": "Production/Stable", "category": "Accounting", "website": "https://github.com/OCA/account-financial-tools", "author": "Agile Business Group, Camptocamp SA, " "Odoo Community Association (OCA)", "maintainers": ["eLBati"], "license": "AGPL-3", "depends": [ "account", ], "data": [ "security/ir.model.access.csv", "security/account_fiscal_year_rule.xml", "views/account_fiscal_year_views.xml", ], }
34.125
819
469
py
PYTHON
15.0
# Copyright 2022 ForgeFlow S.L. (https://www.forgeflow.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openupgradelib import openupgrade @openupgrade.migrate() def migrate(env, version): openupgrade.logged_query( env.cr, """ DELETE FROM ir_model_data imd USING date_range_type drt WHERE imd.model = 'date.range.type' AND imd.res_id = drt.id AND imd.name = 'fiscalyear'""", )
29.3125
469
4,052
py
PYTHON
15.0
from odoo import fields from odoo.tests import common class TestFiscalPosition(common.TransactionCase): def check_compute_fiscal_year( self, company, date, expected_date_from, expected_date_to ): """Compute the fiscal year at a certain date for the company passed as parameter. Then, check if the result matches the 'expected_date_from'/'expected_date_to' dates. :param company: The company. :param date: The date belonging to the fiscal year. :param expected_date_from: The expected date_from after computation. :param expected_date_to: The expected date_to after computation. """ current_date = fields.Date.from_string(date) res = company.compute_fiscalyear_dates(current_date) self.assertEqual(res["date_from"], fields.Date.from_string(expected_date_from)) self.assertEqual(res["date_to"], fields.Date.from_string(expected_date_to)) def test_default_fiscal_year(self): """Basic case with a fiscal year xxxx-01-01 - xxxx-12-31.""" company = self.env.ref("base.main_company") company.fiscalyear_last_day = 31 company.fiscalyear_last_month = "12" self.check_compute_fiscal_year( company, "2017-12-31", "2017-01-01", "2017-12-31", ) self.check_compute_fiscal_year( company, "2017-01-01", "2017-01-01", "2017-12-31", ) def test_leap_fiscal_year_1(self): """Case with a leap year ending the 29 February.""" company = self.env.ref("base.main_company") company.fiscalyear_last_day = 29 company.fiscalyear_last_month = "2" self.check_compute_fiscal_year( company, "2016-02-29", "2015-03-01", "2016-02-29", ) self.check_compute_fiscal_year( company, "2015-03-01", "2015-03-01", "2016-02-29", ) def test_leap_fiscal_year_2(self): """Case with a leap year ending the 28 February.""" company = self.env.ref("base.main_company") company.fiscalyear_last_day = 28 company.fiscalyear_last_month = "2" self.check_compute_fiscal_year( company, "2016-02-29", "2015-03-01", "2016-02-29", ) self.check_compute_fiscal_year( company, "2016-03-01", "2016-03-01", "2017-02-28", ) def test_custom_fiscal_year(self): """Case with custom fiscal years.""" company = self.env.ref("base.main_company") company.fiscalyear_last_day = 31 company.fiscalyear_last_month = "12" # Create custom fiscal year covering the 6 first months of 2017. self.env["account.fiscal.year"].create( { "name": "6 month 2017", "date_from": "2017-01-01", "date_to": "2017-05-31", "company_id": company.id, } ) # Check before the custom fiscal year). self.check_compute_fiscal_year( company, "2017-02-01", "2017-01-01", "2017-05-31", ) # Check after the custom fiscal year. self.check_compute_fiscal_year( company, "2017-11-01", "2017-06-01", "2017-12-31", ) # Create custom fiscal year covering the 3 last months of 2017. self.env["account.fiscal.year"].create( { "name": "last 3 month 2017", "date_from": "2017-10-01", "date_to": "2017-12-31", "company_id": company.id, } ) # Check inside the custom fiscal years. self.check_compute_fiscal_year( company, "2017-07-01", "2017-06-01", "2017-09-30", )
30.69697
4,052
2,803
py
PYTHON
15.0
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from datetime import timedelta from odoo import models from odoo.tools import DEFAULT_SERVER_DATE_FORMAT, date_utils class ResCompany(models.Model): _inherit = "res.company" def compute_fiscalyear_dates(self, current_date): """Computes the start and end dates of the fiscal year where the given 'date' belongs to. :param current_date: A datetime.date/datetime.datetime object. :return: A dictionary containing: * date_from * date_to * [Optionally] record: The fiscal year record. """ self.ensure_one() date_str = current_date.strftime(DEFAULT_SERVER_DATE_FORMAT) # Search a fiscal year record containing the date. fiscalyear = self.env["account.fiscal.year"].search( [ ("company_id", "=", self.id), ("date_from", "<=", date_str), ("date_to", ">=", date_str), ], limit=1, ) if fiscalyear: return { "date_from": fiscalyear.date_from, "date_to": fiscalyear.date_to, "record": fiscalyear, } date_from, date_to = date_utils.get_fiscal_year( current_date, day=self.fiscalyear_last_day, month=int(self.fiscalyear_last_month), ) # Search for fiscal year records reducing # the delta between the date_from/date_to. # This case could happen if there is a gap # between two fiscal year records. # E.g. two fiscal year records: # 2017-01-01 -> 2017-02-01 and 2017-03-01 -> 2017-12-31. # => # The period 2017-02-02 - 2017-02-30 is not covered by a fiscal year record. date_from_str = date_from.strftime(DEFAULT_SERVER_DATE_FORMAT) fiscalyear_from = self.env["account.fiscal.year"].search( [ ("company_id", "=", self.id), ("date_from", "<=", date_from_str), ("date_to", ">=", date_from_str), ], limit=1, ) if fiscalyear_from: date_from = fiscalyear_from.date_to + timedelta(days=1) date_to_str = date_to.strftime(DEFAULT_SERVER_DATE_FORMAT) fiscalyear_to = self.env["account.fiscal.year"].search( [ ("company_id", "=", self.id), ("date_from", "<=", date_to_str), ("date_to", ">=", date_to_str), ], limit=1, ) if fiscalyear_to: date_to = fiscalyear_to.date_from - timedelta(days=1) return { "date_from": date_from, "date_to": date_to, }
34.182927
2,803
3,670
py
PYTHON
15.0
# Copyright 2020 Simone Rubino - Agile Business Group # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.osv import expression class AccountFiscalYear(models.Model): _name = "account.fiscal.year" _description = "Fiscal Year" _rec_name = "name" name = fields.Char( required=True, ) date_from = fields.Date( string="Start Date", required=True, help="Start Date, included in the fiscal year.", ) date_to = fields.Date( string="End Date", required=True, help="Ending Date, included in the fiscal year.", ) company_id = fields.Many2one( comodel_name="res.company", string="Company", required=True, default=lambda self: self.env.company, ) @api.constrains("date_from", "date_to", "company_id") def _check_dates(self): """Check intersection with existing fiscal years.""" for fy in self: # Starting date must be prior to the ending date date_from = fy.date_from date_to = fy.date_to if date_to < date_from: raise ValidationError( _("The ending date must not be prior to the starting date.") ) domain = fy._get_overlapping_domain() overlapping_fy = self.search(domain, limit=1) if overlapping_fy: raise ValidationError( _( "This fiscal year '{fy}' " "overlaps with '{overlapping_fy}'.\n" "Please correct the start and/or end dates " "of your fiscal years." ).format( fy=fy.display_name, overlapping_fy=overlapping_fy.display_name, ) ) def _get_overlapping_domain(self): """Get domain for finding fiscal years overlapping with self. The domain will search only among fiscal years of this company. """ self.ensure_one() # Compare with other fiscal years defined for this company company_domain = [ ("id", "!=", self.id), ("company_id", "=", self.company_id.id), ] date_from = self.date_from date_to = self.date_to # Search fiscal years intersecting with current fiscal year. # This fiscal year's `from` is contained in another fiscal year # other.from <= fy.from <= other.to intersection_domain_from = [ "&", ("date_from", "<=", date_from), ("date_to", ">=", date_from), ] # This fiscal year's `to` is contained in another fiscal year # other.from <= fy.to <= other.to intersection_domain_to = [ "&", ("date_from", "<=", date_to), ("date_to", ">=", date_to), ] # This fiscal year completely contains another fiscal year # fy.from <= other.from (or other.to) <= fy.to intersection_domain_contain = [ "&", ("date_from", ">=", date_from), ("date_from", "<=", date_to), ] intersection_domain = expression.OR( [ intersection_domain_from, intersection_domain_to, intersection_domain_contain, ] ) return expression.AND( [ company_domain, intersection_domain, ] )
33.363636
3,670
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
2,790
py
PYTHON
15.0
import setuptools with open('VERSION.txt', 'r') as f: version = f.read().strip() setuptools.setup( name="odoo-addons-oca-account-financial-tools", description="Meta package for oca-account-financial-tools Odoo addons", version=version, install_requires=[ 'odoo-addon-account_asset_low_value>=15.0dev,<15.1dev', 'odoo-addon-account_asset_management>=15.0dev,<15.1dev', 'odoo-addon-account_asset_management_menu>=15.0dev,<15.1dev', 'odoo-addon-account_asset_number>=15.0dev,<15.1dev', 'odoo-addon-account_balance_line>=15.0dev,<15.1dev', 'odoo-addon-account_chart_update>=15.0dev,<15.1dev', 'odoo-addon-account_chart_update_l10n_eu_oss>=15.0dev,<15.1dev', 'odoo-addon-account_chart_update_l10n_eu_oss_oca>=15.0dev,<15.1dev', 'odoo-addon-account_check_deposit>=15.0dev,<15.1dev', 'odoo-addon-account_cost_center>=15.0dev,<15.1dev', 'odoo-addon-account_fiscal_month>=15.0dev,<15.1dev', 'odoo-addon-account_fiscal_position_vat_check>=15.0dev,<15.1dev', 'odoo-addon-account_fiscal_year>=15.0dev,<15.1dev', 'odoo-addon-account_invoice_constraint_chronology>=15.0dev,<15.1dev', 'odoo-addon-account_journal_general_sequence>=15.0dev,<15.1dev', 'odoo-addon-account_journal_lock_date>=15.0dev,<15.1dev', 'odoo-addon-account_lock_date_update>=15.0dev,<15.1dev', 'odoo-addon-account_lock_to_date>=15.0dev,<15.1dev', 'odoo-addon-account_maturity_date_default>=15.0dev,<15.1dev', 'odoo-addon-account_move_budget>=15.0dev,<15.1dev', 'odoo-addon-account_move_fiscal_month>=15.0dev,<15.1dev', 'odoo-addon-account_move_fiscal_year>=15.0dev,<15.1dev', 'odoo-addon-account_move_force_removal>=15.0dev,<15.1dev', 'odoo-addon-account_move_line_menu>=15.0dev,<15.1dev', 'odoo-addon-account_move_line_purchase_info>=15.0dev,<15.1dev', 'odoo-addon-account_move_line_residual>=15.0dev,<15.1dev', 'odoo-addon-account_move_line_sale_info>=15.0dev,<15.1dev', 'odoo-addon-account_move_line_tax_editable>=15.0dev,<15.1dev', 'odoo-addon-account_move_name_sequence>=15.0dev,<15.1dev', 'odoo-addon-account_move_print>=15.0dev,<15.1dev', 'odoo-addon-account_move_template>=15.0dev,<15.1dev', 'odoo-addon-account_move_total_by_account_internal_group>=15.0dev,<15.1dev', 'odoo-addon-account_netting>=15.0dev,<15.1dev', 'odoo-addon-account_usability>=15.0dev,<15.1dev', 'odoo-addon-base_vat_optional_vies>=15.0dev,<15.1dev', 'odoo-addon-product_category_tax>=15.0dev,<15.1dev', ], classifiers=[ 'Programming Language :: Python', 'Framework :: Odoo', 'Framework :: Odoo :: 15.0', ] )
52.641509
2,790
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100
100
py
PYTHON
15.0
import setuptools setuptools.setup( setup_requires=['setuptools-odoo'], odoo_addon=True, )
16.666667
100