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
|
|---|---|---|---|---|---|---|
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
|
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
|
535
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Base Technical User",
"summary": """
Add a technical user parameter on the company """,
"author": "ACSONE SA/NV, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/server-tools",
"category": "Hidden/Dependency",
"version": "15.0.1.0.0",
"license": "AGPL-3",
"depends": ["base"],
"data": ["views/res_company_view.xml"],
"installable": True,
}
| 35.666667
| 535
|
1,233
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Akretion (http://www.akretion.com).
# @author Sébastien BEAU <sebastien.beau@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import SUPERUSER_ID
from odoo.exceptions import UserError
from odoo.tests import TransactionCase
class SudoTechCase(TransactionCase):
@classmethod
def setUpClass(cls):
super(SudoTechCase, cls).setUpClass()
cls.user_tech = (
cls.env["res.users"]
.with_context(tracking_disable=True, no_reset_password=True)
.create({"login": "tech", "name": "tech"})
)
cls.company = cls.env.ref("base.main_company")
cls.env(user=cls.env.ref("base.user_demo").id)
def test_sudo_tech(self):
self.company.user_tech_id = self.user_tech
self_tech = self.env["res.partner"].sudo_tech()
self.assertEqual(self_tech._uid, self.user_tech.id)
def test_sudo_tech_missing_return_sudo(self):
self_tech = self.env["res.partner"].sudo_tech()
self.assertEqual(self_tech._uid, SUPERUSER_ID)
def test_sudo_tech_missing_raise(self):
with self.assertRaises(UserError):
self.env["res.partner"].sudo_tech(raise_if_missing=True)
| 36.235294
| 1,232
|
756
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Akretion (http://www.akretion.com).
# @author Sébastien BEAU <sebastien.beau@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, models
from odoo.exceptions import UserError
class Base(models.AbstractModel):
_inherit = "base"
def sudo_tech(self, raise_if_missing=False):
self_sudoer = self
tech_user = self.env.user.company_id.user_tech_id
if tech_user:
self_sudoer = self.with_user(tech_user.id)
elif raise_if_missing:
raise UserError(
_("The technical user is missing in the company {}").format(
self.env.user.company_id.name
)
)
return self_sudoer
| 31.458333
| 755
|
435
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResCompany(models.Model):
_inherit = "res.company"
user_tech_id = fields.Many2one(
comodel_name="res.users",
string="Technical User",
help="This user can be used by process for technical purpose",
domain="[('company_id', '=', id)]",
)
| 31.071429
| 435
|
506
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Akretion (http://www.akretion.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Onchange Helper",
"version": "15.0.1.0.1",
"summary": "Technical module that ease execution" " of onchange in Python code",
"author": "Akretion,Camptocamp,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/server-tools",
"license": "AGPL-3",
"category": "Generic Modules",
"depends": ["base"],
"installable": True,
}
| 36.142857
| 506
|
1,456
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests.common import TransactionCase
class TestOnchangeHelper(TransactionCase):
def test01_partner_parent(self):
main_partner = self.env.ref("base.main_partner")
input_vals = dict(parent_id=main_partner.id, type="contact")
updated_vals = self.env["res.partner"].play_onchanges(input_vals, ["parent_id"])
self.assertIn("country_id", updated_vals)
self.assertIn("state_id", updated_vals)
self.assertIn("street", updated_vals)
self.assertIn("zip", updated_vals)
self.assertEqual(updated_vals["country_id"], main_partner.country_id.id)
self.assertEqual(updated_vals["state_id"], main_partner.state_id.id)
self.assertEqual(updated_vals["street"], main_partner.street)
self.assertEqual(updated_vals["zip"], main_partner.zip)
def test02_partner_country(self):
partner_demo = self.env.ref("base.partner_demo")
input_vals = {"country_id": self.env.ref("base.us").id}
updated_vals = partner_demo.play_onchanges(input_vals, ["country_id"])
self.assertIn("country_id", updated_vals)
def test_playing_onchange_on_model(self):
result = self.env["res.partner"].play_onchanges(
{"company_type": "company"}, ["company_type"]
)
self.assertEqual(result["is_company"], True)
| 45.5
| 1,456
|
2,765
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Akretion (http://www.akretion.com)
# Copyright 2016-2017 Camptocamp (http://www.camptocamp.com/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, models
class Base(models.AbstractModel):
_inherit = "base"
@api.model
def _get_new_values(self, record, on_change_result):
vals = on_change_result.get("value", {})
new_values = {}
for fieldname, value in vals.items():
if fieldname not in record:
column = self._fields[fieldname]
if value and column.type == "many2one":
value = value[0] # many2one are tuple (id, name)
new_values[fieldname] = value
return new_values
@api.model
def play_onchanges(self, values, onchange_fields):
"""
:param values: dict of input value that
:param onchange_fields: fields for which onchange methods will be
played
Order in onchange_fields is very important as onchanges methods will
be played in that order.
:return: changed values
"""
# _onchange_spec() will return onchange fields from the default view
# we need all fields in the dict even the empty ones
# otherwise 'onchange()' will not apply changes to them
onchange_specs = {field_name: "1" for field_name, field in self._fields.items()}
all_values = values.copy()
# If self is a record (play onchange on existing record)
# we take the value of the field
# If self is an empty record we will have an empty value
if self:
self.ensure_one()
record_values = self._convert_to_write(
{
field_name: self[field_name]
for field_name, field in self._fields.items()
}
)
else:
# We get default values, they may be used in onchange
record_values = self.default_get(self._fields.keys())
for field in self._fields:
if field not in all_values:
all_values[field] = record_values.get(field, False)
new_values = {}
for field in onchange_fields:
onchange_values = self.onchange(all_values, field, onchange_specs)
new_values.update(self._get_new_values(values, onchange_values))
all_values.update(new_values)
return {
f: v
for f, v in all_values.items()
if not (
self._fields[f].compute
and not self._fields[f].inverse
and self._fields[f].readonly
)
and (f in values or f in new_values or f in onchange_fields)
}
| 38.943662
| 2,765
|
1,504
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
{
"name": "Excel Import/Export/Report Demo",
"version": "15.0.1.0.0",
"author": "Ecosoft,Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/server-tools",
"category": "Tools",
"depends": ["excel_import_export", "sale_management", "purchase", "crm"],
"data": [
"import_export_sale_order/actions.xml",
"import_export_sale_order/templates.xml",
"import_export_purchase_order/actions.xml",
"import_export_purchase_order/templates.xml",
"report_sale_order/report_sale_order.xml",
"report_sale_order/templates.xml",
"report_sale_order/security/ir.model.access.csv",
"report_crm_lead/report_crm_lead.xml",
"report_crm_lead/templates.xml",
"report_crm_lead/security/ir.model.access.csv",
"import_sale_orders/menu_action.xml",
"import_sale_orders/templates.xml",
# Use report action
"report_action/sale_order/report.xml",
"report_action/sale_order/templates.xml",
"report_action/partner_list/report.xml",
"report_action/partner_list/templates.xml",
"report_action/partner_list/report_partner_list.xml",
"report_action/partner_list/security/ir.model.access.csv",
],
"installable": True,
"development_status": "Beta",
"maintainers": ["kittiu"],
}
| 41.777778
| 1,504
|
1,008
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo import fields, models
class ReportSaleOrder(models.TransientModel):
_name = "report.sale.order"
_description = "Wizard for report.sale.order"
_inherit = "xlsx.report"
# Search Criteria
partner_id = fields.Many2one("res.partner", string="Partner")
# Report Result, sale.order
results = fields.Many2many(
"sale.order",
compute="_compute_results",
help="Use compute fields, so there is nothing stored in database",
)
def _compute_results(self):
"""On the wizard, result will be computed and added to results line
before export to excel, by using xlsx.export
"""
self.ensure_one()
Result = self.env["sale.order"]
domain = []
if self.partner_id:
domain += [("partner_id", "=", self.partner_id.id)]
self.results = Result.search(domain)
| 33.6
| 1,008
|
5,189
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import SingleTransactionCase
class TestExcelImportExport(SingleTransactionCase):
@classmethod
def setUpClass(cls):
super(TestExcelImportExport, cls).setUpClass()
@classmethod
def setUpXLSXTemplate(cls):
cls.template_obj = cls.env["xlsx.template"]
# Create xlsx.template using input_instruction
input_instruction = {
"__EXPORT__": {
"sale_order": {
"_HEAD_": {
"B2": 'partner_id.display_name${value or ""}'
"#{align=left;style=text}",
"B3": 'name${value or ""}#{align=left;style=text}',
},
"order_line": {
"A6": 'product_id.display_name${value or ""}' "#{style=text}",
"B6": 'name${value or ""}#{style=text}',
"C6": "product_uom_qty${value or 0}#{style=number}",
"D6": 'product_uom.name${value or ""}#{style=text}',
"E6": "price_unit${value or 0}#{style=number}",
"F6": 'tax_id${value and ","'
'.join([x.display_name for x in value]) or ""}',
"G6": "price_subtotal${value or 0}#{style=number}",
},
}
},
"__IMPORT__": {
"sale_order": {
"order_line": {
"A6": "product_id",
"B6": "name",
"C6": "product_uom_qty",
"D6": "product_uom",
"E6": "price_unit",
"F6": "tax_id",
}
}
},
# '__POST_IMPORT__': '${object.post_import_do_something()}',
}
vals = {
"res_model": "sale.order",
"fname": "sale_order.xlsx",
"name": "Sale Order Template",
"description": "Sample Sales Order Template for testing",
"input_instruction": str(input_instruction),
}
cls.sample_template = cls.template_obj.create(vals)
@classmethod
def setUpSaleOrder(cls):
cls.setUpPrepSaleOrder()
# Create a Sales Order
product_line = {
"name": cls.product_order.name,
"product_id": cls.product_order.id,
"product_uom_qty": 2,
"product_uom": cls.product_order.uom_id.id,
"price_unit": cls.product_order.list_price,
"tax_id": False,
}
cls.sale_order = cls.env["sale.order"].create(
{
"partner_id": cls.partner.id,
"order_line": [(0, 0, product_line), (0, 0, product_line)],
}
)
@classmethod
def setUpManySaleOrder(cls):
cls.setUpPrepSaleOrder()
# Create a Sales Order
product_line = {
"name": cls.product_order.name,
"product_id": cls.product_order.id,
"product_uom_qty": 2,
"product_uom": cls.product_order.uom_id.id,
"price_unit": cls.product_order.list_price,
"tax_id": False,
}
for _i in range(10):
cls.env["sale.order"].create(
{
"partner_id": cls.partner.id,
"order_line": [(0, 0, product_line), (0, 0, product_line)],
}
)
@classmethod
def setUpPrepSaleOrder(cls):
categ_ids = cls.env["res.partner.category"].search([]).ids
cls.partner = cls.env["res.partner"].create(
{"name": "Test Partner", "category_id": [(6, 0, categ_ids)]}
)
# Create a Product
user_type_income = cls.env.ref("account.data_account_type_direct_costs")
cls.account_income_product = cls.env["account.account"].create(
{
"code": "INCOME_PROD111",
"name": "Income - Test Account",
"user_type_id": user_type_income.id,
}
)
# Create category
cls.product_category = cls.env["product.category"].create(
{
"name": "Product Category with Income account",
"property_account_income_categ_id": cls.account_income_product.id,
}
)
# Products
uom_unit = cls.env.ref("uom.product_uom_unit")
cls.product_order = cls.env["product.product"].create(
{
"name": "Test Product",
"standard_price": 235.0,
"list_price": 280.0,
"type": "consu",
"uom_id": uom_unit.id,
"uom_po_id": uom_unit.id,
"invoice_policy": "order",
"expense_policy": "no",
"default_code": "PROD_ORDER",
"service_type": "manual",
"taxes_id": False,
"categ_id": cls.product_category.id,
}
)
| 38.154412
| 5,189
|
1,178
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import Form
from .test_common import TestExcelImportExport
class TestXLSXReport(TestExcelImportExport):
@classmethod
def setUpClass(cls):
super(TestXLSXReport, cls).setUpClass()
def test_xlsx_report(self):
"""Test Report from Sales Order"""
# Create Many Sales Orders
self.setUpManySaleOrder()
ctx = {
"template_domain": [
("res_model", "=", "report.sale.order"),
("fname", "=", "report_sale_order.xlsx"),
("gname", "=", False),
]
}
with Form(self.env["report.sale.order"].with_context(**ctx)) as f:
f.partner_id = self.partner
report_wizard = f.save()
# Test whether it loads correct template
self.assertEqual(
report_wizard.template_id,
self.env.ref("excel_import_export_demo." "report_sale_order_template"),
)
# Report excel
report_wizard.report_xlsx()
self.assertTrue(report_wizard.data)
| 34.647059
| 1,178
|
2,969
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo.tests.common import Form
from .test_common import TestExcelImportExport
class TestXLSXImportExport(TestExcelImportExport):
@classmethod
def setUpClass(cls):
super(TestExcelImportExport, cls).setUpClass()
def test_xlsx_export_import(self):
"""Test Export Excel from Sales Order"""
# Create Sales Order
self.setUpSaleOrder()
# ----------- EXPORT ---------------
ctx = {
"active_model": "sale.order",
"active_ids": [self.sale_order.id],
"template_domain": [
("res_model", "=", "sale.order"),
("fname", "=", "sale_order.xlsx"),
("gname", "=", False),
],
}
f = Form(self.env["export.xlsx.wizard"].with_context(**ctx))
export_wizard = f.save()
# Test whether it loads correct template
self.assertEqual(
export_wizard.template_id,
self.env.ref("excel_import_export_demo.sale_order_xlsx_template"),
)
# Export excel
export_wizard.action_export()
self.assertTrue(export_wizard.data)
self.export_file = export_wizard.data
# ----------- IMPORT ---------------
ctx = {
"active_model": "sale.order",
"active_id": self.sale_order.id,
"template_domain": [
("res_model", "=", "sale.order"),
("fname", "=", "sale_order.xlsx"),
("gname", "=", False),
],
"template_context": {"state": "draft"},
}
with Form(self.env["import.xlsx.wizard"].with_context(**ctx)) as f:
f.import_file = self.export_file
import_wizard = f.save()
# Test sample template
import_wizard.get_import_sample()
self.assertTrue(import_wizard.datas)
# Test whether it loads correct template
self.assertEqual(
import_wizard.template_id,
self.env.ref("excel_import_export_demo.sale_order_xlsx_template"),
)
# Import Excel
import_wizard.action_import()
def test_add_remove_export_import_action(self):
"""On the template itself, test add / remove action"""
template = self.env.ref("excel_import_export_demo.sale_order_xlsx_template")
self.assertTrue(template.import_action_id)
self.assertTrue(template.export_action_id)
# Remove actions
template.remove_export_action()
template.remove_import_action()
self.assertFalse(template.import_action_id)
self.assertFalse(template.export_action_id)
# Add actions back again
template.add_export_action()
template.add_import_action()
self.assertTrue(template.import_action_id)
self.assertTrue(template.export_action_id)
| 38.064103
| 2,969
|
3,961
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from ast import literal_eval
from odoo.exceptions import UserError
from odoo.tests.common import Form
from .test_common import TestExcelImportExport
class TestXLSXTemplate(TestExcelImportExport):
@classmethod
def setUpClass(cls):
super(TestExcelImportExport, cls).setUpClass()
def test_xlsx_template(self):
"""Test XLSX Template input and output instruction"""
self.setUpXLSXTemplate()
instruction_dict = literal_eval(self.sample_template.instruction)
self.assertDictEqual(
instruction_dict,
{
"__EXPORT__": {
"sale_order": {
"_HEAD_": {
"B2": 'partner_id.display_name${value or ""}'
"#{align=left;style=text}#??",
"B3": 'name${value or ""}' "#{align=left;style=text}#??",
},
"order_line": {
"A6": 'product_id.display_name${value or ""}'
"#{style=text}#??",
"B6": 'name${value or ""}#{style=text}#??',
"C6": "product_uom_qty${value or 0}" "#{style=number}#??",
"D6": 'product_uom.name${value or ""}' "#{style=text}#??",
"E6": "price_unit${value or 0}#{style=number}#??",
"F6": 'tax_id${value and ",".join([x.display_name '
'for x in value]) or ""}#{}#??',
"G6": "price_subtotal${value or 0}" "#{style=number}#??",
},
}
},
"__IMPORT__": {
"sale_order": {
"order_line": {
"A6": "product_id",
"B6": "name",
"C6": "product_uom_qty",
"D6": "product_uom",
"E6": "price_unit",
"F6": "tax_id",
}
}
},
"__POST_IMPORT__": False,
},
)
# Finally load excel file into this new template
self.assertFalse(self.sample_template.datas) # Not yet loaded
self.template_obj.load_xlsx_template(
[self.sample_template.id], addon="excel_import_export_demo"
)
self.assertTrue(self.sample_template.datas) # Loaded successfully
def test_xlsx_template_easy_reporting(self):
"""Test XLSX template using easy reporting option"""
sale_model = self.env["ir.model"].search([("model", "=", "sale.order")])
# Create the template
with Form(self.env["xlsx.template"]) as f:
f.name = "Test Easy Reporting"
f.use_report_wizard = True
f.result_model_id = sale_model
template = f.save()
self.assertEqual(template.res_model, "report.xlsx.wizard")
self.assertFalse(template.redirect_action, False)
self.assertTrue(template.result_field)
self.assertFalse(template.report_menu_id)
self.assertEqual(len(template.export_ids), 3)
with self.assertRaises(UserError):
template.add_report_menu()
template.fname = "test.xlsx"
# Add the menu
template.add_report_menu()
self.assertTrue(template.report_menu_id)
res = template.report_menu_id.action.read()[0]
ctx = literal_eval(res["context"])
f = Form(self.env[res["res_model"]].with_context(**ctx))
report_wizard = f.save()
res = report_wizard.action_report()
# Finally reture the report action
self.assertEqual(res["type"], "ir.actions.report")
| 43.527473
| 3,961
|
2,103
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo import fields, models
class ReportCRMLead(models.TransientModel):
_name = "report.crm.lead"
_description = "Wizard for report.crm.lead"
_inherit = "xlsx.report"
# Search Criteria
team_id = fields.Many2one("crm.team", string="Sales Team")
# Report Result, crm.lead
results = fields.Many2many(
"crm.lead",
compute="_compute_results",
)
revenue_by_country = fields.Many2many(
"crm.lead",
compute="_compute_revenue_by_country",
)
revenue_by_team = fields.Many2many(
"crm.lead",
compute="_compute_revenue_by_team",
)
def _compute_results(self):
self.ensure_one()
domain = []
if self.team_id:
domain += [("team_id", "=", self.team_id.id)]
self.results = self.env["crm.lead"].search(domain)
def _compute_revenue_by_country(self):
self.ensure_one()
domain = []
if self.team_id:
domain += [("team_id", "=", self.team_id.id)]
results = self.env["crm.lead"].read_group(
domain,
["country_id", "expected_revenue"],
["country_id"],
orderby="country_id",
)
for row in results:
self.revenue_by_country += self.env["crm.lead"].new(
{
"country_id": row["country_id"],
"expected_revenue": row["expected_revenue"],
}
)
def _compute_revenue_by_team(self):
self.ensure_one()
domain = []
if self.team_id:
domain += [("team_id", "=", self.team_id.id)]
results = self.env["crm.lead"].read_group(
domain, ["team_id", "expected_revenue"], ["team_id"], orderby="team_id"
)
for row in results:
self.revenue_by_team += self.env["crm.lead"].new(
{"team_id": row["team_id"], "expected_revenue": row["expected_revenue"]}
)
| 32.353846
| 2,103
|
917
|
py
|
PYTHON
|
15.0
|
# Copyright 2019 Ecosoft Co., Ltd (http://ecosoft.co.th/)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html)
from odoo import fields, models
class ReportPartnerList(models.TransientModel):
_name = "report.partner.list"
_description = "Wizard for report.partner.list"
partner_ids = fields.Many2many(comodel_name="res.partner")
results = fields.Many2many(
"res.partner",
compute="_compute_results",
help="Use compute fields, so there is nothing store in database",
)
def _compute_results(self):
"""On the wizard, result will be computed and added to results line
before export to excel by report_excel action
"""
self.ensure_one()
domain = []
if self.partner_ids:
domain.append(("id", "in", self.partner_ids.ids))
self.results = self.env["res.partner"].search(domain, order="id")
| 35.269231
| 917
|
746
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Lorenzo Battistini <lorenzo.battistini@agilebg.com>
# Copyright 2017 ForgeFlow <http://www.forgeflow.com>
# Copyright 2018 Hai Dinh <haidd.uit@gmail.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Fetchmail Notify Error to Sender",
"summary": "If fetching mails gives error, send an email to sender",
"version": "15.0.1.0.1",
"category": "Tools",
"author": "Agile Business Group,ForgeFlow,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/server-tools",
"license": "AGPL-3",
"depends": ["fetchmail"],
"data": ["views/fetchmail_view.xml", "data/email_template_data.xml"],
"qweb": [],
"installable": True,
"application": False,
}
| 39.263158
| 746
|
292
|
py
|
PYTHON
|
15.0
|
# Copyright 2023 ForgeFlow <http://www.forgeflow.com>
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
openupgrade.load_data(
env.cr,
"fetchmail_notify_error_to_sender",
"migrations/15.0.1.0.1/noupdate_changes.xml",
)
| 26.545455
| 292
|
581
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Lorenzo Battistini <lorenzo.battistini@agilebg.com>
# Copyright 2017 ForgeFlow <http://www.forgeflow.com>
# Copyright 2018 Hai Dinh <haidd.uit@gmail.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class FetchmailServer(models.Model):
_inherit = "fetchmail.server"
error_notice_template_id = fields.Many2one(
"mail.template",
string="Error notice template",
help="Set here the template to use to send notice to sender when "
"errors occur while fetching email",
)
| 34.176471
| 581
|
1,328
|
py
|
PYTHON
|
15.0
|
# Copyright 2015-2017 Lorenzo Battistini <lorenzo.battistini@agilebg.com>
# Copyright 2017 ForgeFlow <http://www.forgeflow.com>
# Copyright 2018 Hai Dinh <haidd.uit@gmail.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, models
class MailThread(models.AbstractModel):
_inherit = "mail.thread"
@api.model
def message_route(
self, message, message_dict, model=None, thread_id=None, custom_values=None
):
try:
res = super(MailThread, self).message_route(
message,
message_dict,
model=model,
thread_id=thread_id,
custom_values=custom_values,
)
except ValueError as ve:
fetchmail_server_id = self.env.context.get("default_fetchmail_server_id")
if not fetchmail_server_id:
raise ve
fetchmail_server = (
self.env["fetchmail.server"]
.with_context(sender_message=message, route_exception=ve)
.browse(fetchmail_server_id)
)
if not fetchmail_server.error_notice_template_id:
raise ve
fetchmail_server.error_notice_template_id.send_mail(fetchmail_server.id)
raise ve
return res
| 35.891892
| 1,328
|
344
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 LasLabs Inc.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
from odoo import SUPERUSER_ID, api
from .models.module import PARAM_INSTALLED_CHECKSUMS
def uninstall_hook(cr, registry):
env = api.Environment(cr, SUPERUSER_ID, {})
env["ir.config_parameter"].set_param(PARAM_INSTALLED_CHECKSUMS, False)
| 31.272727
| 344
|
1,475
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ACSONE SA/NV.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
import hashlib
import os
from fnmatch import fnmatch
def _fnmatch(filename, patterns):
for pattern in patterns:
if fnmatch(filename, pattern):
return True
return False
def _walk(top, exclude_patterns, keep_langs):
keep_langs = {language.split("_")[0] for language in keep_langs}
for dirpath, dirnames, filenames in os.walk(top):
dirnames.sort()
reldir = os.path.relpath(dirpath, top)
if reldir == ".":
reldir = ""
for filename in sorted(filenames):
filepath = os.path.join(reldir, filename)
if _fnmatch(filepath, exclude_patterns):
continue
if keep_langs and reldir in {"i18n", "i18n_extra"}:
basename, ext = os.path.splitext(filename)
if ext == ".po":
if basename.split("_")[0] not in keep_langs:
continue
yield filepath
def addon_hash(top, exclude_patterns, keep_langs):
"""Compute a sha1 digest of file contents."""
m = hashlib.sha1()
for filepath in _walk(top, exclude_patterns, keep_langs):
# hash filename so empty files influence the hash
m.update(filepath.encode("utf-8"))
# hash file content
with open(os.path.join(top, filepath), "rb") as f:
m.update(f.read())
return m.hexdigest()
| 33.522727
| 1,475
|
700
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 LasLabs Inc.
# Copyright 2018 Brainbean Apps (https://brainbeanapps.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
{
"name": "Module Auto Update",
"summary": "Automatically update Odoo modules",
"version": "15.0.1.0.1",
"category": "Extra Tools",
"website": "https://github.com/OCA/server-tools",
"author": "LasLabs, "
"Juan José Scarafía, "
"Tecnativa, "
"ACSONE SA/NV, "
"Odoo Community Association (OCA)",
"license": "LGPL-3",
"installable": True,
"uninstall_hook": "uninstall_hook",
"depends": ["base"],
"data": ["views/ir_module_module.xml"],
"development_status": "Production/Stable",
}
| 31.727273
| 698
|
9,546
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 LasLabs Inc.
# Copyright 2018 ACSONE SA/NV.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
import os
import tempfile
import mock
import odoo
from odoo.modules import get_module_path
from odoo.tests import TransactionCase
from ..addon_hash import addon_hash
from ..models.module import DEFAULT_EXCLUDE_PATTERNS, IncompleteUpgradeError
MODULE_NAME = "module_auto_update"
class TestModule(TransactionCase):
def setUp(self):
super(TestModule, self).setUp()
self.own_module = self.env["ir.module.module"].search(
[("name", "=", MODULE_NAME)]
)
self.own_dir_path = get_module_path(MODULE_NAME)
keep_langs = self.env["res.lang"].search([]).mapped("code")
self.own_checksum = addon_hash(
self.own_dir_path,
exclude_patterns=DEFAULT_EXCLUDE_PATTERNS.split(","),
keep_langs=keep_langs,
)
self.own_writeable = os.access(self.own_dir_path, os.W_OK)
def test_compute_checksum_dir(self):
"""It should compute the directory's SHA-1 hash"""
self.assertEqual(
self.own_module._get_checksum_dir(),
self.own_checksum,
"Module directory checksum not computed properly",
)
def test_compute_checksum_dir_ignore_excluded(self):
"""It should exclude .pyc/.pyo extensions from checksum
calculations"""
if not self.own_writeable:
self.skipTest("Own directory not writeable")
with tempfile.NamedTemporaryFile(suffix=".pyc", dir=self.own_dir_path):
self.assertEqual(
self.own_module._get_checksum_dir(),
self.own_checksum,
"SHA1 checksum does not ignore excluded extensions",
)
def test_compute_checksum_dir_recomputes_when_file_added(self):
"""It should return a different value when a non-.pyc/.pyo file is
added to the module directory"""
if not self.own_writeable:
self.skipTest("Own directory not writeable")
with tempfile.NamedTemporaryFile(suffix=".py", dir=self.own_dir_path):
self.assertNotEqual(
self.own_module._get_checksum_dir(),
self.own_checksum,
"SHA1 checksum not recomputed",
)
def test_saved_checksums(self):
Imm = self.env["ir.module.module"]
base_module = Imm.search([("name", "=", "base")])
self.assertEqual(base_module.state, "installed")
self.assertFalse(Imm._get_saved_checksums())
Imm._save_installed_checksums()
saved_checksums = Imm._get_saved_checksums()
self.assertTrue(saved_checksums)
self.assertTrue(saved_checksums["base"])
def test_get_modules_with_changed_checksum(self):
Imm = self.env["ir.module.module"]
self.assertTrue(Imm._get_modules_with_changed_checksum())
Imm._save_installed_checksums()
self.assertFalse(Imm._get_modules_with_changed_checksum())
@odoo.tests.tagged("post_install", "-at_install")
class TestModuleAfterInstall(TransactionCase):
def setUp(self):
super(TestModuleAfterInstall, self).setUp()
Imm = self.env["ir.module.module"]
self.own_module = Imm.search([("name", "=", MODULE_NAME)])
self.base_module = Imm.search([("name", "=", "base")])
def test_get_modules_partially_installed(self):
Imm = self.env["ir.module.module"]
self.assertTrue(self.own_module not in Imm._get_modules_partially_installed())
self.own_module.button_upgrade()
self.assertTrue(self.own_module in Imm._get_modules_partially_installed())
self.own_module.button_upgrade_cancel()
self.assertTrue(self.own_module not in Imm._get_modules_partially_installed())
def test_upgrade_changed_checksum(self):
Imm = self.env["ir.module.module"]
Bmu = self.env["base.module.upgrade"]
# check modules are in installed state
installed_modules = Imm.search([("state", "=", "installed")])
self.assertTrue(self.own_module in installed_modules)
self.assertTrue(self.base_module in installed_modules)
self.assertTrue(len(installed_modules) > 2)
# change the checksum of 'base'
Imm._save_installed_checksums()
saved_checksums = Imm._get_saved_checksums()
saved_checksums["base"] = False
Imm._save_checksums(saved_checksums)
changed_modules = Imm._get_modules_with_changed_checksum()
self.assertEqual(len(changed_modules), 1)
self.assertTrue(self.base_module in changed_modules)
def upgrade_module_mock(self_model):
upgrade_module_mock.call_count += 1
# since we are upgrading base, all installed module
# must have been marked to upgrade at this stage
self.assertEqual(self.base_module.state, "to upgrade")
self.assertEqual(self.own_module.state, "to upgrade")
installed_modules.write({"state": "installed"})
upgrade_module_mock.call_count = 0
# upgrade_changed_checksum commits, so mock that
with mock.patch.object(self.env.cr, "commit"):
# we simulate an install by setting module states
Bmu._patch_method("upgrade_module", upgrade_module_mock)
try:
Imm.upgrade_changed_checksum()
self.assertEqual(upgrade_module_mock.call_count, 1)
self.assertEqual(self.base_module.state, "installed")
self.assertEqual(self.own_module.state, "installed")
saved_checksums = Imm._get_saved_checksums()
self.assertTrue(saved_checksums["base"])
self.assertTrue(saved_checksums[MODULE_NAME])
finally:
Bmu._revert_method("upgrade_module")
def test_incomplete_upgrade(self):
Imm = self.env["ir.module.module"]
Bmu = self.env["base.module.upgrade"]
installed_modules = Imm.search([("state", "=", "installed")])
# change the checksum of 'base'
Imm._save_installed_checksums()
saved_checksums = Imm._get_saved_checksums()
saved_checksums["base"] = False
Imm._save_checksums(saved_checksums)
def upgrade_module_mock(self_model):
upgrade_module_mock.call_count += 1
# since we are upgrading base, all installed module
# must have been marked to upgrade at this stage
self.assertEqual(self.base_module.state, "to upgrade")
self.assertEqual(self.own_module.state, "to upgrade")
installed_modules.write({"state": "installed"})
# simulate partial upgrade
self.own_module.write({"state": "to upgrade"})
upgrade_module_mock.call_count = 0
# upgrade_changed_checksum commits, so mock that
with mock.patch.object(self.env.cr, "commit"):
# we simulate an install by setting module states
Bmu._patch_method("upgrade_module", upgrade_module_mock)
try:
with self.assertRaises(IncompleteUpgradeError):
Imm.upgrade_changed_checksum()
self.assertEqual(upgrade_module_mock.call_count, 1)
finally:
Bmu._revert_method("upgrade_module")
def test_incomplete_upgrade_no_checkusm(self):
Imm = self.env["ir.module.module"]
Bmu = self.env["base.module.upgrade"]
installed_modules = Imm.search([("state", "=", "installed")])
# change the checksum of 'base'
Imm._save_installed_checksums()
saved_checksums = Imm._get_saved_checksums()
Imm._save_checksums(saved_checksums)
self.base_module.write({"state": "to upgrade"})
def upgrade_module_mock(self_model):
upgrade_module_mock.call_count += 1
# since we are upgrading base, all installed module
# must have been marked to upgrade at this stage
self.assertEqual(self.base_module.state, "to upgrade")
self.assertEqual(self.own_module.state, "installed")
installed_modules.write({"state": "installed"})
upgrade_module_mock.call_count = 0
# upgrade_changed_checksum commits, so mock that
with mock.patch.object(self.env.cr, "commit"):
# we simulate an install by setting module states
Bmu._patch_method("upgrade_module", upgrade_module_mock)
# got just other modules to_upgrade and no checksum ones
try:
Imm.upgrade_changed_checksum()
self.assertEqual(upgrade_module_mock.call_count, 1)
finally:
Bmu._revert_method("upgrade_module")
def test_nothing_to_upgrade(self):
Imm = self.env["ir.module.module"]
Bmu = self.env["base.module.upgrade"]
Imm._save_installed_checksums()
def upgrade_module_mock(self_model):
upgrade_module_mock.call_count += 1
upgrade_module_mock.call_count = 0
# upgrade_changed_checksum commits, so mock that
with mock.patch.object(self.env.cr, "commit"):
# we simulate an install by setting module states
Bmu._patch_method("upgrade_module", upgrade_module_mock)
try:
Imm.upgrade_changed_checksum()
self.assertEqual(upgrade_module_mock.call_count, 0)
finally:
Bmu._revert_method("upgrade_module")
| 40.969957
| 9,546
|
2,132
|
py
|
PYTHON
|
15.0
|
# Copyright 2018 ACSONE SA/NV.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
import os
import unittest
from .. import addon_hash
from ..models.module import DEFAULT_EXCLUDE_PATTERNS
class TestAddonHash(unittest.TestCase):
def setUp(self):
super(TestAddonHash, self).setUp()
self.sample_dir = os.path.join(
os.path.dirname(__file__),
"sample_module",
)
def test_basic(self):
files = list(
addon_hash._walk(
self.sample_dir,
exclude_patterns=["*/__pycache__/*"],
keep_langs=[],
)
)
self.assertEqual(
files,
[
"README.rst",
"data/f1.xml",
"data/f2.xml",
"i18n/en.po",
"i18n/en_US.po",
"i18n/fr.po",
"i18n/fr_BE.po",
"i18n/test.pot",
"i18n_extra/en.po",
"i18n_extra/fr.po",
"i18n_extra/nl_NL.po",
"models/stuff.py",
"models/stuff.pyc",
"models/stuff.pyo",
"static/src/some.js",
],
)
def test_exclude(self):
files = list(
addon_hash._walk(
self.sample_dir,
exclude_patterns=DEFAULT_EXCLUDE_PATTERNS.split(","),
keep_langs=["fr_FR", "nl"],
)
)
self.assertEqual(
files,
[
"README.rst",
"data/f1.xml",
"data/f2.xml",
"i18n/fr.po",
"i18n/fr_BE.po",
"i18n_extra/fr.po",
"i18n_extra/nl_NL.po",
"models/stuff.py",
],
)
def test2(self):
checksum = addon_hash.addon_hash(
self.sample_dir,
exclude_patterns=["*.pyc", "*.pyo", "*.pot", "static/*"],
keep_langs=["fr_FR", "nl"],
)
self.assertEqual(checksum, "fecb89486c8a29d1f760cbd01c1950f6e8421b14")
| 28.052632
| 2,132
|
10
|
py
|
PYTHON
|
15.0
|
_ = 1 + 1
| 10
| 10
|
6,930
|
py
|
PYTHON
|
15.0
|
# Copyright 2017 LasLabs Inc.
# Copyright 2018 ACSONE SA/NV.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
import json
import logging
import os
from odoo import _, api, exceptions, models, tools
from odoo.modules.module import get_module_path
from ..addon_hash import addon_hash
PARAM_INSTALLED_CHECKSUMS = "module_auto_update.installed_checksums"
PARAM_EXCLUDE_PATTERNS = "module_auto_update.exclude_patterns"
DEFAULT_EXCLUDE_PATTERNS = "*.pyc,*.pyo,i18n/*.pot,i18n_extra/*.pot,static/*"
_logger = logging.getLogger(__name__)
class FailedUpgradeError(exceptions.UserError):
pass
class IncompleteUpgradeError(exceptions.UserError):
pass
def ensure_module_state(env, modules, state):
# read module states, bypassing any Odoo cache
if not modules:
return
env.cr.execute(
"SELECT name FROM ir_module_module " "WHERE id IN %s AND state != %s",
(tuple(modules.ids), state),
)
names = [r[0] for r in env.cr.fetchall()]
if names:
raise FailedUpgradeError(
"The following modules should be in state '%s' "
"at this stage: %s. Bailing out for safety."
% (
state,
",".join(names),
),
)
class Module(models.Model):
_inherit = "ir.module.module"
def _get_checksum_dir(self):
self.ensure_one()
exclude_patterns = self.env["ir.config_parameter"].get_param(
PARAM_EXCLUDE_PATTERNS,
DEFAULT_EXCLUDE_PATTERNS,
)
exclude_patterns = [p.strip() for p in exclude_patterns.split(",")]
keep_langs = self.env["res.lang"].search([]).mapped("code")
module_path = get_module_path(self.name)
if module_path and os.path.isdir(module_path):
checksum_dir = addon_hash(
module_path,
exclude_patterns,
keep_langs,
)
else:
checksum_dir = False
return checksum_dir
@api.model
def _get_saved_checksums(self):
Icp = self.env["ir.config_parameter"]
return json.loads(Icp.get_param(PARAM_INSTALLED_CHECKSUMS, "{}"))
@api.model
def _save_checksums(self, checksums):
Icp = self.env["ir.config_parameter"]
Icp.set_param(PARAM_INSTALLED_CHECKSUMS, json.dumps(checksums))
Icp.flush()
@api.model
def _save_installed_checksums(self):
checksums = {}
installed_modules = self.search([("state", "=", "installed")])
for module in installed_modules:
checksums[module.name] = module._get_checksum_dir()
self._save_checksums(checksums)
@api.model
def _get_modules_partially_installed(self):
return self.search([("state", "in", ("to install", "to remove", "to upgrade"))])
@api.model
def _get_modules_with_changed_checksum(self):
saved_checksums = self._get_saved_checksums()
installed_modules = self.search([("state", "=", "installed")])
return installed_modules.filtered(
lambda r: r._get_checksum_dir() != saved_checksums.get(r.name),
)
@api.model
def upgrade_changed_checksum(self, overwrite_existing_translations=False):
"""Run an upgrade of the database, upgrading only changed modules.
Installed modules for which the checksum has changed since the
last successful run of this method are marked "to upgrade",
then the normal Odoo scheduled upgrade process
is launched.
If there is no module with a changed checksum, and no module in state
other than installed, uninstalled, uninstallable, this method does
nothing, otherwise the normal Odoo upgrade process is launched.
After a successful upgrade, the checksums of installed modules are
saved.
In case of error during the upgrade, an exception is raised.
If any module remains to upgrade or to uninstall after the upgrade
process, an exception is raised as well.
Note: this method commits the current transaction at each important
step, it is therefore not intended to be run as part of a
larger transaction.
"""
_logger.info(
"Checksum upgrade starting (i18n-overwrite=%s)...",
overwrite_existing_translations,
)
tools.config[
"overwrite_existing_translations"
] = overwrite_existing_translations
_logger.info("Updating modules list...")
self.update_list()
changed_modules = self._get_modules_with_changed_checksum()
if not changed_modules and not self._get_modules_partially_installed():
_logger.info(
"No checksum change detected in installed modules "
"and all modules installed, nothing to do."
)
return {
"type": "ir.actions.client",
"tag": "display_notification",
"params": {
"message": _(
"No checksum change detected in installed modules "
"and all modules installed, nothing to do."
),
"type": "success",
"sticky": False,
},
}
_logger.info(
"Marking the following modules to upgrade, "
"for their checksums changed: %s...",
",".join(changed_modules.mapped("name")),
)
changed_modules.button_upgrade()
self.env.cr.commit() # pylint: disable=invalid-commit
# in rare situations, button_upgrade may fail without
# exception, this would lead to corruption because
# no upgrade would be performed and save_installed_checksums
# would update cheksums for modules that have not been upgraded
ensure_module_state(self.env, changed_modules, "to upgrade")
_logger.info("Upgrading...")
self.env["base.module.upgrade"].upgrade_module()
self.env.cr.commit() # pylint: disable=invalid-commit
_logger.info("Upgrade successful, updating checksums...")
self._save_installed_checksums()
self.env.cr.commit() # pylint: disable=invalid-commit
partial_modules = self._get_modules_partially_installed()
if partial_modules:
raise IncompleteUpgradeError(
"Checksum upgrade successful "
"but incomplete for the following modules: %s"
% ",".join(partial_modules.mapped("name"))
)
_logger.info("Checksum upgrade complete.")
return {
"type": "ir.actions.client",
"tag": "display_notification",
"params": {
"message": _("Checksum upgrade complete."),
"type": "success",
"sticky": False,
},
}
| 35
| 6,930
|
617
|
py
|
PYTHON
|
15.0
|
# Copyright 2015, 2017 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2016 Tecnativa, S.L. - Vicent Cubells
# Copyright 2018 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Date & Time Formatter",
"summary": "Helper functions to give correct format to date[time] fields",
"version": "15.0.1.0.0",
"category": "Tools",
"website": "https://github.com/OCA/server-tools",
"author": "Grupo ESOC Ingeniería de Servicios, Tecnativa, Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"depends": ["base"],
}
| 38.5
| 616
|
2,994
|
py
|
PYTHON
|
15.0
|
# Copyright 2015, 2017 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2016 Tecnativa, S.L. - Vicent Cubells
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import datetime
from random import random
from odoo.tests.common import TransactionCase
from odoo.tools import (
DEFAULT_SERVER_DATE_FORMAT,
DEFAULT_SERVER_DATETIME_FORMAT,
DEFAULT_SERVER_TIME_FORMAT,
)
from ..models.res_lang import MODE_DATE, MODE_DATETIME, MODE_TIME
class FormatterCase(TransactionCase):
def setUp(self):
super().setUp()
self.rl = self.env["res.lang"]
self.bm = self.rl.best_match()
self.dt = datetime.datetime.now()
self.d_fmt = self.bm.date_format or DEFAULT_SERVER_DATE_FORMAT
self.t_fmt = self.bm.time_format or DEFAULT_SERVER_TIME_FORMAT
self.kwargs = dict()
def tearDown(self):
# This should be returned
self.expected = self.dt.strftime(self.format)
# Pass a datetime object
self.assertEqual(
self.expected, self.rl.datetime_formatter(self.dt, **self.kwargs)
)
# When the date comes as a string
if isinstance(self.dt, datetime.datetime):
self.dt_str = self.dt.strftime(DEFAULT_SERVER_DATETIME_FORMAT)
elif isinstance(self.dt, datetime.date):
self.dt_str = self.dt.strftime(DEFAULT_SERVER_DATE_FORMAT)
elif isinstance(self.dt, datetime.time):
self.dt_str = self.dt.strftime(DEFAULT_SERVER_TIME_FORMAT)
# Pass a string
self.assertEqual(
self.expected, self.rl.datetime_formatter(self.dt_str, **self.kwargs)
)
# Pass a unicode
self.assertEqual(
self.expected, self.rl.datetime_formatter(str(self.dt_str), **self.kwargs)
)
super().tearDown()
def test_datetime(self):
"""Format a datetime."""
self.format = "{} {}".format(self.d_fmt, self.t_fmt)
self.kwargs = {"template": MODE_DATETIME}
def test_date(self):
"""Format a date."""
self.format = self.d_fmt
self.kwargs = {"template": MODE_DATE}
self.dt = self.dt.date()
def test_time(self):
"""Format times, including float ones."""
self.format = self.t_fmt
self.kwargs = {"template": MODE_TIME}
self.dt = self.dt.time()
# Test float times
for n in range(50):
n = n + random()
# Patch values with >= 24 hours
fmt = self.format.replace("%H", "%02d" % n)
time = (datetime.datetime.min + datetime.timedelta(hours=n)).time()
self.assertEqual(
time.strftime(fmt), self.rl.datetime_formatter(n, **self.kwargs)
)
def test_custom_separator(self):
"""Format a datetime with a custom separator."""
sep = "T"
self.format = "{}{}{}".format(self.d_fmt, sep, self.t_fmt)
self.kwargs = {"template": MODE_DATETIME, "separator": sep}
| 36.962963
| 2,994
|
2,681
|
py
|
PYTHON
|
15.0
|
# Copyright 2015, 2017 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2016 Tecnativa, S.L. - Vicent Cubells
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.exceptions import UserError
from odoo.tests.common import TransactionCase
class BasicCase(TransactionCase):
def setUp(self):
super().setUp()
self.langs = (
self.env.ref("base.lang_en"),
self.env.ref("base.lang_es"),
self.env.ref("base.lang_it"),
self.env.ref("base.lang_pt"),
self.env.ref("base.lang_zh_CN"),
)
self.rl = self.env["res.lang"]
for lang in self.langs:
self.rl._activate_lang(lang.code)
def test_explicit(self):
"""When an explicit lang is used."""
for lang in self.langs:
self.assertEqual(self.rl.best_match(lang.code).code, lang.code)
def test_record(self):
"""When called from a ``res.lang`` record."""
rl = self.rl.with_context(lang="it_IT")
rl.env.user.lang = "pt_PT"
for lang in self.langs:
self.assertEqual(
rl.search([("code", "=", lang.code)]).best_match().code, lang.code
)
def test_context(self):
"""When called with a lang in context."""
self.env.user.lang = "pt_PT"
for lang in self.langs:
self.assertEqual(
self.rl.with_context(lang=lang.code).best_match().code, lang.code
)
def test_user(self):
"""When lang not specified in context."""
for lang in self.langs:
self.env.user.lang = lang.code
# Lang is False in context
self.assertEqual(
self.rl.with_context(lang=False).best_match().code, lang.code
)
# Lang not found in context
self.assertEqual(self.rl.with_context(**{}).best_match().code, lang.code)
def test_first_installed(self):
"""When falling back to first installed language."""
first = self.rl.search([("active", "=", True)], limit=1)
self.env.user.lang = False
self.assertEqual(self.rl.with_context(lang=False).best_match().code, first.code)
def test_unavailable(self):
"""When matches to an unavailable language."""
self.env.user.lang = False
self.rl = self.rl.with_context(lang=False)
first = self.rl.search([("active", "=", True)], limit=1)
# Safe mode
self.assertEqual(self.rl.best_match("fake_LANG").code, first.code)
# Unsafe mode
with self.assertRaises(UserError):
self.rl.best_match("fake_LANG", failure_safe=False)
| 38.3
| 2,681
|
4,113
|
py
|
PYTHON
|
15.0
|
# Copyright 2015, 2017 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2016 Tecnativa, S.L. - Vicent Cubells
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from datetime import datetime, timedelta
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_TIME_FORMAT
# Available modes for :param:`.ResLang.datetime_formatter.template`
MODE_DATETIME = "MODE_DATETIME"
MODE_DATE = "MODE_DATE"
MODE_TIME = "MODE_TIME"
class ResLang(models.Model):
_inherit = "res.lang"
@api.model
def best_match(self, lang=None, failure_safe=True):
"""Get best match of current default lang.
:param str lang:
If a language in the form of "en_US" is supplied, it will have the
highest priority.
:param bool failure_safe:
If ``False`` and the best matched language is not found installed,
an exception will be raised. Otherwise, the first installed
language found in the DB will be returned.
"""
# Find some installed language, as fallback
first_installed = self.search([("active", "=", True)], limit=1)
if not lang:
lang = (
# Object's language, if called like
# ``record.lang.datetime_formatter(datetime_obj)``
(self.ids and self[0].code)
or self.env.context.get("lang")
or self.env.user.lang
or first_installed.code
)
# Get DB lang record
record = self.search([("code", "=", lang)])
try:
record.ensure_one()
except ValueError as error:
if not failure_safe:
raise UserError(
_("Best matched language (%s) not found.") % lang
) from error
else:
record = first_installed
return record
@api.model
def datetime_formatter(
self, value, lang=None, template=MODE_DATETIME, separator=" ", failure_safe=True
):
"""Convert a datetime field to lang's default format.
:type value: `str`, `float` or `datetime.datetime`
:param value:
Datetime that will be formatted to the user's preferred format.
:param str lang:
See :param:`lang` from :meth:`~.best_match`.
:param bool failure_safe:
See :param:`failure_safe` from :meth:`~.best_match`.
:param str template:
Will be used to format :param:`value`. If it is one of the special
constants :const:`MODE_DATETIME`, :const:`MODE_DATE` or
:const:`MODE_TIME`, it will use the :param:`lang`'s default
template for that mode.
:param str separator:
Only used when :param:`template` is :const:`MODE_DATETIME`, as the
separator between the date and time parts.
"""
# Get the correct lang
lang = self.best_match(lang)
# Get the template
if template in {MODE_DATETIME, MODE_DATE, MODE_TIME}:
defaults = []
if "DATE" in template:
defaults.append(lang.date_format or DEFAULT_SERVER_DATE_FORMAT)
if "TIME" in template:
defaults.append(lang.time_format or DEFAULT_SERVER_TIME_FORMAT)
template = separator.join(defaults)
# Convert str to datetime objects
if isinstance(value, str):
try:
value = fields.Datetime.to_datetime(value)
except ValueError:
# Probably failed due to value being only time
value = datetime.strptime(value, DEFAULT_SERVER_TIME_FORMAT)
# Time-only fields are floats for Odoo
elif isinstance(value, float):
# Patch values >= 24 hours
if value >= 24:
template = template.replace("%H", "%d" % value)
# Convert to time
value = (datetime.min + timedelta(hours=value)).time()
return value.strftime(template)
| 41.545455
| 4,113
|
616
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Therp BV <https://therp.nl>
# Copyright 2018 Tecnativa - Sergio Teruel
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
{
"name": "Extended view inheritance",
"version": "15.0.2.0.0",
"development_status": "Mature",
"author": "Therp BV,Odoo Community Association (OCA)",
"license": "LGPL-3",
"category": "Hidden/Dependency",
"summary": "Adds more operators for view inheritance",
"website": "https://github.com/OCA/server-tools",
"depends": ["base"],
"external_dependencies": {"python": ["astor"]},
"demo": ["demo/ir_ui_view.xml"],
}
| 38.5
| 616
|
8,649
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Therp BV <http://therp.nl>
# Copyright 2021 Camptocamp SA (https://www.camptocamp.com).
# @author Iván Todorovich <ivan.todorovich@camptocamp.com>
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from lxml import etree
from odoo.tests.common import TransactionCase
class TestBaseViewInheritanceExtension(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.maxDiff = None
def test_base_view_inheritance_extension(self):
view_id = self.env.ref("base.view_partner_simple_form").id
fields_view_get = self.env["res.partner"].fields_view_get(view_id=view_id)
view = etree.fromstring(fields_view_get["arch"])
# Verify normal attributes work
self.assertEqual(view.xpath("//form")[0].get("string"), "Partner form")
# Verify our extra context key worked
self.assertTrue(
"default_name" in view.xpath('//field[@name="parent_id"]')[0].get("context")
)
self.assertTrue(
"context.get('company_id', context.get('company'))"
in view.xpath('//field[@name="parent_id"]')[0].get("context")
)
def test_update_context_default(self):
source = etree.fromstring(
"""
<form>
<field name="account_move_id" context="{'default_journal_id': journal_id}" />
</form>
"""
)
specs = etree.fromstring(
"""
<field name="account_move_id" position="attributes">
<attribute name="context" operation="update">
{"default_company_id": company_id}
</attribute>
</field>
"""
)
res = self.env["ir.ui.view"].apply_inheritance_specs(source, specs)
self.assertEqual(
res.xpath('//field[@name="account_move_id"]')[0].attrib["context"],
"{'default_journal_id': journal_id, 'default_company_id': company_id}",
)
def test_update_context_complex(self):
source = etree.fromstring(
"""
<form>
<field
name="invoice_line_ids"
context="{
'default_type': context.get('default_type'),
'journal_id': journal_id,
'default_partner_id': commercial_partner_id,
'default_currency_id': (
currency_id != company_currency_id and currency_id or False
),
'default_name': 'The company name',
}"
/>
</form>
"""
)
specs = etree.fromstring(
"""
<field name="invoice_line_ids" position="attributes">
<attribute name="context" operation="update">
{
"default_product_id": product_id,
"default_cost_center_id": (
context.get("handle_mrp_cost") and cost_center_id or False
),
}
</attribute>
</field>
"""
)
res = self.env["ir.ui.view"].apply_inheritance_specs(source, specs)
expected_items = [
"'default_type': context.get('default_type')",
"'journal_id': journal_id",
"'default_partner_id': commercial_partner_id",
(
"'default_currency_id': "
"currency_id != company_currency_id and currency_id or False"
),
"'default_name': 'The company name'",
"'default_product_id': product_id",
(
"'default_cost_center_id': "
"context.get('handle_mrp_cost') and cost_center_id or False"
),
]
self.assertEqual(
res.xpath('//field[@name="invoice_line_ids"]')[0].attrib["context"],
"{%s}" % ", ".join(expected_items),
)
def test_update_attrs_new_key(self):
"""Test that we can add new keys to an existing dict"""
source = etree.fromstring(
"""
<form>
<field
name="ref"
attrs="{'invisible': [('state', '=', 'draft')]}"
/>
</form>
"""
)
specs = etree.fromstring(
"""
<field name="ref" position="attributes">
<attribute name="attrs" operation="update">
{
"required": [("state", "!=", "draft")],
}
</attribute>
</field>
"""
)
res = self.env["ir.ui.view"].apply_inheritance_specs(source, specs)
self.assertEqual(
res.xpath('//field[@name="ref"]')[0].attrib["attrs"],
"{'invisible': [('state', '=', 'draft')], "
"'required': [('state', '!=', 'draft')]}",
)
def test_update_attrs_replace(self):
"""Test that we can replace an existing dict key"""
source = etree.fromstring(
"""
<form>
<field
name="ref"
attrs="{
'invisible': [('state', '=', 'draft')],
'required': [('state', '=', False)],
}"
/>
</form>
"""
)
specs = etree.fromstring(
"""
<field name="ref" position="attributes">
<attribute name="attrs" operation="update">
{
"required": [('state', '!=', 'draft')],
}
</attribute>
</field>
"""
)
res = self.env["ir.ui.view"].apply_inheritance_specs(source, specs)
self.assertEqual(
res.xpath('//field[@name="ref"]')[0].attrib["attrs"],
"{'invisible': [('state', '=', 'draft')], "
"'required': [('state', '!=', 'draft')]}",
)
def test_update_empty_source_dict(self):
"""Test that we can add new keys by creating the dict if it's missing"""
source = etree.fromstring(
"""
<form>
<field name="ref" />
</form>
"""
)
specs = etree.fromstring(
"""
<field name="ref" position="attributes">
<attribute name="attrs" operation="update">
{
"required": [('state', '!=', 'draft')],
}
</attribute>
</field>
"""
)
res = self.env["ir.ui.view"].apply_inheritance_specs(source, specs)
self.assertEqual(
res.xpath('//field[@name="ref"]')[0].attrib["attrs"],
"{'required': [('state', '!=', 'draft')]}",
)
def test_update_operation_not_a_dict(self):
"""We should get an error if we try to update a dict with a non-dict spec"""
source = etree.fromstring(
"""
<form>
<field name="ref" />
</form>
"""
)
specs = etree.fromstring(
"""
<field name="ref" position="attributes">
<attribute name="attrs" operation="update">
["not", "a", "dict"]
</attribute>
</field>
"""
)
with self.assertRaisesRegex(
TypeError, "Operation for attribute `attrs` is not a dict"
):
self.env["ir.ui.view"].apply_inheritance_specs(source, specs)
def test_update_source_not_a_dict(self):
"""We should get an error if we try to update a non-dict attribute"""
source = etree.fromstring(
"""
<form>
<field name="child_ids" domain="[('state', '=', 'confirm')]" />
</form>
"""
)
specs = etree.fromstring(
"""
<field name="child_ids" position="attributes">
<attribute name="domain" operation="update">
{
"required": [('state', '!=', 'draft')],
}
</attribute>
</field>
"""
)
with self.assertRaisesRegex(TypeError, "Attribute `domain` is not a dict"):
self.env["ir.ui.view"].apply_inheritance_specs(source, specs)
| 35.735537
| 8,648
|
8,015
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Therp BV <https://therp.nl>
# Copyright 2018 Tecnativa - Sergio Teruel
# Copyright 2021 Camptocamp SA (https://www.camptocamp.com).
# Copyright 2023 Tecnativa - Carlos Dauden
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
import ast
import re
import astor
from lxml import etree
from odoo import api, models
from odoo.osv import expression
def ast_dict_update(source, update):
"""Perform a dict `update` on an ast.Dict
Behaves similar to :meth:`dict.update`, but on ast.Dict instead.
Only compares string-like ast.Dict keys (ast.Str or ast.Constant).
:returns: The updated ast.Dict
:rtype: ast.Dict
"""
if not isinstance(source, ast.Dict):
raise TypeError("`source` must be an AST dict")
if not isinstance(update, ast.Dict):
raise TypeError("`update` must be an AST dict")
def ast_key_eq(k1, k2):
# python < 3.8 uses ast.Str; python >= 3.8 uses ast.Constant
if type(k1) != type(k2):
return False
elif isinstance(k1, ast.Str):
return k1.s == k2.s
elif isinstance(k1, ast.Constant):
return k1.value == k2.value
toadd_uidx = []
for uidx, ukey in enumerate(update.keys):
found = False
for sidx, skey in enumerate(source.keys):
if ast_key_eq(ukey, skey):
source.values[sidx] = update.values[uidx]
found = True
break
if not found:
toadd_uidx.append(uidx)
for uidx in toadd_uidx:
source.keys.append(update.keys[uidx])
source.values.append(update.values[uidx])
return source
class IrUiView(models.Model):
_inherit = "ir.ui.view"
@api.model
def apply_inheritance_specs(self, source, specs_tree, pre_locate=lambda s: True):
for specs, handled_by in self._iter_inheritance_specs(specs_tree):
pre_locate(specs)
source = handled_by(source, specs)
return source
@api.model
def _iter_inheritance_specs(self, spec):
if spec.tag == "data":
for child in spec:
for node, handler in self._iter_inheritance_specs(child):
yield node, handler
return
if spec.get("position") == "attributes":
if all(not c.get("operation") for c in spec):
yield spec, self._get_inheritance_handler(spec)
return
for child in spec:
node = etree.Element(spec.tag, **spec.attrib)
node.insert(0, child)
yield node, self._get_inheritance_handler_attributes(child)
return
yield spec, self._get_inheritance_handler(spec)
@api.model
def _get_inheritance_handler(self, node):
handler = super().apply_inheritance_specs
if hasattr(self, "inheritance_handler_%s" % node.tag):
handler = getattr(self, "inheritance_handler_%s" % node.tag)
return handler
@api.model
def _get_inheritance_handler_attributes(self, node):
handler = super().apply_inheritance_specs
if hasattr(self, "inheritance_handler_attributes_%s" % node.get("operation")):
handler = getattr(
self, "inheritance_handler_attributes_%s" % node.get("operation")
)
return handler
@api.model
def inheritance_handler_attributes_update(self, source, specs):
"""Implement dict `update` operation on the attribute node.
.. code-block:: xml
<field position="attributes">
<attribute name="context" operation="update">
{
"key": "value",
}
</attribute>
</field>
"""
node = self.locate_node(source, specs)
for spec in specs:
attr_name = spec.get("name")
# Parse ast from both node and spec
node_attr = (node.get(attr_name) or "{}").strip()
source_ast = ast.parse(node_attr, mode="eval").body
update_ast = ast.parse(spec.text.strip(), mode="eval").body
if not isinstance(source_ast, ast.Dict):
raise TypeError(f"Attribute `{attr_name}` is not a dict")
if not isinstance(update_ast, ast.Dict):
raise TypeError(f"Operation for attribute `{attr_name}` is not a dict")
# Update node ast dict
source_ast = ast_dict_update(source_ast, update_ast)
# Dump the ast back to source
# TODO: once odoo requires python >= 3.9; use `ast.unparse` instead
node.attrib[attr_name] = astor.to_source(
source_ast,
pretty_source=lambda s: "".join(s).strip(),
)
return source
@api.model
def inheritance_handler_attributes_text_add(self, source, specs):
"""Implement
<$node position="attributes">
<attribute name="$attribute" operation="text_add">
$text_before {old_value} $text_after
</attribute>
</$node>"""
node = self.locate_node(source, specs)
for attribute_node in specs:
attribute_name = attribute_node.get("name")
old_value = node.get(attribute_name) or ""
node.attrib[attribute_name] = attribute_node.text.format(
old_value=old_value
)
return source
@api.model
def inheritance_handler_attributes_domain_add(self, source, specs):
"""Implement
<$node position="attributes">
<attribute name="$attribute" operation="domain_add"
condition="$field_condition" join_operator="OR">
$domain_to_add
</attribute>
</$node>"""
node = self.locate_node(source, specs)
for attribute_node in specs:
attribute_name = attribute_node.get("name")
condition = attribute_node.get("condition")
join_operator = attribute_node.get("join_operator") or "AND"
old_value = node.get(attribute_name) or ""
if old_value:
old_domain = ast.literal_eval(
self.var2str_domain_text(old_value.strip())
)
new_domain = ast.literal_eval(
self.var2str_domain_text(attribute_node.text.strip())
)
if join_operator == "OR":
new_value = str(expression.OR([old_domain, new_domain]))
else:
new_value = str(expression.AND([old_domain, new_domain]))
new_value = self.str2var_domain_text(new_value)
else:
new_value = attribute_node.text
if condition:
new_value = "{condition} and {new_value} or {old_value}".format(
condition=condition,
new_value=new_value,
old_value=old_value,
)
node.attrib[attribute_name] = new_value
return source
@api.model
def var2str_domain_text(self, domain_str):
"""Replaces var names with str names to allow eval without defined vars"""
# Replace fields in 2 steps because 1 step returns "parent_sufix"."var_sufix"
regex_parent = re.compile(r"parent\.(\b\w+\b)")
domain_str = re.sub(
regex_parent, r"'parent.\1_is_a_var_to_replace'", domain_str
)
regex = re.compile(r"(?<!\')(\b\w+\b)(?!\')")
return re.sub(regex, r"'\1_is_a_var_to_replace'", domain_str)
@api.model
def str2var_domain_text(self, domain_str):
"""Revert var2str_domain_text cleaning apostrophes and suffix in vars"""
pattern = re.compile(r"'(parent\.[^']+)_is_a_var_to_replace'")
domain_str = pattern.sub(r"\1", domain_str)
pattern = re.compile(r"'([^']+)_is_a_var_to_replace'")
return pattern.sub(r"\1", domain_str)
| 38.719807
| 8,015
|
721
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Akretion (https://www.akretion.com).
# @author Sébastien BEAU <sebastien.beau@akretion.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "IAP Alternative Provider",
"summary": "Base module for providing alternative provider for iap apps",
"version": "15.0.1.0.0",
"category": "Tools",
"website": "https://github.com/OCA/server-tools",
"author": "Akretion, Odoo Community Association (OCA)",
"maintainers": ["sebastienbeau"],
"license": "AGPL-3",
"application": False,
"installable": True,
"external_dependencies": {"python": [], "bin": []},
"depends": ["iap"],
"data": ["views/iap_account_view.xml"],
"demo": [],
}
| 34.285714
| 720
|
1,858
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 Moka Tourisme (https://www.mokatourisme.fr).
# @author Pierre Verkest <pierreverkest84@gmail.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import mock
from odoo.tests import TransactionCase
class IapAccountCase(TransactionCase):
def test_create_odoo_iap(self):
account = self.env["iap.account"].create(
{
"name": "Odoo IAP",
"provider": "odoo",
"service_name": "some-service",
}
)
self.assertEqual(account.service_name, "some-service")
def test_create_with_mock(self):
with mock.patch(
"odoo.addons.iap_alternative_provider.models."
"iap_account.IapAccount._get_service_from_provider",
return_value="other-service",
):
account = self.env["iap.account"].create(
{
"name": "Odoo IAP",
"provider": "odoo",
"service_name": "some-service",
}
)
self.assertEqual(account.service_name, "other-service")
def test_write_odoo_iap(self):
account = self.env["iap.account"].create(
{
"name": "Odoo IAP",
"provider": "odoo",
"service_name": "",
}
)
self.assertEqual(account.service_name, "")
account.write({"service_name": "some-service"})
self.assertEqual(account.service_name, "some-service")
with mock.patch(
"odoo.addons.iap_alternative_provider.models."
"iap_account.IapAccount._get_service_from_provider",
return_value="other-service",
):
account.write({"service_name": "some-service-2"})
self.assertEqual(account.service_name, "other-service")
| 35.730769
| 1,858
|
1,151
|
py
|
PYTHON
|
15.0
|
# Copyright 2020 Akretion (https://www.akretion.com).
# @author Sébastien BEAU <sebastien.beau@akretion.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class IapAccount(models.Model):
_inherit = "iap.account"
_name = "iap.account"
name = fields.Char()
provider = fields.Selection([("odoo", "Odoo IAP")], required=True, default="odoo")
def _get_service_from_provider(self):
"""In case that the provider only propose one service you can
return the service_name in you module to simplify the user interface"""
return None
def _set_service_from_provider(self):
for record in self:
service = record._get_service_from_provider()
if service and record.service_name != service:
record.service_name = service
@api.model_create_multi
def create(self, vals_list):
record = super().create(vals_list)
record._set_service_from_provider()
return record
def write(self, vals):
super().write(vals)
self._set_service_from_provider()
return True
| 32.857143
| 1,150
|
492
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-20 ForgeFlow S.L. (www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Fetchmail Incoming Log",
"version": "15.0.1.0.0",
"category": "Tools",
"summary": "Log all messages received, before they start to be processed.",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/server-tools",
"depends": ["mail"],
"installable": True,
}
| 35.142857
| 492
|
1,376
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-20 ForgeFlow S.L. (www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import email
import email.policy
import logging
import xmlrpc.client as xmlrpclib
from odoo import api, models
_logger = logging.getLogger(__name__)
class MailThread(models.AbstractModel):
_inherit = "mail.thread"
@api.model
def message_process(
self,
model,
message,
custom_values=None,
save_original=False,
strip_attachments=False,
thread_id=None,
):
message_copy = message
if isinstance(message, xmlrpclib.Binary):
message = bytes(message.data)
if isinstance(message, str):
message = message.encode("utf-8")
message = email.message_from_bytes(message, policy=email.policy.SMTP)
msg_dict = self.message_parse(message, save_original=save_original)
_logger.info(
"Fetched mail from %s to %s with Message-Id %s",
msg_dict.get("from"),
msg_dict.get("to"),
msg_dict.get("message_id"),
)
return super().message_process(
model,
message_copy,
custom_values=custom_values,
save_original=save_original,
strip_attachments=strip_attachments,
thread_id=thread_id,
)
| 28.081633
| 1,376
|
4,363
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Versada <https://versada.eu/>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
import warnings
from collections import abc
import odoo.http
from odoo.service import wsgi_server
from odoo.service.server import server
from odoo.tools import config as odoo_config
from . import const
from .logutils import (
InvalidGitRepository,
SanitizeOdooCookiesProcessor,
fetch_git_sha,
get_extra_context,
)
_logger = logging.getLogger(__name__)
HAS_SENTRY_SDK = True
try:
import sentry_sdk
from sentry_sdk.integrations.logging import ignore_logger
from sentry_sdk.integrations.threading import ThreadingIntegration
from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware
except ImportError: # pragma: no cover
HAS_SENTRY_SDK = False # pragma: no cover
_logger.debug(
"Cannot import 'sentry-sdk'.\
Please make sure it is installed."
) # pragma: no cover
def before_send(event, hint):
"""Add context to event if include_context is True
and sanitize sensitive data"""
if event.setdefault("tags", {})["include_context"]:
cxtest = get_extra_context(odoo.http.request)
info_request = ["tags", "user", "extra", "request"]
for item in info_request:
info_item = event.setdefault(item, {})
info_item.update(cxtest.setdefault(item, {}))
raven_processor = SanitizeOdooCookiesProcessor()
raven_processor.process(event)
return event
def get_odoo_commit(odoo_dir):
"""Attempts to get Odoo git commit from :param:`odoo_dir`."""
if not odoo_dir:
return
try:
return fetch_git_sha(odoo_dir)
except InvalidGitRepository:
_logger.debug("Odoo directory: '%s' not a valid git repository", odoo_dir)
def initialize_sentry(config):
"""Setup an instance of :class:`sentry_sdk.Client`.
:param config: Sentry configuration
:param client: class used to instantiate the sentry_sdk client.
"""
enabled = config.get("sentry_enabled", False)
if not (HAS_SENTRY_SDK and enabled):
return
_logger.info("Initializing sentry...")
if config.get("sentry_odoo_dir") and config.get("sentry_release"):
_logger.debug(
"Both sentry_odoo_dir and \
sentry_release defined, choosing sentry_release"
)
if config.get("sentry_transport"):
warnings.warn(
"`sentry_transport` has been deprecated. "
"Its not neccesary send it, will use `HttpTranport` by default.",
DeprecationWarning,
)
options = {}
for option in const.get_sentry_options():
value = config.get("sentry_%s" % option.key, option.default)
if isinstance(option.converter, abc.Callable):
value = option.converter(value)
options[option.key] = value
exclude_loggers = const.split_multiple(
config.get("sentry_exclude_loggers", const.DEFAULT_EXCLUDE_LOGGERS)
)
if not options.get("release"):
options["release"] = config.get(
"sentry_release", get_odoo_commit(config.get("sentry_odoo_dir"))
)
# Change name `ignore_exceptions` (with raven)
# to `ignore_errors' (sentry_sdk)
options["ignore_errors"] = options["ignore_exceptions"]
del options["ignore_exceptions"]
options["before_send"] = before_send
options["integrations"] = [
options["logging_level"],
ThreadingIntegration(propagate_hub=True),
]
# Remove logging_level, since in sentry_sdk is include in 'integrations'
del options["logging_level"]
client = sentry_sdk.init(**options)
sentry_sdk.set_tag("include_context", config.get("sentry_include_context", True))
if exclude_loggers:
for item in exclude_loggers:
ignore_logger(item)
# The server app is already registered so patch it here
if server:
server.app = SentryWsgiMiddleware(server.app)
# Patch the wsgi server in case of further registration
wsgi_server.application = SentryWsgiMiddleware(wsgi_server.application)
with sentry_sdk.push_scope() as scope:
scope.set_extra("debug", False)
sentry_sdk.capture_message("Starting Odoo Server", "info")
return client
def post_load():
initialize_sentry(odoo_config)
| 32.080882
| 4,363
|
4,376
|
py
|
PYTHON
|
15.0
|
""" Custom class of raven.core.processors taken of https://git.io/JITko
This is a custom class of processor to filter and sanitize
passwords and keys from request data, it does not exist in
sentry-sdk.
"""
from __future__ import absolute_import
import re
from sentry_sdk._compat import text_type
from .generalutils import string_types, varmap
class SanitizeKeysProcessor(object):
"""Class from raven for sanitize keys, cookies, etc
Asterisk out things that correspond to a configurable set of keys."""
MASK = "*" * 8
def process(self, data, **kwargs):
if "exception" in data:
if "values" in data["exception"]:
for value in data["exception"].get("values", []):
if "stacktrace" in value:
self.filter_stacktrace(value["stacktrace"])
if "request" in data:
self.filter_http(data["request"])
if "extra" in data:
data["extra"] = self.filter_extra(data["extra"])
if "level" in data:
data["level"] = self.filter_level(data["level"])
return data
@property
def sanitize_keys(self):
pass
def sanitize(self, item, value):
if value is None:
return
if not item: # key can be a NoneType
return value
# Just in case we have bytes here, we want to make them into text
# properly without failing so we can perform our check.
if isinstance(item, bytes):
item = item.decode("utf-8", "replace")
else:
item = text_type(item)
item = item.lower()
for key in self.sanitize_keys:
if key in item:
# store mask as a fixed length for security
return self.MASK
return value
def filter_stacktrace(self, data):
for frame in data.get("frames", []):
if "vars" not in frame:
continue
frame["vars"] = varmap(self.sanitize, frame["vars"])
def filter_http(self, data):
for n in ("data", "cookies", "headers", "env", "query_string"):
if n not in data:
continue
# data could be provided as bytes and if it's python3
if isinstance(data[n], bytes):
data[n] = data[n].decode("utf-8", "replace")
if isinstance(data[n], string_types()) and "=" in data[n]:
# at this point we've assumed it's a standard HTTP query
# or cookie
if n == "cookies":
delimiter = ";"
else:
delimiter = "&"
data[n] = self._sanitize_keyvals(data[n], delimiter)
else:
data[n] = varmap(self.sanitize, data[n])
if n == "headers" and "Cookie" in data[n]:
data[n]["Cookie"] = self._sanitize_keyvals(data[n]["Cookie"], ";")
def filter_extra(self, data):
return varmap(self.sanitize, data)
def filter_level(self, data):
return re.sub(r"\x1b(\[.*?[@-~]|\].*?(\x07|\x1b\\))", "", data)
def _sanitize_keyvals(self, keyvals, delimiter):
sanitized_keyvals = []
for keyval in keyvals.split(delimiter):
keyval = keyval.split("=")
if len(keyval) == 2:
sanitized_keyvals.append((keyval[0], self.sanitize(*keyval)))
else:
sanitized_keyvals.append(keyval)
return delimiter.join("=".join(keyval) for keyval in sanitized_keyvals)
class SanitizePasswordsProcessor(SanitizeKeysProcessor):
"""Asterisk out things that look like passwords, credit card numbers,
and API keys in frames, http, and basic extra data."""
KEYS = frozenset(
[
"password",
"secret",
"passwd",
"authorization",
"api_key",
"apikey",
"sentry_dsn",
"access_token",
]
)
VALUES_RE = re.compile(r"^(?:\d[ -]*?){13,16}$")
@property
def sanitize_keys(self):
return self.KEYS
def sanitize(self, item, value):
value = super(SanitizePasswordsProcessor, self).sanitize(item, value)
if isinstance(value, string_types()) and self.VALUES_RE.match(value):
return self.MASK
return value
| 31.710145
| 4,376
|
3,755
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Versada <https://versada.eu/>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import os.path
import urllib.parse
from sentry_sdk._compat import text_type
from werkzeug import datastructures
from .generalutils import get_environ
from .processor import SanitizePasswordsProcessor
def get_request_info(request):
"""
Returns context data extracted from :param:`request`.
Heavily based on flask integration for Sentry: https://git.io/vP4i9.
"""
urlparts = urllib.parse.urlsplit(request.url)
return {
"url": "{}://{}{}".format(urlparts.scheme, urlparts.netloc, urlparts.path),
"query_string": urlparts.query,
"method": request.method,
"headers": dict(datastructures.EnvironHeaders(request.environ)),
"env": dict(get_environ(request.environ)),
}
def get_extra_context(request):
"""
Extracts additional context from the current request (if such is set).
"""
try:
session = getattr(request, "session", {})
except RuntimeError:
ctx = {}
else:
ctx = {
"tags": {
"database": session.get("db", None),
},
"user": {
"email": session.get("login", None),
"id": session.get("uid", None),
},
"extra": {
"context": session.get("context", {}),
},
}
if request.httprequest:
ctx.update({"request": get_request_info(request.httprequest)})
return ctx
class SanitizeOdooCookiesProcessor(SanitizePasswordsProcessor):
"""Custom :class:`raven.processors.Processor`.
Allows to sanitize sensitive Odoo cookies, namely the "session_id" cookie.
"""
KEYS = frozenset(
[
"session_id",
]
)
class InvalidGitRepository(Exception):
pass
def fetch_git_sha(path, head=None):
""">>> fetch_git_sha(os.path.dirname(__file__))
Taken from https://git.io/JITmC
"""
if not head:
head_path = os.path.join(path, ".git", "HEAD")
if not os.path.exists(head_path):
raise InvalidGitRepository(
"Cannot identify HEAD for git repository at %s" % (path,)
)
with open(head_path, "r") as fp:
head = text_type(fp.read()).strip()
if head.startswith("ref: "):
head = head[5:]
revision_file = os.path.join(path, ".git", *head.split("/"))
else:
return head
else:
revision_file = os.path.join(path, ".git", "refs", "heads", head)
if not os.path.exists(revision_file):
if not os.path.exists(os.path.join(path, ".git")):
raise InvalidGitRepository(
"%s does not seem to be the root of a git repository" % (path,)
)
# Check for our .git/packed-refs' file since a `git gc` may have run
# https://git-scm.com/book/en/v2/Git-Internals-Maintenance-and-Data-Recovery
packed_file = os.path.join(path, ".git", "packed-refs")
if os.path.exists(packed_file):
with open(packed_file) as fh:
for line in fh:
line = line.rstrip()
if line and line[:1] not in ("#", "^"):
try:
revision, ref = line.split(" ", 1)
except ValueError:
continue
if ref == head:
return text_type(revision)
raise InvalidGitRepository(
'Unable to find ref to head "%s" in repository' % (head,)
)
with open(revision_file) as fh:
return text_type(fh.read()).strip()
| 31.291667
| 3,755
|
750
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Versada <https://versada.eu/>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Sentry",
"summary": "Report Odoo errors to Sentry",
"version": "15.0.3.0.0",
"category": "Extra Tools",
"website": "https://github.com/OCA/server-tools",
"author": "Mohammed Barsi,"
"Versada,"
"Nicolas JEUDY,"
"Odoo Community Association (OCA),"
"Vauxoo",
"maintainers": ["barsi", "naglis", "versada", "moylop260", "fernandahf"],
"license": "AGPL-3",
"application": False,
"installable": True,
"external_dependencies": {
"python": [
"sentry_sdk<=1.9.0",
]
},
"depends": [
"base",
],
"post_load": "post_load",
}
| 27.777778
| 750
|
1,712
|
py
|
PYTHON
|
15.0
|
try:
from collections.abc import Mapping
except ImportError: # pragma: no cover
# Python < 3.3
from collections import Mapping # pragma: no cover
def string_types():
"""Taken from https://git.io/JIv5J"""
return (str,)
def is_namedtuple(value):
"""https://stackoverflow.com/a/2166841/1843746
But modified to handle subclasses of namedtuples.
Taken from https://git.io/JIsfY
"""
if not isinstance(value, tuple):
return False
f = getattr(type(value), "_fields", None)
if not isinstance(f, tuple):
return False
return all(type(n) == str for n in f)
def iteritems(d, **kw):
"""Override iteritems for support multiple versions python.
Taken from https://git.io/JIvMi
"""
return iter(d.items(**kw))
def varmap(func, var, context=None, name=None):
"""Executes ``func(key_name, value)`` on all values
recurisively discovering dict and list scoped
values. Taken from https://git.io/JIvMN
"""
if context is None:
context = {}
objid = id(var)
if objid in context:
return func(name, "<...>")
context[objid] = 1
if isinstance(var, (list, tuple)) and not is_namedtuple(var):
ret = [varmap(func, f, context, name) for f in var]
else:
ret = func(name, var)
if isinstance(ret, Mapping):
ret = {k: varmap(func, v, context, k) for k, v in iteritems(var)}
del context[objid]
return ret
def get_environ(environ):
"""Returns our whitelisted environment variables.
Taken from https://git.io/JIsf2
"""
for key in ("REMOTE_ADDR", "SERVER_NAME", "SERVER_PORT"):
if key in environ:
yield key, environ[key]
| 27.612903
| 1,712
|
4,310
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Versada <https://versada.eu/>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import collections
import logging
from sentry_sdk import HttpTransport
from sentry_sdk.consts import DEFAULT_OPTIONS
from sentry_sdk.integrations.logging import LoggingIntegration
import odoo.loglevels
def split_multiple(string, delimiter=",", strip_chars=None):
"""Splits :param:`string` and strips :param:`strip_chars` from values."""
if not string:
return []
return [v.strip(strip_chars) for v in string.split(delimiter)]
def to_int_if_defined(value):
if value == "" or value is None:
return
return int(value)
def to_float_if_defined(value):
if value == "" or value is None:
return
return float(value)
SentryOption = collections.namedtuple("SentryOption", ["key", "default", "converter"])
# Mapping of Odoo logging level -> Python stdlib logging library log level.
LOG_LEVEL_MAP = {
getattr(odoo.loglevels, "LOG_%s" % x): getattr(logging, x)
for x in ("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET")
}
DEFAULT_LOG_LEVEL = "warn"
ODOO_USER_EXCEPTIONS = [
"odoo.exceptions.AccessDenied",
"odoo.exceptions.AccessError",
"odoo.exceptions.DeferredException",
"odoo.exceptions.MissingError",
"odoo.exceptions.RedirectWarning",
"odoo.exceptions.UserError",
"odoo.exceptions.ValidationError",
"odoo.exceptions.Warning",
"odoo.exceptions.except_orm",
]
DEFAULT_IGNORED_EXCEPTIONS = ",".join(ODOO_USER_EXCEPTIONS)
EXCLUDE_LOGGERS = ("werkzeug",)
DEFAULT_EXCLUDE_LOGGERS = ",".join(EXCLUDE_LOGGERS)
DEFAULT_ENVIRONMENT = "develop"
DEFAULT_TRANSPORT = "threaded"
def select_transport(name=DEFAULT_TRANSPORT):
return {
"threaded": HttpTransport,
}.get(name, HttpTransport)
def get_sentry_logging(level=DEFAULT_LOG_LEVEL):
if level not in LOG_LEVEL_MAP:
level = DEFAULT_LOG_LEVEL
return LoggingIntegration(level=LOG_LEVEL_MAP[level], event_level=logging.WARNING)
def get_sentry_options():
return [
SentryOption("dsn", "", str.strip),
SentryOption("transport", DEFAULT_OPTIONS["transport"], select_transport),
SentryOption("logging_level", DEFAULT_LOG_LEVEL, get_sentry_logging),
SentryOption("with_locals", DEFAULT_OPTIONS["with_locals"], None),
SentryOption(
"max_breadcrumbs", DEFAULT_OPTIONS["max_breadcrumbs"], to_int_if_defined
),
SentryOption("release", DEFAULT_OPTIONS["release"], None),
SentryOption("environment", DEFAULT_OPTIONS["environment"], None),
SentryOption("server_name", DEFAULT_OPTIONS["server_name"], None),
SentryOption("shutdown_timeout", DEFAULT_OPTIONS["shutdown_timeout"], None),
SentryOption("integrations", DEFAULT_OPTIONS["integrations"], None),
SentryOption(
"in_app_include", DEFAULT_OPTIONS["in_app_include"], split_multiple
),
SentryOption(
"in_app_exclude", DEFAULT_OPTIONS["in_app_exclude"], split_multiple
),
SentryOption(
"default_integrations", DEFAULT_OPTIONS["default_integrations"], None
),
SentryOption("dist", DEFAULT_OPTIONS["dist"], None),
SentryOption(
"sample_rate", DEFAULT_OPTIONS["sample_rate"], to_float_if_defined
),
SentryOption("send_default_pii", DEFAULT_OPTIONS["send_default_pii"], None),
SentryOption("http_proxy", DEFAULT_OPTIONS["http_proxy"], None),
SentryOption("https_proxy", DEFAULT_OPTIONS["https_proxy"], None),
SentryOption("ignore_exceptions", DEFAULT_IGNORED_EXCEPTIONS, split_multiple),
SentryOption("request_bodies", DEFAULT_OPTIONS["request_bodies"], None),
SentryOption("attach_stacktrace", DEFAULT_OPTIONS["attach_stacktrace"], None),
SentryOption("ca_certs", DEFAULT_OPTIONS["ca_certs"], None),
SentryOption("propagate_traces", DEFAULT_OPTIONS["propagate_traces"], None),
SentryOption(
"traces_sample_rate",
DEFAULT_OPTIONS["traces_sample_rate"],
to_float_if_defined,
),
SentryOption(
"auto_enabling_integrations",
DEFAULT_OPTIONS["auto_enabling_integrations"],
None,
),
]
| 35.916667
| 4,310
|
1,978
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Versada <https://versada.eu/>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests import TransactionCase
from ..logutils import SanitizeOdooCookiesProcessor
class TestOdooCookieSanitizer(TransactionCase):
def test_cookie_as_string(self):
data = {
"request": {
"cookies": "website_lang=en_us;"
"session_id=hello;"
"Session_ID=hello;"
"foo=bar"
}
}
proc = SanitizeOdooCookiesProcessor()
result = proc.process(data)
self.assertTrue("request" in result)
http = result["request"]
self.assertEqual(
http["cookies"],
"website_lang=en_us;"
"session_id={m};"
"Session_ID={m};"
"foo=bar".format(m=proc.MASK),
)
def test_cookie_as_string_with_partials(self):
data = {"request": {"cookies": "website_lang=en_us;session_id;foo=bar"}}
proc = SanitizeOdooCookiesProcessor()
result = proc.process(data)
self.assertTrue("request" in result)
http = result["request"]
self.assertEqual(
http["cookies"],
"website_lang=en_us;session_id;foo=bar",
)
def test_cookie_header(self):
data = {
"request": {
"headers": {
"Cookie": "foo=bar;"
"session_id=hello;"
"Session_ID=hello;"
"a_session_id_here=hello"
}
}
}
proc = SanitizeOdooCookiesProcessor()
result = proc.process(data)
self.assertTrue("request" in result)
http = result["request"]
self.assertEqual(
http["headers"]["Cookie"],
"foo=bar;"
"session_id={m};"
"Session_ID={m};"
"a_session_id_here={m}".format(m=proc.MASK),
)
| 28.666667
| 1,978
|
5,324
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Versada <https://versada.eu/>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
import sys
from mock import patch
from sentry_sdk.integrations.logging import _IGNORED_LOGGERS
from sentry_sdk.transport import HttpTransport
from odoo import exceptions
from odoo.tests import TransactionCase
from odoo.tools import config
from ..hooks import initialize_sentry
GIT_SHA = "d670460b4b4aece5915caf5c68d12f560a9fe3e4"
RELEASE = "test@1.2.3"
def remove_handler_ignore(handler_name):
"""Removes handlers of handlers ignored list."""
_IGNORED_LOGGERS.discard(handler_name)
class TestException(exceptions.UserError):
pass
class InMemoryTransport(HttpTransport):
"""A :class:`sentry_sdk.Hub.transport` subclass which simply stores events in a list.
Extended based on the one found in raven-python to avoid additional testing
dependencies: https://git.io/vyGO3
"""
def __init__(self, *args, **kwargs):
self.events = []
self.envelopes = []
def capture_event(self, event, *args, **kwargs):
self.events.append(event)
def capture_envelope(self, envelope, *args, **kwargs):
self.envelopes.append(envelope)
def has_event(self, event_level, event_msg):
for event in self.events:
if (
event.get("level") == event_level
and event.get("logentry", {}).get("message") == event_msg
):
return True
return False
def flush(self, *args, **kwargs):
pass
def kill(self, *args, **kwargs):
pass
class TestClientSetup(TransactionCase):
def setUp(self):
super(TestClientSetup, self).setUp()
self.dsn = "http://public:secret@example.com/1"
config.options["sentry_enabled"] = True
config.options["sentry_dsn"] = self.dsn
self.client = initialize_sentry(config)._client
self.client.transport = InMemoryTransport({"dsn": self.dsn})
self.handler = self.client.integrations["logging"]._handler
def log(self, level, msg, exc_info=None):
record = logging.LogRecord(__name__, level, __file__, 42, msg, (), exc_info)
self.handler.emit(record)
def assertEventCaptured(self, client, event_level, event_msg):
self.assertTrue(
client.transport.has_event(event_level, event_msg),
msg='Event: "%s" was not captured' % event_msg,
)
def assertEventNotCaptured(self, client, event_level, event_msg):
self.assertFalse(
client.transport.has_event(event_level, event_msg),
msg='Event: "%s" was captured' % event_msg,
)
def test_initialize_raven_sets_dsn(self):
self.assertEqual(self.client.dsn, self.dsn)
def test_capture_event(self):
level, msg = logging.WARNING, "Test event, can be ignored"
self.log(level, msg)
level = "warning"
self.assertEventCaptured(self.client, level, msg)
def test_capture_event_exc(self):
level, msg = logging.WARNING, "Test event, can be ignored exception"
try:
raise TestException(msg)
except TestException:
exc_info = sys.exc_info()
self.log(level, msg, exc_info)
level = "warning"
self.assertEventCaptured(self.client, level, msg)
def test_ignore_exceptions(self):
config.options["sentry_ignore_exceptions"] = "odoo.exceptions.UserError"
client = initialize_sentry(config)._client
client.transport = InMemoryTransport({"dsn": self.dsn})
level, msg = logging.WARNING, "Test exception"
try:
raise exceptions.UserError(msg)
except exceptions.UserError:
exc_info = sys.exc_info()
self.log(level, msg, exc_info)
level = "warning"
self.assertEventNotCaptured(client, level, msg)
def test_exclude_logger(self):
config.options["sentry_enabled"] = True
config.options["sentry_exclude_loggers"] = __name__
client = initialize_sentry(config)._client
client.transport = InMemoryTransport({"dsn": self.dsn})
level, msg = logging.WARNING, "Test exclude logger %s" % __name__
self.log(level, msg)
level = "warning"
# Revert ignored logger so it doesn't affect other tests
remove_handler_ignore(__name__)
self.assertEventNotCaptured(client, level, msg)
@patch("odoo.addons.sentry.hooks.get_odoo_commit", return_value=GIT_SHA)
def test_config_odoo_dir(self, get_odoo_commit):
config.options["sentry_odoo_dir"] = "/opt/odoo/core"
client = initialize_sentry(config)._client
self.assertEqual(
client.options["release"],
GIT_SHA,
"Failed to use 'sentry_odoo_dir' parameter appropriately",
)
@patch("odoo.addons.sentry.hooks.get_odoo_commit", return_value=GIT_SHA)
def test_config_release(self, get_odoo_commit):
config.options["sentry_odoo_dir"] = "/opt/odoo/core"
config.options["sentry_release"] = RELEASE
client = initialize_sentry(config)._client
self.assertEqual(
client.options["release"],
RELEASE,
"Failed to use 'sentry_release' parameter appropriately",
)
| 34.571429
| 5,324
|
532
|
py
|
PYTHON
|
15.0
|
# Copyright 2022 ForgeFlow S.L. (www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Fetchmail Incoming Log Test",
"version": "15.0.1.0.0",
"category": "Tools",
"summary": "Tests for 'fetchmail_incoming_log' module.",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/server-tools",
"depends": ["fetchmail_incoming_log", "test_mail"],
"installable": True,
"auto_install": True,
}
| 35.466667
| 532
|
1,221
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-20 ForgeFlow S.L. (www.forgeflow.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo.tests.common import tagged
from odoo.addons.test_mail.data.test_mail_data import MAIL_TEMPLATE
from odoo.addons.test_mail.tests.test_mail_gateway import TestMailgateway
@tagged("mail_gateway")
class TestFetchmailIncomingLog(TestMailgateway):
@classmethod
def setUpClass(cls):
super(TestFetchmailIncomingLog, cls).setUpClass()
cls.fetchmail_server = cls.env["fetchmail.server"].create(
{"name": "Test Fetchmail Server", "server_type": "imap"}
)
def test_message_process(self):
email_from = "test1@example.com"
to_email = "test2@example.com"
msg_id = "Test log message to process"
with self.assertRaises(ValueError):
mail = MAIL_TEMPLATE.format(
to=to_email,
email_from=email_from,
cc="",
subject="testing",
extra="",
msg_id=msg_id,
)
self.env["mail.thread"].with_context(
fetchmail_server_id=self.fetchmail_server.id
).message_process(None, mail)
| 34.885714
| 1,221
|
661
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-21 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
{
"name": "Base Cron Exclusion",
"summary": "Allow you to select scheduled actions that should not run "
"simultaneously.",
"version": "15.0.1.0.0",
"author": "ForgeFlow, Odoo Community Association (OCA)",
"maintainers": ["LoisRForgeFlow", "ChrisOForgeFlow"],
"development_status": "Production/Stable",
"website": "https://github.com/OCA/server-tools",
"category": "Tools",
"depends": ["base"],
"data": ["views/ir_cron_view.xml"],
"license": "LGPL-3",
"installable": True,
}
| 36.722222
| 661
|
2,391
|
py
|
PYTHON
|
15.0
|
# Copyright 2017-21 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
import logging
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
_logger = logging.getLogger(__name__)
class IrCron(models.Model):
_inherit = "ir.cron"
@api.constrains("mutually_exclusive_cron_ids")
def _check_auto_exclusion(self):
for item in self:
if item in item.mutually_exclusive_cron_ids:
raise ValidationError(
_(
"You can not mutually exclude a scheduled actions with "
"itself."
)
)
mutually_exclusive_cron_ids = fields.Many2many(
comodel_name="ir.cron",
relation="ir_cron_exclusion",
column1="ir_cron1_id",
column2="ir_cron2_id",
string="Mutually Exclusive Scheduled Actions",
)
@staticmethod
def _lock_mutually_exclusive_cron(db, job_id):
lock_cr = db.cursor()
lock_cr.execute(
"""
WITH Q1 AS (SELECT ir_cron2_id as cron_id FROM ir_cron_exclusion
WHERE ir_cron1_id=%s
UNION ALL
SELECT ir_cron1_id as cron_id FROM ir_cron_exclusion
WHERE ir_cron2_id=%s)
SELECT * FROM Q1
GROUP BY cron_id;""",
(job_id, job_id),
)
locked_ids = tuple(row[0] for row in lock_cr.fetchall())
if locked_ids:
lock_cr.execute(
"""SELECT *
FROM ir_cron
WHERE numbercall != 0
AND active
AND id IN %s
FOR UPDATE NOWAIT""",
(locked_ids,),
log_exceptions=False,
)
lock_cr.fetchall()
return lock_cr
@classmethod
def _process_job(cls, db, cron_cr, job):
locked_crons = cls._lock_mutually_exclusive_cron(db, job["id"])
try:
res = super(IrCron, cls)._process_job(db, cron_cr, job)
finally:
locked_crons.close()
_logger.debug("released blocks for cron job %s" % job["cron_name"])
return res
| 33.676056
| 2,391
|
604
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2016 Tecnativa - Vicent Cubells
# Copyright 2016 Tecnativa - Cristina Martin R.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Image URLs from HTML field",
"summary": "Extract images found in any HTML field",
"version": "15.0.1.0.1",
"category": "Tools",
"website": "https://github.com/OCA/server-tools",
"author": "Tecnativa, Onestein, Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["base"],
}
| 37.75
| 604
|
2,257
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Tecnativa - Jairo Llopis
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests.common import TransactionCase
from odoo.tools import mute_logger
class ExtractorCase(TransactionCase):
def setUp(self):
super().setUp()
# Shortcut
self.imgs_from_html = self.env["ir.fields.converter"].imgs_from_html
def test_mixed_images_found(self):
"""Images correctly found in <img> elements and backgrounds."""
content = """
<div>
<!-- src-less img -->
<img/>
<p/>
<img src="/path/0"/>
<img src="/path/1"/>
<img src="/path/2"/>
<img src="/path/3"/>
<section style="background : URL('/path/4');;background;ö;">
<div style='BACKGROUND-IMAGE:url(/path/5)'>
<p style="background:uRl("/path/6")">
<img src="/path/7"/>
</p>
</div>
</section>
</div>
"""
# Read all images
for n, url in enumerate(self.imgs_from_html(content)):
self.assertEqual("/path/%d" % n, url)
self.assertEqual(n, 7)
# Read only first image
for n, url in enumerate(self.imgs_from_html(content, 1)):
self.assertEqual("/path/%d" % n, url)
self.assertEqual(n, 0)
@mute_logger("odoo.addons.html_image_url_extractor" + ".models.ir_fields_converter")
def test_empty_html(self):
"""Empty HTML handled correctly."""
self.assertTrue(enumerate(self.imgs_from_html("")))
with self.assertRaisesRegex(Exception, "Document is empty"):
list(self.imgs_from_html("", fail=True))
@mute_logger("odoo.addons.html_image_url_extractor" + ".models.ir_fields_converter")
def test_false_html(self):
"""``False`` HTML handled correctly."""
self.assertTrue(enumerate(self.imgs_from_html(False)))
with self.assertRaisesRegex(Exception, "expected string or bytes-like object"):
list(self.imgs_from_html(False, fail=True))
| 40.25
| 2,254
|
2,468
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Tecnativa - Jairo Llopis
# Copyright 2016 Tecnativa - Vicent Cubells
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
import re
from lxml import etree, html
from odoo import api, models
_logger = logging.getLogger(__name__)
class IrFieldsConverter(models.AbstractModel):
_inherit = "ir.fields.converter"
@api.model
def imgs_from_html(self, html_content, limit=None, fail=False):
"""Extract all images in order from an HTML field in a generator.
:param str html_content:
HTML contents from where to extract the images.
:param int limit:
Only get up to this number of images.
:param bool fail:
If ``True``, exceptions will be raised.
"""
# Parse HTML
try:
doc = html.fromstring(html_content)
except (TypeError, etree.XMLSyntaxError, etree.ParserError):
if fail:
raise
else:
_logger.exception("Failure parsing this HTML:\n%s", html_content)
return
# Required tools
query = """
//img[@src] |
//*[contains(translate(@style, "BACKGROUND", "background"),
'background')]
[contains(translate(@style, "URL", "url"), 'url(')]
"""
rgx = r"""
url\(\s* # Start function
(?P<url>[^)]*) # URL string
\s*\) # End function
"""
rgx = re.compile(rgx, re.IGNORECASE | re.VERBOSE)
# Loop through possible image URLs
for lap, element in enumerate(doc.xpath(query)):
if limit and lap >= limit:
break
if element.tag == "img":
yield element.attrib["src"]
else:
for rule in element.attrib["style"].split(";"):
# Extract background image
parts = rule.split(":", 1)
try:
if parts[0].strip().lower() in {
"background",
"background-image",
}:
yield (rgx.search(parts[1]).group("url").strip("\"'"))
# Malformed CSS or no match for URL
except (IndexError, AttributeError):
_logger.info("Malformed CSS or no match for URL")
| 36.294118
| 2,468
|
1,047
|
py
|
PYTHON
|
15.0
|
# Copyright 2011 Raphaël Valyi, Renato Lima, Guewen Baconnier, Sodexis
# Copyright 2017 Akretion (http://www.akretion.com)
# Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>
# Copyright 2020 Hibou Corp.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
{
"name": "Exception Rule",
"version": "15.0.1.0.2",
"development_status": "Mature",
"category": "Generic Modules",
"summary": """
This module provide an abstract model to manage customizable
exceptions to be applied on different models (sale order, invoice, ...)""",
"author": "Akretion, Sodexis, Camptocamp, Odoo Community Association (OCA)",
"website": "https://github.com/OCA/server-tools",
"depends": ["base_setup"],
"maintainers": ["hparfr", "sebastienbeau"],
"license": "AGPL-3",
"data": [
"security/base_exception_security.xml",
"security/ir.model.access.csv",
"wizard/base_exception_confirm_view.xml",
"views/base_exception_view.xml",
],
"installable": True,
}
| 40.230769
| 1,046
|
5,654
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Akretion Mourad EL HADJ MIMOUNE
# Copyright 2020 Hibou Corp.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo_test_helper import FakeModelLoader
from odoo.exceptions import UserError, ValidationError
from odoo.tests import TransactionCase
class TestBaseException(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.loader = FakeModelLoader(cls.env, cls.__module__)
cls.loader.backup_registry()
from .purchase_test import ExceptionRule, LineTest, PurchaseTest, WizardTest
cls.loader.update_registry((ExceptionRule, LineTest, PurchaseTest, WizardTest))
cls.partner = cls.env["res.partner"].create({"name": "Foo"})
cls.po = cls.env["base.exception.test.purchase"].create(
{
"name": "Test base exception to basic purchase",
"partner_id": cls.partner.id,
"line_ids": [
(0, 0, {"name": "line test", "amount": 120.0, "qty": 1.5})
],
}
)
cls.exception_rule = cls.env["exception.rule"].create(
{
"name": "No ZIP code on destination",
"sequence": 10,
"model": "base.exception.test.purchase",
"code": "if not self.partner_id.zip: failed=True",
"exception_type": "by_py_code",
}
)
exception_rule_confirm_obj = cls.env["exception.rule.confirm.test.purchase"]
cls.exception_rule_confirm = exception_rule_confirm_obj.with_context(
active_model="base.exception.test.purchase", active_ids=cls.po.ids
).create(
{
"related_model_id": cls.po.id,
"ignore": False,
}
)
@classmethod
def tearDownClass(cls):
cls.loader.restore_registry()
return super().tearDownClass()
def test_valid(self):
self.partner.write({"zip": "00000"})
self.exception_rule.active = False
self.po.button_confirm()
self.assertFalse(self.po.exception_ids)
def test_exception_rule_confirm(self):
self.exception_rule_confirm.action_confirm()
self.assertFalse(self.exception_rule_confirm.exception_ids)
def test_fail_by_py(self):
with self.assertRaises(ValidationError):
self.po.button_confirm()
self.po.with_context(raise_exception=False).button_confirm()
self.assertTrue(self.po.exception_ids)
def test_fail_by_domain(self):
self.exception_rule.write(
{
"domain": "[('partner_id.zip', '=', False)]",
"exception_type": "by_domain",
}
)
with self.assertRaises(ValidationError):
self.po.button_confirm()
self.po.with_context(raise_exception=False).button_confirm()
self.assertTrue(self.po.exception_ids)
def test_fail_by_method(self):
self.exception_rule.write(
{
"method": "exception_method_no_zip",
"exception_type": "by_method",
}
)
with self.assertRaises(ValidationError):
self.po.button_confirm()
self.po.with_context(raise_exception=False).button_confirm()
self.assertTrue(self.po.exception_ids)
def test_ignorable_exception(self):
# Block because of exception during validation
with self.assertRaises(ValidationError):
self.po.button_confirm()
self.po.with_context(raise_exception=False).button_confirm()
# Test that we have linked exceptions
self.assertTrue(self.po.exception_ids)
# Test ignore exeception make possible for the po to validate
self.po.action_ignore_exceptions()
self.assertTrue(self.po.ignore_exception)
self.assertFalse(self.po.exceptions_summary)
self.po.button_confirm()
self.assertEqual(self.po.state, "purchase")
def test_purchase_check_exception(self):
self.po.test_purchase_check_exception()
def test_purchase_check_button_approve(self):
self.po.button_approve()
self.assertEqual(self.po.state, "to approve")
def test_purchase_check_button_draft(self):
self.po.button_draft()
self.assertEqual(self.po.state, "draft")
def test_purchase_check_button_confirm(self):
self.partner.write({"zip": "00000"})
self.po.button_confirm()
self.assertEqual(self.po.state, "purchase")
def test_purchase_check_button_cancel(self):
self.po.button_cancel()
self.assertEqual(self.po.state, "cancel")
def test_detect_exceptions(self):
self.po.detect_exceptions()
def test_blocking_exception(self):
self.exception_rule.is_blocking = True
# Block because of exception during validation
with self.assertRaises(ValidationError):
self.po.button_confirm()
# Test that we have linked exceptions
self.po.with_context(raise_exception=False).button_confirm()
self.assertTrue(self.po.exception_ids)
self.assertTrue(self.po.exceptions_summary)
# Test cannot ignore blocked exception
with self.assertRaises(UserError):
self.po.action_ignore_exceptions()
self.assertFalse(self.po.ignore_exception)
with self.assertRaises(ValidationError):
self.po.button_confirm()
self.po.with_context(raise_exception=False).button_confirm()
self.assertTrue(self.po.exception_ids)
self.assertTrue(self.po.exceptions_summary)
| 37.693333
| 5,654
|
3,305
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 Akretion Mourad EL HADJ MIMOUNE
# Copyright 2020 Hibou Corp.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class ExceptionRule(models.Model):
_inherit = "exception.rule"
_name = "exception.rule"
method = fields.Selection(
selection_add=[("exception_method_no_zip", "Purchase exception no zip")]
)
model = fields.Selection(
selection_add=[("base.exception.test.purchase", "Purchase Test")],
ondelete={"base.exception.test.purchase": "cascade"},
)
test_purchase_ids = fields.Many2many("base.exception.test.purchase")
class PurchaseTest(models.Model):
_inherit = "base.exception"
_name = "base.exception.test.purchase"
_description = "Base Exception Test Model"
name = fields.Char(required=True)
user_id = fields.Many2one("res.users", string="Responsible")
state = fields.Selection(
[
("draft", "New"),
("cancel", "Cancelled"),
("purchase", "Purchase"),
("to approve", "To approve"),
("done", "Done"),
],
string="Status",
readonly=True,
default="draft",
)
active = fields.Boolean(default=True)
partner_id = fields.Many2one("res.partner", string="Partner")
line_ids = fields.One2many("base.exception.test.purchase.line", "lead_id")
amount_total = fields.Float(compute="_compute_amount_total", store=True)
@api.depends("line_ids")
def _compute_amount_total(self):
for record in self:
for line in record.line_ids:
record.amount_total += line.amount * line.qty
@api.constrains("ignore_exception", "line_ids", "state")
def test_purchase_check_exception(self):
orders = self.filtered(lambda s: s.state == "purchase")
if orders:
orders._check_exception()
def button_approve(self, force=False):
self.write({"state": "to approve"})
return {}
def button_draft(self):
self.write({"state": "draft"})
return {}
def button_confirm(self):
self.write({"state": "purchase"})
return True
def button_cancel(self):
self.write({"state": "cancel"})
def _reverse_field(self):
return "test_purchase_ids"
def exception_method_no_zip(self):
records_fail = self.env["base.exception.test.purchase"]
for rec in self:
if not rec.partner_id.zip:
records_fail += rec
return records_fail
class LineTest(models.Model):
_name = "base.exception.test.purchase.line"
_description = "Base Exception Test Model Line"
name = fields.Char()
lead_id = fields.Many2one("base.exception.test.purchase", ondelete="cascade")
qty = fields.Float()
amount = fields.Float()
class WizardTest(models.TransientModel):
_name = "exception.rule.confirm.test.purchase"
_inherit = "exception.rule.confirm"
_description = "Base Exception Test Model Confirm"
related_model_id = fields.Many2one("base.exception.test.purchase", "Purchase")
def action_confirm(self):
self.ensure_one()
if self.ignore:
self.related_model_id.ignore_exception = True
return super().action_confirm()
| 31.778846
| 3,305
|
1,523
|
py
|
PYTHON
|
15.0
|
# Copyright 2011 Raphaël Valyi, Renato Lima, Guewen Baconnier, Sodexis
# Copyright 2017 Akretion (http://www.akretion.com)
# Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>
# Copyright 2020 Hibou Corp.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class ExceptionRuleConfirm(models.AbstractModel):
_name = "exception.rule.confirm"
_description = "Exception Rule Confirm Wizard"
related_model_id = fields.Many2one("base.exception")
exception_ids = fields.Many2many(
"exception.rule", string="Exceptions to resolve", readonly=True
)
ignore = fields.Boolean("Ignore Exceptions")
@api.model
def default_get(self, field_list):
res = super().default_get(field_list)
current_model = self.env.context.get("active_model")
model_except_obj = self.env[current_model]
active_ids = self.env.context.get("active_ids")
if len(active_ids) > 1:
raise ValidationError(_("Only 1 ID accepted, got %r.") % active_ids)
active_id = active_ids[0]
related_model_except = model_except_obj.browse(active_id)
exception_ids = related_model_except.exception_ids.ids
res.update({"exception_ids": [(6, 0, exception_ids)]})
res.update({"related_model_id": active_id})
return res
def action_confirm(self):
self.ensure_one()
return {"type": "ir.actions.act_window_close"}
| 41.135135
| 1,522
|
11,980
|
py
|
PYTHON
|
15.0
|
# Copyright 2011 Raphaël Valyi, Renato Lima, Guewen Baconnier, Sodexis
# Copyright 2017 Akretion (http://www.akretion.com)
# Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>
# Copyright 2020 Hibou Corp.
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
import html
import logging
from odoo import _, api, fields, models
from odoo.exceptions import UserError, ValidationError
from odoo.osv import expression
from odoo.tools.safe_eval import safe_eval
_logger = logging.getLogger(__name__)
class ExceptionRule(models.Model):
_name = "exception.rule"
_description = "Exception Rule"
_order = "active desc, sequence asc"
name = fields.Char("Exception Name", required=True, translate=True)
description = fields.Text(translate=True)
sequence = fields.Integer(help="Gives the sequence order when applying the test")
model = fields.Selection(selection=[], string="Apply on", required=True)
exception_type = fields.Selection(
selection=[
("by_domain", "By domain"),
("by_py_code", "By python code"),
("by_method", "By method"),
],
required=True,
default="by_py_code",
help="By python code: allow to define any arbitrary check\n"
"By domain: limited to a selection by an odoo domain:\n"
" performance can be better when exceptions"
" are evaluated with several records\n"
"By method: allow to select an existing check method",
)
domain = fields.Char()
method = fields.Selection(selection=[], readonly=True)
active = fields.Boolean(default=True)
code = fields.Text(
"Python Code",
help="Python code executed to check if the exception apply or "
"not. Use failed = True to block the exception",
)
is_blocking = fields.Boolean(
help="When checked the exception can not be ignored",
)
@api.constrains("exception_type", "domain", "code", "model")
def check_exception_type_consistency(self):
for rule in self:
if (
(rule.exception_type == "by_py_code" and not rule.code)
or (rule.exception_type == "by_domain" and not rule.domain)
or (rule.exception_type == "by_method" and not rule.method)
):
raise ValidationError(
_(
"There is a problem of configuration, python code, "
"domain or method is missing to match the exception "
"type."
)
)
def _get_domain(self):
"""override me to customize domains according exceptions cases"""
self.ensure_one()
return safe_eval(self.domain)
class BaseExceptionMethod(models.AbstractModel):
_name = "base.exception.method"
_description = "Exception Rule Methods"
def _get_main_records(self):
"""
Used in case we check exceptions on a record but write these
exceptions on a parent record. Typical example is with
sale.order.line. We check exceptions on some sale order lines but
write these exceptions on the sale order, so they are visible.
"""
return self
def _reverse_field(self):
raise NotImplementedError()
def _rule_domain(self):
"""Filter exception.rules.
By default, only the rules with the correct model
will be used.
"""
return [("model", "=", self._name), ("active", "=", True)]
def detect_exceptions(self):
"""List all exception_ids applied on self
Exception ids are also written on records
"""
rules = self.env["exception.rule"].sudo().search(self._rule_domain())
all_exception_ids = []
rules_to_remove = {}
rules_to_add = {}
for rule in rules:
records_with_exception = self._detect_exceptions(rule)
reverse_field = self._reverse_field()
main_records = self._get_main_records()
commons = main_records & rule[reverse_field]
to_remove = commons - records_with_exception
to_add = records_with_exception - commons
# we expect to always work on the same model type
if rule.id not in rules_to_remove:
rules_to_remove[rule.id] = main_records.browse()
rules_to_remove[rule.id] |= to_remove
if rule.id not in rules_to_add:
rules_to_add[rule.id] = main_records.browse()
rules_to_add[rule.id] |= to_add
if records_with_exception:
all_exception_ids.append(rule.id)
# Cumulate all the records to attach to the rule
# before linking. We don't want to call "rule.write()"
# which would:
# * write on write_date so lock the exception.rule
# * trigger the recomputation of "main_exception_id" on
# all the sale orders related to the rule, locking them all
# and preventing concurrent writes
# Reversing the write by writing on SaleOrder instead of
# ExceptionRule fixes the 2 kinds of unexpected locks.
# It should not result in more queries than writing on ExceptionRule:
# the "to remove" part generates one DELETE per rule on the relation
# table
# and the "to add" part generates one INSERT (with unnest) per rule.
for rule_id, records in rules_to_remove.items():
records.write({"exception_ids": [(3, rule_id)]})
for rule_id, records in rules_to_add.items():
records.write({"exception_ids": [(4, rule_id)]})
return all_exception_ids
@api.model
def _exception_rule_eval_context(self, rec):
return {
"self": rec,
"object": rec,
"obj": rec,
}
@api.model
def _rule_eval(self, rule, rec):
expr = rule.code
space = self._exception_rule_eval_context(rec)
try:
safe_eval(
expr, space, mode="exec", nocopy=True
) # nocopy allows to return 'result'
except Exception as e:
_logger.exception(e)
raise UserError(
_(
"Error when evaluating the exception.rule"
" rule:\n %(rule_name)s \n(%(error)s)"
)
% {"rule_name": rule.name, "error": e}
) from e
return space.get("failed", False)
def _detect_exceptions(self, rule):
if rule.exception_type == "by_py_code":
return self._detect_exceptions_by_py_code(rule)
elif rule.exception_type == "by_domain":
return self._detect_exceptions_by_domain(rule)
elif rule.exception_type == "by_method":
return self._detect_exceptions_by_method(rule)
def _get_base_domain(self):
return [("ignore_exception", "=", False), ("id", "in", self.ids)]
def _detect_exceptions_by_py_code(self, rule):
"""
Find exceptions found on self.
"""
domain = self._get_base_domain()
records = self.search(domain)
records_with_exception = self.env[self._name]
for record in records:
if self._rule_eval(rule, record):
records_with_exception |= record
return records_with_exception
def _detect_exceptions_by_domain(self, rule):
"""
Find exceptions found on self.
"""
base_domain = self._get_base_domain()
rule_domain = rule._get_domain()
domain = expression.AND([base_domain, rule_domain])
return self.search(domain)
def _detect_exceptions_by_method(self, rule):
"""
Find exceptions found on self.
"""
base_domain = self._get_base_domain()
records = self.search(base_domain)
return getattr(records, rule.method)()
class BaseExceptionModel(models.AbstractModel):
_inherit = "base.exception.method"
_name = "base.exception"
_order = "main_exception_id asc"
_description = "Exception"
main_exception_id = fields.Many2one(
"exception.rule",
compute="_compute_main_error",
string="Main Exception",
store=True,
)
exceptions_summary = fields.Html(compute="_compute_exceptions_summary")
exception_ids = fields.Many2many("exception.rule", string="Exceptions", copy=False)
ignore_exception = fields.Boolean("Ignore Exceptions", copy=False)
def action_ignore_exceptions(self):
if any(self.exception_ids.mapped("is_blocking")):
raise UserError(
_(
"The exceptions can not be ignored, because "
"some of them are blocking."
)
)
self.write({"ignore_exception": True})
return True
@api.depends("exception_ids", "ignore_exception")
def _compute_main_error(self):
for rec in self:
if not rec.ignore_exception and rec.exception_ids:
rec.main_exception_id = rec.exception_ids[0]
else:
rec.main_exception_id = False
@api.depends("exception_ids", "ignore_exception")
def _compute_exceptions_summary(self):
for rec in self:
if rec.exception_ids and not rec.ignore_exception:
rec.exceptions_summary = "<ul>%s</ul>" % "".join(
[
"<li>%s: <i>%s</i> <b>%s<b></li>"
% tuple(
map(
html.escape,
(
e.name,
e.description or "",
_("(Blocking exception)") if e.is_blocking else "",
),
)
)
for e in rec.exception_ids
]
)
else:
rec.exceptions_summary = False
def _popup_exceptions(self):
"""This method is used to show the popup action view.
Used in several dependent modules."""
record = self._get_popup_action()
action = record.sudo().read()[0]
action = {
field: value
for field, value in action.items()
if field in record._get_readable_fields()
}
action.update(
{
"context": {
"active_id": self.ids[0],
"active_ids": self.ids,
"active_model": self._name,
}
}
)
return action
@api.model
def _get_popup_action(self):
return self.env.ref("base_exception.action_exception_rule_confirm")
def _check_exception(self):
"""Check exceptions
This method must be used in a constraint that must be created in the
object that inherits for base.exception.
.. code-block:: python
@api.constrains("ignore_exception")
def sale_check_exception(self):
# ...
self._check_exception()
For convenience, this check can be skipped by setting check_exception=False
in context.
Exceptions will be raised as ValidationError, but this can be disabled
by setting raise_exception=False in context. They will still be detected
and updated on the related record, though.
"""
if not self.env.context.get("check_exception", True): # pragma: no cover
return True
exception_ids = self.detect_exceptions()
if exception_ids and self.env.context.get("raise_exception", True):
exceptions = self.env["exception.rule"].browse(exception_ids)
raise ValidationError("\n".join(exceptions.mapped("name")))
| 37.669811
| 11,979
|
607
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2016 Tecnativa - Vicent Cubells
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Text from HTML field",
"summary": "Generate excerpts from any HTML field",
"version": "15.0.1.0.1",
"category": "Tools",
"website": "https://github.com/OCA/server-tools",
"author": "Grupo ESOC Ingeniería de Servicios, "
"Tecnativa, "
"Onestein, "
"Odoo Community Association (OCA)",
"license": "AGPL-3",
"application": False,
"installable": True,
"depends": ["base"],
}
| 33.666667
| 606
|
1,970
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Jairo Llopis <jairo.llopis@tecnativa.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from lxml import etree
from odoo.tests.common import TransactionCase
from odoo.tools import mute_logger
class ExtractorCase(TransactionCase):
def setUp(self):
super().setUp()
# Shortcut
self.text_from_html = self.env["ir.fields.converter"].text_from_html
def test_excerpts(self):
"""Text gets correctly extracted."""
html = """
<html>
<body>
<div class="this should not appear">
<h1>I'm a title</h1>
<p>I'm a paragraph</p>
<small>¡Pues yo soy español!</small>
</div>
</body>
</html>
"""
self.assertEqual(
self.text_from_html(html),
"I'm a title I'm a paragraph ¡Pues yo soy español!",
)
self.assertEqual(
self.text_from_html(html, 8), "I'm a title I'm a paragraph ¡Pues yo…"
)
self.assertEqual(
self.text_from_html(html, 8, 31), "I'm a title I'm a paragraph ¡P…"
)
self.assertEqual(
self.text_from_html(html, 7, ellipsis=""),
"I'm a title I'm a paragraph ¡Pues",
)
@mute_logger("odoo.addons.html_text.models.ir_fields_converter")
def test_empty_html(self):
"""Empty HTML handled correctly."""
self.assertEqual(self.text_from_html(""), "")
with self.assertRaises(etree.ParserError):
self.text_from_html("", fail=True)
@mute_logger("odoo.addons.html_text.models.ir_fields_converter")
def test_false_html(self):
"""``False`` HTML handled correctly."""
self.assertEqual(self.text_from_html(False), "")
with self.assertRaises(TypeError):
self.text_from_html(False, fail=True)
| 34.982143
| 1,959
|
2,307
|
py
|
PYTHON
|
15.0
|
# Copyright 2016-2017 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2016 Tecnativa - Vicent Cubells
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from lxml import etree, html
from odoo import api, models
_logger = logging.getLogger(__name__)
class IrFieldsConverter(models.AbstractModel):
_inherit = "ir.fields.converter"
@api.model
def text_from_html(
self, html_content, max_words=None, max_chars=None, ellipsis="…", fail=False
):
"""Extract text from an HTML field in a generator.
:param str html_content:
HTML contents from where to extract the text.
:param int max_words:
Maximum amount of words allowed in the resulting string.
:param int max_chars:
Maximum amount of characters allowed in the resulting string. If
you apply this limit, beware that the last word could get cut in an
unexpected place.
:param str ellipsis:
Character(s) to be appended to the end of the resulting string if
it gets truncated after applying limits set in :param:`max_words`
or :param:`max_chars`. If you want nothing applied, just set an
empty string.
:param bool fail:
If ``True``, exceptions will be raised. Otherwise, an empty string
will be returned on failure.
"""
# Parse HTML
try:
doc = html.fromstring(html_content)
except (TypeError, etree.XMLSyntaxError, etree.ParserError):
if fail:
raise
else:
_logger.exception("Failure parsing this HTML:\n%s", html_content)
return ""
# Get words
words = "".join(doc.xpath("//text()")).split()
# Truncate words
suffix = max_words and len(words) > max_words
if max_words:
words = words[:max_words]
# Get text
text = " ".join(words)
# Truncate text
suffix = suffix or max_chars and len(text) > max_chars
if max_chars:
text = text[: max_chars - (len(ellipsis) if suffix else 0)].strip()
# Append ellipsis if needed
if suffix:
text += ellipsis
return text
| 31.148649
| 2,305
|
462
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Quartile Limited
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
{
"name": "Update Restrict Model",
"version": "15.0.1.0.0",
"depends": ["base"],
"website": "https://github.com/OCA/server-tools",
"author": "Odoo Community Association (OCA), Quartile Limited",
"category": "Others",
"license": "LGPL-3",
"data": ["views/ir_model_views.xml", "views/res_users_views.xml"],
"installable": True,
}
| 35.538462
| 462
|
2,363
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Quartile Limited
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo.exceptions import AccessError
from odoo.tests import SavepointCase, tagged
@tagged("post_install", "-at_install")
class TestBaseModelRestrictUpdate(SavepointCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.partner_model = cls.env["ir.model"].search([("model", "=", "res.partner")])[
0
]
cls.partner_model.restrict_update = True
cls.test_partner = cls.env["res.partner"].create({"name": "Test Partner"})
cls.restrict_test_user = cls.env["res.users"].create(
{
"name": "Resticted user",
"login": "resticted@example.com",
"unrestrict_model_update": False,
}
)
cls.permit_test_user = cls.env["res.users"].create(
{
"name": "Permit user",
"login": "permit@example.com",
"email": "permit@example.com",
"unrestrict_model_update": True,
}
)
def test_01_create_partner(self):
with self.assertRaises(AccessError):
self.env["res.partner"].with_user(self.restrict_test_user.id).create(
{"name": "Test Partner"}
)
self.env["res.partner"].with_user(self.permit_test_user.id).create(
{"name": "Test Partner"}
)
def test_02_update_partner(self):
with self.assertRaises(AccessError):
self.test_partner.with_user(self.restrict_test_user.id).update(
{"name": "Test Partner 2"}
)
self.test_partner.with_user(self.permit_test_user.id).update(
{"name": "Test Partner 2"}
)
def test_03_unlink_partner(self):
test_partner = self.test_partner.sudo().copy()
with self.assertRaises(AccessError):
test_partner.with_user(self.restrict_test_user.id).unlink()
test_partner.with_user(self.permit_test_user.id).unlink()
def test_04_readonly_user_update_partner(self):
self.permit_test_user.write({"is_readonly_user": True})
with self.assertRaises(AccessError):
self.test_partner.with_user(self.permit_test_user.id).update(
{"name": "Test Partner 2"}
)
| 37.507937
| 2,363
|
389
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Quartile Limited
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import fields, models
class IrModel(models.Model):
_inherit = "ir.model"
restrict_update = fields.Boolean(
"Update Restrict Model",
help="When selected, the model is restricted to read-only unless the "
"user has the special permission.",
)
| 27.785714
| 389
|
757
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Quartile Limited
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class ResUsers(models.Model):
_inherit = "res.users"
unrestrict_model_update = fields.Boolean(
help="Set to true and the user can update restricted model.",
)
is_readonly_user = fields.Boolean(
"Ready User",
help="Set to true and the user are readonly user on all models",
)
@api.constrains("is_readonly_user")
def _check_is_readonly_user(self):
for user in self:
if self.env.ref("base.group_system") in user.groups_id:
raise UserError(_("You cannot set admin user as a readonly user."))
| 32.913043
| 757
|
2,098
|
py
|
PYTHON
|
15.0
|
# Copyright 2021 Quartile Limited
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import api, models, tools
from odoo.exceptions import AccessError
from odoo.tools.translate import _
class IrModelAccess(models.Model):
_inherit = "ir.model.access"
@api.model
@tools.ormcache_context(
"self.env.uid",
"self.env.su",
"model",
"mode",
"raise_exception",
keys=("lang",),
)
def check(self, model, mode="read", raise_exception=True):
if self.env.su:
return True
res = super().check(model, mode, raise_exception)
if mode != "read" and raise_exception:
if self._test_readonly(model) or self._test_restrict_update(model):
raise AccessError(
_("You are only allowed to read this record. ({} - {})").format(
model, mode
)
)
return res
@api.model
def _test_readonly(self, model):
exclude_models = self._readonly_exclude_models()
if model not in exclude_models and self.env.user.is_readonly_user:
return True
return False
@api.model
def _test_restrict_update(self, model):
self.env.cr.execute(
"SELECT restrict_update FROM ir_model WHERE model = %s", (model,)
)
query_res = self.env.cr.dictfetchone()
if query_res["restrict_update"] and not self.env.user.unrestrict_model_update:
return True
return False
@api.model
def _readonly_exclude_models(self):
"""Models updtate/create by system, and should be excluded from checking"""
return (
self.sudo()
.search(
[
("group_id", "=", False),
"|",
("perm_write", "=", True),
"|",
("perm_create", "=", True),
("perm_unlink", "=", True),
]
)
.mapped("model_id.model")
)
| 31.313433
| 2,098
|
651
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 ABF OSIELL <https://osiell.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
{
"name": "Audit Log",
"version": "15.0.2.0.1",
"author": "ABF OSIELL, Odoo Community Association (OCA)",
"license": "AGPL-3",
"website": "https://github.com/OCA/server-tools",
"category": "Tools",
"depends": ["base"],
"data": [
"security/res_groups.xml",
"security/ir.model.access.csv",
"data/ir_cron.xml",
"views/auditlog_view.xml",
"views/http_session_view.xml",
"views/http_request_view.xml",
],
"application": True,
"installable": True,
}
| 29.590909
| 651
|
1,641
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 ABF OSIELL <https://osiell.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import time
from odoo.tests.common import TransactionCase
class TestAuditlogAutovacuum(TransactionCase):
def setUp(self):
super(TestAuditlogAutovacuum, self).setUp()
self.groups_model_id = self.env.ref("base.model_res_groups").id
self.groups_rule = self.env["auditlog.rule"].create(
{
"name": "testrule for groups",
"model_id": self.groups_model_id,
"log_read": True,
"log_create": True,
"log_write": True,
"log_unlink": True,
"state": "subscribed",
"log_type": "full",
}
)
def tearDown(self):
self.groups_rule.unlink()
super(TestAuditlogAutovacuum, self).tearDown()
def test_autovacuum(self):
log_model = self.env["auditlog.log"]
autovacuum_model = self.env["auditlog.autovacuum"]
group = self.env["res.groups"].create({"name": "testgroup1"})
nb_logs = log_model.search_count(
[("model_id", "=", self.groups_model_id), ("res_id", "=", group.id)]
)
self.assertGreater(nb_logs, 0)
# Milliseconds are ignored by autovacuum, waiting 1s ensure that
# the logs generated will be processed by the vacuum
time.sleep(1)
autovacuum_model.autovacuum(days=0)
nb_logs = log_model.search_count(
[("model_id", "=", self.groups_model_id), ("res_id", "=", group.id)]
)
self.assertEqual(nb_logs, 0)
| 37.295455
| 1,641
|
18,812
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 Therp BV <https://therp.nl>
# © 2018 Pieter Paulussen <pieter_paulussen@me.com>
# © 2021 Stefan Rijnhart <stefan@opener.amsterdam>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests.common import Form, TransactionCase
from odoo.addons.base.models.ir_model import MODULE_UNINSTALL_FLAG
class AuditlogCommon(object):
def test_LogCreation(self):
"""First test, caching some data."""
self.groups_rule.subscribe()
auditlog_log = self.env["auditlog.log"]
group = self.env["res.groups"].create({"name": "testgroup1"})
self.assertTrue(
auditlog_log.search(
[
("model_id", "=", self.groups_model_id),
("method", "=", "create"),
("res_id", "=", group.id),
]
).ensure_one()
)
group.write({"name": "Testgroup1"})
self.assertTrue(
auditlog_log.search(
[
("model_id", "=", self.groups_model_id),
("method", "=", "write"),
("res_id", "=", group.id),
]
).ensure_one()
)
group.unlink()
self.assertTrue(
auditlog_log.search(
[
("model_id", "=", self.groups_model_id),
("method", "=", "unlink"),
("res_id", "=", group.id),
]
).ensure_one()
)
def test_LogCreation2(self):
"""Second test, using cached data of the first one."""
self.groups_rule.subscribe()
auditlog_log = self.env["auditlog.log"]
testgroup2 = self.env["res.groups"].create({"name": "testgroup2"})
self.assertTrue(
auditlog_log.search(
[
("model_id", "=", self.groups_model_id),
("method", "=", "create"),
("res_id", "=", testgroup2.id),
]
).ensure_one()
)
def test_LogCreation3(self):
"""Third test, two groups, the latter being the parent of the former.
Then we remove it right after (with (2, X) tuple) to test the creation
of a 'write' log with a deleted resource (so with no text
representation).
"""
self.groups_rule.subscribe()
auditlog_log = self.env["auditlog.log"]
testgroup3 = testgroup3 = self.env["res.groups"].create({"name": "testgroup3"})
testgroup4 = self.env["res.groups"].create(
{"name": "testgroup4", "implied_ids": [(4, testgroup3.id)]}
)
testgroup4.write({"implied_ids": [(2, testgroup3.id)]})
self.assertTrue(
auditlog_log.search(
[
("model_id", "=", self.groups_model_id),
("method", "=", "create"),
("res_id", "=", testgroup3.id),
]
).ensure_one()
)
self.assertTrue(
auditlog_log.search(
[
("model_id", "=", self.groups_model_id),
("method", "=", "create"),
("res_id", "=", testgroup4.id),
]
).ensure_one()
)
self.assertTrue(
auditlog_log.search(
[
("model_id", "=", self.groups_model_id),
("method", "=", "write"),
("res_id", "=", testgroup4.id),
]
).ensure_one()
)
def test_LogCreation4(self):
"""Fourth test, create several records at once (with create multi
feature starting from Odoo 12) and check that the same number of logs
has been generated.
"""
self.groups_rule.subscribe()
auditlog_log = self.env["auditlog.log"]
groups_vals = [
{"name": "testgroup1"},
{"name": "testgroup3"},
{"name": "testgroup2"},
]
groups = self.env["res.groups"].create(groups_vals)
# Ensure that the recordset returns is in the same order
# than list of vals
expected_names = ["testgroup1", "testgroup3", "testgroup2"]
self.assertEqual(groups.mapped("name"), expected_names)
logs = auditlog_log.search(
[
("model_id", "=", self.groups_model_id),
("method", "=", "create"),
("res_id", "in", groups.ids),
]
)
self.assertEqual(len(logs), len(groups))
def test_LogCreation5(self):
"""Fifth test, create a record and check that the same number of logs
has been generated. And then delete it, check that it has created log
with 0 fields updated.
"""
self.groups_rule.subscribe()
auditlog_log = self.env["auditlog.log"]
testgroup5 = self.env["res.groups"].create({"name": "testgroup5"})
self.assertTrue(
auditlog_log.search(
[
("model_id", "=", self.groups_model_id),
("method", "=", "create"),
("res_id", "=", testgroup5.id),
]
).ensure_one()
)
testgroup5.unlink()
log_record = auditlog_log.search(
[
("model_id", "=", self.groups_model_id),
("method", "=", "unlink"),
("res_id", "=", testgroup5.id),
]
).ensure_one()
self.assertTrue(log_record)
if not self.groups_rule.capture_record:
self.assertEqual(len(log_record.line_ids), 0)
def test_LogCreation6(self):
"""Six test, create a record and check that the same number of logs
has been generated. And then delete it, check that it has created log
with x fields updated as per rule
"""
self.groups_rule.subscribe()
auditlog_log = self.env["auditlog.log"]
testgroup6 = self.env["res.groups"].create({"name": "testgroup6"})
self.assertTrue(
auditlog_log.search(
[
("model_id", "=", self.groups_model_id),
("method", "=", "create"),
("res_id", "=", testgroup6.id),
]
).ensure_one()
)
testgroup6.unlink()
log_record = auditlog_log.search(
[
("model_id", "=", self.groups_model_id),
("method", "=", "unlink"),
("res_id", "=", testgroup6.id),
]
).ensure_one()
self.assertTrue(log_record)
if self.groups_rule.capture_record:
self.assertTrue(len(log_record.line_ids) > 0)
class TestAuditlogFull(TransactionCase, AuditlogCommon):
def setUp(self):
super(TestAuditlogFull, self).setUp()
self.groups_model_id = self.env.ref("base.model_res_groups").id
self.groups_rule = self.env["auditlog.rule"].create(
{
"name": "testrule for groups",
"model_id": self.groups_model_id,
"log_read": True,
"log_create": True,
"log_write": True,
"log_unlink": True,
"log_type": "full",
}
)
def tearDown(self):
self.groups_rule.unlink()
super(TestAuditlogFull, self).tearDown()
class TestAuditlogFast(TransactionCase, AuditlogCommon):
def setUp(self):
super(TestAuditlogFast, self).setUp()
self.groups_model_id = self.env.ref("base.model_res_groups").id
self.groups_rule = self.env["auditlog.rule"].create(
{
"name": "testrule for groups",
"model_id": self.groups_model_id,
"log_read": True,
"log_create": True,
"log_write": True,
"log_unlink": True,
"log_type": "fast",
}
)
def tearDown(self):
self.groups_rule.unlink()
super(TestAuditlogFast, self).tearDown()
class TestFieldRemoval(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
# Clear all existing logging lines
existing_audit_logs = cls.env["auditlog.log"].search([])
existing_audit_logs.unlink()
# Create a test model to remove
cls.test_model = (
cls.env["ir.model"]
.sudo()
.create(
[{"name": "x_test_model", "model": "x_test.model", "state": "manual"}]
)
)
# Create a test model field to remove
cls.test_field = (
cls.env["ir.model.fields"]
.sudo()
.create(
[
{
"name": "x_test_field",
"field_description": "x_Test Field",
"model_id": cls.test_model.id,
"ttype": "char",
"state": "manual",
}
]
)
)
# Setup auditlog rule
cls.auditlog_rule = cls.env["auditlog.rule"].create(
[
{
"name": "test.model",
"model_id": cls.test_model.id,
"log_type": "fast",
"log_read": False,
"log_create": True,
"log_write": True,
"log_unlink": False,
}
]
)
cls.auditlog_rule.subscribe()
# Trigger log creation
rec = cls.env["x_test.model"].create({"x_test_field": "test value"})
rec.write({"x_test_field": "test value 2"})
cls.logs = cls.env["auditlog.log"].search(
[("res_id", "=", rec.id), ("model_id", "=", cls.test_model.id)]
)
def assert_values(self):
"""Assert that the denormalized field and model info is present
on the auditlog records"""
self.logs.refresh()
self.assertEqual(self.logs[0].model_name, "x_test_model")
self.assertEqual(self.logs[0].model_model, "x_test.model")
log_lines = self.logs.mapped("line_ids")
self.assertEqual(len(log_lines), 2)
self.assertEqual(log_lines[0].field_name, "x_test_field")
self.assertEqual(log_lines[0].field_description, "x_Test Field")
self.auditlog_rule.refresh()
self.assertEqual(self.auditlog_rule.model_name, "x_test_model")
self.assertEqual(self.auditlog_rule.model_model, "x_test.model")
def test_01_field_and_model_removal(self):
"""Test field and model removal to check auditlog line persistence"""
self.assert_values()
# Remove the field
self.test_field.with_context(**{MODULE_UNINSTALL_FLAG: True}).unlink()
self.assert_values()
# The field should not be linked
self.assertFalse(self.logs.mapped("line_ids.field_id"))
# Remove the model
self.test_model.with_context(**{MODULE_UNINSTALL_FLAG: True}).unlink()
self.assert_values()
# The model should not be linked
self.assertFalse(self.logs.mapped("model_id"))
# Assert rule values
self.assertFalse(self.auditlog_rule.model_id)
class TestAuditlogFullCaptureRecord(TransactionCase, AuditlogCommon):
def setUp(self):
super(TestAuditlogFullCaptureRecord, self).setUp()
self.groups_model_id = self.env.ref("base.model_res_groups").id
self.groups_rule = self.env["auditlog.rule"].create(
{
"name": "testrule for groups with capture unlink record",
"model_id": self.groups_model_id,
"log_read": True,
"log_create": True,
"log_write": True,
"log_unlink": True,
"log_type": "full",
"capture_record": True,
}
)
def tearDown(self):
self.groups_rule.unlink()
super(TestAuditlogFullCaptureRecord, self).tearDown()
class AuditLogRuleTestForUserFields(TransactionCase):
@classmethod
def setUpClass(cls):
super(AuditLogRuleTestForUserFields, cls).setUpClass()
# get Contact model id
cls.contact_model_id = (
cls.env["ir.model"].search([("model", "=", "res.partner")]).id
)
# get phone field id
cls.fields_to_exclude_ids = (
cls.env["ir.model.fields"]
.search([("model", "=", "res.partner"), ("name", "=", "phone")])
.id
)
# get user id
cls.user = (
cls.env["res.users"]
.with_context(no_reset_password=True, tracking_disable=True)
.create(
{
"name": "Test User",
"login": "testuser",
}
)
)
cls.user_2 = (
cls.env["res.users"]
.with_context(no_reset_password=True, tracking_disable=True)
.create(
{
"name": "Test User2",
"login": "testuser2",
}
)
)
cls.users_to_exclude_ids = cls.user.id
# creating auditlog.rule
cls.auditlog_rule = (
cls.env["auditlog.rule"]
.with_context(tracking_disable=True)
.create(
{
"name": "testrule 01",
"model_id": cls.contact_model_id,
"log_read": True,
"log_create": True,
"log_write": True,
"log_unlink": True,
"log_type": "full",
"capture_record": True,
}
)
)
# Updating phone in fields_to_exclude_ids
cls.auditlog_rule.fields_to_exclude_ids = [[4, cls.fields_to_exclude_ids]]
# Updating users_to_exclude_ids
cls.auditlog_rule.users_to_exclude_ids = [[4, cls.users_to_exclude_ids]]
# Subscribe auditlog.rule
cls.auditlog_rule.subscribe()
cls.auditlog_log = cls.env["auditlog.log"]
# Creating new res.partner
cls.testpartner1 = (
cls.env["res.partner"]
.with_context(tracking_disable=True)
.create(
{
"name": "testpartner1",
"phone": "123",
}
)
)
# Creating new res.partner from excluded user
cls.testpartner2 = (
cls.env["res.partner"]
.with_context(tracking_disable=True)
.with_user(cls.user.id)
.create(
{
"name": "testpartner2",
}
)
)
def test_01_AuditlogFull_field_exclude_create_log(self):
# Checking log is created for testpartner1
create_log_record = self.auditlog_log.search(
[
("model_id", "=", self.auditlog_rule.model_id.id),
("method", "=", "create"),
("res_id", "=", self.testpartner1.id),
]
).ensure_one()
self.assertTrue(create_log_record)
field_names = create_log_record.line_ids.mapped("field_name")
# Checking log lines not created for phone
self.assertTrue("phone" not in field_names)
# Removing created log record
create_log_record.unlink()
def test_02_AuditlogFull_field_exclude_write_log(self):
# Checking fields_to_exclude_ids
self.testpartner1.with_context(tracking_disable=True).write(
{
"phone": "1234567890",
}
)
# Checking log is created for testpartner1
write_log_record = self.auditlog_log.search(
[
("model_id", "=", self.auditlog_rule.model_id.id),
("method", "=", "write"),
("res_id", "=", self.testpartner1.id),
]
).ensure_one()
self.assertTrue(write_log_record)
field_names = write_log_record.line_ids.mapped("field_name")
# Checking log lines not created for phone
self.assertTrue("phone" not in field_names)
def test_03_AuditlogFull_user_exclude_write_log(self):
# Update email in Form view with excluded user
partner_form = Form(
self.testpartner1.with_user(self.user.id).with_context(
tracking_disable=True
)
)
partner_form.email = "vendor@mail.com"
testpartner1 = partner_form.save()
# Checking write log not created
with self.assertRaises(ValueError):
self.auditlog_log.search(
[
("model_id", "=", self.auditlog_rule.model_id.id),
("method", "=", "write"),
("res_id", "=", testpartner1.id),
("user_id", "=", self.user.id),
]
).ensure_one()
def test_04_AuditlogFull_user_exclude_create_log(self):
# Checking create log not created for testpartner2
with self.assertRaises(ValueError):
self.auditlog_log.search(
[
("model_id", "=", self.auditlog_rule.model_id.id),
("method", "=", "create"),
("res_id", "=", self.testpartner2.id),
]
).ensure_one()
def test_05_AuditlogFull_user_exclude_unlink_log(self):
# Removing testpartner2 from excluded user
self.testpartner2.with_user(self.user).unlink()
# Checking delete log not created for testpartner2
with self.assertRaises(ValueError):
self.auditlog_log.search(
[
("model_id", "=", self.auditlog_rule.model_id.id),
("method", "=", "unlink"),
("res_id", "=", self.testpartner2.id),
]
).ensure_one()
def test_06_AuditlogFull_unlink_log(self):
# Removing testpartner1 with user_2
self.testpartner1.with_user(self.user_2).unlink()
delete_log_record = self.auditlog_log.search(
[
("model_id", "=", self.auditlog_rule.model_id.id),
("method", "=", "unlink"),
("res_id", "=", self.testpartner1.id),
("user_id", "=", self.user_2.id),
]
).ensure_one()
# Checking log lines are created
self.assertTrue(delete_log_record)
# Removing auditlog_rule
self.auditlog_rule.unlink()
| 34.262295
| 18,810
|
3,805
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 ABF OSIELL <https://osiell.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class AuditlogLog(models.Model):
_name = "auditlog.log"
_description = "Auditlog - Log"
_order = "create_date desc"
name = fields.Char("Resource Name", size=64)
model_id = fields.Many2one(
"ir.model", string="Model", index=True, ondelete="set null"
)
model_name = fields.Char(readonly=True)
model_model = fields.Char(string="Technical Model Name", readonly=True)
res_id = fields.Integer("Resource ID")
user_id = fields.Many2one("res.users", string="User")
method = fields.Char(size=64)
line_ids = fields.One2many("auditlog.log.line", "log_id", string="Fields updated")
http_session_id = fields.Many2one(
"auditlog.http.session", string="Session", index=True
)
http_request_id = fields.Many2one(
"auditlog.http.request", string="HTTP Request", index=True
)
log_type = fields.Selection(
[("full", "Full log"), ("fast", "Fast log")], string="Type"
)
@api.model_create_multi
def create(self, vals_list):
"""Insert model_name and model_model field values upon creation."""
for vals in vals_list:
if not vals.get("model_id"):
raise UserError(_("No model defined to create log."))
model = self.env["ir.model"].sudo().browse(vals["model_id"])
vals.update({"model_name": model.name, "model_model": model.model})
return super().create(vals_list)
def write(self, vals):
"""Update model_name and model_model field values to reflect model_id
changes."""
if "model_id" in vals:
if not vals["model_id"]:
raise UserError(_("The field 'model_id' cannot be empty."))
model = self.env["ir.model"].sudo().browse(vals["model_id"])
vals.update({"model_name": model.name, "model_model": model.model})
return super().write(vals)
class AuditlogLogLine(models.Model):
_name = "auditlog.log.line"
_description = "Auditlog - Log details (fields updated)"
field_id = fields.Many2one(
"ir.model.fields", ondelete="set null", string="Field", index=True
)
log_id = fields.Many2one(
"auditlog.log", string="Log", ondelete="cascade", index=True
)
old_value = fields.Text()
new_value = fields.Text()
old_value_text = fields.Text("Old value Text")
new_value_text = fields.Text("New value Text")
field_name = fields.Char("Technical name", readonly=True)
field_description = fields.Char("Description", readonly=True)
@api.model_create_multi
def create(self, vals_list):
"""Ensure field_id is not empty on creation and store field_name and
field_description."""
for vals in vals_list:
if not vals.get("field_id"):
raise UserError(_("No field defined to create line."))
field = self.env["ir.model.fields"].sudo().browse(vals["field_id"])
vals.update(
{"field_name": field.name, "field_description": field.field_description}
)
return super().create(vals_list)
def write(self, vals):
"""Ensure field_id is set during write and update field_name and
field_description values."""
if "field_id" in vals:
if not vals["field_id"]:
raise UserError(_("The field 'field_id' cannot be empty."))
field = self.env["ir.model.fields"].sudo().browse(vals["field_id"])
vals.update(
{"field_name": field.name, "field_description": field.field_description}
)
return super().write(vals)
| 40.913978
| 3,805
|
2,042
|
py
|
PYTHON
|
15.0
|
from odoo import fields, models, tools
class AuditlogLogLineView(models.Model):
_name = "auditlog.log.line.view"
_inherit = "auditlog.log.line"
_description = "Auditlog - Log details (fields updated)"
_auto = False
_log_access = True
name = fields.Char()
model_id = fields.Many2one("ir.model")
model_name = fields.Char()
model_model = fields.Char()
res_id = fields.Integer()
user_id = fields.Many2one("res.users")
method = fields.Char()
http_session_id = fields.Many2one(
"auditlog.http.session", string="Session", index=True
)
http_request_id = fields.Many2one(
"auditlog.http.request", string="HTTP Request", index=True
)
log_type = fields.Selection(
selection=lambda r: r.env["auditlog.rule"]._fields["log_type"].selection,
string="Type",
)
def _select_query(self):
return """
alogl.id,
alogl.create_date,
alogl.create_uid,
alogl.write_uid,
alogl.write_date,
alogl.field_id,
alogl.log_id,
alogl.old_value,
alogl.new_value,
alogl.old_value_text,
alogl.new_value_text,
alogl.field_name,
alogl.field_description,
alog.name,
alog.model_id,
alog.model_name,
alog.model_model,
alog.res_id,
alog.user_id,
alog.method,
alog.http_session_id,
alog.http_request_id,
alog.log_type
"""
def _from_query(self):
return """
auditlog_log_line alogl
JOIN auditlog_log alog ON alog.id = alogl.log_id
"""
def _query(self):
return "SELECT %s FROM %s" % (self._select_query(), self._from_query())
def init(self):
tools.drop_view_if_exists(self.env.cr, self._table)
self.env.cr.execute(
"""CREATE or REPLACE VIEW %s as (%s)""" % (self._table, self._query())
)
| 29.594203
| 2,042
|
1,333
|
py
|
PYTHON
|
15.0
|
# Copyright 2016 ABF OSIELL <https://osiell.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from datetime import datetime, timedelta
from odoo import api, fields, models
_logger = logging.getLogger(__name__)
class AuditlogAutovacuum(models.TransientModel):
_name = "auditlog.autovacuum"
_description = "Auditlog - Delete old logs"
@api.model
def autovacuum(self, days, chunk_size=None):
"""Delete all logs older than ``days``. This includes:
- CRUD logs (create, read, write, unlink)
- HTTP requests
- HTTP user sessions
Called from a cron.
"""
days = (days > 0) and int(days) or 0
deadline = datetime.now() - timedelta(days=days)
data_models = ("auditlog.log", "auditlog.http.request", "auditlog.http.session")
for data_model in data_models:
records = self.env[data_model].search(
[("create_date", "<=", fields.Datetime.to_string(deadline))],
limit=chunk_size,
order="create_date asc",
)
nb_records = len(records)
with self.env.norecompute():
records.unlink()
_logger.info("AUTOVACUUM - %s '%s' records deleted", nb_records, data_model)
return True
| 36.027027
| 1,333
|
27,905
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 ABF OSIELL <https://osiell.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import copy
from odoo import _, api, fields, models, modules
from odoo.exceptions import UserError
FIELDS_BLACKLIST = [
"id",
"create_uid",
"create_date",
"write_uid",
"write_date",
"display_name",
"__last_update",
]
# Used for performance, to avoid a dictionary instanciation when we need an
# empty dict to simplify algorithms
EMPTY_DICT = {}
class DictDiffer(object):
"""Calculate the difference between two dictionaries as:
(1) items added
(2) items removed
(3) keys same in both but changed values
(4) keys same in both and unchanged values
"""
def __init__(self, current_dict, past_dict):
self.current_dict, self.past_dict = current_dict, past_dict
self.set_current = set(current_dict)
self.set_past = set(past_dict)
self.intersect = self.set_current.intersection(self.set_past)
def added(self):
return self.set_current - self.intersect
def removed(self):
return self.set_past - self.intersect
def changed(self):
return {o for o in self.intersect if self.past_dict[o] != self.current_dict[o]}
def unchanged(self):
return {o for o in self.intersect if self.past_dict[o] == self.current_dict[o]}
class AuditlogRule(models.Model):
_name = "auditlog.rule"
_description = "Auditlog - Rule"
name = fields.Char(required=True, states={"subscribed": [("readonly", True)]})
model_id = fields.Many2one(
"ir.model",
"Model",
help="Select model for which you want to generate log.",
states={"subscribed": [("readonly", True)]},
ondelete="set null",
index=True,
)
model_name = fields.Char(readonly=True)
model_model = fields.Char(string="Technical Model Name", readonly=True)
user_ids = fields.Many2many(
"res.users",
"audittail_rules_users",
"user_id",
"rule_id",
string="Users",
help="if User is not added then it will applicable for all users",
states={"subscribed": [("readonly", True)]},
)
log_read = fields.Boolean(
"Log Reads",
help=(
"Select this if you want to keep track of read/open on any "
"record of the model of this rule"
),
states={"subscribed": [("readonly", True)]},
)
log_write = fields.Boolean(
"Log Writes",
default=True,
help=(
"Select this if you want to keep track of modification on any "
"record of the model of this rule"
),
states={"subscribed": [("readonly", True)]},
)
log_unlink = fields.Boolean(
"Log Deletes",
default=True,
help=(
"Select this if you want to keep track of deletion on any "
"record of the model of this rule"
),
states={"subscribed": [("readonly", True)]},
)
log_create = fields.Boolean(
"Log Creates",
default=True,
help=(
"Select this if you want to keep track of creation on any "
"record of the model of this rule"
),
states={"subscribed": [("readonly", True)]},
)
log_type = fields.Selection(
[("full", "Full log"), ("fast", "Fast log")],
string="Type",
required=True,
default="full",
help=(
"Full log: make a diff between the data before and after "
"the operation (log more info like computed fields which were "
"updated, but it is slower)\n"
"Fast log: only log the changes made through the create and "
"write operations (less information, but it is faster)"
),
states={"subscribed": [("readonly", True)]},
)
state = fields.Selection(
[("draft", "Draft"), ("subscribed", "Subscribed")],
required=True,
default="draft",
)
action_id = fields.Many2one(
"ir.actions.act_window",
string="Action",
states={"subscribed": [("readonly", True)]},
)
capture_record = fields.Boolean(
help="Select this if you want to keep track of Unlink Record",
)
users_to_exclude_ids = fields.Many2many(
"res.users",
string="Users to Exclude",
context={"active_test": False},
states={"subscribed": [("readonly", True)]},
)
fields_to_exclude_ids = fields.Many2many(
"ir.model.fields",
domain="[('model_id', '=', model_id)]",
string="Fields to Exclude",
states={"subscribed": [("readonly", True)]},
)
_sql_constraints = [
(
"model_uniq",
"unique(model_id)",
(
"There is already a rule defined on this model\n"
"You cannot define another: please edit the existing one."
),
)
]
def _register_hook(self):
"""Get all rules and apply them to log method calls."""
super(AuditlogRule, self)._register_hook()
if not hasattr(self.pool, "_auditlog_field_cache"):
self.pool._auditlog_field_cache = {}
if not hasattr(self.pool, "_auditlog_model_cache"):
self.pool._auditlog_model_cache = {}
if not self:
self = self.search([("state", "=", "subscribed")])
return self._patch_methods()
def _patch_methods(self):
"""Patch ORM methods of models defined in rules to log their calls."""
updated = False
model_cache = self.pool._auditlog_model_cache
for rule in self:
if rule.state != "subscribed" or not self.pool.get(
rule.model_id.model or rule.model_model
):
continue
model_cache[rule.model_id.model] = rule.model_id.id
model_model = self.env[rule.model_id.model or rule.model_model]
# CRUD
# -> create
check_attr = "auditlog_ruled_create"
if rule.log_create and not hasattr(model_model, check_attr):
model_model._patch_method("create", rule._make_create())
setattr(type(model_model), check_attr, True)
updated = True
# -> read
check_attr = "auditlog_ruled_read"
if rule.log_read and not hasattr(model_model, check_attr):
model_model._patch_method("read", rule._make_read())
setattr(type(model_model), check_attr, True)
updated = True
# -> write
check_attr = "auditlog_ruled_write"
if rule.log_write and not hasattr(model_model, check_attr):
model_model._patch_method("write", rule._make_write())
setattr(type(model_model), check_attr, True)
updated = True
# -> unlink
check_attr = "auditlog_ruled_unlink"
if rule.log_unlink and not hasattr(model_model, check_attr):
model_model._patch_method("unlink", rule._make_unlink())
setattr(type(model_model), check_attr, True)
updated = True
return updated
def _revert_methods(self):
"""Restore original ORM methods of models defined in rules."""
updated = False
for rule in self:
model_model = self.env[rule.model_id.model or rule.model_model]
for method in ["create", "read", "write", "unlink"]:
if getattr(rule, "log_%s" % method) and hasattr(
getattr(model_model, method), "origin"
):
model_model._revert_method(method)
delattr(type(model_model), "auditlog_ruled_%s" % method)
updated = True
if updated:
modules.registry.Registry(self.env.cr.dbname).signal_changes()
@api.model
def create(self, vals):
"""Update the registry when a new rule is created."""
if "model_id" not in vals or not vals["model_id"]:
raise UserError(_("No model defined to create line."))
model = self.env["ir.model"].sudo().browse(vals["model_id"])
vals.update({"model_name": model.name, "model_model": model.model})
new_record = super().create(vals)
if new_record._register_hook():
modules.registry.Registry(self.env.cr.dbname).signal_changes()
return new_record
def write(self, vals):
"""Update the registry when existing rules are updated."""
if "model_id" in vals:
if not vals["model_id"]:
raise UserError(_("Field 'model_id' cannot be empty."))
model = self.env["ir.model"].sudo().browse(vals["model_id"])
vals.update({"model_name": model.name, "model_model": model.model})
res = super().write(vals)
if self._register_hook():
modules.registry.Registry(self.env.cr.dbname).signal_changes()
return res
def unlink(self):
"""Unsubscribe rules before removing them."""
self.unsubscribe()
return super(AuditlogRule, self).unlink()
@api.model
def get_auditlog_fields(self, model):
"""
Get the list of auditlog fields for a model
By default it is all stored fields only, but you can
override this.
"""
return list(
n
for n, f in model._fields.items()
if (not f.compute and not f.related) or f.store
)
def _make_create(self):
"""Instanciate a create method that log its calls."""
self.ensure_one()
log_type = self.log_type
users_to_exclude = self.mapped("users_to_exclude_ids")
@api.model_create_multi
@api.returns("self", lambda value: value.id)
def create_full(self, vals_list, **kwargs):
self = self.with_context(auditlog_disabled=True)
rule_model = self.env["auditlog.rule"]
new_records = create_full.origin(self, vals_list, **kwargs)
# Take a snapshot of record values from the cache instead of using
# 'read()'. It avoids issues with related/computed fields which
# stored in the database only at the end of the transaction, but
# their values exist in cache.
new_values = {}
fields_list = rule_model.get_auditlog_fields(self)
for new_record in new_records.sudo():
new_values.setdefault(new_record.id, {})
for fname, field in new_record._fields.items():
if fname not in fields_list:
continue
new_values[new_record.id][fname] = field.convert_to_read(
new_record[fname], new_record
)
if self.env.user in users_to_exclude:
return new_records
rule_model.sudo().create_logs(
self.env.uid,
self._name,
new_records.ids,
"create",
None,
new_values,
{"log_type": log_type},
)
return new_records
@api.model_create_multi
@api.returns("self", lambda value: value.id)
def create_fast(self, vals_list, **kwargs):
self = self.with_context(auditlog_disabled=True)
rule_model = self.env["auditlog.rule"]
vals_list2 = copy.deepcopy(vals_list)
new_records = create_fast.origin(self, vals_list, **kwargs)
new_values = {}
for vals, new_record in zip(vals_list2, new_records):
new_values.setdefault(new_record.id, vals)
if self.env.user in users_to_exclude:
return new_records
rule_model.sudo().create_logs(
self.env.uid,
self._name,
new_records.ids,
"create",
None,
new_values,
{"log_type": log_type},
)
return new_records
return create_full if self.log_type == "full" else create_fast
def _make_read(self):
"""Instanciate a read method that log its calls."""
self.ensure_one()
log_type = self.log_type
users_to_exclude = self.mapped("users_to_exclude_ids")
def read(self, fields=None, load="_classic_read", **kwargs):
result = read.origin(self, fields, load, **kwargs)
# Sometimes the result is not a list but a dictionary
# Also, we can not modify the current result as it will break calls
result2 = result
if not isinstance(result2, list):
result2 = [result]
read_values = {d["id"]: d for d in result2}
# Old API
# If the call came from auditlog itself, skip logging:
# avoid logs on `read` produced by auditlog during internal
# processing: read data of relevant records, 'ir.model',
# 'ir.model.fields'... (no interest in logging such operations)
if self.env.context.get("auditlog_disabled"):
return result
self = self.with_context(auditlog_disabled=True)
rule_model = self.env["auditlog.rule"]
if self.env.user in users_to_exclude:
return result
rule_model.sudo().create_logs(
self.env.uid,
self._name,
self.ids,
"read",
read_values,
None,
{"log_type": log_type},
)
return result
return read
def _make_write(self):
"""Instanciate a write method that log its calls."""
self.ensure_one()
log_type = self.log_type
users_to_exclude = self.mapped("users_to_exclude_ids")
def write_full(self, vals, **kwargs):
self = self.with_context(auditlog_disabled=True)
rule_model = self.env["auditlog.rule"]
fields_list = rule_model.get_auditlog_fields(self)
old_values = {
d["id"]: d
for d in self.sudo()
.with_context(prefetch_fields=False)
.read(fields_list)
}
result = write_full.origin(self, vals, **kwargs)
new_values = {
d["id"]: d
for d in self.sudo()
.with_context(prefetch_fields=False)
.read(fields_list)
}
if self.env.user in users_to_exclude:
return result
rule_model.sudo().create_logs(
self.env.uid,
self._name,
self.ids,
"write",
old_values,
new_values,
{"log_type": log_type},
)
return result
def write_fast(self, vals, **kwargs):
self = self.with_context(auditlog_disabled=True)
rule_model = self.env["auditlog.rule"]
# Log the user input only, no matter if the `vals` is updated
# afterwards as it could not represent the real state
# of the data in the database
vals2 = dict(vals)
old_vals2 = dict.fromkeys(list(vals2.keys()), False)
old_values = {id_: old_vals2 for id_ in self.ids}
new_values = {id_: vals2 for id_ in self.ids}
result = write_fast.origin(self, vals, **kwargs)
if self.env.user in users_to_exclude:
return result
rule_model.sudo().create_logs(
self.env.uid,
self._name,
self.ids,
"write",
old_values,
new_values,
{"log_type": log_type},
)
return result
return write_full if self.log_type == "full" else write_fast
def _make_unlink(self):
"""Instanciate an unlink method that log its calls."""
self.ensure_one()
log_type = self.log_type
users_to_exclude = self.mapped("users_to_exclude_ids")
def unlink_full(self, **kwargs):
self = self.with_context(auditlog_disabled=True)
rule_model = self.env["auditlog.rule"]
fields_list = rule_model.get_auditlog_fields(self)
old_values = {
d["id"]: d
for d in self.sudo()
.with_context(prefetch_fields=False)
.read(fields_list)
}
if self.env.user in users_to_exclude:
return unlink_full.origin(self, **kwargs)
rule_model.sudo().create_logs(
self.env.uid,
self._name,
self.ids,
"unlink",
old_values,
None,
{"log_type": log_type},
)
return unlink_full.origin(self, **kwargs)
def unlink_fast(self, **kwargs):
self = self.with_context(auditlog_disabled=True)
rule_model = self.env["auditlog.rule"]
if self.env.user in users_to_exclude:
return unlink_fast.origin(self, **kwargs)
rule_model.sudo().create_logs(
self.env.uid,
self._name,
self.ids,
"unlink",
None,
None,
{"log_type": log_type},
)
return unlink_fast.origin(self, **kwargs)
return unlink_full if self.log_type == "full" else unlink_fast
def create_logs(
self,
uid,
res_model,
res_ids,
method,
old_values=None,
new_values=None,
additional_log_values=None,
):
"""Create logs. `old_values` and `new_values` are dictionaries, e.g:
{RES_ID: {'FIELD': VALUE, ...}}
"""
if old_values is None:
old_values = EMPTY_DICT
if new_values is None:
new_values = EMPTY_DICT
log_model = self.env["auditlog.log"]
http_request_model = self.env["auditlog.http.request"]
http_session_model = self.env["auditlog.http.session"]
model_model = self.env[res_model]
model_id = self.pool._auditlog_model_cache[res_model]
auditlog_rule = self.env["auditlog.rule"].search([("model_id", "=", model_id)])
fields_to_exclude = auditlog_rule.fields_to_exclude_ids.mapped("name")
for res_id in res_ids:
name = model_model.browse(res_id).name_get()
res_name = name and name[0] and name[0][1]
vals = {
"name": res_name,
"model_id": model_id,
"res_id": res_id,
"method": method,
"user_id": uid,
"http_request_id": http_request_model.current_http_request(),
"http_session_id": http_session_model.current_http_session(),
}
vals.update(additional_log_values or {})
log = log_model.create(vals)
diff = DictDiffer(
new_values.get(res_id, EMPTY_DICT), old_values.get(res_id, EMPTY_DICT)
)
if method == "create":
self._create_log_line_on_create(
log, diff.added(), new_values, fields_to_exclude
)
elif method == "read":
self._create_log_line_on_read(
log,
list(old_values.get(res_id, EMPTY_DICT).keys()),
old_values,
fields_to_exclude,
)
elif method == "write":
self._create_log_line_on_write(
log, diff.changed(), old_values, new_values, fields_to_exclude
)
elif method == "unlink" and auditlog_rule.capture_record:
self._create_log_line_on_read(
log,
list(old_values.get(res_id, EMPTY_DICT).keys()),
old_values,
fields_to_exclude,
)
def _get_field(self, model, field_name):
cache = self.pool._auditlog_field_cache
if field_name not in cache.get(model.model, {}):
cache.setdefault(model.model, {})
# - we use 'search()' then 'read()' instead of the 'search_read()'
# to take advantage of the 'classic_write' loading
# - search the field in the current model and those it inherits
field_model = self.env["ir.model.fields"].sudo()
all_model_ids = [model.id]
all_model_ids.extend(model.inherited_model_ids.ids)
field = field_model.search(
[("model_id", "in", all_model_ids), ("name", "=", field_name)]
)
# The field can be a dummy one, like 'in_group_X' on 'res.users'
# As such we can't log it (field_id is required to create a log)
if not field:
cache[model.model][field_name] = False
else:
field_data = field.read(load="_classic_write")[0]
cache[model.model][field_name] = field_data
return cache[model.model][field_name]
def _create_log_line_on_read(
self, log, fields_list, read_values, fields_to_exclude
):
"""Log field filled on a 'read' operation."""
log_line_model = self.env["auditlog.log.line"]
fields_to_exclude = fields_to_exclude + FIELDS_BLACKLIST
for field_name in fields_list:
if field_name in fields_to_exclude:
continue
field = self._get_field(log.model_id, field_name)
# not all fields have an ir.models.field entry (ie. related fields)
if field:
log_vals = self._prepare_log_line_vals_on_read(log, field, read_values)
log_line_model.create(log_vals)
def _prepare_log_line_vals_on_read(self, log, field, read_values):
"""Prepare the dictionary of values used to create a log line on a
'read' operation.
"""
vals = {
"field_id": field["id"],
"log_id": log.id,
"old_value": read_values[log.res_id][field["name"]],
"old_value_text": read_values[log.res_id][field["name"]],
"new_value": False,
"new_value_text": False,
}
if field["relation"] and "2many" in field["ttype"]:
old_value_text = (
self.env[field["relation"]].browse(vals["old_value"]).name_get()
)
vals["old_value_text"] = old_value_text
return vals
def _create_log_line_on_write(
self, log, fields_list, old_values, new_values, fields_to_exclude
):
"""Log field updated on a 'write' operation."""
log_line_model = self.env["auditlog.log.line"]
fields_to_exclude = fields_to_exclude + FIELDS_BLACKLIST
for field_name in fields_list:
if field_name in fields_to_exclude:
continue
field = self._get_field(log.model_id, field_name)
# not all fields have an ir.models.field entry (ie. related fields)
if field:
log_vals = self._prepare_log_line_vals_on_write(
log, field, old_values, new_values
)
log_line_model.create(log_vals)
def _prepare_log_line_vals_on_write(self, log, field, old_values, new_values):
"""Prepare the dictionary of values used to create a log line on a
'write' operation.
"""
vals = {
"field_id": field["id"],
"log_id": log.id,
"old_value": old_values[log.res_id][field["name"]],
"old_value_text": old_values[log.res_id][field["name"]],
"new_value": new_values[log.res_id][field["name"]],
"new_value_text": new_values[log.res_id][field["name"]],
}
# for *2many fields, log the name_get
if log.log_type == "full" and field["relation"] and "2many" in field["ttype"]:
# Filter IDs to prevent a 'name_get()' call on deleted resources
existing_ids = self.env[field["relation"]]._search(
[("id", "in", vals["old_value"])]
)
old_value_text = []
if existing_ids:
existing_values = (
self.env[field["relation"]].browse(existing_ids).name_get()
)
old_value_text.extend(existing_values)
# Deleted resources will have a 'DELETED' text representation
deleted_ids = set(vals["old_value"]) - set(existing_ids)
for deleted_id in deleted_ids:
old_value_text.append((deleted_id, "DELETED"))
vals["old_value_text"] = old_value_text
new_value_text = (
self.env[field["relation"]].browse(vals["new_value"]).name_get()
)
vals["new_value_text"] = new_value_text
return vals
def _create_log_line_on_create(
self, log, fields_list, new_values, fields_to_exclude
):
"""Log field filled on a 'create' operation."""
log_line_model = self.env["auditlog.log.line"]
fields_to_exclude = fields_to_exclude + FIELDS_BLACKLIST
for field_name in fields_list:
if field_name in fields_to_exclude:
continue
field = self._get_field(log.model_id, field_name)
# not all fields have an ir.models.field entry (ie. related fields)
if field:
log_vals = self._prepare_log_line_vals_on_create(log, field, new_values)
log_line_model.create(log_vals)
def _prepare_log_line_vals_on_create(self, log, field, new_values):
"""Prepare the dictionary of values used to create a log line on a
'create' operation.
"""
vals = {
"field_id": field["id"],
"log_id": log.id,
"old_value": False,
"old_value_text": False,
"new_value": new_values[log.res_id][field["name"]],
"new_value_text": new_values[log.res_id][field["name"]],
}
if log.log_type == "full" and field["relation"] and "2many" in field["ttype"]:
new_value_text = (
self.env[field["relation"]].browse(vals["new_value"]).name_get()
)
vals["new_value_text"] = new_value_text
return vals
def subscribe(self):
"""Subscribe Rule for auditing changes on model and apply shortcut
to view logs on that model.
"""
act_window_model = self.env["ir.actions.act_window"]
for rule in self:
# Create a shortcut to view logs
domain = "[('model_id', '=', %s), ('res_id', '=', active_id)]" % (
rule.model_id.id
)
vals = {
"name": _("View logs"),
"res_model": "auditlog.log",
"binding_model_id": rule.model_id.id,
"domain": domain,
}
act_window = act_window_model.sudo().create(vals)
rule.write({"state": "subscribed", "action_id": act_window.id})
return True
def unsubscribe(self):
"""Unsubscribe Auditing Rule on model."""
# Revert patched methods
self._revert_methods()
for rule in self:
# Remove the shortcut to view logs
act_window = rule.action_id
if act_window:
act_window.unlink()
return self.write({"state": "draft"})
| 39.027972
| 27,905
|
2,181
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 ABF OSIELL <https://osiell.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
from odoo.http import request
class AuditlogtHTTPSession(models.Model):
_name = "auditlog.http.session"
_description = "Auditlog - HTTP User session log"
_order = "create_date DESC"
display_name = fields.Char("Name", compute="_compute_display_name", store=True)
name = fields.Char("Session ID", index=True)
user_id = fields.Many2one("res.users", string="User", index=True)
http_request_ids = fields.One2many(
"auditlog.http.request", "http_session_id", string="HTTP Requests"
)
@api.depends("create_date", "user_id")
def _compute_display_name(self):
for httpsession in self:
create_date = fields.Datetime.from_string(httpsession.create_date)
tz_create_date = fields.Datetime.context_timestamp(httpsession, create_date)
httpsession.display_name = "{} ({})".format(
httpsession.user_id and httpsession.user_id.name or "?",
fields.Datetime.to_string(tz_create_date),
)
def name_get(self):
return [(session.id, session.display_name) for session in self]
@api.model
def current_http_session(self):
"""Create a log corresponding to the current HTTP user session, and
returns its ID. This method can be called several times during the
HTTP query/response cycle, it will only log the user session on the
first call.
If no HTTP user session is available, returns `False`.
"""
if not request:
return False
httpsession = request.session
if httpsession:
existing_session = self.search(
[("name", "=", httpsession.sid), ("user_id", "=", request.uid)], limit=1
)
if existing_session:
return existing_session.id
vals = {"name": httpsession.sid, "user_id": request.uid}
httpsession.auditlog_http_session_id = self.create(vals).id
return httpsession.auditlog_http_session_id
return False
| 41.150943
| 2,181
|
2,801
|
py
|
PYTHON
|
15.0
|
# Copyright 2015 ABF OSIELL <https://osiell.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from psycopg2.extensions import AsIs
from odoo import api, fields, models
from odoo.http import request
class AuditlogHTTPRequest(models.Model):
_name = "auditlog.http.request"
_description = "Auditlog - HTTP request log"
_order = "create_date DESC"
display_name = fields.Char("Name", compute="_compute_display_name", store=True)
name = fields.Char("Path")
root_url = fields.Char("Root URL")
user_id = fields.Many2one("res.users", string="User")
http_session_id = fields.Many2one(
"auditlog.http.session", string="Session", index=True
)
user_context = fields.Char("Context")
log_ids = fields.One2many("auditlog.log", "http_request_id", string="Logs")
@api.depends("create_date", "name")
def _compute_display_name(self):
for httprequest in self:
create_date = fields.Datetime.from_string(httprequest.create_date)
tz_create_date = fields.Datetime.context_timestamp(httprequest, create_date)
httprequest.display_name = "{} ({})".format(
httprequest.name or "?", fields.Datetime.to_string(tz_create_date)
)
def name_get(self):
return [(request.id, request.display_name) for request in self]
@api.model
def current_http_request(self):
"""Create a log corresponding to the current HTTP request, and returns
its ID. This method can be called several times during the
HTTP query/response cycle, it will only log the request on the
first call.
If no HTTP request is available, returns `False`.
"""
if not request:
return False
http_session_model = self.env["auditlog.http.session"]
httprequest = request.httprequest
if httprequest:
if hasattr(httprequest, "auditlog_http_request_id"):
# Verify existence. Could have been rolled back after a
# concurrency error
self.env.cr.execute(
"SELECT id FROM %s WHERE id = %s",
(AsIs(self._table), httprequest.auditlog_http_request_id),
)
if self.env.cr.fetchone():
return httprequest.auditlog_http_request_id
vals = {
"name": httprequest.path,
"root_url": httprequest.url_root,
"user_id": request.uid,
"http_session_id": http_session_model.current_http_session(),
"user_context": request.context,
}
httprequest.auditlog_http_request_id = self.create(vals).id
return httprequest.auditlog_http_request_id
return False
| 41.191176
| 2,801
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.